Spaces:
Runtime error
Runtime error
mayuema
commited on
Commit
•
0754e7d
1
Parent(s):
d2dd1cd
first release
Browse files- FollowYourPose +0 -1
- FollowYourPose/.gitignore +51 -0
- FollowYourPose/followyourpose/data/hdvila.py +245 -0
- FollowYourPose/followyourpose/models/attention.py +375 -0
- FollowYourPose/followyourpose/models/resnet.py +209 -0
- FollowYourPose/followyourpose/models/unet.py +571 -0
- FollowYourPose/followyourpose/models/unet_blocks.py +631 -0
- FollowYourPose/followyourpose/pipelines/pipeline_followyourpose.py +442 -0
- FollowYourPose/followyourpose/util.py +84 -0
- FollowYourPose/test_followyourpose.py +189 -0
FollowYourPose
DELETED
@@ -1 +0,0 @@
|
|
1 |
-
Subproject commit 40a333f7f1e3940903916c419b725a4a17f348a1
|
|
|
|
FollowYourPose/.gitignore
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
/checkpoints
|
3 |
+
|
4 |
+
/data
|
5 |
+
|
6 |
+
/sim_matrix
|
7 |
+
|
8 |
+
/figs
|
9 |
+
|
10 |
+
/log
|
11 |
+
|
12 |
+
|
13 |
+
*.log
|
14 |
+
|
15 |
+
*.sh
|
16 |
+
|
17 |
+
*.pth
|
18 |
+
|
19 |
+
*.jpg
|
20 |
+
|
21 |
+
*.og
|
22 |
+
|
23 |
+
/logs
|
24 |
+
|
25 |
+
/stable_diffusion.egg-info
|
26 |
+
|
27 |
+
/__pycache__
|
28 |
+
|
29 |
+
/outputs
|
30 |
+
|
31 |
+
*.pyc
|
32 |
+
|
33 |
+
/models
|
34 |
+
|
35 |
+
*.ckpt
|
36 |
+
|
37 |
+
/src
|
38 |
+
|
39 |
+
/newsd_weight
|
40 |
+
|
41 |
+
*.yaml
|
42 |
+
|
43 |
+
*.png
|
44 |
+
|
45 |
+
*.yaml
|
46 |
+
|
47 |
+
*.txt
|
48 |
+
|
49 |
+
/data
|
50 |
+
|
51 |
+
/others
|
FollowYourPose/followyourpose/data/hdvila.py
ADDED
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# import os
|
2 |
+
# import random
|
3 |
+
# from abc import abstractmethod
|
4 |
+
# import math
|
5 |
+
# import pandas as pd
|
6 |
+
# import av
|
7 |
+
# import cv2
|
8 |
+
# import decord
|
9 |
+
# import numpy as np
|
10 |
+
# import torch
|
11 |
+
# from PIL import Image
|
12 |
+
# from torch.utils.data import Dataset
|
13 |
+
# from torchvision import transforms
|
14 |
+
# from decord import VideoReader, cpu
|
15 |
+
# import torchvision.transforms._transforms_video as transforms_video
|
16 |
+
# from torchvision.transforms.functional import to_tensor
|
17 |
+
# from collections import OrderedDict
|
18 |
+
# import time
|
19 |
+
# import csv
|
20 |
+
|
21 |
+
# class HDVilaDataset(Dataset):
|
22 |
+
# """
|
23 |
+
# HDVila Dataset.
|
24 |
+
# Assumes webvid data is structured as follows.
|
25 |
+
# HDVila/
|
26 |
+
# part_N/ # 0-10
|
27 |
+
# video_clips/ ($page_dir)
|
28 |
+
# 1.mp4 (videoid.mp4)
|
29 |
+
# ...
|
30 |
+
# 5000.mp4
|
31 |
+
# ...
|
32 |
+
# """
|
33 |
+
# def __init__(self,
|
34 |
+
# video_path,
|
35 |
+
# width=512,
|
36 |
+
# height=512,
|
37 |
+
# n_sample_frames=8,
|
38 |
+
# dataset_set="train",
|
39 |
+
# prompt=None,
|
40 |
+
# sample_frame_rate=2,
|
41 |
+
# sample_start_idx=0,
|
42 |
+
# accelerator=None,
|
43 |
+
# ):
|
44 |
+
|
45 |
+
# try:
|
46 |
+
# host_gpu_num = accelerator.num_processes
|
47 |
+
# host_num = 1
|
48 |
+
# all_rank = host_gpu_num * host_num
|
49 |
+
# global_rank = accelerator.local_process_index
|
50 |
+
# except:
|
51 |
+
# pass
|
52 |
+
# print('dataset rank:', global_rank, ' / ',all_rank, ' ')
|
53 |
+
|
54 |
+
# self.data_dir = '/apdcephfs_cq3/share_1290939/0_public_datasets/hd-vila-100m'
|
55 |
+
# if dataset_set=='train':
|
56 |
+
# self.text_name = 'caption_rm2048_train.csv'
|
57 |
+
# else:
|
58 |
+
# self.text_name = 'caption_2048_val_new.csv'
|
59 |
+
# self.meta_path = os.path.join(self.data_dir, self.text_name)
|
60 |
+
# # text_name = 'caption_2048_val_new.csv'
|
61 |
+
|
62 |
+
# spatial_transform = 'resize_center_crop'
|
63 |
+
# resolution=width
|
64 |
+
# load_raw_resolution=True
|
65 |
+
# # frame_stride=2
|
66 |
+
# video_length= n_sample_frames
|
67 |
+
# fps_max=None
|
68 |
+
# load_resize_keep_ratio=False
|
69 |
+
|
70 |
+
|
71 |
+
|
72 |
+
# self.global_rank = global_rank
|
73 |
+
# self.all_rank = all_rank
|
74 |
+
# # self.subsample = subsample
|
75 |
+
# self.video_length = video_length
|
76 |
+
# self.resolution = [resolution, resolution] if isinstance(resolution, int) else resolution
|
77 |
+
# self.frame_stride = sample_frame_rate
|
78 |
+
# self.load_raw_resolution = load_raw_resolution
|
79 |
+
# self.fps_max = fps_max
|
80 |
+
# self.load_resize_keep_ratio = load_resize_keep_ratio
|
81 |
+
# print('start load meta data')
|
82 |
+
# self._load_metadata()
|
83 |
+
# print('load meta data done!!!')
|
84 |
+
# if spatial_transform is not None:
|
85 |
+
# if spatial_transform == "random_crop":
|
86 |
+
# self.spatial_transform = transforms_video.RandomCropVideo(crop_resolution)
|
87 |
+
# elif spatial_transform == "resize_center_crop":
|
88 |
+
# assert(self.resolution[0] == self.resolution[1])
|
89 |
+
# self.spatial_transform = transforms.Compose([
|
90 |
+
# transforms.Resize(resolution),
|
91 |
+
# transforms_video.CenterCropVideo(resolution),
|
92 |
+
# ])
|
93 |
+
# elif spatial_transform == "center_crop":
|
94 |
+
# self.spatial_transform = transforms_video.CenterCropVideo(resolution)
|
95 |
+
# else:
|
96 |
+
# raise NotImplementedError
|
97 |
+
# else:
|
98 |
+
# self.spatial_transform = None
|
99 |
+
|
100 |
+
# def _load_metadata(self):
|
101 |
+
# # clip_id frame_id caption
|
102 |
+
# last_clip_id = ''
|
103 |
+
# self.metadata = []
|
104 |
+
# start_time = time.time()
|
105 |
+
# caption_path = self.meta_path
|
106 |
+
# count=-1
|
107 |
+
# total_count = 8854264 #8856312 - 2048
|
108 |
+
|
109 |
+
# with open(caption_path, 'r',encoding="utf-8") as csvfile: #41s
|
110 |
+
# reader = csv.DictReader(csvfile)
|
111 |
+
# for row in reader:
|
112 |
+
# if row['clip_id'] != last_clip_id:
|
113 |
+
# count+=1
|
114 |
+
# if count >= (total_count // self.all_rank)*self.all_rank: # drop last
|
115 |
+
# break
|
116 |
+
# last_clip_id = row['clip_id']
|
117 |
+
# if count % self.all_rank == self.global_rank:
|
118 |
+
# self.metadata.append([('%02d'%int(row['part_id']))+row['clip_id']])
|
119 |
+
# self.metadata[-1].append([row['caption']])
|
120 |
+
# else:
|
121 |
+
# if count % self.all_rank == self.global_rank:
|
122 |
+
# self.metadata[-1][-1].append(row['caption'])
|
123 |
+
# # caption_data = pd.read_csv(caption_path) # use time 26+264s
|
124 |
+
|
125 |
+
# # for index,row in caption_data.iterrows():
|
126 |
+
# # if row['clip_id'] != last_clip_id:
|
127 |
+
# # last_clip_id = row['clip_id']
|
128 |
+
# # meta_data[('%02d'%part_id)+row['clip_id']] = [row['caption']]
|
129 |
+
# # else:
|
130 |
+
# # meta_data[('%02d'%part_id)+row['clip_id']].append(row['caption'])
|
131 |
+
# end_time = time.time()
|
132 |
+
# print('load %d - %d items use time: %.1f;' % (len(self.metadata), count, end_time-start_time))
|
133 |
+
# # self.metadata=meta_data
|
134 |
+
|
135 |
+
|
136 |
+
# def _get_video_path(self, sample):
|
137 |
+
# part_id = int(sample[0][:2])
|
138 |
+
# clip_id = sample[0][2:]
|
139 |
+
# video_path = os.path.join(self.data_dir,'part_%d' % part_id, 'video_clips', clip_id)
|
140 |
+
# return video_path
|
141 |
+
|
142 |
+
# def __getitem__(self, index):
|
143 |
+
# while True:
|
144 |
+
|
145 |
+
# index = index % len(self.metadata)
|
146 |
+
# sample = self.metadata[index]
|
147 |
+
# video_path = self._get_video_path(sample)
|
148 |
+
|
149 |
+
# try:
|
150 |
+
# if self.load_raw_resolution:
|
151 |
+
# video_reader = VideoReader(video_path, ctx=cpu(0))
|
152 |
+
# elif self.load_resize_keep_ratio:
|
153 |
+
# # resize scale is according to the short side
|
154 |
+
# h, w, c = VideoReader(video_path, ctx=cpu(0))[0].shape
|
155 |
+
# if h < w:
|
156 |
+
# scale = h / self.resolution[0]
|
157 |
+
# else:
|
158 |
+
# scale = w / self.resolution[1]
|
159 |
+
|
160 |
+
# h = math.ceil(h / scale)
|
161 |
+
# w = math.ceil(w / scale)
|
162 |
+
# video_reader = VideoReader(video_path, ctx=cpu(0), width=w, height=h)
|
163 |
+
# else:
|
164 |
+
# video_reader = VideoReader(video_path, ctx=cpu(0), width=self.resolution[1], height=self.resolution[0])
|
165 |
+
# if len(video_reader) < self.video_length:
|
166 |
+
# print(f"video length ({len(video_reader)}) is smaller than target length({self.video_length})")
|
167 |
+
# index += 1
|
168 |
+
# continue
|
169 |
+
# else:
|
170 |
+
# pass
|
171 |
+
# except:
|
172 |
+
# index += 1
|
173 |
+
# print(f"Load video failed! path = {video_path}")
|
174 |
+
# continue
|
175 |
+
# fps_ori = video_reader.get_avg_fps()
|
176 |
+
|
177 |
+
# fs = self.frame_stride
|
178 |
+
# allf = len(video_reader)
|
179 |
+
# if self.frame_stride != 1:
|
180 |
+
# all_frames = list(range(0, len(video_reader), self.frame_stride))
|
181 |
+
# if len(all_frames) < self.video_length:
|
182 |
+
# fs = len(video_reader) // self.video_length
|
183 |
+
# assert(fs != 0)
|
184 |
+
# all_frames = list(range(0, len(video_reader), fs))
|
185 |
+
# else:
|
186 |
+
# all_frames = list(range(len(video_reader)))
|
187 |
+
|
188 |
+
# # select a random clip
|
189 |
+
# rand_idx = random.randint(0, len(all_frames) - self.video_length)
|
190 |
+
# frame_indices = all_frames[rand_idx:rand_idx+self.video_length]
|
191 |
+
# try:
|
192 |
+
# frames = video_reader.get_batch(frame_indices)
|
193 |
+
# break
|
194 |
+
# except:
|
195 |
+
# print(f"Get frames failed! path = {video_path}")
|
196 |
+
# index += 1
|
197 |
+
# continue
|
198 |
+
|
199 |
+
# assert(frames.shape[0] == self.video_length),f'{len(frames)}, self.video_length={self.video_length}'
|
200 |
+
# frames = torch.tensor(frames.asnumpy()).permute(3, 0, 1, 2).float() # [t,h,w,c] -> [c,t,h,w]
|
201 |
+
|
202 |
+
# if self.spatial_transform is not None:
|
203 |
+
# frames = self.spatial_transform(frames)
|
204 |
+
# assert(frames.shape[2] == self.resolution[0] and frames.shape[3] == self.resolution[1]), f'frames={frames.shape}, self.resolution={self.resolution}'
|
205 |
+
# frames = frames.byte()
|
206 |
+
# # fps
|
207 |
+
# fps_clip = fps_ori // self.frame_stride
|
208 |
+
# if self.fps_max is not None and fps_clip > self.fps_max:
|
209 |
+
# fps_clip = self.fps_max
|
210 |
+
|
211 |
+
# # caption index
|
212 |
+
# middle_idx = (rand_idx + self.video_length /2 )*fs
|
213 |
+
# big_cap_idx = (middle_idx // 64 +1) *64
|
214 |
+
# small_cap_idx = (middle_idx // 64) *64
|
215 |
+
# if big_cap_idx >= allf or ((big_cap_idx-middle_idx) >= (small_cap_idx-middle_idx)):
|
216 |
+
# cap_idx = small_cap_idx
|
217 |
+
# else:
|
218 |
+
# cap_idx = big_cap_idx
|
219 |
+
# # print(middle_idx, small_cap_idx, big_cap_idx,cap_idx)
|
220 |
+
# caption = sample[1][int(cap_idx//64)]
|
221 |
+
|
222 |
+
# frames = frames.permute(1,0,2,3)
|
223 |
+
# skeleton_final = torch.zeros_like(frames).byte()
|
224 |
+
# frames = (frames / 127.5 - 1.0)
|
225 |
+
# skeleton_final = (skeleton_final / 127.5 - 1.0)
|
226 |
+
# example = {'pixel_values': frames, 'sentence': caption, 'pose': skeleton_final}
|
227 |
+
|
228 |
+
|
229 |
+
|
230 |
+
# return example
|
231 |
+
|
232 |
+
# def __len__(self):
|
233 |
+
# return len(self.metadata)
|
234 |
+
# # return 1
|
235 |
+
|
236 |
+
|
237 |
+
# if __name__ == '__main__':
|
238 |
+
# if True: # val
|
239 |
+
# hd_data = HDVila('/apdcephfs_cq3/share_1290939/0_public_datasets/hd-vila-100m','/apdcephfs_cq3/share_1290939/0_public_datasets/hd-vila-100m/caption_2048_val.csv')
|
240 |
+
# else:
|
241 |
+
# hd_data = HDVila('/apdcephfs_cq3/share_1290939/0_public_datasets/hd-vila-100m','/apdcephfs_cq3/share_1290939/0_public_datasets/hd-vila-100m/caption_rm2048_train.csv')
|
242 |
+
# print(len(hd_data))
|
243 |
+
# for i in range(len(hd_data)):
|
244 |
+
# # print(i)
|
245 |
+
# hd_data[i]
|
FollowYourPose/followyourpose/models/attention.py
ADDED
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention.py
|
2 |
+
|
3 |
+
from dataclasses import dataclass
|
4 |
+
from typing import Optional
|
5 |
+
|
6 |
+
import torch
|
7 |
+
import torch.nn.functional as F
|
8 |
+
from torch import nn
|
9 |
+
|
10 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
11 |
+
from diffusers.modeling_utils import ModelMixin
|
12 |
+
from diffusers.utils import BaseOutput
|
13 |
+
from diffusers.utils.import_utils import is_xformers_available
|
14 |
+
from diffusers.models.attention import CrossAttention, FeedForward, AdaLayerNorm
|
15 |
+
|
16 |
+
from einops import rearrange, repeat
|
17 |
+
|
18 |
+
|
19 |
+
@dataclass
|
20 |
+
class Transformer3DModelOutput(BaseOutput):
|
21 |
+
sample: torch.FloatTensor
|
22 |
+
|
23 |
+
|
24 |
+
if is_xformers_available():
|
25 |
+
import xformers
|
26 |
+
import xformers.ops
|
27 |
+
else:
|
28 |
+
xformers = None
|
29 |
+
|
30 |
+
|
31 |
+
class Transformer3DModel(ModelMixin, ConfigMixin):
|
32 |
+
@register_to_config
|
33 |
+
def __init__(
|
34 |
+
self,
|
35 |
+
num_attention_heads: int = 16,
|
36 |
+
attention_head_dim: int = 88,
|
37 |
+
in_channels: Optional[int] = None,
|
38 |
+
num_layers: int = 1,
|
39 |
+
dropout: float = 0.0,
|
40 |
+
norm_num_groups: int = 32,
|
41 |
+
cross_attention_dim: Optional[int] = None,
|
42 |
+
attention_bias: bool = False,
|
43 |
+
activation_fn: str = "geglu",
|
44 |
+
num_embeds_ada_norm: Optional[int] = None,
|
45 |
+
use_linear_projection: bool = False,
|
46 |
+
only_cross_attention: bool = False,
|
47 |
+
upcast_attention: bool = False,
|
48 |
+
):
|
49 |
+
super().__init__()
|
50 |
+
self.use_linear_projection = use_linear_projection
|
51 |
+
self.num_attention_heads = num_attention_heads
|
52 |
+
self.attention_head_dim = attention_head_dim
|
53 |
+
inner_dim = num_attention_heads * attention_head_dim
|
54 |
+
|
55 |
+
# Define input layers
|
56 |
+
self.in_channels = in_channels
|
57 |
+
|
58 |
+
self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)
|
59 |
+
if use_linear_projection:
|
60 |
+
self.proj_in = nn.Linear(in_channels, inner_dim)
|
61 |
+
else:
|
62 |
+
self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
|
63 |
+
|
64 |
+
# Define transformers blocks
|
65 |
+
self.transformer_blocks = nn.ModuleList(
|
66 |
+
[
|
67 |
+
BasicTransformerBlock(
|
68 |
+
inner_dim,
|
69 |
+
num_attention_heads,
|
70 |
+
attention_head_dim,
|
71 |
+
dropout=dropout,
|
72 |
+
cross_attention_dim=cross_attention_dim,
|
73 |
+
activation_fn=activation_fn,
|
74 |
+
num_embeds_ada_norm=num_embeds_ada_norm,
|
75 |
+
attention_bias=attention_bias,
|
76 |
+
only_cross_attention=only_cross_attention,
|
77 |
+
upcast_attention=upcast_attention,
|
78 |
+
)
|
79 |
+
for d in range(num_layers)
|
80 |
+
]
|
81 |
+
)
|
82 |
+
|
83 |
+
# 4. Define output layers
|
84 |
+
if use_linear_projection:
|
85 |
+
self.proj_out = nn.Linear(in_channels, inner_dim)
|
86 |
+
else:
|
87 |
+
self.proj_out = nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0)
|
88 |
+
|
89 |
+
def forward(self, hidden_states, encoder_hidden_states=None, timestep=None, return_dict: bool = True):
|
90 |
+
# Input
|
91 |
+
assert hidden_states.dim() == 5, f"Expected hidden_states to have ndim=5, but got ndim={hidden_states.dim()}."
|
92 |
+
video_length = hidden_states.shape[2]
|
93 |
+
hidden_states = rearrange(hidden_states, "b c f h w -> (b f) c h w")
|
94 |
+
encoder_hidden_states = repeat(encoder_hidden_states, 'b n c -> (b f) n c', f=video_length)
|
95 |
+
|
96 |
+
batch, channel, height, weight = hidden_states.shape
|
97 |
+
residual = hidden_states
|
98 |
+
|
99 |
+
hidden_states = self.norm(hidden_states)
|
100 |
+
if not self.use_linear_projection:
|
101 |
+
hidden_states = self.proj_in(hidden_states)
|
102 |
+
inner_dim = hidden_states.shape[1]
|
103 |
+
hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * weight, inner_dim)
|
104 |
+
else:
|
105 |
+
inner_dim = hidden_states.shape[1]
|
106 |
+
hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * weight, inner_dim)
|
107 |
+
hidden_states = self.proj_in(hidden_states)
|
108 |
+
|
109 |
+
# Blocks
|
110 |
+
for block in self.transformer_blocks:
|
111 |
+
hidden_states = block(
|
112 |
+
hidden_states,
|
113 |
+
encoder_hidden_states=encoder_hidden_states,
|
114 |
+
timestep=timestep,
|
115 |
+
video_length=video_length
|
116 |
+
)
|
117 |
+
|
118 |
+
# Output
|
119 |
+
if not self.use_linear_projection:
|
120 |
+
hidden_states = (
|
121 |
+
hidden_states.reshape(batch, height, weight, inner_dim).permute(0, 3, 1, 2).contiguous()
|
122 |
+
)
|
123 |
+
hidden_states = self.proj_out(hidden_states)
|
124 |
+
else:
|
125 |
+
hidden_states = self.proj_out(hidden_states)
|
126 |
+
hidden_states = (
|
127 |
+
hidden_states.reshape(batch, height, weight, inner_dim).permute(0, 3, 1, 2).contiguous()
|
128 |
+
)
|
129 |
+
|
130 |
+
output = hidden_states + residual
|
131 |
+
|
132 |
+
output = rearrange(output, "(b f) c h w -> b c f h w", f=video_length)
|
133 |
+
if not return_dict:
|
134 |
+
return (output,)
|
135 |
+
|
136 |
+
return Transformer3DModelOutput(sample=output)
|
137 |
+
|
138 |
+
|
139 |
+
class BasicTransformerBlock(nn.Module):
|
140 |
+
def __init__(
|
141 |
+
self,
|
142 |
+
dim: int,
|
143 |
+
num_attention_heads: int,
|
144 |
+
attention_head_dim: int,
|
145 |
+
dropout=0.0,
|
146 |
+
cross_attention_dim: Optional[int] = None,
|
147 |
+
activation_fn: str = "geglu",
|
148 |
+
num_embeds_ada_norm: Optional[int] = None,
|
149 |
+
attention_bias: bool = False,
|
150 |
+
only_cross_attention: bool = False,
|
151 |
+
upcast_attention: bool = False,
|
152 |
+
):
|
153 |
+
super().__init__()
|
154 |
+
self.only_cross_attention = only_cross_attention
|
155 |
+
self.use_ada_layer_norm = num_embeds_ada_norm is not None
|
156 |
+
|
157 |
+
# SC-Attn
|
158 |
+
self.attn1 = SparseCausalAttention(
|
159 |
+
query_dim=dim,
|
160 |
+
heads=num_attention_heads,
|
161 |
+
dim_head=attention_head_dim,
|
162 |
+
dropout=dropout,
|
163 |
+
bias=attention_bias,
|
164 |
+
cross_attention_dim=cross_attention_dim if only_cross_attention else None,
|
165 |
+
upcast_attention=upcast_attention,
|
166 |
+
)
|
167 |
+
self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm) if self.use_ada_layer_norm else nn.LayerNorm(dim)
|
168 |
+
|
169 |
+
# Cross-Attn
|
170 |
+
if cross_attention_dim is not None:
|
171 |
+
self.attn2 = CrossAttention(
|
172 |
+
query_dim=dim,
|
173 |
+
cross_attention_dim=cross_attention_dim,
|
174 |
+
heads=num_attention_heads,
|
175 |
+
dim_head=attention_head_dim,
|
176 |
+
dropout=dropout,
|
177 |
+
bias=attention_bias,
|
178 |
+
upcast_attention=upcast_attention,
|
179 |
+
)
|
180 |
+
else:
|
181 |
+
self.attn2 = None
|
182 |
+
|
183 |
+
if cross_attention_dim is not None:
|
184 |
+
self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm) if self.use_ada_layer_norm else nn.LayerNorm(dim)
|
185 |
+
else:
|
186 |
+
self.norm2 = None
|
187 |
+
|
188 |
+
# Feed-forward
|
189 |
+
self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn)
|
190 |
+
self.norm3 = nn.LayerNorm(dim)
|
191 |
+
|
192 |
+
# Temp-Attn
|
193 |
+
self.attn_temp = CrossAttention(
|
194 |
+
query_dim=dim,
|
195 |
+
heads=num_attention_heads,
|
196 |
+
dim_head=attention_head_dim,
|
197 |
+
dropout=dropout,
|
198 |
+
bias=attention_bias,
|
199 |
+
upcast_attention=upcast_attention,
|
200 |
+
)
|
201 |
+
# nn.init.zeros_(self.attn_temp.to_out[0].weight.data)
|
202 |
+
self.norm_temp = AdaLayerNorm(dim, num_embeds_ada_norm) if self.use_ada_layer_norm else nn.LayerNorm(dim)
|
203 |
+
|
204 |
+
self.conv_temporal = LoRALinearLayer(dim, dim, rank=160, stride=1)
|
205 |
+
|
206 |
+
def set_use_memory_efficient_attention_xformers(self, use_memory_efficient_attention_xformers: bool):
|
207 |
+
if not is_xformers_available():
|
208 |
+
print("Here is how to install it")
|
209 |
+
raise ModuleNotFoundError(
|
210 |
+
"Refer to https://github.com/facebookresearch/xformers for more information on how to install"
|
211 |
+
" xformers",
|
212 |
+
name="xformers",
|
213 |
+
)
|
214 |
+
elif not torch.cuda.is_available():
|
215 |
+
raise ValueError(
|
216 |
+
"torch.cuda.is_available() should be True but is False. xformers' memory efficient attention is only"
|
217 |
+
" available for GPU "
|
218 |
+
)
|
219 |
+
else:
|
220 |
+
try:
|
221 |
+
# Make sure we can run the memory efficient attention
|
222 |
+
_ = xformers.ops.memory_efficient_attention(
|
223 |
+
torch.randn((1, 2, 40), device="cuda"),
|
224 |
+
torch.randn((1, 2, 40), device="cuda"),
|
225 |
+
torch.randn((1, 2, 40), device="cuda"),
|
226 |
+
)
|
227 |
+
except Exception as e:
|
228 |
+
raise e
|
229 |
+
self.attn1._use_memory_efficient_attention_xformers = use_memory_efficient_attention_xformers
|
230 |
+
if self.attn2 is not None:
|
231 |
+
self.attn2._use_memory_efficient_attention_xformers = use_memory_efficient_attention_xformers
|
232 |
+
# self.attn_temp._use_memory_efficient_attention_xformers = use_memory_efficient_attention_xformers
|
233 |
+
|
234 |
+
def forward(self, hidden_states, encoder_hidden_states=None, timestep=None, attention_mask=None, video_length=None):
|
235 |
+
# SparseCausal-Attention
|
236 |
+
norm_hidden_states = (
|
237 |
+
self.norm1(hidden_states, timestep) if self.use_ada_layer_norm else self.norm1(hidden_states)
|
238 |
+
)
|
239 |
+
|
240 |
+
if self.only_cross_attention:
|
241 |
+
hidden_states = (
|
242 |
+
self.attn1(norm_hidden_states, encoder_hidden_states, attention_mask=attention_mask) + hidden_states
|
243 |
+
)
|
244 |
+
else:
|
245 |
+
hidden_states = self.attn1(norm_hidden_states, attention_mask=attention_mask, video_length=video_length) + hidden_states
|
246 |
+
|
247 |
+
if self.attn2 is not None:
|
248 |
+
# Cross-Attention
|
249 |
+
norm_hidden_states = (
|
250 |
+
self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
|
251 |
+
)
|
252 |
+
hidden_states = (
|
253 |
+
self.attn2(
|
254 |
+
norm_hidden_states, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask
|
255 |
+
)
|
256 |
+
+ hidden_states
|
257 |
+
)
|
258 |
+
|
259 |
+
# Feed-forward
|
260 |
+
hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states
|
261 |
+
|
262 |
+
# Temporal-Attention
|
263 |
+
d = hidden_states.shape[1]
|
264 |
+
hidden_states = rearrange(hidden_states, "(b f) d c -> (b d) f c", f=video_length)
|
265 |
+
norm_hidden_states = (
|
266 |
+
self.norm_temp(hidden_states, timestep) if self.use_ada_layer_norm else self.norm_temp(hidden_states)
|
267 |
+
)
|
268 |
+
hidden_states = self.attn_temp(norm_hidden_states) + hidden_states
|
269 |
+
hidden_states = rearrange(hidden_states, "(b d) f c -> (b f) d c", d=d)
|
270 |
+
|
271 |
+
|
272 |
+
hidden_states = rearrange(hidden_states, "(b f) d c -> (b d) c f", d=d, f=video_length)
|
273 |
+
hidden_states = self.conv_temporal(hidden_states)
|
274 |
+
hidden_states = rearrange(hidden_states, "(b d) c f -> (b f) d c", d=d, f=video_length)
|
275 |
+
|
276 |
+
return hidden_states
|
277 |
+
|
278 |
+
|
279 |
+
|
280 |
+
|
281 |
+
class LoRALinearLayer(nn.Module):
|
282 |
+
def __init__(self, in_features, out_features, rank=4, stride=1):
|
283 |
+
super().__init__()
|
284 |
+
|
285 |
+
if rank > min(in_features, out_features):
|
286 |
+
Warning(f"LoRA rank {rank} must be less or equal than {min(in_features, out_features)}, reset to {min(in_features, out_features)//2}")
|
287 |
+
rank = min(in_features, out_features)//2
|
288 |
+
|
289 |
+
|
290 |
+
self.down = nn.Conv1d(in_features, rank, bias=False,
|
291 |
+
kernel_size=3,
|
292 |
+
stride = stride,
|
293 |
+
padding=1,)
|
294 |
+
self.up = nn.Conv1d(rank, out_features, bias=False,
|
295 |
+
kernel_size=3,
|
296 |
+
padding=1,)
|
297 |
+
|
298 |
+
nn.init.normal_(self.down.weight, std=1 / rank)
|
299 |
+
# nn.init.zeros_(self.down.bias.data)
|
300 |
+
|
301 |
+
nn.init.zeros_(self.up.weight)
|
302 |
+
# nn.init.zeros_(self.up.bias.data)
|
303 |
+
if stride > 1:
|
304 |
+
self.skip = nn.AvgPool1d(kernel_size=3, stride=2, padding=1)
|
305 |
+
|
306 |
+
def forward(self, hidden_states):
|
307 |
+
orig_dtype = hidden_states.dtype
|
308 |
+
dtype = self.down.weight.dtype
|
309 |
+
|
310 |
+
down_hidden_states = self.down(hidden_states.to(dtype))
|
311 |
+
up_hidden_states = self.up(down_hidden_states)
|
312 |
+
if hasattr(self, 'skip'):
|
313 |
+
hidden_states=self.skip(hidden_states)
|
314 |
+
return up_hidden_states.to(orig_dtype)+hidden_states
|
315 |
+
|
316 |
+
|
317 |
+
|
318 |
+
|
319 |
+
class SparseCausalAttention(CrossAttention):
|
320 |
+
def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None, video_length=None):
|
321 |
+
batch_size, sequence_length, _ = hidden_states.shape
|
322 |
+
|
323 |
+
encoder_hidden_states = encoder_hidden_states
|
324 |
+
|
325 |
+
if self.group_norm is not None:
|
326 |
+
hidden_states = self.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
327 |
+
|
328 |
+
query = self.to_q(hidden_states)
|
329 |
+
dim = query.shape[-1]
|
330 |
+
query = self.reshape_heads_to_batch_dim(query)
|
331 |
+
|
332 |
+
if self.added_kv_proj_dim is not None:
|
333 |
+
raise NotImplementedError
|
334 |
+
|
335 |
+
encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
|
336 |
+
key = self.to_k(encoder_hidden_states)
|
337 |
+
value = self.to_v(encoder_hidden_states)
|
338 |
+
|
339 |
+
former_frame_index = torch.arange(video_length) - 1
|
340 |
+
former_frame_index[0] = 0
|
341 |
+
|
342 |
+
key = rearrange(key, "(b f) d c -> b f d c", f=video_length)
|
343 |
+
key = torch.cat([key[:, [0] * video_length], key[:, former_frame_index]], dim=2)
|
344 |
+
key = rearrange(key, "b f d c -> (b f) d c")
|
345 |
+
|
346 |
+
value = rearrange(value, "(b f) d c -> b f d c", f=video_length)
|
347 |
+
value = torch.cat([value[:, [0] * video_length], value[:, former_frame_index]], dim=2)
|
348 |
+
value = rearrange(value, "b f d c -> (b f) d c")
|
349 |
+
|
350 |
+
key = self.reshape_heads_to_batch_dim(key)
|
351 |
+
value = self.reshape_heads_to_batch_dim(value)
|
352 |
+
|
353 |
+
if attention_mask is not None:
|
354 |
+
if attention_mask.shape[-1] != query.shape[1]:
|
355 |
+
target_length = query.shape[1]
|
356 |
+
attention_mask = F.pad(attention_mask, (0, target_length), value=0.0)
|
357 |
+
attention_mask = attention_mask.repeat_interleave(self.heads, dim=0)
|
358 |
+
|
359 |
+
# attention, what we cannot get enough of
|
360 |
+
if self._use_memory_efficient_attention_xformers:
|
361 |
+
hidden_states = self._memory_efficient_attention_xformers(query, key, value, attention_mask)
|
362 |
+
# Some versions of xformers return output in fp32, cast it back to the dtype of the input
|
363 |
+
hidden_states = hidden_states.to(query.dtype)
|
364 |
+
else:
|
365 |
+
if self._slice_size is None or query.shape[0] // self._slice_size == 1:
|
366 |
+
hidden_states = self._attention(query, key, value, attention_mask)
|
367 |
+
else:
|
368 |
+
hidden_states = self._sliced_attention(query, key, value, sequence_length, dim, attention_mask)
|
369 |
+
|
370 |
+
# linear proj
|
371 |
+
hidden_states = self.to_out[0](hidden_states)
|
372 |
+
|
373 |
+
# dropout
|
374 |
+
hidden_states = self.to_out[1](hidden_states)
|
375 |
+
return hidden_states
|
FollowYourPose/followyourpose/models/resnet.py
ADDED
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/resnet.py
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
import torch.nn.functional as F
|
6 |
+
|
7 |
+
from einops import rearrange
|
8 |
+
|
9 |
+
|
10 |
+
class InflatedConv3d(nn.Conv2d):
|
11 |
+
def forward(self, x):
|
12 |
+
video_length = x.shape[2]
|
13 |
+
|
14 |
+
x = rearrange(x, "b c f h w -> (b f) c h w")
|
15 |
+
x = super().forward(x)
|
16 |
+
x = rearrange(x, "(b f) c h w -> b c f h w", f=video_length)
|
17 |
+
|
18 |
+
return x
|
19 |
+
|
20 |
+
|
21 |
+
class Upsample3D(nn.Module):
|
22 |
+
def __init__(self, channels, use_conv=False, use_conv_transpose=False, out_channels=None, name="conv"):
|
23 |
+
super().__init__()
|
24 |
+
self.channels = channels
|
25 |
+
self.out_channels = out_channels or channels
|
26 |
+
self.use_conv = use_conv
|
27 |
+
self.use_conv_transpose = use_conv_transpose
|
28 |
+
self.name = name
|
29 |
+
|
30 |
+
conv = None
|
31 |
+
if use_conv_transpose:
|
32 |
+
raise NotImplementedError
|
33 |
+
elif use_conv:
|
34 |
+
conv = InflatedConv3d(self.channels, self.out_channels, 3, padding=1)
|
35 |
+
|
36 |
+
if name == "conv":
|
37 |
+
self.conv = conv
|
38 |
+
else:
|
39 |
+
self.Conv2d_0 = conv
|
40 |
+
|
41 |
+
def forward(self, hidden_states, output_size=None):
|
42 |
+
assert hidden_states.shape[1] == self.channels
|
43 |
+
|
44 |
+
if self.use_conv_transpose:
|
45 |
+
raise NotImplementedError
|
46 |
+
|
47 |
+
# Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16
|
48 |
+
dtype = hidden_states.dtype
|
49 |
+
if dtype == torch.bfloat16:
|
50 |
+
hidden_states = hidden_states.to(torch.float32)
|
51 |
+
|
52 |
+
# upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
|
53 |
+
if hidden_states.shape[0] >= 64:
|
54 |
+
hidden_states = hidden_states.contiguous()
|
55 |
+
|
56 |
+
# if `output_size` is passed we force the interpolation output
|
57 |
+
# size and do not make use of `scale_factor=2`
|
58 |
+
if output_size is None:
|
59 |
+
hidden_states = F.interpolate(hidden_states, scale_factor=[1.0, 2.0, 2.0], mode="nearest")
|
60 |
+
else:
|
61 |
+
hidden_states = F.interpolate(hidden_states, size=output_size, mode="nearest")
|
62 |
+
|
63 |
+
# If the input is bfloat16, we cast back to bfloat16
|
64 |
+
if dtype == torch.bfloat16:
|
65 |
+
hidden_states = hidden_states.to(dtype)
|
66 |
+
|
67 |
+
if self.use_conv:
|
68 |
+
if self.name == "conv":
|
69 |
+
hidden_states = self.conv(hidden_states)
|
70 |
+
else:
|
71 |
+
hidden_states = self.Conv2d_0(hidden_states)
|
72 |
+
|
73 |
+
return hidden_states
|
74 |
+
|
75 |
+
|
76 |
+
class Downsample3D(nn.Module):
|
77 |
+
def __init__(self, channels, use_conv=False, out_channels=None, padding=1, name="conv"):
|
78 |
+
super().__init__()
|
79 |
+
self.channels = channels
|
80 |
+
self.out_channels = out_channels or channels
|
81 |
+
self.use_conv = use_conv
|
82 |
+
self.padding = padding
|
83 |
+
stride = 2
|
84 |
+
self.name = name
|
85 |
+
|
86 |
+
if use_conv:
|
87 |
+
conv = InflatedConv3d(self.channels, self.out_channels, 3, stride=stride, padding=padding)
|
88 |
+
else:
|
89 |
+
raise NotImplementedError
|
90 |
+
|
91 |
+
if name == "conv":
|
92 |
+
self.Conv2d_0 = conv
|
93 |
+
self.conv = conv
|
94 |
+
elif name == "Conv2d_0":
|
95 |
+
self.conv = conv
|
96 |
+
else:
|
97 |
+
self.conv = conv
|
98 |
+
|
99 |
+
def forward(self, hidden_states):
|
100 |
+
assert hidden_states.shape[1] == self.channels
|
101 |
+
if self.use_conv and self.padding == 0:
|
102 |
+
raise NotImplementedError
|
103 |
+
|
104 |
+
assert hidden_states.shape[1] == self.channels
|
105 |
+
hidden_states = self.conv(hidden_states)
|
106 |
+
|
107 |
+
return hidden_states
|
108 |
+
|
109 |
+
|
110 |
+
class ResnetBlock3D(nn.Module):
|
111 |
+
def __init__(
|
112 |
+
self,
|
113 |
+
*,
|
114 |
+
in_channels,
|
115 |
+
out_channels=None,
|
116 |
+
conv_shortcut=False,
|
117 |
+
dropout=0.0,
|
118 |
+
temb_channels=512,
|
119 |
+
groups=32,
|
120 |
+
groups_out=None,
|
121 |
+
pre_norm=True,
|
122 |
+
eps=1e-6,
|
123 |
+
non_linearity="swish",
|
124 |
+
time_embedding_norm="default",
|
125 |
+
output_scale_factor=1.0,
|
126 |
+
use_in_shortcut=None,
|
127 |
+
):
|
128 |
+
super().__init__()
|
129 |
+
self.pre_norm = pre_norm
|
130 |
+
self.pre_norm = True
|
131 |
+
self.in_channels = in_channels
|
132 |
+
out_channels = in_channels if out_channels is None else out_channels
|
133 |
+
self.out_channels = out_channels
|
134 |
+
self.use_conv_shortcut = conv_shortcut
|
135 |
+
self.time_embedding_norm = time_embedding_norm
|
136 |
+
self.output_scale_factor = output_scale_factor
|
137 |
+
|
138 |
+
if groups_out is None:
|
139 |
+
groups_out = groups
|
140 |
+
|
141 |
+
self.norm1 = torch.nn.GroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)
|
142 |
+
|
143 |
+
self.conv1 = InflatedConv3d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
144 |
+
|
145 |
+
if temb_channels is not None:
|
146 |
+
if self.time_embedding_norm == "default":
|
147 |
+
time_emb_proj_out_channels = out_channels
|
148 |
+
elif self.time_embedding_norm == "scale_shift":
|
149 |
+
time_emb_proj_out_channels = out_channels * 2
|
150 |
+
else:
|
151 |
+
raise ValueError(f"unknown time_embedding_norm : {self.time_embedding_norm} ")
|
152 |
+
|
153 |
+
self.time_emb_proj = torch.nn.Linear(temb_channels, time_emb_proj_out_channels)
|
154 |
+
else:
|
155 |
+
self.time_emb_proj = None
|
156 |
+
|
157 |
+
self.norm2 = torch.nn.GroupNorm(num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True)
|
158 |
+
self.dropout = torch.nn.Dropout(dropout)
|
159 |
+
self.conv2 = InflatedConv3d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
160 |
+
|
161 |
+
if non_linearity == "swish":
|
162 |
+
self.nonlinearity = lambda x: F.silu(x)
|
163 |
+
elif non_linearity == "mish":
|
164 |
+
self.nonlinearity = Mish()
|
165 |
+
elif non_linearity == "silu":
|
166 |
+
self.nonlinearity = nn.SiLU()
|
167 |
+
|
168 |
+
self.use_in_shortcut = self.in_channels != self.out_channels if use_in_shortcut is None else use_in_shortcut
|
169 |
+
|
170 |
+
self.conv_shortcut = None
|
171 |
+
if self.use_in_shortcut:
|
172 |
+
self.conv_shortcut = InflatedConv3d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
|
173 |
+
|
174 |
+
def forward(self, input_tensor, temb):
|
175 |
+
hidden_states = input_tensor
|
176 |
+
|
177 |
+
hidden_states = self.norm1(hidden_states)
|
178 |
+
hidden_states = self.nonlinearity(hidden_states)
|
179 |
+
|
180 |
+
hidden_states = self.conv1(hidden_states)
|
181 |
+
|
182 |
+
if temb is not None:
|
183 |
+
temb = self.time_emb_proj(self.nonlinearity(temb))[:, :, None, None, None]
|
184 |
+
|
185 |
+
if temb is not None and self.time_embedding_norm == "default":
|
186 |
+
hidden_states = hidden_states + temb
|
187 |
+
|
188 |
+
hidden_states = self.norm2(hidden_states)
|
189 |
+
|
190 |
+
if temb is not None and self.time_embedding_norm == "scale_shift":
|
191 |
+
scale, shift = torch.chunk(temb, 2, dim=1)
|
192 |
+
hidden_states = hidden_states * (1 + scale) + shift
|
193 |
+
|
194 |
+
hidden_states = self.nonlinearity(hidden_states)
|
195 |
+
|
196 |
+
hidden_states = self.dropout(hidden_states)
|
197 |
+
hidden_states = self.conv2(hidden_states)
|
198 |
+
|
199 |
+
if self.conv_shortcut is not None:
|
200 |
+
input_tensor = self.conv_shortcut(input_tensor)
|
201 |
+
|
202 |
+
output_tensor = (input_tensor + hidden_states) / self.output_scale_factor
|
203 |
+
|
204 |
+
return output_tensor
|
205 |
+
|
206 |
+
|
207 |
+
class Mish(torch.nn.Module):
|
208 |
+
def forward(self, hidden_states):
|
209 |
+
return hidden_states * torch.tanh(torch.nn.functional.softplus(hidden_states))
|
FollowYourPose/followyourpose/models/unet.py
ADDED
@@ -0,0 +1,571 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_condition.py
|
2 |
+
|
3 |
+
from dataclasses import dataclass
|
4 |
+
from typing import List, Optional, Tuple, Union
|
5 |
+
|
6 |
+
import os
|
7 |
+
import json
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torch.nn as nn
|
11 |
+
import torch.utils.checkpoint
|
12 |
+
|
13 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
14 |
+
from diffusers.modeling_utils import ModelMixin
|
15 |
+
from diffusers.utils import BaseOutput, logging
|
16 |
+
from diffusers.models.embeddings import TimestepEmbedding, Timesteps
|
17 |
+
from .unet_blocks import (
|
18 |
+
CrossAttnDownBlock3D,
|
19 |
+
CrossAttnUpBlock3D,
|
20 |
+
DownBlock3D,
|
21 |
+
UNetMidBlock3DCrossAttn,
|
22 |
+
UpBlock3D,
|
23 |
+
get_down_block,
|
24 |
+
get_up_block,
|
25 |
+
conv_nd,
|
26 |
+
avg_pool_nd,
|
27 |
+
)
|
28 |
+
from .resnet import InflatedConv3d
|
29 |
+
from einops import rearrange
|
30 |
+
import sys
|
31 |
+
sys.path.append('FollowYourPose')
|
32 |
+
|
33 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
34 |
+
|
35 |
+
|
36 |
+
@dataclass
|
37 |
+
class UNet3DConditionOutput(BaseOutput):
|
38 |
+
sample: torch.FloatTensor
|
39 |
+
|
40 |
+
|
41 |
+
class UNet3DConditionModel(ModelMixin, ConfigMixin):
|
42 |
+
_supports_gradient_checkpointing = True
|
43 |
+
|
44 |
+
@register_to_config
|
45 |
+
def __init__(
|
46 |
+
self,
|
47 |
+
sample_size: Optional[int] = None,
|
48 |
+
in_channels: int = 4,
|
49 |
+
out_channels: int = 4,
|
50 |
+
center_input_sample: bool = False,
|
51 |
+
flip_sin_to_cos: bool = True,
|
52 |
+
freq_shift: int = 0,
|
53 |
+
down_block_types: Tuple[str] = (
|
54 |
+
"CrossAttnDownBlock3D",
|
55 |
+
"CrossAttnDownBlock3D",
|
56 |
+
"CrossAttnDownBlock3D",
|
57 |
+
"DownBlock3D",
|
58 |
+
),
|
59 |
+
mid_block_type: str = "UNetMidBlock3DCrossAttn",
|
60 |
+
up_block_types: Tuple[str] = (
|
61 |
+
"UpBlock3D",
|
62 |
+
"CrossAttnUpBlock3D",
|
63 |
+
"CrossAttnUpBlock3D",
|
64 |
+
"CrossAttnUpBlock3D"
|
65 |
+
),
|
66 |
+
only_cross_attention: Union[bool, Tuple[bool]] = False,
|
67 |
+
block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
|
68 |
+
layers_per_block: int = 2,
|
69 |
+
downsample_padding: int = 1,
|
70 |
+
mid_block_scale_factor: float = 1,
|
71 |
+
act_fn: str = "silu",
|
72 |
+
norm_num_groups: int = 32,
|
73 |
+
norm_eps: float = 1e-5,
|
74 |
+
cross_attention_dim: int = 1280,
|
75 |
+
attention_head_dim: Union[int, Tuple[int]] = 8,
|
76 |
+
dual_cross_attention: bool = False,
|
77 |
+
use_linear_projection: bool = False,
|
78 |
+
class_embed_type: Optional[str] = None,
|
79 |
+
num_class_embeds: Optional[int] = None,
|
80 |
+
upcast_attention: bool = False,
|
81 |
+
resnet_time_scale_shift: str = "default",
|
82 |
+
):
|
83 |
+
super().__init__()
|
84 |
+
|
85 |
+
self.sample_size = sample_size
|
86 |
+
time_embed_dim = block_out_channels[0] * 4
|
87 |
+
|
88 |
+
# input
|
89 |
+
self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1))
|
90 |
+
|
91 |
+
# time
|
92 |
+
self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
|
93 |
+
timestep_input_dim = block_out_channels[0]
|
94 |
+
|
95 |
+
self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
|
96 |
+
|
97 |
+
# class embedding
|
98 |
+
if class_embed_type is None and num_class_embeds is not None:
|
99 |
+
self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
|
100 |
+
elif class_embed_type == "timestep":
|
101 |
+
self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
|
102 |
+
elif class_embed_type == "identity":
|
103 |
+
self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
|
104 |
+
else:
|
105 |
+
self.class_embedding = None
|
106 |
+
|
107 |
+
self.down_blocks = nn.ModuleList([])
|
108 |
+
self.mid_block = None
|
109 |
+
self.up_blocks = nn.ModuleList([])
|
110 |
+
|
111 |
+
if isinstance(only_cross_attention, bool):
|
112 |
+
only_cross_attention = [only_cross_attention] * len(down_block_types)
|
113 |
+
|
114 |
+
if isinstance(attention_head_dim, int):
|
115 |
+
attention_head_dim = (attention_head_dim,) * len(down_block_types)
|
116 |
+
|
117 |
+
# down
|
118 |
+
output_channel = block_out_channels[0]
|
119 |
+
for i, down_block_type in enumerate(down_block_types):
|
120 |
+
input_channel = output_channel
|
121 |
+
output_channel = block_out_channels[i]
|
122 |
+
is_final_block = i == len(block_out_channels) - 1
|
123 |
+
|
124 |
+
down_block = get_down_block(
|
125 |
+
down_block_type,
|
126 |
+
num_layers=layers_per_block,
|
127 |
+
in_channels=input_channel,
|
128 |
+
out_channels=output_channel,
|
129 |
+
temb_channels=time_embed_dim,
|
130 |
+
add_downsample=not is_final_block,
|
131 |
+
resnet_eps=norm_eps,
|
132 |
+
resnet_act_fn=act_fn,
|
133 |
+
resnet_groups=norm_num_groups,
|
134 |
+
cross_attention_dim=cross_attention_dim,
|
135 |
+
attn_num_head_channels=attention_head_dim[i],
|
136 |
+
downsample_padding=downsample_padding,
|
137 |
+
dual_cross_attention=dual_cross_attention,
|
138 |
+
use_linear_projection=use_linear_projection,
|
139 |
+
only_cross_attention=only_cross_attention[i],
|
140 |
+
upcast_attention=upcast_attention,
|
141 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
142 |
+
)
|
143 |
+
self.down_blocks.append(down_block)
|
144 |
+
|
145 |
+
# mid
|
146 |
+
if mid_block_type == "UNetMidBlock3DCrossAttn":
|
147 |
+
self.mid_block = UNetMidBlock3DCrossAttn(
|
148 |
+
in_channels=block_out_channels[-1],
|
149 |
+
temb_channels=time_embed_dim,
|
150 |
+
resnet_eps=norm_eps,
|
151 |
+
resnet_act_fn=act_fn,
|
152 |
+
output_scale_factor=mid_block_scale_factor,
|
153 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
154 |
+
cross_attention_dim=cross_attention_dim,
|
155 |
+
attn_num_head_channels=attention_head_dim[-1],
|
156 |
+
resnet_groups=norm_num_groups,
|
157 |
+
dual_cross_attention=dual_cross_attention,
|
158 |
+
use_linear_projection=use_linear_projection,
|
159 |
+
upcast_attention=upcast_attention,
|
160 |
+
)
|
161 |
+
else:
|
162 |
+
raise ValueError(f"unknown mid_block_type : {mid_block_type}")
|
163 |
+
|
164 |
+
# count how many layers upsample the videos
|
165 |
+
self.num_upsamplers = 0
|
166 |
+
|
167 |
+
# up
|
168 |
+
reversed_block_out_channels = list(reversed(block_out_channels))
|
169 |
+
reversed_attention_head_dim = list(reversed(attention_head_dim))
|
170 |
+
only_cross_attention = list(reversed(only_cross_attention))
|
171 |
+
output_channel = reversed_block_out_channels[0]
|
172 |
+
for i, up_block_type in enumerate(up_block_types):
|
173 |
+
is_final_block = i == len(block_out_channels) - 1
|
174 |
+
|
175 |
+
prev_output_channel = output_channel
|
176 |
+
output_channel = reversed_block_out_channels[i]
|
177 |
+
input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
|
178 |
+
|
179 |
+
# add upsample block for all BUT final layer
|
180 |
+
if not is_final_block:
|
181 |
+
add_upsample = True
|
182 |
+
self.num_upsamplers += 1
|
183 |
+
else:
|
184 |
+
add_upsample = False
|
185 |
+
|
186 |
+
up_block = get_up_block(
|
187 |
+
up_block_type,
|
188 |
+
num_layers=layers_per_block + 1,
|
189 |
+
in_channels=input_channel,
|
190 |
+
out_channels=output_channel,
|
191 |
+
prev_output_channel=prev_output_channel,
|
192 |
+
temb_channels=time_embed_dim,
|
193 |
+
add_upsample=add_upsample,
|
194 |
+
resnet_eps=norm_eps,
|
195 |
+
resnet_act_fn=act_fn,
|
196 |
+
resnet_groups=norm_num_groups,
|
197 |
+
cross_attention_dim=cross_attention_dim,
|
198 |
+
attn_num_head_channels=reversed_attention_head_dim[i],
|
199 |
+
dual_cross_attention=dual_cross_attention,
|
200 |
+
use_linear_projection=use_linear_projection,
|
201 |
+
only_cross_attention=only_cross_attention[i],
|
202 |
+
upcast_attention=upcast_attention,
|
203 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
204 |
+
)
|
205 |
+
self.up_blocks.append(up_block)
|
206 |
+
prev_output_channel = output_channel
|
207 |
+
|
208 |
+
# out
|
209 |
+
self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps)
|
210 |
+
self.conv_act = nn.SiLU()
|
211 |
+
self.conv_out = InflatedConv3d(block_out_channels[0], out_channels, kernel_size=3, padding=1)
|
212 |
+
|
213 |
+
self.skeleton_adapter = Adapter(cin=int(3*64), channels=[320, 640, 1280, 1280][:4], nums_rb=2, ksize=1, sk=True, use_conv=False)
|
214 |
+
adapter_weight = torch.load('./FollowYourPose/checkpoints/t2iadapter_keypose_sd14v1.pth')
|
215 |
+
self.skeleton_adapter.load_state_dict(adapter_weight)
|
216 |
+
|
217 |
+
|
218 |
+
def set_attention_slice(self, slice_size):
|
219 |
+
r"""
|
220 |
+
Enable sliced attention computation.
|
221 |
+
|
222 |
+
When this option is enabled, the attention module will split the input tensor in slices, to compute attention
|
223 |
+
in several steps. This is useful to save some memory in exchange for a small speed decrease.
|
224 |
+
|
225 |
+
Args:
|
226 |
+
slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
|
227 |
+
When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
|
228 |
+
`"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is
|
229 |
+
provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
|
230 |
+
must be a multiple of `slice_size`.
|
231 |
+
"""
|
232 |
+
sliceable_head_dims = []
|
233 |
+
|
234 |
+
def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):
|
235 |
+
if hasattr(module, "set_attention_slice"):
|
236 |
+
sliceable_head_dims.append(module.sliceable_head_dim)
|
237 |
+
|
238 |
+
for child in module.children():
|
239 |
+
fn_recursive_retrieve_slicable_dims(child)
|
240 |
+
|
241 |
+
# retrieve number of attention layers
|
242 |
+
for module in self.children():
|
243 |
+
fn_recursive_retrieve_slicable_dims(module)
|
244 |
+
|
245 |
+
num_slicable_layers = len(sliceable_head_dims)
|
246 |
+
|
247 |
+
if slice_size == "auto":
|
248 |
+
# half the attention head size is usually a good trade-off between
|
249 |
+
# speed and memory
|
250 |
+
slice_size = [dim // 2 for dim in sliceable_head_dims]
|
251 |
+
elif slice_size == "max":
|
252 |
+
# make smallest slice possible
|
253 |
+
slice_size = num_slicable_layers * [1]
|
254 |
+
|
255 |
+
slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
|
256 |
+
|
257 |
+
if len(slice_size) != len(sliceable_head_dims):
|
258 |
+
raise ValueError(
|
259 |
+
f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
|
260 |
+
f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
|
261 |
+
)
|
262 |
+
|
263 |
+
for i in range(len(slice_size)):
|
264 |
+
size = slice_size[i]
|
265 |
+
dim = sliceable_head_dims[i]
|
266 |
+
if size is not None and size > dim:
|
267 |
+
raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
|
268 |
+
|
269 |
+
# Recursively walk through all the children.
|
270 |
+
# Any children which exposes the set_attention_slice method
|
271 |
+
# gets the message
|
272 |
+
def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
|
273 |
+
if hasattr(module, "set_attention_slice"):
|
274 |
+
module.set_attention_slice(slice_size.pop())
|
275 |
+
|
276 |
+
for child in module.children():
|
277 |
+
fn_recursive_set_attention_slice(child, slice_size)
|
278 |
+
|
279 |
+
reversed_slice_size = list(reversed(slice_size))
|
280 |
+
for module in self.children():
|
281 |
+
fn_recursive_set_attention_slice(module, reversed_slice_size)
|
282 |
+
|
283 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
284 |
+
if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)):
|
285 |
+
module.gradient_checkpointing = value
|
286 |
+
|
287 |
+
def forward(
|
288 |
+
self,
|
289 |
+
sample: torch.FloatTensor,
|
290 |
+
timestep: Union[torch.Tensor, float, int],
|
291 |
+
encoder_hidden_states: torch.Tensor,
|
292 |
+
class_labels: Optional[torch.Tensor] = None,
|
293 |
+
attention_mask: Optional[torch.Tensor] = None,
|
294 |
+
return_dict: bool = True,
|
295 |
+
skeleton: Optional[torch.FloatTensor] = None,
|
296 |
+
train_or_sample: str = 'train',
|
297 |
+
) -> Union[UNet3DConditionOutput, Tuple]:
|
298 |
+
r"""
|
299 |
+
Args:
|
300 |
+
sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor
|
301 |
+
timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps
|
302 |
+
encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states
|
303 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
304 |
+
Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.
|
305 |
+
|
306 |
+
Returns:
|
307 |
+
[`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
|
308 |
+
[`~models.unet_2d_condition.UNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When
|
309 |
+
returning a tuple, the first element is the sample tensor.
|
310 |
+
"""
|
311 |
+
# By default samples have to be AT least a multiple of the overall upsampling factor.
|
312 |
+
# The overall upsampling factor is equal to 2 ** (# num of upsampling layears).
|
313 |
+
# However, the upsampling interpolation output size can be forced to fit any upsampling size
|
314 |
+
# on the fly if necessary.
|
315 |
+
default_overall_up_factor = 2**self.num_upsamplers
|
316 |
+
|
317 |
+
# upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
|
318 |
+
forward_upsample_size = False
|
319 |
+
upsample_size = None
|
320 |
+
|
321 |
+
if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):
|
322 |
+
logger.info("Forward upsample size to force interpolation output size.")
|
323 |
+
forward_upsample_size = True
|
324 |
+
|
325 |
+
# prepare attention_mask
|
326 |
+
if attention_mask is not None:
|
327 |
+
attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
|
328 |
+
attention_mask = attention_mask.unsqueeze(1)
|
329 |
+
|
330 |
+
# center input if necessary
|
331 |
+
if self.config.center_input_sample:
|
332 |
+
sample = 2 * sample - 1.0
|
333 |
+
|
334 |
+
# time
|
335 |
+
timesteps = timestep
|
336 |
+
if not torch.is_tensor(timesteps):
|
337 |
+
# This would be a good case for the `match` statement (Python 3.10+)
|
338 |
+
is_mps = sample.device.type == "mps"
|
339 |
+
if isinstance(timestep, float):
|
340 |
+
dtype = torch.float32 if is_mps else torch.float64
|
341 |
+
else:
|
342 |
+
dtype = torch.int32 if is_mps else torch.int64
|
343 |
+
timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
|
344 |
+
elif len(timesteps.shape) == 0:
|
345 |
+
timesteps = timesteps[None].to(sample.device)
|
346 |
+
|
347 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
348 |
+
timesteps = timesteps.expand(sample.shape[0])
|
349 |
+
|
350 |
+
t_emb = self.time_proj(timesteps)
|
351 |
+
|
352 |
+
# timesteps does not contain any weights and will always return f32 tensors
|
353 |
+
# but time_embedding might actually be running in fp16. so we need to cast here.
|
354 |
+
# there might be better ways to encapsulate this.
|
355 |
+
t_emb = t_emb.to(dtype=self.dtype)
|
356 |
+
emb = self.time_embedding(t_emb)
|
357 |
+
|
358 |
+
if self.class_embedding is not None:
|
359 |
+
if class_labels is None:
|
360 |
+
raise ValueError("class_labels should be provided when num_class_embeds > 0")
|
361 |
+
|
362 |
+
if self.config.class_embed_type == "timestep":
|
363 |
+
class_labels = self.time_proj(class_labels)
|
364 |
+
|
365 |
+
class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
|
366 |
+
emb = emb + class_emb
|
367 |
+
|
368 |
+
# pre-process
|
369 |
+
sample = self.conv_in(sample)
|
370 |
+
|
371 |
+
# down
|
372 |
+
down_block_res_samples = (sample,)
|
373 |
+
features_adapter = self.skeleton_adapter(skeleton)
|
374 |
+
|
375 |
+
for idx, downsample_block in enumerate(self.down_blocks):
|
376 |
+
|
377 |
+
if train_or_sample == 'train':
|
378 |
+
skeleton_feature = None
|
379 |
+
else:
|
380 |
+
skeleton_feature = features_adapter[idx]
|
381 |
+
|
382 |
+
if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
|
383 |
+
sample, res_samples = downsample_block(
|
384 |
+
hidden_states=sample,
|
385 |
+
temb=emb,
|
386 |
+
encoder_hidden_states=encoder_hidden_states,
|
387 |
+
attention_mask=attention_mask,
|
388 |
+
features_adapter=skeleton_feature
|
389 |
+
)
|
390 |
+
else:
|
391 |
+
sample, res_samples = downsample_block(hidden_states=sample, temb=emb, features_adapter=skeleton_feature)
|
392 |
+
|
393 |
+
down_block_res_samples += res_samples
|
394 |
+
|
395 |
+
# mid
|
396 |
+
sample = self.mid_block(
|
397 |
+
sample, emb, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask
|
398 |
+
)
|
399 |
+
|
400 |
+
# up
|
401 |
+
for i, upsample_block in enumerate(self.up_blocks):
|
402 |
+
is_final_block = i == len(self.up_blocks) - 1
|
403 |
+
|
404 |
+
res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
|
405 |
+
down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
|
406 |
+
|
407 |
+
# if we have not reached the final block and need to forward the
|
408 |
+
# upsample size, we do it here
|
409 |
+
if not is_final_block and forward_upsample_size:
|
410 |
+
upsample_size = down_block_res_samples[-1].shape[2:]
|
411 |
+
|
412 |
+
if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
|
413 |
+
sample = upsample_block(
|
414 |
+
hidden_states=sample,
|
415 |
+
temb=emb,
|
416 |
+
res_hidden_states_tuple=res_samples,
|
417 |
+
encoder_hidden_states=encoder_hidden_states,
|
418 |
+
upsample_size=upsample_size,
|
419 |
+
attention_mask=attention_mask,
|
420 |
+
)
|
421 |
+
else:
|
422 |
+
sample = upsample_block(
|
423 |
+
hidden_states=sample, temb=emb, res_hidden_states_tuple=res_samples, upsample_size=upsample_size
|
424 |
+
)
|
425 |
+
# post-process
|
426 |
+
sample = self.conv_norm_out(sample)
|
427 |
+
sample = self.conv_act(sample)
|
428 |
+
sample = self.conv_out(sample)
|
429 |
+
|
430 |
+
if not return_dict:
|
431 |
+
return (sample,)
|
432 |
+
|
433 |
+
return UNet3DConditionOutput(sample=sample)
|
434 |
+
|
435 |
+
@classmethod
|
436 |
+
def from_pretrained_2d(cls, pretrained_model_path, subfolder=None):
|
437 |
+
if subfolder is not None:
|
438 |
+
pretrained_model_path = os.path.join(pretrained_model_path, subfolder)
|
439 |
+
|
440 |
+
config_file = os.path.join(pretrained_model_path, 'config.json')
|
441 |
+
if not os.path.isfile(config_file):
|
442 |
+
raise RuntimeError(f"{config_file} does not exist")
|
443 |
+
with open(config_file, "r") as f:
|
444 |
+
config = json.load(f)
|
445 |
+
config["_class_name"] = cls.__name__
|
446 |
+
config["down_block_types"] = [
|
447 |
+
"CrossAttnDownBlock3D",
|
448 |
+
"CrossAttnDownBlock3D",
|
449 |
+
"CrossAttnDownBlock3D",
|
450 |
+
"DownBlock3D"
|
451 |
+
]
|
452 |
+
config["up_block_types"] = [
|
453 |
+
"UpBlock3D",
|
454 |
+
"CrossAttnUpBlock3D",
|
455 |
+
"CrossAttnUpBlock3D",
|
456 |
+
"CrossAttnUpBlock3D"
|
457 |
+
]
|
458 |
+
|
459 |
+
from diffusers.utils import WEIGHTS_NAME
|
460 |
+
model = cls.from_config(config)
|
461 |
+
model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)
|
462 |
+
if not os.path.isfile(model_file):
|
463 |
+
raise RuntimeError(f"{model_file} does not exist")
|
464 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
465 |
+
for k, v in model.state_dict().items():
|
466 |
+
if '_temp.' in k:
|
467 |
+
state_dict.update({k: v})
|
468 |
+
model.load_state_dict(state_dict, strict=False)
|
469 |
+
|
470 |
+
return model
|
471 |
+
|
472 |
+
|
473 |
+
|
474 |
+
|
475 |
+
class Adapter(nn.Module):
|
476 |
+
def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64, ksize=3, sk=False, use_conv=True):
|
477 |
+
super(Adapter, self).__init__()
|
478 |
+
self.unshuffle = nn.PixelUnshuffle(8)
|
479 |
+
self.channels = channels
|
480 |
+
self.nums_rb = nums_rb
|
481 |
+
self.body = []
|
482 |
+
for i in range(len(channels)):
|
483 |
+
for j in range(nums_rb):
|
484 |
+
if (i!=0) and (j==0):
|
485 |
+
self.body.append(ResnetBlock(channels[i-1], channels[i], down=True, ksize=ksize, sk=sk, use_conv=use_conv))
|
486 |
+
else:
|
487 |
+
self.body.append(ResnetBlock(channels[i], channels[i], down=False, ksize=ksize, sk=sk, use_conv=use_conv))
|
488 |
+
self.body = nn.ModuleList(self.body)
|
489 |
+
self.conv_in = nn.Conv2d(cin,channels[0], 3, 1, 1)
|
490 |
+
|
491 |
+
def forward(self, x):
|
492 |
+
b, t, c, h, w = x.shape
|
493 |
+
x = rearrange(x, 'b t c h w -> (b t) c h w')
|
494 |
+
# unshuffle
|
495 |
+
x = self.unshuffle(x)
|
496 |
+
# extract features
|
497 |
+
features = []
|
498 |
+
x = self.conv_in(x)
|
499 |
+
for i in range(len(self.channels)):
|
500 |
+
for j in range(self.nums_rb):
|
501 |
+
idx = i*self.nums_rb +j
|
502 |
+
x = self.body[idx](x)
|
503 |
+
features.append(x)
|
504 |
+
|
505 |
+
features = [ rearrange(fn, '(b t) c h w -> b c t h w', b=b, t=t) for fn in features]
|
506 |
+
return features
|
507 |
+
|
508 |
+
|
509 |
+
|
510 |
+
class ResnetBlock(nn.Module):
|
511 |
+
def __init__(self, in_c, out_c, down, ksize=3, sk=False, use_conv=True):
|
512 |
+
super().__init__()
|
513 |
+
ps = ksize//2
|
514 |
+
if in_c != out_c or sk==False:
|
515 |
+
self.in_conv = nn.Conv2d(in_c, out_c, ksize, 1, ps)
|
516 |
+
else:
|
517 |
+
# print('n_in')
|
518 |
+
self.in_conv = None
|
519 |
+
self.block1 = nn.Conv2d(out_c, out_c, 3, 1, 1)
|
520 |
+
self.act = nn.ReLU()
|
521 |
+
self.block2 = nn.Conv2d(out_c, out_c, ksize, 1, ps)
|
522 |
+
if sk==False:
|
523 |
+
self.skep = nn.Conv2d(in_c, out_c, ksize, 1, ps)
|
524 |
+
else:
|
525 |
+
self.skep = None
|
526 |
+
|
527 |
+
self.down = down
|
528 |
+
if self.down == True:
|
529 |
+
self.down_opt = Downsample(in_c, use_conv=use_conv)
|
530 |
+
|
531 |
+
def forward(self, x):
|
532 |
+
if self.down == True:
|
533 |
+
x = self.down_opt(x)
|
534 |
+
if self.in_conv is not None: # edit
|
535 |
+
x = self.in_conv(x)
|
536 |
+
|
537 |
+
h = self.block1(x)
|
538 |
+
h = self.act(h)
|
539 |
+
h = self.block2(h)
|
540 |
+
if self.skep is not None:
|
541 |
+
return h + self.skep(x)
|
542 |
+
else:
|
543 |
+
return h + x
|
544 |
+
|
545 |
+
class Downsample(nn.Module):
|
546 |
+
"""
|
547 |
+
A downsampling layer with an optional convolution.
|
548 |
+
:param channels: channels in the inputs and outputs.
|
549 |
+
:param use_conv: a bool determining if a convolution is applied.
|
550 |
+
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
|
551 |
+
downsampling occurs in the inner-two dimensions.
|
552 |
+
"""
|
553 |
+
|
554 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1):
|
555 |
+
super().__init__()
|
556 |
+
self.channels = channels
|
557 |
+
self.out_channels = out_channels or channels
|
558 |
+
self.use_conv = use_conv
|
559 |
+
self.dims = dims
|
560 |
+
stride = 2 if dims != 3 else (1, 2, 2)
|
561 |
+
if use_conv:
|
562 |
+
self.op = conv_nd(
|
563 |
+
dims, self.channels, self.out_channels, 3, stride=stride, padding=padding
|
564 |
+
)
|
565 |
+
else:
|
566 |
+
assert self.channels == self.out_channels
|
567 |
+
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
|
568 |
+
|
569 |
+
def forward(self, x):
|
570 |
+
assert x.shape[1] == self.channels
|
571 |
+
return self.op(x)
|
FollowYourPose/followyourpose/models/unet_blocks.py
ADDED
@@ -0,0 +1,631 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_blocks.py
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
|
6 |
+
from .attention import Transformer3DModel
|
7 |
+
from .resnet import Downsample3D, ResnetBlock3D, Upsample3D
|
8 |
+
|
9 |
+
|
10 |
+
def get_down_block(
|
11 |
+
down_block_type,
|
12 |
+
num_layers,
|
13 |
+
in_channels,
|
14 |
+
out_channels,
|
15 |
+
temb_channels,
|
16 |
+
add_downsample,
|
17 |
+
resnet_eps,
|
18 |
+
resnet_act_fn,
|
19 |
+
attn_num_head_channels,
|
20 |
+
resnet_groups=None,
|
21 |
+
cross_attention_dim=None,
|
22 |
+
downsample_padding=None,
|
23 |
+
dual_cross_attention=False,
|
24 |
+
use_linear_projection=False,
|
25 |
+
only_cross_attention=False,
|
26 |
+
upcast_attention=False,
|
27 |
+
resnet_time_scale_shift="default",
|
28 |
+
):
|
29 |
+
down_block_type = down_block_type[7:] if down_block_type.startswith("UNetRes") else down_block_type
|
30 |
+
if down_block_type == "DownBlock3D":
|
31 |
+
return DownBlock3D(
|
32 |
+
num_layers=num_layers,
|
33 |
+
in_channels=in_channels,
|
34 |
+
out_channels=out_channels,
|
35 |
+
temb_channels=temb_channels,
|
36 |
+
add_downsample=add_downsample,
|
37 |
+
resnet_eps=resnet_eps,
|
38 |
+
resnet_act_fn=resnet_act_fn,
|
39 |
+
resnet_groups=resnet_groups,
|
40 |
+
downsample_padding=downsample_padding,
|
41 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
42 |
+
)
|
43 |
+
elif down_block_type == "CrossAttnDownBlock3D":
|
44 |
+
if cross_attention_dim is None:
|
45 |
+
raise ValueError("cross_attention_dim must be specified for CrossAttnDownBlock3D")
|
46 |
+
return CrossAttnDownBlock3D(
|
47 |
+
num_layers=num_layers,
|
48 |
+
in_channels=in_channels,
|
49 |
+
out_channels=out_channels,
|
50 |
+
temb_channels=temb_channels,
|
51 |
+
add_downsample=add_downsample,
|
52 |
+
resnet_eps=resnet_eps,
|
53 |
+
resnet_act_fn=resnet_act_fn,
|
54 |
+
resnet_groups=resnet_groups,
|
55 |
+
downsample_padding=downsample_padding,
|
56 |
+
cross_attention_dim=cross_attention_dim,
|
57 |
+
attn_num_head_channels=attn_num_head_channels,
|
58 |
+
dual_cross_attention=dual_cross_attention,
|
59 |
+
use_linear_projection=use_linear_projection,
|
60 |
+
only_cross_attention=only_cross_attention,
|
61 |
+
upcast_attention=upcast_attention,
|
62 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
63 |
+
)
|
64 |
+
raise ValueError(f"{down_block_type} does not exist.")
|
65 |
+
|
66 |
+
|
67 |
+
def get_up_block(
|
68 |
+
up_block_type,
|
69 |
+
num_layers,
|
70 |
+
in_channels,
|
71 |
+
out_channels,
|
72 |
+
prev_output_channel,
|
73 |
+
temb_channels,
|
74 |
+
add_upsample,
|
75 |
+
resnet_eps,
|
76 |
+
resnet_act_fn,
|
77 |
+
attn_num_head_channels,
|
78 |
+
resnet_groups=None,
|
79 |
+
cross_attention_dim=None,
|
80 |
+
dual_cross_attention=False,
|
81 |
+
use_linear_projection=False,
|
82 |
+
only_cross_attention=False,
|
83 |
+
upcast_attention=False,
|
84 |
+
resnet_time_scale_shift="default",
|
85 |
+
):
|
86 |
+
up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
|
87 |
+
if up_block_type == "UpBlock3D":
|
88 |
+
return UpBlock3D(
|
89 |
+
num_layers=num_layers,
|
90 |
+
in_channels=in_channels,
|
91 |
+
out_channels=out_channels,
|
92 |
+
prev_output_channel=prev_output_channel,
|
93 |
+
temb_channels=temb_channels,
|
94 |
+
add_upsample=add_upsample,
|
95 |
+
resnet_eps=resnet_eps,
|
96 |
+
resnet_act_fn=resnet_act_fn,
|
97 |
+
resnet_groups=resnet_groups,
|
98 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
99 |
+
)
|
100 |
+
elif up_block_type == "CrossAttnUpBlock3D":
|
101 |
+
if cross_attention_dim is None:
|
102 |
+
raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock3D")
|
103 |
+
return CrossAttnUpBlock3D(
|
104 |
+
num_layers=num_layers,
|
105 |
+
in_channels=in_channels,
|
106 |
+
out_channels=out_channels,
|
107 |
+
prev_output_channel=prev_output_channel,
|
108 |
+
temb_channels=temb_channels,
|
109 |
+
add_upsample=add_upsample,
|
110 |
+
resnet_eps=resnet_eps,
|
111 |
+
resnet_act_fn=resnet_act_fn,
|
112 |
+
resnet_groups=resnet_groups,
|
113 |
+
cross_attention_dim=cross_attention_dim,
|
114 |
+
attn_num_head_channels=attn_num_head_channels,
|
115 |
+
dual_cross_attention=dual_cross_attention,
|
116 |
+
use_linear_projection=use_linear_projection,
|
117 |
+
only_cross_attention=only_cross_attention,
|
118 |
+
upcast_attention=upcast_attention,
|
119 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
120 |
+
)
|
121 |
+
raise ValueError(f"{up_block_type} does not exist.")
|
122 |
+
|
123 |
+
|
124 |
+
class UNetMidBlock3DCrossAttn(nn.Module):
|
125 |
+
def __init__(
|
126 |
+
self,
|
127 |
+
in_channels: int,
|
128 |
+
temb_channels: int,
|
129 |
+
dropout: float = 0.0,
|
130 |
+
num_layers: int = 1,
|
131 |
+
resnet_eps: float = 1e-6,
|
132 |
+
resnet_time_scale_shift: str = "default",
|
133 |
+
resnet_act_fn: str = "swish",
|
134 |
+
resnet_groups: int = 32,
|
135 |
+
resnet_pre_norm: bool = True,
|
136 |
+
attn_num_head_channels=1,
|
137 |
+
output_scale_factor=1.0,
|
138 |
+
cross_attention_dim=1280,
|
139 |
+
dual_cross_attention=False,
|
140 |
+
use_linear_projection=False,
|
141 |
+
upcast_attention=False,
|
142 |
+
):
|
143 |
+
super().__init__()
|
144 |
+
|
145 |
+
self.has_cross_attention = True
|
146 |
+
self.attn_num_head_channels = attn_num_head_channels
|
147 |
+
resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
|
148 |
+
|
149 |
+
# there is always at least one resnet
|
150 |
+
resnets = [
|
151 |
+
ResnetBlock3D(
|
152 |
+
in_channels=in_channels,
|
153 |
+
out_channels=in_channels,
|
154 |
+
temb_channels=temb_channels,
|
155 |
+
eps=resnet_eps,
|
156 |
+
groups=resnet_groups,
|
157 |
+
dropout=dropout,
|
158 |
+
time_embedding_norm=resnet_time_scale_shift,
|
159 |
+
non_linearity=resnet_act_fn,
|
160 |
+
output_scale_factor=output_scale_factor,
|
161 |
+
pre_norm=resnet_pre_norm,
|
162 |
+
)
|
163 |
+
]
|
164 |
+
attentions = []
|
165 |
+
|
166 |
+
for _ in range(num_layers):
|
167 |
+
if dual_cross_attention:
|
168 |
+
raise NotImplementedError
|
169 |
+
attentions.append(
|
170 |
+
Transformer3DModel(
|
171 |
+
attn_num_head_channels,
|
172 |
+
in_channels // attn_num_head_channels,
|
173 |
+
in_channels=in_channels,
|
174 |
+
num_layers=1,
|
175 |
+
cross_attention_dim=cross_attention_dim,
|
176 |
+
norm_num_groups=resnet_groups,
|
177 |
+
use_linear_projection=use_linear_projection,
|
178 |
+
upcast_attention=upcast_attention,
|
179 |
+
)
|
180 |
+
)
|
181 |
+
resnets.append(
|
182 |
+
ResnetBlock3D(
|
183 |
+
in_channels=in_channels,
|
184 |
+
out_channels=in_channels,
|
185 |
+
temb_channels=temb_channels,
|
186 |
+
eps=resnet_eps,
|
187 |
+
groups=resnet_groups,
|
188 |
+
dropout=dropout,
|
189 |
+
time_embedding_norm=resnet_time_scale_shift,
|
190 |
+
non_linearity=resnet_act_fn,
|
191 |
+
output_scale_factor=output_scale_factor,
|
192 |
+
pre_norm=resnet_pre_norm,
|
193 |
+
)
|
194 |
+
)
|
195 |
+
|
196 |
+
self.attentions = nn.ModuleList(attentions)
|
197 |
+
self.resnets = nn.ModuleList(resnets)
|
198 |
+
|
199 |
+
def forward(self, hidden_states, temb=None, encoder_hidden_states=None, attention_mask=None):
|
200 |
+
hidden_states = self.resnets[0](hidden_states, temb)
|
201 |
+
for attn, resnet in zip(self.attentions, self.resnets[1:]):
|
202 |
+
hidden_states = attn(hidden_states, encoder_hidden_states=encoder_hidden_states).sample
|
203 |
+
hidden_states = resnet(hidden_states, temb)
|
204 |
+
|
205 |
+
return hidden_states
|
206 |
+
|
207 |
+
|
208 |
+
class CrossAttnDownBlock3D(nn.Module):
|
209 |
+
def __init__(
|
210 |
+
self,
|
211 |
+
in_channels: int,
|
212 |
+
out_channels: int,
|
213 |
+
temb_channels: int,
|
214 |
+
dropout: float = 0.0,
|
215 |
+
num_layers: int = 1,
|
216 |
+
resnet_eps: float = 1e-6,
|
217 |
+
resnet_time_scale_shift: str = "default",
|
218 |
+
resnet_act_fn: str = "swish",
|
219 |
+
resnet_groups: int = 32,
|
220 |
+
resnet_pre_norm: bool = True,
|
221 |
+
attn_num_head_channels=1,
|
222 |
+
cross_attention_dim=1280,
|
223 |
+
output_scale_factor=1.0,
|
224 |
+
downsample_padding=1,
|
225 |
+
add_downsample=True,
|
226 |
+
dual_cross_attention=False,
|
227 |
+
use_linear_projection=False,
|
228 |
+
only_cross_attention=False,
|
229 |
+
upcast_attention=False,
|
230 |
+
):
|
231 |
+
super().__init__()
|
232 |
+
resnets = []
|
233 |
+
attentions = []
|
234 |
+
|
235 |
+
self.has_cross_attention = True
|
236 |
+
self.attn_num_head_channels = attn_num_head_channels
|
237 |
+
|
238 |
+
for i in range(num_layers):
|
239 |
+
in_channels = in_channels if i == 0 else out_channels
|
240 |
+
resnets.append(
|
241 |
+
ResnetBlock3D(
|
242 |
+
in_channels=in_channels,
|
243 |
+
out_channels=out_channels,
|
244 |
+
temb_channels=temb_channels,
|
245 |
+
eps=resnet_eps,
|
246 |
+
groups=resnet_groups,
|
247 |
+
dropout=dropout,
|
248 |
+
time_embedding_norm=resnet_time_scale_shift,
|
249 |
+
non_linearity=resnet_act_fn,
|
250 |
+
output_scale_factor=output_scale_factor,
|
251 |
+
pre_norm=resnet_pre_norm,
|
252 |
+
)
|
253 |
+
)
|
254 |
+
if dual_cross_attention:
|
255 |
+
raise NotImplementedError
|
256 |
+
attentions.append(
|
257 |
+
Transformer3DModel(
|
258 |
+
attn_num_head_channels,
|
259 |
+
out_channels // attn_num_head_channels,
|
260 |
+
in_channels=out_channels,
|
261 |
+
num_layers=1,
|
262 |
+
cross_attention_dim=cross_attention_dim,
|
263 |
+
norm_num_groups=resnet_groups,
|
264 |
+
use_linear_projection=use_linear_projection,
|
265 |
+
only_cross_attention=only_cross_attention,
|
266 |
+
upcast_attention=upcast_attention,
|
267 |
+
)
|
268 |
+
)
|
269 |
+
self.attentions = nn.ModuleList(attentions)
|
270 |
+
self.resnets = nn.ModuleList(resnets)
|
271 |
+
|
272 |
+
if add_downsample:
|
273 |
+
self.downsamplers = nn.ModuleList(
|
274 |
+
[
|
275 |
+
Downsample3D(
|
276 |
+
out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
|
277 |
+
)
|
278 |
+
]
|
279 |
+
)
|
280 |
+
else:
|
281 |
+
self.downsamplers = None
|
282 |
+
|
283 |
+
self.gradient_checkpointing = False
|
284 |
+
|
285 |
+
def forward(self, hidden_states, temb=None, encoder_hidden_states=None, attention_mask=None, features_adapter=None):
|
286 |
+
output_states = ()
|
287 |
+
idx = 1
|
288 |
+
for resnet, attn in zip(self.resnets, self.attentions):
|
289 |
+
if self.training and self.gradient_checkpointing:
|
290 |
+
|
291 |
+
def create_custom_forward(module, return_dict=None):
|
292 |
+
def custom_forward(*inputs):
|
293 |
+
if return_dict is not None:
|
294 |
+
return module(*inputs, return_dict=return_dict)
|
295 |
+
else:
|
296 |
+
return module(*inputs)
|
297 |
+
|
298 |
+
return custom_forward
|
299 |
+
|
300 |
+
hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
|
301 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
302 |
+
create_custom_forward(attn, return_dict=False),
|
303 |
+
hidden_states,
|
304 |
+
encoder_hidden_states,
|
305 |
+
)[0]
|
306 |
+
else:
|
307 |
+
hidden_states = resnet(hidden_states, temb)
|
308 |
+
hidden_states = attn(hidden_states, encoder_hidden_states=encoder_hidden_states).sample
|
309 |
+
if ((idx+1)%3 == 0) and features_adapter is not None and len(features_adapter):
|
310 |
+
hidden_states = hidden_states + features_adapter
|
311 |
+
idx = idx + 1
|
312 |
+
|
313 |
+
output_states += (hidden_states,)
|
314 |
+
|
315 |
+
if self.downsamplers is not None:
|
316 |
+
for downsampler in self.downsamplers:
|
317 |
+
hidden_states = downsampler(hidden_states)
|
318 |
+
|
319 |
+
output_states += (hidden_states,)
|
320 |
+
|
321 |
+
return hidden_states, output_states
|
322 |
+
|
323 |
+
|
324 |
+
class DownBlock3D(nn.Module):
|
325 |
+
def __init__(
|
326 |
+
self,
|
327 |
+
in_channels: int,
|
328 |
+
out_channels: int,
|
329 |
+
temb_channels: int,
|
330 |
+
dropout: float = 0.0,
|
331 |
+
num_layers: int = 1,
|
332 |
+
resnet_eps: float = 1e-6,
|
333 |
+
resnet_time_scale_shift: str = "default",
|
334 |
+
resnet_act_fn: str = "swish",
|
335 |
+
resnet_groups: int = 32,
|
336 |
+
resnet_pre_norm: bool = True,
|
337 |
+
output_scale_factor=1.0,
|
338 |
+
add_downsample=True,
|
339 |
+
downsample_padding=1,
|
340 |
+
):
|
341 |
+
super().__init__()
|
342 |
+
resnets = []
|
343 |
+
|
344 |
+
for i in range(num_layers):
|
345 |
+
in_channels = in_channels if i == 0 else out_channels
|
346 |
+
resnets.append(
|
347 |
+
ResnetBlock3D(
|
348 |
+
in_channels=in_channels,
|
349 |
+
out_channels=out_channels,
|
350 |
+
temb_channels=temb_channels,
|
351 |
+
eps=resnet_eps,
|
352 |
+
groups=resnet_groups,
|
353 |
+
dropout=dropout,
|
354 |
+
time_embedding_norm=resnet_time_scale_shift,
|
355 |
+
non_linearity=resnet_act_fn,
|
356 |
+
output_scale_factor=output_scale_factor,
|
357 |
+
pre_norm=resnet_pre_norm,
|
358 |
+
)
|
359 |
+
)
|
360 |
+
|
361 |
+
self.resnets = nn.ModuleList(resnets)
|
362 |
+
|
363 |
+
if add_downsample:
|
364 |
+
self.downsamplers = nn.ModuleList(
|
365 |
+
[
|
366 |
+
Downsample3D(
|
367 |
+
out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
|
368 |
+
)
|
369 |
+
]
|
370 |
+
)
|
371 |
+
else:
|
372 |
+
self.downsamplers = None
|
373 |
+
|
374 |
+
self.gradient_checkpointing = False
|
375 |
+
|
376 |
+
def forward(self, hidden_states, temb=None, features_adapter=None):
|
377 |
+
output_states = ()
|
378 |
+
idx = 1
|
379 |
+
for resnet in self.resnets:
|
380 |
+
if self.training and self.gradient_checkpointing:
|
381 |
+
|
382 |
+
def create_custom_forward(module):
|
383 |
+
def custom_forward(*inputs):
|
384 |
+
return module(*inputs)
|
385 |
+
|
386 |
+
return custom_forward
|
387 |
+
|
388 |
+
hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
|
389 |
+
else:
|
390 |
+
hidden_states = resnet(hidden_states, temb)
|
391 |
+
if ((idx+1)%3 == 0) and features_adapter is not None and len(features_adapter):
|
392 |
+
hidden_states = hidden_states + features_adapter
|
393 |
+
idx = idx + 1
|
394 |
+
|
395 |
+
output_states += (hidden_states,)
|
396 |
+
|
397 |
+
if self.downsamplers is not None:
|
398 |
+
for downsampler in self.downsamplers:
|
399 |
+
hidden_states = downsampler(hidden_states)
|
400 |
+
|
401 |
+
output_states += (hidden_states,)
|
402 |
+
|
403 |
+
return hidden_states, output_states
|
404 |
+
|
405 |
+
|
406 |
+
class CrossAttnUpBlock3D(nn.Module):
|
407 |
+
def __init__(
|
408 |
+
self,
|
409 |
+
in_channels: int,
|
410 |
+
out_channels: int,
|
411 |
+
prev_output_channel: int,
|
412 |
+
temb_channels: int,
|
413 |
+
dropout: float = 0.0,
|
414 |
+
num_layers: int = 1,
|
415 |
+
resnet_eps: float = 1e-6,
|
416 |
+
resnet_time_scale_shift: str = "default",
|
417 |
+
resnet_act_fn: str = "swish",
|
418 |
+
resnet_groups: int = 32,
|
419 |
+
resnet_pre_norm: bool = True,
|
420 |
+
attn_num_head_channels=1,
|
421 |
+
cross_attention_dim=1280,
|
422 |
+
output_scale_factor=1.0,
|
423 |
+
add_upsample=True,
|
424 |
+
dual_cross_attention=False,
|
425 |
+
use_linear_projection=False,
|
426 |
+
only_cross_attention=False,
|
427 |
+
upcast_attention=False,
|
428 |
+
):
|
429 |
+
super().__init__()
|
430 |
+
resnets = []
|
431 |
+
attentions = []
|
432 |
+
|
433 |
+
self.has_cross_attention = True
|
434 |
+
self.attn_num_head_channels = attn_num_head_channels
|
435 |
+
|
436 |
+
for i in range(num_layers):
|
437 |
+
res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
|
438 |
+
resnet_in_channels = prev_output_channel if i == 0 else out_channels
|
439 |
+
|
440 |
+
resnets.append(
|
441 |
+
ResnetBlock3D(
|
442 |
+
in_channels=resnet_in_channels + res_skip_channels,
|
443 |
+
out_channels=out_channels,
|
444 |
+
temb_channels=temb_channels,
|
445 |
+
eps=resnet_eps,
|
446 |
+
groups=resnet_groups,
|
447 |
+
dropout=dropout,
|
448 |
+
time_embedding_norm=resnet_time_scale_shift,
|
449 |
+
non_linearity=resnet_act_fn,
|
450 |
+
output_scale_factor=output_scale_factor,
|
451 |
+
pre_norm=resnet_pre_norm,
|
452 |
+
)
|
453 |
+
)
|
454 |
+
if dual_cross_attention:
|
455 |
+
raise NotImplementedError
|
456 |
+
attentions.append(
|
457 |
+
Transformer3DModel(
|
458 |
+
attn_num_head_channels,
|
459 |
+
out_channels // attn_num_head_channels,
|
460 |
+
in_channels=out_channels,
|
461 |
+
num_layers=1,
|
462 |
+
cross_attention_dim=cross_attention_dim,
|
463 |
+
norm_num_groups=resnet_groups,
|
464 |
+
use_linear_projection=use_linear_projection,
|
465 |
+
only_cross_attention=only_cross_attention,
|
466 |
+
upcast_attention=upcast_attention,
|
467 |
+
)
|
468 |
+
)
|
469 |
+
|
470 |
+
self.attentions = nn.ModuleList(attentions)
|
471 |
+
self.resnets = nn.ModuleList(resnets)
|
472 |
+
|
473 |
+
if add_upsample:
|
474 |
+
self.upsamplers = nn.ModuleList([Upsample3D(out_channels, use_conv=True, out_channels=out_channels)])
|
475 |
+
else:
|
476 |
+
self.upsamplers = None
|
477 |
+
|
478 |
+
self.gradient_checkpointing = False
|
479 |
+
|
480 |
+
def forward(
|
481 |
+
self,
|
482 |
+
hidden_states,
|
483 |
+
res_hidden_states_tuple,
|
484 |
+
temb=None,
|
485 |
+
encoder_hidden_states=None,
|
486 |
+
upsample_size=None,
|
487 |
+
attention_mask=None,
|
488 |
+
):
|
489 |
+
for resnet, attn in zip(self.resnets, self.attentions):
|
490 |
+
# pop res hidden states
|
491 |
+
res_hidden_states = res_hidden_states_tuple[-1]
|
492 |
+
res_hidden_states_tuple = res_hidden_states_tuple[:-1]
|
493 |
+
hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
|
494 |
+
|
495 |
+
if self.training and self.gradient_checkpointing:
|
496 |
+
|
497 |
+
def create_custom_forward(module, return_dict=None):
|
498 |
+
def custom_forward(*inputs):
|
499 |
+
if return_dict is not None:
|
500 |
+
return module(*inputs, return_dict=return_dict)
|
501 |
+
else:
|
502 |
+
return module(*inputs)
|
503 |
+
|
504 |
+
return custom_forward
|
505 |
+
|
506 |
+
hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
|
507 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
508 |
+
create_custom_forward(attn, return_dict=False),
|
509 |
+
hidden_states,
|
510 |
+
encoder_hidden_states,
|
511 |
+
)[0]
|
512 |
+
else:
|
513 |
+
hidden_states = resnet(hidden_states, temb)
|
514 |
+
hidden_states = attn(hidden_states, encoder_hidden_states=encoder_hidden_states).sample
|
515 |
+
|
516 |
+
if self.upsamplers is not None:
|
517 |
+
for upsampler in self.upsamplers:
|
518 |
+
hidden_states = upsampler(hidden_states, upsample_size)
|
519 |
+
|
520 |
+
return hidden_states
|
521 |
+
|
522 |
+
|
523 |
+
class UpBlock3D(nn.Module):
|
524 |
+
def __init__(
|
525 |
+
self,
|
526 |
+
in_channels: int,
|
527 |
+
prev_output_channel: int,
|
528 |
+
out_channels: int,
|
529 |
+
temb_channels: int,
|
530 |
+
dropout: float = 0.0,
|
531 |
+
num_layers: int = 1,
|
532 |
+
resnet_eps: float = 1e-6,
|
533 |
+
resnet_time_scale_shift: str = "default",
|
534 |
+
resnet_act_fn: str = "swish",
|
535 |
+
resnet_groups: int = 32,
|
536 |
+
resnet_pre_norm: bool = True,
|
537 |
+
output_scale_factor=1.0,
|
538 |
+
add_upsample=True,
|
539 |
+
):
|
540 |
+
super().__init__()
|
541 |
+
resnets = []
|
542 |
+
|
543 |
+
for i in range(num_layers):
|
544 |
+
res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
|
545 |
+
resnet_in_channels = prev_output_channel if i == 0 else out_channels
|
546 |
+
|
547 |
+
resnets.append(
|
548 |
+
ResnetBlock3D(
|
549 |
+
in_channels=resnet_in_channels + res_skip_channels,
|
550 |
+
out_channels=out_channels,
|
551 |
+
temb_channels=temb_channels,
|
552 |
+
eps=resnet_eps,
|
553 |
+
groups=resnet_groups,
|
554 |
+
dropout=dropout,
|
555 |
+
time_embedding_norm=resnet_time_scale_shift,
|
556 |
+
non_linearity=resnet_act_fn,
|
557 |
+
output_scale_factor=output_scale_factor,
|
558 |
+
pre_norm=resnet_pre_norm,
|
559 |
+
)
|
560 |
+
)
|
561 |
+
|
562 |
+
self.resnets = nn.ModuleList(resnets)
|
563 |
+
|
564 |
+
if add_upsample:
|
565 |
+
self.upsamplers = nn.ModuleList([Upsample3D(out_channels, use_conv=True, out_channels=out_channels)])
|
566 |
+
else:
|
567 |
+
self.upsamplers = None
|
568 |
+
|
569 |
+
self.gradient_checkpointing = False
|
570 |
+
|
571 |
+
def forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None):
|
572 |
+
for resnet in self.resnets:
|
573 |
+
# pop res hidden states
|
574 |
+
res_hidden_states = res_hidden_states_tuple[-1]
|
575 |
+
res_hidden_states_tuple = res_hidden_states_tuple[:-1]
|
576 |
+
hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
|
577 |
+
|
578 |
+
if self.training and self.gradient_checkpointing:
|
579 |
+
|
580 |
+
def create_custom_forward(module):
|
581 |
+
def custom_forward(*inputs):
|
582 |
+
return module(*inputs)
|
583 |
+
|
584 |
+
return custom_forward
|
585 |
+
|
586 |
+
hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
|
587 |
+
else:
|
588 |
+
hidden_states = resnet(hidden_states, temb)
|
589 |
+
|
590 |
+
if self.upsamplers is not None:
|
591 |
+
for upsampler in self.upsamplers:
|
592 |
+
hidden_states = upsampler(hidden_states, upsample_size)
|
593 |
+
|
594 |
+
return hidden_states
|
595 |
+
|
596 |
+
|
597 |
+
|
598 |
+
|
599 |
+
def conv_nd(dims, in_channels, out_channels, kernel_size, **kwargs):
|
600 |
+
"""
|
601 |
+
Create a 1D, 2D, or 3D convolution module.
|
602 |
+
"""
|
603 |
+
if dims == 1:
|
604 |
+
return nn.Conv1d(in_channels, out_channels, kernel_size, **kwargs)
|
605 |
+
elif dims == 2:
|
606 |
+
return nn.Conv2d(in_channels, out_channels, kernel_size, **kwargs)
|
607 |
+
elif dims == 3:
|
608 |
+
if isinstance(kernel_size, int):
|
609 |
+
kernel_size = (1, *((kernel_size,) * 2))
|
610 |
+
if 'stride' in kwargs.keys():
|
611 |
+
if isinstance(kwargs['stride'], int):
|
612 |
+
kwargs['stride'] = (1, *((kwargs['stride'],) * 2))
|
613 |
+
if 'padding' in kwargs.keys():
|
614 |
+
if isinstance(kwargs['padding'], int):
|
615 |
+
kwargs['padding'] = (0, *((kwargs['padding'],) * 2))
|
616 |
+
return nn.Conv3d(in_channels, out_channels, kernel_size, **kwargs)
|
617 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
618 |
+
|
619 |
+
|
620 |
+
|
621 |
+
def avg_pool_nd(dims, *args, **kwargs):
|
622 |
+
"""
|
623 |
+
Create a 1D, 2D, or 3D average pooling module.
|
624 |
+
"""
|
625 |
+
if dims == 1:
|
626 |
+
return nn.AvgPool1d(*args, **kwargs)
|
627 |
+
elif dims == 2:
|
628 |
+
return nn.AvgPool2d(*args, **kwargs)
|
629 |
+
elif dims == 3:
|
630 |
+
return nn.AvgPool3d(*args, **kwargs)
|
631 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
FollowYourPose/followyourpose/pipelines/pipeline_followyourpose.py
ADDED
@@ -0,0 +1,442 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py
|
2 |
+
|
3 |
+
import inspect
|
4 |
+
from typing import Callable, List, Optional, Union
|
5 |
+
from dataclasses import dataclass
|
6 |
+
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
|
10 |
+
from diffusers.utils import is_accelerate_available
|
11 |
+
from packaging import version
|
12 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
13 |
+
|
14 |
+
from diffusers.configuration_utils import FrozenDict
|
15 |
+
from diffusers.models import AutoencoderKL
|
16 |
+
from diffusers.pipeline_utils import DiffusionPipeline
|
17 |
+
from diffusers.schedulers import (
|
18 |
+
DDIMScheduler,
|
19 |
+
DPMSolverMultistepScheduler,
|
20 |
+
EulerAncestralDiscreteScheduler,
|
21 |
+
EulerDiscreteScheduler,
|
22 |
+
LMSDiscreteScheduler,
|
23 |
+
PNDMScheduler,
|
24 |
+
)
|
25 |
+
from diffusers.utils import deprecate, logging, BaseOutput
|
26 |
+
|
27 |
+
from einops import rearrange
|
28 |
+
|
29 |
+
from ..models.unet import UNet3DConditionModel
|
30 |
+
from torchvision import transforms
|
31 |
+
import torchvision.transforms._transforms_video as transforms_video
|
32 |
+
import decord
|
33 |
+
|
34 |
+
|
35 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
36 |
+
|
37 |
+
|
38 |
+
@dataclass
|
39 |
+
class FollowYourPosePipelineOutput(BaseOutput):
|
40 |
+
videos: Union[torch.Tensor, np.ndarray]
|
41 |
+
|
42 |
+
|
43 |
+
class FollowYourPosePipeline(DiffusionPipeline):
|
44 |
+
_optional_components = []
|
45 |
+
|
46 |
+
def __init__(
|
47 |
+
self,
|
48 |
+
vae: AutoencoderKL,
|
49 |
+
text_encoder: CLIPTextModel,
|
50 |
+
tokenizer: CLIPTokenizer,
|
51 |
+
unet: UNet3DConditionModel,
|
52 |
+
scheduler: Union[
|
53 |
+
DDIMScheduler,
|
54 |
+
PNDMScheduler,
|
55 |
+
LMSDiscreteScheduler,
|
56 |
+
EulerDiscreteScheduler,
|
57 |
+
EulerAncestralDiscreteScheduler,
|
58 |
+
DPMSolverMultistepScheduler,
|
59 |
+
],
|
60 |
+
):
|
61 |
+
super().__init__()
|
62 |
+
|
63 |
+
if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
|
64 |
+
deprecation_message = (
|
65 |
+
f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
|
66 |
+
f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
|
67 |
+
"to update the config accordingly as leaving `steps_offset` might led to incorrect results"
|
68 |
+
" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
|
69 |
+
" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
|
70 |
+
" file"
|
71 |
+
)
|
72 |
+
deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
|
73 |
+
new_config = dict(scheduler.config)
|
74 |
+
new_config["steps_offset"] = 1
|
75 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
76 |
+
|
77 |
+
if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
|
78 |
+
deprecation_message = (
|
79 |
+
f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
|
80 |
+
" `clip_sample` should be set to False in the configuration file. Please make sure to update the"
|
81 |
+
" config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
|
82 |
+
" future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
|
83 |
+
" nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
|
84 |
+
)
|
85 |
+
deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
|
86 |
+
new_config = dict(scheduler.config)
|
87 |
+
new_config["clip_sample"] = False
|
88 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
89 |
+
|
90 |
+
is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
|
91 |
+
version.parse(unet.config._diffusers_version).base_version
|
92 |
+
) < version.parse("0.9.0.dev0")
|
93 |
+
is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
|
94 |
+
if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
|
95 |
+
deprecation_message = (
|
96 |
+
"The configuration file of the unet has set the default `sample_size` to smaller than"
|
97 |
+
" 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
|
98 |
+
" following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
|
99 |
+
" CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
|
100 |
+
" \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
|
101 |
+
" configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
|
102 |
+
" in the config might lead to incorrect results in future versions. If you have downloaded this"
|
103 |
+
" checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
|
104 |
+
" the `unet/config.json` file"
|
105 |
+
)
|
106 |
+
deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
|
107 |
+
new_config = dict(unet.config)
|
108 |
+
new_config["sample_size"] = 64
|
109 |
+
unet._internal_dict = FrozenDict(new_config)
|
110 |
+
|
111 |
+
self.register_modules(
|
112 |
+
vae=vae,
|
113 |
+
text_encoder=text_encoder,
|
114 |
+
tokenizer=tokenizer,
|
115 |
+
unet=unet,
|
116 |
+
scheduler=scheduler,
|
117 |
+
)
|
118 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
119 |
+
|
120 |
+
def enable_vae_slicing(self):
|
121 |
+
self.vae.enable_slicing()
|
122 |
+
|
123 |
+
def disable_vae_slicing(self):
|
124 |
+
self.vae.disable_slicing()
|
125 |
+
|
126 |
+
def enable_sequential_cpu_offload(self, gpu_id=0):
|
127 |
+
if is_accelerate_available():
|
128 |
+
from accelerate import cpu_offload
|
129 |
+
else:
|
130 |
+
raise ImportError("Please install accelerate via `pip install accelerate`")
|
131 |
+
|
132 |
+
device = torch.device(f"cuda:{gpu_id}")
|
133 |
+
|
134 |
+
for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
|
135 |
+
if cpu_offloaded_model is not None:
|
136 |
+
cpu_offload(cpu_offloaded_model, device)
|
137 |
+
|
138 |
+
|
139 |
+
@property
|
140 |
+
def _execution_device(self):
|
141 |
+
if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
|
142 |
+
return self.device
|
143 |
+
for module in self.unet.modules():
|
144 |
+
if (
|
145 |
+
hasattr(module, "_hf_hook")
|
146 |
+
and hasattr(module._hf_hook, "execution_device")
|
147 |
+
and module._hf_hook.execution_device is not None
|
148 |
+
):
|
149 |
+
return torch.device(module._hf_hook.execution_device)
|
150 |
+
return self.device
|
151 |
+
|
152 |
+
def _encode_prompt(self, prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt):
|
153 |
+
batch_size = len(prompt) if isinstance(prompt, list) else 1
|
154 |
+
|
155 |
+
text_inputs = self.tokenizer(
|
156 |
+
prompt,
|
157 |
+
padding="max_length",
|
158 |
+
max_length=self.tokenizer.model_max_length,
|
159 |
+
truncation=True,
|
160 |
+
return_tensors="pt",
|
161 |
+
)
|
162 |
+
text_input_ids = text_inputs.input_ids
|
163 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
164 |
+
|
165 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
166 |
+
removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
|
167 |
+
logger.warning(
|
168 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
169 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
170 |
+
)
|
171 |
+
|
172 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
173 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
174 |
+
else:
|
175 |
+
attention_mask = None
|
176 |
+
|
177 |
+
text_embeddings = self.text_encoder(
|
178 |
+
text_input_ids.to(device),
|
179 |
+
attention_mask=attention_mask,
|
180 |
+
)
|
181 |
+
text_embeddings = text_embeddings[0]
|
182 |
+
|
183 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
184 |
+
bs_embed, seq_len, _ = text_embeddings.shape
|
185 |
+
text_embeddings = text_embeddings.repeat(1, num_videos_per_prompt, 1)
|
186 |
+
text_embeddings = text_embeddings.view(bs_embed * num_videos_per_prompt, seq_len, -1)
|
187 |
+
|
188 |
+
# get unconditional embeddings for classifier free guidance
|
189 |
+
if do_classifier_free_guidance:
|
190 |
+
uncond_tokens: List[str]
|
191 |
+
if negative_prompt is None:
|
192 |
+
uncond_tokens = [""] * batch_size
|
193 |
+
elif type(prompt) is not type(negative_prompt):
|
194 |
+
raise TypeError(
|
195 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
196 |
+
f" {type(prompt)}."
|
197 |
+
)
|
198 |
+
elif isinstance(negative_prompt, str):
|
199 |
+
uncond_tokens = [negative_prompt]
|
200 |
+
elif batch_size != len(negative_prompt):
|
201 |
+
raise ValueError(
|
202 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
203 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
204 |
+
" the batch size of `prompt`."
|
205 |
+
)
|
206 |
+
else:
|
207 |
+
uncond_tokens = negative_prompt
|
208 |
+
|
209 |
+
max_length = text_input_ids.shape[-1]
|
210 |
+
uncond_input = self.tokenizer(
|
211 |
+
uncond_tokens,
|
212 |
+
padding="max_length",
|
213 |
+
max_length=max_length,
|
214 |
+
truncation=True,
|
215 |
+
return_tensors="pt",
|
216 |
+
)
|
217 |
+
|
218 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
219 |
+
attention_mask = uncond_input.attention_mask.to(device)
|
220 |
+
else:
|
221 |
+
attention_mask = None
|
222 |
+
|
223 |
+
uncond_embeddings = self.text_encoder(
|
224 |
+
uncond_input.input_ids.to(device),
|
225 |
+
attention_mask=attention_mask,
|
226 |
+
)
|
227 |
+
uncond_embeddings = uncond_embeddings[0]
|
228 |
+
|
229 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
230 |
+
seq_len = uncond_embeddings.shape[1]
|
231 |
+
uncond_embeddings = uncond_embeddings.repeat(1, num_videos_per_prompt, 1)
|
232 |
+
uncond_embeddings = uncond_embeddings.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
233 |
+
|
234 |
+
# For classifier free guidance, we need to do two forward passes.
|
235 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
236 |
+
# to avoid doing two forward passes
|
237 |
+
text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
|
238 |
+
|
239 |
+
return text_embeddings
|
240 |
+
|
241 |
+
def decode_latents(self, latents):
|
242 |
+
video_length = latents.shape[2]
|
243 |
+
latents = 1 / 0.18215 * latents
|
244 |
+
latents = rearrange(latents, "b c f h w -> (b f) c h w")
|
245 |
+
video = self.vae.decode(latents).sample
|
246 |
+
video = rearrange(video, "(b f) c h w -> b c f h w", f=video_length)
|
247 |
+
video = (video / 2 + 0.5).clamp(0, 1)
|
248 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
|
249 |
+
video = video.cpu().float().numpy()
|
250 |
+
return video
|
251 |
+
|
252 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
253 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
254 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
255 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
256 |
+
# and should be between [0, 1]
|
257 |
+
|
258 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
259 |
+
extra_step_kwargs = {}
|
260 |
+
if accepts_eta:
|
261 |
+
extra_step_kwargs["eta"] = eta
|
262 |
+
|
263 |
+
# check if the scheduler accepts generator
|
264 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
265 |
+
if accepts_generator:
|
266 |
+
extra_step_kwargs["generator"] = generator
|
267 |
+
return extra_step_kwargs
|
268 |
+
|
269 |
+
def check_inputs(self, prompt, height, width, callback_steps):
|
270 |
+
if not isinstance(prompt, str) and not isinstance(prompt, list):
|
271 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
272 |
+
|
273 |
+
if height % 8 != 0 or width % 8 != 0:
|
274 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
275 |
+
|
276 |
+
if (callback_steps is None) or (
|
277 |
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
278 |
+
):
|
279 |
+
raise ValueError(
|
280 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
281 |
+
f" {type(callback_steps)}."
|
282 |
+
)
|
283 |
+
|
284 |
+
def prepare_latents(self, batch_size, num_channels_latents, video_length, height, width, dtype, device, generator, latents=None):
|
285 |
+
shape = (batch_size, num_channels_latents, video_length, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
286 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
287 |
+
raise ValueError(
|
288 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
289 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
290 |
+
)
|
291 |
+
|
292 |
+
if latents is None:
|
293 |
+
rand_device = "cpu" if device.type == "mps" else device
|
294 |
+
|
295 |
+
if isinstance(generator, list):
|
296 |
+
shape = (1,) + shape[1:]
|
297 |
+
latents = [
|
298 |
+
torch.randn(shape, generator=generator[i], device=rand_device, dtype=dtype)
|
299 |
+
for i in range(batch_size)
|
300 |
+
]
|
301 |
+
latents = torch.cat(latents, dim=0).to(device)
|
302 |
+
else:
|
303 |
+
latents = torch.randn(shape, generator=generator, device=rand_device, dtype=dtype).to(device)
|
304 |
+
else:
|
305 |
+
if latents.shape != shape:
|
306 |
+
raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
|
307 |
+
latents = latents.to(device)
|
308 |
+
|
309 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
310 |
+
latents = latents * self.scheduler.init_noise_sigma
|
311 |
+
return latents
|
312 |
+
|
313 |
+
@torch.no_grad()
|
314 |
+
def __call__(
|
315 |
+
self,
|
316 |
+
prompt: Union[str, List[str]],
|
317 |
+
video_length: Optional[int],
|
318 |
+
height: Optional[int] = None,
|
319 |
+
width: Optional[int] = None,
|
320 |
+
num_inference_steps: int = 50,
|
321 |
+
guidance_scale: float = 7.5,
|
322 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
323 |
+
num_videos_per_prompt: Optional[int] = 1,
|
324 |
+
eta: float = 0.0,
|
325 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
326 |
+
latents: Optional[torch.FloatTensor] = None,
|
327 |
+
output_type: Optional[str] = "tensor",
|
328 |
+
return_dict: bool = True,
|
329 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
330 |
+
callback_steps: Optional[int] = 1,
|
331 |
+
skeleton_path: Optional[str] = None,
|
332 |
+
**kwargs,
|
333 |
+
):
|
334 |
+
# Default height and width to unet
|
335 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
336 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
337 |
+
|
338 |
+
# Check inputs. Raise error if not correct
|
339 |
+
self.check_inputs(prompt, height, width, callback_steps)
|
340 |
+
|
341 |
+
# Define call parameters
|
342 |
+
batch_size = 1 if isinstance(prompt, str) else len(prompt)
|
343 |
+
device = self._execution_device
|
344 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
345 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
346 |
+
# corresponds to doing no classifier free guidance.
|
347 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
348 |
+
|
349 |
+
# Encode input prompt
|
350 |
+
text_embeddings = self._encode_prompt(
|
351 |
+
prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt
|
352 |
+
)
|
353 |
+
|
354 |
+
# Prepare timesteps
|
355 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
356 |
+
timesteps = self.scheduler.timesteps
|
357 |
+
|
358 |
+
# Prepare latent variables
|
359 |
+
num_channels_latents = self.unet.in_channels
|
360 |
+
latents = self.prepare_latents(
|
361 |
+
batch_size * num_videos_per_prompt,
|
362 |
+
num_channels_latents,
|
363 |
+
video_length,
|
364 |
+
height,
|
365 |
+
width,
|
366 |
+
text_embeddings.dtype,
|
367 |
+
device,
|
368 |
+
generator,
|
369 |
+
latents,
|
370 |
+
)
|
371 |
+
latents_dtype = latents.dtype
|
372 |
+
|
373 |
+
# Prepare extra step kwargs.
|
374 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
375 |
+
|
376 |
+
# Denoising loop
|
377 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
378 |
+
|
379 |
+
skeleton, save_skeleton = self.get_skeleton(skeleton_path)
|
380 |
+
skeleton = skeleton.to(latents.device).repeat(2,1,1,1,1)
|
381 |
+
|
382 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
383 |
+
for i, t in enumerate(timesteps):
|
384 |
+
# expand the latents if we are doing classifier free guidance
|
385 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
386 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
387 |
+
|
388 |
+
# predict the noise residual
|
389 |
+
noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings, skeleton=skeleton, train_or_sample='sample').sample.to(dtype=latents_dtype)
|
390 |
+
|
391 |
+
# perform guidance
|
392 |
+
if do_classifier_free_guidance:
|
393 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
394 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
395 |
+
|
396 |
+
# compute the previous noisy sample x_t -> x_t-1
|
397 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
|
398 |
+
|
399 |
+
# call the callback, if provided
|
400 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
401 |
+
progress_bar.update()
|
402 |
+
if callback is not None and i % callback_steps == 0:
|
403 |
+
callback(i, t, latents)
|
404 |
+
|
405 |
+
# Post-processing
|
406 |
+
video = self.decode_latents(latents)
|
407 |
+
|
408 |
+
# Convert to tensor
|
409 |
+
if output_type == "tensor":
|
410 |
+
video = torch.from_numpy(video)
|
411 |
+
video_skeleton = rearrange(save_skeleton, 'b t h w c -> b c t h w')
|
412 |
+
video = torch.cat([video_skeleton,video],dim=-1)
|
413 |
+
|
414 |
+
if not return_dict:
|
415 |
+
return video
|
416 |
+
|
417 |
+
return FollowYourPosePipelineOutput(videos=video)
|
418 |
+
|
419 |
+
|
420 |
+
@torch.no_grad()
|
421 |
+
def get_skeleton(self,skeleton_path):
|
422 |
+
skeleton_start_end = list(range(0, 120, 5))
|
423 |
+
self_transform = transforms.Compose([transforms.Resize(512),
|
424 |
+
transforms_video.CenterCropVideo(512)])
|
425 |
+
|
426 |
+
vr_skeleton = decord.VideoReader(skeleton_path)
|
427 |
+
# sample frames
|
428 |
+
|
429 |
+
# for start_end in skeleton_start_end:
|
430 |
+
skeleton = vr_skeleton.get_batch(skeleton_start_end)
|
431 |
+
if not isinstance(skeleton,torch.Tensor):
|
432 |
+
skeleton = torch.from_numpy(skeleton.asnumpy()).float()
|
433 |
+
skeleton_video_trans = self_transform(skeleton.permute(3, 0, 1, 2))
|
434 |
+
skeleton_final = skeleton_video_trans.permute(1, 2, 3, 0)
|
435 |
+
# import pdb;pdb.set_trace()
|
436 |
+
|
437 |
+
skeleton_video = (skeleton_final / 255).unsqueeze(0)
|
438 |
+
save_skeleton = skeleton_video.clone().detach()
|
439 |
+
skeleton_video = rearrange(skeleton_video, 'b t h w c -> b t c h w')
|
440 |
+
# skeleton_video = skeleton_video.to(model.device)
|
441 |
+
|
442 |
+
return skeleton_video, save_skeleton
|
FollowYourPose/followyourpose/util.py
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import imageio
|
3 |
+
import numpy as np
|
4 |
+
from typing import Union
|
5 |
+
|
6 |
+
import torch
|
7 |
+
import torchvision
|
8 |
+
|
9 |
+
from tqdm import tqdm
|
10 |
+
from einops import rearrange
|
11 |
+
|
12 |
+
|
13 |
+
def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=4, fps=8):
|
14 |
+
videos = rearrange(videos, "b c t h w -> t b c h w")
|
15 |
+
outputs = []
|
16 |
+
for x in videos:
|
17 |
+
x = torchvision.utils.make_grid(x, nrow=n_rows)
|
18 |
+
x = x.transpose(0, 1).transpose(1, 2).squeeze(-1)
|
19 |
+
if rescale:
|
20 |
+
x = (x + 1.0) / 2.0 # -1,1 -> 0,1
|
21 |
+
x = (x * 255).numpy().astype(np.uint8)
|
22 |
+
outputs.append(x)
|
23 |
+
|
24 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
25 |
+
imageio.mimsave(path, outputs, fps=fps)
|
26 |
+
|
27 |
+
|
28 |
+
# DDIM Inversion
|
29 |
+
@torch.no_grad()
|
30 |
+
def init_prompt(prompt, pipeline):
|
31 |
+
uncond_input = pipeline.tokenizer(
|
32 |
+
[""], padding="max_length", max_length=pipeline.tokenizer.model_max_length,
|
33 |
+
return_tensors="pt"
|
34 |
+
)
|
35 |
+
uncond_embeddings = pipeline.text_encoder(uncond_input.input_ids.to(pipeline.device))[0]
|
36 |
+
text_input = pipeline.tokenizer(
|
37 |
+
[prompt],
|
38 |
+
padding="max_length",
|
39 |
+
max_length=pipeline.tokenizer.model_max_length,
|
40 |
+
truncation=True,
|
41 |
+
return_tensors="pt",
|
42 |
+
)
|
43 |
+
text_embeddings = pipeline.text_encoder(text_input.input_ids.to(pipeline.device))[0]
|
44 |
+
context = torch.cat([uncond_embeddings, text_embeddings])
|
45 |
+
|
46 |
+
return context
|
47 |
+
|
48 |
+
|
49 |
+
def next_step(model_output: Union[torch.FloatTensor, np.ndarray], timestep: int,
|
50 |
+
sample: Union[torch.FloatTensor, np.ndarray], ddim_scheduler):
|
51 |
+
timestep, next_timestep = min(
|
52 |
+
timestep - ddim_scheduler.config.num_train_timesteps // ddim_scheduler.num_inference_steps, 999), timestep
|
53 |
+
alpha_prod_t = ddim_scheduler.alphas_cumprod[timestep] if timestep >= 0 else ddim_scheduler.final_alpha_cumprod
|
54 |
+
alpha_prod_t_next = ddim_scheduler.alphas_cumprod[next_timestep]
|
55 |
+
beta_prod_t = 1 - alpha_prod_t
|
56 |
+
next_original_sample = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
|
57 |
+
next_sample_direction = (1 - alpha_prod_t_next) ** 0.5 * model_output
|
58 |
+
next_sample = alpha_prod_t_next ** 0.5 * next_original_sample + next_sample_direction
|
59 |
+
return next_sample
|
60 |
+
|
61 |
+
|
62 |
+
def get_noise_pred_single(latents, t, context, unet):
|
63 |
+
noise_pred = unet(latents, t, encoder_hidden_states=context)["sample"]
|
64 |
+
return noise_pred
|
65 |
+
|
66 |
+
|
67 |
+
@torch.no_grad()
|
68 |
+
def ddim_loop(pipeline, ddim_scheduler, latent, num_inv_steps, prompt):
|
69 |
+
context = init_prompt(prompt, pipeline)
|
70 |
+
uncond_embeddings, cond_embeddings = context.chunk(2)
|
71 |
+
all_latent = [latent]
|
72 |
+
latent = latent.clone().detach()
|
73 |
+
for i in tqdm(range(num_inv_steps)):
|
74 |
+
t = ddim_scheduler.timesteps[len(ddim_scheduler.timesteps) - i - 1]
|
75 |
+
noise_pred = get_noise_pred_single(latent, t, cond_embeddings, pipeline.unet)
|
76 |
+
latent = next_step(noise_pred, t, latent, ddim_scheduler)
|
77 |
+
all_latent.append(latent)
|
78 |
+
return all_latent
|
79 |
+
|
80 |
+
|
81 |
+
@torch.no_grad()
|
82 |
+
def ddim_inversion(pipeline, ddim_scheduler, video_latent, num_inv_steps, prompt=""):
|
83 |
+
ddim_latents = ddim_loop(pipeline, ddim_scheduler, video_latent, num_inv_steps, prompt)
|
84 |
+
return ddim_latents
|
FollowYourPose/test_followyourpose.py
ADDED
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import datetime
|
3 |
+
import logging
|
4 |
+
import inspect
|
5 |
+
import math
|
6 |
+
import os
|
7 |
+
from typing import Dict, Optional, Tuple
|
8 |
+
from omegaconf import OmegaConf
|
9 |
+
|
10 |
+
import torch
|
11 |
+
import torch.nn.functional as F
|
12 |
+
import torch.utils.checkpoint
|
13 |
+
|
14 |
+
import diffusers
|
15 |
+
import transformers
|
16 |
+
from accelerate import Accelerator
|
17 |
+
from accelerate.logging import get_logger
|
18 |
+
from accelerate.utils import set_seed
|
19 |
+
from diffusers import AutoencoderKL, DDPMScheduler, DDIMScheduler
|
20 |
+
from diffusers.optimization import get_scheduler
|
21 |
+
from diffusers.utils import check_min_version
|
22 |
+
from diffusers.utils.import_utils import is_xformers_available
|
23 |
+
from tqdm.auto import tqdm
|
24 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
25 |
+
|
26 |
+
import sys
|
27 |
+
sys.path.append('FollowYourPose')
|
28 |
+
from followyourpose.models.unet import UNet3DConditionModel
|
29 |
+
from followyourpose.pipelines.pipeline_followyourpose import FollowYourPosePipeline
|
30 |
+
from followyourpose.util import save_videos_grid, ddim_inversion
|
31 |
+
from einops import rearrange
|
32 |
+
|
33 |
+
check_min_version("0.10.0.dev0")
|
34 |
+
|
35 |
+
logger = get_logger(__name__, log_level="INFO")
|
36 |
+
|
37 |
+
|
38 |
+
def collate_fn(examples):
|
39 |
+
"""Concat a batch of sampled image in dataloader
|
40 |
+
"""
|
41 |
+
batch = {
|
42 |
+
"prompt_ids": torch.cat([example["prompt_ids"] for example in examples], dim=0),
|
43 |
+
"images": torch.stack([example["images"] for example in examples]),
|
44 |
+
}
|
45 |
+
return batch
|
46 |
+
|
47 |
+
|
48 |
+
|
49 |
+
def test(
|
50 |
+
pretrained_model_path: str,
|
51 |
+
output_dir: str,
|
52 |
+
validation_data: Dict,
|
53 |
+
validation_steps: int = 100,
|
54 |
+
train_batch_size: int = 1,
|
55 |
+
gradient_accumulation_steps: int = 1,
|
56 |
+
gradient_checkpointing: bool = True,
|
57 |
+
resume_from_checkpoint: Optional[str] = None,
|
58 |
+
mixed_precision: Optional[str] = "fp16",
|
59 |
+
enable_xformers_memory_efficient_attention: bool = True,
|
60 |
+
seed: Optional[int] = None,
|
61 |
+
skeleton_path: Optional[str] = None,
|
62 |
+
):
|
63 |
+
*_, config = inspect.getargvalues(inspect.currentframe())
|
64 |
+
|
65 |
+
accelerator = Accelerator(
|
66 |
+
gradient_accumulation_steps=gradient_accumulation_steps,
|
67 |
+
mixed_precision=mixed_precision,
|
68 |
+
)
|
69 |
+
|
70 |
+
# Make one log on every process with the configuration for debugging.
|
71 |
+
logging.basicConfig(
|
72 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
73 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
74 |
+
level=logging.INFO,
|
75 |
+
)
|
76 |
+
logger.info(accelerator.state, main_process_only=False)
|
77 |
+
if accelerator.is_local_main_process:
|
78 |
+
transformers.utils.logging.set_verbosity_warning()
|
79 |
+
diffusers.utils.logging.set_verbosity_info()
|
80 |
+
else:
|
81 |
+
transformers.utils.logging.set_verbosity_error()
|
82 |
+
diffusers.utils.logging.set_verbosity_error()
|
83 |
+
|
84 |
+
# If passed along, set the training seed now.
|
85 |
+
if seed is not None:
|
86 |
+
set_seed(seed)
|
87 |
+
|
88 |
+
# Handle the output folder creation
|
89 |
+
if accelerator.is_main_process:
|
90 |
+
|
91 |
+
os.makedirs(output_dir, exist_ok=True)
|
92 |
+
os.makedirs(f"{output_dir}/samples", exist_ok=True)
|
93 |
+
os.makedirs(f"{output_dir}/inv_latents", exist_ok=True)
|
94 |
+
OmegaConf.save(config, os.path.join(output_dir, 'config.yaml'))
|
95 |
+
|
96 |
+
# Load scheduler, tokenizer and models.
|
97 |
+
noise_scheduler = DDPMScheduler.from_pretrained(pretrained_model_path, subfolder="scheduler")
|
98 |
+
tokenizer = CLIPTokenizer.from_pretrained(pretrained_model_path, subfolder="tokenizer")
|
99 |
+
text_encoder = CLIPTextModel.from_pretrained(pretrained_model_path, subfolder="text_encoder")
|
100 |
+
vae = AutoencoderKL.from_pretrained(pretrained_model_path, subfolder="vae")
|
101 |
+
unet = UNet3DConditionModel.from_pretrained_2d(pretrained_model_path, subfolder="unet")
|
102 |
+
|
103 |
+
# Freeze vae and text_encoder
|
104 |
+
vae.requires_grad_(False)
|
105 |
+
text_encoder.requires_grad_(False)
|
106 |
+
|
107 |
+
unet.requires_grad_(False)
|
108 |
+
# for name, module in unet.named_modules():
|
109 |
+
# if name.endswith(tuple(trainable_modules)):
|
110 |
+
# for params in module.parameters():
|
111 |
+
# params.requires_grad = True
|
112 |
+
|
113 |
+
if enable_xformers_memory_efficient_attention:
|
114 |
+
if is_xformers_available():
|
115 |
+
unet.enable_xformers_memory_efficient_attention()
|
116 |
+
else:
|
117 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
118 |
+
|
119 |
+
if gradient_checkpointing:
|
120 |
+
unet.enable_gradient_checkpointing()
|
121 |
+
|
122 |
+
|
123 |
+
# Get the validation pipeline
|
124 |
+
validation_pipeline = FollowYourPosePipeline(
|
125 |
+
vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet,
|
126 |
+
scheduler=DDIMScheduler.from_pretrained(pretrained_model_path, subfolder="scheduler")
|
127 |
+
)
|
128 |
+
validation_pipeline.enable_vae_slicing()
|
129 |
+
ddim_inv_scheduler = DDIMScheduler.from_pretrained(pretrained_model_path, subfolder='scheduler')
|
130 |
+
ddim_inv_scheduler.set_timesteps(validation_data.num_inv_steps)
|
131 |
+
|
132 |
+
unet = accelerator.prepare(unet)
|
133 |
+
# For mixed precision training we cast the text_encoder and vae weights to half-precision
|
134 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
135 |
+
weight_dtype = torch.float32
|
136 |
+
if accelerator.mixed_precision == "fp16":
|
137 |
+
weight_dtype = torch.float16
|
138 |
+
elif accelerator.mixed_precision == "bf16":
|
139 |
+
weight_dtype = torch.bfloat16
|
140 |
+
|
141 |
+
# Move text_encode and vae to gpu and cast to weight_dtype
|
142 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
143 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
144 |
+
|
145 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
146 |
+
|
147 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
148 |
+
# The trackers initializes automatically on the main process.
|
149 |
+
if accelerator.is_main_process:
|
150 |
+
accelerator.init_trackers("text2video-fine-tune")
|
151 |
+
|
152 |
+
global_step = 0
|
153 |
+
first_epoch = 0
|
154 |
+
|
155 |
+
# Potentially load in the weights and states from a previous save
|
156 |
+
load_path = None
|
157 |
+
if resume_from_checkpoint:
|
158 |
+
if resume_from_checkpoint != "latest":
|
159 |
+
|
160 |
+
load_path = resume_from_checkpoint
|
161 |
+
output_dir = os.path.abspath(os.path.join(resume_from_checkpoint, ".."))
|
162 |
+
accelerator.print(f"load from checkpoint {load_path}")
|
163 |
+
accelerator.load_state(load_path)
|
164 |
+
|
165 |
+
global_step = int(load_path.split("-")[-1])
|
166 |
+
|
167 |
+
|
168 |
+
if accelerator.is_main_process:
|
169 |
+
samples = []
|
170 |
+
generator = torch.Generator(device=accelerator.device)
|
171 |
+
generator.manual_seed(seed)
|
172 |
+
|
173 |
+
ddim_inv_latent = None
|
174 |
+
from datetime import datetime
|
175 |
+
now = str(datetime.now())
|
176 |
+
print(now)
|
177 |
+
for idx, prompt in enumerate(validation_data.prompts):
|
178 |
+
sample = validation_pipeline(prompt, generator=generator, latents=ddim_inv_latent,
|
179 |
+
skeleton_path=skeleton_path,
|
180 |
+
**validation_data).videos
|
181 |
+
save_videos_grid(sample, f"{output_dir}/inference/sample-{global_step}-{str(seed)}-{now}/{prompt}.gif")
|
182 |
+
samples.append(sample)
|
183 |
+
samples = torch.concat(samples)
|
184 |
+
save_path = f"{output_dir}/inference/sample-{global_step}-{str(seed)}-{now}.mp4"
|
185 |
+
save_videos_grid(samples, save_path)
|
186 |
+
logger.info(f"Saved samples to {save_path}")
|
187 |
+
|
188 |
+
return save_path
|
189 |
+
|