Repository navigation
Description
Goal
Remove accelerate from GPT-QModel entirely: drop it from requirements.txt, have no runtime imports, and never let accelerate load, place, or dispatch our weights. Its job moves to a small, explicit, GPT-QModel-owned WeightLoader.
Why
accelerate is a heavy dependency and its behaviour is implicit. It probes memory, places weights with "auto"/"balanced"/"sequential", flushes the device cache inside hooks (we already subclass AlignDevicesHook/CpuOffload to work around that), and has backward-compat syntax nobody can reason about. Weight loading and execution placement must be explicit: the user (or GPT-QModel) states where every module lives and where it runs, and the loader does exactly that or raises.
Current surface (at 2863a6bca)
Runtime imports of accelerate:
| area | accelerate APIs used |
|---|---|
utils/model.py |
load_checkpoint_in_model, find_tied_parameters, retie_parameters, set_module_tensor_to_device, offload_weight, save_offload_index, OffloadedWeightsLoader, PrefixedDataset, AlignDevicesHook, CpuOffload, SequentialHook, UserCpuOffloadHook, add/remove_hook_to_module, has_offloaded_params |
utils/offload_hooks.py |
subclasses AlignDevicesHook / CpuOffload; named_module_tensors, offload_state_dict, send_to_device, find_device, clear_device_cache, get_non_persistent_buffers |
utils/offload.py |
add_hook_to_module, remove_hook_from_module(s), align_module_device, has_offloaded_params |
utils/looper_helpers.py, looper/stage_inputs_capture.py |
hook class checks |
quantization/awq/utils/utils.py, utils/ebss.py |
cpu_offload_with_hook, tied-param find/retie |
utils/hf.py, utils/model_dequant.py |
init_empty_weights |
utils/safetensor.py, utils/tied_weights.py |
find_tied_parameters |
utils/vram.py, models/loader.py |
get_max_layer_size, convert_file_size_to_int |
models/ports/deepseek_v41_flash/checkpoint.py |
infer_auto_device_map |
nn_modules/hooked_linear.py, models/definitions/ernie4_5_vl_moe.py |
has_offloaded_params |
native gemma3n / gemma4 ports |
add_hook_to_module |
There's also an implicit dependency through transformers. transformers 5.x raises ValueError(... requires accelerate) for any non-None device_map passed to from_pretrained. GPT-QModel passes one on the dense load path (_dense_placement_device_map, which defaults to "auto") and on the quantize-source CPU load ({"": "cpu"}). Once accelerate is gone, HF must load with device_map=None and WeightLoader does all placement.
Design: gptqmodel.weight_loader
Placement: an explicit placement language. Noauto,balanced, or memory probing.- Rules are module-path prefix → target. Layer ranges are written as
model.layers.[0:16]. - Targets:
"cuda:0"(resident),"cpu"(resident),"cpu>cuda:0"(stored on CPU, executes oncuda:0),"disk>cuda:0"(stored on disk, executes oncuda:0). - The longest-prefix rule wins. Every tensor must resolve to exactly one rule, or the load raises (no silent default device).
- A helper builds an explicit even split of a layer stack, e.g.
Placement.split("model.layers", 32, ["cuda:0", "cuda:1"], base="cuda:0", head="cuda:1"). It is deterministic and documented, not memory-guessed. Placement.from_device_map(dict)converts existing explicit dictdevice_maps. Keyword strings ("auto", …) are rejected, or resolved by GPT-QModel's own explicit policy at the call site.
- Rules are module-path prefix → target. Layer ranges are written as
WeightLoader: streams safetensors shards straight onto each tensor's target device (no full CPU staging when the target is an accelerator). It handles dtype casting, keeps fp32 for the modules that need it, re-ties tied weights, and reports missing/unexpected keys.- Execution hooks: a minimal hook system (
add_hook/remove_hook,SequentialHook),AlignDevicesHook(CPU/disk offload executing on an accelerator, never flushing the device cache), andCpuOffloadchains for the AWQ/EBSS sequential offload. Hooks keep the_hf_hook/_old_forwardattribute names, because transformers reads them by attribute name (e.g.generatesetsencoder._hf_hook.io_same_device). - Utilities:
init_empty_weights,set_module_tensor_to_device,find_tied_parameters/retie_parameters,send_to_device,named_module_tensors, offload index read/write (OffloadedWeightsLoader,PrefixedDataset), andhas_offloaded_params/align_module_device. Each one is only as large as GPT-QModel actually needs.
Plan
- Phase 1:
gptqmodel/weight_loader/package (placement, loader, hooks, offload store, utils) plus unit tests - Phase 2: migrate every runtime import to
weight_loader;GPTQModelAlignDevicesHook/GPTQModelCpuOffloadbecome the native hooks - Phase 3: stop passing
device_mapto HFfrom_pretrained; replacesimple_dispatch_modelandload_checkpoint_in_model_then_tie_weightswithWeightLoader - Phase 4: drop
acceleratefromrequirements.txt/requirements/tenstorrent-py312.txt; migrate tests; add an "accelerate not installed" CI guard (import-blocking test) - Phase 5: docs for the placement language
- Module-scoped partial mmap reads (core landed in Remove accelerate: explicit WeightLoader for weight loading, placement and offload (#6471) #6473: mappings are lifetime-bound; a CPU tensor is a zero-copy view of a window covering only its module, and the window is unmapped when the tensor is freed). Accelerate and
safe_openmap the whole safetensors shard, so loading one module from a multi-GiB shard that spans many layers keeps every unrelated layer mapped. That carry-over is why GPT-QModel had to buildLazyTurtle.WeightLoadermust:- read tensors by exact byte range from the validated header (no
safe_openwhole-file maps); - map only a window covering the requested module's tensors. Windows are coalesced only across adjacent tensors of the same module, capped in size, and unmapped as soon as the tensors are copied out. Nothing stays mapped into the next module;
- load a module subset:
WeightLoader.load(model, ckpt, modules=[...]), and exposeWeightLoader.read(names, device)for callers that need raw tensors; - serve
OffloadedWeightsLoadersafetensors_filereferences through the same partial reader; - move every whole-shard
safe_openread onto the partial reader.weight_loader.safe_openis a drop-in, and all 15gptqmodel/importers use it, LazyTurtle included. Remaining:safetensors.torch.load_filecallers
- read tensors by exact byte range from the validated header (no
- Remove
LazyTurtleand the disk offloader (utils/structure.pyLazyTurtle, about 3.4k lines;utils/offload.py, about 2k lines). Both exist only to work around whole-file mmaps and meta/hook offload:- Release used layers.
LazyTurtlematerializes one layer at a time from the checkpoint so earlier layers can leave memory.WeightLoader.load(model, ckpt, modules=[layer])with lifetime-bound targeted mmaps replaces this. - Free CPU RAM after quantizing a layer. Today the layer is written to disk, replaced by meta tensors and re-materialized through offload hooks. Replacement: file-backed tensors. Write the finished layer to a safetensors file in the offload dir and rebind its tensors as zero-copy views of that file. The layer stays usable with no meta tensors, no
AlignDevicesHook/disk_offloadand no restore step, and the kernel evicts and re-reads clean pages under memory pressure.
-
inventory done. Disposable: the per-layer read/release loop (B), the shard-layout warning (N) and dead active-source staging (O). Must move into
WeightLoader: HF v5 reverse conversion maps and scoped renames (D), fused-expert/chunk/interleave/ERNIE transforms (E), concat/merge/zero-pad (F), raw packed/MX export (G), MiMo decode (H), the native-fp32 policy (I), init-only buffer rebuild (J), no-placement params (K), tie snapshot (L), and the.binconversion cache (M) -
WeightLoadergaps to close first: a reusable checkpoint session (parse once;has/aliases/weight_map); source plans (many-to-one and one-to-many source keys); tensor transforms; a dtype-policy callback; a missing-tensor policy; predicate-based skips; device overrides. Port with differential tests againstLazyTurtlebefore deleting it -
quantize source path: meta shell +
WeightLoader.load(modules=[layer])per layer instead ofLazyTurtle -
file_back_moduleprimitive. Hardened after review:posix_fallocateinstead of SIGBUS on a full disk; views underinference_mode(False); model-wide tie rebind; one mapping per file; FNUZ float8 dtypes; attributes kept -
replace
offload_to_disk/undo_offload_to_disk/restore_disk_offloaded_modules/attach_disk_offload_hookwith file-backed rebinding; keep checkpoint/resume (looper/gptq_checkpoint.py) and save (models/writer.py) working from the file-backed tensors -
(LazyTurtle: done in Remove accelerate: explicit WeightLoader for weight loading, placement and offload (#6471) #6473; hook-based offload machinery: Delete the dead hook-based offload machinery (#6471) #6494) delete
LazyTurtle,utils/offload.py's hook-based machinery andQuantizeConfig.offload_to_diskplumbing that has no meaning any more; migrate their tests
- Release used layers.
LazyTurtle removal (in #6473, per maintainer)
- pickle sources disallowed.
.bin/.pt/.pth/.ckptweight sources are refused ("convert to safetensors first") at the artifact trust boundary; LazyTurtle's.bin→ safetensors conversion cache is deleted; the legacy block-float.ptpayload is refused - delete dead and obsolete parts: active-source staging, shard-layout warning
-
weight_loaderpieces:-
CheckpointSession: parse once,has/aliases/weight_map/root/ targetedread - plans: many-to-one and one-to-many source keys (
TensorPlan) - transforms: expert select, chunk, interleave, transpose hint, stack/concat, zero-pad rows, decode
- dtype-policy, missing-tensor and device-override hooks
-
- move LazyTurtle's resolution logic unchanged into a translator that emits plans; run both paths side by side on every LazyTurtle test family until they produce identical tensors
- switch callers (
base.pyshell materialization,writer.py,stage_inputs_capture,tied_weights, model definitions) to the new interface; makeLazyTurtleraise, then delete it
Activity
Remove accelerate: migrate runtime to weight_loader, explicit placeme…
Qubitium commentedon Nov 30, 2026
Progress in draft PR #6473. Design additions since this issue was filed:
acceldevice family.accel:Nis the N-th device of the host's accelerator backend (CUDA / ROCm / XPU / NPU / MPS). It is the recommended spelling, so one placement config works on every backend.accel/accel:autopolicy. It balances by free memory, then falls back to best fit, and raises instead of spilling. Accelerate'sdevice_mapkeywords (auto,balanced,sequential) map onto it.WeightLoaderrefuses pickle checkpoints and validates safetensors and GGUF files strictly before reading. Every byte must belong to a declared tensor; only zero alignment padding is allowed in GGUF; safetensors headers may contain only tensor descriptors and str→str metadata.device_mapto transformers. GPT-QModel never passes one tofrom_pretrained, because transformers requires Accelerate for anydevice_map.docs: describe weight_loader instead of Accelerate in comments and do…
weight_loader: targeted, lifetime-bound partial mmaps instead of whol…
tests: drop accelerate; exercise gptqmodel.weight_loader instead (#6471)
weight_loader: file-backed modules (meta/hook-free disk offload primi…
Route every safetensors read through weight_loader.safe_open; harden …
Isolate Transformers from Accelerate in GPT-QModel processes (#6471)
Offload finalized modules as file-backed tensors instead of meta + ho…
tests: pin file-backed offload instead of meta + hook offload (#6471)
tests: resume restores file-backed modules equal to their artifacts (#…
tests: pin file-backed resume/offload state in the remaining checkpoi…
WIP: GPT-QModel stops consuming Accelerate's device_map; placement= i…
Describe placements instead of device_map in kernel comments (#6471)
2 remaining items
Restore pass reads the same safetensors checkpoint as WeightLoader, n…
accel:auto binds to CPU without a visible accelerator; fix TTNN place…
Merge wl-placement-api: GPT-QModel no longer consumes Accelerate's de…
tests: last branch-only regressions after the placement merge (#6471)
Disallow pickle weight sources; delete LazyTurtle's .bin conversion c…
Merge wl-drop-pickle: pickle weight sources disallowed (#6471)
Replace LazyTurtle with weight_loader CheckpointSource (#6471)
Remove the temporary LazyTurtle differential harness (#6471)
tests: lazy checkpoint memory contract bounds mapped bytes, not mappi…
Remove accelerate: explicit WeightLoader for weight loading, placemen…
Delete the dead hook-based offload machinery (#6471) (#6494)
Qubitium commentedon Nov 30, 2026
All items done: #6473 (WeightLoader, accelerate removed, LazyTurtle replaced) and #6494 (dead hook-based offload machinery) are merged.
QuantizeConfig.offload_to_diskstays: it now drives file-backed offload. Remaining cosmetic leftovers: #6497.chore: drop the last accelerate-style device_map helpers (#6497)
fix: post-#6473 regressions — Trainer in a GPT-QModel process, late-i…