Repository navigation
fix(mem): drop the reference cycles a single-device GPU load leaves behind (#4847) - #4871
Merged
Qubitium merged 1 commit intoNov 17, 2026
Merged
Conversation
…ehind (ModelCloud#4847) A `GPTQModel.load(..., device="cuda")` model kept its VRAM allocated after the last reference went away, until a full cyclic `gc.collect()`. Three independent cycles caused it: * `simple_dispatch_model` installed one `AlignDevicesHook` per device-map entry even when every entry named the same device. `add_hook_to_module` rebinds `module.forward = partial(new_forward, module)` and keeps the old bound method on `module._old_forward`, so every layer became its own cycle. A map that places everything on one device and has nothing left to materialise now skips the hooks, like accelerate's own `dispatch_model` does for a single device. Maps with a CPU/disk entry or meta tensors still get them. * `_LinearWeightMetadata` stored the module strongly (`self._module`), so every `TorchLinear` kept itself alive through its `weight` shim. It now holds a weak reference and rebuilds after unpickling. * `TorchLinear.optimize()` stored `torch.compile(self.dequantize_weight)` on the module; the compiled wrapper held the bound method (and therefore the module). The unbound function is compiled instead and called through a weak reference. Measured with Llama-3.2-1B-Instruct GPTQ 4-bit g128 on an RTX 4090, gc disabled, `torch.cuda.memory_allocated()` after the model is unreachable: | backend | before | after | | --- | --- | --- | | AUTO (MarlinLinear), 20 hooks | 0.959 GiB | 0.000 GiB | | GPTQ_TORCH (TorchLinear), 112 compiled modules | 0.962 GiB | 0.000 GiB | `generate()` on CPU `input_ids` still works; direct CPU-tensor forwards now require the model device, which is what accelerate and transformers do when no hook is installed. Regression tests (red on the parent commit): `tests/test_single_device_dispatch_4847.py` (5 of 8 nodes red) and `tests/test_quant_linear_release_4847.py` (3 of 4 red).
This was referenced Nov 17, 2026
Qubitium
added a commit
that referenced
this pull request
Nov 17, 2026
…evice (#4908) (#4911) #4871 stopped installing the per-module AlignDevicesHook for a single-device placement, so a direct forward no longer moves CPU inputs to the accelerator. The [gptq_triton] case of test_load_state_dict_round_trip_preserves_v1_model loaded on cuda and forwarded CPU input_ids, raising 'Expected all tensors to be on the same device ... index is on cpu'. Move the fixture's inputs to the model's device; the round-trip assertions are unchanged. Red on main d8758c4 (1 failed), green here (27 passed, 1 skipped).
This was referenced Nov 17, 2026
Qubitium
added a commit
that referenced
this pull request
Nov 17, 2026
#4937) (#4986) #4912 made `BaseQModel.optimize()` compile `model.forward` in place so `generate()` enters the compiled path (#4669). Compiling the *bound* method stored that bound method inside the compiled wrapper, and installing the wrapper as an instance attribute closed a `model -> forward -> model` cycle: the model and its VRAM survived the last user reference until a full cyclic `gc.collect()`. Compile the unbound class function instead and reach the instance through a weak reference, the same pattern `TorchLinear.optimize()` uses for `dequantize_weight` (#4871). `_CompiledModelForward` exposes `_torchdynamo_orig_callable` on demand (a stored bound method would recreate the cycle), so unwrapping callers still see the eager callable, and a repeated `optimize()` recompiles the same unbound function instead of stacking proxies. When compilation is unavailable the instance attribute is removed, so the class method is used again.
sLaffey
pushed a commit
to sLaffey/GPTQModel
that referenced
this pull request
Nov 18, 2026
…lCloud#4978) Seven tests went red because their doubles/oracles predate library changes that behave as intended. This is test-only; no product code changes. - test_fusion_kernel_backends: gc.collect() before the weakref check; ModelCloud#4871 leaves transient Dynamo trace garbage that keeps the pre-fusion weight alive. The refs are still asserted dead afterwards. - test_failed_run_fence_4595: del qmodel + gc.collect() so ModelCloud#4829's finalizer runs before the no-leak assertion; a late finalizer must not recreate the released run dir. - test_exl3_projection_resume: add _release_deferred_hessian_sources() to the _Capture double (ModelCloud#4837). - test_kernel_audit_regressions: stub _needs_torch_fallback=lambda: False on the SimpleNamespace self (ModelCloud#4835). - test_moe_resave_preserves_experts_4589: accept the earlier RuntimeError "does not provide tensors" refusal (ModelCloud#4810); still assert no safetensors. - test_positional_mask_capture_4660: build the native oracle with the same mask-derived position_ids the capture uses (ModelCloud#4930). - test_qqq_kernel_memory_4387: snapshot the oracle weight/s_channel before the first forward, which may drop the checkpoint layout (ModelCloud#4856).
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.
Summary
GPTQModel.load(..., device="cuda")left the model's VRAM allocated after the last user reference was dropped; it only came back on a full cyclicgc.collect(). Closes #4847.Three independent reference cycles, each fixed at its source:
utils/model.py::simple_dispatch_modelAlignDevicesHookper map entry even when all entries named the same device;add_hook_to_modulesetsmodule.forward = partial(new_forward, module)and keepsmodule._old_forwarddispatch_modelrule (hooks only for >1 device or"disk")qlinear/torch.py::_LinearWeightMetadataself._module = module— theweightshim held its module stronglyqlinear/torch.py::TorchLinear.optimizetorch.compile(self.dequantize_weight)on the module; the compiled wrapper held the bound method_CompiledDequantizeWeight)Maps with a
cpu/diskentry, meta tensors, or more than one device still get the hooks. All-CPU/MPS maps are unchanged.Measurements
Llama-3.2-1B-Instruct GPTQ 4-bit g128, RTX 4090,
gc.disable(),torch.cuda.memory_allocated()after the model becomes unreachable:MarlinLinear), 20 hooksGPTQ_TORCH(TorchLinear), 112 compiled modulesHooked modules: 20 -> 0.
generate()with CPUinput_idsstill works (transformersmoves them). A direct forward with CPU tensors now requires the model device — the same contract accelerate and transformers have when no hook is installed.The compiled path is numerically identical to eager:
module.dequantize_weight()vsTorchLinear.dequantize_weight(module)on a loaded layer istorch.equal == True, maxdiff 0.0.Tests
New, red on the parent commit:
Existing suites:
ruff checkon all four touched files: All checks passed.Scope
The
gptqmodel/quantization/awq/utils/utils.pycopy ofsimple_dispatch_modelhas the same hook shape but no importers in the tree; left untouched to keep this diff to the live load path.