Skip to content

[BUG] optimize() + generate() always crashes on a CPU-offloaded model ('Inference tensors do not track version counter'): generate() runs the accelerate offload hooks under inference_mode, leaving offloaded params without version counters #5099

Closed

Description

@Qubitium

Found on main @ e75181d, RTX 4090, torch 2.15 + CUDA 13.2, transformers 5.22, accelerate (venv default).

What is wrong

On a model loaded with CPU offload (max_memory with a CPU budget, or a device_map with "cpu" entries), the documented model.optimize(); model.generate(...) flow always fails on the first generate():

RuntimeError: Inference tensors do not track version counter.

It fails for every GPTQ backend tried (AUTO→Marlin, GPTQ_TORCH, GPTQ_TRITON). The same model without optimize(), or optimize() on a GPU-only placement, generates fine.

Cause (two GPT-QModel pieces interact):

If the first compiled call happens under plain torch.no_grad() (model.model(**inputs) or HF model.model.generate), tracing succeeds and later GPTQModel.generate() calls work. The failure needs optimize() followed directly by GPTQModel.generate(), which is the natural order (the optimize() docstring says "The first generate() after this call pays the compile cost").

Repro

import torch
from gptqmodel import GPTQModel
q = GPTQModel.load("Llama-3.2-1B-Instruct-GPTQ-4bits-gp128", dtype=torch.float16,
                   max_memory={0: "400MiB", "cpu": "20GiB"})        # any CPU-offload placement
q.optimize()
tok = q.tokenizer
q.generate(**tok(["The capital of France is"], return_tensors="pt").to("cuda:0"), max_new_tokens=8, do_sample=False)

Output:

RuntimeError: Inference tensors do not track version counter.

Version-counter check after one eager q.generate() (no optimize):

max_memory={0:"400MiB","cpu":"20GiB"}: params/buffers without version counter: 0 after load -> 784 after generate (e.g. model.layers.0.self_attn.q_proj.qweight on cpu)
device="cuda:0":                        0 -> 0

The same crash happens with device="cuda:1", max_memory={1: "400MiB", "cpu": "20GiB"} on a 2-GPU host.

Suggested fix

Run generate() under torch.no_grad() when the model has CPU-offload hooks (the same exception already made for XLA). Alternatively, make the offload hooks move tensors outside inference mode, as the post-quantize offload path does since #4572. A smaller option: have optimize() warn and skip offloaded modules. In any case, the offloaded modules should not be left in the no-version-counter state after a plain generate().

Test that should have caught it

tests/test_cpu_offload_device_map_tied_head_4866.py / tests/test_hf_bridge_cpu_offload_5022.py load offloaded maps but never call optimize() or check version counters. Add an offloaded-map node: optimize() then generate(), and an eager generate() followed by all(p._version is readable).

Severity

Medium: a hard crash of the documented optimize flow for every CPU-offloaded placement. The workarounds are to skip optimize(), or to warm the compiled forward under no_grad first.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim: agent-root-5099-offload-generate is working on this issue now.

    Started 2026-11-18T05:25:43Z. 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: fix: stop generate() from running the accelerate CPU-offload hooks under inference_mode so optimize()+generate() traces on an offloaded model

  2. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-root-5099-offload-generate finished this issue.
    Pull request: #5147

    Root cause: BaseQModel.generate ran every non-XLA model under torch.inference_mode. An Accelerate CPU-offload hook moves each layer with Module._apply on every forward; inside inference mode the second move of an inference buffer stores a tensor without a version counter (#4572), and dynamo reads version counters when tracing the compiled forward installed by optimize(). The eager path left 784 packed buffers without a counter even without optimize(). The fix selects torch.no_grad() only for models that actually carry a moving offload hook (CpuOffload or AlignDevicesHook(offload=True), unwrapping SequentialHook) and keeps inference_mode for every other model. Verified on an RTX 5090: eager generate() 0 -> 0 tensors without _version, and optimize() then generate() produces tokens for AUTO/TritonV2, GPTQ_TORCH, and GPTQ_TRITON; GPU-only AUTO/Marlin and GPTQ_TORCH still pass. A new regression fails on e2f9676c6 with 98 buffers missing a counter and the reported RuntimeError, and passes with the fix.

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