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: preserve CLIP hidden states after first skipped forward (#9806)

Nianze Wu35d08c870cdc
diff --git a/invokeai/backend/model_patcher.py b/invokeai/backend/model_patcher.py
index 39022199e1..c7bd0b7e6b 100644
--- a/invokeai/backend/model_patcher.py
+++ b/invokeai/backend/model_patcher.py
@@ -9,6 +9,7 @@ from typing import Any, Generator, Iterator, List, Optional, Tuple, Type, Union
import torch
from diffusers.models.unets.unet_2d_condition import UNet2DConditionModel
from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
+from transformers.utils.output_capturing import maybe_install_capturing_hooks
from invokeai.app.shared.models import FreeUConfig
from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
@@ -151,7 +152,12 @@ class ModelPatcher:
clip_skip: int,
) -> Generator[None, Any, Any]:
# transformers >=5.6 flattened CLIPTextModel (no `text_model` wrapper); CLIPTextModelWithProjection still wraps.
- layers = getattr(text_encoder, "text_model", text_encoder).encoder.layers
+ clip_model = getattr(text_encoder, "text_model", text_encoder)
+ if clip_skip > 0:
+ # Transformers installs output-capture hooks lazily on the first hidden-state request. Install them on the
+ # complete encoder first, or a request while layers are popped leaves the restored layers unhooked.
+ maybe_install_capturing_hooks(clip_model)
+ layers = clip_model.encoder.layers
skipped_layers = []
try:
for _i in range(clip_skip):
diff --git a/tests/backend/test_clip_text_model_wrapper.py b/tests/backend/test_clip_text_model_wrapper.py
index 915c0afd7d..015d3a0d9c 100644
--- a/tests/backend/test_clip_text_model_wrapper.py
+++ b/tests/backend/test_clip_text_model_wrapper.py
@@ -35,17 +35,43 @@ def _config() -> CLIPTextConfig:
@pytest.mark.parametrize("model_class", [CLIPTextModel, CLIPTextModelWithProjection])
def test_clip_skip_drops_and_restores_the_last_layers(model_class: type[torch.nn.Module]) -> None:
model = model_class(_config()).eval()
+ reference = model_class(_config()).eval()
+ reference.load_state_dict(model.state_dict())
ids = torch.tensor([[0, 5, 6, 2]])
- # transformers records hidden states with hooks installed on the layers present at the first forward, so a first
- # forward under clip skip would leave the restored layers unrecorded (#9722, also on 5.5). Warm up unskipped.
- assert len(model(ids, output_hidden_states=True).hidden_states) == NUM_LAYERS + 1
+ expected = reference(ids, output_hidden_states=True)
with ModelPatcher.apply_clip_skip(model, 2):
- assert len(model(ids, output_hidden_states=True).hidden_states) == NUM_LAYERS - 2 + 1
+ skipped = model(ids, output_hidden_states=True)
+ assert len(skipped.hidden_states) == NUM_LAYERS - 2 + 1
+ torch.testing.assert_close(skipped.hidden_states, expected.hidden_states[:-2])
+ torch.testing.assert_close(
+ skipped.last_hidden_state,
+ getattr(reference, "text_model", reference).final_layer_norm(expected.hidden_states[-3]),
+ )
+
+ restored = model(ids, output_hidden_states=True)
+ assert len(restored.hidden_states) == NUM_LAYERS + 1
+ torch.testing.assert_close(restored.hidden_states, expected.hidden_states)
+ torch.testing.assert_close(restored.last_hidden_state, expected.last_hidden_state)
+
+
+def test_clip_skip_does_not_duplicate_hidden_states_on_a_warmed_projection_model() -> None:
+ model = CLIPTextModelWithProjection(_config()).eval()
+ ids = torch.tensor([[0, 5, 6, 2]])
+ expected = model(ids, output_hidden_states=True)
+
+ with ModelPatcher.apply_clip_skip(model, 1):
+ skipped = model(ids, output_hidden_states=True)
+ assert len(skipped.hidden_states) == NUM_LAYERS
+ torch.testing.assert_close(skipped.hidden_states, expected.hidden_states[:-1])
- assert len(model(ids, output_hidden_states=True).hidden_states) == NUM_LAYERS + 1
+ restored = model(ids, output_hidden_states=True)
+ assert len(restored.hidden_states) == NUM_LAYERS + 1
+ torch.testing.assert_close(restored.hidden_states, expected.hidden_states)
@pytest.mark.parametrize(