Repository navigation
[rl][models] GDN: compile the in_proj split per grad mode (7/7) - #5731
Conversation
|
Reply from claude: 7/7 of the GDN stack, on #5691: @claude please review. |
|
Claude finished @felipemello1's task in 2m 7s —— View job Approve -- please address the items before merging (human-written summary is empty; minor test hardening). See the review. A maintainer still needs to review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The design is a small, local Inductor tuning of one data-movement region, and the measurements back it up. The one thing that blocks merging is the empty human-written summary. A maintainer still needs to review, since this touches models/common/.
What this PR does. The gdn_split_in_proj region was one local_compile with default options. It becomes two thin wrappers under the same region name, and _split_in_proj (still the local_map boundary) chooses between them with projected_TC.requires_grad. The training copy turns off Inductor's pointwise-cat fusion and turns on combo_kernels, so the backward's six-gradient cat becomes per-slice copies instead of one masked kernel. The no-grad copy turns on combo_kernels only, so the generator's four outputs come from one launch. The split body is renamed to _split_grouped_in_proj without other changes.
Example.
trainer, in_proj requires grad: projected_TC.requires_grad=True -> _split_in_proj_with_grad
bwd before: 1 masked kernel choosing among the dq|dk|dv|dz|da|db sources per element
bwd after: triton_for_* kernels, one copy per gradient slice
remat recompute (runs with grad) -> same with_grad compile, no extra graphs
generator / no_grad / frozen in_proj: requires_grad=False -> _split_in_proj_no_grad
before: 4 kernels (q|k|v cat, a, b, gate) after: 1 combo kernel
I picked requires_grad as the predicate over torch.is_grad_enabled() on purpose. With grad enabled but a frozen in_proj and an input that doesn't require grad, no backward runs through the split, so the no-grad options are the right choice there.
Must fix
- PR description -- the "Summary (human-written)" section is empty. Per
CONTRIBUTING.md, the author has to fill it in before merge.
Should consider
tests/unit_tests/gpu/models/common/test_gdn.py:58-- if nothing compiles in a call (a cache hit),codesis empty and both kernel-structure assertions pass while checking nothing. Assert on the number of returned codes (inline comment).tests/unit_tests/gpu/models/common/test_gdn.py:12--importorskip("attn_gym")guards a package thatrequirements.txtalready pins. Delete it (inline comment).tests/unit_tests/gpu/models/common/test_gdn.py:76-- thetriton_for_prefix and theasync_compile.tritonline format are Inductor codegen details. A PyTorch bump that renames them would fail this test with no real regression behind it. That cost is probably acceptable, because the test is the only thing guarding the kernel structure the perf win depends on. If it does break, fix the pattern; don't drop the test.
Details
- Gate. The problem is real and measured: 571 us of a 6190 us 27B TP2 GDN layer, plus 4 decode launches. Inductor options are the right layer. The same cat limits are already used in
activation.py:37,rope.py:202anddeepseek_v3/attention.py:164, so this follows an existing pattern rather than working around an upstream bug. This is the first use ofcombo_kernelsin the repo, so I'd want a maintainer to take a look at that. The split is pure data movement, sobatch_invariant=Trueand the bitwise claim are both plausible. - Two wrappers vs one option dict. The description explains why: a separate graph cache and recompile limit per mode, and about 1.1% of a decode-64 step. Adding per-grad-mode options to
local_compilewould mean bending shared code for one consumer, so the ~20 lines of duplicated decorator are the better trade. - Parallelism. The
local_mapboundary and its in/out types are unchanged, and the branch runs on rank-local tensors.requires_gradis the same on every TP/CP rank, so ranks can't take different compiles. Under remat,remat.recompute_needs_tensor(projected_TC)(gdn.py:640) keeps the recompute on a grad-requiring input, which sends it to the training compile. - Callers.
gdn.py:642and the CPU testtests/unit_tests/cpu/models/common/test_gdn.py:24still call_split_in_proj. The CPU test exercises the eager path through the new dispatch.
Not verified: the timings, the bitwise parity and the kernel counts (needs a GPU run). Also not verified: whether run_and_get_code returns code on an Inductor FX-graph cache hit; I couldn't run Python in this environment.
|
Reply from claude: Addressed the review in 373ff98 (merged up as 63138b4 after 1/7 and 2/7 landed).
@claude please re-review. |
|
Claude finished @felipemello1's task in 1m 46s —— View job Approve -- please address the item before merging. Both test findings are fixed; the human-written summary, which only the PR author can write, is still empty. See the review. A maintainer still needs to review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. Both test findings from the last review are fixed at HEAD, and the new commit doesn't add any problems. The only open item is the human-written summary. A maintainer still needs to review, since this touches models/common/.
What changed since the last review (373ff98, merged up as 63138b4). The gdn.py code is unchanged. The test now captures the generated code without resetting Dynamo, and the kernel regex matches the def triton_...( form that the nightly emits.
Example.
before: run_and_get_code -> torch._dynamo.reset() before each call
T=37 -> compiles a fresh static graph (the comment said "dynamic")
after: _run_and_get_code_no_reset patches GraphLowering.save_output_code only
T=64 static -> T=37 sees the earlier compile -> symbolic graph -> T=1 specialized
no_grad: [1 kernel] exactly; training: exactly 2 codes (fwd, bwd), bwd all triton_for_*
Earlier items
- Resolved:
test_gdn.py:58, the empty-codespass. Inference now asserts== [1]and training assertslen(codes) == 2, so a Dynamo guard hit can't pass silently. - Resolved:
test_gdn.py:12, theimportorskip("attn_gym")call. It's removed. - Resolved: the codegen-pattern fragility point. The regex was fixed for the nightly format, not dropped.
Must fix
- PR description -- the "Summary (human-written)" section is still open. The reply is right that an agent shouldn't fill it in. It is the PR author's job (@felipemello1), and it still has to be written before merge (
CONTRIBUTING.md, "AI-assisted contributions").
Details
_run_and_get_code_no_resetpatchesGraphLowering.save_output_code, a private Inductor method. Upstreamrun_and_get_codepatches the same hook, so this adds no new private surface beyond what the test already relied on. It's test-only, so it needs no TODO.- The fixture now calls
torch._dynamo.reset()before setting up the region too. That keeps the two parametrized cases independent: the second case's T=64 compiles a static graph instead of picking up the first case's automatic-dynamic state. - Minor: with
len(codes) == 2asserted,for backward_code in codes[1:]always runs exactly once oncodes[1]. Indexing directly would be slightly clearer. Not blocking. - No changes to
gdn.pysince the last review. The earlier analysis still applies:requires_gradis the same on every TP/CP rank, remat recompute goes to the training compile, and thelocal_maptypes are unchanged.
Not verified: the GPU test results, and that the 37-token call now compiles a symbolic graph. Torch isn't installed in this environment.
0e986f4 to
1686eb5
Compare
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
## 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.
```python
# 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**
```text
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**
```text
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, f334fd9)
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.
---------
Co-authored-by: Felipe Mello <[email protected]>
gdn_split_in_proj gets two compiles under the same region name: with a backward (training), both cat limits at 0 so the backward copies each gradient into its slice, plus combo_kernels; without one (generator, no_grad), combo_kernels writes the four outputs in one kernel. The split is pure data movement, so outputs and gradients are unchanged.
…ead, training outputs
…orms, asserts what compiled, keeps one Dynamo state so 37 tokens compile the dynamic graph
1686eb5 to
ea0d887
Compare
Summary (human-written)
Agent details
TLDR:
gdn_split_in_projnow compiles twice under the same region name, with Inductor options picked by whether a backward runs. Training: the backward writes each gradient into its slice instead of one masked kernel, GDN layer fwd+bwd -3.7% (Qwen3.5-27B TP2, 16k and 32k tokens). Inference: the four output copies become one kernel, generator GDN layer -3.5 to -4.3 us at decode. Bitwise.Problem
_split_in_proj(5/7) copiesin_proj's output, grouped by key head, intomixed_qkv_TC,a_TH,b_THandgate_THV, inside thegdn_split_in_projregion.Solution
_split_in_proj_with_gradand_split_in_proj_no_gradwrap the unchanged body, renamed_split_grouped_in_proj(a mechanical rename). Two functions, so each gets its own graph cache and recompile limit.max_pointwise_cat_inputs=0andmax_complex_pointwise_cat_inputs=0make Inductor copy each piece into its slice (the knobsfused_binary_activationalready sets for its backward stack);combo_kernels=Truelaunches the remaining copies together.combo_kernels=Trueonly: per-input cat copies would add launches, which dominate at decode sizes._split_in_proj(still thelocal_mapboundary) calls the training compile whenprojected_TC.requires_grad. Remat's recompute runs with grad, so it reuses the training compile.Results
You may ask:
combo_kernelsalone (27B decode 64 split kernels: 3.84 vs 1.99 us, 1 process), ~0.09 ms (1.1%) of the 7.76 ms decode-64 step; at 35B prefill the two tie. The second compile buys that 1.1%.combo_kernelsalone? Training is unchanged with it (27B 16k 6164 vs 6166 us, 1 process): the backward cat stays one masked kernel.BACKEND_MATCH) on each set's first call. Two thin wrappers keep them apart, as theroperegion already does (rope.py:197,:390).NOTE: of the GPU tests below, only the new test and the regions-on engine run compile the split (the others clear the regions). Not run: an RL step end to end, the trainer at 64k tokens, TP > 1 timing (per-GPU shapes at TP1), CP. Cold compile time is not measured at model scale; the test compiles both copies in 7.0 s cold vs 4.6 s warm. At prefill 1 x 2048 the layer delta is about twice the split kernels' delta; the rest is unattributed. TP2 smokes (3 steps, regions on, and with spmd typechecking) exit 0. Who reaches it: every Qwen3.5 / 3.6 config that keeps the model's regions (alphabet_sort 9B varlen and 27B perf, terminal-bench 9B and 35B-A3B); batch-invariant recipes clear the regions.
Test plan
tests/unit_tests/gpu/models/common/test_gdn.py::test_split_in_proj_compiles_per_grad_mode(27B layout and one value head per key head; T = 64, 37, 1: the static, dynamic and specialized graphs): no_grad builds 1 Triton kernel; the training backward builds only per-slice copy (triton_for_*) kernels; outputs and the input grad equal the eager body. With combo removed from the no_grad copy it fails; an adapted copy also failed on 6/7 ([4] == [1]) and with the cat limits removed or the requires_grad pick inverted.test_gdn_cudagraph.py) withgdn_split_in_projon instead ofregions = []: 4 passed (FULL capture, eager vs FULL bitwise); RL CPU suite 504 passed, 2 failed (the known dapo_math env failures); core CPU tests next to the module: same 6 failures as the stack. pre-commit (pyrefly included) clean.Stack (land in order): 1/7 fused gate -> 2/7 metadata reuse -> 3/7 no output memset/copy -> 4/7 decode routing -> 5/7 fused input projections -> 6/7 float32 gate parameters -> 7/7 split compiled per grad mode.