2023-08-29 13:29:05 +00:00
|
|
|
# copied from https://github.com/tencent-ailab/IP-Adapter (Apache License 2.0)
|
|
|
|
# and modified as needed
|
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
from typing import List
|
|
|
|
|
|
|
|
import torch
|
|
|
|
from PIL import Image
|
2023-09-04 23:54:28 +00:00
|
|
|
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
|
2023-08-29 07:51:55 +00:00
|
|
|
|
2023-08-29 13:29:05 +00:00
|
|
|
# FIXME: Getting errors when trying to use PyTorch 2.0 versions of IPAttnProcessor and AttnProcessor
|
|
|
|
# so for now falling back to the default versions
|
|
|
|
# from .utils import is_torch2_available
|
|
|
|
# if is_torch2_available:
|
|
|
|
# from .attention_processor import IPAttnProcessor2_0 as IPAttnProcessor, AttnProcessor2_0 as AttnProcessor
|
|
|
|
# else:
|
|
|
|
# from .attention_processor import IPAttnProcessor, AttnProcessor
|
2023-09-04 23:54:28 +00:00
|
|
|
from .attention_processor import AttnProcessor, IPAttnProcessor
|
2023-08-29 07:51:55 +00:00
|
|
|
from .resampler import Resampler
|
|
|
|
|
|
|
|
|
|
|
|
class ImageProjModel(torch.nn.Module):
|
|
|
|
"""Projection Model"""
|
2023-09-04 23:37:12 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024, clip_extra_context_tokens=4):
|
|
|
|
super().__init__()
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
self.cross_attention_dim = cross_attention_dim
|
|
|
|
self.clip_extra_context_tokens = clip_extra_context_tokens
|
|
|
|
self.proj = torch.nn.Linear(clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim)
|
|
|
|
self.norm = torch.nn.LayerNorm(cross_attention_dim)
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
def forward(self, image_embeds):
|
|
|
|
embeds = image_embeds
|
2023-09-04 23:37:12 +00:00
|
|
|
clip_extra_context_tokens = self.proj(embeds).reshape(
|
|
|
|
-1, self.clip_extra_context_tokens, self.cross_attention_dim
|
|
|
|
)
|
2023-08-29 07:51:55 +00:00
|
|
|
clip_extra_context_tokens = self.norm(clip_extra_context_tokens)
|
|
|
|
return clip_extra_context_tokens
|
|
|
|
|
|
|
|
|
|
|
|
class IPAdapter:
|
|
|
|
def __init__(self, sd_pipe, image_encoder_path, ip_ckpt, device, num_tokens=4):
|
|
|
|
self.device = device
|
|
|
|
self.image_encoder_path = image_encoder_path
|
|
|
|
self.ip_ckpt = ip_ckpt
|
|
|
|
self.num_tokens = num_tokens
|
2023-08-29 13:29:05 +00:00
|
|
|
|
|
|
|
# FIXME:
|
|
|
|
# InvokeAI StableDiffusionPipeline has a to() method that isn't meant to be used
|
|
|
|
# so for now assuming that pipeline is already on the correct device
|
|
|
|
# self.pipe = sd_pipe.to(self.device)
|
|
|
|
self.pipe = sd_pipe
|
2023-08-29 07:51:55 +00:00
|
|
|
self.set_ip_adapter()
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
# load image encoder
|
2023-09-04 23:37:12 +00:00
|
|
|
self.image_encoder = CLIPVisionModelWithProjection.from_pretrained(self.image_encoder_path).to(
|
|
|
|
self.device, dtype=torch.float16
|
|
|
|
)
|
2023-08-29 07:51:55 +00:00
|
|
|
self.clip_image_processor = CLIPImageProcessor()
|
|
|
|
# image proj model
|
|
|
|
self.image_proj_model = self.init_proj()
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
self.load_ip_adapter()
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
def init_proj(self):
|
|
|
|
image_proj_model = ImageProjModel(
|
|
|
|
cross_attention_dim=self.pipe.unet.config.cross_attention_dim,
|
|
|
|
clip_embeddings_dim=self.image_encoder.config.projection_dim,
|
|
|
|
clip_extra_context_tokens=self.num_tokens,
|
|
|
|
).to(self.device, dtype=torch.float16)
|
|
|
|
return image_proj_model
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
def set_ip_adapter(self):
|
|
|
|
unet = self.pipe.unet
|
|
|
|
attn_procs = {}
|
2023-08-29 13:29:05 +00:00
|
|
|
print("Original UNet Attn Processors count:", len(unet.attn_processors))
|
|
|
|
print(unet.attn_processors.keys())
|
2023-08-29 07:51:55 +00:00
|
|
|
for name in unet.attn_processors.keys():
|
|
|
|
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
|
|
|
if name.startswith("mid_block"):
|
|
|
|
hidden_size = unet.config.block_out_channels[-1]
|
|
|
|
elif name.startswith("up_blocks"):
|
|
|
|
block_id = int(name[len("up_blocks.")])
|
|
|
|
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
|
|
|
elif name.startswith("down_blocks"):
|
|
|
|
block_id = int(name[len("down_blocks.")])
|
|
|
|
hidden_size = unet.config.block_out_channels[block_id]
|
|
|
|
if cross_attention_dim is None:
|
|
|
|
attn_procs[name] = AttnProcessor()
|
|
|
|
else:
|
2023-08-29 13:29:05 +00:00
|
|
|
print("swapping in IPAttnProcessor for", name)
|
2023-09-04 23:37:12 +00:00
|
|
|
attn_procs[name] = IPAttnProcessor(
|
|
|
|
hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, scale=1.0
|
|
|
|
).to(self.device, dtype=torch.float16)
|
2023-08-29 07:51:55 +00:00
|
|
|
unet.set_attn_processor(attn_procs)
|
2023-08-29 13:29:05 +00:00
|
|
|
print("Modified UNet Attn Processors count:", len(unet.attn_processors))
|
|
|
|
print(unet.attn_processors.keys())
|
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
def load_ip_adapter(self):
|
|
|
|
state_dict = torch.load(self.ip_ckpt, map_location="cpu")
|
|
|
|
self.image_proj_model.load_state_dict(state_dict["image_proj"])
|
|
|
|
ip_layers = torch.nn.ModuleList(self.pipe.unet.attn_processors.values())
|
|
|
|
ip_layers.load_state_dict(state_dict["ip_adapter"])
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
@torch.inference_mode()
|
|
|
|
def get_image_embeds(self, pil_image):
|
|
|
|
if isinstance(pil_image, Image.Image):
|
|
|
|
pil_image = [pil_image]
|
|
|
|
clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values
|
|
|
|
clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16)).image_embeds
|
|
|
|
image_prompt_embeds = self.image_proj_model(clip_image_embeds)
|
|
|
|
uncond_image_prompt_embeds = self.image_proj_model(torch.zeros_like(clip_image_embeds))
|
|
|
|
return image_prompt_embeds, uncond_image_prompt_embeds
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
def set_scale(self, scale):
|
|
|
|
for attn_processor in self.pipe.unet.attn_processors.values():
|
|
|
|
if isinstance(attn_processor, IPAttnProcessor):
|
|
|
|
attn_processor.scale = scale
|
2023-08-29 13:29:05 +00:00
|
|
|
|
|
|
|
# IPAdapter.generate() method is not used for InvokeAI
|
|
|
|
# left here for reference
|
2023-08-29 07:51:55 +00:00
|
|
|
def generate(
|
|
|
|
self,
|
|
|
|
pil_image,
|
|
|
|
prompt=None,
|
|
|
|
negative_prompt=None,
|
|
|
|
scale=1.0,
|
|
|
|
num_samples=4,
|
|
|
|
seed=-1,
|
|
|
|
guidance_scale=7.5,
|
|
|
|
num_inference_steps=30,
|
|
|
|
**kwargs,
|
|
|
|
):
|
|
|
|
self.set_scale(scale)
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
if isinstance(pil_image, Image.Image):
|
|
|
|
num_prompts = 1
|
|
|
|
else:
|
|
|
|
num_prompts = len(pil_image)
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
if prompt is None:
|
|
|
|
prompt = "best quality, high quality"
|
|
|
|
if negative_prompt is None:
|
|
|
|
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
if not isinstance(prompt, List):
|
|
|
|
prompt = [prompt] * num_prompts
|
|
|
|
if not isinstance(negative_prompt, List):
|
|
|
|
negative_prompt = [negative_prompt] * num_prompts
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(pil_image)
|
|
|
|
bs_embed, seq_len, _ = image_prompt_embeds.shape
|
|
|
|
image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
|
|
|
|
image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
|
|
|
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
|
|
|
|
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
|
|
|
|
|
|
|
with torch.inference_mode():
|
|
|
|
prompt_embeds = self.pipe._encode_prompt(
|
2023-09-04 23:37:12 +00:00
|
|
|
prompt,
|
|
|
|
device=self.device,
|
|
|
|
num_images_per_prompt=num_samples,
|
|
|
|
do_classifier_free_guidance=True,
|
|
|
|
negative_prompt=negative_prompt,
|
|
|
|
)
|
2023-08-29 07:51:55 +00:00
|
|
|
negative_prompt_embeds_, prompt_embeds_ = prompt_embeds.chunk(2)
|
|
|
|
prompt_embeds = torch.cat([prompt_embeds_, image_prompt_embeds], dim=1)
|
|
|
|
negative_prompt_embeds = torch.cat([negative_prompt_embeds_, uncond_image_prompt_embeds], dim=1)
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
generator = torch.Generator(self.device).manual_seed(seed) if seed is not None else None
|
|
|
|
images = self.pipe(
|
|
|
|
prompt_embeds=prompt_embeds,
|
|
|
|
negative_prompt_embeds=negative_prompt_embeds,
|
|
|
|
guidance_scale=guidance_scale,
|
|
|
|
num_inference_steps=num_inference_steps,
|
|
|
|
generator=generator,
|
|
|
|
**kwargs,
|
|
|
|
).images
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
return images
|
2023-08-29 13:29:05 +00:00
|
|
|
|
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
class IPAdapterXL(IPAdapter):
|
|
|
|
"""SDXL"""
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
def generate(
|
|
|
|
self,
|
|
|
|
pil_image,
|
|
|
|
prompt=None,
|
|
|
|
negative_prompt=None,
|
|
|
|
scale=1.0,
|
|
|
|
num_samples=4,
|
|
|
|
seed=-1,
|
|
|
|
num_inference_steps=30,
|
|
|
|
**kwargs,
|
|
|
|
):
|
|
|
|
self.set_scale(scale)
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
if isinstance(pil_image, Image.Image):
|
|
|
|
num_prompts = 1
|
|
|
|
else:
|
|
|
|
num_prompts = len(pil_image)
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
if prompt is None:
|
|
|
|
prompt = "best quality, high quality"
|
|
|
|
if negative_prompt is None:
|
|
|
|
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
if not isinstance(prompt, List):
|
|
|
|
prompt = [prompt] * num_prompts
|
|
|
|
if not isinstance(negative_prompt, List):
|
|
|
|
negative_prompt = [negative_prompt] * num_prompts
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(pil_image)
|
|
|
|
bs_embed, seq_len, _ = image_prompt_embeds.shape
|
|
|
|
image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
|
|
|
|
image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
|
|
|
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
|
|
|
|
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
|
|
|
|
|
|
|
with torch.inference_mode():
|
2023-09-04 23:37:12 +00:00
|
|
|
(
|
|
|
|
prompt_embeds,
|
|
|
|
negative_prompt_embeds,
|
|
|
|
pooled_prompt_embeds,
|
|
|
|
negative_pooled_prompt_embeds,
|
|
|
|
) = self.pipe.encode_prompt(
|
|
|
|
prompt,
|
|
|
|
num_images_per_prompt=num_samples,
|
|
|
|
do_classifier_free_guidance=True,
|
|
|
|
negative_prompt=negative_prompt,
|
|
|
|
)
|
2023-08-29 07:51:55 +00:00
|
|
|
prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1)
|
|
|
|
negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
generator = torch.Generator(self.device).manual_seed(seed) if seed is not None else None
|
|
|
|
images = self.pipe(
|
|
|
|
prompt_embeds=prompt_embeds,
|
|
|
|
negative_prompt_embeds=negative_prompt_embeds,
|
|
|
|
pooled_prompt_embeds=pooled_prompt_embeds,
|
|
|
|
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
|
|
|
num_inference_steps=num_inference_steps,
|
|
|
|
generator=generator,
|
|
|
|
**kwargs,
|
|
|
|
).images
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
return images
|
2023-08-29 13:29:05 +00:00
|
|
|
|
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
class IPAdapterPlus(IPAdapter):
|
|
|
|
"""IP-Adapter with fine-grained features"""
|
|
|
|
|
|
|
|
def init_proj(self):
|
|
|
|
image_proj_model = Resampler(
|
|
|
|
dim=self.pipe.unet.config.cross_attention_dim,
|
|
|
|
depth=4,
|
|
|
|
dim_head=64,
|
|
|
|
heads=12,
|
|
|
|
num_queries=self.num_tokens,
|
|
|
|
embedding_dim=self.image_encoder.config.hidden_size,
|
|
|
|
output_dim=self.pipe.unet.config.cross_attention_dim,
|
2023-09-04 23:37:12 +00:00
|
|
|
ff_mult=4,
|
2023-08-29 07:51:55 +00:00
|
|
|
).to(self.device, dtype=torch.float16)
|
|
|
|
return image_proj_model
|
2023-08-29 13:29:05 +00:00
|
|
|
|
2023-08-29 07:51:55 +00:00
|
|
|
@torch.inference_mode()
|
|
|
|
def get_image_embeds(self, pil_image):
|
|
|
|
if isinstance(pil_image, Image.Image):
|
|
|
|
pil_image = [pil_image]
|
|
|
|
clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values
|
|
|
|
clip_image = clip_image.to(self.device, dtype=torch.float16)
|
|
|
|
clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2]
|
|
|
|
image_prompt_embeds = self.image_proj_model(clip_image_embeds)
|
2023-09-04 23:37:12 +00:00
|
|
|
uncond_clip_image_embeds = self.image_encoder(
|
|
|
|
torch.zeros_like(clip_image), output_hidden_states=True
|
|
|
|
).hidden_states[-2]
|
2023-08-29 07:51:55 +00:00
|
|
|
uncond_image_prompt_embeds = self.image_proj_model(uncond_clip_image_embeds)
|
2023-08-29 13:29:05 +00:00
|
|
|
return image_prompt_embeds, uncond_image_prompt_embeds
|