Repository navigation
fix(gguf): select the fused Torch forward from static gates, not a timing race (#4590) - #4627
Merged
Merged
Conversation
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
force-pushed
the
fix/gguf-deterministic-fused-choice
branch
from
November 17, 2026 05:53
f23e9e1 to
5d85d83
Compare
This was referenced Nov 17, 2026
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.
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
GGUFTorchLinearchose between its fused and dense forward by timing them, per(device, dtype, shape), on the first forward of that shape. The two paths arenot 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_autotunewall-clock race, 1 warmup + 2 launches, 5% margingptqmodel/nn_modules/qlinear/gguf.py:1719-1725_benchmark_forward_runner/_benchmark_{dense,fused}_forward/_sync_benchmark_devicegptqmodel/nn_modules/qlinear/gguf.py:1689-1717_gguf_fused_autotune_cachegptqmodel/nn_modules/qlinear/gguf.py:1739-1747AUTOTUNE = Trueon the GGUF Torch kernelgptqmodel/nn_modules/qlinear/gguf.py:1194gguf_fused_autotune_{warmup,iters,margin}gptqmodel/utils/kernel.py:194-196,gptqmodel/utils/backend_config.py:105,114-116GPTQMODEL_GGUF_FUSED_AUTOTUNE_*env mappingsgptqmodel/__init__.py:97-99Reproduced 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:Max
|Δlogit|between runs: 0.0332. The only difference between the runs is abackground 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 failureNothing 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
gguf_fused_*gates + activation shape_gguf_fused_autotune_cacheAUTOTUNETrueFalse(autotune_enabledno longer selects the GGUF path)gguf_fused_autotune_warmup/_iters/_marginscripts/benchmark_gguf_fused_thresholds.pyBaseQuantLinear.AUTOTUNEstays for kernels where a timing search only picksbetween numerically identical layouts (
ParoQuantTritontiles).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:
The shipped
max_rows = 32/8_388_608-element floor keeps the fused path fordecode and short prefill and the dense path for the wide prefill shapes it
loses; CPU defaults (
max_rows = 64, floor0) come from the same script.5. Failure and ambiguity contract
6. Change inventory
gptqmodel/nn_modules/qlinear/gguf.pygptqmodel/utils/kernel.py,gptqmodel/utils/backend_config.pygptqmodel/__init__.pyscripts/benchmark_gguf_fused_thresholds.py(frombenchmark_gguf_autotune_ab.py)tests/kernels/test_gguf_fused_dispatch_reproducible_4590.pytests/kernels/test_gguf_torch_cpu.py,tests/test_weight_only.pydocs/gguf-torch-fused-dispatch.mdREADME.mddocs/kernel-config.md,docs/backend-selection.md7. Tests / guarantees
test_repeated_first_forward_under_background_load_selects_one_pathtest_two_processes_produce_the_same_path_and_bytestest_decision_does_not_depend_on_call_order_or_shape_historytest_gguf_fused_decision_is_a_pure_function_of_the_static_gatestest_gguf_fused_path_ignores_the_autotune_flagautotune_enabledcannot flip the numericstest_gguf_static_gates_match_the_measured_crossovertest_gguf_forward_uses_the_static_gates_not_a_timed_plantest_gguf_forward_uses_dense_when_the_row_gate_excludes_fusedThe first test fails on the pre-fix code with
assert {False, True} == {True}.8. Validation
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 onthe fused path every time and the logits are bit-identical; the pre-fix numbers
are the table in §1.
9. Reviewer notes
timing only offline) rather than making the two paths numerically identical.
Making the dense CPU path run under
cpu_bf16x3_matmul()would add a globalprecision 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.
gguf_fused_autotune_*is deliberate:GGUFTorchConfigrejectsunknown fields, and a knob that can only be ignored is a dead switch the
project's configuration rules exclude.
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