Repository navigation
fix(dispatch): CPU group-size gate, CPU-offload kernel choice, max_memory, compile paths (#4054) - #4062
Merged
Conversation
…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
This was referenced Nov 14, 2026
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.
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_mapthat offloads layers to CPU, and now honorsmax_memory. Twotorch.compilepaths are made lowerable/disabled as appropriate without changing eager numerics. Net: 12 source files, +842/−48, plusdocs/kernel-dispatch-cpu.mdand 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:2pxgptqmodel/nn_modules/qlinear/torch_fused.py:72(SUPPORTS_GROUP_SIZE = [-1, 16, 32, 64, 128]), inherited attorch_fused_awq.py:46addmm(..., out_dtype=float32)in the FP32-reduce epiloguegptqmodel/nn_modules/qlinear/_numerics.py:146(and_CudaWideMatmul.forwardat:93)gptqmodel/nn_modules/qlinear/w4a_floatx.py:438(W4AFP8Linear.forward)gptqmodel/utils/importer.py:1088-1095(normalize_device_device_map), selection atimporter.py:1274max_memoryswallowed by**kwargs; fixed round-robingptqmodel/models/loader.py:2332(build_layerwise_device_map).train()raised midway; explicit branch droppedadapter; wrong variable in messagegptqmodel/models/base.py:5450,importer.py:1488,nn_modules/qlinear/__init__.py:951,9762. 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:2pxTorchFusedAwqLinear._validatecalls 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:2pxSUPPORTS_CPU_OFFLOADis a new declaration onBaseQuantLinear(defaultFalse, fail closed), setTrueonTritonV2LinearandAwqGEMMTritonLinear— both are CUDA-only to execute but theirpost_initis Torch-only.Item 7 —
max_memoryplacementflowchart 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:2pxItem 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:2px3. Failure and ambiguity contract
RuntimeErrorfrom atenTorchCpuAvx512Linear/TorchLineargptq_torch_fusedNotImplementedErrorat selection naming the resolved sizedevice_mapwith CPU layers + AUTOMarlinLinearselected,ValueError: GPTQ Marlin requires CUDA tensors, got cpuTritonV2Linearselected, loads and runsdevice_mapwith CPU layers + explicitgptq_marlinValueErroratpost_initValueErrorat selection with guidancemax_memorygivendevice_mapdict andmax_memoryValueErrordynamic+cache_implementation="static"LoweringExceptionW4AFP8Linearundertorch.compileInductorError: NameError: name 'gl' is not defined.train()on an inference-only kerneltraining=True4. Change inventory
gptqmodel/nn_modules/qlinear/torch_fused.pyCPU_INT4PACK_GROUP_SIZES,_validate_cpu_int4pack_group_size,_validateoverridegptqmodel/nn_modules/qlinear/torch_fused_awq.pygptqmodel/nn_modules/qlinear/_numerics.pymm+ FP32 addgptqmodel/nn_modules/qlinear/w4a_floatx.py@torch.compiler.disableonforwardgptqmodel/utils/importer.pycpu_offloadgate;adapterpassed in the explicit branchgptqmodel/utils/model.pymake_quant(cpu_offload=...)gptqmodel/models/loader.py_normalize_max_memory,_assign_greedy_device_ids,_module_tensor_bytes,_device_map_uses_cpu, budget-aware map buildergptqmodel/models/base.pytrain()gptqmodel/nn_modules/qlinear/__init__.pySUPPORTS_CPU_OFFLOAD; corrected desc_act/sym messagesgptqmodel/nn_modules/qlinear/tritonv2.py,gemm_awq_triton.pySUPPORTS_CPU_OFFLOADdocs/kernel-dispatch-cpu.mdREADME.mdtests/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.py5. Tests / guarantees
test_selection.py::test_torch_fused_cpu_rejects_group_size_the_int4pack_op_cannot_consumetest_selection.py::test_torch_fused_cpu_keeps_xpu_and_resolved_per_channel_group_sizestest_selection.py::test_cpu_auto_does_not_select_torch_fused_for_group_size_16test_selection.py::test_auto_cpu_offload_skips_a_cuda_only_post_initpost_inittest_selection.py::test_auto_cpu_offload_accepts_a_declared_post_init_safe_cuda_kerneltest_selection.py::test_explicit_cuda_only_backend_rejects_a_cpu_offload_maptest_selection.py::test_explicit_backend_passes_the_adapter_to_validationSUPPORTS_ADAPTERStest_layerwise_device_placement.py(+8)test_linear_fp32_reduce.py::test_bias_path_eager_output_is_bitwise_unchangedaddmmtest_linear_fp32_reduce.py::test_compiled_bias_path_uses_a_lowerable_gemmaddmmtest_linear_fp32_reduce.py::test_compiled_bias_path_matches_eagerrtol=atol=2e-3test_w4afp8_gb10.py::test_w4afp8_linear_runs_under_torch_compiletest_train_mode_atomicity.py.train()leaves no module in training modetest_qlinear_hierarchy.py(+2)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-appsshowed no foreign process before the timing-free runs.Fail-before / pass-after (pristine
origin/mainworktree vs this branch):/tmp/qwen4_gm1)RuntimeError: _weight_int4pack_mm_cpu: expect qGroupSize to be 32, 64, 128 or 256, got 896(kernelTorchFusedLinear)TorchLinear, forward finite, greedy generate OKRuntimeError: ... got 16(kernelTorchFusedLinear)TorchLinear, forward finitedevice_mapwithmodel.layers.2/3: "cpu"ValueError: GPTQ Marlin requires CUDA tensors, got cpuTritonV2Linear; logits bitwise equal to explicitgptq_triton(rel0.0), greedy generate identicalmax_memory={0: "350MiB", "cpu": "8GiB"}cuda:0, 0 on CPUcuda:0, 12 on CPU; forward finitemax_memory={0: "4GiB"}cuda:0cuda:0torch.compile(W4AFP8Linear)InductorError: NameError: name 'gl' is not definedmatmul_fp32_reducecompiled graphaddmmin graphaddmm; eager path stilltorch.equalto the old expressiongenerate(cache_implementation="static")vs"dynamic"LoweringExceptionon the bias pathExact commands → results
Pre-existing failures reproduced on pristine
origin/mainand therefore not claimed as regressions: the 9 intests/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), theEvalutionimport intest_q4_torch_fused.py, andtest_gguf_does_not_accept_generic_torch_backendafter the2c032e02amerge.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.0for fp16/bf16 at rows 1/6/32 and0.015625at fp16 rows 17, within the skill's2e-3relative bound. No weight cache was added or retained;W4AFP8Linearstill rebuilds its E4M3 operand per forward.7. Reviewer notes
SUPPORTS_CPU_OFFLOADis deliberately separate fromSUPPORTS_DEVICES; a kernel may be CUDA-only to execute yet safe topost_initon CPU. The default isFalse, so a new CUDA-only kernel fails closed rather than crashing at load.max_memoryuses a greedy in-order fill, notaccelerate.infer_auto_device_map. That keeps placement deterministic and testable, andinfer_auto_device_mapneeds 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 owninfer_auto_device_mapuses.diskentries are not treated as CPU offload; the existing meta/disk paths (_post_init_cpu_offloaded_marlin) are unchanged.torch.compiler.disableonW4AFP8Linear.forwardis a deliberate graph break. It is the cheaper and safer option than wrapping the Gluon launch intorch.library.custom_op, per the issue's recommendation.docs/kernel-dispatch-cpu.md, linked fromREADME.mdnext to the kernel-dispatch section.