-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
executable file
·198 lines (163 loc) · 7.61 KB
/
Copy pathtrain.py
File metadata and controls
executable file
·198 lines (163 loc) · 7.61 KB
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
187
188
189
190
191
192
193
194
195
196
197
198
import random
import torch
from pathlib import Path
from tqdm import tqdm
from torch.utils.data import DataLoader
from torch.optim.lr_scheduler import LinearLR, CosineAnnealingLR, SequentialLR
import torch.nn.utils as nn_utils
import code.compatibility as compat
from code.config import Config
from code.utils.advanced import get_random_colors, xyac_to_svgs
from code.utils.lossy import lattice_loss
from code.wandblog import WandBLog
from code.data.load import MyDataset
from code.filesystem import CheckPointer, load_checkpoint
from code.models import get_model_class
# Suppress nested tensor warnings
import warnings
warnings.filterwarnings("ignore", message="enable_nested_tensor is True")
warnings.filterwarnings("ignore", category=FutureWarning)
def train_fn(rank:int, config:Config):
"""
Main training loop.
Args:
rank: Process rank/index
config: Instance of config.Config containing parsed settings.
"""
device = compat.get_device()
print(f"Process {rank} initialized on {device}.")
is_master = compat.is_master()
if is_master:
print(f"{rank} is master.")
compat.print_env()
mprint = print
else:
mprint = lambda *args, **kwargs: None
#--------------------------------------------
# Load Data
#--------------------------------------------
mprint(f"Loading data from {config.data_path}...")
dataset = MyDataset(Path(config.data_path)) # CPU
distributed_sampler = compat.get_maybe_distributed_sampler(dataset) # Split data for TPU cores
loader_args = {
'batch_size': config.train['batch_size'],
'sampler': distributed_sampler,
'shuffle': distributed_sampler is None, # distributed_sampler handles shuffling
'num_workers': 0 if distributed_sampler else 4, # distributed_sampler handles multi-threading
'drop_last': True
}
data_loader = DataLoader(dataset, **loader_args)
device_data_loader = compat.get_loader(data_loader, device) # Pre-fetch to device
mprint(dataset) # type: ignore
mprint(f"Batches/Core: {len(data_loader)}")
#--------------------------------------------
# Model Initialization
#--------------------------------------------
Model = get_model_class(config.model['model'])
model = Model(config.model, dataset).to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=config.train['lr'])
model.runtime_setup(optimizer)
# Scheduler (Create it NOW, before loading state)
warmup_epochs = min(10, int(config.train['num_epochs'] * 0.05))
decay_epochs = config.train['num_epochs'] - warmup_epochs
scheduler1 = LinearLR(optimizer, start_factor=0.01, total_iters=warmup_epochs)
scheduler2 = CosineAnnealingLR(optimizer, T_max=decay_epochs)
scheduler = SequentialLR(optimizer, schedulers=[scheduler1, scheduler2], milestones=[warmup_epochs])
load_checkpoint(config.checkpoint_path, model, optimizer, scheduler, mprint)
# Move to device
for state in optimizer.state.values():
for k, v in state.items():
if isinstance(v, torch.Tensor):
state[k] = v.to(device)
elif not isinstance(v, (int, float, bool, type(None))):
warnings.warn(f"Unexpected optimizer state type: '{type(v)}' for key '{k}'")
#--------------------------------------------
# Set an identifier for the run
#--------------------------------------------
identifier = f"{config.timestamp}_{model.descriptor}_t{dataset.num_tiles:03d}"
mprint(f"Identifier for this run: {identifier}")
#--------------------------------------------
# Initialize WandB Logger
#--------------------------------------------
mprint("Initializing WandB (Maybe)...")
if not config.wandb['run_name']:
config.wandb['run_name'] = identifier
wandblog = WandBLog(is_master, config.wandb)
wandblog.info(config, compat, dataset, model)
#--------------------------------------------
# Initialize Checkpointer
#--------------------------------------------
if is_master:
ckptr = CheckPointer(config.output_base_dir, identifier)
ckptr.add_fixed_ckpt_data(dataset, config.config, config.data_path_orig, wandblog.get_run_id())
#--------------------------------------------
# Sample label and colors (to generate tiles)
#--------------------------------------------
sample_label = random.randint(0, dataset.num_classes - 1)
sample_label_tr = torch.tensor([sample_label], dtype=torch.long, device=device)
sample_name = dataset.class_lookup[sample_label]
sample_colors = get_random_colors(dataset.symmetry, 1, dataset.num_tiles, device)
#--------------------------------------------
# Training Loop
#--------------------------------------------
start_epoch = config.resume_epoch
total_epochs = start_epoch + config.train['num_epochs']
iterator = range(start_epoch, total_epochs)
mprint(f"Starting training for {len(iterator)} epochs...")
num_aux_losses = len(model.aux_loss_names)
for epoch in iterator:
total_loss = 0
aux_loss_sums = torch.zeros(num_aux_losses, device=device)
count = 0
# Enable progress bar only on master process
progressbar = tqdm(device_data_loader, disable = not is_master)
for batch in progressbar:
xya, colors, labels = batch
try:
loss, aux_losses = model.train_step(xya, colors, labels)
except RuntimeError as e:
print(f"RuntimeError in Epoch {epoch} at Batch {count}. Total Loss: {total_loss:.4f}")
raise e
# Backpropagate
optimizer.zero_grad()
loss.backward()
nn_utils.clip_grad_norm_(model.parameters(), max_norm=1.)
compat.optimizer_step(optimizer)
total_loss += loss.item()
aux_loss_sums += aux_losses.detach()
count += 1
progressbar.set_description(f"Epoch {epoch} | Loss: {loss.item():.4f}")
scheduler.step()
avg_loss = total_loss / count if count > 0 else 0
to_log = {
'loss/avg_loss': avg_loss,
'grad_norm': nn_utils.clip_grad_norm_(model.parameters(), float('inf')),
'learning_rate': optimizer.param_groups[0]['lr'],
}
# Add averaged aux losses
aux_loss_avgs = (aux_loss_sums / count).cpu().numpy()
for name, value in zip(model.aux_loss_names, aux_loss_avgs):
to_log["loss/"+name] = float(value)
mprint(f"{name} = {value:.4f}")
if is_master and (epoch % config.train['save_interval'] == 0 or epoch == total_epochs - 1):
ckptr.save_checkpoint(epoch, model, optimizer, scheduler, avg_loss) # type: ignore
if config.train['save_samples']:
samples = model.sample(sample_colors, sample_label_tr, 50)
svg = xyac_to_svgs(samples, dataset.symmetry, dataset.side)[0]
svg_fname = f"sv{config.timestamp}_e{epoch:03d}_{sample_name}.svg"
ckptr.save_svg(svg, svg_fname) # type: ignore
wandblog.lsvg(epoch, svg, sample_label, sample_name)
loss_lattice = lattice_loss(dataset.symmetry, samples, dataset.side)
to_log['loss/lattice_sample'] = loss_lattice
mprint(f"Lattice loss: {loss_lattice:.4f}")
wandblog.log_step(to_log, step=epoch)
mprint(f"Epoch {epoch} done. Average Loss: {avg_loss:.4f}\n")
wandblog.finish()
mprint("\n======\nDone!\n======")
#------
# Main
#------
if __name__ == "__main__":
config = Config()
print(config)
compat.launch(train_fn, (config,))