-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_funcs.py
278 lines (224 loc) · 8.02 KB
/
utils_funcs.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# native imports
import os
import argparse
import time
# third-party imports
import torch
import torch.nn as nn
from torchvision.utils import make_grid
import matplotlib.pyplot as plt
import numpy as np
def denormalize(images, means, stds):
"""
Denormalizes image tensors using given means and standard deviations.
Args:
images (torch.Tensor): Images tensor to be denormalized.
means (torch.Tensor): Means used for denormalization.
stds (torch.Tensor): Standard deviations used for denormalization.
Returns:
torch.Tensor: Denormalized images.
"""
means = means.clone().detach()
means = means.reshape(1, 3, 1, 1)
stds = stds.clone().detach()
stds = stds.reshape(1, 3, 1, 1)
means = means.to(get_default_device())
stds = stds.to(get_default_device())
return images * stds + means
def show_batch(dl, stats, save_path):
"""
Displays and saves a batch of images from the dataloader after denormalization.
Args:
data_loader (torch.utils.data.DataLoader): DataLoader instance to fetch data from.
stats (tuple): A tuple containing means and standard deviations for denormalization.
save_path (str): Path where the figure of images should be saved.
"""
for images, labels in dl:
fig, ax = plt.subplots(figsize=(12, 12))
ax.set_xticks([])
ax.set_yticks([])
denorm_images = denormalize(images, *stats)
denorm_images = denorm_images.cpu()
ax.imshow(make_grid(denorm_images[:64], nrow=8).permute(1, 2, 0).clamp(0, 1))
plt.savefig(save_path) # Save the figure to a file
plt.close(fig) # Close the figure to free up memory
break
def get_default_device():
"""Pick GPU if available, else CPU"""
if torch.cuda.is_available():
return torch.device("cuda")
else:
return torch.device("cpu")
def to_device(data, device):
"""Move tensor(s) to chosen device"""
if isinstance(data, (list, tuple)):
return [to_device(x, device) for x in data]
return data.to(device, non_blocking=True)
def accuracy(outputs, labels):
"""
Calculates accuracy for the given batch of outputs and labels.
Args:
outputs (torch.Tensor): Model's predictions.
labels (torch.Tensor): Actual labels.
Returns:
torch.Tensor: Accuracy value.
"""
_, preds = torch.max(outputs, dim=1)
return torch.tensor(torch.sum(preds == labels).item() / len(preds))
# building the model functions
def conv_block(in_channels, out_channels, pool=False):
"""
Returns a block of convolutional layers with optional pooling.
Args:
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
pool (bool, optional): Whether to include max pooling. Defaults to False.
Returns:
nn.Sequential: Convolutional block.
"""
layers = [
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
]
if pool:
layers.append(nn.MaxPool2d(2))
return nn.Sequential(*layers)
@torch.no_grad()
def evaluate(model, val_loader):
"""
Evaluates the model on the given validation loader.
Args:
model (nn.Module): Model to be evaluated.
val_loader (torch.utils.data.DataLoader): DataLoader instance for validation data.
Returns:
dict: Dictionary containing validation loss and accuracy.
"""
model.eval()
outputs = [model.validation_step(batch) for batch in val_loader]
return model.validation_epoch_end(outputs)
def get_lr(optimizer):
"""
Retrieves the current learning rate from the optimizer.
Args:
optimizer (torch.optim.Optimizer): Optimizer instance.
Returns:
float: Current learning rate.
"""
for param_group in optimizer.param_groups:
return param_group["lr"]
def fit_one_cycle(
epochs,
max_lr,
model,
train_loader,
val_loader,
weight_decay=0,
grad_clip=None,
opt_func=torch.optim.SGD,
checkpoint_dir="checkpoints",
top_k=3,
):
"""
Trains a model using the one-cycle policy.
Args:
epochs (int): Number of epochs for training.
max_lr (float): Maximum learning rate.
model (nn.Module): Model to be trained.
train_loader (torch.utils.data.DataLoader): DataLoader instance for training data.
val_loader (torch.utils.data.DataLoader): DataLoader instance for validation data.
weight_decay (float, optional): Weight decay parameter. Defaults to 0.
grad_clip (float, optional): Gradient clipping threshold. Defaults to None.
opt_func (torch.optim.Optimizer, optional): Optimizer class to be used. Defaults to torch.optim.SGD.
checkpoint_dir (str, optional): Directory to save checkpoints. Defaults to "checkpoints".
top_k (int, optional): Unused parameter in the current function. Defaults to 3.
Returns:
list[dict]: List of dictionaries containing training results for each epoch.
"""
torch.cuda.empty_cache()
history = []
# create checkpoint directory if it doesn't exist
os.makedirs(checkpoint_dir, exist_ok=True)
# Set up cutom optimizer with weight decay
optimizer = opt_func(model.parameters(), max_lr, weight_decay=weight_decay)
# Set up one-cycle learning rate scheduler
sched = torch.optim.lr_scheduler.OneCycleLR(
optimizer, max_lr, epochs=epochs, steps_per_epoch=len(train_loader)
)
for epoch in range(epochs):
# Training Phase
model.train()
train_losses = []
lrs = []
for batch in train_loader:
loss = model.training_step(batch)
train_losses.append(loss)
loss.backward()
# Gradient clipping
if grad_clip:
nn.utils.clip_grad_value_(model.parameters(), grad_clip)
optimizer.step()
optimizer.zero_grad()
# Record & update learning rate
lrs.append(get_lr(optimizer))
sched.step()
# Validation phase
result = evaluate(model, val_loader)
result["train_loss"] = torch.stack(train_losses).mean().item()
result["lrs"] = lrs
model.epoch_end(epoch, result)
history.append(result)
# save model checkpoint for the current epoch
timestr = time.strftime("%Y%m%d-%H%M%S")
checkpoint_file = f"{checkpoint_dir}/model_epoch_{timestr}.pth"
torch.save(model.state_dict(), checkpoint_file)
return history
def plot_losses(history, save_path):
train_losses = [x.get("train_loss") for x in history]
val_losses = [x["val_loss"] for x in history]
plt.plot(train_losses, "-bx")
plt.plot(val_losses, "-rx")
plt.xlabel("epoch")
plt.ylabel("loss")
plt.legend(["Training", "Validation"])
plt.title("Loss vs. No. of epochs")
plt.savefig(save_path) # Save the figure to a file
plt.close() # Close the figure to free up memory
def plot_lrs(history, save_path):
lrs = np.concatenate([x.get("lrs", []) for x in history])
plt.plot(lrs)
plt.xlabel("Batch no.")
plt.ylabel("Learning rate")
plt.title("Learning Rate vs. Batch no.")
plt.savefig(save_path) # Save the figure to a file
plt.close() # Close the figure to free up memory
def create_parser():
"""
Create a parser for command line arguments.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--hyper_params_config_path",
help="path to hyper-parameters config file",
type=str,
required=True,
)
parser.add_argument(
"--batch_images_path",
help="path to save batch of images",
type=str,
required=True,
)
parser.add_argument(
"--loss_image_path",
help="path to save loss plot",
type=str,
required=True,
)
parser.add_argument(
"--lr_image_path",
help="path to save learning rate plot",
type=str,
required=True,
)
return parser