Repository navigation
Add vLLM paged QSA attention and graph metadata - #6201
Conversation
## 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
d39d5ff to
9e002ae
Compare
9e002ae to
b72c279
Compare
b72c279 to
333bc54
Compare
379f438 to
1168517
Compare
44ff156 to
ef6a85d
Compare
1168517 to
8c84f5f
Compare
ef6a85d to
8a50703
Compare
8c84f5f to
b725bdc
Compare
|
@claude review |
|
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 ( |
There was a problem hiding this comment.
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
- 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).
torchtitan/rl/generator/vllm/attention/qsa.py:14-- the builder and metadata come fromvllm.models.qwen4_exp, which looks like a fork module, with no TODO or upstream link. Implement them here or depend on upstream vLLM.torchtitan/rl/generator/vllm/attention/qsa.py:22-- with the pinned attn-gym 0.0.20, importingqsa.pyraises an ImportError instead of getting a placeholder. Bump the pin, update the install hint inattn_gym.py, and callrequire_attn_gymin__init__.torchtitan/rl/generator/vllm/attention/qsa.py:59--cudagraph_mode=NONEwithoutenforce_eageris rejected, although the error message says NONE is supported.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 hardcodedindex_block_size=4to the trainer'scompress_ratio=4check.torchtitan/rl/generator/vllm/attention/qsa.py:52-- renamenum_headstonum_kv_heads;query_THKuses the KV-head letterHfor query heads.torchtitan/rl/generator/vllm/attention/qsa.py:87-- buildFullAttentionSpec(...)directly instead of going through akwargsdict.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 thatviews()assumes (heads before tokens, K and V concatenated on the last dim)?QSAPagedBackenddoesn't defineget_kv_cache_shape, and the test builds the tensor by hand and callsbind_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 tomla.py,gdn.pyandkda.pyis consistent. The consumers (qsa_model.pyandple.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.pychanges 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 tailrange(count // 4 * 4, count)) matches the trainer'stail_count_T = local_counts_T.remainder(compress_ratio)inqwen3_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.
| from vllm.models.qwen4_exp.common.qsa_cache import ( | ||
| QSAForwardMetadata, | ||
| QSAMetadataBuilder, | ||
| ) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
| if ( | ||
| not config.model_config.enforce_eager | ||
| and config.compilation_config.cudagraph_mode | ||
| != CUDAGraphMode.FULL_DECODE_ONLY | ||
| ): |
There was a problem hiding this comment.
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:
| 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, |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
| pytest.importorskip( | ||
| "attn_gym.sparse.paged_decode", | ||
| reason="Paged QSA tests require Attention Gym paged sparse attention", | ||
| ) |
There was a problem hiding this comment.
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.yamlruns 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.
b6b75ef to
cefa057
Compare
|
@claude review |
|
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 |
There was a problem hiding this comment.
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
- PR description: "Summary (human-written)" is still empty. The author needs to fill it in.
- Still open:
torchtitan/rl/generator/vllm/attention/qsa.py:26. The description says pinnedattn-gym==0.0.20lackspaged_sparse_decode/PagedKV. With that version,_load_exportraisesAttributeError, so this import fails. #6202 importsqsa.pyfrommodel_wrapper.py/registry.py, so higher up the stack this breaks the whole vLLM generator import. Fix: bump the pin in.ci/docker/requirements.txtand the install hint inattn_gym.py:153(plus its assertions intest_optional_imports.py). Then callrequire_attn_gym(paged_sparse_decode, PagedKV)inPagedCache.__init__, asTorchTitanMLAImpldoes. - 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 theimportorskipand add the file to the B200 RL unit-test step next totest_vllm_mla_backends.py. Until then, nothing guards the reordered-pages and graph-replay invariants.
Should consider
qsa.py:124-- buildFullAttentionSpec(...)directly instead of through akwargsdict.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 thatviews()assumes?QSAPagedBackenddoesn't defineget_kv_cache_shape, and both tests make the tensor by hand and callbind_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 withmla.pyandlinear_attention.py. vLLM stays the owner of allocation. The builder relies only on genericAttentionMetadataBuilderandCommonAttentionMetadata, and makes no host syncs (max_query_lenis 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_reqsat capture. Replay is correct only if vLLM's runner padsseq_lenswith 0,query_start_locwith the real token total, andslot_mappingwith -1 for padded requests. The description says it does; the test simulates it. attn_gym.pychanges 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.
|
@claude review again, dont worry about attention gym pins |
|
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. |
There was a problem hiding this comment.
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
- 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-- buildFullAttentionSpec(...)directly instead of through akwargsdict.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 onlymetadata is Nonefor profile and dummy runs.
Questions
- Still unanswered: which vLLM code reshapes this layer's cache to the
[P, H, N, 2K]layout thatviews()assumes?QSAPagedBackenddoesn't defineget_kv_cache_shape, and both tests build the tensor by hand and callbind_kv_cache. Your TP2/EP2 generation run suggests the real allocation path works. A one-line comment onviews()that points to the vLLM code would make that visible to reviewers.
Details
- Resolved in earlier rounds: the
vllm.models.qwen4_expdependency (the builder now lives here),cudagraph_mode=NONEbeing rejected, thecompress_ratio=4link, and thenum_kv_heads/query_TQKrenames. attendbuilds 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. Readingquery_start_loc[-1]inside the graph picks up each step's real token count.- Replay is correct only if vLLM pads
seq_lenswith 0,query_start_locwith the real token total, andslot_mappingwith -1 (reshape_and_cache_flashskips 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.
372eeab to
6c78630
Compare
6c78630 to
343b112
Compare
343b112 to
9fb1004
Compare
## 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
|
Heads-up: this PR was merged into
|
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'spersistent runner buffers. vLLM already pads them for
FULL_DECODE_ONLYgraphs(zero lengths, null pages,
-1slots), so replay reads each step's requestlayout without extra copies. It only uses vLLM's generic backend and
CommonAttentionMetadatacontracts, likeTorchTitanLinearAttentionMetadataBuilder.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_decodeonce with vLLM'sper-request block table,
query_start_locandseq_lens. Decode-only stepskeep the host-bound call (
max_seqlen_q=1). Steps with prompt rows passmax_seqlen_q=Noneandcausal_topk=True(the paged lightning indexer'soutput 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):gather_attncausal_topkAdd
torchtitan/rl/generator/local_compile.pywith two sharedlocal_compileregion names for generator-only functions,INFERENCE_BATCH_INVARIANT_REGIONandINFERENCE_BATCH_VARIANT_REGION;inference_local_compile(batch_invariant=...), which registers a functionunder the matching one; and
inference_regions(), which returns the regionsthat 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.pyis 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
FULL_DECODE_ONLYdecode replays QSA attentionTesting
pytest -q tests/rl/unit_tests/gpu/test_vllm_qsa.pyThe 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; thetraining-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.20alone does not supply these APIs. No GDN/KDA migration is included.The complete stack passed
pre-commit run --all-files. A deterministic seed-42BF16 debug-model forward/backward (32 tokens) was compared against
44ff1567196fe91ba8a8f96a1aeefbc6715dda8c: loss4.4367218017578125, gradientnorm
22.315799713134766, logits, and all 192 parameter gradients were bitwiseidentical using
torch.equal. This is one-GPU training evidence, not arepresentative-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.