Skip to content

fix(torch): keep a stored wide bias through the GPTQ fallback epilogue - #3786

Merged
Qubitium merged 1 commit into
mainfrom
fix/torch-fallback-wide-bias
Nov 12, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/torch-fallback-wide-bias

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

TL;DR

TorchLinear._forward_eager cast the stored bias to the activation dtype
before the reduction. An FP32 bias that must cancel the partial sum was
therefore rounded (or overflowed) first, and the result depended on which
branch the batch size selected. The fallback now keeps that bias at its stored
width, and matmul_fp32_reduce adds it after a wide reduction and rounds once.
Net diff: +36/-9 in torch.py, +12/-2 in _numerics.py, one new test
module, one docs section.

1. The problem

nn_modules/qlinear/torch.py:446 on main:

if bias is not None and (bias.device != x.device or bias.dtype != x.dtype):
    bias = bias.to(device=x.device, dtype=x.dtype)
out = matmul_fp32_reduce(x, weights, bias=bias).reshape(out_shape)

Reproduction (K=256, N=128, weight all 1, activation 256, FP32 bias
-65535, oracle 1), measured on both an NVIDIA and an AMD device:

activation rows before after
FP16 1 1 1
FP16 2 -inf 1
FP16 65 -inf 1
BF16 1 1 1
BF16 2 0 1
BF16 65 0 1

The row count never changed the arithmetic; it changed the branch. The fused
GEMV/GEMM epilogues already keep the bias wide (_fused_bias_out_dtype), while
the dequantize + matmul fallback narrowed it. On the AMD device the fused
kernels did not engage for this fixture, so every row count failed. The
streaming path had the same cast in front of its per-tile torch.addmm.

No open PR fixes this. The bias-wide series (#3649, #3700, #3753,
#3649-era helpers) covered CUDA/HIP fused and FP4/VPTQ/FP8/GGUF paths, and
#3743/#3747 covered CPU; the portable GPTQ fallback kept its narrowing cast
through all of them.

2. The new flow

flowchart TD
    A["TorchLinear.forward"] --> B{"_should_use_streaming?"}
    B -- "Yes" --> C["_forward_streaming"]
    B -- "No" --> D["_forward_eager"]
    D --> E{"_can_use_rocm_gemv or _can_use_rocm_gemm?"}
    E -- "Yes" --> F["fused kernel, _apply_fused_bias with wide=True"]
    E -- "No" --> G["dequantize_weight + matmul_fp32_reduce"]
    G --> H{"linear_needs_wide_bias(x, bias)?"}
    H -- "Yes" --> I["linear_wide_bias: FP32 sum, one rounding"]
    H -- "No" --> J["narrow epilogue, bias cast to activation dtype"]
    C --> K{"wide_bias or _wants_fp32_reduce?"}
    K -- "Yes" --> L["per-tile FP32 epilogue"]
    K -- "No" --> M{"autocast active?"}
    M -- "No" --> N["torch.addmm with per-tile bias"]
    M -- "Yes" --> O["post-loop out.add_(bias)"]
    classDef fail fill:#fce8e6,stroke:#a33,color:#111
    P["removed: bias cast to activation dtype before the reduction"] --> Q["-65535 becomes -inf in FP16"]
    class P,Q fail
Loading

matmul_fp32_reduce gains the same gate, so every caller that reaches it with
a wide bias (Torch GPTQ eager/streaming, Torch AWQ, FP8 dense, GGUF dense,
Triton dequant, ParoQuant dense) is protected even though only GPTQ narrowed
the bias itself.

3. Failure and ambiguity contract

Situation Before After
Wide bias, eager fallback Cast to activation dtype before the reduction Kept wide, added in FP32, rounded once
Wide bias, streaming Cast before torch.addmm Per-tile FP32 epilogue
Wide bias, autocast active Standalone add kept the promotion linear_wide_bias disables autocast for its GEMM
Bias in the activation dtype Narrow epilogue Unchanged
Bias narrower than the activation Widened losslessly Unchanged
Empty activation Narrow path Wide path, same shape, no error
Bias needs broadcasting — linear_wide_bias reshapes before the add
Temporary dequantized weight Released after the call Unchanged; the regression tracks references and module buffers

4. Change inventory

Area File +/- Purpose
GPTQ eager fallback gptqmodel/nn_modules/qlinear/torch.py +8/-2 Device move only for a wide bias
GPTQ streaming gptqmodel/nn_modules/qlinear/torch.py +12/-4 Per-tile wide epilogue when the bias must stay wide
Shared helper gptqmodel/nn_modules/qlinear/_numerics.py +12/-2 Wide bias routes to linear_wide_bias
Regression tests/kernels/test_torch_wide_bias_fallback.py +225 42 cases
Reference page docs/low-precision-bias-epilogue.md +55 Fallback flow, before/after, measured numbers

5. Tests / guarantees

Test Invariant
test_torch_fallback_keeps_stored_bias_wide[1,2,16,17,65] Eager fallback matches the FP64 oracle exactly for FP16/BF16, both rounded twice
test_torch_streaming_keeps_stored_bias_wide[1,2,65] Streaming tiles match the same oracle
test_torch_fused_and_fallback_boundary[1,2,16,17,65] The branch switch at M=16/17 produces the same value
test_matmul_fp32_reduce_keeps_stored_bias_wide The helper alone, independent of the module
test_matmul_fp32_reduce_keeps_wide_bias_under_autocast Autocast does not re-narrow the operands
test_matmul_fp32_reduce_wide_bias_gradients Input, weight, and bias gradients match FP32
test_matmul_fp32_reduce_representable_wide_bias_stays_accurate Ordinary values stay within 2e-3
Packed qweight/qzeros/scales/g_idx/bias snapshot No in-place mutation; no retained dequantized weight

6. Validation

# NVIDIA device
python -m pytest tests/kernels/test_torch_wide_bias_fallback.py \
  tests/kernels/test_cuda_bias_epilogue.py tests/kernels/test_linear_fp32_reduce.py \
  tests/kernels/test_gptq_torch_cpu_bias_epilogue.py -q
146 passed

# AMD device
python -m pytest tests/kernels/test_torch_wide_bias_fallback.py \
  tests/kernels/test_cuda_bias_epilogue.py tests/kernels/test_linear_fp32_reduce.py \
  tests/test_cpu_bias_cancellation.py -q
137 passed, 6 skipped

The new file fails 28 of 42 cases on the NVIDIA device and all 42 on the AMD
device when reverted to main; all pass with the change. Storage: the module
state after two forwards contains no tensor outside the pre-forward storage
set, and the tracked dequantized tensor is released.

7. Reviewer notes

  • Scope is the portable Torch GPTQ epilogue plus the shared helper it calls.
    TorchLinear._forward_eager's CPU branch, the fused GEMV/GEMM epilogues, and
    the AWQ/FP8/GGUF/ParoQuant forward paths were already correct and are
    untouched.
  • The gate is linear_needs_wide_bias, i.e. dtype-based, matching
    linear_fp32_reduce. No per-value synchronizing check is added, so CUDA
    graph capture and torch.compile are unaffected.
  • A bias stored in the activation dtype still takes the previous narrow path,
    so no new FP32 weight copy appears for the common checkpoint.

TorchLinear._forward_eager narrowed the stored bias to the activation dtype
before matmul_fp32_reduce, so an FP32 bias lost the value needed to cancel the
reduction. With K=256, N=128, an all-ones weight, activations of 256 and an
FP32 bias of -65535, the correct result is 1:

    dtype  rows  before  after
    FP16   1     1       1
    FP16   2     -inf    1
    FP16   65    -inf    1
    BF16   1     1       1
    BF16   2     0       1
    BF16   65    0       1

The row count only selected a branch: the fused GEMV/GEMM epilogues already add
the bias in FP32, while the dequantize + matmul fallback rounded the bias first.
The streaming path had the same narrowing cast in front of its per-tile addmm.

- torch.py eager fallback: move the bias to the activation device only, and let
  matmul_fp32_reduce keep a wide bias out of the low-precision epilogue.
- torch.py streaming: a wide bias now takes the per-tile FP32 epilogue instead
  of addmm on the output dtype; other biases keep the previous cast.
- _numerics.matmul_fp32_reduce: route a bias flagged by linear_needs_wide_bias
  to linear_wide_bias, so HIP, CPU and an active autocast context do not round
  the product before the bias cancels it.
- tests/kernels/test_torch_wide_bias_fallback.py pins M=1/2/16/17/65 for FP16
  and BF16 across the eager, streaming and fused branches against an FP64
  oracle, covers autocast and gradients, and checks that no dequantized weight
  outlives the call.
- docs/low-precision-bias-epilogue.md documents the fallback flow.

Measured on one NVIDIA and one AMD device: before the change 28 of the 42 new
cases fail on the NVIDIA device and all 42 fail on the AMD device; all 42 pass
after it on both. On M=17 decode of a 4096x4096 layer an FP16 bias costs
0.026 ms and an FP32 bias 0.024 ms on the NVIDIA device, 0.046 ms and 0.051 ms
on the AMD device.

Copy link
Copy Markdown
Collaborator

Reviewed: the fallback keeps FP32 bias through the sum. The targeted GPU tests pass (78), Ruff and CI are green, and I found no blocking issue.

@Qubitium
Qubitium merged commit d7a1b8a into main Nov 12, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/torch-fallback-wide-bias branch November 12, 2026 02:30
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.

2 participants