Repository navigation
Remove accelerate: explicit WeightLoader for weight loading, placement and offload (#6471) - #6473
Merged
Merged
Conversation
… 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]>
…nt, 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]>
27 tasks done
…cs (#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]>
…e-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]>
- 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]>
…tive) + 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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
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]>
…oks (#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]>
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]>
…s the only placement input (#6471) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
Conflicts resolved: - utils/internal_gguf.py: take main's fail-closed GGUFReader (#6475), which now rejects gaps, overlaps, trailing data and nonzero alignment padding itself; drop this branch's header_end hook. weight_loader.safety.validate_gguf maps the reader's UnsafeModelArtifactError to UnsafeCheckpointError. - utils/hf.py, utils/structure.py: keep both sides' imports (weight_loader init_empty_weights / safe_open + main's artifact_security, assert_source_read_allowed). - models/loader.py: main moved get_model_local_path after the checkpoint selection; keep main's call and re-attach the GGUF safety check after it. - models/writer.py: take main's rewritten export-shell qzeros block; keep the weight_loader.safe_open import. Tests: GGUF rejection tests accept main's reader wording; the GGUF policy test's HF-loader stub is now a real (empty) nn.Module because the dense load places it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- 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]>
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]>
…nt 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]>
…ever 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]>
…ment 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]>
…vice_map (#6471) User directive: no backward compatibility, no Accelerate device_map. - GPTQModel.load / from_pretrained / from_quantized take placement= (a Placement, a target string such as accel / accel:auto / accel:N / cpu>accel:0 / disk>accel:0, a rules dict, or Placement.budget({...})); device= accepts accel:N. device_map / max_memory / offload_folder / offload_state_dict / offload_buffers raise TypeError naming the replacement; nothing is translated. - Deleted: Placement.from_device_map, the Accelerate-ABI load_checkpoint_in_model shim (load_into_existing replaces the copy-into-slots case), keyword maps, bare-int ordinals, cpu-means-offload dicts, _int_ordinal_device_map, the positional Accelerate calling convention, offload_state_dict staging. Accelerate's vocabulary remains only in hf_normalize_device_device_map, the entry Transformers/Optimum call with their own device_map. - Strict everywhere (maintainer decision): in a GPT-QModel process Transformers' own device_map loads raise; the five HF-bridge dispatch tests now load through GPTQModel.load(placement=...) with their value checks, and a new test pins the Transformers error. docs/weight-loader.md: public API + breaking changes. - Fixes found on the way: ModuleList/ModuleDict rules dispatch to children (their forward never runs); dense default binds accel:auto (was silently CPU); tied groups co-located on bind; mps/mps:0 and cpu/cpu:0 equal; disk> counts as offload (#5194); restore pass reads the same safetensors file as the loader, never a pickle; accel:auto on CPU-only hosts; accelerator_type() with zero visible devices (#6165); TTNN placement coercion. Conflicts: writer/structure/offload imports and lines (keep main's require_weights_only, the file-backed offload driver); tests use the new API via the module-alias import style from the code-quality review. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
Qubitium
marked this pull request as ready for review
November 30, 2026 07:37
…ache (#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]>
3 tasks done
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
…hells (#6517) (#6518) Since #6473 offload_to_disk leaves finalized modules as file-backed CPU views of the run directory: no meta placeholders and no offload hooks. The gptq-offload nodes still looked for meta modules carrying _hf_hook and required has_disk_offloaded_modules() to be false after success, so they failed on a correct model. Assert the documented state instead: no meta leaves, every file-backed module's backing file exists under the run root, and the gptq-offload control actually produced file-backed modules. Co-authored-by: Claude Opus 5.5 <[email protected]>
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
…ssion (#6523) (#6524) save_quantized_embeddings needs a source with root/weight_map since #6473 (requantize records a CheckpointSession). The tests still passed a LazyTurtle-shaped SimpleNamespace, so six nodes raised 'Module replacement save requires a checkpoint source'. Co-authored-by: Claude Opus 5.5 <[email protected]>
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
#6525) (#6526) #6473 replaced the Accelerate hook import in the vendored gemma3n and gemma4 modeling files with gptqmodel.weight_loader.add_hook_to_module without recording the edit, so MANIFEST.json still pinned both files as verbatim and a re-vendor would restore the Accelerate import. Re-record with vendor_transformers_ports.py --all --record-patches. Fixes #6525 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]>
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
GPTQModel.load/from_pretrained/from_quantized raise TypeError for device_map= since #6473, but the DeepSeek-V4.1 examples still passed it and two multi-GPU paragraphs still recommended it. The examples are skip-listed (101B download), so nothing executed them. - Use placement="accel" in the three DeepSeek-V4.1 examples and refresh their NOT_EXECUTED_BLOCKS digests. - Point the multi-GPU prose at placement= and docs/weight-loader.md. - Add a static guard over every docs/README Python block (executed or skip-listed) that rejects Accelerate placement keywords on GPT-QModel loaders, plus a check that each loader really raises TypeError for each removed keyword. Fixes #6507 Co-authored-by: Claude Opus 5.5 <[email protected]>
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
…oads (#6541) (#6543) #6473 moved the V4.1 Placement.budget path from Accelerate's infer_auto_device_map to utils.vram.compute_module_sizes, whose dtype_byte_size raised for int8/uint8 (and int64/float64). V4.1 keeps its packed payloads and scales in those dtypes, so every budget load raised ValueError before placement. Fall back to the dtype's element size for any other torch dtype. Co-authored-by: Claude Opus 5.5 <[email protected]>
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
…#6544) #6473 changed _hf_bridge_load to from_pretrained().to(device). The HF bridge selects kernels for the load device, so a pinned Marlin/ExLlamaV2 checkpoint was rejected on the CPU load before .to() ran, and the runtime-layout save refusal (#6137) was never reached. Use device_map for accelerator targets (requires optional accelerate) and keep CPU loads unchanged. Fixes #6542 Co-authored-by: Claude Opus 5.5 <[email protected]>
4 tasks done
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
…6545) (#6546) #6473 moved _save_module_replacement_safetensors onto CheckpointSource (root, weight_map); the test still built the old turtle namespace. Fixes #6545 Co-authored-by: Claude Opus 5.5 <[email protected]>
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
… LazyTurtle (#6551) #6473 replaced LazyTurtle with CheckpointSource and deleted its tests, but scripts/profile_lazy_turtle_lifecycle.py still imported it and crashed on import, failing three test_cli_entry_points nodes. Fixes #6550 Co-authored-by: Claude Opus 5.5 <[email protected]>
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
This release carries breaking changes (Accelerate removed and placement= replacing device_map= in #6473, pickle checkpoints refused, sccache >= 0.18 for JIT builds, model-owned attention-sink defaults in #6500) and many new features, so it is a minor release per the rule in version.py, not the 7.12.4 patch number main carried. Co-authored-by: Claude Opus 5.5 <[email protected]>
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
…6539) (#6564) Weight-only finalize (RTN/SINQ/GGUF ...) hands file_back_module tensors that were created under inference_mode and rebound with param.data = ... (the #4572 state: not inference, but no version counter). The #6473 writer serialized them through reshape/view, which raises 'Inference tensors do not track version counter', so quantize() crashed with the default offload_to_disk=True. Copy such a tensor once before taking its byte view. Fixes #6539 Co-authored-by: Claude Opus 5.5 <[email protected]>
This was referenced Dec 1, 2026
Merged
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
…lity remedy (#6569) (#6572) The refusal for a quantized placement spanning GPU compute capabilities told users to pass a max_memory budget, which GPTQModel.load rejects with TypeError since #6473. Name placement=Placement.budget({...}) and keep max_memory scoped to the Transformers bridge that shares the text. Co-authored-by: Claude Opus 5.5 <[email protected]>
This was referenced Dec 1, 2026
Merged
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
…tes (#6610) write_safetensors flushed its mmap (msync MS_SYNC) on every call, durable or not. Disk offload backs every module with an in-session file, so each offloaded module blocked the quantization thread on the disk: RTN on Qwen2.5-0.5B spent 7.6 of 12.4 s in 168 mmap.flush calls (pre-#6473: 3.6 s). The page cache already serves every reader of the file and the kernel writes it back on its own, so only a durable write needs the flush. Co-authored-by: Claude Opus 5.5 <[email protected]>
11 tasks done
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
`file_back_module` keeps a zero-copy mapping of each offloaded module for the
rest of the run, and the checkpoint reader keeps one mapping per module group
for CPU-placed models. Python's `mmap` duplicates the mapped file descriptor
unless the caller passes `trackfd=False` (3.13+), and that duplicate stays open
until the mapping is closed, so a 64-expert MoE opens thousands of descriptors
and hits the default soft `RLIMIT_NOFILE` of 1024:
OSError: [Errno 24] Too many open files
.../weight_loader/reader.py:331
Bisect: the pre-#6473 parent (aff56aa) completes OLMoE GPTQ at 1024; #6473
(0043349) introduced the per-module file-backed offload.
Add `gptqmodel/utils/fd_limit.py`:
- `map_file_window(fd, length, offset=0, access=ACCESS_COPY)` asks `mmap` for
an untracked mapping when the interpreter supports it. The mapping still
keeps the file data alive after the caller closes the fd; only the duplicate
descriptor is gone.
- `ensure_nofile_limit()` is the Python 3.11/3.12 fallback where `trackfd`
does not exist: it raises the soft `RLIMIT_NOFILE` to the hard limit (only
ever raises, logs once at debug) and warns once, naming `ulimit -n`, when the
hard limit is still below 4096.
Use the helper at every `mmap.mmap` site in `weight_loader/reader.py` (3) and
`weight_loader/filebacked.py` (1), and call `ensure_nofile_limit()` once at
the start of `GPTQModel.load`, `GPTQModel.from_quantized` and
`BaseQModel.quantize` (a no-op on 3.13+).
The offload format, mapping lifetimes, read order and tensor values are
unchanged; `close()`, `flush()` and `madvise()` do not need the tracked fd and
there are no `size()`/`resize()` calls on these mappings.
This replaces the per-layer offload bundle from the first revision of the PR:
bundling forced a synchronous finalize drain, raised host RSS up to ~2x on
Qwen2.5-0.5B, and still failed for a layer with >~1000 modules.
Tests: `tests/test_offload_fd_bound.py` now exercises the offload write path
(GPTQ, RTN) and a quantized-checkpoint load at a deterministic soft limit of
256; all three fail with EMFILE on main and pass here. A fourth test disables
the trackfd capability and asserts the rlimit fallback raises only the soft
limit. GPU A/B on OLMoE-1B-7B (GPTQ, RTN) and Qwen2.5-0.5B (GPTQ, AWQ) is
bit-identical to main at 65536 with the branch at 1024, and host RSS peak is
unchanged.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
#6659) `file_back_module` keeps a zero-copy mapping of each offloaded module for the rest of the run, and the checkpoint reader keeps one mapping per module group for CPU-placed models. Python's `mmap` duplicates the mapped file descriptor unless the caller passes `trackfd=False` (3.13+), and that duplicate stays open until the mapping is closed, so a 64-expert MoE opens thousands of descriptors and hits the default soft `RLIMIT_NOFILE` of 1024: OSError: [Errno 24] Too many open files .../weight_loader/reader.py:331 Bisect: the pre-#6473 parent (aff56aa) completes OLMoE GPTQ at 1024; #6473 (0043349) introduced the per-module file-backed offload. Add `gptqmodel/utils/fd_limit.py`: - `map_file_window(fd, length, offset=0, access=ACCESS_COPY)` asks `mmap` for an untracked mapping when the interpreter supports it. The mapping still keeps the file data alive after the caller closes the fd; only the duplicate descriptor is gone. - `ensure_nofile_limit()` is the Python 3.11/3.12 fallback where `trackfd` does not exist: it raises the soft `RLIMIT_NOFILE` to the hard limit (only ever raises, logs once at debug) and warns once, naming `ulimit -n`, when the hard limit is still below 4096. Use the helper at every `mmap.mmap` site in `weight_loader/reader.py` (3) and `weight_loader/filebacked.py` (1), and call `ensure_nofile_limit()` once at the start of `GPTQModel.load`, `GPTQModel.from_quantized` and `BaseQModel.quantize` (a no-op on 3.13+). The offload format, mapping lifetimes, read order and tensor values are unchanged; `close()`, `flush()` and `madvise()` do not need the tracked fd and there are no `size()`/`resize()` calls on these mappings. This replaces the per-layer offload bundle from the first revision of the PR: bundling forced a synchronous finalize drain, raised host RSS up to ~2x on Qwen2.5-0.5B, and still failed for a layer with >~1000 modules. Tests: `tests/test_offload_fd_bound.py` now exercises the offload write path (GPTQ, RTN) and a quantized-checkpoint load at a deterministic soft limit of 256; all three fail with EMFILE on main and pass here. A fourth test disables the trackfd capability and asserts the rlimit fallback raises only the soft limit. GPU A/B on OLMoE-1B-7B (GPTQ, RTN) and Qwen2.5-0.5B (GPTQ, AWQ) is bit-identical to main at 65536 with the branch at 1024, and host RSS peak is unchanged. Co-authored-by: Claude Opus 5.5 <[email protected]>
7 tasks done
Qubitium
added a commit
to ModelCloud/Evalution
that referenced
this pull request
Dec 2, 2026
…e placement= (#153) (#154) GPT-QModel's weight_loader migration (ModelCloud/GPTQModel#6473) makes GPTQModel.load reject Accelerate placement keywords, including device_map=None, so every GPTQModel engine build raised TypeError. Default loads now pass only device=. An explicit device_map becomes placement= when GPTQModel.load accepts it ('auto' -> 'accel:auto'); older GPT-QModel releases without placement= still get device_map. Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Tracks #6471. Draft: in progress.
Removes
acceleratefrom GPT-QModel. GPT-QModel owns weight loading, placement, partial reads and offload (gptqmodel.weight_loader), and Transformers neither imports nor calls Accelerate inside a GPT-QModel process.New flow
flowchart TD U["GPTQModel.load / from_pretrained / from_quantized"] --> I["import gptqmodel: _accelerate_isolation.install()<br/>Transformers sees no Accelerate; Accelerate-shaped names -> weight_loader"] U --> P{"placement"} P --> PL["Placement rules: path -> accel:N / cpu>accel:N / disk>accel:N<br/>accel = accel:auto: balanced, then best fit"] PL --> B["Placement.bind(model): concrete devices, ties co-located"] B --> V["safety: safetensors exact tiling / GGUF zero padding; pickle refused"] V --> R["reader: targeted mmaps per module; CPU tensors are zero-copy views"] R --> WL["WeightLoader.load(modules=...) / place() / dispatch()"] WL --> M["model: hooks only where placement needs them"] M --> Q["quantize loop"] Q --> O["offload_to_disk(finalized module)"] O --> FB{"bytes equal to source?"} FB -- yes --> S["back_module_with_source: views of source shard"] FB -- no --> F["file_back_module: filebacked.safetensors + views"] S --> D["in-session model: ordinary CPU tensors, no hooks, no meta"] F --> D V -. "unaccounted bytes / pickle" .-> E1["UnsafeCheckpointError"] P -. "device_map= / max_memory=" .-> E2["TypeError: use placement="] B -. "does not fit / ambiguous / unmatched rule" .-> E3["PlacementError"] classDef failure fill:#ffe8e8,stroke:#b30000,color:#111; class E1,E2,E3 failure;Old flow vs new
accelerate>=1.15.0device_map("auto","balanced", int ordinals,"cpu"/"disk"dict semantics),max_memoryplacement=:Placementrules;accel:N,accel/accel:auto,Placement.budget({...}).device_map=/max_memory=/offload_folder=raiseTypeErrorfrom_pretraineddevice_map(requires Accelerate)WeightLoader.place()safe_open: one mmap of the whole shard, pinned by every tensor it returnsweight_loader.safe_open/ reader: a mapping covers only the requested tensors and is unmapped when they are freedsafe_open/torch.loadaccepts.bin/.pt/.pth/.ckpt: "convert the checkpoint to safetensors first"); LazyTurtle's.binconversion cache is deletedstate_dictbundle + meta +AlignDevicesHook(offload=True); restore at loop exit; live-qzeros map (#4380)filebacked.safetensors) or views of the source shard; nothing to restoreindex.json+attach_disk_offload_hookload_state_dict(assign=True)from artifact viewsweight_loader.hooks; never flush the device cacheMeasurements
Llama-3.2-1B-Instruct, GPTQ 4-bit gs128,
offload_to_disk=True(default), 64 calibration rows, branch vsorigin/mainrun concurrently (GPU 6 / GPU 7). Two repeats:mainWhole-process peak, which includes a GPU reload and generate, varies by ±0.8 GiB between identical runs, so it is not reported as a difference.
Partial mmaps, 64 MiB shard with 16 layers:
safe_openkeeps 64 MiB mapped for one tensor. The reader maps 8 MiB for two live layers, 4 MiB after one is dropped, 0 after both are dropped, and 0 for GPU reads.Accelerate isolation, traced with Accelerate installed: 0 imports and 0 calls across dense load, 2-GPU dense, quantized load + generate + save, and quantize → save → reload → generate.
Evidence
safe_opendrop-intests/test_weight_loader.py(58)tests/test_weight_loader_filebacked.py(12)tests/test_accelerate_isolation.py(6)tests/test_transformers_unpatched.pytests/test_no_accelerate_dependency.pytest_checkpoint_quantization.py::test_quantized_tensors_equal_after_resume(5 variants)gptqmodel-lazy-load-smoke-testing, Accelerate blockedRegression suite, branch vs
origin/main: the same ~150 test files (offload, dispatch, tie, resave, checkpoint, HF bridge, loader, GGUF), run in the same environment.main: 60 failed, 1669 passed, 570 skipped.maindoesn't have, and none in the other direction. All 19 asserted the removed meta + hook mechanism: offloadindex.json,metatelemetry, anAlignDevicesHookon offloaded layers,model_utils.accelerate. They are migrated to the file-backed state in b5e732e and re-verified.Environmental failures, identical on
mainin this environment:torch.opsJIT build (fatbinary … sm_80.cubin);torchvision,optimumandparameterized;test_gguf_package_e2elogits.Reviewer notes
AGENTS.mdnow allows one Transformers patch,gptqmodel/_accelerate_isolation.py(PATCHED_BINDINGS). In a GPT-QModel process, Transformers behaves as if Accelerate were absent, so a user's ownfrom_pretrained(device_map=...)raises Transformers' "requires accelerate".blockfloat.ptpayload is refused. This supersedes the checkpoint-serialization skill's "keep legacy readers" rule for model weights.hf_normalize_device_device_mapstill accepts Transformers'device_mapwhen users load GPT-QModel kernels through plain Transformers. That is an external ABI, not a GPT-QModel path.docs/in-session-model-after-offload.md(diagrams); placement language indocs/weight-loader.md.Status
gptqmodel.weight_loader: placement (accel), loader, hooks, store, safety, partial-mmap reader,safe_opendrop-in, file-backed modulesacceleratedropped from requirements; tests migrateddevice_mapto Transformers; Accelerate isolation patchsafetensors.safe_openingptqmodel/goes through targeted mmaps (LazyTurtle included)load_state_dict(assign=True)device_map=/max_memory=removed,placement=/Placement.budgetadded, Accelerate-compat code deleted (fe3e081)origin/main, conflicts resolved (54ef2c6). Main's fail-closed GGUF reader from Reject suspicious GGUF payloads, chat templates, and unsafe checkpoint shards #6475 is adopted, andvalidate_ggufdelegates to itmainas a failure-set diff: 0 branch-only failures after migration.binconversion cache removed (21beed5)placement=merge:main60 failed / 1669 passed; branch 56 failed / 1732 passed; 0 branch-only after 11628c3weight_loader/translate.py(CheckpointTranslator, which emitsTensorPlans).weight_loader/session.py(CheckpointSession, parse once) andweight_loader/plan.py(TensorPlan+execute, targeted reads) were added, andweight_loader/source.py(CheckpointSource) replacesturtle_modeleverywhere. Staging and the shard-layout warning are deleted, andutils/structure.pygoes from 4,750 to 736 linesmain: quantized checkpoint digest identical (056beb477eab3ff9); lazy-load smoke passes with Accelerate blocked, 0 source bytes mapped🤖 Generated with Claude Code