Repository navigation
fix(gguf): keep the K-quant shift tables on the device so CUDA-graph capture works (#5014) - #5035
Merged
Merged
Conversation
…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.
This was referenced Nov 17, 2026
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.
This was referenced Nov 18, 2026
7 tasks done
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
Fixes #5014.
GGUFTorchLineardeclaresSUPPORTS_GRAPH_CAPTURE = True(measuredon GB10) and
docs/kernel-compile-matrix.mdlisted it as capture-safe, but thatonly held for
Q4_0/Q8_0. Every K-quant dense dequantizer built itsright-shift table on the host on every forward:
A pageable host-to-device copy is illegal during capture, so an explicit
torch.cuda.graphcapture of any K-quant layer failed:That covers the default
GGUFConfig(bits=4, format="q_k_m")output, and outsidecapture the same code issued 1-3 small pageable H2D copies per layer per
forward. The fused K path only serves
M <= 32within*out >= 8,388,608, soevery smaller layer and every prefill took the dense path.
What Changed
gptqmodel/nn_modules/qlinear/gguf.py_u8_shiftnow returns an immutable device constant cached per module anddevice (
(device.type, device.index)-> shift tuple ->uint8tensor)instead of building a new CUDA tensor per call.
clear_weight_cachedropsthe cache, so a device move (
_apply) or a reload rebuilds on the newdevice; it never runs on the forward path.
GGUFTorchLinear.supports_graph_capture()answers for the storedformat:
GRAPH_CAPTURE_QTYPES = {Q4_0, Q8_0, Q4_K, Q5_K, Q6_K}aredevice-dequantized and capturable;
Q2_K,Q3_Kand the remainingcodebook 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, whilegraph_capture_safe(cls)keeps returning the class declaration the protocoltest 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.pyon unmodifiedorigin/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, thewarm-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 thentorch.cuda.graph, M=1 and M=64):mainq4_0q8_0q2_ksupports_graph_capture()False)q3_kq4_kq5_kq6_kFor 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 aftercopying 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_weightin fp32 and fp16,_forward_dequant_matmuland_forward_fused_kare identical for Q4_0/Q8_0/Q4_K/Q5_K/Q6_K. The changeonly caches the same
uint8constants, so no numeric drift is possible.Suite counts (same file set, both trees):
maintest_kernel_compile_levels_quant.py+test_kernel_compile_protocol.pyruff checkclean on all changed files. The GGUF-CUDA llama.cpp lane is notbuilt 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 declarationanswers for the default runtime state and that
GGUFTorchLinearrefines it perstored format; the
_compile_support.pymodule docstring says the same next tothe
SUPPORTS_GRAPH_CAPTUREcontract.Kernel Accuracy Requirements
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.
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
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).
__init__run) lazily creates the cachedict, so the
QQQ-style rehome path cannot raiseAttributeError.SUPPORTS_COMPILEpolicy change: the kernel still declaresSUPPORTS_COMPILE_LEVEL = EAGERbecause dynamo breaks ontensor.is_inference()intensor_cache_key; only the eager CUDA-graphclaim is now true for the formats that actually support it.