Skip to content

perf(fp8): read block-scaled payloads once per forward (#5318) - #5340

Merged
Qubitium merged 1 commit into
mainfrom
perf/fp8-block-decode-5318
Nov 19, 2026
Merged

Qubitium merged 1 commit into
mainfrom
perf/fp8-block-decode-5318

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

Summary

Block-scaled FP8 payloads could not use the row/tensor epilogue from #5173: a
weight_block_size=[128, 128] scale varies along both axes of the reduction,
so the decoded weight has to exist for the GEMM. The portable path built it
with two full-weight passes per forward — a cast into the activation dtype and
then an in-place block scale — so a 1 B/element format moved ~9 B of traffic per
weight element before the GEMM ran. This is the production layout
(transformers FineGrainedFP8, DeepSeek/Qwen).

Net diff: 5 files, +1022/−3. One new Triton module, one payload-derived plan
inside TorchFP8Linear, one regression test file, one mechanism page.

Fixes #5318

Old flow

flowchart TD
    A["TorchFP8Linear.forward"] --> B["_forward_dequant_matmul"]
    B --> C{"_lean_epilogue_eligible"}
    C -- "row/tensor, range-safe" --> D["_forward_lean_scaled_matmul"]
    C -- "block" --> E["cast to activation dtype<br/>full-weight write"]
    E --> F["blocks.div_ or mul_<br/>full-weight read and write"]
    F --> G["matmul_fp32_reduce"]
    classDef cost fill:#fdd,stroke:#c00,color:#000
    class E,F cost
Loading

New flow

flowchart TD
    A["TorchFP8Linear.forward"] --> B["_forward_dequant_matmul"]
    B --> C{"_block_decode_eligible<br/>fused=True"}
    C -- "block payload, rows at or below measured limit" --> D["_forward_block_gemv<br/>scale applied inside the K loop"]
    C -- "no" --> E{"_block_decode_eligible<br/>fused=False"}
    E -- "block payload" --> F["_forward_block_decode<br/>one pass: codes and scale to activation dtype"]
    F --> G["matmul_fp32_reduce"]
    E -- "no" --> H["_lean_epilogue_eligible"]
    H -- "row/tensor" --> I["_forward_lean_scaled_matmul"]
    H -- "no" --> J["portable dequantize_weight"]
    D --> K["output"]
    G --> K
    I --> K
    J --> K
Loading
Path Weight traffic per forward Selected when
_forward_block_gemv reads the 1 B/element payload once; no decoded temporary block payload, float8_e4m3fn/float8_e5m2, CUDA, FP16/BF16 activations, exact divisible 128-wide column blocks, range-safe FP16 bound, no autograd graph, row count at or below the measured limit
_forward_block_decode reads 1 B/element, writes the activation dtype once the payload conditions above minus the fused kernel's row/GEMM/grad limits
_forward_lean_scaled_matmul reads 1 B/element, no decoded temporary row/tensor scales (unchanged, #5146)
portable decode the two-pass cast + scale everything the predicates reject: E8M0, AMD fnuz formats (Triton does not lower them), padded/cropped block scales, non-CUDA, ROCm, torch.compile/export, non-contiguous activations, zero inverse scales

Decision table

Situation Before After
CUDA, block payload, M ≤ fused limit two-pass cast + scale, then GEMM fused product; no decoded weight exists
CUDA, block payload, M above the limit two-pass cast + scale, then GEMM single-pass decode, then the shared FP32-reduced GEMM
Traced/exported graph two-pass Torch decode inside the graph unchanged (_is_compiling() declines the launch)
ROCm portable Torch decode unchanged
E8M0 / fnuz / padded block scale portable Torch decode unchanged
Zero inverse scale portable Torch decode unchanged (inf/NaN decode semantics)
Device or dtype move, reload, weight/scale rebind n/a decode plan recomputed; nothing is reused across payloads

The fused row limit is a measured crossover, not a correctness boundary: past
those row counts a general GEMM overtakes the decode-in-the-loop tiling and
the single-pass decode plus the shared GEMM is the faster of the two.

Projection width Fused product used up to
out_features < 2048 M = 64
out_features >= 2048 M = 192

Storage contract

The single-pass path allocates its decoded weight for the current call only
and releases it before the forward returns; the fused product allocates none.
The plan cache holds booleans and a storage-address key, never a tensor.
test_block_decode_keeps_no_decoded_weight_after_forward pins both.

Validation

All commands run in this worktree.

Command Result
python -m pytest tests/kernels/test_fp8_block_decode_5318.py -q 24 passed
python -m pytest tests/kernels/test_fp8_kernel.py tests/test_fp8_dequant_inplace.py tests/test_rocm_fp8_gating.py tests/test_fp8_packed_weight_lifecycle.py -q 149 passed, 6 skipped
python -m pytest tests/test_fp8_save_offload.py tests/test_fp8_bias_dtype_4575.py tests/test_fp8_bias_native_gemm_4681.py tests/test_fp8_bias_range.py tests/test_fp8_bf16_scale_reload.py tests/test_fp8_peft_lora_4948.py tests/test_fp8_load_peak_4387.py -q 48 passed
python -m pytest tests/kernels/test_kernel_compile_levels_quant.py -q 15 passed, 2 skipped (2:06)
bash format/check.sh All checks passed (ruff 0.14.2)
python -m pytest tests/kernels/test_fp8_block_decode_5318.py -q (ROCm) 24 skipped (decode is NVIDIA-only); the FP8 families on ROCm are unchanged apart from 4 BF16 cases that fail identically on the unmodified base

Red evidence

tests/kernels/test_fp8_block_decode_5318.py run against the unmodified base
(67de3469f, with only the new module importable) fails at the intended
assertion:

E  AssertionError: forward ran a full-weight in-place scale: ['div_']

The probe is a TorchFunctionMode that records in-place mul_/div_ on a
tensor with the decoded weight's element count. It does not name the function
under test, so it fails for the pre-fix cast-then-scale and passes once the
forward reads the payload once. The oracle, storage, and fallback nodes pass on
both trees by design.

torch.compile / CUDA graph

  • torch.compile(fullgraph=True, backend="eager") traces with 0 graph breaks
    and matching output; SUPPORTS_COMPILE_LEVEL is unchanged.
  • An explicit torch.cuda.graph capture replays with matching output.

Measured

Batch-1 decode, L2 flushed before each timed call, medians over ≥21 calls.
Before = the unmodified portable block decode; after = this change.

Projection (K × N) Before After Dense FP16 Gain
4096 × 1024 52.2 us 14.3 us 19.6 us 3.6×
4096 × 4096 156.7 us 28.7 us 48.1 us 5.5×
4096 × 14336 581.6 us 84.1 us 128.0 us 6.9×
14336 × 4096 574.5 us 89.1 us 136.2 us 6.4×

M=16 and M=64 show the same shape (wide projections 5–7×, narrow 2.8–3.4×).
M=128 keeps a 1.9–3.9× gain; M ≥ 256 is 1.5–1.7×, since the shared GEMM takes
over. Prefill remains slower than dense FP16 per element (the format's decode
cost), but the regression the issue reports is gone.

Kernel output equals an independent FP64 oracle within the activation dtype's
rounding limit (2e-3 FP16, 8e-3 BF16) on FP16/BF16, biased and bias-free,
inverse and multiplier semantics, M in 1/3/16/64/128; the accelerated and
portable decodes agree within 4e-3.

Skips and remaining gaps

  • tests/kernels/test_kernel_compile_levels_quant.py skipped 2 cases for
    unavailable native dependencies (the file's own recorded reasons).
  • The 6 skips in the FP8 families are the existing format/device gates
    (float8_e8m0fnu, _scaled_mm unavailable on the build, BF16 support).
  • The decode is qualified on NVIDIA CUDA only. ROCm keeps the portable Torch
    decode and is covered by gating tests, not by a native ROCm kernel
    qualification; enabling it there needs its own numerical evidence.
  • A real FineGrainedFP8 checkpoint load and end-to-end generate() timing
    were not exercised here; the measurements use synthetic payloads with the
    checkpoint's exact 128×128 layout and weight_scale_inv semantics.

Reviewer notes

  • The row limits are hardware-measured; a different device may have a
    different crossover. They are named constants in
    gptqmodel/nn_modules/qlinear/fp8.py and pinned by a test, so a re-measure
    is a two-line change.
  • The plan cache key includes both storage addresses and a generation
    counter, so trading the predicate cost for a dict lookup cannot outlive a
    payload swap.

Block-scaled checkpoints (FineGrainedFP8, DeepSeek/Qwen, block 128x128) could
not use the row/tensor epilogue of #5173: a block scale varies along both
reduction axes, so the decoded weight has to exist for the GEMM. The portable
path built it in two full-weight passes per forward -- a cast into the
activation dtype and then an in-place block scale -- so a 1 B/element format
moved ~9 B per weight element before the GEMM ran.

Add a single-pass Triton decode that reads codes and the block scale once, and
a fused W8A16 product that applies the scale inside the K loop and writes only
the output. Both keep FP32 arithmetic and round once, so the result matches
the reference decode. The fused product is selected at decode and small-prefill
row counts, where a measured crossover shows it beating a general GEMM; past
that the single-pass decode plus the shared FP32-reduced GEMM is faster.

The decode plan (layout, dtype, format, device family, range bound) is
payload-derived and cached per module, invalidated by a reload, a device or
dtype move, or a weight/scale rebind. Traced/exported graphs and ROCm keep the
Torch decode, and the temporary the single-pass path allocates is released
before the forward returns.

Fixes #5318
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants