Skip to content

[rl] Put GPU weights directly into TorchStore, drop trainer staging buffers - #5659

Merged
d4l3k merged 1 commit into
mainfrom
d4l3k/titan-trainer-direct-push
Nov 3, 2026
Merged

d4l3k merged 1 commit into
mainfrom
d4l3k/titan-trainer-direct-push

Conversation

@d4l3k

@d4l3k d4l3k commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Fixes #5654

Root issue: the RL trainer copies its weights into pinned CPU staging buffers, then ts.put_state_dict(direct_rdma=False) copies them again into the colocated StorageVolumes. So every trainer host holds two CPU copies of its shard.

Fix: drop the staging buffers. push_model_state_dict now puts the live GPU state dict with transfer_dtype from a worker thread (asyncio.to_thread).

  • The worker makes the push stream current and synchronizes it. The current stream is thread-local, so this has to happen inside the worker. Transports that read GPU memory outside stream order (RDMA) then see weights from after the last optimizer step.
  • With colocated SharedMemory, TorchStore casts during the D2H copy into StorageVolume memory, so the volume holds the only CPU copy.
  • Persistent buffers keep their registered dtype through preserve_dtype_keys.
  • Push/pull ordering is unchanged: push N is awaited before optimizer step N+1.

Depends on meta-pytorch/torchstore#266, which adds transport-side casting and preserve_dtype_keys. torchtitan installs torchstore@main unpinned, so that PR must land first.

Lines: implementation +60/-91, tests +29/-115.

Test plan:

  • pytest tests/rl/unit_tests/cpu --ignore=tests/rl/unit_tests/cpu/test_dapo_math.py: 482 passed. test_model_defaults[dapo_math] and test_dapo_math.py collection fail with an environment ImportError (CallbackArgs); this is unrelated to the change.
  • New test_push_model_state_dict_puts_on_push_stream_in_worker checks that the push:
    • runs in a worker thread on the push stream and synchronizes it first;
    • puts live tensors (data_ptrs match);
    • passes transfer_dtype, and passes preserve_dtype_keys with the canonical names of nested buffers, excluding non-persistent buffers.
  • Removed the tests for the deleted staging-buffer helpers.

Results (GB200, one client + one local StorageVolume, SharedMemory, 290 fp32 GPU tensors pushed as bf16, median of 5 pushes; old = pinned bf16 staging copy then put):

fp32 shard push time old → new client RSS old → new extra GPU peak
4 GiB 246 → 35 ms 6.46 → 4.20 GiB 7 MiB both
16 GiB 304 → 66 ms 22.54 → 13.46 GiB 28 MiB both

The SHM segments are pinned with cudaHostRegister, so the D2H stays a pinned copy. The cast uses one tensor's worth of GPU scratch at a time. Non-SHM transports still materialize a bf16 GPU copy per put batch. Pushed weights match w.bfloat16() when read back.

This PR was AI-assisted.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 28, 2026
@d4l3k
d4l3k force-pushed the d4l3k/titan-trainer-direct-push branch from 6a259de to 633b855 Compare October 28, 2026 21:42
@d4l3k
d4l3k marked this pull request as ready for review October 29, 2026 00:37
@d4l3k
d4l3k requested a review from felipemello1 as a code owner October 29, 2026 00:37
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 29, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 48s —— View job


Approve -- please address the items before merging (rename the leftover "staging" names; post before/after push timing and memory numbers). See the 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 fix removes a redundant full CPU copy of the trainer shard at the layer that owns it. torchstore#266 merged today, so the new put_state_dict kwargs exist.

What this PR does. The RL trainer no longer keeps its own pinned CPU mirror of the weights. push_model_state_dict hands the live (GPU, possibly DTensor) state dict to ts.put_state_dict with transfer_dtype, and TorchStore does the cast. Persistent buffers keep their dtype through preserve_dtype_keys. The worker thread makes the side stream current and synchronizes it before the put. That way the put sees post-optimizer weights, and casts don't queue behind forward/backward N+1 on the default stream.

Example. fp32 training with a bf16 generator, FSDP, colocated volume:

before: GPU fp32 --copy_(cast, non_blocking)--> pinned CPU bf16 (trainer) --memcpy--> shm bf16 (volume)
        host holds 2 bf16 copies of the shard
after:  GPU fp32 --TorchStore copy_(cast)--> shm bf16 (volume)
        host holds 1 copy; a `norm.scale` buffer stays fp32 via preserve_dtype_keys

Must fix

  1. torchtitan/rl/trainer/trainer.py:438: the stream, the helper, and the comments still talk about "staging", which no longer happens. Rename them (see inline).
  2. torchtitan/rl/trainer/trainer.py:404: the description has no perf or memory numbers. The D2H now writes straight into the shm segment, which may be pageable instead of pinned. Non-SharedMemory transports also allocate a GPU cast copy per batch during the overlapped forward/backward. Please post before/after push timing, blocking time, host RSS, and GPU reserved memory (see inline).

Questions

  • The torchstore#266 description says "Not covered: DTensor inputs with transfer_dtype". That is exactly the FSDP main path here, and the new unit test only uses plain nn.Linear. Did an RL GPU job (e.g. rl-kimi-k3 / 8-GPU build-test) run after #266 merged? Does it check that generator weights match the trainer after a cast push, or only that the run completes?

Not verified: whether TorchStore pins or registers the shm segment for D2H; GPU memory for non-SharedMemory transports; the DTensor + transfer_dtype numerics (needs a GPU run). This touches core RL trainer code, so a maintainer still needs to review.

Comment thread torchtitan/rl/trainer/trainer.py Outdated
# The current stream is thread-local; set it in this worker so TorchStore
# copies wait on the optimizer step rather than on later default-stream
# work. Synchronize because RDMA transports read outside stream order.
stream = self._staging_model_state_dict_stream

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.

After this PR nothing is staged anymore, but the old names are still here: _staging_model_state_dict_stream (L133/135/438), _mark_model_state_dict_ready_for_staging (L136/167/349), "staging must wait" (L172), and "synchronizes the staging stream" (L411). A reader will look for staging buffers that no longer exist. Rename them to match what they do now, e.g. _push_model_state_dict_stream / _mark_model_state_dict_ready_for_push, and update the L172 comment to say the push waits.

Comment on lines +404 to +407
The live GPU tensors are put directly, so the trainer keeps no CPU
snapshot of its own. With the colocated SharedMemory transport,
TorchStore copies (and casts) each tensor straight into StorageVolume
memory; other transports make a GPU cast copy of each batch first.

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.

This trades one CPU copy for a different D2H path, and the description has no numbers for it. Before, D2H went GPU -> pinned buffer (fast and async), followed by a CPU memcpy into the volume. Now D2H goes straight into the StorageVolume shm segment. Unless TorchStore registers or pins that segment (unverified), this is a pageable D2H copy, which can be much slower. If the push then outlasts forward/backward N+1, timing/step/blocking_trainer_push_model_state_dict grows on every step.

Second, for non-SharedMemory transports this docstring says TorchStore makes "a GPU cast copy of each batch". That copy is allocated while forward/backward N+1 is running. Before, the transient was one tensor (copy_(non_blocking=True) casts per tensor on the GPU). If a batch is a whole volume's worth of tensors, peak GPU memory during the overlap goes up.

Please add before/after numbers to the description for timing/weight_sync/trainer_push_model_state_dict, blocking_trainer_push_model_state_dict, trainer host RSS (the claimed win), and trainer/memory/max_reserved_gib, on one representative FSDP run.

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

looks great, thanks a lot

"""Allocate a final-dtype pinned CPU mirror of the model state dict."""
buffer_names = {
def _model_buffer_names(
self, model_state_dict: dict[str, torch.Tensor]

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.

nit: here the arg model_state_dict seems not necessary?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

We need this to drop non-persistent buffers like rope cache, etc. We could just pass the keys but this is simplest, going to keep ti as is

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.

I agree on the dropping buffer part. If we don't do intersection(model_state_dict), wouldn't it be the same thing?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

No, there's named_buffers() in the model that aren't in the state_dict. The intersection limits it to buffers that are actually checkpointed

If we just pass all named buffers we end up with an error from torchstore preserve_dtype_keys not in the state dict

Comment on lines +447 to +449
transfer_dtype=self._transfer_dtype,
# Buffers keep their registered dtype when weights are cast.
preserve_dtype_keys=buffer_names,

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.

Not only for buffers, but also for some params we will need keep them in fp32, when the transfer_dtype is bf16. This is a refactor to be done, and it's good to know that we can just use the two fields here together.

In general FSDP introduced a param_dtype_override_fn in https://github.com/pytorch/pytorch/pull/196626/changes#diff-503f6fc8de55581b0588f7d84d329b8a51ae618ff36a1caf70c60fd56d5a99a7 which is more general. We don't need to change torchstore right now for our needs, but I think it's possible later we will need more customizable contract.

Also it's fine to introduce such general thing later if BC breakage is not a big concern for torchstore (or anything we planned).

…uffers

Fixes #5654. The trainer kept pinned CPU staging buffers plus a second CPU copy in the colocated StorageVolumes. Put the GPU state dict with transfer_dtype from a worker thread on a side stream; shm copies straight into StorageVolume memory while still overlapping fwd/bwd.
@felipemello1

Copy link
Copy Markdown
Contributor

@d4l3k did you have a chance to sanity check correctness? Maybe a 50 step on dapo math? (ask the agent to remove eval, so it goes quicker)

@d4l3k
d4l3k added this pull request to stack #5753 November 3, 2026 01:39
@d4l3k

d4l3k commented Nov 3, 2026

Copy link
Copy Markdown
Member Author

Sanity check: dapo_math (rl_dapo_qwen3_4b_math_8k, Qwen3-4B-Base), 50 steps, validation off. Shrunk to 2 GB200s (trainer TP=1 + 1 generator), torchstore main (includes meta-pytorch/torchstore#266, SHM transport). PR = b2e9ce9, base = its main base 4e8b4b8.

Mean per 10-step window (reward / loss / max trainer-vs-generator logprob diff):

steps PR base
1-10 0.179 / -0.013 / 0.71 0.186 / 0.013 / 0.75
11-20 0.200 / 0.020 / 0.87 0.219 / 0.023 / 0.64
21-30 0.209 / 0.047 / 0.58 0.251 / 0.026 / 1.18
31-40 0.260 / 0.038 / 0.76 0.230 / 0.028 / 0.95
41-50 0.246 / 0.036 / 0.79 0.255 / 0.044 / 0.81
all 0.219 / 0.026 / 0.74 0.228 / 0.027 / 0.87

Reward climbs similarly in both (~0.18 -> ~0.25), grad norm matches (0.141 vs 0.143 mean), and the trainer/generator logprob diff stays flat and in the same range, so the generator gets the updated weights each step. Differences are within run-to-run noise (non-deterministic rollouts). Throughput is the same (6428 vs 6419 tok/s), and blocking push time is negligible in both.

(Run and summary are AI-assisted.)

tianyu-l added a commit that referenced this pull request Nov 3, 2026
… mixed-precision casts

Add Module.Config.preserve_dtype_params: parameters that bulk casts never
lower in precision. FSDP mixed precision (via param_dtype_override_fn) and
checkpoint export keep the wider of the parameter's own dtype and the target;
the RL weight sync sends them in their own dtype.

The RL generator now mirrors the trainer's Controller.Config.precision instead
of generator.model_dtype (removed): it builds the model in precision.dtype,
holds the other parameters in precision.param_dtype, and computes in it.

Defaults on GDN/KDA (A_log, dt_bias), DeepSeek-V4 HcPre/HcHead (hc_*) and
Compressor (ape); flavors set Qwen3.5's GDN gated norm and DeepSeek-V4's
attn_sink. Removes Decoder._fsdp_param_dtype_override_fn.

Stacked on #5659 and the PrecisionConfig PR.
tianyu-l added a commit that referenced this pull request Nov 3, 2026
… mixed-precision casts

Add Module.Config.preserve_dtype_params: parameters that bulk casts never
lower in precision. FSDP mixed precision (via param_dtype_override_fn) and
checkpoint export keep the wider of the parameter's own dtype and the target;
the RL weight sync sends them in their own dtype.

The RL generator now mirrors the trainer's Controller.Config.precision instead
of generator.model_dtype (removed): it builds the model in precision.dtype,
holds the other parameters in precision.param_dtype, and computes in it.

Defaults on GDN/KDA (A_log, dt_bias), DeepSeek-V4 HcPre/HcHead (hc_*) and
Compressor (ape); flavors set Qwen3.5's GDN gated norm and DeepSeek-V4's
attn_sink. Removes Decoder._fsdp_param_dtype_override_fn.

Stacked on #5659 and the PrecisionConfig PR.
tianyu-l added a commit that referenced this pull request Nov 3, 2026
… mixed-precision casts

Add Module.Config.preserve_dtype_params: parameters that bulk casts never
lower in precision. FSDP mixed precision (via param_dtype_override_fn) and
checkpoint export keep the wider of the parameter's own dtype and the target;
the RL weight sync sends them in their own dtype.

The RL generator now mirrors the trainer's Controller.Config.precision instead
of generator.model_dtype (removed): it builds the model in precision.dtype,
holds the other parameters in precision.param_dtype, and computes in it.

Defaults on GDN/KDA (A_log, dt_bias), DeepSeek-V4 HcPre/HcHead (hc_*) and
Compressor (ape); flavors set Qwen3.5's GDN gated norm and DeepSeek-V4's
attn_sink. Removes Decoder._fsdp_param_dtype_override_fn.

Stacked on #5659 and the PrecisionConfig PR.
@d4l3k
d4l3k merged commit 411ce5b into main Nov 3, 2026
tianyu-l added a commit that referenced this pull request Nov 3, 2026
… mixed-precision casts

Add Module.Config.preserve_dtype_params: parameters that bulk casts never
lower in precision. FSDP mixed precision (via param_dtype_override_fn) and
checkpoint export keep the wider of the parameter's own dtype and the target;
the RL weight sync sends them in their own dtype.

The RL generator now mirrors the trainer's Controller.Config.precision instead
of generator.model_dtype (removed): it builds the model in precision.dtype,
holds the other parameters in precision.param_dtype, and computes in it.

Defaults on GDN/KDA (A_log, dt_bias), DeepSeek-V4 HcPre/HcHead (hc_*) and
Compressor (ape); flavors set Qwen3.5's GDN gated norm and DeepSeek-V4's
attn_sink. Removes Decoder._fsdp_param_dtype_override_fn.

Stacked on #5659 and the PrecisionConfig PR.
tianyu-l added a commit that referenced this pull request Nov 3, 2026
… mixed-precision casts

Add Module.Config.preserve_dtype_params: parameters that bulk casts never
lower in precision. FSDP mixed precision (via param_dtype_override_fn) and
checkpoint export keep the wider of the parameter's own dtype and the target;
the RL weight sync sends them in their own dtype.

The RL generator now mirrors the trainer's Controller.Config.precision instead
of generator.model_dtype (removed): it builds the model in precision.dtype,
holds the other parameters in precision.param_dtype, and computes in it.

Defaults on GDN/KDA (A_log, dt_bias), DeepSeek-V4 HcPre/HcHead (hc_*) and
Compressor (ape); flavors set Qwen3.5's GDN gated norm and DeepSeek-V4's
attn_sink. Removes Decoder._fsdp_param_dtype_override_fn.

Stacked on #5659 and the PrecisionConfig PR.
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 3, 2026
… mixed-precision casts

Add Module.Config.preserve_dtype_params: parameters that bulk casts never
lower in precision. FSDP mixed precision (via param_dtype_override_fn) and
checkpoint export keep the wider of the parameter's own dtype and the target;
the RL weight sync sends them in their own dtype.

The RL generator now mirrors the trainer's Controller.Config.precision instead
of generator.model_dtype (removed): it builds the model in precision.dtype,
holds the other parameters in precision.param_dtype, and computes in it.

Defaults on GDN/KDA (A_log, dt_bias), DeepSeek-V4 HcPre/HcHead (hc_*) and
Compressor (ape); flavors set Qwen3.5's GDN gated norm and DeepSeek-V4's
attn_sink. Removes Decoder._fsdp_param_dtype_override_fn.

Stacked on #5659 and the PrecisionConfig PR.
tianyu-l added a commit that referenced this pull request Nov 3, 2026
… mixed-precision casts

Add Module.Config.preserve_dtype_params: parameters that bulk casts never
lower in precision. FSDP mixed precision (via param_dtype_override_fn) and
checkpoint export keep the wider of the parameter's own dtype and the target;
the RL weight sync sends them in their own dtype.

The RL generator now mirrors the trainer's Controller.Config.precision instead
of generator.model_dtype (removed): it builds the model in precision.dtype,
holds the other parameters in precision.param_dtype, and computes in it.

Defaults on GDN/KDA (A_log, dt_bias), DeepSeek-V4 HcPre/HcHead (hc_*) and
Compressor (ape); flavors set Qwen3.5's GDN gated norm and DeepSeek-V4's
attn_sink. Removes Decoder._fsdp_param_dtype_override_fn.

Stacked on #5659 and the PrecisionConfig PR.
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.
felipemello1 pushed a commit that referenced this pull request Nov 5, 2026
…/5-rdma-reads-on-arrival

Conflicts:
- rl/trainer/trainer.py forward_backward: this PR's structure (prefetchers made on arrival, the
  lock, the GPU wait off the event loop); each engine call's FLOPs add to the step's total.
- push_model_state_dict docstring: main's push stream and direct TorchStore put (#5659), plus this
  PR's note that the push can start while forward_backward waits for the GPU.
- RL test_trainer.py: main's push test needs ANY again; FLOPs plumbing in the queued-call test.
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.

[RL] Trainer keeps duplicate CPU weight copy (staging buffers + StorageVolume) on every push

4 participants