Repository navigation
fix(generate): keep version counters on CPU-offloaded models (#5099) - #5147
Merged
Merged
Conversation
`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
force-pushed
the
fix/5099-offload-optimize-generate
branch
from
November 18, 2026 06:06
b2bbd2e to
e06350c
Compare
Qubitium
marked this pull request as ready for review
November 18, 2026 06:10
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 #5099
Summary
GPTQModel.generate()selectedtorch.inference_mode()for every non-XLA model. A CPU-offloaded placement (max_memoryCPU budget or adevice_mapwithcpuentries) installs an Accelerate hook that moves each layer withModule._applyon 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, sooptimize(); generate()crashed while tracing the first decode step. The eager path carried the same defect: onegenerate()on the fully offloaded model left 784 packed buffers without a counter even withoutoptimize().The fix selects
torch.no_grad()only when the model actually carries a moving offload hook (CpuOffloadorAlignDevicesHook(offload=True), unwrappingSequentialHook) and keepsinference_modefor every other model.optimize()itself does not move offloaded tensors (measured 0 tensors without a counter afteroptimize()), so the selection only has to covergenerate().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
e2f9676c6)no_gradonly for XLA, otherwiseinference_mode(gptqmodel/models/base.py:3751-3756)no_gradfor XLA orhas_cpu_offload_hooks(self.model)(gptqmodel/models/base.py::generate)has_cpu_offload_hooksscans_hf_hook, unwrapsSequentialHook, matchesCpuOffloadandAlignDevicesHook(offload=True)(gptqmodel/utils/model.py:1776)CpuOffload.pre_forwardcallsmodule.to(execution_device)underinference_mode;simple_dispatch_modelinstalls that hook (gptqmodel/utils/model.py::simple_dispatch_model)no_gradModule._applyreplaces buffers; the second move of an inference buffer stores a tensor without a version countergenerate()g_idx._versionraisesRuntimeError: Inference tensors do not track version counter(gptqmodel/nn_modules/qlinear/torch.py:1031)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:#146c43New 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:#41464bFailure and ambiguity paths
CpuOffloadorAlignDevicesHook(offload=True)generate()usesno_grad; the hook's moves keep every tensor's version counterAlignDevicesHook(offload=False)inference_modeSequentialHookwraps an offload hookinference_mode, unchangedgenerate()in an outertorch.inference_mode()no_grad; that caller-owned context can still strip a buffer's counter. This PR covers the documentedmodel.optimize(); model.generate()callgenerateis bound (sglang)generate()callEvidence
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 eagergenerate(): 0 -> 784 parameters/buffers without_version.optimize()thengenerate():RuntimeError: Inference tensors do not track version counteratgptqmodel/nn_modules/qlinear/torch.py:1031.After:
generate(): 0 -> 0 tensors without_version.optimize()thengenerate()producesThe capital of France is Paris, ...for AUTO->TritonV2Linear,GPTQ_TORCH(TorchLinear), andGPTQ_TRITON(TritonV2Linear).device="cuda:0": AUTO->MarlinLinearandGPTQ_TORCHstill pass afteroptimize().optimize()alone: 0 tensors without_version(compile setup does not move offloaded weights).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, twocpudecoder layers, one eagergenerate(); asserts the moving hook exists, thatgenerate()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(markedslow) — the documentedoptimize()thengenerate()flow; asserts a token, finite output, and no lost version counters.Red/green evidence (isolated worktree at
e2f9676c6with only the newhas_cpu_offload_hookssymbol added so the module imports; the defectivegenerate()is unchanged):AssertionError: 98 offloaded parameters/buffers have no version counter after one generate()RuntimeError: Inference tensors do not track version counter.atgptqmodel/nn_modules/qlinear/torch.py:1031Affected family, 57 passed:
Docs contract: the 5 new entries pass.
tests/test_docs_contract_refs.pyhas 5 failures indocs/gguf-config-resolution.mdanddocs/rocm-default-environment.mdthat also fail on a cleanupstream/mainworktree (37fac3725); they are unrelated to this change.Lint:
/root/venv/bin/ruff check gptqmodel docs/eora tests setup.pypasses.format/check.shcannot run here because itspip install ruffhits PEP 668 in the system Python; the venv's pinnedruff 0.14.2was used directly.Reviewer notes
torch.inference_mode()chosen by the caller wins over the innerno_grad. A caller-forced inference context can still strip a buffer counter; this PR fixes the documented flow, not a caller-owned stronger context.model.modules()once pergenerate(); O(modules) against a generation call. If a new Accelerate hook class materializes weights per forward, it must be added tohas_cpu_offload_hooks.docs/generate-cpu-offload-autograd.mdcarries the same diagrams and is linked from README's "Memory and recovery" section and the docs index.