mal_core.training

Training subpackage — U-Net model, dataset, and training loop.

1"""Training subpackage — U-Net model, dataset, and training loop."""
2from .model import UNet, combined_loss, eval_dice
3from .dataset import RolloutDataset, get_dataloaders
4from .trainer import train_unet
5from .wrapper import UNetWrapper
6
7__all__ = ["UNet", "combined_loss", "eval_dice", "RolloutDataset", "get_dataloaders", "train_unet", "UNetWrapper"]
class UNet(torch.nn.modules.module.Module):
37class UNet(nn.Module):
38    """Encoder-decoder network that predicts the next state of a patch.
39
40    Four encoder stages with max-pooling between them, a bottleneck at
41    twice the deepest width, and a mirrored decoder that concatenates the
42    skip connections. The head is a 1x1 convolution producing the output
43    channels.
44    """
45
46    def __init__(self, in_channels=6, out_channels=2,
47                 channels=(32, 64, 128, 256)):
48        """Build the network.
49
50        Args:
51            in_channels: channels of the input tensor (state plus environment).
52            out_channels: channels of the predicted next state.
53            channels: width of each encoder stage, deepest last.
54        """
55        super().__init__()
56        c = channels
57        self.enc = nn.ModuleList()
58        prev = in_channels
59        for ch in c:
60            self.enc.append(DoubleConv(prev, ch)); prev = ch
61        self.pool = nn.MaxPool2d(2)
62        self.bottleneck = DoubleConv(c[-1], c[-1] * 2)
63        self.upconvs = nn.ModuleList()
64        self.dec = nn.ModuleList()
65        prev = c[-1] * 2
66        for ch in reversed(c):
67            self.upconvs.append(nn.ConvTranspose2d(prev, ch, 2, stride=2))
68            self.dec.append(DoubleConv(ch * 2, ch))
69            prev = ch
70        self.head = nn.Conv2d(c[0], out_channels, 1)
71
72    def forward(self, x):
73        """Predict the next state from a (N, in_channels, H, W) tensor."""
74        skips = []
75        for enc in self.enc:
76            x = enc(x); skips.append(x); x = self.pool(x)
77        x = self.bottleneck(x)
78        for upc, dec in zip(self.upconvs, self.dec):
79            x = upc(x)
80            skip = skips.pop()
81            if x.shape[-1] != skip.shape[-1]:
82                x = F.interpolate(x, size=skip.shape[-2:], mode="bilinear", align_corners=False)
83            x = torch.cat([x, skip], dim=1)
84            x = dec(x)
85        return self.head(x)

Encoder-decoder network that predicts the next state of a patch.

Four encoder stages with max-pooling between them, a bottleneck at twice the deepest width, and a mirrored decoder that concatenates the skip connections. The head is a 1x1 convolution producing the output channels.

UNet(in_channels=6, out_channels=2, channels=(32, 64, 128, 256))
46    def __init__(self, in_channels=6, out_channels=2,
47                 channels=(32, 64, 128, 256)):
48        """Build the network.
49
50        Args:
51            in_channels: channels of the input tensor (state plus environment).
52            out_channels: channels of the predicted next state.
53            channels: width of each encoder stage, deepest last.
54        """
55        super().__init__()
56        c = channels
57        self.enc = nn.ModuleList()
58        prev = in_channels
59        for ch in c:
60            self.enc.append(DoubleConv(prev, ch)); prev = ch
61        self.pool = nn.MaxPool2d(2)
62        self.bottleneck = DoubleConv(c[-1], c[-1] * 2)
63        self.upconvs = nn.ModuleList()
64        self.dec = nn.ModuleList()
65        prev = c[-1] * 2
66        for ch in reversed(c):
67            self.upconvs.append(nn.ConvTranspose2d(prev, ch, 2, stride=2))
68            self.dec.append(DoubleConv(ch * 2, ch))
69            prev = ch
70        self.head = nn.Conv2d(c[0], out_channels, 1)

Build the network.

Args: in_channels: channels of the input tensor (state plus environment). out_channels: channels of the predicted next state. channels: width of each encoder stage, deepest last.

enc
pool
bottleneck
upconvs
dec
head
def forward(self, x):
72    def forward(self, x):
73        """Predict the next state from a (N, in_channels, H, W) tensor."""
74        skips = []
75        for enc in self.enc:
76            x = enc(x); skips.append(x); x = self.pool(x)
77        x = self.bottleneck(x)
78        for upc, dec in zip(self.upconvs, self.dec):
79            x = upc(x)
80            skip = skips.pop()
81            if x.shape[-1] != skip.shape[-1]:
82                x = F.interpolate(x, size=skip.shape[-2:], mode="bilinear", align_corners=False)
83            x = torch.cat([x, skip], dim=1)
84            x = dec(x)
85        return self.head(x)

Predict the next state from a (N, in_channels, H, W) tensor.

def combined_loss( pred: torch.Tensor, target: torch.Tensor) -> tuple[torch.Tensor, float, float]:
102def combined_loss(pred: torch.Tensor, target: torch.Tensor) -> tuple[torch.Tensor, float, float]:
103    """Combined MSE + Soft-Dice loss for multi-channel epidemiological state."""
104    mse = F.mse_loss(pred, target)
105    sd = soft_dice_loss(pred[:, :1], target[:, :1])  # focus Dice on density/sparse channel
106    loss = mse + 0.5 * sd
107    return loss, float(mse.item()), float(sd.item())

Combined MSE + Soft-Dice loss for multi-channel epidemiological state.

@torch.no_grad()
def eval_dice(pred: torch.Tensor, target: torch.Tensor, thresh: float = 0.5) -> float:
110@torch.no_grad()
111def eval_dice(pred: torch.Tensor, target: torch.Tensor, thresh: float = 0.5) -> float:
112    """Evaluate hard Dice score on the primary channel (vector density).
113
114    thresh is in adult counts (contract 4.0): 0.5 ⇒ >= 1 adult.
115    """
116    p = (pred[:, :1] > thresh).float()
117    t = (target[:, :1] > thresh).float()
118    inter = (p * t).sum()
119    union = p.sum() + t.sum()
120    return float((2 * inter + 1e-6) / (union + 1e-6))

Evaluate hard Dice score on the primary channel (vector density).

thresh is in adult counts (contract 4.0): 0.5 ⇒ >= 1 adult.

class RolloutDataset(typing.Generic[+_T_co]):
 39class RolloutDataset(Dataset):
 40    """Patches of consecutive ABM state snapshots for surrogate training.
 41
 42    Reads the ``*_dayNNN`` state snapshots of a run directory, tiles them
 43    into square patches and pairs each patch with the same patch one day
 44    later, so the dataset yields ``(state_t + env, state_{t+1})`` samples.
 45    The spatial split is fixed: patches whose left column is east of the
 46    raster mid-line belong to the validation split, the rest to training.
 47    """
 48
 49    def __init__(
 50        self,
 51        run_dir: str | Path,
 52        split: Literal["train", "val"] = "train",
 53        patch_size: int = PATCH_SIZE,
 54        subsample: float = 1.0,
 55        preload: bool = False,
 56        include_transmission: bool = True,
 57        env_path: str | Path | None = None,
 58    ):
 59        """Index the patches of a run directory for one spatial split.
 60
 61        Args:
 62            run_dir: directory holding the ``*_dayNNN.tif`` (or ``.npy``)
 63                state snapshots and, optionally, the transmission snapshots.
 64            split: ``"train"`` (west of the raster mid-line) or ``"val"``.
 65            patch_size: side of the square patch in cells.
 66            subsample: fraction of the selected patches to keep, in [0, 1].
 67            preload: read every referenced raster into memory up front.
 68            include_transmission: append the transmission channels when
 69                matching snapshots exist.
 70            env_path: optional NetCDF or GeoTIFF of environmental planes
 71                whose channels are concatenated to the input.
 72
 73        Raises:
 74            FileNotFoundError: no state snapshot files in ``run_dir``.
 75        """
 76        self.run_dir = Path(run_dir)
 77        self.split = split
 78        self.patch_size = patch_size
 79        self.subsample = subsample
 80        self.preload = preload
 81        self.include_transmission = include_transmission
 82        self.env_path = Path(env_path) if env_path else None
 83
 84        self.patches: list[dict] = []
 85        self._data_cache: dict[str, np.ndarray] = {}
 86        self._env_cache: np.ndarray | None = None
 87
 88        self._load_env_if_available()
 89        self._build_patches()
 90        if preload:
 91            self._preload_data()
 92
 93    def _load_env_if_available(self) -> None:
 94        """Load the environmental planes into ``_env_cache``, if any.
 95
 96        Reads the first ``ENV_CHANNELS`` variables of a NetCDF (or bands of
 97        a GeoTIFF) as float32 arrays of shape (channels, height, width);
 98        missing channels are zero-padded. Any failure (unreadable file,
 99        wrong shape) leaves the cache at None, i.e. the environmental input
100        is silently all-zero for that dataset.
101        """
102        if self.env_path and self.env_path.exists():
103            try:
104                if self.env_path.suffix in (".nc", ".nc4"):
105                    import xarray as xr
106                    with xr.open_dataset(self.env_path) as ds:
107                        vars_to_use = [v for v in ["rainfall", "air_temp_c", "jrc_persistent", "lc_built", "lc_wetland", "lc_open_plus_water", "lc_crop"] if v in ds]
108                        arrs = [ds[v].values.squeeze() for v in vars_to_use[:ENV_CHANNELS]]
109                        if len(arrs) < ENV_CHANNELS:
110                            H, W = arrs[0].shape[-2:]
111                            while len(arrs) < ENV_CHANNELS:
112                                arrs.append(np.zeros((H, W), dtype=np.float32))
113                        self._env_cache = np.stack(arrs[:ENV_CHANNELS], axis=0).astype(np.float32)
114                elif self.env_path.suffix in (".tif", ".tiff"):
115                    with rasterio.open(self.env_path) as src:
116                        data = src.read().astype(np.float32)
117                        if data.shape[0] < ENV_CHANNELS:
118                            padded = np.zeros((ENV_CHANNELS, data.shape[1], data.shape[2]), dtype=np.float32)
119                            padded[:data.shape[0]] = data
120                            data = padded
121                        self._env_cache = data[:ENV_CHANNELS]
122            except Exception:
123                self._env_cache = None
124
125    def _build_patches(self) -> None:
126        """Enumerate the (day t, day t+1) patch pairs of the selected split.
127
128        Groups the state snapshots by rollout seed and simulation day, pairs
129        consecutive days, and cuts each raster into patches of
130        ``patch_size`` cells, keeping only the patches of the requested
131        spatial split. A random subsample is drawn when ``subsample`` is
132        below 1. Raises FileNotFoundError when the run directory holds no
133        state snapshot.
134        """
135        # 1. Discover all state snapshot files (excluding transmission files)
136        candidate_tifs = sorted(self.run_dir.glob("*.tif"))
137        state_tifs = [p for p in candidate_tifs if "_day" in p.name and "transmission" not in p.name]
138        state_npys = sorted(self.run_dir.glob("*_day*.npy"))
139
140        use_tiff = len(state_tifs) >= len(state_npys)
141        state_files = state_tifs if use_tiff else state_npys
142
143        if not state_files:
144            raise FileNotFoundError(f"No ABM state snapshot files (*_day*.tif/npy) found in {self.run_dir}")
145
146        # Group by seed/rollout
147        series_by_seed: dict[int, dict[int, Path]] = {}
148        for p in state_files:
149            seed, day = _extract_seed_and_day(p)
150            if seed not in series_by_seed:
151                series_by_seed[seed] = {}
152            series_by_seed[seed][day] = p
153
154        # Check for matching transmission snapshots
155        trans_by_seed: dict[int, dict[int, Path]] = {}
156        if self.include_transmission:
157            trans_files = [p for p in candidate_tifs if "_day" in p.name and "transmission" in p.name]
158            for p in trans_files:
159                seed, day = _extract_seed_and_day(p)
160                if seed not in trans_by_seed:
161                    trans_by_seed[seed] = {}
162                trans_by_seed[seed][day] = p
163
164        # Get raster dimensions
165        first_file = state_files[0]
166        if use_tiff:
167            with rasterio.open(first_file) as src:
168                H, W = src.shape
169        else:
170            sample = np.load(first_file)
171            H, W = sample.shape[-2], sample.shape[-1]
172
173        n_patches_h = max(1, H // self.patch_size)
174        n_patches_w = max(1, W // self.patch_size)
175        mid_col = W // 2
176
177        # Build consecutive temporal pairs (day_t, day_{t+1})
178        for seed, days_dict in series_by_seed.items():
179            sorted_days = sorted(days_dict.keys())
180            for i in range(len(sorted_days) - 1):
181                day_cur = sorted_days[i]
182                day_next = sorted_days[i + 1]
183
184                state_cur = days_dict[day_cur]
185                state_next = days_dict[day_next]
186
187                trans_cur = trans_by_seed.get(seed, {}).get(day_cur)
188                trans_next = trans_by_seed.get(seed, {}).get(day_next)
189
190                has_trans = bool(self.include_transmission and trans_cur and trans_next)
191
192                for r in range(n_patches_h):
193                    for c in range(n_patches_w):
194                        is_east = (c * self.patch_size) >= mid_col
195                        patch_split = "val" if is_east else "train"
196
197                        if patch_split != self.split:
198                            continue
199
200                        self.patches.append({
201                            "state_path": state_cur,
202                            "next_path": state_next,
203                            "trans_path": trans_cur if has_trans else None,
204                            "trans_next_path": trans_next if has_trans else None,
205                            "row": r * self.patch_size,
206                            "col": c * self.patch_size,
207                            "use_tiff": use_tiff,
208                        })
209
210        if self.subsample < 1.0 and self.patches:
211            np.random.seed(42)
212            n_keep = max(1, int(len(self.patches) * self.subsample))
213            indices = np.random.choice(len(self.patches), n_keep, replace=False)
214            self.patches = [self.patches[i] for i in indices]
215
216    def _read_raster(self, path: Path | str, is_tiff: bool) -> np.ndarray:
217        """Read one snapshot as a float32 array of shape (channels, H, W).
218
219        GeoTIFF nodata cells are replaced by 0.0. When ``preload`` is set the
220        array is cached in ``_data_cache`` and returned again on later calls.
221        """
222        p_str = str(path)
223        if p_str in self._data_cache:
224            return self._data_cache[p_str]
225
226        if is_tiff:
227            with rasterio.open(path) as src:
228                arr = src.read().astype(np.float32)
229                nodata = src.nodata
230                if nodata is not None:
231                    arr[arr == nodata] = 0.0
232        else:
233            arr = np.load(path).astype(np.float32)
234            if arr.ndim == 2:
235                arr = arr[np.newaxis]
236
237        if self.preload:
238            self._data_cache[p_str] = arr
239        return arr
240
241    def _preload_data(self) -> None:
242        """Read every raster referenced by the patch index into the cache."""
243        for patch in self.patches:
244            self._read_raster(patch["state_path"], patch["use_tiff"])
245            self._read_raster(patch["next_path"], patch["use_tiff"])
246            if patch["trans_path"]:
247                self._read_raster(patch["trans_path"], True)
248            if patch["trans_next_path"]:
249                self._read_raster(patch["trans_next_path"], True)
250
251    def __len__(self) -> int:
252        """Number of patches in this split."""
253        return len(self.patches)
254
255    def __getitem__(self, idx: int) -> tuple[torch.Tensor, torch.Tensor]:
256        """Return the (input, target) pair of one patch.
257
258        The input stacks the state channels, the transmission channels and
259        the environmental channels of the patch; the target is the same
260        patch one day later. Edge patches smaller than ``patch_size`` are
261        zero-padded. Both tensors are float32.
262        """
263        patch = self.patches[idx]
264        use_tiff = patch["use_tiff"]
265        r, c = patch["row"], patch["col"]
266        ps = self.patch_size
267
268        state_full = self._read_raster(patch["state_path"], use_tiff)
269        next_full = self._read_raster(patch["next_path"], use_tiff)
270
271        state_patch = state_full[:, r:r+ps, c:c+ps]
272        next_patch = next_full[:, r:r+ps, c:c+ps]
273
274        # Pad if edge patch is smaller than patch_size
275        if state_patch.shape[-2] != ps or state_patch.shape[-1] != ps:
276            ch = state_patch.shape[0]
277            padded_s = np.zeros((ch, ps, ps), dtype=np.float32)
278            padded_s[:, :state_patch.shape[-2], :state_patch.shape[-1]] = state_patch
279            state_patch = padded_s
280
281            padded_n = np.zeros((next_patch.shape[0], ps, ps), dtype=np.float32)
282            padded_n[:, :next_patch.shape[-2], :next_patch.shape[-1]] = next_patch
283            next_patch = padded_n
284
285        # Append transmission channels if available
286        if patch["trans_path"] and patch["trans_next_path"]:
287            trans_cur = self._read_raster(patch["trans_path"], True)[:, r:r+ps, c:c+ps]
288            trans_nxt = self._read_raster(patch["trans_next_path"], True)[:, r:r+ps, c:c+ps]
289
290            if trans_cur.shape[-2] != ps or trans_cur.shape[-1] != ps:
291                tch = trans_cur.shape[0]
292                pt_c = np.zeros((tch, ps, ps), dtype=np.float32)
293                pt_c[:, :trans_cur.shape[-2], :trans_cur.shape[-1]] = trans_cur
294                trans_cur = pt_c
295
296                pt_n = np.zeros((trans_nxt.shape[0], ps, ps), dtype=np.float32)
297                pt_n[:, :trans_nxt.shape[-2], :trans_nxt.shape[-1]] = trans_nxt
298                trans_nxt = pt_n
299
300            state_patch = np.concatenate([state_patch, trans_cur], axis=0)
301            next_patch = np.concatenate([next_patch, trans_nxt], axis=0)
302
303        # Environmental channels
304        if self._env_cache is not None and self._env_cache.shape[-2] >= r+ps and self._env_cache.shape[-1] >= c+ps:
305            env_patch = self._env_cache[:, r:r+ps, c:c+ps]
306        else:
307            env_patch = np.zeros((ENV_CHANNELS, ps, ps), dtype=np.float32)
308
309        x = np.concatenate([state_patch, env_patch], axis=0)
310        return torch.from_numpy(x), torch.from_numpy(next_patch)

Patches of consecutive ABM state snapshots for surrogate training.

Reads the *_dayNNN state snapshots of a run directory, tiles them into square patches and pairs each patch with the same patch one day later, so the dataset yields (state_t + env, state_{t+1}) samples. The spatial split is fixed: patches whose left column is east of the raster mid-line belong to the validation split, the rest to training.

RolloutDataset( run_dir: str | pathlib.Path, split: Literal['train', 'val'] = 'train', patch_size: int = 128, subsample: float = 1.0, preload: bool = False, include_transmission: bool = True, env_path: str | pathlib.Path | None = None)
49    def __init__(
50        self,
51        run_dir: str | Path,
52        split: Literal["train", "val"] = "train",
53        patch_size: int = PATCH_SIZE,
54        subsample: float = 1.0,
55        preload: bool = False,
56        include_transmission: bool = True,
57        env_path: str | Path | None = None,
58    ):
59        """Index the patches of a run directory for one spatial split.
60
61        Args:
62            run_dir: directory holding the ``*_dayNNN.tif`` (or ``.npy``)
63                state snapshots and, optionally, the transmission snapshots.
64            split: ``"train"`` (west of the raster mid-line) or ``"val"``.
65            patch_size: side of the square patch in cells.
66            subsample: fraction of the selected patches to keep, in [0, 1].
67            preload: read every referenced raster into memory up front.
68            include_transmission: append the transmission channels when
69                matching snapshots exist.
70            env_path: optional NetCDF or GeoTIFF of environmental planes
71                whose channels are concatenated to the input.
72
73        Raises:
74            FileNotFoundError: no state snapshot files in ``run_dir``.
75        """
76        self.run_dir = Path(run_dir)
77        self.split = split
78        self.patch_size = patch_size
79        self.subsample = subsample
80        self.preload = preload
81        self.include_transmission = include_transmission
82        self.env_path = Path(env_path) if env_path else None
83
84        self.patches: list[dict] = []
85        self._data_cache: dict[str, np.ndarray] = {}
86        self._env_cache: np.ndarray | None = None
87
88        self._load_env_if_available()
89        self._build_patches()
90        if preload:
91            self._preload_data()

Index the patches of a run directory for one spatial split.

Args: run_dir: directory holding the *_dayNNN.tif (or .npy) state snapshots and, optionally, the transmission snapshots. split: "train" (west of the raster mid-line) or "val". patch_size: side of the square patch in cells. subsample: fraction of the selected patches to keep, in [0, 1]. preload: read every referenced raster into memory up front. include_transmission: append the transmission channels when matching snapshots exist. env_path: optional NetCDF or GeoTIFF of environmental planes whose channels are concatenated to the input.

Raises: FileNotFoundError: no state snapshot files in run_dir.

run_dir
split
patch_size
subsample
preload
include_transmission
env_path
patches: list[dict]
def get_dataloaders( run_dir: str | pathlib.Path, batch_size: int = 16, num_workers: int = 0, subsample: float = 1.0, preload: bool = False, include_transmission: bool = True, env_path: str | pathlib.Path | None = None) -> tuple[torch.utils.data.dataloader.DataLoader, torch.utils.data.dataloader.DataLoader]:
313def get_dataloaders(
314    run_dir: str | Path,
315    batch_size: int = 16,
316    num_workers: int = 0,
317    subsample: float = 1.0,
318    preload: bool = False,
319    include_transmission: bool = True,
320    env_path: str | Path | None = None,
321) -> tuple[torch.utils.data.DataLoader, torch.utils.data.DataLoader]:
322    """Build the training and validation data loaders of a run directory.
323
324    The two loaders share the same options; only the spatial split
325    differs. The training loader shuffles its batches, the validation
326    loader does not.
327    """
328    train_ds = RolloutDataset(
329        run_dir,
330        split="train",
331        subsample=subsample,
332        preload=preload,
333        include_transmission=include_transmission,
334        env_path=env_path,
335    )
336    val_ds = RolloutDataset(
337        run_dir,
338        split="val",
339        subsample=subsample,
340        preload=preload,
341        include_transmission=include_transmission,
342        env_path=env_path,
343    )
344
345    train_loader = torch.utils.data.DataLoader(
346        train_ds, batch_size=batch_size, shuffle=True, num_workers=num_workers
347    )
348    val_loader = torch.utils.data.DataLoader(
349        val_ds, batch_size=batch_size, shuffle=False, num_workers=num_workers
350    )
351
352    return train_loader, val_loader

Build the training and validation data loaders of a run directory.

The two loaders share the same options; only the spatial split differs. The training loader shuffles its batches, the validation loader does not.

def train_unet( run_dir: str | pathlib.Path, output_dir: str | pathlib.Path, epochs: int = 50, batch_size: int = 16, lr: float = 0.001, device: str | None = None, subsample: float = 1.0, preload: bool = False, include_transmission: bool = True, env_path: str | pathlib.Path | None = None) -> float:
 15def train_unet(
 16    run_dir: str | Path,
 17    output_dir: str | Path,
 18    epochs: int = 50,
 19    batch_size: int = 16,
 20    lr: float = 1e-3,
 21    device: str | None = None,
 22    subsample: float = 1.0,
 23    preload: bool = False,
 24    include_transmission: bool = True,
 25    env_path: str | Path | None = None,
 26) -> float:
 27    """Train the U-Net surrogate on the rollouts of a run directory.
 28
 29    The input and output channel counts are inferred from the first sample
 30    of the training set. Checkpoints are written to ``output_dir``: the
 31    best validation Dice score as ``best_model.pt``, a checkpoint every
 32    ten epochs and the last epoch as ``final_model.pt``; a ``model.yaml``
 33    manifest describing the model is written last.
 34
 35    Returns:
 36        The best validation Dice score reached (hard Dice on the primary
 37        channel, thresholds expressed in adult counts).
 38    """
 39    output_dir = Path(output_dir)
 40    output_dir.mkdir(parents=True, exist_ok=True)
 41
 42    if device is None:
 43        if torch.cuda.is_available():
 44            device = "cuda"
 45        elif torch.backends.mps.is_available():
 46            device = "mps"
 47        else:
 48            device = "cpu"
 49
 50    train_loader, val_loader = get_dataloaders(
 51        run_dir,
 52        batch_size=batch_size,
 53        subsample=subsample,
 54        preload=preload,
 55        include_transmission=include_transmission,
 56        env_path=env_path,
 57    )
 58
 59    if len(train_loader.dataset) == 0:
 60        raise ValueError(f"Train dataset in {run_dir} is empty. Check snapshot file paths.")
 61
 62    # Determine input / target channels from a sample
 63    sample_x, sample_y = train_loader.dataset[0]
 64    in_channels = sample_x.shape[0]
 65    out_channels = sample_y.shape[0]
 66
 67    model = UNet(in_channels=in_channels, out_channels=out_channels).to(device)
 68    optimizer = Adam(model.parameters(), lr=lr)
 69
 70    best_dice = 0.0
 71    for epoch in range(epochs):
 72        model.train()
 73        train_loss = 0.0
 74        for x, y in train_loader:
 75            x, y = x.to(device), y.to(device)
 76            pred = model(x)
 77            loss, mse_val, dice_val = combined_loss(pred, y)
 78
 79            optimizer.zero_grad()
 80            loss.backward()
 81            optimizer.step()
 82
 83            train_loss += loss.item()
 84
 85        train_loss /= max(1, len(train_loader))
 86
 87        model.eval()
 88        val_dice = 0.0
 89        if len(val_loader) > 0:
 90            with torch.no_grad():
 91                for x, y in val_loader:
 92                    x, y = x.to(device), y.to(device)
 93                    pred = model(x)
 94                    val_dice += eval_dice(pred, y)
 95            val_dice /= len(val_loader)
 96
 97        print(f"Epoch {epoch+1}/{epochs} - train_loss: {train_loss:.4f} - val_dice: {val_dice:.4f}")
 98
 99        if val_dice >= best_dice or epoch == 0:
100            best_dice = val_dice
101            torch.save(model.state_dict(), output_dir / "best_model.pt")
102
103        if (epoch + 1) % 10 == 0:
104            torch.save(model.state_dict(), output_dir / f"model_epoch_{epoch+1}.pt")
105
106    torch.save(model.state_dict(), output_dir / "final_model.pt")
107
108    # Generate model.yaml manifest for ModelRegistry compatibility
109    model_manifest = {
110        "name": output_dir.name or "unet_surrogate",
111        "version": "1.0",
112        "contract_version": "1.1",
113        "in_channels": in_channels,
114        "out_channels": out_channels,
115        "checkpoint": "best_model.pt",
116        "description": f"U-Net surrogate model trained on {run_dir} (in_ch={in_channels}, out_ch={out_channels})",
117    }
118    with open(output_dir / "model.yaml", "w") as f:
119        yaml.safe_dump(model_manifest, f)
120
121    print(f"Training complete. Best val_dice: {best_dice:.4f}. Manifest saved -> {output_dir / 'model.yaml'}")
122    return best_dice

Train the U-Net surrogate on the rollouts of a run directory.

The input and output channel counts are inferred from the first sample of the training set. Checkpoints are written to output_dir: the best validation Dice score as best_model.pt, a checkpoint every ten epochs and the last epoch as final_model.pt; a model.yaml manifest describing the model is written last.

Returns: The best validation Dice score reached (hard Dice on the primary channel, thresholds expressed in adult counts).

class UNetWrapper:
 19class UNetWrapper:
 20    """Wraps the U-Net to implement ModelProtocol for SDSS inference."""
 21
 22    def __init__(
 23        self,
 24        checkpoint_path: str | Path,
 25        device: str | None = None,
 26        in_channels: int | None = None,
 27        out_channels: int | None = None,
 28    ):
 29        """Load a trained checkpoint into a ready-to-predict U-Net.
 30
 31        The channel counts are taken from the arguments, else from the
 32        ``model.yaml`` manifest next to the checkpoint, else inferred from
 33        the shapes of the stored convolution weights. The device defaults to
 34        CUDA, then Apple MPS, then CPU.
 35        """
 36        self.checkpoint_path = Path(checkpoint_path)
 37        if device is None:
 38            if torch.cuda.is_available():
 39                self.device = "cuda"
 40            elif torch.backends.mps.is_available():
 41                self.device = "mps"
 42            else:
 43                self.device = "cpu"
 44        else:
 45            self.device = device
 46
 47        # 1. Try reading manifest model.yaml in the checkpoint directory
 48        manifest_path = self.checkpoint_path.parent / "model.yaml"
 49        if manifest_path.exists():
 50            try:
 51                with open(manifest_path) as f:
 52                    meta = yaml.safe_load(f)
 53                in_channels = in_channels or meta.get("in_channels")
 54                out_channels = out_channels or meta.get("out_channels")
 55            except Exception:
 56                pass
 57
 58        # 2. Load state dict and infer shapes if not provided
 59        state_dict = torch.load(self.checkpoint_path, map_location=self.device, weights_only=True)
 60        if in_channels is None:
 61            # enc.0.block.0.weight shape: (channels, in_channels, 3, 3)
 62            first_w = state_dict.get("enc.0.block.0.weight")
 63            in_channels = first_w.shape[1] if first_w is not None else 6
 64        if out_channels is None:
 65            # head.weight shape: (out_channels, channels, 1, 1)
 66            head_w = state_dict.get("head.weight")
 67            out_channels = head_w.shape[0] if head_w is not None else 2
 68
 69        self.in_channels = in_channels
 70        self.out_channels = out_channels
 71
 72        self.model = UNet(in_channels=in_channels, out_channels=out_channels).to(self.device)
 73        self.model.load_state_dict(state_dict)
 74        self.model.eval()
 75
 76    @torch.no_grad()
 77    def predict(self, state: np.ndarray, env: np.ndarray) -> np.ndarray:
 78        """Predict state_{t+1} from state_t + env.
 79
 80        Args:
 81            state: (C_state, H, W) float32
 82            env: (C_env, H, W) float32
 83
 84        Returns:
 85            prediction: (C_out, H, W) float32
 86        """
 87        # Ensure correct channel alignment
 88        total_ch = state.shape[0] + env.shape[0]
 89        if total_ch < self.in_channels:
 90            missing = self.in_channels - total_ch
 91            pad_ch = np.zeros((missing, state.shape[1], state.shape[2]), dtype=np.float32)
 92            x = np.concatenate([state, env, pad_ch], axis=0)
 93        elif total_ch > self.in_channels:
 94            x = np.concatenate([state, env], axis=0)[:self.in_channels]
 95        else:
 96            x = np.concatenate([state, env], axis=0)
 97
 98        orig_h, orig_w = x.shape[-2], x.shape[-1]
 99
100        # Pad to multiple of 16 for UNet 4-stage pooling
101        pad_h = (16 - (orig_h % 16)) % 16
102        pad_w = (16 - (orig_w % 16)) % 16
103
104        x_tensor = torch.from_numpy(x).unsqueeze(0).to(self.device)
105        if pad_h > 0 or pad_w > 0:
106            x_tensor = F.pad(x_tensor, (0, pad_w, 0, pad_h), mode="replicate")
107
108        pred = self.model(x_tensor)
109
110        # Crop back to original dimensions
111        if pad_h > 0 or pad_w > 0:
112            pred = pred[:, :, :orig_h, :orig_w]
113
114        return pred.squeeze(0).cpu().numpy().astype(np.float32)

Wraps the U-Net to implement ModelProtocol for SDSS inference.

UNetWrapper( checkpoint_path: str | pathlib.Path, device: str | None = None, in_channels: int | None = None, out_channels: int | None = None)
22    def __init__(
23        self,
24        checkpoint_path: str | Path,
25        device: str | None = None,
26        in_channels: int | None = None,
27        out_channels: int | None = None,
28    ):
29        """Load a trained checkpoint into a ready-to-predict U-Net.
30
31        The channel counts are taken from the arguments, else from the
32        ``model.yaml`` manifest next to the checkpoint, else inferred from
33        the shapes of the stored convolution weights. The device defaults to
34        CUDA, then Apple MPS, then CPU.
35        """
36        self.checkpoint_path = Path(checkpoint_path)
37        if device is None:
38            if torch.cuda.is_available():
39                self.device = "cuda"
40            elif torch.backends.mps.is_available():
41                self.device = "mps"
42            else:
43                self.device = "cpu"
44        else:
45            self.device = device
46
47        # 1. Try reading manifest model.yaml in the checkpoint directory
48        manifest_path = self.checkpoint_path.parent / "model.yaml"
49        if manifest_path.exists():
50            try:
51                with open(manifest_path) as f:
52                    meta = yaml.safe_load(f)
53                in_channels = in_channels or meta.get("in_channels")
54                out_channels = out_channels or meta.get("out_channels")
55            except Exception:
56                pass
57
58        # 2. Load state dict and infer shapes if not provided
59        state_dict = torch.load(self.checkpoint_path, map_location=self.device, weights_only=True)
60        if in_channels is None:
61            # enc.0.block.0.weight shape: (channels, in_channels, 3, 3)
62            first_w = state_dict.get("enc.0.block.0.weight")
63            in_channels = first_w.shape[1] if first_w is not None else 6
64        if out_channels is None:
65            # head.weight shape: (out_channels, channels, 1, 1)
66            head_w = state_dict.get("head.weight")
67            out_channels = head_w.shape[0] if head_w is not None else 2
68
69        self.in_channels = in_channels
70        self.out_channels = out_channels
71
72        self.model = UNet(in_channels=in_channels, out_channels=out_channels).to(self.device)
73        self.model.load_state_dict(state_dict)
74        self.model.eval()

Load a trained checkpoint into a ready-to-predict U-Net.

The channel counts are taken from the arguments, else from the model.yaml manifest next to the checkpoint, else inferred from the shapes of the stored convolution weights. The device defaults to CUDA, then Apple MPS, then CPU.

checkpoint_path
in_channels
out_channels
model
@torch.no_grad()
def predict(self, state: numpy.ndarray, env: numpy.ndarray) -> numpy.ndarray:
 76    @torch.no_grad()
 77    def predict(self, state: np.ndarray, env: np.ndarray) -> np.ndarray:
 78        """Predict state_{t+1} from state_t + env.
 79
 80        Args:
 81            state: (C_state, H, W) float32
 82            env: (C_env, H, W) float32
 83
 84        Returns:
 85            prediction: (C_out, H, W) float32
 86        """
 87        # Ensure correct channel alignment
 88        total_ch = state.shape[0] + env.shape[0]
 89        if total_ch < self.in_channels:
 90            missing = self.in_channels - total_ch
 91            pad_ch = np.zeros((missing, state.shape[1], state.shape[2]), dtype=np.float32)
 92            x = np.concatenate([state, env, pad_ch], axis=0)
 93        elif total_ch > self.in_channels:
 94            x = np.concatenate([state, env], axis=0)[:self.in_channels]
 95        else:
 96            x = np.concatenate([state, env], axis=0)
 97
 98        orig_h, orig_w = x.shape[-2], x.shape[-1]
 99
100        # Pad to multiple of 16 for UNet 4-stage pooling
101        pad_h = (16 - (orig_h % 16)) % 16
102        pad_w = (16 - (orig_w % 16)) % 16
103
104        x_tensor = torch.from_numpy(x).unsqueeze(0).to(self.device)
105        if pad_h > 0 or pad_w > 0:
106            x_tensor = F.pad(x_tensor, (0, pad_w, 0, pad_h), mode="replicate")
107
108        pred = self.model(x_tensor)
109
110        # Crop back to original dimensions
111        if pad_h > 0 or pad_w > 0:
112            pred = pred[:, :, :orig_h, :orig_w]
113
114        return pred.squeeze(0).cpu().numpy().astype(np.float32)

Predict state_{t+1} from state_t + env.

Args: state: (C_state, H, W) float32 env: (C_env, H, W) float32

Returns: prediction: (C_out, H, W) float32