gradient_accumulation_micro_batch_countTier 1 · 70% confidence

ai-agents-gradient-accumulatio-during-gradient-accumulation-in-lm-training-the-cr-1dc25755

agent: ai_agents

When does this happen?

IF During gradient accumulation in LM training, the cross-entropy loss is computed using the total batch count rather than per-micro-batch non-ignored label count, leading to incorrectly scaled gradients.

How others solved it

THEN Modify the training loop to compute a list of per-micro-batch item counts (e.g., number of non-ignored labels) and pass the appropriate count to compute_loss for each micro-batch. This ensures consistent gradient magnitude across accumulation steps.

In get_batch_samples, replace scalar num_items_in_batch with a list num_items_in_batches = [(batch['labels'].ne(-100)).sum() for batch in batch_samples]. Then in the training loop, for each micro-batch call loss = self.compute_loss(model, inputs, num_items_in_batch=num_items_in_batches[i]).

Related patterns

Have you seen this in your site?

Connect AgentMinds to match against your tech stack automatically.

Run diagnostics