Skip to content

[PERF] Per-call host overhead in kernel dispatch: torch.ops re-resolved every call, ExLlamaV2 handle key rebuild, bnb version parsing, 4-kernel AWQ GEMV bias epilogue (bitwise-identical, 5-42% at M=1) #3983

Closed

Description

@Qubitium

Perf audit of main @ 93d3ae7 on RTX 4090, torch 2.15. At M=1 (decode) these kernels are CPU/launch-bound: a 4096² Marlin GEMM is ~20 µs of GPU time, against ~17 µs of host time per call. Python overhead on every forward therefore shows up directly in decode tokens/s. Every item below produces bitwise identical output (torch.equal), because the same kernels run with the same arguments.

"Wall" means per-call time over back-to-back eager calls (2000 iterations, best of 3).

1. torch.ops handles are re-resolved through the extension loader on every call (~2.4–3 µs per op)

Each call goes through _extension_api().op(...) → _load_one. That does name normalisation, 2× import_module, a lock, _spec_supported, ext.load(), and the os.environ reads in force_rebuild_enabled(). Cost: 2.42 µs per lookup, against 0.06 µs for a cached handle.

Call sites:

  • gptqmodel/utils/marlin.py:973 (gptq_marlin_gemm → _marlin_resolve_op) and :340
  • gptqmodel/utils/awq.py:121-160 (every AWQ wrapper)
  • gptqmodel/utils/exllamav2.py:256, 325
  • gptqmodel/utils/qqq.py:115 (likewise utils/machete.py)

Two forwards also re-check runtime availability on every call:

  • qlinear/gemv_fast_awq.py:168 (awq_runtime_available(), 2.7 µs)
  • qlinear/exllamav2_awq.py:231 (exllamav2_awq_runtime_available())

M=1 fp16, 4096×4096:

kernel before after change
Marlin GPTQ (host) 16.7–17.0 µs 13.7–14.0 µs −17–19% (bf16 similar)
AWQ GEMM (no bias, wall) 21.2 µs 18.4 µs −13%
AWQ GEMV (no bias, wall) 12.0 µs 9.3 µs −23%
AWQ GEMV_FAST (no bias, wall) 15.1 µs 9.4 µs −38%
Marlin AWQ (bias, wall) 17.65 µs 16.85 µs −5%
ExLlamaV2 AWQ (bias, wall) 28.25 µs 26.33 µs −7%

Fix: reuse the pattern already in utils/paroquant.py:445 (_paroquant_rotation_op): return ext.op(name) directly once ext._namespace_cache is populated, and otherwise fall back to the loader. Or memoise per (kernel, op) and clear the memo in clear_*_extension_cache().

For the two runtime checks, keep the check (tests/test_awq_gemv_fast_jit.py:98 expects ModuleNotFoundError on a fresh module), but remember a per-module _runtime_ok after the first success.

Test note: tests/test_marlin_jit.py monkeypatches _extension_api, so either clear the memo there or bypass it when _extension_api is not the original. These files are also touched by #3857 (stable ABI), which changes build flags but not op lookup.

2. ExLlamaV2 rebuilds its handle cache key on every forward

gptqmodel/nn_modules/qlinear/exllamav2.py:197 (_ensure_q_handle, called from forward) builds a dict, runs dict.update, and computes tensor_cache_key for 4–6 tensors on every call (~4.5 µs). The op is then also resolved as in item 1.

M=1 host time: 23.2–24.0 → 17.3–17.9 µs (−25%) on 4096², 4096×14336, 14336×4096 and 2048², with and without act-order.

Invalidation is unchanged: the make_q_matrix call counts are identical before and after the change, [0, 0, 1, 2, 3, 3] for {forward, forward, attribute replace, in-place mul_, .data= swap, inference-mode forward}. So the #3733 / #3771 handle-lifecycle guarantees and test_exllamav2_handle_tracks_replaced_packed_tensors hold.

Fix: add a fast path at the top of _ensure_q_handle when q_handle is set:

objs, sigs = self._q_fast   # (qweight, qzeros, scales, g_idx, *extra), per-tensor signatures
sig = lambda t: (None if t.is_inference() else t._version, t.data_ptr(), t.dtype, t.shape)
if objs[0] is self.qweight and objs[1] is self.qzeros and objs[2] is self.scales \
   and objs[3] is self.g_idx and all(sig(t) == s for t, s in zip(objs, sigs)):
    return self.q_handle

Otherwise fall through to the existing slow path and refresh _q_fast.

3. bitsandbytes 4-bit forward re-parses versions and rebuilds a string signature on every call

  • qlinear/bitsandbytes.py:160: import_bitsandbytes() runs 2× packaging.version.parse, and it is called twice per forward (:576, :844).
  • qlinear/bitsandbytes.py:577: the cache signature uses str(device), tuple(shape) and 4 Module.__getattr__ per forward.

M=1 fp16, 4096², wall: nf4 27.0 → 22.9 µs (−15%), fp4 26.8 → 22.8 µs, nf4 with bias 28.1 → 22.9 µs. For reference, a bare bnb.matmul_4bit call is 14.2 µs.

Equivalence: 36 cases (nf4/fp4/int8 × bias × M ∈ {1, 16, 300} × fp16/bf16), 0 mismatches.

Fix:

  • Cache the validated module after the first successful version check, and clear it in _clear_availability_state().
  • Build the signature as tuple((t.shape, t.device, t.dtype) for t in (...)). torch.Size and device compare by value, so the semantics are identical.

4. AWQ GEMV / GEMV_FAST bias epilogue uses 4 elementwise kernels where 1 gives the same bits

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

When both operands are fp16, a CUDA fp16 add already computes in fp32 and rounds once, so the result is identical. The current code spends 4 kernels and 3 temporaries on it. The comment's concern, rounding to bf16 before the add, still applies, so keep the wide path for mixed dtypes.

M=1, with bias, wall:

  • GEMV 4096²: 29.65 → 17.27 µs (−42%); 4096×11008: 29.4 → 17.4 µs.
  • GEMV_FAST 4096²: 33.2 → 21.0 µs (−37%); 4096×11008: 32.9 → 20.9 µs.

Equivalence: 40 cases (both kernels × 2 shapes × fp16/bf16 input × M ∈ {1, 4, 16, 64, 300}), 0 mismatches. I also re-checked the fp16+fp16 add identity independently.

if input_dtype == torch.float16 and self.bias.dtype == torch.float16:
    out = torch.add(out, self.bias)
else:
    out = out.float() + self.bias.float()
if out.dtype != input_dtype:
    out = out.to(dtype=input_dtype)

Impact

With ~224 quantized linears per token on a 7B model, items 1–2 alone save roughly 0.5–1.3 ms per decode token in eager mode.

Smaller, unmeasured follow-ups

  • TorchLinear._can_use_rocm_gemv → _can_use_rocm_fused / _can_use_triton_dequant costs 5.2 µs of a 26.7 µs M=1 call: ~20 checks, 2 tuning_family lookups, ~17 __getattr__. Its x-independent part could be memoised, but qzero_format() can change without clearing caches, so this needs care.
  • gptq_gemv / Triton dequant pay ~1.3 µs for launch_config / block_k_for and ~1.2 µs for the torch.cuda.device(...) context per call; both could be cached per device.

🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions