Skip to content

[rl] Batch-invariant FA4 runs use exactly 16-token KV pages - #5870

Merged
felipemello1 merged 1 commit into
mainfrom
felipemello1/fa4-kv-pages/2-bi-16-token-pages
Nov 6, 2026
Merged

felipemello1 merged 1 commit into
mainfrom
felipemello1/fa4-kv-pages/2-bi-16-token-pages

Conversation

@felipemello1

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

Written with Claude Code: the analysis, measurements and test plan below.

TLDR: In batch-invariant mode on SM100/SM103, TorchTitan's vLLM generator now asks FA4 for exactly 16-token KV pages. FA4 then decodes with the same 128-key tiles as prefill. Before, head dim 256 and hybrid models still got pages that are a multiple of 128. There FA4 picks its SwapAB decode kernel, which reads 256-key tiles, so decode logprobs stopped matching prefill.

batch-invariant, FA4 on SM100/SM103     base PR                                  this PR
head dim 256 (Qwen3.5)                  vLLM's 128-token pages -> SwapAB decode  16-token pages
hybrid KV block (e.g. 1152 tokens)      one 1152-token page    -> SwapAB decode  16-token pages
other models                            16-token pages (vLLM default)            16-token pages
# before
if fa4_on_sm10x and not is_in_batch_invariant_mode():
    return [128]
return super().get_supported_kernel_block_sizes()  # [128] at head dim 256, MultipleOf(16) otherwise
# after
if fa4_on_sm10x:
    return [16] if is_in_batch_invariant_mode() else [128]

Problem

  1. SwapAB. FA4 decodes one token per sequence with its SwapAB kernel when the page size is a multiple of 128 (flash_attn/cute/config.py, SwapABPolicy). It reads 256 keys per tile, while prefill reads 128, so decode stops matching prefill bitwise.
  2. Head dim 256. The base PR keeps vLLM's default in batch-invariant mode. For FA4 at head dim 256, vLLM's default is 128-token pages.
  3. Hybrid models. vLLM's default MultipleOf(16) lets a hybrid model's KV block, aligned to its linear-attention state, stay one page: select_common_block_size(1152, ...) returns 1152, a multiple of 128.
  4. Cost. On Qwen3.5-9B, with attn_gym's other two causes taken out (its l2norm pinned to one launch config, FMA fusion off), 128-token pages alone leave decode vs prefill at a max logprob delta of 2.2e-4. 16-token pages make it bitwise.

Solution

  1. In batch-invariant mode with FA4 on SM100/SM103, _FA4PageSize returns exactly [16].
  2. Exactly 16, not MultipleOf(16): a multiple would let the 1152-token page through.
  3. Unchanged: runs without batch-invariant mode (128-token pages), other GPUs and FA3 (vLLM's default).

Results

TestBitwiseParityQwen35Varlen: Qwen3.5-9B-Base, TP2, 2x GB300, FA4 4.0.0b38, torch 2.16.0.dev20261105,
Triton's default FMA fusion on, no env overrides
                              main      this PR + attn_gym fixes (below)
batch invariance              pass      pass
trainer vs vLLM prefill       4.5e-2    bitwise, 5 of 5 sequences
vLLM decode vs prefill        1.0e-4    bitwise, 5 of 5 sequences

The test needs three fixes. This PR is one. The other two are in attn_gym: its l2norm fix is on attn_gym main but not released, and a recurrent-scan fix is an open attention-gym PR. Without them, attn_gym's l2norm and recurrent scan pick launch configs from the batch shape and round the same sequence differently.

You may ask:

  • Why not ask FA4 for its standard decode kernel directly? FA4 reads that choice only from the env var FLASH_ATTENTION_SM100_BACKEND (or from a full per-call kernel config), and torch's varlen attention can't pass either per call. The docstring has a TODO for when it can.
  • Why not set FLASH_ATTENTION_SM100_BACKEND=standard in batch-invariant mode? It's process-wide, has to reach every vLLM worker process, and hides the choice from the code that needs it.

NOTE: Only head-dim-256 and hybrid models change; other models already had 16-token pages in batch-invariant mode. Those two now gather K/V page by page in prefill and decode, which is slower than 128-token pages. Not measured.
NOTE: No CI job runs TestBitwiseParityQwen35Varlen. The B200 job (nightly and ciflow/b200) runs TestBitwiseParityKimiK3DebugVarlen in batch-invariant mode on FA4, so it exercises the 16-token branch. It can't catch this bug: that model's head dims (192, 128) never run SwapAB. Full Qwen3.5 parity in a fresh environment needs an attn-gym release with both fixes; TorchTitan pins attn-gym 0.0.17.

Test plan

pytest tests/rl/unit_tests/cpu/test_vllm_attention.py   # 11 passed; test_fa4_splits_hybrid_kv_blocks_into_pages[True-16] fails on the base PR (1152)
pytest tests/rl/unit_tests/cpu                          # 562 passed, 2 skipped
# 2x GB300, attn_gym main + the recurrent-scan fix on PYTHONPATH
torchrun --nproc-per-node=2 -m pytest tests/rl/unit_tests/gpu/test_bitwise_parity.py::TestBitwiseParityQwen35Varlen   # 3 passed on both ranks

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 5, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 5, 2026
@felipemello1
felipemello1 added this pull request to stack #5864 November 5, 2026 22:12
@felipemello1
felipemello1 marked this pull request as ready for review November 5, 2026 23:35
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 5, 2026
@github-actions
github-actions Bot requested review from liangel-02 and pzhan9 November 5, 2026 23:35
@felipemello1

Copy link
Copy Markdown
Contributor Author

@claude please review

@claude

claude Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 52s —— View job


Approve -- please address the items before merging (empty human-written summary; add an upstream issue link to the FA4 decode-kernel TODO): 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. The fix is small and at the right layer: the KV page-size hook TorchTitan already owns. The test exercises the exact-vs-MultipleOf(16) distinction, which is the regression that matters.

What this PR does. In batch-invariant mode, when FA4 runs on SM100/SM103, _FA4PageSize.get_supported_kernel_block_sizes now returns exactly [16]. Before, it fell through to vLLM's default. With 16-token pages, FA4 never picks its SwapAB decode kernel (which reads 256 keys per tile), so decode uses the same 128-key tiles as prefill. Runs without batch-invariant mode, and other GPUs, behave as before.

Example.

batch-invariant, FA4, SM100            base PR                           this PR
Qwen3.5 (head dim 256)                 vLLM default [128] -> SwapAB      [16]
hybrid, KV block 1152                  MultipleOf(16) -> one 1152 page   1152 / 16 -> 16-token pages
                                       (multiple of 128 -> SwapAB)
dense head dim 128/192                 MultipleOf(16) -> 16              [16] (unchanged)

Must fix

  1. PR description: "Summary (human-written)" is empty. The author needs to fill it in before merge.
  2. torchtitan/rl/generator/vllm/attention/attention.py:63 -- the TODO points at an upstream PyTorch gap (varlen attention can't choose FA4's decode kernel per call) but has no issue link (see inline).

Should consider

  • Raising this with vLLM: its head-dim-256 default and MultipleOf(16) both still admit SwapAB for anyone else running FA4 batch-invariant. That isn't something this PR has to solve.
Details
  • Gate: the problem is concrete and measured: on Qwen3.5-9B, decode vs prefill has a max logprob delta of 2.2e-4 caused by SwapAB alone. The cost (page-by-page K/V gather) is limited to batch-invariant runs on head-dim-256 and hybrid models, which is a debug/parity mode, so the slowdown is acceptable.
  • [16] exact still fits vLLM's hybrid alignment, because every attention block size vLLM can produce there is a multiple of 16. The base PR's [128] path had the stricter constraint.
  • The DiffKV backend shares the mixin and gets the same behavior. test_kv_page_size_follows_flash_impl already covers both backends with (FA4, (10,0), True, 16). That case passed before too (MultipleOf(16) -> 16), so only the new hybrid case (True, 16) guards this change, and it fails on the base PR as described.
  • Pre-existing, not from this PR: test_fa4_page_size_with_kv_cache_spec doesn't patch is_in_batch_invariant_mode, so it depends on global state being off.

Not verified: that FA4's SwapABPolicy keys on a page size that is a multiple of 128 and never picks SwapAB at 16 (I couldn't inspect the installed FA4 or vLLM sources); GPU parity results. A maintainer still needs to review.

Comment on lines +63 to +64
TODO: ask FA4 for its standard decode kernel per call once torch's varlen
attention can pass that choice; batch-invariant runs can then keep 128-token pages.

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 TODO works around a PyTorch gap: torch.nn.attention.varlen gives you no per-call way to choose FA4's decode kernel. Nothing tracks that gap, so the 16-token gather cost (and the slower prefill for head-dim-256 and hybrid models) stays with no exit. CLAUDE.md principle 3 asks for an upstream issue link on TODOs like this. Please file a pytorch/pytorch issue asking for the varlen API to forward the FA4 SM100 backend / SwapAB choice, and link it here, e.g. TODO(pytorch/pytorch#NNNNN): ....

@drisspg

drisspg commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

cc @liangel-02 for the kernel options motivation I mentioned on wednesday

@felipemello1
felipemello1 force-pushed the felipemello1/fa4-kv-pages/2-bi-16-token-pages branch from d262c5f to a96c032 Compare November 6, 2026 01:26
Base automatically changed from felipemello1/fa4-kv-pages/1-128-token-pages to main November 6, 2026 01:26
FA4 admits its SwapAB decode kernel on any page that is a multiple of 128, and SwapAB reads
256 keys per tile while prefill reads 128, so decode stops matching prefill bitwise. vLLM
picks 128-token pages for head dim 256 and keeps a hybrid model's whole KV block (e.g. 1152
tokens) as one page under MultipleOf(16). In batch-invariant mode on SM100/SM103, ask for
exactly 16-token pages.
@felipemello1
felipemello1 force-pushed the felipemello1/fa4-kv-pages/2-bi-16-token-pages branch from a96c032 to af1d7cf Compare November 6, 2026 01:26
@felipemello1
felipemello1 merged commit 5f055ce into main Nov 6, 2026
felipemello1 added a commit that referenced this pull request Nov 8, 2026
…K3) (#5955)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Agent details

**TLDR:** Kimi K3 batch-invariant RL crashes at KV-cache init on GB300
with the current nightly, so main's
`rl_grpo_kimi_k3_debug_batch_invariant` test is red. vLLM sizes Kimi
K3's attention page with K's head size for V too, then refuses to split
the padded block. The unequal-K/V attention backend now reports V's head
size. This PR alone turns the test green. Bottom of a 3-PR stack, based
on main: #5955 (this) -> #5498 -> #5956.

```text
Kimi K3 RL test, bytes per KV block (from vLLM's error)
before:  block stride 638976 (V counted at K's head size) != real page 532480 -> crash at KV-cache init
after:   page estimate = real page -> runs, trainer vs generator logprob diff 0
```

**Problem**
1. **vLLM's estimate.** For a hybrid model, vLLM sizes the attention
page from a spec without `head_size_v`
(`vllm/platforms/interface.py:854-863` on the pinned nightly,
`:1037-1048` on vLLM main), so V gets K's head size. vLLM's DiffKV
backends don't correct it in `customize_spec`.
2. **Smaller V.** Kimi K3's full attention has a smaller V head, so its
real page is smaller than the estimate. The block stride is padded.
3. **Now a crash.** #5870 changed batch-invariant FA4 kernel blocks from
`MultipleOf(16)` to exactly `[16]`, so vLLM must split each KV block,
and it refuses to split a padded block.
4. **Who hits it.** Only batch-invariant Kimi K3:
`uses_compressed_mla_cache` keeps materialized K/V (the unequal-K/V
backend) only in batch-invariant mode. It crashes at KV-cache init on
GB300, on the current nightly and on vLLM main.

**Solution**
1. `TorchTitanVarlenInnerAttentionDiffKVBackend.customize_spec` sets
`head_size_v` to the layer's V head size, then calls vLLM's. vLLM's page
estimate then equals the real page. This is the order vLLM's own fix
uses.
2. vLLM's DiffKV backends keep V's head size on the class
(`set_head_size_v`), so this assumes one V head size per process, as
vLLM does. Kimi K3 has one.
3. A TODO names the vLLM change that deletes this override: vLLM's
DiffKV backends setting `head_size_v` in `customize_spec`. A vLLM-side
fix is drafted at felipemello1/vllm#2.
4. Unchanged: every other attention backend, and models whose K and V
head sizes are equal.

**Results**

```text
Numerics: Kimi K3 batch-invariant RL, trainer vs generator logprob diff max 0 at steps 1-3.

pinned nightly, GB300                            GPUs  ran on        result
tests/rl/unit_tests/cpu                          -     69cc40a54     568 passed, 7 skipped
Kimi K3 batch-invariant RL, 3 steps (rl_h100)    4     69cc40a54     passed; logprob diff max 0 at steps 1-3
                                                       058306e     passed; logprob diff max 0 at steps 1-3
                                                       without fix * crash at KV-cache init
Kimi K3 bitwise parity (B200 CI's test)          1     with fix *    4 passed
```

Rows ran at 69cc40a54, this PR's code before the rebase. The stack was
then rebased onto main 7d88c59, which adds one FSDP commit that
touches none of these files.

058306e is this PR's first commit alone: `replace` after vLLM's
`customize_spec` instead of before. Both give the same spec, because
vLLM's base `customize_spec` returns the spec unchanged.

\* Ran with the next PR's API fixes underneath. They don't touch the
attention page code.

NOTE:
- This changes Kimi K3's KV block size on every GPU. vLLM sizes the
block from the per-token attention page, which drops from 2 x K to K + V
head bytes. Tested on GB300 only.
- B200 CI runs the Kimi K3 parity test only with the `ciflow/b200` tag.
H100 CI never splits blocks, so it never hit the crash.

**Test plan**
- `python -m pytest tests/rl/unit_tests/cpu`
- `torchrun --nproc-per-node=1 -m pytest
tests/rl/unit_tests/gpu/test_bitwise_parity.py::TestBitwiseParityKimiK3DebugVarlen`
- `python -m tests.integration_tests.run_tests <out> --ngpu 4
--test_suite rl_h100 --test_name rl_grpo_kimi_k3_debug_batch_invariant`

---------

Co-authored-by: Felipe Mello <[email protected]>
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