Repository navigation
fix(hf): reselect offload-safe kernels for Marlin at post-init (#6152) - #6253
Conversation
Addresses the code-quality bot note on #6253: the commented-out block was moved along with the __init__ restructure and is dead code.
|
Merge-order note: this PR and #6274 (the HF-bridge consolidation carrying #6178's legacy floor-width 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 I verified the combined file resolves cleanly with both lines and no other conflict in |
f687800 to
691176a
Compare
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.
691176a to
3f66423
Compare
|
Rebased onto Only one hunk conflicted, and it is the known trap: both post-init steps now live at the top of 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 Note for whoever rebases #6274 next: that PR also adds Verification on the rebased head: →
|
|
Integration evidence for the three-way post-init ordering you flagged. I built a throwaway tree from Resulting _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 Suites on that tree — the union of every test file the 13 PRs touch (24 files, Skips are all CUDA/Marlin/ExLlamaV2/offload-device gates. One thing worth a second look before both land: |
`_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.
|
Pushed Root cause
Fix
EvidenceStale-snapshot repro (materialize an offloaded Marlin payload, then run
v1 grouped GPTQ fixture (
Suites (
Cross-PR note for #6274The fixture above sets |
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 keepsMarlinLinear/AwqMarlinLinearon 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
qzerosconversion that Optimum's meta no-op misses for offloaded tensors.What Changed
hf_gptqmodel_post_initcalls_reselect_offloaded_marlin_kernelsbefore the shared post-init loop.model.hf_device_mapand the layer-level Accelerate hook. Swap only layers that cannot initialize:TritonV2Linear/AwqGEMMTritonLinear(GPU execution device) orTorchLinear/AwqTorchLinear(CPU execution device);TorchLinear/AwqTorchLinear;qzerosfor offloaded Marlin layers and publish the converted tensor back to the offload map. A disk-backedqzerosmoves into the loader's writable in-memory state; the disk file is not rewritten._init_runtime_statetoTorchLinear,AwqTorchLinearandAwqGEMMTritonLinearso_switch_quant_linear_classinstalls the target's per-instance state (the existing QQQ pattern)._switch_quant_linear_classgainedpost_init=Falseso the shared post-init loop initializes the swapped module exactly once.TorchLinear/AwqTorchLineardeclareSUPPORTS_CPU_OFFLOAD = True; theirpost_initonly builds derived metadata and leaves persistent packed tensors untouched.docs/hf-interop.md(already linked fromREADME.md).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:#2e7d32The 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".RuntimeError: ... disk-backed entries ...TritonV2Linear/AwqGEMMTritonLinear(or Torch on CPU execution device)ValueError: ... requires CUDA tensors, got cpuTorchLinear/AwqTorchLinearTests
Exact commands (CPU-only unless stated):
Red (source fix reverted, regression tests present):
Green:
End-to-end released-checkpoint check (GPU 4, tiny budgets to force the spill):
The released-checkpoint
generate()step is blocked in this environment by a pre-existingtransformers/acceleratesend_to_device→import mlx.corefailure (ModuleNotFoundError), unrelated to this change; the logits comparison above usesreturn_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
_switch_quant_linear_classare used.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.pyhas one pre-existing failure at this base (gptqmodel/utils/hf.py:768importstransformers.models.auto.configuration_auto); it is unchanged by this PR.BACKEND.MARLINon 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(currentmain, one commit pastf16c0597). The branch actually forked from2d3261dd, not89dbcf91, so the patch was re-applied from that merge base.docs/hf-interop.md: main's [BUG] HF bridge:AutoModelForCausalLM.from_pretrainedof a GPT-QModel GPTQ checkpoint crashes when anyin_featuresis not a multiple ofgroup_size(SmolLM2 hidden=576, g128): bridge returns MarlinLinear without shape info #6149 row and this PR's [BUG] Plain transformers from_pretrained with CPU offload (device_map='auto'+max_memory or cpu entries) fails for every GPTQ/RTN and AWQ-GEMM ckpt: HF bridge never passes cpu_offload (#4890 only fixed native load); #3452 Marlin path rejects Accelerate's OffloadedWeightsLoader #5022 test rows were both added to the Tests table; both were kept.tests/test_hf_bridge_cpu_offload_5022.py→ 16 passed, 3 skipped (same file on865b0b48: 8 passed, 3 skipped). Related suites (tests/kernels/test_selection.py,tests/test_post_init_payload_5261.py,tests/test_qqq_runtime_state_4940.py,tests/test_quantize_in_session_4381.py) → 164 passed, 78 skipped on both bases.ruff checkclean on every changed Python file.hf_gptqmodel_post_init; the two branches conflict only at that call site.