Repository navigation
perf(fp8): read block-scaled payloads once per forward (#5318) - #5340
Merged
Merged
Conversation
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
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 costNew 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_forward_block_gemvfloat8_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_forward_lean_scaled_matmulfnuzformats (Triton does not lower them), padded/cropped block scales, non-CUDA, ROCm,torch.compile/export, non-contiguous activations, zero inverse scalesDecision table
_is_compiling()declines the launch)fnuz/ padded block scaleThe 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.
out_features < 2048out_features >= 2048Storage 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_forwardpins both.Validation
All commands run in this worktree.
python -m pytest tests/kernels/test_fp8_block_decode_5318.py -qpython -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 -qpython -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 -qpython -m pytest tests/kernels/test_kernel_compile_levels_quant.py -qbash format/check.shpython -m pytest tests/kernels/test_fp8_block_decode_5318.py -q(ROCm)Red evidence
tests/kernels/test_fp8_block_decode_5318.pyrun against the unmodified base(
67de3469f, with only the new module importable) fails at the intendedassertion:
The probe is a
TorchFunctionModethat records in-placemul_/div_on atensor 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 graphtorch.compile(fullgraph=True, backend="eager")traces with 0 graph breaksand matching output;
SUPPORTS_COMPILE_LEVELis unchanged.torch.cuda.graphcapture 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.
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.pyskipped 2 cases forunavailable native dependencies (the file's own recorded reasons).
(
float8_e8m0fnu,_scaled_mmunavailable on the build, BF16 support).decode and is covered by gating tests, not by a native ROCm kernel
qualification; enabling it there needs its own numerical evidence.
FineGrainedFP8checkpoint load and end-to-endgenerate()timingwere not exercised here; the measurements use synthetic payloads with the
checkpoint's exact 128×128 layout and
weight_scale_invsemantics.Reviewer notes
different crossover. They are named constants in
gptqmodel/nn_modules/qlinear/fp8.pyand pinned by a test, so a re-measureis a two-line change.
counter, so trading the predicate cost for a dict lookup cannot outlive a
payload swap.