Skip to content

fix(models): honor third-party checkpoint interop in save, Marlin, and export (#4053) - #4059

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4053-marlin
Nov 14, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4053-marlin

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Part of #4053

This is the second half of #4053: items 4-8 and the Minor list. Items 1-3 are covered by the sibling PR.

TL;DR

Five interop paths now trust the checkpoint instead of a runtime default: save() keeps the caller's live model, Marlin decodes a non-contiguous g_idx, is_marlin_format: false is accepted, export(..., "hf") routes through the checkpoint dequantizer, and GPTQ dequantization resolves per-module dynamic bits. 12 files, +~250/-~45, plus 4 new test files and docs/checkpoint-interop.md.

1. Root causes and fixes

Item Root cause (before) Fix
4 models/writer.py:2027 assigned the save shell to self.model, leaving a CPU TorchCpuAvx512Linear model behind after save(). Build the shell in a local model_for_save (models/writer.py:2029) and use it for every save step; self.model is untouched.
5 nn_modules/qlinear/marlin.py:413 replaced g_idx with an empty tensor whenever desc_act=False, ignoring a block-permuted stored index. _g_idx_is_contiguous() (marlin.py:65) detects the mismatch in post_init (marlin.py:374); the module switches to marlin_sort_g_idx + repack, or fails closed on misaligned shapes.
6 quantization/config.py:4045 / :4633 raised for any is_marlin_format value. _is_truthy_compat_flag() (config.py:4126) accepts false/"false" silently; only true raises (config.py:4092, :4751).
7 models/auto.py:1101 dequantized the runtime model with nn_modules/qlinear/torch.dequantize_model, which accepts only TorchLinear, turns quantized embeddings into nn.Linear, and hard-codes fp16. Legacy quantize_config.json-only checkpoints failed earlier at auto.py:1058. format="hf" goes straight to utils/model_dequant.dequantize_model (auto.py:1068); that path handles AWQ, GPTQ, embeddings, and merges legacy quantize_config.json (model_dequant.py:1975). Auxiliary .cache/.git dirs are skipped (model_dequant.py:1939).
8 utils/model_dequant.py:1815 used the global bits for every GPTQ module. _gptq_module_int() (model_dequant.py:1573) resolves dynamic per module; the default is normalized with quant_bits_width (model_dequant.py:1827).
Minor _LEGACY_BACKEND_BY_METHOD had no qqq/gguf/bitsandbytes entry; string bits failed inside packers; sym: null survived parsing. Added mappings (utils/backend.py:169), normalized bits in dequant, and defaulted sym=None to True (config.py:4490).

2. New flow: save keeps the live model

flowchart TD
    A["save_quantized()"] --> B{"load_quantized_model<br/>and format != EXL3?"}
    B -- no --> C["model_for_save = self.model"]
    B -- yes --> D["model_for_save = get_model_with_quantize(qcfg, model_local_path)"]
    D --> E["write config from model_for_save"]
    C --> E
    E --> F["get_state_dict_for_save(model_for_save)"]
    F --> G["write safetensors shards"]
    G --> H["self.model unchanged"]
    H --> I["caller inference keeps live kernel"]
    style D fill:#fff4cc,stroke:#b8860b
    style H fill:#d9f2d9,stroke:#2e7d32
Loading

3. New flow: Marlin g_idx

flowchart TD
    A["MarlinLinear.post_init()"] --> B{"self.desc_act?"}
    B -- yes --> F["activation-order path"]
    B -- no --> C{"_g_idx_is_contiguous(g_idx, K, group_size)?"}
    C -- yes --> D["contiguous path: empty g_idx"]
    C -- no --> E{"marlin_is_tile_aligned(N, K)?"}
    E -- no --> X["raise NotImplementedError<br/>load a non-Marlin backend"]
    E -- yes --> G["set desc_act = True<br/>is_k_full = True"]
    G --> F
    F --> H["marlin_sort_g_idx + gptq_marlin_repack"]
    style X fill:#f8d7da,stroke:#b02a37
    style G fill:#fff4cc,stroke:#b8860b
Loading

4. New flow: export

flowchart TD
    A["GPTQModel.export(model, target, format)"] --> B{"format == hf?"}
    B -- yes --> C["resolve local snapshot"]
    C --> D["dequantize_model(source, target, trust_remote_code)"]
    D --> E["config.json without quantization_config"]
    E --> F["dense safetensors + copied aux files"]
    B -- no --> G["AutoConfig + backend selection"]
    G --> H["GPTQModel.load"]
    H --> I["format == mlx: convert_gptq_to_mlx_weights"]
    style D fill:#fff4cc,stroke:#b8860b
    style F fill:#d9f2d9,stroke:#2e7d32
Loading

5. New flow: per-module GPTQ bits

flowchart TD
    A["convert_gptq_file(path, config)"] --> B["default_bits = quant_bits_width(config.bits)"]
    B --> C["for each module prefix"]
    C --> D["bits = _gptq_module_int(config, prefix, bits, default_bits)"]
    D --> E{"bits == 3?"}
    E -- yes --> F["3-bit unpack path"]
    E -- no --> G["standard unpack_rows / unpack_cols"]
    F --> H["fp64 weight reconstruction"]
    G --> H
    H --> I["finalize_for_save(target_dtype)"]
    style D fill:#fff4cc,stroke:#b8860b
Loading

The same diagrams and contracts are committed in docs/checkpoint-interop.md, linked from README.md.

6. Failure and ambiguity contract

Situation Before After
save() on a loaded Marlin checkpoint self.model becomes a CPU shell; logits rel 1.47 off (issue) self.model unchanged; new test asserts rel < 1e-3
Non-contiguous g_idx, desc_act=False index dropped, contiguous decode activation-order decode
Non-contiguous g_idx, misaligned shapes silently wrong NotImplementedError (use a non-Marlin backend)
is_marlin_format: true rejected still rejected
is_marlin_format: false rejected accepted and dropped
export("hf") on AWQ ValueError: Only models loaded using TorchLinear... dense reloadable directory
export("hf") on quantized embeddings nn.Linear shape error dense embedding weight
export("hf") with only quantize_config.json AttributeError: 'BloomConfig' object has no attribute 'quantization_config' dense reloadable directory
mixed dynamic bits wrong width or crash per-module width

7. Fail-before / pass-after

Item Fail-before evidence Pass-after evidence
4 test_save_keeps_live_model_inference failed with the CPU shell (Expected all tensors to be on the same device); issue measured rel 1.47. Test passes; live-model logits rel < 1e-3.
5 Layer-0 q_proj rel err 0.13885; whole-model Marlin vs Torch rel 0.8756, top-1 0%. Layer-0 rel err 0.00000; whole model rel 0.0674, top-1 87.5% (bf16 accumulation over 28 layers).
6 QuantizeConfig.from_quant_config(... is_marlin_format=False) raised ValueError. false accepted; gemma-1.1-2b-it-GPTQ and hugging-quants Llama-3.1-8B load with Marlin and return finite logits.
7 Bloom export: AttributeError: 'BloomConfig' object has no attribute 'quantization_config'; AWQ export: ValueError: Only models loaded using TorchLinear.... Bloom and AWQ exports reload with AutoModelForCausalLM.from_pretrained and return finite logits; synthetic 3-bit/4-bit and 4-bit/8-bit exports match the fp64 oracle at bf16 precision.
8 3-bit/4-bit: RuntimeError: The size of tensor a (64) must match ... (128); string bits: TypeError: unsupported operand type(s) for //: 'int' and 'str'. Both mixed-width cases and bits: "4" decode exactly against an fp64 oracle.
Minor normalize_backend("torch", quant_method=QQQ) returned BACKEND.TORCH. Returns QQQ_TORCH / GGUF_TORCH / BITSANDBYTES; sym: null -> True; string bits -> int.

8. Test commands and results

CUDA venv (/opt/venvs/cu130t/bin/python, CUDA_VISIBLE_DEVICES=GPU-d458708b-c760-bbf1-08fb-8b8803a2157d):

pytest tests/test_serialization.py tests/test_marlin_g_idx.py -q
  -> 9 passed
pytest tests/qcfg/test_config_dispatch.py tests/qcfg/test_config_serialization.py \
       tests/test_backend_naming.py tests/test_qzero_offsets.py \
       tests/test_awq_dequant_layouts.py tests/test_model_dequant_dynamic_bits.py \
       tests/test_model_dequant_fp8.py tests/test_export.py -q \
       -k "not ignored_layers_are_honored_by_non_fp8_converters"
  -> 139 passed, 1 skipped, 1 deselected
ruff check gptqmodel docs/eora tests setup.py
  -> All checks passed!

ROCm venv (/opt/venvs/rocm101t/bin/python, HIP_VISIBLE_DEVICES=2):

pytest tests/test_model_dequant_dynamic_bits.py tests/qcfg/test_config_dispatch.py \
       tests/qcfg/test_config_serialization.py tests/test_backend_naming.py \
       tests/test_qzero_offsets.py tests/test_awq_dequant_layouts.py \
       tests/test_export.py -q
  -> 105 passed

Item 5 PPL, 32 non-overlapping 512-token wikitext-2 windows, Qwen2-1.5B-Instruct-GPTQ-4bits-gp32:

Marlin before: 64.718    Marlin after: 102.433    GPTQ_TORCH: 102.494

The issue's absolute 48.3/141.8 split could not be reproduced with this windowing; the correctness invariant is that Marlin now matches the Torch decode (0.06% apart) and the layer error drops from 1.4e-1 to 0. Before the fix Marlin ignored g_idx and produced different tokens.

tests/test_q4_marlin.py cannot be collected on the CUDA venv because the environment lacks parameterized (pre-existing, same as tests/kernels/test_gptq.py); the gemma case was exercised directly with GPTQModel.load(..., backend=BACKEND.MARLIN) and returned finite logits.

9. Hardware

  • NVIDIA RTX 4090, UUID GPU-d458708b-c760-bbf1-08fb-8b8803a2157d (never the RTX 5090).
  • AMD R9700, HIP_VISIBLE_DEVICES=2 for CPU-verifiable tests.

10. Reviewer notes

  • get_model_with_quantize itself is owned by the sibling PR; this PR only stops assigning its result to self.model.
  • A non-contiguous g_idx on tile-misaligned shapes fails closed rather than silently decoding contiguous groups.
  • export("hf") keeps the empty-directory case working (resume=True) and refuses a non-empty target, matching dequantize_model's contract.

…d export (#4053)

- keep the caller's live model across save_quantized() instead of swapping
  in the CPU save shell
- decode a non-contiguous g_idx through Marlin's activation-order path
- accept is_marlin_format: false, reject only true
- route GPTQModel.export(..., "hf") through utils.model_dequant
- resolve per-module dynamic bits for GPTQ dequantization
- map torch backend for qqq/gguf/bitsandbytes and normalize string bits /
  null sym
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