Skip to content

[rl][models] GDN: one input projection grouped by key head, shared by trainer and generator (5/7) - #5689

Merged
felipemello1 merged 13 commits into
mainfrom
felipemello1/gdn-stack/5-fused-input-proj
Nov 2, 2026
Merged

felipemello1 merged 13 commits into
mainfrom
felipemello1/gdn-stack/5-fused-input-proj

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: GDN's six input projections become one in_proj parameter, in the trainer and the generator. Its rows are grouped by key head, so a TP shard holds whole heads, as QKVLinear does for GQA. Qwen3.5-27B generator at TP4: decode -14% at 64 requests, mixed -2 to -3%. Trainer: same loss and grads within rounding for every GDN head layout in the repo.

base:     x -> in_proj_q, _k, _v, _z, _a, _b    6 GEMMs -> conv -> recurrence   (the generator first cats q, k, v)
this PR:  x -> in_proj                          1 GEMM  -> split region -> conv -> recurrence

in_proj rows, per key head g (27B: 16 key heads x 1030 rows = 16480):
  [ q_g 128 | k_g 128 | v_g 384 | z_g 384 | a_g 3 | b_g 3 ]
TP4 Shard(0): rank r holds key heads 4r..4r+3, with all six projections
# base: GDN.forward
query_TC = self.in_proj_q(x_TD)  # ... and five more GEMMs
# this PR
mixed_qkv_TC, a_TH, b_TH, gate_THV = _split_in_proj(
    self.in_proj(x_TD), self.in_proj_split_sizes, self.value_head_dim
)

Problem

  1. Six GEMMs. GDN projects x six times (in_proj_q, _k, _v, _z, _a, _b). The generator then concatenates q, k and v for its paged convolution.
  2. Narrow ones. a and b have 48 rows each at 27B, and cuBLAS splits the narrow GEMMs over K: 4 extra reduce kernels per layer, every step.
  3. Cost. Qwen3.5-27B generator at TP4, decode with 64 requests: 9.0 ms per step, 48 GDN layers.
  4. Why not concatenate. A plain [q | k | v | z | a | b] weight can't be TP-sharded: a Shard(0) would split blocks of different sizes across ranks.

Solution

  1. One parameter. GDN.in_proj replaces the six, with rows grouped by key head (layout above), so Shard(0) keeps whole heads.
  2. One split. A compiled region, gdn_split_in_proj, splits the output and copies q, k and v into one contiguous tensor for the convolution. The inner ops (InnerGDN, both CP variants, VLLMInnerGDN) take that tensor.
  3. Checkpoints. The state dict adapter packs HF's four tensors (in_proj_qkv, _z, _a, _b) into in_proj and back, next to its QKV packing.
  4. Unchanged: HF checkpoints, weight sync (the generator receives in_proj like any linear), the convolution weights, the other attention layers.

Results

Numerics: forward bitwise, grads not bitwise. The backward of one in_proj GEMM rounds differently from six GEMMs'.
          The grad gap is the same order as a loss num_chunks change makes (yardstick below).
          Trainer-vs-generator parity in batch-invariant mode: bitwise.

Trainer fwd+bwd vs base, one step. 4-layer Qwen3.5 debug model (3 GDN + 1 attention, 2 key heads), GSM8K SFT,
2048 tokens, bf16, seed 42, deterministic, GB300. The base exports its weights to HF; this PR loads them.
Grads compared in HF names over the 56 text parameters. r = value heads per key head.
r   models               setup   step-1 loss        grad rel L2   worst parameter   HF export, base vs this PR
1   0.8B, 2B             1 GPU   bitwise equal      2.3e-4        4.2e-3            bitwise
2   4B, 9B, 35B-A3B      1 GPU   bitwise equal      2.5e-4        6.8e-3            bitwise
3   27B                  1 GPU   bitwise equal      3.4e-4        6.0e-3            bitwise
4   122B, 397B           1 GPU   bitwise equal      3.4e-4        5.3e-3            bitwise
8   Qwen3.8 2.4T-A95B    1 GPU   bitwise equal      4.6e-4        4.5e-3            bitwise
3                        TP2     bitwise equal      3.4e-4        7.4e-3
3                        CP2     bitwise equal      3.1e-4        6.8e-3
1                        TP2     bitwise equal      2.4e-4        1.7e-2
1                        CP2     bitwise equal      2.0e-4        1.5e-2
yardstick: base, loss num_chunks 8 -> 4 (r=3, 1 GPU)
                                 13.022350 vs 13.022349   1.4e-4   3.4e-3
yardstick: base, TP2 vs 1 GPU (r=3)                      9.7e-4   1.7e-2   (this PR: 9.9e-4, 2.0e-2)
The worst parameters are A_log / dt_bias, whose grads are tiny (|g| 1e-9 to 1e-5) sums of cancelling terms.
Bitwise grads (r=3, 1 GPU): every parameter above the topmost GDN in_proj (the attention layer, lm_head, the final norm, that GDN
layer's conv, A_log, dt_bias, norm, out_proj and MLP). The gap starts at in_proj's backward and flows down.

DCP checkpoint (FSDP2 x2, r=3): train 4 steps saving at step 2, then resume from step 2: steps 3-4 loss bitwise
equal to the uninterrupted run. Two identical runs are bitwise equal (4 steps), as in the base.
Weight sync: RL integration test (FSDP2 x TP2 trainer -> two TP2 generators, batch-invariant): logprob diff max 0
at all 3 steps.
Qwen3.5-27B generator, TP4, GB300, FULL CUDA graphs, 512-token random prompts, per GPU (rank 0).
Median of 60 decode / 20 mixed steps, ms; two runs each (run 1 / run 2), ABBA order; shared host, load 37-61.
                              base           this PR        delta
decode, 64 requests           9.03 / 9.00    7.76 / 7.76    -14%
mixed, 64 requests            35.45 / 35.26  34.32 / 34.50  -2.7%
mixed, 256 requests           37.01 / 36.87  36.13 / 36.14  -2.2%
decode, 256 requests          14.35 / 13.95  13.36 / 12.58  -8%    (noisy: the p10-p90 spread is 1-2 ms in every arm)
decode, 256 requests, GPU kernel time (nsys, 10 steps, without the all-reduce): 11.83 -> 10.13  -14%
weights 12.53 GiB, KV blocks 15927 -> 15931, weight-update peak +0.59 GiB: unchanged

|trainer - generator| logprob: TP4 generator samples 32 prompts x 256 tokens at T=1; TP1 trainer rescores them.
base     mean 6.51e-3   p99 5.51e-2   max 0.83   KL (k3) 1.4e-4   (measured on the stack before its last main sync)
this PR  mean 6.23e-3   p99 5.66e-2   max 0.26   KL (k3) 1.0e-4
Trainer: 200-step SFT run and layer timing
Qwen3.5-0.8B SFT (GSM8K chat, 16k tokens, 1x GB300), both arms from the same HF checkpoint, seed 42, deterministic, 200 steps:
step-1 loss                         1.09036 both
max / mean |this PR - base|         4.0e-3 / 9e-4     yardstick, base with loss num_chunks 8 -> 4: 5.5e-3 / 1.0e-3
mean loss, steps 151-200            0.2389 -> 0.2391
peak memory                         38.91 -> 38.59 GiB

Trainer GDN layer fwd+bwd, GPU kernel time, TP2, ms     base     this PR
Qwen3.5-27B      16k tokens                              5.58     5.43    -2.8%
                 32k tokens                              10.75    10.62   -1.2%
Qwen3.5-35B-A3B  16k                                     2.55     2.58    +1.3%
                 32k                                     4.42     4.50    +1.6%
peak memory above the inputs, GiB: 27B 1.34 -> 1.34 (16k), 2.79 -> 2.79 (32k); 35B-A3B 0.81 -> 0.81, 1.61 -> 1.61

You may ask:

  • Why not fuse only in the generator? Decode is a bit faster that way (-18% vs -14% at 64 requests: no q, k, v copy), but it needs a second copy of the weights, refreshed after every weight load, and an allocator override.
  • Why group by key head, not concatenate per rank as vLLM does? A per-rank layout makes the global row order depend on the TP degree, so checkpoints need a TP-aware split. Grouping by key head gives one layout that any TP degree shards with Shard(0); HF's Qwen3-Next stores its in_proj_qkvz the same way.
  • Why copy q, k and v instead of passing views? vLLM's paged convolution reads one contiguous [q | k | v] block. The copy is the split region's 4 Triton kernels: 4.7-6.6 us per layer at 1-256 tokens (27B TP4).
  • Why is the 35B-A3B trainer layer 1.3-1.6% slower? Likely the split's copies: at D 2048 the six GEMMs are already cheap (not profiled per kernel). 27B (D 5120) gains 1.2-2.8%.
  • Why still three conv weights? One [q | k | v] conv weight would need the same key-head grouping and adapter packing as in_proj. The generator concatenates the three per call: 1.3 us per layer, about 0.8% of a 27B TP4 decode-64 step (48 layers, 7.76 ms). The trainer convolves three column views and pays nothing. Not worth the extra layout.

NOTE: TorchTitan DCP checkpoints saved before this PR have six keys per GDN layer and don't load into in_proj. HF checkpoints load as before, so the way out is to save with checkpointer.last_save_in_hf=True on the old commit and load with checkpointer.initial_load_in_hf=True.
NOTE: a model built from scratch draws one random in_proj instead of six, so its seed-42 losses differ from the base. Models loaded from HF are not affected.
NOTE: Ulysses CP splits in_proj's output and re-concatenates q, k and v: one more copy on that path, not measured.
NOTE: MXFP8 in_proj at TP1 passes the % 32 row check, but its blocks span section boundaries (1030 rows per key head). No recipe quantizes GDN projections.

Test plan

pytest tests/unit_tests/cpu/models tests/unit_tests/cpu/config     # same failures as the base (CPU flex compile, LoRA, 671B topology)
pytest tests/rl/unit_tests/cpu                                    # same 2 env failures as the base
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 \
  tests/unit_tests/cpu/models/common/test_gdn.py tests/unit_tests/cpu/models/qwen3_5/test_qwen3_5_state_dict_adapter.py   # 35 passed
torchrun --nproc_per_node=2 -m pytest tests/rl/unit_tests/gpu/test_bitwise_parity.py::TestBitwiseParityQwen35DebugVarlen   # 4 passed
RL Integration Tests CI (rl_grpo_qwen3_5_debug_tp2_batch_invariant): logprob diff max 0
Trainer parity vs base (table above): a script trains one step on each tree and dumps the loss and grads in HF names
before the optimizer step; the base tree exports HF at that point and this PR loads it. Debug model with
n_value_heads = r x n_key_heads, r in 1, 2, 3, 4, 8; TP2 and CP2 at r = 1 and 3; DCP resume with FSDP2 x2.

5/7 of the GDN generator stack, on top of the decode-routing PR (4/7).

@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 added this pull request to stack #5672 October 29, 2026 08:46
@felipemello1 felipemello1 changed the title [rl] generator: run the six GDN input projections as one GEMM (5/5) [rl] generator: run the six GDN input projections as one GEMM (5/6) Oct 29, 2026
@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 4m 43s —— View job


Verdict: looks good, with minor changes. I found no correctness bugs. Four inline comments: the allocator cap lift needs a try/finally and either a check on a non-GDN model or a gate on GDN layers; the GDN config-swap path lost its CPU test; and two nits.

Review details

What I checked and found sound

  • Refreshing in place keeps CUDA-graph addresses stable. The first refresh_fused_weights call allocates the fused tensors, and later calls copy_ into them. The new CPU test checks that the data_ptrs stay the same and that the six projection storages are freed, for both a group per layer and one group holding both layers.
  • The free and re-allocate cycle. free_storage(projection.weight) frees the unsharded storage, and the next FSDP unshard re-allocates it before copying out. The skip in the init loop (in_proj_q storage size 0 means "already refreshed") is right, because the second unshard() on a group that is already unsharded does nothing.
  • Split sizes and the docstring example add up (q+k+v = 10240, plus z 6144 and a/b 48 each, gives 16480 for 27B at TP1). Fused rows follow each rank's local shard order, which matches local_key_dim and local_num_v_heads.
  • Weight-sync path. load_prefetched_model_state_dict goes through VLLMModelWrapper.load_state_dict, so every load reaches the post-hook that refreshes. Nothing else in torchtitan/rl/generator reads the projection weights between loads (load_weights only lists their names).
  • Scope. No core files change. VLLMGDN and its sharding config stay in rl/generator, and there are no other GDN.Config subclasses for the fields-copy swap to break.

Inline comments

  1. model_wrapper.py:453: wrap the cap lift in try/finally. It also applies to every generator model while only Qwen3.5 was measured, so either run one non-GDN model before vs. after or lift the cap only when the model has VLLMGDN layers.
  2. test_vllm_wrapper.py:106: dropping gdn leaves _replace_vllm_layer_configs's GDN branch and the VLLMGDN.__init__ ValueError without a CPU test. A small test for the config swap would cover both.
  3. nit, model_wrapper.py:318: check isinstance(layer, VLLMGDN) rather than GDN, since only VLLMGDN has refresh_fused_weights.
  4. nit, gdn.py:457: add a comment that the S(0) label on the fused weights is nominal (they are rank-local concatenations) and they must never be redistributed.

Not verified here

I couldn't import torch in this sandbox. So I didn't run the tests or confirm that torch._C._accelerator_get/setAllocatorSettings round-trips the 20 MiB cap that vLLM sets; I relied on the measurements in the PR body for that.

Comment thread torchtitan/rl/generator/vllm/gdn.py Resolved
@felipemello1
felipemello1 force-pushed the felipemello1/gdn-stack/5-fused-input-proj branch from b4ffc72 to 75bcb61 Compare October 29, 2026 10:36
@felipemello1

felipemello1 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Reply from claude: Addressed the review at d78b6fd. The cap lift now runs only for GDN models: on Qwen3-0.6B it helped with expandable segments but cost 114 KV blocks on the default allocator. Added the S(0) comment.
Declined, with reasons inline: the try/finally (vLLM's own finally restores the cap), isinstance(VLLMGDN), and the config-swap test.
Local: parity 4 passed, GDN GPU 16 passed, RL CPU suite unchanged (499-500 passed; dapo_math env failures plus one flaky engine-loop test that passes 3/3 alone).

@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 2m 9s —— View job


Verdict: LGTM. The two follow-up commits fix what they set out to fix, I agree with your reasons for declining the other three comments, and I found nothing new to flag.

Review details (d78b6fd)

Follow-ups from the first review

  • Cap lift now only runs for GDN models (model_wrapper.py:453-465). has_gdn matches the swapped VLLMGDN layers, because it subclasses GDN. Non-GDN models no longer touch the allocator settings, so the Qwen3-0.6B default-allocator loss (-114 blocks) can't happen. Skipping try/finally is fine given that vLLM's own finally restores the cap and init fails if the loop raises.
  • The comment about S(0) being nominal is now on the fused weights' sharding entries (gdn.py:459-460).
  • Keeping isinstance(layer, GDN) holds up. _replace_vllm_layer_configs turns every GDN.Config into VLLMGDN.Config, and importing VLLMGDN at module level would break the deferral explained at model_wrapper.py:58-61.
  • Dropping the config-swap test holds up. test_vllm_replacement_preserves_full_attention_selection[qwen3_5] still runs the GDN branch on CPU. The fields copy loops over dataclasses.fields, and VLLMGDN.Config adds no fields, so nothing can be dropped silently.

Re-checked and sound

  • Parameters are rank-local plain tensors under spmd_types (local_spmd=True, no DTensor TP). So torch.cat over the projection weights in refresh_fused_weights just concatenates each rank's local rows, with no hidden redistribute. The Qwen3.5 input projections are built as plain Linear, so the type(projection) is not Linear check doesn't trip on them.
  • Skip check in the load path. FSDP's load pre-hook moves each group back to sharded, so the post-hook's unshard() always gathers again. in_proj_q therefore always has storage at that point, and the "already refreshed" skip only matters for repeated calls in the init loop. No stale fused weights can slip through.
  • No reader of the freed projections. Nothing in torchtitan/rl/ reads in_proj_*.weight between loads. named_parameters at model_wrapper.py:769 only uses the names, and the qwen3_5 TP divisibility check reads the config, not the weights.
  • gate_TC.unflatten instead of local_head_split is fine because the generator never runs context parallel. The output sharding declares the head placement for both outputs.

Optional, not blocking

  • conv_q/k/v.weight stay allocated next to conv_weight_CW, so the conv weights are held twice. That's a few tens of KiB per layer, so it isn't worth the extra free/re-allocate.

Not verified here

I couldn't run torch, the tests, or pre-commit in this sandbox. The numerics and memory conclusions above come from reading the code plus the measurements in the PR body.

@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:28
@felipemello1
felipemello1 force-pushed the felipemello1/gdn-stack/5-fused-input-proj branch from d78b6fd to 7b80af3 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 52s —— View job


Approve -- please add the one TODO before merging. 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 item below before merging. The re-pushed stack (HEAD 7b80af3) has the same content I reviewed at d78b6fd, and the earlier follow-ups still hold. The one thing left is a missing TODO on a private-API workaround.

What this PR does. In the vLLM generator, VLLMGDN keeps a rank-local fused copy of the six GDN input-projection weights [q|k|v|z|a|b] and of the three conv weights. Each step then runs one GEMM and splits the result into column views, where it used to run six GEMMs and a cat. After each FSDP group unshards, its fused weights are refreshed in place, so CUDA-graph addresses stay stable, and the six projection storages are freed. The init loop also lifts vLLM's 20 MiB split cap, in GDN models only.

Example.

base:    x -> in_proj_q, _k, _v, _z, _a, _b (6 GEMMs) -> cat(q,k,v) -> conv -> recurrence
this PR: x -> F.linear(x, input_weight_CD).split([qkv, z, a, b]) -> conv reads qkv in place -> recurrence
load N:  FSDP unshard group -> refresh_fused_weights(): copy_ into fused weights -> free in_proj_* storage

Must fix

  1. torchtitan/rl/generator/vllm/model_wrapper.py:490 -- the cap lift calls private torch._C._accelerator_*AllocatorSettings to work around vLLM's load-time cap, but there's no TODO with an upstream link (CLAUDE.md principle 3). A one-line comment fixes it (see the inline comment).
Details
  • Earlier findings, re-checked at HEAD. The cap lift is gated on has_gdn (model_wrapper.py:489-501). The S(0) comment is at gdn.py:460-461. The three items you declined (try/finally, isinstance(VLLMGDN), config-swap test) I still consider settled, for the reasons given in the earlier replies.
  • Forward equivalence. VLLMGDN.forward (gdn.py:544-555) does everything GDN.forward (common/attention/gdn.py:518-559) does, apart from remat regions. The generator doesn't use those, and gate_TC.unflatten stands in for local_head_split with no CP in the generator.
  • Compile/graph safety. input_weight_CD/conv_weight_CW are plain tensor attributes. They are assigned once, during the init unshard loop, which runs before vLLM compiles and captures. After that they are only updated in place with copy_, so Dynamo guards and captured addresses stay valid.

Not verified: GPU-side numerics and memory. I relied on the measurements in the PR body.

Comment thread torchtitan/rl/generator/vllm/gdn.py Resolved
@claude

claude Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

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


Request changes: I found no correctness bug in the in_proj redesign, but it now changes the trainer's computation and has no trainer loss or memory comparison yet, and the human-written summary is empty. 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: Request changes -- the redesign resolves @tianyu-l's comment and I found no correctness bug, but it now changes the trainer's main-path computation in shared code, and the PR has no trainer loss or memory comparison yet.

What this PR does. GDN's six input projections become one in_proj parameter. Its rows are grouped per key head as [q|k|v|z|a|b], so a TP Shard(0) holds whole heads, as QKVLinear does. A compiled gdn_split_in_proj region splits the GEMM output and copies q/k/v into one contiguous block. InnerGDN, both CP variants and VLLMInnerGDN now take that block. The base state dict adapter packs and unpacks the logical projections through Shard(1), and the generator's fused copy, refresh hook and allocator override are gone.

Example.

27B, TP4, rank r holds key heads 4r..4r+3:
base:    x -> in_proj_q/_k/_v/_z/_a/_b (6 GEMMs) -> [generator: cat(q,k,v)] -> conv -> recurrence
this PR: x -> in_proj [T, 4*1030] -> split: mixed_qkv [T, 2560], a/b [T, 12], gate [T, 12, 128] -> conv -> recurrence
HF load: in_proj_qkv/_z/_a/_b -> (qwen3_5) in_proj_q.._b -> (base) regroup per key head -> in_proj

Must fix

  1. The PR description has no human-written summary. That section is empty. The author has to write it (see CONTRIBUTING.md, "AI-assisted contributions").

  2. The trainer has no numerics or memory evidence. This now changes the training path for every Qwen3.5/3.6/3.8 run, not just the generator. Two things move numerics:

    • Init: one _LINEAR_INIT draw over 16480 rows replaces six separate draws, so seed-42 losses differ from base.
    • Reduction order: the GEMM output can differ from the six separate GEMMs (the body itself says cuBLAS split-K's the narrow a/b GEMMs).

    The bitwise GPU test runs at toy shapes, so it doesn't cover this. CLAUDE.md asks for a loss comparison on computation changes. Initializing both arms from the same HF checkpoint (for example Qwen3.5-0.8B on C4 for a few hundred steps) removes the init confound. Please also add trainer peak memory at 27B. The split briefly holds projected_TC and its copies together, and the trainer table only reports kernel time.

Should consider

  • gdn.py:559 -- move the head-divisibility check into GDN.Config.__post_init__, and check in_proj.out_features there too (inline).
  • gdn.py:207 -- _split_in_proj's local_map declares no in_types. Pass scalar ints so they can be declared, or add a TODO saying why they can't (inline).
  • tests/unit_tests/cpu/models/qwen3_6/test_qwen3_6.py:83 -- these two tests test models/common/attention/gdn.py and Qwen35StateDictAdapter. .claude/rules/tests.md places tests mirroring the source tree, so move them to tests/unit_tests/cpu/models/common/ and .../qwen3_5/. Both guard real invariants (the strided-head bug fixed in 5647926, and the adapter layout), so keep them.

Questions

  • The 35B-A3B trainer GDN layer gets 1.3-1.6% slower. Is that the four copy kernels outweighing a smaller GEMM (dim 2048)? A short note in the body would tell a maintainer whether that's expected.
Details
  • Earlier findings at HEAD. @tianyu-l's change request is addressed by the redesign. The earlier automated must-fix (a TODO on the private allocator API) and the review-1 items no longer apply, because VLLMGDN, the refresh hook and the allocator override are deleted.
  • TP and FSDP. qwen3_5/model.py:395 already requires tp | n_key_heads, so Shard(0) of in_proj gives each rank whole 1030-row groups. The local split sizes and conv_* shapes match. FSDP dim-0 shards can cut through a group, which is why the adapter goes through Shard(1).
  • Adapter. In _split_gdn_in_proj and _merge_gdn_in_proj, the reshapes only split or merge dims that aren't sharded, so DTensor Shard(1) -> Shard(2) -> Shard(1) propagates cleanly. The order is right: the qwen3_5 from_hf produces logical in_proj_q/k/v/z/a/b, then the base packs them (qwen3_5/state_dict_adapter.py:371). to_hf does the reverse at line 136. One difference from _merge_qkv_linear (which asserts): if the placement wasn't recorded, the result silently stays Shard(1). That's harmless on the HF-load path, which always calls to_hf first.
  • Callsites. Every in_proj_q/_v.out_features reader moved to n_key_heads/n_heads: validation, flops, the TP check, the vLLM registry and wrapper, and the adapter. There are no other GDN.Config builders, no FQN-based LoRA, quantization or remat targets on in_proj_*, and no golden loss files to regenerate.
  • Generator. VLLMInnerGDN gets a contiguous mixed_qkv_TC (the output of cat), which is what the paged conv needs. Weight sync uses native names, so in_proj.weight flows like any linear.
  • Saved activations match base: mixed_qkv_TC stands in for q/k/v, and gate_THV for gate_TC. Only the transient peak can grow, hence must-fix 2.

Not verified: DTensor Shard(1) round-trip on a real multi-axis mesh (only the plain-tensor CPU test runs), trainer memory, GPU numerics. A maintainer still needs to review, since this touches models/base and models/common.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please re-review (head 0ac3fff).

Must fix:

  1. Human-written summary: that section is for the author; I don't fill it.
  2. Trainer evidence, now in the body:
Qwen3.5-0.8B SFT, both arms from the same HF checkpoint, seed 42, deterministic, 200 steps
step-1 loss                    1.09036 both
max / mean |this PR - base|    4.0e-3 / 9e-4    (base with loss num_chunks 8 -> 4: 5.5e-3 / 1.0e-3)
peak memory                    38.91 -> 38.59 GiB
GDN layer fwd+bwd peak, TP2    27B 1.34 -> 1.34 GiB (16k), 2.79 -> 2.79 (32k); 35B-A3B unchanged too

The body also has a NOTE that from-scratch init now draws one in_proj tensor instead of six.

Should consider: all three are done in 0ac3fff. The checks moved to __post_init__, in_types is declared, and the tests now live in tests/unit_tests/cpu/models/common/test_gdn.py and .../qwen3_5/test_qwen3_5_state_dict_adapter.py.

Question (35B-A3B layer +1.3-1.6%): likely the split's copies. At D 2048 the six GEMMs are already cheap, so one GEMM saves less than the copies cost. I haven't profiled it per kernel. There is a line in "You may ask".

@claude

claude Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- @felipemello1 still needs to write the human-written summary before merging. 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 item below before merging. At 0ac3fff the trainer evidence is in the body, all three should-consider items are fixed, and the new commit introduces no problems.

What this PR does. GDN's six input projections become one in_proj parameter whose rows are grouped by key head, so a TP Shard(0) holds whole heads, the same way QKVLinear does. A compiled gdn_split_in_proj region splits the GEMM output into contiguous mixed_qkv, a, b and gate tensors. The state dict adapter packs HF's projections into in_proj and unpacks them back out.

Example.

27B, TP4, rank r holds key heads 4r..4r+3:
base:    x -> in_proj_q/_k/_v/_z/_a/_b (6 GEMMs) -> [generator: cat(q,k,v)] -> conv -> recurrence
this PR: x -> in_proj [T, 4*1030] -> split: mixed_qkv [T, 2560], a/b [T, 12], gate [T, 12, 128] -> conv -> recurrence

Must fix

  1. The "Summary (human-written)" section is still empty. The reply is right that an agent must not fill it in. @felipemello1 has to write it before merge (CONTRIBUTING.md, "AI-assisted contributions").
Earlier findings, checked at HEAD
  • Trainer numerics and memory: resolved. The SFT run starts both arms from the same HF checkpoint. Step-1 loss matches, and the gap (max 4.0e-3, mean 9e-4) is within the gap you get from changing num_chunks alone (5.5e-3 / 1.0e-3). Peak memory goes down, and the per-layer GDN peak is unchanged at 27B and 35B-A3B. The body has a NOTE that from-scratch init draws one tensor where it used to draw six.
  • Checks in GDN.Config.__post_init__: resolved (gdn.py:557-570). It follows KDA.Config. The duplicate assertion in test_build_model_config.py is gone, and every in-repo GDN.Config builder (qwen3_5/flavors.py:411, test_qwen3_5_deltanet.py:396) sets in_proj.out_features consistently.
  • in_types on _split_in_proj: resolved (gdn.py:208-209). The [None] * 6 leaf matches the list argument. Keeping a single in_proj_split_sizes source, which the adapter shares, is a reasonable reason not to switch to scalar ints.
  • Test placement: resolved. The split test is now at tests/unit_tests/cpu/models/common/test_gdn.py, and the adapter layout test is at tests/unit_tests/cpu/models/qwen3_5/test_qwen3_5_state_dict_adapter.py. Both moved verbatim. test_qwen3_6.py has no leftover imports.
  • 35B-A3B question: answered. It's in "You may ask" and marked as not profiled. That's enough for a maintainer to judge it.

A maintainer still needs to review, since this PR touches models/base and models/common.

Not verified: GPU numerics and memory. I relied on the measurements in the PR body.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: CI fix in the latest commit. On the A10G runner, test_extracted_forward_matches_main failed its torch.equal: one in_proj GEMM and six separate ones pick different kernels there, while they match bitwise on GB300. The test now uses torch.testing.assert_close at the fp32 defaults, and the comment says why. No model code changed.

@felipemello1 felipemello1 changed the title [rl][models] GDN: one input projection grouped by key head, shared by trainer and generator (5/6) [rl][models] GDN: one input projection grouped by key head, shared by trainer and generator (5/7) Nov 2, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @tianyu-l, ready for another look. Your question on the generator's fused weight ("why don't we do this for training?") turned into a redesign: GDN now has one in_proj parameter, in the trainer and the generator.

base:     x -> in_proj_q, _k, _v, _z, _a, _b   6 GEMMs                 (the generator also kept a fused copy)
this PR:  x -> in_proj                         1 GEMM -> split region -> conv -> recurrence

in_proj rows grouped by key head g, like QKVLinear's wqkv per KV head (27B: 16 key heads x 1030 rows):
  [ q_g 128 | k_g 128 | v_g 384 | z_g 384 | a_g 3 | b_g 3 ]
TP Shard(0) keeps whole key heads at any TP degree. HF checkpoints load through the adapter (packs the 4 HF tensors).
mixed_qkv_TC, a_TH, b_TH, gate_THV = _split_in_proj(
    self.in_proj(x_TD), self.in_proj_split_sizes, self.value_head_dim
)

Gone with it: the generator's second weight copy, its refresh after every weight load, and the allocator override.

Tests and numerics (full table in the description):

Trainer fwd+bwd vs base, one step, debug model with each head layout in the repo (r = value heads per key head):
r = 1, 2, 3, 4, 8 (0.8B ... Qwen3.8), 1 GPU   step-1 loss bitwise, grads rel L2 2.3e-4 .. 4.6e-4
TP2 and CP2 at r = 1 and 3                    step-1 loss bitwise, grads rel L2 2.0e-4 .. 3.4e-4
yardstick: base, loss num_chunks 8 -> 4       grads rel L2 1.4e-4   (the gap is bf16 rounding of one GEMM's backward vs six)
HF export -> this PR -> HF export             bitwise, all layouts
DCP save at step 2, resume (FSDP2 x2)         steps 3-4 bitwise equal to the uninterrupted run
weight sync (RL CI, batch-invariant)          FSDP2 x TP2 trainer -> two TP2 generators: logprob diff max 0
Qwen3.5-0.8B SFT, 200 steps                   max |loss diff| 4.0e-3 (yardstick 5.5e-3)

Perf: Qwen3.5-27B generator TP4 decode -14% (64 requests), mixed -2 to -3%.
      Trainer GDN layer: 27B -1.2 to -2.8%, 35B-A3B +1.3 to +1.6%.

BC: TorchTitan DCP checkpoints saved before this PR don't load (six keys become one); HF checkpoints load as before (NOTE in the description).

@felipemello1
felipemello1 requested a review from tianyu-l November 2, 2026 05:49
Base automatically changed from felipemello1/gdn-stack/4-decode-routing to main November 2, 2026 07:55
Felipe Mello added 13 commits November 2, 2026 02:55
VLLMGDN (the generator's GDN) keeps fused copies of the local [q|k|v|z|a|b]
projection and [q|k|v] conv weights, and VLLMInnerGDN runs one GEMM and reads
q|k|v as a column view of its output. Each FSDP group's unshard (initial load
and every load_state_dict) refreshes the fused copies of the GDN layers it
holds and frees their six projections' unsharded storages; the next unshard
re-allocates them. So the generator keeps one copy of the weights, and a load
holds one layer's projections twice at most. Parameters, state dict and the
trainer are unchanged.
…g at init

vLLM's load_model caps max_split_size at 20 MiB. A free block of 20 MiB or more then only serves
requests of about its size, so later GDN layers could not reuse the 80 MiB of projections each
layer frees, and with expandable segments ~20 MiB of each stayed mapped after empty_cache
(0.96 GiB at Qwen3.5-27B TP2, -58 KV blocks).
On Qwen3-0.6B (TP1) the lift adds 297 KV blocks with expandable segments but costs 114
(0.28 GiB more reserved after empty_cache) with the default allocator.
… trainer and generator

GDN's six input projections (in_proj_q/k/v/z/a/b) become one in_proj whose rows are grouped by
key head, [q | k | v | z | a | b] per key head, like QKVLinear's wqkv per KV group, so a TP shard
holds whole heads at any TP that divides the key heads. One GEMM in the trainer and the generator.

- GDN.Config: in_proj and n_key_heads replace the six projection configs.
- _split_in_proj (local_compile region gdn_split_in_proj, batch-invariant) copies q|k|v into one
  contiguous mixed_qkv_TC and returns a, b and the gate as [T, H, V].
- The inner ops (InnerGDN, UlyssesInnerGDN, ContextParallelInnerGDN, VLLMInnerGDN) take
  mixed_qkv_TC; VLLMInnerGDN reads it in place for the paged conv.
- The base HF adapter splits and packs in_proj as the six logical projections, so the
  Qwen3.5 HF mapping is unchanged. Native checkpoints with six keys no longer load.
- Removes the generator-only VLLMGDN, its fused-copy refresh, the FSDP storage freeing and the
  allocator-cap lift.
@felipemello1
felipemello1 force-pushed the felipemello1/gdn-stack/5-fused-input-proj branch from 8e2cddb to 5447dd0 Compare November 2, 2026 07:55
@felipemello1
felipemello1 merged commit b832ae4 into main Nov 2, 2026
tianyu-l added a commit that referenced this pull request Nov 3, 2026
…skill fixes (#5759)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

This PR adapts learnings from recent code review experience from me.

## Why
Three problems with the review automation on `main`:

1. **Area routing.** Several areas lack the right PoCs, `cuda_graph` is
named after files that were renamed to `accelerator_graph`, and the RL
vLLM attention code has no area of its own because it is spread across
`torchtitan/rl/generator/vllm/`.
2. **The bot approves one-sided designs.** On #5689 the bot approved a
generator-only fused GDN projection. That design needed `free_storage`
on FSDP-owned params, a refresh hook, a private
`torch._C._accelerator_setAllocatorSettings` call, and an ordering
invariant. A native fused parameter shared with the trainer would delete
all of that, and the bot only said so after being asked to review the
maintainer's review. The first two runs on #5689 didn't load the
`pr-review` skill at all.
3. **A stale REQUEST_CHANGES.** On #5313 the bot wrote "Approve" in a
"review my review" run but submitted `COMMENT`, as the skill instructed
for that mode. Its earlier `REQUEST_CHANGES` stayed and kept blocking
the PR.

**Example (area matching).** A PR touching
`rl/generator/vllm/attention/gdn.py`, `rl/generator/vllm/worker.py` and
`tests/rl/x.py`:

| | Areas matched | Requested |
| --- | --- | --- |
| Before (any prefix match) | `rl` (3) | `felipemello1, pzhan9, wwwjn`
(cap of 3 used up) |
| After (longest prefix) | `rl` (2), `rl_attention` (1) | `felipemello1,
pzhan9, wwwjn, liangel-02, drisspg`, minus the author and
already-requested code owners, capped at 3 |

## What changed
- **`.github/area_reviewers.yml`**
  - `attention` += `fegin`, `liangel-02`
  - `quantization` += `vkuzo`
  - `context_parallel` += `liangel-02`, `drisspg`
  - `cuda_graph` -> `accelerator_graph`, += `sanketpurandare`
- new `rl_attention` (`torchtitan/rl/generator/vllm/attention/`):
`liangel-02`, `drisspg`
- **`.github/workflows/area_reviewers.yml`:** each changed file counts
toward the area with its longest matching prefix, so a subarea wins over
its parent.
- **Mechanical, skim:** `attention.py`, `mla.py`, `gdn.py`, `kda.py`,
`linear_attention.py` move from `torchtitan/rl/generator/vllm/` to
`torchtitan/rl/generator/vllm/attention/` (mirrors
`models/common/attention/`). The only other changes are import updates
in `model_wrapper.py`, `registry.py`, `worker.py`, the moved files, and
the RL tests.
- **`.claude/skills/pr-review/`**
- New gate question 7, "one-sided design": an optimization added to only
one side (generator vs. trainer, inference vs. training, one model or
backend) must be compared against the shared version and what it would
delete. Workaround machinery counts as evidence for the shared version:
private APIs, storage tricks on FSDP-owned tensors, refresh hooks,
copies kept in sync, ordering invariants.
- If the shared version would delete that machinery, the finding is the
lead must-fix with Request changes or Needs discussion, never a TODO.
Same item added to `review-checklist.md`.
- The review event always matches the verdict line in every mode.
`COMMENT` is used only for answers with no verdict.
- The fallback body file is written in the working directory; writes to
`/tmp` are denied.
- **`.github/workflows/claude-code.yml`**
- Allow `mcp__github__create_and_submit_pull_request_review`; its
absence made the #5689 "review my review" run fail to post.
  - The prompt says invoking the `pr-review` skill is the first action.

## Numerics
No computation change. The RL change only moves files and updates
imports.

## Testing
- `pytest tests/rl/unit_tests/cpu/test_vllm_wrapper.py
tests/rl/unit_tests/cpu/test_vllm_registry.py`: 25 passed.
- All moved modules plus `model_wrapper`, `registry` and `worker`
import. The GDN GPU tests collect (23 tests) but were not run on GPU.
- I checked the area-matching logic with a local node script on the
example above.
- The skill and workflow changes take effect only after merge (the
workflows run from `main`).
tianyu-l added a commit that referenced this pull request Nov 26, 2026
…er override; agent self-review; rl/transport (#6407)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why

Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it
approved,
30 then got a formal "request changes" from a maintainer, and about 20
more got
substantive inline asks. In nearly all of them the bot either saw the
problem
and approved anyway, or never asked the questions maintainers ask most
("does
the repo already do this?", "who should own this?"). The opposite
failure, the
bot blocking something a maintainer was fine with, is rare: in the PRs
we
sampled, 2 of its 81 must-fix items were wrong and about a third were
minor
(the empty human-written summary was the biggest source).

**Example** (#6112, controller sizes the rollout worker pool):

```
before: bot approved 10 times; tianyu-l then blocked: "the controller reads
        rollouter.rollouts_per_worker to compute a count it hands back to the
        Rollouter -- violates encapsulation"
after:  same commit, new skill -> Request changes, must-fix #1:
        "controller.py:589 -- wrong owner for the worker count ..."
```

There was also no way for a code owner to overrule the bot except
dismissing
its review in the GitHub UI, and a later `@claude review again` would
block
again.

## What changed

**Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`):
- Verdict rules: Approve only when every remaining item is an edit the
bot
could write itself. Anything the author still owes (a design change, an
unexplained golden change, evidence the PR rests on) is Request changes;
anything only a maintainer can decide is Needs discussion. A hedge like
"a
  maintainer should decide" can't come with Approve.
- Always must-fix: a violated written rule, a silent wrong result, a
second
  definition of an existing concept, a gate finding.
- Design gate: new questions for the existing counterpart, in-repo
ownership,
and the design behind a bug; "ban only what doesn't work on main"; read
the
numbers behind a claim. The overlapping-PR search is mandatory and
reported.
- Re-review covers every commit since the last full review, including
code
taken from the bot's own suggestions. A scoped question gets a
`COMMENT`, not
  a whole-PR verdict.
- The bot fact-checks its own proposed fixes, and cites a source for
claims
  about external tools or marks them unverified (never must-fix).
- An empty "Summary (human-written)" is a one-line "Before merge" note
that
  never affects the verdict.
- Checklist: config ownership direction, general shared wrappers, dead
code the
PR creates, model variants as flavors, a mechanical pass over every new
or
  changed function.

**Code owner override** (`SKILL.md`, `claude-code.yml`,
`CONTRIBUTING.md`): a
code owner comments `@claude override` (optionally `@claude override
2,3:
<reason>`); the bot approves if nothing else is open and doesn't
re-raise the
overridden items. A code owner's GitHub approval or "LGTM" is not an
override,
so a teammate can approve without the bot dropping its findings.
Dismissing the
bot's review still unblocks the PR, but isn't an override: the bot can't
tell
who dismissed it.

**Agent self-review** (`CLAUDE.md`, `pr-description`): an agent
preparing a PR
runs `pr-review` in branch mode first and records unaddressed items in
an
optional "Self-review" section. PRs written without an agent are
unaffected; a
missing section is never a finding.

Where each new rule comes from (maintainer asks the bot missed):

| Change | PRs |
| --- | --- |
| No Approve with open design/evidence items or a "maintainer should
decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 |
| Author waiver can't clear a must-fix | #6201, #6202, #6203 |
| Existing counterpart; one source of truth | #5228, #6169, #5881,
#5823, #5824, #6059, #5812 |
| Responsibility owner; config ownership direction | #6112, #6332,
#5802, #5803, #6325 |
| Fix the design behind the bug; a TODO doesn't justify a workaround |
#5572, #5689, #5657 |
| Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819,
#5543 |
| Re-review covers all new commits; scoped asks don't approve | #5824,
#5842 |
| Mandatory overlap search | #5885, #6248 |
| Ban only what doesn't work on main | #5543 |
| Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868
|

**Rules**: `design.md` gets the one-general-wrapper rule (moved from
`models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the
consumer owning its values; `config.md` gets ownership direction and "a
Config
doesn't read runtime state"; `direction.md` calls all-to-all the MoE
reference
implementation, so a new vendor-specific dispatch path (e.g. #6242)
needs a
reason the existing backends can't serve.

**Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/`
-> d4l3k.

**Mechanical, skim**: `torchtitan/rl/transport/` holds data movement
between RL
actors.
- `rl/model_state_dict_transport.py` ->
`rl/transport/model_state_dict.py`
- `rl/MODEL_STATE_DICT_TRANSPORT.md` ->
`rl/transport/MODEL_STATE_DICT_TRANSPORT.md`
- `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py`
- tests:
`tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py`
->
`tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py`
- imports, READMEs and `scripts/install_rl_env.sh` updated; no code
changes.

## User-facing changes

| Before | After |
| --- | --- |
| Overrule the bot: dismiss its review in the UI, and it blocks again on
the next run | `@claude override [items]: <reason>`; the bot approves
and doesn't re-raise them |
| Empty human-written summary: bot must-fix | One "Before merge" line,
no effect on the verdict |
| `from torchtitan.rl.model_state_dict_transport import ...` | `from
torchtitan.rl.transport.model_state_dict import ...` |
| `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from
torchtitan.rl.transport.rdma_microbatch import ...` |

## Testing

Backtest: the new skill run locally (nothing posted) on each PR at the
commit
and thread state the bot originally saw.

| PR | Bot then | New skill | What the maintainer asked |
| --- | --- | --- | --- |
| #6112 | Approve | Request changes | worker-count ownership (caught) |
| #5837 | Approve | Request changes | apply to `dp_shard` too (caught) |
| #5572 | Approve | Request changes | delete the injection design
(caught) |
| #6201 | Approve after author waived pins | Request changes, waiver
ignored | pins broke GPU tests after merge (caught) |
| #6007 | Approve | Request changes | fold K3.1 into K3 (caught) |
| #5543 | Request changes: "ban it" | Request changes: keep main's path
| don't break gpt-oss + DeepEP (fixed) |
| #6144, #5905 (controls) | Approve | Approve | -- |
| #6137 (control) | Approve | Needs discussion | -- (merge gate on an
upstream API) |

Code owner override, simulated on #6201: override by a code owner lifts
the
named item; `@claude override` from the author changes nothing; a code
owner's
"LGTM" approval followed by "review again" keeps Request changes.

Transport move: 83 RL CPU unit tests pass locally
(`transport/test_model_state_dict.py`, `test_trainer.py`,
`test_engine_loop.py`). `transport/test_rdma_microbatch.py`,
`test_generator.py` and
`test_batcher_actor.py` fail to collect in my env on `origin/main` too
(stale
attention-gym / Monarch), so CI is the check for those.

## Known issues / follow-ups
- Open PRs that edit the moved files rebase cleanly (git follows the
renames),
but new imports of the old module paths will break: #6309 (adds a delta
transport that should live in `rl/transport/`), #6237, #6176, #6177,
#5862,
  and drafts #6127, #6393, #6163, #5764.
- The Actions bot can't read dependency source (e.g. SGLang); follow-up
for the
  workflow.

## Self-review
pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch
mode diffs
against `origin/main` and skips description findings before a
description
exists; the "Config doesn't read runtime state" rule no longer
contradicts
hardware validation; dismissal dropped as an override form (the bot
can't tell
who dismissed); `test_rdma_microbatch.py` added to the transport area.
Not
addressed:
- One concern per PR -- the five changes ship together at the
maintainer's
  request.
- Open PRs touching the moved files -- listed above; the maintainer will
  coordinate.
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