-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathQmain_FromText.py
186 lines (144 loc) · 7.77 KB
/
Qmain_FromText.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
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 13 10:24:26 2020
@author: Edoardo
"""
import sys
sys.path.append('../utils')
import argparse
import torch
import torch.optim as optim
# from utils.Qdataloaders import get_CelebA_QDCGAN_dataloader, get_CelebA_DCGAN_dataloader
from utils.Qdataloaders import CelebA_dataloader2, CelebA_colab_dataloader, CelebAHQ_dataloader, LSUN_dataloader, Flowers_dataloader
from utils.Qdataloaders import CIFAR10_dataloader
from Qtraining_new import Trainer
# from torch import nn
import random
import numpy as np
import os
from GetModel import GetModel
from utils.readFile import readFile
from multiprocessing import cpu_count
if __name__ == '__main__':
parser = argparse.ArgumentParser()#fromfile_prefix_chars='@')
parser.add_argument('--cuda', type=bool, default=True)
parser.add_argument('--gpu_num', type=int, default=1)
parser.add_argument('--colab', type=bool, default=False)
parser.add_argument('--n_workers', default='max')
parser.add_argument('--train_dir', type=str, default='./data/celebA_Train/Train', help="Folder containg training data. It must point to a folder with images in it.")
parser.add_argument('--Dataset', type=str, default='CelebA_GAN', help='CelebA_GAN, CelebAHQ_GAN')
parser.add_argument('--image_size', type=int, default=64)
parser.add_argument('--normalize', type=bool, default=False, help='map value of images from range [0,255] to range [-1,1]')
parser.add_argument('--model', type=str, default='DCGAN_64', help='Models: SNGAN_32, QSNGAN_QSN_32, SNGAN_128, QSNGAN_128_QSN')
parser.add_argument('--noise_dim', type=int, default=128)
parser.add_argument('--BN', type=bool, default=False, help='Apply Batch Normalization')
parser.add_argument('--SN', type=bool, default=False, help='Apply Spectral Normalization')
parser.add_argument('--batch_size', type=int, default=64)
parser.add_argument('--epochs', type=int, default=10)
parser.add_argument('--loss', type=str, default='hinge', help='[hinge, classic, wasserstein]')
parser.add_argument('--lr', type=float, default=0.0002)
parser.add_argument('--betas', default=(0.0, 0.9))
parser.add_argument('--crit_iter', type=int, default=1, help='critic iteration')
parser.add_argument('--gp_weight', type=int, default=0, help='[1,10] for SSGAN, default=0')
parser.add_argument('--print_every', type=int, default=50, help='Print Gen and Disc Loss every n iterations')
parser.add_argument('--plot_images', type=bool, default=True, help='Plot images during training')
parser.add_argument('--save_images', type=bool, default=True, help='Save images every epoch to track performance')
parser.add_argument('--EpochCheckpoints', type=bool, default=True, help='Save model every epoch. If set to False the model will be saved only at the end')
parser.add_argument('--save_FID', type=bool, default=True, help='Save images and compute FID score')
parser.add_argument('--Test_FID_dir', type=str, default='./data/celeba/img_align_celeba/Test_FID_100/', help='Path to Folder with Test images for FID')
parser.add_argument('--TextArgs', type=str, default='TrainingArguments.txt', help='Path to text with training settings')
parse_list=readFile(parser.parse_args().TextArgs)
opt = parser.parse_args(parse_list)
use_cuda = opt.cuda
gpu_num = opt.gpu_num
loss = opt.loss
critic_iterations = opt.crit_iter # [1, 2]
gp_weight = opt.gp_weight # [1, 10]
lr = opt.lr
betas = opt.betas.replace(',', ' ').split()
betas = (float(betas[0]), float(betas[1]))
# print(betas)
epochs = opt.epochs
noise_dim = opt.noise_dim
BN = opt.BN # Batch normalization
# print(BN)
SN = opt.SN # Spectral Normalization
save_FID = opt.save_FID
plot_images = opt.plot_images
img_size = opt.image_size
batch_size = opt.batch_size
print_every = opt.print_every
EpochCheckpoints = opt.EpochCheckpoints
save_images = opt.save_images
dataset = opt.Dataset
colab = opt.colab
n_workers = opt.n_workers
if n_workers=='max':
n_workers = cpu_count()
manualSeed = 999
#manualSeed = random.randint(1, 10000) # use if you want new results
# print("Random Seed: ", manualSeed)
random.seed(manualSeed)
torch.manual_seed(manualSeed)
seed=manualSeed
np.random.seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
model = opt.model
train_dir = opt.train_dir
normalize = opt.normalize
# print(model, BN, SN)
generator, discriminator = GetModel(str_model=model, z_size=noise_dim, BN=BN, SN = SN)
G_params= sum(p.numel() for p in generator.parameters() if p.requires_grad)
print('G parameters:', G_params)
D_params= sum(p.numel() for p in discriminator.parameters() if p.requires_grad)
print('D parameters:', D_params)
print('Total parameters:', G_params+D_params)
print()
if 'Q' in generator.__class__.__name__:
quat_data = True
else:
quat_data= False
if dataset == 'CelebA_GAN':
if not colab:
data_loader, _ , data_name = CelebA_dataloader2(root=train_dir, quat_data = quat_data, normalize=normalize, batch_size=batch_size, img_size=img_size, num_workers=n_workers)
# print('Padded dataset loaded')
else:
data_loader, _ , data_name = CelebA_colab_dataloader(root=train_dir, quat_data = quat_data, normalize=normalize, batch_size=batch_size, img_size=img_size, num_workers=n_workers)
elif dataset == 'CelebAHQ_GAN':
data_loader, _ , data_name = CelebAHQ_dataloader(root=train_dir, quat_data = quat_data, normalize=normalize, batch_size=batch_size, img_size=img_size, num_workers=n_workers)
elif dataset == 'LSUN_Bedroom':
data_loader, _ , data_name = LSUN_dataloader(root=train_dir, quat_data = quat_data, normalize=normalize, batch_size=batch_size, img_size=img_size, num_workers=n_workers)
elif dataset == 'CIFAR10':
data_loader, _ , data_name = CIFAR10_dataloader(root=train_dir, quat_data = quat_data, normalize=normalize, batch_size=batch_size, img_size=img_size, num_workers=n_workers)
elif dataset == '102flowers':
data_loader, _ , data_name = Flowers_dataloader(root=train_dir, quat_data = quat_data, normalize=normalize, batch_size=batch_size, img_size=img_size, num_workers=n_workers)
else:
RuntimeError('Wrong dataset or not implemented')
gen_img_path = './generated_images/'
real_img_path = opt.Test_FID_dir
FID_paths = [gen_img_path, real_img_path]
checkpoint_folder = 'checkpoints/'
if not os.path.isdir(checkpoint_folder):
os.makedirs(checkpoint_folder)
# Initialize optimizers
G_optimizer = optim.Adam(generator.parameters(), lr=lr, betas=betas)
D_optimizer = optim.Adam(discriminator.parameters(), lr=lr, betas=betas)
'''Train model'''
trainer = Trainer(generator, discriminator, G_optimizer, D_optimizer,
use_cuda=use_cuda, gpu_num=gpu_num, print_every = print_every,
loss = loss,
gp_weight=gp_weight,
critic_iterations=critic_iterations,
save_FID = save_FID,
FIDPaths = [gen_img_path, real_img_path],
checkpoint_folder = checkpoint_folder,
plot_images=plot_images,
save_images=save_images,
saveModelsPerEpoch=EpochCheckpoints,
normalize = normalize,
)
trainer.train(data_loader, epochs)