Skip to content

fix(generate): keep version counters on CPU-offloaded models (#5099) - #5147

Merged
Qubitium merged 1 commit into
mainfrom
fix/5099-offload-optimize-generate
Nov 18, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5099-offload-optimize-generate

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #5099

Summary

GPTQModel.generate() selected torch.inference_mode() for every non-XLA model. A CPU-offloaded placement (max_memory CPU budget or a device_map with cpu entries) installs an Accelerate hook that moves each layer with Module._apply on every forward. Parameters survive that move (param.data = ... keeps the counter), but buffers are replaced outright (self._buffers[key] = fn(buf)); the second move of an inference buffer stores a tensor with no version counter (#4572). Dynamo reads version counters, so optimize(); generate() crashed while tracing the first decode step. The eager path carried the same defect: one generate() on the fully offloaded model left 784 packed buffers without a counter even without optimize().

The fix selects torch.no_grad() only when the model actually carries a moving offload hook (CpuOffload or AlignDevicesHook(offload=True), unwrapping SequentialHook) and keeps inference_mode for every other model. optimize() itself does not move offloaded tensors (measured 0 tensors without a counter after optimize()), so the selection only has to cover generate().

Net diff: +379 / -6 across 7 files (2 code, 2 test, 2 docs/index, 1 README). No hook is replaced and no extra tensor copy is introduced.

Before and after

Step Before (e2f9676c6) After
Context selection no_grad only for XLA, otherwise inference_mode (gptqmodel/models/base.py:3751-3756) no_grad for XLA or has_cpu_offload_hooks(self.model) (gptqmodel/models/base.py::generate)
Hook detection none has_cpu_offload_hooks scans _hf_hook, unwraps SequentialHook, matches CpuOffload and AlignDevicesHook(offload=True) (gptqmodel/utils/model.py:1776)
Layer materialization CpuOffload.pre_forward calls module.to(execution_device) under inference_mode; simple_dispatch_model installs that hook (gptqmodel/utils/model.py::simple_dispatch_model) the same move runs under no_grad
Buffer lifecycle Module._apply replaces buffers; the second move of an inference buffer stores a tensor without a version counter the move allocates a normal tensor, so the buffer keeps its counter
Compiled generate() dynamo's guard on g_idx._version raises RuntimeError: Inference tensors do not track version counter (gptqmodel/nn_modules/qlinear/torch.py:1031) the trace succeeds and generation produces tokens

Packed GPT-QModel tensors (qweight, qzeros, scales, g_idx, qzeros_format) are buffers, which is why the version counter was lost there while parameters kept theirs.

Old flow

flowchart TD
    A["BaseQModel.generate()"] --> B{"model.device.type is xla?"}
    B -->|"yes"| N["torch.no_grad()"]
    B -->|"no"| I["torch.inference_mode()"]
    I --> H["CpuOffload.pre_forward: module.to(execution_device)"]
    H -->|"first move of a normal tensor"| V1["buffers keep a version counter"]
    H -->|"second move of an inference buffer"| V0["buffers have no version counter"]
    V1 --> E["eager forward succeeds"]
    V0 --> C["optimize() compiled forward traces"]
    C --> G["dynamo reads g_idx._version"]
    G --> F["RuntimeError: Inference tensors do not track version counter"]
    E --> P["model left polluted for the next compiled call"]
    style F fill:#f8d7da,stroke:#b02a37
    style V0 fill:#f8d7da,stroke:#b02a37
    style P fill:#fff3cd,stroke:#997404
    style V1 fill:#d1e7dd,stroke:#146c43
Loading

New flow

flowchart TD
    A["GPTQModel.generate()"] --> B{"xla or has_cpu_offload_hooks(model)?"}
    B -->|"yes"| N["torch.no_grad()"]
    B -->|"no"| I["torch.inference_mode()"]
    N --> H["CpuOffload.pre_forward: module.to(execution_device)"]
    H --> V["moved params and buffers keep a version counter"]
    I --> R["resident model: no per-forward move"]
    V --> E["eager forward"]
    V --> C["optimize() compiled forward traces"]
    R --> C
    R --> E
    E --> T["generated tokens"]
    C --> T
    style N fill:#d1e7dd,stroke:#146c43
    style V fill:#d1e7dd,stroke:#146c43
    style I fill:#e2e3e5,stroke:#41464b
Loading

Failure and ambiguity paths

Situation Behaviour
A layer carries CpuOffload or AlignDevicesHook(offload=True) generate() uses no_grad; the hook's moves keep every tensor's version counter
A layer carries a resident AlignDevicesHook (offload=False) not counted; the model keeps inference_mode
A SequentialHook wraps an offload hook unwrapped and detected
The model has no offload hook inference_mode, unchanged
The caller wraps generate() in an outer torch.inference_mode() inference mode wins over the inner no_grad; that caller-owned context can still strip a buffer's counter. This PR covers the documented model.optimize(); model.generate() call
A runtime generate is bound (sglang) stays inside the selected context; the runtime owns its tensor lifecycle
A hook is added or removed after load detection runs per generate() call

Evidence

Measured on RTX 5090 (GPU 2), Llama-3.2-1B 4-bit g128, torch 2.15.0+cu132, transformers 5.22.1, accelerate 1.15.0.

Before (e2f9676c6):

  • max_memory={0: "400MiB", "cpu": "20GiB"}, one eager generate(): 0 -> 784 parameters/buffers without _version.
  • optimize() then generate(): RuntimeError: Inference tensors do not track version counter at gptqmodel/nn_modules/qlinear/torch.py:1031.

After:

  • One eager generate(): 0 -> 0 tensors without _version.
  • optimize() then generate() produces The capital of France is Paris, ... for AUTO->TritonV2Linear, GPTQ_TORCH (TorchLinear), and GPTQ_TRITON (TritonV2Linear).
  • GPU-only device="cuda:0": AUTO->MarlinLinear and GPTQ_TORCH still pass after optimize().
  • optimize() alone: 0 tensors without _version (compile setup does not move offloaded weights).
  • Cost of the narrower context on the fully offloaded model, 8-token eager generate, median of 3 after 2 warmups: 5.106 s (inference_mode) vs 5.313 s (no_grad). The path is transfer-bound, so this is within noise; only models with an offload hook pay it.

Tests

New tests/test_optimize_generate_cpu_offload_5099.py:

  • test_eager_generate_keeps_version_counters_on_offloaded_layers — real RTN 4-bit checkpoint, two cpu decoder layers, one eager generate(); asserts the moving hook exists, that generate() produced a token, that the layer is still offloaded, and that no parameter/buffer lost its version counter.
  • test_optimize_then_generate_on_an_offloaded_placement (marked slow) — the documented optimize() then generate() flow; asserts a token, finite output, and no lost version counters.

Red/green evidence (isolated worktree at e2f9676c6 with only the new has_cpu_offload_hooks symbol added so the module imports; the defective generate() is unchanged):

  • fast node: AssertionError: 98 offloaded parameters/buffers have no version counter after one generate()
  • slow node: RuntimeError: Inference tensors do not track version counter. at gptqmodel/nn_modules/qlinear/torch.py:1031
  • both pass with the fix.

Affected family, 57 passed:

CUDA_VISIBLE_DEVICES=2 PYTHONPATH=. HF_HUB_OFFLINE=1 TORCHINDUCTOR_CACHE_DIR=.inductor-cache \
  python -m pytest tests/test_optimize_generate_cpu_offload_5099.py \
  tests/test_optimize_generate_4669.py tests/test_optimize_no_reference_cycle_4937.py \
  tests/test_cpu_offload_device_map_tied_head_4866.py tests/test_cpu_offload_tied_both_copies_4943.py \
  tests/test_marlin_cpu_offload_post_init.py tests/test_generation_compile_policy_4669.py -q

Docs contract: the 5 new entries pass. tests/test_docs_contract_refs.py has 5 failures in docs/gguf-config-resolution.md and docs/rocm-default-environment.md that also fail on a clean upstream/main worktree (37fac3725); they are unrelated to this change.

Lint: /root/venv/bin/ruff check gptqmodel docs/eora tests setup.py passes. format/check.sh cannot run here because its pip install ruff hits PEP 668 in the system Python; the venv's pinned ruff 0.14.2 was used directly.

Reviewer notes

  • Scope limit: an outer torch.inference_mode() chosen by the caller wins over the inner no_grad. A caller-forced inference context can still strip a buffer counter; this PR fixes the documented flow, not a caller-owned stronger context.
  • Detection scans model.modules() once per generate(); O(modules) against a generation call. If a new Accelerate hook class materializes weights per forward, it must be added to has_cpu_offload_hooks.
  • The mechanism page docs/generate-cpu-offload-autograd.md carries the same diagrams and is linked from README's "Memory and recovery" section and the docs index.

`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 tensor replaces
buffers with tensors that have no version counter (#4572). Dynamo reads version
counters, so `optimize()` then `generate()` raised "Inference tensors do not
track version counter" while tracing the first decode step. The eager path left
the same packed buffers without a counter even without `optimize()`.

Select `torch.no_grad()` when the model carries a moving offload hook
(`CpuOffload` or `AlignDevicesHook(offload=True)`, including inside a
`SequentialHook`) and keep `inference_mode` for every other model. Measured on
Llama-3.2-1B 4-bit with all layers offloaded: 5.106 s (inference_mode) vs
5.313 s (no_grad) for an 8-token eager generate, so the narrower context is
within noise on a transfer-bound path.

Add the tensor-lifecycle regression and the documented optimize()+generate()
smoke test, plus a mechanism page with before/after diagrams.
@Qubitium
Qubitium force-pushed the fix/5099-offload-optimize-generate branch from b2bbd2e to e06350c Compare November 18, 2026 06:06
@Qubitium
Qubitium marked this pull request as ready for review November 18, 2026 06:10
@Qubitium
Qubitium merged commit 2656273 into main Nov 18, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/5099-offload-optimize-generate branch November 18, 2026 06:11
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