From 4a6197a685ebf31c7d1ab0ba1b7fdec2170837fe Mon Sep 17 00:00:00 2001 From: chenxuanhong Date: Tue, 15 Feb 2022 01:40:11 +0800 Subject: [PATCH] fix the GPU0 problem --- components/DeConv_Depthwise.py | 32 ++ components/Generator_modulation_depthwise.py | 199 +++++++ data_tools/data_loader_VGGFace2HQ_multigpu.py | 3 +- .../data_loader_VGGFace2HQ_multigpu1.py | 19 +- flops.py | 4 +- speed_test.py | 4 +- train_multigpu.py | 13 +- train_scripts/trainer_multi_gpu.py | 4 +- train_scripts/trainer_multi_gpu1.py | 521 ++++++++++++++++++ train_yamls/train_Depthwise.yaml | 63 +++ 10 files changed, 839 insertions(+), 23 deletions(-) create mode 100644 components/DeConv_Depthwise.py create mode 100644 components/Generator_modulation_depthwise.py create mode 100644 train_scripts/trainer_multi_gpu1.py create mode 100644 train_yamls/train_Depthwise.yaml diff --git a/components/DeConv_Depthwise.py b/components/DeConv_Depthwise.py new file mode 100644 index 0000000..1618898 --- /dev/null +++ b/components/DeConv_Depthwise.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- +############################################################# +# File: DeConv copy.py +# Created Date: Tuesday July 20th 2021 +# Author: Chen Xuanhong +# Email: chenxuanhongzju@outlook.com +# Last Modified: Monday, 14th February 2022 4:54:28 pm +# Modified By: Chen Xuanhong +# Copyright (c) 2021 Shanghai Jiao Tong University +############################################################# +from tokenize import group +from torch import nn + +class DeConv(nn.Module): + def __init__(self, in_channels, out_channels, kernel_size = 3, upsampl_scale = 2, padding="zero"): + super().__init__() + self.upsampling = nn.UpsamplingBilinear2d(scale_factor=upsampl_scale) + padding_size = int((kernel_size -1)/2) + self.conv1x1 = nn.Conv2d(in_channels = in_channels, out_channels = out_channels, kernel_size= 1) + self.conv = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=padding_size, bias=False, groups=out_channels) + # nn.init.xavier_uniform_(self.conv.weight) + # self.__weights_init__() + + # def __weights_init__(self): + # nn.init.xavier_uniform_(self.conv.weight) + + def forward(self, input): + h = self.conv1x1(input) + h = self.upsampling(h) + h = self.conv(h) + return h \ No newline at end of file diff --git a/components/Generator_modulation_depthwise.py b/components/Generator_modulation_depthwise.py new file mode 100644 index 0000000..79064fa --- /dev/null +++ b/components/Generator_modulation_depthwise.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- +############################################################# +# File: Generator.py +# Created Date: Sunday January 16th 2022 +# Author: Chen Xuanhong +# Email: chenxuanhongzju@outlook.com +# Last Modified: Monday, 14th February 2022 11:35:32 pm +# Modified By: Chen Xuanhong +# Copyright (c) 2022 Shanghai Jiao Tong University +############################################################# + +import torch +from torch import nn +from components.DeConv_Depthwise import DeConv +# from components.DeConv_Invo import DeConv + +class Demodule(nn.Module): + def __init__(self, epsilon=1e-8): + """ + @notice: avoid in-place ops. + https://discuss.pytorch.org/t/encounter-the-runtimeerror-one-of-the-variables-needed-for-gradient-computation-has-been-modified-by-an-inplace-operation/836/3 + """ + super(Demodule, self).__init__() + self.epsilon = epsilon + + def forward(self, x): + tmp = torch.mul(x, x) # or x ** 2 + tmp = torch.rsqrt(torch.mean(tmp, (2, 3), True) + self.epsilon) + return x * tmp + +class ApplyStyle(nn.Module): + """ + @ref: https://github.com/lernapparat/lernapparat/blob/master/style_gan/pytorch_style_gan.ipynb + """ + def __init__(self, latent_size, channels): + super(ApplyStyle, self).__init__() + self.linear = nn.Linear(latent_size, channels * 2) + + def forward(self, x, latent): + style = self.linear(latent) # style => [batch_size, n_channels*2] + shape = [-1, 2, x.size(1), 1, 1] + style = style.view(shape) # [batch_size, 2, n_channels, ...] + #x = x * (style[:, 0] + 1.) + style[:, 1] + x = x * (style[:, 0] * 1 + 1.) + style[:, 1] * 1 + return x + +class Modulation(nn.Module): + def __init__(self, latent_size, channels): + super(Modulation, self).__init__() + self.linear = nn.Linear(latent_size, channels) + + def forward(self, x, latent): + style = self.linear(latent) # style => [batch_size, n_channels*2] + shape = [-1, x.size(1), 1, 1] + style = style.view(shape) # [batch_size, 2, n_channels, ...] + #x = x * (style[:, 0] + 1.) + style[:, 1] + x = x * style + return x + +class ResnetBlock_Modulation(nn.Module): + def __init__(self, dim, latent_size, padding_type, activation=nn.ReLU(True)): + super(ResnetBlock_Modulation, self).__init__() + + p = 0 + conv1 = [] + if padding_type == 'reflect': + conv1 += [nn.ReflectionPad2d(1)] + elif padding_type == 'replicate': + conv1 += [nn.ReplicationPad2d(1)] + elif padding_type == 'zero': + p = 1 + else: + raise NotImplementedError('padding [%s] is not implemented' % padding_type) + conv1 += [nn.Conv2d(dim, dim, kernel_size=3, padding = p), Demodule()] + self.conv1 = nn.Sequential(*conv1) + self.style1 = Modulation(latent_size, dim) + self.act1 = activation + + p = 0 + conv2 = [] + if padding_type == 'reflect': + conv2 += [nn.ReflectionPad2d(1)] + elif padding_type == 'replicate': + conv2 += [nn.ReplicationPad2d(1)] + elif padding_type == 'zero': + p = 1 + else: + raise NotImplementedError('padding [%s] is not implemented' % padding_type) + conv2 += [nn.Conv2d(dim, dim, kernel_size=3, padding=p), Demodule()] + self.conv2 = nn.Sequential(*conv2) + self.style2 = Modulation(latent_size, dim) + + + def forward(self, x, dlatents_in_slice): + y = self.conv1(x) + y = self.style1(y, dlatents_in_slice) + y = self.act1(y) + y = self.conv2(y) + y = self.style2(y, dlatents_in_slice) + out = x + y + return out + +class Generator(nn.Module): + def __init__( + self, + **kwargs + ): + super().__init__() + + chn = kwargs["g_conv_dim"] + k_size = kwargs["g_kernel_size"] + res_num = kwargs["res_num"] + + padding_size= int((k_size -1)/2) + padding_type= 'reflect' + + activation = nn.ReLU(True) + + # self.first_layer = nn.Sequential(nn.ReflectionPad2d(3), nn.Conv2d(3, 64, kernel_size=7, padding=0, bias=False), + # nn.BatchNorm2d(64), activation) + self.first_layer = nn.Sequential(nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), + nn.BatchNorm2d(64), activation) + ### downsample + self.down1 = nn.Sequential(nn.Conv2d(64, 64, kernel_size=3, groups=64, padding=1, stride=2), + nn.Conv2d(64, 128, kernel_size=1, bias=False), + nn.BatchNorm2d(128), activation) + + self.down2 = nn.Sequential(nn.Conv2d(128, 128, kernel_size=3, groups=128, padding=1, stride=2), + nn.Conv2d(128, 256, kernel_size=1, bias=False), + nn.BatchNorm2d(256), activation) + + self.down3 = nn.Sequential(nn.Conv2d(256, 256, kernel_size=3, groups=256, padding=1, stride=2), + nn.Conv2d(256, 512, kernel_size=1, bias=False), + nn.BatchNorm2d(512), activation) + + self.down4 = nn.Sequential(nn.Conv2d(512, 512, kernel_size=3, groups=512, padding=1, stride=2), + nn.Conv2d(512, 512, kernel_size=1, bias=False), + nn.BatchNorm2d(512), activation) + + ### resnet blocks + BN = [] + for i in range(res_num): + BN += [ + ResnetBlock_Modulation(512, latent_size=chn, padding_type=padding_type, activation=activation)] + self.BottleNeck = nn.Sequential(*BN) + + self.up4 = nn.Sequential( + DeConv(512,512,3), + nn.BatchNorm2d(512), activation + ) + + self.up3 = nn.Sequential( + DeConv(512,256,3), + nn.BatchNorm2d(256), activation + ) + + self.up2 = nn.Sequential( + DeConv(256,128,3), + nn.BatchNorm2d(128), activation + ) + + self.up1 = nn.Sequential( + DeConv(128,64,3), + nn.BatchNorm2d(64), activation + ) + self.last_layer = nn.Sequential(nn.Conv2d(64, 3, kernel_size=3, padding=1)) + # self.last_layer = nn.Sequential(nn.ReflectionPad2d(3), + # nn.Conv2d(64, 3, kernel_size=7, padding=0)) + + + # self.__weights_init__() + + # def __weights_init__(self): + # for layer in self.encoder: + # if isinstance(layer,nn.Conv2d): + # nn.init.xavier_uniform_(layer.weight) + + # for layer in self.encoder2: + # if isinstance(layer,nn.Conv2d): + # nn.init.xavier_uniform_(layer.weight) + + def forward(self, img, id): + res = self.first_layer(img) + res = self.down1(res) + res = self.down2(res) + res = self.down3(res) + res = self.down4(res) + + for i in range(len(self.BottleNeck)): + res = self.BottleNeck[i](res, id) + + res = self.up4(res) + res = self.up3(res) + res = self.up2(res) + res = self.up1(res) + res = self.last_layer(res) + + return res diff --git a/data_tools/data_loader_VGGFace2HQ_multigpu.py b/data_tools/data_loader_VGGFace2HQ_multigpu.py index 8e71fbf..4afb779 100644 --- a/data_tools/data_loader_VGGFace2HQ_multigpu.py +++ b/data_tools/data_loader_VGGFace2HQ_multigpu.py @@ -5,7 +5,7 @@ # Created Date: Sunday February 6th 2022 # Author: Chen Xuanhong # Email: chenxuanhongzju@outlook.com -# Last Modified: Tuesday, 8th February 2022 10:26:54 pm +# Last Modified: Tuesday, 15th February 2022 1:35:41 am # Modified By: Chen Xuanhong # Copyright (c) 2022 Shanghai Jiao Tong University ############################################################# @@ -56,6 +56,7 @@ class InfiniteSampler(torch.utils.data.Sampler): class data_prefetcher(): def __init__(self, loader, cur_gpu): + torch.cuda.set_device(cur_gpu) self.loader = loader self.dataiter = iter(loader) self.stream = torch.cuda.Stream(device=cur_gpu) diff --git a/data_tools/data_loader_VGGFace2HQ_multigpu1.py b/data_tools/data_loader_VGGFace2HQ_multigpu1.py index 0d03cc7..a98199a 100644 --- a/data_tools/data_loader_VGGFace2HQ_multigpu1.py +++ b/data_tools/data_loader_VGGFace2HQ_multigpu1.py @@ -5,7 +5,7 @@ # Created Date: Sunday February 6th 2022 # Author: Chen Xuanhong # Email: chenxuanhongzju@outlook.com -# Last Modified: Tuesday, 8th February 2022 1:24:27 pm +# Last Modified: Tuesday, 15th February 2022 1:35:06 am # Modified By: Chen Xuanhong # Copyright (c) 2022 Shanghai Jiao Tong University ############################################################# @@ -56,11 +56,12 @@ class InfiniteSampler(torch.utils.data.Sampler): class data_prefetcher(): def __init__(self, loader, cur_gpu): + torch.cuda.set_device(cur_gpu) # must add this line to avoid excessive use of GPU 0 by the prefetcher self.loader = loader self.dataiter = iter(loader) self.stream = torch.cuda.Stream(device=cur_gpu) - self.mean = torch.tensor([0.485, 0.456, 0.406]).cuda(device=cur_gpu).view(1,3,1,1) - self.std = torch.tensor([0.229, 0.224, 0.225]).cuda(device=cur_gpu).view(1,3,1,1) + self.mean = torch.tensor([0.485, 0.456, 0.406]).to(cur_gpu).view(1,3,1,1) + self.std = torch.tensor([0.229, 0.224, 0.225]).to(cur_gpu).view(1,3,1,1) self.cur_gpu = cur_gpu # With Amp, it isn't necessary to manually convert data to half. # if args.fp16: @@ -77,9 +78,9 @@ class data_prefetcher(): # self.src_image1, self.src_image2 = next(self.dataiter) with torch.cuda.stream(self.stream): - self.src_image1 = self.src_image1.cuda(device= self.cur_gpu, non_blocking=True) + self.src_image1 = self.src_image1.to(self.cur_gpu, non_blocking=True) self.src_image1 = self.src_image1.sub_(self.mean).div_(self.std) - self.src_image2 = self.src_image2.cuda(device= self.cur_gpu, non_blocking=True) + self.src_image2 = self.src_image2.to(self.cur_gpu, non_blocking=True) self.src_image2 = self.src_image2.sub_(self.mean).div_(self.std) # With Amp, it isn't necessary to manually convert data to half. # if args.fp16: @@ -171,13 +172,13 @@ def GetLoader( dataset_roots, "jpg", random_seed) device = torch.device('cuda', rank) - # sampler = InfiniteSampler(dataset=content_dataset, rank=rank, num_replicas=num_gpus, seed=random_seed) + sampler = InfiniteSampler(dataset=content_dataset, rank=rank, num_replicas=num_gpus, seed=random_seed) # content_data_loader = data.DataLoader(dataset=content_dataset,batch_size=batch_size, # drop_last=False,shuffle=False,num_workers=num_workers,pin_memory=True, sampler=sampler) content_data_loader = data.DataLoader(dataset=content_dataset,batch_size=batch_size, - drop_last=False,shuffle=True,num_workers=num_workers,pin_memory=True) - # prefetcher = data_prefetcher(content_data_loader,device) - return content_data_loader + drop_last=False,shuffle=False,num_workers=num_workers,pin_memory=True, sampler=sampler) + prefetcher = data_prefetcher(content_data_loader,device) + return prefetcher def denorm(x): out = (x + 1) / 2 diff --git a/flops.py b/flops.py index f5e8eb3..025af80 100644 --- a/flops.py +++ b/flops.py @@ -5,7 +5,7 @@ # Created Date: Sunday February 13th 2022 # Author: Chen Xuanhong # Email: chenxuanhongzju@outlook.com -# Last Modified: Sunday, 13th February 2022 1:37:15 pm +# Last Modified: Monday, 14th February 2022 11:35:11 pm # Modified By: Chen Xuanhong # Copyright (c) 2022 Shanghai Jiao Tong University ############################################################# @@ -21,7 +21,7 @@ from thop import clever_format if __name__ == '__main__': - script = "Generator_config" + script = "Generator_modulation_depthwise" class_name = "Generator" arcface_ckpt= "arcface_ckpt/arcface_checkpoint.tar" model_config={ diff --git a/speed_test.py b/speed_test.py index 691a6e5..47f69be 100644 --- a/speed_test.py +++ b/speed_test.py @@ -5,7 +5,7 @@ # Created Date: Thursday February 10th 2022 # Author: Chen Xuanhong # Email: chenxuanhongzju@outlook.com -# Last Modified: Sunday, 13th February 2022 3:04:07 am +# Last Modified: Monday, 14th February 2022 4:44:38 pm # Modified By: Chen Xuanhong # Copyright (c) 2022 Shanghai Jiao Tong University ############################################################# @@ -18,7 +18,7 @@ import torch if __name__ == '__main__': - script = "Generator_config" + script = "Generator_modulation_depthwise" class_name = "Generator" arcface_ckpt= "arcface_ckpt/arcface_checkpoint.tar" model_config={ diff --git a/train_multigpu.py b/train_multigpu.py index fcd9f95..fd98c92 100644 --- a/train_multigpu.py +++ b/train_multigpu.py @@ -5,7 +5,7 @@ # Created Date: Tuesday April 28th 2020 # Author: Chen Xuanhong # Email: chenxuanhongzju@outlook.com -# Last Modified: Sunday, 13th February 2022 2:16:50 am +# Last Modified: Monday, 14th February 2022 11:54:02 pm # Modified By: Chen Xuanhong # Copyright (c) 2020 Shanghai Jiao Tong University ############################################################# @@ -31,24 +31,24 @@ def getParameters(): parser = argparse.ArgumentParser() # general settings - parser.add_argument('-v', '--version', type=str, default='invoup2', + parser.add_argument('-v', '--version', type=str, default='depthwise', help="version name for train, test, finetune") - parser.add_argument('-t', '--tag', type=str, default='invo_upsample', + parser.add_argument('-t', '--tag', type=str, default='depthwise_conv', help="tag for current experiment") parser.add_argument('-p', '--phase', type=str, default="train", choices=['train', 'finetune','debug'], help="The phase of current project") - parser.add_argument('-c', '--gpus', type=int, nargs='+', default=[0,1]) # <0 if it is set as -1, program will use CPU + parser.add_argument('-c', '--gpus', type=int, nargs='+', default=[0,1,2,3]) # <0 if it is set as -1, program will use CPU parser.add_argument('-e', '--ckpt', type=int, default=74, help="checkpoint epoch for test phase or finetune phase") # training parser.add_argument('--experiment_description', type=str, - default="generator网络前向部分残差的赋值错误,现纠正,重新训练网络") + default="使用depthwise卷积作为基础算子测试性能") - parser.add_argument('--train_yaml', type=str, default="train_Invoup.yaml") + parser.add_argument('--train_yaml', type=str, default="train_Depthwise.yaml") # system logger parser.add_argument('--logger', type=str, @@ -141,6 +141,7 @@ def main(): config = getParameters() # speed up the program cudnn.benchmark = True + cudnn.enabled = True from utilities.logo_class import logo_class logo_class.print_group_logo() diff --git a/train_scripts/trainer_multi_gpu.py b/train_scripts/trainer_multi_gpu.py index 1080b3b..6b07d0d 100644 --- a/train_scripts/trainer_multi_gpu.py +++ b/train_scripts/trainer_multi_gpu.py @@ -5,7 +5,7 @@ # Created Date: Sunday January 9th 2022 # Author: Chen Xuanhong # Email: chenxuanhongzju@outlook.com -# Last Modified: Friday, 11th February 2022 11:18:47 am +# Last Modified: Tuesday, 15th February 2022 12:00:24 am # Modified By: Chen Xuanhong # Copyright (c) 2022 Shanghai Jiao Tong University ############################################################# @@ -215,13 +215,11 @@ def train_loop( img_std = torch.Tensor([0.229, 0.224, 0.225]).view(3,1,1) img_mean = torch.Tensor([0.485, 0.456, 0.406]).view(3,1,1) - cudnn_benchmark = True # Initialize. device = torch.device('cuda', rank) np.random.seed(random_seed * num_gpus + rank) torch.manual_seed(random_seed * num_gpus + rank) - torch.backends.cudnn.benchmark = cudnn_benchmark # Improves training speed. torch.backends.cuda.matmul.allow_tf32 = False # Improves numerical accuracy. torch.backends.cudnn.allow_tf32 = False # Improves numerical accuracy. conv2d_gradfix.enabled = True # Improves training speed. diff --git a/train_scripts/trainer_multi_gpu1.py b/train_scripts/trainer_multi_gpu1.py new file mode 100644 index 0000000..26169c1 --- /dev/null +++ b/train_scripts/trainer_multi_gpu1.py @@ -0,0 +1,521 @@ +#!/usr/bin/env python3 +# -*- coding:utf-8 -*- +############################################################# +# File: trainer_naiv512.py +# Created Date: Sunday January 9th 2022 +# Author: Chen Xuanhong +# Email: chenxuanhongzju@outlook.com +# Last Modified: Tuesday, 15th February 2022 1:25:28 am +# Modified By: Chen Xuanhong +# Copyright (c) 2022 Shanghai Jiao Tong University +############################################################# + +import os +import time +import random +import shutil +import tempfile + +import numpy as np + +import torch +import torch.nn.functional as F + +from torch_utils import misc +from torch_utils import training_stats +from torch_utils.ops import conv2d_gradfix +from torch_utils.ops import grid_sample_gradfix + +from utilities.plot import plot_batch +from losses.cos import cosin_metric +from train_scripts.trainer_multigpu_base import TrainerBase + + +class Trainer(TrainerBase): + + def __init__(self, + config, + reporter): + super(Trainer, self).__init__(config, reporter) + + import inspect + print("Current training script -----------> %s"%inspect.getfile(inspect.currentframe())) + + def train(self): + # Launch processes. + num_gpus = len(self.config["gpus"]) + print('Launching processes...') + torch.multiprocessing.set_start_method('spawn') + with tempfile.TemporaryDirectory() as temp_dir: + torch.multiprocessing.spawn(fn=train_loop, args=(self.config, self.reporter, temp_dir), nprocs=num_gpus) + +# TODO modify this function to build your models +def init_framework(config, reporter, device, rank): + ''' + This function is designed to define the framework, + and print the framework information into the log file + ''' + #===============build models================# + print("build models...") + # TODO [import models here] + torch.cuda.set_device(rank) + torch.cuda.empty_cache() + model_config = config["model_configs"] + + if config["phase"] == "train": + gscript_name = "components." + model_config["g_model"]["script"] + file1 = os.path.join("components", model_config["g_model"]["script"]+".py") + tgtfile1 = os.path.join(config["project_scripts"], model_config["g_model"]["script"]+".py") + shutil.copyfile(file1,tgtfile1) + dscript_name = "components." + model_config["d_model"]["script"] + file1 = os.path.join("components", model_config["d_model"]["script"]+".py") + tgtfile1 = os.path.join(config["project_scripts"], model_config["d_model"]["script"]+".py") + shutil.copyfile(file1,tgtfile1) + + elif config["phase"] == "finetune": + gscript_name = config["com_base"] + model_config["g_model"]["script"] + dscript_name = config["com_base"] + model_config["d_model"]["script"] + + class_name = model_config["g_model"]["class_name"] + package = __import__(gscript_name, fromlist=True) + gen_class = getattr(package, class_name) + gen = gen_class(**model_config["g_model"]["module_params"]) + + # print and recorde model structure + reporter.writeInfo("Generator structure:") + reporter.writeModel(gen.__str__()) + + class_name = model_config["d_model"]["class_name"] + package = __import__(dscript_name, fromlist=True) + dis_class = getattr(package, class_name) + dis = dis_class(**model_config["d_model"]["module_params"]) + + + # print and recorde model structure + reporter.writeInfo("Discriminator structure:") + reporter.writeModel(dis.__str__()) + + arcface1 = torch.load(config["arcface_ckpt"], map_location=torch.device("cpu")) + arcface = arcface1['model'].module + + # train in GPU + + # if in finetune phase, load the pretrained checkpoint + if config["phase"] == "finetune": + model_path = os.path.join(config["project_checkpoints"], + "step%d_%s.pth"%(config["ckpt"], + config["checkpoint_names"]["generator_name"])) + gen.load_state_dict(torch.load(model_path), map_location=torch.device("cpu")) + + model_path = os.path.join(config["project_checkpoints"], + "step%d_%s.pth"%(config["ckpt"], + config["checkpoint_names"]["discriminator_name"])) + dis.load_state_dict(torch.load(model_path), map_location=torch.device("cpu")) + + print('loaded trained backbone model step {}...!'.format(config["project_checkpoints"])) + + gen = gen.to(device) + dis = dis.to(device) + arcface= arcface.to(device) + arcface.requires_grad_(False) + arcface.eval() + + + + return gen, dis, arcface + +# TODO modify this function to configurate the optimizer of your pipeline +def setup_optimizers(config, reporter, gen, dis, rank): + + torch.cuda.set_device(rank) + torch.cuda.empty_cache() + g_train_opt = config['g_optim_config'] + d_train_opt = config['d_optim_config'] + + g_optim_params = [] + d_optim_params = [] + for k, v in gen.named_parameters(): + if v.requires_grad: + g_optim_params.append(v) + else: + reporter.writeInfo(f'Params {k} will not be optimized.') + print(f'Params {k} will not be optimized.') + + for k, v in dis.named_parameters(): + if v.requires_grad: + d_optim_params.append(v) + else: + reporter.writeInfo(f'Params {k} will not be optimized.') + print(f'Params {k} will not be optimized.') + + optim_type = config['optim_type'] + + if optim_type == 'Adam': + g_optimizer = torch.optim.Adam(g_optim_params,**g_train_opt) + d_optimizer = torch.optim.Adam(d_optim_params,**d_train_opt) + else: + raise NotImplementedError( + f'optimizer {optim_type} is not supperted yet.') + # self.optimizers.append(self.optimizer_g) + if config["phase"] == "finetune": + opt_path = os.path.join(config["project_checkpoints"], + "step%d_optim_%s.pth"%(config["ckpt"], + config["optimizer_names"]["generator_name"])) + g_optimizer.load_state_dict(torch.load(opt_path)) + + opt_path = os.path.join(config["project_checkpoints"], + "step%d_optim_%s.pth"%(config["ckpt"], + config["optimizer_names"]["discriminator_name"])) + d_optimizer.load_state_dict(torch.load(opt_path)) + + print('loaded trained optimizer step {}...!'.format(config["project_checkpoints"])) + return g_optimizer, d_optimizer + + +def train_loop( + rank, + config, + reporter, + temp_dir + ): + + version = config["version"] + + ckpt_dir = config["project_checkpoints"] + sample_dir = config["project_samples"] + + log_freq = config["log_step"] + model_freq = config["model_save_step"] + sample_freq = config["sample_step"] + total_step = config["total_step"] + random_seed = config["dataset_params"]["random_seed"] + + + id_w = config["id_weight"] + rec_w = config["reconstruct_weight"] + feat_w = config["feature_match_weight"] + num_gpus = len(config["gpus"]) + batch_gpu = config["batch_size"] // num_gpus + + init_file = os.path.abspath(os.path.join(temp_dir, '.torch_distributed_init')) + if os.name == 'nt': + init_method = 'file:///' + init_file.replace('\\', '/') + torch.distributed.init_process_group(backend='gloo', init_method=init_method, rank=rank, world_size=num_gpus) + else: + init_method = f'file://{init_file}' + torch.distributed.init_process_group(backend='nccl', init_method=init_method, rank=rank, world_size=num_gpus) + + # Init torch_utils. + sync_device = torch.device('cuda', rank) + training_stats.init_multiprocessing(rank=rank, sync_device=sync_device) + + + + if rank == 0: + img_std = torch.Tensor([0.229, 0.224, 0.225]).view(3,1,1) + img_mean = torch.Tensor([0.485, 0.456, 0.406]).view(3,1,1) + + + # Initialize. + device = torch.device('cuda', rank) + np.random.seed(random_seed * num_gpus + rank) + torch.manual_seed(random_seed * num_gpus + rank) + torch.backends.cuda.matmul.allow_tf32 = False # Improves numerical accuracy. + torch.backends.cudnn.allow_tf32 = False # Improves numerical accuracy. + conv2d_gradfix.enabled = True # Improves training speed. + grid_sample_gradfix.enabled = True # Avoids errors with the augmentation pipe. + + # Create dataloader. + if rank == 0: + print('Loading training set...') + + dataset = config["dataset_paths"][config["dataset_name"]] + #================================================# + print("Prepare the train dataloader...") + dlModulename = config["dataloader"] + package = __import__("data_tools.data_loader_%s"%dlModulename, fromlist=True) + dataloaderClass = getattr(package, 'GetLoader') + dataloader_class= dataloaderClass + dataloader = dataloader_class(dataset, + rank, + num_gpus, + batch_gpu, + **config["dataset_params"]) + + # Construct networks. + if rank == 0: + print('Constructing networks...') + gen, dis, arcface = init_framework(config, reporter, device, rank) + + # Check for existing checkpoint + + # Print network summary tables. + # if rank == 0: + # attr = torch.empty([batch_gpu, 3, 512, 512], device=device) + # id = torch.empty([batch_gpu, 3, 112, 112], device=device) + # latent = misc.print_module_summary(arcface, [id]) + # img = misc.print_module_summary(gen, [attr, latent]) + # misc.print_module_summary(dis, [img, None]) + # del attr + # del id + # del latent + # del img + # torch.cuda.empty_cache() + + + # Distribute across GPUs. + if rank == 0: + print(f'Distributing across {num_gpus} GPUs...') + for module in [gen, dis, arcface]: + if module is not None and num_gpus > 1: + for param in misc.params_and_buffers(module): + torch.distributed.broadcast(param, src=0) + + # Setup training phases. + if rank == 0: + print('Setting up training phases...') + #===============build losses===================# + # TODO replace below lines to build your losses + # MSE_loss = torch.nn.MSELoss() + l1_loss = torch.nn.L1Loss() + cos_loss = torch.nn.CosineSimilarity() + + g_optimizer, d_optimizer = setup_optimizers(config, reporter, gen, dis, rank) + + # Initialize logs. + if rank == 0: + print('Initializing logs...') + #==============build tensorboard=================# + if config["logger"] == "tensorboard": + import torch.utils.tensorboard as tensorboard + tensorboard_writer = tensorboard.SummaryWriter(config["project_summary"]) + logger = tensorboard_writer + + elif config["logger"] == "wandb": + import wandb + wandb.init(project="Simswap_HQ", entity="xhchen", notes="512", + tags=[config["tag"]], name=version) + + wandb.config = { + "total_step": config["total_step"], + "batch_size": config["batch_size"] + } + logger = wandb + + + random.seed(random_seed) + randindex = [i for i in range(batch_gpu)] + + # set the start point for training loop + if config["phase"] == "finetune": + start = config["ckpt"] + else: + start = 0 + if rank == 0: + import datetime + start_time = time.time() + + # Caculate the epoch number + print("Total step = %d"%total_step) + + print("Start to train at %s"%(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))) + + from utilities.logo_class import logo_class + logo_class.print_start_training() + + dis.feature_network.requires_grad_(False) + # dataloader = iter(dataloader) + for step in range(start, total_step): + gen.train() + dis.train() + for interval in range(2): + random.shuffle(randindex) + src_image1, src_image2 = dataloader.next() + # src_image1, src_image2 = next(dataloader) + # src_image1, src_image2 = src_image1.to(device), src_image2.to(device) + # if rank ==0: + + # elapsed = time.time() - start_time + # elapsed = str(datetime.timedelta(seconds=elapsed)) + # print("dataloader:",elapsed) + + if step%2 == 0: + img_id = src_image2 + else: + img_id = src_image2[randindex] + + img_id_112 = F.interpolate(img_id,size=(112,112), mode='bicubic') + latent_id = arcface(img_id_112) + latent_id = F.normalize(latent_id, p=2, dim=1) + + if interval == 0: + + img_fake = gen(src_image1, latent_id) + gen_logits,_ = dis(img_fake.detach(), None) + loss_Dgen = (F.relu(torch.ones_like(gen_logits) + gen_logits)).mean() + + real_logits,_ = dis(src_image2,None) + loss_Dreal = (F.relu(torch.ones_like(real_logits) - real_logits)).mean() + + loss_D = loss_Dgen + loss_Dreal + d_optimizer.zero_grad(set_to_none=True) + loss_D.backward() + with torch.autograd.profiler.record_function('discriminator_opt'): + # params = [param for param in dis.parameters() if param.grad is not None] + # if len(params) > 0: + # flat = torch.cat([param.grad.flatten() for param in params]) + # if num_gpus > 1: + # torch.distributed.all_reduce(flat) + # flat /= num_gpus + # misc.nan_to_num(flat, nan=0, posinf=1e5, neginf=-1e5, out=flat) + # grads = flat.split([param.numel() for param in params]) + # for param, grad in zip(params, grads): + # param.grad = grad.reshape(param.shape) + params = [param for param in dis.parameters() if param.grad is not None] + flat = torch.cat([param.grad.flatten() for param in params]) + torch.distributed.all_reduce(flat) + flat /= num_gpus + misc.nan_to_num(flat, nan=0, posinf=1e5, neginf=-1e5, out=flat) + grads = flat.split([param.numel() for param in params]) + for param, grad in zip(params, grads): + param.grad = grad.reshape(param.shape) + d_optimizer.step() + # if rank ==0: + + # elapsed = time.time() - start_time + # elapsed = str(datetime.timedelta(seconds=elapsed)) + # print("Discriminator training:",elapsed) + else: + + # model.netD.requires_grad_(True) + img_fake = gen(src_image1, latent_id) + # G loss + gen_logits,feat = dis(img_fake, None) + + loss_Gmain = (-gen_logits).mean() + img_fake_down = F.interpolate(img_fake, size=(112,112), mode='bicubic') + latent_fake = arcface(img_fake_down) + latent_fake = F.normalize(latent_fake, p=2, dim=1) + loss_G_ID = (1 - cos_loss(latent_fake, latent_id)).mean() + real_feat = dis.get_feature(src_image1) + feat_match_loss = l1_loss(feat["3"],real_feat["3"]) + loss_G = loss_Gmain + loss_G_ID * id_w + \ + feat_match_loss * feat_w + if step%2 == 0: + #G_Rec + loss_G_Rec = l1_loss(img_fake, src_image1) + loss_G += loss_G_Rec * rec_w + + g_optimizer.zero_grad(set_to_none=True) + loss_G.backward() + with torch.autograd.profiler.record_function('generator_opt'): + params = [param for param in gen.parameters() if param.grad is not None] + flat = torch.cat([param.grad.flatten() for param in params]) + torch.distributed.all_reduce(flat) + flat /= num_gpus + misc.nan_to_num(flat, nan=0, posinf=1e5, neginf=-1e5, out=flat) + grads = flat.split([param.numel() for param in params]) + for param, grad in zip(params, grads): + param.grad = grad.reshape(param.shape) + g_optimizer.step() + # if rank ==0: + + # elapsed = time.time() - start_time + # elapsed = str(datetime.timedelta(seconds=elapsed)) + # print("Generator training:",elapsed) + + + # Print out log info + if rank == 0 and (step + 1) % log_freq == 0: + elapsed = time.time() - start_time + elapsed = str(datetime.timedelta(seconds=elapsed)) + # print("ready to report losses") + # ID_Total= loss_G_ID + # torch.distributed.all_reduce(ID_Total) + + epochinformation="[{}], Elapsed [{}], Step [{}/{}], \ + G_ID: {:.4f}, G_loss: {:.4f}, Rec_loss: {:.4f}, Fm_loss: {:.4f}, \ + D_loss: {:.4f}, D_fake: {:.4f}, D_real: {:.4f}". \ + format(version, elapsed, step, total_step, \ + loss_G_ID.item(), loss_G.item(), loss_G_Rec.item(), feat_match_loss.item(), \ + loss_D.item(), loss_Dgen.item(), loss_Dreal.item()) + print(epochinformation) + reporter.writeInfo(epochinformation) + + if config["logger"] == "tensorboard": + logger.add_scalar('G/G_loss', loss_G.item(), step) + logger.add_scalar('G/G_Rec', loss_G_Rec.item(), step) + logger.add_scalar('G/G_feat_match', feat_match_loss.item(), step) + logger.add_scalar('G/G_ID', loss_G_ID.item(), step) + logger.add_scalar('D/D_loss', loss_D.item(), step) + logger.add_scalar('D/D_fake', loss_Dgen.item(), step) + logger.add_scalar('D/D_real', loss_Dreal.item(), step) + elif config["logger"] == "wandb": + logger.log({"G_Loss": loss_G.item()}, step = step) + logger.log({"G_Rec": loss_G_Rec.item()}, step = step) + logger.log({"G_feat_match": feat_match_loss.item()}, step = step) + logger.log({"G_ID": loss_G_ID.item()}, step = step) + logger.log({"D_loss": loss_D.item()}, step = step) + logger.log({"D_fake": loss_Dgen.item()}, step = step) + logger.log({"D_real": loss_Dreal.item()}, step = step) + torch.cuda.empty_cache() + + if rank == 0 and ((step + 1) % sample_freq == 0 or (step+1) % model_freq==0): + gen.eval() + with torch.no_grad(): + imgs = [] + zero_img = (torch.zeros_like(src_image1[0,...])) + imgs.append(zero_img.cpu().numpy()) + save_img = ((src_image1.cpu())* img_std + img_mean).numpy() + for r in range(batch_gpu): + imgs.append(save_img[r,...]) + arcface_112 = F.interpolate(src_image2,size=(112,112), mode='bicubic') + id_vector_src1 = arcface(arcface_112) + id_vector_src1 = F.normalize(id_vector_src1, p=2, dim=1) + + for i in range(batch_gpu): + + imgs.append(save_img[i,...]) + image_infer = src_image1[i, ...].repeat(batch_gpu, 1, 1, 1) + img_fake = gen(image_infer, id_vector_src1).cpu() + + img_fake = img_fake * img_std + img_fake = img_fake + img_mean + img_fake = img_fake.numpy() + for j in range(batch_gpu): + imgs.append(img_fake[j,...]) + print("Save test data") + imgs = np.stack(imgs, axis = 0).transpose(0,2,3,1) + plot_batch(imgs, os.path.join(sample_dir, 'step_'+str(step+1)+'.jpg')) + torch.cuda.empty_cache() + + + + #===============adjust learning rate============# + # if (epoch + 1) in self.config["lr_decay_step"] and self.config["lr_decay_enable"]: + # print("Learning rate decay") + # for p in self.optimizer.param_groups: + # p['lr'] *= self.config["lr_decay"] + # print("Current learning rate is %f"%p['lr']) + + #===============save checkpoints================# + if rank == 0 and (step+1) % model_freq==0: + + torch.save(gen.state_dict(), + os.path.join(ckpt_dir, 'step{}_{}.pth'.format(step + 1, + config["checkpoint_names"]["generator_name"]))) + torch.save(dis.state_dict(), + os.path.join(ckpt_dir, 'step{}_{}.pth'.format(step + 1, + config["checkpoint_names"]["discriminator_name"]))) + + torch.save(g_optimizer.state_dict(), + os.path.join(ckpt_dir, 'step{}_optim_{}'.format(step + 1, + config["checkpoint_names"]["generator_name"]))) + + torch.save(d_optimizer.state_dict(), + os.path.join(ckpt_dir, 'step{}_optim_{}'.format(step + 1, + config["checkpoint_names"]["discriminator_name"]))) + print("Save step %d model checkpoint!"%(step+1)) + torch.cuda.empty_cache() + print("Rank %d process done!"%rank) + torch.distributed.barrier() \ No newline at end of file diff --git a/train_yamls/train_Depthwise.yaml b/train_yamls/train_Depthwise.yaml new file mode 100644 index 0000000..dabff36 --- /dev/null +++ b/train_yamls/train_Depthwise.yaml @@ -0,0 +1,63 @@ +# Related scripts +train_script_name: multi_gpu + +# models' scripts +model_configs: + g_model: + script: Generator_modulation_depthwise + class_name: Generator + module_params: + g_conv_dim: 512 + g_kernel_size: 3 + res_num: 9 + + d_model: + script: projected_discriminator + class_name: ProjectedDiscriminator + module_params: + diffaug: False + interp224: False + backbone_kwargs: {} + +arcface_ckpt: arcface_ckpt/arcface_checkpoint.tar + +# Training information +batch_size: 16 + +# Dataset +dataloader: VGGFace2HQ_multigpu +dataset_name: vggface2_hq +dataset_params: + random_seed: 1234 + dataloader_workers: 4 + +eval_dataloader: DIV2K_hdf5 +eval_dataset_name: DF2K_H5_Eval +eval_batch_size: 2 + +# Dataset + +# Optimizer +optim_type: Adam +g_optim_config: + lr: 0.0004 + betas: [ 0, 0.99] + eps: !!float 1e-8 + +d_optim_config: + lr: 0.0004 + betas: [ 0, 0.99] + eps: !!float 1e-8 + +id_weight: 20.0 +reconstruct_weight: 10.0 +feature_match_weight: 10.0 + +# Log +log_step: 300 +model_save_step: 10000 +sample_step: 1000 +total_step: 1000000 +checkpoint_names: + generator_name: Generator + discriminator_name: Discriminator \ No newline at end of file