Skip to content

[varlen] Add fp8 descales to varlen_attn and varlen_attn_out, and run fp8 SDPA on FA4 - #206590

Draft
felipemello1 wants to merge 6 commits into
pytorch:mainfrom
felipemello1:varlen-fp8-descales
Draft

felipemello1 wants to merge 6 commits into
pytorch:mainfrom
felipemello1:varlen-fp8-descales

Conversation

@felipemello1

Copy link
Copy Markdown
Contributor

Linked issue or supporting maintainer

Supported by @drisspg

BC-breaking?

No.

Summary (human written only)

Agent details (if applicable)

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

TLDR: varlen_attn and varlen_attn_out take q_descale, k_descale and v_descale. With fp8 query, key
and value they run FA4's (or FA3's) fp8 forward, with paged KV and num_splits. The output matches a direct
_flash_attn_fwd call bit for bit (GB300, flash-attn-4 4.0.0b31 and 4.0.0b40), and TorchTitan's direct call
(4.0.0b40). FA4 also runs the experimental dense fp8 SDPA now.

main:     fp8 q/k/v + descales -> no varlen API; TorchTitan calls FA4's private _flash_attn_fwd
this PR:  fp8 q/k/v + descales -> varlen_attn(_out) -> aten .quantized ops -> FA4 / FA3 bridge
          bf16 / fp16 q/k/v    -> varlen_attn(_out) -> aten default ops    (unchanged)
# main: TypeError, varlen_attn has no q_descale argument
# this PR: bf16 output, paged KV, one descale per sequence and KV head
out = varlen_attn(q_fp8, k_cache_fp8, v_cache_fp8, cu_seq_q, None, max_q, max_k,
                  block_table=block_table, seqused_k=seqused_k, num_splits=1,
                  q_descale=q_descale, k_descale=k_descale, v_descale=v_descale)  # descales: (batch, num_kv_heads) fp32

Problem

  1. aten already has an fp8 flash attention forward: _flash_attention_forward.quantized, which takes descales.
  2. It has no block_table and no num_splits, and the out= op behind varlen_attn_out has no fp8 form.
  3. varlen_attn takes no descales, and FA4's bridge rejects fp8 ("query dtype must be float16 or bfloat16").
  4. So TorchTitan's RL generator, which keeps an fp8 KV cache, calls FA4's private _flash_attn_fwd directly.

Solution

  1. _flash_attention_forward.quantized gets kwarg-only block_table and num_splits, as its default overload has.
  2. New _flash_attention_forward_no_dropout_inplace.quantized: the fp8 form of the out= op.
  3. FA4's bridge registers both, plus the dense _scaled_dot_product_flash_attention.quantized, which the
    experimental _scaled_dot_product_attention_quantized calls. FA3's bridge registers the new out= overload.
  4. varlen_attn(_out) routes by the query's dtype: float8_e4m3fn or float8_e5m2 go to .quantized. A missing
    descale means 1. The inputs are checked in Python before any kernel runs.
  5. Unchanged: the default ops, their FA2/FA3/FA4 paths and the bf16/fp16 rules.

Results (GB300, FA4 4.0.0b40 and 4.0.0b31; the same numbers on both unless noted)

vs TorchTitan's direct FA4 call (b40; its call needs TensorwiseScales, so b39+ only)
  24/24 equal on out; lse also equal in the 12 return_lse=True cases
  (paged; decode and verify rows at GQA 24:4 D256, mixed rows at GQA 8:2 D128; causal and window (128, 0);
   return_lse True and False; deterministic on and off)
vs FA4's _flash_attn_fwd, same inputs, torch.equal on out and lse
  b40: 72/72 equal  (GQA 24:4 D256 decode and verify rows, GQA 8:2 D128 mixed; paged and packed;
                     causal and window (128, 0); num_splits None, None + deterministic, 1; with and without out=)
  b31: 24/24 equal  (the D128 shape only: b31's head_dim 256 kernel has no SplitKV)
  num_splits reaches FA4: long-KV decode, num_splits=3 equals the direct call and differs from num_splits=1
varlen vs a bf16 varlen_attn on the dequantized inputs, max |error| / v_descale per (sequence, KV head)
  e4m3: 0.039 packed, 0.026 paged   (test bound 0.25)
  e5m2: 0.094 packed, 0.094 paged   (test bound 0.50)
  wrong descales fail: rows permuted across sequences 2.97-3.16, v_descale dropped 2.23-2.61
dense fp8 SDPA vs fp32 math SDPA on the dequantized inputs, max |error| / v_descale per (batch, KV head)
  e4m3: 0.062 not causal, 0.067 causal   (test bound 0.25; b40)
  e5m2: 0.114 not causal, 0.116 causal   (test bound 0.50; b40)
  v_descale dropped: 2.55-3.16
batch invariance: fp8 with num_splits=1 gives bit-identical output for a sequence alone or in a batch
test_varlen_attention.py: the same 175 failures before and after: 167 need the in-tree FA2 (not built here),
  8 are strict-xfail FA4 rows that pass on 4.0.0b40. Passed: 294 -> 311 (the 17 new tests).
test_fa4.py: the same 82 failures before and after, all from SDPA's backend check on a build without the
  in-tree flash kernels (81 "No available kernel", 1 can_use_flash_attention assert). Passed: 1 -> 5 (the 4 new
  tests).
schema BC check: passes against a schema dump of main

Behavior changes, fp8 inputs only:

  • FA3 already ran fp8 varlen_attn through the default ops, with descale 1 and a warning. It now runs the same
    FA3 function through .quantized, with the same output. The fake output is now bfloat16 (it said fp8 while
    FA3 returned bf16).
  • With no FA3 or FA4 active, an fp8 call raises the .quantized stub's error, not FA2's dtype error.

You may ask:

  • Why a new .quantized overload, not descales on the default out= op? Descales already live in .quantized.
    Adding them to the default op would change the FA2 kernel's C++ signature and need a v3 AOTI shim.
  • Why not torch.nn.attention.experimental? varlen_attn already has inference-only, impl-specific arguments
    (seqused_k, block_table, num_splits). A wrapper would copy its GQA checks and backend selection to call
    the same custom ops.
  • Why only bfloat16 output? FA3 and FA4 write bfloat16 for fp8 inputs.
  • Why no cuDNN? cuDNN varlen rejects fp8 inputs.
  • AOTI: .quantized gets a v2 C shim entry (block_table, num_splits); the new overload is listed like its
    default sibling. Both since 2.16.
  • Graph breaks: disallow_in_graph now lists the out= op's .default and .quantized overload objects too.
    Dynamo blocks by object id, so the packet entry alone does not cover them.

NOTE:

  • CI pins FA4 4.0.0b31, so CI tests the descale form of releases before 4.0.0b39 (q_descale= arguments). The
    bridge keeps that form for those releases. The TensorwiseScales form of 4.0.0b39+ was tested locally on b40.
    This PR does not move CI's pin.
  • The FA3 lines mirror its default overload and are untested: no SM90 GPU was available.
  • fp8 is forward only. A descale or input that requires grad raises before the kernel runs.

Test plan

python -m pytest test/test_varlen_attention.py -k "fp8 or batch_invariance"   # FA4 4.0.0b31 and 4.0.0b40
python -m pytest test/nn/attention/test_fa4.py -k fp8_sdpa                    # FA4 4.0.0b31 and 4.0.0b40
python -m pytest test/test_varlen_attention.py test/nn/attention/test_fa4.py
python -m pytest test/test_decomp.py::HasDecompTest::test_has_decomposition
python test/forward_backward_compatibility/check_forward_backward_compatibility.py --existing-schemas <dump from main>

New tests:

  • test_fp8_descales: e4m3 and e5m2, paged and packed, eager and torch.compile(fullgraph=True) for both
    varlen_attn and varlen_attn_out, plus opcheck's fake tensor test.
  • test_fp8_descales_errors.
  • An fp8 row in test_batch_invariance that compares with torch.equal.
  • test_fa4.py::test_fp8_sdpa_matches_dequantized_reference: e4m3 and e5m2, causal and not, GQA 8:2.

…rd ops

`_flash_attention_forward.quantized` (the fp8 flash attention forward) now takes the kwarg-only
`block_table` and `num_splits` that its default overload already has. A new overload,
`_flash_attention_forward_no_dropout_inplace.quantized`, is the fp8 form of the `out=` op behind
`varlen_attn_out`. Both CUDA kernels stay stubs that raise until FA3 or FA4 is activated, as the existing
`.quantized` op does. Their meta functions give a bfloat16 output for float8_e4m3fn and float8_e5m2.
The AOTI C shim gets a v2 of the first op and the new op, both since 2.16.

The new arguments are kwarg-only with defaults, so existing callers keep working. The schema BC check
passes against a schema dump of main.

Test Plan:
python test/forward_backward_compatibility/dump_all_function_schemas.py --filename main_schemas.txt  # on main
python test/forward_backward_compatibility/check_forward_backward_compatibility.py --existing-schemas main_schemas.txt
python -m pytest test/test_decomp.py::HasDecompTest::test_has_decomposition

Written with Claude Code (an AI assistant).
FA4's bridge now registers `_flash_attention_forward.quantized` and
`_flash_attention_forward_no_dropout_inplace.quantized`. They take float8_e4m3fn or float8_e5m2 query,
key and value with float32 descales of shape (batch, num_kv_heads), and write a bfloat16 output. FA4
runs the fp8 forward on SM100-family GPUs only. The descales reach `_flash_attn_fwd` as
`scales=TensorwiseScales(...)` on flash-attn-4 4.0.0b39 and later, and as `q_descale`, `k_descale` and
`v_descale` on older releases. The default overloads keep the float16 and bfloat16 rule.

FA3's bridge registers the new `out=` overload with the function it already uses for the default one,
which now passes the descales through.

Test Plan: the varlen tests in the next commit run these ops.

Written with Claude Code (an AI assistant).
`varlen_attn` and `varlen_attn_out` take kwarg-only `q_descale`, `k_descale` and `v_descale`. With fp8
query, key and value they call the `.quantized` flash attention ops, so paged KV (`block_table`,
`seqused_k`) and `num_splits` work in fp8 too. The output is bfloat16.

The inputs are checked before any kernel runs: descales need an fp8 query; query, key and value share
one fp8 dtype; each descale is float32 on CUDA with shape (batch, num_kv_heads); `out` is bfloat16; and
no input or descale requires grad, since fp8 runs forward only. `_validate_descale` and `DescaleType`
move from the experimental quantized SDPA module to `torch/nn/attention/_utils.py`, so the varlen module
does not import from `experimental`.

Test Plan:
python -m pytest test/test_varlen_attention.py -k "fp8 or batch_invariance"
python -m pytest test/test_varlen_attention.py
Both on a GB300 with flash-attn-4 4.0.0b31 and 4.0.0b40.

Written with Claude Code (an AI assistant).
FA4's bridge now registers `_scaled_dot_product_flash_attention.quantized`, the op behind the
experimental `_scaled_dot_product_attention_quantized`. It reuses the fp8 path of the flash ops: fp8
query, key and value (float8_e4m3fn or float8_e5m2) with float32 descales of shape (batch,
num_kv_heads), and a bfloat16 output in the query's layout. The op's meta now maps float8_e5m2 to a
bfloat16 output too. The C++ stub's error and the experimental docstring name FA4 next to FA3.

Test Plan:
```bash
python -m pytest test/nn/attention/test_fa4.py -k fp8_sdpa
```
Run on a GB300 with flash-attn-4 4.0.0b31 and 4.0.0b40.

Written with Claude Code (an AI assistant).
…ials

The fp8 dtype tuple now lives once in `torch/nn/attention/_utils.py`, used by the varlen API, the FA4
bridge and the two `.quantized` metas. FA4's two flash attention impls take the descales right after
`return_debug_mask`, where the `.quantized` schemas put them, so each `.quantized` overload is a
`functools.partial(impl, quantized=True)` instead of a wrapper. The comment on the pre-4.0.0b39
descale form now states which flash-attn-4 releases take it.

`test_fp8_descales` now compiles `varlen_attn_out` too, the fp8 tests skip with `IS_SM10X`, the
`varlen_attn_out` docstring says fp8 inputs need a bfloat16 `out`, and the descale batch error says
"number of sequences".

Test Plan:
```bash
python -m pytest test/test_varlen_attention.py -k "fp8 or batch_invariance"
python -m pytest test/nn/attention/test_fa4.py -k fp8_sdpa
python -m pytest test/test_varlen_attention.py test/nn/attention/test_fa4.py
```
Run on a GB300 with flash-attn-4 4.0.0b31 and 4.0.0b40.

Written with Claude Code (an AI assistant).
The comment on FA4's older descale form no longer repeats CI's flash-attn-4 pin, which lives in
another file. The `DescaleType` docstring says that `varlen_attn` always uses PER_HEAD, since it
takes no descale-type argument.

Test Plan: comment and docstring only. Lint:
```bash
lintrunner torch/nn/attention/_fa4.py torch/nn/attention/_utils.py
```

Written with Claude Code (an AI assistant).
@pytorch-bot

pytorch-bot Bot commented Nov 25, 2026

Copy link
Copy Markdown

Attention! native_functions.yaml was changed

If you are adding a new function or defaulted argument to native_functions.yaml, you cannot use it from pre-existing Python frontend code until our FC window passes (two weeks). Split your PR into two PRs, one which adds the new C++ functionality, and one that makes use of it from Python, and land them two weeks apart. See https://github.com/pytorch/pytorch/wiki/PyTorch's-Python-Frontend-Backward-and-Forward-Compatibility-Policy#forwards-compatibility-fc for more info.


Attention! PyTorch one of the C-stable API file was changed

You MUST NOT change existing function declarations in this, as this header defines a stable C ABI. If you need to change the signature for a function, introduce a new v2 version of the function and modify code generation to target the new version of the function.

@pytorch-bot

pytorch-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/206590

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit 02b2744 with merge base 8d5a301 (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant