Skip to content

Drop the GDN in_proj split copy and per-step casts in the Flash-Next vLLM generator - #6305

Draft
liangel-02 wants to merge 6 commits into
liangel-02/stack/31from
liangel-02/stack/30
Draft

liangel-02 wants to merge 6 commits into
liangel-02/stack/31from
liangel-02/stack/30

Conversation

@liangel-02

@liangel-02 liangel-02 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PRs:


Drop the GDN in_proj split copy and per-step casts in the Flash-Next vLLM generator

Summary (human-written)

Why

Flash-Next's GDN in_proj rows are grouped by key head:

projection [q0 k0 v0 | q1 k1 v1 | ...]
gates      [z0 a0 b0 | z1 a1 b1 | ...]

so every generator step copies q|k|v into the contiguous block the convolution
reads and a, b, z into their own tensors (SplitInProjGDN._split_in_proj: a
cat kernel plus inductor's triton_poi_fused_0). VLLMInnerGDN.forward also
concatenates the three conv weights and casts A_log and dt_bias to FP32 on
every call (Flash-Next keeps them in BF16). Per GDN layer that is 3.8 us + 4.1 us
at decode, 230 us at 8192 prefill tokens and 50 us in an 8x210-token + 64-decode
step. SGLang reorders its in_proj rows once at load and reads strided views, so
it pays none of this.

What changed

  • The vLLM generator swaps SplitInProjGDN for VLLMSplitInProjGDN (same
    config-type swap as the other generation layers) when in_proj's projection
    and gates are plain Linears. After every model state dict load it reorders
    its in_proj rows in place to

    projection [q of every key head | k ... | v ...]
    gates      [z ... | a ... | b ...]
    

    so _split_in_proj returns the projection GEMM output itself as the
    convolution input and z, a, b as strided views of the gates GEMM output, which
    the Attention Gym conv, decode and gate kernels and the gated norm read in
    place.

  • The same step caches the concatenated conv weight and FP32 copies of A_log
    and dt_bias in non-persistent buffers, allocated on the first load and
    updated in place afterwards.

  • ModelStateDictLoader hands each module that defines
    process_loaded_weights_ the parameters a load just filled (every parameter
    after the initial load, the trainable ones after a weight sync), inside
    inference mode like the unshard. Frozen weights are therefore reordered
    exactly once: later loads refill their shards from the already reordered
    unsharded storage. The hook's contract is in _process_loaded_weights's
    docstring.

  • All writes go into storage allocated before CUDA graph capture, so captured
    graphs keep reading the same addresses.

Why the trainer does not own this layout: the reordered layout depends on the
tensor-parallel degree. Each TP rank holds whole key heads and reorders only
its local ones, so the generator's row order differs between TP layouts and
cannot be the trainer's parameter or checkpoint layout. The trainer, its state
dict and the HF/checkpoint layout are unchanged; loads still deliver the
trainer's layout, and the generator reorders after every load.

LoRA and quantized in_proj configs keep the old path: they carry row-indexed
state (lora_b rows, scales) that the reorder does not touch.

Before After
Split copy + conv-weight cat + 2 FP32 casts every GDN step Reorder and caches once per weight load; split is free views
Loader has no post-load hook process_loaded_weights_ hook with the loaded parameter names

Numerics

Outputs and recurrent states are bitwise unchanged (per-layer microbenchmark,
all cases; the permuted-row GEMM is bitwise). Full Flash-Next model, seeded
generation: decode tokens and logprobs bitwise identical before and after on
88/88 requests.

Performance

Qwen3.8-Flash-Next, 48 layers (36 GDN), real weights, DP4/EP4 on 4 GB300, 64
sequences at ~2.1k context, FULL CUDA graphs:

Before After
Decode step 15.08 ms 14.66 ms (-0.42 ms)
Arrival steps (new prompts join) 34.5-36.0 ms 34.0-34.7 ms

Per GDN layer (chained-layer CUDA-graph microbenchmark, same per-GPU layout as
SGLang's DP-attention 4):

Step Before After SGLang
Decode, 16 sequences/GPU 60.9 us 53.7 us 54.2 us
Prefill, 1 x 8192 tokens 1165 us 944 us 1062 us
8x210 arriving + 64 decoding 392 us 339 us 388 us

Testing

pytest -q tests/rl/unit_tests/gpu/test_gdn_graph_metadata.py
pytest -q tests/rl/unit_tests/cpu/test_generator_model.py

The GPU test checks bitwise output, state equality and buffer freshness across
two different weight loads (and that the buffers keep their addresses); it
fails if the reorder is skipped on a weight sync or the caches are not
refreshed. The CPU test checks which parameter names the hook receives at init
and on later loads.

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

Flash-Next averages each completed block's raw indexer keys, then applies key
normalization and RoPE at the block's starting position. If prefill stops after
three tokens, the next decode token must complete that original block. Pooling
already-transformed keys produces a different model.

```text
prefill: raw keys k0 k1 k2 -> unfinished ring
next token: k3 -> mean(k0, k1, k2, k3) -> key norm -> RoPE(position=0)
             -> candidate cache -> paged_lightning_indexer -> QSA attention
```

- Preserve the training projection parameters and replace generation computation.
- Store one transformed candidate per four raw tokens in key-only compressed
  pages (`MLAAttentionSpec` with `tokens_per_state=4`), and retain only the
  unfinished raw block in a key-only per-request ring (`CircularBufferSpec`),
  honoring vLLM's allocated page stride when hybrid cache pages are enlarged.
- Pool raw keys and compute cache slots in TorchTitan from the new
  `QSAPagedMetadata.query_positions` (the compiled `vllm_query_positions` in
  `attention/query_positions.py`, cached per step), which maps each packed query
  row to its request and absolute position and also covers TorchTitan's
  sequence-parallel padding rows. Candidate and ring rows are written by
  indexed assignment into the stride-aware cache views.
- Call Attention Gym's read-only `paged_lightning_indexer`. In batch-invariant
  mode, sort valid block IDs to match the training attention order.
- The generator enables the shared inference `local_compile` regions from #6201
  that have registered functions (`inference_regions()`), adding the
  batch-variant one only outside batch-invariant mode. Users cannot opt out yet;
  a TODO records moving this to a generator `ModelConfigTransform`.
- `vllm_attention_backend` returns `None` for models with QSA layers
  (`uses_paged_qsa_cache`): their `PagedCache` pages select `QSAPagedBackend`,
  so vLLM's global attention backend is unused.
- `model_config_to_hf_config_dict` reports Flash-Next's hyper-connection norm
  epsilon as `rms_norm_eps`, since Flash-Next has no final `norm.eps`.

Retaining the full raw-key history consumes extra cache memory. Reconstructing
means from transformed keys is mathematically incorrect.

| Before | After |
| --- | --- |
| Indexer operates on complete training documents | Cached selection supports chunked prefill and decode |
| Generic attention replacement for QSA | Flash-Next projection and indexer adapters |

`pytest -q tests/rl/unit_tests/gpu/test_vllm_qsa.py`

The real Attention Gym indexer is exercised across append lengths `3, 1, 9, 6, 1`.
Stored pooled keys are checked exactly against raw-key means followed by the
training normalization/RoPE. Selected IDs are checked against an independent
reference, including causal exclusion and padded ring-page strides.

The complete stack also generated identical tokens with eager execution and
CUDA graphs while selecting only two blocks, splitting a 37-token prefill, and
allowing another request to finish early. PLE serving is supplied by the next
commit.

Validation used local B200 GPUs and an Attention Gym development build preserving
the original cuDNN linear kernels, with the paged sparse APIs added. The pinned
`attn-gym==0.0.20` alone does not supply these APIs. No GDN/KDA migration is included.

The complete stack passed `pre-commit run --all-files`. A deterministic seed-42
BF16 debug-model forward/backward (32 tokens) was compared against
`44ff1567196fe91ba8a8f96a1aeefbc6715dda8c`: loss `4.4367218017578125`, gradient
norm `22.315799713134766`, logits, and all 192 parameter gradients were bitwise
identical using `torch.equal`. This is one-GPU training evidence, not a
representative-data convergence run or a 125B performance measurement.

Additional cache-reuse validation: 38 focused tests pass, including native
metadata, padded cache strides, and extra sequence-parallel model rows.
Across three rounds of two requests, generated tokens and log probabilities
are exactly equal to published stack 02f9eb9 in BF16 Dist-MoE TP2/EP2 + SP,
both eager and FULL_DECODE_ONLY, on both ranks. Full pre-commit checks pass.

stack-info: PR: #6202, branch: qwen38-rl-2-indexer
…vLLM generator

## 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

Flash-Next's GDN in_proj rows are grouped by key head:

    projection [q0 k0 v0 | q1 k1 v1 | ...]
    gates      [z0 a0 b0 | z1 a1 b1 | ...]

so every generator step copies q|k|v into the contiguous block the convolution
reads and a, b, z into their own tensors (`SplitInProjGDN._split_in_proj`: a
cat kernel plus inductor's `triton_poi_fused_0`). `VLLMInnerGDN.forward` also
concatenates the three conv weights and casts `A_log` and `dt_bias` to FP32 on
every call (Flash-Next keeps them in BF16). Per GDN layer that is 3.8 us + 4.1 us
at decode, 230 us at 8192 prefill tokens and 50 us in an 8x210-token + 64-decode
step. SGLang reorders its in_proj rows once at load and reads strided views, so
it pays none of this.

## What changed

- The vLLM generator swaps `SplitInProjGDN` for `VLLMSplitInProjGDN` (same
  config-type swap as the other generation layers) when in_proj's `projection`
  and `gates` are plain Linears. After every model state dict load it reorders
  its in_proj rows in place to

      projection [q of every key head | k ... | v ...]
      gates      [z ... | a ... | b ...]

  so `_split_in_proj` returns the projection GEMM output itself as the
  convolution input and z, a, b as strided views of the gates GEMM output, which
  the Attention Gym conv, decode and gate kernels and the gated norm read in
  place.
- The same step caches the concatenated conv weight and FP32 copies of `A_log`
  and `dt_bias` in non-persistent buffers, allocated on the first load and
  updated in place afterwards.
- `ModelStateDictLoader` hands each module that defines
  `process_loaded_weights_` the parameters a load just filled (every parameter
  after the initial load, the trainable ones after a weight sync), inside
  inference mode like the unshard. Frozen weights are therefore reordered
  exactly once: later loads refill their shards from the already reordered
  unsharded storage. The hook's contract is in `_process_loaded_weights`'s
  docstring.
- All writes go into storage allocated before CUDA graph capture, so captured
  graphs keep reading the same addresses.

Why the trainer does not own this layout: the reordered layout depends on the
tensor-parallel degree. Each TP rank holds whole key heads and reorders only
its local ones, so the generator's row order differs between TP layouts and
cannot be the trainer's parameter or checkpoint layout. The trainer, its state
dict and the HF/checkpoint layout are unchanged; loads still deliver the
trainer's layout, and the generator reorders after every load.

LoRA and quantized in_proj configs keep the old path: they carry row-indexed
state (`lora_b` rows, scales) that the reorder does not touch.

| Before | After |
| --- | --- |
| Split copy + conv-weight cat + 2 FP32 casts every GDN step | Reorder and caches once per weight load; split is free views |
| Loader has no post-load hook | `process_loaded_weights_` hook with the loaded parameter names |

## Numerics

Outputs and recurrent states are bitwise unchanged (per-layer microbenchmark,
all cases; the permuted-row GEMM is bitwise). Full Flash-Next model, seeded
generation: decode tokens and logprobs bitwise identical before and after on
88/88 requests.

## Performance

Qwen3.8-Flash-Next, 48 layers (36 GDN), real weights, DP4/EP4 on 4 GB300, 64
sequences at ~2.1k context, FULL CUDA graphs:

| | Before | After |
| --- | --- | --- |
| Decode step | 15.08 ms | 14.66 ms (-0.42 ms) |
| Arrival steps (new prompts join) | 34.5-36.0 ms | 34.0-34.7 ms |

Per GDN layer (chained-layer CUDA-graph microbenchmark, same per-GPU layout as
SGLang's DP-attention 4):

| Step | Before | After | SGLang |
| --- | --- | --- | --- |
| Decode, 16 sequences/GPU | 60.9 us | 53.7 us | 54.2 us |
| Prefill, 1 x 8192 tokens | 1165 us | 944 us | 1062 us |
| 8x210 arriving + 64 decoding | 392 us | 339 us | 388 us |

## Testing

```bash
pytest -q tests/rl/unit_tests/gpu/test_gdn_graph_metadata.py
pytest -q tests/rl/unit_tests/cpu/test_generator_model.py
```

The GPU test checks bitwise output, state equality and buffer freshness across
two different weight loads (and that the buffers keep their addresses); it
fails if the reorder is skipped on a weight sync or the caches are not
refreshed. The CPU test checks which parameter names the hook receives at init
and on later loads.

stack-info: PR: #6305, branch: liangel-02/stack/30
@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 20, 2026
liangel-02 added a commit that referenced this pull request Nov 20, 2026
…vLLM generator

## 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

Flash-Next's GDN in_proj rows are grouped by key head:

    projection [q0 k0 v0 | q1 k1 v1 | ...]
    gates      [z0 a0 b0 | z1 a1 b1 | ...]

so every generator step copies q|k|v into the contiguous block the convolution
reads and a, b, z into their own tensors (`SplitInProjGDN._split_in_proj`: a
cat kernel plus inductor's `triton_poi_fused_0`). `VLLMInnerGDN.forward` also
concatenates the three conv weights and casts `A_log` and `dt_bias` to FP32 on
every call (Flash-Next keeps them in BF16). Per GDN layer that is 3.8 us + 4.1 us
at decode, 230 us at 8192 prefill tokens and 50 us in an 8x210-token + 64-decode
step. SGLang reorders its in_proj rows once at load and reads strided views, so
it pays none of this.

## What changed

- The vLLM generator swaps `SplitInProjGDN` for `VLLMSplitInProjGDN` (same
  config-type swap as the other generation layers) when in_proj's `projection`
  and `gates` are plain Linears. After every model state dict load it reorders
  its in_proj rows in place to

      projection [q of every key head | k ... | v ...]
      gates      [z ... | a ... | b ...]

  so `_split_in_proj` returns the projection GEMM output itself as the
  convolution input and z, a, b as strided views of the gates GEMM output, which
  the Attention Gym conv, decode and gate kernels and the gated norm read in
  place.
- The same step caches the concatenated conv weight and FP32 copies of `A_log`
  and `dt_bias` in non-persistent buffers, allocated on the first load and
  updated in place afterwards.
- `ModelStateDictLoader` hands each module that defines
  `process_loaded_weights_` the parameters a load just filled (every parameter
  after the initial load, the trainable ones after a weight sync), inside
  inference mode like the unshard. Frozen weights are therefore reordered
  exactly once: later loads refill their shards from the already reordered
  unsharded storage. The hook's contract is in `_process_loaded_weights`'s
  docstring.
- All writes go into storage allocated before CUDA graph capture, so captured
  graphs keep reading the same addresses.

Why the trainer does not own this layout: the reordered layout depends on the
tensor-parallel degree. Each TP rank holds whole key heads and reorders only
its local ones, so the generator's row order differs between TP layouts and
cannot be the trainer's parameter or checkpoint layout. The trainer, its state
dict and the HF/checkpoint layout are unchanged; loads still deliver the
trainer's layout, and the generator reorders after every load.

LoRA and quantized in_proj configs keep the old path: they carry row-indexed
state (`lora_b` rows, scales) that the reorder does not touch.

| Before | After |
| --- | --- |
| Split copy + conv-weight cat + 2 FP32 casts every GDN step | Reorder and caches once per weight load; split is free views |
| Loader has no post-load hook | `process_loaded_weights_` hook with the loaded parameter names |

## Numerics

Outputs and recurrent states are bitwise unchanged (per-layer microbenchmark,
all cases; the permuted-row GEMM is bitwise). Full Flash-Next model, seeded
generation: decode tokens and logprobs bitwise identical before and after on
88/88 requests.

## Performance

Qwen3.8-Flash-Next, 48 layers (36 GDN), real weights, DP4/EP4 on 4 GB300, 64
sequences at ~2.1k context, FULL CUDA graphs: decode step 15.08 -> 14.63 ms
(-0.45 ms). Per GDN layer at 8192 prefill tokens the 230 us split copy is gone.

## Testing

```bash
pytest -q tests/rl/unit_tests/gpu/test_gdn_graph_metadata.py
pytest -q tests/rl/unit_tests/cpu/test_generator_model.py
```

The GPU test checks bitwise output, state equality and buffer freshness across
two different weight loads (and that the buffers keep their addresses); it
fails if the reorder is skipped on a weight sync or the caches are not
refreshed. The CPU test checks which parameter names the hook receives at init
and on later loads.

stack-info: PR: #6305, branch: liangel-02/stack/30
@github-actions
github-actions Bot requested a review from pzhan9 November 20, 2026 22:51
@github-actions
github-actions Bot requested a review from drisspg November 20, 2026 22:51
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 20, 2026
@liangel-02
liangel-02 marked this pull request as draft November 20, 2026 22:56
@liangel-02
liangel-02 changed the base branch from qwen38-rl-4-recipe to qwen3-8-fn-6-pipeline November 20, 2026 22:56
liangel-02 added a commit that referenced this pull request Nov 20, 2026
…vLLM generator

## 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

Flash-Next's GDN in_proj rows are grouped by key head:

    projection [q0 k0 v0 | q1 k1 v1 | ...]
    gates      [z0 a0 b0 | z1 a1 b1 | ...]

so every generator step copies q|k|v into the contiguous block the convolution
reads and a, b, z into their own tensors (`SplitInProjGDN._split_in_proj`: a
cat kernel plus inductor's `triton_poi_fused_0`). `VLLMInnerGDN.forward` also
concatenates the three conv weights and casts `A_log` and `dt_bias` to FP32 on
every call (Flash-Next keeps them in BF16). Per GDN layer that is 3.8 us + 4.1 us
at decode, 230 us at 8192 prefill tokens and 50 us in an 8x210-token + 64-decode
step. SGLang reorders its in_proj rows once at load and reads strided views, so
it pays none of this.

## What changed

- The vLLM generator swaps `SplitInProjGDN` for `VLLMSplitInProjGDN` (same
  config-type swap as the other generation layers) when in_proj's `projection`
  and `gates` are plain Linears. After every model state dict load it reorders
  its in_proj rows in place to

      projection [q of every key head | k ... | v ...]
      gates      [z ... | a ... | b ...]

  so `_split_in_proj` returns the projection GEMM output itself as the
  convolution input and z, a, b as strided views of the gates GEMM output, which
  the Attention Gym conv, decode and gate kernels and the gated norm read in
  place.
- The same step caches the concatenated conv weight and FP32 copies of `A_log`
  and `dt_bias` in non-persistent buffers, allocated on the first load and
  updated in place afterwards.
- `ModelStateDictLoader` hands each module that defines
  `process_loaded_weights_` the parameters a load just filled (every parameter
  after the initial load, the trainable ones after a weight sync), inside
  inference mode like the unshard. Frozen weights are therefore reordered
  exactly once: later loads refill their shards from the already reordered
  unsharded storage. The hook's contract is in `_process_loaded_weights`'s
  docstring.
- All writes go into storage allocated before CUDA graph capture, so captured
  graphs keep reading the same addresses.

Why the trainer does not own this layout: the reordered layout depends on the
tensor-parallel degree. Each TP rank holds whole key heads and reorders only
its local ones, so the generator's row order differs between TP layouts and
cannot be the trainer's parameter or checkpoint layout. The trainer, its state
dict and the HF/checkpoint layout are unchanged; loads still deliver the
trainer's layout, and the generator reorders after every load.

LoRA and quantized in_proj configs keep the old path: they carry row-indexed
state (`lora_b` rows, scales) that the reorder does not touch.

| Before | After |
| --- | --- |
| Split copy + conv-weight cat + 2 FP32 casts every GDN step | Reorder and caches once per weight load; split is free views |
| Loader has no post-load hook | `process_loaded_weights_` hook with the loaded parameter names |

## Numerics

Outputs and recurrent states are bitwise unchanged (per-layer microbenchmark,
all cases; the permuted-row GEMM is bitwise). Full Flash-Next model, seeded
generation: decode tokens and logprobs bitwise identical before and after on
88/88 requests.

## Performance

Qwen3.8-Flash-Next, 48 layers (36 GDN), real weights, DP4/EP4 on 4 GB300, 64
sequences at ~2.1k context, FULL CUDA graphs:

| | Before | After |
| --- | --- | --- |
| Decode step | 15.08 ms | 14.66 ms (-0.42 ms) |
| Arrival steps (new prompts join) | 34.5-36.0 ms | 34.0-34.7 ms |

Per GDN layer (chained-layer CUDA-graph microbenchmark, same per-GPU layout as
SGLang's DP-attention 4):

| Step | Before | After | SGLang |
| --- | --- | --- | --- |
| Decode, 16 sequences/GPU | 60.9 us | 53.7 us | 54.2 us |
| Prefill, 1 x 8192 tokens | 1165 us | 944 us | 1062 us |
| 8x210 arriving + 64 decoding | 392 us | 339 us | 388 us |

## Testing

```bash
pytest -q tests/rl/unit_tests/gpu/test_gdn_graph_metadata.py
pytest -q tests/rl/unit_tests/cpu/test_generator_model.py
```

The GPU test checks bitwise output, state equality and buffer freshness across
two different weight loads (and that the buffers keep their addresses); it
fails if the reorder is skipped on a weight sync or the caches are not
refreshed. The CPU test checks which parameter names the hook receives at init
and on later loads.

stack-info: PR: #6305, branch: liangel-02/stack/30
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to qwen38-rl-4-recipe November 20, 2026 22:56
@liangel-02
liangel-02 marked this pull request as ready for review November 20, 2026 22:56
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
@liangel-02

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @liangel-02's task in 5m 6s —— View job


Approve -- please address the items before merging (empty human-written summary; add a docstring on VLLMSplitInProjGDN explaining the layout invariant): 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 design is sound: the TP-dependent row order rules out a trainer-owned layout, the reorder runs exactly once per filled parameter, and the caches stay at fixed addresses for CUDA graphs. What remains is documentation of the invariant the fast path depends on. This touches the shared RL generator loader, so a maintainer still needs to review.

What this PR does. In the vLLM generator, a Flash-Next GDN layer with plain-Linear in_proj becomes VLLMSplitInProjGDN. After every state-dict load, ModelStateDictLoader calls the layer's new process_loaded_weights_ hook with the parameter names the load filled. The hook reorders the projection/gates rows in place from key-head-major to section-major. It also refreshes three cached buffers: the concatenated conv weight and FP32 copies of A_log/dt_bias. After that, the per-step split is just views, with no per-step cat or casts.

Example. One TP rank holding 2 local key heads:

trainer/loaded layout   projection [q0 k0 v0 | q1 k1 v1]   gates [z0 a0 b0 | z1 a1 b1]
after hook (generator)  projection [q0 q1 | k0 k1 | v0 v1] gates [z0 z1 | a0 a1 | b0 b1]

before: mixed_qkv = cat(q, k, v) copy; a, b, z = .contiguous() copies; cat(conv_q,k,v); A_log.float()
after:  mixed_qkv = projection GEMM output; a, b, z = strided views; cached conv/A_log/dt_bias

load N+1 with LoRA base frozen: frozen rows are not passed to the hook. Their shards are
refilled from the already-reordered unsharded storage, so they are not reordered twice.

Must fix

  1. PR description: "Summary (human-written)" is empty. The author needs to fill it in.
  2. torchtitan/rl/generator/vllm/attention/gdn.py:425 -- VLLMSplitInProjGDN has no docstring. The layout invariant _split_in_proj relies on, and why it can't be the trainer's layout, need to be in code (inline).

Should consider

  • torchtitan/rl/generator/vllm/model_wrapper.py:194 -- add a comment explaining why LoRA/quantized in_proj keep the old path (inline).
  • torchtitan/rl/generator/vllm/attention/gdn.py:411 -- _run_inner_gdn restates the inner GDN sharding layouts by hand and drops VLLMInnerGDN.forward's shape asserts (inline).

Questions

  • The conv-weight cat in VLLMInnerGDN.forward (and the A_log/dt_bias casts when they are not FP32) also runs every step for Qwen3.5's GDN in the generator. Is extending the cached-buffer half of this change to plain GDN planned as a follow-up?
Details
  • Gate. The problem is measured (-0.42 ms of a 15.08 ms decode step, 4xGB300) and has a clear root cause (the interleaved row order forces a copy). On question 7, a trainer-native section-major layout would have to depend on the TP degree, which would break DCP resharding and the HF adapter. So a generator-side reorder is the right layer.
  • Loader hook. The duck-typed hook lives in ModelStateDictLoader, which is shared with SGLang. The loader is the only component that knows which parameters a load filled and how frozen shards get refilled (_restore_sharded_params). Moving the loop into the vLLM engine would duplicate that knowledge, so I'm not asking to move it.
  • TP/FSDP. Generator TP parameters are local tensors (spmd_distribute_tensor), not DTensors, so _group_rows_by_section_ permutes only local key heads, as intended. FSDP shards the TP-local tensor on dim 0. Frozen refills chunk the reordered unsharded weight, and the all-gather rebuilds it consistently.
  • Failed load. If fetch raises, load re-raises before the hook runs, so the model is left in a mixed layout. The next successful load refills every trainable parameter and reorders it, so recovery works.
  • Inference mode. The derived buffers are created inside inference_mode (inference tensors) and only read in vLLM's inference-mode forward, so that's fine.

Not verified: bitwise numerics and perf (needs GPUs); strided a/b/gate in the batch-invariant paged_gdn path (the new GPU test doesn't enable batch-invariant mode); behaviour with spmd_typechecking on, since the cached buffers are created outside a typed region.

)


class VLLMSplitInProjGDN(SplitInProjGDN):

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 class has no docstring, but its correctness depends on a hidden invariant: _split_in_proj returns projection_TC as mixed_qkv_TC, and takes z/a/b as section-major slices. That is only right after process_loaded_weights_ has reordered the rows in place. If a forward runs on the trainer layout (say a future load path skips the hook), the outputs are silently wrong instead of raising. Right now the reason the trainer can't own this layout (each TP rank reorders only its local key heads, so the row order depends on the TP layout) is written only in the PR description.

Fix: add a class docstring covering:

  • the before/after row diagram ([q0 k0 v0 | q1 k1 v1 | ...] -> [q of every local key head | k ... | v ...], same for z/a/b);
  • that the reorder and caches are redone after every load, via ModelStateDictLoader._process_loaded_weights;
  • that the layout depends on the TP degree, which is why the trainer and checkpoint layout stay unchanged.

delta_net_cfg, inner_attention=vllm_inner_gdn_cfg
)
in_proj_cfg = delta_net_cfg.in_proj
if (

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.

LoRA and quantized in_proj configs fall back to the slower path here without saying so. The reason (they carry row-indexed state that the reorder doesn't permute) is only in the PR description. A reader could take the type(...) is Linear.Config checks for arbitrary strictness and loosen them, which would silently break LoRA/fp8 outputs. Suggest a one-line comment, plus a TODO if extending the reorder to those configs is planned:

Suggested change
if (
# LoRA and quantized in_proj keep SplitInProjGDN: their row-indexed state
# (lora_b rows, per-row scales) is not permuted by VLLMSplitInProjGDN's reorder.
if (

),
out_types=spmd.PartitionSpec(("dp", "cp"), "tp", None),
)
def _run_inner_gdn(

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.

_run_inner_gdn skips self.inner_attention(...), so it has to restate the layouts of inner_gated_delta_net_sharding_config (qwen3_5/sharding.py:87) as hand-written PartitionSpecs. It also drops VLLMInnerGDN.forward's checks (key_head_dim == head_k_dim, value_head_dim == head_v_dim, conv_weight_CW.shape[-1] == conv_kernel_size). Now there are two sources of truth for the inner GDN's boundary, and if they diverge nothing catches it until a TP/CP run misbehaves. At minimum, keep the shape asserts here, and add a comment pointing at the sharding config these specs must match.

@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to qwen38-rl-4-recipe November 20, 2026 23:11
@liangel-02
liangel-02 marked this pull request as ready for review November 20, 2026 23:11
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

PLE needs the preceding token IDs for n-gram hashing and the preceding normed
activations for its dilated convolution. A decode call supplies only new tokens,
so running the training PLE path independently on each call loses that history.
Row-owned PLE parameters also sit outside FSDP load groups and need explicit
handling during policy updates.

For a request split into `3 + 14 + 10` tokens, cached PLE must match one full
27-token evaluation. Reordering requests or reusing a finished request's state
must not mix their histories.

- Add `VLLMPLELayer` (`torchtitan/rl/generator/vllm/model/ple.py`). Each request's
  history is the last `(kernel_size - 1) * dilation` normed rows (BF16) and the
  last `ngram_size - 1` token IDs (int64), indexed circularly. It lives in
  model-owned buffers that the worker allocates after vLLM binds the KV cache,
  indexed by the state slots of the same layer's GDN attention, so it follows
  that request's slot through reordering and slot reuse. Packed steps store
  only each request's final window.
- PLE registers no KV-cache spec of its own. vLLM's hybrid KV-cache manager
  gives every group the layer count of the smallest spec bucket, so a
  one-layer PLE state forced one layer per group for all of Flash-Next: 73
  KV-cache groups, each building attention metadata every step, instead of 6.
  A TODO marks this workaround until vLLM supports per-bucket group sizes. A
  PLE layer without GDN attention raises `ValueError`.
- The generator reuses the trainer's math. `NGramEmbedding.mix_hashes`,
  `NGramEmbedding.lookup`/`gather_features`, `PLELayer.gate_score`/`gate_apply`
  and `PLELayer.conv_shifts`/`conv_output` are split out of the training
  forward; trainer outputs and gradients are bitwise unchanged.
- Decode-sized steps (at most `max_num_seqs` tokens on every DP rank)
  all-gather hash IDs over the row mesh, look up locally owned rows (non-owned
  rows read as -0.0) and reduce-scatter, which is bitwise equal to a plain
  gather. Larger steps keep the row-sharded slot route, now sized by the step's
  DP-max token count instead of `max_num_batched_tokens`.
- `local_compile` regions: the trainer's PLE hashing, gate and convolution
  register as `ple_hash_ids`, `ple_gate` and `ple_conv`. They are not added to
  the Flash-Next defaults, so recipes keep running PLE eagerly; enabling them by
  default needs trainer loss, step-time and memory evidence and is left to a
  follow-up. The generator's gate (as two functions so its BF16 rounding
  matches the trainer's training-mode graph) and tiled convolution register
  under `ple_gate` and `ple_conv`, so they compile exactly when the trainer's
  do. History reads with hashing, the owned-row
  lookup and the per-token request indices (`vllm_query_requests` in
  `attention/query_positions.py`) register under the shared
  `inference_batch_invariant` region.
- `_replace_vllm_layer_configs` swaps `PLELayer.Config` for
  `VLLMPLELayer.Config`, the same path that swaps in the QSA, GDN, and KDA
  generation layers.
- Load non-FSDP parameters into their existing storage, while preserving frozen
  parameters and requiring every published trainable parameter to be filled.
- `VLLMPLELayer` rejects prefix caching, `mamba_cache_mode` other than
  `"none"` (its history follows a fixed GDN state slot), and speculative
  decoding.
- The history buffers take about 180 KiB per GDN state slot for the 125B
  model's PLE layer (9 x 10240 BF16 rows plus 2 int64 IDs). GDN has one state
  slot per KV-cache block, so the total scales with vLLM's KV-cache size, not
  with `max_num_seqs`: at DP4/EP4 on GB300 (4,081,987 KV-cache tokens in
  1568-token blocks, about 2,600 slots) they take about 0.45 GiB per GPU. They
  are allocated after vLLM sizes the KV cache, so they come out of the memory
  headroom left for CUDA graph capture. At most `max_num_seqs` slots are live at
  once; accounting for the buffers before KV sizing, or sizing them to live
  requests through a slot-to-row map, is a possible follow-up.

The generator passes PLE its token IDs and positions through the stock vLLM model wrapper; #6206 lets the Flash-Next model default them.

| Before | After |
| --- | --- |
| PLE loses history between generation calls | Chunked prefill/decode keeps per-request history, keyed by the layer's GDN state slot |
| Loader requires every parameter to belong to FSDP | Row-owned parameters load in place; frozen rows stay resident |

```bash
pytest -q tests/rl/unit_tests/gpu/test_vllm_ple.py
pytest -q tests/rl/unit_tests/cpu/test_vllm_wrapper.py \
  tests/rl/unit_tests/cpu/test_vllm_registry.py \
  tests/rl/unit_tests/cpu/test_generator_model.py \
  tests/rl/unit_tests/cpu/test_model_defaults.py
```

`test_vllm_ple.py` passes, including the 2-GPU owned-row gather test. Generator
PLE output is bitwise equal to the trainer `PLELayer` through chunk boundaries,
EOS resets, request reordering, state-slot reuse and padded single-token decode
steps, with eager, partial and full `local_compile` regions. The owned-row
gather is bitwise equal to the slot route with uneven DP token counts. The CPU
RL and Flash-Next suites pass (67 passed, 2 skipped).

Against the trainer's training-mode compiled PLE at production dimensions, the
generator output is 99.57% bitwise at batch 8 decode (max abs 0.031; the rest
comes from the M=8 split-K GEMM, which also differs eager vs eager), 100% at
batch 64 decode, and at least 99.995% for packed steps. Compiling the gate as
one region, as before, matched only about 84%.

PLE layer cost per step (4-layer Flash-Next slice, dummy weights, 2 GB300 at
DP2/EP2, FULL_DECODE_ONLY graphs, summed kernel time between marker kernels,
contexts = DAPO prompt + uniform(1, 4096) generated tokens):

| Shape | This PR | SGLang (Miles, TP2/EP2) |
| --- | --- | --- |
| Decode, batch 8 | 63.3 us | 68 us |
| Decode, batch 16 | 61.9 us | 72.1 us |
| Decode, batch 64 | 70.0 us | 111 us |
| 8 decoding + 8x210 arriving | 514 us | 1318 us |
| 64 decoding + 8x210 arriving | 543 us | 1309 us |

Two ranks only; at 8 ranks both sides' communication costs change. Loading a
production checkpoint end to end and an RL convergence run are not part of this
PR. Validation used an Attention Gym development build with the paged sparse
APIs; the pinned `attn-gym==0.0.20` alone does not supply them.

stack-info: PR: #6203, branch: qwen38-rl-3-ple
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## What changed

- The vLLM generator serves text-only Flash-Next with the stock
  `VLLMModelWrapper`. `Qwen38FlashNextModel.forward` now defaults
  `ple_input_ids` to the token IDs and `document_positions` to the positions
  when they are not passed, which is what generation supplies (one document per
  request, token-ID inputs); it raises if the model does not embed token IDs
  itself or gets no positions. Training always passes both and is unchanged.
- `register_to_vllm` rejects multimodal Flash-Next and vision processors for
  generation.
- `rl_grpo_qwen3_8_flash_next_debug` (`torchtitan_recipes/tests/rl/alphabet_sort.py`):
  random-init Flash-Next on four GPUs, an FSDP2 trainer and a TP2/EP2
  generator with compressed QSA caches, cached PLE and FULL_DECODE_ONLY
  graphs, with validation on like the other recipes. It runs as a 4-GPU B200
  RL integration test. Flash-Next pipeline parallelism (#6055) has not landed,
  so the trainer does not use PP yet.

## Testing

```bash
python -m tests.integration_tests.run_tests <output_dir> --test_suite rl_b200 --ngpu 4
pytest -q tests/rl/unit_tests/cpu/test_model_defaults.py
```

stack-info: PR: #6308, branch: liangel-02/stack/31

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.

Sorry I couldn't figure out what's going on in short amount of time, but I would block this change until I understand it.

@liangel-02
liangel-02 marked this pull request as draft November 20, 2026 23:23
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
@liangel-02
liangel-02 changed the base branch from qwen38-rl-4-recipe to qwen3-8-fn-6-pipeline November 20, 2026 23:23
liangel-02 added a commit that referenced this pull request Nov 20, 2026
…vLLM generator

## 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

Flash-Next's GDN in_proj rows are grouped by key head:

    projection [q0 k0 v0 | q1 k1 v1 | ...]
    gates      [z0 a0 b0 | z1 a1 b1 | ...]

so every generator step copies q|k|v into the contiguous block the convolution
reads and a, b, z into their own tensors (`SplitInProjGDN._split_in_proj`: a
cat kernel plus inductor's `triton_poi_fused_0`). `VLLMInnerGDN.forward` also
concatenates the three conv weights and casts `A_log` and `dt_bias` to FP32 on
every call (Flash-Next keeps them in BF16). Per GDN layer that is 3.8 us + 4.1 us
at decode, 230 us at 8192 prefill tokens and 50 us in an 8x210-token + 64-decode
step. SGLang reorders its in_proj rows once at load and reads strided views, so
it pays none of this.

## What changed

- The vLLM generator swaps `SplitInProjGDN` for `VLLMSplitInProjGDN` (same
  config-type swap as the other generation layers) when in_proj's `projection`
  and `gates` are plain Linears. After every model state dict load it reorders
  its in_proj rows in place to

      projection [q of every key head | k ... | v ...]
      gates      [z ... | a ... | b ...]

  so `_split_in_proj` returns the projection GEMM output itself as the
  convolution input and z, a, b as strided views of the gates GEMM output, which
  the Attention Gym conv, decode and gate kernels and the gated norm read in
  place.
- The same step caches the concatenated conv weight and FP32 copies of `A_log`
  and `dt_bias` in non-persistent buffers, allocated on the first load and
  updated in place afterwards.
- `ModelStateDictLoader` hands each module that defines
  `process_loaded_weights_` the parameters a load just filled (every parameter
  after the initial load, the trainable ones after a weight sync), inside
  inference mode like the unshard. Frozen weights are therefore reordered
  exactly once: later loads refill their shards from the already reordered
  unsharded storage. The hook's contract is in `_process_loaded_weights`'s
  docstring.
- All writes go into storage allocated before CUDA graph capture, so captured
  graphs keep reading the same addresses.

Why the trainer does not own this layout: the reordered layout depends on the
tensor-parallel degree. Each TP rank holds whole key heads and reorders only
its local ones, so the generator's row order differs between TP layouts and
cannot be the trainer's parameter or checkpoint layout. The trainer, its state
dict and the HF/checkpoint layout are unchanged; loads still deliver the
trainer's layout, and the generator reorders after every load.

LoRA and quantized in_proj configs keep the old path: they carry row-indexed
state (`lora_b` rows, scales) that the reorder does not touch.

| Before | After |
| --- | --- |
| Split copy + conv-weight cat + 2 FP32 casts every GDN step | Reorder and caches once per weight load; split is free views |
| Loader has no post-load hook | `process_loaded_weights_` hook with the loaded parameter names |

## Numerics

Outputs and recurrent states are bitwise unchanged (per-layer microbenchmark,
all cases; the permuted-row GEMM is bitwise). Full Flash-Next model, seeded
generation: decode tokens and logprobs bitwise identical before and after on
88/88 requests.

## Performance

Qwen3.8-Flash-Next, 48 layers (36 GDN), real weights, DP4/EP4 on 4 GB300, 64
sequences at ~2.1k context, FULL CUDA graphs:

| | Before | After |
| --- | --- | --- |
| Decode step | 15.08 ms | 14.66 ms (-0.42 ms) |
| Arrival steps (new prompts join) | 34.5-36.0 ms | 34.0-34.7 ms |

Per GDN layer (chained-layer CUDA-graph microbenchmark, same per-GPU layout as
SGLang's DP-attention 4):

| Step | Before | After | SGLang |
| --- | --- | --- | --- |
| Decode, 16 sequences/GPU | 60.9 us | 53.7 us | 54.2 us |
| Prefill, 1 x 8192 tokens | 1165 us | 944 us | 1062 us |
| 8x210 arriving + 64 decoding | 392 us | 339 us | 388 us |

## Testing

```bash
pytest -q tests/rl/unit_tests/gpu/test_gdn_graph_metadata.py
pytest -q tests/rl/unit_tests/cpu/test_generator_model.py
```

The GPU test checks bitwise output, state equality and buffer freshness across
two different weight loads (and that the buffers keep their addresses); it
fails if the reorder is skipped on a weight sync or the caches are not
refreshed. The CPU test checks which parameter names the hook receives at init
and on later loads.

stack-info: PR: #6305, branch: liangel-02/stack/30
liangel-02 added a commit that referenced this pull request Nov 20, 2026
…vLLM generator

## 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

Flash-Next's GDN in_proj rows are grouped by key head:

    projection [q0 k0 v0 | q1 k1 v1 | ...]
    gates      [z0 a0 b0 | z1 a1 b1 | ...]

so every generator step copies q|k|v into the contiguous block the convolution
reads and a, b, z into their own tensors (`SplitInProjGDN._split_in_proj`: a
cat kernel plus inductor's `triton_poi_fused_0`). `VLLMInnerGDN.forward` also
concatenates the three conv weights and casts `A_log` and `dt_bias` to FP32 on
every call (Flash-Next keeps them in BF16). Per GDN layer that is 3.8 us + 4.1 us
at decode, 230 us at 8192 prefill tokens and 50 us in an 8x210-token + 64-decode
step. SGLang reorders its in_proj rows once at load and reads strided views, so
it pays none of this.

## What changed

- The vLLM generator swaps `SplitInProjGDN` for `VLLMSplitInProjGDN` (same
  config-type swap as the other generation layers) when in_proj's `projection`
  and `gates` are plain Linears. After every model state dict load it reorders
  its in_proj rows in place to

      projection [q of every key head | k ... | v ...]
      gates      [z ... | a ... | b ...]

  so `_split_in_proj` returns the projection GEMM output itself as the
  convolution input and z, a, b as strided views of the gates GEMM output, which
  the Attention Gym conv, decode and gate kernels and the gated norm read in
  place.
- The same step caches the concatenated conv weight and FP32 copies of `A_log`
  and `dt_bias` in non-persistent buffers, allocated on the first load and
  updated in place afterwards.
- `ModelStateDictLoader` hands each module that defines
  `process_loaded_weights_` the parameters a load just filled (every parameter
  after the initial load, the trainable ones after a weight sync), inside
  inference mode like the unshard. Frozen weights are therefore reordered
  exactly once: later loads refill their shards from the already reordered
  unsharded storage. The hook's contract is in `_process_loaded_weights`'s
  docstring.
- All writes go into storage allocated before CUDA graph capture, so captured
  graphs keep reading the same addresses.

Why the trainer does not own this layout: the reordered layout depends on the
tensor-parallel degree. Each TP rank holds whole key heads and reorders only
its local ones, so the generator's row order differs between TP layouts and
cannot be the trainer's parameter or checkpoint layout. The trainer, its state
dict and the HF/checkpoint layout are unchanged; loads still deliver the
trainer's layout, and the generator reorders after every load.

LoRA and quantized in_proj configs keep the old path: they carry row-indexed
state (`lora_b` rows, scales) that the reorder does not touch.

| Before | After |
| --- | --- |
| Split copy + conv-weight cat + 2 FP32 casts every GDN step | Reorder and caches once per weight load; split is free views |
| Loader has no post-load hook | `process_loaded_weights_` hook with the loaded parameter names |

## Numerics

Outputs and recurrent states are bitwise unchanged (per-layer microbenchmark,
all cases; the permuted-row GEMM is bitwise). Full Flash-Next model, seeded
generation: decode tokens and logprobs bitwise identical before and after on
88/88 requests.

## Performance

Qwen3.8-Flash-Next, 48 layers (36 GDN), real weights, DP4/EP4 on 4 GB300, 64
sequences at ~2.1k context, FULL CUDA graphs:

| | Before | After |
| --- | --- | --- |
| Decode step | 15.08 ms | 14.66 ms (-0.42 ms) |
| Arrival steps (new prompts join) | 34.5-36.0 ms | 34.0-34.7 ms |

Per GDN layer (chained-layer CUDA-graph microbenchmark, same per-GPU layout as
SGLang's DP-attention 4):

| Step | Before | After | SGLang |
| --- | --- | --- | --- |
| Decode, 16 sequences/GPU | 60.9 us | 53.7 us | 54.2 us |
| Prefill, 1 x 8192 tokens | 1165 us | 944 us | 1062 us |
| 8x210 arriving + 64 decoding | 392 us | 339 us | 388 us |

## Testing

```bash
pytest -q tests/rl/unit_tests/gpu/test_gdn_graph_metadata.py
pytest -q tests/rl/unit_tests/cpu/test_generator_model.py
```

The GPU test checks bitwise output, state equality and buffer freshness across
two different weight loads (and that the buffers keep their addresses); it
fails if the reorder is skipped on a weight sync or the caches are not
refreshed. The CPU test checks which parameter names the hook receives at init
and on later loads.

stack-info: PR: #6305, branch: liangel-02/stack/30
@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to liangel-02/stack/31 November 20, 2026 23:23
@liangel-02
liangel-02 changed the base branch from liangel-02/stack/31 to main November 21, 2026 12:44
liangel-02 added a commit that referenced this pull request Nov 21, 2026
…vLLM generator

## 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

Flash-Next's GDN in_proj rows are grouped by key head:

    projection [q0 k0 v0 | q1 k1 v1 | ...]
    gates      [z0 a0 b0 | z1 a1 b1 | ...]

so every generator step copies q|k|v into the contiguous block the convolution
reads and a, b, z into their own tensors (`SplitInProjGDN._split_in_proj`: a
cat kernel plus inductor's `triton_poi_fused_0`). `VLLMInnerGDN.forward` also
concatenates the three conv weights and casts `A_log` and `dt_bias` to FP32 on
every call (Flash-Next keeps them in BF16). Per GDN layer that is 3.8 us + 4.1 us
at decode, 230 us at 8192 prefill tokens and 50 us in an 8x210-token + 64-decode
step. SGLang reorders its in_proj rows once at load and reads strided views, so
it pays none of this.

## What changed

- The vLLM generator swaps `SplitInProjGDN` for `VLLMSplitInProjGDN` (same
  config-type swap as the other generation layers) when in_proj's `projection`
  and `gates` are plain Linears. After every model state dict load it reorders
  its in_proj rows in place to

      projection [q of every key head | k ... | v ...]
      gates      [z ... | a ... | b ...]

  so `_split_in_proj` returns the projection GEMM output itself as the
  convolution input and z, a, b as strided views of the gates GEMM output, which
  the Attention Gym conv, decode and gate kernels and the gated norm read in
  place.
- The same step caches the concatenated conv weight and FP32 copies of `A_log`
  and `dt_bias` in non-persistent buffers, allocated on the first load and
  updated in place afterwards.
- `ModelStateDictLoader` hands each module that defines
  `process_loaded_weights_` the parameters a load just filled (every parameter
  after the initial load, the trainable ones after a weight sync), inside
  inference mode like the unshard. Frozen weights are therefore reordered
  exactly once: later loads refill their shards from the already reordered
  unsharded storage. The hook's contract is in `_process_loaded_weights`'s
  docstring.
- All writes go into storage allocated before CUDA graph capture, so captured
  graphs keep reading the same addresses.

Why the trainer does not own this layout: the reordered layout depends on the
tensor-parallel degree. Each TP rank holds whole key heads and reorders only
its local ones, so the generator's row order differs between TP layouts and
cannot be the trainer's parameter or checkpoint layout. The trainer, its state
dict and the HF/checkpoint layout are unchanged; loads still deliver the
trainer's layout, and the generator reorders after every load.

LoRA and quantized in_proj configs keep the old path: they carry row-indexed
state (`lora_b` rows, scales) that the reorder does not touch.

| Before | After |
| --- | --- |
| Split copy + conv-weight cat + 2 FP32 casts every GDN step | Reorder and caches once per weight load; split is free views |
| Loader has no post-load hook | `process_loaded_weights_` hook with the loaded parameter names |

## Numerics

Outputs and recurrent states are bitwise unchanged (per-layer microbenchmark,
all cases; the permuted-row GEMM is bitwise). Full Flash-Next model, seeded
generation: decode tokens and logprobs bitwise identical before and after on
88/88 requests.

## Performance

Qwen3.8-Flash-Next, 48 layers (36 GDN), real weights, DP4/EP4 on 4 GB300, 64
sequences at ~2.1k context, FULL CUDA graphs:

| | Before | After |
| --- | --- | --- |
| Decode step | 15.08 ms | 14.66 ms (-0.42 ms) |
| Arrival steps (new prompts join) | 34.5-36.0 ms | 34.0-34.7 ms |

Per GDN layer (chained-layer CUDA-graph microbenchmark, same per-GPU layout as
SGLang's DP-attention 4):

| Step | Before | After | SGLang |
| --- | --- | --- | --- |
| Decode, 16 sequences/GPU | 60.9 us | 53.7 us | 54.2 us |
| Prefill, 1 x 8192 tokens | 1165 us | 944 us | 1062 us |
| 8x210 arriving + 64 decoding | 392 us | 339 us | 388 us |

## Testing

```bash
pytest -q tests/rl/unit_tests/gpu/test_gdn_graph_metadata.py
pytest -q tests/rl/unit_tests/cpu/test_generator_model.py
```

The GPU test checks bitwise output, state equality and buffer freshness across
two different weight loads (and that the buffers keep their addresses); it
fails if the reorder is skipped on a weight sync or the caches are not
refreshed. The CPU test checks which parameter names the hook receives at init
and on later loads.

stack-info: PR: #6305, branch: liangel-02/stack/30
…onfig

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

#6164 deleted `ModelConfigConverter`, `validate_converter_compatibility` and
the `converters` argument of every `build_model_config`, while the Flash-Next
model (#6046-#6054) landed still using them. On main, importing
`torchtitan.models.qwen3_8_flash_next` fails with
`ImportError: cannot import name 'ModelConfigConverter'`, so every Flash-Next
test errors at collection.

This applies #6164's change to Flash-Next: remove the import, the `converters`
argument and its conversion block from `build_model_config`, as #6164 did for
the other models. Recipes apply converters as transforms with
`apply_transforms`. No in-repo caller passes `converters` to Flash-Next.

```bash
pytest -q tests/unit_tests/cpu/models/qwen3_8_flash_next
```

stack-info: PR: #6316, branch: liangel-02/stack/32
## 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

The Flash-Next training model selects complete four-token blocks plus the current
incomplete tail. Generation needs to read those selections from vLLM's physical
KV pages across appends, request reordering, and graph padding. The existing
vLLM replacement does not implement that QSA cache contract.

For a request with 11 tokens selecting block 0, attention must read token
positions `[0, 1, 2, 3, 8, 9, 10]`, even if its logical pages have moved.

## What changed

- Add a parameter-free vLLM page owner calling Attention Gym `paged_sparse_decode`.
- Add `QSAPagedMetadataBuilder`, which builds decode metadata as views of vLLM's
  persistent runner buffers. vLLM already pads them for `FULL_DECODE_ONLY` graphs
  (zero lengths, null pages, `-1` slots), so replay reads each step's request
  layout without extra copies. It only uses vLLM's generic backend and
  `CommonAttentionMetadata` contracts, like `TorchTitanLinearAttentionMetadataBuilder`.
- Preserve request-local addressing, incomplete causal tails, and inactive rows.
- Reject unsupported cache dtypes, speculative decoding, decode CP, and graph modes.
- Every step calls Attention Gym's `paged_sparse_decode` once with vLLM's
  per-request block table, `query_start_loc` and `seq_lens`. Decode-only steps
  keep the host-bound call (`max_seqlen_q=1`). Steps with prompt rows pass
  `max_seqlen_q=None` and `causal_topk=True` (the paged lightning indexer's
  output satisfies that contract), so each row finds its request on the device
  and prompt rows are attended in query tiles that load each K/V chunk once.
  No step gathers a prompt's context or needs host token counts. This needs the
  Attention Gym change that adds `causal_topk`
  (meta-pytorch/attention-gym#979).

  QSA attention per layer, GB300, 24/2 heads, against gathering each prompt's
  context and running `gather_attn` (timed eagerly, since it needs host counts):

  | Step | `gather_attn` | `causal_topk` |
  | --- | --- | --- |
  | 16 decode + 2 x 137 | 143.5 us | 46.3 us |
  | 64 decode + 8 x 210 | 271.2 us | 119.3 us |
  | 64 decode + 8 x 1000 | 827.6 us | 438.3 us |
  | 2 x 4096 | 1360.0 us | 1034.2 us |
  | 1 x 8192 | 1970.6 us | 1924.5 us |

- Add `torchtitan/rl/generator/local_compile.py` with two shared
  `local_compile` region names for generator-only functions,
  `INFERENCE_BATCH_INVARIANT_REGION` and `INFERENCE_BATCH_VARIANT_REGION`;
  `inference_local_compile(batch_invariant=...)`, which registers a function
  under the matching one; and `inference_regions()`, which returns the regions
  that have registered functions (leaving out the batch-variant one in
  batch-invariant mode), so a generator can enable them without knowing which
  layers registered functions. Core `torchtitan/distributed/local_compile.py`
  is unchanged. QSA's padding-row helper registers under the batch-invariant
  region; the generator enables the regions in #6202.
- The common Attention Gym export additions are mechanical import plumbing.

vLLM remains responsible for allocation and reclamation; Python-owned request
caches would duplicate that ownership.

## User-facing changes

| Before | After |
| --- | --- |
| No paged QSA attention adapter | Sparse block IDs read directly from vLLM KV pages |
| No QSA graph metadata | `FULL_DECODE_ONLY` decode replays QSA attention |

## Testing

`pytest -q tests/rl/unit_tests/gpu/test_vllm_qsa.py`

The attention test checks reordered physical pages against an independent sparse
causal reference, including incomplete tails and padding. The graph test refreshes
persistent metadata buffers in place with vLLM's padding, as vLLM's runner does,
and checks replay after changing page tables, lengths, and live request counts.

Full Flash-Next generation additionally needs the indexer and PLE changes in the
next two commits.

## Validation scope

This commit alone is covered by `tests/rl/unit_tests/gpu/test_vllm_qsa.py`; the
training-loss and generation checks below cover the whole stack.

Validation used local B200 GPUs and an Attention Gym development build preserving
the original cuDNN linear kernels, with the paged sparse APIs added. The pinned
`attn-gym==0.0.20` alone does not supply these APIs. No GDN/KDA migration is included.

The complete stack passed `pre-commit run --all-files`. A deterministic seed-42
BF16 debug-model forward/backward (32 tokens) was compared against
`44ff1567196fe91ba8a8f96a1aeefbc6715dda8c`: loss `4.4367218017578125`, gradient
norm `22.315799713134766`, logits, and all 192 parameter gradients were bitwise
identical using `torch.equal`. This is one-GPU training evidence, not a
representative-data convergence run or a 125B performance measurement.

Additional cache-reuse validation: 38 focused tests pass, including native
metadata, padded cache strides, and extra sequence-parallel model rows.
Across three rounds of two requests, generated tokens and log probabilities
are exactly equal to published stack 02f9eb9 in BF16 Dist-MoE TP2/EP2 + SP,
both eager and FULL_DECODE_ONLY, on both ranks. Full pre-commit checks pass.

stack-info: PR: #6201, branch: qwen38-rl-1-generator
@liangel-02
liangel-02 changed the base branch from main to liangel-02/stack/31 November 21, 2026 12:44
tianyu-l pushed a commit that referenced this pull request Nov 21, 2026
…onfig (#6316)

Stacked PRs:
 * #6305
 * #6308
 * #6203
 * #6202
 * #6201
 * __->__#6316


--- --- ---

### [qwen3_8_fn] Drop the removed ModelConfigConverter from
build_model_config


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

#6164 deleted `ModelConfigConverter`, `validate_converter_compatibility`
and
the `converters` argument of every `build_model_config`, while the
Flash-Next
model (#6046-#6054) landed still using them. On main, importing
`torchtitan.models.qwen3_8_flash_next` fails with
`ImportError: cannot import name 'ModelConfigConverter'`, so every
Flash-Next
test errors at collection.

This applies #6164's change to Flash-Next: remove the import, the
`converters`
argument and its conversion block from `build_model_config`, as #6164
did for
the other models. Recipes apply converters as transforms with
`apply_transforms`. No in-repo caller passes `converters` to Flash-Next.

```bash
pytest -q tests/unit_tests/cpu/models/qwen3_8_flash_next
```
wwwjn pushed a commit that referenced this pull request Nov 23, 2026
Stacked PRs:
 * #6305
 * #6308
 * #6203
 * #6202
 * __->__#6201
 * #6316


--- --- ---

### Add vLLM paged QSA attention and graph metadata


## 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

The Flash-Next training model selects complete four-token blocks plus
the current
incomplete tail. Generation needs to read those selections from vLLM's
physical
KV pages across appends, request reordering, and graph padding. The
existing
vLLM replacement does not implement that QSA cache contract.

For a request with 11 tokens selecting block 0, attention must read
token
positions `[0, 1, 2, 3, 8, 9, 10]`, even if its logical pages have
moved.

## What changed

- Add a parameter-free vLLM page owner calling Attention Gym
`paged_sparse_decode`.
- Add `QSAPagedMetadataBuilder`, which builds decode metadata as views
of vLLM's
persistent runner buffers. vLLM already pads them for `FULL_DECODE_ONLY`
graphs
(zero lengths, null pages, `-1` slots), so replay reads each step's
request
  layout without extra copies. It only uses vLLM's generic backend and
`CommonAttentionMetadata` contracts, like
`TorchTitanLinearAttentionMetadataBuilder`.
- Preserve request-local addressing, incomplete causal tails, and
inactive rows.
- Reject unsupported cache dtypes, speculative decoding, decode CP, and
graph modes.
- Every step calls Attention Gym's `paged_sparse_decode` once with
vLLM's
per-request block table, `query_start_loc` and `seq_lens`. Decode-only
steps
keep the host-bound call (`max_seqlen_q=1`). Steps with prompt rows pass
`max_seqlen_q=None` and `causal_topk=True` (the paged lightning
indexer's
output satisfies that contract), so each row finds its request on the
device
and prompt rows are attended in query tiles that load each K/V chunk
once.
No step gathers a prompt's context or needs host token counts. This
needs the
  Attention Gym change that adds `causal_topk`
  (meta-pytorch/attention-gym#979).

QSA attention per layer, GB300, 24/2 heads, against gathering each
prompt's
context and running `gather_attn` (timed eagerly, since it needs host
counts):

  | Step | `gather_attn` | `causal_topk` |
  | --- | --- | --- |
  | 16 decode + 2 x 137 | 143.5 us | 46.3 us |
  | 64 decode + 8 x 210 | 271.2 us | 119.3 us |
  | 64 decode + 8 x 1000 | 827.6 us | 438.3 us |
  | 2 x 4096 | 1360.0 us | 1034.2 us |
  | 1 x 8192 | 1970.6 us | 1924.5 us |

- Add `torchtitan/rl/generator/local_compile.py` with two shared
  `local_compile` region names for generator-only functions,
`INFERENCE_BATCH_INVARIANT_REGION` and `INFERENCE_BATCH_VARIANT_REGION`;
`inference_local_compile(batch_invariant=...)`, which registers a
function
under the matching one; and `inference_regions()`, which returns the
regions
  that have registered functions (leaving out the batch-variant one in
batch-invariant mode), so a generator can enable them without knowing
which
layers registered functions. Core
`torchtitan/distributed/local_compile.py`
is unchanged. QSA's padding-row helper registers under the
batch-invariant
  region; the generator enables the regions in #6202.
- The common Attention Gym export additions are mechanical import
plumbing.

vLLM remains responsible for allocation and reclamation; Python-owned
request
caches would duplicate that ownership.

## User-facing changes

| Before | After |
| --- | --- |
| No paged QSA attention adapter | Sparse block IDs read directly from
vLLM KV pages |
| No QSA graph metadata | `FULL_DECODE_ONLY` decode replays QSA
attention |

## Testing

`pytest -q tests/rl/unit_tests/gpu/test_vllm_qsa.py`

The attention test checks reordered physical pages against an
independent sparse
causal reference, including incomplete tails and padding. The graph test
refreshes
persistent metadata buffers in place with vLLM's padding, as vLLM's
runner does,
and checks replay after changing page tables, lengths, and live request
counts.

Full Flash-Next generation additionally needs the indexer and PLE
changes in the
next two commits.

## Validation scope

This commit alone is covered by
`tests/rl/unit_tests/gpu/test_vllm_qsa.py`; the
training-loss and generation checks below cover the whole stack.

Validation used local B200 GPUs and an Attention Gym development build
preserving
the original cuDNN linear kernels, with the paged sparse APIs added. The
pinned
`attn-gym==0.0.20` alone does not supply these APIs. No GDN/KDA
migration is included.

The complete stack passed `pre-commit run --all-files`. A deterministic
seed-42
BF16 debug-model forward/backward (32 tokens) was compared against
`44ff1567196fe91ba8a8f96a1aeefbc6715dda8c`: loss `4.4367218017578125`,
gradient
norm `22.315799713134766`, logits, and all 192 parameter gradients were
bitwise
identical using `torch.equal`. This is one-GPU training evidence, not a
representative-data convergence run or a 125B performance measurement.

Additional cache-reuse validation: 38 focused tests pass, including
native
metadata, padded cache strides, and extra sequence-parallel model rows.
Across three rounds of two requests, generated tokens and log
probabilities
are exactly equal to published stack 02f9eb9 in BF16 Dist-MoE TP2/EP2 +
SP,
both eager and FULL_DECODE_ONLY, on both ranks. Full pre-commit checks
pass.
@liangel-02
liangel-02 force-pushed the liangel-02/stack/31 branch 2 times, most recently from a825566 to bfd80b4 Compare December 1, 2026 22:43

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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