Repository navigation
perf(kernels): cache per-call dispatch decisions (#3983) - #4000
Merged
Merged
Conversation
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.
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.
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, twoimport_modulecalls, the build lock,_spec_supported,ext.load(), and theos.environreads inforce_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:2pxMeasured 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_handlebuilt a dict, merged it intoq_tensors, and rantensor_cache_keyfor 4-6 tensors on every call (qlinear/exllamav2.py:197on origin/main).1c. bitsandbytes re-validates per forward
import_bitsandbytes()parsed two versions per call and is called twice per forward;_refresh_quant_staterebuilt a signature withstr(device)and 4Module.__getattr__per tensor.1d. AWQ bias epilogue used four kernels
out = out.float() + self.bias.float(); out = out.to(input_dtype)atqlinear/gemv_awq.py:229andqlinear/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:2pxloaded_op(gptqmodel/utils/cpp.py:2025) only reads the extension's own namespace and handle cache.clear_cache()resets both, so everyclear_*_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_apiis 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:2pxmake_q_matrixcall counts stay[0, 0, 1, 2, 3, 3]for {forward, forward, attribute replace, in-placemul_,.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:2pxSignature 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.devicecompare 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:2pxA CUDA FP16 add already accumulates in FP32 and rounds once. BF16 inputs and mixed dtypes keep the wide path.
3. Change inventory
gptqmodel/utils/cpp.pyloaded_opgptqmodel/utils/marlin.py_marlin_resolve_opfast pathgptqmodel/utils/awq.py_awq_opfor all 7 wrappersgptqmodel/utils/exllamav2.py_exllamav2_opfor all 6 call sitesgptqmodel/utils/qqq.py,utils/machete.py_qqq_op,_machete_opqlinear/exllamav2.py_q_fastsnapshotqlinear/gemv_fast_awq.py,qlinear/exllamav2_awq.py_runtime_okqlinear/bitsandbytes.pyqlinear/gemv_awq.py,qlinear/gemv_fast_awq.pytests/test_kernel_dispatch_caching.pyscripts/benchmark_kernel_dispatch_overhead.pyscripts/verify_kernel_dispatch_equivalence.pytorch.equalproofdocs/kernel-dispatch-caching.md,README.md4. Bitwise equivalence
scripts/verify_kernel_dispatch_equivalence.pycaptures the kernel result, applies the pre-change expression as an independent oracle, and requirestorch.equal: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 onorigin/main(aad1d12) and on this branch with the same script._ensure_q_handleROCm (R9700,
HIP_VISIBLE_DEVICES=0), same script; the CUDA-only AWQ/Marlin/QQQ/Machete extensions are skipped by design:_ensure_q_handleHardware: 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):
Related suites (CUDA venv):
The 5 failures are
tests/test_machete_jit.pypost-init/state-dict cases that fail identically on unmodifiedorigin/main(Machete needs SM90). ROCm:40 passedfor the dispatch tests; the related suite is167 passed, 7 failed— the same 5 Machete cases plustest_awq_gemm_validation_matches_native_width_and_group_contractandtest_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_mm/machete_prepack_Bfast 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.bnb.matmul_4bitdid 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_REBUILDis a build-time knob. A mid-process toggle now takes effect on the nextload()/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-existingtensor_cache_keycache 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 changedata_ptrand are detected.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.