LigerFusedLinearGRPOLoss produces ~100x larger grad_norm than TRL's non-Liger-Kernel path due to missing vLLM IS correction and other differences
Summary
When using use_liger_kernel=True with TRL v0.27.2's GRPOTrainer and vLLM, grad_norm is ~100x larger than the non-Liger-Kernel path. This is primarily caused by the vLLM importance sampling correction not being applied in the Liger-Kernel loss path. Several other silent differences also exist.
List of differences (TRL v0.27.2)
| # | Difference | TRL (non-Liger-Kernel) | Liger-Kernel | Impact | Silent? |
|---|---|---|---|---|---|
| 1 | vLLM IS correction | per_token_loss *= importance_sampling_ratio (L2351-L2352) |
Not applied | ~100-300x (primary cause) | Yes |
| 2 | dapo/cispo normalizer | num_items_in_batch / num_processes (total tokens across entire generation batch) (L2371) |
all_reduce(sum(attention_mask)) / world_size (current micro-batch only), then divided by current_gradient_accumulation_steps (Liger-Kernel L116-117, TRL L2194) |
Several-fold depending on length variance | Yes |
| 3 | tool_mask | completion_mask * tool_mask (L2243) |
completion_mask only (TRL L2178) |
Proportional to tool token ratio | Yes |
| 4 | use_bias_correction_kl | per_token_kl *= coef_1 (L2315-L2316) |
Not implemented | KL term only | Yes |
| 5 | delta (ratio clamping) | coef_1 = clamp(coef_1, max=delta) (L2326-L2327) |
Not implemented | Changes clipping behavior | Yes |
| 6 | off_policy_mask, top_entropy_quantile, sequence-level IS, sapo | Supported | Not supported | - | No (raises error) |
Where to fix
| # | Difference | Where to fix | Notes |
|---|---|---|---|
| 1 | vLLM IS correction | Liger-Kernel + TRL | Liger-Kernel: add parameter to apply per_token_loss *= is_ratio before reduction. TRL: pass it from compute_liger_loss |
| 2 | dapo/cispo normalizer | Liger-Kernel + TRL | Liger-Kernel: accept an external normalizer. TRL: pass num_items_in_batch |
| 3 | tool_mask | TRL only | Pass completion_mask * tool_mask in compute_liger_loss |
| 4 | use_bias_correction_kl | Liger-Kernel + TRL | Liger-Kernel: add flag to ppo_loss_fn. TRL: pass it |
| 5 | delta (ratio clamping) | Liger-Kernel + TRL | Liger-Kernel: add clamp argument for coef_1. TRL: pass it |
Observed behavior
With DAPO loss on a large model using vLLM in GRPOTrainer:
| Metric (step 1) | Liger-Kernel (use_liger_kernel=True) |
Non-Liger-Kernel |
|---|---|---|
grad_norm |
31.09 | 0.29 |
loss |
0.0187 | -0.0001 |
The IS ratio mean was ~0.003–0.01, so the non-Liger-Kernel path scales down the loss by that factor, while the Liger-Kernel path passes it through as-is.
Conclusion
The primary cause is # 1: vLLM IS correction is not applied in Liger-Kernel. Since the IS ratio must be multiplied before reduction, it cannot be fixed on the TRL side alone — a Liger-Kernel change is necessary. Only # 3 can be resolved with a one-line fix on the TRL side.
Minimal repro (vLLM IS correction)
I used a direct GRPOTrainer.compute_loss() repro (no rollout/generation), with fixed tensors and 5 steps.
import torch
from trl import GRPOConfig, GRPOTrainer
MODEL = "HuggingFaceTB/SmolLM2-135M"
B, P, T = 2, 8, 16
IS_RATIO = 0.01
STEPS = 5
BASE_SEED = 42
def reward_fn(prompts, completions, **kwargs):
return [1.0] * len(prompts)
def make_inputs(model, step):
device = next(model.parameters()).device
vocab = model.config.vocab_size
g = torch.Generator().manual_seed(BASE_SEED + step)
prompt_ids = torch.randint(10, vocab, (B, P), generator=g, dtype=torch.long).to(device)
completion_ids = torch.randint(10, vocab, (B, T), generator=g, dtype=torch.long).to(device)
prompt_mask = torch.ones_like(prompt_ids)
completion_mask = torch.ones_like(completion_ids)
return {
"prompt_ids": prompt_ids,
"prompt_mask": prompt_mask,
"completion_ids": completion_ids,
"completion_mask": completion_mask,
"advantages": torch.ones(B, device=device),
"old_per_token_logps": torch.full((B, T), -2.0, device=device),
"importance_sampling_ratio": torch.full((B, T), IS_RATIO, device=device),
"num_items_in_batch": float(completion_mask.sum().item()),
}
def grad_norm(model):
s = torch.zeros((), device=next(model.parameters()).device)
for p in model.parameters():
if p.grad is not None:
s = s + p.grad.float().pow(2).sum()
return s.sqrt().item()
def build_case(use_liger, use_vllm_is):
args = GRPOConfig(
output_dir="tmp_grpo_issue_repro",
max_steps=1,
per_device_train_batch_size=2,
num_generations=2,
gradient_accumulation_steps=1,
use_liger_kernel=use_liger,
use_vllm=False, # avoid server init in repro
vllm_importance_sampling_correction=use_vllm_is,
beta=0.0,
loss_type="dapo",
importance_sampling_level="token",
bf16=False,
fp16=False,
report_to="none",
save_strategy="no",
disable_tqdm=True,
)
trainer = GRPOTrainer(model=MODEL, reward_funcs=reward_fn, args=args, train_dataset=None)
trainer.use_vllm = True
trainer.vllm_importance_sampling_correction = use_vllm_is
trainer.current_gradient_accumulation_steps = trainer.args.gradient_accumulation_steps
model = trainer.model.cuda()
model.train()
return trainer, model
def run_step(trainer, model, step):
model.zero_grad(set_to_none=True)
loss = trainer.compute_loss(model, make_inputs(model, step))
loss.backward()
return grad_norm(model)
def run_case_steps(use_liger, use_vllm_is):
trainer, model = build_case(use_liger, use_vllm_is)
return [run_step(trainer, model, s) for s in range(STEPS)]
if __name__ == "__main__":
non_off = run_case_steps(False, False)
non_on = run_case_steps(False, True)
liger_off = run_case_steps(True, False)
liger_on = run_case_steps(True, True)
print("step | non_liger(off/on ratio) | liger(off/on ratio)")
for s in range(STEPS):
ratio_non = non_on[s] / non_off[s]
ratio_liger = liger_on[s] / liger_off[s]
print(f"{s+1:>4} | non_liger: {non_off[s]:.6e}->{non_on[s]:.6e}, ratio={ratio_non:.6f} | "
f"liger: {liger_off[s]:.6e}->{liger_on[s]:.6e}, ratio={ratio_liger:.6f}")
Observed output
step | non_liger(off/on ratio) | liger(off/on ratio)
1 | non_liger: 9.116095e-03->9.116097e-05, ratio=0.010000 | liger: 9.116122e-03->9.116122e-03, ratio=1.000000
2 | non_liger: 8.003094e-03->8.003095e-05, ratio=0.010000 | liger: 8.003096e-03->8.003096e-03, ratio=1.000000
3 | non_liger: 1.983273e-03->1.983274e-05, ratio=0.010000 | liger: 1.983265e-03->1.983265e-03, ratio=1.000000
4 | non_liger: 2.166789e-03->2.166788e-05, ratio=0.010000 | liger: 2.166775e-03->2.166775e-03, ratio=1.000000
5 | non_liger: 1.514107e-03->1.514108e-05, ratio=0.010000 | liger: 1.514113e-03->1.514113e-03, ratio=1.000000
mean ratio(non-liger, IS on/off): 0.010000
mean ratio(liger, IS on/off): 1.000000
@yukiu00 can this issue be closed?
@kashif Have you already fixed this? CC: @yukiu00
@kashif @shivam2199
Sorry for the delayed reply, @kashif.
As far as I can tell, only item # 1 has been fixed so far: the vLLM importance sampling correction is now applied in the Liger path. Since that was the primary cause of the ~100x larger grad_norm, the original 100x-scale discrepancy described in this issue is no longer present.
That said, the other differences listed in this issue are still unresolved as far as I know, so the Liger and non-Liger paths are not fully equivalent yet.
So, if the scope of this issue is the main ~100x grad_norm problem, I think it can be closed. If we want to track the remaining differences toward full parity, it would probably be better to handle them in separate issues.
thanks @yukiu00 I have fixed the remaining things in #1202 if you can check? Regarding tool mask, TRL pre-multiplies tool_mask into both inputs before Liger sees them, so Liger never operates on completion_mask alone in multi-turn scenarios.
@kashif I took another look at #1202, and also checked the current TRL main plus the latest TRL release tag I found (v1.2.0).
My read is:
- The original large
grad_normissue from this report, item #1, is fixed: the Liger path now has the vLLM importance sampling ratio path, and latest TRL already passesimportance_sampling_ratioasvllm_is_ratiointoLigerFusedLinearGRPOLoss. - For
tool_mask, I agree with your comment. Latest TRL buildsloss_mask = completion_mask * tool_maskbefore calling Liger, so that part is not a remaining Liger-side gap. - #1202 adds the Liger-side API/support for
num_items_in_batch,delta, anduse_bias_correction_kl, which is useful. However, this does not yet look end-to-end equivalent with latest TRL, because current TRLcompute_liger_lossstill only passesvllm_is_ratiotoself.liger_grpo_loss. It does not passnum_items_in_batch,delta, oruse_bias_correction_klinto the Liger loss path. The non-Liger path still usesinputs["num_items_in_batch"] / self.accelerator.num_processesfor DAPO/CISPO/VESPO, while the Liger path returnsloss / current_gradient_accumulation_steps.
So I think #1202 resolves more of the Liger-side missing pieces, but I would not call #1082 fully resolved as a parity issue until the TRL-side plumbing is updated to pass those new Liger args. If the scope is only the original ~100x grad_norm regression from missing vLLM IS correction, then yes, that specific problem is fixed.
@yukiu00 https://github.com/huggingface/trl/pull/5690 is the PR to add the missing arguments in TRL
@kashif thanks, I checked huggingface/trl#5690.
It covers most of what I mentioned: delta, use_bias_correction_kl, SAPO temps, and VESPO params are now passed to LigerFusedLinearGRPOLoss, and the Liger min version is bumped to >=0.8.0.
The only remaining gap I still see is num_items_in_batch. compute_liger_loss still does not pass num_items_in_batch=inputs["num_items_in_batch"] to the Liger loss, and it still divides the returned loss by current_gradient_accumulation_steps. For DAPO/CISPO/VESPO, the non-Liger path uses inputs["num_items_in_batch"] / self.accelerator.num_processes instead.
So #1202 + huggingface/trl#5690 look close, but I think that last normalizer path is still needed for full parity.
ok let me check
Verification note: the primary cause here (vLLM importance-sampling correction not applied in the Liger GRPO path) appears fixed on current TRL main — the liger path now receives vllm_is_ratio and TRL passes inputs["importance_sampling_ratio"] through (compute_liger_loss).
A/B on GB10 (DGX Spark, sm_121), TRL main @ 3e72f8e, liger-kernel 0.8.0, vllm 0.24.0, torch 2.11.0:
- Setup: GRPOTrainer, Qwen3-0.6B, gsm8k train[:256], vllm colocate, 30 steps, num_generations=8, num_iterations=4 (off-policy, so the IS correction engages), identical configs except
use_liger_kernel. use_liger_kernel=False: grad_norm min 0.80 / median 2.12 / max 4.56use_liger_kernel=True: grad_norm min 0.95 / median 2.23 / max 4.30
Same order of magnitude and same trajectory shape (not the ~100x reported on v0.27.2), and per-step rewards track between arms. Suggest this can be closed unless a remaining sub-item from the table is still reproducible on main.
@kashif would it make sense to split out top_entropy_quantile support (item # 6) into its own issue/PR, separate from the numerical-parity fixes (items # 1–5)? This needs new functionality (per-token entropy), which the Triton path doesn't compute anywhere today.
Looked at _selective_log_softmax_kernel in ops/grpo_loss.py - it already streams the vocab dimension in chunks with an online-logsumexp reduction (running m_i/l_i, rescaled via alpha on each update), and only ever emits LOG_P for the selected token; the per-chunk logits never leave the kernel. Entropy (Σ_v p_v · log p_v) needs the same full-vocab streaming reduction, so it looks like it can ride along in that same loop as a second running accumulator, rescaled by the same alpha correction whenever m_i updates — computed from chunk data that's already loaded.
Before I work on the implementation: would you want this as a flag on the existing kernel (e.g. return_entropy=True emitting a second (batch, seq) output alongside LOG_P), or would you rather it live as a separate kernel? And is top_entropy_quantile masking itself (the actual top-quantile selection before loss reduction) something you'd want handled in the Triton kernel too, or left to the Python-level chunked_loss/grpo_loss.py once per-token entropy comes back? Happy to draft an RFC or a first-pass PR once there's a preferred direction.
Two PRs that cover item 6 for the chunked LigerFusedLinearGRPOLoss path:
- #1557 adds
off_policy_mask_threshold(OPSM, DeepSeek-V3.2 Eq. 9), with an optionalsampling_per_token_logpsargument so drift can be measured against the sampler like TRL'sget_off_policy_mask. - #1558 adds
top_entropy_quantile, computing per-token entropy in a no-grad streaming pre-pass over the lm_head (second online accumulator alongside the logsumexp) and gathering the quantile threshold across ranks when distributed.
Both follow TRL's _compute_loss ordering (policy term, then the mask, then the vLLM IS ratio, then the KL term). As @sumehta noted above, the Triton path does not compute per-token entropy today, so #1558 is scoped to the chunked path only. Sequence-level IS and SAPO from item 6 are already supported on main.
#take
Hi @ByronHsu @tcc0403 @kashif (and cc @sumehta @nvdm59) — following up on the discussion above: since #1558 covers top_entropy_quantile on the chunked_loss path via a no-grad streaming pre-pass while the Triton _selective_log_softmax_kernel path in ops/grpo_loss.py still lacks per-token entropy, I'd like to take on adding single-pass online token entropy + top_entropy_quantile support for the Triton GRPO kernel (unless anyone already has a WIP branch for the Triton path).
Proposed Design
- Shift-invariant single-pass online entropy accumulator (
s_i) in_selective_log_softmax_kernel:- Instead of accumulating raw
sum(exp(u - m) * u)(which suffers FP32 catastrophic cancellation under large shared logit offsets, similar to#1535), track a non-negative shifted accumulator in FP32 alongside(m_i, l_i)across vocabulary tiles:s_new = alpha * s_old + (alpha * l_old) * (m_new - m_old) + sum(exp(-(m_new - u)) * (m_new - u))yieldingH = log(l_N) + s_N / l_Nin a single HBM streaming pass without materializing[B*T, V]probs/logits. - Gate all entropy loads/stores behind
COMPUTE_ENTROPY: tl.constexpr = Falseso default callers incur zero register or bandwidth overhead, and guard fully masked initial vocab tiles (m_i == -inf -> alpha = 0.0, aligned with#1653).
- Instead of accumulating raw
- Single-pass fused backward:
- Fuse
grad_log_probsand optionalgrad_entropy(g_h * p * (-log p - H)) into one vocabulary streaming pass whenentropy_coeff != 0.0, while keepingtop_entropy_quantilemasking as a pure stop-gradient mask matching upstream TRL.
- Fuse
- TRL-aligned
top_entropy_quantile& chunked integration:- Match
trl/trainer/grpo_trainer.py(get_high_entropy_maskwith1 - top_entropy_quantilethreshold and-1e9cross-rank gather padding perhuggingface/trl#3933) and wireops/grpo_loss.py+chunked_loss/grpo_loss.pyso callers can obtain exact per-token entropy in one forward pass without a separatelm_headGEMM pre-pass.
- Match
I have opened an initial Draft PR (#1678) with the kernel implementation, unit/convergence tests (large logit offset shift-invariance up to +1000, fully masked initial vocab tiles + finite-difference Jacobian checks, and multi-step DAPO + top_entropy_quantile convergence), and a V=151936 latency/HBM benchmark script — and will populate full GPU test & benchmark results before marking it Ready for Review. Happy to also open a dedicated tracking sub-issue linked to #1082 if you prefer!