88
99"""
1010
11+ from contextlib import nullcontext
1112from datetime import datetime
1213from numcodecs import blosc
1314from 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 ):
0 commit comments