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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
from typing import List
|
| 4 |
+
from collections import namedtuple, OrderedDict
|
| 5 |
+
|
| 6 |
+
def is_torch2_available():
|
| 7 |
+
return hasattr(torch.nn.functional, "scaled_dot_product_attention")
|
| 8 |
+
|
| 9 |
+
if is_torch2_available():
|
| 10 |
+
from .attention_processor import (
|
| 11 |
+
AttnProcessor2_0 as AttnProcessor,
|
| 12 |
+
)
|
| 13 |
+
from .attention_processor import (
|
| 14 |
+
CNAttnProcessor2_0 as CNAttnProcessor,
|
| 15 |
+
)
|
| 16 |
+
from .attention_processor import (
|
| 17 |
+
IPAttnProcessor2_0 as IPAttnProcessor,
|
| 18 |
+
)
|
| 19 |
+
from .attention_processor import (
|
| 20 |
+
TA_IPAttnProcessor2_0 as TA_IPAttnProcessor,
|
| 21 |
+
)
|
| 22 |
+
else:
|
| 23 |
+
from .attention_processor import AttnProcessor, CNAttnProcessor, IPAttnProcessor, TA_IPAttnProcessor
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ImageProjModel(torch.nn.Module):
|
| 27 |
+
"""Projection Model"""
|
| 28 |
+
|
| 29 |
+
def __init__(self, cross_attention_dim=2048, clip_embeddings_dim=1280, clip_extra_context_tokens=4):
|
| 30 |
+
super().__init__()
|
| 31 |
+
|
| 32 |
+
self.cross_attention_dim = cross_attention_dim
|
| 33 |
+
self.clip_extra_context_tokens = clip_extra_context_tokens
|
| 34 |
+
self.proj = torch.nn.Linear(clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim)
|
| 35 |
+
self.norm = torch.nn.LayerNorm(cross_attention_dim)
|
| 36 |
+
|
| 37 |
+
def forward(self, image_embeds):
|
| 38 |
+
embeds = image_embeds
|
| 39 |
+
clip_extra_context_tokens = self.proj(embeds).reshape(
|
| 40 |
+
-1, self.clip_extra_context_tokens, self.cross_attention_dim
|
| 41 |
+
)
|
| 42 |
+
clip_extra_context_tokens = self.norm(clip_extra_context_tokens)
|
| 43 |
+
return clip_extra_context_tokens
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class MLPProjModel(torch.nn.Module):
|
| 47 |
+
"""SD model with image prompt"""
|
| 48 |
+
def __init__(self, cross_attention_dim=2048, clip_embeddings_dim=1280):
|
| 49 |
+
super().__init__()
|
| 50 |
+
|
| 51 |
+
self.proj = torch.nn.Sequential(
|
| 52 |
+
torch.nn.Linear(clip_embeddings_dim, clip_embeddings_dim),
|
| 53 |
+
torch.nn.GELU(),
|
| 54 |
+
torch.nn.Linear(clip_embeddings_dim, cross_attention_dim),
|
| 55 |
+
torch.nn.LayerNorm(cross_attention_dim)
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
def forward(self, image_embeds):
|
| 59 |
+
clip_extra_context_tokens = self.proj(image_embeds)
|
| 60 |
+
return clip_extra_context_tokens
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class MultiIPAdapterImageProjection(torch.nn.Module):
|
| 64 |
+
def __init__(self, IPAdapterImageProjectionLayers):
|
| 65 |
+
super().__init__()
|
| 66 |
+
self.image_projection_layers = torch.nn.ModuleList(IPAdapterImageProjectionLayers)
|
| 67 |
+
|
| 68 |
+
def forward(self, image_embeds: List[torch.FloatTensor]):
|
| 69 |
+
projected_image_embeds = []
|
| 70 |
+
|
| 71 |
+
# currently, we accept `image_embeds` as
|
| 72 |
+
# 1. a tensor (deprecated) with shape [batch_size, embed_dim] or [batch_size, sequence_length, embed_dim]
|
| 73 |
+
# 2. list of `n` tensors where `n` is number of ip-adapters, each tensor can hae shape [batch_size, num_images, embed_dim] or [batch_size, num_images, sequence_length, embed_dim]
|
| 74 |
+
if not isinstance(image_embeds, list):
|
| 75 |
+
image_embeds = [image_embeds.unsqueeze(1)]
|
| 76 |
+
|
| 77 |
+
if len(image_embeds) != len(self.image_projection_layers):
|
| 78 |
+
raise ValueError(
|
| 79 |
+
f"image_embeds must have the same length as image_projection_layers, got {len(image_embeds)} and {len(self.image_projection_layers)}"
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
for image_embed, image_projection_layer in zip(image_embeds, self.image_projection_layers):
|
| 83 |
+
batch_size, num_images = image_embed.shape[0], image_embed.shape[1]
|
| 84 |
+
image_embed = image_embed.reshape((batch_size * num_images,) + image_embed.shape[2:])
|
| 85 |
+
image_embed = image_projection_layer(image_embed)
|
| 86 |
+
# image_embed = image_embed.reshape((batch_size, num_images) + image_embed.shape[1:])
|
| 87 |
+
|
| 88 |
+
projected_image_embeds.append(image_embed)
|
| 89 |
+
|
| 90 |
+
return projected_image_embeds
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class IPAdapter(torch.nn.Module):
|
| 94 |
+
"""IP-Adapter"""
|
| 95 |
+
def __init__(self, unet, image_proj_model, adapter_modules, ckpt_path=None):
|
| 96 |
+
super().__init__()
|
| 97 |
+
self.unet = unet
|
| 98 |
+
self.image_proj = image_proj_model
|
| 99 |
+
self.ip_adapter = adapter_modules
|
| 100 |
+
|
| 101 |
+
if ckpt_path is not None:
|
| 102 |
+
self.load_from_checkpoint(ckpt_path)
|
| 103 |
+
|
| 104 |
+
def forward(self, noisy_latents, timesteps, encoder_hidden_states, image_embeds):
|
| 105 |
+
ip_tokens = self.image_proj(image_embeds)
|
| 106 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states, ip_tokens], dim=1)
|
| 107 |
+
# Predict the noise residual
|
| 108 |
+
noise_pred = self.unet(noisy_latents, timesteps, encoder_hidden_states).sample
|
| 109 |
+
return noise_pred
|
| 110 |
+
|
| 111 |
+
def load_from_checkpoint(self, ckpt_path: str):
|
| 112 |
+
# Calculate original checksums
|
| 113 |
+
orig_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj.parameters()]))
|
| 114 |
+
orig_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.ip_adapter.parameters()]))
|
| 115 |
+
|
| 116 |
+
state_dict = torch.load(ckpt_path, map_location="cpu")
|
| 117 |
+
keys = list(state_dict.keys())
|
| 118 |
+
if keys != ["image_proj", "ip_adapter"]:
|
| 119 |
+
state_dict = revise_state_dict(state_dict)
|
| 120 |
+
|
| 121 |
+
# Load state dict for image_proj_model and adapter_modules
|
| 122 |
+
self.image_proj.load_state_dict(state_dict["image_proj"], strict=True)
|
| 123 |
+
self.ip_adapter.load_state_dict(state_dict["ip_adapter"], strict=True)
|
| 124 |
+
|
| 125 |
+
# Calculate new checksums
|
| 126 |
+
new_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj.parameters()]))
|
| 127 |
+
new_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.ip_adapter.parameters()]))
|
| 128 |
+
|
| 129 |
+
# Verify if the weights have changed
|
| 130 |
+
assert orig_ip_proj_sum != new_ip_proj_sum, "Weights of image_proj_model did not change!"
|
| 131 |
+
assert orig_adapter_sum != new_adapter_sum, "Weights of adapter_modules did not change!"
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class IPAdapterPlus(torch.nn.Module):
|
| 135 |
+
"""IP-Adapter"""
|
| 136 |
+
def __init__(self, unet, image_proj_model, adapter_modules, ckpt_path=None):
|
| 137 |
+
super().__init__()
|
| 138 |
+
self.unet = unet
|
| 139 |
+
self.image_proj = image_proj_model
|
| 140 |
+
self.ip_adapter = adapter_modules
|
| 141 |
+
|
| 142 |
+
if ckpt_path is not None:
|
| 143 |
+
self.load_from_checkpoint(ckpt_path)
|
| 144 |
+
|
| 145 |
+
def forward(self, noisy_latents, timesteps, encoder_hidden_states, image_embeds):
|
| 146 |
+
ip_tokens = self.image_proj(image_embeds)
|
| 147 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states, ip_tokens], dim=1)
|
| 148 |
+
# Predict the noise residual
|
| 149 |
+
noise_pred = self.unet(noisy_latents, timesteps, encoder_hidden_states).sample
|
| 150 |
+
return noise_pred
|
| 151 |
+
|
| 152 |
+
def load_from_checkpoint(self, ckpt_path: str):
|
| 153 |
+
# Calculate original checksums
|
| 154 |
+
orig_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj.parameters()]))
|
| 155 |
+
orig_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.ip_adapter.parameters()]))
|
| 156 |
+
org_unet_sum = []
|
| 157 |
+
for attn_name, attn_proc in self.unet.attn_processors.items():
|
| 158 |
+
if isinstance(attn_proc, (TA_IPAttnProcessor, IPAttnProcessor)):
|
| 159 |
+
org_unet_sum.append(torch.sum(torch.stack([torch.sum(p) for p in attn_proc.parameters()])))
|
| 160 |
+
org_unet_sum = torch.sum(torch.stack(org_unet_sum))
|
| 161 |
+
|
| 162 |
+
state_dict = torch.load(ckpt_path, map_location="cpu")
|
| 163 |
+
keys = list(state_dict.keys())
|
| 164 |
+
if keys != ["image_proj", "ip_adapter"]:
|
| 165 |
+
state_dict = revise_state_dict(state_dict)
|
| 166 |
+
|
| 167 |
+
# Check if 'latents' exists in both the saved state_dict and the current model's state_dict
|
| 168 |
+
strict_load_image_proj_model = True
|
| 169 |
+
if "latents" in state_dict["image_proj"] and "latents" in self.image_proj.state_dict():
|
| 170 |
+
# Check if the shapes are mismatched
|
| 171 |
+
if state_dict["image_proj"]["latents"].shape != self.image_proj.state_dict()["latents"].shape:
|
| 172 |
+
print(f"Shapes of 'image_proj.latents' in checkpoint {ckpt_path} and current model do not match.")
|
| 173 |
+
print("Removing 'latents' from checkpoint and loading the rest of the weights.")
|
| 174 |
+
del state_dict["image_proj"]["latents"]
|
| 175 |
+
strict_load_image_proj_model = False
|
| 176 |
+
|
| 177 |
+
# Load state dict for image_proj_model and adapter_modules
|
| 178 |
+
self.image_proj.load_state_dict(state_dict["image_proj"], strict=strict_load_image_proj_model)
|
| 179 |
+
missing_key, unexpected_key = self.ip_adapter.load_state_dict(state_dict["ip_adapter"], strict=False)
|
| 180 |
+
if len(missing_key) > 0:
|
| 181 |
+
for ms in missing_key:
|
| 182 |
+
if "ln" not in ms:
|
| 183 |
+
raise ValueError(f"Missing key in adapter_modules: {len(missing_key)}")
|
| 184 |
+
if len(unexpected_key) > 0:
|
| 185 |
+
raise ValueError(f"Unexpected key in adapter_modules: {len(unexpected_key)}")
|
| 186 |
+
|
| 187 |
+
# Calculate new checksums
|
| 188 |
+
new_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj.parameters()]))
|
| 189 |
+
new_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.ip_adapter.parameters()]))
|
| 190 |
+
|
| 191 |
+
# Verify if the weights loaded to unet
|
| 192 |
+
unet_sum = []
|
| 193 |
+
for attn_name, attn_proc in self.unet.attn_processors.items():
|
| 194 |
+
if isinstance(attn_proc, (TA_IPAttnProcessor, IPAttnProcessor)):
|
| 195 |
+
unet_sum.append(torch.sum(torch.stack([torch.sum(p) for p in attn_proc.parameters()])))
|
| 196 |
+
unet_sum = torch.sum(torch.stack(unet_sum))
|
| 197 |
+
|
| 198 |
+
assert org_unet_sum != unet_sum, "Weights of adapter_modules in unet did not change!"
|
| 199 |
+
assert (unet_sum - new_adapter_sum < 1e-4), "Weights of adapter_modules did not load to unet!"
|
| 200 |
+
|
| 201 |
+
# Verify if the weights have changed
|
| 202 |
+
assert orig_ip_proj_sum != new_ip_proj_sum, "Weights of image_proj_model did not change!"
|
| 203 |
+
assert orig_adapter_sum != new_adapter_sum, "Weights of adapter_mod`ules did not change!"
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
class IPAdapterXL(IPAdapter):
|
| 207 |
+
"""SDXL"""
|
| 208 |
+
|
| 209 |
+
def forward(self, noisy_latents, timesteps, encoder_hidden_states, unet_added_cond_kwargs, image_embeds):
|
| 210 |
+
ip_tokens = self.image_proj(image_embeds)
|
| 211 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states, ip_tokens], dim=1)
|
| 212 |
+
# Predict the noise residual
|
| 213 |
+
noise_pred = self.unet(noisy_latents, timesteps, encoder_hidden_states, added_cond_kwargs=unet_added_cond_kwargs).sample
|
| 214 |
+
return noise_pred
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class IPAdapterPlusXL(IPAdapterPlus):
|
| 218 |
+
"""IP-Adapter with fine-grained features"""
|
| 219 |
+
|
| 220 |
+
def forward(self, noisy_latents, timesteps, encoder_hidden_states, unet_added_cond_kwargs, image_embeds):
|
| 221 |
+
ip_tokens = self.image_proj(image_embeds)
|
| 222 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states, ip_tokens], dim=1)
|
| 223 |
+
# Predict the noise residual
|
| 224 |
+
noise_pred = self.unet(noisy_latents, timesteps, encoder_hidden_states, added_cond_kwargs=unet_added_cond_kwargs).sample
|
| 225 |
+
return noise_pred
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class IPAdapterFull(IPAdapterPlus):
|
| 229 |
+
"""IP-Adapter with full features"""
|
| 230 |
+
|
| 231 |
+
def init_proj(self):
|
| 232 |
+
image_proj_model = MLPProjModel(
|
| 233 |
+
cross_attention_dim=self.pipe.unet.config.cross_attention_dim,
|
| 234 |
+
clip_embeddings_dim=self.image_encoder.config.hidden_size,
|
| 235 |
+
).to(self.device, dtype=torch.float16)
|
| 236 |
+
return image_proj_model
|