Skip to content

[BUG] Follow-up on #4071/#4082/#4083/#4085: AWQ batch_size>1 crash (regression), CPU AUTO kernels corrupt state_dict (inf/NaN), v1<->v2 state_dict copy, PEFT on Marlin, HF random weights for exl3/gguf, MLX batched generate #4091

Closed

Description

@Qubitium

Regression and completeness review of the fix PRs #4071, #4082, #4083 and #4085 on main @ a15e6bf (CUDA RTX 4090 and CPU; MLX export checked with mlx-cpu). Before/after comparisons use git archive trees of each PR's parent commit.

1. #4071 regression: AWQ with batch_size>1 crashes (high)

The new token_rows default (#4071) sends batched captures into the chunked reference replay without the attention mask:

model.quantize(c4_texts, batch_size=4)   # Qwen2.5-0.5B-Instruct, AWQ 4-bit g128
  awq_processor.py:2069 _search_best_scale -> :2506 _build_chunked_reference_outputs -> :3043 _iter_prepared_forward_outputs
  TypeError: Qwen2Attention.forward() missing 1 required positional argument: 'attention_mask'
39b6276^ (before #4071): OK      batch_size=1: OK

Fix: when rows are re-chunked, carry the per-row attention mask (and the matching position ids and cache kwargs) along. Add a test with batch_size>1 to tests/test_awq_variable_length_ppl.py.

2. #4085 / #4061 incomplete: CPU AUTO kernels produce a corrupt state_dict(); load_state_dict(state_dict()) gives inf/NaN (high, silent)

TorchAtenLinear (the CPU AUTO kernel for fp16) and TorchFusedLinear (bf16) replace qweight/qzeros with int4pack words and float affine offsets in transform_cpu (qlinear/torch_fused.py:394-422). Then:

  • state_dict() serializes these runtime buffers.
  • checkpoint_layout_qzeros (qlinear/__init__.py:1275-1320) applies the integer v2→v1 revert to the float offsets, which gives inf or 65536.
  • _load_from_state_dict (:1325-1356) converts them again on the way back.

Unlike Marlin and ExLlamaV2, these kernels don't raise.

Llama-3.2-1B-Instruct-GPTQ-4bits-gp128 (v1), CPU:
  AUTO -> TorchAten fp16: state_dict qzeros dtype float16, qzeros[0] [inf, inf, inf]; after load_state_dict: layer maxdiff inf
  GPTQ_TORCH_FUSED bf16:  qzeros[0] [65536.0, ...];                                   layer maxdiff 290816.0
  full model round trip: TorchAten sym v1 -> logits NaN, ' Berlin' -> '!'; TorchFused bf16 sym/asym v1 -> maxdiff ~26, ' Berlin' -> ' clock'
  (AVX512, AWQ fused/aten and v2 checkpoints round-trip exactly)

v1 checkpoints are the common case, so on CPU this breaks torch.save(model.state_dict()) restores, Trainer/accelerate checkpoints, and save_pretrained through state_dict. The tree before #4085 is broken too.

Fix: while a module is transformed, have _save_to_state_dict emit the checkpoint-layout snapshot (the fused training path already captures one, capture_fused_train_state). On load, restore the checkpoint layout and re-transform, or raise as Marlin does. tests/test_checkpoint_interop_4053.py only covers Torch and Triton.

3. #4085 regression: copying a state_dict between models loaded from v1 and v2 checkpoints corrupts the target (medium)

_load_from_state_dict (qlinear/__init__.py:1339-1352) assumes the incoming words use the target's _checkpoint_format_on_disk. Nothing in the state_dict records the source's layout.

A = Llama-3.2-1B-Instruct-GPTQ-4bits-gp128 (v1), B = Llama-3.2-1B-Instruct HF-GPTQ v2, GPTQ_TORCH
A.load_state_dict(B.state_dict()): maxdiff 25.6, next token ' discipline' (B: ' Berlin')   | before #4085: 0.19, ' Berlin'
B.load_state_dict(A.state_dict()): maxdiff 26.7, 'imid'                                     | before #4085: same (already broken)

Fix: record the layout in the state_dict, e.g. get_extra_state/set_extra_state or a small qzeros_format buffer, and convert based on the source's format.

4. PEFT adapters can't be loaded or saved on the default CUDA kernel (Marlin) (medium; origin #4061, not handled by #4085's PEFT path)

_save_to_state_dict raises unconditionally in qlinear/marlin.py:480, marlin_awq.py:359 and exllamav2.py:189. PEFT 0.21 set_peft_model_state_dict calls model.state_dict() (peft/utils/save_and_load.py:963), so even loading an adapter fails:

adapter trained/saved on GPTQ_TORCH, PeftModel.from_pretrained(<MARLIN base>) -> RuntimeError: Marlin rewrites qweight ...
PeftModel(<MARLIN base>).save_pretrained(...)                                  -> RuntimeError
same on GPTQ_TORCH -> OK, maxdiff 0.0

The raise is documented (docs/checkpoint-interop.md §3), but breaking adapter loading is not. Fix: raise only in the GPTQModel and HF serialization paths, and let read-only state_dict() callers get the runtime tensors (or the snapshot).

5. #4085 incomplete: transformers still loads random weights for other GPTQModel-only methods, and for GGUF when gptqmodel isn't imported (medium)

gptqmodel/__init__.py:131-158 registers a refusing quantizer only for gptqmodel_gguf, and only once import gptqmodel has run:

gptqmodel imported:   AutoModelForCausalLM.from_pretrained(Llama-3.2-1B-Instruct-EXL3-W4-ALL) -> "Unknown quantization type, got exl3 ... skip the quantization" + MISSING table -> random Linear weights
plain transformers:   from_pretrained(<gptqmodel_gguf ckpt>) -> "Unknown quantization type, got gptqmodel_gguf" -> loads, next token '一面' (random weights)
with the import:      ValueError (as intended)

docs/checkpoint-interop.md:361 says plain HF raises ValueError. The same applies, by inspection, to the other methods in _UNAMBIGUOUS_EXPORT_METHOD_BY_FORMAT that HF doesn't know: qqq, nf12, tt_blockfloat. MACaQ is in #4090.

Fix: register refusers for every GPTQModel-only quant_method. Also add a save-time hf_compat_warnings entry, and document that plain transformers only warns.

6. #4085 incomplete: pickling after optimize() still fails for FP8 and EXL3 Torch (low)

qlinear/fp8.py:686 and exllamav3_torch.py:590 store a compiled bound method in self._compiled_forward; vptq_torch.py:300 does the same per inspection.

FP8_TORCH  (Qwen2.5-0.5B fp8, cpu, optimize()) -> torch.save: PicklingError: Can't pickle <function TorchFP8Linear._forward_dequant_matmul>
EXL3_TORCH (Llama-3.2-1B EXL3, cpu, optimize()) -> PicklingError ... ExllamaV3TorchLinear._forward_eager

TorchLinear, TritonV2, Marlin, AWQ, GGUF and the CPU fused kernels pickle fine, and deepcopy works.

Fix: add a __getstate__ on BaseQuantLinear that drops _compiled_forward and resets optimized.

7. #4082 regression: a CPU-only max_memory with device="cuda:0" selects a CUDA kernel, places every layer on CPU, and forward crashes (low-medium)

models/loader.py:755-776 (_normalize_explicit_placement) and :2626-2635:

GPTQModel.load(Llama-3.2-1B-GPTQ, device="cuda:0", max_memory={"cpu": "10GiB"})
  placement {'cpu': '985MiB'}, kernel TritonV2Linear -> forward: ValueError: Expected a cuda device, but got: cpu
before #4082: placement {'cuda:0': '985MiB'}, forward OK

max_memory={"cpu": ...} with no device, or with device="cuda", crashes the same way both before and after.

Fix: if the budget names no accelerator, select kernels for CPU, or reject the combination.

8. #4083: MLX generate() with batched, left-padded input_ids treats the pad tokens as prompt tokens (medium for Apple users)

utils/mlx.py:525 (_mlx_prompt_list) and :674 ignore attention_mask, so pad ids become part of each prompt. Other unused kwargs are dropped silently.

generate(**tok(prompts, padding=True))  -> row 0: 'extrasextras...'
same prompt alone                        -> 'RandRand...'    (match: False)

Fix: strip the pad positions per row using attention_mask (or pad_token_id) before calling mlx_lm.

9. #4083: an eos_token_id passed to one MLX call sticks to the shared tokenizer for all later calls (low)

utils/mlx.py:562-574 does tokenizer.eos_token_ids = set(current) | ids on the wrapper bound in functools.partial:

call1 'Hi'                         -> 'RandRand뎀뎀뎀뎀等待等待'
call2 'Hi', eos_token_id=145456
call3 'Hi' (no eos argument)       -> 'RandRand'   (truncated by call2's EOS)

Fix: use a per-call copy, or restore the set in a finally.

10. #4083: MLX export on Linux now writes a layout that stock mlx_lm.load rejects (low-medium)

utils/mlx.py:184-185 routes every TorchLinear to gptq_dtype, which leads to the *.linear.* key prefix at :229. This happens because _validate_source(check_platform=False) enables the packed transfer on Linux.

export of an asym RTN checkpoint -> mlx_lm.load(out): ValueError: Received 576 parameters not in model: model.layers.0.mlp.down_proj.linear.biases ...
same export before #4083 -> loads in stock mlx_lm, generates 'Paris. The capital of the'

The transfer itself is now accurate (relative error 0.0013–0.0017, dynamic overrides and -: exclusions honored). docs/mlx-runtime.md says the checkpoint needs the custom runtime, but stock mlx_lm users on Linux lost a working path. Fix: keep a stock-compatible export by default, or as an option, or fail early with a clear message.

Checked, no defect found

Plausible, not verified

  • device_map="balanced" with max_memory behaves like sequential. With Llama-1B and {0: 500MiB, 1: 3GiB}, everything goes to cuda:1, because the 525 MB embedding moves the greedy cursor past device 0.
  • AVX512's state_dict() emits qzeros 247, which isn't a v1 word. The round trip is exact, but a raw save_pretrained file is likely non-standard.
  • Dependency: tokenicer 0.0.14 calls os.environ.setdefault("HF_HOME", "/tmp/tokenicer_hf_home") at import gptqmodel, so child processes inherit an unexpected HF cache location.

🤖 Generated with Claude Code

Activity

  1. added
    bug
    on Nov 15, 2026
  2. Qubitium commented on Nov 15, 2026

    @Qubitium
    CollaboratorAuthor

    All ten items are now on main, in three parts:

    The item-1 root cause is worth recording: _pack_token_rows set feature_kwargs[name] = {}, so the processor-wide [B,1,S,S] mask could not be aligned to the packed rows and _align_module_kwargs_to_input silently dropped attention_mask/position_ids; _iter_prepared_forward_outputs then called attention without its required mask. The fix carries provenance out of _pack_token_rows and rebuilds a per-document block-diagonal additive mask plus the original position_ids, keeping 2-D captured masks (FlashAttention) 2-D.

    For items 2-4, state_dict() is now a real checkpoint for every kernel: qzeros are emitted in the recorded on-disk layout, qzeros_format is self-describing in the state-dict metadata, and _load_from_state_dict converts from the source's recorded layout — which is what makes the v1↔v2 copy exact (A←B maxdiff 0.2509→0.0, B←A 0.1298→0.0) and stops CPU AUTO kernels serializing inf/NaN.

    Two honest notes rather than silent gaps:

    • The AWQ-vs-RTN sweep shows a 2.27 PPL regression on the gemma-3-1b symmetric cell versus the previous synthetic cross-document replay (still 7.8 PPL better than RTN). That is the cost of replacing synthetic cross-document causal replay with correct per-document replay; it was not tuned away.
    • A 2-D captured mask (FlashAttention) keeps its 2-D form, so cross-document separation is not expressible there. Documented in docs/awq-calibration-aggregation.md.

    Closing as resolved.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions