Repository navigation
perf(fp8): lean W8A16 decode with exact codes and an FP32 scale epilogue - #5173
Merged
Merged
Conversation
…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.
This was referenced Nov 18, 2026
Qubitium
marked this pull request as ready for review
November 18, 2026 08:13
This was referenced Nov 18, 2026
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
FP8Config()defaults to weight-only W8A16, so CUDA AUTO loadsTorchFP8Linear. Every forward rebuilt the full decoded weight before theGEMM: 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:
dtype, run the GEMM on the
[out, in]weight's transposed view with anFP32 output, then apply the scale to that output and round once. No
decoded weight and no transpose copy.
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 #5146Root cause
_forward_dequant_matmulcalleddequantize_weightfor every forward, and_dequantize_nativedid four full-weight passes including a.transpose(0, 1).contiguous()whose only purpose was to handmatmul_fp32_reducean[in, out]operand.torch.mm/torch.addmmaccept the
[out, in]weight's transposed view directly, and a per-row scalecan 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 cost902f1a42e)_forward_dequant_matmul,gptqmodel/nn_modules/qlinear/fp8.py:938dequantize_weight,:588_dequantize_native,:628_dequantize_native,:628-669[in, out]weightNew 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_lean_epilogue_eligible,gptqmodel/nn_modules/qlinear/fp8.py:837_forward_lean_scaled_matmul,:878_forward_dequant_matmul,:938codes.t()view,:915:920-931:899-908dequantize_weight+matmul_fp32_reduce, unchangedMechanism page with the same diagrams:
docs/fp8-lean-decode-epilogue.md, linkedfrom 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 branchdisabled on the same packed module:
M=1
gate_projbreakdown: 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:generate()64 tokensThe 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_weightor the leanpath), 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||).Ordering argument: for a row scale
s,sum_k x_k * code_k / s = (sum_k x_k * code_k) / s, becausesis constant across the reduction foreach 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-fixreaches ~2.5e-3 RMS (max element~7.8e-3, about one BF16 weight ulp), which is larger than the existing
2e-3relative 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_w8a16oracle was corrected to model the newun-narrowed row/tensor arithmetic; its
rtol=atol=2e-3was left unchanged andstill passes. The new equivalence test uses a dtype-resolution bound
(
1e-3FP16,4e-3BF16) only for the lean-vs-pre-fix comparison and requiresthe lean path to be no less accurate than the FP64 oracle.
Storage
_forward_lean_scaled_matmulallocates 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_weightis called at all for a range-safepayload. The reference path still materialises a temporary decoded weight for
the current computation only.
Failure paths
0/0rows_expanded_scale_invfloat8_e8m0fnuFunctionTests
New regression suite
tests/kernels/test_fp8_lean_decode_5146.py:test_fp8_lean_decode_matches_fp64_oracledequantize_weightcalltest_fp8_lean_decode_retains_only_packed_weightstest_fp8_lean_decode_does_not_regress_to_fp32_roundtripRed/green evidence:
902f1a42e: in a disposable worktree at the base commit, all37new test cases fail at the intended assertions — e.g.assert decoded_calls == [](the pre-fix forward calleddequantize_weight),AssertionError: a full decoded weight was materialised for this forward, andFP8 forward 1551.1us is 5.1x the lean reference 304.2us; the FP32 round trip returned.37 passed.Existing FP8 suites (GPU 4):
The 6 skips are pre-existing
torch._scaled_mmformat limitations for E5M2 onthis GPU, not the lean path.
test_fp8_peft_lora_4948.py,test_lora_cuda_autograd.pyand the compile/graph-capture tests pass, so theautograd fallback and warmed CUDA graph capture still work.
ruff check gptqmodel docs/eora tests setup.pypasses.format/check.shitself cannot run in this container because its unconditional
pip install ruff==0.14.2is blocked by PEP 668; the sameruff checkcommandwas run with the installed ruff (0.17.4) and passed.
Files changed
gptqmodel/nn_modules/qlinear/fp8.py: lean gate, lean decode, zero-scalecache, invalidation.
tests/kernels/test_fp8_lean_decode_5146.py: new numerical, storage andthroughput 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 theold tests asserted the removed full-weight dequant; tolerances unchanged.
scripts/benchmark_fp8_decode_5146.py: documented per-layer before/afterbenchmark with
--check.docs/fp8-lean-decode-epilogue.md,README.md: mechanism page and link.Unverified
issue's sm_120 absolute numbers are not reproduced.
and
IS_ROCM-excluded); they were not benchmarked.correctness, not benchmarked.
out of scope.