Skip to content

perf(fp8): lean W8A16 decode with exact codes and an FP32 scale epilogue - #5173

Merged
Qubitium merged 1 commit into
mainfrom
fix/5146-fp8-decode-path
Nov 18, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5146-fp8-decode-path

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

FP8Config() defaults to weight-only W8A16, so CUDA AUTO loads
TorchFP8Linear. Every forward rebuilt the full decoded weight before the
GEMM: FP8 → FP32, an FP32 divide, a narrow to the activation dtype, and a
contiguous transpose — about 23 B of traffic per weight element for a
1 B/element format. At batch-1 decode that traffic dominated the GEMM
(bs1 decode was ~10x dense FP16 in this environment).

This PR adds a lean decode path for range-safe payloads:

  • row/tensor scales: cast the exact FP8 codes straight to the activation
    dtype, run the GEMM on the [out, in] weight's transposed view with an
    FP32 output, then apply the scale to that output and round once. No
    decoded weight and no transpose copy.
  • block scales: cast the exact codes and divide them in place with the
    scale kept in FP32 (mixed-dtype opmath promotes to FP32 and rounds once).
    This is the same arithmetic as the reference path, without the FP32 weight
    temporary or the transpose copy.

Everything the gate rejects keeps the existing dequantize-then-matmul path
unchanged: ROCm, E8M0, autocast, zero inverse scales, padded block scales,
autograd that needs the wide-GEMM Function, and non-range-safe payloads.

Fixes #5146

Root cause

_forward_dequant_matmul called dequantize_weight for every forward, and
_dequantize_native did four full-weight passes including a
.transpose(0, 1).contiguous() whose only purpose was to hand
matmul_fp32_reduce an [in, out] operand. torch.mm / torch.addmm
accept the [out, in] weight's transposed view directly, and a per-row scale
can be applied to the FP32 product instead of the full weight.

Old flow

flowchart TD
    A["TorchFP8Linear.forward"] --> B["_forward_dequant_matmul"]
    B --> C{"_native_gemm_eligible"}
    C -- "range-safe FP16/BF16 CUDA" --> D["dequantize_weight(dtype)"]
    C -- "not range-safe" --> E["dequantize_weight(FP32)<br/>FP32 matmul"]
    D --> F["_dequantize_native<br/>FP8 to FP32, FP32 divide,<br/>narrow, transpose copy"]
    F --> G["matmul_fp32_reduce"]
    E --> H["output.to(dtype)"]
    classDef cost fill:#fdd,stroke:#c00,color:#000
    class F cost
Loading
Mechanism Before (902f1a42e)
Decode entry _forward_dequant_matmul, gptqmodel/nn_modules/qlinear/fp8.py:938
Full-weight decode dequantize_weight, :588
Native arithmetic _dequantize_native, :628
Transpose copy _dequantize_native, :628-669
GEMM operand contiguous [in, out] weight

New flow

flowchart TD
    A["TorchFP8Linear.forward"] --> B["_forward_dequant_matmul"]
    B --> C{"_lean_epilogue_eligible"}
    C -- "range-safe row or tensor" --> D["_forward_lean_scaled_matmul<br/>cast codes, mm on .t(),<br/>FP32 output scale"]
    C -- "range-safe block" --> E["cast codes, in-place FP32-opmath divide,<br/>mm on .t()"]
    C -- "ROCm, E8M0, autocast,<br/>zero scale, padded block,<br/>autograd, not range-safe" --> F["dequantize_weight<br/>reference path"]
    D --> G["FP32 product + bias,<br/>round once to activation dtype"]
    E --> H["matmul_fp32_reduce"]
    F --> I["existing dequantize-then-matmul"]
    classDef fallback fill:#ffd,stroke:#a60,color:#000
    class F,I fallback
Loading
Mechanism After
Decision _lean_epilogue_eligible, gptqmodel/nn_modules/qlinear/fp8.py:837
Lean decode _forward_lean_scaled_matmul, :878
Entry point _forward_dequant_matmul, :938
Row/tensor operand codes.t() view, :915
Row/tensor scale FP32 output epilogue, :920-931
Block scale in-place FP32-opmath divide, :899-908
Reference path dequantize_weight + matmul_fp32_reduce, unchanged

Mechanism page with the same diagrams:
docs/fp8-lean-decode-epilogue.md, linked
from the FP8 row of README.md.

Measurements

Device: physical GPU 4, NVIDIA RTX 4090, sm_89, torch 2.15.0+cu132, CUDA 13.2.
sm_120 was not available for this run: the coordinator restricted the work
to GPU 4, which is a 4090. The issue's sm_120 absolute numbers are therefore
not reproduced; the shape of the result is the same.

Per-layer, FP16, CUDA events, 100 iters after warmup, pre_fix = lean branch
disabled on the same packed module:

M projection dense FP16 pre-fix FP8 lean FP8 lean/dense pre-fix/lean
1 q_proj 4096x4096 17.8 us 311.8 us 61.1 us 3.44x 5.10x
1 gate_proj 4096x14336 97.0 us 1553.8 us 305.3 us 3.15x 5.09x
1 down_proj 14336x4096 95.8 us 1562.3 us 300.3 us 3.14x 5.20x
2048 q_proj 359.2 us 754.4 us 502.4 us 1.40x 1.50x
2048 gate_proj 1323.8 us 2795.0 us 1879.7 us 1.42x 1.49x
2048 down_proj 1321.4 us 2771.7 us 1562.7 us 1.18x 1.77x

M=1 gate_proj breakdown: cast 207.5 us, mm(..., out_dtype=fp32) 122.0 us,
epilogue 3.7 us, full forward 297.5 us. The remaining cost is the per-call
code cast; a fused W8A16 FP8 kernel is the follow-up (the issue's "longer
term" item), not part of this PR.

End-to-end, 4-layer Llama-3.1-8B-shaped model (hidden 4096, intermediate
14336, 880.8 M params), FP16, DynamicCache:

dense FP16 pre-fix FP8 lean FP8 lean vs pre-fix
decode step, bs1 2.17 ms 21.82 ms 5.12 ms 4.26x faster
prefill 512 6.5 ms 27.3 ms 9.9 ms 2.76x faster
prefill 2048 23.1 ms 44.8 ms 30.3 ms 1.48x faster
generate() 64 tokens 292.0 tok/s 41.8 tok/s 196.6 tok/s 4.70x faster

The lean path is still slower than dense FP16 at M=1 (2.36x decode) because it
must write and re-read a full FP16 copy of the weight. Removing that cast is
the fused-kernel follow-up.

Numerics

Independent FP64 dequant oracle (never calls dequantize_weight or the lean
path), same packed payload, M=1 and M=2048, FP16 and BF16, E4M3 and E5M2,
tensor/row/block scales, inverse and multiplier semantics. Errors are
normalized RMS (||actual - oracle|| / ||oracle||).

case lean vs FP64 oracle pre-fix vs FP64 oracle lean vs pre-fix
E4M3 row, FP16, M=1 0 2.9e-4 2.9e-4
E4M3 row, FP16, M=2048 1.5e-5 3.2e-4 3.2e-4
E4M3 row, BF16, M=1 0 2.6e-3 2.6e-3
E4M3 row, BF16, M=2048 1.9e-5 2.5e-3 2.5e-3
E4M3 block, FP16 3.0e-4 3.0e-4 0 (bitwise equal)
E4M3 block, BF16 2.5e-3 2.5e-3 0 (bitwise equal)
E5M2 tensor/row, FP16, M=1 0 2.7e-4 2.7e-4
E5M2 tensor/row, BF16, M=2048 1.2e-5 2.3e-3 2.3e-3
E5M2 block, FP16 3.1e-4 3.1e-4 0 (bitwise equal)

Ordering argument: for a row scale s, sum_k x_k * code_k / s = (sum_k x_k * code_k) / s, because s is constant across the reduction for
each output row. The FP32 output is what keeps the unscaled product in range:
the codes carry the inverse scale, so the unscaled product can exceed the
activation dtype's finite range even when the decoded weight is in range.
Applying the scale in FP32 and rounding once is at least as accurate as
dividing each weight in FP32 and rounding it to the activation dtype before
the GEMM, which is exactly what the measurements show.

Honest note on BF16: lean vs pre-fix reaches ~2.5e-3 RMS (max element
~7.8e-3, about one BF16 weight ulp), which is larger than the existing 2e-3
relative tolerance for a few elements. This is not a loosened tolerance:
the pre-fix path is the less accurate one because it rounds the whole decoded
weight to BF16, while the lean path is ~100x closer to the FP64 oracle
(1.9e-5 vs 2.5e-3). The existing
test_fp8_default_forward_is_w8a16 oracle was corrected to model the new
un-narrowed row/tensor arithmetic; its rtol=atol=2e-3 was left unchanged and
still passes. The new equivalence test uses a dtype-resolution bound
(1e-3 FP16, 4e-3 BF16) only for the lean-vs-pre-fix comparison and requires
the lean path to be no less accurate than the FP64 oracle.

Storage

_forward_lean_scaled_matmul allocates the cast codes for the current call;
block scaling mutates that fresh tensor in place. Nothing is stored on the
module, in a buffer, closure or compiled graph constant. After repeated
forwards the module still holds only the FP8 codes, FP32 scales and FP32 bias;
the test also fails if dequantize_weight is called at all for a range-safe
payload. The reference path still materialises a temporary decoded weight for
the current computation only.

Failure paths

Situation Behaviour
Decoded weight outside the activation dtype's finite range reference FP32 dequant + FP32 matmul
Zero inverse scale reference path; the epilogue cannot reproduce 0/0 rows
Block scale shape does not match the weight reference path; padded/cropped scales keep _expanded_scale_inv
float8_e8m0fnu reference path; its CUDA cast produces NaNs
ROCm reference path; native FP8 casts are not qualified there
Autocast active reference path; the GEMM operands are narrowed by autocast
Autograd needs the wide-GEMM Function reference path
Native cast previously disabled reference path

Tests

New regression suite tests/kernels/test_fp8_lean_decode_5146.py:

Test Invariant
test_fp8_lean_decode_matches_fp64_oracle tensor/row/block × inverse/multiplier × FP16/BF16 × M=1/257 match the FP64 oracle; the pre-fix path is not more accurate; no dequantize_weight call
test_fp8_lean_decode_retains_only_packed_weights repeated forwards leave only FP8 codes + FP32 scale + FP32 bias; no decoded weight is materialised
test_fp8_lean_decode_does_not_regress_to_fp32_roundtrip 4096x14336 M=1 stays within 1.8x of the cast+GEMM+epilogue emulation and 6x of dense FP16

Red/green evidence:

  • Red on 902f1a42e: in a disposable worktree at the base commit, all
    37 new test cases fail at the intended assertions — e.g.
    assert decoded_calls == [] (the pre-fix forward called
    dequantize_weight), AssertionError: a full decoded weight was materialised for this forward, and FP8 forward 1551.1us is 5.1x the lean reference 304.2us; the FP32 round trip returned.
  • Green on this branch: 37 passed.

Existing FP8 suites (GPU 4):

python -m pytest tests/test_fp8.py tests/test_fp8_save_offload.py \
  tests/test_fp8_peft_lora_4948.py tests/test_fp8_packed_weight_lifecycle.py \
  tests/test_fp8_nonfinite_source.py tests/test_fp8_bias_range.py \
  tests/test_fp8_load_peak_4387.py tests/test_fp8_bf16_scale_reload.py \
  tests/test_fp8_bias_native_gemm_4681.py tests/test_fp8_bias_dtype_4575.py \
  tests/test_fp8_dequant_inplace.py tests/kernels/test_fp8_kernel.py \
  tests/kernels/test_fp8_lean_decode_5146.py \
  tests/kernels/test_inference_numeric_range.py \
  tests/kernels/test_cuda_bias_epilogue.py \
  tests/kernels/test_compile_capability_4739.py \
  tests/test_generation_compile_policy_4669.py -q
831 passed, 6 skipped

The 6 skips are pre-existing torch._scaled_mm format limitations for E5M2 on
this GPU, not the lean path. test_fp8_peft_lora_4948.py,
test_lora_cuda_autograd.py and the compile/graph-capture tests pass, so the
autograd fallback and warmed CUDA graph capture still work.

ruff check gptqmodel docs/eora tests setup.py passes. format/check.sh
itself cannot run in this container because its unconditional
pip install ruff==0.14.2 is blocked by PEP 668; the same ruff check command
was run with the installed ruff (0.17.4) and passed.

Files changed

  • gptqmodel/nn_modules/qlinear/fp8.py: lean gate, lean decode, zero-scale
    cache, invalidation.
  • tests/kernels/test_fp8_lean_decode_5146.py: new numerical, storage and
    throughput regressions.
  • tests/kernels/test_fp8_kernel.py, tests/test_fp8_bias_range.py,
    tests/test_fp8_bias_native_gemm_4681.py: model the new arithmetic where the
    old tests asserted the removed full-weight dequant; tolerances unchanged.
  • scripts/benchmark_fp8_decode_5146.py: documented per-layer before/after
    benchmark with --check.
  • docs/fp8-lean-decode-epilogue.md, README.md: mechanism page and link.

Unverified

  • sm_120 was not available; all measurements are sm_89 (RTX 4090). The
    issue's sm_120 absolute numbers are not reproduced.
  • ROCm, XPU, MPS and CPU are unchanged by design (the lean gate is CUDA-only
    and IS_ROCM-excluded); they were not benchmarked.
  • Training/autograd still takes the reference path; it was tested for
    correctness, not benchmarked.
  • The fused W8A16 FP8 kernel that would remove the remaining per-call cast is
    out of scope.

…5146)

The default FP8Config() forward rebuilt the whole decoded weight on every
call: FP8 -> FP32, an FP32 divide, a narrow to the activation dtype, and a
contiguous transpose, about 23 B of traffic per weight element before the
GEMM. At batch-1 decode the weight traffic dominated.

For range-safe row/tensor scales, cast the exact FP8 codes straight to the
activation dtype, run the GEMM on the [out, in] weight's transposed view with
an FP32 output, and apply the scale to that output before rounding once. The
FP32 output keeps the unscaled product in range because the codes carry the
inverse scale. Block scales cast the exact codes and divide them in place
with the scale kept in FP32, which is the same arithmetic as the reference
path without the FP32 weight temporary or the transpose copy.

Everything the lean gate rejects (ROCm, E8M0, autocast, zero inverse scales,
padded block scales, autograd needing the wide-GEMM Function, and non-range-safe
payloads) keeps the existing dequantize-then-matmul path unchanged. No decoded
weight is retained between calls.

Measured on an RTX 4090 (sm_89, torch 2.15.0+cu132), 4096x14336, M=1:
dense FP16 97 us, pre-fix FP8 1554 us, lean FP8 305 us (5.1x faster). A
4-layer Llama-3.1-8B-shaped model decodes at 5.12 ms/step instead of 21.82 ms
(dense 2.17 ms). The remaining per-call code cast is the follow-up fused-kernel
work.

Adds a numerical equivalence/storage/throughput regression suite, a benchmark
script, and docs/fp8-lean-decode-epilogue.md with the before/after flow.
@Qubitium
Qubitium marked this pull request as ready for review November 18, 2026 08:13
@Qubitium
Qubitium merged commit 7d4797c into main Nov 18, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/5146-fp8-decode-path branch November 18, 2026 08:13
Qubitium pushed a commit that referenced this pull request Nov 19, 2026
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

Development

Successfully merging this pull request may close these issues.

1 participant