SPF / newSPF /models /spf_module.py
connorxian's picture
Upload 157 files
b1541cc verified
Raw History Blame Contribute Delete
13.2 kB
import os
import random
import argparse
from pathlib import Path
import json
import itertools
import time
import sys
from typing import Any, Optional, Tuple, Union
sys.path.append( os.path.dirname(os.path.abspath(__file__) ) )
import cv2
import numpy as np
import torch
import torch.nn.functional as F
import torch.nn as nn
import matplotlib.cm as cm
from torchvision import transforms
from PIL import Image
from transformers import CLIPImageProcessor
from accelerate import Accelerator
from accelerate.logging import get_logger
from accelerate.utils import ProjectConfiguration
from diffusers import AutoencoderKL, DDPMScheduler
from diffusers.models.lora import LoRALinearLayer
from transformers import CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
from diffusers.models.attention import Attention
from attn_processor import NormalJointAttnProcessor2_0
from diffusers.models.attention_processor import JointAttnProcessor2_0
def visual_attn_map(vis_map, vis_token_index):
vis_map_list = []
if len(vis_map.shape) == 4:
Resolution_vis = int(vis_map.shape[-2]**0.5)
vis = vis_map[1].sum(dim=0).transpose(0,1).view(-1,Resolution_vis, Resolution_vis)[vis_token_index].cpu().numpy()
vis = ((vis-vis.min())/(vis.max() - vis.min()) *255).astype(np.uint8)
colormap = cm.get_cmap('rainbow')
rainbow_img_array = colormap(vis / 255.0)
rainbow_img_array = (rainbow_img_array[:, :, :3] * 255).astype(np.uint8)
return Image.fromarray(rainbow_img_array).resize((512,512)).convert("RGB")
def visual_rgb_img(img):
rgb_img = img.detach().cpu().numpy()
if len(img.shape) == 3:
rgb_img = Image.fromarray(((rgb_img-rgb_img.min())/(rgb_img.max() - rgb_img.min()) *255).astype(np.uint8))
elif len(img.shape) == 2:
rgb_img = ((rgb_img-rgb_img.min())/(rgb_img.max() - rgb_img.min()) *255).astype(np.uint8)
colormap = cm.get_cmap('rainbow')
rainbow_img_array = colormap(rgb_img / 255.0)
rainbow_img_array = (rainbow_img_array[:, :, :3] * 255).astype(np.uint8)
rgb_img = Image.fromarray(rainbow_img_array).resize((512,512)).convert("RGB")
return rgb_img
class TransformerProjmodel(Attention):
def __init__(self, query_dim = None):
super().__init__(query_dim = query_dim)
class TextProjModel(torch.nn.Module):
"""Projection Model"""
def __init__(self, cross_attention_dim=768, clip_embeddings_dim=768, clip_extra_context_tokens=4):
super().__init__()
self.generator = None
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)
def forward(self, image_embeds):
embeds = image_embeds
clip_extra_context_tokens = self.proj(embeds).reshape(
-1, self.clip_extra_context_tokens, self.cross_attention_dim
)
clip_extra_context_tokens = self.norm(clip_extra_context_tokens)
return clip_extra_context_tokens
class MLPProjModel(torch.nn.Module):
"""SD model with image prompt"""
def __init__(self, cross_attention_dim=768, clip_embeddings_dim=768):
super().__init__()
self.proj = torch.nn.Sequential(
torch.nn.Linear(clip_embeddings_dim, clip_embeddings_dim),
torch.nn.GELU(),
torch.nn.Linear(clip_embeddings_dim, cross_attention_dim),
torch.nn.LayerNorm(cross_attention_dim)
)
def forward(self, image_embeds):
clip_extra_context_tokens = self.proj(image_embeds)
return clip_extra_context_tokens
class SPF_Adapter(torch.nn.Module):
def __init__(self, transformer, ckpt_path=None, pool_token = False, device = "cuda"):
super().__init__()
self.device = device
self.transformer = transformer
class TPPortrait_Adapter(torch.nn.Module):
"""IP-Adapter"""
def __init__(self, unet, cross_attention_dim=768, ckpt_path=None, pool_token = False, device = "cuda"):
super().__init__()
self.device = device
self.unet = unet
# self.image_proj_model = image_proj_model
if pool_token:
self.ShapeText_Projection = TextProjModel(cross_attention_dim, cross_attention_dim)
else:
self.ShapeText_Projection = MLPProjModel(cross_attention_dim, cross_attention_dim)
self.adapter_modules = torch.nn.ModuleList(self.unet.attn_processors.values())
if ckpt_path is not None:
self.load_from_checkpoint(ckpt_path)
def forward(self,
noisy_latents,
timesteps,
encoder_hidden_states,
text_shape_embeds,
down_block_res_samples=None,
mid_block_res_sample=None,
):
text_shape_tokens = self.ShapeText_Projection(text_shape_embeds)
encoder_hidden_states = torch.cat([encoder_hidden_states, text_shape_tokens], dim=1)
# Predict the noise residual
noise_pred = self.unet(
noisy_latents,
timesteps,
encoder_hidden_states,
down_block_additional_residuals=[sample.to(dtype=weight_dtype) for sample in down_block_res_samples] if down_block_res_samples is not None else None,
mid_block_additional_residual=mid_block_res_sample.to(dtype=weight_dtype) if mid_block_res_sample is not None else None,
return_dict = False,
)[0]
return noise_pred
def load_from_checkpoint(self, ckpt_path: str):
# Calculate original checksums
orig_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.ShapeText_Projection.parameters()]))
orig_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
state_dict = torch.load(ckpt_path, map_location="cpu")
# Load state dict for image_proj_model and adapter_modules
self.ShapeText_Projection.load_state_dict(state_dict["ShapeText_Projection"], strict=True)
self.adapter_modules.load_state_dict(state_dict["TP_model"], strict=True)
# Calculate new checksums
new_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.ShapeText_Projection.parameters()]))
new_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
# Verify if the weights have changed
assert orig_ip_proj_sum != new_ip_proj_sum, "Weights of image_proj_model did not change!"
assert orig_adapter_sum != new_adapter_sum, "Weights of adapter_modules did not change!"
print(f"Successfully loaded weights from checkpoint {ckpt_path}")
def finegrained_encoder_setting(self, text_encoder, tokenizer):
self.TP_Encoder = text_encoder.to(self.device)
self.TP_tokenizer = tokenizer
def generate(
self,
pipe,
faceid_embeds=None,
global_prompt=None,
finegrained_prompt=None,
negative_prompt=None,
scale=1.0,
num_samples=1,
all_tokens=True,
seed=None,
generator=None,
guidance_scale=7.5,
num_inference_steps=30,
s_scale=1.0,
**kwargs,
):
with torch.inference_mode():
global_prompt_embeds_, global_negative_prompt_embeds_ = pipe.encode_prompt(
global_prompt,
device=pipe.device,
num_images_per_prompt=num_samples,
do_classifier_free_guidance=True,
negative_prompt=negative_prompt,
)
assert (hasattr(self, "TP_Encoder") and hasattr(self, "TP_tokenizer")), "Enocder not exisit!"
if all_tokens:
finegrained_embeds_ = self.TP_Encoder(self.TP_tokenizer(finegrained_prompt, padding="max_length", truncation=True, return_tensors="pt").input_ids.to(pipe.device), output_hidden_states=True)[0]
finegrained_negative_prompt_embeds_ = self.TP_Encoder(self.TP_tokenizer("", padding="max_length", truncation=True, return_tensors="pt").input_ids.to(pipe.device), output_hidden_states=True)[0]
else:
finegrained_embeds_ = self.TP_Encoder.encode_text(self.TP_tokenizer(finegrained_prompt))[0]
finegrained_negative_prompt_embeds_ = self.TP_Encoder.encode_text(self.TP_tokenizer(""))[0]
finegrained_embeds_ = self.ShapeText_Projection(finegrained_embeds_.to(pipe.device, global_prompt_embeds_.dtype))
finegrained_negative_prompt_embeds_ = self.ShapeText_Projection(finegrained_negative_prompt_embeds_.to(pipe.device, global_prompt_embeds_.dtype))
prompt_embeds = torch.cat([global_prompt_embeds_, finegrained_embeds_], dim=1)
negative_prompt_embeds = torch.cat([global_negative_prompt_embeds_, finegrained_negative_prompt_embeds_], dim=1)
images = pipe(
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_prompt_embeds,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
generator=generator,
# num_images_per_prompt = num_samples,
**kwargs,
)
return images
def inverse(
self,
pipe,
latents,
global_prompt=None,
finegrained_prompt=None,
negative_prompt=None,
scale=1.0,
num_samples=1,
all_tokens=True,
seed=None,
generator=None,
guidance_scale=7.5,
num_inference_steps=30,
s_scale=1.0,
**kwargs,
):
with torch.inference_mode():
global_prompt_embeds_, global_negative_prompt_embeds_ = pipe.encode_prompt(
global_prompt,
device=pipe.device,
num_images_per_prompt=num_samples,
do_classifier_free_guidance=True,
negative_prompt=negative_prompt,
)
assert (hasattr(self, "TP_Encoder") and hasattr(self, "TP_tokenizer")), "Enocder not exisit!"
if all_tokens:
finegrained_embeds_ = self.TP_Encoder(self.TP_tokenizer(finegrained_prompt, padding="max_length", truncation=True, return_tensors="pt").input_ids.to(pipe.device), output_hidden_states=True)[0]
finegrained_negative_prompt_embeds_ = self.TP_Encoder(self.TP_tokenizer("", padding="max_length", truncation=True, return_tensors="pt").input_ids.to(pipe.device), output_hidden_states=True)[0]
else:
finegrained_embeds_ = self.TP_Encoder.encode_text(self.TP_tokenizer(finegrained_prompt))[0]
finegrained_negative_prompt_embeds_ = self.TP_Encoder.encode_text(self.TP_tokenizer(""))[0]
finegrained_embeds_ = self.ShapeText_Projection(finegrained_embeds_.to(pipe.device, global_prompt_embeds_.dtype))
finegrained_negative_prompt_embeds_ = self.ShapeText_Projection(finegrained_negative_prompt_embeds_.to(pipe.device, global_prompt_embeds_.dtype))
prompt_embeds = torch.cat([global_prompt_embeds_, finegrained_embeds_], dim=1)
negative_prompt_embeds = torch.cat([global_negative_prompt_embeds_, finegrained_negative_prompt_embeds_], dim=1)
inv_latents, _ = pipe(
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_prompt_embeds,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
generator=generator,
output_type='latent',
latents = latents,
return_dict=False,
**kwargs,
)
return inv_latents
def SPF_set_attnprocessor(transformer):
# hidden_size = transformer.config.attention_head_dim * transformer.config.num_attention_heads
attn_procs = {}
# transformers_sd = transformer.state_dict()
for name in transformer.attn_processors.keys():
layer_name = name.split(".processor")[0]
if 1:
# weights = {
# "to_k_ip.weight": transformers_sd[layer_name + ".to_k.weight"],
# "to_k_ip.bias": transformers_sd[layer_name + ".to_k.bias"],
# "to_v_ip.weight": transformers_sd[layer_name + ".to_v.weight"],
# "to_v_ip.bias": transformers_sd[layer_name + ".to_v.bias"],
# "norm_added_k.weight": transformers_sd[layer_name + ".norm_k.weight"],
# "norm_added_k.bias": transformers_sd[layer_name + ".norm_k.bias"],
# }
attn_procs[name] = NormalJointAttnProcessor2_0()
# attn_procs[name].load_state_dict(weights, strict=False)
else:
attn_procs[name] = JointAttnProcessor2_0()
transformer.set_attn_processor(attn_procs)
# adapter_modules = torch.nn.ModuleList(components.transformer.attn_processors.values())