Training and optimization
Reduction, Masking, Weighting, and Multi-Output Objectives
Trace how per-example losses, masks, weights, and task coefficients alter gradient scale and the behavior a model prioritizes.
By the end you can
- Explain how sum, mean, and normalized reductions change gradient scale
- Distinguish masking invalid targets from reweighting valid observations
- Diagnose unstable or misleading multi-loss combinations
- Design a reduction policy that remains comparable across batches
Example
The same examples produced a different update, and it took a patch to notice
On 16 October 2024 Hugging Face published a fix for a loss-normalization bug in the Transformers Trainer. Nothing was wrong with the model, the data or the optimizer. The division was in the wrong place.
With gradient accumulation the code averaged each micro-batch's cross-entropy separately, then averaged those means. Every one of those steps was a mean over valid tokens. The result was still not the quantity anyone intended. Hugging Face said so in the announcement: “the correct loss should be computed by the total loss across all batches in a gradient accumulation step divided by the total number of all non padding tokens in those batches. This is not the same as the average of the per-batch loss values.”
Both computations are means over valid tokens. Only one of them is the loss.
- Before the fix, each micro-batch's cross-entropy was averaged over its own valid tokens and those means were then averaged, so a micro-batch carrying few valid tokens counted as much as one carrying many.
- The fix replaced that with reduction="sum" divided by a new num_items_in_batch argument: one numerator, one denominator, divided once across the whole accumulation step.
- It shipped as two pull requests, #34191 for the models and #34198 for the Trainer API, announced the same day.
- Independent projects hit the same denominator within days: PyTorch Lightning issue #20350, “Gradient accumulation calcluation may be incorrect”, was filed on 19 October 2024 by a user who had measured worse performance with accumulation than with multiple devices.
- The moral is narrower and more useful than a warning about padding: a mean over valid tokens is not one rule, and where the division happens decides the update.
Comparison
Masking and weighting solve different problems, and neither is read off the data
Masking excludes positions where the target is undefined, unavailable or irrelevant. Padding tokens are the standard example. The claim it makes is that no supervised error exists there, so the denominator counts valid positions only, and the risk it carries is a hidden missingness pattern. Weighting changes the influence of a target that is perfectly valid — a rare-class coefficient, say. Its claim is that this error matters differently, its denominator is often the total weight, and its risk is distorted calibration. Sampling does neither. It changes which observations appear in the batch at all, as when rare events are oversampled. It alters the distribution of updates, its denominator is batch-dependent, and its risk is duplicated noisy cases. Confusing the three can hide missing supervision or manufacture biased gradients.
How much of a batch carries supervised error at all is a dial, not a measurement. BERT set it once in 2018 and the field inherited the setting: “In all of our experiments, we mask 15% of all WordPiece tokens in each sequence at random.” The authors were explicit that this bounds the supervision available per step, noting that “the masked LM only make predictions on 15% of tokens in each batch”. Wettig and colleagues at Princeton turned the dial in 2023 and found 15% is not optimal. Masking 40% beat it for BERT-large-size models: SQuAD 88.0 → 89.8, QNLI 90.9 → 91.6, MNLI 84.2 → 84.5. Pushed to 80%, validation perplexity went from 17.7 to 1141.4, and more than 95% of fine-tuning performance survived anyway. The number a mask moves first is not the number anyone deploys.
The weighting side has a matching trap, and it is a spelling trap. PyTorch's torch.nn.CrossEntropyLoss ships the signature (weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean', label_smoothing=0.0). Under reduction='mean' with class weights it divides the weighted sum by Σ w_{y_n}·1{y_n ≠ ignore_index} — the sum of the weights over non-ignored targets. Keras 3 uses the same word for a different denominator, and documents the choice on the reduction argument of its base Loss class: “"sum" sums the loss, "sum_over_batch_size" and "mean" sum the loss and divide by the sample size, and "mean_with_sample_weight" sums the loss and divides by the sum of the sample weights.” Its default is sum_over_batch_size. Dividing by the weights is the separate opt-in. Two frameworks a team may already have in one repository disagree by default about what the word mean names once weights exist.
Masking
Excludes positions where the target is undefined, unavailable, or irrelevant.
- Example: padding tokens
- Meaning: no supervised error exists
- Denominator: valid positions only
- Risk: hidden missingness pattern
Weighting
Changes the influence of a valid target in the objective.
- Example: rare-class coefficient
- Meaning: error matters differently
- Denominator: often total weight
- Risk: distorted calibration
Sampling
Changes which observations appear in the batch at all.
- Example: oversample rare events
- Meaning: alter update distribution
- Denominator: batch-dependent
- Risk: duplicated noisy cases
Analogy
A committee that aggregates votes with different rules
Some members of a committee abstain, some votes carry extra weight, and several subcommittees submit scores of their own. The final decision depends on both votes and aggregation rules. Who may vote and how much each vote counts are written into the aggregation rule, not discovered in the votes. Reduction rules are part of the objective itself.
A coefficient rescales one gradient contribution under a particular reduction. It does not directly state how much the organization values that task. Shared parameters can create conflict even after losses have similar magnitudes. Later lessons examine multi-task gradient geometry and methods that respond to interference.
Focal loss turns this dial deliberately. Published in 2017, it multiplies cross-entropy by a modulating factor with a focusing parameter γ, and its authors report having “found γ = 2 to work best in our experiments”. At that setting the reweighting is severe, and they quantify it: “with γ = 2, an example classified with pt = 0.9 would have 100× lower loss compared with CE and with pt ≈ 0.968 it would have 1000× lower loss”. Nothing about the data changed. Only its weight in the sum.
Aggregation determines whose error can move the model.
Case
One loss coefficient worth eighteen points of segmentation accuracy
One loss coefficient, with everything else held fixed, moved a segmentation score by eighteen points. Kendall, Gal and Cipolla, who measured it, said plainly why it was worth measuring: “the performance of such systems is strongly dependent on the relative weighting between each task’s loss”.
The experiment, published in 2018 by Kendall and colleagues, trained one network on semantic classification and depth regression together. The architecture, the data and the optimizer were held fixed. Only the two loss weights moved between runs. Classification IoU ran from 42.7% at a classification weight of 0.1 up to 60.4% at a weight of 0.85, and learning the weights from task uncertainty reached 62.7%.
Re-weighting alone was worth 17.7 points. Learning the weights added a further 2.3. The full span from worst to best was 20.0 points — out of a coefficient that is often left at 1.
Figure
Visual
From local errors to a scalar objective
The order of these operations matters, because each one changes what the next one is dividing.
First, compute elemental losses: an error for each token, pixel, sample, pair or task output. Second, apply validity masks, removing positions without meaningful targets or observable outcomes. Third, apply weights, changing influence for classes, examples, tasks or confidence levels. Fourth, choose denominators — samples, valid elements, total weight, or another quantity you have declared out loud. Fifth, combine objectives into the single scalar that is backpropagated.
The Transformers gradient-accumulation bug lived entirely in step four. PyTorch and Keras 3 disagree there by default. It is the step most often inherited rather than chosen.
1. Compute elemental losses
Produce an error for each token, pixel, sample, pair, or task output.
2. Apply validity masks
Remove positions without meaningful targets or observable outcomes.
3. Apply weights
Change influence for classes, examples, tasks, or confidence levels.
4. Choose denominators
Normalize by samples, valid elements, total weight, or another declared quantity.
5. Combine objectives
Aggregate task or head losses into the scalar used for backpropagation.
Key idea
Empty or nearly empty supervision needs an explicit policy
A batch can contain no positive anchors, no observed labels for one task, or no valid sequence positions after filtering. Dividing by zero is only the most obvious failure. Silently returning zero loss may skip learning while dashboards look normal.
Frameworks encode a default policy, and it is easy to inherit unnoticed. PyTorch's CrossEntropyLoss defaults to reduction='mean' and ignore_index=-100, where ignore_index “Specifies a target value that is ignored and does not contribute to the input gradient”. Hugging Face's token classification guide relies on exactly that, instructing readers to assign “the label -100 to the special tokens [CLS] and [SEP] so they’re ignored by the PyTorch loss function”. The number is a convention, not a property of the data. A padding id of 0 silently trains on padding.
DAPO shows what a deliberate policy is worth. In that 2025 reinforcement-learning recipe, prompts whose sampled answers are all correct receive identical rewards, so the group advantage is zero — and with it the policy gradient: “A zero advantage results in zero policy gradients, shrinking the magnitude and increasing the noise sensitivity of the batch gradient, thereby degrading sample efficiency.” The number of such samples “continues to increase” during training. So the authors over-sample and discard prompts whose accuracy is 0 or 1 until the batch is full of usable ones. That filtering rule records the largest single jump in their ablation: AIME 2024 avg@32 rising from 42 to 50.
Hugging Face's TRL treats the same condition as a monitoring signal rather than an edge case, logging frac_reward_zero_std — “The fraction of samples in the generation batch with a reward std of zero, implying there is little diversity for that prompt (all answers are correct or incorrect).” Record empty-batch counts, decide whether to skip the update, and test the effect on optimizer state.
Missing supervision is a data event, not merely a numerical edge case.
The denominator defines the unit of one update
A mean per image, a mean per positive label and a mean per annotated pixel produce different gradient units. Batch composition can therefore change effective step size even when the optimizer learning rate is fixed.
DAPO isolated that effect. It changed only the loss reduction of GRPO — from averaging tokens within a sample and then averaging samples, to a single average over all tokens in the batch, 1/Σ|o_i|. The complaint is about a denominator, not a gradient: “Since all samples are assigned the same weight in the loss calculation, tokens within longer responses (which contain more tokens) may have a disproportionately lower contribution to the overall loss, which can lead to two adverse effects.” In the ablation, AIME 2024 avg@32 rose from 41 to 42 with the token-level loss, and the authors note the gain is in stability rather than score. The full recipe reached 50 points on Qwen2.5-32B, above DeepSeek-R1-Zero-Qwen-32B's 47, using 50% of the training steps. Hugging Face's TRL has since made this reduction its default, shipping loss_type="dapo" and marking the original sequence-length normalization "grpo" as “Not recommended due to length bias”.
The denominator also fixes what a learning rate means. Minibatch SGD divides the summed gradient by the batch size n, so a rule can be stated directly on that division. Goyal and colleagues at Facebook AI Research stated it in 2017: “Linear Scaling Rule: When the minibatch size is multiplied by k, multiply the learning rate by k.” With it they trained ResNet-50 on ImageNet at minibatch 8192 across 256 GPUs in one hour, with no loss of accuracy and roughly 90% scaling efficiency from 8 to 256 GPUs.
It is a rule about an arithmetic mean, and it holds only as far as that mean does. Shallue and colleagues, in the Journal of Machine Learning Research in 2019, measured 71,638,836 loss values over 168,160 models across 35 workloads. They found the rule is not general — “their learning rate heuristic broke down for even larger batch sizes” — and captioned their Figure 8 “Optimal effective learning rates do not always follow linear or square root scaling heuristics.”
The denominator should match whatever the project intends to keep stable. Log both numerator and denominator so scale changes are visible.
A learning rate is meaningful only relative to the loss reduction that creates its gradients.
Visual
Audit a multi-output loss before tuning coefficients
This procedure catches scale problems before a weight sweep. Log every component — unweighted loss, valid count, weighted numerator and final contribution. Inspect gradient norms, measuring how each component affects shared and task-specific parameters. Perturb batch composition with short, long, sparse, dense, positive-free and heavily masked batches. Verify invariants: check whether duplicating an example or changing padding alters the intended unit. Then tune with decision metrics, using validation behavior rather than comparable-looking loss numbers.
That last step is the one most often replaced by machinery, and two groups reported at NeurIPS 2022 that the machinery does not pay. Xin and colleagues at Google ran large-scale language and vision experiments on the specialised multi-task optimizers, and put the result in one sentence of their abstract: “We show that, despite the added design and computational complexity of these algorithms, MTO methods do not yield any performance improvements beyond what is achievable via traditional optimization approaches.”
Kurin and colleagues reached the same place from the other direction in 2022. They found that “unitary scalarization” — simply minimising the sum of the task losses — “matches or improves upon the performance of complex multi-task optimizers in popular supervised and reinforcement learning settings”, once standard single-task regularization and stabilization are applied. They argue that many specialised multi-task optimizers “can be partly interpreted as forms of regularization”.
A plain weighted sum, audited and tuned against decision metrics, is the baseline the specialised methods have to beat. On this evidence they do not.
1. Log every component
Track unweighted loss, valid count, weighted numerator, and final contribution.
2. Inspect gradient norms
Measure how each component affects shared and task-specific parameters.
3. Perturb batch composition
Test short, long, sparse, dense, positive-free, and heavily masked batches.
4. Verify invariants
Check whether duplicating an example or changing padding alters the intended unit.
5. Tune with decision metrics
Adjust coefficients using validation behavior, not comparable-looking loss numbers.
Key takeaways
- Loss reduction determines the unit and scale of a gradient update even when the examples do not change: the Transformers gradient-accumulation bug patched on 16 October 2024 was a mean of per-micro-batch means where a single sum over non-padding tokens belonged.
- Masks exclude undefined supervision, weights alter valid influence, and sampling changes which observations enter the update; BERT's 15% masking rate was a choice, and 40% measured better for BERT-large-size models.
- The word mean does not fix a denominator: PyTorch's CrossEntropyLoss divides by the sum of the class weights over non-ignored targets, while Keras 3 defaults to sum_over_batch_size and offers mean_with_sample_weight as a separate opt-in.
- Empty-supervision batches need explicit behavior, monitoring and tests. DAPO's rule of discarding prompts with accuracy 0 or 1 records the largest single jump in its ablation, AIME 2024 avg@32 rising from 42 to 50, and TRL logs frac_reward_zero_std for the same condition.
- A learning rate is meaningful only against the reduction that produced its gradients: the Linear Scaling Rule follows from the 1/n mean, and a study of 71,638,836 loss values over 168,160 models across 35 workloads found it breaks down at larger batch sizes.
- Equal scalar loss values do not guarantee equal influence, and specialised combination machinery is not the remedy: two independent groups at NeurIPS 2022 found a properly tuned weighted sum matched it.