forked from facebookresearch/pytorch_GAN_zoo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
136 lines (110 loc) · 5.26 KB
/
train.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
import os
import sys
import importlib
import argparse
from models.utils.utils import getVal, getLastCheckPoint, loadmodule
from models.utils.config import getConfigOverrideFromParser, \
updateParserWithConfig
import json
def getTrainer(name):
match = {"PGAN": ("progressive_gan_trainer", "ProgressiveGANTrainer"),
"StyleGAN":("styleGAN_trainer", "StyleGANTrainer"),
"DCGAN": ("DCGAN_trainer", "DCGANTrainer")}
if name not in match:
raise AttributeError("Invalid module name")
return loadmodule("models.trainer." + match[name][0],
match[name][1],
prefix='')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Testing script')
parser.add_argument('model_name', type=str,
help='Name of the model to launch, available models are\
PGAN and PPGAN. To get all possible option for a model\
please run train.py $MODEL_NAME -overrides')
parser.add_argument('--no_vis', help=' Disable all visualizations',
action='store_true')
parser.add_argument('--np_vis', help=' Replace visdom by a numpy based \
visualizer (SLURM)',
action='store_true')
parser.add_argument('--restart', help=' If a checkpoint is detected, do \
not try to load it',
action='store_true')
parser.add_argument('-n', '--name', help="Model's name",
type=str, dest="name", default="default")
parser.add_argument('-d', '--dir', help='Output directory',
type=str, dest="dir", default='output_networks')
parser.add_argument('-c', '--config', help="Model's name",
type=str, dest="configPath")
parser.add_argument('-s', '--save_iter', help="If it applies, frequence at\
which a checkpoint should be saved. In the case of a\
evaluation test, iteration to work on.",
type=int, dest="saveIter", default=16000)
parser.add_argument('-e', '--eval_iter', help="If it applies, frequence at\
which a checkpoint should be saved",
type=int, dest="evalIter", default=100)
parser.add_argument('-S', '--Scale_iter', help="If it applies, scale to work\
on")
parser.add_argument('-v', '--partitionValue', help="Partition's value",
type=str, dest="partition_value")
# Retrieve the model we want to launch
baseArgs, unknown = parser.parse_known_args()
trainerModule = getTrainer(baseArgs.model_name)
# Build the output durectory if necessary
if not os.path.isdir(baseArgs.dir):
os.mkdir(baseArgs.dir)
# Add overrides to the parser: changes to the model configuration can be
# done via the command line
parser = updateParserWithConfig(parser, trainerModule._defaultConfig)
kwargs = vars(parser.parse_args())
configOverride = getConfigOverrideFromParser(
kwargs, trainerModule._defaultConfig)
if kwargs['overrides']:
parser.print_help()
sys.exit()
# Checkpoint data
modelLabel = kwargs["name"]
restart = kwargs["restart"]
print(restart)
checkPointDir = os.path.join(kwargs["dir"], modelLabel)
checkPointData = getLastCheckPoint(checkPointDir, modelLabel)
if not os.path.isdir(checkPointDir):
os.mkdir(checkPointDir)
# Training configuration
configPath = kwargs.get("configPath", None)
if configPath is None:
raise ValueError("You need to input a configuratrion file")
with open(kwargs["configPath"], 'rb') as file:
trainingConfig = json.load(file)
# Model configuration
modelConfig = trainingConfig.get("config", {})
for item, val in configOverride.items():
modelConfig[item] = val
trainingConfig["config"] = modelConfig
# Visualization module
vis_module = None
if baseArgs.np_vis:
vis_module = importlib.import_module("visualization.np_visualizer")
elif baseArgs.no_vis:
print("Visualization disabled")
else:
vis_module = importlib.import_module("visualization.visualizer")
print("Running " + baseArgs.model_name)
# Path to the image dataset
pathDB = trainingConfig["pathDB"]
trainingConfig.pop("pathDB", None)
partitionValue = getVal(kwargs, "partition_value",
trainingConfig.get("partitionValue", None))
GANTrainer = trainerModule(pathDB,
useGPU=True,
visualisation=vis_module,
lossIterEvaluation=kwargs["evalIter"],
checkPointDir=checkPointDir,
saveIter= kwargs["saveIter"],
modelLabel=modelLabel,
partitionValue=partitionValue,
**trainingConfig)
# If a checkpoint is found, load it
if not restart and checkPointData is not None:
trainConfig, pathModel, pathTmpData = checkPointData
GANTrainer.loadSavedTraining(pathModel, trainConfig, pathTmpData)
GANTrainer.train()