In Reinforcement Learning from Human Feedback (RLHF), the policy model (your LLM) is trained to maximize a reward signal. This is done by calculating a loss for each token generated by the model. How these individual token losses are combined—or aggregated—into a single scalar value for the gradient update is a critical choice that can significantly impact training dynamics, stability, and model behavior.

Background: Batches, Padding, and Masking

To train a language model efficiently, we process multiple sequences at once in a “batch.” However, these sequences often have different lengths. Since deep learning models require inputs to be of a uniform shape, we must standardize their lengths.

Padding: The standard solution is to make all sequences in a batch as long as the longest sequence. Shorter sequences are appended with special “padding” tokens until they reach this maximum length.

Masking: We don’t want the model to learn from these artificial padding tokens. A loss mask is a binary tensor with the same shape as the batch (bs, response_length). It contains a 1 for every real token and a 0 for every padding token. By multiplying the loss matrix by this mask, we ensure that the loss for padding tokens becomes zero, effectively ignoring them during training.

The four aggregation methods below handle the losses from these variable-length, masked sequences in different ways.

Let’s denote the loss for the -th token in the -th sequence of a batch as . The loss_mask ensures that we only consider losses from actual tokens, not padding. Let be the true length of sequence .

1. token-mean

This is the most straightforward approach. It calculates the mean of the loss across every single valid token in the entire batch.

Implementation:

loss = verl_F.masked_mean(loss_mat, loss_mask)

How it works: It sums the losses of all unmasked tokens in the batch and divides by the total number of unmasked tokens.

Implication: Every token contributes equally to the final loss. Consequently, sequences with more tokens (longer sequences) have a greater influence on the gradient update. If the reward model is biased towards length, this mode will amplify that bias.

2. seq-mean-token-sum

This mode first sums the losses within each sequence and then averages these sums across all sequences in the batch.

Implementation:

seq_losses = torch.sum(loss_mat * loss_mask, dim=-1) # token-sum
loss = torch.mean(seq_losses)                      # seq-mean

How it works: For each sequence, it calculates the total loss. Then, it computes the simple average of these per-sequence totals.

Implication: This mode also gives more weight to longer sequences. A sequence with 20 tokens will have a summed loss that is likely much larger than a sequence with 5 tokens, so it will have a proportionally larger impact on the final averaged loss.

3. seq-mean-token-mean

This mode normalizes the loss for each sequence by its own length before averaging across the batch. This is also referred to as the sample-level loss.

Implementation:

# token-mean for each sequence
seq_losses = torch.sum(loss_mat * loss_mask, dim=-1) / torch.sum(loss_mask, dim=-1)
loss = torch.mean(seq_losses) # seq-mean

How it works: It first calculates the average loss for each sequence individually. Then, it averages these sequence-level averages.

Implication: Each sequence contributes equally to the final loss, regardless of its length. This directly counteracts length bias. The optimization objective shifts from “get the highest total reward” to “get the highest average reward per token.” This makes it the most effective mode for mitigating length-based reward hacking.

4. seq-mean-token-sum-norm

This mode sums the total loss across the entire batch and then divides by a single normalizer: the padded length of the sequences in the batch.

Implementation:

seq_losses = torch.sum(loss_mat * loss_mask, dim=-1)
loss = torch.sum(seq_losses) / loss_mask.shape[-1]

How it works: The name seq-mean-token-sum-norm can be misleading. The implementation does not perform a seq-mean. Instead, it first calculates the sum of losses for each sequence (token-sum), then sums these sums to get the total loss for the entire batch. This total loss is then normalized by the maximum sequence length.

Implication: The effectiveness of this normalization depends heavily on the consistency of loss_mask.shape[-1] (the padding length) across batches. If all batches are padded to the same length (as the code comment suggests is ideal), it acts as a consistent scaling factor. However, it does not normalize for the actual sequence length () like seq-mean-token-mean does, so it is still more susceptible to length bias than that mode.

Conclusion: Which Mode is Best for Reducing Length Hacking?

To determine the best approach for mitigating length-based reward hacking, especially when training with batches that contain sequences of different sizes, we must analyze all four choices: token-mean, seq-mean-token-sum, seq-mean-token-sum-norm, and seq-mean-token-mean.

Based on the implementations, seq-mean-token-mean is the superior choice.

Why? It is the only method that properly normalizes for sequence length on a per-sample basis. In a batch with sequences of lengths [10, 50, 100], the implementation torch.sum(loss_mat * loss_mask, dim=-1) / torch.sum(loss_mask, dim=-1) correctly calculates the average loss for the 10-token, 50-token, and 100-token sequences individually. The final loss is the mean of these three sequence-level averages, giving each sample equal importance. This forces the model to optimize for the average quality of its tokens rather than the total reward, directly discouraging the strategy of generating longer, low-quality text.

token-mean and seq-mean-token-sum are both vulnerable to length hacking in variable-length batches. The 100-token sequence will contribute significantly more to the total loss signal than the 10-token sequence, creating a vicious cycle if the reward model has any length bias.

seq-mean-token-sum-norm is an interesting alternative, but its reliance on a potentially variable padding dimension (loss_mask.shape[-1]) makes it less principled. If the max length in a batch is 100, all sequences are effectively judged against this same denominator, which doesn’t accurately reflect the true length of shorter sequences in that batch.

While seq-mean-token-mean might be “unstable in long-CoT scenarios” as the original paper notes, this is a trade-off. The instability can arise because the per-token advantage signal in very long sequences might be noisy or dilute important signals. However, if your primary observed problem is the model’s output length growing uncontrollably, switching to seq-mean-token-mean is the most direct and theoretically sound solution to try first.