"""The sample this method trains on, and the DataModule that batches it.""" from typing import Any, TypedDict import torch from lightning import LightningDataModule from torch.utils.data import DataLoader, Dataset from geosave.ml.transforms import ImageAugmenter class Sample(TypedDict): """One whole scene, as `SceneDataset` returns it. A collated batch holds the same keys with a leading batch axis. Attributes: image: float32 `(band, y, x)` pixels as the preprocessor prepared them. target: int64 `(y, x)` class ids, `ignore_index` where unknown. transform: float64 `(6,)` affine coefficients of the scene's grid. crs: int64 EPSG code of the scene's grid. centroid: float32 `(2,)` source-scene centre, latitude then longitude. year: int64 `(1,)` acquisition year. day_of_year: int64 `(1,)` acquisition day, starting at 1. """ image: torch.Tensor target: torch.Tensor transform: torch.Tensor crs: torch.Tensor centroid: torch.Tensor year: torch.Tensor day_of_year: torch.Tensor class DataModule(LightningDataModule): """Batch whole scenes; crop and augment training batches on the device. Scenes are 510 x 510 px, so they batch whole. A training batch is cut to `crop_size` and augmented by the Kornia steps of `augmentations`, image and target together. Validation batches stay whole scenes, which the Module predicts chip by chip as a release does. Args: train: Training dataset returning a `Sample` per scene. val: Validation dataset returning a `Sample` per scene. test: Optional final evaluation dataset, unused during fit. augmentations: Kornia augmentations by `name` and `init_args`, run in order on training batches. List `RandomCrop` first. crop_size: Height and width in pixels `RandomCrop` cuts. ignore_index: Label a target pixel takes where an augmentation invented it; the datasets' and the Module's `ignore_index`. batch_size: Training scenes per batch. eval_batch_size: Validation scenes per batch. num_workers: DataLoader worker processes. """ def __init__( self, train: Dataset, val: Dataset, augmentations: list[dict[str, Any]], crop_size: int, ignore_index: int, batch_size: int, eval_batch_size: int, num_workers: int, test: Dataset | None = None, ) -> None: super().__init__() self.train_dataset = train self.val_dataset = val self.test_dataset = test self.augmenter = ImageAugmenter(augmentations, crop_size) self.ignore_index = ignore_index self.batch_size = batch_size self.eval_batch_size = eval_batch_size self.num_workers = num_workers def train_dataloader(self) -> DataLoader: """Return shuffled batches of whole training scenes.""" return DataLoader( self.train_dataset, batch_size=self.batch_size, shuffle=True, drop_last=True, num_workers=self.num_workers, persistent_workers=self.num_workers > 0, ) def val_dataloader(self) -> DataLoader: """Return batches of whole validation scenes, in order.""" return DataLoader( self.val_dataset, batch_size=self.eval_batch_size, shuffle=False, num_workers=self.num_workers, persistent_workers=self.num_workers > 0, ) def test_dataloader(self) -> DataLoader: """Read the held-out evaluation cohort only for an explicit test run.""" if self.test_dataset is None: raise ValueError("configure a test dataset before running test") return DataLoader( self.test_dataset, batch_size=self.eval_batch_size, shuffle=False, num_workers=self.num_workers, persistent_workers=self.num_workers > 0, ) def on_after_batch_transfer(self, batch: Sample, dataloader_idx: int) -> Sample: """Crop and augment a training batch; leave every other batch as it is.""" if self.trainer is None or not self.trainer.training: return batch image = batch["image"] target = batch["target"] # Kornia fills the pixels an augmentation invents with zero, so class # ids move up by one and zero means "unknown" while augmenting. shifted = (target + 1).masked_fill(target == self.ignore_index, 0).float() image, shifted = self.augmenter(image, shifted, data_keys=["input", "mask"]) target = shifted.round().long() - 1 target = target.masked_fill(target < 0, self.ignore_index) # The crop moved the pixels without moving `transform`: the grid of a # training batch is no longer exact, and training does not read it. return { "image": image, "target": target, "transform": batch["transform"], "crs": batch["crs"], "centroid": batch["centroid"], "year": batch["year"], "day_of_year": batch["day_of_year"], }