Skip to content

Commit 9d9eb66

Browse files
authored
Merge pull request #20 from AllenNeuralDynamics/feat-amp
feat: train with amp
2 parents 134c1f8 + f4e54db commit 9d9eb66

3 files changed

Lines changed: 19 additions & 118 deletions

File tree

src/aind_exaspim_image_compression/machine_learning/train.py

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
99
"""
1010

11+
from contextlib import nullcontext
1112
from datetime import datetime
1213
from numcodecs import blosc
1314
from torch.optim.lr_scheduler import CosineAnnealingLR
@@ -34,7 +35,8 @@ def __init__(
3435
device="cuda:0",
3536
lr=1e-3,
3637
max_epochs=200,
37-
model=None
38+
model=None,
39+
use_amp=True,
3840
):
3941
"""
4042
Instantiates a Trainer object.
@@ -53,6 +55,8 @@ def __init__(
5355
Maximum number of training epochs. Default is 200.
5456
model : None or nn.Module, optional
5557
Model to be trained on the given datasets. Default is None.
58+
use_amp : bool, optional
59+
Indication of whether to use mixed precision. Default is True.
5660
"""
5761
# Initializations
5862
exp_name = "session-" + datetime.today().strftime("%Y%m%d_%H%M")
@@ -63,18 +67,19 @@ def __init__(
6367
self.batch_size = batch_size
6468
self.device = device
6569
self.max_epochs = max_epochs
66-
self.log_dir = log_dir
70+
self.log_dir = log_dir
6771

6872
self.codec = blosc.Blosc(cname="zstd", clevel=5, shuffle=blosc.SHUFFLE)
6973
self.criterion = nn.L1Loss()
74+
self.model = model.to(device) if model else UNet().to(device)
7075
self.optimizer = optim.AdamW(self.model.parameters(), lr=lr)
7176
self.scheduler = CosineAnnealingLR(self.optimizer, T_max=25)
7277
self.writer = SummaryWriter(log_dir=log_dir)
7378

74-
if model is None:
75-
self.model = UNet().to("cuda")
79+
if use_amp:
80+
self.autocast = torch.autocast(device_type="cuda", dtype=torch.float16)
7681
else:
77-
self.model = model
82+
self.autocast = nullcontext()
7883

7984
# --- Core Routines ---
8085
def run(self, train_dataset, val_dataset):
@@ -176,7 +181,7 @@ def validate_step(self, val_dataloader, epoch):
176181
losses.append(loss.detach().cpu())
177182

178183
# Log results
179-
loss, cratio = np.mean(losses), np.mean(cratios)
184+
loss, cratio = np.mean(losses), np.median(cratios)
180185
self.writer.add_scalar("val_loss", loss, epoch)
181186
self.writer.add_scalar("val_cratio", cratio, epoch)
182187

@@ -206,11 +211,12 @@ def forward_pass(self, x, y):
206211
loss : torch.Tensor
207212
Computed loss value.
208213
"""
209-
x = x.to("cuda")
210-
y = y.to("cuda")
211-
hat_y = self.model(x)
212-
loss = self.criterion(hat_y, y)
213-
return hat_y, loss
214+
with self.autocast:
215+
x = x.to("cuda")
216+
y = y.to("cuda")
217+
hat_y = self.model(x)
218+
loss = self.criterion(hat_y, y)
219+
return hat_y, loss
214220

215221
# --- Helpers ---
216222
def compute_cratios(self, imgs, mn_mx):

src/aind_exaspim_image_compression/machine_learning/unet3d.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,10 +138,10 @@ def __init__(self, in_channels, out_channels, mid_channels=None):
138138

139139
# Instance attributes
140140
self.double_conv = nn.Sequential(
141-
nn.Conv3d(in_channels, mid_channels, kernel_size=3, padding=1),
141+
nn.Conv3d(in_channels, mid_channels, kernel_size=4, padding=1),
142142
nn.BatchNorm3d(mid_channels),
143143
nn.LeakyReLU(negative_slope=0.01, inplace=True),
144-
nn.Conv3d(mid_channels, out_channels, kernel_size=3, padding=1),
144+
nn.Conv3d(mid_channels, out_channels, kernel_size=4, padding=1),
145145
nn.BatchNorm3d(out_channels),
146146
nn.LeakyReLU(negative_slope=0.01, inplace=True)
147147
)

src/aind_exaspim_image_compression/machine_learning/vit3d.py

Lines changed: 0 additions & 105 deletions
This file was deleted.

0 commit comments

Comments
 (0)