Skip to content

fix(dispatch): repair CPU optimize/compile, max_memory and HIP/autograd gates (#4068) - #4082

Merged
Qubitium merged 1 commit into
mainfrom
fix/issue-4068-dispatch
Nov 15, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/issue-4068-dispatch

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4068
Part of #4072 (items 2-4)

TL;DR

Six small dispatch/compile/build fixes, one per root cause: the five CPU kernel
optimize overrides now accept the base signature; the CPU int4pack helper is a
torch.compiler.disable boundary; an indexed device no longer replaces a
max_memory budget; the five HIP JIT loaders stage their sources under the
build cache; ParoQuantTritonLinear packs a strided decode slice; and the
bitsandbytes/GGUF Triton matmuls fall back when autograd must flow through the
input. docs/kernel-dispatch-cpu.md carries the diagrams; README.md links it.

1. model.optimize() on CPU AUTO kernels

gptqmodel/models/base.py:3210 forwards (backend, mode, fullgraph) to every
quantized module. Five overrides took optimize(self) with no parameters:
TorchAtenLinear (torch_aten_kernel.py:150), TorchFusedLinear
(torch_fused.py:232), TorchFusedAwqLinear (torch_fused_awq.py:165),
TorchAtenAwqLinear (torch_aten_kernel_awq.py:139) and TorchInt8Linear
(torch_int8.py:392). A CPU AUTO model therefore raised
TypeError: ... unexpected keyword argument 'fullgraph' before compiling
anything. They now match the base signature and forward all three options.

Before (base 39b62765e): TypeError in BaseQModel.optimize.
After: model.optimize(backend="eager") on a CPU model with 168 CPU kernels
completes and marks every module optimized.

2. CPU int4pack under torch.compile

_cpu_int4pack_mm (torch_fused.py:92) casts FP16/BF16 to FP32 and calls
aten::_weight_int4pack_mm_for_cpu. Inductor fused the cast into a Pointwise
node and could not lower int4pack on it. The #4060 FP32 product is what keeps a
biased FP16 pre-bias sum finite, so reverting to the dense FP16 path was not an
option. The helper is now decorated with torch.compiler.disable: the cast and
op stay eager inside the compiled model, and the FP32 product is unchanged.

flowchart TD
    A["TorchAtenLinear / TorchFusedLinear forward"] --> B{"biased FP16 or BF16?"}
    B -- "yes" --> C["_cpu_int4pack_mm FP32 product"]
    B -- "no" --> D["_cpu_int4pack_mm activation-dtype product"]
    C --> E["torch.compiler.disable boundary"]
    D --> E
    E --> F["aten::_weight_int4pack_mm_for_cpu eager"]
    F --> G["bias add, round once"]
    style E fill:#d1e7dd,stroke:#146c43,stroke-width:2px
Loading

Before: 4/4 cases failed with
InductorError: LoweringException: AssertionError: <class 'torch._inductor.ir.Pointwise'>.
After: FP16+bias returns 65216.0, BF16 returns 65024.0, both finite, and
compiled output is bitwise equal to eager.

3. max_memory with an indexed device

The old loader converted device="cuda:0" to {"": device} after the
device_map/max_memory conflict check (loader.py old ~L1915 and ~L1931), so
the explicit-map branch won and the cap was dropped. _normalize_explicit_placement
(loader.py:720) now decides both together: without a budget an indexed device
is still a full-model map; with max_memory it selects the accelerator family
and the budgeted layer-wise map owns placement. A device_map dict plus
max_memory still raises.

flowchart TD
    A["from_quantized(device, device_map, max_memory)"] --> B["_normalize_explicit_placement"]
    B --> C{"explicit device_map dict and max_memory?"}
    C -- "yes" --> D["ValueError: pass one, not both"]
    C -- "no" --> E{"indexed device and no max_memory?"}
    E -- "yes" --> F["full-model explicit map"]
    E -- "no" --> G["requested_device_map stays None"]
    G --> H["build_layerwise_device_map with budgets"]
    style D fill:#f8d7da,stroke:#b02a37,stroke-width:2px
    style H fill:#d1e7dd,stroke:#146c43,stroke-width:2px
Loading

Measured with Llama-3.2-1B-Instruct-GPTQ-4bits-gp128,
max_memory={0: "300MiB", "cpu": "20GiB"}, dtype=float16:

device base 39b62765e this branch
None {'cpu': 18, 'cuda:0': 2} {'cpu': 18, 'cuda:0': 2}
"cuda:0" {'cuda:0': 1} (cap dropped) {'cpu': 18, 'cuda:0': 2}
torch.device("cuda:0") {'cuda:0': 1} (cap dropped) {'cpu': 18, 'cuda:0': 2}

Same result on the R9700.

4. HIP JIT loaders write into the source tree (#4072 item 2)

torch hipifies out-of-tree sources by writing <name>_hip.{hip,cpp} next to the
original. allspark_hip.py:40, hadamard.py:31, quantization/gptq_cuda.py:16,
exllamav3/ext.py:75 and paroquant.py:317 passed checkout paths directly;
.gitignore:228-229 hid the generated files, and a read-only install could not
build. TorchOpsJitExtension now has stage_hip_sources (cpp.py:1221): it
copies the source root to <base_build_root>/_src, remaps the source and
include paths, and builds from the copy. All five loaders set the flag;
nf12_hip and tt_blockfloat_hip already staged their own sources.

flowchart TD
    A["TorchOpsJitExtension.load()"] --> B["_resolved_sources_and_include_paths"]
    B --> C{"stage_hip_sources and ROCm?"}
    C -- "no" --> D["build from checkout paths"]
    C -- "yes" --> E["copy source root to base_build_root/_src"]
    E --> F["remap sources and include paths"]
    F --> G["torch JIT build + hipify"]
    G --> H["generated files stay in _src"]
    style D fill:#f8d7da,stroke:#b02a37,stroke-width:2px
    style H fill:#d1e7dd,stroke:#146c43,stroke-width:2px
Loading

Verified on gfx1201: a fresh ParoQuant rotation build and a fresh Hadamard build
both loaded, and find gptqmodel_ext -type f was byte-for-byte unchanged before
and after. The generated rotation.hip, hadamard_hip.cpp and
fast_hadamard_transform_hip.hip landed in the temp _src.

5. ParoQuantTritonLinear strided decode (#4072 item 3)

paroquant_triton.py:224 now calls
x.reshape(-1, x.shape[-1]).contiguous(). generate() feeds
hidden_states[:, -1:, :]; the fused rotation rejects a strided view. The
existing strided test is parametrized over ParoLinear and
ParoQuantTritonLinear (tests/kernels/test_paroquant.py:535).

Before: RuntimeError: ParoQuant rotation tensors must be contiguous.
After: both classes return max diff 0.0 against the contiguous call on the
4090 and the R9700.

6. bitsandbytes / GGUF Triton autograd gate (#4072 item 4)

bitsandbytes.py:901 adds
not (torch.is_grad_enabled() and x.requires_grad) to the Triton dispatch.
gguf_triton.py:2080 routes a grad-requiring input (or trainable bias) to
GGUFTorchLinear.forward. Both Triton paths are raw launches with no backward.

Before (M=16, x.requires_grad=True): bitsandbytes grad_fn=None,
x.grad=None; GGUF used the fused path.
After: the vendor bitsandbytes kernel is used and MatMul4BitBackward is
present; GGUF uses the torch path, out.grad_fn is set, and x.grad is finite.

Validation

Hardware: RTX 4090 GPU-1ece7ec2-d88d-9284-93c8-d2578d90ad7e; AMD R9700
HIP_VISIBLE_DEVICES=1 (gfx1201). Never the RTX 5090.

Fail-before on a clean origin/main worktree (39b62765e), with the new tests
copied in:

Test Base result
tests/test_cpu_kernel_optimize.py TypeError: ... unexpected keyword argument 'fullgraph'
tests/test_inference_fp16_overflow.py::test_cpu_fused_layers_compile_through_the_int4pack_path 4 failed, LoweringException
tests/test_hip_jit_source_staging.py 7 failed, AttributeError: stage_hip_sources
test_paroquant_cuda_forward_packs_a_strided_activation[ParoQuantTritonLinear] RuntimeError: ... must be contiguous
test_triton_dispatch_falls_back_when_the_input_needs_grad AssertionError: Triton ... must not service a grad input
test_grad_input_uses_the_differentiable_torch_path AssertionError: fused Triton path used
loader repro, device="cuda:0" + max_memory {'cuda:0': 1}

Pass-after:

# CPU (CUDA venv, no GPU needed)
PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest \
  tests/test_cpu_kernel_optimize.py tests/test_layerwise_device_placement.py \
  tests/test_hip_jit_source_staging.py \
  "tests/test_inference_fp16_overflow.py::test_cpu_fused_layers_compile_through_the_int4pack_path" -q
42 passed

# RTX 4090
CUDA_VISIBLE_DEVICES=GPU-1ece7ec2-d88d-9284-93c8-d2578d90ad7e PYTHONPATH=$PWD \
  /opt/venvs/cu130t/bin/python -m pytest tests/kernels/test_paroquant.py \
  tests/kernels/test_gguf_triton_bias_epilogue.py -q
73 passed, 1 skipped

# R9700
HIP_VISIBLE_DEVICES=1 PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest \
  tests/kernels/test_paroquant.py -q
43 passed, 7 skipped
HIP_VISIBLE_DEVICES=1 PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest \
  tests/kernels/test_bitsandbytes_rocm_triton.py -q
42 passed, 2 skipped
HIP_VISIBLE_DEVICES=1 PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest \
  "tests/kernels/test_gguf_rocm_triton.py::test_gguf_triton_rocm_matches_independent_oracle" -q
12 passed

Wider CPU-adjacent run (test_inference_fp16_overflow.py,
test_torch_compile_fallback.py, test_kernel_audit_regressions.py,
test_ret_idx_cache_invalidation.py, the new tests): 233 passed, 1 skipped, and
the two failures below, which also fail on base 39b62765e:
test_marlin_bias_cancels_before_the_fp16_cast[gptq] (For act_order, num_groups must be > 1) and
test_exllamav2_gptq_forward_compacts_noncontiguous_activations (test lambda
does not accept out_dtype).

ruff check gptqmodel docs/eora tests setup.py -> All checks passed!

Reviewer notes

  • torch.compiler.disable is a deliberate graph break; a torch.library.custom_op
    would keep fullgraph but needs a fake implementation and a new op contract.
    The default optimize(fullgraph=False) path is the one that regressed.
  • HIP staging copies the source root, not just the listed .cu files, so local
    headers and the caller's include paths keep resolving. A build root inside the
    checkout is rejected instead of recursing.
  • The GGUF gate also checks a trainable bias, not only x.requires_grad, since
    the fused launch drops that gradient too.
  • No new GPTQMODEL_* behaviour switches; no dense weight cache is retained.

…ad gates

- give the five CPU kernel optimize overrides the base signature (#4068)
- disable tracing inside _cpu_int4pack_mm so Inductor can lower the
  FP16+bias and BF16 int4pack path while keeping the #4060 FP32 product
- resolve an indexed device with max_memory before the conflict check so
  the budgeted layer-wise map is not replaced by a full-model map
- stage HIP JIT sources under the build cache for allspark, hadamard,
  gptq_block, exllamav3 and paroquant (#4072 items 2-4)
- pack the ParoQuant Triton flat activation and gate the bitsandbytes and
  GGUF Triton matmuls on requires_grad
@Qubitium
Qubitium merged commit 6842a9d into main Nov 15, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4068-dispatch branch November 15, 2026 00:52
Qubitium added a commit that referenced this pull request Nov 15, 2026
) (#4105)

* fix(rocm): stage HIP sources, make AWQ split-K deterministic, scope the BLAS pin (#4092)

ROCm follow-ups to #4072/#4075 after #4079/#4082:

- HIP JIT builds stage sources by default for every extension, including
  include roots inside the checkout, and refuse to hipify a tracked source in
  place. A CUDA-only extension can no longer overwrite the hand-written
  tt_blockfloat_hip sources; tt_blockfloat_cuda.prewarm()/_ops() are gated by
  supported().
- The AWQ Triton generic fused plan uses split_k_iters=1 on RDNA4 and whenever
  deterministic algorithms are enabled, removing the tl.atomic_add split-K
  reduction that made repeats differ. The exact-shape RDNA4 rules were already
  split-K=1.
- The deterministic rocBLAS override is scoped to run plans that build a
  Hessian (ProcessorStep.GPTQ). AWQ/RTN/QQQ keep hipBLASLt, which is 8-14x
  faster for their fp16/bf16 GEMMs. The GPTQ family keeps the override for its
  calibration forward and replay because those activations feed the Hessian;
  pinning only the X^T X GEMM regressed Qwen2.5-0.5B to 332/795 differing
  tensors. The switch is reference counted for concurrent workers.
- The hipBLASLt opt-in logs a warning once and the docs record that it gives
  up cross-process reproducibility.

Cross-process determinism after the change: GPTQ 0/483 and AWQ 0/371 on
Llama-3.2-1B (128 samples), and the Qwen2.5-0.5B test at 0/795.

* docs(rocm): record the post-#4094-merge measurements (#4092)

Re-measured on the reconciled tree (origin/main d7a41a1, gfx1201):

- F.linear TFLOPS rocBLAS -> hipBLASLt: 9.5 -> 139.0 (bf16 4096x4096x14336),
  10.2 -> 119.8 (fp16 512x2048x8192), 0.5 -> 7.3 (bf16 16x896x4864),
  20.5 vs 16.3 (fp32 8192x4096 X^T X; rocBLAS wins).
- Cross-process determinism: GPTQ 0/483, AWQ 0/371 (Llama-3.2-1B, 128
  samples). End-to-end 58.1/61.4 s (GPTQ) and 50.7/45.5 s (AWQ).
- Opt-in evidence is now a 4-run sample for
  GPTQMODEL_ROCM_QUANT_BLAS=hipblaslt: 222/483 differing between the two
  kernel-selection groups, 0 within a group; ROCBLAS_USE_HIPBLASLT=1 stays at
  224/483.
Qubitium added a commit that referenced this pull request Nov 17, 2026
…ry GPU (#4637)

max_memory is the authoritative placement list (#4082), but kernel selection
expanded the CUDA family to every visible GPU. On a mixed-generation host
(RTX 5090 sm_120 + RTX 4090 sm_89) the capability check then rejected budgets
that never touched the other card: max_memory={1: '20GiB'} and even a
GPU+CPU offload budget with BACKEND.TORCH failed with cuda:0=12.0,
cuda:1=8.9.

Resolve max_memory to the concrete accelerator devices it names and hand that
tuple to the layer-wise/kernel path, so the capability check only sees GPUs
that will hold weights. Integer ordinals now resolve against the active
accelerator instead of CPU when no device was passed, and a device that
contradicts the budget is rejected with an actionable message.

Issue #4632.
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