Skip to content

fix(load): make explicit CPU-offload device maps survive the first forward (#4866) - #4890

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4866
Nov 17, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4866

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4866.

Root cause

simple_dispatch_model (the loader's own explicit-device_map path) made two device assumptions that break on CPU-offload maps:

  1. Tied group split across devices. retie_parameters(model, tied_params) rebinds a whole tied group to the first non-meta member. With lm_head on CPU, that CPU copy won the tie and was written into model.embed_tokens.weight, while embed_tokens kept an AlignDevicesHook that moves input_ids to the accelerator -> F.embedding got a CUDA index and a CPU weight.
  2. Parameterless module offloaded. Every CPU entry got accelerate.cpu_offload_with_hook, including model.rotary_emb; CpuOffload.pre_forward reads next(module.parameters()) -> StopIteration.

Both loaded cleanly and crashed only on the first forward.

Fix

Evidence (tiny 2-layer tied Llama, GB10 + CPU)

map parent fixed
head_cpu RuntimeError ... index_select forward OK, tie kept
1_then_cpu RuntimeError ... index_select OK
rotary_cpu StopIteration OK, AlignDevicesHook
cpu_then1 StopIteration OK

All four are bitwise equal to the all-accelerator placement (max|delta| 0.0). Untied control: lm_head stays cpu, distinct tensor, finite forward.

Tests

  • new tests/test_cpu_offload_device_map_tied_head_4866.py: 12 passed; on parent 11 of 12 fail (both errors reproduced)
  • combined run (new test, test_internvl_untied_lm_head_4799, test_rehome_hook_realign, test_loader_offload_staging_4385): 51 passed, 3 skipped
  • ruff check gptqmodel tests: clean

Residual risk

  • The end-to-end 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.
  • A tied group whose members are all CPU/disk, or that resolves through the root "" entry, is left untouched.
  • Collapsing a tied group onto its GPU member changes the stated placement for that module (documented in docs/kernel-dispatch-cpu.md §2); it trades a crash for GPU residency rather than duplicating the tensor per device.

…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.
@Qubitium
Qubitium merged commit a43e305 into main Nov 17, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4866 branch November 17, 2026 18:05
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).
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`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant