|
""" |
|
Train a diffusion model on images. |
|
""" |
|
import json |
|
import sys |
|
import os |
|
|
|
sys.path.append('.') |
|
|
|
|
|
import traceback |
|
|
|
import torch as th |
|
import torch.multiprocessing as mp |
|
import torch.distributed as dist |
|
import numpy as np |
|
|
|
import argparse |
|
import dnnlib |
|
from guided_diffusion import dist_util, logger |
|
from guided_diffusion.resample import create_named_schedule_sampler |
|
from guided_diffusion.script_util import ( |
|
args_to_dict, |
|
add_dict_to_argparser, |
|
continuous_diffusion_defaults, |
|
model_and_diffusion_defaults, |
|
create_model_and_diffusion, |
|
) |
|
from guided_diffusion.continuous_diffusion import make_diffusion as make_sde_diffusion |
|
import nsr |
|
import nsr.lsgm |
|
|
|
|
|
from nsr.script_util import create_3DAE_model, encoder_and_nsr_defaults, loss_defaults, rendering_options_defaults, eg3d_options_default |
|
from datasets.shapenet import load_data, load_eval_data, load_memory_data |
|
from nsr.losses.builder import E3DGELossClass |
|
|
|
from utils.torch_utils import legacy, misc |
|
from torch.utils.data import Subset |
|
from pdb import set_trace as st |
|
|
|
from dnnlib.util import EasyDict, InfiniteSampler |
|
|
|
from datasets.eg3d_dataset import init_dataset_kwargs |
|
|
|
|
|
|
|
SEED = 0 |
|
|
|
|
|
def training_loop(args): |
|
|
|
logger.log("dist setup...") |
|
|
|
th.cuda.set_device( |
|
args.local_rank) |
|
th.cuda.empty_cache() |
|
|
|
th.cuda.manual_seed_all(SEED) |
|
np.random.seed(SEED) |
|
|
|
dist_util.setup_dist(args) |
|
|
|
|
|
|
|
|
|
logger.configure(dir=args.logdir) |
|
|
|
logger.log("creating ViT encoder and NSR decoder...") |
|
|
|
device = dist_util.dev() |
|
|
|
args.img_size = [args.image_size_encoder] |
|
|
|
logger.log("creating model and diffusion...") |
|
|
|
|
|
if args.denoise_in_channels == -1: |
|
args.diffusion_input_size = args.image_size_encoder |
|
args.denoise_in_channels = args.out_chans |
|
args.denoise_out_channels = args.out_chans |
|
else: |
|
assert args.denoise_out_channels != -1 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
denoise_model, diffusion = create_model_and_diffusion( |
|
**args_to_dict(args, |
|
model_and_diffusion_defaults().keys())) |
|
denoise_model.to(dist_util.dev()) |
|
denoise_model.train() |
|
|
|
opts = eg3d_options_default() |
|
if args.sr_training: |
|
args.sr_kwargs = dnnlib.EasyDict( |
|
channel_base=opts.cbase, |
|
channel_max=opts.cmax, |
|
fused_modconv_default='inference_only', |
|
use_noise=True |
|
) |
|
|
|
logger.log("creating encoder and NSR decoder...") |
|
auto_encoder = create_3DAE_model( |
|
**args_to_dict(args, |
|
encoder_and_nsr_defaults().keys())) |
|
|
|
auto_encoder.to(device) |
|
auto_encoder.eval() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
logger.log("freeze triplane decoder...") |
|
for param in auto_encoder.decoder.triplane_decoder.parameters( |
|
): |
|
|
|
param.requires_grad_(False) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if args.cfg in ('afhq', 'ffhq'): |
|
|
|
if args.sr_training: |
|
|
|
logger.log("AE triplane decoder reuses G_ema SR module...") |
|
auto_encoder.decoder.triplane_decoder.superresolution.load_state_dict( |
|
G_ema.superresolution.state_dict()) |
|
|
|
|
|
for param in auto_encoder.decoder.triplane_decoder.superresolution.parameters( |
|
): |
|
param.requires_grad_(False) |
|
|
|
|
|
logger.log("creating eg3d data loader...") |
|
training_set_kwargs, dataset_name = init_dataset_kwargs( |
|
data=args.data_dir, |
|
class_name='datasets.eg3d_dataset.ImageFolderDataset' |
|
) |
|
|
|
|
|
|
|
|
|
training_set_kwargs.use_labels = True |
|
training_set_kwargs.xflip = True |
|
training_set_kwargs.random_seed = SEED |
|
|
|
|
|
|
|
training_set = dnnlib.util.construct_class_by_name( |
|
**training_set_kwargs) |
|
|
|
training_set = dnnlib.util.construct_class_by_name( |
|
**training_set_kwargs) |
|
|
|
training_set_sampler = InfiniteSampler( |
|
dataset=training_set, |
|
rank=dist_util.get_rank(), |
|
num_replicas=dist_util.get_world_size(), |
|
seed=SEED) |
|
|
|
data = iter( |
|
th.utils.data.DataLoader( |
|
dataset=training_set, |
|
sampler=training_set_sampler, |
|
batch_size=args.batch_size, |
|
pin_memory=True, |
|
num_workers=args.num_workers, |
|
)) |
|
|
|
|
|
eval_data = th.utils.data.DataLoader(dataset=Subset( |
|
training_set, np.arange(10)), |
|
batch_size=args.eval_batch_size, |
|
num_workers=1) |
|
|
|
else: |
|
|
|
logger.log("creating data loader...") |
|
|
|
|
|
|
|
if args.overfitting: |
|
logger.log("create overfitting memory dataset") |
|
data = load_memory_data( |
|
file_path=args.eval_data_dir, |
|
batch_size=args.batch_size, |
|
reso=args.image_size, |
|
reso_encoder=args.image_size_encoder, |
|
num_workers=args.num_workers, |
|
load_depth=True |
|
) |
|
else: |
|
logger.log("create all instances dataset") |
|
|
|
data = load_data( |
|
file_path=args.data_dir, |
|
batch_size=args.batch_size, |
|
reso=args.image_size, |
|
reso_encoder=args.image_size_encoder, |
|
num_workers=args.num_workers, |
|
load_depth=True, |
|
preprocess=auto_encoder.preprocess, |
|
dataset_size=args.dataset_size, |
|
|
|
) |
|
|
|
eval_data = load_eval_data( |
|
file_path=args.eval_data_dir, |
|
batch_size=args.eval_batch_size, |
|
reso=args.image_size, |
|
reso_encoder=args.image_size_encoder, |
|
num_workers=args.num_workers, |
|
load_depth=True |
|
) |
|
|
|
|
|
|
|
if dist_util.get_rank() == 0: |
|
with open(os.path.join(args.logdir, 'args.json'), 'w') as f: |
|
json.dump(vars(args), f, indent=2) |
|
|
|
args.schedule_sampler = create_named_schedule_sampler( |
|
args.schedule_sampler, diffusion) |
|
|
|
opt = dnnlib.EasyDict(args_to_dict(args, loss_defaults().keys())) |
|
loss_class = E3DGELossClass(device, opt).to(device) |
|
|
|
logger.log("training...") |
|
|
|
TrainLoop = { |
|
'adm': nsr.TrainLoop3DDiffusion, |
|
'dit': nsr.TrainLoop3DDiffusionDiT, |
|
'ssd': nsr.TrainLoop3DDiffusionSingleStage, |
|
|
|
'ssd_cvD_sds': nsr.TrainLoop3DDiffusionSingleStagecvDSDS, |
|
'ssd_cvd_sds_no_separate_sds_step': |
|
nsr.TrainLoop3DDiffusionSingleStagecvDSDS_sdswithrec, |
|
'vpsde_lsgm_noD': nsr.lsgm.TrainLoop3DDiffusionLSGM_noD, |
|
|
|
|
|
}[args.trainer_name] |
|
|
|
if 'vpsde' in args.trainer_name: |
|
sde_diffusion = make_sde_diffusion( |
|
dnnlib.EasyDict( |
|
args_to_dict(args, |
|
continuous_diffusion_defaults().keys()))) |
|
assert args.mixed_prediction, 'enable mixed_prediction by default' |
|
logger.log('create VPSDE diffusion.') |
|
else: |
|
sde_diffusion = None |
|
|
|
dist_util.synchronize() |
|
|
|
TrainLoop(rec_model=auto_encoder, |
|
denoise_model=denoise_model, |
|
diffusion=diffusion, |
|
sde_diffusion=sde_diffusion, |
|
loss_class=loss_class, |
|
data=data, |
|
eval_data=eval_data, |
|
**vars(args)).run_loop() |
|
|
|
|
|
def create_argparser(**kwargs): |
|
|
|
|
|
defaults = dict( |
|
dataset_size=-1, |
|
diffusion_input_size=-1, |
|
trainer_name='adm', |
|
use_amp=False, |
|
triplane_scaling_divider=1.0, |
|
overfitting=False, |
|
num_workers=4, |
|
image_size=128, |
|
image_size_encoder=224, |
|
iterations=150000, |
|
schedule_sampler="uniform", |
|
anneal_lr=False, |
|
lr=5e-5, |
|
weight_decay=0.0, |
|
lr_anneal_steps=0, |
|
batch_size=1, |
|
eval_batch_size=12, |
|
microbatch=-1, |
|
ema_rate="0.9999", |
|
log_interval=50, |
|
eval_interval=2500, |
|
save_interval=10000, |
|
resume_checkpoint="", |
|
resume_checkpoint_EG3D="", |
|
use_fp16=False, |
|
fp16_scale_growth=1e-3, |
|
data_dir="", |
|
eval_data_dir="", |
|
|
|
logdir="/mnt/lustre/yslan/logs/nips23/", |
|
load_submodule_name='', |
|
ignore_resume_opt=False, |
|
|
|
denoised_ae=True, |
|
) |
|
|
|
defaults.update(model_and_diffusion_defaults()) |
|
defaults.update(continuous_diffusion_defaults()) |
|
defaults.update(encoder_and_nsr_defaults()) |
|
defaults.update(loss_defaults()) |
|
|
|
parser = argparse.ArgumentParser() |
|
add_dict_to_argparser(parser, defaults) |
|
|
|
return parser |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
|
|
os.environ[ |
|
"TORCH_DISTRIBUTED_DEBUG"] = "DETAIL" |
|
|
|
args = create_argparser().parse_args() |
|
args.local_rank = int(os.environ["LOCAL_RANK"]) |
|
args.gpus = th.cuda.device_count() |
|
|
|
|
|
|
|
args.rendering_kwargs = rendering_options_defaults(args) |
|
|
|
|
|
logger.log('Launching processes...') |
|
|
|
logger.log('Available devices ', th.cuda.device_count()) |
|
logger.log('Current cuda device ', th.cuda.current_device()) |
|
|
|
|
|
try: |
|
training_loop(args) |
|
|
|
except Exception as e: |
|
|
|
traceback.print_exc() |
|
dist_util.cleanup() |
|
|