synapse_net.training.models

Model factories and pretrained backbone utilities for training.

  1"""Model factories and pretrained backbone utilities for training."""
  2from typing import Optional, Tuple
  3import numpy as np
  4
  5import torch
  6
  7from torch_em.model import UNet2d, AnisotropicUNet
  8from torch_em.model.cryozoo import get_cryozoounet
  9from torch_em.model.unetr import get_unetr_model
 10from torch_em.transform.raw import normalize_percentile, get_raw_transform_for_pretrained_vit
 11
 12from .dataloaders import _determine_ndim
 13
 14try:
 15    from micro_sam.v1.util import models as microsam_models
 16except ImportError:
 17    microsam_models = None
 18
 19try:
 20    from micro_sam.v2.util import models as microsam2_models
 21except ImportError:
 22    microsam2_models = None
 23
 24try:
 25    from micro_sam.models.vfm import get_vfm_model
 26except ImportError:
 27    get_vfm_model = None
 28
 29
 30def get_3d_model(
 31    out_channels: int,
 32    in_channels: int = 1,
 33    scale_factors: Tuple[Tuple[int, int, int]] = [[1, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
 34    initial_features: int = 32,
 35    final_activation: str = "Sigmoid",
 36    norm: Optional[str] = "InstanceNorm",
 37) -> torch.nn.Module:
 38    """Get the U-Net model for 3D segmentation tasks.
 39
 40    Args:
 41        out_channels: The number of output channels of the network.
 42        scale_factors: The downscaling factors for each level of the U-Net encoder.
 43        initial_features: The number of features in the first level of the U-Net.
 44            The number of features increases by a factor of two in each level.
 45        final_activation: The activation applied to the last output layer.
 46        norm: The normalization layer used in the convolutional blocks, or None for no normalization.
 47
 48    Returns:
 49        The U-Net.
 50    """
 51    model = AnisotropicUNet(
 52        scale_factors=scale_factors,
 53        in_channels=in_channels,
 54        out_channels=out_channels,
 55        initial_features=initial_features,
 56        gain=2,
 57        final_activation=final_activation,
 58        norm=norm,
 59    )
 60    return model
 61
 62
 63def get_2d_model(
 64    out_channels: int,
 65    in_channels: int = 1,
 66    initial_features: int = 32,
 67    final_activation: str = "Sigmoid",
 68) -> torch.nn.Module:
 69    """Get the U-Net model for 2D segmentation tasks.
 70
 71    Args:
 72        out_channels: The number of output channels of the network.
 73        initial_features: The number of features in the first level of the U-Net.
 74            The number of features increases by a factor of two in each level.
 75        final_activation: The activation applied to the last output layer.
 76
 77    Returns:
 78        The U-Net.
 79    """
 80    model = UNet2d(
 81        in_channels=in_channels,
 82        out_channels=out_channels,
 83        initial_features=initial_features,
 84        gain=2,
 85        depth=4,
 86        final_activation=final_activation,
 87    )
 88    return model
 89
 90
 91def _check_backbone(backbone, model_type, patch_shape):
 92    if backbone == "cryosiam":
 93        if model_type is not None:
 94            raise ValueError(f"The 'cryosiam' backbone has no model_type; got model_type='{model_type}'.")
 95        if _determine_ndim(patch_shape)[0]:
 96            raise ValueError(f"The 'cryosiam' backbone only supports 3D training; got patch_shape={patch_shape}.")
 97        if any(s % 8 for s in patch_shape):
 98            raise ValueError(
 99                f"The patch_shape for 'cryosiam' backbone must be divisible by 8; got patch_shape={patch_shape}."
100            )
101    elif (backbone is None) != (model_type is None):
102        raise ValueError(
103            "backbone and model_type must both be set for ViT backbones; "
104            f"got backbone={backbone} and model_type={model_type}."
105        )
106
107
108def _get_model(
109    patch_shape, out_channels, in_channels=1, backbone=None, model_type=None,
110    encoder_checkpoint=None, final_activation="Sigmoid", norm="InstanceNorm", scale_factors=None,
111):
112    is_2d, ndim = _determine_ndim(patch_shape)
113
114    if backbone == "cryosiam":
115        assert in_channels == 1
116        return get_cryozoounet(out_channels=out_channels, encoder=backbone, final_activation=final_activation)
117
118    if backbone is not None:
119        assert in_channels == 1
120        if encoder_checkpoint is None:
121            encoder_checkpoint = _get_checkpoint(backbone=backbone, model_type=model_type)
122        return get_unetr_model(
123            ndim=ndim, backbone=backbone, model_type=model_type,
124            encoder_checkpoint=encoder_checkpoint,
125            out_channels=out_channels, final_activation=final_activation,
126        )
127
128    if is_2d:
129        return get_2d_model(out_channels=out_channels, in_channels=in_channels, final_activation=final_activation)
130
131    scale_kwargs = {} if scale_factors is None else {"scale_factors": scale_factors}
132    return get_3d_model(
133        out_channels=out_channels, in_channels=in_channels, final_activation=final_activation, norm=norm,
134        **scale_kwargs,
135    )
136
137
138def normalize_percentile_to_0_1_inverted(raw):
139    """Normalize the raw data with percentiles to [0, 1] and invert the contrast."""
140    raw = 1 - normalize_percentile(raw)
141    return torch.clamp(raw, 0, 1) if torch.is_tensor(raw) else np.clip(raw, 0, 1)
142
143
144def get_raw_transform(backbone):
145    """Get the raw transform and the maximum input value for a pretrained backbone.
146
147    The ViT backbones are handled by `torch_em.transform.raw.get_raw_transform_for_pretrained_vit`.
148
149    Args:
150        backbone: The pretrained encoder. Options: "sam", "sam2", "dinov2", "dinov3", "cryosiam", or None.
151
152    Returns:
153        The raw transform. It normalizes the raw data with percentiles to [0, 255] for "sam",
154            and to [0, 1] for "sam2", "dinov2" and "dinov3". For "cryosiam" it also inverts the contrast.
155            None if `backbone` is None, so the loaders use the default torch-em standardization.
156        The maximum input value `clip_max`. The intensity augmentations clip their output to
157            [0, clip_max], so that the input stays in the expected range. None if `backbone` is None.
158    """
159    if backbone == "cryosiam":
160        return normalize_percentile_to_0_1_inverted, 1
161
162    if backbone not in ("sam", "sam2", "dinov2", "dinov3", None):
163        raise ValueError(f"Unsupported backbone '{backbone}'.")
164    return get_raw_transform_for_pretrained_vit(backbone)
165
166
167def _get_checkpoint(backbone, model_type):
168
169    if backbone == "sam":
170        if microsam_models is None:
171            raise RuntimeError(
172                "The 'sam' backbone requires micro_sam. Install it with 'conda install -c conda-forge micro_sam'."
173                )
174        model_registry = microsam_models()
175        encoder_checkpoint = model_registry.fetch(model_type, progressbar=True)
176
177    elif backbone == "sam2":
178        if microsam2_models is None:
179            raise RuntimeError(
180                "The 'sam2' backbone requires micro_sam with SAM2 support ('micro_sam.v2') and sam2."
181                )
182        model_registry = microsam2_models()
183        encoder_checkpoint = model_registry.fetch(model_type, progressbar=True)
184
185    elif backbone == "dinov2":
186        if get_vfm_model is None:
187            raise RuntimeError("The 'dinov2' backbone requires micro_sam with the 'micro_sam.models.vfm' module.")
188        encoder_checkpoint = get_vfm_model(f"{model_type}_dinov2", device="cpu").model.state_dict()
189
190    elif backbone == "dinov3":
191        if get_vfm_model is None:
192            raise RuntimeError("The 'dinov3' backbone requires micro_sam with the 'micro_sam.models.vfm' module.")
193        encoder_checkpoint = get_vfm_model(f"{model_type}_dinov3", device="cpu").model.state_dict()
194    else:
195        raise ValueError(f"Unsupported backbone '{backbone}'.")
196
197    return encoder_checkpoint
def get_3d_model( out_channels: int, in_channels: int = 1, scale_factors: Tuple[Tuple[int, int, int]] = [[1, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]], initial_features: int = 32, final_activation: str = 'Sigmoid', norm: Optional[str] = 'InstanceNorm') -> torch.nn.modules.module.Module:
31def get_3d_model(
32    out_channels: int,
33    in_channels: int = 1,
34    scale_factors: Tuple[Tuple[int, int, int]] = [[1, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]],
35    initial_features: int = 32,
36    final_activation: str = "Sigmoid",
37    norm: Optional[str] = "InstanceNorm",
38) -> torch.nn.Module:
39    """Get the U-Net model for 3D segmentation tasks.
40
41    Args:
42        out_channels: The number of output channels of the network.
43        scale_factors: The downscaling factors for each level of the U-Net encoder.
44        initial_features: The number of features in the first level of the U-Net.
45            The number of features increases by a factor of two in each level.
46        final_activation: The activation applied to the last output layer.
47        norm: The normalization layer used in the convolutional blocks, or None for no normalization.
48
49    Returns:
50        The U-Net.
51    """
52    model = AnisotropicUNet(
53        scale_factors=scale_factors,
54        in_channels=in_channels,
55        out_channels=out_channels,
56        initial_features=initial_features,
57        gain=2,
58        final_activation=final_activation,
59        norm=norm,
60    )
61    return model

Get the U-Net model for 3D segmentation tasks.

Arguments:
  • out_channels: The number of output channels of the network.
  • scale_factors: The downscaling factors for each level of the U-Net encoder.
  • initial_features: The number of features in the first level of the U-Net. The number of features increases by a factor of two in each level.
  • final_activation: The activation applied to the last output layer.
  • norm: The normalization layer used in the convolutional blocks, or None for no normalization.
Returns:

The U-Net.

def get_2d_model( out_channels: int, in_channels: int = 1, initial_features: int = 32, final_activation: str = 'Sigmoid') -> torch.nn.modules.module.Module:
64def get_2d_model(
65    out_channels: int,
66    in_channels: int = 1,
67    initial_features: int = 32,
68    final_activation: str = "Sigmoid",
69) -> torch.nn.Module:
70    """Get the U-Net model for 2D segmentation tasks.
71
72    Args:
73        out_channels: The number of output channels of the network.
74        initial_features: The number of features in the first level of the U-Net.
75            The number of features increases by a factor of two in each level.
76        final_activation: The activation applied to the last output layer.
77
78    Returns:
79        The U-Net.
80    """
81    model = UNet2d(
82        in_channels=in_channels,
83        out_channels=out_channels,
84        initial_features=initial_features,
85        gain=2,
86        depth=4,
87        final_activation=final_activation,
88    )
89    return model

Get the U-Net model for 2D segmentation tasks.

Arguments:
  • out_channels: The number of output channels of the network.
  • initial_features: The number of features in the first level of the U-Net. The number of features increases by a factor of two in each level.
  • final_activation: The activation applied to the last output layer.
Returns:

The U-Net.

def normalize_percentile_to_0_1_inverted(raw):
139def normalize_percentile_to_0_1_inverted(raw):
140    """Normalize the raw data with percentiles to [0, 1] and invert the contrast."""
141    raw = 1 - normalize_percentile(raw)
142    return torch.clamp(raw, 0, 1) if torch.is_tensor(raw) else np.clip(raw, 0, 1)

Normalize the raw data with percentiles to [0, 1] and invert the contrast.

def get_raw_transform(backbone):
145def get_raw_transform(backbone):
146    """Get the raw transform and the maximum input value for a pretrained backbone.
147
148    The ViT backbones are handled by `torch_em.transform.raw.get_raw_transform_for_pretrained_vit`.
149
150    Args:
151        backbone: The pretrained encoder. Options: "sam", "sam2", "dinov2", "dinov3", "cryosiam", or None.
152
153    Returns:
154        The raw transform. It normalizes the raw data with percentiles to [0, 255] for "sam",
155            and to [0, 1] for "sam2", "dinov2" and "dinov3". For "cryosiam" it also inverts the contrast.
156            None if `backbone` is None, so the loaders use the default torch-em standardization.
157        The maximum input value `clip_max`. The intensity augmentations clip their output to
158            [0, clip_max], so that the input stays in the expected range. None if `backbone` is None.
159    """
160    if backbone == "cryosiam":
161        return normalize_percentile_to_0_1_inverted, 1
162
163    if backbone not in ("sam", "sam2", "dinov2", "dinov3", None):
164        raise ValueError(f"Unsupported backbone '{backbone}'.")
165    return get_raw_transform_for_pretrained_vit(backbone)

Get the raw transform and the maximum input value for a pretrained backbone.

The ViT backbones are handled by torch_em.transform.raw.get_raw_transform_for_pretrained_vit.

Arguments:
  • backbone: The pretrained encoder. Options: "sam", "sam2", "dinov2", "dinov3", "cryosiam", or None.
Returns:

The raw transform. It normalizes the raw data with percentiles to [0, 255] for "sam", and to [0, 1] for "sam2", "dinov2" and "dinov3". For "cryosiam" it also inverts the contrast. None if backbone is None, so the loaders use the default torch-em standardization. The maximum input value clip_max. The intensity augmentations clip their output to [0, clip_max], so that the input stays in the expected range. None if backbone is None.