-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlarge_scale_inference.py
299 lines (255 loc) · 11 KB
/
large_scale_inference.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import argparse, os, sys, glob, yaml, math, random, json
sys.path.append('.')
sys.path.append('./scripts/evaluation/')
import datetime, time
import numpy as np
from omegaconf import OmegaConf
from collections import OrderedDict
from tqdm import trange, tqdm
from einops import rearrange, repeat
from functools import partial
import torch
from pytorch_lightning import seed_everything
from funcs import load_model_checkpoint, load_prompts, load_image_batch, get_filelist, save_videos
from funcs import batch_ddim_sampling
from utils.utils import instantiate_from_config, encode_attribute_multiple
import torchvision
from pathlib import Path
from PIL import Image
import torch.nn.functional as F
import cv2
import scipy as sp
from scipy import stats
from dataclasses import dataclass
import pyrallis
# My utils
from utils.attention_utils import *
from utils.vis_utils import *
from utils.test_list import *
@dataclass
class GenerateConfig:
frames: int
savedir: str = "./z_submit_results"
postfix: str = ""
seed: int = 17
num_rounds: int = 1
ablate_id: str = "0,1,2,3,4"
until_time: int = 13
use_short_pick_list: bool = False
run_baselines: bool = True
run_reg_wihtout_recap: bool = False
# sampling
num_timesteps: int = 25
cfg_scale: float = 12
# prompt
negative_prompt: str = ""
# split
data_from: int = 0
cur_split_id: int = 0
num_per_split: int = 2
def __post_init__(self):
os.makedirs(self.savedir, exist_ok=True)
def img_callback(pred_x0, i):
video = model.decode_first_stage_2DAE(pred_x0).clip(-1.0, 1.0)
video = (video / 2 + 0.5).clamp(0, 1) # -1,1 -> 0,1
save_path_inter = f"step{i}.jpg"
save_path_inter = os.path.join(save_dir_latest, save_path_inter)
save_image_grid(video, save_path_inter, rescale=False, n_rows=8, )
@pyrallis.wrap()
def run(run_config: GenerateConfig):
ddim_steps = run_config.num_timesteps
unconditional_guidance_scale = run_config.cfg_scale
config = 'configs/inference_t2v_512_v2.0.yaml'
ckpt = 'checkpoints/base_512_v2/model.ckpt'
savedir = run_config.savedir
fps = 28
height, width = 320, 512
gpu_num = 1
mode = "base"
n_samples = 1
bs = 1
savefps = 8 # 10
global frames
frames = run_config.frames # 16 #64 #-1
args_dict = {
"ckpt_path": ckpt,
"config": config,
"mode": mode,
"fps": fps,
"width": width,
"height": height,
"n_samples": n_samples,
"bs": bs,
"ddim_steps": ddim_steps, "ddim_eta": 1.0,
"unconditional_guidance_scale": unconditional_guidance_scale,
"savedir": savedir, "frames": frames,
"savefps": savefps,
}
args = OmegaConf.create(args_dict)
print(args)
## step 1: model config
## -----------------------------------------------------------------
config = OmegaConf.load(args.config)
# data_config = config.pop("data", OmegaConf.create())
model_config = config.pop("model", OmegaConf.create())
global model
model = instantiate_from_config(model_config)
model = model.cuda()
assert os.path.exists(args.ckpt_path), f"Error: checkpoint [{args.ckpt_path}] Not Found!"
model = load_model_checkpoint(model, args.ckpt_path)
model.eval()
## sample shape
assert (args.height % 16 == 0) and (args.width % 16 == 0), "Error: image size [h,w] should be multiples of 16!"
## latent noise shape
h, w = args.height // 8, args.width // 8
frames = model.temporal_length if args.frames < 0 else args.frames
channels = model.channels
print("Frames: ", frames)
## saving folders
now = datetime.datetime.now().strftime("%Y-%m-%d")
save_dir = os.path.join(args.savedir, now + f'-{mode}' + run_config.postfix)
os.makedirs(save_dir, exist_ok=True)
print("Create save_dir: ", save_dir)
# Set seed here
seed_list = [run_config.seed + i * 177 for i in range(run_config.num_rounds)]
print("Seed list: ", seed_list)
indices_list = None
global save_dir_latest
def run_generation(prompt, attribute_list, attention_store, save_dir, seed_list, use_delta_attention,
ablation_dict, use_ref_delta_attention=False):
## step 3: run over samples
## -----------------------------------------------------------------
start = time.time()
n_rounds = len(seed_list)
for idx in range(0, n_rounds):
attention_store.reset()
cur_prompt = prompt
cur_seed = seed_list[idx]
seed_everything(cur_seed)
save_prompt = "-".join((cur_prompt.replace("/", "").split(" ")[:15]))
num_attribute = len(attribute_list)
if num_attribute > 0:
save_dir_cur = f"embed{num_attribute}"
else:
save_dir_cur = "prompt"
# Temp Test
if use_delta_attention:
save_dir_cur += f"_deltaAttn_f{frames}_{post_fix_folder}"
else:
save_dir_cur += f"_f{frames}"
save_dir_latest_parent = os.path.join(save_dir, save_prompt, save_dir_cur)
global save_dir_latest
save_dir_latest = os.path.join(save_dir_latest_parent, f"{cur_seed}")
attention_store.set_save_dir(os.path.join(save_dir_latest, "attention"))
# print(f'Work on prompt {idx + 1} / {n_rounds}... Seed={cur_seed}')
print(cur_prompt)
batch_size = args.bs
noise_shape = [batch_size, channels, frames, h, w]
fps = torch.tensor([args.fps] * batch_size).to(model.device).long()
x_T = None
print(f'----> saved in {save_dir_latest}')
if isinstance(cur_prompt, str):
prompts = [cur_prompt]
if len(attribute_list) == 0:
print("Use normal prompt embedding.")
text_emb = model.get_learned_conditioning(prompts) # (1,77,1024)
else:
print("Use attrbites embeddings.")
# text_emb = encode_attribute(model, positive_attribute, negative_attribute, frames)
text_emb = encode_attribute_multiple(model, attribute_list, frames, interpolation_mode,
indices_list=indices_list)
if args.mode == 'base':
cond = {"c_crossattn": [text_emb], "fps": fps}
else:
raise NotImplementedError
## inference
batch_samples = batch_ddim_sampling(
model, cond, noise_shape, args.n_samples,
args.ddim_steps, args.ddim_eta, args.unconditional_guidance_scale,
verbose=True, img_callback=img_callback,
x_T=x_T,
)
## b,samples,c,t,h,w
file_names = [f"{cur_seed}"]
save_videos(batch_samples, save_dir_latest_parent, file_names, fps=args.savefps, ext_name="gif")
final_frame_save_dir = os.path.join(save_dir_latest, 'final_video')
save_image_batch(batch_samples[0, 0], final_frame_save_dir)
# Save config
config_cur = {
"seed": cur_seed,
"prompt": cur_prompt,
# "negative_prompt": n_prompt,
"attribute_list": attribute_list,
"ablation_dict": ablation_dict,
}
with open(os.path.join(save_dir_latest, f"{save_dir_cur}.json"), "w") as outfile:
json.dump(config_cur, outfile, indent=4)
print()
print(f"Saved in {args.savedir}. Time used: {(time.time() - start):.2f} seconds")
data_start = run_config.data_from + run_config.cur_split_id * run_config.num_per_split
data_end = data_start + run_config.num_per_split
print(f'---> Start = {data_start}, End = {data_end}')
for prompt_id in range(data_start, data_end):
if run_config.use_short_pick_list:
prompt = short_pick_list[prompt_id]["prompt"]
attribute_list = short_pick_list[prompt_id]["subprompts"]
else:
prompt = gpt_prompt_list[prompt_id]["prompt"]
attribute_list = gpt_prompt_list[prompt_id]["subprompts"]
interpolation_mode = "linear"
# Attention store related
keep_timestep_list = []
save_timestep_list = [*range(1, 26)]
save_maps = True
save_npy = False
attention_store = AttentionStore(
base_width=64, base_height=40,
keep_timestep_list=keep_timestep_list,
save_timestep_list=save_timestep_list,
save_maps=save_maps, save_npy=save_npy
)
use_ref_delta_attention = False
use_delta_attention = False
register_attention_control(model, attention_store)
if run_config.run_baselines:
print("Use delta attention: ", use_delta_attention)
# print("-------> Run base model.")
run_generation(prompt, [], attention_store, save_dir, seed_list, use_delta_attention,
ablation_dict=None, use_ref_delta_attention=False)
# print("-------> Run Multi Prompt.")
# run_generation(prompt, attribute_list, attention_store, save_dir, seed_list, use_delta_attention,
# ablation_dict=None, use_ref_delta_attention=False)
use_delta_attention = True
ablate_id_list = run_config.ablate_id.split(',')
print(run_config.ablate_id, ablate_id_list)
for ablation_cur_id in ablate_id_list:
#for i, ablation_dict in enumerate(ablation_dict_list):
# if str(i) not in ablate_id_list:
# continue
if ablation_cur_id is None:
break
else:
print(len(ablation_dict_list), int(ablation_cur_id))
ablation_dict = ablation_dict_list[int(ablation_cur_id)]
register_attention_control_vstar(model, attention_store, ablation_dict)
post_fix_folder = ""
ablation_dict.update({"until_time":run_config.until_time})
for i, k in enumerate(ablation_dict["regularize_res_list"]):
diag = ablation_dict[f'diag_{k}']
scale = ablation_dict[f'scale_{k}']
if i != 0:
post_fix_folder += '_'
post_fix_folder += f"res{k}-std{diag}"
if scale != 1.0:
post_fix_folder += f"-scale{scale}"
until_time = ablation_dict["until_time"]
post_fix_folder += f"-until{until_time}"
print("-------> Run Attention Ablation: ", post_fix_folder)
if run_config.run_reg_wihtout_recap:
run_generation(prompt, [], attention_store, save_dir, seed_list, use_delta_attention,
ablation_dict=ablation_dict, use_ref_delta_attention=False)
else:
run_generation(prompt, attribute_list, attention_store, save_dir, seed_list, use_delta_attention,
ablation_dict=ablation_dict, use_ref_delta_attention=False)
if __name__ == '__main__':
run()