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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
training script for imagedream
|
| 3 |
+
- the config system is similar with stable diffusion ldm code base(using omigaconf, yaml; target, params initialization, etc.)
|
| 4 |
+
- the training code base is similar with unidiffuser training code base using accelerate
|
| 5 |
+
|
| 6 |
+
concat channel as input, pred xyz value mapped pixedl as groundtruth
|
| 7 |
+
"""
|
| 8 |
+
from omegaconf import OmegaConf
|
| 9 |
+
import argparse
|
| 10 |
+
import datetime
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from torch.utils.data import DataLoader
|
| 13 |
+
import os.path as osp
|
| 14 |
+
import numpy as np
|
| 15 |
+
import os
|
| 16 |
+
import torch
|
| 17 |
+
import wandb
|
| 18 |
+
from libs.base_utils import get_data_generator, PrintContext
|
| 19 |
+
from libs.base_utils import setup, instantiate_from_config, dct2str, add_prefix, get_obj_from_str
|
| 20 |
+
from absl import logging
|
| 21 |
+
from einops import rearrange
|
| 22 |
+
from libs.sample import ImageDreamDiffusion
|
| 23 |
+
|
| 24 |
+
def train(config, unk):
|
| 25 |
+
# using pipeline to extract models
|
| 26 |
+
accelerator, device = setup(config, unk)
|
| 27 |
+
with PrintContext(f"{'access STAT':-^50}", accelerator.is_main_process):
|
| 28 |
+
print(accelerator.state)
|
| 29 |
+
dtype = {
|
| 30 |
+
"fp16": torch.float16,
|
| 31 |
+
"fp32": torch.float32,
|
| 32 |
+
"no": torch.float32,
|
| 33 |
+
"bf16": torch.bfloat16,
|
| 34 |
+
}[accelerator.state.mixed_precision]
|
| 35 |
+
num_frames = config.num_frames
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
################## load models ##################
|
| 39 |
+
model_config = config.models.config
|
| 40 |
+
model_config = OmegaConf.load(model_config)
|
| 41 |
+
model = instantiate_from_config(model_config.model)
|
| 42 |
+
state_dict = torch.load(config.models.resume, map_location="cpu")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
model_in_conv_keys = ["model.diffusion_model.input_blocks.0.0.weight",]
|
| 46 |
+
in_conv_keys = ["diffusion_model.input_blocks.0.0.weight"]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def modify_keys(state_dict, in_keys, out_keys, cur_state_dict=None):
|
| 50 |
+
print("this function only for fuse channel model")
|
| 51 |
+
for in_key in in_keys:
|
| 52 |
+
p = state_dict[in_key]
|
| 53 |
+
if cur_state_dict is not None:
|
| 54 |
+
p_cur = cur_state_dict[in_key]
|
| 55 |
+
print(p_cur.shape, p.shape)
|
| 56 |
+
if p_cur.shape == p.shape:
|
| 57 |
+
print(f"skip {in_key} because of same shape")
|
| 58 |
+
continue
|
| 59 |
+
state_dict[in_key] = torch.cat([p, torch.zeros_like(p)], dim=1) * 0.5
|
| 60 |
+
for out_key in out_keys:
|
| 61 |
+
p = state_dict[out_key]
|
| 62 |
+
if cur_state_dict is not None:
|
| 63 |
+
p_cur = cur_state_dict[out_key]
|
| 64 |
+
print(p_cur.shape, p.shape)
|
| 65 |
+
if p_cur.shape == p.shape:
|
| 66 |
+
print(f"skip {out_key} because of same shape")
|
| 67 |
+
continue
|
| 68 |
+
state_dict[out_key] = torch.cat([p, torch.zeros_like(p)], dim=0)
|
| 69 |
+
return state_dict
|
| 70 |
+
|
| 71 |
+
def wipe_keys(state_dict, keys):
|
| 72 |
+
for key in keys:
|
| 73 |
+
state_dict.pop(key)
|
| 74 |
+
return state_dict
|
| 75 |
+
|
| 76 |
+
unet_config = model_config.model.params.unet_config
|
| 77 |
+
is_normal_inout_channel = not (unet_config.params.in_channels != 4 or unet_config.params.out_channels != 4)
|
| 78 |
+
|
| 79 |
+
if not is_normal_inout_channel:
|
| 80 |
+
state_dict = modify_keys(state_dict, model_in_conv_keys, [], model.state_dict())
|
| 81 |
+
|
| 82 |
+
print(model.load_state_dict(state_dict, strict=False))
|
| 83 |
+
print("loaded model from {}".format(config.models.resume))
|
| 84 |
+
if config.models.get("resume_unet", None) is not None:
|
| 85 |
+
unet_state_dict = torch.load(config.models.resume_unet, map_location="cpu")
|
| 86 |
+
if not is_normal_inout_channel:
|
| 87 |
+
unet_state_dict = modify_keys(unet_state_dict, in_conv_keys, [], model.model.state_dict())
|
| 88 |
+
print(model.model.load_state_dict(unet_state_dict, strict= False))
|
| 89 |
+
print(f"______ load unet from {config.models.resume_unet} ______")
|
| 90 |
+
model.to(device)
|
| 91 |
+
model.device = device
|
| 92 |
+
model.clip_model.device = device
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
################# setup optimizer #################
|
| 96 |
+
from torch.optim import AdamW
|
| 97 |
+
from accelerate.utils import DummyOptim
|
| 98 |
+
optimizer_cls = (
|
| 99 |
+
AdamW
|
| 100 |
+
if accelerator.state.deepspeed_plugin is None
|
| 101 |
+
or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config
|
| 102 |
+
else DummyOptim
|
| 103 |
+
)
|
| 104 |
+
optimizer = optimizer_cls(model.model.parameters(), **config.optimizer)
|
| 105 |
+
|
| 106 |
+
################# prepare datasets #################
|
| 107 |
+
dataset = instantiate_from_config(config.train_data)
|
| 108 |
+
eval_dataset = instantiate_from_config(config.eval_data)
|
| 109 |
+
|
| 110 |
+
dl_config = config.dataloader
|
| 111 |
+
dataloader = DataLoader(dataset, **dl_config, batch_size=config.batch_size)
|
| 112 |
+
|
| 113 |
+
model, optimizer, dataloader, = accelerator.prepare(model, optimizer, dataloader)
|
| 114 |
+
|
| 115 |
+
generator = get_data_generator(dataloader, accelerator.is_main_process, "train")
|
| 116 |
+
if config.get("sampler", None) is not None:
|
| 117 |
+
sampler_cls = get_obj_from_str(config.sampler.target)
|
| 118 |
+
sampler = sampler_cls(model, device, dtype, **config.sampler.params)
|
| 119 |
+
else:
|
| 120 |
+
sampler = ImageDreamDiffusion(model, config.mode, num_frames, device, dtype, dataset.camera_views,
|
| 121 |
+
offset_noise=config.get("offset_noise", False),
|
| 122 |
+
ref_position=dataset.ref_position,
|
| 123 |
+
random_background=dataset.random_background,
|
| 124 |
+
resize_rate=dataset.resize_rate)
|
| 125 |
+
|
| 126 |
+
################# evaluation code #################
|
| 127 |
+
def evaluation():
|
| 128 |
+
from PIL import Image
|
| 129 |
+
import numpy as np
|
| 130 |
+
return_ls = []
|
| 131 |
+
for i in range(accelerator.process_index, len(eval_dataset), accelerator.num_processes):
|
| 132 |
+
item = eval_dataset[i]
|
| 133 |
+
cond = item['cond']
|
| 134 |
+
images = sampler.diffuse("3D assets.", cond,
|
| 135 |
+
pixel_images=item["cond_raw_images"],
|
| 136 |
+
n_test=2)
|
| 137 |
+
images = np.concatenate(images, 0)
|
| 138 |
+
images = [Image.fromarray(images)]
|
| 139 |
+
return_ls.append(dict(images=images, ident=eval_dataset[i]['ident']))
|
| 140 |
+
return return_ls
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
global_step = 0
|
| 144 |
+
total_step = 0
|
| 145 |
+
log_step = 0
|
| 146 |
+
eval_step = 0
|
| 147 |
+
save_step = config.save_interval
|
| 148 |
+
|
| 149 |
+
unet = model.model
|
| 150 |
+
while True:
|
| 151 |
+
item = next(generator)
|
| 152 |
+
unet.train()
|
| 153 |
+
bs = item["clip_cond"].shape[0]
|
| 154 |
+
BS = bs * num_frames
|
| 155 |
+
item["clip_cond"] = item["clip_cond"].to(device).to(dtype)
|
| 156 |
+
item["vae_cond"] = item["vae_cond"].to(device).to(dtype)
|
| 157 |
+
camera_input = item["cameras"].to(device)
|
| 158 |
+
camera_input = camera_input.reshape((BS, camera_input.shape[-1]))
|
| 159 |
+
|
| 160 |
+
gd_type = config.get("gd_type", "pixel")
|
| 161 |
+
if gd_type == "pixel":
|
| 162 |
+
item["target_images_vae"] = item["target_images_vae"].to(device).to(dtype)
|
| 163 |
+
gd = item["target_images_vae"]
|
| 164 |
+
elif gd_type == "xyz":
|
| 165 |
+
item["target_images_xyz_vae"] = item["target_images_xyz_vae"].to(device).to(dtype)
|
| 166 |
+
item["target_images_vae"] = item["target_images_vae"].to(device).to(dtype)
|
| 167 |
+
gd = item["target_images_xyz_vae"]
|
| 168 |
+
elif gd_type == "fusechannel":
|
| 169 |
+
item["target_images_vae"] = item["target_images_vae"].to(device).to(dtype)
|
| 170 |
+
item["target_images_xyz_vae"] = item["target_images_xyz_vae"].to(device).to(dtype)
|
| 171 |
+
gd = torch.cat((item["target_images_vae"], item["target_images_xyz_vae"]), dim=0)
|
| 172 |
+
else:
|
| 173 |
+
raise NotImplementedError
|
| 174 |
+
|
| 175 |
+
with torch.no_grad(), accelerator.autocast("cuda"):
|
| 176 |
+
ip_embed = model.clip_model.encode_image_with_transformer(item["clip_cond"])
|
| 177 |
+
ip_ = ip_embed.repeat_interleave(num_frames, dim=0)
|
| 178 |
+
|
| 179 |
+
ip_img = model.get_first_stage_encoding(model.encode_first_stage(item["vae_cond"]))
|
| 180 |
+
|
| 181 |
+
gd = rearrange(gd, "B F C H W -> (B F) C H W")
|
| 182 |
+
pixel_images = rearrange(item["target_images_vae"], "B F C H W -> (B F) C H W")
|
| 183 |
+
latent_target_images = model.get_first_stage_encoding(model.encode_first_stage(gd))
|
| 184 |
+
pixel_images = model.get_first_stage_encoding(model.encode_first_stage(pixel_images))
|
| 185 |
+
|
| 186 |
+
if gd_type == "fusechannel":
|
| 187 |
+
latent_target_images = rearrange(latent_target_images, "(B F) C H W -> B F C H W", B=bs * 2)
|
| 188 |
+
image_latent, xyz_latent = torch.chunk(latent_target_images, 2)
|
| 189 |
+
fused_channel_latent = torch.cat((image_latent, xyz_latent), dim=-3)
|
| 190 |
+
latent_target_images = rearrange(fused_channel_latent, "B F C H W -> (B F) C H W")
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
if item.get("captions", None) is not None:
|
| 194 |
+
caption_ls = np.array(item["caption"]).T.reshape((-1, BS)).squeeze()
|
| 195 |
+
prompt_cond = model.get_learned_conditioning(caption_ls)
|
| 196 |
+
elif item.get("caption", None) is not None:
|
| 197 |
+
prompt_cond = model.get_learned_conditioning(item["caption"])
|
| 198 |
+
prompt_cond = prompt_cond.repeat_interleave(num_frames, dim=0)
|
| 199 |
+
else:
|
| 200 |
+
prompt_cond = model.get_learned_conditioning(["3D assets."]).repeat(BS, 1, 1)
|
| 201 |
+
condition = {
|
| 202 |
+
"context": prompt_cond,
|
| 203 |
+
"ip": ip_,
|
| 204 |
+
# "ip_img": ip_img,
|
| 205 |
+
"camera": camera_input,
|
| 206 |
+
"pixel_images": pixel_images,
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
with torch.autocast("cuda"), accelerator.accumulate(model):
|
| 210 |
+
time_steps = torch.randint(0, model.num_timesteps, (BS,), device=device)
|
| 211 |
+
noise = torch.randn_like(latent_target_images, device=device)
|
| 212 |
+
x_noisy = model.q_sample(latent_target_images, time_steps, noise)
|
| 213 |
+
output = unet(x_noisy, time_steps, **condition, num_frames=num_frames)
|
| 214 |
+
loss = torch.nn.functional.mse_loss(noise, output)
|
| 215 |
+
|
| 216 |
+
accelerator.backward(loss)
|
| 217 |
+
optimizer.step()
|
| 218 |
+
optimizer.zero_grad()
|
| 219 |
+
global_step += 1
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
total_step = global_step * config.total_batch_size
|
| 224 |
+
if total_step > log_step:
|
| 225 |
+
metrics = dict(
|
| 226 |
+
loss = accelerator.gather(loss.detach().mean()).mean().item(),
|
| 227 |
+
scale = accelerator.scaler.get_scale() if accelerator.scaler is not None else -1
|
| 228 |
+
)
|
| 229 |
+
log_step += config.log_interval
|
| 230 |
+
if accelerator.is_main_process:
|
| 231 |
+
logging.info(dct2str(dict(step=total_step, **metrics)))
|
| 232 |
+
wandb.log(add_prefix(metrics, 'train'), step=total_step)
|
| 233 |
+
|
| 234 |
+
if total_step > save_step and accelerator.is_main_process:
|
| 235 |
+
logging.info("saving done")
|
| 236 |
+
torch.save(unet.state_dict(), osp.join(config.ckpt_root, f"unet-{total_step}"))
|
| 237 |
+
save_step += config.save_interval
|
| 238 |
+
logging.info("save done")
|
| 239 |
+
|
| 240 |
+
if total_step > eval_step:
|
| 241 |
+
logging.info("evaluationing")
|
| 242 |
+
unet.eval()
|
| 243 |
+
return_ls = evaluation()
|
| 244 |
+
cur_eval_base = osp.join(config.eval_root, f"{total_step:07d}")
|
| 245 |
+
os.makedirs(cur_eval_base, exist_ok=True)
|
| 246 |
+
wandb_image_ls = []
|
| 247 |
+
for item in return_ls:
|
| 248 |
+
for i, im in enumerate(item["images"]):
|
| 249 |
+
im.save(osp.join(cur_eval_base, f"{item['ident']}-{i:03d}-{accelerator.process_index}-.png"))
|
| 250 |
+
wandb_image_ls.append(wandb.Image(im, caption=f"{item['ident']}-{i:03d}-{accelerator.process_index}"))
|
| 251 |
+
|
| 252 |
+
wandb.log({"eval_samples": wandb_image_ls})
|
| 253 |
+
eval_step += config.eval_interval
|
| 254 |
+
logging.info("evaluation done")
|
| 255 |
+
|
| 256 |
+
accelerator.wait_for_everyone()
|
| 257 |
+
if total_step > config.max_step:
|
| 258 |
+
break
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
if __name__ == "__main__":
|
| 262 |
+
# load config from config path, then merge with cli args
|
| 263 |
+
parser = argparse.ArgumentParser()
|
| 264 |
+
parser.add_argument(
|
| 265 |
+
"--config", type=str, default="configs/nf7_v3_SNR_rd_size_stroke.yaml"
|
| 266 |
+
)
|
| 267 |
+
parser.add_argument(
|
| 268 |
+
"--logdir", type=str, default="train_logs", help="the dir to put logs"
|
| 269 |
+
)
|
| 270 |
+
parser.add_argument(
|
| 271 |
+
"--resume_workdir", type=str, default=None, help="specify to do resume"
|
| 272 |
+
)
|
| 273 |
+
args, unk = parser.parse_known_args()
|
| 274 |
+
print(args, unk)
|
| 275 |
+
config = OmegaConf.load(args.config)
|
| 276 |
+
if args.resume_workdir is not None:
|
| 277 |
+
assert osp.exists(args.resume_workdir), f"{args.resume_workdir} not exists"
|
| 278 |
+
config.config.workdir = args.resume_workdir
|
| 279 |
+
config.config.resume = True
|
| 280 |
+
OmegaConf.set_struct(config, True) # prevent adding new keys
|
| 281 |
+
cli_conf = OmegaConf.from_cli(unk)
|
| 282 |
+
config = OmegaConf.merge(config, cli_conf)
|
| 283 |
+
config = config.config
|
| 284 |
+
OmegaConf.set_struct(config, False)
|
| 285 |
+
config.logdir = args.logdir
|
| 286 |
+
config.config_name = Path(args.config).stem
|
| 287 |
+
|
| 288 |
+
train(config, unk)
|
| 289 |
+
|
| 290 |
+
|