Skip to content

fix(hf): reselect offload-safe kernels for Marlin at post-init (#6152) - #6253

Merged
Qubitium merged 3 commits into
mainfrom
fix/6152-issue
Nov 29, 2026
Merged

Qubitium merged 3 commits into
mainfrom
fix/6152-issue

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes #6152.

AutoModelForCausalLM.from_pretrained(device_map="auto", max_memory=..., offload_folder=...) regressed in #4620: Transformers resolves the map after kernel selection, so AUTO keeps MarlinLinear / AwqMarlinLinear on layers Accelerate then offloads. Disk-backed layers hit _post_init_cpu_offloaded_marlin's writable-map refusal; all-CPU layers hit Marlin's CUDA-tensor check.

This restores the pre-#4620 reselection at the post-init bridge without patching Transformers, and handles the v1→v2 qzeros conversion that Optimum's meta no-op misses for offloaded tensors.

What Changed

  • hf_gptqmodel_post_init calls _reselect_offloaded_marlin_kernels before the shared post-init loop.
  • Resolve each Marlin layer's placement from model.hf_device_map and the layer-level Accelerate hook. Swap only layers that cannot initialize:
  • Convert v1 qzeros for offloaded Marlin layers and publish the converted tensor back to the offload map. A disk-backed qzeros moves into the loader's writable in-memory state; the disk file is not rewritten.
  • Added _init_runtime_state to TorchLinear, AwqTorchLinear and AwqGEMMTritonLinear so _switch_quant_linear_class installs the target's per-instance state (the existing QQQ pattern). _switch_quant_linear_class gained post_init=False so the shared post-init loop initializes the swapped module exactly once.
  • TorchLinear / AwqTorchLinear declare SUPPORTS_CPU_OFFLOAD = True; their post_init only builds derived metadata and leaves persistent packed tensors untouched.
  • Documented the flow in docs/hf-interop.md (already linked from README.md).
  • No Transformers/Accelerate patching; no all-GPU kernel change.

Logic Flow Documentation

flowchart TD
    A["hf_gptqmodel_post_init after dispatch"] --> B{"Marlin module?"}
    B -->|"no"| C["shared gptqmodel_post_init"]
    B -->|"yes"| D{"resolved placement cpu or disk?"}
    D -->|"no"| C
    D -->|"yes"| E{"payload is meta?"}
    E -->|"no"| F["swap to CPU Torch kernel"]
    E -->|"yes"| G{"writable in-memory snapshot?"}
    G -->|"yes"| H["keep Marlin and repack snapshot"]
    G -->|"no"| I["convert v1 qzeros and swap to Triton/Torch"]
    F --> C
    H --> C
    I --> C
    style C fill:#d9f2d9,stroke:#2e7d32
    style H fill:#d9f2d9,stroke:#2e7d32
    style I fill:#d9f2d9,stroke:#2e7d32
Loading

The old decision was "AUTO selected one kernel from the unresolved keyword, and post-init either initialized it or raised". The new decision is shown above; the mechanism page is docs/hf-interop.md §6 "Post-dispatch reselection for CPU/disk offload".

Situation Before After
All-GPU resolved map Marlin Marlin
CPU-mapped layer, writable in-memory snapshot Marlin + #5022 repack Marlin + #5022 repack
Disk-backed layer RuntimeError: ... disk-backed entries ... TritonV2Linear / AwqGEMMTritonLinear (or Torch on CPU execution device)
All-CPU resident map, no dispatch hook ValueError: ... requires CUDA tensors, got cpu TorchLinear / AwqTorchLinear

Tests

Exact commands (CPU-only unless stated):

cd /root/openai-audit/issue-6152/tests
CUDA_VISIBLE_DEVICES="" PYTHONPATH=/root/openai-audit/issue-6152:/root/openai-audit/issue-6152/tests \
  /root/venv/bin/python -m pytest test_hf_bridge_cpu_offload_5022.py -q -rs \
  -k "hf_post_init_all_cpu or hf_post_init_disk_offloaded or converts_v1_qzeros"

CUDA_VISIBLE_DEVICES="" PYTHONPATH=/root/openai-audit/issue-6152:/root/openai-audit/issue-6152/tests \
  /root/venv/bin/python -m pytest test_hf_bridge_cpu_offload_5022.py -q -rs

CUDA_VISIBLE_DEVICES=4 PYTHONPATH=/root/openai-audit/issue-6152:/root/openai-audit/issue-6152/tests \
  /root/venv/bin/python -m pytest test_hf_bridge_cpu_offload_5022.py -q -rs \
  -k "native_load_uses_an_offload_safe_kernel or awq_marlin_uses_the_shared_offload_post_init"

CUDA_VISIBLE_DEVICES="" PYTHONPATH=/root/openai-audit/issue-6152:/root/openai-audit/issue-6152/tests \
  /root/venv/bin/python -m pytest test_qqq_runtime_state_4940.py test_post_init_payload_5261.py \
  test_quantize_in_session_4381.py kernels/test_selection.py test_docs_contract_refs.py -q -rs

/root/venv/bin/ruff check gptqmodel/models/base.py gptqmodel/nn_modules/qlinear/gemm_awq_triton.py \
  gptqmodel/nn_modules/qlinear/torch.py gptqmodel/nn_modules/qlinear/torch_awq.py \
  gptqmodel/utils/model.py tests/test_hf_bridge_cpu_offload_5022.py

Red (source fix reverted, regression tests present):

6 failed, 13 deselected
E ValueError: GPTQ Marlin requires CUDA tensors, got `cpu`.
E ValueError: AWQ Marlin requires CUDA tensors, got `cpu`.
E RuntimeError: CPU-offloaded Marlin requires a writable in-memory weights map:
  ['qweight', 'g_idx', 'scales', 'qzeros'] are disk-backed entries ...
E RuntimeError: CPU-offloaded Marlin requires a writable in-memory weights map:
  ['qweight', 'qzeros', 'scales'] are disk-backed entries ...
E AssertionError: Tensor-likes are not equal! (v1 qzeros 0x77777777 vs v2 0x88888888)

Green:

6 passed, 13 deselected
16 passed, 3 skipped (CPU-only full family; the 3 skips are the accelerator-gated native-load/AWQ Marlin nodes)
3 passed (same family on CUDA_VISIBLE_DEVICES=4)
24 passed, 6 skipped (runtime-state, post-init payload, in-session quantize)
140 passed, 72 skipped (kernel selection)
33 passed (docs contract references)
1 passed (test_transformers_unpatched.py)

End-to-end released-checkpoint check (GPU 4, tiny budgets to force the spill):

Qwen/Qwen2.5-0.5B-Instruct-GPTQ-Int4
  placements {'0', 'cpu', 'disk'}; kernels ['MarlinLinear', 'TritonV2Linear']
  mixed logits vs all-GPU: max |dlogit| 0.0390625, argmax agree 100%
Qwen/Qwen2.5-0.5B-Instruct-AWQ
  placements {'0', 'cpu', 'disk'}; kernels ['AwqMarlinLinear', 'AwqGEMMTritonLinear']
  mixed logits vs all-GPU: max |dlogit| 0.0234375, argmax agree 100%

The released-checkpoint generate() step is blocked in this environment by a pre-existing transformers/accelerate send_to_device → import mlx.core failure (ModuleNotFoundError), unrelated to this change; the logits comparison above uses return_dict=False.

Measured Impact

No performance or VRAM claim. All-GPU loads still use Marlin; only offloaded layers are reinterpreted. The released-checkpoint mixed loads above match the all-GPU reference logits.

Model Support / Module Plan

Not applicable: no MODEL_MAP, definition, module-plan or fusion change.

AWQ onboarding safety

Not applicable: no new model/alias or AWQ grouping/search/replay/fold change. The AWQ change is the offload-safe kernel reselect only.

Review Requirements

  • Reviewed this PR.
  • Matches existing project structure, APIs and conventions.
  • No unnecessary monkeypatching; package-owned post-init and _switch_quant_linear_class are used.
  • Minimized the impacted code surface.
  • Considered regressions: all-GPU and writable CPU-offload snapshot paths are kept, and the family tests cover both.

Kernel Accuracy Requirements

Not applicable: no kernel math, packing, fusion or dtype change. End-to-end logits for both released checkpoints were compared with the all-GPU load (above).

Notes

  • tests/test_model_port_policy.py has one pre-existing failure at this base (gptqmodel/utils/hf.py:768 imports transformers.models.auto.configuration_auto); it is unchanged by this PR.
  • Explicit BACKEND.MARLIN on a GPU-resident map keeps Marlin. On a CPU/disk-offloaded map Marlin cannot initialize, so the bridge falls back to the offload-safe kernel rather than raising.

Rebase onto main (2026-11-29)

Rebased onto 865b0b48 (current main, one commit past f16c0597). The branch actually forked from 2d3261dd, not 89dbcf91, so the patch was re-applied from that merge base.

Qubitium added a commit that referenced this pull request Nov 29, 2026
Addresses the code-quality bot note on #6253: the commented-out block was
moved along with the __init__ restructure and is dead code.

Copy link
Copy Markdown
Collaborator Author

Merge-order note: this PR and #6274 (the HF-bridge consolidation carrying #6178's legacy floor-width qzeros repair) both insert one call at the top of hf_gptqmodel_post_init in gptqmodel/utils/model.py, so they conflict on that single hunk. The resolution is to keep both lines, in this order:

def hf_gptqmodel_post_init(model, use_act_order, quantize_config=None, max_input_length=None):
    _materialize_hf_sym_qzeros(model)          # #6178 legacy floor-width qzeros
    _reselect_offloaded_marlin_kernels(model)  # #6152 offload-safe kernel reselect
    model = gptqmodel_post_init(model, use_act_order, quantize_config, max_input_length)

They are independent pre-post-init repairs — #6178 converts a legacy qzeros layout for symmetric GPTQ before buffers are initialized; this PR reinterprets Marlin layers that Accelerate will offload before the shared post-init loop initializes them. Neither reads state the other writes.

I verified the combined file resolves cleanly with both lines and no other conflict in utils/model.py, so whoever merges second only needs that two-line edit.

@Qubitium
Qubitium marked this pull request as ready for review November 29, 2026 04:45
Rebased onto main after #6344 landed. Both post-init steps are preserved:

* `_reselect_offloaded_marlin_kernels` (this PR) reinterprets layers that
  AUTO put on Marlin from the unresolved `device_map` keyword but that
  Accelerate then offloads, so they are re-selected before the shared
  post-init loop initializes them.
* `_repair_bridge_missing_g_idx` (#6344) rebuilds a canonical `g_idx` for
  checkpoints that ship none.

The reselect runs first so the repair reads the `desc_act` of the module the
layer was actually rebuilt as.
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Rebased onto be148244 (was conflicting after #6344 landed).

Only one hunk conflicted, and it is the known trap: both post-init steps now live at the top of hf_gptqmodel_post_init.

def hf_gptqmodel_post_init(model, use_act_order: bool, quantize_config: QuantizeConfig = None,
                        max_input_length: Optional[int] = None):
    # Transformers resolves `device_map="auto"` from `max_memory` only after
    # the kernel was selected from the unresolved keyword, so AUTO can still
    # hold a Marlin layer that Accelerate then offloads. Reinterpret those
    # layers before the shared post-init loop initializes them.
    _reselect_offloaded_marlin_kernels(model)
    # Rebuild the canonical `g_idx` after any class swap above, so the repair
    # reads the `desc_act` the final module was actually built with.
    _repair_bridge_missing_g_idx(model, use_act_order)
    model = gptqmodel_post_init(model, use_act_order, quantize_config, max_input_length)

Both are preserved. I deliberately put the reselect first: it swaps layer classes, and #6344's repair keys off desc_act, so it should read the module the layer was actually rebuilt as rather than the pre-swap one.

Note for whoever rebases #6274 next: that PR also adds _materialize_hf_sym_qzeros at this same spot. All three calls are independent and all three must survive.

Verification on the rebased head:

cd tests && CUDA_VISIBLE_DEVICES="" PYTHONPATH=<clone>:<clone>/tests \
  /root/venv/bin/python -m pytest test_hf_bridge_cpu_offload_5022.py \
  test_hf_bridge_missing_g_idx_6339.py -q -rs -p no:cacheprovider

→ 21 passed, 3 skipped (the three skips are pre-existing: two need an accelerator for the resident layers, one needs an NVIDIA CUDA build for Marlin)

ruff check on all changed files → All checks passed.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Integration evidence for the three-way post-init ordering you flagged.

I built a throwaway tree from main = 0dd8e8ab and applied every open PR's own diff
(gh pr diff + git apply --3way --index): 6248, 6253, 6258, 6269, 6270, 6274, 6297, 6329,
6337, 6343, 6351, 6352, 6353. All 13 apply clean; only this one hunk needs the manual edit you
described.

Resulting hf_gptqmodel_post_init (all three definitions present, each called once):

_reselect_offloaded_marlin_kernels(model)              # #6152
_repair_bridge_missing_g_idx(model, use_act_order)     # #6344, already in main
_materialize_hf_sym_qzeros(model)                      # #6178, from #6274
model = gptqmodel_post_init(model, use_act_order, quantize_config, max_input_length)

I kept your order (reselect first) and appended the qzeros materialization after the g_idx
repair, so each step reads the class the previous one left behind.

Suites on that tree — the union of every test file the 13 PRs touch (24 files,
tests/models/ excluded), CPU:

529 passed, 22 skipped, 0 failed in 200.05s

Skips are all CUDA/Marlin/ExLlamaV2/offload-device gates.

One thing worth a second look before both land: _materialize_hf_sym_qzeros keys off
module._HF_DEFER_SYM_QZEROS, and the reselect replaces modules with new MarlinLinear
instances. If the replacement does not carry that flag over, a legacy-floor-width checkpoint
whose layers get reselected to Marlin would have its deferred qzeros never materialized —
invisible to either PR alone. I have a separate check running on exactly that; I will report
here if it is real.

agent added 2 commits November 29, 2026 11:49
`_switch_quant_linear_class()` reassigns `__class__`, which drops the
checkpoint-format markers the HF bridge's #6178 compatibility wrapper keeps
on the generated subclass. A reselected offloaded Marlin layer then loses
`_HF_DEFER_SYM_QZEROS`, so the post-load bridge skips the deferred symmetric
`qzeros` materialization and decodes an unmaterialized buffer.

Carry the truthy markers onto the instance across the swap and cover the
reselect path with a regression test.
`_post_init_cpu_offloaded_marlin` decided whether an Accelerate snapshot exists from `checkpoint_payload_is_meta()`. A loader can materialize an offloaded layer's payload before the bridge runs, so the probe is false while the layer-level hook still owns a writable map. The early return then called `post_init()` on the resident tensors: on CPU Marlin raised `ValueError: GPTQ Marlin requires CUDA tensors, got cpu`, and on CUDA the map kept the pre-repack layout.

Decide from `_layer_offload_hook()` instead. When the hook exists, always materialize from the map on its execution device, repack, return to meta and publish every persistent tensor the map replays. Derive those names from the module's parameters/buffers rather than only the meta ones, so a stale snapshot is refreshed and the #5022 invariant holds.

Tests: v1 grouped GPTQ `device_map="auto"` + `max_memory` offload fixture, the stale-snapshot regression (CPU stub and CUDA), and a CPU-only structural check of the reselect decision.

Copy link
Copy Markdown
Collaborator Author

Pushed 8d473e04a (on top of edc872ab3) with the stale-snapshot fix for the #6274 interaction.

Root cause

_post_init_cpu_offloaded_marlin used checkpoint_payload_is_meta() to decide whether an Accelerate snapshot exists. A loader can materialize an offloaded layer's payload before the bridge runs, so the probe is false while the layer-level hook still owns a writable map. The early return then called post_init() on the resident tensors: on CPU Marlin raised ValueError: GPTQ Marlin requires CUDA tensors, got cpu; on CUDA the map kept the pre-repack layout. _marlin_needs_offload_kernel correctly kept Marlin because the map is writable (#5022), so the bug is entirely in the post-init decision.

Fix

  • Decide from _layer_offload_hook(module). If a layer-level hook exists, always pre_forward → post_init → post_forward and publish the repacked tensors to the writable map.
  • Derive the refreshed names from the module's persistent parameters/buffers, not only the tensors that are still meta. That is what makes a materialized/stale payload repack into the snapshot. qzeros_format is excluded: it is a derived state-dict marker, not checkpoint payload.
  • A layer with no hook keeps the old resident path; a meta payload with no layer-level hook still raises the existing _layer_offload_hook error.
  • The all-GPU and writable CPU-snapshot paths stay on Marlin; no reselect change.

Evidence

Stale-snapshot repro (materialize an offloaded Marlin payload, then run _post_init_cpu_offloaded_marlin on GPU):

tree result
base be148244 ValueError: GPTQ Marlin requires CUDA tensors, got cpu
#6253 edc872ab3 same ValueError
#6253 8d473e04a passes; map matches a resident post_init exactly
#6253 8d473e04a + #6274 f6f7b06d8 passes; map matches exactly

v1 grouped GPTQ fixture (checkpoint_format: gptq, meta.v2: false, backend: auto; tiny 1-layer Llama, device_map="auto", max_memory={0: "32KiB", "cpu": "4GiB"}, offload_folder):

tree kernels forward
base be148244 7 × TorchLinear finite
#6253 edc872ab3 7 × TorchLinear finite
#6253 8d473e04a + #6274 f6f7b06d8 7 × MarlinLinear finite; offload map == resident reference

Suites (test_hf_bridge_cpu_offload_5022, test_cpu_offload_*, test_single_device_dispatch_4847, test_hf_bridge_mixed_capability_5084, test_offload_*, test_marlin_cpu_offload_post_init, test_hf_bridge_missing_g_idx_6339, kernels/test_selection):

Cross-PR note for #6274

The fixture above sets meta.v2: false in quantize_config.json (the GPTQModel sidecar) but keeps the classic AutoGPTQ config.json shape without meta. Adding meta.v2: false to the HF quantization_config makes _hf_legacy_qzeros_layout() classify this current-width v1 checkpoint as a pre-7.3.4 floor-width one; on an offloaded Marlin layer _materialize_hf_sym_qzeros() then raises its own RuntimeError before _post_init_cpu_offloaded_marlin runs. That is a separate #6274-owned detection path, not this fix. The two fixes are independent and both are needed for that exact sidecar shape.

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