Skip to content

[RL] Fix varlen RL on ROCm by gathering the paged KV cache - #4866

Draft
yuxinwan-amd wants to merge 1 commit into
pytorch:mainfrom
yuxinwan-amd:rl-generator-rocm-attention-backend
Draft

yuxinwan-amd wants to merge 1 commit into
pytorch:mainfrom
yuxinwan-amd:rl-generator-rocm-attention-backend

Conversation

@yuxinwan-amd

@yuxinwan-amd yuxinwan-amd commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Problem

vllm_attention_backend names CUSTOM for every varlen model on every
platform. CUSTOM is the generator's own varlen backend -- it computes with the
kernel the trainer computes with, which is what makes one model definition valid
on both sides.

On ROCm it cannot run. CUSTOM 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

An inherited assert (FlashAttention version not detected) fires first, but it
is only a symptom: vLLM detects no flash-attn version on ROCm, and CUSTOM
never 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 CUSTOM keeps 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_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 on
current vLLM the assert raises AttributeError on every call rather than
checking anything.

User-facing change

before after
ROCm varlen RL AssertionError at the first attention call trains
ROCm sliding-window varlen same AssertionError NotImplementedError naming the gap
ROCm unequal K/V head dims same AssertionError ValueError naming the gap
CUDA unchanged unchanged

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

leg decode_ms logprob_diff/max peak mean
before (deferring to vLLM's ROCM_ATTN) 212.2 11.67 3.75
this change 837.9 9.09 2.84

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 the
decode_ms column also spans upstream changes to the weight-sync path.
main itself cannot be measured here: it raises in attention before reaching a
step.

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):

batch result
decode only, q=[1,1,1] k=[100,256,37] 2.4e-03
prefill only, q=[128,64] k=[128,64] 7.0e-03
extend, q=[64] k=[256] 2.9e-03
mixed, q=[128,1,1] k=[128,256,37] 7.5e-03
mixed, fixed stride 512 7.8e-03

With varlen_attn's window_size=(-1, 0) instead of the sentinel, the mixed
cases are off by 3.2 -- that is the degradation this PR works around.

Testing

tests/rl/unit_tests/cpu/test_vllm_wrapper.py covers the gather on CPU: each
sequence comes back verbatim at the offset cu_seqlens_k reports, in both
stride 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

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 24, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/rocm
  • ciflow/rl

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
@pytorch-bot

pytorch-bot Bot commented Sep 24, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/rocm
  • ciflow/rl

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.

@yuxinwan-amd
yuxinwan-amd force-pushed the rl-generator-rocm-attention-backend branch from 5127b0d to 9ede108 Compare September 24, 2026 22:07
@yuxinwan-amd yuxinwan-amd changed the title [RL] Route the ROCm generator to vLLM's AITER FlashAttention backend [RL] Keep varlen RL working on ROCm by deferring backend choice to vLLM Sep 24, 2026
rishisinhanj added a commit to rishisinhanj/torchtitan that referenced this pull request Sep 25, 2026
…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]>
@yuxinwan-amd
yuxinwan-amd force-pushed the rl-generator-rocm-attention-backend branch from 9ede108 to 8741ce7 Compare October 19, 2026 15:12
@yuxinwan-amd
yuxinwan-amd marked this pull request as ready for review October 19, 2026 16:28
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 19, 2026
Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
Comment on lines +112 to +115
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.

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.

Breaking "unified model" implicitly sounds not right. Maybe what you really want to have is a rocm-vllm replacement of VLLMEngine in this file.

@yuxinwan-amd
yuxinwan-amd marked this pull request as draft October 19, 2026 20:22
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 19, 2026
@yuxinwan-amd
yuxinwan-amd force-pushed the rl-generator-rocm-attention-backend branch 3 times, most recently from ccddc90 to aeecdda Compare November 2, 2026 20:11
@felipemello1

Copy link
Copy Markdown
Contributor

@claude please review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 3m 40s —— View job


Request changes -- review posted: the description describes the old backend=None design rather than the code at HEAD, and the AITER impl doesn't run the trainer's kernel as the PR claims.

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

  1. The description is stale. It describes returning None from a vllm_attention_backend() helper in engine.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.
  2. @tianyu-l's comment (no unified model) is only partly addressed. The model and the CUSTOM backend 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 torch varlen_attn_out on the gathered K/V. That needs no aiter dependency.
  3. attention.py:141-147 -- two device-to-host syncs per layer per eager forward. Build the gather indices once per forward.
  4. attention.py:124-140 -- the capture path, which is the default FULL-graph decode path, copies num_seqs * max_model_len K/V rows per layer. Memory and throughput are unmeasured.
  5. Removing the use_cascade assert (old line 204) changes the CUDA path, and the PR doesn't explain why.
  6. attention.py:66-69 -- the DiffKV backend on ROCm still hits the old assert.
  7. attention.py:367-376 -- add a TODO with a pytorch/pytorch issue link for ROCm varlen block_table support. 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 lse use the same (H, T) layout as torch's? out_transform assumes 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."

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.

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.

Comment on lines 66 to 69
def get_impl_cls():
if torch.version.hip is not None:
return AiterVarlenInnerAttentionImpl
return TorchTitanVarlenInnerAttentionImpl

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.

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.

Comment on lines +367 to +376
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."""

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.

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 a TODO with a pytorch/pytorch issue link, so it is removed once torch supports paged KV on ROCm.
  • The _activate_flash_attention_impl hook (and the base-class restructure that adds it) only exists to make this no-op. On ROCm get_cuda_flash_attention_impl() already returns None, 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__.

Comment on lines +466 to +499
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@yuxinwan-amd
yuxinwan-amd force-pushed the rl-generator-rocm-attention-backend branch 2 times, most recently from 4583fa0 to 149e69b Compare November 4, 2026 16:59
`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.
@yuxinwan-amd
yuxinwan-amd force-pushed the rl-generator-rocm-attention-backend branch from 149e69b to a1d4a7c Compare November 4, 2026 19:28
@yuxinwan-amd yuxinwan-amd changed the title [RL] Keep varlen RL working on ROCm by deferring backend choice to vLLM [RL] Fix varlen RL on ROCm by gathering the paged KV cache Nov 4, 2026

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/rl ciflow/rocm CLA Signed This label is managed by the Meta Open Source bot. module: rocm

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants