Skip to content

fix(gguf): keep the K-quant shift tables on the device so CUDA-graph capture works (#5014) - #5035

Merged
Qubitium merged 1 commit into
mainfrom
root/gguf-kquant-graph-5014
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
root/gguf-kquant-graph-5014

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Fixes #5014. GGUFTorchLinear declares SUPPORTS_GRAPH_CAPTURE = True (measured
on GB10) and docs/kernel-compile-matrix.md listed it as capture-safe, but that
only held for Q4_0/Q8_0. Every K-quant dense dequantizer built its
right-shift table on the host on every forward:

@staticmethod
def _u8_shift(values, device):
    return torch.tensor(values, dtype=torch.uint8, device=device)

A pageable host-to-device copy is illegal during capture, so an explicit
torch.cuda.graph capture of any K-quant layer failed:

RuntimeError: Cannot copy between CPU and CUDA tensors during CUDA graph capture
unless the CPU tensor is pinned.

That covers the default GGUFConfig(bits=4, format="q_k_m") output, and outside
capture the same code issued 1-3 small pageable H2D copies per layer per
forward. The fused K path only serves M <= 32 with in*out >= 8,388,608, so
every smaller layer and every prefill took the dense path.

What Changed

  • gptqmodel/nn_modules/qlinear/gguf.py
    • _u8_shift now returns an immutable device constant cached per module and
      device ((device.type, device.index) -> shift tuple -> uint8 tensor)
      instead of building a new CUDA tensor per call. clear_weight_cache drops
      the cache, so a device move (_apply) or a reload rebuilds on the new
      device; it never runs on the forward path.
    • New GGUFTorchLinear.supports_graph_capture() answers for the stored
      format
      : GRAPH_CAPTURE_QTYPES = {Q4_0, Q8_0, Q4_K, Q5_K, Q6_K} are
      device-dequantized and capturable; Q2_K, Q3_K and the remaining
      codebook formats still dequantize through numpy on the host and cannot be
      captured.
  • gptqmodel/nn_modules/qlinear/_compile_support.py: graph_capture_safe(instance)
    consults supports_graph_capture() when present, while
    graph_capture_safe(cls) keeps returning the class declaration the protocol
    test checks. This is the "codify the level in the kernel" contract: a class
    that serves several stored formats can now answer per instance instead of
    over-claiming.
  • tests/kernels/gen_compile_matrix.py + docs/kernel-compile-matrix.md:
    the header documents the per-instance refinement (the table itself is
    unchanged, because the class declaration still covers the device formats).
    Regenerated with python -m tests.kernels.gen_compile_matrix; idempotent.
  • tests/kernels/test_gguf_kquant_graph_capture_5014.py (new, 19 nodes).

Tests

tests/kernels/test_gguf_kquant_graph_capture_5014.py on unmodified
origin/main (test copied into a separate worktree): 15 failed, 4 passed —
every q4_k/q5_k/q6_k capture node raises the pinned-copy RuntimeError, the
warm-forward counter finds 4 host-built CUDA tensors per call, the shift table
is rebuilt on every call, and the per-format helper does not exist. On this
branch: 19 passed.

Capture matrix (2-D GGUFTorchLinear, 512x256, fp16, warm-up then
torch.cuda.graph, M=1 and M=64):

bits main this PR
q4_0 capture OK capture OK
q8_0 capture OK capture OK
q2_k FAIL pinned-copy not capturable by design (supports_graph_capture() False)
q3_k FAIL pinned-copy not capturable by design
q4_k FAIL pinned-copy capture OK
q5_k FAIL pinned-copy capture OK
q6_k FAIL pinned-copy capture OK

For the capturable formats the test asserts the replay, not the capture-time
buffer (a capture records work instead of running it, so the buffer is only
meaningful after graph.replay()): replay with the same input and replay after
copying a different input into the same buffer are both bitwise equal to eager.
The two host-dequantized formats are only asserted at the declaration level — a
failed capture poisons the caching allocator's graph pool for the rest of the
process, so it is never attempted.

Bitwise equality against the pre-change code (same fixture, sha256 of the
tensors): dequantize_weight in fp32 and fp16, _forward_dequant_matmul and
_forward_fused_k are identical for Q4_0/Q8_0/Q4_K/Q5_K/Q6_K. The change
only caches the same uint8 constants, so no numeric drift is possible.

Suite counts (same file set, both trees):

run main this PR
9 GGUF torch/format files 147 passed 166 passed (+19 = the new file)
test_kernel_compile_levels_quant.py + test_kernel_compile_protocol.py 59 passed, 173 skipped 78 passed, 173 skipped (+19)
the above plus the GGUF files and the new file, after the rebase — 208 passed, 168 skipped

ruff check clean on all changed files. The GGUF-CUDA llama.cpp lane is not
built with CUDA on this host, so those nodes are skipped/failing identically on
both trees and are untouched by this change.

Model Support / Module Plan

No model or module-plan change. The kernel declaration protocol gained a
per-instance refinement hook, which any multi-format kernel can now implement.

Logic Flow Documentation

docs/kernel-compile-matrix.md (generated) documents that a class declaration
answers for the default runtime state and that GGUFTorchLinear refines it per
stored format; the _compile_support.py module docstring says the same next to
the SUPPORTS_GRAPH_CAPTURE contract.

Kernel Accuracy Requirements

  • Accuracy: bitwise identical (sha256 of the dequantized weight in fp32 and
    fp16, plus both forward paths) rather than an oracle tolerance, because the
    change only memoizes constants. Verified for every K-quant kind and the
    Q4_0/Q8_0 controls.
  • Device report: capture is validated on sm_80 (PG506, torch
    2.15.0.dev20260928+cu130). The declaration is per format, not per
    architecture; the two host-dequantized formats are explicitly excluded
    instead of being silently assumed.

Notes

  • The cache is per module and per device, keyed by the shift tuple; it holds
    three tables of 2-8 bytes each, which is what makes capture possible (a
    warmed module must not allocate device memory from host data inside the
    captured region).
  • A module rehomed by a class swap (no __init__ run) lazily creates the cache
    dict, so the QQQ-style rehome path cannot raise AttributeError.
  • No SUPPORTS_COMPILE policy change: the kernel still declares
    SUPPORTS_COMPILE_LEVEL = EAGER because dynamo breaks on
    tensor.is_inference() in tensor_cache_key; only the eager CUDA-graph
    claim is now true for the formats that actually support it.

…ks (#5014)

`GGUFTorchLinear` declares `SUPPORTS_GRAPH_CAPTURE = True` and the compile
matrix listed it as capture-safe, but only Q4_0/Q8_0 actually were. Every
K-quant dense dequantizer (Q4_K/Q5_K/Q6_K and Q2_K/Q3_K) built its right-shift
table with `torch.tensor(values, dtype=torch.uint8, device=blocks.device)` on
every forward. A pageable host-to-device copy is illegal during capture, so an
explicit `torch.cuda.CUDAGraph` capture of any K-quant layer raised

    RuntimeError: Cannot copy between CPU and CUDA tensors during CUDA graph
    capture unless the CPU tensor is pinned.

which covers the default `GGUFConfig(bits=4, format="q_k_m")` output. Outside
capture the same code issued one to three small copies per layer per forward.

`_u8_shift` now returns an immutable device constant cached per module and
device (`(device.type, device.index)` -> shift tuple -> tensor), so a warm
forward issues no host copy at all and a warmed layer captures with a stable
allocation. `clear_weight_cache` drops the cache, so a device move or a reload
rebuilds on the new device; it never runs on the forward path.

The host-dequantized formats (Q2_K/Q3_K and the remaining codebook types) still
cannot be captured, so the claim is now honest per instance:
`GGUFTorchLinear.supports_graph_capture()` answers for the stored format, and
`graph_capture_safe(instance)` returns it while `graph_capture_safe(cls)` keeps
returning the class declaration the protocol test checks.
`docs/kernel-compile-matrix.md` documents the refinement (table unchanged).

Dequantized weights and forward outputs are bitwise identical: the same
sha256 for `dequantize_weight` in fp32 and fp16, `_forward_dequant_matmul` and
`_forward_fused_k` on Q4_0/Q8_0/Q4_K/Q5_K/Q6_K before and after.
@Qubitium
Qubitium merged commit 0ff0c0e into main Nov 17, 2026
9 checks passed
@Qubitium
Qubitium deleted the root/gguf-kquant-graph-5014 branch November 17, 2026 23:53
Qubitium added a commit that referenced this pull request Nov 18, 2026
…S_GRAPH_CAPTURE (#5014) (#5045)

``graph_capture_safe()`` consulted an instance's ``supports_graph_capture()``
hook before looking at the class declaration, so a kernel that declares
``SUPPORTS_GRAPH_CAPTURE = False`` but inherits ``GGUFTorchLinear``'s per-format
hook (``GGUFCppKernel``, ``GGUFCudaKernel``) was reported capturable whenever
its format happened to be in ``GRAPH_CAPTURE_QTYPES``. The hook is a
refinement of the declaration, not an override of it: it may narrow ``True``
per runtime format, never widen a ``False``.

``graph_capture_safe()`` now reads the declaration first and only asks the
instance when that declaration is ``True``. ``GGUFTorchLinear``'s own hook
applies the same rule, so ``GGUFTorchLinear.supports_graph_capture()`` also
answers ``False`` on a subclass that turned the claim off. No runtime format
changes: Q2_K/Q3_K still narrow to ``False`` and Q4_K/Q5_K/Q6_K stay
capturable.

Follow-up to #5014 / #5035. The test node fails on unmodified main (the
helper answers ``True`` for a subclass that declares ``False``) and passes
here; the other 19 nodes of the file are unchanged.
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