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-manager): recover accounting after failed transfers

JPPhoto4a8e3685212c
diff --git a/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_with_partial_load.py b/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_with_partial_load.py
index 33be044572..4409836134 100644
--- a/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_with_partial_load.py
+++ b/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_with_partial_load.py
@@ -1,4 +1,6 @@
import weakref
+from contextlib import contextmanager
+from typing import Iterator
import torch
@@ -183,13 +185,26 @@ class CachedModelWithPartialLoad:
for module in self._model.modules():
for name, buffer in module.named_buffers():
if name in module._non_persistent_buffers_set:
- module._buffers[name] = buffer.to(device, copy=True)
+ if buffer.device.type != device.type or (
+ device.index is not None and buffer.device.index != device.index
+ ):
+ module._buffers[name] = buffer.to(device, copy=True)
def _set_autocast_enabled_in_all_modules(self, enabled: bool):
"""Set autocast_enabled flag in all modules that support device autocasting."""
for module in self._modules_that_support_autocast.values():
module.set_device_autocasting_enabled(enabled)
+ @contextmanager
+ def _transfer_operation(self) -> Iterator[None]:
+ """Invalidate derived residency state if a transfer leaves the model partially changed."""
+ try:
+ yield
+ except BaseException:
+ self._cur_vram_bytes = None
+ self._set_autocast_enabled_in_all_modules(True)
+ raise
+
@property
def model(self) -> torch.nn.Module:
return self._model
@@ -268,12 +283,12 @@ class CachedModelWithPartialLoad:
# Tied names come along, but the count stays what the caller asked about: required tensors repaired.
self._select_with_aliases(keys_to_repair, key)
repaired_required_tensors += 1
- if len(keys_to_repair) == 0:
- return 0
-
- self._load_state_dict_with_device_conversion(cur_state_dict, keys_to_repair, self._compute_device)
- self._move_non_persistent_buffers_to_device(self._compute_device)
- self._cur_vram_bytes = None
+ with self._transfer_operation():
+ if keys_to_repair:
+ self._load_state_dict_with_device_conversion(cur_state_dict, keys_to_repair, self._compute_device)
+ self._move_non_persistent_buffers_to_device(self._compute_device)
+ if keys_to_repair:
+ self._cur_vram_bytes = None
return repaired_required_tensors
def _load_state_dict_with_device_conversion(
@@ -380,9 +395,6 @@ class CachedModelWithPartialLoad:
`max_bytes` was reached while more weights would otherwise have been selected — i.e.
another call can make further progress toward the same `vram_bytes_to_load` budget.
"""
- # TODO(ryand): Handle the case where an exception is thrown while loading or unloading weights. At the very
- # least, we should reset self._cur_vram_bytes to None.
-
if max_bytes is not None and max_bytes <= 0:
# A non-positive cap would return (0, truncated=True) forever and spin any caller that
# loops until settled.
@@ -443,25 +455,26 @@ class CachedModelWithPartialLoad:
vram_bytes_loaded += self._select_with_aliases(keys_to_load, key)
- if len(keys_to_load) > 0:
- # We load the entire state dict, not just the parameters that changed, in case there are modules that
- # override _load_from_state_dict() and do some funky stuff that requires the entire state dict.
- # Alternatively, in the future, grouping parameters by module could probably solve this problem.
- self._load_state_dict_with_device_conversion(cur_state_dict, keys_to_load, self._compute_device)
+ with self._transfer_operation():
+ if len(keys_to_load) > 0:
+ # We load the entire state dict, not just the parameters that changed, in case there are modules that
+ # override _load_from_state_dict() and do some funky stuff that requires the entire state dict.
+ # Alternatively, in the future, grouping parameters by module could probably solve this problem.
+ self._load_state_dict_with_device_conversion(cur_state_dict, keys_to_load, self._compute_device)
- if self._cur_vram_bytes is not None:
- self._cur_vram_bytes += vram_bytes_loaded
+ if self._cur_vram_bytes is not None:
+ self._cur_vram_bytes += vram_bytes_loaded
- if fully_loaded and not truncated:
- self._set_autocast_enabled_in_all_modules(False)
- else:
- # Not fully resident (or a truncated pass whose remaining keys are unknown): the
- # autocast wrappers must stay enabled so the model stays runnable either way.
- self._set_autocast_enabled_in_all_modules(True)
+ if fully_loaded and not truncated:
+ self._set_autocast_enabled_in_all_modules(False)
+ else:
+ # Not fully resident (or a truncated pass whose remaining keys are unknown): the
+ # autocast wrappers must stay enabled so the model stays runnable either way.
+ self._set_autocast_enabled_in_all_modules(True)
- # Move all non-persistent buffers to the compute device. These are a weird edge case and do not participate in
- # the vram_bytes_loaded tracking.
- self._move_non_persistent_buffers_to_device(self._compute_device)
+ # Move all non-persistent buffers to the compute device. These are a weird edge case and do not participate
+ # in the vram_bytes_loaded tracking.
+ self._move_non_persistent_buffers_to_device(self._compute_device)
return vram_bytes_loaded, truncated
@@ -503,13 +516,14 @@ class CachedModelWithPartialLoad:
vram_bytes_freed += self._select_with_aliases(keys_to_offload, key)
- if len(keys_to_offload) > 0:
- self._load_state_dict_with_device_conversion(cur_state_dict, keys_to_offload, torch.device("cpu"))
+ with self._transfer_operation():
+ if len(keys_to_offload) > 0:
+ self._load_state_dict_with_device_conversion(cur_state_dict, keys_to_offload, torch.device("cpu"))
- if self._cur_vram_bytes is not None:
- self._cur_vram_bytes -= vram_bytes_freed
+ if self._cur_vram_bytes is not None:
+ self._cur_vram_bytes -= vram_bytes_freed
- # We may have gone from a fully-loaded model to a partially-loaded model, so we need to reapply the custom
- # layers.
- self._set_autocast_enabled_in_all_modules(True)
+ # We may have gone from a fully-loaded model to a partially-loaded model, so we need to reapply the custom
+ # layers.
+ self._set_autocast_enabled_in_all_modules(True)
return vram_bytes_freed
diff --git a/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_with_partial_load.py b/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_with_partial_load.py
index 81309713ca..50e77c7f72 100644
--- a/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_with_partial_load.py
+++ b/tests/backend/model_manager/load/model_cache/cached_model/test_cached_model_with_partial_load.py
@@ -536,14 +536,17 @@ def test_partial_transfer_failure_invalidates_vram_accounting(operation: str, mo
def test_transfer_failure_after_one_module_recounts_actual_residency(operation: str, monkeypatch: pytest.MonkeyPatch):
"""OOM/device errors can interrupt the module-by-module transfer after earlier modules changed devices."""
model = torch.nn.Sequential(torch.nn.Linear(4, 4), torch.nn.Linear(4, 2))
+ apply_custom_layers_to_model(model)
first_bytes = sum(param.numel() * param.element_size() for param in model[0].parameters())
second_bytes = sum(param.numel() * param.element_size() for param in model[1].parameters())
cached_model = CachedModelWithPartialLoad(
model=model, compute_device=torch.device("meta"), keep_ram_copy=operation == "unload"
)
if operation == "unload":
- # Retain genuine CPU weights before simulating initial accelerator residency.
- model.to("meta")
+ # Start from fully loaded state so failure must re-enable custom autocast.
+ cached_model.full_load_to_vram()
+ assert not model[0].is_device_autocasting_enabled()
+ assert not model[1].is_device_autocasting_enabled()
transfer = cached_model.partial_unload_from_vram
assert cached_model.cur_vram_bytes() == first_bytes + second_bytes
expected_devices = ("cpu", "meta")
@@ -564,3 +567,43 @@ def test_transfer_failure_after_one_module_recounts_actual_residency(operation:
assert tuple(module.weight.device.type for module in model) == expected_devices
assert cached_model.cur_vram_bytes() == expected_bytes
+ assert model[0].is_device_autocasting_enabled()
+ assert model[1].is_device_autocasting_enabled()
+
+
+def test_partial_load_buffer_failure_invalidates_accounting_and_enables_autocast(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ model = DummyModule()
+ apply_custom_layers_to_model(model)
+ cached_model = CachedModelWithPartialLoad(model=model, compute_device=torch.device("meta"), keep_ram_copy=False)
+
+ def fail_buffer_move(device: torch.device) -> None:
+ raise RuntimeError("simulated buffer transfer failure")
+
+ monkeypatch.setattr(cached_model, "_move_non_persistent_buffers_to_device", fail_buffer_move)
+
+ with pytest.raises(RuntimeError, match="simulated buffer transfer failure"):
+ cached_model.full_load_to_vram()
+
+ assert cached_model._cur_vram_bytes is None
+ assert model.linear1.is_device_autocasting_enabled()
+ assert model.linear2.is_device_autocasting_enabled()
+
+
+def test_partial_load_retry_after_failure_accounts_actual_residency(monkeypatch: pytest.MonkeyPatch) -> None:
+ model = torch.nn.Sequential(torch.nn.Linear(4, 4), torch.nn.Linear(4, 2))
+ cached_model = CachedModelWithPartialLoad(model=model, compute_device=torch.device("meta"), keep_ram_copy=False)
+ original_load = model[1]._load_from_state_dict
+
+ def fail_second_module(*args, **kwargs):
+ raise RuntimeError("second module transfer failed")
+
+ monkeypatch.setattr(model[1], "_load_from_state_dict", fail_second_module)
+ with pytest.raises(RuntimeError, match="second module transfer failed"):
+ cached_model.full_load_to_vram()
+
+ monkeypatch.setattr(model[1], "_load_from_state_dict", original_load)
+ cached_model.full_load_to_vram()
+
+ assert cached_model.cur_vram_bytes() == cached_model.total_bytes()
diff --git a/tests/backend/model_manager/load/model_cache/cached_model/test_repair_required_tensors.py b/tests/backend/model_manager/load/model_cache/cached_model/test_repair_required_tensors.py
index 306e655a18..4def0378d4 100644
--- a/tests/backend/model_manager/load/model_cache/cached_model/test_repair_required_tensors.py
+++ b/tests/backend/model_manager/load/model_cache/cached_model/test_repair_required_tensors.py
@@ -14,6 +14,7 @@ class ModelWithRequiredScale(torch.nn.Module):
super().__init__()
self.linear = torch.nn.Linear(4, 4)
self.scale = torch.nn.Parameter(torch.ones(4))
+ self.register_buffer("transient", torch.ones(4), persistent=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.linear(x) * self.scale
@@ -45,3 +46,60 @@ def test_repair_required_tensors_on_compute_device(device: torch.device, keep_ra
assert cached_model._cur_vram_bytes is None
assert model.scale.device.type == device.type
assert all(param.device.type == "cpu" for param in model.linear.parameters())
+
+
+def test_repair_failure_invalidates_accounting_and_retry_repairs_remaining_tensors(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ model = torch.nn.Sequential(torch.nn.Linear(4, 4), torch.nn.Linear(4, 2))
+ cached_model = CachedModelWithPartialLoad(model=model, compute_device=torch.device("meta"), keep_ram_copy=False)
+ cached_model._cur_vram_bytes = 0
+ original_load = model[1]._load_from_state_dict
+
+ def fail_second_module(*args, **kwargs):
+ raise RuntimeError("second module repair failed")
+
+ monkeypatch.setattr(model[1], "_load_from_state_dict", fail_second_module)
+
+ with pytest.raises(RuntimeError, match="second module repair failed"):
+ cached_model.repair_required_tensors_on_compute_device()
+
+ assert model[0].weight.is_meta
+ assert not model[1].weight.is_meta
+ assert cached_model._cur_vram_bytes is None
+
+ monkeypatch.setattr(model[1], "_load_from_state_dict", original_load)
+ repaired_tensors = cached_model.repair_required_tensors_on_compute_device()
+
+ assert repaired_tensors == 2
+ assert all(param.is_meta for param in model.parameters())
+ assert cached_model.cur_vram_bytes() == cached_model.total_bytes()
+
+
+def test_repair_retries_non_persistent_buffer_after_required_tensor_moves(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ model = ModelWithRequiredScale()
+ cached_model = CachedModelWithPartialLoad(model=model, compute_device=torch.device("meta"), keep_ram_copy=False)
+ cached_model._cur_vram_bytes = 0
+ move_buffers = cached_model._move_non_persistent_buffers_to_device
+
+ def fail_buffer_move(device: torch.device) -> None:
+ raise RuntimeError("simulated buffer repair failure")
+
+ monkeypatch.setattr(cached_model, "_move_non_persistent_buffers_to_device", fail_buffer_move)
+
+ with pytest.raises(RuntimeError, match="simulated buffer repair failure"):
+ cached_model.repair_required_tensors_on_compute_device()
+
+ assert model.scale.is_meta
+ assert model.transient.device.type == "cpu"
+ assert cached_model._cur_vram_bytes is None
+
+ monkeypatch.setattr(cached_model, "_move_non_persistent_buffers_to_device", move_buffers)
+ assert cached_model.repair_required_tensors_on_compute_device() == 0
+ assert model.transient.is_meta
+
+ repaired_buffer = model.transient
+ assert cached_model.repair_required_tensors_on_compute_device() == 0
+ assert model.transient is repaired_buffer