Repository navigation
[rl] SGLang generator: fp8 KV cache through FA4's fp8 forward - #6413
felipemello1 wants to merge 5 commits into
Conversation
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.
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 3m 26s —— View job Approve, with two optional cleanups. See the review. |
There was a problem hiding this comment.
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 bydescales 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 inSGLangEngine.__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_argskey 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_fwdcall 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
descalesannotation 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
TestSGLangMTPFp8KVCacheto whichever lands second), and #6379 (adjacent test lines). Each has a stated rebase plan. - "auto" path.
descales=None, andoutkeepsq.dtype, so nothing changes. The FA4 floor bump to b39 is needed forTensorwiseScalesin both PRs. - MLA detection (
engine.py:290) checkslayer.attention.inner_attentionagainstMLAAttention.Config, the same waysglang/model_wrapper.py:128recognizes MLA, so DeepSeek V3 and Kimi K3 are both caught. - Calibrated scales. If SGLang ever passes
k_descale/v_descale, the hook's existingunsupportedkwargs 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: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)There was a problem hiding this comment.
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
descalesargument and its docstring entry are gone. Thekey_cachedocstring 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.
| 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()}" | ||
| ) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
…s; drop the descales sentinel
…s TensorwiseScales
|
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 |
There was a problem hiding this comment.
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 SGLangMust fix
-
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:andscales=TensorwiseScales(*descales). Its vLLM hook passes the reallayer._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 Noneor equivalent, keeping thedescalesargument there. - Reword the NOTE: whichever PR lands second re-adds
descalesfor 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.
- Push the matching #6365 change: the dtype dispatch, plus
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_fwdaccept e4m3 q/K/V with noscales(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
descalesentirely. 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.
- Thread 1 (sentinel): resolved in be6e0b8. The author went further than my suggestion and 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.queryis 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;
TestSGLangMTPFp8KVCachegoes with whichever lands second), #6379 (adjacent test lines).direction.mdhas 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.
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 atgpu_memory_limit0.5). The trainer-vs-generator logprob gap grows 2.3x (mean |diff| 0.0210 vs 0.0093).Problem
gpu_memory_limit0.5 holds 6.14M bf16 KV tokens on a GB300.--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.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
kv_cache_dtype: Literal["auto", "fp8"], as on the vLLM engine. "fp8" passeskv_cache_dtype="fp8_e4m3"to SGLang; the key joins_TORCHTITAN_SERVER_ARGS.paged_varlen_attention_outcalls FA4's private_flash_attn_fwdwhen the KV cache is fp8 e4m3, with the same code and TODOs as the vLLM PR.kv_cache_dtype='auto') fortensor_parallel_degree> 1,data_parallel_degree> 1, sliding-window layers, MLA layers and a HiCache storage backend (Mooncake).debug.batch_invariantraises too: the trainer runs bf16. The backend refuses fp8 off the SM100 family.Results
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:
pytorch/pytorch#206590adds descales), and FA4's public varlen call has noout=to write into SGLang's output buffer. Same reason as the vLLM PR, whose TODO this PR keeps.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.pypicks 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_forwardhook 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 withkv_cache_dtype="fp8", about 40 lines, no production code). The two compose with no code change.Test plan
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).fp8_parity.py(a one-off script, not in the PR) builds the trainer andSGLangEnginein one process, once perkv_cache_dtype.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.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.torchtitan/rl/): all hooks pass.test_sglang_bitwise_parity.py(this box has one GPU). They run with "auto", whose path is unchanged.