Finetuning with gradient accumulation weights micro-batches, not tokens, so the objective depends on `micro_batch_size`
All five finetuning scripts (full, lora, lora_legacy, adapter, adapter_v2) compute the loss of a micro-batch with chunked_cross_entropy, which returns the mean over the micro-batch's non-masked target tokens. Then they call
fabric.backward(loss / train.gradient_accumulation_iters(devices, num_nodes))(e.g. litgpt/finetune/lora.py L358-359). So one optimizer step minimizes the average of the per-micro-batch means, not the mean over all target tokens of the step. A token in a micro-batch with few target tokens weighs more than a token in a long one. DDP/FSDP then average these per-rank averages.
With the default micro_batch_size=1, this weights every sequence equally, whatever its length. Some people want that. The problem is that the objective changes when you change micro_batch_size at a fixed global_batch_size. With micro_batch_size > 1 you get a token mean inside each micro-batch and a sample mean across micro-batches. So a run that lowers micro_batch_size to fit in memory is optimizing a different objective, not the same objective computed in smaller pieces.
To see how large the effect is, I ran Qwen3-1.7B-Base with LoRA on 16 samples from tests/data/_fixtures/alpaca.json (38 to 134 target tokens per sample). I compared the accumulated gradient of one optimizer step (global_batch_size=16) with the gradient of the token-level mean loss over the same 16 samples. The relative L2 difference is about 21% at micro_batch_size=1, 16% at 2 and 5% at 4 (fp32, three random LoRA initializations).
Hugging Face Transformers fixed the same problem in its Trainer in v4.46.0, released in October 2024 (blog post "Fixing Gradient Accumulation", PRs #34191 and #34198). The Trainer prefetches the batches of one accumulation step, counts their label tokens (num_items_in_batch) and divides the summed loss by that count. Cross-device averaging followed in v4.47.0 (#34373, average_tokens_across_devices, on by default in current releases). It gathers the count across processes and multiplies the loss by the number of processes, to undo DDP's gradient averaging.
Proposal: add an opt-in TrainArgs option, --train.loss_normalization {micro_batch,token}. The default would be micro_batch, so current behavior and results don't change. With token, each accumulation window is prefetched and its target tokens are counted and summed over the data-parallel ranks. Each micro-batch's loss is then weighted by its share of those tokens. The accumulated gradient is then the gradient of the token-level mean over the whole optimizer step, the same as processing the global batch at once. If maintainers agree, the default could flip to token in a later release.
I have this implemented, with tests that check the gradient against a single-batch computation for all five scripts. I'm happy to open the PR if this is welcome.
Source: Lightning-AI/litgpt