Skip to content

feat: add end-to-end TE NVFP4 training with per-token vLLM rollout - #3566

Merged
terrykong merged 67 commits into
NVIDIA-NeMo:mainfrom
zhangyimi:codex/nvfp4-pertoken-draft-main-20260805
Sep 19, 2026
Merged

terrykong merged 67 commits into
NVIDIA-NeMo:mainfrom
zhangyimi:codex/nvfp4-pertoken-draft-main-20260805

Conversation

@zhangyimi

@zhangyimi zhangyimi commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

This PR addresses #3432 by adding an opt-in end-to-end NVFP4 W4A4
reinforcement-learning path on NVIDIA Blackwell GPUs, demonstrated with
Qwen3-30B-A3B-Base GRPO. It upgrades the shared vLLM runtime from 0.25.1 to
0.26.0 for per-token NVFP4 support and includes ModelOpt refit compatibility
fixes required by that upgrade. Additional changes fix existing FP8
checkpoint-name mapping and generation-router probe handling.

During policy training, Transformer Engine applies NVFP4 to routed-expert MLP
computation with per-token activation scaling. The model retains BF16
parameters and FP32 optimizer states, and the current backward path is
dequantized. After each policy update, NeMo RL exports BF16 Hugging Face-named weights
through Megatron Bridge and refits colocated vLLM engines. The vLLM worker
quantizes and packs routed-expert weights while loading each refit, then uses
pre-quantized NVFP4 expert weights with dynamic per-token activation scaling
during rollout.

The architectural boundary is explicit: training owns the BF16 policy weights,
refit transports BF16, and the rollout worker owns quantization into its serving
representation. W4A4 applies to selected routed-expert computations, not the
whole model, optimizer state, or weight-transfer format.

Implementation

  • Adds TE FP4 configuration, a per-module precision recipe for routed-expert
    NVFP4 computation, and FP4 token alignment. Keeps persistent policy weights
    in BF16 and rejects incompatible FP8/FP4 settings and FP4 parameter storage
    when generation/refit is enabled. An explicit BF16 catch-all protects
    attention, dense MLPs, and shared experts. Startup validation parses the
    effective training and evaluation recipes, including inherited autocast
    behavior, and validates the required TE environment settings.
  • Keeps the Megatron policy worker refit stream in BF16 and performs block-16
    NVFP4 routed-expert weight quantization inside the vLLM worker during native
    layerwise reload.
  • Registers an nvfp4_pertoken vLLM quantization mode and integrates it with
    vLLM's layerwise reload lifecycle while preserving CUDA-graph parameter
    storage.
  • Uses vLLM's native weight loaders for sharding and adds complete-refit checks,
    IPC lifetime handling, and fatal error propagation rather than serving stale
    weights. Pipeline-parallel limitations are noted below.
  • Derives rollout BF16 boundary-layer exclusions from Megatron configuration.
    Determines model eligibility from constructed routed-expert capabilities and
    checkpoint mappings rather than an architecture-name allowlist.
  • Restores expert-routing capture for monolithic fused-MoE kernels so router
    replay / R3 receives the routing information required by the training path.
  • Adds a Qwen3-30B-A3B-Base long-run recipe and a Qwen3-30B-A3B quick recipe,
    unit coverage, a 20-step GB200 nightly smoke test, and an end-to-end usage
    and design guide. The 8-node driver is manual-only; the 4-node quick test
    is registered in nightly_gb200.txt.
  • Rejects vLLM PP>1 in both synchronous and asynchronous engine modes and
    rejects SingleController at configuration validation. GRPO is the validated
    entry point; PPO and distillation emit coverage warnings.
  • Updates the vLLM/FlashInfer runtime and Transformer Engine dependencies
    required by this path.

Compatibility fixes required by the vLLM 0.26 upgrade

The vLLM upgrade changes Nemotron-H weight loading to delegate through
AutoWeightsLoader to each RoutedExperts layer. This exposes two regressions
in existing ModelOpt refit paths, addressed here:

  • Nested quantizer-buffer loading: the new loader uses single-level
    getattr, so it cannot resolve names such as w13_input_quantizer._amax.
    Add temporary aliases during refit, with scoped setup and cleanup in
    patches.py.
  • Non-gated expert-weight loading: the new loader interprets rank-3
    w13 payloads as fused gate/up tensors. Emit non-gated batched weights as
    per-expert payloads so they load correctly under vLLM 0.26.

These changes preserve existing ModelOpt refit behavior after the shared
runtime upgrade. The associated FlashInfer/CUTLASS/Quack dependency alignment
and package-source changes are detailed below.

Other fixes to existing paths

  • Generation-router probe handling: handles an aiohttp
    ClientConnectionResetError during /v1/models probing with a 404 response
    without marking the backend unhealthy or evicting it. Other forwarding
    failures retain the existing health handling. Adds failure logging and a
    regression test for the disconnected-probe case.
  • FP8 checkpoint-name resolution: extracts a resolver shared by FP8 and
    NVFP4 and fixes dotted prefix/substring mapping on the existing FP8 path.
    A failed lookup returns None instead of a partially traversed parent.
    DeepSeek V4 retains its full checkpoint mapper, applied once before packed
    module resolution. This includes behavior fixes as well as code reuse.

NeMo Gym dataset compatibility after the lockfile refresh

The lockfile refresh also resolved datasets from 5.0.0 to 5.0.1 and
pyarrow from 24.0.0 to 25.0.1, without changing their direct requirements.
Datasets 5.0.1 introduced chunk-independent fingerprinting:
when hashing an in-memory Arrow table to produce its dataset fingerprint, its
serializer calls combine_chunks() on each column.

NemoGymDataset stores each raw JSONL line in extra_env_info. For the large
SWE1, RLVR, and MOPD inputs, the combined column exceeds ordinary Arrow
string's approximately 2 GiB limit for 32-bit offsets. Construction therefore
fails inside fingerprinting with ArrowInvalid: offset overflow while concatenating arrays, before training starts. Smaller inputs stay below this
limit, which explains why other dataset jobs could pass.

Declare extra_env_info as Value("large_string") when constructing the
dataset, providing 64-bit offsets, and retain task_name as Value("string").
This preserves the raw JSON values and repetition behavior and works with
Datasets 5.0.1/PyArrow 25.0.1 without a dependency downgrade.

Dependency updates

This PR upgrades the shared runtime, not only the NVFP4 path. Reviewers of other
recipes should be aware of these:

Dependency Before After
vLLM 0.25.1 0.26.0
flashinfer-python / -cubin / -jit-cache (vLLM extra) 0.6.13 0.6.14
nvidia-cutlass-dsl (vLLM extra) 4.5.2 4.6.0
quack-kernels No explicit vLLM-extra pin Explicit vLLM-extra pin to 0.6.1
nvidia-modelopt c3b913b9 43fd41a5
Transformer Engine (override) release_v2.15 2.18.0 release package

vLLM upgrade: per-token NVFP4 rollout uses vLLM 0.26's
make_nvfp4_moe_kernel(..., per_token_activation=True) interface. The vLLM
extra is aligned to FlashInfer 0.6.14, CUTLASS DSL 4.6.0, and Quack 0.6.1.
The upgrade also requires the following package-resolution changes:

  • Replace the global nvidia-cutlass-dsl-libs-base exclusion with dependency
    metadata overrides for CUTLASS 4.5.0–4.5.2, allowing 4.6.x to retain its
    required libs-base/libs-core packages.
  • Resolve flashinfer-cubin through the official FlashInfer index across
    extras, instead of restricting that source to SGLang. Version requirements
    remain per extra: vLLM requests 0.6.14; MCore requests 0.6.8.post1. This source
    mapping does not add the package to extras that do not depend on it.

TE NVFP4 training dependencies: the TE and ModelOpt version changes support
the training path and its TE compatibility requirements.

  • Switch TE from the release_v2.15 Git build to
    transformer-engine[pytorch,core_cu13]==2.18.0. The release separates the
    CUDA 13 core binaries
    from the Torch extension package.
    Both no-build-isolation-package and the torch dependency with
    match-runtime=true remain configured for transformer-engine-torch.
    Removing the old monolithic-package entries does not remove those extension
    build settings. The locked Torch version remains 2.11.0+cu130.
  • Docker sets NVTE_WITH_NCCL_EP=0 by default; custom builds can opt in with
    --build-arg NVTE_WITH_NCCL_EP=1.

Issues

Related to #3432

Usage

The Qwen3-30B-A3B-Base configuration behind the results below, on 8 nodes with
4 GB200 GPUs per node:

uv run examples/run_grpo.py \
  --config examples/configs/recipes/llm/grpo-qwen3-30ba3b-base-8n4g-megatron-te-nvfp4-pertoken.yaml

See docs/design-docs/te-nvfp4-per-token-rollout.md for the complete
configuration and execution flow.

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? Visit our Testing Guide for how to run tests
  • Did you add or update any necessary documentation? Visit our Document Development Guide for how to write, build and test the docs.

Additional Information

Validation

Coverage shipped in this revision

  • Targeted unit tests cover NVFP4 quantization and packing, refit expansion and
    reload, setup validation, TE FP4 configuration, Megatron worker integration,
    boundary-layer exclusions, ModelOpt compatibility, and routing capture.
    Regression cases also cover effective precision in training/evaluation,
    renamed recipe keys, BF16 fallback ordering, unsupported PP/SingleController
    configurations, DeepSeek mapping, disconnected router probes, and combined
    FP32-LM-head/NVFP4 patch configuration.
  • The registered GB200 quick smoke runs 20 steps on 4 nodes with 4 GPUs per
    node
    . It checks the selected backend and precision path, at least 20
    quantized refits, stable expert-group counts, and rollout artifacts for every
    step.
  • Smoke metric gates require mean generation KL error below 0.02, median
    token-probability ratio error below 1.5, positive reward and valid samples,
    finite loss/gradient norms, and nonzero gradients.
  • The 8-node recipe provides longer GRPO validation with periodic checkpoints;
    it is separate from the registered quick nightly smoke.

These describe committed test coverage, not a claim that all tests have passed
on every subsequent revision.

DFW nightly validation against reference

Compared PR DFW pipeline 68569004
with reference 68179588,
covering 134 matching tests on H100. Counts use the latest attempt per test.

The reference tested RL commit b03da0f469cdb2882bda83c0f04317c6159ed266;
the PR pipeline tested 2e13bf9f8b2d9dd8a5bddb09e3db6141a1b72a11.
The revisions differ by nine upstream-main commits plus the PR changes, and
use different CI revisions, so this comparison alone does not establish causality.

Run Passed Failed
Reference 77 57
PR, initial attempts 75 59
PR, after clean reruns 94 40

Initially, 23 tests failed only in the PR run. All 23 were retried with
fresh experiment state at the same tested PR commit, with training-start
evidence verified and target-step skips excluded:

  • 19 passed, including the NVFP4 distillation test,
    which completed 25 training steps and all seven checks.
  • Four reproducibly failed during NeMo Gym dataset construction, before
    training, with Arrow string-offset overflow.

After those retries, 73 tests passed in both pipelines, 36 failed in both,
four failed only in the PR pipeline, and 21 passed in the PR pipeline but
failed in the reference.

Dataset failure and validated fix

The lockfile refresh resolved Datasets 5.0.1 and PyArrow 25.0.1. Datasets 5.0.1
introduced chunk-independent fingerprinting,
which combines Arrow chunks while hashing an in-memory dataset. NeMo Gym
stores raw JSONL lines in extra_env_info; these large inputs exceed ordinary
Arrow strings' approximately 2 GiB offset limit.

Fix 50f7ed0b1
explicitly stores that column as large_string, using 64-bit offsets.
Dependency versions remain unchanged.

All four cases then passed full local Slurm runs on 2e13bf9f8b2d plus
the schema fix, using fresh experiment directories and the original training
targets and metric thresholds:

Test Failed GitLab job Passing Slurm job Steps Metric checks
Qwen3-1.7B Super SWE1, 1 node × 8 GPUs 446139543 18926860 5/5 3/3 passed
Qwen3-1.7B Super RLVR, 6 nodes × 8 GPUs 446109684 18926861 5/5 3/3 passed
Qwen3-30B-A3B Thinking async SWE1, 16 nodes × 8 GPUs 446109683 18926862 3/3 1/1 passed
Qwen3-1.7B packed MOPD, 3 nodes × 8 GPUs 446109730 18926863 5/5 2/2 passed

All four exited successfully without Arrow overflow; all nine metric checks
passed
with Datasets 5.0.1 / PyArrow 25.0.1. W&B uploads were disabled.
MOPD's allocation increased from 18 to 45 minutes for local startup; it
completed in 7m48s.

The updated PR checkout also passed CPU loader smoke job 18928236, verifying
raw JSON and Unicode preservation, task names, Arrow types, fingerprinting,
and repetition, plus focused lint, formatting, and type checks. Its loader's
executable code matches the version used in the four full runs.

Interpretation

All 23 initially PR-only failures now have passing evidence: 19 through clean
GitLab retries and four through validation of the schema fix. The GitLab
pipeline itself remains 94 passed / 40 failed. The 36 shared failing tests
were not revalidated; matching failed statuses do not imply matching causes.
These results do not constitute a full-suite pass on the current PR head.

Recorded GB200 nightly result

The registered 4-node × 4-GPU GB200 nightly passed all 20 steps and all test
checks in 31m26s, within the 90-minute limit, with
NRL_FORCE_REBUILD_VENVS=true (2026-09-18, commit 2e13bf9f8, job 2849377).

All seven metric checks passed:

Metric Recorded value Requirement
Minimum valid samples 16 > 0
Mean generation KL error 0.00826177 < 0.02
Median token-probability ratio error 1.06359762 < 1.5
Maximum reward 1.0 > 0
Loss finite at every step True True
Gradient norm finite at every step True True
Mean gradient norm after step 1 0.15925850 > 0

Representative performance

Qwen3-30B-A3B-Base on 8 nodes with 4 GB200 GPUs per node. Both reported runs
enable R3/router replay. All values are medians over the 900 logged steps shared
by the two runs.

The columns identify the BF16-rollout baseline and the NVFP4 W4A4 path.
The exact training-precision configuration of the historical baseline and
immutable run/config references still need to be attached. Until then, treat
these as representative end-to-end run results, not a controlled ablation
establishing that rollout precision was the only changed setting.

Metric BF16 rollout baseline NVFP4 W4A4 path Change
Rollout generation throughput 472.9 tokens/s/GPU 661.4 tokens/s/GPU 1.40x
Generation time 220.5 s 154.6 s 1.43x faster
Observed step time 276.4 s 237.2 s 14.2% lower
Token-normalized end-to-end throughput 367.1 tokens/s/GPU 421.1 tokens/s/GPU 1.15x
Policy training throughput 3,196 tokens/s/GPU 2,681 tokens/s/GPU 0.84x
Weight transfer/update 1.8 s 19.2 s 17.4 s higher
Median response length 5,608 tokens 5,612 tokens 1.00x
Rollout model weights 56.88 GiB 18.07 GiB 68.2% lower
KV-cache capacity 331,744 870,560 2.62x

Median response length matches to within 0.1%, limiting response-length
variation as an explanation for the throughput difference. The missing
baseline configuration still prevents treating this as an isolated precision
comparison. NVFP4 W4A4 is applied only to routed-expert MLPs; the other modules remain BF16, and
the NVFP4 result includes quantization and weight refit after each policy
update.

There is still substantial headroom on every part of the step. Refit is the
largest added overhead and is profiled in the design doc. Measured policy
training throughput is also lower; the NVFP4 path currently uses dequantized
backward computation, but the table alone does not isolate the cause of the
training-throughput difference. The rollout numbers were measured with
conservative quantization-kernel settings, so generation has room to improve as
well. Follow-up work is planned on all three. The memory figures describe the
vLLM rollout model and KV cache, not the peak memory of the complete colocated
RL process.

Current scope and follow-up

  • End-to-end evidence: Qwen3-30B-A3B GRPO in the registered 4-node GB200
    smoke and historical Qwen3-30B-A3B-Base results on 8 nodes. The 8-node recipe
    uses Megatron TP=2 / EP=8 / PP=1 and colocated vLLM TP=1 / EP=1 / PP=1.
    Runtime results are tied to the revisions stated above.
  • Model and algorithm coverage: eligibility uses routed-expert capabilities
    and checkpoint mappings. Other architectures, dense/hybrid layouts, PPO,
    and distillation have no end-to-end validation established here. Dense-only
    models and fused shared-expert layouts are rejected. SingleController is
    explicitly rejected during setup.
  • Runtime constraints: Megatron training and colocated vLLM rollout,
    default CUDA IPC refit (refit_transport=null), vLLM PP=1 / EP=1,
    BF16 engine precision, kv_cache_dtype=auto, and the FlashInfer TRT-LLM
    NVFP4 backend. vLLM PP>1 is rejected for both synchronous and asynchronous
    engines; this restriction is on rollout PP. Standalone evaluation,
    speculative decoding, and competing quantization/load-format overrides
    are unsupported.
  • Precision contract: routed-expert NVFP4 with BF16 attention, dense/shared
    linears, and configured boundary layers. The shipped recipe has a final
    BF16 catch-all; setup checks effective training and evaluation settings on
    representative module paths, and trainer/rollout checks enforce boundary
    agreement. These guards do not establish end-to-end support for additional
    model architectures.

Follow-up work includes support for cross-stage vLLM PP refits, refit
optimization, native NVFP4 backward computation, and longer stability and
model-quality studies. The faster fused-expert refit prototype discussed in
the design doc is not included. Shared vLLM patch-version enforcement and
executor consolidation remain tracked in #4155. The review question about
whether captured router top-k choices exactly match the fused TRT-LLM kernel's
choices still needs direct evidence; routing-capture coverage alone does not
establish that equivalence.

Historical 900-step quality comparison

The same two runs, over their first 900 shared steps. Blue is the BF16 baseline;
orange is NVFP4 W4A4 per-token rollout.

Qwen3-30B-A3B-Base GRPO, BF16 versus NVFP4 W4A4 per-token rollout: reward, validation accuracy, response length, rollout throughput, train-rollout logprob error, generation KL error, entropy, and policy training throughput

Reward, response length, and validation accuracy track the BF16 baseline, and
entropy does not collapse. The train-rollout logprob error stays near its ideal
value of 1.0 for both runs. Generation KL error is higher under W4A4, which is
the expected cost of a quantized rollout. These observations are limited to
the reported 900-step window; longer stability validation remains follow-up
work.

@copy-pr-bot

copy-pr-bot Bot commented Aug 10, 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.

@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Aug 10, 2026
sharonyu-115 added a commit to sharonyu-115/RL that referenced this pull request Aug 19, 2026
… reload

wandb comparison against the pr3566verify campaign (same recipe, only this
branch's vLLM-side quantization differs) surfaced two gen_kl_error spikes
(~9x median) at steps 42 and 78 that never occur across pr3566verify's
544-step history. train/policy_kl_error explodes at the same steps
(73.7, 79714.5), the signature of training recomputing a wildly different
probability than what was actually generated for a sampled token.

Root cause: NvFp4PerTokenQuantizer.process() cloned pending gate/up halves
before buffering them, but handed passthrough tensors (attention, router,
embeddings, shared experts, ignored-BF16 expert layers) straight through as
views into the shared IPC buffer. vLLM's layerwise reload buffers every
weight_loader call's arguments — including the tensor — and replays them at
layer completion (vllm/model_executor/model_loader/reload/layerwise.py),
which can land after the sender has recycled this batch's buffer for a
later one (see policy/utils.py's ping-pong double buffering). Confirmed
against vLLM 0.26.0 source: `bound_args = loader_signature.bind(*args,
**kwargs)` retains the tensor argument by reference, not by value.

This is the "cross-batch staleness on passthrough tensors" defect reported
separately against PR NVIDIA-NeMo#3566 (upstream, out of scope for this refactor) but
it also applies here: this quantizer's own passthrough path had the same
gap. Clone every passthrough tensor, matching the pending-half clone
already in place.

Signed-off-by: Shuang Yu <[email protected]>
zhangyimi pushed a commit to zhangyimi/RL that referenced this pull request Aug 25, 2026
… worker

PR NVIDIA-NeMo#3566 quantizes routed-expert weights on the Megatron training worker,
inside the HF-export iterator, and fuses each expert layer into transport
tensors that the vLLM worker expands back before load_weights. This makes
NVFP4 a parallel architecture instead of a sibling of the existing FP8/MXFP8
"real quant" rollout path (quantize on the vLLM side at refit-load time).

Move quantization to the vLLM worker: NvFp4PerTokenQuantizer quantizes
routed-expert projections in NvFp4PerTokenWorkerExtension._load_hf_weights,
stateful only over a single gate/up pair (never a whole layer), so the refit
stream reverts to plain BF16 and becomes byte-identical to a BF16 run. The
Megatron worker's HF-export iterator collapses back to its pre-PR shape
(_iter_params_with_optional_kv_scales_impl is byte-identical to
origin/main's _iter_params_with_optional_kv_scales); it keeps maybe_init_zmq
(sender-side timeout) and all FP4 training-side code untouched.

nvfp4_pertoken.py and nvfp4_pertoken_vllm.py merge into a single vLLM-side
module (nvfp4_pertoken.py), matching fp8.py's naming: bare <format>.py is
the vLLM-side quantizer, and the file is no longer vLLM-free at module
scope. get_module_from_param_name moves from a private fp8.py helper to a
shared one, reused to probe a layer's owning quant method (the mechanism by
which additional_ignore BF16 expert layers are honored on the vLLM side).

Two PR NVIDIA-NeMo#3566 defects found during review are out of scope for this change
and are reported separately: cross-batch staleness in the layerwise
reloader's retained BF16 passthrough tensors, and the policy.quant_cfg /
generation.quant_cfg guard-gap in the mutual-exclusion check.

Signed-off-by: Shuang Yu <[email protected]>
@sharonyu-115 sharonyu-115 added the CI:L1 Run doctests, unit tests, and functional tests label Aug 25, 2026
@sharonyu-115

Copy link
Copy Markdown
Contributor

/ok to test 713997d

@zhangyimi
zhangyimi force-pushed the codex/nvfp4-pertoken-draft-main-20260805 branch from 3f81e10 to 048263c Compare August 25, 2026 09:12
zhangyimi pushed a commit to zhangyimi/RL that referenced this pull request Aug 25, 2026
… worker

PR NVIDIA-NeMo#3566 quantizes routed-expert weights on the Megatron training worker,
inside the HF-export iterator, and fuses each expert layer into transport
tensors that the vLLM worker expands back before load_weights. This makes
NVFP4 a parallel architecture instead of a sibling of the existing FP8/MXFP8
"real quant" rollout path (quantize on the vLLM side at refit-load time).

Move quantization to the vLLM worker: NvFp4PerTokenQuantizer quantizes
routed-expert projections in NvFp4PerTokenWorkerExtension._load_hf_weights,
stateful only over a single gate/up pair (never a whole layer), so the refit
stream reverts to plain BF16 and becomes byte-identical to a BF16 run. The
Megatron worker's HF-export iterator collapses back to its pre-PR shape
(_iter_params_with_optional_kv_scales_impl is byte-identical to
origin/main's _iter_params_with_optional_kv_scales); it keeps maybe_init_zmq
(sender-side timeout) and all FP4 training-side code untouched.

nvfp4_pertoken.py and nvfp4_pertoken_vllm.py merge into a single vLLM-side
module (nvfp4_pertoken.py), matching fp8.py's naming: bare <format>.py is
the vLLM-side quantizer, and the file is no longer vLLM-free at module
scope. get_module_from_param_name moves from a private fp8.py helper to a
shared one, reused to probe a layer's owning quant method (the mechanism by
which additional_ignore BF16 expert layers are honored on the vLLM side).

Two PR NVIDIA-NeMo#3566 defects found during review are out of scope for this change
and are reported separately: cross-batch staleness in the layerwise
reloader's retained BF16 passthrough tensors, and the policy.quant_cfg /
generation.quant_cfg guard-gap in the mutual-exclusion check.

Signed-off-by: Shuang Yu <[email protected]>
zhangyimi pushed a commit to zhangyimi/RL that referenced this pull request Aug 25, 2026
… reload

wandb comparison against the pr3566verify campaign (same recipe, only this
branch's vLLM-side quantization differs) surfaced two gen_kl_error spikes
(~9x median) at steps 42 and 78 that never occur across pr3566verify's
544-step history. train/policy_kl_error explodes at the same steps
(73.7, 79714.5), the signature of training recomputing a wildly different
probability than what was actually generated for a sampled token.

Root cause: NvFp4PerTokenQuantizer.process() cloned pending gate/up halves
before buffering them, but handed passthrough tensors (attention, router,
embeddings, shared experts, ignored-BF16 expert layers) straight through as
views into the shared IPC buffer. vLLM's layerwise reload buffers every
weight_loader call's arguments — including the tensor — and replays them at
layer completion (vllm/model_executor/model_loader/reload/layerwise.py),
which can land after the sender has recycled this batch's buffer for a
later one (see policy/utils.py's ping-pong double buffering). Confirmed
against vLLM 0.26.0 source: `bound_args = loader_signature.bind(*args,
**kwargs)` retains the tensor argument by reference, not by value.

This is the "cross-batch staleness on passthrough tensors" defect reported
separately against PR NVIDIA-NeMo#3566 (upstream, out of scope for this refactor) but
it also applies here: this quantizer's own passthrough path had the same
gap. Clone every passthrough tensor, matching the pending-half clone
already in place.

Signed-off-by: Shuang Yu <[email protected]>
@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test 048263c

@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test ecedaf2

@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test b29495f

@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test 44c76f2

@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test da158e3

@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test 4df56fe

@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test b57931c

@github-actions github-actions Bot added the CI Relating to CI label Aug 26, 2026
@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test 12f2878

@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test 91c3d5e

@zhangyimi
zhangyimi force-pushed the codex/nvfp4-pertoken-draft-main-20260805 branch from 91c3d5e to 4ca610d Compare August 26, 2026 16:45
@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test 4ca610d

@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test b632c96

@github-actions github-actions Bot removed the CI Relating to CI label Aug 26, 2026
@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test acde305

@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test acac996

@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test f8fea80

@sharonyu-115 sharonyu-115 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for this — it's a substantial and unusually careful piece of integration work. The _dense() fix for stride-0 expanded scale views, the FLASHINFER_TRTLLM hard guard, the "ModelOpt" in class name duck-typing note, and the 275-line design doc all show you chased real failure modes rather than working around symptoms. Two of the workarounds here are correct diagnoses of genuine vLLM 0.26.0 bugs (details below). The perf table and convergence curve are appreciated, as is the honest caveat that they're representative rather than a controlled A/B — no additional numbers requested.

Reviewed by a team of six agents against the pinned upstream sources (vLLM 0.26.0, TransformerEngine @e7c550c5, Megatron-LM @14346b65, Megatron-Bridge @8c46dc42). 25 candidate findings were raised and adversarially challenged; 6 survived and are posted below. Five were dropped for wrong premises and nine as duplicates or disproportionate — I've kept only findings with a verified premise and a concrete fix.

Checks that passed locally: ruff check and ruff format clean on all 66 changed Python files; tools/config_cli.py minimize-check passes on both new recipes; test_recipes_and_test_suites.py 12/12; all 18 tests in test_vllm_nvfp4_pertoken.py pass against vLLM 0.26.0 on CPU. The quantization math was independently verified on CPU — the 6.0 * 448.0 global-scale constant matches vLLM's convention, the E4M3 block scale saturates at exactly 448.0, and the {0,1,44..47} layer selection has no off-by-one. No GPU was available, so kernel numerics and the GB200 path are unverified here.

Two notes that are not defects: the disabled.txt / nightly_gb200.txt split reconciles correctly (the quick variant is genuinely enabled, with a documented rationale for parking the 8n4g driver), and the FlashInfer/TE version skews between extras are pre-existing and intentional.

Generated by Claude Code

Comment thread nemo_rl/models/megatron/setup.py Resolved
@zhangyimi

Copy link
Copy Markdown
Contributor Author

/ok to test 237ba75

sharonyu-115 and others added 9 commits September 18, 2026 22:57
…60916

fix: validate NVFP4 rollout and centralize refit compatibility
Regenerate uv.lock with uv 0.11.28 against the updated Gym metadata. Preserve Ray 2.56.1 and the PR dependency versions, with the registry torch-memory-saver variant matching upstream main at 0.0.10b1.

Cover NVFP4 backend validation with omitted, mapping, and typed draft configurations after preserving upstream draft normalization.

Signed-off-by: Shuang Yu <[email protected]>
The PR lockfile refresh resolves datasets 5.0.1 and pyarrow 25.0.1.
Datasets 5.0.1 combines Arrow chunks while fingerprinting in-memory
tables (huggingface/datasets#8339). NemoGymDataset stores raw JSONL
lines in extra_env_info, so large inputs exceed the approximately
2 GiB limit of Arrow string's 32-bit offsets during Dataset.from_dict.
This raises ArrowInvalid before training starts.

Declare extra_env_info as large_string, which uses 64-bit offsets,
and keep task_name as string. Preserve raw JSON values, repetition,
and the current dependency versions. Explain the schema choice at
the construction site.

Validation: four full Slurm runs on 2e13bf9 plus this schema fix
passed the original training targets and all nine metric checks:
18926860 (SWE1), 18926861 (RLVR), 18926862 (async SWE1), and
18926863 (MOPD). These are not full-run results for the rebased head.
The updated loader is executable-code-identical to that tested fix.
CPU smoke job 18928236 verifies the updated checkout with datasets
5.0.1/pyarrow 25.0.1; focused Ruff and Pyrefly checks pass.

Signed-off-by: Shuang Yu <[email protected]>
@sharonyu-115

Copy link
Copy Markdown
Contributor

/ok to test f6a2920

@sharonyu-115

Copy link
Copy Markdown
Contributor

thanks @zhangyimi and @sharonyu-115 for the great feature and addressing feedback. approved modulo CI passing and rebasing the PR to resolve conflicts

Thanks @terrykong for the review. All good comments. Got them addressed plus a datasets related regression discovered from nightly run (details documented in the PR description). Just rebased and running CI.

@sharonyu-115

Copy link
Copy Markdown
Contributor

CI failures to be fixed by #4209

@sharonyu-115

Copy link
Copy Markdown
Contributor

/ok to test 7a4bf09

@sharonyu-115

Copy link
Copy Markdown
Contributor

thanks @zhangyimi and @sharonyu-115 for the great feature and addressing feedback. approved modulo CI passing and rebasing the PR to resolve conflicts

Thanks @terrykong for the review. All good comments. Got them addressed plus a datasets related regression discovered from nightly run (details documented in the PR description). Just rebased and running CI.

Hi @terrykong, would you help review the latest change and approve? Thanks!

@terrykong
terrykong enabled auto-merge (squash) September 19, 2026 19:30
@terrykong
terrykong merged commit 3491eed into NVIDIA-NeMo:main Sep 19, 2026
105 checks passed
yfw added a commit that referenced this pull request Sep 20, 2026
Brings #3566 (end-to-end TE NVFP4 training with per-token vLLM rollout) and
three smaller commits onto the vLLM 0.29 bump.

Conflicts and resolution:
- pyproject.toml: main bumped vLLM to 0.26.0 / flashinfer 0.6.14 /
  nvidia-cutlass-dsl 4.6.0 and pinned quack-kernels==0.6.1; this branch keeps
  vLLM 0.29.0 / flashinfer 0.6.18 / cutlass-dsl 4.6.2 and takes no quack pin
  (vLLM 0.29 requires quack-kernels==0.6.4). TransformerEngine 2.18.0 (PyPI)
  and ModelOpt 43fd41a58 are taken from main: that ModelOpt revision is a
  release cherry-pick that carries #2054's RoutedExperts vLLM plugin and does
  not contain #1550's GroupedQuantizer, so the pin note is kept and reworded.
  flashinfer-cubin index and the cutlass 4.5.x dependency-metadata are main's.
- uv.lock: regenerated from this branch's lock; only ModelOpt (0.46.0 @
  43fd41a5), TransformerEngine 2.15.0+git -> 2.18.0 (+ -cu13/-torch wheels,
  nvdlfw-inspect) and the dropped cutlass libs-base 4.5.0 entry changed.
- quantization/fp8.py: main's refactor of the module lookup into
  quantization/utils.py::resolve_module_from_param_name is taken; the
  ambiguous-shard fix from 28beca5 (vLLM 0.29 lists `wkv` under two fused
  modules) is ported into the new resolver, and its tests call the renamed
  public get_module_from_param_name.
- modelopt vllm_quant_backend.py and its test: main's per-expert non-gated
  W13 emission (superset of a3aa6cd) is taken.

Also fixes the pyrefly error from 000cd24: `_tied_embedding_aliases` now
accepts `torch.nn.Module | None`.

Signed-off-by: Yi-Fu Wu <[email protected]>
@yfw yfw mentioned this pull request Sep 20, 2026
4 tasks done
yfw added a commit that referenced this pull request Sep 21, 2026
… vLLM 0.29 / torch 2.13

Three failures from the first full CI + nightly pass on the merged head:

- Async checkpoint saves died at the first save with
  `DistNetworkError: ... EADDRINUSE` inside torch's process-based DCP
  checkpointer (`_async_process_executor`): rank 0 probes a port with
  `get_free_port()` and the daemons then rendezvous on it with a fresh GLOO
  group, but the port was taken again before the daemon bound it. It hit
  every DTensor save in the run (L1 GRPO resume, the converter round-trip
  test, the llama3.2-1b fsdp2tp2 tq_mooncake nightly recipe) after the
  Automodel bump made daemon creation synchronous across ranks. The
  Automodel checkpoint manager now opts the daemons into torch's
  `DCP_USE_PREFIX_STORE=1` mode when `MASTER_ADDR`/`MASTER_PORT` are
  present, so they join the training process group's TCPStore under a
  prefix and bind nothing. Unit-tested.
- `nvfp4_pertoken.py` (from #3566) called `make_nvfp4_moe_kernel(...,
  layer=layer)`; vLLM 0.29 dropped that parameter (it already takes
  `per_token_activation`), so the new `te_nvfp4_pertoken_quick` GB200 recipe
  died with `TypeError: unexpected keyword argument 'layer'`.
- `test_decode_vs_prefill.sh` OOMed on GB200 at the first MoE forward: with
  `gpu_memory_utilization=0.8` vLLM 0.29 sized a 93 GiB KV cache for
  Nemotron-3-Nano-30B (TP2) and the FlashInfer TRT-LLM BF16 MoE kernel then
  could not allocate its 4 GiB workspace (the same test is memory-marginal
  on `main`'s H100 runners too). The diagnostics tool gains a
  `--gpu-memory-utilization` flag and the functional test passes 0.7.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
lauradang added a commit to lauradang/RL that referenced this pull request Sep 22, 2026
Bring main a9c3178 (25 commits since the previous merge base 702cd79) into
the branch on top of the #5 submodule bump (00621c2).

Conflicts:
- nemo_rl/algorithms/single_controller_utils/setup.py and
  tests/unit/single_controller/test_setup.py: keep main's sharded Gym stacks
  (NVIDIA-NeMo#3373), multi-teacher MOPD (NVIDIA-NeMo#4045), critic optimizer rebuild (NVIDIA-NeMo#4213) and
  Mooncake storage checkpoints (NVIDIA-NeMo#3898) next to the Megatron token-capture
  setup guards and backend wiring; the vLLM-only capture guard is replaced by
  the backend-aware one.
- tests/unit/models/generation/test_vllm_token_capture_hosting.py: keep main's
  stripped staged token arrays (NVIDIA-NeMo#4206) on top of the shared vLLM chain-cache
  prefix resolution.
- pyproject.toml (semantic conflict, auto-merged by git): main NVIDIA-NeMo#3566 removed
  `exclude-dependencies = ["nvidia-cutlass-dsl-libs-base"]` in favour of
  per-version dependency-metadata overrides for CUTLASS DSL 4.5.x, while this
  branch's mcore extra pinned nvidia-cutlass-dsl[cu13]==4.8.0.dev0 (68b63da).
  Without the exclusion that pin drags in the pre-release
  nvidia-cutlass-dsl-libs-base==4.8.0.dev0, which uv refuses for a transitive
  dependency, so `uv lock` no longer resolves. Pin 4.6.2 instead: it is the
  stable release flashinfer-python 0.6.18.post1 actually requires
  (>=4.6.2a0), and it is the pin NVIDIA-NeMo#4139 uses for the same
  Megatron-Bridge bump on main.
- uv.lock: regenerated from main's copy with uv 0.11.28 (the docker/Dockerfile
  pin), so it carries main's new git pins (Model-Optimizer, sglang, Lens,
  TransferQueue, nvidia-resiliency-ext, torch_memory_saver) together with the
  Gym and Megatron-Bridge main pins and the flashinfer index spelling from #5.
  `uv lock --check` passes with uv 0.11.28 and 0.12.5.

Submodule pins: Automodel follows main (72daceffa); Gym (9fc05c0ff) and
Megatron-Bridge (fcea83a85) stay at the #5 pins, which descend from main's.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
lauradang added a commit to lauradang/RL that referenced this pull request Sep 29, 2026
Bring main a9c3178 (25 commits since the previous merge base 702cd79) into
the branch on top of the #5 submodule bump (00621c2).

Conflicts:
- nemo_rl/algorithms/single_controller_utils/setup.py and
  tests/unit/single_controller/test_setup.py: keep main's sharded Gym stacks
  (NVIDIA-NeMo#3373), multi-teacher MOPD (NVIDIA-NeMo#4045), critic optimizer rebuild (NVIDIA-NeMo#4213) and
  Mooncake storage checkpoints (NVIDIA-NeMo#3898) next to the Megatron token-capture
  setup guards and backend wiring; the vLLM-only capture guard is replaced by
  the backend-aware one.
- tests/unit/models/generation/test_vllm_token_capture_hosting.py: keep main's
  stripped staged token arrays (NVIDIA-NeMo#4206) on top of the shared vLLM chain-cache
  prefix resolution.
- pyproject.toml (semantic conflict, auto-merged by git): main NVIDIA-NeMo#3566 removed
  `exclude-dependencies = ["nvidia-cutlass-dsl-libs-base"]` in favour of
  per-version dependency-metadata overrides for CUTLASS DSL 4.5.x, while this
  branch's mcore extra pinned nvidia-cutlass-dsl[cu13]==4.8.0.dev0 (68b63da).
  Without the exclusion that pin drags in the pre-release
  nvidia-cutlass-dsl-libs-base==4.8.0.dev0, which uv refuses for a transitive
  dependency, so `uv lock` no longer resolves. Pin 4.6.2 instead: it is the
  stable release flashinfer-python 0.6.18.post1 actually requires
  (>=4.6.2a0), and it is the pin NVIDIA-NeMo#4139 uses for the same
  Megatron-Bridge bump on main.
- uv.lock: regenerated from main's copy with uv 0.11.28 (the docker/Dockerfile
  pin), so it carries main's new git pins (Model-Optimizer, sglang, Lens,
  TransferQueue, nvidia-resiliency-ext, torch_memory_saver) together with the
  Gym and Megatron-Bridge main pins and the flashinfer index spelling from #5.
  `uv lock --check` passes with uv 0.11.28 and 0.12.5.

Submodule pins: Automodel follows main (72daceffa); Gym (9fc05c0ff) and
Megatron-Bridge (fcea83a85) stay at the #5 pins, which descend from main's.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Laura Dang <[email protected]>
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 Documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants