Repository navigation
fix(load): make explicit CPU-offload device maps survive the first forward (#4866) - #4890
Merged
Merged
Conversation
…rward (#4866) `simple_dispatch_model` is the loader's own placement path for an explicit `device_map` (`loader.py` calls it instead of `accelerate.dispatch_model`). Two of its steps assumed a mapped module owns parameters on one device, so a documented CPU-offload map loaded cleanly and then raised on the first forward. Tied embeddings with `lm_head` (or the tail) on CPU: `retie_parameters` rebinds a tied group to a single tensor and takes the first non-meta member, so the CPU `lm_head` copy won the tie while `model.embed_tokens` kept an `AlignDevicesHook` that moved `input_ids` to the accelerator. `F.embedding` then received a CUDA index and a CPU weight: RuntimeError: Expected all tensors to be on the same device, but got index is on cuda:0, different from other tensors on cpu (index_select) Keep each really-tied group on one device before any hook is installed: the group follows the accelerator of its GPU member (never the root entry, never when every member is offloaded). The hooks also share one materialized copy per device through Accelerate's `tied_params_map`, so the tie survives the first forward instead of each hook moving its own copy. A parameterless module mapped to CPU (`model.rotary_emb`, which a "first N layers on CPU" map produces) was given `accelerate.cpu_offload_with_hook`; `CpuOffload.pre_forward` reads `next(module.parameters())` and raised `StopIteration`. Such a module now stays on `main_device` with an `AlignDevicesHook`, the same choice the `max_memory` builder makes for structural modules. Both rules are driven by `find_tied_parameters`, i.e. by the parameter objects that are actually shared, so an untied checkpoint keeps its own head on the device the map names (#4799 is unaffected). Tests: `tests/test_cpu_offload_device_map_tied_head_4866.py` drives the four maps from the issue (`head_cpu`, `1_then_cpu`, `rotary_cpu`, `cpu_then1`), asserts a finite forward, the tie identity after the forward, bitwise equality with the all-accelerator placement, the untied control, and the absence of a `CpuOffload` hook on the parameterless module. 12 passed; on the parent 11 of the 12 fail with the two errors above.
# Conflicts: # gptqmodel/utils/model.py
This was referenced Nov 17, 2026
Qubitium
added a commit
that referenced
this pull request
Nov 17, 2026
… (#4960) `load_checkpoint_in_model_then_tie_weights` hands the explicit `device_map` to accelerate and then calls `tie_weights(missing_keys=...)`. When the checkpoint stores both `lm_head.weight` and `model.embed_tokens.weight` -- AutoAWQ format and GPTQModel <= 1.x tied checkpoints -- transformers compares the two with `torch.equal`. A map that puts one side on CPU and the other on the accelerator made that comparison raise before `simple_dispatch_model`, which #4890 taught to keep a really-tied group on one device, ever ran: RuntimeError: Expected all tensors to be on the same device, but got other is on cpu, different from other tensors on cuda:0 (wrapper_CUDA__equal) The model is not tied yet at that point, so `find_tied_parameters` sees no group. Apply the same placement rule to the load map from the model's *declared* `{target: source}` mapping -- the exact list `tie_weights` iterates -- plus the identity groups when the model already ties at construction. Every pair transformers may compare is then on one device, so it reaches its own "both present but different, so do not tie" path instead of raising. The untied head keeps its own placement: with `tie_word_embeddings=False` there is no declared pair, and a tied config that stores a distinct head now compares on one device and is left untied (#4799). Measured with a tiny quantized tied Qwen2 (2 layers, g32) loaded through `GPTQModel.load(..., device_map=...)`: tied checkpoint, both copies stored (parent) head_cpu / 1_then_cpu / cpu_then1: RuntimeError (wrapper_CUDA__equal) rotary_cpu: ok same checkpoint (fixed) all four maps: load, forward finite, `lm_head.weight is embed_tokens.weight`, both on one device, logits bitwise equal across the four maps The same checkpoint that stores only `embed_tokens` (the #4866 shape) and the untied control are unchanged. Tests: `tests/test_cpu_offload_tied_both_copies_4943.py` loads the real quantized checkpoint in three published shapes (embed only, both copies equal, both copies different) through the four #4866 maps and asserts the load, a finite forward, the surviving tie and the untied control, plus bitwise equality between the two tied shapes. 13 passed; on the parent 7 fail with the cross-device `torch.equal` error. The #4866 file, the #4799 InternVL file, the HF load bridge, the loader offload staging and the rehome hook tests stay green (94 passed, 3 skipped).
This was referenced Nov 17, 2026
Qubitium
added a commit
that referenced
this pull request
Nov 18, 2026
…5046) Plain `transformers`/Optimum loading of a GPT-QModel GPTQ/RTN or AWQ-GEMM checkpoint with a map that offloads layers to CPU failed at load time, although `GPTQModel.load` serves the same maps since #4890: * GPTQ/RTN: `RuntimeError: CPU-offloaded Marlin requires a writable in-memory weights map.` * AWQ-GEMM: `ValueError: AWQ Marlin requires CUDA tensors, got 'meta'.` Two independent causes. 1. The bridge never told the selector about the offload. `from_quantized` derives `cpu_offload` from the map and passes it to `select_quant_linear`, so AUTO skips a kernel whose `post_init` needs CUDA. The HF entry points did not: `hf_select_quant_linear`, `hf_select_quant_linear_v2` (Transformers' GPTQ quantizer, Optimum's `GPTQQuantizer.convert_model`, and AWQ's `replace_with_awq_linear`) and the native bridge's `make_quant` all selected `MarlinLinear`/`AwqMarlinLinear` for an offloading map. The check now lives in `utils.importer.device_map_uses_cpu` (the native loader's `_device_map_uses_cpu` delegates to it) and `auto_cpu_offload`, which narrows it to AUTO so an explicit `backend="marlin"` stays the caller's choice. 2. `_post_init_cpu_offloaded_marlin` accepted only a plain `dict` or a `PrefixedDataset` over a `dict`. Transformers dispatches through Accelerate, which attaches `AlignDevicesHook(weights_map=PrefixedDataset(OffloadedWeightsLoader(...)))`, so the #3452 path could never run from a real `from_pretrained`. `_cpu_offload_writable_storage` unwraps the prefix and writes through the loader's in-memory `state_dict`, refusing only entries that live in its disk `index` (same message, now naming the disk-backed keys). `AwqMarlinLinear` shares the post-init: it repacks into the Marlin layout too, and before this it ran `post_init` on `meta`.
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.
Fixes #4866.
Root cause
simple_dispatch_model(the loader's own explicit-device_mappath) made two device assumptions that break on CPU-offload maps:retie_parameters(model, tied_params)rebinds a whole tied group to the first non-meta member. Withlm_headon CPU, that CPU copy won the tie and was written intomodel.embed_tokens.weight, whileembed_tokenskept anAlignDevicesHookthat movesinput_idsto the accelerator ->F.embeddinggot a CUDA index and a CPU weight.accelerate.cpu_offload_with_hook, includingmodel.rotary_emb;CpuOffload.pre_forwardreadsnext(module.parameters())->StopIteration.Both loaded cleanly and crashed only on the first forward.
Fix
_keep_tied_groups_on_one_device: a really-tied group follows the accelerator of its GPU member (root entry never rewritten; untouched when every member is offloaded), applied before hooks are installed.tied_params_mapbuilt fromfind_tied_parameters, so each device materializes one shared copy and the tie survives the forward.cpu_offload_groupskips modules without parameters; such a CPU-mapped module is placed onmain_devicewith anAlignDevicesHook, matching the existingmax_memorybuilder rule.tie_word_embeddings, so untied heads keep their placement ([BUG] InternVL3-hf: quantize() ties the untied lm_head to embed_tokens (LazyTurtle re-calls tie_weights() off the composite config's default tie_word_embeddings=True) and the checkpoint omits lm_head: PPL 23.59 -> 29.98 #4799 unaffected).Evidence (tiny 2-layer tied Llama, GB10 + CPU)
head_cpuRuntimeError ... index_select1_then_cpuRuntimeError ... index_selectrotary_cpuStopIterationAlignDevicesHookcpu_then1StopIterationAll four are bitwise equal to the all-accelerator placement (max|delta| 0.0). Untied control:
lm_headstayscpu, distinct tensor, finite forward.Tests
tests/test_cpu_offload_device_map_tied_head_4866.py: 12 passed; on parent 11 of 12 fail (both errors reproduced)test_internvl_untied_lm_head_4799,test_rehome_hook_realign,test_loader_offload_staging_4385): 51 passed, 3 skippedruff check gptqmodel tests: cleanResidual risk
GPTQModel.load(..., device_map=...)path was not driven against a real quantized checkpoint on this host; coverage is the dispatch function, which is the sole failing component.""entry, is left untouched.docs/kernel-dispatch-cpu.md§2); it trades a crash for GPU residency rather than duplicating the tensor per device.