Skip to content

fix: restore base modules and re-pick CPU kernels after weight-only quantize (#4381) - #4426

Merged
Qubitium merged 8 commits into
mainfrom
pr/4381
Nov 16, 2026
Merged

Qubitium merged 8 commits into
mainfrom
pr/4381

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Weight-only methods (FP8/GGUF) load the model as a checkpoint-backed meta shell. embed_tokens, norm and rotary_emb are already on meta before the offload step, so capture_offloaded_base_modules records nothing for them, _restore_offloaded_base_modules is a no-op, and quantize() returns a model that cannot run in-session. Separately, AWQ GEMM / QQQ / GGUF select a CUDA-only packing kernel from quantize_config.device; post_quantize then leaves the packed layers on CPU, so the first in-session forward fails on the CPU backend.

What Changed

  • WeightOnlyLooper now materializes meta base modules from the lazy-turtle checkpoint after the loop (skipping packed modules), or raises the actionable "reload the saved checkpoint" error when materialization is impossible.
  • Added rehome_quantized_kernel() in BaseQModel.quantize(): after after_quantize() it inspects the device the packed layers actually live on, selects a kernel for that device (select_in_session_quant_linear), and reinterprets layout-compatible CUDA-only modules (AWQ GEMM -> AwqTorchLinear, QQQ -> QQQTorchLinear, GGUF Triton -> GGUFTorchLinear). If no portable kernel exists (for example AWQ GEMV on CPU), it raises the reload-the-checkpoint guidance instead of returning a broken model.
  • Updated the GGUF post-quantize kernel expectations in tests/test_weight_only.py, since the in-session model now ends on the portable Torch kernel.
  • New regression tests in tests/test_quantize_in_session_4381.py.

Tests

$ export GPTQ_BYPASS_SAFETY_CHECKS=1 PYTHONPATH=$PWD CUDA_VISIBLE_DEVICES=
$ python3 -m pytest tests/test_offload_autograd.py tests/test_offload_base_modules_restored.py \
    tests/test_offload_files.py tests/test_offload_run_cleanup_4368.py tests/test_offload_run_namespace.py \
    tests/test_kernel_config.py tests/test_quantize_in_session_4381.py -q
137 passed, 4 skipped

$ python3 -m pytest tests/test_weight_only_looper.py -q
2 failed, 18 passed
# Both failures are pre-existing on origin/main (verified in a clean worktree):
#   test_weight_only_looper_quantizes_input_and_lm_head_embeddings_only
#   test_weight_only_looper_respects_dense_and_moe_vram_strategy_devices

$ python3 -m pytest tests/test_weight_only.py -q
1 failed, 42 passed, 44 skipped
# Pre-existing failure on origin/main:
#   test_gguf_forward_requests_dequantized_weight_in_input_dtype

$ ruff check gptqmodel/looper/weight_only_looper.py gptqmodel/models/base.py \
    tests/test_quantize_in_session_4381.py tests/test_weight_only.py
All checks passed!

Not runnable here: the CUDA C++ extensions (AWQ GEMM, QQQ, GGUF Triton) are not built in this CPU-only container and cannot be built here. The kernel re-home is covered with CPU-only unit tests that mock the CUDA-only candidates as unavailable; the meta-base-module path is covered with a tiny locally-built Llama meta shell and a stub turtle materializer. The GPU end-to-end repro was not executed.

Model Support / Module Plan

N/A — no new model types or registry entries.

Fixes #4381

Comment thread tests/test_quantize_in_session_4381.py Resolved
…ns (#4372) (#4427)

LongCat-Flash interleaves attn0 -> mlps0 -> attn1 -> mlps1, but the tree
emitted both attention sub-blocks before both MLPs. Its MLA q_a/kv_a and
q_b/kv_b also shared a subset. Restructure the layer declaration into
per-sub-block entries so the emitted subsets follow the forward order, and
split the MLA stages.

Also move the attention output projection after its producers in
kimi_linear, nemotron_h (including the Nemotron Omni copy), bailing_moe,
and deepseek_vl_v2, and give lfm2_moe's conv in_proj/out_proj distinct
subsets.

Add static subset-order assertions and a generic tiny-model data-flow
probe that perturbs each declared Linear and requires every consumer to be
in a later subset. Update the registered module-plan fixture, the bailing
shared-expert plan test, and teach _tiny_config about lfm2_moe layer types.
Add lfm2_moe to the AWQ fold-preservation families.
)

AWQ FORMAT.GEMV/GEMV_FAST/LLM_AWQ kernels declare SUPPORTS_DTYPES=[fp16], but the quantize path loaded a bf16 shell model and only failed in layer-0 finalize after the AWQ search had run. Extend _coerce_quantized_awq_dtype to the quantize path and teach it that AUTO selects fp16-only kernels for those layouts: auto-selected dtypes are fixed to fp16 (logged, whole model) while an explicit unsupported dtype raises a ValueError naming the conflict and both fixes. Apply the same explicit-dtype contract to checkpoint loads.
* fix(gguf): serialize ggml-cuda entry process-wide (#4378)

`_GGMLBridge.cuda_backend_lock` handed out one lock per CUDA device, so forwards on cuda:0 and cuda:1 could be inside ggml-cuda at the same time. ggml-cuda shares cuBLAS handles and memory pools across devices; on 2x RTX 4090 with PYTHON_GIL=0, 4 threads x 200 forwards aborted 5 of 20 runs in cublasGemmEx.

Return one re-entrant process-wide lock from `cuda_backend_lock`. The per-device backend-handle map is unchanged, and single-thread latency is unchanged because a forward already took one lock.

Add CPU-runnable regression tests that assert both devices share one lock and that cross-device forwards never overlap inside the backend critical section. They fail on the pre-fix code (max_active == 2).

Update the GIL=0 ledger with the concurrency contract change.

* test(gguf): give the plan-weight fake the process-wide backend lock

The kernel takes the bridge's cuda_backend_lock for every ggml-cuda entry,
but _FakeBridge predated that contract and had no such method, so
test_kernel_builds_the_weight_once_for_many_batch_sizes failed whenever a
CUDA device was visible. Expose the lock from the fake.

* test(gguf): collect worker failures as Exception, not BaseException

Code Quality flagged the two worker-thread handlers. They still re-raise the
collected failure in the main thread; narrowing the catch keeps
KeyboardInterrupt/SystemExit out of the collected list.
Code Quality flagged the test for importing the module both as an alias and
with from-import. The two monkeypatches now target the module path by string,
which still rebinds the global that rehome_quantized_kernel looks up.
@Qubitium
Qubitium merged commit 1b48454 into main Nov 16, 2026
8 checks passed
@Qubitium
Qubitium deleted the pr/4381 branch November 16, 2026 14:04
Qubitium added a commit that referenced this pull request Nov 17, 2026
…4846)

Section A of #4769, each item fixed at its test double/oracle/expectation.
No library behaviour was changed.

Fixed:
- test_exl3_workspace_release / test_offload_base_modules_restored: give the
  ModuleLooper doubles the state loop() now reads (_inflight_layer,
  _dangling_threads, Device-SMI handles, and a real model for the success
  path). Before: AttributeError while handling the injected failure; after:
  7 passed.
- test_local_model_paths: the fake loaded models are SimpleNamespace doubles
  with log_kv_cache_estimate, matching GPTQModel.load. Before: AttributeError
  on a bare object(); after: 29 passed.
- test_diffusion_gemma_support: the hand-built DiffusionGemmaQModel double now
  carries quantize_config.activation_mode. Before: AttributeError; after: the
  post-quantize sync test passes.
- test_tenstorrent_support: window starts follow the current
  iter_calibration_windows spacing (0, 18, 37, 56). Before: the stale
  [0, 14, 28, 42] oracle.
- test_model::test_dequantize_model_awq: the fixture packs the real AWQ GEMM
  [0, 2, 4, 6, 1, 3, 5, 7] interleave instead of natural order, which is what
  dequantize_model reverses. Before: 95/128 elements differed.
- test_fallback: the sym=True oracle uses zero = 2 ** (bits - 1) for every
  strategy, not an asymmetric zero point. Before: 32/32 zero mismatches.
- test_gsq_method_adapters: FP8 pack_calibrated keeps the checkpoint bias in
  FP32 on purpose; assert that dtype and value instead of FP16.
- test_serialization: offload_to_disk_path is deliberately absent from the
  checkpoint meta (#4327); assert its absence instead of its presence.
- test_norm_lifecycle: quantize() now materializes the model and keeps the v2
  runtime zero layout (#4380/#4426/#4063); assert no meta/inference parameters
  and validate_tuning_model(model.model) instead of the stale reload-only
  guard.
- test_vptq_memory_4391: the legacy reference allocates >= 2 full-size
  temporaries on torch 2.15, not exactly 3; pin that it is worse than the
  chunked path instead of an exact torch-version-dependent count.
- test_jamba_support: the module tree declares mamba.x_proj (#4245); update
  the simple list and the dense-mixer assertions.
- test_marlin_jit: with desc_act=False and one group, g_idx is all zeros, not
  arange(in_features).
- test_dynamic::test_skip_module: replace brittle paris/king keyword matching
  on greedy output with a coherence check on the continuation.
- test_allspark_awq_cuda: install the checkpoint tensors as buffers, as a real
  load does, instead of Parameters that _kernel_bias caches as a second
  parameter (which leaked _bias_value into state_dict).
- test_bits_new: select the bit width with parameterized.expand([2, 3, 4, 8])
  instead of the BITS environment variable (AGENTS.md: behaviour comes from
  config/API, not env).
- test_checkpoint_method_compatibility: use group_size=128 for the native AWQ
  GEMV/LLM-AWQ formats (GEMV accepts 64/128, LLM-AWQ only 128) and widen the
  fixture to hidden_size=128 for LLM-AWQ, whose in_features must divide 128.
  Gate the ~30-minute subprocess matrix behind the new opt-in
  checkpoint_recovery marker (same mechanism as gptq_cuda_e2e) so the file no
  longer always times out in a 600 s slot. Target cases
  test_format_checkpoint_recovery[awq-gemv], [awq-llm-awq] and both eora
  variants pass with -m checkpoint_recovery.

Skipped because this host is CUDA sm_80, not ROCm:
- every ROCm/gfx1201-only item belongs to #4770 and was not touched.

Deferred:
- tests/test_quant_batch.py::test_diff_batch: an FP32-calibration +
  dequantized-weight rewrite OOMs here (GPU 5 has ~14 GiB free while a shared
  83 GiB process holds the card), so it was not shipped unverified.
- test_bits_new was exercised for bits=2 against a 15M local model only; the
  1B eval of the other widths does not fit the 600 s slot here.

Environment-only failures seen while validating (not changed):
- test_serialization.py::test_gptq_v1_serialization and
  test_save_keeps_live_model_inference: flash_attn_2_cuda undefined symbol.
- test_diffusion_gemma_support.py::test_diffusion_gemma_generic_defusion_preserves_forward:
  defuser 0.0.25 is older than the required 0.0.31.
- test_jamba_support.py::test_tiny_jamba_gptq_quantization_smoke: mamba-ssm is
  not installed.

Validation (CUDA_VISIBLE_DEVICES=5, sm_80):
- 13 touched files in one run: 380 passed, 110 skipped, 4 failed (the three
  environment-only causes above).
- test_model.py -k dequantize_model: 12 passed, 1 skipped.
- test_marlin_jit.py::test_marlin_cuda_smoke_build_and_forward: 1 passed.
- test_dynamic.py::TestDynamic::test_skip_module: 1 passed (flash-attn
  auto-enable disabled locally because the host extension has an undefined
  symbol; the committed test still hits that environment failure).
- test_checkpoint_method_compatibility.py default: 4 passed, 95 skipped;
  -m checkpoint_recovery targeted AWQ GEMV/LLM-AWQ cases: 4 passed.
- test_bits_new.py::Test::test_quant_and_eora_0 (bits=2, 15M model): 1 passed.
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