Skip to content

fix(dispatch): CPU group-size gate, CPU-offload kernel choice, max_memory, compile paths (#4054) - #4062

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4054-dispatch
Nov 14, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4054-dispatch

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Part of #4054

Items 3–7 and the Minor list of #4054. Items 1–2 (AWQ CUDA GEMV_FAST split-K, GEMV OOB) are the sibling PR #4058 and are not in this diff. Branch merged with origin/main @ 2c032e02a.

TL;DR

Five dispatch/placement defects and three Minor items. AUTO no longer selects a CPU kernel whose group size the packed int4 op rejects, no longer selects a CUDA-only kernel for a device_map that offloads layers to CPU, and now honors max_memory. Two torch.compile paths are made lowerable/disabled as appropriate without changing eager numerics. Net: 12 source files, +842/−48, plus docs/kernel-dispatch-cpu.md and 2 new/expanded test files.

1. The problem (old flow)

flowchart TD
    A["select_quant_linear(AUTO, device=CPU)"] --> B["validate(TorchAtenLinear)<br/>group_size 16 / -1 rejected"]
    B --> C["validate(TorchFusedLinear)<br/>declares -1, 16, 32, 64, 128"]
    C --> D["selected -> TorchFusedLinear"]
    D --> E["load succeeds"]
    E --> F["first forward"]
    F --> G["aten::_weight_int4pack_mm_for_cpu"]
    G --> H["RuntimeError: expect qGroupSize<br/>to be 32, 64, 128 or 256, got 896 / got 16"]
    style H fill:#f8d7da,stroke:#b02a37,stroke-width:2px
Loading
Item Old mechanism file:line before
3 CPU group size declared but never checked against the int4pack op gptqmodel/nn_modules/qlinear/torch_fused.py:72 (SUPPORTS_GROUP_SIZE = [-1, 16, 32, 64, 128]), inherited at torch_fused_awq.py:46
4 addmm(..., out_dtype=float32) in the FP32-reduce epilogue gptqmodel/nn_modules/qlinear/_numerics.py:146 (and _CudaWideMatmul.forward at :93)
5 Gluon FP8 launch compiled by Inductor gptqmodel/nn_modules/qlinear/w4a_floatx.py:438 (W4AFP8Linear.forward)
6 Kernel selected from accelerator entries only; CPU map entries ignored gptqmodel/utils/importer.py:1088-1095 (normalize_device_device_map), selection at importer.py:1274
7 max_memory swallowed by **kwargs; fixed round-robin gptqmodel/models/loader.py:2332 (build_layerwise_device_map)
Minor .train() raised midway; explicit branch dropped adapter; wrong variable in message gptqmodel/models/base.py:5450, importer.py:1488, nn_modules/qlinear/__init__.py:951,976

2. The new flow

Item 3 — CPU int4pack group-size gate

flowchart TD
    A["TorchFusedLinear._validate"] --> B["super()._validate (bits/sym/desc_act/shape)"]
    B --> C{"normalize_device(device) == DEVICE.CPU?"}
    C -- "no" --> D["XPU keeps declared -1 and 16"]
    C -- "yes" --> E["_validate_cpu_int4pack_group_size"]
    E --> F{"group_size == -1?"}
    F -- "yes, in_features known" --> G["resolved = in_features"]
    F -- "yes, in_features None" --> H["defer to per-module validation"]
    F -- "no" --> I["resolved = group_size"]
    G --> J{"resolved in 32, 64, 128, 256?"}
    I --> J
    J -- "yes" --> K["candidate stays valid"]
    J -- "no" --> L["NotImplementedError:<br/>CPU int4pack rejects the size"]
    H --> K
    style L fill:#f8d7da,stroke:#b02a37,stroke-width:2px
Loading

TorchFusedAwqLinear._validate calls the same helper, so the AWQ variant cannot drift.

Item 6 — CPU-offload-aware selection

flowchart TD
    A["from_quantized(device_map)"] --> B["_device_map_uses_cpu(explicit_device_map)"]
    B --> C{"CPU entry, or cpu<br/>max_memory budget?"}
    C -- "no" --> D["cpu_offload = False"]
    C -- "yes" --> E["cpu_offload = True"]
    E --> F["make_quant(..., cpu_offload=True)"]
    F --> G["select_quant_linear(cpu_offload=True)"]
    G --> H{"SUPPORTS_DEVICES has<br/>CPU or DEVICE.ALL?"}
    H -- "yes" --> I["post_init-safe"]
    H -- "no" --> J{"SUPPORTS_CPU_OFFLOAD?"}
    J -- "yes" --> I
    J -- "no" --> K["reject candidate"]
    style K fill:#f8d7da,stroke:#b02a37,stroke-width:2px
Loading

SUPPORTS_CPU_OFFLOAD is a new declaration on BaseQuantLinear (default False, fail closed), set True on TritonV2Linear and AwqGEMMTritonLinear — both are CUDA-only to execute but their post_init is Torch-only.

Item 7 — max_memory placement

flowchart TD
    A["GPTQModel.load(max_memory=...)"] --> B["from_quantized pops max_memory"]
    B --> C["_normalize_max_memory"]
    C --> D["ordered device string + byte budget"]
    D --> E["build_layerwise_device_map"]
    E --> F["units = input embedding, then decoder layers"]
    F --> G["_module_tensor_bytes per unit"]
    G --> H["_assign_greedy_device_ids"]
    H --> I{"fits current budget?"}
    I -- "yes" --> J["assign, subtract bytes"]
    I -- "no" --> K{"another budget?"}
    K -- "yes" --> H
    K -- "no" --> L["ValueError: cannot hold unit"]
    J --> M["head + ignored modules use remaining budget"]
    style L fill:#f8d7da,stroke:#b02a37,stroke-width:2px
Loading

Item 4 — compile-safe bias epilogue

flowchart TD
    A["matmul_fp32_reduce(x, weight, bias)"] --> B{"_wants_fp32_reduce(x)"}
    B -- "yes" --> C{"torch.compiler.is_compiling()?"}
    C -- "no" --> D["torch.addmm(bias.float(), flat_x, weight,<br/>out_dtype=float32)"]
    C -- "yes" --> E["torch.mm(flat_x, weight,<br/>out_dtype=float32) + bias.float()"]
    D --> F["eager rounding bitwise unchanged"]
    E --> G["Inductor lowers the graph"]
    style G fill:#d1e7dd,stroke:#146c43,stroke-width:2px
Loading

3. Failure and ambiguity contract

Situation Before After
CPU g16 / per-channel 896 + AUTO loads, first forward RuntimeError from aten rejected at selection; AUTO falls through to TorchCpuAvx512Linear / TorchLinear
CPU g16 + explicit gptq_torch_fused loads, first forward raises NotImplementedError at selection naming the resolved size
device_map with CPU layers + AUTO MarlinLinear selected, ValueError: GPTQ Marlin requires CUDA tensors, got cpu TritonV2Linear selected, loads and runs
device_map with CPU layers + explicit gptq_marlin ValueError at post_init ValueError at selection with guidance
max_memory given silently ignored placement restricted to named devices; overflow raises
device_map dict and max_memory one silently won ValueError
3-bit/dynamic + cache_implementation="static" Inductor LoweringException generates
W4AFP8Linear under torch.compile InductorError: NameError: name 'gl' is not defined eager graph break, correct output
.train() on an inference-only kernel raised midway, 6/59 modules left training=True rejected before any child is touched

4. Change inventory

File ± Purpose
gptqmodel/nn_modules/qlinear/torch_fused.py +82 CPU_INT4PACK_GROUP_SIZES, _validate_cpu_int4pack_group_size, _validate override
gptqmodel/nn_modules/qlinear/torch_fused_awq.py +40 inherits the gate
gptqmodel/nn_modules/qlinear/_numerics.py +15 compiling branch uses mm + FP32 add
gptqmodel/nn_modules/qlinear/w4a_floatx.py +6 @torch.compiler.disable on forward
gptqmodel/utils/importer.py +21 cpu_offload gate; adapter passed in the explicit branch
gptqmodel/utils/model.py +2 make_quant(cpu_offload=...)
gptqmodel/models/loader.py +216 _normalize_max_memory, _assign_greedy_device_ids, _module_tensor_bytes, _device_map_uses_cpu, budget-aware map builder
gptqmodel/models/base.py +46 atomic train()
gptqmodel/nn_modules/qlinear/__init__.py +13 SUPPORTS_CPU_OFFLOAD; corrected desc_act/sym messages
gptqmodel/nn_modules/qlinear/tritonv2.py, gemm_awq_triton.py +4 each declare SUPPORTS_CPU_OFFLOAD
docs/kernel-dispatch-cpu.md new reference page (diagrams above)
README.md +1 links the new page
tests/kernels/test_selection.py, test_layerwise_device_placement.py, test_train_mode_atomicity.py (new), test_qlinear_hierarchy.py, test_linear_fp32_reduce.py, test_w4afp8_gb10.py +440 regression coverage

5. Tests / guarantees

Test Invariant
test_selection.py::test_torch_fused_cpu_rejects_group_size_the_int4pack_op_cannot_consume CPU g16 and per-channel 896 rejected
test_selection.py::test_torch_fused_cpu_keeps_xpu_and_resolved_per_channel_group_sizes XPU keeps -1/16; per-channel resolving to 128 stays valid
test_selection.py::test_cpu_auto_does_not_select_torch_fused_for_group_size_16 AUTO falls through to a CPU-valid kernel
test_selection.py::test_auto_cpu_offload_skips_a_cuda_only_post_init CPU-offload map rejects CUDA-only post_init
test_selection.py::test_auto_cpu_offload_accepts_a_declared_post_init_safe_cuda_kernel declared-safe kernel stays eligible
test_selection.py::test_explicit_cuda_only_backend_rejects_a_cpu_offload_map explicit Marlin + CPU offload fails with guidance
test_selection.py::test_explicit_backend_passes_the_adapter_to_validation explicit branch honors SUPPORTS_ADAPTERS
test_layerwise_device_placement.py (+8) budget parsing, greedy placement, overflow, CPU detection, byte estimate
test_linear_fp32_reduce.py::test_bias_path_eager_output_is_bitwise_unchanged eager bias path bitwise equal to pre-fix addmm
test_linear_fp32_reduce.py::test_compiled_bias_path_uses_a_lowerable_gemm compiled graph contains no addmm
test_linear_fp32_reduce.py::test_compiled_bias_path_matches_eager compiled vs eager within rtol=atol=2e-3
test_w4afp8_gb10.py::test_w4afp8_linear_runs_under_torch_compile W4A runs compiled, matches eager
test_train_mode_atomicity.py failed .train() leaves no module in training mode
test_qlinear_hierarchy.py (+2) desc_act/sym messages name the right contract

6. Validation

Hardware: 1× RTX 4090 GPU-1892aea4-cc09-827c-b9a5-93d4eef7f5ae (SM 8.9), 1× R9700 (HIP_VISIBLE_DEVICES=0). nvidia-smi --query-compute-apps showed no foreign process before the timing-free runs.

Fail-before / pass-after (pristine origin/main worktree vs this branch):

Repro Before After
CPU load, real 4-layer Qwen2.5-0.5B GPTQ per-channel (/tmp/qwen4_gm1) RuntimeError: _weight_int4pack_mm_cpu: expect qGroupSize to be 32, 64, 128 or 256, got 896 (kernel TorchFusedLinear) kernel TorchLinear, forward finite, greedy generate OK
CPU load, same model g16, AVX512 kernel unavailable RuntimeError: ... got 16 (kernel TorchFusedLinear) kernel TorchLinear, forward finite
device_map with model.layers.2/3: "cpu" ValueError: GPTQ Marlin requires CUDA tensors, got cpu TritonV2Linear; logits bitwise equal to explicit gptq_triton (rel 0.0), greedy generate identical
max_memory={0: "350MiB", "cpu": "8GiB"} 28 modules on cuda:0, 0 on CPU 16 on cuda:0, 12 on CPU; forward finite
max_memory={0: "4GiB"} 28 on cuda:0 28 on cuda:0
torch.compile(W4AFP8Linear) InductorError: NameError: name 'gl' is not defined compiles, matches eager
matmul_fp32_reduce compiled graph addmm in graph no addmm; eager path still torch.equal to the old expression
Qwen2.5-0.5B-GPTQ-Int4 generate(cache_implementation="static") vs "dynamic" Inductor LoweringException on the bias path identical token IDs

Exact commands → results

# CUDA venv (torch 2.16.0.dev+cu130), 4090
ruff check gptqmodel docs/eora tests setup.py
  -> All checks passed!

pytest tests/kernels/test_selection.py tests/test_layerwise_device_placement.py \
       tests/test_train_mode_atomicity.py tests/kernels/test_qlinear_hierarchy.py \
       tests/kernels/test_linear_fp32_reduce.py tests/kernels/test_w4afp8_gb10.py -q
  -> 233 passed, 1 failed, 41 skipped

# the single failure is pre-existing on origin/main @ 2c032e02a:
#   tests/kernels/test_selection.py::test_gguf_does_not_accept_generic_torch_backend
#   (DID NOT RAISE ValueError) — reproduced identically in a pristine origin/main worktree

# ROCm venv (torch 2.16.0.dev+rocm10.1), R9700
HIP_VISIBLE_DEVICES=0 pytest tests/kernels/test_selection.py \
       tests/test_layerwise_device_placement.py tests/test_train_mode_atomicity.py \
       tests/kernels/test_qlinear_hierarchy.py tests/kernels/test_linear_fp32_reduce.py -q
  -> 189 passed, 66 skipped

# CPU-only repros on both venvs
pytest tests/test_cpu_bias_cancellation.py tests/kernels/test_triton_fp32_reduce.py \
       tests/test_rocm_kernel_contracts.py tests/test_loader.py \
       tests/test_kernel_dispatch_caching.py tests/test_quant_module_device.py \
       tests/test_q4_torch_fused.py tests/test_torch_fused_asym_qzeros.py \
       tests/test_hf_gptqmodel_load_bridge.py -q
  -> 503 passed, 1 failed
#   the failure is tests/test_q4_torch_fused.py::TestsTorchFused::test_torch_fused
#   -> ValueError: Evalution is required for evaluation (missing optional package)

Pre-existing failures reproduced on pristine origin/main and therefore not claimed as regressions: the 9 in tests/test_kernel_audit_regressions.py (test_device_move_restores_checkpoint_layout, test_cpu_layer_accepts_new_activation_dtype_after_move, test_exllamav2_gptq_forward_compacts_noncontiguous_activations), the Evalution import in test_q4_torch_fused.py, and test_gguf_does_not_accept_generic_torch_backend after the 2c032e02a merge.

Numerics: the FP32-reduce eager branch is untouched, so its rounding is bitwise identical (asserted). The compiled branch differs from eager only where cuBLAS splits the reduction differently — measured max abs difference 0.0 for fp16/bf16 at rows 1/6/32 and 0.015625 at fp16 rows 17, within the skill's 2e-3 relative bound. No weight cache was added or retained; W4AFP8Linear still rebuilds its E4M3 operand per forward.

7. Reviewer notes

  • SUPPORTS_CPU_OFFLOAD is deliberately separate from SUPPORTS_DEVICES; a kernel may be CUDA-only to execute yet safe to post_init on CPU. The default is False, so a new CUDA-only kernel fails closed rather than crashing at load.
  • max_memory uses a greedy in-order fill, not accelerate.infer_auto_device_map. That keeps placement deterministic and testable, and infer_auto_device_map needs the real weight shapes and a tied-weight pass. Limitation: the estimate is per-module parameter/buffer bytes, so it ignores activation and scratch space — the same approximation Accelerate's own infer_auto_device_map uses.
  • disk entries are not treated as CPU offload; the existing meta/disk paths (_post_init_cpu_offloaded_marlin) are unchanged.
  • torch.compiler.disable on W4AFP8Linear.forward is a deliberate graph break. It is the cheaper and safer option than wrapping the Gluon launch in torch.library.custom_op, per the issue's recommendation.
  • Docs: docs/kernel-dispatch-cpu.md, linked from README.md next to the kernel-dispatch section.

…mory, compile paths (#4054)

Items 3-7 plus the Minor list of #4054.

* CPU AUTO selected `TorchFusedLinear` for group_size -1/16 although
  `aten::_weight_int4pack_mm_for_cpu` only accepts 32/64/128/256, so the
  first forward raised. Declare the CPU group-size contract in
  `TorchFusedLinear._validate` and inherit it in `TorchFusedAwqLinear`;
  XPU keeps -1/16.
* `matmul_fp32_reduce`/`_CudaWideMatmul` used
  `torch.addmm(..., out_dtype=float32)`, which Inductor cannot lower.
  Keep the eager expression bitwise unchanged and use
  `torch.mm(..., out_dtype=float32) + bias.float()` only while compiling.
* `W4AFP8Linear.forward` is `torch.compiler.disable`-d: Inductor codegens
  the Gluon kernel without its `gl` namespace.
* A `device_map` with CPU entries made AUTO pick a CUDA-only kernel whose
  `post_init` needs CUDA. `select_quant_linear(cpu_offload=...)` now also
  requires the CPU-safe declaration `SUPPORTS_CPU_OFFLOAD` (True on the
  Triton V2 / AWQ Triton kernels).
* `max_memory` was swallowed by `**kwargs`. `build_layerwise_device_map`
  now parses it into ordered budgets, restricts placement to the named
  devices, places embedding/layers/head greedily by tensor bytes, and
  raises instead of exceeding a cap.
* Minor: a failed `.train()` no longer leaves a partially-updated module
  tree; the explicit-backend branch of `select_quant_linear` passes
  `adapter` to validation; the desc_act/sym error text names the right
  contract instead of `bits`.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant