Skip to content

feat(vllm): fp32 LM head for all models via vLLM head_dtype - #4922

Closed
nvegesna-netizen wants to merge 4 commits into
NVIDIA-NeMo:mainfrom
nvegesna-netizen:nvegesna/vllm-fp32-lm-head-all-models
Closed

nvegesna-netizen wants to merge 4 commits into
NVIDIA-NeMo:mainfrom
nvegesna-netizen:nvegesna/vllm-fp32-lm-head-all-models

Conversation

@nvegesna-netizen

@nvegesna-netizen nvegesna-netizen commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

Makes policy.generation.vllm_cfg.fp32_lm_head work for every model, not only Nemotron-H. It now sets vLLM's
native hf_overrides={"head_dtype": "float32"} (vllm-project/vllm#48390,
in the pinned vLLM 0.29.0) and removes the Nemotron-H-only source patch.

Issues

Follow-up to #4096. Today vllm_cfg.fp32_lm_head=true on any non-Nemotron-H model only produces a warning, and
generation keeps the BF16 head. The pairing that validate_fp32_lm_head_config enforces therefore ends up
effectively one-sided for Qwen, Llama and other models, which its own error message says makes the mismatch worse.

Changes

  • vllm_worker._apply_fp32_lm_head: when the flag is set, adds head_dtype="float32" to the engine's
    hf_overrides.
    • vLLM's LogitsProcessor then runs the lm_head GEMM on the BF16 operands with an FP32 output
      (torch.mm(..., out_dtype=float32)). That is the same GEMM as Megatron's logit_dtype=float32, which
      megatron_cfg.fp32_lm_head sets.
    • It works for any model whose lm_head is unquantized; the FP8 rollout path already excludes lm_head by
      default.
    • Unlike the old patch, it does not cast the lm_head weight to an FP32 copy on every step.
  • Removed: _patch_vllm_nemotron_h_fp32_lm_head, the NRL_VLLM_FP32_LM_HEAD env plumbing, and the
    non-Nemotron-H warning, together with the HF-config fetch that warning needed in Policy.__init__. Once
    head_dtype is set, vLLM never calls lm_head.forward or quant_method.apply, so the patch would be dead code.
  • Validation:
    • NRL_VLLM_FP32_LM_HEAD in vllm_cfg.env_vars is still rejected, now with "no longer read".
    • A head_dtype in policy.hf_config_overrides or generation.vllm_kwargs.hf_overrides is rejected, so the
      flag stays the single switch covered by the trainer-match check.
    • In the worker, a conflicting head_dtype override raises.
  • Tests:
    • New tests/unit/models/generation/test_vllm_fp32_lm_head.py, including a @pytest.mark.vllm test that pins
      vLLM's head_dtype contract.
    • Nemotron-H patch tests removed. The routed-experts-capture threading coverage they carried is kept as two
      smaller tests.
  • Functional test (tests/functional/vllm_fp32_lm_head.sh): now checks the numerics directly instead of a log
    line.
    • It uses logprobs_mode="raw_logits", so vLLM returns the sampled token's raw logit.
    • With the BF16 head (control), every value is BF16-representable. With the FP32 head, at least half must be off
      the BF16 grid.
    • It runs on Qwen3-0.6B (tied embeddings) and NVIDIA-Nemotron-3-Nano-4B (the previously supported path).

Usage

policy:
  megatron_cfg:
    fp32_lm_head: true
  generation:
    vllm_cfg:
      fp32_lm_head: ${policy.megatron_cfg.fp32_lm_head}  # already the default wiring in the example configs

Validation

Run on H200 ×2 with the locked environment (uv sync --locked --extra vllm --group test, vLLM 0.29.0), main at
4d464d5 vs this PR:

Check main this PR
Unit: test_vllm_patches.py, test_policy_validation.py, test_vllm_fp8_hf_overrides.py, test_vllm_fp32_lm_head.py (new) 68 passed, 21 errors 62 passed, 21 errors
Unit, --vllm-only 16 passed 16 passed
Functional, Qwen/Qwen3-0.6B (tied embeddings) — PASS: 16/16 sampled raw logits off the bf16 grid (bf16 head: 0/16)
Functional, nvidia/NVIDIA-Nemotron-3-Nano-4B-BF16 — PASS: 16/16 off the bf16 grid (bf16 head: 0/16)
Mutation: _apply_fp32_lm_head forced to a no-op — functional check FAILS as intended (fp32 head looks bf16-rounded)
  • The 21 errors are the same tests on both sides. All are gated-repo 401s (meta-llama/Llama-3.2-1B) because the
    runner had no HF token.
  • Test-count change: 23 Nemotron-H patch tests are removed and 17 new tests are added. The --vllm-only count
    stays at 16: the new head_dtype contract test replaces the Nemotron-H source-anchor test.
  • TP=2 with CUDA graphs (a separate check, not part of this PR's tests): GH200, tensor_parallel_size=2,
    enforce_eager=False (FULL_AND_PIECEWISE graphs captured).
    • raw_logits: fp32 head 64/64 off the bf16 grid, bf16 head 0/64, on both models.
    • processed_logprobs (what training consumes): every matched greedy token differs between the bf16 and fp32
      heads (42/42 Qwen, 51/51 Nemotron; mean |Δ| ≈ 0.013–0.015). So the fp32 logits reach log_softmax; vLLM's
      sampler only upcasts.
  • Environment: the functional test ran with NEMO_RL_PY_EXECUTABLES_SYSTEM=1, so all actors share one venv, and
    with deep_ep/deep_gemm not installed. Neither is used by these models.

Why this matters: on Qwen3-8B GRPO in NeMo-RL (grpo_math_8B_megatron, nightly 3cde458 with vLLM 0.29.0, one
GB200 node per arm, 3 steps, seed 42, plus a replicate), an FP32 LM head on both sides cut gen_kl_error 74%
(7.5e-4 → 2.0e-4; the replicate is within 2%) and token_mult_prob_error − 1 by 49%. Megatron's FP32 head alone
gives only −37%. Setting policy.generation.vllm_kwargs.hf_overrides.head_dtype by hand does not work in GRPO:
grpo.py overwrites vllm_kwargs["hf_overrides"] with policy.hf_config_overrides (ppo.py and distillation.py do
the same), so the override never reaches vLLM. (The two-sided run above patched that line to merge the dicts.) This
PR sets head_dtype inside the vLLM worker, after that overwrite. Today a two-sided setup only works for
Nemotron-H, because NeMo-RL rejects one-sided configs; this PR makes it reachable for other models.

Before your PR is "Ready for review"

Pre checks:

  • Make sure you read and followed Contributor guidelines
  • Did you write any new necessary tests?
  • Did you run the unit tests and functional tests locally? (on an H200 node; see Validation)
  • Did you add or update any necessary documentation? (config docstrings and example-config comments; no docs page mentions the flag)

Additional Information

🤖 Generated with Claude Code

vllm_cfg.fp32_lm_head now sets vLLM's native hf_overrides
head_dtype="float32" (vllm-project/vllm#48390, in the pinned 0.29.0),
which runs the lm_head GEMM on the bf16 operands with an fp32 output for any
model whose lm_head is unquantized. That is the same GEMM as Megatron's
logit_dtype=float32 (policy.megatron_cfg.fp32_lm_head), so the matched pair
now removes the head's bf16 rounding from the generation/training logprob
mismatch for every model, not only Nemotron-H.

With head_dtype set, vLLM's LogitsProcessor no longer calls lm_head.forward
or quant_method.apply, so the Nemotron-H source patch would be dead code; it
is removed together with its env-var plumbing and the non-Nemotron-H warning.
NRL_VLLM_FP32_LM_HEAD in vllm_cfg.env_vars and a head_dtype in the hf
overrides are rejected so the flag stays the single, validated switch.

The functional test now checks the result instead of a log line: with
logprobs_mode=raw_logits the sampled token's raw logit is bf16-representable
with the bf16 head (control) and off the bf16 grid with the fp32 head, on
Qwen3-0.6B (tied embeddings) and Nemotron-3-Nano-4B.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Nitin Vegesna <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Oct 26, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@nvegesna-netizen nvegesna-netizen left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Self-review by a review team: RL code, vLLM upstream, tests, bug scan, design, PR history, and a devil's-advocate pass that challenged every finding. No finding reached the bar for an ask. Below is what was checked, then two notes for later.

Checked against the pinned code

  • vLLM side. The pinned vLLM 0.29.0 contains vllm-project/vllm#48390. With head_dtype="float32", LogitsProcessor._apply_head runs the head GEMM on the bf16 operands with an fp32 output (torch.mm(..., out_dtype=self.head_dtype)). The logits stay fp32 through the TP gather and the sampler, for both logprobs_mode values. A quantized lm_head raises when the engine starts, so it cannot fail silently.
  • Megatron side. megatron_cfg.fp32_lm_head sets logit_dtype = torch.float32, and Megatron-Core's _linear_forward also runs bf16 operands with an fp32 output. The precision matches vLLM; the kernels differ, so the logits are close but not bit-for-bit equal.
  • Every vLLM worker gets the setting. The sync, async and both quantized workers build their engine through _load_model, which calls _apply_fp32_lm_head after _merge_fp8_kwargs. The async worker reuses it (vllm_worker_async.py). Later steps only add quantization_config, so head_dtype is kept.
  • Every model NeMo-RL runs. All 244 compute_logits definitions in vLLM at the pinned commit were checked. Every model NeMo-RL uses goes through _apply_head, including tied embeddings, VLM wrappers and MTP/EAGLE draft heads.
  • No leftovers. Nothing in the repo still refers to the removed Nemotron-H patch, its env plumbing or its helpers.
  • The legacy env-var rejection is needed. Two recipes on super-v3.5-posttraining set NRL_VLLM_FP32_LM_HEAD: '1' (reasoning_teacher.yaml, student_rlvr.yaml). When they reach main, the "no longer read" error stops them from silently running a bf16 head.
  • The functional check is sound. With raw_logits, a bf16 head can only give values on the bf16 grid, even after soft-capping and scaling; an fp32 head gives almost none. The >= half threshold is far from flaky, and the bf16 control run catches a check that silently does nothing. The test runs in L1, on every merge group and push to main, so a vLLM bump that stops honoring head_dtype, or a refactor that drops the _apply_fp32_lm_head call, cannot merge unnoticed.
  • Lint. ruff and ruff-format pass on the changed files.

Notes for later (not asks for this PR)

Not verified in this review: nothing ran on a GPU or on a real vLLM install. The GPU results are the H200/GH200 runs in the description.

Generated by Claude Code

Resolve the conflict in nemo_rl/models/policy/utils.py: keep main's
LoRA refit helpers (#3964) and drop the _NEMOTRON_H_* constants, which
this branch no longer uses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Nitin Vegesna <[email protected]>
@guyueh1 guyueh1 added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Nov 2, 2026
@guyueh1

guyueh1 commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

/ok to test e64fb77

@copy-pr-bot

copy-pr-bot Bot commented Nov 2, 2026

Copy link
Copy Markdown

/ok to test e64fb77

@guyueh1, there was an error processing your request: E2

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/

@guyueh1

guyueh1 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

@nvegesna-netizen this is a nice cleanup overall, but the vllm head_dtype=float32 and the current NemotronH patch have a difference:

  • current NemotronH patch cast the hidden and weight to float32 first and then execute the torch.matmul
  • vllm head_dtype=float32 calls torch.mm(hidden, weight.T, out_dtype=float32)

My understanding is, the two are numerically same if the torch.mm(..., out_dtype-float32) uses FP32 accumulation in its GEMM. The numerical equivalence can be broken if the torch.mm internally uses a Reduced Precision Reduction (https://docs.pytorch.org/docs/2.15/notes/numerical_accuracy.html#reduced-precision-reduction-for-fp16-and-bf16-gemms). Do you think we should additionally patch the vllm's shared logit process inside a context that use torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = (False, False) to ensure numerical equivalence to the existing patch? or is there other ways to guarantee this.

@guyueh1

guyueh1 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

/ok to test e64fb77

@nvegesna-netizen

Copy link
Copy Markdown
Contributor Author

Thanks, good question. Short answer: the context manager isn't needed, and the head_dtype path is actually a closer match to the trainer than the old patch was.

I checked on a B200 (torch 2.13.0+cu130, TE 2.18.0) with Qwen3-8B head shapes (hidden size 4096, vocab 151,936), batch sizes 1–2048:

  1. RPR has no effect here. torch.mm(..., out_dtype=fp32) gives bit-identical logits with allow_bf16_reduced_precision_reduction on and off (checked on torch 2.9). This matches the cuBLAS docs: the flag only matters when the output dtype is narrower than the accumulation dtype, and here both are FP32.
  2. vLLM's head_dtype=float32 matches the trainer bit-for-bit. Megatron's fp32_lm_head runs the same GEMM (bf16 inputs, FP32 output) through TE's general_gemm. Running that call and vLLM's on the same inputs gives identical logits at every batch size, so the log-prob difference is exactly 0.
  3. The old upcast patch did not match. Its log-probs differ from the trainer's by up to ~2e-4, with TF32 on or off. That's small, but this PR removes it. For scale, a bf16 head differs by ~0.1.

These comparisons use equal batch sizes on both sides. In real runs the trainer and vLLM batch tokens differently, and cuBLAS may then pick different kernels, so individual logits can differ in the last FP32 bits. Precision stays the same.

@guyueh1

guyueh1 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

sounds good

@nvegesna-netizen

Copy link
Copy Markdown
Contributor Author

/ok to test 52ae9fc

@nvegesna-netizen nvegesna-netizen self-assigned this Nov 3, 2026
@guyueh1 guyueh1 added CI:L2 Run doctests, unit tests, functional tests, and convergence tests and removed CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) labels Nov 3, 2026
@guyueh1

guyueh1 commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

/ok to test 52ae9fc

@guyueh1

guyueh1 commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

/ok to test 1cf892c

@ZhiyuLi-Nvidia

Copy link
Copy Markdown
Contributor

Thank you @nvegesna-netizen. Awesome and clean PR. LGTM!

@ZhiyuLi-Nvidia
ZhiyuLi-Nvidia enabled auto-merge (squash) November 3, 2026 23:54
auto-merge was automatically disabled November 4, 2026 00:46

Pull request was closed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:L2 Run doctests, unit tests, functional tests, and convergence tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants