One former soldier who would give only his first name, Mohamed, because deserting is illegal, said that he had served in Ramadi and that his colleagues started deserting months ago as the deaths started mounting. “I felt like I was fighting armies, not an army,” said Mohamed, 24.

The militants came in waves, sending suicide bombers when their ammunition grew scarce. Mohamed said that eight of his friends had died and that he almost did, too, when a mortar shell struck his Humvee. When militants singled him out as a target for assassination, forcing him to flee, it was almost a relief.

“I’m tired,” he said. “Everyone is tired.”

The government has played down the scale of the crisis, in part by registering soldiers as “missing” rather than as deserters. Officials also blamed the problem on unrelated issues — saying, for instance, that soldiers were not returning from home leave, but only because roads leading to the battlefields had become unsafe.

Lt. Gen. Rashid Fleih, the commander of operations in Anbar Province, said last week that recent successes by the army in clearing several highways would resolve that issue. “Now the soldier who is on leave can go back to his unit without any problems,” he said. After the defeat in Mosul, though, the crisis could not be so easily brushed away. For the first time on Tuesday, the government publicly invoked the law forbidding desertions, threatening harsh punishments, including the death penalty, according to a media adviser for the prime minister, Nuri Kamal al-Maliki.

The government, though, seemed to have limited leverage. In interviews, several deserters cited the ferocity of the battle as their primary reason for leaving. They spoke of nerve-racking patrols in remote areas or in contested cities, surrounded, at times, by hostile residents. They searched booby-trapped houses and traveled roads full of bombs. Most terrifying, though, they said, were the snipers.

Their stories added detail to the brutal shadowy war between the militants and the army — the latest trauma for a country still reeling from the American invasion and occupation and the sectarian civil war that followed.