Skip to content

[rl] SGLang generator: fp8 KV cache through FA4's fp8 forward - #6413

Draft
felipemello1 wants to merge 5 commits into
mainfrom
felipemello1/sgl203/s1-fp8-kv-cache
Draft

felipemello1 wants to merge 5 commits into
mainfrom
felipemello1/sgl203/s1-fp8-kv-cache

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: SGLangEngine.Config.kv_cache_dtype = "fp8" stores K and V in e4m3 and runs FA4's fp8 forward for decode and prefill. "auto" (bf16) stays the default and keeps the trainer's kernel. This is the SGLang side of the vLLM fp8 PR ("[rl] vLLM generator: fp8 KV cache through FA4's fp8 forward, MTP verify steps included"), without the MTP verify steps. Qwen3.5-0.8B on one GB300: 2.00x the KV tokens (12.28M vs 6.14M at gpu_memory_limit 0.5). The trainer-vs-generator logprob gap grows 2.3x (mean |diff| 0.0210 vs 0.0093).

On main, an fp8 KV cache reaches torch's varlen attention, which rejects the e4m3 query. This PR casts q, and an e4m3 cache picks FA4's fp8 forward, so the pool holds 12.28M KV tokens instead of 6.14M.

Problem

  1. The KV cache caps how much context one generator holds. Qwen3.5-0.8B at gpu_memory_limit 0.5 holds 6.14M bf16 KV tokens on a GB300.
  2. SGLang has an fp8 KV cache (--kv-cache-dtype fp8_e4m3), but main has no fp8 path in TorchTitan's SGLang attention backend. Its docstring says fp8 KV raises, but nothing checks for it.
  3. On main, extra_server_args={"kv_cache_dtype": "fp8_e4m3"} sends the e4m3 cache (and, in decode, an e4m3 query) to torch's varlen attention, whose FA4 bridge takes only an fp16 or bf16 query (torch/nn/attention/_fa4.py).

Solution

  1. kv_cache_dtype: Literal["auto", "fp8"], as on the vLLM engine. "fp8" passes kv_cache_dtype="fp8_e4m3" to SGLang; the key joins _TORCHTITAN_SERVER_ARGS.
  2. The hook casts q to e4m3 when the cache is fp8. Every scale is 1: SGLang stores K/V unscaled without a quantization config, and TorchTitan's attention layers have none. It allocates a bf16 output, since FA4's fp8 forward writes bf16.
  3. paged_varlen_attention_out calls FA4's private _flash_attn_fwd when the KV cache is fp8 e4m3, with the same code and TODOs as the vLLM PR.
  4. One rule for setups no fp8 run covered: a ValueError with the fix (kv_cache_dtype='auto') for tensor_parallel_degree > 1, data_parallel_degree > 1, sliding-window layers, MLA layers and a HiCache storage backend (Mooncake). debug.batch_invariant raises too: the trainer runs bf16. The backend refuses fp8 off the SM100 family.
  5. "auto" runs the same code as before.

Results

Trainer vs SGLang logprobs of the sampled tokens. Qwen3.5-0.8B, TP 1, breakable CUDA graphs, one GB300,
32 prompts of 1k-12k tokens (slices of one source file repeated 20 times), 512 tokens each at temperature 1
(16,384 tokens scored), gpu_memory_limit 0.5, one run per arm:
                     KV capacity (tokens)   mean |diff|   max |diff|   k3 KL     ratio outside [0.2, 5]
  auto (bf16)        6,141,936              0.0093        0.239        1.89e-4   0
  fp8                12,283,872             0.0210        0.675        1.07e-3   0
  fp8 / auto         2.00x                  2.26x                      5.6x
k3 KL: the mean over tokens of r - 1 - log r, r = p_trainer / p_generator (an estimate of KL(generator || trainer)).
For scale, the vLLM PR measured 2.3x mean |diff| and 3.5x k3 on another model (Qwen3.8-27B) and 27k-78k contexts.

The fp8 path ran: SGLang's KV pool dtype is float8_e4m3fn, and every attention hook call took the fp8 path
(1,032 calls at CUDA graph capture, 84 during generation, 0 on the bf16 path).

Kernel, the hook vs an fp32 reference on the same e4m3 values (rel L2; bar 0.05):
  decode rows (e4m3 q):    0.017, 0.022, 0.000
  prefill rows (bf16 q):   0.019, 0.007, 0.023

2x the KV tokens is not 2x the sessions on a hybrid model: fp8 halves only the KV bytes, and GDN states keep their size. Qwen3.5-0.8B: 12,288 B of KV per token in bf16 (6 attention layers x 2 x 2 KV heads x 256 x 2 B), and about 19.5 MB per GDN state (18 layers, mostly a 16 x 128 x 128 fp32 state each). A 10k-token session that holds 2-5 states takes 162-221 MB in bf16 and 100-159 MB in fp8: about 1.4-1.6x the sessions.

You may ask:

  • Why a private FA4 call? torch's varlen attention takes no fp8 inputs (pytorch/pytorch#206590 adds descales), and FA4's public varlen call has no out= to write into SGLang's output buffer. Same reason as the vLLM PR, whose TODO this PR keeps.
  • Why no scale tensors? SGLang's layers have none, and FA4 reads a missing scale as 1. Passing tensors of ones gives the same output bit for bit, but an eager decode call takes 120.8 us instead of 63.8 us (64 rows x 2,048 keys, one GB300, one probe run).

NOTE: end-to-end speed, Qwen3.5-0.8B on one GB300 under a 128-session agent load (a one-off harness, one run per arm): 6,443 vs 5,960 output tok/s with fp8 vs bf16 KV (+8%); decode steps 3.97 vs 4.77 ms. At this size the KV cache is never full, so the gain is the decode step alone.
NOTE: not tested with fp8, so it raises: TP > 1, DP > 1, sliding-window and MLA layers, a HiCache storage backend. Also not tested: calibrated KV scales.
NOTE: torchtitan/rl/generator/attention/attention.py picks FA4's fp8 forward by the cache dtype. The vLLM fp8 PR gets the same file in its next push, so whichever lands second merges it with no conflict.
NOTE: this PR and "[rl] SGLang generator: top-k logprobs for score centering" change adjacent lines of tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py: that PR's _before_trainer_forward hook and this PR's _assert_trainer_logprobs_match. Whichever lands second rebases. Their other shared files merge cleanly.
NOTE: fp8 KV cache with MTP drafts: whichever of this PR and "[rl] SGLang generator: MTP speculative decoding for Qwen3.5" lands second carries TestSGLangMTPFp8KVCache (the MTP test with kv_cache_dtype="fp8", about 40 lines, no production code). The two compose with no code change.

Test plan

  • 1 GPU (GB300, FA4 4.0.0b41, nvidia-cutlass-dsl 4.8.0):
    • pytest tests/rl/unit_tests/gpu/test_sglang_fp8_attention.py -v: 4 passed (decode and prefill rows through _paged_attention, head dims 256 and 128). Skipped without SGLang or off the SM100 family.
    • torchrun --nproc-per-node=1 -m pytest tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py::TestSGLangFp8KVCacheGDNHiCache -v: 7 passed, 2 skipped (92 s). A smoke test of the engine: the GDN HiCache engine tests with an fp8 KV cache at TP 1, trainer vs SGLang logprobs within mean |diff| 0.01 for a fresh prompt, a cached turn, a turn loaded back from host memory and a model state dict load; the pool dtype is e4m3. Measured 1.2e-3 to 1.9e-3 per sequence in three runs on a GB300 (CI runs a B200). Skipped: the two batch-invariance tests (fp8 runs outside batch-invariant mode).
    • Mutation check: with a k scale of 2.0 passed to FA4, this class still passes (mean |diff| 4.0e-3 to 6.2e-3: the random-weight model's attention is flat), so it is a smoke test, as its docstring says. The kernel test catches the wrong scale: its 4 cases fail (rel L2 0.70-0.74, bar 0.05).
    • Both added to the B200 RL CI job's SGLang step.
  • Engine check above: fp8_parity.py (a one-off script, not in the PR) builds the trainer and SGLangEngine in one process, once per kv_cache_dtype.
  • Refusals: a CPU probe builds SGLangEngine.Config(kv_cache_dtype="fp8") with DP 2, TP 2, DeepSeek V3 debug (MLA), Muse Glimmer debug (sliding windows) and a Mooncake storage backend: each raises its ValueError.
  • CPU: pytest tests/rl/unit_tests/cpu: 771 passed, 8 skipped, 2 failed. The 2 fail on main too: test_kv_offload_coordination.py::test_terminal_cleanup_preserves_block_identity, 2 cases.
  • pre-commit on the changed files (pyrefly excludes torchtitan/rl/): all hooks pass.
  • Not run: the 2-GPU classes of test_sglang_bitwise_parity.py (this box has one GPU). They run with "auto", whose path is unchanged.

SGLangEngine.Config.kv_cache_dtype = "fp8" stores K and V in e4m3 (scale 1)
and runs FA4's fp8 forward for decode and prefill. "auto" (bf16) stays the
default and keeps the trainer's kernel. Setups no fp8 run covered raise.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 27, 2026
@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve, with two optional cleanups. See 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 -- fp8 is opt-in, "auto" runs exactly the code it ran before, the refusals cover everything untested, and the two items below are optional cleanups. A maintainer still needs to review.

What this PR does. It adds SGLangEngine.Config.kv_cache_dtype: Literal["auto", "fp8"]. "fp8" maps to SGLang's kv_cache_dtype="fp8_e4m3", and the key is reserved from extra_server_args. With an e4m3 pool, the TorchTitan SGLang backend casts q to e4m3, which matters for prefill (SGLang already casts decode q). It allocates a bf16 output and sends the call to FA4's private _flash_attn_fwd with scale-1 TensorwiseScales, the same fp8 branch #6365 adds to the shared paged_varlen_attention_out. The engine refuses fp8 with batch invariance, TP > 1, DP > 1, sliding windows, MLA and Mooncake. The backend refuses it off SM100.

Example.

SGLangEngine.Config(kv_cache_dtype="fp8")  # Qwen3.5-0.8B, TP 1, GB300
# main:  no field; extra_server_args={"kv_cache_dtype": "fp8_e4m3"} sends e4m3 K/V
#        (and an e4m3 decode q) to torch's varlen_attn, whose FA4 bridge rejects them
# PR:    KV pool float8_e4m3fn, 12.28M tokens vs 6.14M; decode and prefill rows go to
#        FA4 fp8 with bf16 out; trainer-vs-SGLang mean |logprob diff| 0.0210 vs 0.0093
SGLangEngine.Config(kv_cache_dtype="fp8") + debug.batch_invariant / TP 2 / DSV3 (MLA)
# PR:    ValueError naming the setup, "set kv_cache_dtype='auto'"

Should consider

  • torchtitan/rl/generator/attention/attention.py:63 -- the fp8 path is chosen by descales is not None, so SGLang passes (None, None, None) only as a signal. Dispatching on the cache dtype removes the sentinel. This file is shared with #6365.
  • torchtitan/rl/generator/sglang/attention/attention.py:59 -- the SM100 refusal could join the other fp8 refusals in SGLangEngine.__init__, so it fails before the scheduler is built.
Details
  • Gate. The problem is real on main: there is no fp8 field, and a raw extra_server_args key reaches torch's varlen bridge, which takes only fp16/bf16. The layer is right: engine config plus the engine's attention backend, with the kernel call in the shared generator attention module both engines use. The private _flash_attn_fwd call has a TODO pointing at pytorch/pytorch#206590. There is no trainer side, since the trainer has no KV cache, so question 8 doesn't apply. Value: 2.00x KV tokens and +8% output tok/s end to end (one run per arm), at 2.3x the logprob gap. That is a fair trade for an opt-in knob.
  • Counterpart. #6365 (vLLM, bot-approved) uses the same config field, the same batch-invariance and sliding-window refusals, and the same FA4 branch. The shared file differs only in the descales annotation and the second TODO, which the description says #6365 will adopt. Until it does, the second PR to land has a small textual conflict there.
  • Overlap search. "fp8 KV cache", "paged_varlen_attention_out", "SGLang generator": #6365, #6366, #6414 (MTP; the description assigns TestSGLangMTPFp8KVCache to whichever lands second), and #6379 (adjacent test lines). Each has a stated rebase plan.
  • "auto" path. descales=None, and out keeps q.dtype, so nothing changes. The FA4 floor bump to b39 is needed for TensorwiseScales in both PRs.
  • MLA detection (engine.py:290) checks layer.attention.inner_attention against MLAAttention.Config, the same way sglang/model_wrapper.py:128 recognizes MLA, so DeepSeek V3 and Kimi K3 are both caught.
  • Calibrated scales. If SGLang ever passes k_descale/v_descale, the hook's existing unsupported kwargs check raises instead of silently using scale 1.
  • Tests. The kernel test catches a wrong scale (per the mutation check). The engine class guards pool-dtype plumbing and HiCache copies of fp8 KV. Neither duplicates an existing test.

Not verified: SGLang's decode-path q cast and out allocation under fp8 (SGLang source not available here; the description's call counts and parity numbers are the evidence), and GPU test results.

Before merge: fill in the human-written summary.

Returns:
The written ``out[:num_tokens]``, and the logsumexp with ``return_lse``.
"""
if descales is not None:

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.

Should consider: the fp8 path is picked by descales is not None, so SGLang has to pass (None, None, None) only to say "this is fp8". The kernel choice actually depends on the cache dtype, and that dtype already says it. You could dispatch on key_cache.dtype == torch.float8_e4m3fn and let descales=None mean scale 1 (TensorwiseScales() if descales is None else TensorwiseScales(*descales)). Then the annotation becomes tuple[torch.Tensor | None, ...] | None without the sentinel, and sglang/attention/attention.py:140 goes away. vLLM's call is unchanged, since it passes real tensors. This file is shared with #6365, so make the change in whichever PR lands first.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Kept as is for now, so the two fp8 PRs don't conflict.

  • This file is byte-identical to the vLLM fp8 PR's pending version ("[rl] vLLM generator: fp8 KV cache through FA4's fp8 forward, MTP verify steps included"). Whichever lands second merges it with no conflict.
  • If only this PR switched to dispatching on the cache dtype, the two PRs would conflict in paged_varlen_attention_out.
  • I agree the dtype is the better signal. It should land as one change to the shared file after both PRs, or in both PRs at once.
# today (both PRs)
if descales is not None:              # SGLang passes (None, None, None) to mean "fp8, scale 1"
# the suggestion, for the follow-up
if key_cache.dtype == torch.float8_e4m3fn:
    scales = TensorwiseScales() if descales is None else TensorwiseScales(*descales)

@felipemello1 felipemello1 Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done in 6a00a75. paged_varlen_attention_out now picks FA4's fp8 forward by the cache dtype, and the sentinel is gone. The vLLM fp8 PR gets the same file in its next push.

# before
if descales is not None:          # SGLang passed (None, None, None)
    ...
    scales=TensorwiseScales(*descales),
# after
if key_cache.dtype == torch.float8_e4m3fn:
    ...                           # no scales argument: every scale is 1
  • The descales argument and its docstring entry are gone. The key_cache docstring now says that an fp8 e4m3 cache runs FA4's fp8 forward with every scale 1.
  • The SGLang hook no longer builds or passes descales.
  • Without TensorwiseScales, the FA4 floor bump has no reason left, so both PRs keep main's >=4.0.0b38. That wheel already takes fp8 inputs without scales.

Comment on lines +59 to +66
if (
model_runner.kv_cache_dtype == torch.float8_e4m3fn
and torch.cuda.get_device_capability()[0] != 10
):
raise ValueError(
"An fp8 KV cache runs FA4's fp8 forward, which needs an SM100-family "
f"GPU; got capability {torch.cuda.get_device_capability()}"
)

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.

Should consider: kv_cache_dtype is now reserved from extra_server_args, so SGLangEngine.Config.kv_cache_dtype is the only way to get an fp8 pool. That means this refusal could go into the untested / refusal block in SGLangEngine.__init__, next to the other fp8 checks. There it fails before register_to_sglang and Scheduler(...) instead of inside backend construction, and all fp8 refusals live in one place. If you keep it here, leave it as is. It is correct, just later.

@felipemello1 felipemello1 Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Kept here. It checks the pool dtype SGLang actually built (model_runner.kv_cache_dtype), in the backend whose hook calls FA4's fp8 kernel.

It still fails during the engine build, before any request: SGLang constructs this backend while it builds the model runner. Moving the check to SGLangEngine.__init__ would fail earlier, before SGLang loads the model and allocates the pools. It would not change what is refused.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review (6a00a75: fp8 path picked by the cache dtype, as in your thread-1 suggestion; FA4 floor back to main's)

@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the item before merging (the PR description says the shared attention file is byte-identical to #6365's, but #6365's HEAD still carries descales/TensorwiseScales for vLLM's calibrated scales). See 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 -- please address the item below before merging. be6e0b8 and 6a00a75 make the change correctly for this PR: the fp8 path is chosen by the cache dtype, the sentinel is gone, and the floor is main's again. The one remaining item is a description note that is out of date with #6365. A maintainer still needs to review.

What changed since the last review. paged_varlen_attention_out now takes FA4's fp8 forward when key_cache.dtype == torch.float8_e4m3fn. It no longer has a descales argument and passes no scales=, so every scale is 1. The SGLang hook only casts q and allocates a bf16 out. Dropping TensorwiseScales removes the reason for the b39 floor, so install_rl_env.sh and validate_release_gpu.sh are back at >=4.0.0b38 and no longer show up in the PR diff.

Example.

# torchtitan/rl/generator/attention/attention.py:58
# before (20c4e7d): if descales is not None: ... scales=TensorwiseScales(*descales)
#                   SGLang passed descales=(None, None, None) only to select fp8
# now:              if key_cache.dtype == torch.float8_e4m3fn: ...  # no scales -> all 1
# vLLM on main:     vllm/attention/attention.py:233 asserts kv_cache_dtype isn't fp8,
#                   so the new dtype branch is reachable only from SGLang

Must fix

  1. The PR description doesn't match #6365. The NOTE says this file "is byte-identical to the vLLM fp8 PR's version", and the reply on thread 1 says the change was made "in both this PR and the vLLM fp8 PR". #6365's HEAD (0e7ce67, last pushed 2026-11-26) still has descales: tuple[...] | None = None, if descales is not None: and scales=TensorwiseScales(*descales). Its vLLM hook passes the real layer._k_scale/_v_scale, and its test uses scales (2.0, 0.5, 4.0). So the shared function can't stay byte-identical as written. #6365 needs real scales, which this version has removed. If #6365 rebases by taking this file as is, vLLM silently runs scale 1 over calibrated K/V. Fix one of two ways:

    • Push the matching #6365 change: the dtype dispatch, plus scales=TensorwiseScales(*descales) if descales is not None else None or equivalent, keeping the descales argument there.
    • Reword the NOTE: whichever PR lands second re-adds descales for vLLM's calibrated scales, so the shared file needs a real merge.

    Either way, a description edit or a push to the other PR. This PR's code doesn't change.

Questions

  • The floor is >=4.0.0b38, but the kernel test and the engine test ran on 4.0.0b41. Does b38's _flash_attn_fwd accept e4m3 q/K/V with no scales (unverified: no FA4 here)? If it doesn't, a b38 install fails inside FA4 with an error rather than producing wrong numbers. CI installs the newest wheel, so CI wouldn't notice.
Details
  • Earlier findings.
    • Thread 1 (sentinel): resolved in be6e0b8. The author went further than my suggestion and dropped descales entirely. With no in-repo consumer of non-unit scales on main, that is the minimal choice here. The cost lands on #6365 (item 1).
    • Thread 2 (SM100 check placement): the author's reply holds. The check reads the pool dtype SGLang actually built, and it still fails during engine build, before any request is served. Dropped.
  • Re-review scope. Every commit since the last full review (20c4e7d): the main merge 88dea29, be6e0b8 and 6a00a75. The merge adds no conflict resolution in PR files. The rest of the diff is unchanged from the reviewed version.
  • Dtype dispatch safety. The branch checks only key_cache.dtype. query is documented as e4m3 with an fp8 cache. The SGLang hook casts it (sglang/attention/attention.py:138, a no-op for decode), and the kernel test covers both decode (e4m3 q) and prefill (bf16 q). A future caller with calibrated scales would get scale 1 silently. The docstring now states that contract, and the only such caller is #6365 (item 1).
  • Overlap search. "fp8 KV cache", "paged_varlen_attention_out", "SGLang generator": #6365 (vLLM fp8; shared file diverges, item 1), #6414 (MTP; TestSGLangMTPFp8KVCache goes with whichever lands second), #6379 (adjacent test lines). direction.md has no migration that supersedes this.

Not verified: GPU test results at HEAD, and FA4 b38's fp8 support.

Before merge: fill in the human-written summary.

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

1 participant