Skip to content

fix(gguf): select the fused Torch forward from static gates, not a timing race (#4590) - #4627

Merged
Qubitium merged 1 commit into
mainfrom
fix/gguf-deterministic-fused-choice
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/gguf-deterministic-fused-choice

Conversation

@ZX-ModelCloud

@ZX-ModelCloud ZX-ModelCloud commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

GGUFTorchLinear chose between its fused and dense forward by timing them, per
(device, dtype, shape), on the first forward of that shape. The two paths are
not bitwise equivalent, so the arithmetic a layer used — and therefore the
logits — depended on what else the process was doing. This replaces the race
with the module's static shape gates.

1. The problem

flowchart TD
    A["GGUFTorchLinear.forward"] --> B["_should_use_fused_k_forward"]
    B --> C{"autotune_enabled?"}
    C -- "yes" --> D["_autotune: 1 warmup + 2 launches per path<br/>`gguf.py:1719-1725`, `gguf.py:1694-1717`"]
    D --> E{"fused faster by > 5%?"}
    E -- "yes" --> F["_forward_fused_k<br/>CPU: cpu_bf16x3_matmul, `gguf.py:1911`"]
    E -- "no" --> G["_forward_dequant_matmul<br/>CPU: IEEE FP32, `gguf.py:1791-1793`"]
    C -- "no" --> F
    H["Unrelated thread / load"] -.-> D
    classDef failure fill:#fce8e6,stroke:#a33,color:#111
    class D,E failure
Loading
Mechanism removed Location
_autotune wall-clock race, 1 warmup + 2 launches, 5% margin gptqmodel/nn_modules/qlinear/gguf.py:1719-1725
_benchmark_forward_runner / _benchmark_{dense,fused}_forward / _sync_benchmark_device gptqmodel/nn_modules/qlinear/gguf.py:1689-1717
per-shape decision cache _gguf_fused_autotune_cache gptqmodel/nn_modules/qlinear/gguf.py:1739-1747
AUTOTUNE = True on the GGUF Torch kernel gptqmodel/nn_modules/qlinear/gguf.py:1194
gguf_fused_autotune_{warmup,iters,margin} gptqmodel/utils/kernel.py:194-196, gptqmodel/utils/backend_config.py:105,114-116
retired GPTQMODEL_GGUF_FUSED_AUTOTUNE_* env mappings gptqmodel/__init__.py:97-99

Reproduced on Qwen2.5-0.5B-Instruct Q4_K_M (GGUFConfig(bits=4, format="q_k_m"),
GGUF_TORCH, CPU, float16), same 7-token input, 4 processes:

Process Modules on the fused path logits checksum
idle 104 / 168 -17482.8208
busy thread 157 / 168 -17189.0795
idle 137 / 168 -16752.2017
busy thread 163 / 168 -16844.2119

Max |Δlogit| between runs: 0.0332. The only difference between the runs is a
background thread doing its own matmul.

2. The new flow

flowchart TD
    A["GGUFTorchLinear.forward"] --> B["_should_use_fused_k_forward"]
    B --> C["_is_fused_k_forward_candidate<br/>`gguf.py:1667-1684`"]
    C --> D{"quantized qtype, no adapter,<br/>not training, no grad?"}
    D -- "no" --> G["_forward_dequant_matmul"]
    D -- "yes" --> E{"max_rows > 0 and rows <= max_rows<br/>and in*out >= min_matrix_elements?"}
    E -- "no" --> G
    E -- "yes" --> F["_forward_fused_k"]
    classDef failure fill:#fce8e6,stroke:#a33,color:#111
    class G failure
Loading

Nothing times either path and no decision is cached, so the answer is the same
on every call, in every process, regardless of load.

3. Before and after

Mechanism Before After
Path selection timed race per device/dtype/shape pure function of gguf_fused_* gates + activation shape
Decision cache _gguf_fused_autotune_cache none
AUTOTUNE True False (autotune_enabled no longer selects the GGUF path)
Timing config gguf_fused_autotune_warmup/_iters/_margin removed (not kept as dead config)
Retired env vars mapped to the three fields "removed; GGUF fused dispatch is static"
Gate tuning implicit, online offline via scripts/benchmark_gguf_fused_thresholds.py

BaseQuantLinear.AUTOTUNE stays for kernels where a timing search only picks
between numerically identical layouts (ParoQuantTriton tiles).

4. Numerics

Both paths stay within the documented GGUF Torch tolerance: against an FP64
dequantized-weight oracle, relative error is 1.6e-3..1.7e-3 for the fused and
the dense path (Q4_K/Q6_K/Q8_0, 1x7/7x7/32 rows, BF16 activations). The residual
is the quantized weight, not the GEMM. Fused-vs-dense drift is bounded by the
activation dtype's rounding, not by the selector.

CUDA measured with interleaved single-launch CUDA events on the target host:

Layer dtype dense/fused
Q4_K 2048x8192 bf16 / fp32 1.54-1.70x
Q4_K 2048x8192 fp16 0.90x
Q5_K 2048x8192 bf16 / fp32 1.43-1.51x
Q6_K 4096x4096 bf16 / fp32 1.55-1.65x

The shipped max_rows = 32 / 8_388_608-element floor keeps the fused path for
decode and short prefill and the dense path for the wide prefill shapes it
loses; CPU defaults (max_rows = 64, floor 0) come from the same script.

5. Failure and ambiguity contract

Situation Before After
Same input, process idle one path same path
Same input, unrelated thread busy 104/168 vs 157/168 modules on the fused path same path, bit-identical logits
Same input, fresh process different logits bit-identical logits
Shape above the row ceiling whichever timing won dense path
Adapter attached, training, or grad enabled whichever timing won dense path

6. Change inventory

Area File ± Purpose
dispatch gptqmodel/nn_modules/qlinear/gguf.py +19 −66 static gates only; timing helpers removed
config gptqmodel/utils/kernel.py, gptqmodel/utils/backend_config.py −10 drop the three timing knobs
config gptqmodel/__init__.py +3 −3 retired env vars report "removed"
tooling scripts/benchmark_gguf_fused_thresholds.py (from benchmark_gguf_autotune_ab.py) ±~180 offline gate tuning, records drift + selected path
tests tests/kernels/test_gguf_fused_dispatch_reproducible_4590.py +172 new
tests tests/kernels/test_gguf_torch_cpu.py, tests/test_weight_only.py +130 −125 replace the autotune tests
docs docs/gguf-torch-fused-dispatch.md +134 new reference page, linked from README.md
docs docs/kernel-config.md, docs/backend-selection.md −4 +1 removed fields

7. Tests / guarantees

Test Invariant
test_repeated_first_forward_under_background_load_selects_one_path a busy neighbour thread cannot move a module between paths, or change the bytes
test_two_processes_produce_the_same_path_and_bytes two fresh processes pick the same path and the same checksum
test_decision_does_not_depend_on_call_order_or_shape_history the answer is per-shape, not per-call-order
test_gguf_fused_decision_is_a_pure_function_of_the_static_gates nothing benchmarks either path
test_gguf_fused_path_ignores_the_autotune_flag autotune_enabled cannot flip the numerics
test_gguf_static_gates_match_the_measured_crossover shipped gate defaults are pinned
test_gguf_forward_uses_the_static_gates_not_a_timed_plan widening/narrowing a gate at run time switches paths
test_gguf_forward_uses_dense_when_the_row_gate_excludes_fused the row ceiling still routes to dense

The first test fails on the pre-fix code with assert {False, True} == {True}.

8. Validation

# GGUF + weight-only + backend-config suites
python -m pytest tests/kernels/test_gguf_*.py tests/test_weight_only.py tests/test_backend_config.py -q
# 486 passed, 145 skipped

# backend / config / CPU-policy / concurrency subset
python -m pytest tests/test_backend_config.py tests/test_cpu_policy_4396.py tests/test_runtime_config_4448.py \
    tests/test_concurrency_guards.py tests/kernels/test_gguf_cpp_path_selection.py \
    tests/kernels/test_gguf_cpp_activation_quantization.py tests/test_gguf_cpu_autocast_cancellation.py \
    tests/test_gguf_bias_range.py -q
# 91 passed, 73 skipped

ruff check gptqmodel/nn_modules/qlinear/gguf.py gptqmodel/utils/kernel.py \
    gptqmodel/utils/backend_config.py tests/kernels/test_gguf_torch_cpu.py \
    tests/kernels/test_gguf_fused_dispatch_reproducible_4590.py tests/test_weight_only.py \
    scripts/benchmark_gguf_fused_thresholds.py
# All checks passed!

End-to-end on the reported checkpoint (Qwen2.5-0.5B-Instruct Q4_K_M,
GGUF_TORCH, CPU): the same 4-process idle/busy sweep selects 168/168 on
the fused path every time and the logits are bit-identical; the pre-fix numbers
are the table in §1.

9. Reviewer notes

  • This takes the issue's second suggested option (deterministic static rule,
    timing only offline) rather than making the two paths numerically identical.
    Making the dense CPU path run under cpu_bf16x3_matmul() would add a global
    precision scope to the fallback that also serves offload/edge shapes, and it
    measured within 20% of the fused path at the shapes where the fused path
    exists, so it buys nothing.
  • Removing gguf_fused_autotune_* is deliberate: GGUFTorchConfig rejects
    unknown fields, and a knob that can only be ignored is a dead switch the
    project's configuration rules exclude.
  • Not in scope: ROCm fused-kernel run-to-run reduction differences (~7e-3 on a
    2048x8192 Q4_K layer). They exist before and after this change and are a
    property of the fused kernel, not of the selector.

Fixes #4590

@Qubitium

Copy link
Copy Markdown
Collaborator

@ZX-ModelCloud Resolve conflict and reviews

…ming race (#4590)

`GGUFTorchLinear._should_use_fused_k_forward` picked between
`_forward_fused_k` and `_forward_dequant_matmul` by timing one warmup plus two
launches of each path per `(device, dtype, shape)` and keeping the fused path
when it won by more than 5%. The two paths are not bitwise equivalent -- on CPU
the fused reduction runs inside `cpu_bf16x3_matmul()` while the dense one is
IEEE FP32 -- so which arithmetic a module used depended on unrelated process
load, and the logits changed run to run.

Reproduced on Qwen2.5-0.5B-Instruct Q4_K_M with `GGUF_TORCH` on CPU: four runs
of the same 7-token input selected the fused path for 104, 137, 157 and 163 of
168 modules depending on a background `matmul` thread, with up to 0.033 logit
drift. A neighbouring thread changes nothing about the checkpoint.

The choice is now a pure function of the shipped shape gates
(`gguf_fused_cpu_max_rows`, `gguf_fused_cpu_min_matrix_elements`,
`gguf_fused_cuda_max_rows`, `gguf_fused_cuda_min_matrix_elements`) and the
activation shape. Nothing times either path, and no decision is cached, so the
same input takes the same path in every forward and every process. Both paths
stay at 1.6e-3..1.7e-3 relative error against an FP64 dequantized-weight oracle,
so this is a performance choice, not a numerics trade-off.

The three timing knobs are removed rather than kept as dead config:
`KernelConfig.gguf_fused_autotune_warmup/_iters/_margin`,
`GGUFTorchConfig.fused_autotune_*`, `GGUFTorchLinear.AUTOTUNE` (now `False`)
and the retired `GPTQMODEL_GGUF_FUSED_AUTOTUNE_*` mappings, which now report
the setting as removed. `scripts/benchmark_gguf_autotune_ab.py` becomes
`scripts/benchmark_gguf_fused_thresholds.py`: it interleaves the two paths on
one module, reports both timings, the output drift and the path the shipped
gates select, so the defaults can be re-derived offline.

Tests: `tests/kernels/test_gguf_fused_dispatch_reproducible_4590.py` pins that a
busy neighbour thread, call order, and a fresh process cannot change the path or
the bytes (the first assertion fails on the pre-fix code with `{False, True} ==
{True}`); `tests/kernels/test_gguf_torch_cpu.py` pins that nothing benches the
paths, that `autotune_enabled` cannot flip the result, and the shipped gate
defaults; `tests/test_weight_only.py` pins that widening/narrowing the gate at
run time switches paths. 444 passed, 145 skipped across the GGUF and
weight-only suites; 91 passed, 73 skipped across the backend/config/CPU
policy suites; ruff clean.

Docs: `docs/gguf-torch-fused-dispatch.md` (linked from `README.md`) carries the
before/after flow, the removed mechanism with file references, the numerics and
the measured numbers.
@ZX-ModelCloud
ZX-ModelCloud force-pushed the fix/gguf-deterministic-fused-choice branch from f23e9e1 to 5d85d83 Compare November 17, 2026 05:53
@Qubitium
Qubitium merged commit dfa180d into main Nov 17, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/gguf-deterministic-fused-choice branch November 17, 2026 05:54
Qubitium added a commit that referenced this pull request Nov 17, 2026
Fix the test-side fallout of #4716, #4657, #4627 and #4508. Only entries
that fail on this sm_80 host (PG506) and whose stated reasoning reproduces
were changed; the rest are recorded with their outcome.

1. 8587f0b (#4716, native FP8 GEMM for a wide bias)
   - tests/kernels/test_fp8_kernel.py::test_fp8_default_forward_is_w8a16
     REPRODUCED on sm_80: 6 bf16 cases failed with 1-ulp (0.0078125) diffs
     against rtol/atol 2e-3. The oracle now narrows the decoded weight to
     the activation dtype, matching the native path; the bound is the
     half-ulp at unity (2^-9 ~= 2e-3). FIXED.
   - tests/test_fp8_bias_range.py::test_fp8_gpu_dequant_fallback_keeps_bias_wide
     REPRODUCED on sm_80 (fp16: actual 0.0 vs oracle 0.0078125). Renamed to
     test_fp8_gpu_native_gemm_keeps_bias_wide and rewritten for the #3737
     intent: finite output, FP32 bias, residual bounded by one activation-
     dtype ulp of |x.w|. FIXED.

2. bf5adeb (#4657, Marlin bias kept in checkpoint order)
   - tests/test_marlin_scratch_cuda.py 288/200 cases REPRODUCED on sm_80:
     8 failed with "b_bias.size(0) != size_n". scripts/marlin_scratch_fixture.py
     now passes layer._kernel_bias(a) (padded, tile-ordered FP32) instead of
     the checkpoint-order layer.bias. FIXED (8 failed -> 68 passed, 2 skipped).

3. 60376e9 (#4714, default placement in one capability group)
   - tests/test_tenstorrent_support.py already passes on current main: the
     monkeypatched _record accepts **kwargs (fixed upstream by 50f1752).
     ALREADY PASSES on sm_80.

4. 34672a7 (#4585, modules snapshot the kernel policy)
   - tests/kernels/test_bitsandbytes_rocm_triton.py triton cases SKIP on
     sm_80 (no tuned bitsandbytes tile for this family). DEFERRED: the
     stated failure cannot be reproduced here.

5. dfa180d (#4627, GGUF path chosen from static gates)
   - both tests REPRODUCED on sm_80 with AttributeError
     _benchmark_forward_runner. The removed timing hook is no longer patched;
     each test asserts the hook stays absent. FIXED.

6. fd8d524 (#4599, AwqGEMVTorchLinear CPU reader)
   - both kernel-registry contract tests already pass on current main
     (AwqGEMVTorchLinear is in EXCLUDED and the ROCm audit table; fixed
     upstream by ab151fe). ALREADY PASSES on sm_80.

7. d2a0508 (#4283, dense-module adapters)
   - tests/kernels/test_gptq.py::TestKernelOutput errors on sm_80 before the
     adapter path: this host's flash_attn_2_cuda has an undefined symbol, so
     the stated Lora assertion is never reached. DEFERRED: blocked by the
     pre-existing host flash_attn failure; the fix cannot be verified here.

8. f201837 (#4508, activation-quantization wording)
   - both tests REPRODUCED on sm_80. The refusal still fires; the regex now
     matches "activation quantized|activation scales". FIXED.

9. b225a43 (#4727, static-cache compile test)
   - ROCm-only failure. On sm_80 the CUDA leg runs and fails earlier on the
     host flash_attn symbol, so the ROCm gate cannot be reproduced.
     DEFERRED.

Test run (GPU 4):
  tests/kernels/test_fp8_kernel.py tests/test_fp8_bias_range.py
  tests/test_marlin_scratch_cuda.py tests/test_marlin_scratch_benchmark.py
  tests/kernels/test_gguf_cpp_activation_quantization.py
  tests/kernels/test_gguf_cpp_path_selection.py tests/test_auto_module_decoder.py
  => 254 passed, 35 skipped, 1 failed.
The single failure is the pre-existing sm_80
test_fp8_w8a8_forward_is_batch_invariant (native torch._scaled_mm needs
sm_89+); it fails identically on origin/main.
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.

[BUG] GGUF Torch CPU picks fused (BF16x3) vs dense (IEEE) per shape by a wall-clock race: logits depend on concurrent CPU load and differ run to run

2 participants