Repository navigation
fix(hf): packable selection, per-layer shape dispatch and legacy qzeros in the HF bridge (#6191, #6178, #6336) - #6274
Conversation
|
Merge-order note: this PR and #6253 (the 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 applies cleanly with both lines ( |
91dcfb4 to
f16b3e2
Compare
|
Rebased onto |
f16b3e2 to
be702ac
Compare
… 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.
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.
|
Blocking defect found in the consolidation; fixed in
before Reproduced on a legacy-marked checkpoint (
The fix skips the rebuild for a kernel that does not own a New I also split Verification at
|
`_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.
3640e9b to
f6f7b06
Compare
|
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 (
Traceback: Mechanism, instrumented on main + #6253 + #6274: for every offloaded layer
On Proposed fix (in #6253's owner code, not this PR): Reproduction is 12 lines (tiny 1-layer Llama, Note the two PRs are interdependent in both directions: #6253's Separately, #6253's marker preservation ( |
|
Correction / status on my earlier "blocking" note — #6253 now carries the fix, and my fixture was partly invalid.
|
`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.
…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]>
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]>
…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]>
…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]>
Summary
Consolidates #6345 (
fix/6336-perf) into this branch. It now carries all three HF-bridge fixes:GPTQConfig(backend="marlin")/"exllama_v2"calibrates every layer and then crashes at pack ("cannot pack quantized weights"), becausehf_select_quant_linear_v2(pack=True)returns the inference-only kernel #6191 — pack with a kernel that can actually pack when the HF bridge is asked to quantize for an inference-only backend (Marlin, ExLlamaV2).ModelCloud/Granite-4.0-H-350M-GPTQMODEL-W4A16) no longer load: legacyqzeroswidth for out_features % 32 != 0 is rejected #6178 — accept pre-fix(qlinear): size GPTQ buffers by pack_factor and skip Laguna g_proj quantization #2983 GPTQ checkpoints whoseqzerosuse the legacy floor width (out_features // 32 * bits), and reject legacy asymmetric/planar/non-2-4-8-bit checkpoints with a clear error.from_pretrainedof every grouped GPTQ checkpoint on CUDA now getsTorchLinearinstead ofMarlinLinear(decode ~1.3-2.5x slower, prefill ~1.5-2x slower) #6336 — keep the already-selected AUTO kernel for group-aligned layers on plain-HF loads; only a partial-group layer gets the auto-paddingTorchLinear.Fixes #6191, #6178, #6336
How
pack=Truevspack=Falseresolve nowBoth entry points share one selection body; the pack flag decides which branch is authoritative.
pack=True(quantizing)_hf_pack_backend()resolves the requested backend. A pack-capable backend is kept. An inference-only backend (Marlin, ExLlamaV2, ...) is validated once withselect_quant_linear(..., pack=False)so a real contract mismatch (for examplebits=3for Marlin) still raises before calibration; then it warns and returnsBACKEND.AUTO. The savedquantization_configstill records the requested backend, so a reload selects it for inference.select_quant_linear(..., pack=True)runs with the resolved backend. AUTO's pack gate keeps only kernels with a pack API._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 withpack=True, so both concrete classes remain packable. The legacyqzeroswrapper never runs on this path (it is load-only).Net:
pack=Truealways 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)_hf_pack_backend()returns the backend unchanged.ShapeAware<AutoKernel>:in_features % group_size == 0builds the AUTO kernel (MarlinLinearon CUDA,TorchCpuAvx512Linearon CPU), while a partial group (or an unknown width) builds the auto-paddingTorchLinear.7.3.4(or carries the legacyv2/v2_alphamarkers), the legacyqzeroswrapper is applied to both concrete kernels before the dispatcher is built, so the floor-width deferral is preserved on either width branch.Net:
pack=Falsekeeps 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=FalseAUTO path still performs exactly 2select_quant_linearcalls 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=Truewith 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
gptqmodel/utils/importer.py:_ShapeAwareKernelMeta,_shape_aware_gptq_kernel()and_shape_safe_gptq_selection()were carried over. The only adaptation is the pack-aware call signature and an optionalwrap_kernelhook so [BUG] loader/HF bridge: GPTQ checkpoints saved by GPT-QModel before #2983 (e.g. publishedModelCloud/Granite-4.0-H-350M-GPTQMODEL-W4A16) no longer load: legacyqzeroswidth for out_features % 32 != 0 is rejected #6178's legacyqzerossubclass can be applied to both dispatcher branches.tests/test_hf_bridge_grouped_load_cost_6336.py: new file, unchanged from fix(hf): keep the AUTO kernel for group-aligned layers on plain-HF loads (#6336, #6332, #6334) #6345.tests/test_hf_bridge_missing_shape_6149.py: per-layer contract from fix(hf): keep the AUTO kernel for group-aligned layers on plain-HF loads (#6336, #6332, #6334) #6345, unchanged.tests/test_hf_packing_api.py:test_hf_bridge_forwards_in_features_to_kernel_validationnow asserts fix(hf): keep the AUTO kernel for group-aligned layers on plain-HF loads (#6336, #6332, #6334) #6345's per-layer contract; fix(hf): packable selection, per-layer shape dispatch and legacy qzeros in the HF bridge (#6191, #6178, #6336) #6274's pack/inference assertions are kept alongside it.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 singlebackendfield:pack=False(load/inference): unchanged; the explicit backend is honoured.pack=Truewith a packable explicit backend: unchanged.pack=Truewith an inference-only kernel (Marlin, ExLlamaV2, ...): warn and pack with the method default (AUTO). The savedquantization_configstill records the requested backend, so reload selects it for inference.select_quant_linear(..., pack=False)), so an unsatisfiable contract (e.g.bits=3for Marlin) raises its clear error before calibration instead of packing a checkpoint the saved config cannot load.hf_select_quant_linear()andhf_select_quant_linear_v2()build the selection kwargs once, resolve the backend through that helper, recomputecpu_offloadfor the resolved backend, and select.#6178 — legacy floor-width
qzerosgptqmodel/nn_modules/qlinear/__init__.pylegacy_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 runtimeqzeros(TorchAten/TorchFused int4pack offsets) are untouched.qzeros_symmetric_word()/qzeros_word_for_dtype(): the packed constant for 2/4/8-bit and its signedtorch.fullvalue.GPTQQuantLinear._prepare_legacy_qzeros_state_dict()(called from_load_from_state_dict_locked) pads a legacy symmetricqzerosbefore the copy.sym=False, planar, or non-2/4/8-bit legacy checkpoints raise a clearlegacy pre-#2983 GPTQ qzeros layouterror.qzerosfrom 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_alphameta, ormeta.quantizer = gptqmodel:<version>older than7.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 symmetricqzeros. 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 symmetricqzerosin the kernel's target runtime layout beforegptqmodel_post_init.#6336 — per-layer shape dispatch
gptqmodel/utils/importer.py:_shape_aware_gptq_kernel()returnsShapeAware<AutoKernel>— a subclass of the already-selected AUTO kernel whose__new__readsin_featuresand dispatches;kernel_for_width()is one modulo test.__instancecheck__keeps Optimum'sisinstance/get_layersworking 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'stests/directory withPYTHONPATH=<clone>:<clone>/tests.Target suite (both PRs' files plus the adjacent bridge regression):
118 passed, 11 skipped(all skips are pre-existing CUDA-device gates).Broader affected set:
395 passed, 75 skipped.Lint
Files
gptqmodel/utils/importer.pygptqmodel/nn_modules/qlinear/__init__.pygptqmodel/utils/model.pytests/test_hf_packing_api.pytests/kernels/test_qlinear_hierarchy.pytests/test_checkpoint_interop_4053.pytests/test_hf_bridge_grouped_load_cost_6336.pytests/test_hf_bridge_missing_shape_6149.pySkips / unverified
ModelCloud/Granite-4.0-H-350M-GPTQMODEL-W4A16) no longer load: legacyqzeroswidth for out_features % 32 != 0 is rejected #6178.isinstancecoverage), not the benchmark.Head
9c647ac7e777bbb54cb4bf2afb7d7a94e500c986onfix/hf-bridge-layout-consolidated.