Repository navigation
fix(fp4,vptq): keep stored bias wide through the linear epilogue - #3753
Conversation
Both FP4 and VPTQ narrowed the stored bias to the activation dtype before the reduction. An FP32 -65536 bias became -inf as FP16, and a finite dot near the FP16 limit was rounded before the bias cancelled it. With a unit weight, sixteen 4096 FP16 activations, and that bias, the correct output is zero but the fixed paths returned -inf on CPU, ROCm, and CUDA (VPTQ), and FP4 CPU disagreed with its own FP32 oracle. - Add linear_wide_bias, linear_needs_wide_bias, and promote_bias to _numerics: a wider stored bias is added after a wide reduction and the output is rounded once; a narrower bias is widened losslessly. - Route FP4 CPU/accelerator and VPTQ Torch/CUDA dense forward through it, and skip the native VPTQ fused kernel when the bias cannot widen, since that kernel requires the output dtype. - Keep the VPTQ bias buffer in FP32 so a checkpoint value survives packing, and reject values FP32 cannot store exactly. - Add regressions against an independent FP64 oracle for FP4, VPTQ, and the shared helper, plus the persistent-storage check for the VPTQ path. - Document the flow, the before/after mechanisms with file:line evidence, and the failure paths under docs/low-precision-bias-epilogue.md.
1e8b8da to
7489032
Compare
Follow-up to the wide-bias epilogue work in this branch. * `linear_wide_bias` flattened the activation and then added the bias to the 2-D product, so a per-token (non-1-D) bias that `main` accepted now raised a shape error. Add the bias after reshaping when it does not broadcast against the flattened product, which keeps the documented broadcast semantics and the wide cancellation. * `VPTQCudaLinear` skipped the native fused kernel for every layer whose stored bias was FP32. With the FP32 buffer this branch introduced, that disabled the fused decode path for every biased layer. The kernel adds the bias after its own FP32/FP64 accumulation and only requires the storage dtype, so narrow a representable bias losslessly and keep the fused path. A value FP16/BF16 cannot hold still takes the FP32 epilogue. * `_build_fp4_forward_module` narrowed the checkpoint bias to the activation dtype before `TorchFP4Linear` could apply the wide epilogue, turning an FP32 `-65536` into FP16 `-inf`. Keep the stored width. * Correct the CPU/HIP claim in the reference pages: CUDA and HIP use the FP32 `out_dtype` GEMM, only CPU falls back to FP32 operands. Recorded on the reference hardware with the tests introduced here: the fused kernel is used again for representable biases (0.070 ms / 0.140 ms at 1/4 rows for 4096x4096 against 0.142 ms before this change), the broadcast regression is exact against an FP64 oracle for FP16 and BF16 on CPU and CUDA, and the FP4 CUDA path returns the oracle value for both dtypes. Tests: tests/kernels/test_linear_fp32_reduce.py, tests/kernels/test_fp4_cpu.py, tests/test_vptq.py, tests/test_auto_module_decoder.py, tests/kernels/test_fp8_kernel.py.
Follow-up to the wide-bias epilogue work in this branch. * `VPTQCudaLinear` recomputed the exact representability comparison on every forward. That comparison reads device memory, so it synchronises the host; on a 4096x4096 FP16 layer the fused kernel took 0.073 ms for one row against 0.021 ms without the gate, and 0.139 ms against 0.021 ms at four rows. Cache the answer under `tensor_cache_key`, which invalidates on `copy_` through the version counter. `load_quant_result` clears it explicitly because `.data.copy_` does not bump an inference tensor's version. With the cache the fused layer costs 0.032 ms / 0.097 ms at one and four rows. * Add the missing regressions: a per-batch bias that only broadcasts after the output reshape raises a shape error on the flattened product; the FP4 checkpoint builder narrowed `-65536` to FP16 `-inf`; and the cached gate must follow both an in-place `copy_` and an explicit clear. Each new test was run against the pre-fix code and fails there. * Move the broadcast-bias regression to `tests/test_cpu_bias_cancellation.py` as well, so CPU-only CI covers it instead of the CUDA-gated file alone. Tests: tests/test_cpu_bias_cancellation.py, tests/test_auto_module_decoder.py, tests/kernels/test_linear_fp32_reduce.py, tests/kernels/test_fp4_cpu.py, tests/kernels/test_cuda_bias_epilogue.py, tests/kernels/test_fp8_kernel.py, tests/kernels/test_triton_fp32_reduce.py, tests/test_vptq.py.
The stored bias now survives at its checkpoint width (FP32 for VPTQ, the stored width for FP4), but the epilogue decision still keyed off the buffer dtype. Every ordinary checkpoint bias therefore took `linear_wide_bias`, which has no `out_dtype` GEMM on CPU and copies the whole weight to FP32 on every forward. Add `bias_narrows_losslessly` to prove an exact cast, and use it at each call site: `VPTQLinear._promote_stored_bias` for the Torch and VPTQ CUDA dense paths, and `TorchFP4Linear._epilogue_bias` for the CPU and torchao paths. A value the activation dtype cannot hold still keeps the wide epilogue. The check is recomputed per call. `tensor_cache_key` cannot observe `.data.copy_`/`.data.fill_`, so a cached answer stayed stale after an in-place write; the check costs microseconds against a full-weight decode. This removes the fused-kernel gate cache and its `clear_weight_cache` override. Measured on CPU, 4096x4096 FP16 decode: VPTQ 22.7 ms -> 4.8 ms (4.9 ms narrow baseline), FP4 33.6 ms -> 24.4 ms (21.6 ms baseline). Unrepresentable values still pay the wide path. Tests pin the value gate at each call site so deleting it fails, and the docs record the shipped line references and the transient-copy cost. Signed-off-by: ZX-ModelCloud <[email protected]>
ZX-ModelCloud
left a comment
There was a problem hiding this comment.
Reviewed commit 3fd1a2a. Two issues reproduced: checkpoint reload loses the newly preserved VPTQ bias precision, and the value-dependent representability check breaks CUDA Graph capture and fullgraph compilation. Details are attached inline.
Validation of the five suites (test_fp4_cpu, test_linear_fp32_reduce, test_cpu_bias_cancellation, test_vptq, and test_auto_module_decoder): CUDA: 366 passed; ROCm: 272 passed, 94 skipped. Both runs excluded test_tiny_qwen3_vptq_cuda_smoke, as noted in the PR. The additional reload and graph/compile reproductions are not covered by those passing suites.
|
Review notes: I checked the stored-bias promotion, value-based narrow/wide gate, FP4 and VPTQ call sites, and call-local decoded-weight lifetime. The five changed bias/decoder suites passed locally ( |
Qubitium
left a comment
There was a problem hiding this comment.
Reviewed the FP4/VPTQ stored-bias epilogues and integrated the branch with current main. The five changed suites pass locally (366 cases plus the separately rerun VPTQ CUDA smoke); affected cross-suite checks pass after integration (99 passed, 7 HIP-only skipped), and a direct CUDA FP4 cancellation case returned the FP64-oracle zero. Ruff and diff checks pass. Validation details are in the PR discussion.
|
Final review update for head |
The before/after table cited `models/base.py:3795-3802`, which is the `TorchFP8Linear` construction, and described "Before" as the state of `main`. The narrowing it describes was removed by PR #3753, so it never existed on `main`, and the FP4 decoder lives in `_build_fp4_forward_module` (`models/base.py:3831-3875`, bias at 3871). Cite the decoder symbol and its bias line, and state that "Before" is the pre-#3753 code for every row. The diagram paragraph now names the builder instead of two comment lines.
* test(fp4): pin the graph-safe bias gate on the FP4 wrapper `bias_narrows_losslessly` now short-circuits while a CUDA Graph is capturing or `torch.compile` is tracing, but only the VPTQ forward had capture/replay and fullgraph coverage. Both quantizers call the same helper, so exercise the FP4 accelerator wrapper with a stored FP32 `-65536` bias as well; without the escape hatch the capture fails with "operation failed due to a previous error during capture". Document the two new control flows, the checkpoint preservation lists and the capture/compile short-circuit, so the reference page matches the shipped decision path. * test(fp4): select the wide epilogue for both activation dtypes `bias_narrows_losslessly(-65536.0, torch.bfloat16)` is `True`: BF16 holds that value exactly, so the BF16 parameterization returned `(bias.to(bfloat16), False)` and ran the stock torchao NVFP4 `F.linear`. `linear_wide_bias` was never called, and reverting `_epilogue_bias` to unconditional narrowing still passed it. Use `0.1`, which is inexact in both FP16 and BF16, assert that the wide epilogue is selected, and compare against an FP64 oracle. That also keeps every output finite: the old fixture returned `-inf` in part of the FP16 row, so the bitwise comparison was mostly asserting `-inf == -inf`. Document the FP4 checkpoint path separately, since it keeps the bias width in the decoder instead of the loader's preservation lists, and note that FP4 is not advertised on ROCm. * docs(fp4): point the bias-width rows at the FP4 decoder The before/after table cited `models/base.py:3795-3802`, which is the `TorchFP8Linear` construction, and described "Before" as the state of `main`. The narrowing it describes was removed by PR #3753, so it never existed on `main`, and the FP4 decoder lives in `_build_fp4_forward_module` (`models/base.py:3831-3875`, bias at 3871). Cite the decoder symbol and its bias line, and state that "Before" is the pre-#3753 code for every row. The diagram paragraph now names the builder instead of two comment lines. * test(fp4): replay the live bias and pin the VPTQ fused-oracle tolerance The FP4 capture/compile regression only replayed the bias value that was present at capture time, so a graph that baked in that value — or a forward that cached the representability answer, which `.data` writes do not bump a version counter for — would still have passed. Replay three `.data.fill_` values and compare each against an FP64 oracle, which is the FP4 counterpart of `test_vptq_bias_epilogue_captures_and_replays_live_values`. `test_vptq_cuda_representable_wide_bias_keeps_fused_kernel` compared the fused kernel against the FP64 oracle bitwise on unseeded activations. The kernel accumulates in FP32 (FP64 for BF16) and rounds once, so its partial-sum order differs from the oracle's; measured over 200 random draws per dtype the spread is at most 2 ULP and eager FP32 accumulation reproduces most draws exactly, which made the test fail intermittently in a full-suite run. Keep the documented `2e-3` inference limit instead of a bit pattern the kernel is not required to produce. Document that a captured or compiled layer with a representable FP32 bias stays on the wide epilogue while eager takes the cheap one. The result is bitwise identical; only the kernel changes, and the extra private-pool memory is recorded.
… path (#3764) Two pre-existing failures on `f68935b61` were stale test contracts, not regressions from the CPU fusion work. QQQ oracle double-rounded the bias. `test_qqq_cpu.oracle` narrowed `accum * scale * channels` to the activation dtype and then added the bias, while the kernel (qqq.py:722, per #3753) keeps the INT8 reduction and its scales in FP32, adds the bias there, and rounds once. On `test_qqq_bias_noncontiguous_and_empty` the double round disagreed on 446/1792 elements by one visible step (<= 0.0039). Bias is now added in FP32 before the single narrowing cast, which makes the oracle match the module bitwise for both float16 and bfloat16. EXL3 audit test pinned a path deleted by #3731. #3717 asserted wide inputs reached the native kernel with FP32 input/output; #3731 (`86a59903e`) routed non-FP16 activations through `ExllamaV3TorchLinear`, whose inner takes only `x` and upcasts to FP32 internally. The stale stub therefore raised `TypeError: forward() missing 1 required positional argument`. The test now pins the live dispatch: wide inputs reach the Torch inner with the caller dtype and never touch `_ensure_inner`, FP16 keeps the native FP16 kernel with an explicit `out_dtype`, and each half asserts the other path is not taken. Added an end-to-end case where 1e10/1e-10 straddle the FP16 range so an FP16-first path would yield inf/0; the module stays finite and within 2e-3 relative L2 of the FP64 oracle. Verified on f68935b (AVX512-BF16 host, torch 2.15.0+cu132): - test_kernel_audit_regressions + test_qqq_cpu: 67 passed - the four exl3/qqq suites: 143 passed, 5 skipped - tests/module_tree fusion/fusable/module_plan: 728 passed, 633 skipped - test_torch_cpu_avx512(+_awq): 87 passed - 12-layout fusion sweep: all exact, err=0.0e+00
TL;DR
FP4 and VPTQ cast the stored bias to the activation dtype before the linear reduction. A finite dot product that the bias cancels was therefore rounded (or overflowed) first, so the layer returned
-infor a wrong value. The fix keeps a wider stored bias out of the low-precision operands, adds it after a wide reduction, and rounds once.Keeping the bias wide at its stored width made every ordinary checkpoint bias look wide, because the VPTQ buffer is FP32 by construction. The epilogue gate therefore keys off the stored values (
bias_narrows_losslessly), not the buffer dtype: an exactly representable bias still takes the cheap narrow epilogue, and only a value the activation dtype cannot hold pays for the wide path.1. The problem
Both implementations narrowed the bias before the reduction:
bias.to(dtype=x.dtype)beforeF.linear/ the torchao wrappergptqmodel/nn_modules/qlinear/fp4.py:78-83bias.to(dtype=x.dtype)beforelinear_fp32_reducegptqmodel/nn_modules/qlinear/vptq_torch.py:536-539bias.to(dtype=x.dtype)before the GEMMgptqmodel/nn_modules/qlinear/vptq_cuda.py:150-152gptqmodel/nn_modules/qlinear/vptq_cuda.py:117-120codebook_dtype, so packing lost the checkpoint rangegptqmodel/nn_modules/qlinear/vptq_torch.py:264-267flowchart LR A["Stored FP32 bias -65536"] --> B["bias.to dtype=x.dtype"] B --> C["FP16 -inf"] C --> D["FP16 dot 67584 + (-inf)"] D --> E["Output -inf, oracle 0"] classDef failure fill:#fce8e6,stroke:#a33,color:#111 class C,E failureReproduced on an unmodified
origin/maincheckout:-inf-infRuntimeError: VPTQ CUDA bias has an unexpected dtypeThe FP4 unit code decodes to
33/32, so the real dot is 67584 rather than 65536; the tests assert the measured quantized value.2. The new flow
flowchart TD A["Quantized linear forward"] --> B["Reconstruct temporary weight"] B --> C{"linear_needs_wide_bias: FP16/BF16 activation and wider stored bias?"} C -- "Yes" --> D{"bias_narrows_losslessly: is the cast exact?"} D -- "Yes" --> E["bias.to dtype=x.dtype: narrow epilogue"] D -- "No" --> F["linear_wide_bias: wide reduction, round once"] C -- "No" --> G["promote_bias: widen a narrower bias only"] G --> H{"_wants_fp32_reduce on NVIDIA CUDA?"} H -- "Yes" --> I["_CudaWideMatmul or torch.mm with FP32 output, bias in FP32"] H -- "No" --> J{"_fuse_bias_epilogue on CPU or HIP?"} J -- "Yes" --> K["torch.addmm, one epilogue"] J -- "No" --> L["F.linear with the promoted bias"] E --> M["Round once to the activation dtype"] F --> M I --> M K --> M L --> M M --> N["Release the temporary weight"] classDef failure fill:#fce8e6,stroke:#a33,color:#111 class O,P failure O["Old path: bias narrowed before the reduction"] --> P["-inf or a rounded partial sum"]linear_wide_biasrequests an FP32 output fromtorch.mmon NVIDIA CUDA, so the tensor-core operands stay FP16/BF16 and no expanded FP32 weight copy is retained. HIP acceptsout_dtypetoo, but_WIDE_REDUCE_DEVICESdeliberately keeps that request CUDA-only: HIP already accumulates these operands in FP32, and the extra request measured bitwise identical while costing latency and transient memory. CPU multiplies FP32 operands, because it has noout_dtypefortorch.mm. Autograd-active calls use the FP32 operand path, because the FP32-output CUDA ops have no autograd derivative.3. Per-subsystem detail
Dtype promotion contract
promote_biasis the inverse of the removed narrowing: a bias in a strictly narrower floating dtype is widened (lossless), and a wider or incomparable bias is returned unchanged so the caller adds it after the reduction. FP16 and BF16 are treated as equally wide because neither dtype contains the other.flowchart TD A["promote_bias x, bias"] --> B{"bias dtype == x dtype?"} B -- "Yes" --> C["Return bias unchanged"] B -- "No" --> D{"bias width < x width?"} D -- "Yes" --> E["bias.to dtype=x.dtype"] D -- "No" --> F["Return bias unchanged; caller adds after the reduction"]Exact-cast gate
bias_narrows_losslessly(bias, dtype)compares the cast against the source in FP64, so it rejects overflow (-65536as FP16), mantissa loss, and NaN, and preserves the sign of zero. It is recomputed per call, not cached:tensor_cache_keycannot observe.data.copy_/.data.fill_, which do not bump a version counter, so a cached answer stayed stale after an in-place write. The comparison costs microseconds against a full-weight decode.Two call sites consume it, so the decision reaches the reduction and not just a helper:
VPTQLinear._promote_stored_biasTorchFP4Linear._epilogue_biaswideflagVPTQ CUDA dispatch
flowchart TD A["VPTQCudaLinear.forward"] --> B["wide_bias = linear_needs_wide_bias and not bias_narrows_losslessly"] B --> C{"x dtype == codebook dtype and rows <= fused limit and not wide_bias?"} C -- "Yes" --> D["vptq_cuda_linear fused kernel"] C -- "No" --> E["_dequantize_cuda then linear_fp32_reduce"] E --> F["Wide bias added after a wide reduction"] classDef failure fill:#fce8e6,stroke:#a33,color:#111 class G,H failure G["Wide bias sent to the fused kernel"] --> H["RuntimeError: unexpected bias dtype"]VPTQ bias storage
The buffer is now FP32, and
load_quant_resultcopies the checkpoint value at its own width. A value FP32 cannot represent exactly raises instead of being silently rounded. Packed indices and codebooks remain the only persistent weight state.4. Failure and ambiguity contract
-infor a wrong valuebias_narrows_losslesslyproves the cast; narrow epilogue, no FP32 weight copy.data.copy_,.data.fill_)_fuse_bias_epiloguedeclines; the standalone expression keeps promotionload_quant_resultraises5. Change inventory
gptqmodel/nn_modules/qlinear/_numerics.pylinear_wide_bias,linear_needs_wide_bias,promote_bias,bias_narrows_losslessly, unified_fuse_bias_epiloguegptqmodel/nn_modules/qlinear/fp4.py_epilogue_bias, exact-cast gate for CPU/accelerator routinggptqmodel/nn_modules/qlinear/vptq_torch.py_promote_stored_bias; FP32 bias buffer and exact copygptqmodel/nn_modules/qlinear/vptq_cuda.pytests/kernels/test_fp4_cpu.py,tests/kernels/test_linear_fp32_reduce.py,tests/test_vptq.pydocs/low-precision-bias-epilogue.md,docs/vptq.md,docs/cuda-quantized-bias-epilogue.md,README.md6. Tests / guarantees
test_fp4_cpu_forward_keeps_fp32_bias_rangetest_fp4_cpu_forward_promotes_narrow_biastest_fp4_representable_fp32_bias_uses_narrow_epiloguetest_fp4_narrow_epilogue_rounds_once_for_representable_biastest_fp4_cpu_forward_uses_the_exact_cast_gateF.linearsees the activation dtype, and an inexact value reacheslinear_wide_biaswith FP32test_linear_fp32_reduce_never_narrows_wide_biastest_linear_fp32_reduce_wide_bias_layoutstest_vptq_wide_bias_cancels_without_dense_cachetest_vptq_representable_wide_bias_keeps_narrow_epiloguetest_vptq_unrepresentable_bias_still_opens_the_wide_epiloguetest_vptq_inplace_bias_write_reenables_the_wide_epilogue.data.fill_is observed on the next calltest_vptq_forward_consumes_the_exact_cast_gatetest_vptq_cuda_fused_bias_gate_follows_live_valuestest_vptq_cuda_wide_bias_skips_fused_kerneltest_vptq_pack_preserves_fp32_bias_rangeThe three call-site tests were mutation-checked: deleting the
_epilogue_bias/_promote_stored_biascall from the forward makes them fail.7. Validation
Run against an independent FP64 oracle with
rtol=0, atol=0(exact equality):tests/kernels/test_fp4_cpu.pytests/kernels/test_linear_fp32_reduce.pytests/test_vptq.pytest_fp4_cpu,test_linear_fp32_reduce,test_cpu_bias_cancellation,test_vptq,test_auto_module_decoder) on NVIDIA CUDAlinear_fp32_reduceand the VPTQ module match the FP64 oracle bitwise for FP16 and BF16 at M = 1, 2, 16, 128, 1024, and for non-contiguous 3D inputs. FP32 activations with an FP16 bias also promote correctly.ruff check gptqmodel tests setup.py docs/eorapasses. One unrelated failure,test_tiny_qwen3_vptq_cuda_smoke, aborts inside the P2P Hessian copy during quantization and fails identically on unmodifiedmain; it is excluded from the counts above and is not caused by this change.Epilogue cost
Measured on a 4096x4096 FP16 layer with resident inputs, one decode. Keying the epilogue off the buffer dtype alone would open the FP32 path for every checkpoint bias:
The wide path itself costs a transient FP32 weight copy on CPU:
12.4-14.7 msagainst0.10-0.14 msfor the fused low-precision epilogue. It is for correctness, not decode throughput, and an unrepresentable value still pays it.8. Reviewer notes
.datawrites, and the check is negligible next to the weight decode it guards.