Skip to content

fix(mem): drop the reference cycles a single-device GPU load leaves behind (#4847) - #4871

Merged
Qubitium merged 1 commit into
ModelCloud:mainfrom
Qubitium:fix/4847-single-device-dispatch
Nov 17, 2026
Merged

Qubitium merged 1 commit into
ModelCloud:mainfrom
Qubitium:fix/4847-single-device-dispatch

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

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 cyclic gc.collect(). Closes #4847.

Three independent reference cycles, each fixed at its source:

Where Cycle Fix
utils/model.py::simple_dispatch_model one AlignDevicesHook per map entry even when all entries named the same device; add_hook_to_module sets module.forward = partial(new_forward, module) and keeps module._old_forward a map that places everything on one non-offload device and has nothing left to materialise installs no hooks, matching accelerate's dispatch_model rule (hooks only for >1 device or "disk")
qlinear/torch.py::_LinearWeightMetadata self._module = module — the weight shim held its module strongly weak reference; the shim rebuilds lazily after unpickling
qlinear/torch.py::TorchLinear.optimize stored torch.compile(self.dequantize_weight) on the module; the compiled wrapper held the bound method compile the unbound function, call it through a weak reference (_CompiledDequantizeWeight)

Maps with a cpu/disk entry, 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:

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

Hooked modules: 20 -> 0. generate() with CPU input_ids still works (transformers moves 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() vs TorchLinear.dequantize_weight(module) on a loaded layer is torch.equal == True, maxdiff 0.0.

Tests

New, red on the parent commit:

python -m pytest tests/test_single_device_dispatch_4847.py tests/test_quant_linear_release_4847.py -q
# 12 passed
# parent commit: 5/8 and 3/4 fail

Existing suites:

python -m pytest tests/test_torch.py tests/test_torch_compile_fallback.py     tests/test_generation_compile_policy_4669.py tests/test_rehome_hook_realign.py -q
# 87 passed, 1 skipped
python -m pytest tests/test_qwen4_exp_support.py -q            # 42 passed, 1 skipped
python -m pytest tests/test_norm_requant.py tests/test_serialization.py -q   # 22 passed

ruff check on all four touched files: All checks passed.

Scope

The gptqmodel/quantization/awq/utils/utils.py copy of simple_dispatch_model has the same hook shape but no importers in the tree; left untouched to keep this diff to the live load path.

…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).
@Qubitium
Qubitium merged commit 1ba6703 into ModelCloud:main Nov 17, 2026
1 check passed
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).
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).
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