Skip to content

Remove accelerate dependency: explicit GPT-QModel WeightLoader for weight loading, placement and offload #6471

Done

Description

@Qubitium

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

  1. Placement: an explicit placement language. No auto, 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 on cuda:0), "disk>cuda:0" (stored on disk, executes on cuda: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 dict device_maps. Keyword strings ("auto", …) are rejected, or resolved by GPT-QModel's own explicit policy at the call site.
  2. 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.
  3. Execution hooks: a minimal hook system (add_hook / remove_hook, SequentialHook), AlignDevicesHook (CPU/disk offload executing on an accelerator, never flushing the device cache), and CpuOffload chains for the AWQ/EBSS sequential offload. Hooks keep the _hf_hook / _old_forward attribute names, because transformers reads them by attribute name (e.g. generate sets encoder._hf_hook.io_same_device).
  4. 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), and has_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/GPTQModelCpuOffload become the native hooks
  • Phase 3: stop passing device_map to HF from_pretrained; replace simple_dispatch_model and load_checkpoint_in_model_then_tie_weights with WeightLoader
  • Phase 4: drop accelerate from requirements.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_open map 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 build LazyTurtle. WeightLoader must:
    • read tensors by exact byte range from the validated header (no safe_open whole-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 expose WeightLoader.read(names, device) for callers that need raw tensors;
    • serve OffloadedWeightsLoader safetensors_file references through the same partial reader;
    • move every whole-shard safe_open read onto the partial reader. weight_loader.safe_open is a drop-in, and all 15 gptqmodel/ importers use it, LazyTurtle included. Remaining: safetensors.torch.load_file callers
  • Remove LazyTurtle and the disk offloader (utils/structure.py LazyTurtle, about 3.4k lines; utils/offload.py, about 2k lines). Both exist only to work around whole-file mmaps and meta/hook offload:
    1. Release used layers. LazyTurtle materializes 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.
    2. 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_offload and 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 .bin conversion cache (M)

    • WeightLoader gaps 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 against LazyTurtle before deleting it

    • quantize source path: meta shell + WeightLoader.load(modules=[layer]) per layer instead of LazyTurtle

    • file_back_module primitive. Hardened after review: posix_fallocate instead of SIGBUS on a full disk; views under inference_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_hook with 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 and QuantizeConfig.offload_to_disk plumbing that has no meaning any more; migrate their tests

LazyTurtle removal (in #6473, per maintainer)

  • pickle sources disallowed. .bin/.pt/.pth/.ckpt weight sources are refused ("convert to safetensors first") at the artifact trust boundary; LazyTurtle's .bin → safetensors conversion cache is deleted; the legacy block-float .pt payload is refused
  • delete dead and obsolete parts: active-source staging, shard-layout warning
  • weight_loader pieces:
    • CheckpointSession: parse once, has / aliases / weight_map / root / targeted read
    • 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.py shell materialization, writer.py, stage_inputs_capture, tied_weights, model definitions) to the new interface; make LazyTurtle raise, then delete it

Activity

  1. self-assigned this
    on Nov 30, 2026
  2. Qubitium commented on Nov 30, 2026

    @Qubitium
    CollaboratorAuthor

    Progress in draft PR #6473. Design additions since this issue was filed:

    • accel device family. accel:N is 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:auto policy. It balances by free memory, then falls back to best fit, and raises instead of spilling. Accelerate's device_map keywords (auto, balanced, sequential) map onto it.
    • Checkpoint safety. WeightLoader refuses 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.
    • No device_map to transformers. GPT-QModel never passes one to from_pretrained, because transformers requires Accelerate for any device_map.
  3. 2 remaining items

  4. Qubitium commented on Nov 30, 2026

    @Qubitium
    CollaboratorAuthor

    All items done: #6473 (WeightLoader, accelerate removed, LazyTurtle replaced) and #6494 (dead hook-based offload machinery) are merged. QuantizeConfig.offload_to_disk stays: it now drives file-backed offload. Remaining cosmetic leftovers: #6497.

  5. added 2 commits that reference this issue on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions