Skip to content

Integrate the paged lightning indexer with compressed QSA caches - #6202

Open
liangel-02 wants to merge 1 commit into
qwen38-rl-1-qsafrom
qwen38-rl-2-indexer
Open

liangel-02 wants to merge 1 commit into
qwen38-rl-1-qsafrom
qwen38-rl-2-indexer

Conversation

@liangel-02

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

Copy link
Copy Markdown
Contributor

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.

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 Add vLLM paged QSA attention and graph metadata #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.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 19, 2026
@liangel-02
liangel-02 changed the base branch from qwen38-rl-1-generator to qwen3-8-fn-6-pipeline November 19, 2026 01:38
@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to qwen38-rl-1-generator November 19, 2026 01:39
@liangel-02
liangel-02 changed the base branch from qwen38-rl-1-generator to qwen3-8-fn-6-pipeline November 19, 2026 01:45
@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to qwen38-rl-1-generator November 19, 2026 01:45
@liangel-02
liangel-02 changed the base branch from qwen38-rl-1-generator to qwen3-8-fn-6-pipeline November 19, 2026 01:52
@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to qwen38-rl-1-generator November 19, 2026 01:52
@liangel-02
liangel-02 changed the base branch from qwen38-rl-1-generator to qwen3-8-fn-6-pipeline November 19, 2026 01:54
@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to qwen38-rl-1-generator November 19, 2026 01:55
liangel-02 added a commit that referenced this pull request Nov 19, 2026
## 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

Stacked on #6203, which provides the cached PLE generation layer. This PR is the
final step that connects the stack into a runnable RL job:

- Flash-Next's decoder takes `ple_input_ids` and `document_positions` in
  addition to the token IDs and positions every TorchTitan model receives. The
  generic `VLLMModelWrapper.forward` passes only `positions`, so a Flash-Next
  generator fails before PLE runs.
- The generator needs a matching trainer, rollout workload, and initial
  checkpoint configuration for disaggregated RL.

```python
from torchtitan_recipes.rl.qwen3_8_flash_next import (
    qwen3_8_flash_next_dapo_disaggregated,
)

config = qwen3_8_flash_next_dapo_disaggregated(
    hf_assets_path="/checkpoints/qwen3_8_flash_next",
    dapo_math_repo_id="your-org/dapo-math",
)
```

## What changed

Generator integration:

- Add `VLLMFlashNextModelWrapper` (`torchtitan/rl/generator/vllm/qwen3_8_flash_next.py`),
  which overrides only `forward`: vLLM's token IDs feed PLE hashing and its
  positions feed PLE document positions. The per-layer PLE replacement stays in
  `_replace_vllm_layer_configs` (#6203).
- `register_to_vllm` selects the wrapper for `Qwen38FlashNextModel.Config`, the
  same way it selects `VLLMMultimodalModelWrapper` for image-serving generators,
  and raises `ValueError` for multimodal Flash-Next generation.

Recipe (`torchtitan_recipes/rl/qwen3_8_flash_next.py`):

- Add a text-only, disaggregated DAPO/GRPO recipe with 32 trainer GPUs and two
  8-GPU generators, GPU-resident frozen PLE, frozen indexers, and explicit initial
  HF checkpoint loading. It selects optional BF16 Dist-MoE and decode graphs.
- Configure 30 training iterations with 16 prompts and 8 samples per prompt,
  an 8192-token context, and a 4096-token response limit.
- Use BF16 compute with FP32 master parameters, AdamW, and the DAPO loss.
- Keep the frozen n-gram table specialization local to the recipe.

## User-facing changes

| Before | After |
| --- | --- |
| Flash-Next generators use the generic wrapper and omit PLE inputs | Flash-Next generators run text generation through vLLM |
| No check for Flash-Next multimodal generation | Raises `ValueError` for multimodal Flash-Next generation |
| No Flash-Next RL recipe | `qwen3_8_flash_next_dapo_disaggregated(...)` |

## Testing

```bash
pytest -q tests/rl/unit_tests/gpu/test_vllm_qsa.py \
  tests/rl/unit_tests/gpu/test_vllm_ple.py \
  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
```

38 passed.

Debug-model generation with initialized weights, the real paged indexer, and
paged QSA attention, using two requests (a 3-token prompt, and a 37-token prompt
split by chunked prefill) that finish at different steps:

| Configuration | Result |
| --- | --- |
| 1 GPU, eager | `[53, 27, 17]`, `[25, 39, 56, 18, 59]` |
| 1 GPU, `FULL_DECODE_ONLY` CUDA graphs | identical to eager |
| 4 GPUs, DP2/TP2/EP4 + SP, eager | completes on every rank |

Each configuration produced the same tokens as the earlier revision of this
stack, in which the PLE layer replacement lived in the wrapper. Loading a full
released HF checkpoint was not exercised.

## Numerics and performance

The supporting stack has deterministic debug-model parity recorded in #6202.
These checks do not validate this full recipe's loss, reward curve, or
throughput.

Dist-MoE execution validation is deferred. The full 48-GPU recipe, production
checkpoint/data run, and matched end-to-end performance comparison have not been
run. No throughput improvement is claimed from the debug smoke tests.

The recipe requires the same Attention Gym development build as the supporting
stack: 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.

stack-info: PR: #6206, branch: qwen38-rl-4-recipe
@liangel-02
liangel-02 changed the base branch from qwen38-rl-1-generator to main November 19, 2026 04:31
liangel-02 added a commit that referenced this pull request Nov 19, 2026
## 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

Stacked on #6203, which provides the cached PLE generation layer. This PR is the
final step that connects the stack into a runnable RL job:

- Flash-Next's decoder takes `ple_input_ids` and `document_positions` in
  addition to the token IDs and positions every TorchTitan model receives. The
  generic `VLLMModelWrapper.forward` passes only `positions`, so a Flash-Next
  generator fails before PLE runs.
- The generator needs a matching trainer, rollout workload, and initial
  checkpoint configuration for disaggregated RL.

```python
from torchtitan_recipes.rl.qwen3_8_flash_next import (
    qwen3_8_flash_next_dapo_disaggregated,
)

config = qwen3_8_flash_next_dapo_disaggregated(
    hf_assets_path="/checkpoints/qwen3_8_flash_next",
    dapo_math_repo_id="your-org/dapo-math",
)
```

## What changed

Generator integration:

- Add `VLLMFlashNextModelWrapper` (`torchtitan/rl/generator/vllm/qwen3_8_flash_next.py`),
  which overrides only `forward`: vLLM's token IDs feed PLE hashing and its
  positions feed PLE document positions. The per-layer PLE replacement stays in
  `_replace_vllm_layer_configs` (#6203).
- `register_to_vllm` selects the wrapper for `Qwen38FlashNextModel.Config`, the
  same way it selects `VLLMMultimodalModelWrapper` for image-serving generators,
  and raises `ValueError` for multimodal Flash-Next generation.

Recipe (`torchtitan_recipes/rl/qwen3_8_flash_next.py`):

- Add a text-only, disaggregated DAPO/GRPO recipe with 32 trainer GPUs and two
  8-GPU generators, GPU-resident frozen PLE, frozen indexers, and explicit initial
  HF checkpoint loading. It selects optional BF16 Dist-MoE and decode graphs.
- Configure 30 training iterations with 16 prompts and 8 samples per prompt,
  an 8192-token context, and a 4096-token response limit.
- Use BF16 compute with FP32 master parameters, AdamW, and the DAPO loss.
- Keep the frozen n-gram table specialization local to the recipe.

## User-facing changes

| Before | After |
| --- | --- |
| Flash-Next generators use the generic wrapper and omit PLE inputs | Flash-Next generators run text generation through vLLM |
| No check for Flash-Next multimodal generation | Raises `ValueError` for multimodal Flash-Next generation |
| No Flash-Next RL recipe | `qwen3_8_flash_next_dapo_disaggregated(...)` |

## Testing

```bash
pytest -q tests/rl/unit_tests/gpu/test_vllm_qsa.py \
  tests/rl/unit_tests/gpu/test_vllm_ple.py \
  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
```

38 passed.

Debug-model generation with initialized weights, the real paged indexer, and
paged QSA attention, using two requests (a 3-token prompt, and a 37-token prompt
split by chunked prefill) that finish at different steps:

| Configuration | Result |
| --- | --- |
| 1 GPU, eager | `[53, 27, 17]`, `[25, 39, 56, 18, 59]` |
| 1 GPU, `FULL_DECODE_ONLY` CUDA graphs | identical to eager |
| 4 GPUs, DP2/TP2/EP4 + SP, eager | completes on every rank |

Each configuration produced the same tokens as the earlier revision of this
stack, in which the PLE layer replacement lived in the wrapper. Loading a full
released HF checkpoint was not exercised.

## Numerics and performance

The supporting stack has deterministic debug-model parity recorded in #6202.
These checks do not validate this full recipe's loss, reward curve, or
throughput.

Dist-MoE execution validation is deferred. The full 48-GPU recipe, production
checkpoint/data run, and matched end-to-end performance comparison have not been
run. No throughput improvement is claimed from the debug smoke tests.

The recipe requires the same Attention Gym development build as the supporting
stack: 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.

stack-info: PR: #6206, branch: qwen38-rl-4-recipe
@liangel-02
liangel-02 changed the base branch from main to qwen38-rl-1-generator November 19, 2026 04:36
liangel-02 added a commit that referenced this pull request Nov 19, 2026
## 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

Stacked on #6203, which provides the cached PLE generation layer. This PR is the
final step that connects the stack into a runnable RL job:

- Flash-Next's decoder takes `ple_input_ids` and `document_positions` in
  addition to the token IDs and positions every TorchTitan model receives. The
  generic `VLLMModelWrapper.forward` passes only `positions`, so a Flash-Next
  generator fails before PLE runs.
- The generator needs a matching trainer, rollout workload, and initial
  checkpoint configuration for disaggregated RL.

```python
from torchtitan_recipes.rl.qwen3_8_flash_next import (
    qwen3_8_flash_next_dapo_disaggregated,
)

config = qwen3_8_flash_next_dapo_disaggregated(
    hf_assets_path="/checkpoints/qwen3_8_flash_next",
    dapo_math_repo_id="your-org/dapo-math",
)
```

## What changed

Generator integration:

- Add `VLLMFlashNextModelWrapper` (`torchtitan/rl/generator/vllm/qwen3_8_flash_next.py`),
  which overrides only `forward`: vLLM's token IDs feed PLE hashing and its
  positions feed PLE document positions. The per-layer PLE replacement stays in
  `_replace_vllm_layer_configs` (#6203).
- `register_to_vllm` selects the wrapper for `Qwen38FlashNextModel.Config`, the
  same way it selects `VLLMMultimodalModelWrapper` for image-serving generators,
  and raises `ValueError` for multimodal Flash-Next generation.

Recipe (`torchtitan_recipes/rl/qwen3_8_flash_next.py`):

- Add a text-only, disaggregated DAPO/GRPO recipe with 32 trainer GPUs and two
  8-GPU generators, GPU-resident frozen PLE, frozen indexers, and explicit initial
  HF checkpoint loading. It selects optional BF16 Dist-MoE and decode graphs.
- Configure 30 training iterations with 16 prompts and 8 samples per prompt,
  an 8192-token context, and a 4096-token response limit.
- Use BF16 compute with FP32 master parameters, AdamW, and the DAPO loss.
- Keep the frozen n-gram table specialization local to the recipe.

## User-facing changes

| Before | After |
| --- | --- |
| Flash-Next generators use the generic wrapper and omit PLE inputs | Flash-Next generators run text generation through vLLM |
| No check for Flash-Next multimodal generation | Raises `ValueError` for multimodal Flash-Next generation |
| No Flash-Next RL recipe | `qwen3_8_flash_next_dapo_disaggregated(...)` |

## Testing

```bash
pytest -q tests/rl/unit_tests/gpu/test_vllm_qsa.py \
  tests/rl/unit_tests/gpu/test_vllm_ple.py \
  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
```

38 passed.

Debug-model generation with initialized weights, the real paged indexer, and
paged QSA attention, using two requests (a 3-token prompt, and a 37-token prompt
split by chunked prefill) that finish at different steps:

| Configuration | Result |
| --- | --- |
| 1 GPU, eager | `[53, 27, 17]`, `[25, 39, 56, 18, 59]` |
| 1 GPU, `FULL_DECODE_ONLY` CUDA graphs | identical to eager |
| 4 GPUs, DP2/TP2/EP4 + SP, eager | completes on every rank |

Each configuration produced the same tokens as the earlier revision of this
stack, in which the PLE layer replacement lived in the wrapper. Loading a full
released HF checkpoint was not exercised.

## Numerics and performance

The supporting stack has deterministic debug-model parity recorded in #6202.
These checks do not validate this full recipe's loss, reward curve, or
throughput.

BF16 Dist-MoE debug generation passed with TP2/EP2 and sequence parallelism
in eager mode and with decode graphs. The full 48-GPU recipe, production
checkpoint/data run, and matched end-to-end performance comparison have not
been run. No throughput improvement is claimed from the debug smoke tests.

The recipe requires the same Attention Gym development build as the supporting
stack: 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.

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: #6206, branch: qwen38-rl-4-recipe
liangel-02 added a commit that referenced this pull request Nov 19, 2026
## 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

Stacked on #6203, which provides the cached PLE generation layer. This PR is the
final step that connects the stack into a runnable RL job:

- Flash-Next's decoder takes `ple_input_ids` and `document_positions` in
  addition to the token IDs and positions every TorchTitan model receives. The
  generic `VLLMModelWrapper.forward` passes only `positions`, so a Flash-Next
  generator fails before PLE runs.
- The generator needs a matching trainer, rollout workload, and initial
  checkpoint configuration for disaggregated RL.

```python
from torchtitan_recipes.rl.qwen3_8_flash_next import (
    qwen3_8_flash_next_dapo_disaggregated,
)

config = qwen3_8_flash_next_dapo_disaggregated(
    hf_assets_path="/checkpoints/qwen3_8_flash_next",
    dapo_math_repo_id="your-org/dapo-math",
)
```

## What changed

Generator integration:

- Add `VLLMFlashNextModelWrapper` (`torchtitan/rl/generator/vllm/qwen3_8_flash_next.py`),
  which overrides only `forward`: vLLM's token IDs feed PLE hashing and its
  positions feed PLE document positions. The per-layer PLE replacement stays in
  `_replace_vllm_layer_configs` (#6203).
- `register_to_vllm` selects the wrapper for `Qwen38FlashNextModel.Config`, the
  same way it selects `VLLMMultimodalModelWrapper` for image-serving generators,
  and raises `ValueError` for multimodal Flash-Next generation.

Recipe (`torchtitan_recipes/rl/qwen3_8_flash_next.py`):

- Add a text-only, disaggregated DAPO/GRPO recipe with 32 trainer GPUs and two
  8-GPU generators, GPU-resident frozen PLE, frozen indexers, and explicit initial
  HF checkpoint loading. It selects optional BF16 Dist-MoE and decode graphs.
- Configure 30 training iterations with 16 prompts and 8 samples per prompt,
  an 8192-token context, and a 4096-token response limit.
- Use BF16 compute with FP32 master parameters, AdamW, and the DAPO loss.
- Keep the frozen n-gram table specialization local to the recipe.

## User-facing changes

| Before | After |
| --- | --- |
| Flash-Next generators use the generic wrapper and omit PLE inputs | Flash-Next generators run text generation through vLLM |
| No check for Flash-Next multimodal generation | Raises `ValueError` for multimodal Flash-Next generation |
| No Flash-Next RL recipe | `qwen3_8_flash_next_dapo_disaggregated(...)` |

## Testing

```bash
pytest -q tests/rl/unit_tests/gpu/test_vllm_qsa.py \
  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
```

38 passed.

Debug-model generation with initialized weights, the real paged indexer, and
paged QSA attention, using two requests (a 3-token prompt, and a 37-token prompt
split by chunked prefill) that finish at different steps:

| Configuration | Result |
| --- | --- |
| 1 GPU, eager | `[53, 27, 17]`, `[25, 39, 56, 18, 59]` |
| 1 GPU, `FULL_DECODE_ONLY` CUDA graphs | identical to eager |
| 4 GPUs, DP2/TP2/EP4 + SP, eager | completes on every rank |

Each configuration produced the same tokens as the earlier revision of this
stack, in which the PLE layer replacement lived in the wrapper. Loading a full
released HF checkpoint was not exercised.

## Numerics and performance

The supporting stack has deterministic debug-model parity recorded in #6202.
These checks do not validate this full recipe's loss, reward curve, or
throughput.

BF16 Dist-MoE debug generation passed with TP2/EP2 and sequence parallelism
in eager mode and with decode graphs. The full 48-GPU recipe, production
checkpoint/data run, and matched end-to-end performance comparison have not
been run. No throughput improvement is claimed from the debug smoke tests.

The recipe requires the same Attention Gym development build as the supporting
stack: 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.

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: #6206, branch: qwen38-rl-4-recipe
liangel-02 added a commit that referenced this pull request Nov 19, 2026
## 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

Stacked on #6203, which provides the cached PLE generation layer. This PR is the
final step that connects the stack into a runnable RL job:

- Flash-Next's decoder takes `ple_input_ids` and `document_positions` in
  addition to the token IDs and positions every TorchTitan model receives. The
  generic `VLLMModelWrapper.forward` passes only `positions`, so a Flash-Next
  generator fails before PLE runs.
- The generator needs a matching trainer, rollout workload, and initial
  checkpoint configuration for disaggregated RL.

```python
from torchtitan_recipes.rl.qwen3_8_flash_next import (
    qwen3_8_flash_next_dapo_disaggregated,
)

config = qwen3_8_flash_next_dapo_disaggregated(
    hf_assets_path="/checkpoints/qwen3_8_flash_next",
    dapo_math_repo_id="your-org/dapo-math",
)
```

## What changed

Generator integration:

- Add `VLLMFlashNextModelWrapper` (`torchtitan/rl/generator/vllm/qwen3_8_flash_next.py`),
  which overrides only `forward`: vLLM's token IDs feed PLE hashing and its
  positions feed PLE document positions. The per-layer PLE replacement stays in
  `_replace_vllm_layer_configs` (#6203).
- `register_to_vllm` selects the wrapper for `Qwen38FlashNextModel.Config`, the
  same way it selects `VLLMMultimodalModelWrapper` for image-serving generators,
  and raises `ValueError` for multimodal Flash-Next generation.

Recipe (`torchtitan_recipes/rl/qwen3_8_flash_next.py`):

- Add a text-only, disaggregated DAPO/GRPO recipe with 32 trainer GPUs and two
  8-GPU generators, GPU-resident frozen PLE, frozen indexers, and explicit initial
  HF checkpoint loading. It selects optional BF16 Dist-MoE and decode graphs.
- Configure 30 training iterations with 16 prompts and 8 samples per prompt,
  an 8192-token context, and a 4096-token response limit.
- Use BF16 compute with FP32 master parameters, AdamW, and the DAPO loss.
- Keep the frozen n-gram table specialization local to the recipe.

## User-facing changes

| Before | After |
| --- | --- |
| Flash-Next generators use the generic wrapper and omit PLE inputs | Flash-Next generators run text generation through vLLM |
| No check for Flash-Next multimodal generation | Raises `ValueError` for multimodal Flash-Next generation |
| No Flash-Next RL recipe | `qwen3_8_flash_next_dapo_disaggregated(...)` |

## Testing

```bash
pytest -q tests/rl/unit_tests/gpu/test_vllm_qsa.py \
  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
```

38 passed.

Debug-model generation with initialized weights, the real paged indexer, and
paged QSA attention, using two requests (a 3-token prompt, and a 37-token prompt
split by chunked prefill) that finish at different steps:

| Configuration | Result |
| --- | --- |
| 1 GPU, eager | `[53, 27, 17]`, `[25, 39, 56, 18, 59]` |
| 1 GPU, `FULL_DECODE_ONLY` CUDA graphs | identical to eager |
| 4 GPUs, DP2/TP2/EP4 + SP, eager | completes on every rank |

Each configuration produced the same tokens as the earlier revision of this
stack, in which the PLE layer replacement lived in the wrapper. Loading a full
released HF checkpoint was not exercised.

## Numerics and performance

The supporting stack has deterministic debug-model parity recorded in #6202.
These checks do not validate this full recipe's loss, reward curve, or
throughput.

BF16 Dist-MoE debug generation passed with TP2/EP2 and sequence parallelism
in eager mode and with decode graphs. The full 48-GPU recipe, production
checkpoint/data run, and matched end-to-end performance comparison have not
been run. No throughput improvement is claimed from the debug smoke tests.

The recipe requires the same Attention Gym development build as the supporting
stack: 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.

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: #6206, branch: qwen38-rl-4-recipe
liangel-02 added a commit that referenced this pull request Nov 19, 2026
## 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

Stacked on #6203, which provides the cached PLE generation layer. This PR is the
final step that connects the stack into a runnable RL job:

- Flash-Next's decoder takes `ple_input_ids` and `document_positions` in
  addition to the token IDs and positions every TorchTitan model receives. The
  generic `VLLMModelWrapper.forward` passes only `positions`, so a Flash-Next
  generator fails before PLE runs.
- The generator needs a matching trainer, rollout workload, and initial
  checkpoint configuration for disaggregated RL.

```python
from torchtitan_recipes.rl.qwen3_8_flash_next import (
    qwen3_8_flash_next_dapo_disaggregated,
)

config = qwen3_8_flash_next_dapo_disaggregated(
    hf_assets_path="/checkpoints/qwen3_8_flash_next",
    dapo_math_repo_id="your-org/dapo-math",
)
```

## What changed

Generator integration:

- Add `VLLMFlashNextModelWrapper` (`torchtitan/rl/generator/vllm/qwen3_8_flash_next.py`),
  which overrides only `forward`: vLLM's token IDs feed PLE hashing and its
  positions feed PLE document positions. The per-layer PLE replacement stays in
  `_replace_vllm_layer_configs` (#6203).
- `register_to_vllm` selects the wrapper for `Qwen38FlashNextModel.Config`, the
  same way it selects `VLLMMultimodalModelWrapper` for image-serving generators,
  and raises `ValueError` for multimodal Flash-Next generation.

Recipe (`torchtitan_recipes/rl/qwen3_8_flash_next.py`):

- Add a text-only, disaggregated DAPO/GRPO recipe with 32 trainer GPUs and two
  8-GPU generators, GPU-resident frozen PLE, frozen indexers, and explicit initial
  HF checkpoint loading. It selects optional BF16 Dist-MoE and decode graphs.
- Configure 30 training iterations with 16 prompts and 8 samples per prompt,
  an 8192-token context, and a 4096-token response limit.
- Use BF16 compute with FP32 master parameters, AdamW, and the DAPO loss.
- Keep the frozen n-gram table specialization local to the recipe.

## User-facing changes

| Before | After |
| --- | --- |
| Flash-Next generators use the generic wrapper and omit PLE inputs | Flash-Next generators run text generation through vLLM |
| No check for Flash-Next multimodal generation | Raises `ValueError` for multimodal Flash-Next generation |
| No Flash-Next RL recipe | `qwen3_8_flash_next_dapo_disaggregated(...)` |

## Testing

```bash
pytest -q tests/rl/unit_tests/gpu/test_vllm_qsa.py \
  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
```

38 passed.

Debug-model generation with initialized weights, the real paged indexer, and
paged QSA attention, using two requests (a 3-token prompt, and a 37-token prompt
split by chunked prefill) that finish at different steps:

| Configuration | Result |
| --- | --- |
| 1 GPU, eager | `[53, 27, 17]`, `[25, 39, 56, 18, 59]` |
| 1 GPU, `FULL_DECODE_ONLY` CUDA graphs | identical to eager |
| 4 GPUs, DP2/TP2/EP4 + SP, eager | completes on every rank |

Each configuration produced the same tokens as the earlier revision of this
stack, in which the PLE layer replacement lived in the wrapper. Loading a full
released HF checkpoint was not exercised.

## Numerics and performance

The supporting stack has deterministic debug-model parity recorded in #6202.
These checks do not validate this full recipe's loss, reward curve, or
throughput.

BF16 Dist-MoE debug generation passed with TP2/EP2 and sequence parallelism
in eager mode and with decode graphs. The full 48-GPU recipe, production
checkpoint/data run, and matched end-to-end performance comparison have not
been run. No throughput improvement is claimed from the debug smoke tests.

The recipe requires the same Attention Gym development build as the supporting
stack: 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.

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: #6206, branch: qwen38-rl-4-recipe
@liangel-02

Copy link
Copy Markdown
Contributor Author

@claude review again ignore issues w/ attn gym dependencies

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @liangel-02's task in 3m 50s —— View job


Approve -- please address the items below before merging. See the review on this PR: 2 small must-fix items, one of them an inline comment. As requested, it skips the Attention Gym dependencies.

@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 code-level items from the last review and all three of @tianyu-l's comments are resolved. What's left is the missing human-written summary and a comment on an invariant that isn't written down. As you asked, I skipped the Attention Gym pins and dependencies.

What this PR does. In the generator, Flash-Next layers keep the trainer's QSAAttention and swap in VLLMQSAIndexer and VLLMQSAInnerAttention. When a step completes a 4-token block, the indexer averages that block's raw keys, applies k_layernorm and then RoPE at the block start, and stores the result in a key-only candidate page. Raw keys from earlier steps come from a per-request ring, which keeps only the unfinished block. paged_lightning_indexer then selects the blocks, and in batch-invariant mode they are sorted into the trainer's order. Every vLLM model now turns on the shared inference local_compile regions.

Example.

chunk 1 (pos 0-2):  no block completes; ring <- k0 k1 k2; candidates = []
chunk 2 (pos 3):    row 3: mean(ring[0..2], k3) -> k_norm -> RoPE(0) -> candidate b0
                    ring keeps nothing (seq_len 4 % 4 == 0); row 3 may select b0
trainer, same 4 tokens: raw_key[0:4].mean -> same b0, same selection (GPU test, append 3,1,9,6,1)

Resolved since the last review

  • compress_ratio is now read from attention_cfg.inner_attention.
  • The private concat_and_cache_mla is gone; the code now uses indexed assignment into the stride-aware views.
  • @tianyu-l, separate files: qsa_model.py is folded into qsa.py. query_positions.py has its second consumer in #6203.
  • @tianyu-l, vllm_attention_backend: the uses_paged_qsa_cache docstring now explains why QSA layers ignore the global backend.
  • @tianyu-l, local_compile: the regions are now generic (INFERENCE_BATCH_INVARIANT_REGION / INFERENCE_BATCH_VARIANT_REGION), and a TODO records the ModelConfigTransform option.

Must fix

  1. PR description: there is no "Summary (human-written)" section. CONTRIBUTING.md and CLAUDE.md ask the author to write it (2-5 sentences, per .github/pull_request_template.md).
  2. torchtitan/rl/generator/vllm/attention/qsa.py:386 -- masked rows write to page 0 offset 0, which relies on vLLM's null block. Add a one-line comment (inline).

Should consider

  • torchtitan/rl/generator/vllm/registry.py:185 -- still open: a per-model isinstance in the shared HF-config builder, plus a Qwen38FlashNextModel import, for an rms_norm_eps the comment says is unused.
Details
  • Ring reads. A row that completes a block reads at most 3 earlier positions. Any of them before this step's start belong to the previous step's unfinished block, and the ring keeps exactly that block (position >= seq_len // 4 * 4). The reads in _decode_prep come before the writes at lines 386-387.
  • Block-table trim. The removed block_table trim is no longer needed: a candidate page covers the same 16 tokens as a KV page, so the table width already bounds the candidates.
  • Order outside batch-invariant mode. The block order there follows the kernel, not the trainer's sorted order. That only changes accumulation order, and that mode isn't bitwise anyway.
  • Pooled-key RoPE position. It still uses the logical position_T - 3, not positions[block_start]. The two agree for 1D text positions only. This needs revisiting if Flash-Next image serving is added.
  • Speculative decoding (latent). The ring keep-rule uses seq_lens, which would include draft tokens, so a rejected draft could drop raw keys that are needed later. The generator doesn't configure speculative decoding today, so this is not a finding.

Not verified: GPU numerics and graph replay, and whether the pinned vLLM provides CircularBufferSpec, MLAAttentionSpec(tokens_per_state=...) and the 4D [P, H, N, K] layout that views() assumes. A maintainer still needs to review.

Comment on lines +386 to +387
pooled_cache_PNHK[candidate_pages_T, candidate_offsets_T] = pooled_TK[:, None]
raw_cache_PNHK[ring_pages_T, ring_offsets_T] = raw_key_TK[:, None]

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.

These indexed writes have no skip value. The earlier concat_and_cache_mla / reshape_and_cache_flash calls skipped slot -1. Here, every row that doesn't finish a block, every row that falls in a completed block, and every SP padding row writes to page 0, offset 0 (masked_fill(..., 0) at lines 328, 330, 345, 346). Those are also duplicate indices, so which value lands there is undefined. That's only safe because vLLM reserves block 0 as the null block, and the pool shares that block across all cache groups, so nothing ever reads it. The code doesn't say this anywhere, so it looks like a bug, and a later edit to the masks or the allocator could silently corrupt a real page.

Add a one-line comment where the masks are built, e.g. # Skipped rows write to page 0, vLLM's reserved null block, which no request reads. Unverified: I couldn't import vLLM here to confirm that the pinned version still reserves block 0.

@liangel-02
liangel-02 changed the base branch from qwen38-rl-1-generator to qwen3-8-fn-6-pipeline November 20, 2026 18:44
@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to qwen38-rl-1-generator November 20, 2026 18:44
@liangel-02
liangel-02 changed the base branch from qwen38-rl-1-generator to qwen3-8-fn-6-pipeline November 20, 2026 19:49
@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to qwen38-rl-1-generator November 20, 2026 19:49
@liangel-02
liangel-02 marked this pull request as ready for review November 20, 2026 19:54
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 20, 2026 19:54
@liangel-02
liangel-02 requested a review from tianyu-l November 20, 2026 19:54
@liangel-02
liangel-02 marked this pull request as draft November 20, 2026 22:10
@liangel-02
liangel-02 changed the base branch from qwen38-rl-1-generator to qwen3-8-fn-6-pipeline November 20, 2026 22:10
model_config.local_compile,
regions=[
*regions,
*(name for name in inference_regions() if name not in regions),

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.

please double check that --
when inference_regions() and the is_in_batch_invariant_mode() in it are called, batch invariance mode is already set.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

yes, batch-invariant mode is already set by the time inference_regions() runs

@wwwjn

wwwjn commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

I will have a follow up PR to fix the lint failure and related CI issue once the stack is merged

<!-- 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 the training
indexer's selection, including causal exclusion and padded ring-page strides.
The comparison ignores order: `paged_lightning_indexer` leaves the order of
selected IDs unspecified outside batch-invariant mode.

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.

The checks below were run on local B200 GPUs before the Attention Gym pin bump
(previous commit), with a development build that had the paged sparse APIs.
`test_vllm_qsa.py` passes at the new pin on GB300.

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.

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

3 participants