Skip to content

fix(hf): packable selection, per-layer shape dispatch and legacy qzeros in the HF bridge (#6191, #6178, #6336) - #6274

Merged
Qubitium merged 4 commits into
mainfrom
fix/hf-bridge-layout-consolidated
Nov 29, 2026
Merged

Qubitium merged 4 commits into
mainfrom
fix/hf-bridge-layout-consolidated

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Consolidates #6345 (fix/6336-perf) into this branch. It now carries all three HF-bridge fixes:

Fixes #6191, #6178, #6336

How pack=True vs pack=False resolve now

Both entry points share one selection body; the pack flag decides which branch is authoritative.

pack=True (quantizing)

  1. _hf_pack_backend() resolves the requested backend. A pack-capable backend is kept. An inference-only backend (Marlin, ExLlamaV2, ...) is validated once with select_quant_linear(..., pack=False) so a real contract mismatch (for example bits=3 for Marlin) still raises before calibration; then it warns and returns BACKEND.AUTO. The saved quantization_config still records the requested backend, so a reload selects it for inference.
  2. select_quant_linear(..., pack=True) runs with the resolved backend. AUTO's pack gate keeps only kernels with a pack API.
  3. _shape_safe_gptq_selection() may still add the per-layer dispatcher when the selected packable kernel cannot auto-pad and no width was supplied. Its fallback selection also runs with pack=True, so both concrete classes remain packable. The legacy qzeros wrapper never runs on this path (it is load-only).

Net: pack=True always resolves to a packable kernel (or a dispatcher of two packable kernels), and the requested inference backend is preserved in the saved config.

pack=False (loading/inference)

  1. _hf_pack_backend() returns the backend unchanged.
  2. An explicit backend keeps its existing selection; the shape-aware dispatch is AUTO-only.
  3. A shape-blind AUTO grouped GPTQ selection returns ShapeAware<AutoKernel>: in_features % group_size == 0 builds the AUTO kernel (MarlinLinear on CUDA, TorchCpuAvx512Linear on CPU), while a partial group (or an unknown width) builds the auto-padding TorchLinear.
  4. When the checkpoint's producer metadata predates 7.3.4 (or carries the legacy v2/v2_alpha markers), the legacy qzeros wrapper is applied to both concrete kernels before the dispatcher is built, so the floor-width deferral is preserved on either width branch.

Net: pack=False keeps the explicit-backend contract, keeps the fast AUTO kernel for aligned layers, and only pays the portable kernel where the group is partial.

Selection count

The plain-HF pack=False AUTO path still performs exactly 2 select_quant_linear calls per checkpoint (AUTO + one pre-selected padding fallback), independent of module count; per-layer decisions are one modulo test. #6345's assertion is unchanged. pack=True with an inference-only backend adds one call: the explicit contract probe in _hf_pack_backend(), which is required so an unsatisfiable backend fails before calibration instead of after it.

Consolidation of #6345

No work from either PR was dropped.

What changed (combined)

#6191 — packable kernel selection (gptqmodel/utils/importer.py)

_hf_pack_backend() resolves the bridge's single backend field:

  • pack=False (load/inference): unchanged; the explicit backend is honoured.
  • pack=True with a packable explicit backend: unchanged.
  • pack=True with an inference-only kernel (Marlin, ExLlamaV2, ...): warn and pack with the method default (AUTO). The saved quantization_config still records the requested backend, so reload selects it for inference.
  • The requested backend is validated without the pack gate first (select_quant_linear(..., pack=False)), so an unsatisfiable contract (e.g. bits=3 for Marlin) raises its clear error before calibration instead of packing a checkpoint the saved config cannot load.

hf_select_quant_linear() and hf_select_quant_linear_v2() build the selection kwargs once, resolve the backend through that helper, recompute cpu_offload for the resolved backend, and select.

#6178 — legacy floor-width qzeros

  • gptqmodel/nn_modules/qlinear/__init__.py
    • legacy_qzeros_columns(): the legacy floor width.
    • qzeros_standard_shape(): the current packed shape. Translation only runs when the live buffer is the standard packed layout, so kernel-private runtime qzeros (TorchAten/TorchFused int4pack offsets) are untouched.
    • qzeros_symmetric_word() / qzeros_word_for_dtype(): the packed constant for 2/4/8-bit and its signed torch.full value.
    • GPTQQuantLinear._prepare_legacy_qzeros_state_dict() (called from _load_from_state_dict_locked) pads a legacy symmetric qzeros before the copy. sym=False, planar, or non-2/4/8-bit legacy checkpoints raise a clear legacy pre-#2983 GPTQ qzeros layout error.
    • The HF-bridge subclass hides the redundant symmetric qzeros from the expected state dict only while loading; checkpoint serialization keeps it.
  • gptqmodel/utils/importer.py
    • _hf_legacy_qzeros_layout() selects compatibility only for positively identified old producers: v2/v2_alpha meta, or meta.quantizer = gptqmodel:<version> older than 7.3.4 (first release with fix(qlinear): size GPTQ buffers by pack_factor and skip Laguna g_proj quantization #2983).
    • _hf_legacy_qzeros_quant_linear() returns a cached subclass of the selected kernel that defers symmetric qzeros. Current checkpoints without producer metadata keep exact shape validation.
  • gptqmodel/utils/model.py
    • _prepare_legacy_qzeros_buffers() sizes the buffer for Accelerate/lazy copy; _finalize_legacy_qzeros() validates the constant and pads back to the current width.
    • _materialize_hf_sym_qzeros() regenerates deferred symmetric qzeros in the kernel's target runtime layout before gptqmodel_post_init.

#6336 — per-layer shape dispatch

gptqmodel/utils/importer.py:

  • _shape_aware_gptq_kernel() returns ShapeAware<AutoKernel> — a subclass of the already-selected AUTO kernel whose __new__ reads in_features and dispatches; kernel_for_width() is one modulo test.
  • A metaclass __instancecheck__ keeps Optimum's isinstance / get_layers working for both concrete kernels.
  • _shape_safe_gptq_selection() selects the padding kernel once per checkpoint and returns the dispatcher. It composes with fix(hf): packable selection, per-layer shape dispatch and legacy qzeros in the HF bridge (#6191, #6178, #6336) #6274: _hf_pack_backend() resolves the packing backend first, then the shape-aware decision runs on that resolved backend.

Tests

All commands run CPU-only with CUDA_VISIBLE_DEVICES="" from the repo's tests/ directory with PYTHONPATH=<clone>:<clone>/tests.

Target suite (both PRs' files plus the adjacent bridge regression):

/root/venv/bin/python -m pytest test_hf_packing_api.py test_hf_bridge_grouped_load_cost_6336.py \
  test_hf_bridge_missing_shape_6149.py test_checkpoint_interop_4053.py \
  kernels/test_qlinear_hierarchy.py test_hf_bridge_missing_g_idx_6339.py \
  -q -rs -p no:cacheprovider

118 passed, 11 skipped (all skips are pre-existing CUDA-device gates).

Broader affected set:

/root/venv/bin/python -m pytest test_hf_bridge_cpu_offload_5022.py \
  test_hf_bridge_mixed_capability_5084.py kernels/test_selection.py \
  test_docs_contract_refs.py test_hf_bridge_missing_g_idx_6339.py \
  -q -rs -p no:cacheprovider

395 passed, 75 skipped.

Lint

/root/venv/bin/ruff check gptqmodel/utils/importer.py tests/test_hf_packing_api.py \
  tests/test_hf_bridge_grouped_load_cost_6336.py tests/test_hf_bridge_missing_shape_6149.py
All checks passed!

Files

  • gptqmodel/utils/importer.py
  • gptqmodel/nn_modules/qlinear/__init__.py
  • gptqmodel/utils/model.py
  • tests/test_hf_packing_api.py
  • tests/kernels/test_qlinear_hierarchy.py
  • tests/test_checkpoint_interop_4053.py
  • tests/test_hf_bridge_grouped_load_cost_6336.py
  • tests/test_hf_bridge_missing_shape_6149.py

Skips / unverified

Head

9c647ac7e777bbb54cb4bf2afb7d7a94e500c986 on fix/hf-bridge-layout-consolidated.

Copy link
Copy Markdown
Collaborator Author

Merge-order note: this PR and #6253 (the from_pretrained(device_map=...) Marlin reselect fix, #6152) 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 the buffers are initialized, and #6152 reinterprets Marlin layers that Accelerate will offload before the shared post-init loop initializes them. Neither reads state the other writes, so either order works; the above matches the order in which the repairs were written.

I verified the combined file applies cleanly with both lines (git merge-file with that resolution leaves no conflict), but I did not re-run #6152's GPU evidence on this branch, so I left the two PRs separate rather than folding a 7-file offload/Marlin change into this one. Whoever merges second can take the two-line resolution above.

@Qubitium
Qubitium force-pushed the fix/hf-bridge-layout-consolidated branch 2 times, most recently from 91dcfb4 to f16b3e2 Compare November 29, 2026 08:41
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Rebased onto abde192e. gptqmodel/utils/importer.py was the only conflict: main's #6326 replaced #6323's shape-blind refusal with an AUTO fallback to the portable auto-padding Torch kernel, while this PR adds _hf_pack_backend() and the legacy floor-width symmetric qzeros deferral. Kept both intents — the bridge resolves the pack backend, selects with it, applies main's shape-safe Torch fallback when the caller omits in_features, then wraps a legacy qzeros checkpoint. Dropped the old _reject_unvalidatable_shape_blind_selection raise body (superseded by main's _needs_shape_safe_gptq_kernel()). Adapted tests/test_hf_packing_api.py to the new contract: shape-blind selection now asserts the TorchLinear fallback instead of ValueError, while in_features=896 still selects Marlin and 576 still avoids it. Verified with CUDA_VISIBLE_DEVICES="": 96 passed, 11 skipped; pristine abde192e on the same files is 2 failed / 84 passed / 11 skipped (the same two stale tests). ruff check passes on all changed Python files.

…he HF bridge (#6191, #6178)

Rebased onto be14824; keeps both the #6344
g_idx repair and the deferred symmetric qzeros materialization in
hf_gptqmodel_post_init, and keeps main's #6327 shape-blind fallback
contract in test_hf_packing_api.
@Qubitium
Qubitium force-pushed the fix/hf-bridge-layout-consolidated branch from f16b3e2 to be702ac Compare November 29, 2026 09:58
… legacy qzeros (#6191, #6178, #6336)

Bring #6345's ShapeAware<AutoKernel> dispatcher into #6274's HF bridge
selection path:

- _shape_safe_gptq_selection() now takes the pack flag and selects the
  auto-padding fallback with the same pack gate, so a pack=True call still
  resolves to a packable kernel.
- _hf_pack_backend() runs first and resolves the packing backend; the
  shape-aware decision is layered on the resolved backend.
- the legacy floor-width qzeros wrapper is applied to both concrete kernels
  of the dispatcher (aligned AUTO and partial-group fallback), so #6178's
  deferral survives the per-layer split.
- the plain-HF pack=False AUTO path keeps its constant two selections.

Merged test_hf_packing_api.py keeps #6345's per-layer assertions and
#6274's pack/inference assertions.
@Qubitium Qubitium changed the title fix(hf): packable kernel selection and legacy floor-width qzeros in the HF bridge (#6191, #6178) fix(hf): packable selection, per-layer shape dispatch and legacy qzeros in the HF bridge (#6191, #6178, #6336) Nov 29, 2026
The #6336 per-layer dispatcher only checked the partial-group rule, so an
AUTO kernel that passed model-wide validation (in_features/out_features
unknown) could still reject the real layer shape. The CPU AVX512 kernel
requires out_features % 32 == 0, so a plain-HF load of a model with a
1744-wide intermediate crashed during layer replacement; route those
layers to the pre-selected TorchLinear fallback.

TorchAtenLinear also advertised SUPPORTS_AUTO_PADDING=True although its
CPU int4pack validation rejects a partial last group. That made the
shape-blind bridge skip the dispatcher for group_size=32 checkpoints and
crash on a 48-wide layer. Declare the contract the op actually enforces.

Update the #6169 dtype tests for the dispatcher's second (padding)
selection and add regression tests for both paths.
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Blocking defect found in the consolidation; fixed in 3640e9b0a.

_materialize_hf_sym_qzeros rebuilt every deferred qzeros with register_buffer,
but Marlin keeps its zero point in a packed Parameter and never reads the words.
An AUTO load of a legacy floor-width checkpoint on CUDA therefore raised

KeyError: "attribute 'qzeros' already exists"

before gptqmodel_post_init could run. The portable Torch kernel was unaffected,
which is why the existing CPU-only coverage missed it — and it only shows up once
#6152's reselect and this PR's deferral are both present, so neither PR alone
reproduces it.

Reproduced on a legacy-marked checkpoint (meta.quantizer = gptqmodel:5.1.0-dev,
backend: auto, one layer, 32-aligned):

tree plain-HF from_pretrained(device_map={"": 0})
0dd8e8ab (main) RuntimeError: You set ignore_mismatched_sizes to False ... (legacy width, expected)
#6274 23ecb5be3 KeyError: attribute 'qzeros' already exists
#6274 3640e9b0a loads, MarlinLinear for every projection, finite logits

The fix skips the rebuild for a kernel that does not own a qzeros buffer — the
deferral only hides the legacy width from the core loader, so there is nothing
left to repair — and replaces the constructor's meta placeholder with the empty
parameter the kernel's own runtime state installs, so a resident layer is not
mistaken for an offloaded one (that was the second failure behind the first:
RuntimeError: An offloaded quantized layer requires a layer-level Accelerate offload hook).

New tests/test_hf_bridge_legacy_qzeros_marlin_6274.py covers the Marlin load on
CUDA, the portable path on CPU, and both branches of the skip directly.

I also split test_dispatcher_respects_out_features_divisibility: its
construction half calls selected(...), which builds a real MarlinLinear and
needs the CUDA extension, so it failed the whole file on a CPU host. The
kernel_for_width assertions stay unguarded; the construction assertions moved
to their own test behind marlin_import_exception is not None.

Verification at 3640e9b0a:

# CUDA (CUDA_VISIBLE_DEVICES=1)
test_checkpoint_interop_4053, test_hf_packing_api, test_hf_bridge_missing_shape_6149,
test_hf_bridge_grouped_load_cost_6336, test_cpu_int4pack_dispatch_contracts,
test_hf_bridge_missing_g_idx_6339, test_hf_bridge_legacy_qzeros_marlin_6274,
kernels/test_qlinear_hierarchy, kernels/test_selection
-> 317 passed, 46 skipped, 0 failed

# CPU (CUDA_VISIBLE_DEVICES="")
-> 277 passed, 86 skipped, 0 failed

ruff check clean on all changed files. Ready for review.

`_materialize_hf_sym_qzeros` rebuilt every deferred symmetric `qzeros` with
`register_buffer`, but Marlin keeps its zero point in a packed `Parameter`
and never reads the words. An AUTO load of a legacy floor-width checkpoint on
CUDA therefore raised `KeyError: attribute 'qzeros' already exists` before
`gptqmodel_post_init` could run; the portable Torch kernel was unaffected,
which is why the CPU-only coverage missed it.

The deferral only hides the legacy width from the core loader, so a kernel
that does not own a `qzeros` buffer has nothing left to repair. Skip it, and
replace the constructor's meta placeholder with the empty parameter the
kernel's own runtime state installs, so a resident layer is not mistaken for
an offloaded one.

`tests/test_hf_bridge_legacy_qzeros_marlin_6274.py` covers the Marlin load on
CUDA, the portable path on CPU, and both branches of the skip directly.
@Qubitium
Qubitium force-pushed the fix/hf-bridge-layout-consolidated branch from 3640e9b to f6f7b06 Compare November 29, 2026 11:54
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Second blocking finding — #6274 must not merge before this is resolved. It needs #6253's reselect, and even with #6253 the combination still fails.

Once #6336's dispatcher keeps the AUTO kernel for group-aligned layers, a v1 grouped GPTQ checkpoint (checkpoint_format: gptq, meta.v2: false — the classic AutoGPTQ/GPTQModel save, not the pre-7.3.4 "legacy" case) dispatched with device_map="auto" + max_memory offload no longer loads:

tree from_pretrained(dir, device_map="auto", max_memory={0: "80MiB", "cpu": "4GiB"}, offload_folder=...)
be148244 (base of this PR) loads, TorchLinear
0dd8e8ab (main) loads, TorchLinear
#6274 alone f6f7b06d8 ValueError: GPTQ Marlin requires CUDA tensors, got 'cpu'
main + #6253 + #6274 same ValueError

Traceback:

optimum/gptq/quantizer.py:624 post_init_model
 -> gptqmodel/utils/model.py hf_gptqmodel_post_init
 -> gptqmodel/utils/model.py gptqmodel_post_init
 -> _post_init_cpu_offloaded_marlin(module)
 -> module.post_init()
 -> marlin.py:408 marlin_validate_runtime_device(...)
ValueError: GPTQ Marlin requires CUDA tensors, got `cpu`.

Mechanism, instrumented on main + #6253 + #6274: for every offloaded layer

CHK model.layers.0.self_attn.k_proj  meta=True  runtime_device=cpu  qweight.device=cpu
  -> _marlin_needs_offload_kernel == False

_marlin_needs_offload_kernel takes the meta branch and asks _marlin_offload_needs_reselection, which returns False because the offload map is writable in memory (disk_index is None) — it assumes the #5022 snapshot-refresh path will handle the layer. By the time _post_init_cpu_offloaded_marlin runs, the payload is no longer meta (the tensors were materialized onto the CPU device), so it takes its "resident weights, no snapshot to refresh" early return and calls module.post_init() on CPU tensors, which Marlin rejects.

On be148244/main this never happens because the shape-blind selection returns TorchLinear; the dispatcher is what puts a Marlin instance there.

Proposed fix (in #6253's owner code, not this PR): _post_init_cpu_offloaded_marlin should decide from the attached offload hook rather than from checkpoint_payload_is_meta(). When the layer has a layer-level offload hook, always hook.pre_forward(module) → post_init() → hook.post_forward(module, None) and refresh the snapshot; only fall back to a plain post_init() when there is no hook. Alternatively _marlin_needs_offload_kernel should reselect when runtime_device() is CPU even though the payload is still meta.

Reproduction is 12 lines (tiny 1-layer Llama, bits=4, group_size=128, sym=True, desc_act=False, saved with v2: false, backend: auto, then device_map="auto" with an 80 MiB GPU budget). I can attach the fixture if useful.

Note the two PRs are interdependent in both directions: #6253's _convert_offloaded_marlin_qzeros and its reselect are what make an offloaded Marlin layer loadable at all, and #6274 is what starts producing Marlin instances for offloaded layers. Merging either alone is fine; the pair needs the fix above.

Separately, #6253's marker preservation (edc872ab3) is required for this PR's _materialize_hf_sym_qzeros to see _HF_DEFER_SYM_QZEROS after a class swap — without it a reselected legacy layer is silently skipped.

@Qubitium
Qubitium marked this pull request as ready for review November 29, 2026 12:37
@Qubitium
Qubitium merged commit 613fa40 into main Nov 29, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/hf-bridge-layout-consolidated branch November 29, 2026 12:37
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Correction / status on my earlier "blocking" note — #6253 now carries the fix, and my fixture was partly invalid.

  1. The v1 + offload ValueError: GPTQ Marlin requires CUDA tensors is fixed in fix(hf): reselect offload-safe kernels for Marlin at post-init (#6152) #6253 8d473e04a. That commit decides _post_init_cpu_offloaded_marlin from the attached layer hook instead of checkpoint_payload_is_meta(), so a payload the loader already materialized on CPU is repacked through the hook and the snapshot is refreshed. Measured by that agent on the combined tree: the classic AutoGPTQ HF-sidecar shape now loads with all-Marlin layers and an offload map identical to the all-GPU reference, and test_marlin_cpu_offload_post_init.py plus the [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 in-place-repack tests pass on CPU and GPU.

  2. My two-sidecar fixture (meta.v2: false in BOTH config.json and quantize_config.json) is not a valid gate. On that shape this PR's _hf_legacy_qzeros_layout() classifies a current-width v1 checkpoint as pre-7.3.4 and defers qzeros; for an offloaded layer this PR then raises

    RuntimeError: <Kernel>: a legacy floor-width symmetric GPTQ checkpoint cannot be
    materialized on a CPU/disk-offloaded layer. Load it with `offload_state_dict=False`
    and a resident device map.
    

    I tried relaxing that to "skip materialization for a kernel that does not own a qzeros buffer" (Marlin never reads the words), but the same fixture then fails inside the forward with a device mismatch — and it fails on 0dd8e8ab (main) the same way, before either PR is involved:

    RuntimeError: Expected all tensors to be on the same device, but got index is on cuda:0,
    different from other tensors on cpu
    

    So that fixture exercises a pre-existing offload defect of its own and cannot discriminate this pair. I reverted the relaxation rather than ship an unverified change: a clear, actionable error beats silently continuing into a known-broken path.

  3. Net: the two PRs are independent and both needed, and neither needs a code change from the other. fix(hf): reselect offload-safe kernels for Marlin at post-init (#6152) #6253 handles the offload post-init; this PR handles the legacy width for resident layers and raises an explicit error when that combination cannot be repaired. Documented limitation: a pre-7.3.4-marked checkpoint loaded with CPU/disk offload needs offload_state_dict=False, and the error says so.

Qubitium pushed a commit that referenced this pull request Nov 29, 2026
`device_map="auto"` resolves `max_memory` only after the kernel was selected,
so at reselect time an offloaded layer is still a meta placeholder with no
layer-level hook and no `hf_device_map`. `_marlin_needs_offload_kernel` read
the missing hook as "the bridge does not own the map" and declined the
reselect; `_post_init_cpu_offloaded_marlin` then saw a payload that was no
longer meta (materialized onto the CPU device), found no hook, and called
Marlin's `post_init()` on CPU tensors:

    ValueError: GPTQ Marlin requires CUDA tensors, got `cpu`.

Since #6274's per-layer dispatcher keeps the AUTO kernel for group-aligned
layers, every published pre-7.3.4 GPTQ checkpoint loaded with
`device_map="auto"` + `max_memory` hit this. Measured on
`ModelCloud/DeepSeek-R1-Distill-Qwen-7B-gptqmodel-4bit-vortex-v1`:

    0dd8e8a  offload OK  {'TorchLinear': 196}
    3082b02  offload FAIL ValueError: GPTQ Marlin requires CUDA tensors
    this tree offload OK  {'TorchLinear': 196}

A layer that already has a layer-level hook keeps the writable-snapshot path
(#5022) and stays on Marlin; only the "no hook yet, placement is CPU" state is
now reselected.

`tests/test_marlin_offload_reselect_6383.py` pins the decision: meta + no hook
+ CPU placement reselects, a writable in-memory snapshot keeps Marlin, a
disk-backed snapshot reselects, and resident GPU/CPU layers keep their
existing outcomes.
Qubitium added a commit that referenced this pull request Nov 30, 2026
…ent; document breaking changes (#6471)

- #6396/#5022/#6274/#6157/kimi-k3: the device_map='auto' + max_memory/offload_folder
  scenarios now load through GPTQModel.load(placement=...) (Placement.budget,
  cpu>accel:0, disk>cpu + offload_dir) or WeightLoader.place, keeping their value
  assertions (exact clean-checkpoint logits for #6157, resident-equal logits for
  the offload cases, the repaired A_log payload/forward/resave for kimi-k3).
- Removed only the HF-bridge-internal assertions with no GPT-QModel-path
  equivalent: the Marlin CPU-offload snapshot repack (#5022) and the
  _HF_DEFER_SYM_QZEROS flag checks (#6274).
- New: plain Transformers from_pretrained(device_map / max_memory / offload_folder)
  on a GPT-QModel checkpoint in a gptqmodel process raises 'requires accelerate'.
- Fix: disk> placements count as offload for from_quantized (kernel selection and
  the post-load meta check), matching #5194.
- docs/weight-loader.md: Breaking changes section.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Qubitium added a commit that referenced this pull request Nov 30, 2026
A container's forward never runs, so an execution hook on it never fired: a
rule like {'model.layers': 'cpu>accel:0'} left every layer on CPU while its
inputs were on the accelerator. simple_dispatch_model expands container entries
per child and WeightLoader.dispatch hooks the children. Regression test is red
without the fix. Also: #5022/#6274 ported tests use the portable kernel as the
numeric oracle and a CPU-kernel tolerance.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Qubitium added a commit that referenced this pull request Nov 30, 2026
…t and offload (#6471) (#6473)

* weight_loader: explicit Accelerate-free weight loading, placement and offload (#6471)

Adds gptqmodel.weight_loader: an explicit Placement language (module path ->
device, cpu>dev / disk>dev offload, [a:b] layer ranges, no auto/memory probing),
WeightLoader (streams safetensors shards straight to each placed device, dtype
and fp32-keep rules, key conversion, disk offload, retie, strict reports),
execution hooks (AlignDevicesHook / CpuOffload that never flush the device
cache and drive parameterless packed modules), the on-disk offload store and
tensor primitives. Depends only on torch and safetensors.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Remove accelerate: migrate runtime to weight_loader, explicit placement, safe-file loading (#6471)

- Every runtime accelerate import now uses gptqmodel.weight_loader; utils/offload_hooks.py
  (subclasses that only suppressed Accelerate's cache flush) is deleted, the dead AWQ
  simple_dispatch_model copy is removed, DeepSeek V4.1 drops infer_auto_device_map for
  an explicit layer-split / budget-pack policy.
- transformers is never handed a device_map (it requires Accelerate for any non-None
  map): the HF load runs on CPU and WeightLoader.place() applies the placement.
- Placement gains the backend-neutral accel family: 'accel:N', and 'accel' /
  'accel:auto' (balanced by free memory, then best fit; raises instead of spilling).
  device_map='auto'/'balanced'/'sequential' map onto accel:auto.
- WeightLoader refuses pickle checkpoints and validates safetensors (exact tensor
  tiling, tensor-only header, str metadata) and GGUF (aligned, zero padding only, no
  unused bytes) before reading.
- accelerate removed from requirements.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: describe weight_loader instead of Accelerate in comments and docs (#6471)

Comments and docstrings that named Accelerate as the loading / hook / offload
mechanism now describe gptqmodel.weight_loader (AlignDevicesHook, CpuOffload,
WeightLoader, offload store). Markdown no longer says GPT-QModel loads through
Accelerate, and docs/weight-loader.md documents the Placement language (accel:N,
accel:auto, cpu>/disk> offload, ranges, resolution rules), the plan_layers /
plan_budget / accel:auto policies, the device_map mapping, WeightLoader
load/place/dispatch and the checkpoint safety rules. No executable code changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* weight_loader: targeted, lifetime-bound partial mmaps instead of whole-shard maps (#6471)

safe_open (and Accelerate on top of it) maps an entire shard, and every tensor it
returns pins that mapping, so loading one layer of a multi-layer shard kept all of
it mapped into later loads -- the reason LazyTurtle exists.

weight_loader.reader reads tensors by the exact byte ranges of the validated header:
- each mmap covers one group (default: one leaf module) and nothing else;
- CPU tensors kept at their stored dtype are zero-copy views of their window, and
  the kernel unmaps the window when the last of them is freed (layer moved to an
  accelerator, replaced or dropped);
- accelerator / cast reads copy out and unmap at once; oversized copies stream
  through bounded windows;
- WeightLoader.load(..., modules=[...]) loads one module subset, read()/read_checkpoint
  expose raw tensors, OffloadedWeightsLoader safetensors references use the same reader.

Measured on a 16-layer shard: safe_open keeps the full file mapped for one tensor;
the reader maps exactly the live layers and 0 bytes once they are freed or on GPU.

Also fixes import-order lint left by the migration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* tests: drop accelerate; exercise gptqmodel.weight_loader instead (#6471)

- Every test that imported accelerate now uses gptqmodel.weight_loader (hooks,
  offload store, init_empty_weights, load_checkpoint_in_model, ...). A small
  tests/offload_test_utils.cpu_offload rebuilds the CPU-offload hook layout the
  tests relied on; dispatch_model's disk case goes through WeightLoader.place.
- References to the deleted gptqmodel.utils.offload_hooks move to the
  weight_loader hooks; the no-cache-flush test now asserts weight_loader hooks
  never call clear_device_cache / empty_cache.
- Dense-load tests assert transformers never receives a device_map; placement is
  recorded at _place_hf_loaded_model.
- New tests/test_no_accelerate_dependency.py: imports and a dense cuda:0 load +
  generate with accelerate blocked, plus static checks that gptqmodel/ (outside
  ports) has no accelerate import and requirements do not list it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* weight_loader: file-backed modules (meta/hook-free disk offload primitive) + store fixes (#6471)

file_back_module(module, path) writes a module's tensors to an exact-tiling,
naturally aligned safetensors file (atomic, no NumPy) and rebinds each tensor as a
zero-copy view of a targeted mmap of it. The module stays a normal module: no meta
placeholders, no offload hooks, no restore step; its memory is clean page cache
(evict=True drops it right away) and the mapping dies with the tensors. Ties,
Parameter class/attributes and requires_grad are preserved. This is the building
block for retiring LazyTurtle and utils/offload.py.

Fixes:
- offload store accepts os.PathLike paths (torch.from_file needs str).
- disk-offloaded tensors keep the checkpoint's stored bytes/dtype in the offload
  file; only the meta slot takes the final dtype (unchanged offload format).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* weight_loader: lint

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Route every safetensors read through weight_loader.safe_open; harden file-backed modules (#6471)

weight_loader.safe_open is a drop-in for safetensors.safe_open (keys/get_tensor/
get_slice/metadata) over validated, targeted, lifetime-bound mmaps: each
get_tensor maps only that tensor (>= 1 MiB CPU tensors are zero-copy views
released with the tensor, smaller ones are copies), get_slice on leading rows maps
only those rows, and a failed mmap (vm.max_map_count) falls back to a copy.
All 15 gptqmodel modules that imported safetensors.safe_open -- LazyTurtle
(utils/structure.py), writer, model/model_dequant, looper checkpoint/input-cache
spools, gguf packaging, ... -- now use it, so no code path maps a whole shard.

file_back_module, per the offloader review:
- reserve space with posix_fallocate before writing through the mapping, so a
  full disk raises OSError instead of SIGBUS;
- rebuild views under inference_mode(False) (finalizer threads, #4572);
- root= rebinds aliases outside the module (tied lm_head);
- default granularity 'file' (one mapping per file-backed module);
- dtypes without a safetensors name (FNUZ float8) are stored as raw words with
  the dtype recorded in __metadata__; tensor attributes are kept on buffers too.

AGENTS.md: replace the stale GPTQModelAlignDevicesHook reference and state the
weight_loader rule (no device_map to Transformers, no whole-file mmaps).

Validated: lazy-load smoke test (skill gptqmodel-lazy-load-smoke-testing) passes
with accelerate blocked; 0 bytes of the source shard mapped after load/quantize.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Isolate Transformers from Accelerate in GPT-QModel processes (#6471)

Traced with Accelerate installed: GPT-QModel paths made no Accelerate function
calls, but Transformers imported it (integrations/accelerate.py:50) and kept
Accelerate-bound names on GPT-QModel's paths: modeling_utils.add_hook_to_module
(resize_token_embeddings on any _hf_hook module), extract_model_from_parallel
(unwrap_model), generation.utils AlignDevicesHook/add_hook_to_module (generate
with hf_device_map). Without Accelerate, from_pretrained(gguf_file=...) refused to
run at all, breaking GPT-QModel's dense GGUF import on this branch.

gptqmodel/_accelerate_isolation.py, installed by import gptqmodel before any
Transformers modeling module loads:
- Transformers sees is_accelerate_available() == False, so it never imports
  Accelerate (and never calls it if something imported Transformers first);
- the Accelerate-shaped names are bound to gptqmodel.weight_loader equivalents;
- modeling_utils reports those helpers bound, so its GGUF guard and unwrap_model
  run on GPT-QModel code.
Result with Accelerate installed: 0 Accelerate imports and 0 calls across dense
load, 2-GPU dense, quantized load+generate+save and quantize->save->reload->generate.

This is a maintainer-sanctioned exception to the no-patching rule: AGENTS.md
documents it, and tests/test_transformers_unpatched.py allow-lists exactly
PATCHED_BINDINGS. tests/test_accelerate_isolation.py: 6 cases, all red with the
isolation disabled, green with it.

Also fixes test_resave_missing_modules_4452, which still monkeypatched
model_utils.accelerate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Offload finalized modules as file-backed tensors instead of meta + hooks (#6471)

offload_to_disk keeps its signature, lock, meta/empty skips and the <4 KiB CPU
move (#6180), but no longer writes a state_dict bundle, replaces tensors with meta
or attaches AlignDevicesHook(offload=True):
- a changed module is written to offload/<name>/filebacked.safetensors (live
  layout, so no GPTQ v1/v2 qzeros round trip, #4380) and rebound as zero-copy
  views of it; aliases are rebound model-wide (tied lm_head, #4597);
- a module still byte-equal to the source checkpoint (#4395/#4463) is rebound to
  views of the source shard, nothing written; modules whose state_dict re-encodes
  live tensors never take this path;
- the backing file is not named module.safetensors, so checkpoint capture can
  never reuse a live-layout file as a checkpoint bundle;
- has_disk_offloaded_modules counts file-backed modules, so the run root outlives
  them (#4807).
Checkpoint resume loads restored packed modules with load_state_dict(assign=True)
from weight_loader.safe_open views of the artifact (module's own layout
conversion) and materializes meta non-persistent buffers (#4777, #4562) instead of
attach_disk_offload_hook.
write_safetensors only fsyncs when durable=True: a sync per module cost +40%
quantize wall time.

Llama-3.2-1B GPTQ 4-bit, offload_to_disk=True, branch vs main (2 repeats):
quantized checkpoint bit-identical (482 tensors), same generation, wall time equal
(131.4 vs 131.2 s); peak RSS after load 1.04 vs 1.40 GiB, quantize peak 2.60-2.90 vs
3.04-3.08 GiB, after save 3.02-3.07 vs 3.08-3.12 GiB. All 71 file-backed tensors are
still live views of their files after quantize.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* tests: pin file-backed offload instead of meta + hook offload (#6471)

Migrate the offload families to the file-backed offloader's observable state:
modules are file-backed (FILE_BACKED_ATTR -> offload/<name>/filebacked.safetensors,
or "source" when rebound to the untouched source checkpoint), tensors are real
CPU views of the backing file, no meta placeholders and no offload hooks.
Guarantees kept with independent expected values: forward equals pre-offload and
live v2 qzeros are kept while state_dict() still emits checkpoint v1 (#4380);
a forced offload runs no qzeros conversion (#5850); round trip through
GPTQModel.load from the file-backed model's state_dict; size threshold; tied
embedding/head rebound together (#4203); loader dispatch hooks untouched (#6156);
in-session model CPU/no hooks/movable/class forward, survives run-dir removal
(#4450); cancelled/failed runs keep file-backed layers and their run dir
(#4807/#4860); source reference writes nothing and maps the source, falls back on
a 1-byte diff, sharded sources (#4395/#4463); run dir lifecycle (#4368); run
namespaces; ERNIE hook-end release; Pangu last-layer replay (#5135).
Writer offload-index tests now build their safetensors/unhashed fixtures with the
store APIs (offload_to_safetensors_reference / disk_offload).

Removed (only asserted the old mechanism): 4450
test_restore_reports_modules_it_cannot_materialize (strict failure of the hook
restore, which nothing produces any more) and
test_resumed_packed_module_hook_is_materialized_at_loop_exit (attach_disk_offload_hook;
resume is covered by the checkpoint-resume families).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* WIP: GPT-QModel stops consuming Accelerate's device_map; placement= is the only placement input (#6471)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* tests: resume restores file-backed modules equal to their artifacts (#6471)

test_quantized_tensors_equal_after_resume asserted restored packed modules are
meta, a property of the removed hook-based resume path. It now asserts the new
state -- no meta, no offload hook, state_dict() exactly equal to the checkpoint
artifact read with upstream safetensors -- and keeps the end-to-end guarantee
that resumed and completed runs are tensor-identical to the baseline (5 variants
pass; they were masked by the meta assertion).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Describe placements instead of device_map in kernel comments (#6471)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Strict everywhere: port Accelerate-dispatch tests to GPTQModel placement; document breaking changes (#6471)

- #6396/#5022/#6274/#6157/kimi-k3: the device_map='auto' + max_memory/offload_folder
  scenarios now load through GPTQModel.load(placement=...) (Placement.budget,
  cpu>accel:0, disk>cpu + offload_dir) or WeightLoader.place, keeping their value
  assertions (exact clean-checkpoint logits for #6157, resident-equal logits for
  the offload cases, the repaired A_log payload/forward/resave for kimi-k3).
- Removed only the HF-bridge-internal assertions with no GPT-QModel-path
  equivalent: the Marlin CPU-offload snapshot repack (#5022) and the
  _HF_DEFER_SYM_QZEROS flag checks (#6274).
- New: plain Transformers from_pretrained(device_map / max_memory / offload_folder)
  on a GPT-QModel checkpoint in a gptqmodel process raises 'requires accelerate'.
- Fix: disk> placements count as offload for from_quantized (kernel selection and
  the post-load meta check), matching #5194.
- docs/weight-loader.md: Breaking changes section.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Address code-quality review on #6473

- weight_loader/reader.py: explain why a rejected madvise read-ahead hint is
  ignored instead of an empty except.
- tests: import gptqmodel.utils.model / gptqmodel.weight_loader one way per file
  (module alias) in test_qwen4_exp_support, test_fp8_load_peak_4387 and
  test_offload_hooks_no_cache_flush.
(The unused param in weight_loader/tensors.py was already removed.)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Dispatch rules on a ModuleList/ModuleDict to its children (#6471)

A container's forward never runs, so an execution hook on it never fired: a
rule like {'model.layers': 'cpu>accel:0'} left every layer on CPU while its
inputs were on the accelerator. simple_dispatch_model expands container entries
per child and WeightLoader.dispatch hooks the children. Regression test is red
without the fix. Also: #5022/#6274 ported tests use the portable kernel as the
numeric oracle and a CPU-kernel tolerance.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* tests: pin file-backed resume/offload state in the remaining checkpoint tests (#6471)

Branch-vs-main diff of the regression suite (same environment) left 19 branch-only
failures, all assertions of the removed meta + hook mechanism:
- checkpoint bias / AWQ scale dtype restore (#4324, #6153): read offload
  index.json; now compare the restored tensor and its dtype with the artifact
  read independently.
- test_checkpoint_scale_dtype: monkeypatched model_utils.accelerate.
- multi-GPU partial Hessian recovery (14 cases): telemetry expected restored
  packed tensors on meta; they are file-backed CPU tensors (storage still disk).
- test_transformers_unpatched: offload expected an AlignDevicesHook; file-backed
  offload installs none.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Restore pass reads the same safetensors checkpoint as WeightLoader, never a pickle (#6471)

_restore_checkpoint_buffers still resolved a directory like Accelerate
(pytorch_model.bin first) and torch.load-ed it, so with both files present the
restore read a different, pickle checkpoint than the main WeightLoader load.
It now resolves exactly like weight_loader.checkpoint_files and refuses
non-safetensors files. Tests: the pickle reload case asserts the refusal; the
directory-resolution test pins safetensors over a decoy pickle; the LazyTurtle
conversion fixture no longer passes a device_map.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* accel:auto binds to CPU without a visible accelerator; fix TTNN placement coercion (#6471)

- accelerator_type() is None when the build's accelerator has no visible device
  (#6165: current_accelerator() reports the wheel's backend at device_count 0).
- accel:auto on such a host binds the subtree to CPU, so a plain dense
  GPTQModel.load(path) keeps working on CPU-only machines; explicit accel:N still
  raises.
- _resolve_native_ttnn_placement coerces a placement mapping before reading chips.
- test_accel_auto_balances pins equal free memory (was flaky on shared GPUs).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* tests: last branch-only regressions after the placement merge (#6471)

Full-suite diff, merged branch vs origin/main (44a08b8), same environment:
main 60 failed / 1669 passed, branch 56 failed / 1732 passed; 6 main-only failures
(HF-bridge offload tests now ported to placement=), 2 branch-only, fixed here:
- test_loader_offload_staging_4385: pins offload_dir= forwarding and that
  Accelerate's offload_folder / offload_state_dict / offload_buffers raise.
- test_resave_missing_modules_4452: monkeypatch the renamed
  _load_with_weight_loader.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Disallow pickle weight sources; delete LazyTurtle's .bin conversion cache (#6471)

Maintainer decision: quantization from pickle-only sources is dropped.
- utils/artifact_security.validate_tensor_files: a checkpoint whose tensor source
  is only .bin/.pt/.pth/.ckpt (or a pickle shard index) raises
  UnsafeModelArtifactError 'convert the checkpoint to safetensors first'. A pickle
  file next to safetensors weights is ignored and never unpickled (every
  GPT-QModel reader and Transformers' default load the safetensors files).
- utils/structure.py: delete LazyTurtle's pickle -> safetensors conversion cache
  (refcounted leases, path locks, atexit cleanup, full HF reload + re-save; -353
  lines) and its offload_path / close() plumbing; a pickle-only source raises
  UnsafeCheckpointError.
- utils/tt_blockfloat_quant.py: the legacy blockfloat.pt payload is refused, not
  torch.load-ed.
Tests: conversion-cache / conversion-mapping tests removed with the feature;
tests/test_pickle_sources_refused.py pins refusal (with torch.load made to fail,
proving nothing is unpickled) and the mixed-directory case; the tenstorrent and
artifact-security legacy-payload tests now assert refusal; the #4941
tokenizer-flag tests use a safetensors source. Same-file-set diff against the PR
head: the only new failures were these intended ones, now migrated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Replace LazyTurtle with weight_loader CheckpointSource (#6471)

LazyTurtle (utils/structure.py, ~3.3k lines) is removed; no compat names.
- weight_loader/session.py  CheckpointSession: one selected checkpoint opened
  once: shard map, shard-path containment, eager header validation, targeted
  reads (replaces LazyTurtle._load_weight_map/_checkpoint_shard_path and
  base.py's _QuantizedCheckpointSource).
- weight_loader/translate.py  CheckpointTranslator: LazyTurtle's resolution
  logic moved unchanged (HF v5 reverse conversion maps, scoped renamings,
  module_tree MoE aliases, definition aliases, fused experts, Chunk/Interleave,
  ERNIE, concat/MergeModulelist, zero-pad rows, tie-partner fallback #5399,
  precedence intact); plan_tensor() returns TensorPlans.
- weight_loader/plan.py  TensorPlan + execute(): the tensor ops (select, split,
  interleave, chunk, transpose, assemble, zero-pad, MiMo decode, shape check),
  same error messages, prefix CheckpointSource:.
- weight_loader/source.py  CheckpointSource (session + translator): materialize
  submodule / direct meta / whole shell, raw tensors for floatx/MX decoders,
  tie snapshot with lock-first init order (#4799/#4973), native-fp32 slots,
  init-only buffer templates, no-placement params, publish-before-swap (#5088).
- Deleted: active-source staging, shard-layout warning, LazyTurtle-only
  mmap/release bookkeeping. BaseQModel.turtle_model -> checkpoint_source;
  LazyTurtle.maybe_create -> CheckpointSource.from_checkpoint; writer uses the
  public weight_map/root/index_filename/resolve_* API.
- Tests migrated (API names only); obsolete staging/layout-warning tests removed.
- TEMPORARY (removed in the next commit): tests/_lazy_turtle_reference.py,
  tests/_checkpoint_source_differential.py plugin and
  tests/test_checkpoint_source_differential.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Remove the temporary LazyTurtle differential harness (#6471)

CheckpointSource was run side by side with LazyTurtle frozen at 8f47028:
- every migrated LazyTurtle/structure test family under the comparison plugin:
  21,973 identical comparisons (init weight maps, conversion renamings and
  converters, tie snapshots, every resolver call, materialized submodules /
  direct-meta / sync_all_meta / raw decoder tensors incl. raised errors);
  1 difference, from a test that monkeypatches the new instance's
  _materialize_direct_meta_tensors to a no-op (not seen by the reference);
- real checkpoints (Llama-3.2-1B, tied-head Qwen2.5-0.5B, fused-expert
  Qwen3-30B-A3B first two layers + every non-layer module): 54 materialized
  modules and 1,233 tensor resolutions, 0 differences.
The migrated family tests remain the permanent guard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* tests: lazy checkpoint memory contract bounds mapped bytes, not mapping count (#6471)

The contract is: no whole-file mapping held across finalized layers, bounded host
RSS. weight_loader keeps a byte-equal base module (Llama-3.2's tied embedding) as a
targeted view of its own 501 MiB instead of rewriting it, so 'zero mappings' no
longer stands for that contract. Assert live mapped bytes <= the largest checkpoint
tensor (+2 pages) and < the file size; the RSS bound is unchanged.
Measured (layers 0-3): RSS 2.399/2.402/2.402/2.402 GiB vs main 2.889/2.402/2.402/2.403.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Qubitium added a commit that referenced this pull request Dec 1, 2026
…gain (#6528)

#6473 replaced device_map={'': 0} with from_pretrained().to('cuda:0').
Without a device_map the HF bridge selects the kernel on CPU, so the
test never reached MarlinLinear (the #6274 path) and failed. Restore the
device_map spelling, gated on the now-optional accelerate.

Fixes #6527

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment