Repository navigation
[RL] Fix varlen RL on ROCm by gathering the paged KV cache - #4866
yuxinwan-amd wants to merge 1 commit into
Conversation
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows. |
1 similar comment
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows. |
5127b0d to
9ede108
Compare
…elper Two independent audits confirmed the in-loop generator profiling mechanism (Controller.Config.profile_at_step, start_profiling/stop_profiling actor endpoints + fanout, VLLMGenerator.Config.enable_profiling/ProfilerConfig wiring) never produced a working trace -- three variants of triggering Kineto capture from inside a Monarch actor all crash on this stack (torch nightly + vLLM + Monarch + ROCm gfx950). The only mechanism that actually captured a generator trace is the standalone rl/generate.py script, which has no Monarch actor at all. Reverting the dead plumbing rather than leaving code that looks like a working symmetric counterpart to --trainer.profiler.enable-profiling but crashes on use. Also: extract vllm_attention_backend() (the real, load-bearing ROCm fix, ports PR pytorch#4866) out of duplicated copies in generate.py and generator.py into a single shared torchtitan/rl/attention_backend.py. Drop the unused --warmup flag in generate.py and trim a debugging-history docstring down to the invariant it actually needs to state. Remove the duplicate Dockerfile copy under rishi_experiments/ (repo root copy is canonical, matches the handbook build command). Co-Authored-By: Claude Sonnet 5 <[email protected]>
9ede108 to
8741ce7
Compare
| the head sizes it supports and falls back when either does not hold. The | ||
| consequence is that a ROCm generator attends with a different kernel from | ||
| its trainer, so trainer/generator log-prob parity is a property to measure | ||
| rather than one the shared model definition supplies. |
There was a problem hiding this comment.
Breaking "unified model" implicitly sounds not right. Maybe what you really want to have is a rocm-vllm replacement of VLLMEngine in this file.
ccddc90 to
aeecdda
Compare
|
@claude please review |
|
Claude finished @felipemello1's task in 3m 40s —— View job Request changes -- review posted: the description describes the old |
There was a problem hiding this comment.
Verdict: Request changes -- the code was rewritten but the description wasn't, and the new design's main claim (the generator runs the trainer's kernel) doesn't hold in-repo.
What this PR does (at aeecdda). On ROCm, CUSTOM now picks a new AiterVarlenInnerAttentionImpl. It copies each sequence's paged KV into contiguous rows (_gather_paged_kv) and calls aiter.flash_attn_varlen_func. While a CUDA graph is being captured, every sequence is padded to the full block-table width so tensor shapes stay fixed. The base impl is split into _activate_flash_attention_impl and _attend hooks, and the use_cascade assert is removed.
Example. rl_grpo_qwen3_0_6b_varlen on MI355X:
main: CUSTOM -> TorchTitanVarlenInnerAttentionImpl -> AssertionError: FlashAttention version not detected
this PR: CUSTOM -> AiterVarlenInnerAttentionImpl -> gather pages -> aiter varlen
trainer still: torch varlen_attn -> torch's ROCm flash backend (AOTriton/CK)
Must fix
- The description is stale. It describes returning
Nonefrom avllm_attention_backend()helper inengine.py/generate.py. That code isn't in the PR, so the verification and log-prob table cover code that no longer exists. Rewrite it for this design and re-measure. - @tianyu-l's comment (no unified model) is only partly addressed. The model and the
CUSTOMbackend are shared again, but the kernel still differs from the trainer's.attention.py:394-401: no "AITER override" exists in torchtitan. A smaller alternative: run torchvarlen_attn_outon the gathered K/V. That needs noaiterdependency. attention.py:141-147-- two device-to-host syncs per layer per eager forward. Build the gather indices once per forward.attention.py:124-140-- the capture path, which is the default FULL-graph decode path, copiesnum_seqs * max_model_lenK/V rows per layer. Memory and throughput are unmeasured.- Removing the
use_cascadeassert (old line 204) changes the CUDA path, and the PR doesn't explain why. attention.py:66-69-- the DiffKV backend on ROCm still hits the old assert.attention.py:367-376-- add a TODO with a pytorch/pytorch issue link for ROCm varlenblock_tablesupport. The no-op hook only exists to silence a warning.
Should consider
test_vllm_wrapper.py:466-499-- two tests duplicate the parametrized one.
Questions
- Does aiter's varlen
lseuse the same(H, T)layout as torch's?out_transformassumes it.
Not verified: kernel identity on ROCm, the memory figures, aiter's API behaviour (no GPU or aiter here). A maintainer still needs to review.
| @@ -201,8 +258,6 @@ def forward( | |||
| "fp8" | |||
| ), "FP8 KV cache not supported yet." | |||
|
|
|||
| assert not attn_metadata.use_cascade, "Cascade not supported yet." | |||
There was a problem hiding this comment.
Removing this assert changes the CUDA path too (TorchTitanVarlenInnerAttentionImpl.forward), not just ROCm. The PR doesn't explain why. If cascade metadata now reaches this impl, it ignores the prefix/suffix split. That is only correct if seq_lens/block_table always cover the full context when use_cascade=True. Please restore the assert, or explain in the PR why the impl is correct under cascade, as its own change.
| def get_impl_cls(): | ||
| if torch.version.hip is not None: | ||
| return AiterVarlenInnerAttentionImpl | ||
| return TorchTitanVarlenInnerAttentionImpl |
There was a problem hiding this comment.
Only TorchTitanVarlenInnerAttentionBackend gets the ROCm branch. TorchTitanVarlenInnerAttentionDiffKVBackend.get_impl_cls still returns TorchTitanVarlenInnerAttentionDiffKVImpl on ROCm, so a model with value_head_dim != head_dim still reaches the vllm_flash_attn_version assert, now inside _attend. Either give the DiffKV backend the same branch, or raise a ValueError at engine build time for ROCm + unequal K/V.
| class AiterVarlenInnerAttentionImpl(TorchTitanVarlenInnerAttentionImpl): | ||
| """The ROCm half of CUSTOM: same model, same kernel, no page table. | ||
|
|
||
| torch's ROCm varlen kernel refuses a paged KV cache outright, and no ROCm | ||
| varlen entry point accepts one today, so this gathers the pages into | ||
| contiguous rows and runs the kernel the trainer runs. | ||
| """ | ||
|
|
||
| def _activate_flash_attention_impl(self) -> None: | ||
| """No-op: aiter selects its own kernel, and torch ships no ROCm FA3/FA4.""" |
There was a problem hiding this comment.
Two small things on this class:
- The whole class works around torch's ROCm varlen rejecting
block_table. Per the repo rules, an upstream gap needs aTODOwith a pytorch/pytorch issue link, so it is removed once torch supports paged KV on ROCm. - The
_activate_flash_attention_implhook (and the base-class restructure that adds it) only exists to make this no-op. On ROCmget_cuda_flash_attention_impl()already returnsNone, so the base just logs the "falling back to FA2" warning. Correcting that warning for ROCm in the base, without the override, would remove the hook and the unrelated diff in__init__.
| def test_gather_paged_kv_shape_is_fixed_while_capturing(monkeypatch): | ||
| # A CUDA graph replays with different context lengths in the same buffers, | ||
| # so under capture nothing about the gather's shape may depend on them. | ||
| _capturing(monkeypatch, True) | ||
| page_size, num_kv_heads, head_dim = 16, 2, 8 | ||
| block_table = torch.arange(3 * 4).view(3, 4).to(torch.int32) | ||
| key_cache, value_cache = _paged_cache(12, page_size, num_kv_heads, head_dim) | ||
|
|
||
| shapes = set() | ||
| for seq_lens in ([1, 1, 1], [64, 64, 64], [5, 40, 63]): | ||
| key, _, cu_padded = _gather_paged_kv( | ||
| key_cache, | ||
| value_cache, | ||
| block_table, | ||
| torch.tensor(seq_lens, dtype=torch.int32), | ||
| ) | ||
| shapes.add((tuple(key.shape), tuple(cu_padded.tolist()))) | ||
|
|
||
| assert len(shapes) == 1 | ||
|
|
||
|
|
||
| def test_gather_paged_kv_packs_only_the_live_context(monkeypatch): | ||
| # Outside capture the gather must move the context, not the whole table. | ||
| _capturing(monkeypatch, False) | ||
| page_size, num_kv_heads, head_dim = 16, 2, 8 | ||
| block_table = torch.arange(2 * 8).view(2, 8).to(torch.int32) | ||
| key_cache, value_cache = _paged_cache(16, page_size, num_kv_heads, head_dim) | ||
|
|
||
| key, _, _ = _gather_paged_kv( | ||
| key_cache, value_cache, block_table, torch.tensor([20, 3], dtype=torch.int32) | ||
| ) | ||
|
|
||
| assert key.shape[0] == 23 | ||
|
|
There was a problem hiding this comment.
These two tests duplicate test_gather_paged_kv_reproduces_each_sequence, which already asserts key.shape[0] == sum(seq_lens) when not capturing and cu_padded == i * stride when capturing, across three length sets. If fixed shape under capture is the invariant to keep, add one key.shape assertion to the parametrized test and delete both of these.
4583fa0 to
149e69b
Compare
`vllm_attention_backend` names CUSTOM for every varlen model on every platform,
but on ROCm CUSTOM cannot run: it attends over vLLM's paged KV cache, and
torch's ROCm varlen kernel refuses a page table outright.
RuntimeError: [ROCm] mha_varlen_fwd: block_table_ must be nullopt
Gather each sequence's pages into contiguous rows and the page table is no
longer needed. The gathered rows go to the same AOTriton varlen kernel the
trainer runs, so CUSTOM keeps its point: one model definition, one kernel.
Two details make that work.
Bottom-right causal. A decode query sits at the end of its sequence, so the
mask must be aligned per sequence -- `k_len - q_len` differs across a batch
that mixes prefill and decode. AOTriton spells this as
`WindowValue::BottomRightAligned`, which ROCm's `calculate_swa` installs only
when no explicit window is given. `varlen_attn`'s causal branch always sends
`window_size_right=0`, which overwrites the sentinel and degrades the mask to
top-left, so this calls `torch.ops.aten._flash_attention_forward` directly. A
sliding window cannot be combined with bottom-right alignment today, so those
layers raise; unequal K/V head dims raise for the same reason.
Fixed-stride rows. Packing would need the batch's total context length on the
host -- a sync per layer, and unreadable during a CUDA graph capture. Rows are
laid out at a fixed stride instead and `seqused_k` carries the real lengths, so
the kernel never reads the padding. Under capture the stride is the whole block
table; otherwise it is the batch's own longest context.
Also drops `assert not attn_metadata.use_cascade`: vLLM removed the field, so
the assert raises AttributeError on every call rather than checking anything.
Mask checked against an explicit bottom-right reference (max |err|, bf16):
decode-only 2.4e-03, prefill-only 7.0e-03, extend 2.9e-03, mixed 7.5e-03, mixed
at a fixed stride 7.8e-03. With `varlen_attn`'s `(-1, 0)` instead of the
sentinel the mixed cases are off by 3.2.
Cost. 8x MI355X, Qwen3-0.6B alphabet-sort GRPO, trainer TP=2 / generator TP=4,
10 steps:
leg decode_ms logprob_diff/max peak mean
before (deferring to vLLM) 212.2 11.67 3.75
this change 837.9 9.09 2.84
Attention itself is ~20us; the rest is the gather, which runs at ~12% of HBM
bandwidth. Five runs of the gathered path peaked at 4.70, 6.64, 6.53, 8.46 and
9.09 with means of 2.55 to 3.19, so the spread on the peak is about +-2 and
parity should be read as "no worse". The baseline row predates this branch's
rebase, so the decode_ms column compares across upstream changes to the weight
sync path as well; `main` cannot be measured here because it raises in
attention before reaching a step.
149e69b to
a1d4a7c
Compare
Problem
vllm_attention_backendnamesCUSTOMfor every varlen model on everyplatform.
CUSTOMis the generator's own varlen backend -- it computes with thekernel the trainer computes with, which is what makes one model definition valid
on both sides.
On ROCm it cannot run.
CUSTOMattends over vLLM's paged KV cache, and torch'sROCm varlen kernel refuses a page table outright:
An inherited assert (
FlashAttention version not detected) fires first, but itis only a symptom: vLLM detects no flash-attn version on ROCm, and
CUSTOMnever calls vLLM's flash-attn anyway.
Fix
Gather each sequence's pages into contiguous rows; the page table is then not
needed. The gathered rows go to the same AOTriton varlen kernel the trainer
runs, so
CUSTOMkeeps its point.Two details make that work.
Bottom-right causal. A decode query sits at the end of its sequence, so the
mask must be aligned per sequence --
k_len - q_lendiffers across a batch thatmixes prefill and decode. AOTriton spells this as
WindowValue::BottomRightAligned, which ROCm'scalculate_swainstalls onlywhen no explicit window is given.
varlen_attn's causal branch always sendswindow_size_right=0, which overwrites the sentinel and degrades the mask totop-left, so this calls
torch.ops.aten._flash_attention_forwarddirectly. Asliding window cannot be combined with bottom-right alignment today, so those
layers raise. Unequal K/V head dims raise for the same reason.
Fixed-stride rows. Packing would need the batch's total context length on
the host -- a sync per layer, and unreadable during a CUDA graph capture. Rows
are laid out at a fixed stride instead and
seqused_kcarries the real lengths,so the kernel never reads the padding. Under capture the stride is the whole
block table; otherwise it is the batch's own longest context.
Also drops
assert not attn_metadata.use_cascade: vLLM removed the field, so oncurrent vLLM the assert raises
AttributeErroron every call rather thanchecking anything.
User-facing change
AssertionErrorat the first attention callAssertionErrorNotImplementedErrornaming the gapAssertionErrorValueErrornaming the gapNumerics and cost
8x MI355X (gfx950), ROCm 10.0, torch 2.16.0.dev20261009+rocm10.0,
rl_grpo_qwen3_0_6b_varlen, trainer TP=2 / generator TP=4, 10 steps.logprob_diff/maxpeakROCM_ATTN)One run per leg, no fixed seed. Five runs of the gathered path gave peaks of
4.70, 6.64, 6.53, 8.46 and 9.09 with means of 2.55 to 3.19, so the spread on the
peak is about +-2 and the parity numbers should be read as "no worse", not as an
improvement.
The baseline row predates this branch's rebase onto current
main, so thedecode_mscolumn also spans upstream changes to the weight-sync path.mainitself cannot be measured here: it raises in attention before reaching astep.
Attention itself is ~20us; the rest is the gather, which runs at ~12% of HBM
bandwidth. A fused gather kernel is the obvious follow-up, but it cannot remove
the padding volume -- that needs paged varlen upstream (see the
TODO).Correctness of the mask
Checked against an explicit bottom-right causal reference (
max |err|, bf16):q=[1,1,1] k=[100,256,37]q=[128,64] k=[128,64]q=[64] k=[256]q=[128,1,1] k=[128,256,37]With
varlen_attn'swindow_size=(-1, 0)instead of the sentinel, the mixedcases are off by 3.2 -- that is the degradation this PR works around.
Testing
tests/rl/unit_tests/cpu/test_vllm_wrapper.pycovers the gather on CPU: eachsequence comes back verbatim at the offset
cu_seqlens_kreports, in bothstride regimes and across page sizes; the capture layout keeps one shape across
three different context-length sets; and a strided cache view is read without
materializing the cache.
cc @zstreet87