File size: 5,252 Bytes
9ec5995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6daa104
 
 
9ec5995
 
 
 
 
 
6daa104
 
 
9ec5995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6daa104
 
 
9ec5995
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
"""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"],
        }