Skip to content

Connect Flash-Next generation and add a debug RL recipe - #6206

Open
liangel-02 wants to merge 10 commits into
qwen38-rl-3-plefrom
qwen38-rl-4-recipe
Open

liangel-02 wants to merge 10 commits into
qwen38-rl-3-plefrom
qwen38-rl-4-recipe

Conversation

@liangel-02

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

Copy link
Copy Markdown
Contributor

@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-3-ple to qwen3-8-fn-6-pipeline November 19, 2026 01:52
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 cached PLE and the Flash-Next generator wrapper.
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

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

This PR contains only `torchtitan_recipes/rl/qwen3_8_flash_next.py`. Model
integration, parameter loading, and their tests are in #6203.

## User-facing changes

| Before | After |
| --- | --- |
| No Flash-Next RL recipe | `qwen3_8_flash_next_dapo_disaggregated(...)` |

## Testing

`pre-commit run --all-files` passed.

The recipe file is byte-for-byte identical to the one previously included in
commit `346c33ba435bcee83bfd62bf14c027abc4a0509d`. This split changes commit
boundaries only; the complete stack's source tree is unchanged. No new runtime
tests were run for the split.

## Numerics and performance

The supporting stack has deterministic debug-model parity and generation smoke
results recorded in #6203. Those 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 qwen3-8-fn-6-pipeline to qwen38-rl-3-ple November 19, 2026 01:52
@liangel-02
liangel-02 changed the base branch from qwen38-rl-3-ple to qwen3-8-fn-6-pipeline 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 cached PLE and the Flash-Next generator wrapper.
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

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

This PR contains only `torchtitan_recipes/rl/qwen3_8_flash_next.py`. Model
integration, parameter loading, and their tests are in #6203.

## User-facing changes

| Before | After |
| --- | --- |
| No Flash-Next RL recipe | `qwen3_8_flash_next_dapo_disaggregated(...)` |

## Testing

`pre-commit run --all-files` passed.

The recipe file is byte-for-byte identical to the one previously included in
commit `346c33ba435bcee83bfd62bf14c027abc4a0509d`. This split changes commit
boundaries only; the complete stack's source tree is unchanged. No new runtime
tests were run for the split.

## Numerics and performance

The supporting stack has deterministic debug-model parity and generation smoke
results recorded in #6203. Those 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 qwen3-8-fn-6-pipeline to qwen38-rl-3-ple 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-3-ple 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-3-ple 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
liangel-02 force-pushed the qwen38-rl-4-recipe branch 2 times, most recently from be62e82 to 61554ff Compare November 19, 2026 06:04
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
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to qwen38-rl-3-ple November 19, 2026 22:46
@liangel-02
liangel-02 changed the base branch from qwen38-rl-3-ple to qwen3-8-fn-6-pipeline November 20, 2026 18:13
liangel-02 added a commit that referenced this pull request Nov 20, 2026
stack-info: PR: #6206, branch: qwen38-rl-4-recipe
@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to qwen38-rl-3-ple November 20, 2026 18:13
@liangel-02
liangel-02 changed the base branch from qwen38-rl-3-ple to qwen3-8-fn-6-pipeline November 20, 2026 18:23
liangel-02 added a commit that referenced this pull request Nov 20, 2026
stack-info: PR: #6206, branch: qwen38-rl-4-recipe
@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to qwen38-rl-3-ple November 20, 2026 18:23
@liangel-02
liangel-02 changed the base branch from qwen38-rl-3-ple to qwen3-8-fn-6-pipeline November 20, 2026 18:44
liangel-02 added a commit that referenced this pull request Nov 20, 2026
stack-info: PR: #6206, branch: qwen38-rl-4-recipe
@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to qwen38-rl-3-ple November 20, 2026 18:44
Qwen3.8-Flash-Next extends Qwen3.5 with four gated residual streams, Qwen
Sparse Attention (QSA) and a hashed n-gram embedding (PLE). This adds the
model, its HF state dict adapter, the report's optimizer policy, FSDP and EP.

- Model (torchtitan/models/qwen3_8_flash_next/): Qwen3.5 GDN, vision and
  lifecycle reused; gated residual streams; document-local hashed PLE; QSA on
  Attention Gym gather_attn with lightning_indexer block selection and the
  no-grad indexer teacher (the indexer scores each query chunk only
  against the blocks its documents can reach, since the data pipeline caps
  documents at max_context_length); text (Qwen38FlashNextModel) and multimodal
  (Qwen38FlashNextMultimodalModel) classes; the shared TokenChoiceTopKRouter.
- Row-sharded PLE (row_sharded_embedding.py): the table is a DTensor on the
  dense SPMD mesh (Shard(0) on dp, replicated on cp/tp), excluded from FSDP
  all-gathers; lookups route unique IDs, vectors and gradients to their DP row
  owners through an autograd.Function with an explicit backward.
- Optimizer recipe (torchtitan_recipes/models/qwen3_8_flash_next.py): DistMuon
  for decoder linear maps, AdamW for embeddings, head, router, gates, norms and
  vision, Adam for PLE.
- HF parity script (scripts/checkpoint_conversion/): text, vision and
  image/video forward/backward with exact expert and token selections; logits
  gated against an FP32 copy of the reference.
- qwen3_8_flash_next_fsdp in the B200 suite: FSDP2 + EP2, save and resume.
- Mechanical: public Qwen3.5 config factory names.
QSA blocked accelerator-graph capture: QSAIndexMetadata and _select_blocks
used nonzero and bincount, whose output sizes depend on the batch and force a
host synchronization, and the complete-block count G changed every batch.

- QSAIndexMetadata keeps T // R block rows (inactive rows point at the first
  valid token and lie outside every document's candidate range), a
  fixed-length compaction of valid tokens, and valid-token document offsets
  with T + 1 slots. Attention Gym only binary-searches the offsets per token,
  so the spare slots cost nothing and no document capacity is needed.
- _select_blocks runs lightning_indexer over the compacted tokens with those
  offsets and maps results back to token order without scatter.
- The GPU test captures an indexer step on one document layout and replays
  another; it runs in the B200 workflow.

Numerics: eager selections and gradients are unchanged when a batch has T/R
complete blocks (released 125B QSA layer bitwise; debug recipe 10 steps
identical). Otherwise the larger block pool changes the indexer-score GEMM
shape and thus rounding only; padding the 1/n block pool alone reproduces the
new trajectory exactly. Float64 old vs new with padding: 7.7e-16.
@liangel-02
liangel-02 changed the base branch from qwen38-rl-3-ple to qwen3-8-fn-6-pipeline November 20, 2026 19:49
liangel-02 added a commit that referenced this pull request Nov 20, 2026
stack-info: PR: #6206, branch: qwen38-rl-4-recipe
@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to qwen38-rl-3-ple November 20, 2026 19:49
… slots

Row-sharded routing used torch.unique, copied per-owner counts to the host and
passed per-batch split lists into the lookup all-to-all, so its metadata and
collectives changed shape every batch and could not be replayed in a graph.

- prepare_row_sharded_embedding takes max_ids_per_owner: every requester
  sends each owner a fixed [C] slot of distinct IDs (sort + mask dedup), and
  both all-to-alls use equal splits. No count reaches the host.
- Each requester's slots carry a validity flag (IDs in range, within C);
  owners assert on all received flags, so invalid input still fails on every
  owner, now asynchronously.
- RowShardedEmbeddingMetadata is a registered pytree dataclass.
- Flash-Next derives C from its hash-head layout: each head owns a
  contiguous row range, so an owner receives at most min(T, overlap)
  distinct IDs per head, where overlap is how many of the head's rows it
  owns (released table at DP16/DP64: C = 4,508 at T = 4096, 16,796 at
  T = 16384).

Numerics: lookups, gradients and AdamW state match the dense reference
exactly in the CPU/Gloo tests; the FSDP2/EP2 integration matches 2/n at every
step.
With 2/n and 3/n, Flash-Next forward/backward has no host synchronization
and no batch-dependent shapes, so it can be captured and replayed as one
accelerator graph. This adds a test that guards that, and a recipe for the
released model.

- qwen38_flash_next_125b_dist_moe fine-tunes the released 125B-A6B decoder
  from its HF checkpoint on 16 GB300s: FSDP16 + EP16 with Dist-MoE,
  2M tokens per step (8 x 16K-token microbatches per rank, the per-GPU
  work of a 33.5M-token step on 256 GPUs), full remat, forward/backward as
  one accelerator graph, and the fused gated residual read override below.
  Measured (torch nightly 20261118): 378.5 TFLOPS/GPU, 15.14% MFU,
  243.4 GiB peak (steps 4-30); 418.2 TFLOPS/GPU (16.73%) with forced
  round-robin routing.
- Fused gated residual read (opt-in override in torchtitan_recipes/overrides,
  enabled by this recipe). GatedResidual's hc_norm runs as Triton kernels
  with a hand-written backward (the compiled backward fused the input
  gradient into a 16K-row column reduction, 0.73 ms per call), and its
  down [C -> R] and inject [C -> S] projections run as one GEMM (inject's
  [10240 -> 4] GEMM alone lands on slow sm80 kernels). Parameters and
  checkpoint keys are unchanged; config validation rejects projections or an
  hc_norm the fused path would bypass. Not bitwise: a GPU test bounds the output
  and every gradient within 2x eager's error against an fp64 golden. One
  call at T=16K, fwd+bwd under graph replay: 2.56 -> 1.52 ms; end to end
  304.8 -> 321.3 TFLOPS/GPU.
- Fused QSA indexer teacher (opt-in override, enabled by this recipe). The
  KL target (head-mean softmax over the selected tokens, max-pooled per
  block) gathered a [Q, J, H_kv, K] key copy, wrote fp32 logits and ran a
  separate softmax: 18.8 ms per layer per microbatch at 125B shapes.
  gather_attn already computes the softmax normalizer, so each token's
  probability does not depend on the rest of the selection. The override
  asks it for the log-sum-exp and computes head-summed probabilities densely
  per 64-query tile against the context window before it (tensor-core
  GEMMs, skipping key tiles before the tile's first selected token), then
  gathers and max-pools the selected blocks: 1.4-2.2 ms depending on
  document lengths. It targets QSAAttention.Config to read the indexer's
  RoPE context. Not bitwise: error against an fp64 golden 1.52e-7 vs
  1.21e-7 (its GPU test needs SM100 and runs in the B200 workflow). 5/n
  adds its TP path with the model's. End to end (natural routing, after
  1/n's indexer window) 335.1 -> 369.4 TFLOPS/GPU; loss at
  step 30 2.27438 vs 2.27436.
- GDN in_proj split (model code, every flavor). Flash-Next's GDN in_proj is a
  SplitLinear (q|k|v projection, z|a|b gates); SplitLinear interleaves the two
  GEMM outputs per key head only for the shared GDN to split them again.
  Flash-Next's linear-attention layers are now SplitInProjGDN (gdn.py, a GDN
  subclass in the model folder; the shared GDN is unchanged), which builds
  mixed_qkv, a, b and the gate straight from the two outputs, removing that
  ~540 MB copy and its backward split per layer call. Bitwise identical: a GPU
  test compares outputs and all gradients against the shared GDN, and the
  debug model's loss, grad_norm and indexer loss match the shared GDN bitwise
  over 10 steps (seed 42, deterministic).
  369.4 -> 378.5 TFLOPS/GPU (natural routing), 406.0 -> 418.2
  (round-robin), peak memory unchanged.
- Graph replay needs a fixed document capacity, so the recipe caps packed
  rows at 64 documents (twice c4_document_capacity's 16K estimate).
- A 0.5 Dist-MoE activation slot holds the full expert intermediates of
  about the first half of the MoE layers (decided per layer on device)
  instead of recomputing them: +2.9% throughput for ~45 GiB. Saving whole
  GDN blocks from remat (block_overrides) bought ~1% for 31.6 GiB and is
  not used.
- 125B-A6B-text flavor: the released decoder without the vision encoder.
  It loads from the multimodal checkpoint.
- B200 integration test: FSDP2 + EP2 with Dist-MoE and full remat captures
  forward/backward at step 3 and replays it at step 4 with a new document
  layout, so it fails on any host synchronization or batch-dependent shape.
  It has no golden yet: the B200 lane is red on main, so a B200 golden
  (checked bitwise against the same config run eagerly) follows once it runs
  again (TODO in the test).
Shard QSA heads and PLE feature columns over TP with sequence-parallel
residuals. The indexer teacher sums head probabilities across TP before
max pooling each block, and the TP-replicated indexer contributes its KL
gradient once. The PLE table becomes DP-row x TP-column owned.

- Text-only embeddings run in the global SPMD context so their output
  records the DP shard; only the vision path needs the DP-local context.
- SplitLinear splits gates by their fixed per-group width: the SPMD checker
  reads a passed size as global, which the local group count is not.
- TP runs with or without SP. TP-unsharded weights (grouped norms, residual
  mixer linears) take the TP type of their input: I without SP, R otherwise.
- Multimodal flavors run under TP: like Qwen3.5, the fused embeddings
  declare their DP x CP token sharding before replicate_to_residual, which
  otherwise fails typechecking.
- DistMuon does not support TP yet (#5678), so the DistMuon policy raises
  under TP.
- 4/n's fused teacher override gets the same TP path: its kernel writes
  per-token head sums, which are all-reduced over TP before block pooling,
  and the indexer KL is scaled by 1/TP like the parent's. Its unit test
  checks a simulated TP2 head split against the pooled single-rank result.
Non-final stages send all four residual streams; the final stage owns the
stream mixer, final norm and LM head. Every stage receives original token
IDs and document positions, and the first local model part prepares PLE
routing through a weak reference when an interleaved schedule puts the
table on a later local part.

- Static stage metadata. pipeline_llm takes an optional stage_io, and
  build_decoder_stage_io / DecoderStageIO become public. Flash-Next's
  pipeline_flash_next (pipeline_parallel.py) starts from core's decoder
  boundaries and declares the hidden
  boundary as [T, num_streams * D], so PyTorch skips its metadata-inference
  forward. That forward ran every stage on uninitialized hidden states,
  whose routing could collapse onto a few experts and overflow Dist-MoE's
  scratch. With declared boundaries, PP works with Dist-MoE, and stages
  build on fake process groups. A split the static metadata cannot describe raises.
- The rename duplicates #6049's; whichever lands second drops it.
- Remaining bans, at build time: zero-bubble and CSV schedules (under full
  remat the split weight-gradient pass reads the shared MoE routing remat
  region as an unrecomputed placeholder; TODO), multimodal flavors (TODO),
  and a stage split that separates the mixer, norm and LM head.
- The DistMuon policy now works under PP. OptimizersContainer built one
  optimizer per (model part, config) and raised when a pattern matched
  nothing in a part, but the policy's PLE Adam pattern matches only the
  part holding layers.1 and its DistMuon pattern misses a
  tok_embeddings-only part. The container now skips empty (part, config)
  pairs and raises only when a pattern matches nothing on every PP rank:
  one all-reduce over the PP group at build time, and the old local check
  without PP. A fake-PP process holds one stage and skips the check. DistMuon itself already ignores compute layouts for other
  stages and skips empty buckets.

Tests: B200 FSDP2+TP2+SP+EP4+PP2 (all-to-all, AdamW; DistMuon has no TP
support, so the text debug recipe takes an optimizer argument) and
FSDP2+EP2+PP2 with the DistMuon policy, Dist-MoE and accelerator graphs,
both Interleaved1F1B with full remat and PLE on a later local part. A
CPU test covers the container's skip-and-raise rule over two model
parts, with and without a PP group.

Numerics (GB300, seed 42, deterministic, shared seed checkpoint):
- FSDP2+TP2+EP4+PP2 against the same config without PP (4 accumulation
  microbatches instead of 4 PP microbatches, same data): step 1 identical
  (loss 7.73923, grad_norm 5.0487); later steps differ only by gradient
  summation order (step 10 loss 5.44578 vs 5.44624).
- Debug Dist-MoE PP tracks all-to-all PP on the same mesh: step-1 loss
  7.73953 vs 7.73918.
- The TP2+SP PP config passes. The 125B recipe at FSDP8+EP8+PP2 gets past
  stage setup, then runs out of memory at step 2 on the PLE-holding stage,
  as the memory model predicts.
## 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
<!-- 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
<!-- 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/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 model wrapper that feeds PLE its token IDs and positions is in #6206.

| 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
stack-info: PR: #6206, branch: qwen38-rl-4-recipe
from torchtitan.rl.generator.vllm.model_wrapper import VLLMModelWrapper


class VLLMFlashNextModelWrapper(VLLMModelWrapper):

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.

Instead, can we make VLLMModelWrapper general?

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