Skip to content

[fsdp2][mp] per-param mixed_precision policy - #196626

Closed
anshul-si wants to merge 19 commits into
gh/anshul-si/141/basefrom
gh/anshul-si/141/head
Closed

anshul-si wants to merge 19 commits into
gh/anshul-si/141/basefrom
gh/anshul-si/141/head

Conversation

@anshul-si

@anshul-si anshul-si commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary: We want to enable per-param mixed precision policy in FSDP2 for several reasons including KDA, etc.

Key Points
All-gather: During all-gather, existing homogenous path remains unchanged. When parameters require different compute dtypes, FSDP groups staging copies by source/target dtype and invokes the existing uint8 communication buffer, keeping only one AG per fully_shard. As seen in benchmarking results below, there is a small perf difference in the copy-in which can be attributed to foreach_copy uses a fixed four elements per thread, so for uint8 vs bf16, we have twice as much element-level scheduling and instruction work to transfer the same number of bytes.

Reduce-scatter: Parameters using different compute_dtypes inevitably results in gradients with different dtypes, but a reduce-scatter input buffer must have a single dtype. When all parameters share reduce_dtype, we want FSDP to preserve existing single-collective behavior. To support this efficiently, the existing _chunk_cat.out CUDA path was extended to read heterogeneous BF16/FP32 inputs and cast them directly into the reduction buffer while performing chunking and padding. Without this fused path, FSDP would need to materialize full-size tensors in the reduction dtype and then run the ordinary homogeneous packing kernel, adding another read/write pass and substantial temporary memory. The existing operator schema and homogeneous kernels remain intact. If parameters request genuinely different reduction dtypes, FSDP instead creates one bucket and one reduce-scatter per effective dtype.

Benchmarking: We first isolated reduce-scatter packing on an H100 using a transformer-like workload containing 50.3 million elements and small FP32 islands. Fused mixed BF16/FP32-to-FP32 packing took 0.1888 ms, compared with 0.3582 ms for pre-casting into FP32 staging tensors followed by homogeneous packing, reducing packing latency by approximately 47% while avoiding roughly 192 MiB of temporary FP32 storage. We then measured all-gather using real FSDP parameter objects and a KDA-style layout containing FP32 decay parameters, normalization weights, and a router gate. Across grouped and approximately 500-parameter layouts, raw packing was approximately 8.7–8.8%
slower, complete copy-in was approximately 2.4–2.5% slower, and copy-out was unchanged. Finally, we ran an eight-block, 1.75-billion-parameter KDA-style model through real FSDP2 forward and backward passes, including per-block unsharding, resharding, NCCL collectives, and gradient reduction. Across both benchmark orderings, total all-gather copy-in was 4.2–4.9% slower, copy-out varied from −0.6% to +0.3%, and synchronized forward-plus-backward time remained approximately 53 ms for both configurations, showing no measurable end-to-end regression.

Stack from ghstack (oldest at bottom):

Pull-Request: #196576

ghstack-source-id: aee9a75
Pull-Request: #196576

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196626

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (3 Unrelated Failures)

As of commit 7611d46 with merge base c4e269e (image):

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (fsdp) release notes category labels Sep 10, 2026
@anshul-si anshul-si added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 10, 2026
anshul-si added a commit that referenced this pull request Sep 10, 2026
ghstack-source-id: 5de48e6
Pull-Request: #196576

ghstack-source-id: 5de48e6
Pull Request resolved: #196626
anshul-si added a commit that referenced this pull request Sep 10, 2026
ghstack-source-id: 21e38a7
Pull-Request: #196576

ghstack-source-id: 21e38a7
Pull Request resolved: #196626
**Summary:** We want to enable per-param mixed precision policy in FSDP2 for several reasons including KDA, etc. 

**Key Points**
All-gather: During all-gather, existing homogenous path remains unchanged. When parameters require different compute dtypes, FSDP groups staging copies by source/target dtype and invokes the existing uint8 communication buffer, keeping only one AG per fully_shard. 

Reduce-scatter: Parameters using different compute_dtypes inevitably results in gradients with different dtypes, but a reduce-scatter input buffer must have a single dtype. When all parameters share reduce_dtype, we want FSDP to preserve existing single-collective behavior. To support this efficiently, the existing _chunk_cat.out CUDA path was extended to read heterogeneous BF16/FP32 inputs and cast them directly into the reduction buffer while performing chunking and padding. Without this fused path, FSDP would need to materialize full-size tensors in the reduction dtype and then run the ordinary homogeneous packing kernel, adding another read/write pass and substantial temporary memory. The existing operator schema and homogeneous kernels remain intact. If parameters request genuinely different reduction dtypes, FSDP instead creates one bucket and one reduce-scatter per effective dtype.

Benchmarking: We first isolated reduce-scatter packing on an H100 using a transformer-like workload containing 50.3 million elements and small FP32 islands. Fused mixed BF16/FP32-to-FP32 packing took 0.1888 ms, compared with 0.3582 ms for pre-casting into FP32 staging tensors followed by homogeneous packing, reducing packing latency by approximately 47% while avoiding roughly 192 MiB of temporary FP32 storage. We then measured all-gather using real FSDP parameter objects and a KDA-style layout containing FP32 decay parameters, normalization weights, and a router gate. Across grouped and approximately 500-parameter layouts, raw packing was approximately 8.7–8.8%
slower, complete copy-in was approximately 2.4–2.5% slower, and copy-out was unchanged. Finally, we ran an eight-block, 1.75-billion-parameter KDA-style model through real FSDP2 forward and backward passes, including per-block unsharding, resharding, NCCL collectives, and gradient reduction. Across both benchmark orderings, total all-gather copy-in was 4.2–4.9% slower, copy-out varied from −0.6% to +0.3%, and synchronized forward-plus-backward time remained approximately 53 ms for both configurations, showing no measurable end-to-end regression.
 

Pull-Request: #196576

[ghstack-poisoned]
anshul-si added a commit that referenced this pull request Sep 11, 2026
ghstack-source-id: 1a4b41a
Pull-Request: #196576

ghstack-source-id: 1a4b41a
Pull Request resolved: #196626
**Summary:** We want to enable per-param mixed precision policy in FSDP2 for several reasons including KDA, etc. 

**Key Points**
All-gather: During all-gather, existing homogenous path remains unchanged. When parameters require different compute dtypes, FSDP groups staging copies by source/target dtype and invokes the existing uint8 communication buffer, keeping only one AG per fully_shard. As seen in benchmarking results below, there is a small perf difference in the copy-in which can be attributed to foreach_copy uses a fixed four elements per thread, so for uint8 vs bf16, we have twice as much element-level scheduling and instruction work to transfer the same number of bytes. 

Reduce-scatter: Parameters using different compute_dtypes inevitably results in gradients with different dtypes, but a reduce-scatter input buffer must have a single dtype. When all parameters share reduce_dtype, we want FSDP to preserve existing single-collective behavior. To support this efficiently, the existing _chunk_cat.out CUDA path was extended to read heterogeneous BF16/FP32 inputs and cast them directly into the reduction buffer while performing chunking and padding. Without this fused path, FSDP would need to materialize full-size tensors in the reduction dtype and then run the ordinary homogeneous packing kernel, adding another read/write pass and substantial temporary memory. The existing operator schema and homogeneous kernels remain intact. If parameters request genuinely different reduction dtypes, FSDP instead creates one bucket and one reduce-scatter per effective dtype.

Benchmarking: We first isolated reduce-scatter packing on an H100 using a transformer-like workload containing 50.3 million elements and small FP32 islands. Fused mixed BF16/FP32-to-FP32 packing took 0.1888 ms, compared with 0.3582 ms for pre-casting into FP32 staging tensors followed by homogeneous packing, reducing packing latency by approximately 47% while avoiding roughly 192 MiB of temporary FP32 storage. We then measured all-gather using real FSDP parameter objects and a KDA-style layout containing FP32 decay parameters, normalization weights, and a router gate. Across grouped and approximately 500-parameter layouts, raw packing was approximately 8.7–8.8%
slower, complete copy-in was approximately 2.4–2.5% slower, and copy-out was unchanged. Finally, we ran an eight-block, 1.75-billion-parameter KDA-style model through real FSDP2 forward and backward passes, including per-block unsharding, resharding, NCCL collectives, and gradient reduction. Across both benchmark orderings, total all-gather copy-in was 4.2–4.9% slower, copy-out varied from −0.6% to +0.3%, and synchronized forward-plus-backward time remained approximately 53 ms for both configurations, showing no measurable end-to-end regression.
 

Pull-Request: #196576

[ghstack-poisoned]
anshul-si added a commit that referenced this pull request Sep 11, 2026
ghstack-source-id: 83f5ab2
Pull-Request: #196576

ghstack-source-id: 83f5ab2
Pull Request resolved: #196626
@anshul-si
anshul-si marked this pull request as ready for review September 11, 2026 07:19
**Summary:** We want to enable per-param mixed precision policy in FSDP2 for several reasons including KDA, etc. 

**Key Points**
All-gather: During all-gather, existing homogenous path remains unchanged. When parameters require different compute dtypes, FSDP groups staging copies by source/target dtype and invokes the existing uint8 communication buffer, keeping only one AG per fully_shard. As seen in benchmarking results below, there is a small perf difference in the copy-in which can be attributed to foreach_copy uses a fixed four elements per thread, so for uint8 vs bf16, we have twice as much element-level scheduling and instruction work to transfer the same number of bytes. 

Reduce-scatter: Parameters using different compute_dtypes inevitably results in gradients with different dtypes, but a reduce-scatter input buffer must have a single dtype. When all parameters share reduce_dtype, we want FSDP to preserve existing single-collective behavior. To support this efficiently, the existing _chunk_cat.out CUDA path was extended to read heterogeneous BF16/FP32 inputs and cast them directly into the reduction buffer while performing chunking and padding. Without this fused path, FSDP would need to materialize full-size tensors in the reduction dtype and then run the ordinary homogeneous packing kernel, adding another read/write pass and substantial temporary memory. The existing operator schema and homogeneous kernels remain intact. If parameters request genuinely different reduction dtypes, FSDP instead creates one bucket and one reduce-scatter per effective dtype.

Benchmarking: We first isolated reduce-scatter packing on an H100 using a transformer-like workload containing 50.3 million elements and small FP32 islands. Fused mixed BF16/FP32-to-FP32 packing took 0.1888 ms, compared with 0.3582 ms for pre-casting into FP32 staging tensors followed by homogeneous packing, reducing packing latency by approximately 47% while avoiding roughly 192 MiB of temporary FP32 storage. We then measured all-gather using real FSDP parameter objects and a KDA-style layout containing FP32 decay parameters, normalization weights, and a router gate. Across grouped and approximately 500-parameter layouts, raw packing was approximately 8.7–8.8%
slower, complete copy-in was approximately 2.4–2.5% slower, and copy-out was unchanged. Finally, we ran an eight-block, 1.75-billion-parameter KDA-style model through real FSDP2 forward and backward passes, including per-block unsharding, resharding, NCCL collectives, and gradient reduction. Across both benchmark orderings, total all-gather copy-in was 4.2–4.9% slower, copy-out varied from −0.6% to +0.3%, and synchronized forward-plus-backward time remained approximately 53 ms for both configurations, showing no measurable end-to-end regression.
 

Pull-Request: #196576

[ghstack-poisoned]
anshul-si added a commit that referenced this pull request Sep 17, 2026
ghstack-source-id: b237cd9
Pull Request resolved: #196626
[ghstack-poisoned]
anshul-si added a commit that referenced this pull request Sep 17, 2026
ghstack-source-id: 49dd557
Pull Request resolved: #196626
[ghstack-poisoned]
@weifengpy

Copy link
Copy Markdown
Contributor

@anshul-si I introduced torch.ops.fsdp.chunk_cat_mixed_dtype. maybe rebase on #198668 and review them ?

meta-codesync Bot pushed a commit to meta-pytorch/flex_shard that referenced this pull request Oct 3, 2026
Summary:
This diff accomplishes the goals of separating sharded and unsharded gradient dtypes (pytorch/pytorch#194434) and per-param mixed precision (pytorch/pytorch#196626). In order to accomplish this we created args that save grad_dtype if it was explicitly set before Flexshard is called. During accumulation, we need to determine what the accumulation dtype should be now that we have saved gradient_dtype. Unlike FSDP2, where we simply use param.grad_dtype = dtype, FlexShard's full params are outputs of _BucketUnshard.apply. They have a grad_fn on purpose, because that's how the grad reaches _BucketUnshard.backward and the reduce-scatter. As a result, they aren't leaf parameters and will fail, which is why use set_output_grad_dtype instead. As a result of this change, we can now have parameters with different grad_dtype, so we use the promote_types of accumulation dtypes of bucket’s trainable parameters, leaving out frozen parameters. One thing, which is documented is that if grad_dtype is None and reduce_dtype is unset, and there is a unused param on one rank, FlexShard still reduces it, using zero gradient in the foward dtype, its possible that ranks can hang.

We also have to make changes to Flexshard's dist muon as a result of saving grad_dtpyes. Previosuly, a param's grad_dtype would just default to be the original storage_dtype since we didn't set it when FlexShard creates a new param. Now that we save the grad_dtype we could end up with situation where the real params grad_dtype is different for real param storage dtype. However, dist_muon's proxy creates a new dtensor whose grad_dtype is the same as the tensor's own default. When we try to assign proxy.grad, we get dtype mismatch.

Reviewed By: weifengpy

Differential Revision: D121468586

Pull Request resolved: #23
[ghstack-poisoned]
anshul-si added a commit that referenced this pull request Oct 3, 2026
ghstack-source-id: cceee1f
Pull Request resolved: #196626
@anshul-si

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

garrett361 added a commit to PrimeIntellect-ai/prime-rl that referenced this pull request Oct 7, 2026
… and activation checkpointing (#3925)

With `moe_router_dtype="float32"` (the RL default) and activation
checkpointing on, every MoE block ran eager under `torch.compile`. Two
things combine to cause it:

- The fp32 router is its own FSDP2 unit, and FSDP2 hooks are
dynamo-disabled, so the router always breaks the graph.
- Under `compile(AC(block))` the checkpoint compiles as a higher-order
op, which forbids breaks, so Dynamo ran the whole block eagerly.

This PR compiles inside the checkpoint instead: for any checkpointed
block that holds a nested FSDP unit (today, the fp32 router), an eager
checkpoint now wraps the compiled block (`AC(compile(block))`), so the
nested unit's break only splits the block into compiled graphs. To see
those units, compile now runs after FSDP. Compiling in place keeps the
same module object, so the order changes nothing at runtime.

The reorder is safe. The old `AC -> Compile -> FSDP` comment was ported
from TorchTitan in #923, when `apply_compile` still wrapped each block
with `torch.compile(block)`. #957 switched to in-place `.compile()` two
days later without revisiting it. With in-place compile, both orders
trace the same frames: graph breaks, loss and step time match on both
workloads, and `fullgraph=True` (with a bf16 router) still compiles with
zero graph breaks.

| Workload (8x H200, EP 8, full AC) | before (s/step) | after (s/step) |
MFU |
|---|---|---|---|
| GLM-4.5-Air, 16 layers, real data | 6.21, 6.17 | 5.22, 5.21 | 35% to
42% |
| Qwen3-30B-A3B, fake data | 5.96, 5.96 | 4.51, 4.51 | 32% to 42% |

Two runs per arm, each the median `time/step` over steps 5 to 20, no
offloading. Peak memory is unchanged, and loss and grad norm track the
baseline within run-to-run noise.

![Qwen3-30B-A3B MoE layer forward, before and
after](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/09e64ed1afc27e97fda6080556171522e29c9a0e/pr-figures/fp32-router-compile/qwen_layer_forward.png)

**Figure:** one MoE layer's forward on Qwen3-30B-A3B, before and after
this PR. The orange eager elementwise kernels collapse into a few pink
compiled Triton kernels, so the layer's forward drops from 16.4 to 11.3
ms.

<details><summary>Same view on GLM-4.5-Air</summary>

![GLM-4.5-Air MoE layer forward, before and
after](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/09e64ed1afc27e97fda6080556171522e29c9a0e/pr-figures/fp32-router-compile/glm_layer_forward.png)

</details>

## Alternative considered

Keeping recompute inside the compiler: drop the block-level checkpoint
and instead checkpoint two compiled regions that exclude the router, the
attention module and the post-router MoE work. It beat the baseline but
was slower than this PR (Qwen3-30B 5.50 vs 4.51 s/step, GLM-4.5-Air 5.85
vs 5.22 s/step) and used more memory, because the norms and the router's
fp32 activations stay outside any checkpoint.

## North star: fullgraph fp32 router support

Fullgraph compile with an fp32 router stays unsupported, and
`model.compile.fullgraph=true` still raises for it. The blocker is the
router's FSDP unit itself: FSDP2 applies one mixed-precision policy per
unit, so the fp32 router cannot share the block's bf16 unit, and its
dynamo-disabled hooks are the graph break above. PyTorch
[#196626](pytorch/pytorch#196626) adds
per-parameter mixed precision, which lets the router stay in the block's
unit. That removes the break, enables fullgraph, and makes this PR's
compile-inside-AC path unnecessary, so it should be reverted then.
#196626 is on PyTorch `main` but not yet in a release.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
**Summary:** We want to enable per-param mixed precision policy in FSDP2 for several reasons including KDA, etc.

**Key Points**
All-gather: During all-gather, existing homogenous path remains unchanged. When parameters require different compute dtypes, FSDP groups staging copies by source/target dtype and invokes the existing uint8 communication buffer, keeping only one AG per fully_shard. As seen in benchmarking results below, there is a small perf difference in the copy-in which can be attributed to foreach_copy uses a fixed four elements per thread, so for uint8 vs bf16, we have twice as much element-level scheduling and instruction work to transfer the same number of bytes.

Reduce-scatter: Parameters using different compute_dtypes inevitably results in gradients with different dtypes, but a reduce-scatter input buffer must have a single dtype. When all parameters share reduce_dtype, we want FSDP to preserve existing single-collective behavior. To support this efficiently, the existing _chunk_cat.out CUDA path was extended to read heterogeneous BF16/FP32 inputs and cast them directly into the reduction buffer while performing chunking and padding. Without this fused path, FSDP would need to materialize full-size tensors in the reduction dtype and then run the ordinary homogeneous packing kernel, adding another read/write pass and substantial temporary memory. The existing operator schema and homogeneous kernels remain intact. If parameters request genuinely different reduction dtypes, FSDP instead creates one bucket and one reduce-scatter per effective dtype.

Benchmarking: We first isolated reduce-scatter packing on an H100 using a transformer-like workload containing 50.3 million elements and small FP32 islands. Fused mixed BF16/FP32-to-FP32 packing took 0.1888 ms, compared with 0.3582 ms for pre-casting into FP32 staging tensors followed by homogeneous packing, reducing packing latency by approximately 47% while avoiding roughly 192 MiB of temporary FP32 storage. We then measured all-gather using real FSDP parameter objects and a KDA-style layout containing FP32 decay parameters, normalization weights, and a router gate. Across grouped and approximately 500-parameter layouts, raw packing was approximately 8.7–8.8%
slower, complete copy-in was approximately 2.4–2.5% slower, and copy-out was unchanged. Finally, we ran an eight-block, 1.75-billion-parameter KDA-style model through real FSDP2 forward and backward passes, including per-block unsharding, resharding, NCCL collectives, and gradient reduction. Across both benchmark orderings, total all-gather copy-in was 4.2–4.9% slower, copy-out varied from −0.6% to +0.3%, and synchronized forward-plus-backward time remained approximately 53 ms for both configurations, showing no measurable end-to-end regression.

Pull-Request: pytorch#196576
Pull Request resolved: pytorch#196626
Approved by: https://github.com/weifengpy
tianyu-l added a commit to pytorch/torchtitan 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/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: distributed (fsdp) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants