Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(model-cache): move GGUF and SDNQ weights fully to the device on full load (#10096)

Alexander Eichhorn7a2e798e50cb
diff --git a/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_only_full_load.py b/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_only_full_load.py
index 69bea6db01..f41cfc09dc 100644
--- a/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_only_full_load.py
+++ b/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_only_full_load.py
@@ -7,6 +7,10 @@ from invokeai.backend.model_manager.load.model_cache.counted_dtypes import retur
from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore
from invokeai.backend.model_manager.load.model_cache.tensor_aliases import StorageKey, analyze_state_dict, storage_key
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
+from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor
+
+# Tensor subclasses whose packed data lives in Python attributes beside the wrapper (see `_move_packed_params`).
+_PACKED_TENSOR_TYPES = (GGMLTensor, SDNQTensor)
class CachedModelOnlyFullLoad:
@@ -58,6 +62,9 @@ class CachedModelOnlyFullLoad:
if isinstance(model, torch.nn.Module)
else None
)
+ self._has_packed_params = isinstance(model, torch.nn.Module) and any(
+ isinstance(p, _PACKED_TENSOR_TYPES) for p in model.parameters()
+ )
# A CPU read-only copy of the model's state dict.
self._cpu_state_dict: dict[str, torch.Tensor] | None = None
@@ -179,14 +186,9 @@ class CachedModelOnlyFullLoad:
new_state_dict[k] = copied[key]
self._model.load_state_dict(new_state_dict, assign=True)
- check_for_gguf = hasattr(self._model, "state_dict") and self._model.state_dict().get("img_in.weight")
- if isinstance(check_for_gguf, GGMLTensor):
- old_value = torch.__future__.get_overwrite_module_params_on_conversion()
- torch.__future__.set_overwrite_module_params_on_conversion(True)
- self._model.to(self._compute_device)
- torch.__future__.set_overwrite_module_params_on_conversion(old_value)
- else:
- self._model.to(self._compute_device)
+ if self._has_packed_params:
+ self._move_packed_params(self._compute_device)
+ self._model.to(self._compute_device)
self._retie_shared_weights()
self._is_in_vram = True
@@ -205,14 +207,9 @@ class CachedModelOnlyFullLoad:
# The RAM copy still has its tied names pointing at one tensor, so this restores the tie as well.
self._model.load_state_dict(self._cpu_state_dict, assign=True)
- check_for_gguf = hasattr(self._model, "state_dict") and self._model.state_dict().get("img_in.weight")
- if isinstance(check_for_gguf, GGMLTensor):
- old_value = torch.__future__.get_overwrite_module_params_on_conversion()
- torch.__future__.set_overwrite_module_params_on_conversion(True)
- self._model.to(self._offload_device)
- torch.__future__.set_overwrite_module_params_on_conversion(old_value)
- else:
- self._model.to(self._offload_device)
+ if self._has_packed_params:
+ self._move_packed_params(self._offload_device)
+ self._model.to(self._offload_device)
self._retie_shared_weights()
self._is_in_vram = False
@@ -228,6 +225,27 @@ class CachedModelOnlyFullLoad:
if self._counted_dtypes is not None:
return_to_counted_dtypes(self._model, self._counted_dtypes, self._alias_groups, self._cpu_state_dict)
+ def _move_packed_params(self, device: torch.device) -> None:
+ """Move the GGUF and SDNQ parameters to `device` by replacing them, before `nn.Module.to()` sees them.
+
+ Between the CPU and an accelerator, `.to()` updates a parameter in place with `param.data = moved`, which swaps
+ only the wrapper's tensor metadata: the packed data, a Python attribute, stays behind, and every forward
+ dequantizes there and copies the result over. Torch's global `set_overwrite_module_params_on_conversion` would
+ replace them instead, but per-device caches load concurrently and would race on it. A parameter shared by
+ several modules is moved once, since `_retie_shared_weights` cannot recognize packed copies as one weight.
+ """
+ moved_by_id: dict[int, torch.nn.Parameter] = {}
+ for module in self._model.modules():
+ for name, param in module._parameters.items():
+ if not isinstance(param, _PACKED_TENSOR_TYPES):
+ continue
+ if id(param) not in moved_by_id:
+ moved = param.to(device)
+ if moved is not param:
+ moved = torch.nn.Parameter(moved, requires_grad=param.requires_grad)
+ moved_by_id[id(param)] = moved
+ module._parameters[name] = moved_by_id[id(param)]
+
def _retie_shared_weights(self) -> None:
"""Re-point the names of a tied weight at one tensor after a device change.
diff --git a/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_only_full_load.py b/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_only_full_load.py
index 3c19386350..235beff515 100644
--- a/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_only_full_load.py
+++ b/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_only_full_load.py
@@ -1,8 +1,15 @@
+from typing import Callable
+
+import gguf
+import pytest
import torch
from invokeai.backend.model_manager.load.model_cache.cached_model.cached_model_only_full_load import (
CachedModelOnlyFullLoad,
)
+from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
+from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor
+from invokeai.backend.quantization.sdnq.utils import SDNQQuantizationType
from tests.backend.model_manager.load.model_cache.cached_model.utils import (
DummyModule,
TiedWeightsModule,
@@ -182,3 +189,88 @@ def test_non_torch_model(device: str, keep_ram_copy: bool):
# Running inference on the CPU should work.
output1 = model.run_inference(torch.randn(1, 10))
assert output1.device.type == "cpu"
+
+
+def _gguf_q8_0_weight(weight: torch.Tensor) -> torch.nn.Parameter:
+ raw = gguf.quantize(weight.numpy(), gguf.GGMLQuantizationType.Q8_0)
+ return torch.nn.Parameter(
+ GGMLTensor(torch.from_numpy(raw), gguf.GGMLQuantizationType.Q8_0, weight.shape, torch.float32),
+ requires_grad=False,
+ )
+
+
+def _sdnq_int8_weight(weight: torch.Tensor) -> torch.nn.Parameter:
+ scale = weight.abs().amax(dim=1, keepdim=True) / 127
+ data = torch.round(weight / scale).to(torch.int8)
+ return torch.nn.Parameter(
+ SDNQTensor(data, SDNQQuantizationType.INT8_SYM, weight.shape, torch.float32, scale=scale),
+ requires_grad=False,
+ )
+
+
+def _packed_payloads(weight: torch.Tensor) -> list[torch.Tensor]:
+ """The tensors a packed weight keeps as Python attributes, beside its wrapper."""
+ if isinstance(weight, SDNQTensor):
+ return [weight.quantized_data, weight._scale]
+ assert isinstance(weight, GGMLTensor)
+ return [weight.quantized_data]
+
+
+def _model_with_packed_weight(
+ module_name: str, make_packed_weight: Callable[[torch.Tensor], torch.nn.Parameter]
+) -> torch.nn.Module:
+ torch.manual_seed(0)
+ linear = torch.nn.Linear(64, 64, bias=False)
+ linear.weight = make_packed_weight(linear.weight.detach())
+ model = torch.nn.Module()
+ model.add_module(module_name, linear)
+ return model
+
+
+parameterize_packed_weight = pytest.mark.parametrize(
+ "make_packed_weight", [_gguf_q8_0_weight, _sdnq_int8_weight], ids=["gguf", "sdnq"]
+)
+
+
+@parameterize_mps_and_cuda
+@parameterize_packed_weight
+@parameterize_keep_ram_copy
+def test_a_quantized_weight_runs_on_the_device_and_returns_to_the_cpu(
+ device: str, make_packed_weight: Callable[[torch.Tensor], torch.nn.Parameter], keep_ram_copy: bool
+):
+ model = _model_with_packed_weight("proj_in", make_packed_weight)
+ cached_model = CachedModelOnlyFullLoad(
+ model=model, compute_device=torch.device(device), total_bytes=100, keep_ram_copy=keep_ram_copy
+ )
+ x = torch.randn(2, 64)
+ expected = model.proj_in(x)
+
+ cached_model.full_load_to_vram()
+
+ assert {t.device.type for t in _packed_payloads(model.proj_in.weight)} == {device}
+ assert torch.allclose(model.proj_in(x.to(device)).cpu(), expected, atol=1e-4)
+
+ cached_model.full_unload_from_vram()
+
+ assert {t.device.type for t in _packed_payloads(model.proj_in.weight)} == {"cpu"}
+
+
+@parameterize_packed_weight
+def test_a_quantized_weight_shared_by_two_layers_moves_as_one_copy(
+ make_packed_weight: Callable[[torch.Tensor], torch.nn.Parameter],
+):
+ """Moving each layer's parameter on its own would give the shared weight two copies on the device, and the re-tie
+ after the move cannot rejoin them: a packed weight has no storage of its own to recognize the alias by. The meta
+ device takes the same replace-the-parameter path the load uses on every device, so this runs without a GPU.
+ """
+ model = _model_with_packed_weight("proj_in", make_packed_weight)
+ model.add_module("proj_out", torch.nn.Linear(64, 64, bias=False))
+ model.proj_out.weight = model.proj_in.weight
+ cached_model = CachedModelOnlyFullLoad(
+ model=model, compute_device=torch.device("meta"), total_bytes=100, keep_ram_copy=False
+ )
+
+ cached_model.full_load_to_vram()
+
+ assert model.proj_in.weight.quantized_data.device.type == "meta"
+ assert model.proj_out.weight.quantized_data is model.proj_in.weight.quantized_data