Skip to content

Fix numeric range loss across quantized inference kernels - #3520

Merged
Qubitium merged 6 commits into
mainfrom
fix/inference-numeric-range
Nov 4, 2026
Merged

Qubitium merged 6 commits into
mainfrom
fix/inference-numeric-range

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Finite inputs and quantized weights can currently produce zeros, infinities, or NaNs even when the expected inference output is representable. For example, FP8 inverse scales can zero an entire E5M2 projection, QQQ maps a valid 0.125 output to zero, and AWQ/ExLlamaV2 partial reductions overflow before cancellation. This PR fixes the eleven confirmed groups from the inference audit in one change.

  • Preserve FP32 scale arithmetic in FP8/FP4 reference and native CPU decoders. Preserve BF16 subnormals in AVX512 stores. Match QQQ's Torch/CUDA and Metal activation-scale arithmetic, including zero rows.
  • Keep CPU INT8 channel scales wide. Choose FP32 CPU INT4 compute when affine zero offsets overflow, underflow, or lose the exact zero-point identity. Stop CPU fused layers from changing global compiler-freezing settings.
  • Use FP32 ExLlamaV2 group dots and split reductions; preserve BF16/FP32 activation range. Allocate reconstruction scratch per operation, and run dependent native work on the current CUDA stream.
  • Widen both GEMV_FAST decode partials and its prefill split-K workspace. Disable AWQ Marlin's low-precision atomics when FP32 reduction is requested.
  • Reconstruct GGUF superblock scales and accumulate chunks in FP32. Keep EXL3 Torch transforms wide until final scaling.
  • Apply VPTQ residual addition and normalization in FP32 in Torch, CUDA, and quantizer reconstruction. Use FP32-output tensor-core matmul for portable low-precision fallbacks without changing process-wide cuBLAS flags.

GGUF / ExLlamaV2 performance follow-up (ec8376bdf):

The accuracy fixes above were correct but slow in two paths: GGUF penalized every format, and ExLlamaV2 serialized its FP32 reductions. This commit restores tensor-core throughput without widening any reduction. No tolerance, oracle, or accuracy assertion changed — only how the same arithmetic is scheduled.

  • GGUF dequant target: GPU dequantization now produces the activation dtype directly. The earlier code forced FP32 for every format, which doubled the transient weight copy for no benefit in Q4_0/Q8_0/Q6_K. CPU keeps FP32 reconstruction.
  • GGUF Q4_K/Q5_K guard: these subtract a per-subblock minimum, so a scale product must stay in range even when the final weight is representable. Instead of always using FP32, a cached O(num_blocks) check over the d/d_min columns widens only when a scale product can actually leave the target dtype. Extreme scales still take the wide path; ordinary weights keep FP16.
  • GGUF Q6_K exactness: the two exact integer factors (|q| ≤ 32, |scales| ≤ 127) are multiplied in int16 before widening, so a zero code cannot become 0 * inf. Both operands stay int16 — the mixed int16×int8 broadcast measures 128 µs vs 95 µs for int16×int16 on ROCm, and was itself the regression.
  • GGUF fusion: FP16 activations and weights use addmm with an FP32 out_dtype so tensor cores carry the reduction. BF16 and CPU keep FP32 operands; BF16 operands round reconstructed weights before the GEMM and break the 2e-3 fusion contract.
  • GGUF chunking: byte-budgeted by default (32 MiB), so ordinary layers issue one GEMM instead of eight.
  • ExLlamaV2 dot: dot22_8_f uses two independent FP32 FMA chains instead of one serial chain.
  • ExLlamaV2 dense path: cublasGemmEx with CUBLAS_COMPUTE_32F reconstructs directly into the FP16 destination, replacing an FP32 mm plus a separate copy.
  • ExLlamaV2 split-K: private FP32 slices plus one fused reduce launch, with a bounded fallback (32 MiB) to a single zeroed buffer and atomics for wide layers.
  • ExLlamaV2 barrier: __syncthreads() moved ahead of the inactive-column return so all threads reach it.
  • ExLlamaV2 dispatch: the caller's force_cuda is passed through instead of being hardcoded true.

Production GGUF layer shapes through forward(), FP16, speedup = main 72cde6db / this commit:

Format Median Range
Q8_0 1.20× 1.19–1.23×
Q4_0 1.08× 1.00–1.10×
Q5_K 1.04× 0.98–1.04×
Q4_K 0.99× 0.93–1.00×
Q6_K 0.98× 0.98–0.99×

Q4_K/Q5_K measured 0.66–0.71× before the scale-range guard, because those formats had been forced to build FP32 chunks on real layer shapes. That was the genuine regression in this work; it is now at or above parity.

ExLlamaV2 by row count on RTX 4090, median over the six measured K,N shapes:

Rows Median Range
1 0.82× 0.81–0.84×
16 0.93× 0.84–0.96×
64 0.98× 0.94–1.20×
128 0.97× 0.95–0.99×
256 0.98× 0.77–1.07×

Two residual costs are irreducible and are the accuracy fix itself:

  • 1-row ExLlamaV2 (~3 µs): the split-K FP32 partial buffer plus its reduction launch. Forcing the atomic fallback does not help (18.7 µs either way), so the cost is the mandatory FP32 reduction, not allocation policy.
  • 256-row, 8192×2048 ExLlamaV2 (1.30×): CUBLAS_COMPUTE_32F measures ~61 µs there, about 282 TFLOPS and ~85% of Ada BF16-class peak. FP16-accumulate is 2.3 µs but fails the cancellation tests. This cannot be recovered without reintroducing the bug.

Lowering MAX_Q_GEMM_ROWS to shrink the FP32 dense region was also tested and is much worse: rows=1, K=8192 goes from 22.4 µs to 47.0 µs. The >50-row dense policy stays.

ROCm GGUF on R9700 is within noise of the preceding PR build (median 0.96×, worst 0.91×). ROCm process-to-process drift is 5–10%, so those figures use alternating-order, four-run medians rather than a stale log comparison. All 60 cases are finite on both vendors.

A review note flagged a possible double-counted last_chunk offset in split-K for row counts not divisible by 8. It does not reproduce: rows 1/8/9/16/17/23/64/65 on both GPTQ and AWQ match the dense FP32 reference to ≤7e-4 (FP16 rounding). The pre-offset lands inside split 0's slice and blockIdx.z * c_split_stride advances by whole slices, so the offsets compose. The misleading comment was corrected instead. That path remains untested by the benchmark harness, which only uses multiples of 8, and by the numeric fixtures, which use K=256 and never produce a tail chunk; a regression test pairing non-multiple-of-8 rows with K≥4096 is worth adding separately.

Validation at ec8376bdf: 411 passed / 8 skipped on RTX 4090 (CUDA) — numeric range and fusion suites, ExLlamaV2 GPTQ/AWQ JIT, and test_gguf_qlinear_llama.py; 25 passed on R9700 (ROCm) for the GGUF numeric range and fusion subset; every benchmarked case finite on both vendors. The 218-failure sets in test_gguf_all_formats.py and test_internal_gguf.py are identical on main and unrelated to this change.

Marlin scheduling follow-up (4a557398d):

The earlier slowdown was caused by retaining the old split-K schedule after replacing FP16 atomic accumulation with ordered FP32 reduction. Narrow output matrices had very few independent output tiles and long chains of blocks waiting on reduction locks. The precision change exposed that scheduling cost; FP32 arithmetic alone was not responsible for the regression.

On Ada, eligible AWQ layers now use 16×128 output tiles for batch sizes divisible by 16, creating more independent work in a single launch. Other row counts keep the original tile selector. The grid limits K splits to four per output tile (eight for larger row-tail tiles at K≥4096), bounded by the original launch size. All accumulation and split reductions remain FP32; unsafe FP16 atomics stay disabled. Kernel arithmetic, packed storage, scratch capacity, and allocation ownership are unchanged.

The policy is limited to SM89, AWQ 4-bit integer zero points, group size 128, no activation order, FP32 reduction without atomics, M≤128, N≤2048 with N divisible by 128, and 2048≤K≤8192. Other configurations retain their existing dispatch. There is no runtime autotuner or new user setting.

Matched RTX 4090 / FP16 timings in microseconds (M,K,N):

Shape Main 72cde6db Accurate PR b6cba3528 Scheduled FP32 PR
1,2048,256 21.9 27.7 21.3
16,2048,256 22.5 29.7 21.8
64,2048,256 29.4 54.9 21.9
128,2048,256 29.6 55.0 22.0
64,4096,256 31.9 83.8 23.5
64,8192,256 36.9 148.8 25.8
128,8192,256 41.5 189.7 25.9
128,8192,1024 41.5 66.1 30.8
64,8192,2048 69.1 67.3 30.9
128,8192,2048 52.9 51.5 40.9

Main's timings are a historical baseline: its FP16 atomic path fails the large-intermediate cancellation tests. The final column preserves the accuracy fix. For the original M=64,K=2048,N=256 regression, latency falls from 54.9 to 21.9 µs; at K=8192 it falls from 148.8 to 25.8 µs. Both are faster than main on the same measured inputs.

Method: resident packed weights and activations, 10 warmups, three blocks of 100 forwards, synchronization after every forward, median of the three block medians. Each revision runs in a fresh process with no experimental launch interception. The matrix covers 36 eligible shapes plus 24 controls. All 36 eligible shapes improved in this run; unchanged-dispatch controls varied from −0.5% to +7.7% across processes. These are kernel/layer latency measurements, not model throughput. BF16 is covered for correctness; the timing table is FP16 only.

Validation: 124 exact-oracle cases pass (31 shapes × FP16/BF16 × random logical codes/cancellation), with three forwards per case on a non-default stream and no new retained expanded weights. Cases cover aligned batches and row tails, K/N boundaries, alternate group sizes, and 8-bit controls. Expectations use independent logical codes and FP64 products, explicitly reproducing Marlin's existing product-rounding-before-bias epilogue. Exact visible-output equality is required; no tolerance is relaxed.

The broader numerical/Marlin/JIT/scratch/offload run passed 586 tests with two skips for unavailable second-device visibility. The forced JIT rebuild smoke test is run separately in a fresh interpreter because the loader correctly rejects rebuilding an already-registered torch.ops library. That fresh-process rebuild and forward test passed for both FP16 and BF16 (1 test passed). The 124-case schedule run overlaps 108 cases in the broader run. The original 312-case CUDA/CPU measurement sweep still has zero out-of-tolerance, nonfinite, or erroneously zeroed outputs, with all recorded error metrics unchanged from the preceding PR revision.

Full 60-shape timing matrix, µs
M,K,N Main Accurate PR Scheduled FP32 PR
1,2048,256 21.9 27.7 21.3
16,2048,256 22.5 29.7 21.8
64,2048,256 29.4 54.9 21.9
128,2048,256 29.6 55.0 22.0
256,2048,256 32.0 55.0 55.1
1,2048,1024 21.8 28.6 21.3
16,2048,1024 23.2 30.7 22.1
64,2048,1024 32.2 55.2 23.0
128,2048,1024 36.0 65.8 22.8
256,2048,1024 47.6 45.3 45.5
1,2048,2048 24.1 23.8 21.4
16,2048,2048 25.5 25.1 22.2
64,2048,2048 67.3 62.4 22.9
128,2048,2048 44.1 41.2 24.6
256,2048,2048 37.8 35.4 37.5
1,4096,256 21.8 35.2 22.3
16,4096,256 22.8 39.0 23.4
64,4096,256 31.9 83.8 23.5
128,4096,256 33.4 83.9 23.5
256,4096,256 39.1 104.8 112.9
1,4096,1024 22.2 27.5 22.4
16,4096,1024 23.7 29.9 23.4
64,4096,1024 38.8 105.4 24.3
128,4096,1024 37.0 62.9 25.5
256,4096,1024 51.1 46.0 48.9
1,4096,2048 24.6 23.5 22.5
16,4096,2048 26.3 25.0 23.6
64,4096,2048 68.9 64.3 25.7
128,4096,2048 48.1 45.0 30.6
256,4096,2048 44.8 42.0 44.5
1,8192,256 22.2 53.4 24.5
16,8192,256 23.7 60.9 25.9
64,8192,256 36.9 148.8 25.8
128,8192,256 41.5 189.7 25.9
256,8192,256 40.5 106.8 111.7
1,8192,1024 22.6 27.9 24.3
16,8192,1024 24.3 30.4 25.8
64,8192,1024 39.1 105.3 26.8
128,8192,1024 41.5 66.1 30.8
256,8192,1024 58.0 52.9 55.1
1,8192,2048 25.2 24.6 24.3
16,8192,2048 27.0 26.2 25.8
64,8192,2048 69.1 67.3 30.9
128,8192,2048 52.9 51.5 40.9
256,8192,2048 56.9 55.6 57.7
1,8192,4096 25.0 24.3 24.3
16,8192,4096 27.0 26.3 26.2
64,8192,4096 54.4 53.0 53.1
128,8192,4096 56.6 55.2 55.2
256,8192,4096 79.1 77.6 77.2
1,1024,256 22.7 22.4 22.5
16,1024,256 23.8 23.5 23.5
64,1024,256 36.0 35.7 35.8
128,1024,256 35.9 35.6 35.8
256,1024,256 36.0 35.8 35.8
1,8320,256 22.9 36.1 36.1
16,8320,256 24.4 39.9 39.9
64,8320,256 35.7 151.8 151.2
128,8320,256 38.9 88.0 88.2
256,8320,256 41.0 68.5 68.6

Performance follow-up in b6cba3528 (baseline: the initial accuracy-fix commit 8ecc80a8):

QQQ's eager GPU activation quantizer now fuses FP32 conversion, row scaling, division, rounding, and INT8 conversion into one optional Triton kernel on CUDA/ROCm. It preserves Torch's FP32 reciprocal multiplication for /127: using a differently rounded division changed one threshold code, so that change was corrected rather than accepting a code mismatch. CPU, compiled, strided, oversized-row, and missing-Triton paths retain the Torch implementation.

AWQ GEMV_FAST/LLM_AWQ prefill keeps split intermediates in FP32 and casts directly in the final owning CTA. Prefills without split-K allocate neither the FP32 output staging buffer nor semaphores. GGUF casts activations once and uses an operation-local FP32 addmm_ accumulator, avoiding separate chunk-product/add tensors and the initial zero-fill. No dense weight cache is introduced.

Latency in microseconds, initial PR → optimized PR:

Path / M,K,N (or quantizer M,K) RTX 4090 / CUDA R9700 / ROCm
QQQ Torch full layer / 1,128,128 218.9 → 192.2 374.7 → 381.1
GGUF chunked / 1,512,16384 165.9 → 164.4 453.2 → 441.9
QQQ activation quantization / 1,4096 49.4 → 18.6 64.1 → 47.5
QQQ activation quantization / 64,4096 49.3 → 18.6 125.7 → 47.4
QQQ activation quantization / 1,32768 49.4 → 22.8 67.6 → 48.7
AWQ GEMV_FAST prefill / 1,2048,256 25.7 → 24.9 —
AWQ GEMV_FAST prefill / 16,2048,256 26.6 → 25.7 —
AWQ GEMV_FAST prefill / 64,2048,256 28.3 → 24.8 —
AWQ GEMV_FAST prefill / 256,2048,256 38.4 → 36.7 —

Portable rows use six alternating A/B blocks of 100 synchronized forwards in the same resident process, after warming both implementations 30 times; the table shows the median of the block medians. Both implementations use the same module, packed weights, inputs, and Torch settings. AWQ uses three independent processes per revision, each with 10 warmups and 100 synchronized forwards; the table shows the median of those process medians. Compilation is excluded.

Separate-process portable measurements showed about 5–6% drift in an unchanged EXL3 control on ROCm, so the resident A/B comparison above isolates the changed portable operations. The tiny full QQQ layer on ROCm still has no clear speedup (the reported median is 1.7% slower despite faster activation quantization). The later Marlin scheduling results are reported above. These measurements do not establish whole-model throughput gains.

Profiling confirms the work removed: QQQ quantization launches 11 → 1 GPU kernels on both devices; GGUF launches 26 → 22 on CUDA and 28 → 24 on ROCm. AWQ prefill launches 3 → 2 at M=1, 3 → 1 at M=64, and 2 → 1 at M=256.

The quantizer's measured peak extra allocation at M=64,K=4096 falls from 3,408,896 to 525,312 bytes on both devices. AWQ M=64 falls from 131,072 to 65,536 bytes. These probe peaks include overlapping returned tensors. Reachable packed state remains unchanged: QQQ 550,208 B, GGUF 4,718,592 B, AWQ 278,528 B. GGUF's FP32 weight-chunk workspace remains necessary; this follow-up does not eliminate its earlier memory increase.

Final validation at b6cba3528: 854 passed / 15 skipped on CUDA, 774 passed / 81 skipped on ROCm, including the original numerical/storage/integration suites plus QQQ CPU, GGUF CPU, and 97 new fusion fixtures. The new fixtures cover exact quantized codes at rounding thresholds and their neighboring inputs, tiny/large scales, FP16/BF16/FP32, zero/empty/strided rows, random oracle comparisons, padded multi-chunk GGUF with bias, and AWQ prefill dispatch boundaries through 256 rows. No accuracy tolerance was relaxed. Ruff and git diff --check pass.

Initial accuracy-fix validation on this host (8ecc80a8):

  • RTX 4090 / CUDA: 693 passed, 7 skipped in the boundary, Torch/storage, FP8, AWQ, dispatch, and JIT integration run.
  • Radeon AI PRO R9700 / ROCm: 631 passed, 55 skipped in the corresponding portable suite. Native CUDA-only paths are skipped explicitly.
  • Numerical/CPU regressions: 486 passed; 17 cases deselected by not tiny and not checkpoint and not benchmark. An additional final CPU INT4/backend suite passed all 87 tests.
  • The new boundary file contains 312 cases on CUDA, including all finite FP8 codes and all FP4 codes across scalar/AVX2/AVX512 scale layouts, FP16/BF16, cancellation, tiny scales, repeated forwards, retained-storage checks, and a non-default CUDA stream. ExLlamaV2 also covers FP32.
  • Independent FP64 arithmetic oracles; rounded-output tolerances are at most rtol=atol=2e-3. One BF16 discrepancy in the VPTQ matrix was an adjacent output code at a verified midpoint (FP64 distance 5.4e-8); the test explicitly adjudicates adjacent midpoint cases without loosening the general tolerance. Quantizer/codebook round trips and discrete-code checks pass.
  • Ruff and git diff --check pass.

Numerical A/B results (added after the initial pass-count-only report):

The entire 312-case measurement sweep was rerun at optimized commit b6cba3528. Every recorded error metric below is unchanged from 8ecc80a8, including the raw FP64 drift. CUDA, ROCm, and CPU still have zero out-of-tolerance outputs, nonfinite outputs, and erroneously zeroed nonzero results.

The same 312 boundary fixtures from test_inference_numeric_range.py were instrumented to record outputs before assertions, using main 72cde6db versus PR 8ecc80a8, seed 20261103, and the same independent FP64 expectations. Main failures were recorded rather than stopping the sweep. CUDA measured all 312 cases: 92 GPU and 220 CPU. ROCm measured 263: 43 GPU and the same 220 CPU; 49 NVIDIA-only fixtures were skipped. There were no setup/runtime errors in either sweep. CPU results were identical between the two environments and are reported once.

These are intentionally adversarial overflow/underflow/cancellation fixtures. Percentages below describe these fixtures' output elements, not model accuracy, perplexity, or an estimated production error rate. Repeated columns and SIMD/layout variants contribute separately to the denominators.

An output is outside tolerance if it is nonfinite or abs(actual - rounded_oracle) > atol + rtol*abs(rounded_oracle). Inference uses rtol=atol=2e-3; FP8/FP4 CPU decoding uses exact equality. Nonzero-to-zero counts use the dtype-rounded oracle, so mandatory final-output underflow is not counted as a bug.

Measured outputs Cases with an out-of-tolerance value, main → PR Elements outside tolerance, main → PR Nonfinite elements, main → PR Erroneously zeroed elements, main → PR
RTX 4090 / CUDA (291,200 elements) 60/92 → 0/92 214,208 (73.56%) → 0 (0%) 180,224 → 0 42,560 → 0
R9700 / ROCm (20,608 elements) 20/43 → 0/43 18,368 (89.13%) → 0 (0%) 17,344 → 0 896 → 0
CPU (both environments) (103,276 elements) 110/220 → 0/220 22,874 (22.15%) → 0 (0%) 4,576 → 0 17,658 → 0

Maximum absolute error against the dtype-rounded oracle, grouped across applicable devices/dtypes. A nonfinite result has unbounded error; the finite subset maximum is shown separately rather than silently dropping NaNs/infinities. CPU cases are counted once.

Path Main maximum error PR maximum error
FP8 inference 0.125 0
QQQ Torch 0.125 0
CPU INT4 nonfinite; finite max 16384 0
CPU INT8 0.0078125 0
GGUF superblock nonfinite; finite max 0 0
GGUF chunked nonfinite; finite max 0 0
EXL3 Torch nonfinite; finite max 0.25 0.25
VPTQ nonfinite; finite max 0 0
VPTQ native nonfinite; finite max 0 0
ExLlamaV2 nonfinite; finite max 48 0
AWQ partial sums nonfinite; finite max 0 0
QQQ native 0.125 0
FP8 CPU decode nonfinite; finite max 0.00170898 0
FP4 CPU decode 1.78814e-07 0
Torch fallback nonfinite (no finite outputs) 0
ExLlamaV2 split nonfinite (no finite outputs) 0

The remaining 0.25 EXL3 FP16 discrepancy occurs on CPU and ROCm and is within the inference tolerance; it is also present on main's CPU path. CUDA EXL3 matches the rounded oracle exactly in this sweep. The GPU sweeps otherwise have zero rounded-oracle error on the PR. Underflow is checked independently: for example, main ExLlamaV2 loses BF16 results around 1.63e-9 to zero, which absolute tolerance alone would accept; the PR preserves them.

Returned-output error against the unrounded FP64 oracle is not always zero even when the rounded oracle matches exactly. Below, normalized raw drift is max(abs(actual - FP64_oracle)) / max(abs(FP64_oracle)), taking the worst nonzero-reference case per row. These are output measurements, not instrumentation of internal FP32 accumulators.

PR path / dtype Max raw absolute drift Max normalized raw drift Max rounded-oracle drift
ExLlamaV2 / float16 4 0.000228571 0
ExLlamaV2 / bfloat16 384 0.0021978 0
ExLlamaV2 / float32 0 0 0
EXL3 Torch / float16 0.125327 0.000195829 0.25
EXL3 Torch / bfloat16 1.98952 0.00186821 0
FP8 CPU decode / float16 2.98023e-08 0.00416667 0
FP8 CPU decode / bfloat16 4.59177e-41 3.58732e-43 0
FP4 CPU decode / float16 2.98023e-08 0.166667 0
FP4 CPU decode / bfloat16 0 0 0

All other measured PR groups have zero raw FP64 drift on these constructed fixtures. The BF16 ExLlamaV2 example is 174720 → 175104, a required BF16 rounding step: raw drift 384 (0.21978%), rounded-oracle drift 0. FP4's FP16 subnormal fixture has raw drift 2.98e-8 (16.67% of that tiny tensor's maximum); its returned values still match the rounded oracle exactly. Neither is presented as an arithmetic failure or hidden by reporting only pass counts.

These numerical probes use the test file's documented shapes and stored quantized values, including its specified decoded-weight rounding. They do not replace the broader regression suite above or the outstanding Metal/model-scale validation.

Initial accuracy-fix microbenchmarks (8ecc80a8, before the performance follow-up) against main 72cde6db: resident tensors, 3 warmups, median of 20 forwards, synchronization after each forward. These are small-kernel measurements, not model throughput claims. FP16 timings in microseconds:

Path / M,K,N RTX 4090 before → after R9700 before → after
QQQ Torch / 1,128,128 205.1 → 215.7 378.1 → 391.6
GGUF chunked / 1,512,16384 158.5 → 172.8 439.9 → 502.1
EXL3 Torch / 1,128,128 226.3 → 234.5 385.4 → 513.1
ExLlamaV2 GPTQ / 1,256,256 17.0 → 22.1 —
ExLlamaV2 GPTQ / 16,256,256 21.7 → 23.5 —
ExLlamaV2 GPTQ / 64,256,256 22.4 → 27.0 —
ExLlamaV2 AWQ / 1,256,256 19.5 → 26.6 —
ExLlamaV2 AWQ / 16,256,256 24.5 → 27.6 —
ExLlamaV2 AWQ / 64,256,256 24.9 → 31.7 —
AWQ GEMV_FAST prefill / 1,2048,256 24.6 → 26.6 —
AWQ GEMV_FAST prefill / 16,2048,256 25.6 → 27.2 —
AWQ GEMV_FAST prefill / 64,2048,256 27.8 → 28.8 —
AWQ Marlin / 1,2048,256 24.4 → 29.3 —
AWQ Marlin / 16,2048,256 24.2 → 31.1 —
AWQ Marlin / 64,2048,256 31.8 → 56.9 —

Wider arithmetic has a latency and temporary-memory cost. Packed checkpoint/cache storage in these probes is unchanged (e.g. ExLlamaV2 GPTQ 36,096 B, AWQ 34,048 B; GGUF 4,718,592 B). ExLlamaV2 no longer owns persistent dense scratch. Its small-M float reduction uses 4*M*N transient bytes; large-M reconstruction is local to the operation. GGUF's measured peak extra CUDA allocation rose from about 36.3 to 60.6 MiB in the chunk benchmark, including temporary/workspace allocations. No new dense/expanded weight cache is retained.

Metal's QQQ scale correction is source-reviewed with updated tests, but Apple hardware was unavailable; its model-shape validation remains outstanding. This PR does not certify unexecuted optional runtimes or SM90/Blackwell-specific kernels. Paro's separately documented per-stage rounding contract is outside the eleven confirmed defects.

@Qubitium

Qubitium commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Updated performance table (RTX 4090, FP16)

The Marlin regression was a scheduling problem, not a reason to weaken the FP32 accuracy fix. Replacing FP16 atomic accumulation with ordered FP32 reduction left the old split-K schedule in place. Narrow output matrices then had too few independent output tiles and long reduction-lock chains. The final policy uses 16x128 output tiles for eligible AWQ layers at batch sizes divisible by 16, with K splits capped at four per output tile (eight for larger row-tail tiles at K >= 4096). All accumulation remains FP32 and unsafe FP16 atomics stay disabled.

Microseconds, matched resident-tensor measurements at commit 4a557398d:

M,K,N Main 72cde6db Initial accuracy PR Final FP32 PR
1,2048,256 21.9 27.7 21.3
16,2048,256 22.5 29.7 21.8
64,2048,256 29.4 54.9 21.9
128,2048,256 29.6 55.0 22.0
64,4096,256 31.9 83.8 23.5
64,8192,256 36.9 148.8 25.8
128,8192,256 41.5 189.7 25.9
128,8192,1024 41.5 66.1 30.8
64,8192,2048 69.1 67.3 30.9
128,8192,2048 52.9 51.5 40.9

At the original regression point (64,2048,256), latency improves from 54.9 to 21.9 microseconds. At 64,8192,256, it improves from 148.8 to 25.8 microseconds. Both final results are faster than main on the same inputs.

Method: resident packed weights and activations, 10 warmups, three blocks of 100 synchronized forwards, median of the three block medians, fresh process per revision. Main is a historical baseline because its FP16 atomic path fails the cancellation tests. BF16 is covered for correctness; this timing table is FP16 only. The full 60-shape matrix, including unchanged-dispatch controls, remains in the PR description.

Validation: 124 exact FP16/BF16 oracle cases pass across 31 shapes, including aligned batches, row tails, K/N boundaries, alternate group sizes, and 8-bit controls. Exact visible-output equality is required; no tolerance was relaxed.

Keep the numeric-range fixes while recovering the throughput they cost.

GGUF:
- Dequantize directly to the activation dtype on GPU; the earlier code
  forced FP32 for every format, which doubled the transient weight copy.
- Q4_K/Q5_K still subtract per-subblock minima, so they widen to FP32 only
  when a scale product can leave the target range. A cached O(blocks) guard
  over the d/d_min columns keeps extreme-scale layers failing safe without
  paying FP32 for ordinary weights.
- Q6_K multiplies the two exact integer factors (|q|<=32, |scales|<=127) in
  int16 before widening, so a zero code cannot become 0 * inf. Both operands
  stay int16; the mixed int16 x int8 broadcast is much slower on ROCm.
- Fuse the dequantized FP16 operands through addmm with a FP32 out_dtype so
  CUDA tensor cores carry the reduction. BF16 and CPU keep FP32 operands.
- Chunking is byte-budgeted by default, so ordinary layers issue one GEMM.

ExLlamaV2:
- dot22_8_f uses two independent FP32 FMA chains instead of one serial one.
- The dense path (>50 rows) reconstructs and runs cublasGemmEx with
  CUBLAS_COMPUTE_32F straight into the FP16 destination, replacing the
  FP32 mm plus copy.
- Split-K writes private FP32 slices and reduces them in one fused launch,
  with a bounded fallback to a single zeroed buffer plus atomics.
- Move __syncthreads() before the inactive-column return so all threads
  reach the barrier.
- Pass the caller's force_cuda through instead of hardcoding true.

Validated on RTX 4090 (CUDA) and R9700 (ROCm): 411 passed / 8 skipped on
CUDA, 25 GGUF numeric tests on ROCm, every benchmarked case finite. GGUF
and ExLlamaV2 are now at parity or faster than main except the mandatory
FP32-reduction cost at large row counts.

Qubitium commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

GGUF / ExLlamaV2 performance follow-up (ec8376bdf)

The accuracy fixes were correct but slow in two paths. This commit restores tensor-core throughput without widening any reduction. Both formats were validated in parallel on separate GPUs: GGUF on CUDA device 1 + ROCm, ExLlamaV2 on CUDA device 0.

Main is a historical baseline. Its FP16-atomic paths fail the cancellation tests, so every "vs main" number compares against code that is numerically wrong on the boundary fixtures. The comparison that matters for regressions is "vs previous PR build," which is unchanged or better throughout.

What changed

  • GGUF, dequant target: GPU dequantization now produces the activation dtype directly. Forcing FP32 for every format doubled the transient weight copy for no benefit in Q4_0/Q8_0/Q6_K.
  • GGUF, Q4_K/Q5_K guard: these subtract a per-subblock minimum, so the scale product must stay in range even when the final weight is representable. Instead of always using FP32, a cached O(num_blocks) check over the d/d_min columns widens only when a scale product can actually leave the target dtype. Ordinary weights keep FP16; extreme scales still take the wide path.
  • GGUF, Q6_K exactness: the two exact integer factors (|q| ≤ 32, |scales| ≤ 127) are multiplied in int16 before widening, so a zero code cannot become 0 * inf. Keeping both operands int16 matters: the mixed int16×int8 broadcast measures 128 µs vs 95 µs for int16×int16 on ROCm, and was itself the regression.
  • GGUF, fusion: FP16 activations and weights go through addmm with a FP32 out_dtype, so tensor cores carry the reduction. BF16 and CPU keep FP32 operands; BF16 operands round reconstructed weights before the GEMM and break the 2e-3 fusion contract.
  • GGUF, chunking: byte-budgeted by default (32 MiB), so ordinary layers issue a single GEMM instead of eight.
  • ExLlamaV2, dot product: dot22_8_f uses two independent FP32 FMA chains instead of one serial chain.
  • ExLlamaV2, dense path: cublasGemmEx with CUBLAS_COMPUTE_32F reconstructs directly into the FP16 destination, replacing an FP32 mm plus a separate copy.
  • ExLlamaV2, split-K: private FP32 slices plus one fused reduce launch, with a bounded fallback (32 MiB) to a single zeroed buffer and atomics for wide layers.
  • ExLlamaV2, barrier: __syncthreads() moved ahead of the inactive-column return, so all threads reach it.
  • ExLlamaV2, dispatch: the caller's force_cuda is passed through instead of being hardcoded true.

Production GGUF layer shapes (speedup = main / this PR)

Real 4-bit layer geometry through forward(), FP16, median of 40 synchronized forwards:

Format Median Range
Q8_0 1.20× 1.19–1.23×
Q4_0 1.08× 1.00–1.10×
Q5_K 1.04× 0.98–1.04×
Q4_K 0.99× 0.93–1.00×
Q6_K 0.98× 0.98–0.99×

Q4_K/Q5_K were 0.66–0.71× before the guard. That was the real regression in this work; it is now at or above parity.

ExLlamaV2 by row count (RTX 4090, median over 6 shapes)

Rows Median Range
1 0.82× 0.81–0.84×
16 0.93× 0.84–0.96×
64 0.98× 0.94–1.20×
128 0.97× 0.95–0.99×
256 0.98× 0.77–1.07×

Where the remaining cost is

Two costs are irreducible, and both are the accuracy fix itself:

  • 1-row ExLlamaV2 (~3 µs): the split-K FP32 partial buffer plus its reduction launch. Disabling the split buffer does not help (18.7 µs either way); the cost is the mandatory FP32 reduction, not allocation policy.
  • 256-row, 8192×2048 ExLlamaV2 (1.30×): CUBLAS_COMPUTE_32F measures ~61 µs there, about 282 TFLOPS, ~85% of Ada BF16-class peak. FP16-accumulate is 2.3 µs but fails the cancellation tests. This cannot be recovered without reintroducing the bug.

Also confirmed: lowering MAX_Q_GEMM_ROWS to shrink the FP32 dense region is much worse — rows=1, K=8192 goes from 22.4 µs to 47.0 µs. The >50-row dense policy stays.

ROCm

GGUF on R9700 is within noise of the previous PR build (median 0.96×, worst 0.91×). ROCm process-to-process variance is ~5–10%, so I used alternating-order, 4-run medians rather than comparing against a stale log. All 60 cases finite.

Note: the first ROCm comparison suggested an ~11% dense Q6_K regression. It was process drift, not code — the unchanged q6_k dequant measured 350.9 µs vs 357.3 µs, and the int16 change above removed what real cost existed.

Split-K tail verification

An earlier review flagged a possible double-counted last_chunk offset for row counts not divisible by 8. It does not reproduce. Rows 1/8/9/16/17/23/64/65 on both GPTQ and AWQ match the dense FP32 reference to ≤7e-4 (FP16 rounding). The pre-offset lands inside split 0's slice and blockIdx.z * c_split_stride advances by whole slices, so the two offsets compose. I rewrote the misleading comment to say so.

The benchmark harness only uses row counts that are multiples of 8, and the numeric tests use K=256, which never produces a tail chunk. A regression test pairing non-multiple-of-8 rows with K≥4096 would close that gap — worth adding separately.

Validation

  • CUDA (RTX 4090): 411 passed, 8 skipped — numeric range + fusion suites, ExLlamaV2 GPTQ/AWQ JIT, and test_gguf_qlinear_llama.py.
  • ROCm (R9700): 25 passed for the GGUF numeric range + fusion subset.
  • Every benchmarked case reported finite: true on both vendors.
  • The 218-failure sets in test_gguf_all_formats.py / test_internal_gguf.py are identical on main and are unrelated to this change.

Accuracy is unchanged: still zero out-of-tolerance, nonfinite, and erroneously zeroed outputs across the boundary sweep. This commit only changes how the same arithmetic is scheduled.

The three QQQ fusion tests mixed `import ... as qqq` with
`from ... import QQQLinear`. The module alias is required where the tests
monkeypatch `qqq._qqq_gpu_quantizer`, so standardize on it instead of
dropping it: patching the class attribute would not intercept the module
function that the quantizer dispatch actually calls.
Q4_K/Q5_K reconstruct d * scale * code - d_min * min, so the peak term is
d * 63 * code_max, not d * 63. Bounding the bare scale product let a
representable weight saturate to inf on the narrow FP16 path: with d=74,
scale=63 and code=15 the exact weight is 10017 (in range) while the
intermediate 69930 is not.

The guard now scales the per-block extreme by 15 (Q4_K) or 31 (Q5_K),
keeping the check O(num_blocks) over the d/d_min columns. Adds a
regression test that fails on the previous guard.

Qubitium commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 846956d15: a real gap in the GGUF K-quant range guard that my own perf work introduced in this PR.

Bug. _compute_k_scale_overflow bounded only d * 63. The reconstructed term is d * scale * code, so the true peak is d * 63 * code_max (code_max = 15 for Q4_K, 31 for Q5_K). A scale product that fits FP16 can therefore still overflow one code step later, and the narrow path saturates to inf for a weight that is perfectly representable.

Reproduction. Q4_K with d = 74, scale = 63, code = 15: exact weight 74*63*15 - d_min*63 = 10017, which is in FP16 range, but the intermediate 69930 is not. Old guard returned False, narrow path gave inf. New guard returns True and the dense path gives 10016 (one FP16 ulp at that magnitude), finite.

Fix. The guard now multiplies the per-block d/d_min extreme by 15 * 63 or 31 * 63, so it still runs over O(num_blocks) columns and keeps the per-layer cache on (data_ptr, _version, shape, dtype).

Test. test_gguf_superblock_scale_times_code_range is parametrized over {q4_k, q5_k} x {fp16, bf16} x {cpu, cuda}. It fails on the previous guard (test_gguf_superblock_scale_times_code_range[dtype0-q4_k-cpu] and [dtype0-q4_k-cuda]), and passes now. The assertion is _k_scale_overflows(...) == (d*63*code_max > finfo(dtype).max) rather than a hardcoded True, because BF16 has enough range that False is the correct answer there; only FP16 additionally asserts True. The value oracle is a wide FP32 dequant of the same block, not hand-derived packing.

Validation after the change

  • CUDA (2x RTX 4090): test_inference_numeric_range + test_inference_numeric_fusion + ExLlamaV2 JIT suites — 417 passed, 8 skipped.
  • ROCm (2x R9700): test_inference_numeric_range + test_inference_numeric_fusion — 342 passed, 75 skipped; GGUF superblock subset 16 passed.
  • Adjacent GGUF suites (test_gguf_torch_cpu, test_gguf_qlinear_llama, test_mlx_gguf*) — 27 passed, 3 skipped.
  • ruff check clean on both changed files.

This is a correctness fix on the guard only; the perf numbers already posted are unchanged, since the wider branch is still taken per layer off the same cached predicate.

@Qubitium
Qubitium merged commit 97eac85 into main Nov 4, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/inference-numeric-range branch November 4, 2026 03:31
Qubitium added a commit that referenced this pull request Nov 4, 2026
…mports (#3526)

* fix(triton): keep the GPTQ reduction in FP32 and repair kernel test imports

The Triton dequant path computed `input @ dequantized_weight` in the
activation dtype, so every output drifted by about one bf16 ulp relative to
the Torch backend, which rounds once after an FP32 reduction. PR #3520 fixed
the Torch, GGUF, ExLlamaV2 and Marlin epilogues but missed this path.

- Route both quant_matmul branches through matmul_fp32_reduce so Triton and
  Torch agree bit-for-bit on CUDA. HIP already accumulates in FP32 for
  low-precision operands, so the ROCm result is unchanged.
- tests/kernels/test_triton_fp32_reduce.py pins the FP32 epilogue against an
  independent FP64 oracle and asserts Triton/Torch bit equality; arithmetic
  error is reported separately from the visible low-precision output error.
- test_inference_numeric_{fusion,range}.py referenced sibling helpers through
  bare module names that only resolve when tests/ is on sys.path, so
  `pytest tests/kernels/test_inference_numeric_fusion.py` (the exact CI form)
  died with ModuleNotFoundError and collected nothing.
- test_torch_int8.py pre-rounded the channel scale to the activation dtype in
  its oracle. The kernel multiplies the canonical FP32 scale and rounds only
  the output, so the oracle disagreed with a correct kernel for every bf16
  case; compare arithmetic in FP64 and keep the visible rounding separate.

* fix(numerics): skip the FP32-output request on HIP, harden kernel oracles

Follow-up to #3526 addressing review measurements.

The wide `out_dtype=float32` request is only needed on CUDA, where cuBLAS
starts accumulating fp16/bf16 GEMMs in the operand dtype once it splits the
reduction. HIP already accumulates these operands in FP32, so the request
only adds a cast and a transient FP32 output.

Measured on gfx1201 (Radeon AI PRO R9700, HIP 7.16.26385):
- narrow vs wide bitwise identical across 96 shape/dtype/bit cases and 150
  random matmuls, and 400/400 matmul+linear configs including the
  `transpose=True` backward branch.
- wide cost was +4.1% .. +39.5% latency and up to +144 MiB peak allocation;
  both now gone.

CUDA behaviour is unchanged, so the #3526 numerics fix and its bit-for-bit
Torch agreement still hold there.

Test hardening:
- `test_triton_fp32_reduce.py` imported `quant_matmul` at module scope, so
  `pytest.importorskip("triton")` was unreachable and a Triton-less
  environment got a collection error instead of a skip. The import is now
  lazy; verified `1 error` -> `12 skipped`.
- Replace the self-referential "arithmetic error" assertions, which compared
  Torch against itself, with the real constraint the kernels must satisfy:
  half an output-dtype ulp plus the FP32 accumulation slack, measured against
  an independent FP64 oracle. Injecting the old narrow matmul fails 8 cases.
- Add backward (`transpose=True`) coverage; `TritonV2Linear.SUPPORTS_TRAINING`
  is True and this branch had none.
- Allow mandatory output rounding in the visible-error check: a bf16 half-ulp
  at magnitude 2 is 7.8e-3, which `atol=2e-3` rejected on a correct kernel.

Verification (RTX 4090 / torch 2.15.0+cu132 / triton 3.9.0, and gfx1201 /
torch 2.16.0.dev+rocm10.1):
- `test_triton_fp32_reduce.py` + `test_torch_int8.py`: CUDA 45 passed,
  ROCm 39 passed / 12 skipped.
- `test_gptq.py`, `test_inference_numeric_{range,fusion}.py`,
  `test_awq_triton_accum.py`: 464 passed, 16 skipped.
- Torch/GGUF/AWQ/FP8 consumers of the shared helper: 77 passed / 7 skipped
  (CUDA), 72 passed / 12 skipped (ROCm).
- `test_torch_int8.py` on main: 15 failed -> 29 passed.
- `ruff check gptqmodel tests` clean.

No weight cache is introduced: the dequantized tile is still consumed by the
matmul and released (verified by weakref after forward), and a 1 MiB dense
layer weight is not retained -- only 8 KiB of scales.

* fix(numerics): preserve the ROCm bias epilogue for batched inputs

---------

Co-authored-by: Qubitium <[email protected]>
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