Skip to content

[rl] generator: keep GDN A_log/dt_bias in float32 (6/7) - #5691

Merged
felipemello1 merged 2 commits into
mainfrom
felipemello1/gdn-stack/6-fp32-decay-params
Nov 2, 2026
Merged

felipemello1 merged 2 commits into
mainfrom
felipemello1/gdn-stack/6-fp32-decay-params

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: The generator now holds GDN's A_log and dt_bias as float32 parameters. The float32 cast the GDN kernels need then happens once per weight load, in load_state_dict's copy_, 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.

# this PR, VLLMModelWrapper.__init__, on the meta model before parallelize
for param in (module.A_log, module.dt_bias):  # every GDN module
    param.data = param.data.float()
    param.requires_grad_(False)
self.model._fsdp_param_dtype_override_fn = lambda param: param.dtype

# Decoder._apply_fsdp (core): forwards FSDP's existing knob; the default None is main's path
param_dtype_override_fn=self._fsdp_param_dtype_override_fn,

Problem

  1. The generator's GDN kernels (Attention Gym's decode, gate and chunk kernels) take A_log and dt_bias in float32 only.
  2. vLLM builds the generator model in bf16, so VLLMInnerGDN casts both with .float(): 2 casts on decode steps, 4 on packed steps, in every GDN layer, inside the CUDA graphs.

Solution

  1. Float32 parameters. VLLMModelWrapper converts every GDN's A_log and dt_bias to float32 and freezes them: FSDP requires one dtype among the parameters that have a grad.
  2. FSDP keeps each parameter's dtype. FSDP casts every parameter to mixed_precision_param (bf16) when it unshards. Decoder._fsdp_param_dtype_override_fn forwards FSDP's param_dtype_override_fn through apply_fsdp_to_decoder. The generator sets it to lambda param: param.dtype; its other parameters are already bf16.
  3. Receive what the trainer sends. The trainer sends parameters in the generator's dtype and buffers in their own (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_dict then casts A_log and dt_bias to float32.
  4. VLLMInnerGDN drops its six .float() calls.
  5. Unchanged: the trainer, the kernels, and every model that doesn't set the attribute (FSDP gets None, as on main).
  6. Changed for non-bf16 generators: the override applies to every generator model. With 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 in model_dtype.

Results

Numerics: bitwise. GDN layer output, SSM and conv state equal the base in every cell below, eager and one CUDA-graph
          replay. Trainer-vs-generator parity test: 4 passed on both ranks.

GDN layer (GDN module + VLLMInnerGDN), per GPU, GB300, CUDA graphs, L2 flushed, us. Median of 20 rotated blocks of
40 replays. base = 5/7 (bf16 + .float()). Control = the base against a second copy of itself, in the same cell.
                          Qwen3.5-27B TP4                     Qwen3.5-35B-A3B TP2
step                      base    this PR  delta  control     base    this PR  delta  control
decode, 64 requests        66.4    62.6    -3.8   +0.4         68.5    65.2    -3.2   -0.1
decode, 256 requests      115.5   111.6    -4.0   -1.1        133.5   130.0    -3.4   -0.5
1 x 2k prefill            237.6   231.8    -5.8   +0.9        232.3   227.6    -4.7   +1.4
61 decodes + 4 chunks     242.8   237.2    -5.6   +1.2        244.2   238.6    -5.5   -0.2

27B TP4 step, estimated as delta x 48 GDN layers over 5/7's measured step times (not measured end to end):
decode, 64 requests     -0.18 of 7.76 ms         (-2.3%)
decode, 256 requests    -0.19 of 12.6-15.2 ms    (-1.3 to -1.5%; 3 runs varied this much)
mixed, 64 requests      -0.27 of 34.4 ms         (-0.8%)

You may ask:

  • Why not keep a float32 copy and refresh it after each load (the first version)? It needed a per-load hook in the wrapper. Float32 parameters need none: the load's own copy_ casts.
  • Why not float32 buffers, which FSDP leaves alone? FSDP turns parameters into DTensors but leaves buffers rank-local. The state dict would hold A_log as a local [heads / TP] tensor, and the weight sync, which reshards DTensors, breaks at TP > 1 (the parity test failed this way).
  • Why a Decoder attribute? The generator never calls fully_shard (parallelize -> _apply_fsdp is core), and a parallelize argument would change all 6 _apply_fsdp implementations. The generator sets _skip_lm_head the same way.
  • Why not float32 in the trainer too? The trainer would compute with its float32 master values while the generator gets bf16 ones, so trainer-vs-generator parity would stop being bitwise.

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_log as F32 with bf16-exact values and dt_bias as BF16. A non-bf16-exact float32 A_log would 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

TORCHTITAN_QWEN3_5_0_8B_HF_PATH=<Qwen3.5-0.8B-Base> pytest tests/rl/unit_tests/gpu/test_gdn_cudagraph.py \
  tests/rl/unit_tests/gpu/test_gdn_graph_metadata.py tests/unit_tests/gpu/models/qwen3_5/test_qwen3_5_deltanet.py   # 27 passed
torchrun --nproc_per_node=2 -m pytest tests/rl/unit_tests/gpu/test_bitwise_parity.py::TestBitwiseParityQwen35DebugVarlen   # 4 passed
torchrun --nproc_per_node=2 -m pytest tests/rl/unit_tests/gpu/test_bitwise_parity.py::TestBitwiseParityGptOssVarlen
  # not in CI; float32 trainer masters: weight sync + dtype assert pass, then the trainer-only test_batch_invariance
  # fails on rank 0 and the ranks hang; it fails the same way on the base (5/7, f334fd991)
pytest tests/unit_tests/cpu/distributed/test_fsdp.py   # 11 passed; new: float32 parameter after unshard, with and without the override
pytest tests/rl/unit_tests/cpu                         # 506 passed, 8 skipped
pytest tests/unit_tests/cpu/distributed tests/unit_tests/cpu/models tests/unit_tests/cpu/config   # same 6 failures as the base (dist-MoE x2, LoRA, mrope x3)
FSDP degree > 1: CPU probe only (NOTE above).

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.

@felipemello1
felipemello1 added this pull request to stack #5672 October 29, 2026 09:21
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 29, 2026
@felipemello1
felipemello1 force-pushed the felipemello1/gdn-stack/6-fp32-decay-params branch from c5cb7b7 to 2dccef1 Compare October 29, 2026 09:55
@felipemello1

Copy link
Copy Markdown
Contributor Author

@claude please review

@claude

claude Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

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 origin/felipemello1/gdn-stack/5-fused-input-proj.

Correctness

  • Numerics are unchanged. Every place the kernels read these values already did A_log.float() / dt_bias.float(): the decode kernel at gdn.py:269-270 and gdn.py:340-341, and gate_transform at gdn.py:378-379. A float32 copy taken once per load gives the same values, and those .float() calls are now no-ops. Your "2 casts on decode, 4 on packed" count matches the code.
  • copy=True is correct and needed. _unshard_and_free_sharded_params unshards under torch.inference_mode() (model_wrapper.py:304) but calls refresh_fused_weights outside it. With float32 parameters, a plain .to(torch.float32) would return the inference-mode parameter itself, and the next load's copy_ into it would raise. With the copy, you get a normal tensor.
  • The new tensors are refreshed with copy_ after the first load, the same way as input_weight_CD / conv_weight_CW, so the addresses captured in CUDA graphs stay valid. The first-load check only looks at the two older fused tensors, but all four are always set together, so that is fine.
  • The TP placement is unchanged. The copies are the local [H_local] shards, and they go through the same parameter_placement entries in vllm_inner_gdn_sharding_config as before. Like input_weight_CD, they are plain tensors.

Suggestions (non-blocking)

  1. The test never checks that the copies are float32. The CPU test builds float32 parameters, so it covers the copy=True aliasing case but not the cast. If someone replaced .to(torch.float32, copy=True) with .clone(), the test would still pass. A one-line check next to the torch.equal loop (test_vllm_wrapper.py:295-297) would cover the PR's main promise:
    assert getattr(gdn, f"{name}_fp32_H").dtype == torch.float32, name
    Making the two parameters bf16 in the fixture would also test the real cast path. Fix this →
  2. Make the test fixture match __init__. test_vllm_wrapper.py:258 sets input_weight_CD = conv_weight_CW = None but not the two new attributes. The test passes only because the first refresh creates them. Setting all four to None keeps the hand-built VLLMGDN in step with VLLMGDN.__init__.
  3. The .float() calls inside VLLMInnerGDN are now dead code. VLLMGDN is the only caller, and it always passes float32. You could drop the .float() calls at gdn.py:269-270, 340-341 and 378-379, and state the float32 contract on VLLMInnerGDN.forward's A_log_H / dt_bias_H, so readers don't assume a cast still happens there. The class docstring at gdn.py:72-73 ("passes fused copies of the projection and conv weights") could also mention the float32 gate parameters. This is only a readability cleanup; it doesn't affect performance.
  4. Optional small simplification. After the first load, the code makes a temporary float32 copy and then copies it in. self.A_log_fp32_H.copy_(self.A_log) would cast directly into the existing buffer. It only runs once per load and the tensors are a few dozen floats, so this is purely a matter of taste. Matching the existing build-then-copy_ pattern is reasonable.

No unrelated changes or callsites seem to be missed. refresh_fused_weights has a single caller (model_wrapper.py:321), and the trainer-side GDN is untouched.

The repo's /pr-review skill isn't on this branch, so I wrote this review directly into this comment instead of posting it as a PR review with inline comments. I didn't run tests: GPU tests need hardware, and I didn't run the CPU test here either.

@felipemello1
felipemello1 force-pushed the felipemello1/gdn-stack/6-fp32-decay-params branch 2 times, most recently from 28b67d1 to 0ea522c Compare October 29, 2026 11:07
@felipemello1

felipemello1 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Reply from claude: Review addressed in 0ea522c (rebased onto d78b6fd):

  1. dtype assert added in the loop. The stand-in now runs in bf16 and float32, because on float32 alone the assert cannot fail (.clone() of float32 is float32); bf16 + .clone() now fails.
  2. The fixture sets A_log_fp32_H / dt_bias_fp32_H to None. 3. The six .float() calls are dropped, with float32 stated in VLLMInnerGDN.forward (the kernels reject other dtypes).
  3. Kept the build-then-copy_ pattern, to match the fused weights.

@felipemello1
felipemello1 marked this pull request as ready for review October 29, 2026 15:27
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 29, 2026
@github-actions
github-actions Bot requested a review from pzhan9 October 29, 2026 15:27
@felipemello1
felipemello1 force-pushed the felipemello1/gdn-stack/6-fp32-decay-params branch from 0ea522c to 53318df Compare October 29, 2026 15:40
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 4s —— View job


Approve: nothing blocking, and the four items from the earlier review are handled. Review

@claude claude Bot 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.

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

  1. 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, removing copy=True fails it (the copy would be the inference-mode parameter itself, and the second load's copy_ would raise). Resolved.
  2. The test sets A_log_fp32_H and dt_bias_fp32_H to None, matching VLLMGDN.__init__ (gdn.py:512-513). Resolved.
  3. The .float() calls are gone at gdn.py:269-270, 341-342 and 379-380, and the float32 requirement is stated in the forward docstring at gdn.py:431. Resolved.
  4. 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.forward is the only production caller. The GPU tests that call _forward directly 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 when in_proj_q still has storage. A_log and dt_bias live 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 existing parameter_placement entries in vllm_inner_gdn_sharding_config (gdn.py:464-465).
  • Follow-up, not this PR. kda.py:240 has the same per-step A_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.

@felipemello1
felipemello1 force-pushed the felipemello1/gdn-stack/6-fp32-decay-params branch from 53318df to a53030e Compare October 29, 2026 15:48

@tianyu-l tianyu-l 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.

will do a refactor to introduce per-fqn dtype so that a_log and dt_bias stay fp32 is never casted to bf16

cc @wwwjn

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Parked. The PR below this one (5/6) now shares one grouped in_proj between the trainer and the generator, so the per-load refresh_fused_weights hook this PR used to keep float32 A_log/dt_bias copies is gone. Its gain (1.5-5.0 us per GDN layer per step, bitwise) still holds, but it needs another way to cast once per weight load. I'll redo it on top of the new 5/6, or close it if that ends up not worth it.

@felipemello1
felipemello1 marked this pull request as draft November 1, 2026 23:43
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 1, 2026
@felipemello1
felipemello1 marked this pull request as ready for review November 2, 2026 00:35
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 2, 2026
@felipemello1
felipemello1 marked this pull request as draft November 2, 2026 00:41
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 2, 2026
@felipemello1
felipemello1 force-pushed the felipemello1/gdn-stack/6-fp32-decay-params branch from ff88955 to 594f95d Compare November 2, 2026 03:10
@felipemello1 felipemello1 changed the title [rl] generator: keep float32 GDN A_log/dt_bias with the fused weights (6/6) [rl] generator: keep GDN A_log/dt_bias in float32 (6/6) Nov 2, 2026
@felipemello1
felipemello1 marked this pull request as ready for review November 2, 2026 03:18
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 2, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Redone in 594f95d (6/6 of the GDN stack). The generator holds GDN's A_log/dt_bias as float32 parameters, FSDP keeps their dtype through a Decoder._fsdp_param_dtype_override_fn passthrough (default None = main's path), and the receive copy uses the dtypes the trainer sends. Bitwise; GDN layer -3.2 to -5.8 us per step. Details and tests in the body.

@claude please review.

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 3m 29s —— View job


Approve (please add the TODO on the new Decoder hook before merging; a maintainer still needs to review the core change): Review

@claude claude Bot 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.

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

  1. 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. For model_dtype != "bfloat16" it changes the unshard dtype, from bf16 to model_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_fsdp forwards the attribute. The other _apply_fsdp overrides (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 at model_wrapper.py:401-402 is accurate. The generator never computes grads, so freezing costs nothing.
  • Receive dtypes vs trainer. trainer.py:509-514 sends parameters as _transfer_dtype when generator_dtype != training.dtype, and otherwise in their own training.dtype. In the second case (bf16 trainer, bf16 generator), the sent dtype equals model_dtype, so model_wrapper.py:468-476 matches both cases. The new assert in test_bitwise_parity.py checks exactly this.
  • Quantized params. _ShardedFSDPTensor.fsdp_pre_all_gather reads mp_policy.param_dtype directly (_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_config set, outside the RL loop) now keeps a float32 A_log unrounded. The NOTE in the description covers this. In the RL loop the config is None, and weights arrive bf16 from the trainer.
  • KDA (kda.py) still casts A_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.

Comment thread torchtitan/models/common/decoder.py Resolved
@felipemello1 felipemello1 changed the title [rl] generator: keep GDN A_log/dt_bias in float32 (6/6) [rl] generator: keep GDN A_log/dt_bias in float32 (6/7) Nov 2, 2026
@felipemello1
felipemello1 force-pushed the felipemello1/gdn-stack/6-fp32-decay-params branch from 96effd4 to 3621d9b Compare November 2, 2026 07:55
Base automatically changed from felipemello1/gdn-stack/5-fused-input-proj to main November 2, 2026 15:21
Felipe Mello added 2 commits November 2, 2026 10:21
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.
@felipemello1
felipemello1 force-pushed the felipemello1/gdn-stack/6-fp32-decay-params branch from 3621d9b to 1f37f3d Compare November 2, 2026 15:21
@felipemello1
felipemello1 merged commit c3093f7 into main Nov 2, 2026
d4l3k added a commit that referenced this pull request Nov 3, 2026
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.
tianyu-l added a commit that referenced this pull request Nov 4, 2026
…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.
tianyu-l added a commit that referenced this pull request Nov 4, 2026
… 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants