Skip to content

perf(kernels): cache per-call dispatch decisions (#3983) - #4000

Merged
Qubitium merged 1 commit into
mainfrom
fix/issue-3983
Nov 14, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/issue-3983

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #3983

TL;DR

Four per-call host costs in the kernel dispatch path are replaced by cached decisions: torch.ops handle resolution, the ExLlamaV2 q-matrix handle key, bitsandbytes version/QuantState checks, and the AWQ FP16 bias epilogue. 12 files touched, +1278/−34 with tests, docs, and two runnable scripts. Every change is bitwise neutral: the same kernels run with the same arguments.

1. The problem

1a. torch.ops handles re-resolved through the loader

Every wrapper called _extension_api().op(name, op_name), which goes through _load_one: name normalization, two import_module calls, the build lock, _spec_supported, ext.load(), and the os.environ reads in force_rebuild_enabled().

flowchart TD
    A["awq_gemm_forward / gptq_marlin_gemm / ..."] --> B["_extension_api().op(name, op_name)"]
    B --> C["_load_one: normalize, import, lock,<br/>support probe, load, env reads"]
    C --> D["extension.op(op_name)"]
    D --> E["launch kernel"]
    style C fill:#f8d7da,stroke:#b02a37,stroke-width:2px
Loading

Measured 4.8-5.6 us per lookup against 0.15 us for a cached handle.

1b. ExLlamaV2 rebuilds its handle key every forward

_ensure_q_handle built a dict, merged it into q_tensors, and ran tensor_cache_key for 4-6 tensors on every call (qlinear/exllamav2.py:197 on origin/main).

1c. bitsandbytes re-validates per forward

import_bitsandbytes() parsed two versions per call and is called twice per forward; _refresh_quant_state rebuilt a signature with str(device) and 4 Module.__getattr__ per tensor.

1d. AWQ bias epilogue used four kernels

out = out.float() + self.bias.float(); out = out.to(input_dtype) at qlinear/gemv_awq.py:229 and qlinear/gemv_fast_awq.py:210.

2. The new flow

flowchart TD
    A["awq_gemm_forward / gptq_marlin_gemm / ..."] --> B["_awq_op / _marlin_resolve_op / _exllamav2_op"]
    B --> C{"_extension_api is<br/>original loader?"}
    C -- "no" --> D["_extension_api().op(name, op_name)"]
    C -- "yes" --> E["loaded_op(extension, op_name)"]
    E --> F{"extension._namespace_cache<br/>is set?"}
    F -- "no" --> D
    F -- "yes" --> G{"op in<br/>extension._op_cache?"}
    G -- "yes" --> H["return cached torch.ops handle"]
    G -- "no" --> I["getattr(namespace, op_name)<br/>store in _op_cache"]
    I --> H
    D --> J["_load_one"]
    J --> K["extension.op(op_name)"]
    style D fill:#fff3cd,stroke:#997404,stroke-width:2px
    style J fill:#fff3cd,stroke:#997404,stroke-width:2px
Loading

loaded_op (gptqmodel/utils/cpp.py:2025) only reads the extension's own namespace and handle cache. clear_cache() resets both, so every clear_*_extension_cache() invalidates it. Each wrapper module captures its original loader at import time (_MARLIN_EXTENSION_API, _AWQ_EXTENSION_API, _EXLLAMAV2_EXTENSION_API, _QQQ_EXTENSION_API, _MACHETE_EXTENSION_API) so a test that replaces _extension_api is never shadowed by a memoised handle.

ExLlamaV2 q-matrix handle

flowchart TD
    A["forward -> _ensure_q_handle"] --> B{"_fusion_native_view?"}
    B -- "yes" --> C["return q_handle"]
    B -- "no" --> D{"_q_fast snapshot exists<br/>and q_handle set?"}
    D -- "yes" --> E{"first 4 tensors are<br/>the same objects?"}
    E -- "no" --> G["slow path"]
    E -- "yes" --> F{"(version, data_ptr, dtype, shape)<br/>unchanged for every tensor?"}
    F -- "yes" --> H["return q_handle"]
    F -- "no" --> G
    G --> I["merge q_tensors, tensor_cache_key,<br/>_release_q_handle if key changed"]
    I --> J["ext_make_q_matrix if q_handle is None"]
    J --> K["store _q_fast snapshot"]
    K --> H
    style G fill:#fff3cd,stroke:#997404,stroke-width:2px
Loading

make_q_matrix call counts stay [0, 0, 1, 2, 3, 3] for {forward, forward, attribute replace, in-place mul_, .data= swap, inference-mode forward} — pinned by a test.

bitsandbytes

flowchart TD
    A["BitsAndBytesLinear.forward"] --> B["import_bitsandbytes()"]
    B --> C{"_VALIDATED_BITSANDBYTES<br/>set?"}
    C -- "yes" --> D["return cached module"]
    C -- "no" --> E["import bitsandbytes,<br/>version.parse twice"]
    E --> F{"version >= minimum?"}
    F -- "no" --> G["raise ImportError"]
    F -- "yes" --> H["store module"]
    H --> D
    D --> I["_refresh_quant_state()"]
    I --> J{"signature ==<br/>_quant_state_signature?"}
    J -- "yes" --> K["reuse QuantState"]
    J -- "no" --> L["QuantState.from_dict"]
    style G fill:#f8d7da,stroke:#b02a37,stroke-width:2px
Loading

Signature is now tuple((t.shape, t.device, t.dtype) for t in (...)) (bitsandbytes.py:597): one attribute lookup per tensor, no string formatting. torch.Size/torch.device compare by value, so the predicate is unchanged.

AWQ bias epilogue

flowchart TD
    A["out = gemv/gemv_fast kernel"] --> B{"bias is not None?"}
    B -- "no" --> E["out.to(input_dtype)"]
    B -- "yes" --> C{"input_dtype == float16 and<br/>bias.dtype == float16?"}
    C -- "yes" --> D["out = torch.add(out, bias)"]
    C -- "no" --> F["out = out.float() + bias.float()"]
    D --> E
    F --> E
    style F fill:#fff3cd,stroke:#997404,stroke-width:2px
Loading

A CUDA FP16 add already accumulates in FP32 and rounds once. BF16 inputs and mixed dtypes keep the wide path.

3. Change inventory

Area File ± Purpose
op fast path helper gptqmodel/utils/cpp.py +27 loaded_op
Marlin gptqmodel/utils/marlin.py +18/−1 _marlin_resolve_op fast path
AWQ gptqmodel/utils/awq.py +30/−7 _awq_op for all 7 wrappers
ExLlamaV2 gptqmodel/utils/exllamav2.py +33/−6 _exllamav2_op for all 6 call sites
QQQ / Machete gptqmodel/utils/qqq.py, utils/machete.py +18, +22 _qqq_op, _machete_op
ExLlamaV2 handle qlinear/exllamav2.py +36 _q_fast snapshot
AWQ probes qlinear/gemv_fast_awq.py, qlinear/exllamav2_awq.py +21, +11 _runtime_ok
bitsandbytes qlinear/bitsandbytes.py +32/−7 validated module + tuple signature
Bias epilogue qlinear/gemv_awq.py, qlinear/gemv_fast_awq.py +11, +21 single FP16 add
Tests tests/test_kernel_dispatch_caching.py +497 19 regression tests
Benchmarks scripts/benchmark_kernel_dispatch_overhead.py +230 reproduces the table
Equivalence scripts/verify_kernel_dispatch_equivalence.py +133 128-case torch.equal proof
Docs docs/kernel-dispatch-caching.md, README.md +192, +1 flow + contracts

4. Bitwise equivalence

scripts/verify_kernel_dispatch_equivalence.py captures the kernel result, applies the pre-change expression as an independent oracle, and requires torch.equal:

  • kernels: AWQ GEMV, AWQ GEMV_FAST
  • shapes: 4096x4096, 4096x14336, 14336x4096, 2048x2048
  • M: 1, 16, 300, 640
  • dtypes: fp16, bf16
  • bias: on, off
cases=128 mismatches=0 max_abs_diff=0

The dispatch, handle, and bitsandbytes changes do not alter arithmetic at all; they return the same handle / skip a rebuild whose result is identical.

5. Host-time table (RTX 4090, 2000 iterations, best of 5)

scripts/benchmark_kernel_dispatch_overhead.py, run on origin/main (aad1d12) and on this branch with the same script.

Path before after change
Marlin op resolution 5.57 us 0.34 us -94%
AWQ op resolution 4.85 us 0.15 us -97%
ExLlamaV2 op resolution 4.86 us 0.16 us -97%
QQQ op resolution 4.83 us 0.15 us -97%
ExLlamaV2 _ensure_q_handle 6.66 us 2.99 us -55%
bitsandbytes version check 2.44 us 0.08 us -97%
bitsandbytes QuantState signature 6.12 us 1.99 us -68%
AWQ GEMM 4096x4096, M=1 32.57 us 23.64 us -27%
AWQ GEMM bias 31.55 us 24.70 us -22%
AWQ GEMV 4096x4096, M=1 19.03 us 12.55 us -34%
AWQ GEMV bias 19.90 us 12.92 us -35%
AWQ GEMV_FAST 4096x4096, M=1 28.65 us 16.80 us -41%
AWQ GEMV_FAST bias 29.94 us 19.61 us -35%
Bias epilogue 4096x4096 (wide -> single) 16.6 us 3.9 us -76%

ROCm (R9700, HIP_VISIBLE_DEVICES=0), same script; the CUDA-only AWQ/Marlin/QQQ/Machete extensions are skipped by design:

Path before after
ExLlamaV2 _ensure_q_handle 6.32 us 3.04 us
bitsandbytes version check 2.45 us 0.08 us
bitsandbytes QuantState signature 6.08 us 1.92 us
Bias epilogue (wide -> single) 13.1-18.2 us 3.3-4.5 us

Hardware: RTX 4090 GPU-1892aea4-cc09-827c-b9a5-93d4eef7f5ae (CUDA 13.0, torch 2.16.0.dev) and Radeon AI PRO R9700 (HIP_VISIBLE_DEVICES=0, ROCm 10.1). The RTX 5090 was not used.

6. Tests

tests/test_kernel_dispatch_caching.py (19 tests): loader-call counting for Marlin/AWQ/ExLlamaV2/QQQ/Machete, cache-clear invalidation, the fake-loader identity guard, ExLlamaV2 handle rebuild counts and fast-path key-rebuild counting, in-place write detection, bitsandbytes version caching + signature shape + invalidation, and the FP16 bias add (single kernel, wide path for BF16, bitwise equality).

Fail before / pass after (same file, origin/main worktree vs branch):

# origin/main aad1d1243
PYTHONPATH=/tmp/wt3983 ... pytest tests/test_kernel_dispatch_caching.py -q
=> 11 failed, 8 passed

# fix/issue-3983
PYTHONPATH=$PWD ... pytest tests/test_kernel_dispatch_caching.py -q
=> 19 passed

Related suites (CUDA venv):

pytest tests/test_kernel_dispatch_caching.py tests/test_extension_load_api.py -q
=> 40 passed
pytest tests/test_kernel_audit_regressions.py tests/test_exllamav2_jit.py tests/test_exllamav2_awq_jit.py tests/test_marlin_jit.py tests/test_machete_jit.py -m "not cuda" -q
=> 169 passed, 20 deselected, 5 failed

The 5 failures are tests/test_machete_jit.py post-init/state-dict cases that fail identically on unmodified origin/main (Machete needs SM90). ROCm: 40 passed for the dispatch tests; the related suite is 167 passed, 7 failed — the same 5 Machete cases plus test_awq_gemm_validation_matches_native_width_and_group_contract and test_machete_validation_checks_extension_availability, both also failing on unmodified main under ROCm.

ruff check gptqmodel docs/eora tests setup.py scripts/benchmark_kernel_dispatch_overhead.py scripts/verify_kernel_dispatch_equivalence.py => All checks passed.

7. Reviewer notes and limitations

  • Machete is not executable here. It is SM90-only and this host is Ada (SM89), so machete_mm/machete_prepack_B fast paths are covered by loader-call counting only, not a real kernel run. The helper is the same one exercised by the AWQ/Marlin paths.
  • bitsandbytes forward equivalence was not reproduced. The CUDA venv has no bitsandbytes; the ROCm venv has 0.50.2 but bnb.matmul_4bit did not make progress in this environment (killed after ~7 minutes). The change is a memoisation plus an equivalent signature predicate, and the cache contract (validate once, clear on _clear_availability_state(), rebuild on shape/device/dtype change) is unit-tested with fakes.
  • GPTQMODEL_*_FORCE_REBUILD is a build-time knob. A mid-process toggle now takes effect on the next load() / clear_*_extension_cache(), not on every op call. This is the cost of removing the per-call environment reads the issue measured.
  • .data.copy_() writes are not visible to _version, so they do not invalidate the ExLlamaV2 snapshot. The pre-existing tensor_cache_key cache had the same blind spot; .data = swaps (the case in the fix(exllamav2): reuse act-order handle #3733/fix(exllamav2): preserve shuffled words across handle lifecycle #3771 sequence) do change data_ptr and are detected.
  • No GPTQMODEL_* behaviour switches were added. No dense or expanded weight cache is retained: the new caches hold handles, a native pointer, a validated module, and scalar signatures.

torch.ops handles were re-resolved through the extension loader on every
call: name normalization, two import_module calls, the build lock, support
probes, load() and the rebuild env reads. Reuse the loaded namespace via
loaded_op() and fall back to the loader otherwise. clear_cache() resets the
namespace and handle cache, and an identity guard keeps a memoised handle
from shadowing a test's fake loader.

Also stop rebuilding decisions that cannot change between calls:
ExLlamaV2 _ensure_q_handle compares a per-tensor identity/version/pointer
snapshot instead of rebuilding q_tensors and tensor_cache_key; the AWQ
GEMV/GEMV_FAST runtime probes memoise after the first success; bitsandbytes
validates its version once per process and builds the QuantState signature
from (shape, device, dtype) tuples.

The AWQ bias epilogue now uses one FP16 add instead of widening both
operands, which a CUDA FP16 add already does internally. BF16 and mixed
dtypes keep the wide path. Outputs are bitwise identical: 128/128 cases
match torch.equal against the pre-change expression.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant