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(ltx2): run the prompt encoder on cards that partially load it
Lincoln Stein6bf9d756c9ec
diff --git a/invokeai/app/invocations/text_encoder/ltx2_text_encoder.py b/invokeai/app/invocations/text_encoder/ltx2_text_encoder.pyindex 7546c86ed6..e95533377c 100644--- a/invokeai/app/invocations/text_encoder/ltx2_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/ltx2_text_encoder.py@@ -26,7 +26,6 @@ from invokeai.backend.ltx2.text_conditioning import (estimate_connector_working_memory,estimate_tower_working_memory,)-from invokeai.backend.model_manager.load.model_cache.utils import get_effective_devicefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData@@ -92,8 +91,39 @@ class LTX2TextEncoderInvocation(BaseInvocation):prompts.append(self.negative_prompt)# The 12B tower and the 6 GB connectors run in two phases with the states parked in RAM in- # between, so only one of them is resident at a time. Loading the tower first also keeps the- # cache from evicting the small tokenizer record to make room for it (issue #7513).+ # between, so only one of them is resident at a time.+ hidden_states = self._encode_with_tower(context, prompts)++ connectors_info = context.models.load(self.text_encoder.connectors)+ connector_memory = estimate_connector_working_memory(hidden_states[0][0])+ with connectors_info.model_on_device(working_mem_bytes=connector_memory) as (_, connectors):+ context.util.signal_progress("Running the LTX-2 text connectors")+ names = [+ context.conditioning.save(+ ConditioningFieldData(+ conditionings=[apply_connectors(connectors, *state, device=connectors_info.compute_device)]+ )+ )+ for state in hidden_states+ ]++ return LTX2TextEncoderOutput(+ conditioning=LTX2ConditioningField(conditioning_name=names[0]),+ negative_conditioning=LTX2ConditioningField(conditioning_name=names[1]) if len(names) > 1 else None,+ )++ def _encode_with_tower(+ self, context: InvocationContext, prompts: list[str]+ ) -> list[tuple[torch.Tensor, torch.Tensor]]:+ """Run the Gemma-4 tower over each prompt and return the packed states and masks, on the CPU.++ A method of its own so every reference to the tower is gone when it returns. Loading the+ connectors next can evict the tower from a small RAM cache while its weights are still on the+ device, and a reference kept past that point pins those weights in VRAM where the cache no+ longer accounts for them.+ """+ # Loading the tower first keeps the cache from evicting the small tokenizer record to make+ # room for it (issue #7513).text_encoder_info = context.models.load(self.text_encoder.text_encoder)tokenizer_info = context.models.load(self.text_encoder.tokenizer)# Read off the unlocked model, before the VRAM lock the reservation applies to.@@ -103,7 +133,6 @@ class LTX2TextEncoderInvocation(BaseInvocation):tokenizer_info.model_on_device() as (_, tokenizer),text_encoder_info.model_on_device(working_mem_bytes=tower_memory) as (_, text_encoder),):- device = get_effective_device(text_encoder)context.util.signal_progress("Running the LTX-2 Gemma-4 text encoder")for prompt in prompts:states, mask = encode_hidden_states(@@ -111,20 +140,7 @@ class LTX2TextEncoderInvocation(BaseInvocation):tokenizer,prompt,max_sequence_length=self.max_sequence_length,- device=device,+ device=text_encoder_info.compute_device,)hidden_states.append((states.cpu(), mask.cpu()))-- connectors_info = context.models.load(self.text_encoder.connectors)- connector_memory = estimate_connector_working_memory(hidden_states[0][0])- with connectors_info.model_on_device(working_mem_bytes=connector_memory) as (_, connectors):- context.util.signal_progress("Running the LTX-2 text connectors")- names = [- context.conditioning.save(ConditioningFieldData(conditionings=[apply_connectors(connectors, *state)]))- for state in hidden_states- ]-- return LTX2TextEncoderOutput(- conditioning=LTX2ConditioningField(conditioning_name=names[0]),- negative_conditioning=LTX2ConditioningField(conditioning_name=names[1]) if len(names) > 1 else None,- )+ return hidden_statesdiff --git a/invokeai/backend/ltx2/text_conditioning.py b/invokeai/backend/ltx2/text_conditioning.pyindex 66c5928c24..7f37fd9174 100644--- a/invokeai/backend/ltx2/text_conditioning.py+++ b/invokeai/backend/ltx2/text_conditioning.py@@ -87,9 +87,15 @@ def encode_hidden_states(@torch.no_grad()-def apply_connectors(connectors, hidden_states: torch.Tensor, attention_mask: torch.Tensor) -> LTX2ConditioningInfo:- """Project the packed per-layer states into the video and audio prompt streams."""- device = next(connectors.parameters()).device+def apply_connectors(+ connectors, hidden_states: torch.Tensor, attention_mask: torch.Tensor, device: torch.device+) -> LTX2ConditioningInfo:+ """Project the packed per-layer states into the video and audio prompt streams.++ ``device`` is the cache's compute device, not one read off the weights: when the connectors are+ only partially loaded, most weights stay in RAM and are streamed per forward, while the+ registers the forward mixes into the states are on the device.+ """dtype = next(connectors.parameters()).dtypevideo_embeds, audio_embeds, mask = connectors(hidden_states.to(device=device, dtype=dtype),diff --git a/tests/app/invocations/test_ltx2_nodes.py b/tests/app/invocations/test_ltx2_nodes.pyindex a43b0bc227..1f56f75f21 100644--- a/tests/app/invocations/test_ltx2_nodes.py+++ b/tests/app/invocations/test_ltx2_nodes.py@@ -1,6 +1,9 @@"""LTX-2 node contracts that do not need a model: what each node refuses, and why."""+import gcimport wave+import weakref+from contextlib import contextmanagerfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import MagicMock@@ -14,6 +17,7 @@ from pydantic import ValidationErrorimport invokeai.app.invocations.ltx2.ltx2_audio_conditioning as ltx2_audio_conditioningimport invokeai.app.invocations.ltx2.ltx2_extend_conditioning as ltx2_extend_conditioningimport invokeai.app.invocations.ltx2.ltx2_video_conditioning as ltx2_video_conditioning+import invokeai.app.invocations.text_encoder.ltx2_text_encoder as ltx2_text_encoderimport invokeai.app.invocations.vae.ltx2_latents_to_video as ltx2_latents_to_videofrom invokeai.app.invocations.fields import (LatentsField,@@ -1503,3 +1507,55 @@ def _denoise_state_stub(keyframe_rows: int):class _StopAfterState(Exception):"""Ends the invocation once the state has been built, before any model is loaded."""+++class _LoadedModel:+ """The part of ``LoadedModel`` the prompt node uses: the model, its device and a lock."""++ def __init__(self, model: object) -> None:+ self.model = model+ self.compute_device = torch.device("cpu")++ @contextmanager+ def model_on_device(self, working_mem_bytes: int | None = None):+ yield None, self.model+++def test_the_prompt_node_lets_go_of_the_tower_before_it_loads_the_connectors(monkeypatch) -> None:+ """Loading the connectors can evict the tower from a small RAM cache while its weights are still on the+ device; a reference the node still holds then pins them in VRAM, where the cache no longer counts them."""+ from invokeai.app.invocations.model import LTX2TextEncoderField++ tower_alive_at_connector_load: list[bool] = []+ tower_ref: list[weakref.ref] = []++ def load(identifier: ModelIdentifierField) -> _LoadedModel:+ if identifier.key == "text_encoder":+ tower = torch.nn.Linear(1, 1)+ tower_ref.append(weakref.ref(tower))+ return _LoadedModel(tower)+ if identifier.key == "connectors":+ gc.collect()+ tower_alive_at_connector_load.append(tower_ref[0]() is not None)+ return _LoadedModel(object())++ monkeypatch.setattr(+ ltx2_text_encoder, "encode_hidden_states", lambda *_a, **_k: (torch.zeros(1, 4, 8), torch.ones(1, 4))+ )+ monkeypatch.setattr(ltx2_text_encoder, "apply_connectors", lambda *_a, **_k: MagicMock())+ context = _context()+ context.models.load.side_effect = load+ context.conditioning.save.return_value = "conditioning"++ node = ltx2_text_encoder.LTX2TextEncoderInvocation(+ id="prompt",+ prompt="a cat",+ text_encoder=LTX2TextEncoderField(+ tokenizer=_identifier("tokenizer"),+ text_encoder=_identifier("text_encoder"),+ connectors=_identifier("connectors"),+ ),+ )+ node.invoke(context)++ assert tower_alive_at_connector_load == [False]diff --git a/tests/backend/ltx2/test_ltx2_real_files.py b/tests/backend/ltx2/test_ltx2_real_files.pyindex 4adb08e4aa..0b0bf951df 100644--- a/tests/backend/ltx2/test_ltx2_real_files.py+++ b/tests/backend/ltx2/test_ltx2_real_files.py@@ -231,7 +231,7 @@ def _encode_prompts(device: torch.device, prompts: list[str]):connectors = _loader(LTX2FolderModel, device)._load_model(_folder_config(), SubModelType.Connectors)connectors = connectors.to(device).eval()- conditionings = [apply_connectors(connectors, *state) for state in states]+ conditionings = [apply_connectors(connectors, *state, device=device) for state in states]del connectorsgc.collect()TorchDevice.empty_cache()diff --git a/tests/backend/ltx2/test_ltx2_text_conditioning.py b/tests/backend/ltx2/test_ltx2_text_conditioning.pynew file mode 100644index 0000000000..f8b3668061--- /dev/null+++ b/tests/backend/ltx2/test_ltx2_text_conditioning.py@@ -0,0 +1,51 @@+"""LTX-2 text connectors under the model cache's partial loading."""++import pytest+import torch++from invokeai.backend.ltx2.text_conditioning import apply_connectors+from invokeai.backend.model_manager.load.model_cache.cached_model.cached_model_with_partial_load import (+ CachedModelWithPartialLoad,+)+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (+ apply_custom_layers_to_model,+)+++def _tiny_connectors() -> torch.nn.Module:+ from diffusers.pipelines.ltx2.connectors import LTX2TextConnectors++ torch.manual_seed(0)+ return LTX2TextConnectors(+ caption_channels=16,+ text_proj_in_factor=3,+ video_connector_num_attention_heads=2,+ video_connector_attention_head_dim=8,+ video_connector_num_layers=1,+ video_connector_num_learnable_registers=4,+ audio_connector_num_attention_heads=2,+ audio_connector_attention_head_dim=8,+ audio_connector_num_layers=1,+ audio_connector_num_learnable_registers=4,+ ).eval()++[email protected](not torch.cuda.is_available(), reason="Requires CUDA.")+def test_connectors_run_with_only_required_weights_on_the_device():+ """With no VRAM to spare, only the registers are resident and the projection weights stream from RAM."""+ connectors = _tiny_connectors()+ # Left-padded, as the Gemma tokenizer emits it, so the registers fill the tail.+ hidden_states = torch.randn(1, 8, 48)+ attention_mask = torch.tensor([[0, 0, 0, 1, 1, 1, 1, 1]])+ expected = apply_connectors(connectors, hidden_states, attention_mask, device=torch.device("cpu"))++ apply_custom_layers_to_model(connectors)+ cached = CachedModelWithPartialLoad(connectors, torch.device("cuda"))+ cached.partial_load_to_vram(0)+ assert next(connectors.parameters()).device.type == "cpu"++ actual = apply_connectors(connectors, hidden_states, attention_mask, device=torch.device("cuda"))++ torch.testing.assert_close(actual.video_embeds, expected.video_embeds, atol=1e-4, rtol=1e-4)+ torch.testing.assert_close(actual.audio_embeds, expected.audio_embeds, atol=1e-4, rtol=1e-4)+ torch.testing.assert_close(actual.attention_mask, expected.attention_mask)