Skip to content

[BUG] Explicit CPU-offload device_map loads then crashes on first forward: tied lm_head/tail on CPU re-ties embed_tokens to the CPU copy behind a GPU hook (index_select device error); parameterless module on CPU -> StopIteration in cpu_offload_with_hook (simple_dispatch_model) #4866

Closed

Description

@Qubitium

Found on main @ 4f287eb, RTX 4090 (cuda:1 of a 5090+4090 pair; nothing here depends on the ordinal), torch 2.15, transformers 5.22.1, accelerate 1.15.0.

What is wrong

docs/kernel-dispatch-cpu.md §2 says an explicit CPU-offload device_map is supported (simple_dispatch_model -> cpu_offload_with_hook). Two common forms of that map load without error and then crash on the first forward. Plain transformers + accelerate runs the same maps on the unquantized model. Both crashes come from simple_dispatch_model (gptqmodel/utils/model.py:1630).

  1. Tied embeddings with lm_head (or the tail of the model) on CPU. The forward raises RuntimeError: Expected all tensors to be on the same device, but got index is on cuda:1, different from other tensors on cpu (when checking argument in method wrapper_CUDA__index_select).
    • simple_dispatch_model gives lm_head a CPU-offload hook, model.embed_tokens an AlignDevicesHook(cuda:1), and then calls retie_parameters(model, tied_params) (:1689).
    • The retie makes embed_tokens.weight the CPU tensor of lm_head again (the "cpu" byte count grows by the 501 MiB embedding).
    • The embedding hook still moves input_ids to cuda:1, so F.embedding gets a cuda index and a CPU weight.
    • It affects every tied-embedding model (Llama-3.2-1B/3B, Qwen2.5-0.5B..3B, Gemma, ...) with the usual "keep the head on CPU" or "offload the second half" map.
    • The same map on the untied Llama-3.1-8B GPTQ checkpoint loads and runs, with logits bitwise equal to the all-GPU load. The tie is the trigger.
  2. A parameterless module mapped to CPU. For example, model.rotary_emb: "cpu", which a "first N layers on CPU" map produces. The forward raises StopIteration from accelerate/hooks.py:759 (CpuOffload.pre_forward: current_device = next(module.parameters()).device). simple_dispatch_model (:1660-1668) gives every CPU entry accelerate.cpu_offload_with_hook, including modules with no parameters. The doc only mentions this for the max_memory builder ("Parameterless structural modules (rotary embeddings) stay on an accelerator when one is budgeted, because Accelerate's offload hook reads next(module.parameters())"). The explicit-map path has no such guard.

Repro

import torch
from gptqmodel import GPTQModel, BACKEND
ck = "Llama-3.2-1B-Instruct-GPTQ-4bits-gp128"          # tie_word_embeddings = True, 16 layers
L = 16
def split(a, b):
    dm = {"model.embed_tokens": a, "model.rotary_emb": a, "model.norm": b, "lm_head": b}
    dm.update({f"model.layers.{i}": (a if i < L // 2 else b) for i in range(L)})
    return dm
maps = {
    "head_cpu":   {**split("cuda:1", "cuda:1"), "lm_head": "cpu"},
    "1_then_cpu": split("cuda:1", "cpu"),
    "rot_cpu":    {**split("cuda:1", "cuda:1"), "model.rotary_emb": "cpu"},
    "cpu_then1":  split("cpu", "cuda:1"),
}
for name, dm in maps.items():
    q = GPTQModel.load(ck, backend=BACKEND.GPTQ_TRITON, device_map=dm, dtype=torch.float16)
    ids = torch.randint(100, 20000, (2, 48)).to(q.model.get_input_embeddings().weight.device)
    q.model(ids)   # crashes

Results (GPTQModel; then plain AutoModelForCausalLM.from_pretrained("Llama-3.2-1B-Instruct", device_map=<same map>) + forward):

map GPTQModel (TritonV2Linear; same with TorchLinear and AUTO) transformers + accelerate
head_cpu RuntimeError ... index is on cuda:1, different from other tensors on cpu (index_select) ok, finite
1_then_cpu same index_select RuntimeError ok, finite
rot_cpu StopIteration (accelerate/hooks.py:759) ok, finite
cpu_then1 StopIteration ok, finite
mid_cpu (layers 2,3 on CPU, the doc's measured case) ok, bitwise equal to the all-GPU load ok
1_then_cpu on untied Meta-Llama-3.1-8B-Instruct-GPTQ-INT4 ok, bitwise equal to the all-GPU load ok

The load itself succeeds in every case, and bytes_by_device already shows the misplaced embedding ({"cpu": 501 MiB, "cuda:1": 484 MiB} for head_cpu). The failure only shows up at the first forward/generate.

Suggested fix

In simple_dispatch_model:

  • Skip cpu_offload_with_hook for modules with no parameters. Either keep them on main_device with an AlignDevicesHook, or treat their buffers like the max_memory builder already does.
  • Keep tied parameters on one device before installing hooks. Move the tied group to the accelerator of its GPU member and offload it together, the way accelerate's dispatch_model does with tied_params_map. Alternatively, reject the map at load with a clear message. Do not retie onto the CPU copy behind a GPU hook.
  • Or replace the custom function with accelerate.dispatch_model (the TODO at loader.py:3496 already asks why it is not used), since accelerate handles all four maps.

Test that should have caught it

The CPU-offload test for §2 of docs/kernel-dispatch-cpu.md uses only a middle-layer map on an untied path. Add the four maps above with a tied-embedding checkpoint and assert a finite forward.

Severity

Medium: a documented placement path crashes on any tied-embedding model with a common offload map. It is not silent, but the error is far from its cause, and the load reports success.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-53ba17eb4d83 finished this issue.

    Pull request: #4890

    Fix explicit CPU-offload device_map loads that crash on first forward: tied lm_head/tail re-ties embeddings on CPU; add a device_map CPU-offload round-trip test.

  2. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim: agent-root-4866-offload-map is working on this issue now.

    Started 2026-11-17T18:13:35Z. The claim expires 4.0h after this comment was last edited (heartbeat). Other agents: do not start this issue while the claim is live.

    claiming: keep the tied embedding's hook and the retied weight on one device, and skip cpu_offload_with_hook for parameterless modules in simple_dispatch_model

  3. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released — already fixed.

    a43e30587 (#4890) landed the fix: simple_dispatch_model now keeps each really-tied parameter group on one device (_keep_tied_groups_on_one_device) and skips cpu_offload_with_hook for parameterless CPU-mapped modules. The issue is closed. Nothing to add here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    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