Skip to content

unet

Implementation of a flexible U-net.

Originally inspired by: https://github.com/milesial/Pytorch-UNet

Classes:

  • ConvBlock

    Convolution block: conv => BN => act.

  • DoubleConv

    Double convolution (conv => BN => ReLU) * 2.

  • DownBlock

    Down-scaling block.

  • UNet

    U-net model.

  • UpBlock

    Up-scaling block.

ConvBlock

ConvBlock(
    in_ch: int,
    out_ch: int,
    kernel_size: int,
    stride: int = 1,
    dilation: int = 1,
    pad_mode: str = "replicate",
    residual: bool = False,
    bias: bool = True,
    last_block: bool = False,
)

Bases: Sequential

Convolution block: conv => BN => act.

Source code in src/autoden/models/unet.py
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
def __init__(
    self,
    in_ch: int,
    out_ch: int,
    kernel_size: int,
    stride: int = 1,
    dilation: int = 1,
    pad_mode: str = "replicate",
    residual: bool = False,
    bias: bool = True,
    last_block: bool = False,
):
    pad_size = (kernel_size - 1) // 2 + (dilation - 1)
    if last_block:
        post_conv = []
    else:
        post_conv = [nn.BatchNorm2d(out_ch), nn.LeakyReLU(0.2, inplace=True)]
    super().__init__(
        nn.Conv2d(
            in_ch,
            out_ch,
            kernel_size=kernel_size,
            stride=stride,
            dilation=dilation,
            padding=pad_size,
            padding_mode=pad_mode,
            bias=bias,
        ),
        *post_conv,
    )
    if residual and in_ch != out_ch:
        print(f"Warning: Residual connections not available when {in_ch=} is different from {out_ch=}")
        residual = False
    self.residual = residual

DoubleConv

DoubleConv(
    in_ch: int, out_ch: int, pad_mode: str = "replicate"
)

Bases: Sequential

Double convolution (conv => BN => ReLU) * 2.

Source code in src/autoden/models/unet.py
82
83
84
85
86
def __init__(self, in_ch: int, out_ch: int, pad_mode: str = "replicate"):
    super().__init__(
        ConvBlock(in_ch, out_ch, kernel_size=3, pad_mode=pad_mode),
        ConvBlock(out_ch, out_ch, kernel_size=1),
    )

DownBlock

DownBlock(
    in_ch: int,
    out_ch: int,
    bilinear: bool = True,
    pad_mode: str = "replicate",
)

Bases: Sequential

Down-scaling block.

Source code in src/autoden/models/unet.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def __init__(self, in_ch: int, out_ch: int, bilinear: bool = True, pad_mode: str = "replicate"):
    if bilinear:
        down_block = [nn.AvgPool2d(2)]
    else:
        down_block = [ConvBlock(in_ch, in_ch, kernel_size=2, stride=2)]
    super().__init__(
        *down_block,
        DoubleConv(in_ch, out_ch, pad_mode=pad_mode),
    )
    self.pad_mode = pad_mode.lower()

UNet

UNet(
    n_channels_in: int,
    n_channels_out: int,
    n_features: int = 32,
    n_levels: int = 3,
    n_channels_skip: int | None = None,
    bilinear: bool = True,
    pad_mode: str = "replicate",
    device: str = "cuda" if is_available() else "cpu",
    verbose: bool = False,
)

Bases: Module

U-net model.

Source code in src/autoden/models/unet.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def __init__(
    self,
    n_channels_in: int,
    n_channels_out: int,
    n_features: int = 32,
    n_levels: int = 3,
    n_channels_skip: int | None = None,
    bilinear: bool = True,
    pad_mode: str = "replicate",
    device: str = "cuda" if pt.cuda.is_available() else "cpu",
    verbose: bool = False,
):
    init_params = locals()
    del init_params["self"]
    del init_params["__class__"]

    super().__init__()
    self.init_params = init_params
    self.device = device

    if pad_mode.lower() not in PAD_MODES:
        raise ValueError(f"Padding mode {pad_mode} should be one of {PAD_MODES}")
    self.pad_mode = pad_mode.lower()

    encoder, decoder = _compute_architecture(
        n_levels=n_levels, n_features=n_features, n_skip=n_channels_skip, verbose=verbose
    )

    self.in_layer = DoubleConv(n_channels_in, n_features, pad_mode=pad_mode)
    self.encoder_layers = nn.ModuleList([DownBlock(*lvl, bilinear=bilinear, pad_mode=pad_mode) for lvl in encoder])
    self.decoder_layers = nn.ModuleList([UpBlock(*lvl, bilinear=bilinear, pad_mode=pad_mode) for lvl in decoder])
    self.out_layer = ConvBlock(n_features, n_channels_out, kernel_size=1, last_block=True, pad_mode=pad_mode)

    if verbose:
        print(
            f"Model {self.__class__.__name__} - "
            f"num. parameters: {sum(p.numel() for p in self.parameters() if p.requires_grad)}"
        )
    self.to(self.device)

UpBlock

UpBlock(
    in_ch: int,
    skip_ch: int | None,
    out_ch: int,
    bilinear: bool = False,
    pad_mode: str = "replicate",
)

Bases: Module

Up-scaling block.

Source code in src/autoden/models/unet.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def __init__(self, in_ch: int, skip_ch: int | None, out_ch: int, bilinear: bool = False, pad_mode: str = "replicate"):
    super().__init__()
    self.skip_ch = skip_ch

    # Bilinear up-sampling tends to give better results, and use fewer weights
    if bilinear:
        self.up_block = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True)
    else:
        self.up_block = nn.ConvTranspose2d(in_ch, in_ch, kernel_size=2, stride=2)

    if skip_ch is not None:
        n_skip = skip_ch
        if skip_ch > 0:
            self.skip_block = ConvBlock(in_ch, skip_ch, kernel_size=1)
    else:
        n_skip = in_ch

    self.conv_block = DoubleConv(in_ch + n_skip, out_ch, pad_mode=pad_mode)