Skip to content

fix(awq): give FORMAT.GEMV_FAST and LLM_AWQ a CPU in-session reader (#4736) - #4753

Merged
Qubitium merged 2 commits into
ModelCloud:mainfrom
n-o-t-mugen:fix/4736-awq-gemv-fast-cpu-insession
Nov 17, 2026
Merged

Qubitium merged 2 commits into
ModelCloud:mainfrom
n-o-t-mugen:fix/4736-awq-gemv-fast-cpu-insession

Conversation

@n-o-t-mugen

Copy link
Copy Markdown
Contributor

Fixes #4736 (the GEMV_FAST / LLM_AWQ half of #4554).

Summary

quantize() with format="gemv_fast" or format="llm-awq" always raised at the very end, after calibration had finished and before save() could run:

RuntimeError: Quantize: quantized layers use kernels that cannot run on the final device `cpu` (AwqGEMVFastLinear). ...

The quantize loop leaves packed layers on CPU, and rehome_quantized_kernel() must switch them to a kernel that runs there. #4599 added that CPU reader for FORMAT.GEMV only. The GEMV_FAST interleaved layout (shared by LLM_AWQ) had only CUDA-only kernels, so select_in_session_quant_linear(qcfg, cpu) returned No valid quant linear and the whole calibration was lost.

This PR applies the #4599 approach to GEMV_FAST and LLM_AWQ: it adds a portable Torch CPU reader for the layout.

What Changed

  • AwqGEMVFastTorchLinear / LLMAwqTorchLinear (gptqmodel/nn_modules/qlinear/gemv_fast_awq.py): CPU readers of the exact packed buffers the CUDA kernels use (INT16 interleaved qweight, FP16 scales, FP16 offset in qzeros / scaled_zeros).
    • Each forward reuses the existing, tested _dequantize_awq_gemv_fast layout inverse, accumulates in FP32 and rounds once. The dense tile is a bounded temporary and is never cached on the module.
    • SUPPORTS_FORMATS priority 0 plus PORTABLE_CPU_FALLBACK = True, so they are reached only when AUTO has no CPU kernel. The accelerator AUTO order is unchanged.
    • The layout contract (group 128, in % 64, out % 128, int16 pack) matches the native classes, so a CPU-packed checkpoint stays loadable by the CUDA extension.
    • LLMAwqTorchLinear also derives from LLMAwqLinear, so layout-keyed consumers (utils/mlx.py) still route it as LLM_AWQ.
    • QUANT_TYPE keeps the awq_ prefix because pack_module dispatches AWQ packers on it.
    • SUPPORTS_COMPILE_LEVEL = AOT_EAGER (measured, see below) and SUPPORTS_GRAPH_CAPTURE = False (CPU-only).
  • CPU-only quantize host (gptqmodel/models/base.py): GEMV_FAST / LLM_AWQ now pack with BACKEND.AWQ_TORCH instead of the CUDA-only AWQ_GEMV_FAST. Before, they were refused before calibration with does not support device: DEVICE.CPU.
  • Docs: rehome-resolution Mermaid diagram plus a before/after table in docs/in-session-model-after-offload.md; also docs/quantization-guide.md, docs/support-matrix.md and docs/kernel-compile-matrix.md (two new rows).

Behaviour after this PR

Flow Before After
CUDA quantize, gemv_fast / llm-awq RuntimeError after calibration, nothing saved Returns; in-session model runs on the CPU reader; save() writes the requested format
CPU-only quantize, same formats Refused before calibration Packs with AWQ_TORCH; quantize -> save -> AUTO reload on CPU
Reload on CUDA (BACKEND.GEMV_FAST / AUTO) n/a Unchanged: native AwqGEMVFastLinear / LLMAwqLinear
gemv, gemm, other methods - Unchanged

Usage (no API change):

model = GPTQModel.load(model_id, AWQConfig(bits=4, group_size=128, format="gemv_fast"))  # or "llm-awq"
model.quantize(CalibrationConfig(dataset=calib))   # no longer raises
model.save(out_dir)                                # GEMV_FAST checkpoint, int16 [out/4, in] qweight
GPTQModel.load(out_dir, device="cuda", backend=BACKEND.GEMV_FAST)  # fast native path

The in-session model after quantize() runs on the CPU reader, which is correct but dequantizes per forward, as with GEMV since #4599. For fast inference, save and reload on the GPU.

Out of scope / not fixed

  • ROCm: no kernel reads this layout on ROCm. The quantize-time select_quant_linear(backend=AWQ_GEMV_FAST, device=DEVICE.ROCM) check rejects it before calibration (verified directly), so no calibration is lost there, but ROCm still cannot produce these formats. That needs a Triton GEMV_FAST reader and is a separate change.
  • Pre-existing on main, untouched: test_audit_covers_every_registered_kernel was already red because AwqGEMVTorchLinear (fix(awq): portable CPU GEMV reader so quantize() completes in session (#4554) #4599) is missing from the audit buckets. This PR classifies only its own two classes (as OTHER_KERNELS).

Tests

  • Unit tests have been executed and passed, or the reason they are not applicable is documented.
  • I added a new simple/fast unit test for this change, or documented why that is not applicable.

New tests in the existing #4554 family suite, tests/test_awq_gemv_insession_4554.py, parametrized over gemv_fast and llm_awq:

  • test_awq_gemv_fast_cpu_insession_kernel_is_the_documented_fallback: CPU selection returns the new reader with priority 0.
  • test_rehome_switches_native_gemv_fast_module_to_cpu_reader: a module packed by the native class is rehomed; the packed buffers stay byte-identical; the output matches an independent fake-quant oracle (its own round/clamp codes and FP16 offset, FP32 accumulate); no FP32 buffer remains after the forward.
  • test_awq_gemv_fast_quantize_save_and_reload_on_cpu: tiny Llama, quantize -> in-session forward -> save() (format kept, int16 [out/4, in] qweight) -> AUTO reload on CPU, with bit-identical logits.

Red on unmodified main @ b225a438 (new tests run against a main worktree, with the new class names stubbed):

ValueError: No valid quant linear                                  # selection
RuntimeError: Quantize: quantized layers use kernels that cannot run on the final device `cpu` (AwqGEMVFastLinear) ...
RuntimeError: ... (LLMAwqLinear) ...                               # rehome, the issue's exact error
ValueError: <class '...AwqGEMVFastLinear'> does not support device: DEVICE.CPU   # CPU-host quantize

Green on this branch (rebased on ebe5558a):

pytest tests/test_awq_gemv_insession_4554.py tests/kernels/test_kernel_compile_protocol.py
# 10/10 in-session tests pass; compile protocol: see note below

pytest tests/kernels/test_kernel_compile_protocol.py tests/kernels/test_selection.py \
  tests/module_tree/test_fusion_kernel_backends.py tests/test_awq_dequant_layouts.py \
  tests/test_awq_gemv_fast_pack_vectorized.py tests/test_awq_affine_range.py \
  tests/test_kernel_audit_regressions.py tests/test_kernel_dispatch_caching.py \
  tests/test_lazy_kernel_registry_import.py tests/test_mlx_awq_variants.py \
  tests/test_quantize_in_session_4381.py tests/test_rehome_cpu_fallback_pairs.py \
  tests/test_checkpoint_modules.py tests/test_hf_packing_api.py \
  tests/test_rocm_kernel_contracts.py tests/test_awq_gemv_insession_4554.py
# branch: 88 failed / 842 passed; upstream main: 88 failed / 822 passed
# identical failure set (environment-only, see below); 0 new failures

ruff check gptqmodel docs/eora tests setup.py   # ruff 0.14.2: All checks passed!

Compile level evidence: torch.compile(module, fullgraph=True, backend=...) on both readers (CPU, torch 2.15.0+cpu) gives eager OK and aot_eager OK, both bit-identical to the eager forward. Inductor was not measured (no host C++ compiler), so the declaration stops at AOT_EAGER.

Environment and limits, please read:

  • Validated on CPU only: Windows, Python 3.14, torch 2.15.0+cpu. pypcre has no Windows wheel and fcntl is POSIX-only, so local test shims for both were used outside the repo. The 88 shared failures are Triton/CUDA-unavailable tests, plus test_docs_matrix_matches_the_declarations, whose only diff here is the ParoTritonLinear row, unregistered without Triton.

  • Not run:

    • tests/test_awq_gemv_fast.py::test_awq_gemv_fast_quantized_model_loads_and_generates
    • tests/test_awq_llm_awq.py::test_llm_awq_checkpoint_loads_with_gemv_fast_backend_and_generates

    They need CUDA and the /monster/data model and dataset. The step they failed on (the rehome) is covered above, and their CUDA reload/generate path is not modified. Could a maintainer run these two on CUDA?

  • ROCm: not run (see Out of scope).

Model Support / Module Plan

Not applicable: no model, alias or definition change.

AWQ onboarding safety

Not applicable: no model onboarding or AWQ grouping/search/replay/fold change. Only the runtime reader of an existing checkpoint layout and the pack-backend choice for a CPU host.

Logic Flow Documentation

  • This change does not alter a major logic flow, or the required diagrams and docs page are included below.
  • New-flow Mermaid diagram(s) describe the shipped code using real symbol names.
  • The removed/replaced mechanism is shown or tabulated with file:line evidence.
  • Failure and ambiguity paths are marked and visually distinct from success.
  • A reference page under docs/ repeats the diagrams, titled for the mechanism, and is linked from README.md.

Diagram summary: docs/in-session-model-after-offload.md ("AWQ CPU readers for the GEMV layouts", already linked from README.md) shows rehome_quantized_kernel -> select_in_session_quant_linear -> AUTO CPU kernel, else PORTABLE_CPU_FALLBACK reader (GEMV / GEMV_FAST / LLM_AWQ), else the RuntimeError path. It includes a before/after table per format.

flowchart TD
    A["quantize() finishes<br/>packed AWQ layers on cpu"] --> B["rehome_quantized_kernel"]
    B --> C["select_in_session_quant_linear(qcfg, cpu)"]
    C --> D{"AUTO CPU kernel<br/>for the format?"}
    D -- "GEMM" --> E["AwqTorchLinear"]
    D -- "no" --> F{"PORTABLE_CPU_FALLBACK<br/>reader for the format?"}
    F -- "GEMV" --> G["AwqGEMVTorchLinear (#4554)"]
    F -- "GEMV_FAST" --> H["AwqGEMVFastTorchLinear (new)"]
    F -- "LLM_AWQ" --> I["LLMAwqTorchLinear (new)"]
    F -- "none" --> X["RuntimeError: reload guidance"]
    E & G & H & I --> S["_switch_quant_linear_class<br/>packed buffers unchanged"]
    S --> T["in-session forward, save(), AUTO reload on cpu"]
    style X fill:#f8d7da,stroke:#b02a37,stroke-width:2px
Loading

Review Requirements

I or an AI agent (such as Codex or Claude) have:

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

  • For kernel-related changes, accuracy drift was measured against an applicable independent Torch FP32/FP64 oracle, or the reason this is not applicable is documented.
  • Fusion support changes preserve AUTO's native class and add actual-device FP16/BF16 tests where supported, native shape/workspace/descriptor checks, mutation, direct source calls, exact restoration and packed-storage checks. (Not applicable: no fusion change; the new classes are not registered in fusion_kernels.kernel_specs(), same as AwqGEMVTorchLinear.)
  • The complete kernel inventory/device report lists unavailable dependencies, architecture restrictions and unqualified formats; skips are not validation. (Partial: CPU only. CUDA/ROCm unavailable here; see Tests.)

Oracle: the output was compared against an independent FP32 fake-quant reference within rtol=1e-3, atol=1e-2, FP16 output, FP32 accumulation.

Notes

@Qubitium

Copy link
Copy Markdown
Collaborator

@n-o-t-mugen Thank you for your first PR. Checking. Will merge soon.

n-o-t-mugen and others added 2 commits November 17, 2026 14:16
…odelCloud#4736)

quantize(format=GEMV_FAST / LLM_AWQ) packs every layer and leaves it on CPU,
but the only kernels for that interleaved layout are CUDA-only.
rehome_quantized_kernel() therefore raised "No valid quant linear" ->
RuntimeError after the whole calibration, before save() could run. ModelCloud#4599
fixed only FORMAT.GEMV.

Add AwqGEMVFastTorchLinear and LLMAwqTorchLinear, portable CPU readers of the
same packed INT16 qweight and FP16 scales/offset buffers. They reuse the
existing _dequantize_awq_gemv_fast layout inverse as a bounded per-forward
temporary. They are explicit-only (SUPPORTS_FORMATS priority 0), so the
accelerator AUTO order does not change, and select_quant_linear() reaches them
for a CPU target through PORTABLE_CPU_FALLBACK. LLMAwqTorchLinear stays an
LLMAwqLinear so layout-keyed consumers keep routing it as LLM_AWQ. A CPU-only
quantize host now packs these formats with BACKEND.AWQ_TORCH instead of
refusing before calibration.

The saved checkpoint keeps the requested format and its interleaved packing,
and AUTO reload on CPU selects the same reader.
The rebase onto main brings the new `AwqGEMVTorchLinear` CPU reader, which
main registers in `KERNELS`. This PR already owns the `OTHER_KERNELS`
inventory, so add it there; without it
`test_audit_covers_every_registered_kernel` reports the kernel as
unclassified (it fails the same way on unmodified main).
@Qubitium
Qubitium force-pushed the fix/4736-awq-gemv-fast-cpu-insession branch from b8ffb62 to 9534238 Compare November 17, 2026 14:19
@Qubitium
Qubitium merged commit a55bca3 into ModelCloud:main Nov 17, 2026
4 checks passed

@Qubitium Qubitium left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

Reviewed the diff and ran it on Linux aarch64 (torch 2.11.0+cu130, 1x GB10 sm_121) with the model present in the CPU reader path.

Verified

  • tests/test_awq_gemv_insession_4554.py: 10/10 pass both with CUDA_VISIBLE_DEVICES="" and with the GB10 visible.
  • The reader reuses the already-tested _dequantize_awq_gemv_fast layout inverse, so the packed qweight / scales / zero-offset contract is unchanged. The rehome test proves the buffers stay byte-identical and the output matches an independent fake-quant oracle.
  • quantize() -> save() -> AUTO reload on CPU keeps the requested gemv_fast / llm_awq format and the INT16 [out/4, in] layout.
  • Accelerator AUTO order is untouched: priority-0 SUPPORTS_FORMATS plus SUPPORTS_DEVICES=[CPU] and PORTABLE_CPU_FALLBACK.
  • docs/kernel-compile-matrix.md matches the declarations (test_docs_matrix_matches_the_declarations passes).
  • Rebased head (9534238d) includes the AwqGEMVTorchLinear ROCm-audit classification, so test_audit_covers_every_registered_kernel is green again.

One gap left (not blocking this PR, follow-up lands it)

tests/module_tree/test_fusion_kernel_backends.py::test_every_registered_gptq_awq_kernel_has_an_explicit_fusion_contract
fails on this branch: the two new classes are registered kernels but are in neither kernel_specs() nor the EXCLUDED
inventory. That assertion was already red on main for AwqGEMVTorchLinear (#4599 left it out), so this PR adds two
more names to an already-failing assertion rather than introducing a new failure class.

I had prepared the fix locally (inventory entries with reasons + measured AOT_EAGER cases for both readers in
tests/kernels/test_kernel_compile_levels_awq.py, which pin the declaration the way #4737 requires), but
"Allow edits by maintainers" is currently off on this PR, so I could not push it. I will land it as an immediate
follow-up PR against main together with the AwqGEMVTorchLinear entry, which also clears the pre-existing red test.

Notes

  • SUPPORTS_DTYPES = [torch.float16] mirrors the native kernels, but the forward already works for BF16/FP32 inputs
    (it casts to FP32 and back). Widening that declaration needs its own dtype tests; not done here.
  • docs/support-matrix.md's METHOD.AWQ CPU row still lists only FORMAT.GEMM; it was already incomplete after #4599
    and that row documents the AVX512 backend, not the portable readers.
  • The two CUDA model-generation tests (test_awq_gemv_fast.py, test_awq_llm_awq.py) could not run here:
    /monster/data/model/Llama-3.2-1B and the C4 calibration file are not present on this host.

Test runs

  • tests/test_awq_gemv_insession_4554.py: 10 passed (CPU-only and GPU).
  • tests/test_rocm_kernel_contracts.py + tests/module_tree/test_fusion_kernel_backends.py: 512 passed, 161 skipped
    once the inventory follow-up is applied; without it, only the fusion inventory assertion fails (see above).
  • Broader AWQ suite failure set is identical to unmodified main (AVX512 kernels on this aarch64 host, QQQ group
    scales) - no new failures.

Merging now; the follow-up PR will close the inventory gap.

@Qubitium

Copy link
Copy Markdown
Collaborator

Reviewed and verified on GB10 + CPU-only; posting the review as a review comment (it did not attach to the discussion). Merging now, with the fusion-inventory follow-up landing immediately after.

ZX-ModelCloud added a commit that referenced this pull request Nov 18, 2026
)

#4753 gave FORMAT.GEMV_FAST and FORMAT.LLM_AWQ portable Torch readers, but only
for a CPU-only host: on ROCm every path refused before calibration. AUTO raised
"No valid quant linear", BACKEND.AWQ_TORCH rejected DEVICE.ROCM ("only supports
cpu"), and BACKEND.AWQ_GEMV_TRITON does not declare either format, so the
documented format/platform combination could not be produced at all.

Resolve the pack backend from the device family: awq_gemv_fast_pack_backend()
returns BACKEND.AWQ_GEMV_FAST on NVIDIA and BACKEND.AWQ_TORCH wherever the
extension cannot build (CPU, ROCm). Both portable readers now declare
DEVICE.CPU/CUDA/ROCM and are reached by the per-family portable fallback in
select_quant_linear, which is now keyed on the target families instead of
"CPU only" (PORTABLE_FALLBACK; the GEMV reader keeps its CPU-only declaration).

The readers move the packed words to the input device inside forward() rather
than rewriting module state, so an AUTO reload of a saved checkpoint works on
ROCm without an explicit backend and keeps only packed INT16/FP16 storage. An
AUTO CUDA load still selects the native kernel, and the GEMV-on-ROCm refusal
now names only FORMAT.GEMV and the readers that do apply.

Fixes #5109
Qubitium pushed a commit that referenced this pull request Nov 18, 2026
) (#5176)

#4753 gave FORMAT.GEMV_FAST and FORMAT.LLM_AWQ portable Torch readers, but only
for a CPU-only host: on ROCm every path refused before calibration. AUTO raised
"No valid quant linear", BACKEND.AWQ_TORCH rejected DEVICE.ROCM ("only supports
cpu"), and BACKEND.AWQ_GEMV_TRITON does not declare either format, so the
documented format/platform combination could not be produced at all.

Resolve the pack backend from the device family: awq_gemv_fast_pack_backend()
returns BACKEND.AWQ_GEMV_FAST on NVIDIA and BACKEND.AWQ_TORCH wherever the
extension cannot build (CPU, ROCm). Both portable readers now declare
DEVICE.CPU/CUDA/ROCM and are reached by the per-family portable fallback in
select_quant_linear, which is now keyed on the target families instead of
"CPU only" (PORTABLE_FALLBACK; the GEMV reader keeps its CPU-only declaration).

The readers move the packed words to the input device inside forward() rather
than rewriting module state, so an AUTO reload of a saved checkpoint works on
ROCm without an explicit backend and keeps only packed INT16/FP16 storage. An
AUTO CUDA load still selects the native kernel, and the GEMV-on-ROCm refusal
now names only FORMAT.GEMV and the readers that do apply.

Fixes #5109
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants