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(imagemap): load CLIP towers with the top-level projection_dim

Lincoln Stein88603a4207df
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index d4abb4c012..f2cf095f78 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -463,11 +463,18 @@ class ImageIndexService(ImageIndexServiceBase):
from transformers import AutoTokenizer, CLIPTextModelWithProjection, SiglipTextModel
+ from invokeai.backend.model_manager.util.clip_tower_config import clip_tower_config_override
+
model_path = str(self._model_abs_path())
is_siglip = self._model_config.type is ModelType.SigLIP
try:
tokenizer = AutoTokenizer.from_pretrained(model_path, local_files_only=True)
text_cls = SiglipTextModel if is_siglip else CLIPTextModelWithProjection
+ # Full-CLIP checkpoints may carry a nested projection_dim
+ # that disagrees with the weights; see
+ # clip_tower_config_override.
+ tower_config = None if is_siglip else clip_tower_config_override(model_path, "text")
+ extra_kwargs = {} if tower_config is None else {"config": tower_config}
# skip_torch_weight_init serializes nothing: it monkey-patches
# torch.nn.Linear/_ConvNd/Embedding.reset_parameters process-wide
# and restores whatever it saw on entry. Two threads inside it at
@@ -478,7 +485,7 @@ class ImageIndexService(ImageIndexServiceBase):
# load_state_dict(assign=True) would hijack these parameters onto
# the meta device. Same reasoning as ModelLoader._load_and_cache.
with MODEL_LOAD_LOCK.write_lock(), skip_torch_weight_init():
- model = text_cls.from_pretrained(model_path, local_files_only=True)
+ model = text_cls.from_pretrained(model_path, local_files_only=True, **extra_kwargs)
except Exception as e:
# Vision-only or partial installs (e.g. the IP-Adapter image
# encoder, or a full-CLIP checkpoint shipped without tokenizer
@@ -1355,16 +1362,20 @@ class ImageIndexService(ImageIndexServiceBase):
if self._cpu_model is None:
from transformers import CLIPVisionModelWithProjection, SiglipVisionModel
+ from invokeai.backend.model_manager.util.clip_tower_config import clip_tower_config_override
+
model_path = str(self._model_abs_path())
- model_cls = (
- SiglipVisionModel
- if self._model_config.type is ModelType.SigLIP
- else CLIPVisionModelWithProjection
- )
+ is_siglip = self._model_config.type is ModelType.SigLIP
+ model_cls = SiglipVisionModel if is_siglip else CLIPVisionModelWithProjection
+ # Full-CLIP checkpoints may carry a nested projection_dim
+ # that disagrees with the weights; see
+ # clip_tower_config_override.
+ tower_config = None if is_siglip else clip_tower_config_override(model_path, "vision")
+ extra_kwargs = {} if tower_config is None else {"config": tower_config}
# Process-global patch, so it needs the process-global lock —
# see _get_text_encoder for what goes wrong without it.
with MODEL_LOAD_LOCK.write_lock(), skip_torch_weight_init():
- model = model_cls.from_pretrained(model_path, local_files_only=True)
+ model = model_cls.from_pretrained(model_path, local_files_only=True, **extra_kwargs)
model.eval()
self._cpu_model = model
return self._embed(self._cpu_model, images, torch.device("cpu"))
diff --git a/invokeai/backend/model_manager/load/model_loaders/clip_vision.py b/invokeai/backend/model_manager/load/model_loaders/clip_vision.py
index 0150e24248..c0ef3fc87d 100644
--- a/invokeai/backend/model_manager/load/model_loaders/clip_vision.py
+++ b/invokeai/backend/model_manager/load/model_loaders/clip_vision.py
@@ -8,6 +8,7 @@ from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.load.load_default import ModelLoader
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
from invokeai.backend.model_manager.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelType
+from invokeai.backend.model_manager.util.clip_tower_config import clip_tower_config_override
@ModelLoaderRegistry.register(base=BaseModelType.Any, type=ModelType.CLIPVision, format=ModelFormat.Diffusers)
@@ -27,8 +28,12 @@ class ClipVisionLoader(ModelLoader):
model_path = Path(config.path)
+ # Full-CLIP checkpoints may carry a nested projection_dim that
+ # disagrees with the weights; see clip_tower_config_override.
+ tower_config = clip_tower_config_override(model_path, "vision")
+ extra_kwargs = {} if tower_config is None else {"config": tower_config}
model = CLIPVisionModelWithProjection.from_pretrained(
- model_path, torch_dtype=self._torch_dtype, local_files_only=True
+ model_path, torch_dtype=self._torch_dtype, local_files_only=True, **extra_kwargs
)
assert isinstance(model, CLIPVisionModelWithProjection)
diff --git a/invokeai/backend/model_manager/util/clip_tower_config.py b/invokeai/backend/model_manager/util/clip_tower_config.py
new file mode 100644
index 0000000000..e8fa812dd2
--- /dev/null
+++ b/invokeai/backend/model_manager/util/clip_tower_config.py
@@ -0,0 +1,44 @@
+"""Sub-tower config resolution for full-CLIP checkpoints.
+
+``CLIPVisionModelWithProjection`` / ``CLIPTextModelWithProjection`` size their
+projection head from the *nested* ``vision_config`` / ``text_config``
+``projection_dim``. ``CLIPModel`` itself sizes both projections from the
+*top-level* ``projection_dim`` and never reads the nested values — so a
+published full-CLIP repo can carry nested defaults that disagree with its own
+weights (apple/DFN2B-CLIP-ViT-L-14-39B: top-level 768, nested 512) and still
+load fine as ``CLIPModel``, while the WithProjection classes build a 512-wide
+head and fail on the 768-wide checkpoint tensor. The top-level value is the
+authoritative one; these helpers copy it into the sub-config so a tower can be
+loaded on its own.
+"""
+
+from pathlib import Path
+from typing import Literal, Optional
+
+from transformers import AutoConfig, CLIPConfig, CLIPTextConfig, CLIPVisionConfig
+
+
+def clip_tower_config_override(
+ model_path: str | Path, tower: Literal["vision", "text"]
+) -> Optional[CLIPVisionConfig | CLIPTextConfig]:
+ """The config to pass when loading one tower of the checkpoint at ``model_path``.
+
+ Returns ``None`` when the checkpoint is not a full ``CLIPModel`` (e.g. a
+ vision-only IP-Adapter image-encoder directory, or a SigLIP model) — the
+ tower class's own config handling is already correct there, and the caller
+ should not pass an override.
+ """
+ try:
+ config = AutoConfig.from_pretrained(str(model_path), local_files_only=True)
+ except Exception:
+ # AutoConfig is stricter than both the install probe and the tower
+ # classes' own config resolution: it refuses a config.json with no
+ # model_type, which the pre-override load path accepted. Returning
+ # None restores that path exactly; a genuinely broken directory then
+ # fails in from_pretrained with its usual error.
+ return None
+ if not isinstance(config, CLIPConfig):
+ return None
+ sub_config = config.vision_config if tower == "vision" else config.text_config
+ sub_config.projection_dim = config.projection_dim
+ return sub_config
diff --git a/tests/backend/model_manager/util/test_clip_tower_config.py b/tests/backend/model_manager/util/test_clip_tower_config.py
new file mode 100644
index 0000000000..31f8cdd66a
--- /dev/null
+++ b/tests/backend/model_manager/util/test_clip_tower_config.py
@@ -0,0 +1,113 @@
+"""Tests for sub-tower config resolution on full-CLIP checkpoints."""
+
+import pytest
+import torch
+from transformers import (
+ CLIPConfig,
+ CLIPModel,
+ CLIPTextModelWithProjection,
+ CLIPVisionConfig,
+ CLIPVisionModelWithProjection,
+)
+
+from invokeai.backend.model_manager.util.clip_tower_config import clip_tower_config_override
+
+# A full CLIPModel whose top-level projection_dim (8) differs from the nested
+# configs' untouched default (512) — the exact shape of published repos like
+# apple/DFN2B-CLIP-ViT-L-14-39B, where CLIPModel loads but the WithProjection
+# tower classes build a wrong-sized head.
+_TINY_FULL_CLIP = CLIPConfig(
+ projection_dim=8,
+ vision_config={
+ "hidden_size": 16,
+ "intermediate_size": 32,
+ "num_hidden_layers": 1,
+ "num_attention_heads": 2,
+ "image_size": 8,
+ "patch_size": 4,
+ },
+ text_config={
+ "hidden_size": 16,
+ "intermediate_size": 32,
+ "num_hidden_layers": 1,
+ "num_attention_heads": 2,
+ "max_position_embeddings": 12,
+ "vocab_size": 99,
+ },
+)
+
+
+def full_clip_dir(tmp_path):
+ torch.manual_seed(0)
+ CLIPModel(_TINY_FULL_CLIP).save_pretrained(tmp_path)
+ return tmp_path
+
+
+def test_override_copies_top_level_projection_dim(full_clip_dir) -> None:
+ for tower in ("vision", "text"):
+ override = clip_tower_config_override(full_clip_dir, tower)
+ assert override is not None
+ assert override.projection_dim == 8
+
+
+def test_towers_load_and_match_full_model(full_clip_dir) -> None:
+ full = CLIPModel.from_pretrained(full_clip_dir).eval()
+ vision = CLIPVisionModelWithProjection.from_pretrained(
+ full_clip_dir, config=clip_tower_config_override(full_clip_dir, "vision")
+ ).eval()
+ text = CLIPTextModelWithProjection.from_pretrained(
+ full_clip_dir, config=clip_tower_config_override(full_clip_dir, "text")
+ ).eval()
+
+ assert vision.visual_projection.out_features == 8
+ assert text.text_projection.out_features == 8
+
+ def as_tensor(features) -> torch.Tensor:
+ # transformers >= 5 returns BaseModelOutputWithPooling from
+ # CLIPModel.get_*_features; older versions returned a bare tensor.
+ if isinstance(features, torch.Tensor):
+ return features
+ return features.pooler_output
+
+ torch.manual_seed(1)
+ pixel_values = torch.randn(1, 3, 8, 8)
+ input_ids = torch.tensor([[1, 5, 9, 2]])
+ with torch.no_grad():
+ assert torch.allclose(
+ vision(pixel_values=pixel_values).image_embeds, as_tensor(full.get_image_features(pixel_values))
+ )
+ assert torch.allclose(text(input_ids=input_ids).text_embeds, as_tensor(full.get_text_features(input_ids)))
+
+
+def test_override_is_none_when_config_has_no_model_type(tmp_path) -> None:
+ # The install probe accepts a config.json with architectures but no
+ # model_type, and the tower classes load such a dir; AutoConfig refuses
+ # it. The helper must return None (pre-override behavior), not raise.
+ import json
+
+ config = json.loads((_write_vision_only(tmp_path) / "config.json").read_text())
+ del config["model_type"]
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ assert clip_tower_config_override(tmp_path, "vision") is None
+
+
+def _write_vision_only(tmp_path):
+ config = CLIPVisionConfig(
+ hidden_size=16,
+ intermediate_size=32,
+ num_hidden_layers=1,
+ num_attention_heads=2,
+ image_size=8,
+ patch_size=4,
+ projection_dim=8,
+ )
+ CLIPVisionModelWithProjection(config).save_pretrained(tmp_path)
+ return tmp_path
+
+
+def test_override_is_none_for_vision_only_checkpoint(tmp_path) -> None:
+ # A vision-only dir (e.g. an IP-Adapter image encoder) has a correct config
+ # of its own; the override must not interfere.
+ _write_vision_only(tmp_path)
+ assert clip_tower_config_override(tmp_path, "vision") is None