Skip to content

Add vLLM paged QSA attention and graph metadata - #6201

Merged
wwwjn merged 1 commit into
liangel-02/stack/32from
qwen38-rl-1-generator
Nov 23, 2026
Merged

wwwjn merged 1 commit into
liangel-02/stack/32from
qwen38-rl-1-generator

Conversation

@liangel-02

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

Copy link
Copy Markdown
Contributor

Stacked PRs:


Add vLLM paged QSA attention and graph metadata

Summary (human-written)

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
    (make paged_sparse_decode cudagraphable 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 Integrate the paged lightning indexer with compressed QSA caches #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.

## 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
@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 force-pushed the qwen38-rl-1-generator branch from d39d5ff to 9e002ae Compare November 19, 2026 01:38
@liangel-02
liangel-02 force-pushed the qwen38-rl-1-generator branch from 9e002ae to b72c279 Compare November 19, 2026 01:55
@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to main November 19, 2026 04:31
@liangel-02
liangel-02 force-pushed the qwen38-rl-1-generator branch from b72c279 to 333bc54 Compare November 19, 2026 04:31
@liangel-02
liangel-02 changed the base branch from main to qwen3-8-fn-6-pipeline November 19, 2026 04:35
@liangel-02
liangel-02 force-pushed the qwen38-rl-1-generator branch 2 times, most recently from 379f438 to 1168517 Compare November 19, 2026 05:29
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-6-pipeline branch from 44ff156 to ef6a85d Compare November 19, 2026 05:42
@liangel-02
liangel-02 force-pushed the qwen38-rl-1-generator branch from 1168517 to 8c84f5f Compare November 19, 2026 06:09
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-6-pipeline branch from ef6a85d to 8a50703 Compare November 19, 2026 06:09
@liangel-02
liangel-02 force-pushed the qwen38-rl-1-generator branch from 8c84f5f to b725bdc Compare November 19, 2026 06:27
@liangel-02

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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


Request changes: the QSA metadata builder comes from what looks like a vLLM-fork module (vllm.models.qwen4_exp), and paged_sparse_decode needs an attn-gym newer than the pinned 0.0.20. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Request changes -- the graph-metadata half of this PR comes from a module that appears to exist only in a vLLM fork, and the attention kernel needs an unreleased attn-gym, so neither can be imported or tested against the pinned dependencies.

What this PR does. It adds PagedCache, a vLLM attention layer with no parameters. vLLM allocates a FullAttentionSpec KV cache for it. Each step it writes K/V with reshape_and_cache_flash, then calls Attention Gym's paged_sparse_decode with the selected 4-token block IDs, which also covers the causal tail of the current incomplete block. Rows past query_start_loc[-1] (graph padding) are set to zero. The metadata builder (QSAMetadataBuilder) is imported from vllm.models.qwen4_exp, not added here.

Example. A request of 11 tokens whose last token selects block 0:

blocks_TB[t] = [0]
logical tokens read: [0,1,2,3] (block 0) + [8,9,10] (incomplete tail)
physical slots:      block_table[req, pos // 16] * 16 + pos % 16
before: no paged QSA layer in the vLLM generator
after:  PagedCache.attend reads those 7 slots from vLLM's pages; padded rows return 0

Must fix

  1. The PR description: "Summary (human-written)" is empty. "What changed" lists "Stage stable decode metadata for graph replay", but that code isn't in this diff (see 2).
  2. torchtitan/rl/generator/vllm/attention/qsa.py:14 -- the builder and metadata come from vllm.models.qwen4_exp, which looks like a fork module, with no TODO or upstream link. Implement them here or depend on upstream vLLM.
  3. torchtitan/rl/generator/vllm/attention/qsa.py:22 -- with the pinned attn-gym 0.0.20, importing qsa.py raises an ImportError instead of getting a placeholder. Bump the pin, update the install hint in attn_gym.py, and call require_attn_gym in __init__.
  4. torchtitan/rl/generator/vllm/attention/qsa.py:59 -- cudagraph_mode=NONE without enforce_eager is rejected, although the error message says NONE is supported.
  5. tests/rl/unit_tests/gpu/test_vllm_qsa.py:15 -- the test always skips and isn't in any workflow. Remove the skip and add it to the B200 RL unit-test step.

Should consider

  • torchtitan/rl/generator/vllm/attention/qsa.py:130 -- tie the hardcoded index_block_size=4 to the trainer's compress_ratio=4 check.
  • torchtitan/rl/generator/vllm/attention/qsa.py:52 -- rename num_heads to num_kv_heads; query_THK uses the KV-head letter H for query heads.
  • torchtitan/rl/generator/vllm/attention/qsa.py:87 -- build FullAttentionSpec(...) directly instead of going through a kwargs dict.
  • torchtitan/rl/generator/vllm/attention/qsa.py:119 -- metadata.seq_lens.numel() == 0: can vLLM build metadata with zero requests? If not, drop that branch.

Questions

  • What code produces the [P, H, N, 2K] page layout that views() assumes (heads before tokens, K and V concatenated on the last dim)? QSAPagedBackend doesn't define get_kv_cache_shape, and the test builds the tensor by hand and calls bind_kv_cache. That means vLLM's real allocation and reshape path for this layer is never exercised.
Details
  • Design check: the RL generator has to own a QSA-aware paged reader because vLLM can't read this sparse selection. Putting it under rl/generator/vllm/attention/ next to mla.py, gdn.py and kda.py is consistent. The consumers (qsa_model.py and ple.py) arrive in #6202 and #6203. I don't see a design objection to the approach. The blocker is that its main dependencies (QSAMetadataBuilder, paged_sparse_decode) aren't available from pinned or released packages, so the graph-replay staging can't be reviewed or run in CI.
  • The attn_gym.py changes are mechanical export plumbing. They are fine once the pin bump exists.
  • #6202 also imports vllm.models.qwen4_exp.nvidia.ops.qsa, so the dependency on the vLLM fork grows further up the stack.
  • The reference in test_paged_qsa_mixed_queries_tail_and_padding (block 0, plus tail range(count // 4 * 4, count)) matches the trainer's tail_count_T = local_counts_T.remainder(compress_ratio) in qwen3_8_flash_next/attention.py.

Not verified: whether the pinned vLLM nightly contains vllm.models.qwen4_exp and AttentionLayerBase.bind_kv_cache (vLLM couldn't be imported in this job). No GPU tests were run.

Comment on lines +14 to +17
from vllm.models.qwen4_exp.common.qsa_cache import (
QSAForwardMetadata,
QSAMetadataBuilder,
)

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.

The metadata builder and forward metadata come from vllm.models.qwen4_exp.common.qsa_cache. Upstream vLLM keeps models under vllm.model_executor.models, and nothing else in the repo imports a vllm.models.* module, so this looks like it needs a private vLLM build, not the nightly pinned in scripts/install_rl_env.sh (unverified: I couldn't import vLLM in this job).

That has two consequences:

  • The PR title and the "Stage stable decode metadata for graph replay" bullet describe code that isn't in this diff. The padding/replay staging that the graph test exercises lives in QSAMetadataBuilder, so reviewers can't see it.
  • The RL generator would import a model-specific module from a vLLM fork, with no TODO or link.

Fix: either implement the builder here the way TorchTitanMLAMetadataBuilder (mla.py) and TorchTitanLinearAttentionMetadataBuilder (linear_attention.py) do, or link the upstream vLLM PR, bump the vLLM pin once it lands, and add a TODO. Either way, update the description.

from vllm.v1.attention.backends.fa_utils import reshape_and_cache_flash
from vllm.v1.kv_cache_interface import FullAttentionSpec

from torchtitan.models.common.attn_gym import paged_sparse_decode, PagedKV

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.

With the pinned attn-gym[linear,cudnn]==0.0.20 (.ci/docker/requirements.txt), attn_gym.sparse imports fine but has no paged_sparse_decode/PagedKV. In attn_gym._load_export, getattr then raises AttributeError instead of returning a placeholder, so this from ... import fails when qsa.py is imported. And the install hint in _raise_for still points at 0.0.20, which doesn't have these APIs.

Fix: land this together with an attn-gym pin bump to a release that ships these APIs, and update the hint in attn_gym.py too. Then call require_attn_gym(paged_sparse_decode, PagedKV) in PagedCache.__init__, as TorchTitanMLAImpl.__init__ does, so a missing backend fails at build time and not in the first vLLM profile run.

Comment on lines +59 to +63
if (
not config.model_config.enforce_eager
and config.compilation_config.cudagraph_mode
!= CUDAGraphMode.FULL_DECODE_ONLY
):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This check rejects cudagraph_mode=NONE when enforce_eager=False, but the error message says NONE is supported. A user who turns off graphs through the compilation config gets a contradictory error. Allow both modes:

Suggested change
if (
not config.model_config.enforce_eager
and config.compilation_config.cudagraph_mode
!= CUDAGraphMode.FULL_DECODE_ONLY
):
if (
not config.model_config.enforce_eager
and config.compilation_config.cudagraph_mode
not in (CUDAGraphMode.NONE, CUDAGraphMode.FULL_DECODE_ONLY)
):

metadata.query_start_loc,
metadata.seq_lens,
max_seqlen_q=metadata.max_query_len,
index_block_size=4,

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.

4 is the trainer's compress_ratio. The training model enforces it with raise ValueError("Flash-Next QSA requires compress_ratio=4") in qwen3_8_flash_next/attention.py. Add a short comment that points there, or pass compress_ratio in from the consumer. Otherwise a future flavor with a different ratio would make the generator read the wrong tail tokens without any error.


supports_dcp = False

def __init__(self, *, prefix: str, num_heads: int, head_dim: int):

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.

num_heads is the KV head count: it feeds FullAttentionSpec(num_kv_heads=...), and the test passes num_heads=2 with 4 query heads. Rename it num_kv_heads to match vLLM. On the same point, the legend defines H as KV heads, yet query_THK in attend has query heads. Give query heads their own letter, e.g. query_TQK.

Comment on lines +15 to +18
pytest.importorskip(
"attn_gym.sparse.paged_decode",
reason="Paged QSA tests require Attention Gym paged sparse attention",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This test never runs in CI:

  • With the pinned attn-gym 0.0.20 this guard always skips.
  • The file isn't listed in any workflow. integration_test_rl_b200.yaml runs an explicit list of GPU tests, e.g. test_vllm_mla_backends.py.

Once the dependencies are available, remove the skip and add this file to the B200 RL unit-test step. Otherwise the reordered-pages and replay invariants it checks have no guard.

@liangel-02
liangel-02 force-pushed the qwen38-rl-1-generator branch 2 times, most recently from b6b75ef to cefa057 Compare November 19, 2026 07:43
@liangel-02

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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


Request changes: the vLLM-fork dependency is gone, but the kernel still needs an attn-gym newer than the pinned 0.0.20, so qsa.py can't be imported with that version and its test always skips. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Request changes -- the vLLM-fork dependency is gone, but the kernel still needs an attn-gym release newer than the pinned 0.0.20. With the pinned version qsa.py can't be imported, and its only test always skips.

What this PR does. It adds PagedCache, a vLLM layer with no parameters, which stores K/V in a FullAttentionSpec cache that vLLM allocates. The PR also adds QSAPagedMetadataBuilder, which hands back views of vLLM's CommonAttentionMetadata buffers: block table cut to max_num_pages columns, query_start_loc and seq_lens cut to num_reqs. Because these are views, FULL_DECODE_ONLY replay reads each step's request layout without copies. attend writes K/V with reshape_and_cache_flash, calls paged_sparse_decode with index_block_size=4, and zeroes the rows past query_start_loc[-1].

Example.

request: 11 tokens, last token selects block 0
read:    positions [0,1,2,3] + tail [8,9,10]
slot:    block_table[req, pos // 16] * 16 + pos % 16
graph:   captured with 4 requests; replay after vLLM rewrites
         the buffers in place to 2 requests -> rows 2,3 have seq_len 0, output 0

Resolved since the last review: the vllm.models.qwen4_exp import (the builder now lives in this file), cudagraph_mode=NONE is allowed, the compress_ratio=4 link is commented, and the num_kv_heads / query_TQK renames are in.

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author needs to fill it in.
  2. Still open: torchtitan/rl/generator/vllm/attention/qsa.py:26. The description says pinned attn-gym==0.0.20 lacks paged_sparse_decode/PagedKV. With that version, _load_export raises AttributeError, so this import fails. #6202 imports qsa.py from model_wrapper.py/registry.py, so higher up the stack this breaks the whole vLLM generator import. Fix: bump the pin in .ci/docker/requirements.txt and the install hint in attn_gym.py:153 (plus its assertions in test_optional_imports.py). Then call require_attn_gym(paged_sparse_decode, PagedKV) in PagedCache.__init__, as TorchTitanMLAImpl does.
  3. Still open: tests/rl/unit_tests/gpu/test_vllm_qsa.py:15. With the pinned attn-gym the test always skips, and no workflow runs it. Once (2) lands, remove the importorskip and add the file to the B200 RL unit-test step next to test_vllm_mla_backends.py. Until then, nothing guards the reordered-pages and graph-replay invariants.

Should consider

  • qsa.py:124 -- build FullAttentionSpec(...) directly instead of through a kwargs dict.
  • qsa.py:156 -- seq_lens.numel() == 0: if vLLM never builds metadata with zero requests, delete that branch.

Questions

  • Still unanswered: what produces the [P, H, N, 2K] page layout that views() assumes? QSAPagedBackend doesn't define get_kv_cache_shape, and both tests make the tensor by hand and call bind_kv_cache. vLLM's real allocate-and-reshape path for this layer never runs in a test.
Details
  • Design: owning a QSA-aware paged reader in rl/generator/vllm/attention/ is consistent with mla.py and linear_attention.py. vLLM stays the owner of allocation. The builder relies only on generic AttentionMetadataBuilder and CommonAttentionMetadata, and makes no host syncs (max_query_len is already a Python int). I have no design objection.
  • Graph replay: the slices are views of the runner's persistent buffers, and their shapes are fixed by the padded num_reqs at capture. Replay is correct only if vLLM's runner pads seq_lens with 0, query_start_loc with the real token total, and slot_mapping with -1 for padded requests. The description says it does; the test simulates it.
  • attn_gym.py changes are mechanical export plumbing.

Not verified: that the pinned vLLM nightly has KVCacheSpec.max_num_blocks_per_req and AttentionLayerBase.bind_kv_cache, and that it pads FULL-graph metadata as described. vLLM couldn't be inspected in this job, and no GPU tests were run.

@liangel-02

Copy link
Copy Markdown
Contributor Author

@claude review again, dont worry about attention gym pins

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @liangel-02's task in 1m 34s —— View job


Approve, with items to address before merging: with the attn-gym pin out of scope, the only must-fix left is filling in the human-written summary. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. At your request, the attn-gym pin is out of scope here. Without it, nothing blocking remains. No new commits since the last review (HEAD is still cefa057). This decision rests on code I already reviewed plus your end-to-end validation. A maintainer still needs to review, since the PR touches models/common/attn_gym.py.

What this PR does. It adds PagedCache, a vLLM layer with no parameters, which holds K/V in a FullAttentionSpec cache that vLLM allocates. It also adds QSAPagedMetadataBuilder, which returns views of vLLM's persistent CommonAttentionMetadata buffers so that FULL_DECODE_ONLY replay reads each step's layout. attend writes K/V with reshape_and_cache_flash, calls paged_sparse_decode with index_block_size=4, and zeroes the rows past query_start_loc[-1].

Example.

request: 11 tokens, last token selects block 0
read:    positions [0,1,2,3] + tail [8,9,10]
slot:    block_table[req, pos // 16] * 16 + pos % 16
graph:   captured with 4 requests; vLLM rewrites the buffers in place to 2 requests
         -> replay reads the new tables/lengths, rows 2,3 have seq_len 0 -> output 0

Waived for this PR: the attn-gym pin bump and require_attn_gym. The test's importorskip and adding test_vllm_qsa.py to the B200 RL unit-test step follow from the pin. Until both land, CI doesn't check the reordered-pages and graph-replay invariants.

Must fix

  1. PR description: "Summary (human-written)" is still empty. Only the author can fill it in.

Should consider

  • torchtitan/rl/generator/vllm/attention/qsa.py:124 -- build FullAttentionSpec(...) directly instead of through a kwargs dict.
  • torchtitan/rl/generator/vllm/attention/qsa.py:157 -- metadata.seq_lens.numel() == 0: if vLLM never builds metadata with zero requests, delete this branch. Keep only metadata is None for profile and dummy runs.

Questions

  • Still unanswered: which vLLM code reshapes this layer's cache to the [P, H, N, 2K] layout that views() assumes? QSAPagedBackend doesn't define get_kv_cache_shape, and both tests build the tensor by hand and call bind_kv_cache. Your TP2/EP2 generation run suggests the real allocation path works. A one-line comment on views() that points to the vLLM code would make that visible to reviewers.
Details
  • Resolved in earlier rounds: the vllm.models.qwen4_exp dependency (the builder now lives here), cudagraph_mode=NONE being rejected, the compress_ratio=4 link, and the num_kv_heads / query_TQK renames.
  • attend builds the valid-row mask on every call, not in the builder. That is the right place for it: the builder runs outside the captured graph, so a mask built there would be stale on replay. Reading query_start_loc[-1] inside the graph picks up each step's real token count.
  • Replay is correct only if vLLM pads seq_lens with 0, query_start_loc with the real token total, and slot_mapping with -1 (reshape_and_cache_flash skips negative slots). The graph test simulates this.

Not verified: the pinned vLLM nightly's max_num_blocks_per_req, bind_kv_cache, the KV reshape path, and its FULL-graph padding. vLLM couldn't be inspected in this job, and no GPU tests were run.

@liangel-02
liangel-02 changed the base branch from qwen3-8-fn-6-pipeline to main November 19, 2026 21:08
@liangel-02
liangel-02 force-pushed the qwen38-rl-1-generator branch from 372eeab to 6c78630 Compare November 20, 2026 22:10
@liangel-02
liangel-02 marked this pull request as ready for review November 20, 2026 22:11
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
@liangel-02
liangel-02 marked this pull request as draft November 20, 2026 22:51
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
@liangel-02
liangel-02 marked this pull request as ready for review November 20, 2026 22:51
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
@liangel-02
liangel-02 marked this pull request as draft November 20, 2026 22:56
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
@liangel-02
liangel-02 marked this pull request as ready for review November 20, 2026 22:56
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
Comment thread torchtitan/distributed/local_compile.py Resolved
Comment thread torchtitan/distributed/local_compile.py Resolved
@liangel-02
liangel-02 marked this pull request as draft November 20, 2026 23:10
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
@liangel-02
liangel-02 force-pushed the qwen38-rl-1-generator branch from 6c78630 to 343b112 Compare November 20, 2026 23:11
@liangel-02
liangel-02 marked this pull request as ready for review November 20, 2026 23:11
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
@liangel-02
liangel-02 marked this pull request as draft November 20, 2026 23:23
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
@liangel-02
liangel-02 force-pushed the qwen38-rl-1-generator branch from 343b112 to 9fb1004 Compare November 20, 2026 23:23
@liangel-02
liangel-02 marked this pull request as ready for review November 20, 2026 23:23
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Nov 21, 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

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 02f9eb94 in BF16 Dist-MoE TP2/EP2 + SP,
both eager and FULL_DECODE_ONLY, on both ranks. Full pre-commit checks pass.

stack-info: PR: pytorch/torchtitan#6201, branch: qwen38-rl-1-generator
@wwwjn

wwwjn commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Heads-up: this PR was merged into liangel-02/stack/32 instead of main (its base was not retargeted after #6316 landed), so the change is not on main yet. I'll follow up and land it into main. Two things first:

  1. Wrong base branch. We'll turn the whole stack (Add vLLM paged QSA attention and graph metadata #6201, Integrate the paged lightning indexer with compressed QSA caches #6202, Add cached PLE support to Flash-Next generation #6203, Connect Flash-Next generation and add a debug RL recipe #6308, Drop the GDN in_proj split copy and per-step casts in the Flash-Next vLLM generator #6305) into a GitHub stack first, so each PR targets the right base and retargets to main as the PR below it lands.
  2. Wait for attention-gym. This PR needs make paged_sparse_decode cudagraphable meta-pytorch/attention-gym#979 (causal_topk for paged_sparse_decode); without it this PR's RL 1 GPU tests fail with TypeError: paged_sparse_decode() got an unexpected keyword argument 'causal_topk'. Integrate the paged lightning indexer with compressed QSA caches #6202 needs Add paged lightning indexer reference and cache contract meta-pytorch/attention-gym#959 (and [WIP] N*G Triton group gemm for MoE  #960 for the fused indexer). Once these land, we bump the attn-gym pin in .ci/docker/requirements.txt and merge.

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