Skip to content

[rl] vLLM generator: fp8 KV cache through FA4's fp8 forward, MTP verify steps included - #6365

Closed
felipemello1 wants to merge 3 commits into
felipemello1/mtp-full-graphs-prefillfrom
felipemello1/vllm-fp8-kv-cache
Closed

felipemello1 wants to merge 3 commits into
felipemello1/mtp-full-graphs-prefillfrom
felipemello1/vllm-fp8-kv-cache

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

Needs retesting on B200 (SM100): every number below is from one GB300 (SM103). FA4's split heuristics are tuned per GPU, so B200 timings can differ.

Stack, bottom to top:

  1. "[rl] GDN builder: stage steps with drafts in fixed buffers"
  2. "[rl] MTP: replay the verify CUDA graph only when every row verifies"
  3. "[rl] GDN layer: run steps with drafts from TorchTitan's builder"
  4. "[rl] MTP speculative decoding in the vLLM generator"
  5. "[rl] MTP verify steps: run verify rows on FA4's decode kernel"
  6. "[rl] MTP on GDN models: FULL CUDA graphs for steps with prefill"
  7. this PR

The stack lands after the vLLM 0.33 PRs ("[rl] generator: vLLM 0.33 API fixes and TP padding in the model wrapper", "[rl] Install vLLM 0.33.0 on the torch nightly"). "[rl] generator: run on vLLM's model runner V2 (vLLM 0.34)" rebases on it.

TLDR: VLLMEngine.Config.kv_cache_dtype = "fp8" stores K and V in e4m3 and runs FA4's fp8 forward for decode and prefill rows. "auto" (bf16) stays the default and keeps the trainer's kernel. Qwen3.8-27B on one GB300: 2x the KV tokens (5.81M vs 2.90M), and 1,043 vs 902 output tok/s at 32 sessions with 27k-135k contexts. With fp8 SwapAB decode (an open FA4 PR), the same code gives 1,170. MTP drafts work with fp8 too: each verify step is one FA4 varlen call.

With kv_cache_dtype fp8, K and V take 1 byte per value instead of 2 and run FA4's fp8 forward, MTP verify steps included as one varlen call, so one GB300 engine holds 5.81M KV tokens instead of 2.90M, for 1,043 output tok/s vs 902 with bf16 and 1,170 with FA4's fp8 SwapAB PR.

kv_cache_dtype = "fp8"
  -> EngineArgs.kv_cache_dtype = "fp8": vLLM writes K/V in e4m3 (scale 1) and quantizes the query
  -> TorchTitanVarlenInnerAttentionImpl views the cache as e4m3
  -> paged_varlen_attention_out sees key_cache.dtype == float8_e4m3fn -> FA4 _flash_attn_fwd
     (bf16 keeps torch's varlen attention, the trainer's kernel)

Problem

  1. The KV cache caps how much context an engine holds: Qwen3.8-27B fits 2.90M bf16 tokens on one GB300 (gpu memory 0.85).
  2. Long agent loads fill it. 46 sessions with 27k-135k contexts and an 80 GiB CPU KV offload: KV sits at 89-92%, requests wait for KV (5.8 on average), and the engine gives 788 output tok/s.
  3. vLLM has an fp8 KV cache, but TorchTitan's attention impl asserts "FP8 KV cache not supported yet.".
  4. vLLM's fp8 check in FlashAttentionBackend is about vLLM's own FlashAttention build, which has no fp8 kernel at head dim 256. TorchTitan's backend subclasses it, so the check would refuse fp8 too.

Solution

  1. kv_cache_dtype: Literal["auto", "fp8"], passed to vLLM's EngineArgs. vLLM's cache write needed no change.
  2. The impl views the cache as e4m3. Every scale is 1: VLLMInnerAttention builds vLLM's Attention without a quant_config.
  3. paged_varlen_attention_out picks the fp8 path from the cache dtype. It calls FA4's private _flash_attn_fwd with the arguments torch's FA4 bridge passes. num_splits is 1 under deterministic algorithms, as torch's bridge sets it for the bf16 call.
  4. supports_combination hides fp8 from FlashAttentionBackend's check, and refuses a non-SM100 GPU with a reason. The impl passes "auto" to FlashAttentionImpl.__init__ for the same reason.
  5. Refused with a ValueError that says how to fix it:
    • fp8 with debug.batch_invariant: the trainer runs bf16.
    • fp8 on a model with sliding-window layers (gpt-oss, muse_glimmer, muse_spark): untested. gpt-oss is also the only model with attention sinks (out_transform), so this covers sinks too.
    • fp8 with tensor_parallel_degree > 1: untested.
    • fp8 on a model with MLA layers (DeepSeek-V3, Kimi K3): untested. Their K and V head dims differ, and vLLM runs the attention backend TorchTitan passes for them unchecked.
    • Not refused here: fp8 on a flex-attention model. vLLM refuses it at engine start.
  6. fp8 MTP verify steps make one FA4 varlen call with max_seqlen_q = 1 + k, at any row count. They skip the verify-steps PR's decode call + fp32 tail, which has no fp8 path.
    • On FA4 4.0.0b40, this call runs FA4's standard fp8 kernel: 0.686 ms per layer at 26 rows.
    • With FA4's open token-mode PR, the same call runs SwapAB with no change here: 0.441 ms (table below).
  7. Unchanged: "auto" runs the same code as before. The FA4 floor stays at 4.0.0b38, which has the fp8 forward and every argument the call passes.

Results

Numerics: not bitwise vs bf16 KV: K, V and the query are stored in e4m3, and FA4 rounds P to e4m3 before P @ V.
  Kernel, rel L2:
    fp8 FA4 vs bf16 FA4 on the same e4m3 values,          1.5e-3 decode rows, 4.3e-3 prefill rows
      engine-like inputs (long contexts, some large keys)
    fp8 FA4 vs an fp32 reference on the dequantized       ~0.02 (bar: 0.05)
      values, the GPU test's flat random attention
  A CUDA graph replayed after the KV lengths change is bitwise equal to eager.
  Trainer-vs-generator logprob gap: the trainer scores 34,816 generated tokens, temperature 1, 27k-78k contexts.
                      mean |diff|   k3 KL     tokens with ratio outside [0.2, 5]
    bf16 KV           0.0096        1.05e-3   4
    fp8 KV            0.0217        3.66e-3   19
    stock vLLM bf16   0.0157        1.16e-3   4
    stock vLLM fp8    0.0252        4.07e-3   17
  fp8 raises the gap 2.3x by mean and 3.5x by k3, a bit below stock vLLM's fp8.
Qwen3.8-27B, one GB300, TP1, gpu memory 0.85, FULL CUDA graphs, prefix caching, max_num_batched_tokens 16384,
32 sessions sharing one 27k prompt + own histories (27k-135k), 180 s window, one run per arm:
                                                  bf16 KV   fp8 KV   fp8 / bf16
  KV tokens                                       2.90M     5.81M    2.00x
  output tok/s, FA4 4.0.0b40                      902       1,043    1.16x
    (fp8 decode on FA4's standard kernel)
  output tok/s, FA4 with fp8 SwapAB (open PR)     902       1,170    1.30x
fp8 MTP-3 verify call (rows of 4 tokens, causal), one Qwen3.8-27B attention layer (24 q heads, 4 KV heads,
hd256, 128-token pages), one GB300, CUDA-graph replay, warm, median of 30, ms:
requests, layout                                standard fp8 kernel    FA4 token-mode PR
                                                (FA4 4.0.0b40's path)  (SwapAB)
26, 3 shared prompts (27k / 55k / 77k), 69k     0.686                  0.441
40, one shared 27k prompt, 27k-135k             1.430                  0.909

When KV is full (46 sessions, 80 GiB CPU KV offload, FA4 with fp8 SwapAB): fp8 gives 1,303 output tok/s with KV at 51-54% and no request waiting, vs 788 for bf16 with KV at 89-92%. Not a controlled pair: fp8 ran at gpu memory 0.9, bf16 at 0.85.

Where fp8 does not gain: on FA4 4.0.0b40, SwapAB takes only bf16/fp16, so fp8 decode runs FA4's standard kernel, which gets almost nothing from L2 on shared prompt pages. One layer, 26 requests in 3 groups sharing 27k / 55k / 77k prompts: 0.685 ms in fp8 vs 0.581 ms for bf16 SwapAB. With the FA4 fp8 SwapAB PR: 0.346 ms.

NOTE:

  • The engine and drift numbers ran on a development branch that also carries generator changes not in this stack, and the pre-merge version of main's CPU KV offload connector. That branch passed the layer's q, k, v scales (all 1.0) to FA4. This PR passes none, which FA4 treats as 1. One run per arm. Not re-measured on this stack.
  • The one-call fp8 verify path has no throughput or logprob run. An engine probe ran it at this head: Qwen3.5-0.8B, fp8 KV, k = 3, FULL, one GB300, 8 requests (4 arriving next to verify rows), all finished. Earlier fp8 + MTP-3 runs used another verify path (each row's tokens packed as query heads): 1,634 output tok/s at 32 sessions (fp8 alone 1,170; stock vLLM fp8 + MTP-3: 1,634).
  • Prefix-cache reuse gets coarser. A hybrid model's KV block grows from 896 to 1,664 tokens, and a prefix hit ends on a block boundary, so each agent turn recomputes ~400 more prompt tokens (2,053 vs 1,679 in the earlier run). TODO at the site.
  • fp8 with main's CPU KV offload connector ran in the 46-session engine runs above, but no test covers it: main's offload GPU test (multi-GPU) runs bf16 KV only.
  • Two open PRs edit vllm/attention/attention.py; the one that lands second rebases: the vLLM V2 model runner PR and the ROCm paged-KV gather PR.

You may ask: why FA4's private _flash_attn_fwd? torch's varlen attention takes no fp8 inputs, and FA4's public flash_attn_varlen_func has no out= to write into vLLM's output buffer. An open PyTorch PR adds fp8 descales to varlen_attn. TODO at the site to switch to torch's call once it lands.

Follow up / TODO (each has a # TODO at its site)

  • Calibrated per-layer KV scales: with scale 1, values above 448 clip and values below 2^-6 lose precision. They need a descales argument in paged_varlen_attention_out. The gain is not measured.
  • Raise the FA4 floor to the first release with fp8 SwapAB token mode (an open FA4 PR).
  • Call torch's varlen_attn_out once the open PyTorch PR lands, instead of FA4's private call.
  • Stop hiding fp8 from FlashAttentionBackend's check if this backend stops subclassing it.
  • fp8 with tensor parallelism, with sliding windows and with MLA: test, then lift the refusals.
  • Coarser prefix reuse: try vLLM's prefix_match_unit or a smaller mamba_block_size.

Test plan

pytest tests/rl/unit_tests/cpu
pytest tests/rl/unit_tests/gpu/test_vllm_verify_attention.py   # 1 GPU (GB300); also in the B200 RL workflow
pre-commit run --files <changed files>
RL CPU suite   793 passed, 0 failed, 8 skipped on the pinned vLLM (1.0.0.dev20261107; PR 6: 788 passed), main merged
               in. New: test_fp8_kv_cache_refusals (4 cases) and kv_cache_dtype as a TorchTitan-owned engine arg.
GPU            test_vllm_verify_attention.py: 6 passed (42 s). auto and fp8 on verify, few-row and mixed batches
               through `forward` (vLLM's uint8 storage, e4m3 query) against an fp32 reference on the dequantized
               values. The uniform fp8 steps assert one FA4 call with max_seqlen_q == 4.
               Also at this head: test_gdn_graph_metadata.py 38 passed (31 s); test_gdn_cudagraph.py (with the
               fused-kernel PR) 5 passed (497 s).
pre-commit     all hooks pass (pyrefly and lychee skipped)

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 55s —— View job


Approve -- please address the 5 items before merging (a maintainer still needs to review): 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 design is opt-in and the default path is unchanged. The remaining items are small local edits: a config-time check, an upstream issue link, a test fold, and a refusal for paths nobody has run. A maintainer still needs to review.

What this PR does. It adds VLLMEngine.Config.kv_cache_dtype: Literal["auto", "fp8"] and passes it to vLLM's EngineArgs. With "fp8", vLLM writes K/V as e4m3 and quantizes the query. The TorchTitan attention impl views the uint8 cache as e4m3, takes per-layer _q/_k/_v_scale expanded to (batch, num_kv_heads), and paged_varlen_attention_out(descales=...) calls FA4's private _flash_attn_fwd with TensorwiseScales. supports_combination and __init__ hide fp8 from FlashAttentionBackend's own check, and non-SM100 GPUs are refused. fp8 is refused together with batch-invariant mode or MTP drafts.

Example.

VLLMEngine.Config(kv_cache_dtype="fp8"), Qwen3.8-27B, GB300
  before: AssertionError "FP8 KV cache not supported yet." in impl.forward
  after:  cache 2.90M -> 5.81M tokens; decode/prefill rows -> _flash_attn_fwd(q_e4m3, k_e4m3, v_e4m3, scales=...)
          trainer/generator logprob mean |diff| 0.0096 -> 0.0217 (opt-in; "auto" path unchanged)
VLLMEngine.Config(kv_cache_dtype="fp8", num_speculative_tokens=3) -> ValueError (verify rows pass no descales yet)

Must fix

  1. The PR description's Summary (human-written) section is empty. The author needs to fill it in.
  2. torchtitan/rl/generator/vllm/engine.py:308 -- the fp8 + drafts check reads only Config fields, so it should move to Config.__post_init__ (inline).
  3. torchtitan/rl/generator/attention/attention.py:61 -- the private _flash_attn_fwd call has a TODO but no upstream issue link ("no torch issue filed yet") (inline).
  4. tests/rl/unit_tests/gpu/test_paged_attention_fp8.py:128 -- this test mostly duplicates the new fp8 cases of test_vllm_verify_attention.py. Put a leading 1-token row in its mixed case, then delete this file and its workflow line (inline).
  5. torchtitan/rl/generator/vllm/attention/attention.py:321 -- fp8 reaches sliding-window, sink (out_transform / return_lse), and head-dim-64 configurations (gpt-oss) that no run covers. Refuse them or test them (inline).

Questions

  • TP > 1 with fp8 is listed as untested. The descale shape uses the local num_kv_heads, so it looks right. Is a TP2 run planned before this lands, or should TP > 1 be refused like the other untested combinations?
Details
  • Gate: the problem is real (an assert on main), and vLLM already writes fp8. The gap is only in TorchTitan's backend, so the layer is right. Not one-sided: the trainer has no KV cache, and the PR refuses the one mode (batch-invariant) that needs trainer parity.
  • Checked: descale batch dim = query_start_loc.shape[0] - 1 matches block_table/seqused_k in both the decode and prefill split calls (they keep the full batch and zero the other call's rows). Under FULL graphs the padded batch is fixed per graph, and the scales are static per-layer tensors, so replay is safe. _verify_rows_as_decode passes no descales, but it is only reachable with drafts, which fp8 refuses.
  • sglang's caller of paged_varlen_attention_out is unaffected (descales=None).

Not verified: vLLM internals I couldn't import here (query_quant setup when the parent impl gets "auto", and the 2D query requirement). The FA4 fp8 forward behavior with windows or sinks also needs a GPU run.

Comment thread torchtitan/rl/generator/vllm/engine.py Resolved
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Round 1 fixes are in 3be3ff0 (see the threads). Two items have no thread:

Must 4: the duplicate fp8 test. Done. test_paged_attention_fp8.py and its workflow line are gone. The mixed case of test_vllm_verify_attention.py now starts with a 1-token row, so its fp8 run sends the descales through both FA4 calls (decode and varlen). That case change lives in the MTP verify steps PR, below this one:

# A leading 1-token row: FA4's decode call for it, the varlen call for the rest.
([1, 4, 4], [257, 130, 30_000], False),

Q: TP > 1. No TP2 run: the GPU host has one GPU. The descales are per-layer scalars expanded over the local KV heads, so TP only changes that count. The body keeps the NOTE "not tested with fp8: TP > 1". Refusing it is the author's call; I flagged it to him.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 6s —— View job


Approve -- please address the 5 items before merging (a maintainer still needs to review): 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 round-1 code fixes are in at 3be3ff0. What's left is small and local: one more refusal, a link, the summary, the description, and one test run. A maintainer still needs to review.

What this PR does. It adds VLLMEngine.Config.kv_cache_dtype: Literal["auto", "fp8"] and passes it to vLLM's EngineArgs. With fp8, TorchTitan's CUSTOM backend views the cache as e4m3 and expands the layer's _q/_k/_v_scale to (batch, num_kv_heads). It then calls FA4's private _flash_attn_fwd with TensorwiseScales for both the decode call and the prefill call. fp8 is refused with drafts (at config time), with batch-invariant mode, and on models with sliding-window layers.

Example.

VLLMEngine.Config(kv_cache_dtype="fp8"), Qwen3.8-27B (varlen, full causal), GB300
  before: AssertionError "FP8 KV cache not supported yet."
  after:  2.90M -> 5.81M KV tokens; both split calls -> _flash_attn_fwd(..., scales=TensorwiseScales(q, k, v))
VLLMEngine.Config(kv_cache_dtype="fp8", num_speculative_tokens=3)  -> ValueError at config time
fp8 + gpt-oss / muse_glimmer / muse_spark (windowed layers)        -> ValueError at engine start
fp8 + a FlexInnerAttention model                                   -> reaches vLLM's flex backend (see inline)

Round 1 status

  • Resolved: the drafts check is in __post_init__; the duplicate fp8 test is gone (the mixed case's leading 1-token row now sends descales through both FA4 calls); windowed models are refused.
  • Still open: the human-written summary (item 1) and the upstream issue link for _flash_attn_fwd (item 3, torchtitan/rl/generator/attention/attention.py:61).

Must fix

  1. The PR description's Summary (human-written) section is still empty. The author needs to fill it in.
  2. torchtitan/rl/generator/attention/attention.py:61 -- the TODO on the private _flash_attn_fwd call still says "no torch issue filed yet". It needs the pytorch/pytorch issue link (CLAUDE.md principle 3).
  3. torchtitan/rl/generator/vllm/engine.py:316 -- fp8 isn't refused for flex-attention models, which bypass the FA4 fp8 path this PR adds (inline).
  4. Description: "gpt-oss is the one such model here" (the sliding-window refusal) is not accurate. muse_glimmer (flavors.py:242) and muse_spark (flavors.py:427) also have windowed layers, and both have RL recipes. The check refuses them through getattr, so the code is right. Fix the sentence, because a maintainer reading it would conclude only gpt-oss loses fp8.
  5. Test plan: the GPU test ran only on an unreleased FA4 branch (fp8 SwapAB), and the run on a released FA4 is "pending for this head". On a released FA4, fp8 decode takes a different kernel (the standard one), so that path has no correctness run at this head. Run test_vllm_verify_attention.py on FA4 4.0.0b39 or b40 and record the result before merging.
Details
  • Gate (unchanged from round 1): the problem is real on the base branch (an assert). The fix lives in TorchTitan's backend, which is the right layer, and it is opt-in. "auto" runs the same code as before.
  • Checked at HEAD: descales goes through both entries of calls (vllm/attention/attention.py:423-437), and each call keeps the full batch, so the (batch, num_kv_heads) shape matches block_table/seqused_k. _verify_rows_as_decode doesn't pass descales, but it is reachable only with drafts, which the config refuses. Compressed MLA refuses fp8 itself (mla.py:147).
  • Minor, not blocking: when torch's flash impl is not FA4, current_flash_attention_impl() == "FA4" is false. fp8 then skips the decode/prefill split but still calls FA4 directly. That only costs performance on mixed batches.

Not verified: whether vLLM's FlexAttention backend refuses fp8 during backend selection (vLLM isn't importable here).

Comment thread torchtitan/rl/generator/vllm/engine.py Resolved
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Round 2 is in 8c367cd and the body. Must 1 and 2 (the Summary, the torch issue link) wait on the author.

  • Must 3, flex models: vLLM already refuses fp8 there at engine start: its flex backend lists no fp8 KV cache dtype. So I added no check. The kv_cache_dtype docstring now says fp8 is for varlen attention. Details in the thread.
  • Must 4, the description: fixed. The sliding-window line now names gpt-oss, muse_glimmer and muse_spark.
  • Must 5, a released FA4: test_vllm_verify_attention.py on FA4 4.0.0b40 at 8c367cd: 5 passed, 1 skipped (the fp8 verify case, which this PR refuses). Now in the test plan.

Before/after for the docstring:

before: runs FA4's fp8 forward (SM100 family only)
after:  runs FA4's fp8 forward (varlen attention on the SM100 family only;
        vLLM's flex backend refuses fp8)

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 54s —— View job


Approve -- please address the 2 items before merging (the human-written Summary and the upstream issue link; a maintainer still needs to review): 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 code fixes from rounds 1 and 2 are in at 8c367cd, and the new commit only changes a docstring. The two items left are edits only the author can make. A maintainer still needs to review.

What this PR does. It adds VLLMEngine.Config.kv_cache_dtype: Literal["auto", "fp8"] and passes it to vLLM's EngineArgs. With fp8, TorchTitan's CUSTOM backend views the cache as e4m3, expands the layer's _q/_k/_v_scale to (batch, num_kv_heads), and calls FA4's private _flash_attn_fwd with TensorwiseScales. fp8 is refused in three cases: with drafts (at config time), with batch-invariant mode, and on models with sliding-window layers. On flex-attention models, vLLM's backend validation refuses it.

Example.

VLLMEngine.Config(kv_cache_dtype="fp8"), Qwen3.8-27B, GB300
  before: AssertionError "FP8 KV cache not supported yet."
  after:  2.90M -> 5.81M KV tokens; decode + prefill calls -> _flash_attn_fwd(..., scales=TensorwiseScales(q, k, v))
VLLMEngine.Config(kv_cache_dtype="fp8", num_speculative_tokens=3)  -> ValueError at config time
fp8 + gpt-oss / muse_glimmer / muse_spark                          -> ValueError at engine start
fp8 + a FlexInnerAttention model                                   -> vLLM: "kv_cache_dtype not supported"

Round 2 status

  • Resolved: flex models (vLLM refuses fp8 through AttentionConfig(backend=...), and the docstring now scopes fp8 to varlen attention). The sliding-window sentence in the description now names all three models. The test plan now has a released-FA4 run (4.0.0b40: 5 passed, 1 skipped).
  • Still open: items 1 and 2 below.

Must fix

  1. The PR description's Summary (human-written) section is still empty. The author needs to fill it in.
  2. torchtitan/rl/generator/attention/attention.py:61 -- the TODO on the private _flash_attn_fwd call still says "no torch issue filed yet". It needs a pytorch/pytorch issue link (CLAUDE.md principle 3).
Details
  • Gate (unchanged): the problem is real on the base branch (an assert), and vLLM already writes fp8. The gap is only in TorchTitan's backend, which is the right layer. The change is opt-in, and "auto" runs the same code as before.
  • 8c367cd changes only the kv_cache_dtype docstring. The new wording is consistent with the backend routing in registry.py and the engine-side checks.
  • The window check reads getattr(layer.attention, "sliding_window_size", None), the same field model_wrapper.py:118 passes to vLLM, so the refusal and the wrapper can't disagree about which layers are windowed.

Not verified: vLLM's flex-backend refusal of fp8 (vLLM isn't importable here; I took it from the author's cited source lines).

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the 2 items before merging (the human-written Summary and the upstream issue link; a maintainer still needs to review): 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 only new commit since round 3, e5678e9, refuses fp8 with TP > 1, which answers the round-1 question about TP. The two items left are edits only the author can make. A maintainer still needs to review.

What this PR does. It adds VLLMEngine.Config.kv_cache_dtype: Literal["auto", "fp8"]. With fp8, TorchTitan's CUSTOM backend views the cache as e4m3 and calls FA4's private _flash_attn_fwd with TensorwiseScales built from the layer's _q/_k/_v_scale. fp8 is refused with MTP drafts (at config time), with batch-invariant mode, with tensor_parallel_degree > 1, and on models with sliding-window layers. On flex-attention models, vLLM's own backend validation refuses it.

Example.

VLLMEngine.Config(kv_cache_dtype="fp8") + InferenceParallelismConfig(tensor_parallel_degree=2)
  before (8c367cda7): builds; each rank expands the scales over its local KV heads, a path no run has checked
  after  (e5678e9a6): ValueError "kv_cache_dtype='fp8' is untested with tensor parallelism, but tensor_parallel_degree=2; ..."

Round 3 status

  • New: the TP refusal (engine.py:318) comes before the window check and reads parallelism.tensor_parallel_degree, the field InferenceParallelismConfig defines (parallelism.py:21). It has a TODO that says what to check before lifting it (TP2 logprobs vs TP1). The test is a third id in the existing test_fp8_kv_cache_refusals, not a new test.
  • Still open: items 1 and 2 below.

Must fix

  1. The PR description's Summary (human-written) section is still empty. The author needs to fill it in.
  2. torchtitan/rl/generator/attention/attention.py:61 -- the TODO on the private _flash_attn_fwd call still says "no torch issue filed yet". It needs a pytorch/pytorch issue link (CLAUDE.md principle 3).

Not verified: the TP refusal only runs at engine start, and no GPU test reaches it (the CPU test covers it).

@felipemello1 felipemello1 changed the title [rl] vLLM generator: fp8 KV cache through FA4's fp8 forward [rl] vLLM generator: fp8 KV cache through FA4's fp8 forward, MTP verify steps included Nov 25, 2026
@felipemello1
felipemello1 removed this pull request from stack #6368 November 26, 2026 02:13
@felipemello1
felipemello1 changed the base branch from felipemello1/mtp-verify-steps to felipemello1/mtp-uniform-verify November 26, 2026 02:13
@felipemello1
felipemello1 added this pull request to stack #6404 November 26, 2026 02:13
…fy steps included

VLLMEngine.Config.kv_cache_dtype="fp8" stores K/V in e4m3 at scale 1 and runs FA4's fp8
forward; paged_varlen_attention_out picks it from the cache dtype. MTP verify steps make
one varlen call. Refused: debug.batch_invariant, tensor parallelism, sliding windows, and
GPUs outside SM100.
@felipemello1
felipemello1 removed this pull request from stack #6404 November 28, 2026 17:44
@felipemello1
felipemello1 force-pushed the felipemello1/vllm-fp8-kv-cache branch from 0e7ce67 to 4bf200c Compare November 28, 2026 17:45
@felipemello1
felipemello1 changed the base branch from felipemello1/mtp-uniform-verify to felipemello1/mtp-full-graphs-prefill November 28, 2026 17:45
@felipemello1
felipemello1 added this pull request to stack #6434 November 28, 2026 17:50
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve, no must-fix items left; three open questions are in the review (vLLM's dynamic KV scales, fp8 on MLA-shaped layers, an fp8 + MTP engine run): 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 -- the rewrite (4bf200c) is smaller than the round-3 version. It drops the descale plumbing and runs fp8 MTP verify steps through the existing varlen call. Both round-3 must-fix items are cleared. A maintainer still needs to review.

What this PR does. It adds VLLMEngine.Config.kv_cache_dtype: Literal["auto", "fp8"] and forwards it to EngineArgs. With fp8, TorchTitanVarlenInnerAttentionImpl views vLLM's uint8 cache as e4m3. paged_varlen_attention_out then sees an e4m3 key_cache and calls FA4's private _flash_attn_fwd with every scale left at 1. fp8 verify steps skip _verify_rows_as_decode and make one varlen call with max_seqlen_q = 1 + k. fp8 is refused with batch-invariant mode, with TP > 1, on models with sliding-window layers, and on non-SM100 GPUs (in supports_combination).

Example.

Qwen3.8-27B, VLLMEngine.Config(kv_cache_dtype="fp8", num_speculative_tokens=3), GB300
  round 3 (e5678e9a6): ValueError at config time (verify rows passed no descales)
  4bf200c:             verify step, 26 rows x 4 tokens -> one _flash_attn_fwd(q_e4m3, k_e4m3, v_e4m3,
                       cu_seqlens_q=query_start_loc, max_seqlen_q=4); no decode call, no fp32 tail
kv_cache_dtype="auto": the same code as before (`not is_fp8` only adds a term to the verify-path condition)

Round 3 status

  • Resolved: the upstream link. The TODO now points at pytorch/pytorch#206590 and Dao-AILab/flash-attention#3217 (torchtitan/rl/generator/attention/attention.py:58).
  • Moot: the config-time drafts check. fp8 + drafts is supported now, and VLLMEngine.Config no longer refuses it.

Should consider

  • #6413 (SGLang fp8, based on main) adds the same paged_varlen_attention_out hunk (blob 4c9896ee28). #6366 (a draft based on this branch) adds fp8 verify rows with descales, which this PR now covers in a different way. Land the shared hunk once and rebase the other PR onto it. Close #6366 or say what it still adds.

Questions

  • Scales of 1 are assumed but never checked. vLLM's Attention computes dynamic q/k/v scales when cache_config.calculate_kv_scales is set. add_extra_vllm_engine_args does not block that key (engine.py:89). If vLLM still honors it, the cache write and the query quantization would use those scales while FA4 assumes 1, and the logprobs would be silently wrong. Is that reachable? If so, add "calculate_kv_scales" to the refused keys, or raise when fp8 is set together with it. Unverified: whether the pinned vLLM still has the field.
  • Uncompressed MLA layers (head dim 192, V head dim 128) go through TorchTitanVarlenInnerAttentionDiffKVBackend. It does not override supports_combination (vllm/attention/attention.py:168), and VLLMInnerAttention passes it as attn_backend (:670). If vLLM doesn't re-validate a backend passed this way, fp8 runs FA4's fp8 forward at 192/128, and no test or run covers that. The TP and sliding-window cases are refused for the same reason. Does vLLM refuse this at engine start? If not, a refusal next to the window check would fit, raised when any full-attention layer's value head dim differs from its head dim. Unverified: vLLM isn't importable here.
  • There is no engine run for the one-call fp8 verify path (body NOTE). A short MTP-3 + fp8 engine run would show that it composes with FULL graphs for steps with prefill (the PR below this one). Is one planned before merge?
Details
  • Gate: unchanged from earlier rounds. The problem is real (an assert on the base branch). The fix is in TorchTitan's backend, which is the right layer. It is opt-in. Dropping the descales removes the (batch, num_kv_heads) expansion and the scale reads from forward, and the TODO at VLLMInnerAttention.__init__ names what calibrated scales would need.
  • Checked at HEAD: in the fp8 mixed-batch split, both calls write out=output[:num_actual_tokens] with clamped cu_seqlens_q, so each call writes only its own rows, as in the bf16 path. The fp8 num_splits follows torch.are_deterministic_algorithms_enabled(), and batch-invariant mode is refused for fp8 anyway. The window and TP checks need model and parallelism, so engine init is the right place for them.
  • The GPU test count stays the same for fp8 verify: one call through _verify_rows_as_decode (bf16) and one varlen call (fp8). The new asserts on max_seqlen_q == 4 and cu_seqlens_q is query_start_loc pin the one-call path.
  • Overlap search: fp8 kv cache -> #6413, #6366; paged_varlen_attention_out -> #6413.

Not verified: GPU behavior; vLLM internals (query_quant setup, validation of a backend passed as attn_backend, calculate_kv_scales).

Before merge: fill in the human-written summary.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: The review's three questions. Fixed in 6348be1: MLA layers are refused.

  1. calculate_kv_scales can't be reached: our pinned vLLM (9f03b510c) has no such field. Neither vllm/config/cache.py nor vllm/engine/arg_utils.py names it, so EngineArgs rejects the key.
  2. MLA: refused at engine init, next to the window check. MLA is the only TorchTitan attention whose K and V head dims differ (get_attention_dimensions, torchtitan/rl/generator/model.py:54-56), so this covers the DiffKV backend.
mla_layers = [
    layer_id
    for layer_id, layer in enumerate(model.layers)
    if hasattr(layer.attention, "qk_nope_head_dim")
]
if mla_layers:
    # TODO: test fp8 with MLA (DeepSeek-V3, Kimi K3), then lift this. Its K and V head dims
    # differ, and vLLM runs the attention backend TorchTitan passes for it unchecked.
    raise ValueError(
        "kv_cache_dtype='fp8' is untested with MLA attention, but layers "
        f"{mla_layers[:2]} use it; set kv_cache_dtype='auto'"
    )
  1. fp8 + MTP engine run: a VLLMEngine with fp8 KV, k = 3 and FULL graphs served 8 requests at this head (Qwen3.5-0.8B, one GB300). 4 of them arrived next to verify rows. All finished. It has no throughput or logprob check; the PR body says so.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve, no must-fix items. The new MLA refusal (6348be1) settles the last open question, and two optional suggestions are in 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 -- since my last full review (4bf200c) there is one new commit, 6348be1, which refuses fp8 on MLA layers. I have no must-fix items. A maintainer still needs to review.

What changed since the last review. The merge commit 05a15fe only brings in the base branch. I compared this PR's diff on the 5 changed files before and after the merge, and the MLA commit is the only difference. 6348be1 adds a refusal at engine start, next to the sliding-window check, and adds an mla case to the existing test_fp8_kv_cache_refusals.

Example.

VLLMEngine.Config(kv_cache_dtype="fp8"), a DeepSeek-V3 / Kimi K2.7 / Kimi K3 model
  4bf200c: builds; FA4's fp8 forward would run at qk 192 / v 128, which no run has covered
  6348be1: ValueError "kv_cache_dtype='fp8' is untested with MLA attention, but layers [0, 1] use it; ..."

Answers to the round-4 questions

  • calculate_kv_scales: the author says the pinned vLLM (9f03b510c) has no such field, so EngineArgs rejects the key. That rules out the silent scale mismatch I asked about.
  • MLA: resolved by the refusal. It uses the same discriminator as get_attention_dimensions (model.py:54), and every MLA attention config has qk_nope_head_dim: deepseek_v3/attention.py:44, which kimi_k2_7 reuses, and kimi_k3_1/flavors.py:117.
  • fp8 + MTP engine run: an 8-request smoke run with k = 3 and FULL graphs finished. The body says it has no throughput or logprob check, which is enough for an opt-in path.

Should consider

  • torchtitan/rl/generator/vllm/engine.py:401 -- the check could call get_attention_dimensions instead of repeating its hasattr test (inline). Optional.
  • Still open from round 4: #6413 (SGLang fp8) adds the same paged_varlen_attention_out hunk, and #6366 (a draft based on this branch) adds fp8 verify rows that this PR already covers in another way. Land the shared hunk once, and close #6366 or say what it still adds.
Details
  • Gate: unchanged. The problem is real on the base branch (an assert). The fix is in TorchTitan's backend, which is the right layer, and it is opt-in: "auto" runs the same code as before.
  • The new refusal reads the model config, so engine init is the right place for it, as for the window and TP checks. The test adds an id to the existing parametrize, not a new test.
  • Overlap search: fp8 kv cache -> #6413, #6366 (unchanged).

Not verified: the pinned vLLM has no calculate_kv_scales field. vLLM isn't importable here, so this rests on the author's reply.

Before merge: fill in the human-written summary.

Comment on lines +401 to +405
mla_layers = [
layer_id
for layer_id, layer in enumerate(model.layers)
if hasattr(layer.attention, "qk_nope_head_dim")
]

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.

hasattr(layer.attention, "qk_nope_head_dim") copies the duck-type test inside get_attention_dimensions (torchtitan/rl/generator/model.py:54). The TODO gives the reason for the refusal as "K and V head dims differ". If a second attention type ever gets a different V head dim, get_attention_dimensions will learn about it, but this check will not. You could ask the function for the fact itself, which keeps one definition:

mla_layers = [
    layer_id
    for layer_id, layer in enumerate(model.layers)
    if len(set(get_attention_dimensions(layer.attention, model.dim)[2:])) > 1
]

Today it refuses the same layers. The error message could then say "different K and V head dims" instead of "MLA". This is optional; the current check is correct for every model in the repo.

felipemello1 added a commit to felipemello1/torchtitan that referenced this pull request Nov 30, 2026
…pytorch#6366 on pytorch#6365's head)

Port of pytorch#6366 (ad1774b; its own delta e5678e9..ad1774b) onto pytorch#6365's head 6348be1,
which dropped the descales: fp8 is now told by the cache dtype. As r8 (597ebff) ran it:
- paged_varlen_attention_out takes query_len_in_heads on the fp8 path; fa4_takes_query_len_in_heads().
- Uniform fp8 verify steps go to _verify_rows_as_decode at any row count, which makes one decode call over
  every key; FA4 hides each token's later keys. V head dims unlike K's keep the varlen call.
- The engine refuses fp8 with drafts on an FA4 without query_len_in_heads.

Needs an FA4 with query_len_in_heads (Dao-AILab/flash-attention#3217); the r11 run puts r8's copy
fa4_b40_fp8swapab first on PYTHONPATH. Per layer on the r11 venv (runshared:46): verify 1.436 -> 0.973 ms,
decode 1.433 -> 0.953 ms.
@liangel-02

Copy link
Copy Markdown
Contributor

Superseded by #6479

@liangel-02 liangel-02 closed this Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

2 participants