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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(model-manager): bound GGUF embedding decode RAM (#10214)
Nianze Wu33e69d66fc05
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex cca4cc16c4..85eaade33e 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -1382,7 +1382,12 @@ class Qwen3VLEncoderGGUFLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncoder_GGload_state_dict_ignoring_extras(model, sd, source="Qwen3-VL encoder GGUF", assign=True, allow_missing=True)- materialize_quantized_embedding(model.language_model.embed_tokens, ram_cache=self._ram_cache)+ materialize_quantized_embedding(+ model.language_model.embed_tokens,+ ram_cache=self._ram_cache,+ model=model,+ state_dict=sd,+ )_reject_incomplete_load(model, what="Qwen3-VL encoder GGUF")diff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.pyindex d30957ba80..07fead4003 100644--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py@@ -1432,7 +1432,12 @@ class MistralEncoderGGUFLoader(ModelLoader):f"Mistral encoder (GGUF): {len(missing)} keys missing from state dict (first 5: {missing[:5]})")- materialize_quantized_embedding(model.embed_tokens, ram_cache=self._ram_cache)+ materialize_quantized_embedding(+ model.embed_tokens,+ ram_cache=self._ram_cache,+ model=model,+ state_dict=sd,+ )_reinit_inv_freq(model, mistral_config, compute_dtype)diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex 7b7fcf559e..1084e0e2c8 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -381,7 +381,12 @@ class ZImageDiffusersModel(GenericDiffusersLoader):"SDNQ Z-Image Qwen3 text encoder", missing, unexpected, allowed_missing={"lm_head.weight"})- if materialize_quantized_embedding(model.model.embed_tokens, ram_cache=self._ram_cache):+ if materialize_quantized_embedding(+ model.model.embed_tokens,+ ram_cache=self._ram_cache,+ model=model,+ state_dict=sd,+ ):logger.info("Dequantized embed_tokens weight for embedding lookups")# Handle tied weights@@ -1552,7 +1557,12 @@ class Qwen3EncoderGGUFLoader(ModelLoader):# GGMLTensor wrappers will be dequantized on-the-fly during inferenceload_state_dict_ignoring_extras(model, sd, source="Qwen3 GGUF text encoder", assign=True, allow_missing=True)- if materialize_quantized_embedding(model.model.embed_tokens, ram_cache=self._ram_cache):+ if materialize_quantized_embedding(+ model.model.embed_tokens,+ ram_cache=self._ram_cache,+ model=model,+ state_dict=sd,+ ):logger.info("Dequantized embed_tokens weight for embedding lookups")# Handle tied weights - llama.cpp GGUF doesn't include lm_head.weight when embeddings are tied@@ -1739,7 +1749,12 @@ class Qwen3EncoderSDNQLoader(ModelLoader):missing, unexpected = model.load_state_dict(sd, strict=False, assign=True)raise_on_incomplete_sdnq_load("SDNQ Qwen3 encoder", missing, unexpected, allowed_missing={"lm_head.weight"})- if materialize_quantized_embedding(model.model.embed_tokens, ram_cache=self._ram_cache):+ if materialize_quantized_embedding(+ model.model.embed_tokens,+ ram_cache=self._ram_cache,+ model=model,+ state_dict=sd,+ ):logger.info("Dequantized embed_tokens weight for embedding lookups")# Handle tied weightsdiff --git a/invokeai/backend/model_manager/load/quantized_embedding.py b/invokeai/backend/model_manager/load/quantized_embedding.pyindex 6c7bde6004..a5173cc198 100644--- a/invokeai/backend/model_manager/load/quantized_embedding.py+++ b/invokeai/backend/model_manager/load/quantized_embedding.py@@ -1,46 +1,71 @@-"""Materializing a quantized embedding weight, with the host RAM it needs reserved first.--A quantized encoder has to undo the quantization of exactly one tensor: ``embed_tokens.weight``.-``nn.Embedding`` indexes its weight directly, and neither ``GGMLTensor`` nor ``SDNQTensor`` can serve-an indexed read from packed storage -- so the lookup would fail at the user's first prompt, long-after the load that could have prevented it. It is also the weight least worth keeping packed: it is-the model's entire input representation, and one dequantized copy is the price of every lookup being-a plain gather.--The framework reserves a model's *file size* before a load (``ModelLoader._load_and_cache``), which-by construction does not cover unpacking a tensor on top of it. That gap is the reason this lives in-one place: 0.78 GB for a Qwen3-VL 4B, 1.24 GB for the 8B, and several times that at the peak.--Callers are the five single-file text-encoder loaders that reach a quantized embedding: Qwen3-VL-GGUF, Qwen3 GGUF, Qwen3 SDNQ, Z-Image diffusers SDNQ and Mistral GGUF. Not an inventory of every-such step in the tree -- ``gemma2_encoder.py`` dequantizes a 1.18 GB Gemma-2 embedding from a free-function with no cache to reserve against, and ``flux.py`` does the same for T5 and CLIP. Those are-other families, still unreserved, and folding them in means threading a cache through their call-chains.+"""Materialize indexed embedding weights within an absolute host RAM reservation.++``nn.Embedding`` indexes its weight directly, which neither GGML nor SDNQ serves in packed form.+Gemma-2's encoder and Flux's T5/CLIP still materialize embeddings without a reservation; their+load paths do not pass a cache here."""+from collections.abc import Iterable, Mapping+from itertools import chainfrom typing import Anyimport torchfrom invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache-from invokeai.backend.quantization.gguf.ggml_tensor import HOST_DEQUANT_PEAK_COPIES+from invokeai.backend.quantization.gguf.ggml_tensor import HOST_DEQUANT_PEAK_COPIES, GGMLTensor+from invokeai.backend.quantization.gguf.loaders import ggml_unpack_temp_bytes, unpack_ggml_tensor+from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor-def materialize_quantized_embedding(embedding: torch.nn.Module, *, ram_cache: ModelCache) -> bool:+def materialize_quantized_embedding(+ embedding: torch.nn.Module, *, model: torch.nn.Module, state_dict: Mapping[str, torch.Tensor], ram_cache: ModelCache+) -> bool:"""Replace ``embedding.weight`` with a dequantized ``Parameter``, reserving the room first.Does nothing and returns False when the weight is already a plain tensor, so a caller can run itunconditionally over a model whose quantization it does not know.++ The model parameters, buffers, checkpoint values and embedding are all counted. Shared backing+ storage is counted once, including checkpoint aliases retained by assign=True and weights the+ model did not consume. Meta tensors do not hold storage."""weight: Any = embedding.weightdequantize = getattr(weight, "get_dequantized_tensor", None)if dequantize is None:return False- # `.shape` is the dequantized shape on both wrapper types; `Tensor.numel()` is not overridden and- # would report the packed element count instead -- for a 4-bit quant, roughly half of what is- # about to be allocated.- ram_cache.make_room(HOST_DEQUANT_PEAK_COPIES * weight.shape.numel() * weight.compute_dtype.itemsize)- embedding.weight = torch.nn.Parameter(dequantize(), requires_grad=False)+ held_bytes = _held_tensor_bytes(chain((weight,), state_dict.values(), model.parameters(), model.buffers()))+ # `.shape` is logical on both wrappers; `Tensor.numel()` instead reports packed elements.+ output_bytes = weight.shape.numel() * weight.compute_dtype.itemsize+ if isinstance(weight, GGMLTensor):+ # Some unquantized GGML decodes return a view; reserving an output is conservative there.+ ram_cache.make_room(held_bytes + output_bytes + ggml_unpack_temp_bytes(weight))+ result = unpack_ggml_tensor(weight)+ else:+ # SDNQ retains whole-tensor decoding. Its peak allowance already includes the result.+ ram_cache.make_room(held_bytes + HOST_DEQUANT_PEAK_COPIES * output_bytes)+ result = dequantize()+ # Keep the original Parameter intact if reserving or decoding raises.+ embedding.weight = torch.nn.Parameter(result, requires_grad=False)return True+++def _held_tensor_bytes(tensors: Iterable[torch.Tensor]) -> int:+ """Live backing storage, including quantized payloads and storage retained by tensor views."""+ seen: set[torch.UntypedStorage] = set()+ total = 0+ for tensor in tensors:+ if isinstance(tensor, SDNQTensor):+ payloads = tensor.storage_tensors()+ elif isinstance(tensor, GGMLTensor):+ payloads = (tensor.quantized_data,)+ else:+ payloads = (tensor,)+ for payload in payloads:+ if payload is None or payload.is_meta:+ continue+ storage = payload.untyped_storage()+ if storage not in seen:+ seen.add(storage)+ total += storage.nbytes()+ return totaldiff --git a/invokeai/backend/quantization/gguf/loaders.py b/invokeai/backend/quantization/gguf/loaders.pyindex 996623f963..b1b1706f1d 100644--- a/invokeai/backend/quantization/gguf/loaders.py+++ b/invokeai/backend/quantization/gguf/loaders.py@@ -428,7 +428,7 @@ def unpack_ggml_at_load(its packed size, everything replaced at its unpacked size, and one replacement in flight. BF16 isreinterpreted rather than run through the GGML kernel, which widens through int32 and float32 onthe way -- about 8 bytes per element. What is in flight beside a result is the packed original it- replaces and, for a quantized tensor, the temporaries of one row slice (see `_unpack`).+ replaces and, for a quantized tensor, the temporaries of one row slice (see `unpack_ggml_tensor`)."""linear_params = {f"{module_name}.{param_name}"@@ -452,11 +452,11 @@ def unpack_ggml_at_load(for key, value in sd.items()if key not in unpacked)- in_flight = max((_in_flight_bytes(sd[key]) for key in keys), default=0)+ in_flight = max((sd[key].quantized_data.nbytes + ggml_unpack_temp_bytes(sd[key]) for key in keys), default=0)reserve(kept + sum(unpacked.values()) + in_flight)# One at a time, so each packed original is released as its replacement lands.for key in keys:- sd[key] = _unpack(sd[key])+ sd[key] = unpack_ggml_tensor(sd[key])return len(keys)@@ -467,17 +467,19 @@ def _row_slices(value: GGMLTensor) -> tuple[torch.Tensor, int, int]:return rows, per_row, max(1, _UNPACK_CHUNK_ELEMENTS // per_row)-def _in_flight_bytes(value: GGMLTensor) -> int:- """What replacing `value` holds beside its result: the packed original, released only once the result- lands, and for a quantized tensor the decode temporaries of one slice."""- packed = value.quantized_data.nbytes+def ggml_unpack_temp_bytes(value: GGMLTensor) -> int:+ """Decode temporaries beside the output and packed original, bounded to one row slice.++ Callers budget the original separately: a state dict can release it as its replacement lands,+ whereas materializing a model parameter can leave its checkpoint alias alive.+ """if value._ggml_quantization_type in _UNQUANTIZED_GGML_TYPES:- return packed+ return 0rows, per_row, step = _row_slices(value)- return packed + HOST_DEQUANT_PEAK_COPIES * min(step, rows.shape[0]) * per_row * value.compute_dtype.itemsize+ return HOST_DEQUANT_PEAK_COPIES * min(step, rows.shape[0]) * per_row * value.compute_dtype.itemsize-def _unpack(value: GGMLTensor) -> torch.Tensor:+def unpack_ggml_tensor(value: GGMLTensor) -> torch.Tensor:"""`value` as a plain tensor in its compute dtype; BF16 as a view of its bytes, not a decode.A quantized tensor is decoded a slice of rows at a time into its preallocated result. GGML blocksdiff --git a/invokeai/backend/quantization/sdnq/sdnq_tensor.py b/invokeai/backend/quantization/sdnq/sdnq_tensor.pyindex 69bb1fb01e..12b9492bc5 100644--- a/invokeai/backend/quantization/sdnq/sdnq_tensor.py+++ b/invokeai/backend/quantization/sdnq/sdnq_tensor.py@@ -286,6 +286,14 @@ class SDNQTensor(torch.Tensor):"""Whether this tensor has SVD correction components."""return self._svd_up is not None and self._svd_down is not None+ def storage_tensors(self) -> tuple[torch.Tensor, ...]:+ """Packed data and auxiliary tensors retained by this wrapper."""+ return tuple(+ t+ for t in (self.quantized_data, self._scale, self._zero_point, self._svd_up, self._svd_down)+ if isinstance(t, torch.Tensor)+ )+def sdnq_storage_nbytes(self) -> int:"""Actual in-memory storage of this quantized tensor, in bytes.@@ -296,11 +304,7 @@ class SDNQTensor(torch.Tensor):the real storage — the packed data plus every auxiliary tensor — so cache eviction andpartial-load budgets operate on true sizes."""- total = self.quantized_data.nelement() * self.quantized_data.element_size()- for aux in (self._scale, self._zero_point, self._svd_up, self._svd_down):- if isinstance(aux, torch.Tensor):- total += aux.nelement() * aux.element_size()- return total+ return sum(t.nelement() * t.element_size() for t in self.storage_tensors())def requires_grad_(self, mode: bool = True) -> torch.Tensor:"""SDNQTensor is only for inference, not training. This is a no-op."""diff --git a/tests/backend/model_manager/load/test_mistral_encoder_gguf_loader.py b/tests/backend/model_manager/load/test_mistral_encoder_gguf_loader.pyindex acef309ad0..60ec7069c9 100644--- a/tests/backend/model_manager/load/test_mistral_encoder_gguf_loader.py+++ b/tests/backend/model_manager/load/test_mistral_encoder_gguf_loader.py@@ -35,6 +35,7 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch)from invokeai.backend.model_manager.load.model_loaders.mistral_encoder import MistralEncoderGGUFLoaderfrom invokeai.backend.model_manager.taxonomy import MistralVariantType+from invokeai.backend.quantization.gguf import loaders as gguf_loadersfrom invokeai.backend.quantization.gguf.ggml_tensor import HOST_DEQUANT_PEAK_COPIES as PEAK_COPIESfrom invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor@@ -114,13 +115,15 @@ def _write_gguf(path: Path, architecture: str, tensors: dict[str, np.ndarray], mreturn path-def _write_uniform_gguf(path: Path) -> Path:+def _write_uniform_gguf(path: Path, *, extra_weights: bool = False) -> Path:"""The llama.cpp tensor set for a tiny Mistral decoder, every value `_FILL`.No `attn_q_norm` / `attn_k_norm`: `MistralModel` has no QK norm, and a real Mistral GGUF carriesnone either."""shapes: dict[str, tuple[int, ...]] = {"token_embd.weight": (_VOCAB, _HIDDEN), "output_norm.weight": (_HIDDEN,)}+ if extra_weights:+ shapes["unused_projection.weight"] = (_FFN, _HIDDEN)for layer in range(_LAYERS):shapes.update({@@ -264,17 +267,35 @@ def test_the_shared_converter_lands_every_weight_in_the_mistral_module_tree(tmp_assert projection.weight.shape == (projection.out_features, projection.in_features)-def test_the_embedding_is_materialized_and_its_copy_reserved(tmp_path, monkeypatch) -> None:- """The site this change added a reservation to. `nn.Embedding` indexes its weight directly, so- the dequantized copy is unavoidable — and the framework reserved only the file size.[email protected]("extra_weights", [False, True])+def test_embedding_reservation_covers_live_model_and_checkpoint(tmp_path, monkeypatch, extra_weights):+ """The checkpoint survives assign=True, including weights the model does not use. Its assigned+ parameters alias those bytes; model-owned RoPE buffers are additional live storage."""+ path = _write_uniform_gguf(tmp_path / "mistral_budget.gguf", extra_weights=extra_weights)+ reader = gguf.GGUFReader(path)+ packed_bytes = sum(int(tensor.n_bytes) for tensor in reader.tensors)+ del reader+ monkeypatch.setattr(gguf_loaders, "_UNPACK_CHUNK_ELEMENTS", 3 * _HIDDEN)ram_cache = create_autospec(ModelCache, instance=True)+ model_buffer_bytes = []+ real_load = MistralModel.load_state_dict- model = _load(tmp_path, monkeypatch, _write_uniform_gguf(tmp_path / "mistral_tiny.gguf"), ram_cache=ram_cache)+ def recording(model, *args, **kwargs):+ result = real_load(model, *args, **kwargs)+ model_buffer_bytes.append(sum(b.untyped_storage().nbytes() for b in model.buffers() if not b.is_meta))+ return result- assert not isinstance(model.embed_tokens.weight, GGMLTensor)- assert model.embed_tokens(torch.tensor([[0, 1]])).shape == (1, 2, _HIDDEN)- assert ram_cache.make_room.call_args_list == [call(PEAK_COPIES * _VOCAB * _HIDDEN * torch.float32.itemsize)]+ monkeypatch.setattr(MistralModel, "load_state_dict", recording)++ model = _load(tmp_path, monkeypatch, path, ram_cache=ram_cache)++ output_bytes = _VOCAB * _HIDDEN * torch.float32.itemsize+ chunk_bytes = 3 * _HIDDEN * torch.float32.itemsize+ assert ram_cache.make_room.call_args_list == [+ call(packed_bytes + model_buffer_bytes[0] + output_bytes + PEAK_COPIES * chunk_bytes)+ ]+ assert torch.allclose(model.embed_tokens(torch.tensor([[0, 63]])), torch.full((1, 2, _HIDDEN), _FILL), atol=1e-3)@pytest.mark.parametrize(diff --git a/tests/backend/model_manager/load/test_quantized_embedding.py b/tests/backend/model_manager/load/test_quantized_embedding.pyindex aa2ab85775..e60c1012cb 100644--- a/tests/backend/model_manager/load/test_quantized_embedding.py+++ b/tests/backend/model_manager/load/test_quantized_embedding.py@@ -1,24 +1,58 @@-"""Materializing a quantized embedding weight, and reserving the RAM it needs first.--Five encoder loaders share this one step. The reservation is the part worth pinning: the framework-reserves a model's file size before the load, which by construction does not cover unpacking a-tensor on top of it, and getting the figure from the *packed* element count would under-reserve by-whatever the quantization saved — roughly half for a 4-bit quant.-"""+"""Embedding materialization must budget live storage and bound GGML decode temporaries."""from unittest.mock import call, create_autospec+import gguf+import pytestimport torchfrom invokeai.backend.model_manager.load.model_cache.model_cache import ModelCachefrom invokeai.backend.model_manager.load.quantized_embedding import materialize_quantized_embedding+from invokeai.backend.quantization.gguf import loadersfrom invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensorfrom invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensorfrom invokeai.backend.quantization.sdnq.utils import SDNQQuantizationType+from tests.backend.quantization.gguf.test_loaders import _quantized_embedding_VOCAB, _HIDDEN = 64, 32+def test_ggml_embedding_decodes_bounded_rows_bit_exactly(monkeypatch):+ qtype = gguf.GGMLQuantizationType.Q8_0+ dtype = torch.float32+ rows_per_chunk = 3+ budget = rows_per_chunk * 512+ monkeypatch.setattr(loaders, "_UNPACK_CHUNK_ELEMENTS", budget)+ embedding = torch.nn.Embedding(37, 512, device="meta")+ weight = _quantized_embedding(qtype, rows=37, width=512)+ weight.compute_dtype = dtype+ embedding.weight = torch.nn.Parameter(weight, requires_grad=False)+ # Independent whole-tensor decode, before observing the production calls.+ expected = weight.get_dequantized_tensor()+ decoded = []+ real_decode = GGMLTensor.get_dequantized_tensor+ cache = create_autospec(ModelCache, instance=True)++ def recording(tensor):+ assert cache.make_room.called+ result = real_decode(tensor)+ decoded.append(result.numel())+ return result++ monkeypatch.setattr(GGMLTensor, "get_dequantized_tensor", recording)++ assert materialize_quantized_embedding(embedding, ram_cache=cache, model=embedding, state_dict={}) is True++ assert decoded == [3 * 512] * 12 + [512]+ assert torch.equal(embedding.weight.view(torch.uint8), expected.view(torch.uint8))+ assert embedding.weight.dtype == dtype+ assert embedding.weight.device == weight.quantized_data.device+ assert not embedding.weight.requires_grad+ assert cache.make_room.call_args_list == [+ call(weight.quantized_data.nbytes + expected.nbytes + 6 * rows_per_chunk * 512 * dtype.itemsize)+ ]++def _q8_0_embedding() -> torch.nn.Embedding:"""A real Q8_0 `GGMLTensor` on an `nn.Embedding`, as `gguf_sd_loader` hands one over."""import gguf@@ -41,16 +75,18 @@ def _q8_0_embedding() -> torch.nn.Embedding:def test_a_packed_weight_is_materialized_and_reserved_by_its_dequantized_size() -> None:+ """The wrapper's logical shape sizes the output; numel() counts packed elements instead."""ram_cache = create_autospec(ModelCache, instance=True)embedding = _q8_0_embedding()# The packed element count is a different number from the logical one in either direction — Q8_0# spends 34 bytes per 32 values, a 4-bit quant roughly half — so a reservation taken from it is# simply wrong, not conservative.assert embedding.weight.quantized_data.numel() != _VOCAB * _HIDDEN+ weight_bytes = embedding.weight.quantized_data.nbytes- assert materialize_quantized_embedding(embedding, ram_cache=ram_cache) is True+ assert materialize_quantized_embedding(embedding, ram_cache=ram_cache, model=embedding, state_dict={}) is True- assert ram_cache.make_room.call_args_list == [call(6 * _VOCAB * _HIDDEN * torch.float32.itemsize)]+ assert ram_cache.make_room.call_args_list == [call(weight_bytes + 7 * _VOCAB * _HIDDEN * torch.float32.itemsize)]assert not isinstance(embedding.weight, GGMLTensor)assert embedding.weight.shape == (_VOCAB, _HIDDEN)# An indexed read is the whole reason this step exists.@@ -65,18 +101,15 @@ def test_a_plain_weight_is_left_alone_and_reserves_nothing() -> None:embedding = torch.nn.Embedding(_VOCAB, _HIDDEN)weight_before = embedding.weight- assert materialize_quantized_embedding(embedding, ram_cache=ram_cache) is False+ assert materialize_quantized_embedding(embedding, ram_cache=ram_cache, model=embedding, state_dict={}) is Falseassert ram_cache.make_room.call_args_list == []assert embedding.weight is weight_before-def test_an_sdnq_weight_is_handled_by_the_same_duck_typed_path() -> None:- """Three of the five call sites are SDNQ, not GGUF, and `SDNQTensor` shares no base class with- `GGMLTensor` — only `get_dequantized_tensor`, `.shape` as the dequantized shape, and- `.compute_dtype`. That contract is what the helper dispatches on, so it is asserted against the- real type: `compute_dtype` is a plain public attribute elsewhere reached via `hasattr`, so- renaming it would look free and would break every SDNQ encoder load.+def test_an_sdnq_weight_keeps_whole_tensor_decoding_and_reserves_its_payloads(monkeypatch) -> None:+ """SDNQ and GGML share a duck-typed contract, not a base class. The helper needs SDNQ's public+ compute_dtype to size the allocation even though other code mostly accesses it via hasattr."""ram_cache = create_autospec(ModelCache, instance=True)embedding = torch.nn.Embedding(_VOCAB, _HIDDEN)@@ -90,10 +123,162 @@ def test_an_sdnq_weight_is_handled_by_the_same_duck_typed_path() -> None:),requires_grad=False,)+ weight = embedding.weight+ expected = weight.get_dequantized_tensor()+ decoded = []+ real_decode = SDNQTensor.get_dequantized_tensor++ def recording(tensor):+ assert ram_cache.make_room.called+ decoded.append(tensor)+ return real_decode(tensor)++ monkeypatch.setattr(SDNQTensor, "get_dequantized_tensor", recording)- assert materialize_quantized_embedding(embedding, ram_cache=ram_cache) is True+ assert materialize_quantized_embedding(embedding, ram_cache=ram_cache, model=embedding, state_dict={}) is True- assert ram_cache.make_room.call_args_list == [call(6 * _VOCAB * _HIDDEN * torch.bfloat16.itemsize)]+ assert ram_cache.make_room.call_args_list == [call(weight.sdnq_storage_nbytes() + 6 * expected.nbytes)]+ assert len(decoded) == 1 and decoded[0] is weight+ assert torch.equal(embedding.weight, expected)assert not isinstance(embedding.weight, SDNQTensor)assert embedding.weight.dtype is torch.bfloat16assert embedding(torch.tensor([[0, 1]])).shape == (1, 2, _HIDDEN)++[email protected]("shared", [False, True])+def test_checkpoint_and_model_aliases_count_their_backing_storage_once(shared):+ embedding = _q8_0_embedding()+ model = torch.nn.Module()+ model.add_module("embedding", embedding)+ model.add_module("projection", torch.nn.Linear(32, 64, bias=False, device="meta"))+ projection_weight = embedding.weight.detach() if shared else embedding.weight.clone()+ model.projection.weight = torch.nn.Parameter(projection_weight, requires_grad=False)+ storage = torch.arange(100, dtype=torch.float32)+ model.register_buffer("frequencies", storage[:8])+ unused = torch.ones(79)+ checkpoint = {+ "embed.weight": embedding.weight.detach(),+ "tied.weight": embedding.weight.detach(),+ "unused": unused,+ "buffer_view": storage[8:16],+ "meta": torch.empty(10000, device="meta"),+ }+ cache = create_autospec(ModelCache, instance=True)+ packed_bytes = embedding.weight.quantized_data.nbytes+ output_bytes = _VOCAB * _HIDDEN * torch.float32.itemsize++ assert materialize_quantized_embedding(embedding, ram_cache=cache, model=model, state_dict=checkpoint)++ assert cache.make_room.call_args_list == [+ call((packed_bytes if shared else 2 * packed_bytes) + storage.nbytes + unused.nbytes + 7 * output_bytes)+ ]+ assert isinstance(model.projection.weight, GGMLTensor)+ assert isinstance(checkpoint["embed.weight"], GGMLTensor)+++def test_other_live_sdnq_weights_include_all_auxiliary_storage_once():+ embedding = _q8_0_embedding()+ auxiliary = [torch.ones(64, 1), torch.zeros(64, 1), torch.ones(64, 2), torch.ones(2, 32)]+ other = SDNQTensor(+ data=torch.ones(64, 32, dtype=torch.int8),+ quantization_type=SDNQQuantizationType.INT8_ASYM,+ tensor_shape=torch.Size((64, 32)),+ compute_dtype=torch.float32,+ scale=auxiliary[0],+ zero_point=auxiliary[1],+ svd_up=auxiliary[2],+ svd_down=auxiliary[3],+ )+ cache = create_autospec(ModelCache, instance=True)+ packed_bytes = embedding.weight.quantized_data.nbytes+ held_bytes = other.quantized_data.nbytes + sum(t.nbytes for t in auxiliary)++ checkpoint = {"other": other, "alias": other.detach(), **{f"aux_{i}": t for i, t in enumerate(auxiliary)}}+ assert materialize_quantized_embedding(embedding, ram_cache=cache, model=embedding, state_dict=checkpoint)++ assert cache.make_room.call_args_list == [+ call(packed_bytes + held_bytes + 7 * _VOCAB * _HIDDEN * torch.float32.itemsize)+ ]+++ "qtype", [gguf.GGMLQuantizationType.F32, gguf.GGMLQuantizationType.F16, gguf.GGMLQuantizationType.BF16]+)+def test_unquantized_ggml_storage_still_materializes_in_the_compute_dtype(qtype):+ dtype = {+ gguf.GGMLQuantizationType.F32: torch.float32,+ gguf.GGMLQuantizationType.F16: torch.float16,+ gguf.GGMLQuantizationType.BF16: torch.bfloat16,+ }[qtype]+ source = torch.linspace(-1, 1, 64 * 32).reshape(64, 32).to(dtype)+ packed = source.view(torch.uint8) if qtype == gguf.GGMLQuantizationType.BF16 else source+ embedding = torch.nn.Embedding(64, 32, device="meta")+ embedding.weight = torch.nn.Parameter(+ GGMLTensor(packed, qtype, torch.Size((64, 32)), torch.float32), requires_grad=False+ )+ cache = create_autospec(ModelCache, instance=True)++ assert materialize_quantized_embedding(embedding, ram_cache=cache, model=embedding, state_dict={})++ assert torch.equal(embedding.weight, source.float())+ assert embedding.weight.dtype == torch.float32+ assert cache.make_room.call_args_list == [call(packed.nbytes + source.numel() * torch.float32.itemsize)]++[email protected]("failure", ["reservation", "decode"])+def test_failed_materialization_preserves_the_original_weight(monkeypatch, failure):+ embedding = _q8_0_embedding()+ weight = embedding.weight+ cache = create_autospec(ModelCache, instance=True)+ monkeypatch.setattr(loaders, "_UNPACK_CHUNK_ELEMENTS", 3 * _HIDDEN)+ calls = []+ real_decode = GGMLTensor.get_dequantized_tensor++ def failing_decode(tensor):+ calls.append(tensor.shape.numel())+ if len(calls) == 2:+ raise RuntimeError("decode failed")+ return real_decode(tensor)++ monkeypatch.setattr(GGMLTensor, "get_dequantized_tensor", failing_decode)+ if failure == "reservation":+ cache.make_room.side_effect = RuntimeError("reservation failed")++ with pytest.raises(RuntimeError, match=f"{failure} failed"):+ materialize_quantized_embedding(embedding, ram_cache=cache, model=embedding, state_dict={})++ assert embedding.weight is weight+ assert calls == ([] if failure == "reservation" else [3 * _HIDDEN] * 2)++[email protected]("failure", ["reservation", "decode"])+def test_failed_sdnq_materialization_preserves_the_original_weight(monkeypatch, failure):+ embedding = torch.nn.Embedding(_VOCAB, _HIDDEN)+ embedding.weight = torch.nn.Parameter(+ SDNQTensor(+ data=torch.ones((_VOCAB, _HIDDEN), dtype=torch.int8),+ quantization_type=SDNQQuantizationType.INT8_SYM,+ tensor_shape=torch.Size((_VOCAB, _HIDDEN)),+ compute_dtype=torch.float32,+ scale=torch.ones(1),+ ),+ requires_grad=False,+ )+ weight = embedding.weight+ cache = create_autospec(ModelCache, instance=True)+ decoded = []++ def fail_decode(tensor):+ assert cache.make_room.called+ decoded.append(tensor)+ raise RuntimeError("decode failed")++ monkeypatch.setattr(SDNQTensor, "get_dequantized_tensor", fail_decode)+ if failure == "reservation":+ cache.make_room.side_effect = RuntimeError("reservation failed")++ with pytest.raises(RuntimeError, match=f"{failure} failed"):+ materialize_quantized_embedding(embedding, ram_cache=cache, model=embedding, state_dict={})++ assert embedding.weight is weight+ assert decoded == ([] if failure == "reservation" else [weight])diff --git a/tests/backend/model_manager/load/test_quantized_embedding_review.py b/tests/backend/model_manager/load/test_quantized_embedding_review.pynew file mode 100644index 0000000000..943d61841a--- /dev/null+++ b/tests/backend/model_manager/load/test_quantized_embedding_review.py@@ -0,0 +1,36 @@+"""The reservation owns the complete, deduplicated in-flight model and checkpoint."""++from unittest.mock import create_autospec++import pytest+import torch++from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache+from invokeai.backend.model_manager.load.quantized_embedding import materialize_quantized_embedding+from tests.backend.model_manager.load.test_quantized_embedding import _q8_0_embedding++[email protected]("missing", ["model", "state_dict"])+def test_model_and_checkpoint_are_required_even_for_a_plain_embedding(missing):+ embedding = torch.nn.Embedding(2, 2)+ args = {"model": embedding, "state_dict": {}}+ del args[missing]+ with pytest.raises(TypeError, match=missing):+ materialize_quantized_embedding(embedding, ram_cache=create_autospec(ModelCache, instance=True), **args)+++def test_counts_nonaliased_model_parameters_but_not_meta_storage():+ embedding = _q8_0_embedding()+ model = torch.nn.Module()+ model.embedding = embedding+ model.extra = torch.nn.Parameter(torch.ones(31), requires_grad=False)+ model.meta = torch.nn.Parameter(torch.empty(10000, device="meta"), requires_grad=False)+ model.register_buffer("buffer", torch.ones(11))+ checkpoint = {"embedding": embedding.weight.detach(), "unused": torch.ones(7)}+ cache = create_autospec(ModelCache, instance=True)+ packed = embedding.weight.quantized_data.nbytes+ output = embedding.weight.shape.numel() * torch.float32.itemsize++ assert materialize_quantized_embedding(embedding, model=model, state_dict=checkpoint, ram_cache=cache)++ cache.make_room.assert_called_once_with(packed + (31 + 11 + 7) * 4 + 7 * output)diff --git a/tests/backend/model_manager/load/test_qwen3_embedding_reservation.py b/tests/backend/model_manager/load/test_qwen3_embedding_reservation.pynew file mode 100644index 0000000000..c61817a2ac--- /dev/null+++ b/tests/backend/model_manager/load/test_qwen3_embedding_reservation.py@@ -0,0 +1,106 @@+"""Exercise each Z-Image Qwen3 embedding loader through its real CPU cache and files."""++from unittest.mock import Mock++import gguf+import pytest+import torch+import transformers+from safetensors.torch import save_file+from transformers import Qwen3Config, Qwen3ForCausalLM++from invokeai.backend.model_manager.configs.qwen3_encoder import Qwen3Encoder_GGUF_Config, Qwen3Encoder_SDNQ_Config+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache+from invokeai.backend.model_manager.load.model_loaders import z_image+from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor+from tests.fixtures.quantized_payloads import write_gguf++VOCAB, HIDDEN = 32, 128++[email protected]("kind", ["gguf", "sdnq", "diffusers_sdnq"])+def test_qwen3_loader_reserves_live_storage_before_embedding_decode(monkeypatch, tmp_path, kind):+ config = Qwen3Config(+ vocab_size=VOCAB,+ hidden_size=HIDDEN,+ intermediate_size=256,+ num_hidden_layers=1,+ num_attention_heads=1,+ num_key_value_heads=1,+ head_dim=128,+ tie_word_embeddings=True,+ )+ sd = {k: v.detach().clone() for k, v in Qwen3ForCausalLM(config).state_dict().items() if k != "lm_head.weight"}+ sd["unused_payload"] = torch.ones(13)+ embed = sd.pop("model.embed_tokens.weight")+ if kind == "gguf":+ path = tmp_path / "tiny.gguf"+ write_gguf(path, sd, q8_0={"model.embed_tokens.weight": embed}, architecture="qwen3")+ reader = gguf.GGUFReader(path)+ checkpoint_bytes = sum(int(t.n_bytes) for t in reader.tensors)+ del reader+ else:+ path = tmp_path / "tiny.safetensors"+ sd["model.embed_tokens.weight"] = torch.full((VOCAB, HIDDEN), 10, dtype=torch.int8)+ sd["model.embed_tokens.scale"] = torch.tensor([0.1])+ # A second wrapper's independent auxiliary storage stays live during embedding decode.+ sd["model.layers.0.self_attn.q_proj.weight"] = torch.ones((HIDDEN, HIDDEN), dtype=torch.int8)+ sd["model.layers.0.self_attn.q_proj.scale"] = torch.tensor([0.2])+ sd["model.layers.0.self_attn.q_proj.zero_point"] = torch.tensor([1.0])+ checkpoint_bytes = sum(t.nbytes for t in sd.values())+ save_file(sd, path)++ observed_buffers = []++ class ModelWithExtraParameter(Qwen3ForCausalLM):+ def load_state_dict(self, *args, **kwargs):+ result = super().load_state_dict(*args, **kwargs)+ assert self.lm_head.weight.is_meta+ # This storage is not in the checkpoint and cannot be counted through its aliases.+ self.extra = torch.nn.Parameter(torch.ones(19), requires_grad=False)+ self.register_buffer("extra_buffer", torch.ones(23), persistent=False)+ observed_buffers.append(sum(b.untyped_storage().nbytes() for b in self.buffers() if not b.is_meta))+ return result++ monkeypatch.setattr(transformers, "Qwen3ForCausalLM", ModelWithExtraParameter)+ monkeypatch.setattr(z_image.TorchDevice, "choose_torch_device", lambda: torch.device("cpu"))+ monkeypatch.setattr(z_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _: torch.float32)+ cache = ModelCache(+ execution_device_working_mem_gb=0,+ enable_partial_loading=False,+ keep_ram_copy_of_weights=False,+ max_ram_cache_size_gb=1,+ execution_device="cpu",+ shared_cpu_weights=None,+ )+ cache.make_room = Mock(wraps=cache.make_room)+ if kind != "gguf":+ real_decode = SDNQTensor.get_dequantized_tensor++ def decode_after_reservation(weight):+ assert cache.make_room.call_count == 1+ return real_decode(weight)++ monkeypatch.setattr(SDNQTensor, "get_dequantized_tensor", decode_after_reservation)++ try:+ if kind == "gguf":+ loader = object.__new__(z_image.Qwen3EncoderGGUFLoader)+ loader._ram_cache = cache+ model = loader._load_from_gguf(Qwen3Encoder_GGUF_Config.model_construct(path=str(path)))+ elif kind == "sdnq":+ loader = object.__new__(z_image.Qwen3EncoderSDNQLoader)+ loader._ram_cache = cache+ model = loader._load_from_sdnq(Qwen3Encoder_SDNQ_Config.model_construct(path=str(path)))+ else:+ loader = object.__new__(z_image.ZImageDiffusersModel)+ loader._ram_cache = cache+ model = loader._load_sdnq_text_encoder(path)++ output_bytes = VOCAB * HIDDEN * torch.float32.itemsize+ decode_budget = 7 * output_bytes if kind == "gguf" else 6 * output_bytes+ cache.make_room.assert_called_once_with(checkpoint_bytes + 19 * 4 + observed_buffers[0] + decode_budget)+ assert model.lm_head.weight is model.model.embed_tokens.weight+ assert model.model.embed_tokens(torch.tensor([[0, 1]])).shape == (1, 2, HIDDEN)+ finally:+ cache.shutdown()diff --git a/tests/backend/model_manager/load/test_qwen3_vl_gguf_loader.py b/tests/backend/model_manager/load/test_qwen3_vl_gguf_loader.pyindex 6129dcf47f..6573a2f00c 100644--- a/tests/backend/model_manager/load/test_qwen3_vl_gguf_loader.py+++ b/tests/backend/model_manager/load/test_qwen3_vl_gguf_loader.py@@ -7,6 +7,7 @@ wrappers the loader has to cope with. See ``qwen3vl_gguf_fixture`` for what is afrom unittest.mock import call, create_autospec+import ggufimport pytestimport torchimport transformers.configuration_utils@@ -122,22 +123,19 @@ def test_a_krea2_shaped_forward_produces_hidden_states(loaded_encoder) -> None:def test_the_embedding_materialization_is_reserved(monkeypatch, tmp_path) -> None:- """The framework reserves the GGUF's file size, which does not cover unpacking a tensor on top- of it — 0.78 GB for the 4B, 1.24 GB for the 8B, and several times that at the peak. Unreserved,- that is what pushes a tight machine into swap.-- The expected figure is computed from the *dequantized* shape on purpose: `Tensor.numel()` is not- overridden on a GGMLTensor and reports the packed element count instead — a different number- either way, and for a 4-bit quant roughly half of what is about to be allocated. The multiplier- is imported rather than restated: what this test owns is that the loader reserves against the- right *tensor*, while `test_quantized_embedding.py` owns the multiplier's value.- """+ """Budget the live checkpoint, model-owned buffers, output and one slice of temporaries."""ram_cache = create_autospec(ModelCache, instance=True)encoder = load_tiny_gguf_encoder(monkeypatch, tmp_path, ram_cache=ram_cache)embed_weight = encoder.language_model.embed_tokens.weight- expected = PEAK_COPIES * embed_weight.shape.numel() * torch.float32.itemsize+ reader = gguf.GGUFReader(tmp_path / "qwen3vl_tiny.gguf")+ packed_bytes = sum(int(t.n_bytes) for t in reader.tensors)+ del reader+ buffer_bytes = sum(b.untyped_storage().nbytes() for b in encoder.buffers() if not b.is_meta)+ # This tiny embedding fits in one slice. The whole tensor's logical size, not its packed+ # element count, gives both the output and the decode allowance.+ expected = packed_bytes + buffer_bytes + (1 + PEAK_COPIES) * embed_weight.shape.numel() * torch.float32.itemsizeassert ram_cache.make_room.call_args_list == [call(expected)]diff --git a/tests/backend/quantization/gguf/test_loaders.py b/tests/backend/quantization/gguf/test_loaders.pyindex 6d60d211d6..c1aac84c23 100644--- a/tests/backend/quantization/gguf/test_loaders.py+++ b/tests/backend/quantization/gguf/test_loaders.py@@ -423,6 +423,38 @@ def _quantized_embedding(qtype: gguf.GGMLQuantizationType, rows: int = 37, width)[email protected]("rows_per_chunk", [1, 3])[email protected]("dtype", [torch.float32, torch.float16, torch.bfloat16])+ "qtype",+ [gguf.GGMLQuantizationType.Q8_0, gguf.GGMLQuantizationType.Q6_K, gguf.GGMLQuantizationType.IQ4_NL],+ ids=lambda qtype: qtype.name,+)+def test_unpack_decodes_bounded_rows_bit_exactly(monkeypatch, qtype, dtype, rows_per_chunk):+ # A row wider than the budget still decodes whole; 37 rows also gives a short final slice.+ budget = 511 if rows_per_chunk == 1 else 3 * 512+ monkeypatch.setattr(loaders, "_UNPACK_CHUNK_ELEMENTS", budget)+ weight = _quantized_embedding(qtype)+ weight.compute_dtype = dtype+ expected = weight.get_dequantized_tensor()+ decoded = []+ real_decode = GGMLTensor.get_dequantized_tensor++ def record_rows(tensor):+ result = real_decode(tensor)+ decoded.append(result.numel())+ return result++ monkeypatch.setattr(GGMLTensor, "get_dequantized_tensor", record_rows)+ result = loaders.unpack_ggml_tensor(weight)++ assert decoded == ([512] * 37 if rows_per_chunk == 1 else [3 * 512] * 12 + [512])+ assert result.dtype == dtype+ assert result.device == weight.quantized_data.device+ # Compare bytes so NaNs, their payloads, and signed zeros must match exactly.+ assert torch.equal(result.view(torch.uint8), expected.view(torch.uint8))++@pytest.mark.parametrize("qtype",[diff --git a/tests/backend/quantization/sdnq/test_sdnq_tensor_size.py b/tests/backend/quantization/sdnq/test_sdnq_tensor_size.pyindex c192766dc0..d25989c8f9 100644--- a/tests/backend/quantization/sdnq/test_sdnq_tensor_size.py+++ b/tests/backend/quantization/sdnq/test_sdnq_tensor_size.py@@ -37,6 +37,7 @@ def test_uint4_with_svd_size_is_packed_plus_auxiliary():)expected = _nbytes(data, scale, zero_point, svd_up, svd_down)+ assert all(a is b for a, b in zip(t.storage_tensors(), (data, scale, zero_point, svd_up, svd_down), strict=True))assert t.sdnq_storage_nbytes() == expectedassert calc_tensor_size(t) == expected# The naive accounting (dequantized shape × uint8) both over-counts and omits the aux payloads.@@ -59,5 +60,6 @@ def test_int5_size_is_packed_plus_scale():)expected = _nbytes(data, scale)+ assert all(a is b for a, b in zip(t.storage_tensors(), (data, scale), strict=True))assert t.sdnq_storage_nbytes() == expectedassert calc_tensor_size(t) == expected