CoolFace
Apppublic

acmyu/KeyframesAI

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
test.py207 linesDownload Raw Back to root
1import glob
2import os
3import torch
4from torch import nn
5from PIL import Image
6import numpy as np
7from diffusers import UniPCMultistepScheduler
8from src.models.stage2_inpaint_unet_2d_condition import Stage2_InapintUNet2DConditionModel
9
10from torchvision import transforms
11from diffusers.models.controlnet import ControlNetConditioningEmbedding
12from transformers import CLIPImageProcessor
13from transformers import Dinov2Model
14from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel,ControlNetModel,DDIMScheduler
15from src.pipelines.PCDMs_pipeline import PCDMsPipeline
16from single_extract_pose import inference_pose
17
18
19class ImageProjModel(torch.nn.Module):
20    """SD model with image prompt"""
21    def __init__(self, in_dim, hidden_dim, out_dim, dropout = 0.):
22        super().__init__()
23
24        self.net = nn.Sequential(
25            nn.Linear(in_dim, hidden_dim),
26            nn.GELU(),
27            nn.Dropout(dropout),
28            nn.LayerNorm(hidden_dim),
29            nn.Linear(hidden_dim, out_dim),
30            nn.Dropout(dropout)
31        )
32
33    def forward(self, x):  
34        return self.net(x)
35        
36class SDModel(torch.nn.Module):
37    """SD model with image prompt"""
38    def __init__(self, unet) -> None:
39        super().__init__()
40        self.image_proj_model = ImageProjModel(in_dim=1536, hidden_dim=768, out_dim=1024).to(device).to(dtype=torch.float16)
41        self.unet = unet
42        self.pose_proj = ControlNetConditioningEmbedding(
43            conditioning_embedding_channels=320,
44            block_out_channels=(16, 32, 96, 256),
45            conditioning_channels=3).to(device).to(dtype=torch.float16)
46
47
48def image_grid(imgs, rows, cols):
49    assert len(imgs) == rows * cols
50    w, h = imgs[0].size
51    print(w, h)
52    grid = Image.new("RGB", size=(cols * w, rows * h))
53    grid_w, grid_h = grid.size
54
55    for i, img in enumerate(imgs):
56        grid.paste(img, box=(i % cols * w, i // cols * h))
57    return grid
58
59def load_mydict(model_ckpt_path):
60    model_sd = torch.load(model_ckpt_path, map_location="cpu")["module"]
61
62    image_proj_model_dict = {}
63    pose_proj_dict = {}
64    unet_dict = {}
65    for k in model_sd.keys():
66        if k.startswith("pose_proj"):
67            pose_proj_dict[k.replace("pose_proj.", "")] = model_sd[k]
68
69        elif k.startswith("image_proj_model"):
70            image_proj_model_dict[k.replace("image_proj_model.", "")] = model_sd[k]
71
72
73        elif k.startswith("unet"):
74            unet_dict[k.replace("unet.", "")] = model_sd[k]
75        else:
76            print(k)
77    return image_proj_model_dict, pose_proj_dict, unet_dict
78
79
80        
81device = "cuda"
82pretrained_model_name_or_path ="stabilityai/stable-diffusion-2-1-base"
83image_encoder_path = "facebook/dinov2-giant"
84#model_ckpt_path = "./pcdms_ckpt.pt"   # ckpt path
85model_ckpt_path = 'fine_tuned_pcdms.pt'
86
87
88clip_image_processor = CLIPImageProcessor()
89img_transform = transforms.Compose([
90    transforms.ToTensor(),
91    transforms.Normalize([0.5], [0.5]),
92])
93
94generator = torch.Generator(device=device).manual_seed(42)
95unet = Stage2_InapintUNet2DConditionModel.from_pretrained(pretrained_model_name_or_path, torch_dtype=torch.float16,subfolder="unet",in_channels=9, low_cpu_mem_usage=False, ignore_mismatched_sizes=True).to(device)
96vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path,subfolder="vae").to(device, dtype=torch.float16)
97image_encoder = Dinov2Model.from_pretrained(image_encoder_path).to(device, dtype=torch.float16)
98noise_scheduler = DDIMScheduler(
99    num_train_timesteps=1000,
100    beta_start=0.00085,
101    beta_end=0.012,
102    beta_schedule="scaled_linear",
103    clip_sample=False,
104    set_alpha_to_one=False,
105    steps_offset=1,
106)
107
108image_proj_model = ImageProjModel(in_dim=1536, hidden_dim=768, out_dim=1024).to(device).to(dtype=torch.float16)
109pose_proj_model = ControlNetConditioningEmbedding(
110    conditioning_embedding_channels=320,
111    block_out_channels=(16, 32, 96, 256),
112    conditioning_channels=3).to(device).to(dtype=torch.float16)
113
114"""
115# load weight
116image_proj_model_dict, pose_proj_dict, unet_dict = load_mydict(model_ckpt_path)
117image_proj_model.load_state_dict(image_proj_model_dict)
118pose_proj_model.load_state_dict(pose_proj_dict)
119unet.load_state_dict(unet_dict)
120"""
121
122# load models
123model_sd = torch.load(model_ckpt_path, map_location="cpu")
124image_proj_model.load_state_dict(model_sd.image_proj_model.state_dict())
125pose_proj_model.load_state_dict(model_sd.pose_proj.state_dict())
126unet.load_state_dict(model_sd.unet.state_dict())
127
128pipe = PCDMsPipeline.from_pretrained(pretrained_model_name_or_path, unet=unet,  torch_dtype=torch.float16, scheduler=noise_scheduler,feature_extractor=None,safety_checker=None).to(device)
129
130print('====================== model load finish ===================')
131
132
133
134
135
136
137num_samples = 1
138image_size = (512, 512)
139s_img_path = 'imgs/sm.png' # input image 1
140target_pose_img = 'imgs/pose.png' # input image 2
141
142
143s_img = Image.open(s_img_path).convert("RGB").resize(image_size, Image.BICUBIC)
144black_image = Image.new("RGB", s_img.size, (0, 0, 0)).resize(image_size, Image.BICUBIC)
145
146s_img_t_mask = Image.new("RGB", (s_img.width * 2, s_img.height))
147s_img_t_mask.paste(s_img, (0, 0))
148s_img_t_mask.paste(black_image, (s_img.width, 0))
149
150s_pose = inference_pose(s_img_path, image_size=(image_size[1], image_size[0])).resize(image_size, Image.BICUBIC)
151print('source image width: {}, height: {}'.format(s_pose.width, s_pose.height))
152t_pose = Image.open(target_pose_img).convert("RGB").resize((image_size), Image.BICUBIC)
153
154st_pose = Image.new("RGB", (s_pose.width * 2, s_pose.height))
155st_pose.paste(s_pose, (0, 0))
156st_pose.paste(t_pose, (s_pose.width, 0))
157
158
159clip_s_img = clip_image_processor(images=s_img, return_tensors="pt").pixel_values
160vae_image = torch.unsqueeze(img_transform(s_img_t_mask), 0)
161cond_st_pose = torch.unsqueeze(img_transform(st_pose), 0)
162
163mask1 = torch.ones((1, 1, int(image_size[0] / 8), int(image_size[1] / 8))).to(device, dtype=torch.float16)
164mask0 = torch.zeros((1, 1, int(image_size[0] / 8), int(image_size[1] / 8))).to(device, dtype=torch.float16)
165mask = torch.cat([mask1, mask0], dim=3)
166
167
168with torch.inference_mode():
169    cond_pose = pose_proj_model(cond_st_pose.to(dtype=torch.float16, device=device))
170    simg_mask_latents = pipe.vae.encode(vae_image.to(device, dtype=torch.float16)).latent_dist.sample()
171    simg_mask_latents = simg_mask_latents * 0.18215
172
173    images_embeds = image_encoder(clip_s_img.to(device, dtype=torch.float16)).last_hidden_state
174    image_prompt_embeds = image_proj_model(images_embeds)
175    uncond_image_prompt_embeds = image_proj_model(torch.zeros_like(images_embeds))
176
177bs_embed, seq_len, _ = image_prompt_embeds.shape
178image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
179image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
180uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
181uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
182
183output, _ = pipe(
184    simg_mask_latents= simg_mask_latents,
185    mask = mask,
186    cond_pose = cond_pose,
187    prompt_embeds=image_prompt_embeds,
188    negative_prompt_embeds=uncond_image_prompt_embeds,
189    height=image_size[1],
190    width=image_size[0]*2,
191    num_images_per_prompt=num_samples,
192    guidance_scale=2.0,
193    generator=generator,
194    num_inference_steps=50,
195)
196
197output = output.images[-1]
198
199save_output = []
200result = output.crop((image_size[0], 0, image_size[0] * 2, image_size[1]))
201save_output.append(result.resize((352, 512), Image.BICUBIC))
202save_output.insert(0, t_pose.resize((352, 512), Image.BICUBIC))
203save_output.insert(0, s_img.resize((352, 512), Image.BICUBIC))
204grid = image_grid(save_output, 1, 3)
205grid.save("out.png")
206
207