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.

Stop model identification from holding whole checkpoints in RAM

Alexander Eichhorn8d2f9adaf8b6
diff --git a/invokeai/backend/model_hash/model_hash.py b/invokeai/backend/model_hash/model_hash.py
index 40046c28f3..4933f42810 100644
--- a/invokeai/backend/model_hash/model_hash.py
+++ b/invokeai/backend/model_hash/model_hash.py
@@ -31,6 +31,12 @@ HASHING_ALGORITHMS = Literal[
]
MODEL_FILE_EXTENSIONS = (".ckpt", ".safetensors", ".bin", ".pt", ".pth")
+HASH_CHUNK_SIZE = 8 * 1024 * 1024
+"""Size of the buffer model files are read through when hashing.
+
+Large enough that the read syscalls are not the bottleneck, small enough that hashing a model costs a
+fixed few megabytes no matter how big the model is."""
+
class ModelHash:
"""
@@ -152,9 +158,33 @@ class ModelHash:
files.append(Path(root, file))
return files
+ @staticmethod
+ def _feed(hasher: "blake3", file_path: Path) -> str:
+ """Feeds a file to a hasher through a fixed-size buffer and returns the hexdigest.
+
+ Deliberately not blake3's `update_mmap`: mapping a multi-GB checkpoint charges the whole file to the
+ process working set and keeps it mapped for as long as the hasher lives. Freshly installed models are
+ moved immediately after hashing, and on Windows a live mapping blocks that move. Reading the same bytes
+ through a buffer costs `HASH_CHUNK_SIZE` instead of the file size, and for the single-threaded default it
+ is also faster than mapping.
+
+ Args:
+ hasher: The blake3 hasher to feed
+ file_path: Path to the file to hash
+
+ Returns:
+ Hexdigest of the hash of the file
+ """
+ buffer = bytearray(HASH_CHUNK_SIZE)
+ mv = memoryview(buffer)
+ with open(file_path, "rb", buffering=0) as f:
+ while n := f.readinto(mv):
+ hasher.update(mv[:n])
+ return hasher.hexdigest()
+
@staticmethod
def _blake3(file_path: Path) -> str:
- """Hashes a file using BLAKE3, using parallelized and memory-mapped I/O to avoid reading the entire file into memory.
+ """Hashes a file using BLAKE3, hashing each buffer of the file in parallel.
Args:
file_path: Path to the file to hash
@@ -162,9 +192,7 @@ class ModelHash:
Returns:
Hexdigest of the hash of the file
"""
- file_hasher = blake3(max_threads=blake3.AUTO)
- file_hasher.update_mmap(file_path)
- return file_hasher.hexdigest()
+ return ModelHash._feed(blake3(max_threads=blake3.AUTO), file_path)
@staticmethod
def _blake3_single(file_path: Path) -> str:
@@ -176,9 +204,7 @@ class ModelHash:
Returns:
Hexdigest of the hash of the file
"""
- file_hasher = blake3()
- file_hasher.update_mmap(file_path)
- return file_hasher.hexdigest()
+ return ModelHash._feed(blake3(), file_path)
@staticmethod
def _get_hashlib(algorithm: HASHING_ALGORITHMS) -> Callable[[Path], str]:
diff --git a/invokeai/backend/model_manager/configs/factory.py b/invokeai/backend/model_manager/configs/factory.py
index c695cf41bf..6960f3d4e2 100644
--- a/invokeai/backend/model_manager/configs/factory.py
+++ b/invokeai/backend/model_manager/configs/factory.py
@@ -512,6 +512,25 @@ class ModelClassificationResult:
class ModelConfigFactory:
+ @staticmethod
+ def _detach_traceback(e: Exception) -> Exception:
+ """Drop the traceback and exception chain from a failed match before it is stored.
+
+ A stored traceback pins the frames of the config class that raised it, and those frames hold the
+ model's whole state dict in their locals. Exception/traceback/frame is a reference cycle, so the
+ state dict survives until the cyclic collector runs - and that collector is driven by object
+ counts, while a state dict is a few thousand objects holding gigabytes. Installing a queue of
+ models therefore accumulates every probed checkpoint in RAM (and, for safetensors, keeps the file
+ mapped, which is why moving the file afterwards needs retries on Windows).
+
+ Nothing reads these tracebacks: `details` is only ever consumed for the exception's type and
+ message.
+ """
+ e.__traceback__ = None
+ e.__context__ = None
+ e.__cause__ = None
+ return e
+
@staticmethod
def from_dict(fields: dict[str, Any]) -> AnyModelConfig:
"""Return the appropriate config object from raw dict values."""
@@ -722,19 +741,19 @@ class ModelConfigFactory:
details[candidate_name] = candidate_class.from_model_on_disk(mod, fields) # type: ignore
except NotAMatchError as e:
# This means the model didn't match this config class. It's not an error, just no match.
- details[candidate_name] = e
+ details[candidate_name] = ModelConfigFactory._detach_traceback(e)
except InvalidMatchError as e:
# This means the model *is* this config class' kind of model, but is unusable (e.g. a
# truncated checkpoint). Recorded like any other result here; the fallback below is
# what treats it differently from a plain no-match.
- details[candidate_name] = e
+ details[candidate_name] = ModelConfigFactory._detach_traceback(e)
except ValidationError as e:
# This means the model matched, but we couldn't create the pydantic model instance for the config.
# Maybe invalid overrides were provided?
- details[candidate_name] = e
+ details[candidate_name] = ModelConfigFactory._detach_traceback(e)
except Exception as e:
# Some other unexpected error occurred. Store the exception for reporting later.
- details[candidate_name] = e
+ details[candidate_name] = ModelConfigFactory._detach_traceback(e)
# Extract just the successful matches
matches = [r for r in details.values() if isinstance(r, Config_Base)]
diff --git a/invokeai/backend/model_manager/model_on_disk.py b/invokeai/backend/model_manager/model_on_disk.py
index e5fdf1f617..f8b9798061 100644
--- a/invokeai/backend/model_manager/model_on_disk.py
+++ b/invokeai/backend/model_manager/model_on_disk.py
@@ -1,3 +1,4 @@
+import json
from pathlib import Path
from typing import Any, Optional, TypeAlias
@@ -20,6 +21,48 @@ StateDict: TypeAlias = dict[str | int, Any] # When are the keys int?
logger = InvokeAILogger.get_logger()
+SAFETENSORS_DTYPES: dict[str, torch.dtype] = {
+ "BOOL": torch.bool,
+ "U8": torch.uint8,
+ "I8": torch.int8,
+ "F8_E4M3": torch.float8_e4m3fn,
+ "F8_E5M2": torch.float8_e5m2,
+ "U16": torch.uint16,
+ "I16": torch.int16,
+ "BF16": torch.bfloat16,
+ "F16": torch.float16,
+ "U32": torch.uint32,
+ "I32": torch.int32,
+ "F32": torch.float32,
+ "U64": torch.uint64,
+ "I64": torch.int64,
+ "F64": torch.float64,
+}
+"""safetensors dtype names mapped to their torch equivalents."""
+
+
+def _safetensors_meta_state_dict(path: Path) -> StateDict:
+ """Build a state dict of `meta` tensors from a safetensors file's header.
+
+ Identification only ever reads keys, shapes and dtypes off a state dict - never tensor data - so loading
+ the tensors costs the model's full size in RAM for every probe and buys nothing. The header is a few KB at
+ the front of the file, and `meta` tensors carry the shape and dtype without any storage behind them.
+
+ Raises:
+ Exception: The header could not be parsed, or names a dtype with no torch equivalent. Callers should
+ fall back to loading the file for real.
+ """
+ with open(path, "rb") as f:
+ header_length = int.from_bytes(f.read(8), "little")
+ header = json.loads(f.read(header_length))
+
+ header.pop("__metadata__", None)
+ return {
+ key: torch.empty(info["shape"], dtype=SAFETENSORS_DTYPES[info["dtype"]], device="meta")
+ for key, info in header.items()
+ }
+
+
def _is_sdnq_safetensors(path: Path) -> bool:
"""Check if a safetensors file contains SDNQ-quantized weights by checking for weight+scale pairs."""
try:
@@ -135,7 +178,9 @@ class ModelOnDisk:
)
else:
raise RuntimeError(f"Error scanning the model at {path.stem} for malware. Aborting import.")
- checkpoint = torch.load(path, map_location="cpu")
+ # `meta` for the same reason the safetensors branch reads only the header: identification
+ # needs the shapes, not the weights, and torch skips reading the storages entirely.
+ checkpoint = torch.load(path, map_location="meta")
assert isinstance(checkpoint, dict)
elif path.suffix.endswith(".gguf"):
checkpoint = gguf_sd_loader(path, compute_dtype=torch.float32)
@@ -143,7 +188,11 @@ class ModelOnDisk:
if _is_sdnq_safetensors(path):
checkpoint = sdnq_sd_loader(path, compute_dtype=torch.float32)
else:
- checkpoint = safetensors.torch.load_file(path)
+ try:
+ checkpoint = _safetensors_meta_state_dict(path)
+ except Exception:
+ logger.debug(f"Could not read the safetensors header of {path}, loading the whole file")
+ checkpoint = safetensors.torch.load_file(path)
else:
raise ValueError(f"Unrecognized model extension: {path.suffix}")