torch_em.trainer.default_trainer

  1from __future__ import annotations
  2
  3import os
  4import time
  5import inspect
  6import warnings
  7import contextlib
  8from tqdm import tqdm
  9from functools import partial
 10from datetime import datetime
 11from collections import OrderedDict
 12from importlib import import_module
 13from typing import Any, Callable, Dict, Optional, Union, Literal
 14
 15import numpy as np
 16
 17import torch
 18
 19from .wandb_logger import WandbLogger
 20from .tensorboard_logger import TensorboardLogger
 21from ..util import auto_compile, get_constructor_arguments, is_compiled
 22
 23
 24class DefaultTrainer:
 25    """Trainer class for training a segmentation network.
 26
 27    The trainer class implements the core logic for training a network with pytorch.
 28    It implements a training loop to run training and validation, which is started with `fit`.
 29    The checkpoints and logs from the training run will be saved in the current working directory,
 30    or in the directory specifified by `save_root`. Training can be continued from a checkpoint
 31    by passing it's location to the `load_from_checkpoint` argument of `fit`.
 32
 33    A pre-configured instance of the trainer can be obtained from `torch_em.default_segmentation_trainer`.
 34    Alternatively, the trainer class can also be instantiated as in this example:
 35    ```python
 36    import torch
 37    from torch_em.loss import DiceLoss
 38    from torch_em.model import UNet2d
 39    from torch_em.data.datasets.light_microscopy import get_dsb_loader
 40    from torch_em.trainer import DefaultTrainer
 41
 42    # The training data will be downloaded to this location.
 43    data_root = "/path/to/save/the/training/data"
 44    patch_shape = (256, 256)
 45
 46    # Create the model and optimizer.
 47    model = UNet2d(in_channels=1, out_channels=1)
 48    optimizer = torch.optim.AdamW(model.parameters())
 49
 50    trainer = DefaultTrainer(
 51        name="unet-training",
 52        train_loader=get_dsb_loader(path=data_root, patch_shape=patch_shape, split="train"),
 53        val_loader=get_dsb_loader(path=data_root, patch_shape=patch_shape, split="test"),
 54        model=model,
 55        loss=DiceLoss(),  # The loss function.
 56        optimizer=optimizer,
 57        metric=DiceLoss(),  # The metric. The trainer expects smaller values to represent better results.
 58        device="cuda",  # The device to use for training.
 59    )
 60    trainer.fit(iterations=int(2.5e4))  # Train for 25.000 iterations.
 61    ```
 62
 63    Args:
 64        name: The name of the checkpoint that will be created by the trainer.
 65        train_loader: The data loader containing the training data.
 66        val_loader: The data loader containing the validation data.
 67        model: The model to train.
 68        loss: The loss function for training.
 69        optimizer: The optimizer.
 70        metric: The metric for validation.
 71        device: The torch device to use for training. If None, will use a GPU if available.
 72        lr_scheduler: The learning rate scheduler.
 73        log_image_interval: The interval for saving images during logging, in training iterations.
 74        mixed_precision: Whether to train with mixed precision.
 75        early_stopping: The patience for early stopping in epochs. If None, early stopping will not be used.
 76        logger: The logger class. Will be instantiated for logging.
 77            By default uses `torch_em.training.tensorboard_logger.TensorboardLogger`.
 78        logger_kwargs: The keyword arguments for the logger class.
 79        id_: Unique identifier for the trainer. If None then `name` will be used.
 80        save_root: The root folder for saving the checkpoint and logs.
 81        compile_model: Whether to compile the model before training.
 82        rank: Rank argument for distributed training. See `torch_em.multi_gpu_training` for details.
 83        mixed_precision_dtype: The dtype for autocast in mixed precision training, 'float16' or 'bfloat16'.
 84            The default is 'float16' on the GPU and 'bfloat16' on the CPU. Use 'bfloat16' to avoid overflows.
 85    """
 86    def __init__(
 87        self,
 88        name: Optional[str],
 89        train_loader: torch.utils.data.DataLoader,
 90        val_loader: torch.utils.data.DataLoader,
 91        model: torch.nn.Module,
 92        loss: torch.nn.Module,
 93        optimizer: torch.optim.Optimizer,
 94        metric: Callable,
 95        device: Union[str, torch.device],
 96        lr_scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None,
 97        log_image_interval: int = 100,
 98        mixed_precision: bool = True,
 99        early_stopping: Optional[int] = None,
100        logger=TensorboardLogger,
101        logger_kwargs: Optional[Dict[str, Any]] = None,
102        id_: Optional[str] = None,
103        save_root: Optional[str] = None,
104        compile_model: Optional[Union[bool, str]] = None,
105        rank: Optional[int] = None,
106        mixed_precision_dtype: Optional[str] = None,
107    ):
108        if name is None and not issubclass(logger, WandbLogger):
109            raise TypeError("Name cannot be None if not using the WandbLogger")
110
111        self._generate_name = name is None
112        self.name = name
113        self.id_ = id_ or name
114        self.train_loader = train_loader
115        self.val_loader = val_loader
116        self.model = model
117        self.loss = loss
118        self.optimizer = optimizer
119        self.metric = metric
120        self.device = torch.device(device)
121        self.lr_scheduler = lr_scheduler
122        self.log_image_interval = log_image_interval
123        self.save_root = save_root
124        self.compile_model = compile_model
125        self.rank = rank
126        self._device_type = "cpu" if self.device.type == "cpu" else "cuda"
127
128        self._iteration = 0
129        self._epoch = 0
130        self._best_epoch = 0
131        # The best validation metric of this training. It is restored by `load_checkpoint`.
132        self.best_metric = np.inf
133
134        self.mixed_precision = mixed_precision
135        # These are the defaults of torch.autocast for each device type.
136        self.mixed_precision_dtype = mixed_precision_dtype or ("bfloat16" if self._device_type == "cpu" else "float16")
137        self.early_stopping = early_stopping
138        self.train_time = 0.0
139
140        if mixed_precision:
141            # Only float16 needs gradient scaling. bfloat16 has the same range as float32.
142            self.scaler = torch.GradScaler(self._device_type, enabled=self.mixed_precision_dtype == "float16")
143        else:
144            self.scaler = None
145
146        self.logger_class = logger
147        self.logger_kwargs = logger_kwargs
148        self.log_image_interval = log_image_interval
149
150    @property
151    def checkpoint_folder(self):
152        assert self.id_ is not None  # Because the logger may generate and set trainer.id on logger.__init__.
153        # Save_root enables saving the checkpoints somewhere else than in the local folder.
154        # This is handy for filesystems with limited space, where saving the checkpoints
155        # and log files can lead to running out of space.
156        save_root = getattr(self, "save_root", None)
157        return os.path.join("./checkpoints", self.id_) if save_root is None else\
158            os.path.join(save_root, "./checkpoints", self.id_)
159
160    @property
161    def iteration(self):
162        return self._iteration
163
164    @property
165    def epoch(self):
166        return self._epoch
167
168    class Deserializer:
169        """Determines how to deserialize the trainer kwargs from serialized 'init_data'.
170
171        Examples:
172            To extend the initialization process you can inherite from this Deserializer in an inherited Trainer class.
173            Note that `DefaultTrainer.Deserializer.load_generic()` covers most cases already.
174
175            This example adds `the_answer` kwarg, which requires 'calculations' upon initialization:
176            >>> class MyTrainer(DefaultTrainer):
177            >>>     def __init__(self, *args, the_answer: int, **kwargs):
178            >>>         super().__init__(*args, **kwargs)
179            >>>         self.the_answer = the_answer  # this allows the default Serializer to save the new kwarg,
180            >>>                                       # see DefaultTrainer.Serializer
181            >>>
182            >>>     class Deserializer(DefaultTrainer.Deserializer):
183            >>>         def load_the_answer(self):
184            >>>             generic_answer = self.init_data["the_answer"]
185            >>>             # (device dependent) special deserialization
186            >>>             if self.trainer_kwargs["device"].type == "cpu":  # accessing previously deserialized kwarg
187            >>>                 self.trainer_kwargs["the_answer"] = generic_answer + 1
188            >>>             else:
189            >>>                 self.trainer_kwargs["the_answer"] = generic_answer * 2
190
191        Args:
192            init_data: The initialization data of the trainer.
193            save_path: The path where the checkpoint was saved.
194            device: The device.
195        """
196
197        def __init__(self, init_data: Dict, save_path: str, device: Union[str, torch.device]):
198            self.init_data = init_data
199            self.save_path = save_path
200            # Populate with deserialized trainer kwargs during deserialization; possibly overwrite 'device'.
201            self.trainer_kwargs: Dict[str, Any] = dict(
202                device=torch.device(self.init_data["device"]) if device is None else torch.device(device)
203            )
204
205        def load(self, kwarg_name: str, optional):
206            """@private
207            """
208            # `optional` is True if self.trainer.__class__.__init__ specifies a default value for 'kwarg_name'
209            if kwarg_name == "device":
210                pass  # deserialized in __init__
211            elif kwarg_name.endswith("_loader"):
212                self.load_data_loader(kwarg_name, optional)
213            else:
214                load = getattr(self, f"load_{kwarg_name}", self.load_generic)
215                load(kwarg_name, optional=optional)
216
217        def load_data_loader(self, loader_name, optional) -> None:
218            """@private
219            """
220            ds = self.init_data.get(loader_name.replace("_loader", "_dataset"))
221            if ds is None and optional:
222                return
223
224            loader_kwargs = self.init_data[f"{loader_name}_kwargs"]
225            loader = torch.utils.data.DataLoader(ds, **loader_kwargs)
226            # monkey patch shuffle loader_name to the loader
227            loader.shuffle = loader_kwargs.get("shuffle", False)
228            self.trainer_kwargs[loader_name] = loader
229
230        def load_generic(
231            self,
232            kwarg_name: str,
233            *dynamic_args: Dict,
234            optional: bool,
235            only_class: bool = False,
236            dynamic_kwargs: Optional[Dict[str, Any]] = None,
237        ) -> None:
238            """@private
239            """
240            if kwarg_name in self.init_data:
241                self.trainer_kwargs[kwarg_name] = self.init_data[kwarg_name]
242                return
243
244            this_cls = self.init_data.get(f"{kwarg_name}_class", None)
245            if this_cls is None:
246                if optional:
247                    return
248                else:
249                    raise RuntimeError(f"Could not find init data for {kwarg_name} in {self.save_path}")
250
251            assert isinstance(this_cls, str), this_cls
252            assert "." in this_cls, this_cls
253            cls_p, cls_m = this_cls.rsplit(".", 1)
254            this_cls = getattr(import_module(cls_p), cls_m)
255            if only_class:
256                self.trainer_kwargs[kwarg_name] = this_cls
257            else:
258                self.trainer_kwargs[kwarg_name] = this_cls(
259                    *dynamic_args, **self.init_data.get(f"{kwarg_name}_kwargs", {}), **(dynamic_kwargs or {})
260                )
261
262        def load_name(self, kwarg_name: str, optional: bool):
263            """@private
264            """
265            self.trainer_kwargs[kwarg_name] = os.path.split(os.path.dirname(self.save_path))[1]
266
267        def load_optimizer(self, kwarg_name: str, optional: bool):
268            """@private
269            """
270            self.load_generic(kwarg_name, self.trainer_kwargs["model"].parameters(), optional=optional)
271
272        def load_lr_scheduler(self, kwarg_name: str, optional: bool):
273            """@private
274            """
275            self.load_generic(kwarg_name, self.trainer_kwargs["optimizer"], optional=optional)
276
277        # todo: remove and rename kwarg 'logger' to 'logger_class'
278        def load_logger(self, kwarg_name: str, optional: bool):
279            """@private
280            """
281            assert kwarg_name == "logger"
282            self.load_generic("logger", optional=optional, only_class=True)
283
284    @staticmethod
285    def _get_save_dict(save_path, device):
286        if not os.path.exists(save_path):
287            raise ValueError(f"Cannot find checkpoint {save_path}")
288        return torch.load(save_path, map_location=device, weights_only=False)
289
290    @classmethod
291    def from_checkpoint(
292        cls,
293        checkpoint_folder: Union[os.PathLike, str],
294        name: Literal["best", "latest"] = "best",
295        device: Optional[Union[str, torch.device]] = None,
296    ):
297        """@private
298        """
299        save_path = os.path.join(checkpoint_folder, f"{name}.pt")
300        # make sure the correct device is set if we don't have access to CUDA
301        if not torch.cuda.is_available():
302            device = "cpu"
303        save_dict = cls._get_save_dict(save_path, device)
304        deserializer = cls.Deserializer(save_dict["init"], save_path, device)
305
306        has_kwargs = False
307        deserialized = []
308        for name, parameter in inspect.signature(cls).parameters.items():
309            if name == "kwargs":
310                has_kwargs = True
311                continue
312            deserializer.load(name, optional=parameter.default is not inspect.Parameter.empty)
313            deserialized.append(name)
314
315        # to deserialze kwargs we can't rely on inspecting the signature, so we
316        # go through the remaning kwarg names in init data instead
317        if has_kwargs:
318            kwarg_names = list(set(deserializer.init_data.keys()) - set(deserialized))
319            for name in kwarg_names:
320                if name.endswith("_kwargs"):
321                    continue
322                elif name.endswith("_dataset"):
323                    deserializer.load(name.replace("dataset", "loader"), optional=False)
324                elif name.endswith("_class"):
325                    deserializer.load(name.replace("_class", ""), optional=False)
326                else:
327                    deserializer.load(name, optional=False)
328
329        trainer = cls(**deserializer.trainer_kwargs)
330        trainer._initialize(0, save_dict)
331        trainer._is_initialized = True
332        return trainer
333
334    class Serializer:
335        """Implements how to serialize trainer kwargs from a trainer instance.
336
337        Examples:
338            To extend the serialization process you can inherite from this Serializer in a derived Trainer class.
339            Note that the methods `dump_generic_builtin()`, `dump_generic_class()` and `dump_generic_instance()`
340            called by the `dump()` method when appropriate cover most cases already.
341
342            This example adds `the_answer` kwarg, which requires extra steps on dumping only because we don't keep a
343            'the_answer' attribute:
344            >>> class MyTrainer(DefaultTrainer):
345            >>>     def __init__(self, *args, the_answer: int, **kwargs):
346            >>>         super().__init__(*args, **kwargs)
347            >>>         # self.the_answer = the_answer  # this would allow the default Serializer to save the new kwarg,
348            >>>         # but let's make things more interesting...
349            >>>         self.the = the_answer // 10
350            >>>         self.answer = the_answer % 10
351            >>>
352            >>>     class Serializer(DefaultTrainer.Serializer):
353            >>>         trainer: MyTrainer
354            >>>         def dump_the_answer(self, kwarg_name: str) -> None:  # custom dump method for 'the_answer' kwarg
355            >>>             assert kwarg_name == "the_answer"
356            >>>             # populate self.init_data with the serialized data required by Deserializer
357            >>>             # to restore the trainer kwargs
358            >>>             self.init_data["the_answer"] = self.trainer.the * 10 + self.trainer.answer
359
360            This example with both Serializer and Deserializer adds `the_answer` kwarg,
361            while saving it in two separate entries 'the' and 'answer'
362            >>> class MyTrainer(DefaultTrainer):
363            >>>     def __init__(self, *args, the_answer: int, **kwargs):
364            >>>         super().__init__(*args, **kwargs)
365            >>>         self.the_answer = the_answer
366            >>>
367            >>>     class Serializer(DefaultTrainer.Serializer):
368            >>>         trainer: MyTrainer
369            >>>         def dump_the_answer(self, kwarg_name: str):
370            >>>             assert kwarg_name == "the_answer"
371            >>>             self.init_data.update({
372            >>>                 "the": self.trainer.the_answer // 10,
373            >>>                 "answer": self.trainer.the_answer % 10
374            >>>             })
375            >>>
376            >>>     class Deserializer(DefaultTrainer.Deserializer):
377            >>>         def load_the_answer(self, kwarg_name: str, optional: bool):
378            >>>             assert kwarg_name == "the_answer"
379            >>>             # 'optional' is True if MyTrainer.__init__ specifies a default value for 'kwarg_name'
380            >>>             self.trainer_kwargs[kwarg_name] = self.init_data["the"] * 10 + self.init_data["answer"]
381
382        Args:
383            trainer: The trainer instance.
384        """
385
386        def __init__(self, trainer: DefaultTrainer):
387            self.trainer = trainer
388            self.init_data = {}  # to be populated during serialization process
389
390        def dump(self, kwarg_name: str) -> None:
391            """@private
392            """
393            dumper = getattr(self, f"dump_{kwarg_name}", None)
394            if dumper is not None:
395                dumper(kwarg_name)
396            elif kwarg_name.endswith("_loader"):
397                self.dump_data_loader(kwarg_name)
398            elif kwarg_name.endswith("_class"):
399                self.dump_generic_class(kwarg_name)
400            elif not hasattr(self.trainer, kwarg_name):
401                raise AttributeError(
402                    f"{self.trainer.__class__} missing attribute '{kwarg_name}' "
403                    f"or special dump method {self.trainer.__class__}.Serializer.dump_{kwarg_name}()"
404                )
405            else:
406                assert hasattr(self.trainer, kwarg_name)
407                obj = getattr(self.trainer, kwarg_name)
408                if obj is None or type(obj) in (
409                    bool,
410                    bytearray,
411                    bytes,
412                    dict,
413                    float,
414                    frozenset,
415                    int,
416                    list,
417                    set,
418                    str,
419                    tuple,
420                ):
421                    self.dump_generic_builtin(kwarg_name)
422                else:
423                    self.dump_generic_instance(kwarg_name)
424
425        def dump_generic_builtin(self, kwarg_name: str) -> None:
426            """@private
427            """
428            assert hasattr(self.trainer, kwarg_name)
429            self.init_data[kwarg_name] = getattr(self.trainer, kwarg_name)
430
431        def dump_generic_class(self, kwarg_name: str) -> None:
432            """@private
433            """
434            assert hasattr(self.trainer, kwarg_name)
435            assert kwarg_name.endswith("_class")
436            obj = getattr(self.trainer, kwarg_name)
437            self.init_data[kwarg_name] = None if obj is None else f"{obj.__module__}.{obj.__name__}"
438
439        def dump_generic_instance(self, kwarg_name: str) -> None:
440            """@private
441            """
442            assert hasattr(self.trainer, kwarg_name)
443            instance = getattr(self.trainer, kwarg_name)
444            self.init_data.update(
445                {
446                    f"{kwarg_name}_class": f"{instance.__class__.__module__}.{instance.__class__.__name__}",
447                    f"{kwarg_name}_kwargs": get_constructor_arguments(instance),
448                }
449            )
450
451        def dump_device(self, kwarg_name: str):
452            """@private
453            """
454            assert hasattr(self.trainer, kwarg_name)
455            self.init_data[kwarg_name] = str(getattr(self.trainer, kwarg_name))
456
457        def dump_data_loader(self, kwarg_name: str) -> None:
458            """@private
459            """
460            assert hasattr(self.trainer, kwarg_name)
461            loader = getattr(self.trainer, kwarg_name)
462            if loader is None:
463                return
464            self.init_data.update(
465                {
466                    f"{kwarg_name.replace('_loader', '_dataset')}": loader.dataset,
467                    f"{kwarg_name}_kwargs": get_constructor_arguments(loader),
468                }
469            )
470
471        def dump_logger(self, kwarg_name: str):  # todo: remove and rename kwarg 'logger' to 'logger_class'
472            """@private
473            """
474            self.dump_generic_class(f"{kwarg_name}_class")
475
476        def dump_model(self, kwarg_name: str):
477            """@private
478            """
479            if is_compiled(self.trainer.model):
480                self.init_data.update(
481                    {"model_class": self.trainer._model_class, "model_kwargs": self.trainer._model_kwargs}
482                )
483            else:
484                self.dump_generic_instance("model")
485
486    def _build_init(self) -> Dict[str, Any]:
487        serializer = self.Serializer(self)
488        for name in inspect.signature(self.__class__).parameters:
489            # special rules to serialize kwargs
490            # if a trainer class inherits from DefaultTrainer and has **kwargs
491            # they need to be saved in self._kwargs
492            if name == "kwargs":
493                if not hasattr(self, "_kwargs"):
494                    msg = "The trainer class has **kwargs in its signature, but is missing the _kwargs attribute. " +\
495                          "Please add self._kwargs to its __init__ function"
496                    raise RuntimeError(msg)
497                kwargs = getattr(self, "_kwargs")
498                for kwarg_name in kwargs:
499                    serializer.dump(kwarg_name)
500                continue
501            serializer.dump(name)
502
503        return serializer.init_data
504
505    def _initialize(self, iterations, load_from_checkpoint, epochs=None):
506        assert self.train_loader is not None
507        assert self.val_loader is not None
508        assert self.model is not None
509        assert self.loss is not None
510        assert self.optimizer is not None
511        assert self.metric is not None
512        assert self.device is not None
513
514        if load_from_checkpoint is not None:
515            self.load_checkpoint(load_from_checkpoint)
516
517        if sum((iterations is not None, epochs is not None)) != 1:
518            raise ValueError(
519                "Exactly one of 'iterations' or 'epochs' has to be specified to initialize the trainer."
520                f"You have passed 'iterations'={iterations} and 'epochs'={epochs}"
521            )
522
523        if epochs is None:
524            epochs = int(np.ceil(float(iterations) / len(self.train_loader)))
525        else:
526            iterations = epochs * len(self.train_loader)
527
528        self.max_iteration = self._iteration + iterations
529        self.max_epoch = self._epoch + epochs
530
531        if not getattr(self, "_is_initialized", False):
532            # check if we compile the model (only supported by pytorch 2)
533            # to enable (de)serialization of compiled models, we keep track of the model class and kwargs
534            if is_compiled(self.model):
535                warnings.warn(
536                    "You have passed a compiled model to the trainer."
537                    "It will not be possible to (de)serialize the trainer with it."
538                    "If you want to be able to do this please pass the normal model."
539                    "It can be automatically compiled by setting 'compile_model' to True"
540                )
541            self._model_class = f"{self.model.__class__.__module__}.{self.model.__class__.__name__}"
542            self._model_kwargs = get_constructor_arguments(self.model)
543            self.model = auto_compile(self.model, self.compile_model)
544
545            self.model.to(self.device)
546            self.loss.to(self.device)
547
548            # this saves all the information that is necessary
549            # to fully load the trainer from the checkpoint
550            self.init_data = self._build_init()
551
552            if self.logger_class is None:
553                self.logger = None
554            else:
555                # may set self.name if self.name is None
556                save_root = getattr(self, "save_root", None)
557                try:
558                    self.logger = self.logger_class(self, save_root, **(self.logger_kwargs or {}))
559                except (PermissionError, RuntimeError):
560                    warnings.warn(
561                        f"The checkpoint folder at {self.checkpoint_folder} could not be created."
562                        "The most likely reason for this is that you copied the checkpoint somewhere else,"
563                        "so we skip this error to enable loading the model from this checkpoint."
564                    )
565
566            try:
567                os.makedirs(self.checkpoint_folder, exist_ok=True)
568            except PermissionError:
569                warnings.warn(
570                    f"The checkpoint folder at {self.checkpoint_folder} could not be created."
571                    "The most likely reason for this is that you copied the checkpoint somewhere else,"
572                    "so we skip this error to enable loading the model from this checkpoint."
573                )
574                pass
575
576        # The best metric so far: infinity for a new training, otherwise the value of the loaded checkpoint
577        # or of the previous call to `fit`. So a training that is continued only replaces the best checkpoint
578        # with an epoch that is better than all epochs before it.
579        return self.best_metric
580
581    def save_checkpoint(self, name, current_metric, best_metric, train_time=0.0, **extra_save_dict):
582        """@private
583        """
584        save_path = os.path.join(self.checkpoint_folder, f"{name}.pt")
585        extra_init_dict = extra_save_dict.pop("init", {})
586        save_dict = {
587            "iteration": self._iteration,
588            "epoch": self._epoch,
589            "best_epoch": self._best_epoch,
590            "best_metric": best_metric,
591            "current_metric": current_metric,
592            "model_state": self.model.state_dict(),
593            "optimizer_state": self.optimizer.state_dict(),
594            "init": self.init_data | extra_init_dict,
595            "train_time": train_time,
596            "timestamp": datetime.now().strftime("%d-%m-%Y (%H:%M:%S)"),
597        }
598        save_dict.update(**extra_save_dict)
599        if self.scaler is not None:
600            save_dict.update({"scaler_state": self.scaler.state_dict()})
601        if self.lr_scheduler is not None:
602            save_dict.update({"scheduler_state": self.lr_scheduler.state_dict()})
603
604        rank = getattr(self, "rank", None)
605        if rank is None or rank == 0:
606            torch.save(save_dict, save_path)
607
608    def load_checkpoint(self, checkpoint="best"):
609        """@private
610        """
611        if isinstance(checkpoint, str):
612            save_path = os.path.join(self.checkpoint_folder, f"{checkpoint}.pt")
613            if not os.path.exists(save_path):
614                warnings.warn(f"Cannot load checkpoint. {save_path} does not exist.")
615                return
616            save_dict = torch.load(save_path, weights_only=False)
617        elif isinstance(checkpoint, dict):
618            save_dict = checkpoint
619        else:
620            raise RuntimeError
621
622        self._iteration = save_dict["iteration"]
623        # Checkpoints are saved at the end of an epoch, before the epoch counter is incremented.
624        # So the stored value is the index of the last finished epoch, and the next epoch has the index + 1.
625        self._epoch = save_dict["epoch"] + 1
626        self._best_epoch = save_dict["best_epoch"]
627        self.best_metric = save_dict["best_metric"]
628        self.current_metric = save_dict["current_metric"]
629        self.train_time = save_dict.get("train_time", 0.0)
630
631        model_state = save_dict["model_state"]
632        # to enable loading compiled models
633        compiled_prefix = "_orig_mod."
634        model_state = OrderedDict(
635            [(k[len(compiled_prefix):] if k.startswith(compiled_prefix) else k, v) for k, v in model_state.items()]
636        )
637        self.model.load_state_dict(model_state)
638        # we need to send the network to the device before loading the optimizer state!
639        self.model.to(self.device)
640
641        self.optimizer.load_state_dict(save_dict["optimizer_state"])
642        scaler_state = save_dict.get("scaler_state")
643        if self.scaler is not None and scaler_state:
644            self.scaler.load_state_dict(scaler_state)
645        if self.lr_scheduler is not None:
646            self.lr_scheduler.load_state_dict(save_dict["scheduler_state"])
647
648        return save_dict
649
650    def _verify_if_training_completed(self, checkpoint="latest"):
651        save_path = os.path.join(self.checkpoint_folder, f"{checkpoint}.pt")
652        save_dict = torch.load(save_path, weights_only=False) if os.path.exists(save_path) else None
653        if save_dict and self.max_iteration == save_dict.get("iteration"):
654            return True
655        return False
656
657    def fit(
658        self,
659        iterations: Optional[int] = None,
660        load_from_checkpoint: Optional[Union[os.PathLike, str]] = None,
661        epochs: Optional[int] = None,
662        save_every_kth_epoch: Optional[int] = None,
663        progress=None,
664        overwrite_training: bool = True,
665    ):
666        """Run neural network training.
667
668        Exactly one of 'iterations' or 'epochs' has to be passed.
669
670        Args:
671            iterations: How long to train, specified in iterations.
672            load_from_checkpoint: Path to a checkpoint from where training should be continued .
673            epochs: How long to train, specified in epochs.
674            save_every_kth_epoch: Save checkpoints after every kth epoch in a separate file.
675                The corresponding checkpoints will be saved with the naming scheme 'epoch-{epoch}.pt'.
676            progress: Optional progress bar for integration with external tools. Expected to follow the tqdm interface.
677            overwrite_training: Whether to overwrite existing checkpoints in the save directory.
678        """
679        best_metric = self._initialize(iterations, load_from_checkpoint, epochs)
680
681        if not overwrite_training:
682            if load_from_checkpoint is not None:
683                raise ValueError(
684                    "We do not support 'overwrite_training=False' and 'load_from_checkpoint' at the same time."
685                )
686
687            if self._verify_if_training_completed():
688                print(
689                    f"The model is trained for {self.max_iteration} iterations / {self.max_epoch} epochs "
690                    "and 'overwrite_training' is set to 'False'."
691                )
692                print(f"The checkpoints are located at '{os.path.abspath(self.checkpoint_folder)}'.")
693                return
694
695        print(
696            "Start fitting for",
697            self.max_iteration - self._iteration,
698            "iterations / ",
699            self.max_epoch - self._epoch,
700            "epochs",
701        )
702        print("with", len(self.train_loader), "iterations per epoch")
703
704        if self.mixed_precision:
705            train_epoch = self._train_epoch_mixed
706            validate = self._validate_mixed
707            print("Training with mixed precision")
708        else:
709            train_epoch = self._train_epoch
710            validate = self._validate
711            print("Training with single precision")
712
713        total_iterations = epochs * len(self.train_loader) if iterations is None else iterations
714        if progress is None:
715            progress = tqdm(total=total_iterations, desc=f"Epoch {self._epoch}", leave=True)
716        else:
717            progress.total = total_iterations
718            progress.set_description(f"Epoch {self._epoch}")
719
720        msg = "Epoch %i: average [s/it]: %f, current metric: %f, best metric: %f"
721        train_epochs = self.max_epoch - self._epoch
722        t_start = time.time()
723        for epoch in range(train_epochs):
724
725            # Ensure data is shuffled differently at each epoch.
726            try:
727                self.train_loader.sampler.set_epoch(epoch)
728            except AttributeError:
729                pass
730
731            # Run training and validation for this epoch
732            t_per_iter = train_epoch(progress)
733            current_metric = validate()
734
735            # perform all the post-epoch steps:
736
737            # apply the learning rate scheduler
738            if self.lr_scheduler is not None:
739                self.lr_scheduler.step(current_metric)
740
741            # how long did we train in total?
742            total_train_time = (time.time() - t_start) + self.train_time
743
744            # save this checkpoint as the new best checkpoint if
745            # it has the best overall validation metric
746            if current_metric < best_metric:
747                best_metric = current_metric
748                self.best_metric = best_metric
749                self._best_epoch = self._epoch
750                self.save_checkpoint("best", current_metric, best_metric, train_time=total_train_time)
751
752            # save this checkpoint as the latest checkpoint
753            self.save_checkpoint("latest", current_metric, best_metric, train_time=total_train_time)
754
755            # if we save after every k-th epoch then check if we need to save now
756            if save_every_kth_epoch is not None and (self._epoch + 1) % save_every_kth_epoch == 0:
757                self.save_checkpoint(
758                    f"epoch-{self._epoch + 1}", current_metric, best_metric, train_time=total_train_time
759                )
760
761            # if early stopping has been specified then check if the stopping condition is met
762            if self.early_stopping is not None:
763                epochs_since_best = self._epoch - self._best_epoch
764                if epochs_since_best > self.early_stopping:
765                    print("Stopping training because there has been no improvement for", self.early_stopping, "epochs")
766                    break
767
768            self._epoch += 1
769            progress.set_description(msg % (self._epoch, t_per_iter, current_metric, best_metric), refresh=True)
770
771        print(f"Finished training after {self._epoch} epochs / {self._iteration} iterations.")
772        print(f"The best epoch is number {self._best_epoch}.")
773
774        if self._generate_name:
775            self.name = None
776
777        # Update the train time
778        self.train_time = total_train_time
779
780        # TODO save the model to wandb if we have the wandb logger
781        if isinstance(self.logger, WandbLogger):
782            self.logger.get_wandb().finish()
783
784    def _accumulate_gradients(self, loss):
785        """Accumulate gradients without an optimizer step."""
786        if self.mixed_precision:
787            loss = self.scaler.scale(loss)
788        loss.backward()
789
790    def _backprop(self, loss):
791        loss.backward()
792        self.optimizer.step()
793
794    def _backprop_mixed(self, loss):
795        self.scaler.scale(loss).backward()
796        self.scaler.step(self.optimizer)
797        self.scaler.update()
798
799    def _train_epoch(self, progress):
800        return self._train_epoch_impl(progress, contextlib.nullcontext, self._backprop)
801
802    def _train_epoch_mixed(self, progress):
803        return self._train_epoch_impl(
804            progress,
805            partial(torch.autocast, device_type=self._device_type, dtype=getattr(torch, self.mixed_precision_dtype)),
806            self._backprop_mixed
807        )
808
809    def _forward_and_loss(self, x, y):
810        pred = self.model(x)
811        if self._iteration % self.log_image_interval == 0:
812            if pred.requires_grad:
813                pred.retain_grad()
814
815        loss = self.loss(pred, y)
816        return pred, loss
817
818    def _train_epoch_impl(self, progress, forward_context, backprop: Callable[[torch.Tensor], None]):
819        self.model.train()
820
821        n_iter = 0
822        t_per_iter = time.time()
823        for x, y in self.train_loader:
824            x, y = x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True)
825
826            self.optimizer.zero_grad()
827
828            with forward_context():
829                pred, loss = self._forward_and_loss(x, y)
830
831            backprop(loss)
832
833            lr = [pm["lr"] for pm in self.optimizer.param_groups][0]
834            if self.logger is not None:
835                self.logger.log_train(self._iteration, loss, lr, x, y, pred, log_gradients=True)
836
837            self._iteration += 1
838            n_iter += 1
839            if self._iteration >= self.max_iteration:
840                break
841            progress.update(1)
842
843        t_per_iter = (time.time() - t_per_iter) / n_iter
844        return t_per_iter
845
846    def _validate(self):
847        return self._validate_impl(contextlib.nullcontext)
848
849    def _validate_mixed(self):
850        return self._validate_impl(
851            partial(torch.autocast, device_type=self._device_type, dtype=getattr(torch, self.mixed_precision_dtype))
852        )
853
854    def _validate_impl(self, forward_context):
855        self.model.eval()
856
857        metric_val = 0.0
858        loss_val = 0.0
859
860        with torch.no_grad():
861            for x, y in self.val_loader:
862                x, y = x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True)
863                with forward_context():
864                    pred, loss = self._forward_and_loss(x, y)
865                    metric = self.metric(pred, y)
866
867                loss_val += loss.item()
868                metric_val += metric.item()
869
870        metric_val /= len(self.val_loader)
871        loss_val /= len(self.val_loader)
872        if self.logger is not None:
873            self.logger.log_validation(self._iteration, metric_val, loss_val, x, y, pred)
874        return metric_val
class DefaultTrainer:
 25class DefaultTrainer:
 26    """Trainer class for training a segmentation network.
 27
 28    The trainer class implements the core logic for training a network with pytorch.
 29    It implements a training loop to run training and validation, which is started with `fit`.
 30    The checkpoints and logs from the training run will be saved in the current working directory,
 31    or in the directory specifified by `save_root`. Training can be continued from a checkpoint
 32    by passing it's location to the `load_from_checkpoint` argument of `fit`.
 33
 34    A pre-configured instance of the trainer can be obtained from `torch_em.default_segmentation_trainer`.
 35    Alternatively, the trainer class can also be instantiated as in this example:
 36    ```python
 37    import torch
 38    from torch_em.loss import DiceLoss
 39    from torch_em.model import UNet2d
 40    from torch_em.data.datasets.light_microscopy import get_dsb_loader
 41    from torch_em.trainer import DefaultTrainer
 42
 43    # The training data will be downloaded to this location.
 44    data_root = "/path/to/save/the/training/data"
 45    patch_shape = (256, 256)
 46
 47    # Create the model and optimizer.
 48    model = UNet2d(in_channels=1, out_channels=1)
 49    optimizer = torch.optim.AdamW(model.parameters())
 50
 51    trainer = DefaultTrainer(
 52        name="unet-training",
 53        train_loader=get_dsb_loader(path=data_root, patch_shape=patch_shape, split="train"),
 54        val_loader=get_dsb_loader(path=data_root, patch_shape=patch_shape, split="test"),
 55        model=model,
 56        loss=DiceLoss(),  # The loss function.
 57        optimizer=optimizer,
 58        metric=DiceLoss(),  # The metric. The trainer expects smaller values to represent better results.
 59        device="cuda",  # The device to use for training.
 60    )
 61    trainer.fit(iterations=int(2.5e4))  # Train for 25.000 iterations.
 62    ```
 63
 64    Args:
 65        name: The name of the checkpoint that will be created by the trainer.
 66        train_loader: The data loader containing the training data.
 67        val_loader: The data loader containing the validation data.
 68        model: The model to train.
 69        loss: The loss function for training.
 70        optimizer: The optimizer.
 71        metric: The metric for validation.
 72        device: The torch device to use for training. If None, will use a GPU if available.
 73        lr_scheduler: The learning rate scheduler.
 74        log_image_interval: The interval for saving images during logging, in training iterations.
 75        mixed_precision: Whether to train with mixed precision.
 76        early_stopping: The patience for early stopping in epochs. If None, early stopping will not be used.
 77        logger: The logger class. Will be instantiated for logging.
 78            By default uses `torch_em.training.tensorboard_logger.TensorboardLogger`.
 79        logger_kwargs: The keyword arguments for the logger class.
 80        id_: Unique identifier for the trainer. If None then `name` will be used.
 81        save_root: The root folder for saving the checkpoint and logs.
 82        compile_model: Whether to compile the model before training.
 83        rank: Rank argument for distributed training. See `torch_em.multi_gpu_training` for details.
 84        mixed_precision_dtype: The dtype for autocast in mixed precision training, 'float16' or 'bfloat16'.
 85            The default is 'float16' on the GPU and 'bfloat16' on the CPU. Use 'bfloat16' to avoid overflows.
 86    """
 87    def __init__(
 88        self,
 89        name: Optional[str],
 90        train_loader: torch.utils.data.DataLoader,
 91        val_loader: torch.utils.data.DataLoader,
 92        model: torch.nn.Module,
 93        loss: torch.nn.Module,
 94        optimizer: torch.optim.Optimizer,
 95        metric: Callable,
 96        device: Union[str, torch.device],
 97        lr_scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None,
 98        log_image_interval: int = 100,
 99        mixed_precision: bool = True,
100        early_stopping: Optional[int] = None,
101        logger=TensorboardLogger,
102        logger_kwargs: Optional[Dict[str, Any]] = None,
103        id_: Optional[str] = None,
104        save_root: Optional[str] = None,
105        compile_model: Optional[Union[bool, str]] = None,
106        rank: Optional[int] = None,
107        mixed_precision_dtype: Optional[str] = None,
108    ):
109        if name is None and not issubclass(logger, WandbLogger):
110            raise TypeError("Name cannot be None if not using the WandbLogger")
111
112        self._generate_name = name is None
113        self.name = name
114        self.id_ = id_ or name
115        self.train_loader = train_loader
116        self.val_loader = val_loader
117        self.model = model
118        self.loss = loss
119        self.optimizer = optimizer
120        self.metric = metric
121        self.device = torch.device(device)
122        self.lr_scheduler = lr_scheduler
123        self.log_image_interval = log_image_interval
124        self.save_root = save_root
125        self.compile_model = compile_model
126        self.rank = rank
127        self._device_type = "cpu" if self.device.type == "cpu" else "cuda"
128
129        self._iteration = 0
130        self._epoch = 0
131        self._best_epoch = 0
132        # The best validation metric of this training. It is restored by `load_checkpoint`.
133        self.best_metric = np.inf
134
135        self.mixed_precision = mixed_precision
136        # These are the defaults of torch.autocast for each device type.
137        self.mixed_precision_dtype = mixed_precision_dtype or ("bfloat16" if self._device_type == "cpu" else "float16")
138        self.early_stopping = early_stopping
139        self.train_time = 0.0
140
141        if mixed_precision:
142            # Only float16 needs gradient scaling. bfloat16 has the same range as float32.
143            self.scaler = torch.GradScaler(self._device_type, enabled=self.mixed_precision_dtype == "float16")
144        else:
145            self.scaler = None
146
147        self.logger_class = logger
148        self.logger_kwargs = logger_kwargs
149        self.log_image_interval = log_image_interval
150
151    @property
152    def checkpoint_folder(self):
153        assert self.id_ is not None  # Because the logger may generate and set trainer.id on logger.__init__.
154        # Save_root enables saving the checkpoints somewhere else than in the local folder.
155        # This is handy for filesystems with limited space, where saving the checkpoints
156        # and log files can lead to running out of space.
157        save_root = getattr(self, "save_root", None)
158        return os.path.join("./checkpoints", self.id_) if save_root is None else\
159            os.path.join(save_root, "./checkpoints", self.id_)
160
161    @property
162    def iteration(self):
163        return self._iteration
164
165    @property
166    def epoch(self):
167        return self._epoch
168
169    class Deserializer:
170        """Determines how to deserialize the trainer kwargs from serialized 'init_data'.
171
172        Examples:
173            To extend the initialization process you can inherite from this Deserializer in an inherited Trainer class.
174            Note that `DefaultTrainer.Deserializer.load_generic()` covers most cases already.
175
176            This example adds `the_answer` kwarg, which requires 'calculations' upon initialization:
177            >>> class MyTrainer(DefaultTrainer):
178            >>>     def __init__(self, *args, the_answer: int, **kwargs):
179            >>>         super().__init__(*args, **kwargs)
180            >>>         self.the_answer = the_answer  # this allows the default Serializer to save the new kwarg,
181            >>>                                       # see DefaultTrainer.Serializer
182            >>>
183            >>>     class Deserializer(DefaultTrainer.Deserializer):
184            >>>         def load_the_answer(self):
185            >>>             generic_answer = self.init_data["the_answer"]
186            >>>             # (device dependent) special deserialization
187            >>>             if self.trainer_kwargs["device"].type == "cpu":  # accessing previously deserialized kwarg
188            >>>                 self.trainer_kwargs["the_answer"] = generic_answer + 1
189            >>>             else:
190            >>>                 self.trainer_kwargs["the_answer"] = generic_answer * 2
191
192        Args:
193            init_data: The initialization data of the trainer.
194            save_path: The path where the checkpoint was saved.
195            device: The device.
196        """
197
198        def __init__(self, init_data: Dict, save_path: str, device: Union[str, torch.device]):
199            self.init_data = init_data
200            self.save_path = save_path
201            # Populate with deserialized trainer kwargs during deserialization; possibly overwrite 'device'.
202            self.trainer_kwargs: Dict[str, Any] = dict(
203                device=torch.device(self.init_data["device"]) if device is None else torch.device(device)
204            )
205
206        def load(self, kwarg_name: str, optional):
207            """@private
208            """
209            # `optional` is True if self.trainer.__class__.__init__ specifies a default value for 'kwarg_name'
210            if kwarg_name == "device":
211                pass  # deserialized in __init__
212            elif kwarg_name.endswith("_loader"):
213                self.load_data_loader(kwarg_name, optional)
214            else:
215                load = getattr(self, f"load_{kwarg_name}", self.load_generic)
216                load(kwarg_name, optional=optional)
217
218        def load_data_loader(self, loader_name, optional) -> None:
219            """@private
220            """
221            ds = self.init_data.get(loader_name.replace("_loader", "_dataset"))
222            if ds is None and optional:
223                return
224
225            loader_kwargs = self.init_data[f"{loader_name}_kwargs"]
226            loader = torch.utils.data.DataLoader(ds, **loader_kwargs)
227            # monkey patch shuffle loader_name to the loader
228            loader.shuffle = loader_kwargs.get("shuffle", False)
229            self.trainer_kwargs[loader_name] = loader
230
231        def load_generic(
232            self,
233            kwarg_name: str,
234            *dynamic_args: Dict,
235            optional: bool,
236            only_class: bool = False,
237            dynamic_kwargs: Optional[Dict[str, Any]] = None,
238        ) -> None:
239            """@private
240            """
241            if kwarg_name in self.init_data:
242                self.trainer_kwargs[kwarg_name] = self.init_data[kwarg_name]
243                return
244
245            this_cls = self.init_data.get(f"{kwarg_name}_class", None)
246            if this_cls is None:
247                if optional:
248                    return
249                else:
250                    raise RuntimeError(f"Could not find init data for {kwarg_name} in {self.save_path}")
251
252            assert isinstance(this_cls, str), this_cls
253            assert "." in this_cls, this_cls
254            cls_p, cls_m = this_cls.rsplit(".", 1)
255            this_cls = getattr(import_module(cls_p), cls_m)
256            if only_class:
257                self.trainer_kwargs[kwarg_name] = this_cls
258            else:
259                self.trainer_kwargs[kwarg_name] = this_cls(
260                    *dynamic_args, **self.init_data.get(f"{kwarg_name}_kwargs", {}), **(dynamic_kwargs or {})
261                )
262
263        def load_name(self, kwarg_name: str, optional: bool):
264            """@private
265            """
266            self.trainer_kwargs[kwarg_name] = os.path.split(os.path.dirname(self.save_path))[1]
267
268        def load_optimizer(self, kwarg_name: str, optional: bool):
269            """@private
270            """
271            self.load_generic(kwarg_name, self.trainer_kwargs["model"].parameters(), optional=optional)
272
273        def load_lr_scheduler(self, kwarg_name: str, optional: bool):
274            """@private
275            """
276            self.load_generic(kwarg_name, self.trainer_kwargs["optimizer"], optional=optional)
277
278        # todo: remove and rename kwarg 'logger' to 'logger_class'
279        def load_logger(self, kwarg_name: str, optional: bool):
280            """@private
281            """
282            assert kwarg_name == "logger"
283            self.load_generic("logger", optional=optional, only_class=True)
284
285    @staticmethod
286    def _get_save_dict(save_path, device):
287        if not os.path.exists(save_path):
288            raise ValueError(f"Cannot find checkpoint {save_path}")
289        return torch.load(save_path, map_location=device, weights_only=False)
290
291    @classmethod
292    def from_checkpoint(
293        cls,
294        checkpoint_folder: Union[os.PathLike, str],
295        name: Literal["best", "latest"] = "best",
296        device: Optional[Union[str, torch.device]] = None,
297    ):
298        """@private
299        """
300        save_path = os.path.join(checkpoint_folder, f"{name}.pt")
301        # make sure the correct device is set if we don't have access to CUDA
302        if not torch.cuda.is_available():
303            device = "cpu"
304        save_dict = cls._get_save_dict(save_path, device)
305        deserializer = cls.Deserializer(save_dict["init"], save_path, device)
306
307        has_kwargs = False
308        deserialized = []
309        for name, parameter in inspect.signature(cls).parameters.items():
310            if name == "kwargs":
311                has_kwargs = True
312                continue
313            deserializer.load(name, optional=parameter.default is not inspect.Parameter.empty)
314            deserialized.append(name)
315
316        # to deserialze kwargs we can't rely on inspecting the signature, so we
317        # go through the remaning kwarg names in init data instead
318        if has_kwargs:
319            kwarg_names = list(set(deserializer.init_data.keys()) - set(deserialized))
320            for name in kwarg_names:
321                if name.endswith("_kwargs"):
322                    continue
323                elif name.endswith("_dataset"):
324                    deserializer.load(name.replace("dataset", "loader"), optional=False)
325                elif name.endswith("_class"):
326                    deserializer.load(name.replace("_class", ""), optional=False)
327                else:
328                    deserializer.load(name, optional=False)
329
330        trainer = cls(**deserializer.trainer_kwargs)
331        trainer._initialize(0, save_dict)
332        trainer._is_initialized = True
333        return trainer
334
335    class Serializer:
336        """Implements how to serialize trainer kwargs from a trainer instance.
337
338        Examples:
339            To extend the serialization process you can inherite from this Serializer in a derived Trainer class.
340            Note that the methods `dump_generic_builtin()`, `dump_generic_class()` and `dump_generic_instance()`
341            called by the `dump()` method when appropriate cover most cases already.
342
343            This example adds `the_answer` kwarg, which requires extra steps on dumping only because we don't keep a
344            'the_answer' attribute:
345            >>> class MyTrainer(DefaultTrainer):
346            >>>     def __init__(self, *args, the_answer: int, **kwargs):
347            >>>         super().__init__(*args, **kwargs)
348            >>>         # self.the_answer = the_answer  # this would allow the default Serializer to save the new kwarg,
349            >>>         # but let's make things more interesting...
350            >>>         self.the = the_answer // 10
351            >>>         self.answer = the_answer % 10
352            >>>
353            >>>     class Serializer(DefaultTrainer.Serializer):
354            >>>         trainer: MyTrainer
355            >>>         def dump_the_answer(self, kwarg_name: str) -> None:  # custom dump method for 'the_answer' kwarg
356            >>>             assert kwarg_name == "the_answer"
357            >>>             # populate self.init_data with the serialized data required by Deserializer
358            >>>             # to restore the trainer kwargs
359            >>>             self.init_data["the_answer"] = self.trainer.the * 10 + self.trainer.answer
360
361            This example with both Serializer and Deserializer adds `the_answer` kwarg,
362            while saving it in two separate entries 'the' and 'answer'
363            >>> class MyTrainer(DefaultTrainer):
364            >>>     def __init__(self, *args, the_answer: int, **kwargs):
365            >>>         super().__init__(*args, **kwargs)
366            >>>         self.the_answer = the_answer
367            >>>
368            >>>     class Serializer(DefaultTrainer.Serializer):
369            >>>         trainer: MyTrainer
370            >>>         def dump_the_answer(self, kwarg_name: str):
371            >>>             assert kwarg_name == "the_answer"
372            >>>             self.init_data.update({
373            >>>                 "the": self.trainer.the_answer // 10,
374            >>>                 "answer": self.trainer.the_answer % 10
375            >>>             })
376            >>>
377            >>>     class Deserializer(DefaultTrainer.Deserializer):
378            >>>         def load_the_answer(self, kwarg_name: str, optional: bool):
379            >>>             assert kwarg_name == "the_answer"
380            >>>             # 'optional' is True if MyTrainer.__init__ specifies a default value for 'kwarg_name'
381            >>>             self.trainer_kwargs[kwarg_name] = self.init_data["the"] * 10 + self.init_data["answer"]
382
383        Args:
384            trainer: The trainer instance.
385        """
386
387        def __init__(self, trainer: DefaultTrainer):
388            self.trainer = trainer
389            self.init_data = {}  # to be populated during serialization process
390
391        def dump(self, kwarg_name: str) -> None:
392            """@private
393            """
394            dumper = getattr(self, f"dump_{kwarg_name}", None)
395            if dumper is not None:
396                dumper(kwarg_name)
397            elif kwarg_name.endswith("_loader"):
398                self.dump_data_loader(kwarg_name)
399            elif kwarg_name.endswith("_class"):
400                self.dump_generic_class(kwarg_name)
401            elif not hasattr(self.trainer, kwarg_name):
402                raise AttributeError(
403                    f"{self.trainer.__class__} missing attribute '{kwarg_name}' "
404                    f"or special dump method {self.trainer.__class__}.Serializer.dump_{kwarg_name}()"
405                )
406            else:
407                assert hasattr(self.trainer, kwarg_name)
408                obj = getattr(self.trainer, kwarg_name)
409                if obj is None or type(obj) in (
410                    bool,
411                    bytearray,
412                    bytes,
413                    dict,
414                    float,
415                    frozenset,
416                    int,
417                    list,
418                    set,
419                    str,
420                    tuple,
421                ):
422                    self.dump_generic_builtin(kwarg_name)
423                else:
424                    self.dump_generic_instance(kwarg_name)
425
426        def dump_generic_builtin(self, kwarg_name: str) -> None:
427            """@private
428            """
429            assert hasattr(self.trainer, kwarg_name)
430            self.init_data[kwarg_name] = getattr(self.trainer, kwarg_name)
431
432        def dump_generic_class(self, kwarg_name: str) -> None:
433            """@private
434            """
435            assert hasattr(self.trainer, kwarg_name)
436            assert kwarg_name.endswith("_class")
437            obj = getattr(self.trainer, kwarg_name)
438            self.init_data[kwarg_name] = None if obj is None else f"{obj.__module__}.{obj.__name__}"
439
440        def dump_generic_instance(self, kwarg_name: str) -> None:
441            """@private
442            """
443            assert hasattr(self.trainer, kwarg_name)
444            instance = getattr(self.trainer, kwarg_name)
445            self.init_data.update(
446                {
447                    f"{kwarg_name}_class": f"{instance.__class__.__module__}.{instance.__class__.__name__}",
448                    f"{kwarg_name}_kwargs": get_constructor_arguments(instance),
449                }
450            )
451
452        def dump_device(self, kwarg_name: str):
453            """@private
454            """
455            assert hasattr(self.trainer, kwarg_name)
456            self.init_data[kwarg_name] = str(getattr(self.trainer, kwarg_name))
457
458        def dump_data_loader(self, kwarg_name: str) -> None:
459            """@private
460            """
461            assert hasattr(self.trainer, kwarg_name)
462            loader = getattr(self.trainer, kwarg_name)
463            if loader is None:
464                return
465            self.init_data.update(
466                {
467                    f"{kwarg_name.replace('_loader', '_dataset')}": loader.dataset,
468                    f"{kwarg_name}_kwargs": get_constructor_arguments(loader),
469                }
470            )
471
472        def dump_logger(self, kwarg_name: str):  # todo: remove and rename kwarg 'logger' to 'logger_class'
473            """@private
474            """
475            self.dump_generic_class(f"{kwarg_name}_class")
476
477        def dump_model(self, kwarg_name: str):
478            """@private
479            """
480            if is_compiled(self.trainer.model):
481                self.init_data.update(
482                    {"model_class": self.trainer._model_class, "model_kwargs": self.trainer._model_kwargs}
483                )
484            else:
485                self.dump_generic_instance("model")
486
487    def _build_init(self) -> Dict[str, Any]:
488        serializer = self.Serializer(self)
489        for name in inspect.signature(self.__class__).parameters:
490            # special rules to serialize kwargs
491            # if a trainer class inherits from DefaultTrainer and has **kwargs
492            # they need to be saved in self._kwargs
493            if name == "kwargs":
494                if not hasattr(self, "_kwargs"):
495                    msg = "The trainer class has **kwargs in its signature, but is missing the _kwargs attribute. " +\
496                          "Please add self._kwargs to its __init__ function"
497                    raise RuntimeError(msg)
498                kwargs = getattr(self, "_kwargs")
499                for kwarg_name in kwargs:
500                    serializer.dump(kwarg_name)
501                continue
502            serializer.dump(name)
503
504        return serializer.init_data
505
506    def _initialize(self, iterations, load_from_checkpoint, epochs=None):
507        assert self.train_loader is not None
508        assert self.val_loader is not None
509        assert self.model is not None
510        assert self.loss is not None
511        assert self.optimizer is not None
512        assert self.metric is not None
513        assert self.device is not None
514
515        if load_from_checkpoint is not None:
516            self.load_checkpoint(load_from_checkpoint)
517
518        if sum((iterations is not None, epochs is not None)) != 1:
519            raise ValueError(
520                "Exactly one of 'iterations' or 'epochs' has to be specified to initialize the trainer."
521                f"You have passed 'iterations'={iterations} and 'epochs'={epochs}"
522            )
523
524        if epochs is None:
525            epochs = int(np.ceil(float(iterations) / len(self.train_loader)))
526        else:
527            iterations = epochs * len(self.train_loader)
528
529        self.max_iteration = self._iteration + iterations
530        self.max_epoch = self._epoch + epochs
531
532        if not getattr(self, "_is_initialized", False):
533            # check if we compile the model (only supported by pytorch 2)
534            # to enable (de)serialization of compiled models, we keep track of the model class and kwargs
535            if is_compiled(self.model):
536                warnings.warn(
537                    "You have passed a compiled model to the trainer."
538                    "It will not be possible to (de)serialize the trainer with it."
539                    "If you want to be able to do this please pass the normal model."
540                    "It can be automatically compiled by setting 'compile_model' to True"
541                )
542            self._model_class = f"{self.model.__class__.__module__}.{self.model.__class__.__name__}"
543            self._model_kwargs = get_constructor_arguments(self.model)
544            self.model = auto_compile(self.model, self.compile_model)
545
546            self.model.to(self.device)
547            self.loss.to(self.device)
548
549            # this saves all the information that is necessary
550            # to fully load the trainer from the checkpoint
551            self.init_data = self._build_init()
552
553            if self.logger_class is None:
554                self.logger = None
555            else:
556                # may set self.name if self.name is None
557                save_root = getattr(self, "save_root", None)
558                try:
559                    self.logger = self.logger_class(self, save_root, **(self.logger_kwargs or {}))
560                except (PermissionError, RuntimeError):
561                    warnings.warn(
562                        f"The checkpoint folder at {self.checkpoint_folder} could not be created."
563                        "The most likely reason for this is that you copied the checkpoint somewhere else,"
564                        "so we skip this error to enable loading the model from this checkpoint."
565                    )
566
567            try:
568                os.makedirs(self.checkpoint_folder, exist_ok=True)
569            except PermissionError:
570                warnings.warn(
571                    f"The checkpoint folder at {self.checkpoint_folder} could not be created."
572                    "The most likely reason for this is that you copied the checkpoint somewhere else,"
573                    "so we skip this error to enable loading the model from this checkpoint."
574                )
575                pass
576
577        # The best metric so far: infinity for a new training, otherwise the value of the loaded checkpoint
578        # or of the previous call to `fit`. So a training that is continued only replaces the best checkpoint
579        # with an epoch that is better than all epochs before it.
580        return self.best_metric
581
582    def save_checkpoint(self, name, current_metric, best_metric, train_time=0.0, **extra_save_dict):
583        """@private
584        """
585        save_path = os.path.join(self.checkpoint_folder, f"{name}.pt")
586        extra_init_dict = extra_save_dict.pop("init", {})
587        save_dict = {
588            "iteration": self._iteration,
589            "epoch": self._epoch,
590            "best_epoch": self._best_epoch,
591            "best_metric": best_metric,
592            "current_metric": current_metric,
593            "model_state": self.model.state_dict(),
594            "optimizer_state": self.optimizer.state_dict(),
595            "init": self.init_data | extra_init_dict,
596            "train_time": train_time,
597            "timestamp": datetime.now().strftime("%d-%m-%Y (%H:%M:%S)"),
598        }
599        save_dict.update(**extra_save_dict)
600        if self.scaler is not None:
601            save_dict.update({"scaler_state": self.scaler.state_dict()})
602        if self.lr_scheduler is not None:
603            save_dict.update({"scheduler_state": self.lr_scheduler.state_dict()})
604
605        rank = getattr(self, "rank", None)
606        if rank is None or rank == 0:
607            torch.save(save_dict, save_path)
608
609    def load_checkpoint(self, checkpoint="best"):
610        """@private
611        """
612        if isinstance(checkpoint, str):
613            save_path = os.path.join(self.checkpoint_folder, f"{checkpoint}.pt")
614            if not os.path.exists(save_path):
615                warnings.warn(f"Cannot load checkpoint. {save_path} does not exist.")
616                return
617            save_dict = torch.load(save_path, weights_only=False)
618        elif isinstance(checkpoint, dict):
619            save_dict = checkpoint
620        else:
621            raise RuntimeError
622
623        self._iteration = save_dict["iteration"]
624        # Checkpoints are saved at the end of an epoch, before the epoch counter is incremented.
625        # So the stored value is the index of the last finished epoch, and the next epoch has the index + 1.
626        self._epoch = save_dict["epoch"] + 1
627        self._best_epoch = save_dict["best_epoch"]
628        self.best_metric = save_dict["best_metric"]
629        self.current_metric = save_dict["current_metric"]
630        self.train_time = save_dict.get("train_time", 0.0)
631
632        model_state = save_dict["model_state"]
633        # to enable loading compiled models
634        compiled_prefix = "_orig_mod."
635        model_state = OrderedDict(
636            [(k[len(compiled_prefix):] if k.startswith(compiled_prefix) else k, v) for k, v in model_state.items()]
637        )
638        self.model.load_state_dict(model_state)
639        # we need to send the network to the device before loading the optimizer state!
640        self.model.to(self.device)
641
642        self.optimizer.load_state_dict(save_dict["optimizer_state"])
643        scaler_state = save_dict.get("scaler_state")
644        if self.scaler is not None and scaler_state:
645            self.scaler.load_state_dict(scaler_state)
646        if self.lr_scheduler is not None:
647            self.lr_scheduler.load_state_dict(save_dict["scheduler_state"])
648
649        return save_dict
650
651    def _verify_if_training_completed(self, checkpoint="latest"):
652        save_path = os.path.join(self.checkpoint_folder, f"{checkpoint}.pt")
653        save_dict = torch.load(save_path, weights_only=False) if os.path.exists(save_path) else None
654        if save_dict and self.max_iteration == save_dict.get("iteration"):
655            return True
656        return False
657
658    def fit(
659        self,
660        iterations: Optional[int] = None,
661        load_from_checkpoint: Optional[Union[os.PathLike, str]] = None,
662        epochs: Optional[int] = None,
663        save_every_kth_epoch: Optional[int] = None,
664        progress=None,
665        overwrite_training: bool = True,
666    ):
667        """Run neural network training.
668
669        Exactly one of 'iterations' or 'epochs' has to be passed.
670
671        Args:
672            iterations: How long to train, specified in iterations.
673            load_from_checkpoint: Path to a checkpoint from where training should be continued .
674            epochs: How long to train, specified in epochs.
675            save_every_kth_epoch: Save checkpoints after every kth epoch in a separate file.
676                The corresponding checkpoints will be saved with the naming scheme 'epoch-{epoch}.pt'.
677            progress: Optional progress bar for integration with external tools. Expected to follow the tqdm interface.
678            overwrite_training: Whether to overwrite existing checkpoints in the save directory.
679        """
680        best_metric = self._initialize(iterations, load_from_checkpoint, epochs)
681
682        if not overwrite_training:
683            if load_from_checkpoint is not None:
684                raise ValueError(
685                    "We do not support 'overwrite_training=False' and 'load_from_checkpoint' at the same time."
686                )
687
688            if self._verify_if_training_completed():
689                print(
690                    f"The model is trained for {self.max_iteration} iterations / {self.max_epoch} epochs "
691                    "and 'overwrite_training' is set to 'False'."
692                )
693                print(f"The checkpoints are located at '{os.path.abspath(self.checkpoint_folder)}'.")
694                return
695
696        print(
697            "Start fitting for",
698            self.max_iteration - self._iteration,
699            "iterations / ",
700            self.max_epoch - self._epoch,
701            "epochs",
702        )
703        print("with", len(self.train_loader), "iterations per epoch")
704
705        if self.mixed_precision:
706            train_epoch = self._train_epoch_mixed
707            validate = self._validate_mixed
708            print("Training with mixed precision")
709        else:
710            train_epoch = self._train_epoch
711            validate = self._validate
712            print("Training with single precision")
713
714        total_iterations = epochs * len(self.train_loader) if iterations is None else iterations
715        if progress is None:
716            progress = tqdm(total=total_iterations, desc=f"Epoch {self._epoch}", leave=True)
717        else:
718            progress.total = total_iterations
719            progress.set_description(f"Epoch {self._epoch}")
720
721        msg = "Epoch %i: average [s/it]: %f, current metric: %f, best metric: %f"
722        train_epochs = self.max_epoch - self._epoch
723        t_start = time.time()
724        for epoch in range(train_epochs):
725
726            # Ensure data is shuffled differently at each epoch.
727            try:
728                self.train_loader.sampler.set_epoch(epoch)
729            except AttributeError:
730                pass
731
732            # Run training and validation for this epoch
733            t_per_iter = train_epoch(progress)
734            current_metric = validate()
735
736            # perform all the post-epoch steps:
737
738            # apply the learning rate scheduler
739            if self.lr_scheduler is not None:
740                self.lr_scheduler.step(current_metric)
741
742            # how long did we train in total?
743            total_train_time = (time.time() - t_start) + self.train_time
744
745            # save this checkpoint as the new best checkpoint if
746            # it has the best overall validation metric
747            if current_metric < best_metric:
748                best_metric = current_metric
749                self.best_metric = best_metric
750                self._best_epoch = self._epoch
751                self.save_checkpoint("best", current_metric, best_metric, train_time=total_train_time)
752
753            # save this checkpoint as the latest checkpoint
754            self.save_checkpoint("latest", current_metric, best_metric, train_time=total_train_time)
755
756            # if we save after every k-th epoch then check if we need to save now
757            if save_every_kth_epoch is not None and (self._epoch + 1) % save_every_kth_epoch == 0:
758                self.save_checkpoint(
759                    f"epoch-{self._epoch + 1}", current_metric, best_metric, train_time=total_train_time
760                )
761
762            # if early stopping has been specified then check if the stopping condition is met
763            if self.early_stopping is not None:
764                epochs_since_best = self._epoch - self._best_epoch
765                if epochs_since_best > self.early_stopping:
766                    print("Stopping training because there has been no improvement for", self.early_stopping, "epochs")
767                    break
768
769            self._epoch += 1
770            progress.set_description(msg % (self._epoch, t_per_iter, current_metric, best_metric), refresh=True)
771
772        print(f"Finished training after {self._epoch} epochs / {self._iteration} iterations.")
773        print(f"The best epoch is number {self._best_epoch}.")
774
775        if self._generate_name:
776            self.name = None
777
778        # Update the train time
779        self.train_time = total_train_time
780
781        # TODO save the model to wandb if we have the wandb logger
782        if isinstance(self.logger, WandbLogger):
783            self.logger.get_wandb().finish()
784
785    def _accumulate_gradients(self, loss):
786        """Accumulate gradients without an optimizer step."""
787        if self.mixed_precision:
788            loss = self.scaler.scale(loss)
789        loss.backward()
790
791    def _backprop(self, loss):
792        loss.backward()
793        self.optimizer.step()
794
795    def _backprop_mixed(self, loss):
796        self.scaler.scale(loss).backward()
797        self.scaler.step(self.optimizer)
798        self.scaler.update()
799
800    def _train_epoch(self, progress):
801        return self._train_epoch_impl(progress, contextlib.nullcontext, self._backprop)
802
803    def _train_epoch_mixed(self, progress):
804        return self._train_epoch_impl(
805            progress,
806            partial(torch.autocast, device_type=self._device_type, dtype=getattr(torch, self.mixed_precision_dtype)),
807            self._backprop_mixed
808        )
809
810    def _forward_and_loss(self, x, y):
811        pred = self.model(x)
812        if self._iteration % self.log_image_interval == 0:
813            if pred.requires_grad:
814                pred.retain_grad()
815
816        loss = self.loss(pred, y)
817        return pred, loss
818
819    def _train_epoch_impl(self, progress, forward_context, backprop: Callable[[torch.Tensor], None]):
820        self.model.train()
821
822        n_iter = 0
823        t_per_iter = time.time()
824        for x, y in self.train_loader:
825            x, y = x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True)
826
827            self.optimizer.zero_grad()
828
829            with forward_context():
830                pred, loss = self._forward_and_loss(x, y)
831
832            backprop(loss)
833
834            lr = [pm["lr"] for pm in self.optimizer.param_groups][0]
835            if self.logger is not None:
836                self.logger.log_train(self._iteration, loss, lr, x, y, pred, log_gradients=True)
837
838            self._iteration += 1
839            n_iter += 1
840            if self._iteration >= self.max_iteration:
841                break
842            progress.update(1)
843
844        t_per_iter = (time.time() - t_per_iter) / n_iter
845        return t_per_iter
846
847    def _validate(self):
848        return self._validate_impl(contextlib.nullcontext)
849
850    def _validate_mixed(self):
851        return self._validate_impl(
852            partial(torch.autocast, device_type=self._device_type, dtype=getattr(torch, self.mixed_precision_dtype))
853        )
854
855    def _validate_impl(self, forward_context):
856        self.model.eval()
857
858        metric_val = 0.0
859        loss_val = 0.0
860
861        with torch.no_grad():
862            for x, y in self.val_loader:
863                x, y = x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True)
864                with forward_context():
865                    pred, loss = self._forward_and_loss(x, y)
866                    metric = self.metric(pred, y)
867
868                loss_val += loss.item()
869                metric_val += metric.item()
870
871        metric_val /= len(self.val_loader)
872        loss_val /= len(self.val_loader)
873        if self.logger is not None:
874            self.logger.log_validation(self._iteration, metric_val, loss_val, x, y, pred)
875        return metric_val

Trainer class for training a segmentation network.

The trainer class implements the core logic for training a network with pytorch. It implements a training loop to run training and validation, which is started with fit. The checkpoints and logs from the training run will be saved in the current working directory, or in the directory specifified by save_root. Training can be continued from a checkpoint by passing it's location to the load_from_checkpoint argument of fit.

A pre-configured instance of the trainer can be obtained from torch_em.default_segmentation_trainer. Alternatively, the trainer class can also be instantiated as in this example:

import torch
from torch_em.loss import DiceLoss
from torch_em.model import UNet2d
from torch_em.data.datasets.light_microscopy import get_dsb_loader
from torch_em.trainer import DefaultTrainer

# The training data will be downloaded to this location.
data_root = "/path/to/save/the/training/data"
patch_shape = (256, 256)

# Create the model and optimizer.
model = UNet2d(in_channels=1, out_channels=1)
optimizer = torch.optim.AdamW(model.parameters())

trainer = DefaultTrainer(
    name="unet-training",
    train_loader=get_dsb_loader(path=data_root, patch_shape=patch_shape, split="train"),
    val_loader=get_dsb_loader(path=data_root, patch_shape=patch_shape, split="test"),
    model=model,
    loss=DiceLoss(),  # The loss function.
    optimizer=optimizer,
    metric=DiceLoss(),  # The metric. The trainer expects smaller values to represent better results.
    device="cuda",  # The device to use for training.
)
trainer.fit(iterations=int(2.5e4))  # Train for 25.000 iterations.
Arguments:
  • name: The name of the checkpoint that will be created by the trainer.
  • train_loader: The data loader containing the training data.
  • val_loader: The data loader containing the validation data.
  • model: The model to train.
  • loss: The loss function for training.
  • optimizer: The optimizer.
  • metric: The metric for validation.
  • device: The torch device to use for training. If None, will use a GPU if available.
  • lr_scheduler: The learning rate scheduler.
  • log_image_interval: The interval for saving images during logging, in training iterations.
  • mixed_precision: Whether to train with mixed precision.
  • early_stopping: The patience for early stopping in epochs. If None, early stopping will not be used.
  • logger: The logger class. Will be instantiated for logging. By default uses torch_em.training.tensorboard_logger.TensorboardLogger.
  • logger_kwargs: The keyword arguments for the logger class.
  • id_: Unique identifier for the trainer. If None then name will be used.
  • save_root: The root folder for saving the checkpoint and logs.
  • compile_model: Whether to compile the model before training.
  • rank: Rank argument for distributed training. See torch_em.multi_gpu_training for details.
  • mixed_precision_dtype: The dtype for autocast in mixed precision training, 'float16' or 'bfloat16'. The default is 'float16' on the GPU and 'bfloat16' on the CPU. Use 'bfloat16' to avoid overflows.
DefaultTrainer( name: Optional[str], train_loader: torch.utils.data.dataloader.DataLoader, val_loader: torch.utils.data.dataloader.DataLoader, model: torch.nn.modules.module.Module, loss: torch.nn.modules.module.Module, optimizer: torch.optim.optimizer.Optimizer, metric: Callable, device: Union[str, torch.device], lr_scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None, log_image_interval: int = 100, mixed_precision: bool = True, early_stopping: Optional[int] = None, logger=<class 'torch_em.trainer.tensorboard_logger.TensorboardLogger'>, logger_kwargs: Optional[Dict[str, Any]] = None, id_: Optional[str] = None, save_root: Optional[str] = None, compile_model: Union[bool, str, NoneType] = None, rank: Optional[int] = None, mixed_precision_dtype: Optional[str] = None)
 87    def __init__(
 88        self,
 89        name: Optional[str],
 90        train_loader: torch.utils.data.DataLoader,
 91        val_loader: torch.utils.data.DataLoader,
 92        model: torch.nn.Module,
 93        loss: torch.nn.Module,
 94        optimizer: torch.optim.Optimizer,
 95        metric: Callable,
 96        device: Union[str, torch.device],
 97        lr_scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None,
 98        log_image_interval: int = 100,
 99        mixed_precision: bool = True,
100        early_stopping: Optional[int] = None,
101        logger=TensorboardLogger,
102        logger_kwargs: Optional[Dict[str, Any]] = None,
103        id_: Optional[str] = None,
104        save_root: Optional[str] = None,
105        compile_model: Optional[Union[bool, str]] = None,
106        rank: Optional[int] = None,
107        mixed_precision_dtype: Optional[str] = None,
108    ):
109        if name is None and not issubclass(logger, WandbLogger):
110            raise TypeError("Name cannot be None if not using the WandbLogger")
111
112        self._generate_name = name is None
113        self.name = name
114        self.id_ = id_ or name
115        self.train_loader = train_loader
116        self.val_loader = val_loader
117        self.model = model
118        self.loss = loss
119        self.optimizer = optimizer
120        self.metric = metric
121        self.device = torch.device(device)
122        self.lr_scheduler = lr_scheduler
123        self.log_image_interval = log_image_interval
124        self.save_root = save_root
125        self.compile_model = compile_model
126        self.rank = rank
127        self._device_type = "cpu" if self.device.type == "cpu" else "cuda"
128
129        self._iteration = 0
130        self._epoch = 0
131        self._best_epoch = 0
132        # The best validation metric of this training. It is restored by `load_checkpoint`.
133        self.best_metric = np.inf
134
135        self.mixed_precision = mixed_precision
136        # These are the defaults of torch.autocast for each device type.
137        self.mixed_precision_dtype = mixed_precision_dtype or ("bfloat16" if self._device_type == "cpu" else "float16")
138        self.early_stopping = early_stopping
139        self.train_time = 0.0
140
141        if mixed_precision:
142            # Only float16 needs gradient scaling. bfloat16 has the same range as float32.
143            self.scaler = torch.GradScaler(self._device_type, enabled=self.mixed_precision_dtype == "float16")
144        else:
145            self.scaler = None
146
147        self.logger_class = logger
148        self.logger_kwargs = logger_kwargs
149        self.log_image_interval = log_image_interval
name
id_
train_loader
val_loader
model
loss
optimizer
metric
device
lr_scheduler
log_image_interval
save_root
compile_model
rank
best_metric
mixed_precision
mixed_precision_dtype
early_stopping
train_time
logger_class
logger_kwargs
checkpoint_folder
151    @property
152    def checkpoint_folder(self):
153        assert self.id_ is not None  # Because the logger may generate and set trainer.id on logger.__init__.
154        # Save_root enables saving the checkpoints somewhere else than in the local folder.
155        # This is handy for filesystems with limited space, where saving the checkpoints
156        # and log files can lead to running out of space.
157        save_root = getattr(self, "save_root", None)
158        return os.path.join("./checkpoints", self.id_) if save_root is None else\
159            os.path.join(save_root, "./checkpoints", self.id_)
iteration
161    @property
162    def iteration(self):
163        return self._iteration
epoch
165    @property
166    def epoch(self):
167        return self._epoch
def fit( self, iterations: Optional[int] = None, load_from_checkpoint: Union[str, os.PathLike, NoneType] = None, epochs: Optional[int] = None, save_every_kth_epoch: Optional[int] = None, progress=None, overwrite_training: bool = True):
658    def fit(
659        self,
660        iterations: Optional[int] = None,
661        load_from_checkpoint: Optional[Union[os.PathLike, str]] = None,
662        epochs: Optional[int] = None,
663        save_every_kth_epoch: Optional[int] = None,
664        progress=None,
665        overwrite_training: bool = True,
666    ):
667        """Run neural network training.
668
669        Exactly one of 'iterations' or 'epochs' has to be passed.
670
671        Args:
672            iterations: How long to train, specified in iterations.
673            load_from_checkpoint: Path to a checkpoint from where training should be continued .
674            epochs: How long to train, specified in epochs.
675            save_every_kth_epoch: Save checkpoints after every kth epoch in a separate file.
676                The corresponding checkpoints will be saved with the naming scheme 'epoch-{epoch}.pt'.
677            progress: Optional progress bar for integration with external tools. Expected to follow the tqdm interface.
678            overwrite_training: Whether to overwrite existing checkpoints in the save directory.
679        """
680        best_metric = self._initialize(iterations, load_from_checkpoint, epochs)
681
682        if not overwrite_training:
683            if load_from_checkpoint is not None:
684                raise ValueError(
685                    "We do not support 'overwrite_training=False' and 'load_from_checkpoint' at the same time."
686                )
687
688            if self._verify_if_training_completed():
689                print(
690                    f"The model is trained for {self.max_iteration} iterations / {self.max_epoch} epochs "
691                    "and 'overwrite_training' is set to 'False'."
692                )
693                print(f"The checkpoints are located at '{os.path.abspath(self.checkpoint_folder)}'.")
694                return
695
696        print(
697            "Start fitting for",
698            self.max_iteration - self._iteration,
699            "iterations / ",
700            self.max_epoch - self._epoch,
701            "epochs",
702        )
703        print("with", len(self.train_loader), "iterations per epoch")
704
705        if self.mixed_precision:
706            train_epoch = self._train_epoch_mixed
707            validate = self._validate_mixed
708            print("Training with mixed precision")
709        else:
710            train_epoch = self._train_epoch
711            validate = self._validate
712            print("Training with single precision")
713
714        total_iterations = epochs * len(self.train_loader) if iterations is None else iterations
715        if progress is None:
716            progress = tqdm(total=total_iterations, desc=f"Epoch {self._epoch}", leave=True)
717        else:
718            progress.total = total_iterations
719            progress.set_description(f"Epoch {self._epoch}")
720
721        msg = "Epoch %i: average [s/it]: %f, current metric: %f, best metric: %f"
722        train_epochs = self.max_epoch - self._epoch
723        t_start = time.time()
724        for epoch in range(train_epochs):
725
726            # Ensure data is shuffled differently at each epoch.
727            try:
728                self.train_loader.sampler.set_epoch(epoch)
729            except AttributeError:
730                pass
731
732            # Run training and validation for this epoch
733            t_per_iter = train_epoch(progress)
734            current_metric = validate()
735
736            # perform all the post-epoch steps:
737
738            # apply the learning rate scheduler
739            if self.lr_scheduler is not None:
740                self.lr_scheduler.step(current_metric)
741
742            # how long did we train in total?
743            total_train_time = (time.time() - t_start) + self.train_time
744
745            # save this checkpoint as the new best checkpoint if
746            # it has the best overall validation metric
747            if current_metric < best_metric:
748                best_metric = current_metric
749                self.best_metric = best_metric
750                self._best_epoch = self._epoch
751                self.save_checkpoint("best", current_metric, best_metric, train_time=total_train_time)
752
753            # save this checkpoint as the latest checkpoint
754            self.save_checkpoint("latest", current_metric, best_metric, train_time=total_train_time)
755
756            # if we save after every k-th epoch then check if we need to save now
757            if save_every_kth_epoch is not None and (self._epoch + 1) % save_every_kth_epoch == 0:
758                self.save_checkpoint(
759                    f"epoch-{self._epoch + 1}", current_metric, best_metric, train_time=total_train_time
760                )
761
762            # if early stopping has been specified then check if the stopping condition is met
763            if self.early_stopping is not None:
764                epochs_since_best = self._epoch - self._best_epoch
765                if epochs_since_best > self.early_stopping:
766                    print("Stopping training because there has been no improvement for", self.early_stopping, "epochs")
767                    break
768
769            self._epoch += 1
770            progress.set_description(msg % (self._epoch, t_per_iter, current_metric, best_metric), refresh=True)
771
772        print(f"Finished training after {self._epoch} epochs / {self._iteration} iterations.")
773        print(f"The best epoch is number {self._best_epoch}.")
774
775        if self._generate_name:
776            self.name = None
777
778        # Update the train time
779        self.train_time = total_train_time
780
781        # TODO save the model to wandb if we have the wandb logger
782        if isinstance(self.logger, WandbLogger):
783            self.logger.get_wandb().finish()

Run neural network training.

Exactly one of 'iterations' or 'epochs' has to be passed.

Arguments:
  • iterations: How long to train, specified in iterations.
  • load_from_checkpoint: Path to a checkpoint from where training should be continued .
  • epochs: How long to train, specified in epochs.
  • save_every_kth_epoch: Save checkpoints after every kth epoch in a separate file. The corresponding checkpoints will be saved with the naming scheme 'epoch-{epoch}.pt'.
  • progress: Optional progress bar for integration with external tools. Expected to follow the tqdm interface.
  • overwrite_training: Whether to overwrite existing checkpoints in the save directory.
class DefaultTrainer.Deserializer:
169    class Deserializer:
170        """Determines how to deserialize the trainer kwargs from serialized 'init_data'.
171
172        Examples:
173            To extend the initialization process you can inherite from this Deserializer in an inherited Trainer class.
174            Note that `DefaultTrainer.Deserializer.load_generic()` covers most cases already.
175
176            This example adds `the_answer` kwarg, which requires 'calculations' upon initialization:
177            >>> class MyTrainer(DefaultTrainer):
178            >>>     def __init__(self, *args, the_answer: int, **kwargs):
179            >>>         super().__init__(*args, **kwargs)
180            >>>         self.the_answer = the_answer  # this allows the default Serializer to save the new kwarg,
181            >>>                                       # see DefaultTrainer.Serializer
182            >>>
183            >>>     class Deserializer(DefaultTrainer.Deserializer):
184            >>>         def load_the_answer(self):
185            >>>             generic_answer = self.init_data["the_answer"]
186            >>>             # (device dependent) special deserialization
187            >>>             if self.trainer_kwargs["device"].type == "cpu":  # accessing previously deserialized kwarg
188            >>>                 self.trainer_kwargs["the_answer"] = generic_answer + 1
189            >>>             else:
190            >>>                 self.trainer_kwargs["the_answer"] = generic_answer * 2
191
192        Args:
193            init_data: The initialization data of the trainer.
194            save_path: The path where the checkpoint was saved.
195            device: The device.
196        """
197
198        def __init__(self, init_data: Dict, save_path: str, device: Union[str, torch.device]):
199            self.init_data = init_data
200            self.save_path = save_path
201            # Populate with deserialized trainer kwargs during deserialization; possibly overwrite 'device'.
202            self.trainer_kwargs: Dict[str, Any] = dict(
203                device=torch.device(self.init_data["device"]) if device is None else torch.device(device)
204            )
205
206        def load(self, kwarg_name: str, optional):
207            """@private
208            """
209            # `optional` is True if self.trainer.__class__.__init__ specifies a default value for 'kwarg_name'
210            if kwarg_name == "device":
211                pass  # deserialized in __init__
212            elif kwarg_name.endswith("_loader"):
213                self.load_data_loader(kwarg_name, optional)
214            else:
215                load = getattr(self, f"load_{kwarg_name}", self.load_generic)
216                load(kwarg_name, optional=optional)
217
218        def load_data_loader(self, loader_name, optional) -> None:
219            """@private
220            """
221            ds = self.init_data.get(loader_name.replace("_loader", "_dataset"))
222            if ds is None and optional:
223                return
224
225            loader_kwargs = self.init_data[f"{loader_name}_kwargs"]
226            loader = torch.utils.data.DataLoader(ds, **loader_kwargs)
227            # monkey patch shuffle loader_name to the loader
228            loader.shuffle = loader_kwargs.get("shuffle", False)
229            self.trainer_kwargs[loader_name] = loader
230
231        def load_generic(
232            self,
233            kwarg_name: str,
234            *dynamic_args: Dict,
235            optional: bool,
236            only_class: bool = False,
237            dynamic_kwargs: Optional[Dict[str, Any]] = None,
238        ) -> None:
239            """@private
240            """
241            if kwarg_name in self.init_data:
242                self.trainer_kwargs[kwarg_name] = self.init_data[kwarg_name]
243                return
244
245            this_cls = self.init_data.get(f"{kwarg_name}_class", None)
246            if this_cls is None:
247                if optional:
248                    return
249                else:
250                    raise RuntimeError(f"Could not find init data for {kwarg_name} in {self.save_path}")
251
252            assert isinstance(this_cls, str), this_cls
253            assert "." in this_cls, this_cls
254            cls_p, cls_m = this_cls.rsplit(".", 1)
255            this_cls = getattr(import_module(cls_p), cls_m)
256            if only_class:
257                self.trainer_kwargs[kwarg_name] = this_cls
258            else:
259                self.trainer_kwargs[kwarg_name] = this_cls(
260                    *dynamic_args, **self.init_data.get(f"{kwarg_name}_kwargs", {}), **(dynamic_kwargs or {})
261                )
262
263        def load_name(self, kwarg_name: str, optional: bool):
264            """@private
265            """
266            self.trainer_kwargs[kwarg_name] = os.path.split(os.path.dirname(self.save_path))[1]
267
268        def load_optimizer(self, kwarg_name: str, optional: bool):
269            """@private
270            """
271            self.load_generic(kwarg_name, self.trainer_kwargs["model"].parameters(), optional=optional)
272
273        def load_lr_scheduler(self, kwarg_name: str, optional: bool):
274            """@private
275            """
276            self.load_generic(kwarg_name, self.trainer_kwargs["optimizer"], optional=optional)
277
278        # todo: remove and rename kwarg 'logger' to 'logger_class'
279        def load_logger(self, kwarg_name: str, optional: bool):
280            """@private
281            """
282            assert kwarg_name == "logger"
283            self.load_generic("logger", optional=optional, only_class=True)

Determines how to deserialize the trainer kwargs from serialized 'init_data'.

Examples:

To extend the initialization process you can inherite from this Deserializer in an inherited Trainer class. Note that DefaultTrainer.Deserializer.load_generic() covers most cases already.

This example adds the_answer kwarg, which requires 'calculations' upon initialization:

>>> class MyTrainer(DefaultTrainer):
>>>     def __init__(self, *args, the_answer: int, **kwargs):
>>>         super().__init__(*args, **kwargs)
>>>         self.the_answer = the_answer  # this allows the default Serializer to save the new kwarg,
>>>                                       # see DefaultTrainer.Serializer
>>>
>>>     class Deserializer(DefaultTrainer.Deserializer):
>>>         def load_the_answer(self):
>>>             generic_answer = self.init_data["the_answer"]
>>>             # (device dependent) special deserialization
>>>             if self.trainer_kwargs["device"].type == "cpu":  # accessing previously deserialized kwarg
>>>                 self.trainer_kwargs["the_answer"] = generic_answer + 1
>>>             else:
>>>                 self.trainer_kwargs["the_answer"] = generic_answer * 2
Arguments:
  • init_data: The initialization data of the trainer.
  • save_path: The path where the checkpoint was saved.
  • device: The device.
DefaultTrainer.Deserializer(init_data: Dict, save_path: str, device: Union[str, torch.device])
198        def __init__(self, init_data: Dict, save_path: str, device: Union[str, torch.device]):
199            self.init_data = init_data
200            self.save_path = save_path
201            # Populate with deserialized trainer kwargs during deserialization; possibly overwrite 'device'.
202            self.trainer_kwargs: Dict[str, Any] = dict(
203                device=torch.device(self.init_data["device"]) if device is None else torch.device(device)
204            )
init_data
save_path
trainer_kwargs: Dict[str, Any]
class DefaultTrainer.Serializer:
335    class Serializer:
336        """Implements how to serialize trainer kwargs from a trainer instance.
337
338        Examples:
339            To extend the serialization process you can inherite from this Serializer in a derived Trainer class.
340            Note that the methods `dump_generic_builtin()`, `dump_generic_class()` and `dump_generic_instance()`
341            called by the `dump()` method when appropriate cover most cases already.
342
343            This example adds `the_answer` kwarg, which requires extra steps on dumping only because we don't keep a
344            'the_answer' attribute:
345            >>> class MyTrainer(DefaultTrainer):
346            >>>     def __init__(self, *args, the_answer: int, **kwargs):
347            >>>         super().__init__(*args, **kwargs)
348            >>>         # self.the_answer = the_answer  # this would allow the default Serializer to save the new kwarg,
349            >>>         # but let's make things more interesting...
350            >>>         self.the = the_answer // 10
351            >>>         self.answer = the_answer % 10
352            >>>
353            >>>     class Serializer(DefaultTrainer.Serializer):
354            >>>         trainer: MyTrainer
355            >>>         def dump_the_answer(self, kwarg_name: str) -> None:  # custom dump method for 'the_answer' kwarg
356            >>>             assert kwarg_name == "the_answer"
357            >>>             # populate self.init_data with the serialized data required by Deserializer
358            >>>             # to restore the trainer kwargs
359            >>>             self.init_data["the_answer"] = self.trainer.the * 10 + self.trainer.answer
360
361            This example with both Serializer and Deserializer adds `the_answer` kwarg,
362            while saving it in two separate entries 'the' and 'answer'
363            >>> class MyTrainer(DefaultTrainer):
364            >>>     def __init__(self, *args, the_answer: int, **kwargs):
365            >>>         super().__init__(*args, **kwargs)
366            >>>         self.the_answer = the_answer
367            >>>
368            >>>     class Serializer(DefaultTrainer.Serializer):
369            >>>         trainer: MyTrainer
370            >>>         def dump_the_answer(self, kwarg_name: str):
371            >>>             assert kwarg_name == "the_answer"
372            >>>             self.init_data.update({
373            >>>                 "the": self.trainer.the_answer // 10,
374            >>>                 "answer": self.trainer.the_answer % 10
375            >>>             })
376            >>>
377            >>>     class Deserializer(DefaultTrainer.Deserializer):
378            >>>         def load_the_answer(self, kwarg_name: str, optional: bool):
379            >>>             assert kwarg_name == "the_answer"
380            >>>             # 'optional' is True if MyTrainer.__init__ specifies a default value for 'kwarg_name'
381            >>>             self.trainer_kwargs[kwarg_name] = self.init_data["the"] * 10 + self.init_data["answer"]
382
383        Args:
384            trainer: The trainer instance.
385        """
386
387        def __init__(self, trainer: DefaultTrainer):
388            self.trainer = trainer
389            self.init_data = {}  # to be populated during serialization process
390
391        def dump(self, kwarg_name: str) -> None:
392            """@private
393            """
394            dumper = getattr(self, f"dump_{kwarg_name}", None)
395            if dumper is not None:
396                dumper(kwarg_name)
397            elif kwarg_name.endswith("_loader"):
398                self.dump_data_loader(kwarg_name)
399            elif kwarg_name.endswith("_class"):
400                self.dump_generic_class(kwarg_name)
401            elif not hasattr(self.trainer, kwarg_name):
402                raise AttributeError(
403                    f"{self.trainer.__class__} missing attribute '{kwarg_name}' "
404                    f"or special dump method {self.trainer.__class__}.Serializer.dump_{kwarg_name}()"
405                )
406            else:
407                assert hasattr(self.trainer, kwarg_name)
408                obj = getattr(self.trainer, kwarg_name)
409                if obj is None or type(obj) in (
410                    bool,
411                    bytearray,
412                    bytes,
413                    dict,
414                    float,
415                    frozenset,
416                    int,
417                    list,
418                    set,
419                    str,
420                    tuple,
421                ):
422                    self.dump_generic_builtin(kwarg_name)
423                else:
424                    self.dump_generic_instance(kwarg_name)
425
426        def dump_generic_builtin(self, kwarg_name: str) -> None:
427            """@private
428            """
429            assert hasattr(self.trainer, kwarg_name)
430            self.init_data[kwarg_name] = getattr(self.trainer, kwarg_name)
431
432        def dump_generic_class(self, kwarg_name: str) -> None:
433            """@private
434            """
435            assert hasattr(self.trainer, kwarg_name)
436            assert kwarg_name.endswith("_class")
437            obj = getattr(self.trainer, kwarg_name)
438            self.init_data[kwarg_name] = None if obj is None else f"{obj.__module__}.{obj.__name__}"
439
440        def dump_generic_instance(self, kwarg_name: str) -> None:
441            """@private
442            """
443            assert hasattr(self.trainer, kwarg_name)
444            instance = getattr(self.trainer, kwarg_name)
445            self.init_data.update(
446                {
447                    f"{kwarg_name}_class": f"{instance.__class__.__module__}.{instance.__class__.__name__}",
448                    f"{kwarg_name}_kwargs": get_constructor_arguments(instance),
449                }
450            )
451
452        def dump_device(self, kwarg_name: str):
453            """@private
454            """
455            assert hasattr(self.trainer, kwarg_name)
456            self.init_data[kwarg_name] = str(getattr(self.trainer, kwarg_name))
457
458        def dump_data_loader(self, kwarg_name: str) -> None:
459            """@private
460            """
461            assert hasattr(self.trainer, kwarg_name)
462            loader = getattr(self.trainer, kwarg_name)
463            if loader is None:
464                return
465            self.init_data.update(
466                {
467                    f"{kwarg_name.replace('_loader', '_dataset')}": loader.dataset,
468                    f"{kwarg_name}_kwargs": get_constructor_arguments(loader),
469                }
470            )
471
472        def dump_logger(self, kwarg_name: str):  # todo: remove and rename kwarg 'logger' to 'logger_class'
473            """@private
474            """
475            self.dump_generic_class(f"{kwarg_name}_class")
476
477        def dump_model(self, kwarg_name: str):
478            """@private
479            """
480            if is_compiled(self.trainer.model):
481                self.init_data.update(
482                    {"model_class": self.trainer._model_class, "model_kwargs": self.trainer._model_kwargs}
483                )
484            else:
485                self.dump_generic_instance("model")

Implements how to serialize trainer kwargs from a trainer instance.

Examples:

To extend the serialization process you can inherite from this Serializer in a derived Trainer class. Note that the methods dump_generic_builtin(), dump_generic_class() and dump_generic_instance() called by the dump() method when appropriate cover most cases already.

This example adds the_answer kwarg, which requires extra steps on dumping only because we don't keep a 'the_answer' attribute:

>>> class MyTrainer(DefaultTrainer):
>>>     def __init__(self, *args, the_answer: int, **kwargs):
>>>         super().__init__(*args, **kwargs)
>>>         # self.the_answer = the_answer  # this would allow the default Serializer to save the new kwarg,
>>>         # but let's make things more interesting...
>>>         self.the = the_answer // 10
>>>         self.answer = the_answer % 10
>>>
>>>     class Serializer(DefaultTrainer.Serializer):
>>>         trainer: MyTrainer
>>>         def dump_the_answer(self, kwarg_name: str) -> None:  # custom dump method for 'the_answer' kwarg
>>>             assert kwarg_name == "the_answer"
>>>             # populate self.init_data with the serialized data required by Deserializer
>>>             # to restore the trainer kwargs
>>>             self.init_data["the_answer"] = self.trainer.the * 10 + self.trainer.answer

This example with both Serializer and Deserializer adds the_answer kwarg, while saving it in two separate entries 'the' and 'answer'

>>> class MyTrainer(DefaultTrainer):
>>>     def __init__(self, *args, the_answer: int, **kwargs):
>>>         super().__init__(*args, **kwargs)
>>>         self.the_answer = the_answer
>>>
>>>     class Serializer(DefaultTrainer.Serializer):
>>>         trainer: MyTrainer
>>>         def dump_the_answer(self, kwarg_name: str):
>>>             assert kwarg_name == "the_answer"
>>>             self.init_data.update({
>>>                 "the": self.trainer.the_answer // 10,
>>>                 "answer": self.trainer.the_answer % 10
>>>             })
>>>
>>>     class Deserializer(DefaultTrainer.Deserializer):
>>>         def load_the_answer(self, kwarg_name: str, optional: bool):
>>>             assert kwarg_name == "the_answer"
>>>             # 'optional' is True if MyTrainer.__init__ specifies a default value for 'kwarg_name'
>>>             self.trainer_kwargs[kwarg_name] = self.init_data["the"] * 10 + self.init_data["answer"]
Arguments:
  • trainer: The trainer instance.
DefaultTrainer.Serializer(trainer: DefaultTrainer)
387        def __init__(self, trainer: DefaultTrainer):
388            self.trainer = trainer
389            self.init_data = {}  # to be populated during serialization process
trainer
init_data