Repository navigation
[rl] generator: keep GDN A_log/dt_bias in float32 (6/7) - #5691
Conversation
c5cb7b7 to
2dccef1
Compare
|
@claude please review |
|
Claude finished @felipemello1's task in 1m 6s —— View job Review: [rl] keep float32 GDN A_log/dt_bias with the fused weights (6/6)Verdict: LGTM. A few small non-blocking suggestions below. I checked this against Correctness
Suggestions (non-blocking)
No unrelated changes or callsites seem to be missed. The repo's |
28b67d1 to
0ea522c
Compare
|
Reply from claude: Review addressed in 0ea522c (rebased onto d78b6fd):
|
0ea522c to
53318df
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 1m 4s —— View job Approve: nothing blocking, and the four items from the earlier review are handled. Review |
There was a problem hiding this comment.
Verdict: Approve -- I found nothing blocking at HEAD (53318df), and the four items from the first round are handled.
What this PR does. VLLMGDN.refresh_fused_weights now keeps float32 copies of A_log and dt_bias next to the fused projection and conv weights. It copies into them in place on each load, so the addresses captured by CUDA graphs stay valid. VLLMGDN.forward passes these copies to VLLMInnerGDN, which drops its six per-step .float() casts and states that it expects float32 inputs.
Example. A bf16 generator running a GDN decode step:
before: each step A_log (bf16) -> .float() -> recurrent_gdn_decode (one cast kernel per tensor, inside the graph)
after: each load A_log (bf16) -> copy_ into A_log_fp32_H
each step A_log_fp32_H -> recurrent_gdn_decode (no cast)
The values are the same either way, because the old code already cast these same bf16 values to float32. So the outputs should be bitwise identical, as the description says.
Earlier review, checked at HEAD
- The dtype assert is in the loop, and the test now runs with both bf16 and fp32. With bf16, replacing the cast with
.clone()fails the test. With fp32, removingcopy=Truefails it (the copy would be the inference-mode parameter itself, and the second load'scopy_would raise). Resolved. - The test sets
A_log_fp32_Handdt_bias_fp32_HtoNone, matchingVLLMGDN.__init__(gdn.py:512-513). Resolved. - The
.float()calls are gone atgdn.py:269-270,341-342and379-380, and the float32 requirement is stated in theforwarddocstring atgdn.py:431. Resolved. - You kept the build-then-
copy_pattern to match the fused weights. That is fine.
Details
- Callers. No other code passes bf16 into
VLLMInnerGDN.VLLMGDN.forwardis the only production caller. The GPU tests that call_forwarddirectly already pass float32 (test_gdn_graph_metadata.py:486-487,test_gdn_cudagraph.py:200). - Refresh timing. In
_unshard_and_free_sharded_params(model_wrapper.py:352-357), the refresh runs whenin_proj_qstill has storage.A_loganddt_biaslive in the same layer and the same FSDP group as the projections, so all four copies are refreshed on the same load. The first-load check only tests the two older tensors, but all four are always assigned together, so that is fine. - TP. The copies are the local
[H_local]shards and keep the existingparameter_placemententries invllm_inner_gdn_sharding_config(gdn.py:464-465). - Follow-up, not this PR.
kda.py:240has the same per-stepA_log_H.float()/dt_bias_HK.float()pattern. If KDA's generator path gets fused weights, the same change would apply there.
Not verified: GPU timings and bitwise parity (I don't have the hardware), and the CPU test with bf16 FSDP on gloo, which I didn't run. A maintainer still needs to review.
53318df to
a53030e
Compare
|
Reply from claude: Parked. The PR below this one (5/6) now shares one grouped |
ff88955 to
594f95d
Compare
|
Reply from claude: Redone in 594f95d (6/6 of the GDN stack). The generator holds GDN's @claude please review. |
|
Claude finished @felipemello1's task in 3m 29s —— View job Approve (please add the TODO on the new |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The redesign removes the per-load hook and keeps the core change to a passthrough whose default is main's path. It now touches core Decoder, which tianyu-l's earlier approval (on the old design) did not cover, so a maintainer still needs to review.
What this PR does. VLLMModelWrapper turns every GDN's A_log/dt_bias into frozen float32 parameters on the meta model. Through a new Decoder._fsdp_param_dtype_override_fn it tells FSDP to keep each parameter's own dtype. It builds the pinned receive copy in the dtypes the trainer sends: parameters in model_dtype, buffers in their own dtype. The bf16 -> fp32 cast then happens in load_state_dict's copy_, and VLLMInnerGDN drops its six .float() calls.
Example. A bf16 Qwen3.5 generator, TP2, one GDN layer:
base: A_log param bf16 [H/2] --FSDP unshard--> bf16 --.float() every step, in the graph--> kernel
this PR: A_log param fp32 [H/2] --FSDP unshard (override keeps fp32)--> fp32 --> kernel
weight sync: trainer sends bf16 -> pinned receive buffer bf16 (not fp32: RDMA asserts equal dtypes)
-> load_state_dict copy_ into the fp32 shard (the one cast per load)
The values are the same bf16 values widened to fp32 either way, so the result is bitwise identical.
Must fix
torchtitan/models/common/decoder.py:161-- the core hook has a single consumer and no TODO linking it to the planned per-FQN dtype refactor (inline).
Should consider
torchtitan/rl/generator/vllm/model_wrapper.py:409-- the override applies to every generator model. Formodel_dtype != "bfloat16"it changes the unshard dtype, from bf16 tomodel_dtype. The description's "Unchanged" line doesn't mention this (inline).
Details
- Passthrough reaches Qwen3.5.
Qwen35Model(MultimodalModel)->MultimodalModel._apply_fsdp->super()._apply_fsdp->Decoder._apply_fsdpforwards the attribute. The other_apply_fsdpoverrides (deepseek_v4, flux, deepseek_v3 MTP, transformers backend) don't forward it, but none of them holds a GDN. - Freezing. FSDP2's uniform-dtype check only covers parameters with
requires_grad, so the comment atmodel_wrapper.py:401-402is accurate. The generator never computes grads, so freezing costs nothing. - Receive dtypes vs trainer.
trainer.py:509-514sends parameters as_transfer_dtypewhengenerator_dtype != training.dtype, and otherwise in their owntraining.dtype. In the second case (bf16 trainer, bf16 generator), the sent dtype equalsmodel_dtype, somodel_wrapper.py:468-476matches both cases. The new assert intest_bitwise_parity.pychecks exactly this. - Quantized params.
_ShardedFSDPTensor.fsdp_pre_all_gatherreadsmp_policy.param_dtypedirectly (_fsdp_tensor.py:381). In the generator, that dtype equals the parameter dtype, so the override changes nothing for MXFP8/NVFP4 weights. - Standalone HF load (
checkpointer_configset, outside the RL loop) now keeps a float32A_logunrounded. The NOTE in the description covers this. In the RL loop the config isNone, and weights arrive bf16 from the trainer. - KDA (
kda.py) still castsA_log_H.float()/dt_bias_HK.float()every step. The same change could apply there as a follow-up.
Not verified: GPU timings, bitwise parity, FSDP degree > 1 on GPU, and the RDMA receive path. I could not run torch in this environment.
96effd4 to
3621d9b
Compare
The generator's GDN kernels read A_log and dt_bias in float32, so every GDN layer cast them on every step. The generator now holds them as frozen float32 parameters: Decoder._fsdp_param_dtype_override_fn passes FSDP's param_dtype_override_fn through, and the generator sets it to keep each parameter's own dtype. The pinned receive copy is built in the dtype the trainer sends (parameters in the model dtype, buffers in their own), and load_state_dict casts once per weight load. VLLMInnerGDN drops its six .float() calls.
…ers carry a per-FQN dtype
3621d9b to
1f37f3d
Compare
Root issue: RL generators prefetch each policy from the StorageVolume into a full pinned CPU copy of the weights before loading it into vLLM. GB300 generator hosts have little CPU memory and OOM on this copy. Fix: one load path, `VLLMModelWrapper.load_model_state_dict(fetch)`, walks the FSDP groups one at a time (reshard, restore sharded params, `fetch` the group's subset in place, unshard and free; buffers last). Every parameter must be filled. `Generator.Config.model_state_dict_load_mode` picks the fetch: | `model_state_dict_load_mode` | prefetch | fetch during load | generator host memory | |---|---|---|---| | `"cpu_prefetch"` (default, previous behavior) | StorageVolume -> pinned CPU copy, overlaps generation | `copy_` from the pinned copy | +1 full weight copy | | `"gpu_fetch"` | no-op | TorchStore read straight into the GPU weights | none | A gloo all-reduce agrees on load failure across generator ranks before rank 0 replies; on a fetch failure every rank still unshards every group (avoids an all-gather hang) and then stops the engine loop. gpu_fetch tradeoff: the transfer runs inside the load while the engine is paused rather than overlapping generation. gpu_fetch rejects quantized parameters at init. Parameters whose dtype differs from the model dtype (float32 GDN `A_log`/`dt_bias`, #5691) are fetched into model-dtype staging tensors and cast, since the trainer sends the model dtype and torchstore requires matching dtypes. The trainer-side duplicate copy (#5654) was removed by #5659. Requires meta-pytorch/torchstore#252 (merged). Test plan: - CPU: `pytest tests/rl/unit_tests/cpu` with no GPU: all pass (gpu_fetch load path covered by `test_vllm_wrapper`/`test_generator`, incl. float32 param staging). - GPU (GB200): `torchrun --nproc-per-node=2 -m pytest tests/rl/unit_tests/gpu/test_bitwise_parity.py::TestBitwiseParityQwen35DebugVarlen`: 5 passed on both ranks. Trainer vs vLLM prefill and decode are bitwise identical, including a reload through `load_model_state_dict` after CUDA graph replay. - E2E async RL on GB200 through TorchStore (before merging main): - Qwen3 debugmodel, gen TP2, 4 steps: logprob_diff/max 0.0099-0.012 in both modes. - Qwen3 8B, gen TP1, 5 syncs: logprob_diff/max 0.21-0.31 in both modes (same as before this PR; untrained weights, not batch invariant). Generator memory, Qwen3 8B, gen TP1: | mode | host RSS | GPU growth in sync | sync time | |---|---|---|---| | `cpu_prefetch` | 24.7 GiB (16 GiB pinned copy) | +1 GiB on first sync only | 0.48 s, overlapped with generation | | `gpu_fetch` | 3.8-3.9 GiB | 0 | 1.1-1.2 s, engine paused | Lines changed: impl +306/-88, tests +436/-100, CI 0.
…oad into ParallelismConfig (#5776) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> Apparently not only trainer cares about precision; generator also cares. This PR moves it out from `TrainingConfig` as a standalone config, owned by core trainer and RL controller, preparing for the next PR. ## Why The model's dtypes (`training.dtype`, `training.mixed_precision_param`, `training.mixed_precision_reduce`) live on `TrainingConfig`, owned by `TrainingEngine.Config`. In RL they describe the model that both the trainer and the generators run, but only the trainer can see them: - The generator builds its model with its own `generator.model_dtype` and fabricates a `TrainingConfig()` just to call `model.parallelize(training=...)`. - `model.parallelize` takes the whole `TrainingConfig`, but reads only those three fields plus `enable_cpu_offload`. This PR is a mechanical move. #5774 (stacked on top) then makes the generator mirror the trainer's precision from this one config and deletes `generator.model_dtype`. **Example.** ```python # before config.training.dtype = "float32" config.training.mixed_precision_param = "bfloat16" config.training.enable_cpu_offload = True model.parallelize(parallelism_context=..., training=config.training, parallelism=..., ...) # after config.precision.dtype = "float32" # Trainer.Config.precision / Controller.Config.precision config.precision.param_dtype = "bfloat16" config.parallelism.fsdp_enable_cpu_offloading = True model.parallelize(parallelism_context=..., precision=config.precision, parallelism=..., ...) ``` ## What changed - `PrecisionConfig(dtype, param_dtype, reduce_dtype)` in `torchtitan/config/configs.py`. `param_dtype`/`reduce_dtype` match FSDP's `MixedPrecisionPolicy` names. - Ownership: core `Trainer.Config.precision` and RL `Controller.Config.precision`, not `TrainingEngine.Config`. `TrainingEngine` receives it as a constructor argument, like `model_config`. In RL the controller passes the same object to the trainer (and, in #5774, to the generators). - `training.enable_cpu_offload` -> `parallelism.fsdp_enable_cpu_offloading`, next to the other `fsdp_*` options, so `model.parallelize` / `_apply_fsdp` take `precision=` and no longer need `training`. - The Dist-MoE `param_dtype == "bfloat16"` check moves from `TrainingEngine.Config.__post_init__` to `Trainer.Config` and `Controller.Config`, where `precision` is visible (two 5-line copies, both at config time). - GraphTrainer (experiment): its models read the token budget in `parallelize`, so `GraphTrainingEngine` passes `training` there through its existing kwargs hook. - Mechanical, skimmable: every `parallelize`/`_apply_fsdp`/`pipeline` signature, recipes, tests, docs (`BF16_OPTIMIZER_STATES.md`, `dist_moe/README.md`, `BITWISE_PARITY.md`, `numerics_debugging` skill). ## Alternatives considered - Keep the fields in `TrainingConfig` and have the RL controller forward them to the generator: the generator would read the trainer's config, and `parallelize` would still take the whole `TrainingConfig`. - Put precision on the model config: duplicated on `trainer.model` and `generator.model` with an equality check, and dtype is a per-run choice, not architecture. ## User-facing changes | Before | After | | --- | --- | | `training.dtype` | `precision.dtype` | | `training.mixed_precision_param` | `precision.param_dtype` | | `training.mixed_precision_reduce` | `precision.reduce_dtype` | | `training.enable_cpu_offload` | `parallelism.fsdp_enable_cpu_offloading` | | RL: `trainer.training.dtype` | `precision.dtype` (on `Controller.Config`) | ## Numerics No computation change. Loss and grad_norm bitwise identical to main (01586df), 20 steps, seed 42, deterministic, flex attention, 2 GPUs, GB300, read from TensorBoard: | Config | Result | | --- | --- | | llama3 debugmodel, FSDP 2 (fp32 masters) | bitwise identical | | llama3 debugmodel, FSDP 2, `reduce_dtype="bfloat16"` | bitwise identical | | kimi_k3 debugmodel, FSDP 2 (bf16 masters, `dtype="bfloat16"`) | bitwise identical | PP, `param_dtype="float32"` and FSDP CPU offload configs could not run on this host for main or this PR (a torch nightly pipelining API mismatch, an fp32 backward kernel limit, and a hang in CPU offload), so they rely on CI. ## Testing - CPU unit suites (`tests/unit_tests/cpu`, `tests/rl/unit_tests/cpu`, graph_trainer and torchft tests touched here): same results as main. The remaining failures also fail on main on this aarch64 host (LoRA, Qwen3.5 MRoPE x3, graph_trainer Dist-MoE recipe tests, autoparallel not installed). - `test_rl_dist_moe_recipe.py` now also covers the RL `Controller.Config` copy of the Dist-MoE check, the only guard for RL trainers; the core copy stays covered by `test_runtime_config_requires_bfloat16_unsharded_parameters`. `test_cpu_offload_requires_distinct_dp_shard_seeds` covers the renamed offload field. - `test_generator_dist_moe_mxfp8.py` (CI `rl-b200`) has failed on main since #5691: its fake trainer model is a `SimpleNamespace` without the `named_buffers` the weight-sync helper now reads. This PR gives the fake `named_buffers` so `rl-b200` is green (test-only). This PR was AI-assisted.
… mixed-precision casts (#5774) Stacked on #5776 (GitHub stack: this PR's base is #5776's branch). ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> pytorch/pytorch#196626 added `MixedPrecisionPolicy.param_dtype_override_fn` so FSDP can leave chosen parameters alone. E.g., for GDN / KDA, the params `A_log` and `dt_bias` should never go through down-casting, during FSDP's pre-all-gather. This PR is making it configurable. ## Why FSDP2 mixed precision (`precision.param_dtype="bfloat16"`) casts every fp32 master parameter to bf16 at all-gather. Some parameters are numerically sensitive, and their reference checkpoints store them in float32 on HF: | Model | Stored as F32 on HF | | --- | --- | | Qwen3.5 (0.8B, 27B, 35B-A3B) | GDN `linear_attn.A_log`, GDN gated norm `linear_attn.norm.weight` | | Kimi-Linear-48B-A3B (KDA) | `A_log`, `dt_bias` | | DeepSeek-V4-Flash | `hc_*_fn/base/scale`, `attn_sink`, compressor `ape` | On main the kernels then upcast bf16-rounded values (`gdn.py:480`, `kda.py:128`, `mhc.py:112`). DSV4 even creates its head hc params with `dtype=torch.float32`, and FSDP still rounds them. The same rounding happens when RL publishes weights to generators (`transfer_dtype`) and when a final checkpoint is exported (`export_dtype`). pytorch/pytorch#196626 added `MixedPrecisionPolicy.param_dtype_override_fn` so FSDP can leave chosen parameters alone. **Example.** ```python # GDN.Config (component default) preserve_dtype_params: tuple[str, ...] = ("A_log", "dt_bias") # fp32 masters, precision.param_dtype="bfloat16" # before: FSDP all-gathers A_log in bf16; kernel computes exp(A_log.bf16().float()) # after: A_log is all-gathered and used in fp32; RL sends and the generator uses it in fp32; # export_dtype="bfloat16" keeps it fp32, as in the HF release ``` ## What changed - `Module.Config.preserve_dtype_params: tuple[str, ...]`: names of a module's own parameters that bulk casts never lower in precision. Validated at build. `Module.named_preserve_dtype_params()` yields `(fqn, param)` for a module tree, like `named_parameters()`. - Components whose math always needs it set the default: GDN and KDA (`A_log`, `dt_bias`), DSV4 `HcPre`/`HcHead` (`hc_*`), DSV4 `Compressor` (`ape`). Flavors set it for single instances of generic modules: Qwen3.5's GDN `GatedRMSNorm`, DSV4's `attn_sink` `Linear`. - FSDP: `mixed_precision_policy(module, ...)` builds the policy with `param_dtype_override_fn` (the wider of the parameter's dtype and `param_dtype`). Every core FSDP site that shards TorchTitan modules uses it (decoder, multimodal encoder, Flux model). Flux's HF T5/CLIP encoders keep their own policy (no TorchTitan modules). The graph_trainer experiment's SimpleFSDP has no per-parameter override, so `GraphTrainerModel.parallelize` raises if a model lists preserved params (none does today). Removes `Decoder._fsdp_param_dtype_override_fn`, added in #5691 with a TODO asking for this. Quantization converters raise on a `Linear` that lists preserved params instead of silently dropping the field. - RL (on #5776): the generator mirrors the trainer's `Controller.Config.precision` instead of its own `generator.model_dtype` (removed). It builds the model in `precision.dtype`, so buffers and preserved params get the trainer's dtypes. It holds every other parameter in `precision.param_dtype` and computes in it (vLLM `dtype`; the wrapper raises if they differ), so its FSDP casts nothing. The generator model is frozen, and parameters are cast with `torch.utils.swap_tensors`, since `param.data =` leaves a quantized tensor subclass's (MXFP8/NVFP4) inner tensor in the old dtype. vLLM's attention layers are still built in vLLM's model dtype, because vLLM picks their backend from the default dtype. The trainer sends parameters in `param_dtype` (`transfer_dtype`, when it differs from `dtype`), and buffers and preserved params in their own dtype (`preserve_dtype_keys`). The generator's receive buffers are its sharded state dict as is (`cpu_prefetch`), and `gpu_fetch` (#5652) fetches straight into the sharded parameters, so #5652's cast of float32 parameters through model-dtype staging tensors is removed. This generalizes #5691's GDN-only handling. With bf16 masters, GDN `A_log`/`dt_bias` reach the generator in bf16, so `VLLMInnerGDN` casts them at its kernel call on every forward (`.float()`, a no-op for fp32 tensors), as the trainer's GDN does. With fp32 masters this keeps #5691's saving. - Checkpoint export: `export_state_dict(state_dict, *, dtype, model_parts)` replaces the duplicated cast loops in both checkpointers and both `scripts/checkpoint_conversion/` converters. The converters now cast before `to_hf`, like the in-training export. - Mechanical, skimmable: test updates for the removed `param_dtype_override_fn` argument, `models/README.md` bullet, reworded KDA TODO. ## Alternatives considered - Run-level FQN regex list in the training config: puts an architecture property into every recipe, and patterns break across PP splits and renames. - Class attribute only: can't vary per instance (Qwen3.5 preserves one `GatedRMSNorm`, KDA's stays bf16). - Tagging `nn.Parameter` objects: tags are lost through `to_empty`, `param.data =` and DTensor re-wrapping. - Requiring fp32 masters for RL: several GDN/KDA RL recipes train with bf16 masters. - Keeping `generator.model_dtype` and upcasting preserved params to at least fp32 on the wire and in the generator: a heuristic that guesses the trainer's dtypes. Mirroring the trainer's `precision` makes every dtype match by construction. FlexShard's `param_dtype_overrides` (an FQN map) can consume `named_preserve_dtype_params` directly once it lands; not wired here. ## User-facing changes | | Before | After | | --- | --- | --- | | Qwen3.5 / DSV4 training, fp32 masters | listed params all-gathered in bf16 | all-gathered and computed in fp32 | | Kimi K3 training, fp32 masters | KDA `A_log`/`dt_bias` in bf16 | fp32 | | bf16 masters (`precision.dtype="bfloat16"`) | unchanged | unchanged (params stay bf16) | | RL generator dtype | `generator.model_dtype` (every recipe: `"bfloat16"`) | `precision.param_dtype` (default `"bfloat16"`); `generator.model_dtype` removed | | RL generator, fp32 masters | GDN `A_log`/`dt_bias` fp32, values bf16-rounded | all listed params fp32 and unrounded | | `export_dtype="bfloat16"` | every float tensor bf16 | listed params stay fp32 | | `convert_to_hf.py --export_dtype bfloat16` | cast after `to_hf`, so adapter-created tensors were cast too (DSV4 `tid2eid`: int64 -> fp32 in `to_hf`, then rounded to bf16) | cast before `to_hf`; `tid2eid` stays fp32 | ## Numerics Deterministic, seed 42, flex attention, 2 GPUs FSDP, GB300; base = main with #5659 (+ #5776, which is bitwise identical to main). | Config | Masters | Result | | --- | --- | --- | | llama3 debugmodel (no preserved params), 20 steps | fp32 | loss and grad_norm bitwise identical | | kimi_k3 debugmodel, 20 steps | bf16 | bitwise identical (params stay bf16) | | qwen3_5 / deepseek_v4 debugmodel | fp32 | change from step 1, as expected | C4 (`allenai/c4`) convergence, 600 steps, mean loss over each window: | Steps | qwen3_5 base | qwen3_5 this PR | deepseek_v4 base | deepseek_v4 this PR | | --- | --- | --- | --- | --- | | 90-100 | 2.4372 | 2.4361 | 2.5241 | 2.5236 | | 290-300 | 2.0829 | 2.0805 | 2.0742 | 2.0712 | | 490-500 | 1.9237 | 1.9231 | 1.9038 | 1.9006 | | 551-600 | 1.9489 | 1.9467 | 1.8937 | 1.8909 | No golden loss file covers an affected config: the only one, `kimi_k3_b200.txt`, uses bf16 masters. ## Performance Every FSDP group holding a preserved param now all-gathers mixed dtypes (FSDP's byte path). - Qwen3.5-0.8B, fp32 masters, FSDP 2, seq 4096, GB300, median tokens/s over steps 5-20, three runs each alternating on the same GPUs: base 24.1k / 24.1k / 22.3k, this PR 25.1k / 23.0k / 23.6k (run-to-run noise about 5%). Peak active memory 28.66 GiB in both. - DeepSeek-V4 debugmodel: 63.6k vs 63.0k tokens/s (concurrent runs on separate GPU pairs, within noise); peak memory identical. ## Testing - CPU unit suites (checkpointer, scripts, distributed, config, models, quantization, RL): pass, except 6 failures that also fail on main on aarch64 (dist-MoE x2, LoRA, Qwen3.5 MRoPE x3). - Kimi K3 RL batch-invariant integration test (`rl_grpo_kimi_k3_debug_batch_invariant`, 4 GPUs, bf16 masters): `bit_wise/logprob_diff/max = 0` at every step. - Qwen3.5 trainer-vs-generator bitwise parity GPU test (`TestBitwiseParityQwen35DebugVarlen`, fp32 masters, asserts every receive dtype equals what the trainer sends): 4 passed. - DeepSeek V3 RL integration test (`rl_grpo_deepseek_v3_debug`, 4 GPUs, fp32 masters, weight sync over Monarch/TorchStore): runs all steps. This also covers building vLLM MLA attention inside an fp32-master generator model. - MXFP8 Dist-MoE generator test (`test_generator_dist_moe_mxfp8.py`, fp32 masters, quantized tensor-subclass experts cast to bf16 on meta): passes. Since #5691 it had passed a `SimpleNamespace` without `named_buffers` to the shared weight-sync helper; it now passes a stand-in with the generator's buffer and preserved-param names, so the helper's receive-dtype assertion covers MXFP8 experts. - Extended tests: `test_fsdp.py` (preserved param unshards in its dtype), `test_trainer.py` (preserved names in `preserve_dtype_keys`), `test_torch_checkpointing.py` (export keeps a preserved fp32 param), `test_bitwise_parity.py` (receive dtypes). ## Known issues / follow-ups - Not run here: the 8-GPU `rl_grpo_qwen3_5_debug_tp2_batch_invariant` CI config. A 4-GPU variant (trainer DP 1) is not bitwise on base or on this PR. - Norm weights in general (beyond Qwen3.5's GDN gated norm) are a follow-up after convergence studies. - RL with bf16 masters: the generator now receives GDN `A_log`/`dt_bias` in bf16, the trainer's dtype, so `VLLMInnerGDN` casts them each step again. That costs the 3-6 us per GDN layer per step that #5691 saved (Qwen3.5-27B / 35B-A3B measurements there); fp32 masters keep the saving. - Separate issue found while validating: `VarlenInnerAttention` defaults to cuDNN attention first, whose dQ backward is not deterministic under `debug.deterministic=True` on SM100+ (flash is). Numerics above use flex attention for that reason. This PR was AI-assisted.
Summary (human-written)
Agent details
TLDR: The generator now holds GDN's
A_loganddt_biasas float32 parameters. The float32 cast the GDN kernels need then happens once per weight load, inload_state_dict'scopy_, instead of in every GDN layer on every step. GDN layer -3.2 to -5.8 us per step (Qwen3.5-27B TP4, 35B-A3B TP2), bitwise.Problem
A_loganddt_biasin float32 only.VLLMInnerGDNcasts both with.float(): 2 casts on decode steps, 4 on packed steps, in every GDN layer, inside the CUDA graphs.Solution
VLLMModelWrapperconverts every GDN'sA_loganddt_biasto float32 and freezes them: FSDP requires one dtype among the parameters that have a grad.mixed_precision_param(bf16) when it unshards.Decoder._fsdp_param_dtype_override_fnforwards FSDP'sparam_dtype_override_fnthroughapply_fsdp_to_decoder. The generator sets it tolambda param: param.dtype; its other parameters are already bf16.rl/trainer/trainer.py:506-514). The pinned CPU copy that receives them is now built the same way, because torchstore's RDMA transport copies raw bytes and asserts equal dtypes.load_state_dictthen castsA_loganddt_biasto float32.VLLMInnerGDNdrops its six.float()calls.generator.model_dtype="bfloat16"(the default, and required for batch invariance) nothing changes. With float32 or float16 (allowed outside batch-invariant mode), FSDP used to cast the unsharded weights to bf16 (TrainingConfig().mixed_precision_param); now they stay inmodel_dtype.Results
You may ask:
copy_casts.A_logas a local[heads / TP]tensor, and the weight sync, which reshards DTensors, breaks at TP > 1 (the parity test failed this way).Decoderattribute? The generator never callsfully_shard(parallelize->_apply_fsdpis core), and aparallelizeargument would change all 6_apply_fsdpimplementations. The generator sets_skip_lm_headthe same way.NOTE: not tested: weight sync over RDMA (multi-host). The receive dtypes follow from torchstore's dtype assert (
torchstore/transport/monarch_rdma.py). The parity test now asserts that every receive tensor has the dtype the trainer sends.NOTE: a generator that loads an HF checkpoint directly gets the same numbers: released Qwen3.5 checkpoints (0.8B-Base, 9B-Base, 27B, 35B-A3B-Base) store
A_logas F32 with bf16-exact values anddt_biasas BF16. A non-bf16-exact float32A_logwould now load unrounded.NOTE: at FSDP degree > 1 (vLLM DP > 1), FSDP all-gathers the mixed dtypes as bytes. Checked on CPU only (FSDP 2 and 4, TP2 x FSDP2, TP4 x FSDP2: float32 after unshard and after a load); the GPU tests below run at FSDP degree 1.
Test plan
6/7 of the GDN generator stack, on top of 5/7 (one GDN input projection); 7/7 (#5731, the split compiled per grad mode) is on top of it.