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(minimax-h3): stop the AdaLN overlay pinning its transformer file (#10360)

Vladimir Babin8d721a280621
diff --git a/invokeai/backend/minimax_h3/adaln_overlay.py b/invokeai/backend/minimax_h3/adaln_overlay.py
index 74c7d776c7..04323597f5 100644
--- a/invokeai/backend/minimax_h3/adaln_overlay.py
+++ b/invokeai/backend/minimax_h3/adaln_overlay.py
@@ -17,7 +17,8 @@ FL2VA quality and reference adherence - keeping FL2VA's attention, MLPs and outp
swap happens at denoise time on the cached FL2VA transformer, the same shape as LoRA patching:
no merged checkpoint is written, and the base model stays shared in the model cache.
-Only the selected AdaLN tensors are read from the overlay checkpoint (mmap): ~1.7 MB per block
+Only the selected AdaLN tensors are read from the overlay checkpoint, with pread into owned
+buffers rather than mmap, so the cached overlay holds no view of the file: ~1.7 MB per block
on the AdaLN-pruned repacks, ~520 MB per block on a full bf16 checkpoint. The model cache keys
local models by path alone, so the selection rides on the path as a fragment and each distinct
selection is its own cache record.
@@ -107,7 +108,7 @@ class MiniMaxH3AdaLNOverlay(torch.nn.Module):
the file's curve table, if it is an AdaLN-pruned checkpoint.
"""
file_path, start_block, end_block, include_final_layer = cls._parse_selection_path(path)
- with safe_open(file_path, framework="pt", device="cpu") as f:
+ with safe_open(file_path, framework="pt", device="cpu", backend="pread") as f:
keys = set(f.keys())
file_blocks = [int(m.group(1)) for key in keys if (m := _BLOCK_KEY_RE.match(key))]
if not file_blocks or _FINAL_ADALN_KEY + "weight" not in keys:
diff --git a/tests/backend/minimax_h3/test_adaln_overlay.py b/tests/backend/minimax_h3/test_adaln_overlay.py
index 66d2bc4c01..10064befc0 100644
--- a/tests/backend/minimax_h3/test_adaln_overlay.py
+++ b/tests/backend/minimax_h3/test_adaln_overlay.py
@@ -24,6 +24,7 @@ from invokeai.backend.patches.layer_patcher import LayerPatcher
from invokeai.backend.patches.layers.lora_layer import LoRALayer
from invokeai.backend.patches.lora_conversions.minimax_h3_lora_constants import MINIMAX_H3_LORA_TRANSFORMER_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from tests.fixtures.safetensors_files import needs_mapping_that_shows_file_writes, tensors_reading_the_file
# Two DiT blocks so a block range can exclude one; latent channel counts are the real 24/32 so
# the denoise loop's packing accepts the model.
@@ -161,6 +162,14 @@ def test_load_reads_only_the_selected_projections(tmp_path: Path, overlay_sd) ->
)
+@needs_mapping_that_shows_file_writes
+def test_load_keeps_no_view_of_the_transformer_file(tmp_path: Path, overlay_sd) -> None:
+ path = _save(tmp_path / "ref2va.safetensors", overlay_sd)
+ overlay = MiniMaxH3AdaLNOverlay.load_model(MiniMaxH3AdaLNOverlay.selection_path(path, 0, 49, True))
+
+ assert tensors_reading_the_file(overlay, path) == []
+
+
def test_selection_paths_round_trip_and_an_empty_selection_is_refused(tmp_path: Path, overlay_sd) -> None:
path = _save(tmp_path / "ref2va.safetensors", overlay_sd)
assert MiniMaxH3AdaLNOverlay.selection_path(path, 25, 49, False).name == "ref2va.safetensors#adaln-25-49"
diff --git a/tests/backend/model_manager/load/test_loaders_read_float8_checkpoints_owned.py b/tests/backend/model_manager/load/test_loaders_read_float8_checkpoints_owned.py
index 9a8eaff480..1089dae289 100644
--- a/tests/backend/model_manager/load/test_loaders_read_float8_checkpoints_owned.py
+++ b/tests/backend/model_manager/load/test_loaders_read_float8_checkpoints_owned.py
@@ -13,6 +13,7 @@ from pathlib import Path
import pytest
+import invokeai.backend as backend
import invokeai.backend.model_manager.load.model_loaders as model_loaders
_FOLDS = {
@@ -60,22 +61,25 @@ def test_no_loader_folds_float8_weights_it_read_with_a_raw_load_file() -> None:
)
-#: (file, function) pairs that read tensors through a `safe_open` without choosing its backend, each with the reason it
-#: keeps nothing mapped.
+#: (file under `invokeai/backend`, function) pairs that read tensors through a `safe_open` without choosing its backend,
+#: each with the reason it keeps nothing mapped.
_ALLOWED_MAPPED_READS: dict[tuple[str, str], str] = {
- ("mistral_encoder.py", "_extract_tekken_bytes"): "copies the tokenizer's bytes out and keeps no tensor",
(
- "ltx2.py",
+ "model_manager/load/model_loaders/mistral_encoder.py",
+ "_extract_tekken_bytes",
+ ): "copies the tokenizer's bytes out and keeps no tensor",
+ (
+ "model_manager/load/model_loaders/ltx2.py",
"_read_dense_component",
): "a file it accepts has no float8 weight (reject_float8_weights refuses it after the read), so mmap is the backend `safetensors_backend` would pick",
}
def _mapped_tensor_readers() -> list[tuple[str, str]]:
- """Functions that open a file with `safe_open` and take tensors from it without passing a ``backend``.
+ """Functions in `invokeai/backend` that open a file with `safe_open` and take tensors from it without a ``backend``.
The default backend is mmap: each tensor it returns is a view of the file, and a cast to the dtype it already has
- keeps the view. A loader reading tensors this way must say which backend it means (`pread` through
+ keeps the view. Code reading tensors this way must say which backend it means (`pread` through
`load_safetensors_checkpoint`, or an explicit ``backend=``), so that the choice is made and visible. Opening a file
to list its keys is fine: only a ``with`` block that calls ``get_tensor`` counts.
"""
@@ -88,20 +92,21 @@ def _mapped_tensor_readers() -> list[tuple[str, str]]:
and not any(keyword.arg == "backend" for keyword in call.keywords)
)
+ root = Path(inspect.getfile(backend)).parent
found = []
- for path in sorted(Path(inspect.getfile(model_loaders)).parent.glob("*.py")):
+ for path in sorted(root.rglob("*.py")):
for function in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
if not isinstance(function, (ast.FunctionDef, ast.AsyncFunctionDef)):
continue
for block in ast.walk(function):
if isinstance(block, ast.With) and "get_tensor" in _called_names(block):
if any(is_default_backend_open(item) for item in block.items):
- found.append((path.name, function.name))
+ found.append((path.relative_to(root).as_posix(), function.name))
return found
@pytest.mark.platform_independent
-def test_no_loader_takes_tensors_from_a_safe_open_it_left_on_the_default_backend() -> None:
+def test_no_backend_code_takes_tensors_from_a_safe_open_it_left_on_the_default_backend() -> None:
offenders = [site for site in _mapped_tensor_readers() if site not in _ALLOWED_MAPPED_READS]
assert offenders == [], (