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): keep tied weights as one tensor

Alexander Eichhorna4a116fe67f6
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 226f65f699..efa0de36d4 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
@@ -4,6 +4,7 @@ from typing import Any
import torch
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
@@ -44,6 +45,12 @@ class CachedModelOnlyFullLoad:
self._shared_key: str | None = None
self._shared_release_finalizer: weakref.finalize | None = None
+ # The keys of every tied weight, so a device change can re-point them at one tensor (see
+ # `_retie_shared_weights`). Empty for models that are not `nn.Module`s and for the usual untied ones.
+ self._alias_groups: dict[str, tuple[str, ...]] = (
+ analyze_state_dict(model.state_dict()).groups if isinstance(model, torch.nn.Module) else {}
+ )
+
# A CPU read-only copy of the model's state dict.
self._cpu_state_dict: dict[str, torch.Tensor] | None = None
if isinstance(model, torch.nn.Module) and keep_ram_copy:
@@ -153,9 +160,15 @@ class CachedModelOnlyFullLoad:
return 0
if self._cpu_state_dict is not None:
+ # Tied weights appear under several keys; copying each name on its own would put two copies on the device
+ # and untie them (see `tensor_aliases`).
+ copied: dict[StorageKey, torch.Tensor] = {}
new_state_dict: dict[str, torch.Tensor] = {}
for k, v in self._cpu_state_dict.items():
- new_state_dict[k] = v.to(self._compute_device, copy=True)
+ key = storage_key(v)
+ if key not in copied:
+ copied[key] = v.to(self._compute_device, copy=True)
+ 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")
@@ -167,6 +180,7 @@ class CachedModelOnlyFullLoad:
else:
self._model.to(self._compute_device)
+ self._retie_shared_weights()
self._is_in_vram = True
return self._total_bytes
@@ -180,6 +194,7 @@ class CachedModelOnlyFullLoad:
return 0
if self._cpu_state_dict is not None:
+ # 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")
@@ -191,5 +206,22 @@ class CachedModelOnlyFullLoad:
else:
self._model.to(self._offload_device)
+ self._retie_shared_weights()
self._is_in_vram = False
return self._total_bytes
+
+ def _retie_shared_weights(self) -> None:
+ """Re-point the names of a tied weight at one tensor after a device change.
+
+ `nn.Module.to()` copies each module's parameters with no memo across the modules that share one, so a tied
+ weight arrives as two tensors -- twice the memory, and writes through one name no longer visible through the
+ other. Only the `keep_ram_copy=False` path goes through `.to()` for the weights; with a RAM copy the state
+ dict is moved above, one copy per distinct tensor, and never splits. Dropping the duplicate here keeps its
+ cost to the move itself rather than for as long as the model is resident.
+ """
+ if not self._alias_groups:
+ return
+ state_dict = self._model.state_dict()
+ self._model.load_state_dict(
+ {key: state_dict[group[0]] for key, group in self._alias_groups.items()}, strict=False, assign=True
+ )
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 d19de2b1cd..33be044572 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
@@ -3,10 +3,14 @@ import weakref
import torch
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,
+ move_shared,
+)
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_module_mixin import (
CustomModuleMixin,
)
-from invokeai.backend.util.calc_tensor_size import calc_tensor_size
from invokeai.backend.util.logging import InvokeAILogger
@@ -51,7 +55,13 @@ class CachedModelWithPartialLoad:
# below. The re-point only swaps tensor storage; keys, shapes and dtypes are unchanged, so the
# metadata is identical either way. Computing it first keeps the acquire the last (and only
# failure-prone) step, so a failure there can release the reference cleanly without leaking it.
- self._state_dict_bytes = {k: calc_tensor_size(v) for k, v in model_state_dict.items()}
+ #
+ # Tied weights share one tensor under several keys. Their bytes are charged to the first of those keys and
+ # the rest are charged 0, so every sum over this dict counts the memory once; `_aliases` below keeps the
+ # group moving as a unit, so a charged key and its free aliases are never on different devices.
+ aliases = analyze_state_dict(model_state_dict)
+ self._aliases = aliases.groups
+ self._state_dict_bytes = aliases.bytes_by_key
self._total_bytes = sum(self._state_dict_bytes.values())
self._cur_vram_bytes: int | None = None
self._modules_that_support_autocast = self._find_modules_that_support_autocast()
@@ -94,6 +104,19 @@ class CachedModelWithPartialLoad:
self._cpu_state_dict = cpu_state_dict
+ def _select_with_aliases(self, selected: set[str], key: str) -> int:
+ """Add `key` and everything tied to it to `selected`; return the bytes that adds.
+
+ A group moves as a unit: selecting only the alias that is charged 0 bytes would move the memory while the
+ accounting recorded nothing.
+ """
+ added_bytes = 0
+ for group_key in self._aliases.get(key, (key,)):
+ if group_key not in selected:
+ selected.add(group_key)
+ added_bytes += self._state_dict_bytes[group_key]
+ return added_bytes
+
def _find_modules_that_support_autocast(self) -> dict[str, torch.nn.Module]:
"""Find all modules that support autocasting."""
return {n: m for n, m in self._model.named_modules() if isinstance(m, CustomModuleMixin)} # type: ignore
@@ -238,18 +261,20 @@ class CachedModelWithPartialLoad:
movement invalidates the cached VRAM accounting.
"""
cur_state_dict = self._model.state_dict()
- keys_to_repair = {
- key
- for key in self._keys_in_modules_that_do_not_support_autocast
- if cur_state_dict[key].device.type != self._compute_device.type
- }
+ keys_to_repair: set[str] = set()
+ repaired_required_tensors = 0
+ for key in self._keys_in_modules_that_do_not_support_autocast:
+ if cur_state_dict[key].device.type != self._compute_device.type:
+ # 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
- return len(keys_to_repair)
+ return repaired_required_tensors
def _load_state_dict_with_device_conversion(
self, state_dict: dict[str, torch.Tensor], keys_to_convert: set[str], target_device: torch.device
@@ -283,6 +308,7 @@ class CachedModelWithPartialLoad:
peak virtual memory usage. Specifically, we want to avoid a case where we hold references to all of the CPU weights
and CUDA weights simultaneously, because Windows will reserve virtual memory for both.
"""
+ moved: dict[StorageKey, torch.Tensor] = {}
for module_name, module in self._model.named_modules():
module_keys = self._state_dict_keys_by_module_prefix.get(module_name, [])
# Calculate the length of the module name prefix.
@@ -295,7 +321,7 @@ class CachedModelWithPartialLoad:
if key in keys_to_convert:
# It is important that we overwrite `state_dict[key]` to avoid keeping two copies of the same
# parameter.
- state_dict[key] = state_dict[key].to(target_device)
+ state_dict[key] = move_shared(state_dict[key], target_device, moved)
# Note that we keep parameters that have not been moved to a new device in case the module implements
# weird custom state dict loading logic that requires all parameters to be present.
module_state_dict[key[prefix_len:]] = state_dict[key]
@@ -319,11 +345,13 @@ class CachedModelWithPartialLoad:
"""Convert parameters to the target device and load them into the model. Leverages the `cpu_state_dict` to speed
up transfers of weights to the CPU.
"""
+ moved: dict[StorageKey, torch.Tensor] = {}
for key in keys_to_convert:
if target_device.type == "cpu":
+ # The CPU copy already shares one tensor between tied keys, so this restores the tie too.
state_dict[key] = cpu_state_dict[key]
else:
- state_dict[key] = state_dict[key].to(target_device)
+ state_dict[key] = move_shared(state_dict[key], target_device, moved)
self._model.load_state_dict(state_dict, assign=True)
@@ -375,9 +403,7 @@ class CachedModelWithPartialLoad:
if param.device.type == self._compute_device.type:
continue
- keys_to_load.add(key)
- param_size = self._state_dict_bytes[key]
- vram_bytes_loaded += param_size
+ vram_bytes_loaded += self._select_with_aliases(keys_to_load, key)
if vram_bytes_loaded > vram_bytes_to_load:
logger = InvokeAILogger.get_logger()
@@ -404,14 +430,18 @@ class CachedModelWithPartialLoad:
break
param_size = self._state_dict_bytes[key]
+ if param_size == 0 and key in self._aliases:
+ # A tied key whose group is charged to another name. It is loaded with that name, against the budget;
+ # selecting it here would move the group's memory without the budget ever seeing its bytes.
+ continue
+
if vram_bytes_loaded + param_size > vram_bytes_to_load:
# TODO(ryand): Should we just break here? If we couldn't fit this parameter into VRAM, is it really
# worth continuing to search for a smaller parameter that would fit?
fully_loaded = False
continue
- keys_to_load.add(key)
- vram_bytes_loaded += param_size
+ 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
@@ -461,12 +491,17 @@ class CachedModelWithPartialLoad:
if param.device.type == offload_device:
continue
- if keep_required_weights_in_vram and key in self._keys_in_modules_that_do_not_support_autocast:
+ # A group is kept whenever any of its names is required: offloading it through one of its other names
+ # would take the required tensor to the CPU with it, and the next forward would fail on the device
+ # mismatch.
+ if keep_required_weights_in_vram and any(
+ group_key in self._keys_in_modules_that_do_not_support_autocast
+ for group_key in self._aliases.get(key, (key,))
+ ):
required_weights_in_vram += self._state_dict_bytes[key]
continue
- keys_to_offload.add(key)
- vram_bytes_freed += self._state_dict_bytes[key]
+ 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"))
diff --git a/invokeai/backend/model_manager/load/model_cache/shared_cpu_weights.py b/invokeai/backend/model_manager/load/model_cache/shared_cpu_weights.py
index 2992e1adfb..e0a8db38b4 100644
--- a/invokeai/backend/model_manager/load/model_cache/shared_cpu_weights.py
+++ b/invokeai/backend/model_manager/load/model_cache/shared_cpu_weights.py
@@ -4,7 +4,7 @@ from dataclasses import dataclass, field
import torch
-from invokeai.backend.util.calc_tensor_size import calc_tensor_size
+from invokeai.backend.model_manager.load.model_cache.tensor_aliases import analyze_state_dict
@dataclass
@@ -90,7 +90,8 @@ class SharedCpuWeightsStore:
if entry is None:
entry = _SharedWeightsEntry(
state_dict=state_dict,
- total_bytes=sum(calc_tensor_size(v) for v in state_dict.values()),
+ # Tied weights appear under several keys; charging each name would count that memory twice.
+ total_bytes=sum(analyze_state_dict(state_dict).bytes_by_key.values()),
)
self._entries[key] = entry
entry.refcount += 1
diff --git a/invokeai/backend/model_manager/load/model_cache/tensor_aliases.py b/invokeai/backend/model_manager/load/model_cache/tensor_aliases.py
new file mode 100644
index 0000000000..ebb64cc50e
--- /dev/null
+++ b/invokeai/backend/model_manager/load/model_cache/tensor_aliases.py
@@ -0,0 +1,82 @@
+"""Recognizing state dict entries that are one tensor under several names.
+
+A tied weight -- a language model's `lm_head.weight` sharing the embedding matrix is the common case, and every Qwen3
+text encoder InvokeAI loads is built that way -- appears in `state_dict()` under each of its names. Summing such a
+dict charges the memory once per name, and moving each name to the compute device on its own allocates it once per
+name and unties them: a Qwen3 4B encoder wastes 0.7 GiB of VRAM that way, an 8B encoder 1.2 GiB.
+"""
+
+from dataclasses import dataclass
+
+import torch
+
+from invokeai.backend.util.calc_tensor_size import calc_tensor_size
+
+# A tensor's identity as memory: two entries with the same key are the same bytes, read the same way.
+StorageKey = tuple[int, int, torch.dtype, tuple[int, ...], tuple[int, ...]] | int
+
+
+def storage_key(tensor: torch.Tensor) -> StorageKey:
+ """A key that is equal for two tensors exactly when they are the same memory, read the same way.
+
+ Tensors with no memory behind them answer by identity instead: `data_ptr()` is 0 for meta tensors and for
+ zero-element ones, so keying on it would declare every such tensor the same memory as the others. Quantized
+ tensor subclasses (GGUF, SDNQ) do not expose an untyped storage at all and fall back the same way. Identity
+ treats a tensor as unshared, which only forgoes deduplication; it never reports two distinct tensors as one.
+
+ The dtype and the byte offset are part of the key because two views of one storage can start at the same address
+ and still be different values -- handing one of them out for the other would be a silently wrong weight.
+ """
+ try:
+ data_pointer = tensor.untyped_storage().data_ptr()
+ except (NotImplementedError, RuntimeError, AttributeError):
+ return id(tensor)
+ if data_pointer == 0:
+ return id(tensor)
+ return (
+ data_pointer,
+ tensor.storage_offset() * tensor.element_size(),
+ tensor.dtype,
+ tuple(tensor.shape),
+ tuple(tensor.stride()),
+ )
+
+
+@dataclass(frozen=True)
+class StateDictAliases:
+ """How a state dict's keys map onto memory.
+
+ `bytes_by_key` charges each tensor to the first key that names it and the rest 0, so summing it counts the memory
+ once. `groups` names, for every key that shares memory, all the keys of that group: a caller moving tensors
+ between devices has to keep a group together, or the bytes charged to one key would move under another.
+ """
+
+ bytes_by_key: dict[str, int]
+ groups: dict[str, tuple[str, ...]]
+
+
+def analyze_state_dict(state_dict: dict[str, torch.Tensor]) -> StateDictAliases:
+ """Charge every tensor in `state_dict` once and find the keys that share memory."""
+ bytes_by_key: dict[str, int] = {}
+ keys_by_storage: dict[StorageKey, list[str]] = {}
+ for key, tensor in state_dict.items():
+ key_storage = storage_key(tensor)
+ group = keys_by_storage.setdefault(key_storage, [])
+ bytes_by_key[key] = calc_tensor_size(tensor) if not group else 0
+ group.append(key)
+ groups = {key: tuple(group) for group in keys_by_storage.values() if len(group) > 1 for key in group}
+ return StateDictAliases(bytes_by_key=bytes_by_key, groups=groups)
+
+
+def move_shared(tensor: torch.Tensor, device: torch.device, moved: dict[StorageKey, torch.Tensor]) -> torch.Tensor:
+ """Move `tensor` to `device`, reusing the result for every other entry that is the same memory.
+
+ `moved` accumulates across one conversion pass, so the tensors stay tied on the target device instead of becoming
+ independent copies.
+ """
+ key = storage_key(tensor)
+ already_moved = moved.get(key)
+ if already_moved is None:
+ already_moved = tensor.to(device)
+ moved[key] = already_moved
+ return already_moved
diff --git a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py
index 8483e5590d..d6ba9f9771 100644
--- a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py
+++ b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py
@@ -297,8 +297,6 @@ class MiniMaxH3TextEncoderCheckpointModel(ModelLoader):
Like the H3 transformer checkpoints, quantized layers are not autocast-wrapped, so
residency is all-or-nothing: the int8 file needs ~26 GiB free VRAM while encoding (it
idle-offloads afterwards); graceful partial-load degradation is the folder encoder's job.
- If partial load does engage, the tied lm_head/embed_tokens alias additionally splits into
- two device tensors (~1.56 GB overhead) - see the tie_weights() note in the load path.
"""
def _load_model(
@@ -413,10 +411,8 @@ class MiniMaxH3TextEncoderCheckpointModel(ModelLoader):
)
# Re-tie now that embed_tokens holds the loaded tensor (assign=True replaced the meta
# parameter the original tie pointed at). The head is never run; tying keeps the module
- # free of meta tensors and adds no RAM (aliased storage). Caveat: the model cache's
- # partial-load path moves state-dict keys independently (no data_ptr dedupe), so on that
- # path the tied pair splits into two device tensors (~1.56 GB extra VRAM, double-counted
- # in the cache's accounting). Fully-resident loads - the intended regime - keep the alias.
+ # free of meta tensors and adds no RAM (aliased storage), and the model cache keeps the
+ # alias on the compute device too (see `tensor_aliases`).
model.tie_weights()
return model
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 509d6494a9..3c19386350 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
@@ -5,6 +5,7 @@ from invokeai.backend.model_manager.load.model_cache.cached_model.cached_model_o
)
from tests.backend.model_manager.load.model_cache.cached_model.utils import (
DummyModule,
+ TiedWeightsModule,
parameterize_keep_ram_copy,
parameterize_mps_and_cuda,
)
@@ -65,6 +66,46 @@ def test_cached_model_full_load_and_unload(device: str, keep_ram_copy: bool):
assert all(p.device.type == "cpu" for p in cached_model.model.parameters())
+@parameterize_keep_ram_copy
+def test_a_tie_broken_by_the_move_is_restored(keep_ram_copy: bool):
+ """A tied weight is in the state dict under both names, and `nn.Module.to()` copies each module's parameters
+ without a memo across the modules that share one: the weight arrives as two tensors, so the model holds memory it
+ never reads through the second name and `total_bytes` (which counts it once) under-reports what is resident.
+
+ The split is staged here rather than provoked with a real device, so this runs on any machine: the load has to
+ put both names back on one tensor, whether it restores them from the RAM copy or re-points them afterwards.
+ """
+ model = TiedWeightsModule()
+ cached_model = CachedModelOnlyFullLoad(
+ model=model, compute_device=torch.device("cpu"), total_bytes=100, keep_ram_copy=keep_ram_copy
+ )
+ model.head.weight = torch.nn.Parameter(model.embed.weight.clone())
+ assert model.head.weight.data_ptr() != model.embed.weight.data_ptr()
+
+ cached_model.full_load_to_vram()
+
+ assert model.head.weight.data_ptr() == model.embed.weight.data_ptr()
+
+
+@parameterize_mps_and_cuda
+@parameterize_keep_ram_copy
+def test_a_tied_weight_survives_a_device_round_trip(device: str, keep_ram_copy: bool):
+ model = TiedWeightsModule()
+ cached_model = CachedModelOnlyFullLoad(
+ model=model, compute_device=torch.device(device), total_bytes=100, keep_ram_copy=keep_ram_copy
+ )
+
+ cached_model.full_load_to_vram()
+
+ assert model.head.weight.device.type == device
+ assert model.head.weight.data_ptr() == model.embed.weight.data_ptr()
+
+ cached_model.full_unload_from_vram()
+
+ assert model.head.weight.device.type == "cpu"
+ assert model.head.weight.data_ptr() == model.embed.weight.data_ptr()
+
+
@parameterize_mps_and_cuda
def test_cached_model_get_cpu_state_dict(device: str):
model = DummyModule()
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 342f5f6492..cedc9f6b95 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
@@ -12,6 +12,8 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch
from invokeai.backend.util.calc_tensor_size import calc_tensor_size
from tests.backend.model_manager.load.model_cache.cached_model.utils import (
DummyModule,
+ TiedRequiredParameterModule,
+ TiedWeightsModule,
parameterize_keep_ram_copy,
parameterize_mps_and_cuda,
)
@@ -37,6 +39,97 @@ def test_cached_model_total_bytes(device: str, model: DummyModule, keep_ram_copy
assert cached_model.total_bytes() == (linear1_numel + linear2_numel + buffer1_numel) * 4
+@parameterize_keep_ram_copy
+def test_a_tied_weight_is_counted_once(keep_ram_copy: bool):
+ """The state dict lists a tied weight under every name it has, so summing it charges the same memory twice.
+
+ The cache decides what to evict from that total: a Qwen3 4B encoder looked 0.7 GiB larger than it is, an 8B
+ encoder 1.2 GiB.
+ """
+ model = TiedWeightsModule()
+
+ cached_model = CachedModelWithPartialLoad(
+ model=model, compute_device=torch.device("cpu"), keep_ram_copy=keep_ram_copy
+ )
+
+ assert cached_model.total_bytes() == calc_tensor_size(model.embed.weight) + calc_tensor_size(
+ model.linear.weight
+ ) + calc_tensor_size(model.linear.bias)
+
+
+@parameterize_keep_ram_copy
+def test_a_budget_too_small_for_a_tied_group_leaves_all_of_it_behind(keep_ram_copy: bool):
+ """The bytes of a tied group are charged to one of its names. Letting the other name — charged 0, so it fits any
+ budget — pull the group in would move the memory past the budget the caller computed from free VRAM, and leave
+ the charged name behind on the CPU.
+
+ Runs against the meta device so it covers machines without an accelerator; the tensors it moves are real.
+ """
+ model = TiedWeightsModule()
+ apply_custom_layers_to_model(model)
+ cached_model = CachedModelWithPartialLoad(
+ model=model, compute_device=torch.device("meta"), keep_ram_copy=keep_ram_copy
+ )
+ # Room for the untied linear, one byte short of the tied matrix.
+ budget = calc_tensor_size(model.linear.weight) + calc_tensor_size(model.linear.bias)
+
+ loaded_bytes = cached_model.partial_load_to_vram(budget)
+
+ assert loaded_bytes <= budget
+ assert not model.embed.weight.is_meta
+ assert not model.head.weight.is_meta
+ assert model.head.weight.data_ptr() == model.embed.weight.data_ptr()
+
+
+def test_a_tied_group_with_a_required_member_is_kept_on_the_device():
+ """`keep_required_weights_in_vram` protects the weights a partially-loaded model cannot run without. Offloading
+ such a weight through a tied name that is not itself required would leave the next forward with its tensors on
+ two devices."""
+ model = TiedRequiredParameterModule()
+ apply_custom_layers_to_model(model)
+ cached_model = CachedModelWithPartialLoad(model=model, compute_device=torch.device("meta"), keep_ram_copy=False)
+ cached_model.full_load_to_vram()
+
+ freed_bytes = cached_model.partial_unload_from_vram(cached_model.total_bytes(), keep_required_weights_in_vram=True)
+
+ assert freed_bytes == 0
+ assert model.required.is_meta
+ assert model.linear.weight.is_meta
+
+
+@parameterize_mps_and_cuda
+@parameterize_keep_ram_copy
+def test_a_tied_weight_stays_one_tensor_across_the_device(device: str, keep_ram_copy: bool):
+ """Moving each name separately put a second copy on the compute device and untied the two, so the model spent
+ VRAM it never reads through the second name."""
+ model = TiedWeightsModule()
+ apply_custom_layers_to_model(model)
+ cached_model = CachedModelWithPartialLoad(
+ model=model, compute_device=torch.device(device), keep_ram_copy=keep_ram_copy
+ )
+ if device == "cuda":
+ torch.cuda.empty_cache()
+ allocated_before = torch.cuda.memory_allocated()
+
+ loaded_bytes = cached_model.full_load_to_vram()
+
+ assert loaded_bytes == cached_model.total_bytes()
+ assert model.head.weight.device.type == device
+ assert model.head.weight.data_ptr() == model.embed.weight.data_ptr()
+ if device == "cuda":
+ # The device really holds one copy, not two tensors that happen to compare equal. The bound allows the
+ # allocator's block rounding but not a second embedding matrix.
+ assert torch.cuda.memory_allocated() - allocated_before < cached_model.total_bytes() + calc_tensor_size(
+ model.embed.weight
+ )
+
+ freed_bytes = cached_model.partial_unload_from_vram(cached_model.total_bytes())
+
+ assert freed_bytes == loaded_bytes
+ assert model.head.weight.device.type == "cpu"
+ assert model.head.weight.data_ptr() == model.embed.weight.data_ptr()
+
+
@parameterize_mps_and_cuda
@parameterize_keep_ram_copy
def test_cached_model_cur_vram_bytes(device: str, model: DummyModule, keep_ram_copy: bool):
diff --git a/tests/backend/model_manager/load/model_cache/cached_model/utils.py b/tests/backend/model_manager/load/model_cache/cached_model/utils.py
index 4974efe8bb..426f0ba72b 100644
--- a/tests/backend/model_manager/load/model_cache/cached_model/utils.py
+++ b/tests/backend/model_manager/load/model_cache/cached_model/utils.py
@@ -22,6 +22,41 @@ class DummyModule(torch.nn.Module):
return x
+class TiedWeightsModule(torch.nn.Module):
+ """A language model's shape: the output projection shares its weight with the embedding.
+
+ Every Qwen3 text encoder InvokeAI loads is tied this way, and so are many transformers models. The state dict
+ lists that one tensor under both names, which is what the cache has to account for and move as one.
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.embed = torch.nn.Embedding(128, 64)
+ self.head = torch.nn.Linear(64, 128, bias=False)
+ self.head.weight = self.embed.weight
+ self.linear = torch.nn.Linear(64, 64)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return self.head(self.linear(self.embed(x)))
+
+
+class TiedRequiredParameterModule(torch.nn.Module):
+ """A tie that spans an autocast-wrapped module and a parameter the cache must keep on the compute device.
+
+ Root parameters sit in no wrapped module, so the cache counts them among the weights a partially-loaded model
+ cannot run without. Tying one to a wrapped module's weight is what makes "keep the required weights" and "move a
+ tied group as a unit" pull in opposite directions.
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.linear = torch.nn.Linear(64, 128, bias=False)
+ self.required = torch.nn.Parameter(self.linear.weight)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return self.linear(x) + self.required.sum()
+
+
is_github_ci = os.getenv("GITHUB_ACTIONS") == "true"
parameterize_mps_and_cuda = pytest.mark.parametrize(
diff --git a/tests/backend/model_manager/load/model_cache/test_shared_cpu_weights.py b/tests/backend/model_manager/load/model_cache/test_shared_cpu_weights.py
index 72ec3a40a8..e7d09d8c58 100644
--- a/tests/backend/model_manager/load/model_cache/test_shared_cpu_weights.py
+++ b/tests/backend/model_manager/load/model_cache/test_shared_cpu_weights.py
@@ -47,6 +47,17 @@ def test_total_bytes_counts_each_key_once():
assert store.total_bytes_in_use() == 820
+def test_a_tied_weight_counts_once():
+ """A tied weight (a text encoder's lm_head sharing the embedding) is in the state dict under both names; charging
+ each name would make the RAM budget evict against a model that is smaller than it looks."""
+ store = SharedCpuWeightsStore()
+ weight = torch.ones(10, 10, dtype=torch.float32) # 400 bytes
+
+ store.acquire("k", {"embed.weight": weight, "head.weight": weight})
+
+ assert store.total_bytes_in_use() == 400
+
+
def test_release_frees_only_at_zero():
store = SharedCpuWeightsStore()
store.acquire("k", _state_dict())
diff --git a/tests/backend/model_manager/load/model_cache/test_tensor_aliases.py b/tests/backend/model_manager/load/model_cache/test_tensor_aliases.py
new file mode 100644
index 0000000000..2d06de02f5
--- /dev/null
+++ b/tests/backend/model_manager/load/model_cache/test_tensor_aliases.py
@@ -0,0 +1,58 @@
+"""Which state dict entries the model cache treats as one tensor.
+
+Everything the cache does with tied weights -- charging their bytes once, moving them as a unit -- rests on
+`storage_key` answering equal only for entries that really are the same memory. Answering equal for two unrelated
+tensors would hand one layer's weights to another, silently.
+"""
+
+import torch
+
+from invokeai.backend.model_manager.load.model_cache.tensor_aliases import (
+ analyze_state_dict,
+ move_shared,
+ storage_key,
+)
+
+
+def test_two_names_for_one_tensor_are_charged_once_and_grouped():
+ weight = torch.ones(8, 4)
+ aliases = analyze_state_dict({"embed.weight": weight, "head.weight": weight, "bias": torch.ones(4)})
+
+ assert sum(aliases.bytes_by_key.values()) == weight.nelement() * 4 + 16
+ assert aliases.groups["head.weight"] == ("embed.weight", "head.weight")
+ assert "bias" not in aliases.groups
+
+
+def test_distinct_tensors_of_equal_shape_are_kept_apart():
+ aliases = analyze_state_dict({"a": torch.ones(8, 4), "b": torch.ones(8, 4)})
+
+ assert aliases.groups == {}
+ assert all(size > 0 for size in aliases.bytes_by_key.values())
+
+
+def test_views_of_one_storage_that_read_different_values_are_kept_apart():
+ """A same-shaped view with another dtype starts at the same address and is not the same values."""
+ weight = torch.ones(8, 4, dtype=torch.float16)
+
+ assert storage_key(weight) != storage_key(weight.view(torch.int16))
+
+
+def test_tensors_without_memory_answer_by_identity():
+ """`data_ptr()` is 0 for meta and zero-element tensors, so keying on it alone would declare them all one tensor."""
+ # Held in variables: identity keys are only distinct while both tensors are alive.
+ first_meta, second_meta = torch.empty(4, 4, device="meta"), torch.empty(4, 4, device="meta")
+ first_empty, second_empty = torch.empty(0), torch.empty(0)
+
+ assert storage_key(first_meta) != storage_key(second_meta)
+ assert storage_key(first_empty) != storage_key(second_empty)
+
+
+def test_moving_one_of_two_names_moves_both_to_the_same_tensor():
+ weight = torch.ones(8, 4)
+ moved: dict = {}
+
+ first = move_shared(weight, torch.device("meta"), moved)
+ second = move_shared(weight, torch.device("meta"), moved)
+
+ assert first is second
+ assert first.is_meta