torch_em.model.hybrid_unetr
UNETR with hybrid 2D/3D decoders that read multi-scale encoder features.
The decoders read the encoder features at stride 4, 8 and 16 (e.g. of the SAM2 Hiera encoder) and the preprocessed image, from which an image stem computes the skips at stride 2 and 1. They follow the hybrid 2D/3D recipe:
- All spatial operations are 2D and run on the z-slices folded into the batch: (B, C, Z, H, W) becomes (B * Z, C, H, W). The normalization is a GroupNorm on the folded tensor, so its statistics are per slice.
- The context along z comes only from residual branches that are zero-initialized and skipped for a single slice:
ZResidual(convolution along z) andZAttention(attention along z).
The same weights therefore decode single images (Z = 1) and volumes (Z > 1). At initialization a volume decodes exactly to the stack of its decoded slices.
The blocks and decoders take the features with z folded into the batch, (B * Z, C, H, W). The ones with
context along z also take the number of slices n_z.
The decoders:
HieraUDecoder("hiera_u"): a plain skip U-decoder.C3F2Decoder("c3f2"): a coarse-3D / fine-2D fusion head. ConvNeXt blocks with attention along z at stride 16, with convolutions along z at strides 8 and 4, and a 2D image-guided upsampling head.CAGD3DDecoder("cagd_3d"): the decoder of MedCAGD (Wazir et al., arXiv 2607.00409, https://github.com/saadwazir/MedCAGD) adapted to the hybrid recipe: gated skip fusion, context aggregators, refinement blocks with channel recalibration and deep supervision.
HybridUNETR combines an encoder with one of the decoders.
1"""UNETR with hybrid 2D/3D decoders that read multi-scale encoder features. 2 3The decoders read the encoder features at stride 4, 8 and 16 (e.g. of the SAM2 Hiera encoder) and the preprocessed 4image, from which an image stem computes the skips at stride 2 and 1. They follow the hybrid 2D/3D recipe: 5 6- All spatial operations are 2D and run on the z-slices folded into the batch: (B, C, Z, H, W) becomes 7 (B * Z, C, H, W). The normalization is a GroupNorm on the folded tensor, so its statistics are per slice. 8- The context along z comes only from residual branches that are zero-initialized and skipped for a single slice: 9 `ZResidual` (convolution along z) and `ZAttention` (attention along z). 10 11The same weights therefore decode single images (Z = 1) and volumes (Z > 1). At initialization a volume decodes 12exactly to the stack of its decoded slices. 13 14The blocks and decoders take the features with z folded into the batch, (B * Z, C, H, W). The ones with 15context along z also take the number of slices `n_z`. 16 17The decoders: 18- `HieraUDecoder` ("hiera_u"): a plain skip U-decoder. 19- `C3F2Decoder` ("c3f2"): a coarse-3D / fine-2D fusion head. ConvNeXt blocks with attention along z at stride 16, 20 with convolutions along z at strides 8 and 4, and a 2D image-guided upsampling head. 21- `CAGD3DDecoder` ("cagd_3d"): the decoder of MedCAGD (Wazir et al., arXiv 2607.00409, 22 https://github.com/saadwazir/MedCAGD) adapted to the hybrid recipe: gated skip fusion, context aggregators, 23 refinement blocks with channel recalibration and deep supervision. 24 25`HybridUNETR` combines an encoder with one of the decoders. 26""" 27 28import math 29from os import PathLike 30from copy import deepcopy 31from collections.abc import Mapping 32from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union 33 34import torch 35import torch.nn as nn 36import torch.nn.functional as F 37 38from .unetr import UNETRBase 39 40 41def fold_z(x: torch.Tensor) -> torch.Tensor: 42 """Fold z into the batch: (B, C, Z, H, W) to (B * Z, C, H, W). 43 44 Args: 45 x: The input tensor. 46 47 Returns: 48 The folded tensor. 49 """ 50 b, c, z, h, w = x.shape 51 return x.transpose(1, 2).reshape(b * z, c, h, w) 52 53 54def unfold_z(x: torch.Tensor, n_z: int) -> torch.Tensor: 55 """Unfold z from the batch: (B * Z, C, H, W) to (B, C, Z, H, W). 56 57 Args: 58 x: The folded tensor. 59 n_z: The number of slices Z. 60 61 Returns: 62 The unfolded tensor. 63 """ 64 bz, c, h, w = x.shape 65 return x.reshape(bz // n_z, n_z, c, h, w).transpose(1, 2) 66 67 68def _group_norm(channels: int) -> nn.GroupNorm: 69 groups = min(8, channels) 70 # GroupNorm requires the channel count to be divisible by the number of groups. 71 while channels % groups != 0: 72 groups -= 1 73 return nn.GroupNorm(groups, channels) 74 75 76def _resize_to(x: torch.Tensor, reference: torch.Tensor) -> torch.Tensor: 77 if x.shape[-2:] == reference.shape[-2:]: 78 return x 79 return F.interpolate(x, size=reference.shape[-2:], mode="bilinear", align_corners=False) 80 81 82def _resize_cat(x: torch.Tensor, skip: torch.Tensor) -> torch.Tensor: 83 return torch.cat([_resize_to(x, skip), skip], dim=1) 84 85 86# The coarsest stride in the decoders (the stride-32 bottleneck of `CAGD3DDecoder`). 87_MAX_DECODER_STRIDE = 32 88 89 90def _crop_padding( 91 levels: Sequence[torch.Tensor], image: torch.Tensor, height: int, width: int 92) -> Tuple[List[torch.Tensor], torch.Tensor]: 93 """Crop the padding of the preprocessing from the image and the encoder features before decoding. 94 95 The crop is rounded up to the stride-32 grid, so that all strides of the decoder stay exactly aligned. 96 It is skipped if the padded size is not on this grid. 97 """ 98 padded_h, padded_w = image.shape[-2:] 99 if padded_h % _MAX_DECODER_STRIDE != 0 or padded_w % _MAX_DECODER_STRIDE != 0: 100 return list(levels), image 101 crop_h = min(padded_h, math.ceil(height / _MAX_DECODER_STRIDE) * _MAX_DECODER_STRIDE) 102 crop_w = min(padded_w, math.ceil(width / _MAX_DECODER_STRIDE) * _MAX_DECODER_STRIDE) 103 if (crop_h, crop_w) == (padded_h, padded_w): 104 return list(levels), image 105 levels = [ 106 level[..., :level.shape[-2] * crop_h // padded_h, :level.shape[-1] * crop_w // padded_w] 107 for level in levels 108 ] 109 return levels, image[..., :crop_h, :crop_w] 110 111 112# 113# BLOCKS 114# 115 116 117class ZResidual(nn.Module): 118 """A residual branch along z: x + pointwise(GELU(depthwise_z(x))). 119 120 The pointwise convolution is zero-initialized, so the branch starts as the identity. 121 It is skipped for a single slice, so 2D inputs never see it. 122 123 Args: 124 channels: The number of channels. 125 kernel_size: The kernel size along z. It must be odd. 126 """ 127 def __init__(self, channels: int, kernel_size: int = 3): 128 super().__init__() 129 self.depthwise = nn.Conv3d( 130 channels, channels, kernel_size=(kernel_size, 1, 1), padding=(kernel_size // 2, 0, 0), groups=channels, 131 ) 132 self.act = nn.GELU() 133 self.pointwise = nn.Conv3d(channels, channels, kernel_size=1) 134 nn.init.zeros_(self.pointwise.weight) 135 nn.init.zeros_(self.pointwise.bias) 136 137 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 138 if n_z == 1: 139 return x 140 volume = unfold_z(x, n_z) 141 return x + fold_z(self.pointwise(self.act(self.depthwise(volume)))) 142 143 144class ZAttention(nn.Module): 145 """Residual self-attention along z at every xy position, with a learned relative position bias. 146 147 The output projection is zero-initialized, so the block starts as the identity. 148 It is skipped for a single slice. 149 150 Args: 151 channels: The number of channels. 152 n_heads: The number of attention heads. By default, it uses one head per 64 channels. 153 max_distance: The largest z distance with its own position bias. Larger distances share the last one. 154 """ 155 def __init__(self, channels: int, n_heads: Optional[int] = None, max_distance: int = 16): 156 super().__init__() 157 self.n_heads = n_heads or max(1, channels // 64) 158 if channels % self.n_heads != 0: 159 raise ValueError(f"{channels} channels cannot be split into {self.n_heads} heads.") 160 self.norm = nn.LayerNorm(channels) 161 self.qkv = nn.Linear(channels, 3 * channels) 162 self.proj = nn.Linear(channels, channels) 163 nn.init.zeros_(self.proj.weight) 164 nn.init.zeros_(self.proj.bias) 165 self.max_distance = max_distance 166 self.position_bias = nn.Parameter(torch.zeros(self.n_heads, 2 * max_distance + 1)) 167 168 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 169 if n_z == 1: 170 return x 171 bz, c, h, w = x.shape 172 b = bz // n_z 173 tokens = x.reshape(b, n_z, c, h, w).permute(0, 3, 4, 1, 2).reshape(b * h * w, n_z, c) 174 qkv = self.qkv(self.norm(tokens)).reshape(-1, n_z, 3, self.n_heads, c // self.n_heads) 175 q, k, v = qkv.permute(2, 0, 3, 1, 4) 176 index = torch.arange(n_z, device=x.device) 177 distance = (index[None] - index[:, None]).clamp(-self.max_distance, self.max_distance) + self.max_distance 178 bias = self.position_bias[:, distance].to(q.dtype)[None] 179 out = F.scaled_dot_product_attention(q, k, v, attn_mask=bias) 180 out = self.proj(out.transpose(1, 2).reshape(-1, n_z, c)) 181 out = out.reshape(b, h, w, n_z, c).permute(0, 3, 4, 1, 2).reshape(bz, c, h, w) 182 return x + out 183 184 185class HybridBlock(nn.Module): 186 """A residual 2D block with per-slice GroupNorm and an optional zero-initialized z branch. 187 188 Args: 189 in_channels: The number of input channels. 190 out_channels: The number of output channels. 191 with_z: Whether to add the z branch. 192 """ 193 def __init__(self, in_channels: int, out_channels: int, with_z: bool = True): 194 super().__init__() 195 self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1, bias=False) 196 self.norm1 = _group_norm(out_channels) 197 self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False) 198 self.norm2 = _group_norm(out_channels) 199 self.shortcut = nn.Identity() if in_channels == out_channels else nn.Conv2d(in_channels, out_channels, 1) 200 self.act = nn.GELU() 201 self.z_branch = ZResidual(out_channels) if with_z else None 202 203 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 204 y = self.act(self.norm1(self.conv1(x))) 205 y = self.norm2(self.conv2(y)) 206 y = self.act(y + self.shortcut(x)) 207 if self.z_branch is not None: 208 y = self.z_branch(y, n_z) 209 return y 210 211 212class NeXtBlock(nn.Module): 213 """A ConvNeXt block in xy (7x7 depthwise, per-slice norm, inverted bottleneck), then an optional z module. 214 215 Args: 216 channels: The number of channels. 217 z_mode: The z module: 'attention' (`ZAttention`), 'conv' (`ZResidual`) or None. 218 """ 219 def __init__(self, channels: int, z_mode: Optional[str] = None): 220 super().__init__() 221 self.depthwise = nn.Conv2d(channels, channels, 7, padding=3, groups=channels) 222 self.norm = nn.GroupNorm(1, channels) 223 self.mlp = nn.Sequential( 224 nn.Conv2d(channels, 4 * channels, 1), nn.GELU(), nn.Conv2d(4 * channels, channels, 1), 225 ) 226 if z_mode == "attention": 227 self.z_module = ZAttention(channels) 228 elif z_mode == "conv": 229 self.z_module = ZResidual(channels) 230 elif z_mode is None: 231 self.z_module = None 232 else: 233 raise ValueError(f"Invalid z_mode {z_mode}") 234 235 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 236 x = x + self.mlp(self.norm(self.depthwise(x))) 237 return x if self.z_module is None else self.z_module(x, n_z) 238 239 240# 241# DECODERS 242# 243 244 245class HybridDecoder(nn.Module): 246 """Base class of the hybrid decoders. 247 248 It holds the projections of the stride-4 and stride-8 encoder features and the image stem, which computes 249 the skips at stride 1 (`stem1`) and stride 2 (`stem2`). A decoder implements 250 `forward(features, image, n_z)`, with all tensors folded: 251 - features: The encoder features at stride 4, 8 and 16, each of shape (B * Z, C_l, H_l, W_l). 252 - image: The preprocessed image of shape (B * Z, 3, H, W). 253 - n_z: The number of slices Z. 254 It returns logits of shape (B * Z, out_channels, H, W). During deep-supervision training it returns 255 `(logits, auxiliary_logits)`, with the auxiliary predictions in a list. 256 257 Args: 258 out_channels: The number of output channels. 259 stem_widths: The widths of the image stem at strides 1 and 2. 260 in_channels: The channels of the encoder features at stride 4, 8 and 16. 261 skip_projections: The output channels of the 1x1 projections of the stride-4 and stride-8 features. 262 The defaults correspond to `conv_s0` and `conv_s1` of the SAM2 mask decoder. 263 norm: The function that creates the normalization layer of the image stem for a number of channels. 264 activation: The activation of the image stem. 265 skip_activation: The activation applied after the skip projections. Decoders whose next layer on the 266 skips is another 1x1 convolution use it, so that the two convolutions do not collapse into one 267 linear map. 268 """ 269 def __init__( 270 self, 271 out_channels: int, 272 stem_widths: Sequence[int] = (16, 32), 273 in_channels: Sequence[int] = (256, 256, 256), 274 skip_projections: Sequence[int] = (32, 64), 275 norm: Callable[[int], nn.Module] = _group_norm, 276 activation: Callable[[], nn.Module] = nn.GELU, 277 skip_activation: Optional[Callable[[], nn.Module]] = None, 278 ): 279 super().__init__() 280 if len(in_channels) != 3: 281 raise ValueError(f"Expected the channels of three feature levels, got {in_channels}.") 282 self.out_channels = out_channels 283 self.in_channels = tuple(in_channels) 284 st1, st2 = stem_widths 285 self.stem1 = nn.Sequential(nn.Conv2d(3, st1, 3, padding=1, bias=False), norm(st1), activation()) 286 self.stem2 = nn.Sequential(nn.Conv2d(st1, st2, 3, stride=2, padding=1, bias=False), norm(st2), activation()) 287 self.skip_channels = tuple(skip_projections) 288 self.proj_s4 = nn.Conv2d(self.in_channels[0], self.skip_channels[0], 1) 289 self.proj_s8 = nn.Conv2d(self.in_channels[1], self.skip_channels[1], 1) 290 self.skip_act = None if skip_activation is None else skip_activation() 291 292 def _project(self, features: Sequence[torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 293 s4, s8, s16 = features 294 s4, s8 = self.proj_s4(s4), self.proj_s8(s8) 295 if self.skip_act is not None: 296 s4, s8 = self.skip_act(s4), self.skip_act(s8) 297 return s4, s8, s16 298 299 300class HieraUDecoder(HybridDecoder): 301 """A plain skip U-decoder on the encoder features at stride 4, 8 and 16 and an image stem. 302 303 All spatial operations are 2D on the slices folded into the batch. The z branches of the blocks at 304 strides 16 to 2 carry the 3D context. The full-resolution block is 2D only. 305 306 Args: 307 out_channels: The number of output channels. 308 widths: The decoder widths at strides 16, 8, 4, 2 and 1. 309 stem_widths: The widths of the image stem at strides 1 and 2. 310 in_channels: The channels of the encoder features at stride 4, 8 and 16. 311 skip_projections: The output channels of the 1x1 projections of the stride-4 and stride-8 features. 312 """ 313 def __init__( 314 self, 315 out_channels: int = 5, 316 widths: Sequence[int] = (192, 128, 64, 32, 16), 317 stem_widths: Sequence[int] = (16, 32), 318 in_channels: Sequence[int] = (256, 256, 256), 319 skip_projections: Sequence[int] = (32, 64), 320 ): 321 super().__init__(out_channels, stem_widths, in_channels, skip_projections) 322 w16, w8, w4, w2, w1 = widths 323 st1, st2 = stem_widths 324 c4, c8 = self.skip_channels 325 self.block16 = HybridBlock(self.in_channels[2], w16) 326 self.block8 = HybridBlock(w16 + c8, w8) 327 self.block4 = HybridBlock(w8 + c4, w4) 328 self.block2 = HybridBlock(w4 + st2, w2) 329 self.block1 = HybridBlock(w2 + st1, w1, with_z=False) 330 self.out_conv = nn.Conv2d(w1, out_channels, 1) 331 332 def forward(self, features: Sequence[torch.Tensor], image: torch.Tensor, n_z: int) -> torch.Tensor: 333 """Apply the decoder, see `HybridDecoder`.""" 334 s4, s8, s16 = self._project(features) 335 stem1 = self.stem1(image) 336 stem2 = self.stem2(stem1) 337 x = self.block16(s16, n_z) 338 x = self.block8(_resize_cat(x, s8), n_z) 339 x = self.block4(_resize_cat(x, s4), n_z) 340 x = self.block2(_resize_cat(x, stem2), n_z) 341 x = self.block1(_resize_cat(x, stem1), n_z) 342 return self.out_conv(x) 343 344 345class C3F2Decoder(HybridDecoder): 346 """A coarse-3D / fine-2D fusion head on the encoder features at stride 4, 8 and 16 and an image stem. 347 348 Stride 16: two ConvNeXt blocks, each followed by attention along z. All long-range z reasoning happens here. 349 Stride 8 and 4: additive top-down fusion with the lateral features and ConvNeXt blocks with z convolutions 350 (the last block at stride 4 is 2D). Finer: two transposed convolutions to full resolution, each fused with the 351 image stem, in 2D only. 352 353 Args: 354 out_channels: The number of output channels. 355 widths: The widths at strides 16, 8 and 4. 356 head_width: The width of the stride-2 head. The stride-1 head uses the stride-1 stem width. 357 stem_widths: The widths of the image stem at strides 1 and 2. 358 in_channels: The channels of the encoder features at stride 4, 8 and 16. 359 skip_projections: The output channels of the 1x1 projections of the stride-4 and stride-8 features. 360 They are followed by a GELU, since the lateral convolutions are also 1x1. 361 """ 362 def __init__( 363 self, 364 out_channels: int = 5, 365 widths: Sequence[int] = (256, 128, 64), 366 head_width: int = 32, 367 stem_widths: Sequence[int] = (16, 32), 368 in_channels: Sequence[int] = (256, 256, 256), 369 skip_projections: Sequence[int] = (32, 64), 370 ): 371 super().__init__(out_channels, stem_widths, in_channels, skip_projections, skip_activation=nn.GELU) 372 w16, w8, w4 = widths 373 st1, st2 = stem_widths 374 c4, c8 = self.skip_channels 375 self.lateral16 = nn.Conv2d(self.in_channels[2], w16, 1) 376 self.blocks16 = nn.ModuleList([NeXtBlock(w16, "attention"), NeXtBlock(w16, "attention")]) 377 self.lateral8 = nn.Conv2d(c8, w8, 1) 378 self.reduce8 = nn.Conv2d(w16, w8, 1) 379 self.blocks8 = nn.ModuleList([NeXtBlock(w8, "conv"), NeXtBlock(w8, "conv")]) 380 self.lateral4 = nn.Conv2d(c4, w4, 1) 381 self.reduce4 = nn.Conv2d(w8, w4, 1) 382 self.blocks4 = nn.ModuleList([NeXtBlock(w4, "conv"), NeXtBlock(w4, None)]) 383 self.up2 = nn.Sequential(nn.ConvTranspose2d(w4, head_width, 2, stride=2), _group_norm(head_width), nn.GELU()) 384 self.fuse2 = nn.Sequential( 385 nn.Conv2d(head_width + st2, head_width, 3, padding=1, bias=False), _group_norm(head_width), nn.GELU(), 386 ) 387 self.up1 = nn.Sequential(nn.ConvTranspose2d(head_width, st1, 2, stride=2), _group_norm(st1), nn.GELU()) 388 self.fuse1 = nn.Sequential( 389 nn.Conv2d(2 * st1, st1, 3, padding=1, bias=False), _group_norm(st1), nn.GELU(), 390 ) 391 self.out_conv = nn.Conv2d(st1, out_channels, 1) 392 393 @staticmethod 394 def _run(blocks, x, n_z): 395 for block in blocks: 396 x = block(x, n_z) 397 return x 398 399 def forward(self, features: Sequence[torch.Tensor], image: torch.Tensor, n_z: int) -> torch.Tensor: 400 """Apply the decoder, see `HybridDecoder`.""" 401 s4, s8, s16 = self._project(features) 402 stem1 = self.stem1(image) 403 stem2 = self.stem2(stem1) 404 x = self._run(self.blocks16, self.lateral16(s16), n_z) 405 lateral = self.lateral8(s8) 406 x = self._run(self.blocks8, _resize_to(self.reduce8(x), lateral) + lateral, n_z) 407 lateral = self.lateral4(s4) 408 x = self._run(self.blocks4, _resize_to(self.reduce4(x), lateral) + lateral, n_z) 409 x = self.fuse2(_resize_cat(self.up2(x), stem2)) 410 x = self.fuse1(_resize_cat(self.up1(x), stem1)) 411 return self.out_conv(x) 412 413 414# 415# CAGD-3D: MedCAGD adapted to the hybrid 2D/3D recipe. 416# 417 418 419def _cagd_group_norm(channels: int) -> nn.GroupNorm: 420 """GroupNorm with the group count of MedCAGD (4 to 32 channels per group). Per slice on folded inputs.""" 421 for groups in (32, 16, 8, 4, 2, 1): 422 if channels % groups == 0 and 4 <= channels // groups <= 32: 423 return nn.GroupNorm(groups, channels) 424 return nn.GroupNorm(1, channels) 425 426 427class ECA(nn.Module): 428 """Efficient channel attention of MedCAGD with a learned temperature, pooled per slice. 429 430 MedCAGD averages three convolutions of the global mean (its pooling scales 1, 2, 4 all reduce to the global 431 mean). This is linear and thus equal to one convolution, which is used here. 432 433 Args: 434 channels: The number of channels. 435 is_encoder: Whether to use the kernel size rule of MedCAGD for encoder (skip) or for decoder features. 436 """ 437 def __init__(self, channels: int, is_encoder: bool = True): 438 super().__init__() 439 gamma, b = (2.0, 1.0) if is_encoder else (2.4, 0.8) 440 k = int(abs(math.log2(channels) / gamma + b)) 441 k = k + 1 if k % 2 == 0 else k 442 self.conv = nn.Conv1d(1, 1, kernel_size=k, padding=(k - 1) // 2, bias=False) 443 self.log_tau = nn.Parameter(torch.zeros(())) 444 self.tau_min, self.tau_max = 0.5, 2.0 445 446 def forward(self, x: torch.Tensor) -> torch.Tensor: 447 logits = self.conv(x.mean(dim=(2, 3))[:, None])[:, 0] # (N, C), N = slices 448 tau = self.log_tau.exp().clamp(self.tau_min, self.tau_max) 449 attention = torch.sigmoid(logits / tau) 450 attention = attention / (attention.mean(dim=1, keepdim=True) + 1e-6) 451 return x * attention[..., None, None] 452 453 454class GlobalContext(nn.Module): 455 """The residual global-context attention of MedCAGD (a GCNet block), pooled per slice. 456 457 Args: 458 channels: The number of channels. 459 reduction: The channel reduction of the transform. 460 """ 461 def __init__(self, channels: int, reduction: int = 16): 462 super().__init__() 463 inter = max(4, channels // reduction) # MedCAGD: max(1, ...); same for the default widths (>= 64) 464 self.mask = nn.Conv2d(channels, 1, kernel_size=1) 465 self.transform = nn.Sequential( 466 nn.Conv2d(channels, inter, kernel_size=1, bias=False), 467 nn.GroupNorm(1, inter), # = LayerNorm([inter, 1, 1]) of MedCAGD 468 nn.ReLU(inplace=True), 469 nn.Conv2d(inter, channels, kernel_size=1, bias=False), 470 ) 471 472 def forward(self, x: torch.Tensor) -> torch.Tensor: 473 n, c, h, w = x.shape 474 weights = torch.softmax(self.mask(x).reshape(n, 1, h * w), dim=-1) 475 context = torch.bmm(x.reshape(n, c, h * w), weights.transpose(1, 2)).reshape(n, c, 1, 1) 476 return x + self.transform(context) 477 478 479class SCAGate(nn.Module): 480 """The attention gate of MedCAGD (SCA-Gate): gates the skip features with guidance from the decoder. 481 482 Changed against MedCAGD: 483 - For large inputs: the spatial competition is a softmax over the H * W positions of a slice, with 484 values of about 1 / (H * W), which is numerically zero for inputs of size 1024. It is rescaled by H * W 485 (mean one) and clamped at `max_spatial`. 486 - The global channel modulation G is an SE-style bottleneck (conv, SiLU, conv, sigmoid). MedCAGD applies 487 the sigmoid directly after conv and SiLU, which limits the factor 1 + G to [1.43, 2). 488 489 Args: 490 guide_channels: The channels of the upsampled decoder features. 491 skip_channels: The channels of the skip features. 492 inter_channels: The latent width. 493 max_spatial: The maximum of the rescaled spatial attention. 494 """ 495 def __init__(self, guide_channels: int, skip_channels: int, inter_channels: int, max_spatial: float = 4.0): 496 super().__init__() 497 self.eca_skip = ECA(skip_channels, is_encoder=True) 498 self.eca_guide = ECA(guide_channels, is_encoder=False) 499 500 def branch(channels): 501 return nn.Sequential( 502 nn.Conv2d(channels, inter_channels, 3, padding=1, bias=False), _cagd_group_norm(inter_channels), 503 nn.SiLU(), 504 nn.Conv2d(inter_channels, inter_channels, 3, padding=2, dilation=2, groups=inter_channels, 505 bias=False), 506 _cagd_group_norm(inter_channels), nn.SiLU(), 507 ) 508 self.theta, self.phi = branch(guide_channels), branch(skip_channels) 509 hidden_channels = max(8, inter_channels // 4) 510 self.global_fc = nn.Sequential( 511 nn.Conv2d(guide_channels + skip_channels, hidden_channels, 1), nn.SiLU(), 512 nn.Conv2d(hidden_channels, inter_channels, 1), nn.Sigmoid(), 513 ) 514 self.dw3 = nn.Conv2d(inter_channels, inter_channels, 3, padding=1, groups=inter_channels, bias=False) 515 self.dw5 = nn.Conv2d(inter_channels, inter_channels, 5, padding=2, groups=inter_channels, bias=False) 516 self.score = nn.Conv2d(inter_channels, 1, 1, bias=False) 517 self.log_tau = nn.Parameter(torch.tensor(0.7).log()) 518 self.tau_min, self.tau_max = 0.3, 2.0 519 self.max_spatial = max_spatial 520 self.att = nn.Sequential(nn.GroupNorm(1, inter_channels), nn.Conv2d(inter_channels, 1, 1), nn.Hardsigmoid()) 521 522 def forward(self, guide: torch.Tensor, skip: torch.Tensor) -> torch.Tensor: 523 skip = self.eca_skip(skip) 524 guide = self.eca_guide(guide) 525 fused = F.normalize(self.theta(guide) * self.phi(skip), p=2, dim=1) 526 fused = fused + self.global_fc(torch.cat([guide, skip], dim=1).mean(dim=(2, 3), keepdim=True)) * fused 527 score = self.score(self.dw3(fused) + self.dw5(fused)) 528 n, _, h, w = score.shape 529 tau = self.log_tau.exp().clamp(self.tau_min, self.tau_max) 530 spatial = torch.softmax(score.reshape(n, h * w) / tau, dim=-1).reshape(n, 1, h, w) * (h * w) 531 fused = fused * (1.0 + spatial.clamp(max=self.max_spatial)) 532 return skip * self.att(fused + 1e-5) 533 534 535class DWBlock(nn.Module): 536 """The conv block of MedCAGD (depthwise 3x3 and pointwise, twice), followed by a zero-initialized z branch. 537 538 Args: 539 in_channels: The number of input channels. 540 out_channels: The number of output channels. 541 with_z: Whether to add the z branch. 542 """ 543 def __init__(self, in_channels: int, out_channels: int, with_z: bool = True): 544 super().__init__() 545 self.block = nn.Sequential( 546 nn.Conv2d(in_channels, in_channels, 3, padding=1, groups=in_channels, bias=False), 547 _cagd_group_norm(in_channels), nn.SiLU(), 548 nn.Conv2d(in_channels, out_channels, 1, bias=False), _cagd_group_norm(out_channels), nn.SiLU(), 549 nn.Conv2d(out_channels, out_channels, 3, padding=1, groups=out_channels, bias=False), 550 _cagd_group_norm(out_channels), nn.SiLU(), 551 nn.Conv2d(out_channels, out_channels, 1, bias=False), _cagd_group_norm(out_channels), nn.SiLU(), 552 ) 553 self.z_branch = ZResidual(out_channels) if with_z else None 554 555 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 556 x = self.block(x) 557 return x if self.z_branch is None else self.z_branch(x, n_z) 558 559 560class RefinementBlock(nn.Module): 561 """The refinement block of MedCAGD: conv block, optional depthwise spatial conv and channel recalibration. 562 563 Args: 564 channels: The number of channels. 565 spatial_focus: Whether to add the depthwise spatial convolution. 566 with_z: Whether to add the z branch to the conv block. 567 """ 568 def __init__(self, channels: int, spatial_focus: bool, with_z: bool = True): 569 super().__init__() 570 self.conv = DWBlock(channels, channels, with_z=with_z) 571 self.spatial = nn.Conv2d(channels, channels, 3, padding=1, groups=channels) if spatial_focus else None 572 self.eca = ECA(channels) 573 574 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 575 x = self.conv(x, n_z) 576 if self.spatial is not None: 577 x = self.spatial(x) 578 return self.eca(x) 579 580 581class CAGDStage(nn.Module): 582 """The decoder block of MedCAGD: transposed-conv upsampling, gated skip fusion and the conv block. 583 584 The skips are gated only if they have more than 64 channels, as in MedCAGD. 585 586 Args: 587 in_channels: The number of input channels. 588 skip_channels: The channels of the skip features. 589 out_channels: The number of output channels. 590 with_z: Whether to add the z branch to the conv block. 591 """ 592 def __init__(self, in_channels: int, skip_channels: int, out_channels: int, with_z: bool = True): 593 super().__init__() 594 self.up = nn.ConvTranspose2d(in_channels, out_channels, kernel_size=2, stride=2) 595 self.gate = SCAGate(out_channels, skip_channels, max(1, skip_channels // 2)) if skip_channels > 64 else None 596 self.conv = DWBlock(out_channels + skip_channels, out_channels, with_z=with_z) 597 598 def forward(self, x: torch.Tensor, skip: torch.Tensor, n_z: int) -> torch.Tensor: 599 x = _resize_to(self.up(x), skip) 600 if self.gate is not None: 601 skip = self.gate(x, skip) 602 return self.conv(torch.cat([x, skip], dim=1), n_z) 603 604 605class ContextAggregator(nn.Module): 606 """The context aggregator of MedCAGD: all pyramid levels projected, resized and averaged, plus global context. 607 608 Args: 609 in_channels: The channels of the pyramid levels. 610 out_channels: The number of output channels. 611 """ 612 def __init__(self, in_channels: Sequence[int], out_channels: int): 613 super().__init__() 614 self.proj = nn.ModuleList([nn.Conv2d(c, out_channels, kernel_size=1) for c in in_channels]) 615 self.global_context = GlobalContext(out_channels) 616 617 def forward(self, features: Sequence[torch.Tensor], reference: torch.Tensor) -> torch.Tensor: 618 fused = sum(_resize_to(proj(f), reference) for f, proj in zip(features, self.proj)) 619 return self.global_context(fused / len(features)) 620 621 622class CAGD3DDecoder(HybridDecoder): 623 """The decoder of MedCAGD on the encoder features at stride 4, 8 and 16, adapted to the hybrid 2D/3D recipe. 624 625 MedCAGD: Wazir et al., arXiv 2607.00409, https://github.com/saadwazir/MedCAGD. 626 627 Pyramid: 1x1 projections of the features at stride 4, 8 and 16. The stride-32 level is a strided 3x3 convolution 628 of the stride-16 features. The bottleneck (conv, attention along z, global context) and the stages at strides 629 16, 8 and 4 (gated fusion, context aggregator, refinement) follow MedCAGD. All global pooling is per slice 630 and the blocks have zero-initialized z branches. 631 632 Changed against MedCAGD: the last stage runs at stride 2 with an image-stem skip instead of at full resolution 633 (the full-resolution stage of MedCAGD costs 1.7x the FLOPs). It is followed by a transposed convolution to 634 full resolution, fused with the stride-1 stem. 635 636 Deep supervision (optional): 1x1 heads on the stages at strides 16, 8 and 4 predict all output channels. 637 During training the auxiliary logits are upsampled to the image size and returned with the main logits. 638 The loss should use all three auxiliary outputs, ordered from deepest to shallowest. 639 With `deep_supervision=True`, the model returns the tuple `(prediction, auxiliary_outputs)` in training mode. 640 Train it with `HybridUNETRDeepSupervisionTrainer` from `torch_em.trainer.hybrid_unetr_trainer`. 641 `DefaultTrainer`, or other code that calls the model in training mode (e.g. the self-training trainers), 642 receives the tuple instead of a tensor and fails. 643 644 Args: 645 out_channels: The number of output channels. 646 widths: The pyramid widths at strides 4, 8, 16 and 32. 647 stem_widths: The widths of the image stem at strides 1 and 2. 648 deep_supervision: Whether to build the deep supervision heads. 649 in_channels: The channels of the encoder features at stride 4, 8 and 16. 650 skip_projections: The output channels of the 1x1 projections of the stride-4 and stride-8 features. 651 They are followed by a SiLU, since the pyramid convolutions are also 1x1. The defaults match the 652 pyramid widths (256 -> 64 -> SiLU -> 64 and 256 -> 128 -> SiLU -> 128), so they are wider than 653 `conv_s0` and `conv_s1` of SAM2 and `HybridUNETR.init_skip_projections` does not apply to them. 654 """ 655 def __init__( 656 self, 657 out_channels: int = 5, 658 widths: Sequence[int] = (64, 128, 320, 512), 659 stem_widths: Sequence[int] = (16, 32), 660 deep_supervision: bool = False, 661 in_channels: Sequence[int] = (256, 256, 256), 662 skip_projections: Sequence[int] = (64, 128), 663 ): 664 super().__init__( 665 out_channels, stem_widths, in_channels, skip_projections, 666 norm=_cagd_group_norm, activation=nn.SiLU, skip_activation=nn.SiLU, 667 ) 668 w4, w8, w16, w32 = widths 669 st1, st2 = stem_widths 670 c4, c8 = self.skip_channels 671 c16 = self.in_channels[2] 672 self.p4 = nn.Conv2d(c4, w4, 1) 673 self.p8 = nn.Conv2d(c8, w8, 1) 674 self.p16 = nn.Conv2d(c16, w16, 1) 675 self.p32 = nn.Conv2d(c16, w32, 3, stride=2, padding=1) 676 677 self.bottleneck_conv = nn.Sequential(nn.Conv2d(w32, w32, 3, padding=1), _cagd_group_norm(w32), nn.SiLU()) 678 self.bottleneck_z = ZAttention(w32) 679 self.bottleneck_context = GlobalContext(w32) 680 681 levels = (w4, w8, w16, w32) 682 self.stage16, self.context16, self.ref16 = ( 683 CAGDStage(w32, w16, w16), ContextAggregator(levels, w16), RefinementBlock(w16, spatial_focus=False), 684 ) 685 self.stage8, self.context8, self.ref8 = ( 686 CAGDStage(w16, w8, w8), ContextAggregator(levels, w8), RefinementBlock(w8, spatial_focus=True), 687 ) 688 self.stage4, self.context4, self.ref4 = ( 689 CAGDStage(w8, w4, w4), ContextAggregator(levels, w4), RefinementBlock(w4, spatial_focus=True), 690 ) 691 self.stage2 = CAGDStage(w4, st2, st2) 692 self.ref2 = RefinementBlock(st2, spatial_focus=True) 693 694 self.head_up = nn.Sequential( 695 nn.ConvTranspose2d(st2, st1, kernel_size=2, stride=2), _cagd_group_norm(st1), nn.SiLU(), 696 ) 697 self.head_fuse = nn.Sequential( 698 nn.Conv2d(2 * st1, st1, 3, padding=1, bias=False), _cagd_group_norm(st1), nn.SiLU(), 699 ) 700 self.out_conv = nn.Conv2d(st1, out_channels, 1) 701 self.aux_heads = nn.ModuleList( 702 [nn.Conv2d(c, out_channels, 1) for c in (w16, w8, w4)] 703 ) if deep_supervision else None 704 705 def forward( 706 self, features: Sequence[torch.Tensor], image: torch.Tensor, n_z: int 707 ) -> Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]: 708 """Apply the decoder, see `HybridDecoder`.""" 709 s4, s8, s16 = self._project(features) 710 stem1 = self.stem1(image) 711 stem2 = self.stem2(stem1) 712 p4, p8, p16 = self.p4(s4), self.p8(s8), self.p16(s16) 713 b = self.bottleneck_conv(self.p32(s16)) 714 b = self.bottleneck_context(self.bottleneck_z(b, n_z)) 715 levels = [p4, p8, p16, b] 716 717 d16 = self.stage16(b, p16, n_z) 718 d16 = self.ref16(d16 + self.context16(levels, d16), n_z) 719 d8 = self.stage8(d16, p8, n_z) 720 d8 = self.ref8(d8 + self.context8(levels, d8), n_z) 721 d4 = self.stage4(d8, p4, n_z) 722 d4 = self.ref4(d4 + self.context4(levels, d4), n_z) 723 d2 = self.ref2(self.stage2(d4, stem2, n_z), n_z) 724 725 out = self.out_conv(self.head_fuse(_resize_cat(self.head_up(d2), stem1))) 726 727 if self.training and self.aux_heads is not None: 728 auxiliary_logits = [ 729 _resize_to(head(d), image) for head, d in zip(self.aux_heads, (d16, d8, d4)) 730 ] 731 return out, auxiliary_logits 732 return out 733 734 735HYBRID_DECODERS = {"hiera_u": HieraUDecoder, "c3f2": C3F2Decoder, "cagd_3d": CAGD3DDecoder} 736"""The hybrid decoders by name.""" 737 738 739# 740# MODEL 741# 742 743 744class HybridUNETR(UNETRBase): 745 """A UNETR for 2D and 3D inputs with a multi-scale encoder and a hybrid 2D/3D decoder. 746 747 The model applies the encoder to each slice and decodes all slices together. The same weights process 748 images of shape (B, C, Y, X) and volumes of shape (B, C, Z, Y, X). An image is processed like a volume 749 with a single slice. 750 751 Each slice is resized (if `resize_input`) and zero-padded to the input size of the encoder. Before decoding, 752 the padding is cropped from the image and the encoder features, rounded up to the stride-32 grid, so that the 753 per-slice normalization and global pooling in the decoder see (almost) no padding. The encoder itself still 754 sees the padding. 755 756 The forward pass returns the prediction. During training with deep supervision (see `CAGD3DDecoder`), it 757 returns `(prediction, auxiliary_outputs)` instead. The training loss should use the tensors from this pair, 758 including under DistributedDataParallel. 759 760 The state of the model has the two prefixes 'encoder.' and 'decoder.'. 761 762 Args: 763 img_size: The input size of the image encoder, used to build it if it is given by name. Preprocessing 764 resizes and pads the slices to `encoder.img_size`, so for an encoder module this argument does not 765 change the preprocessing. 766 backbone: The name of the vision transformer implementation. The model was designed for 'sam2'. 767 encoder: The image encoder. Can either be a name, such as 'hvit_t', or a torch module. 768 A module must have the attribute `img_size` and return a tuple, with the list of features 769 at stride 4, 8 and 16 as second element, like `torch_em.model.vit.ViT_Sam2`. 770 decoder: The decoder. Can either be a name from `HYBRID_DECODERS` ('hiera_u', 'c3f2' or 'cagd_3d') or 771 a torch module that implements the interface of `HybridDecoder` and has the attribute `in_channels`. 772 decoder_kwargs: The keyword arguments for the decoder, if it is given by name. 773 out_channels: The number of output channels. It is ignored if the decoder is a torch module. 774 use_sam_stats: Whether to normalize the input data with the statistics of the pretrained SAM2 model. 775 use_mae_stats: Whether to normalize the input data with the statistics of the pretrained MAE model. 776 use_dino_stats: Whether to normalize the input data with the statistics of the pretrained DINO models. 777 use_imagenet_stats: Whether to normalize with standard ImageNet statistics. 778 resize_input: Whether to resize each slice so that its longest side matches `encoder.img_size`. 779 If False, slices must not be larger than `encoder.img_size` and are only padded. 780 encoder_checkpoint: Checkpoint for initializing the image encoder. 781 Can either be a filepath or an already loaded checkpoint. It does not initialize the projections 782 of the stride-4 and stride-8 features in the decoder, see `init_skip_projections`. 783 final_activation: The activation to apply before resizing the output. It receives a 4D tensor for an image 784 and a 5D tensor for a volume. 785 perform_range_checks: Whether to validate the input value range before normalization on each forward pass. 786 kwargs: Keyword arguments for `torch_em.model.vit.get_vision_transformer`, if the encoder is given by name. 787 """ 788 def __init__( 789 self, 790 img_size: int = 1024, 791 backbone: str = "sam2", 792 encoder: Union[nn.Module, str] = "hvit_t", 793 decoder: Union[nn.Module, str] = "hiera_u", 794 decoder_kwargs: Optional[dict] = None, 795 out_channels: int = 1, 796 use_sam_stats: bool = False, 797 use_mae_stats: bool = False, 798 use_dino_stats: bool = False, 799 use_imagenet_stats: bool = False, 800 resize_input: bool = True, 801 encoder_checkpoint: Optional[Union[str, PathLike, Mapping]] = None, 802 final_activation: Optional[Union[str, nn.Module]] = None, 803 perform_range_checks: bool = True, 804 **kwargs 805 ) -> None: 806 if isinstance(decoder, str): 807 if decoder not in HYBRID_DECODERS: 808 raise ValueError(f"Invalid decoder '{decoder}', choose from {list(HYBRID_DECODERS)}.") 809 decoder_module = HYBRID_DECODERS[decoder](out_channels=out_channels, **(decoder_kwargs or {})) 810 elif isinstance(decoder, nn.Module): 811 if decoder_kwargs: 812 raise ValueError("The decoder_kwargs are only supported for a decoder that is given by name.") 813 decoder_module = decoder 814 else: 815 raise TypeError("The decoder must be a decoder name or a torch module.") 816 817 super().__init__( 818 img_size=img_size, 819 backbone=backbone, 820 encoder=encoder, 821 out_channels=out_channels, 822 use_sam_stats=use_sam_stats, 823 use_mae_stats=use_mae_stats, 824 use_dino_stats=use_dino_stats, 825 use_imagenet_stats=use_imagenet_stats, 826 resize_input=resize_input, 827 encoder_checkpoint=encoder_checkpoint, 828 final_activation=final_activation, 829 # Read the stride-16 width from the decoder to support custom encoders. 830 embed_dim=decoder_module.in_channels[-1], 831 perform_range_checks=perform_range_checks, 832 **kwargs, 833 ) 834 self.init_kwargs = { 835 "img_size": img_size, "backbone": backbone, "encoder": encoder, "decoder": decoder, 836 "decoder_kwargs": deepcopy(decoder_kwargs), "out_channels": out_channels, "use_sam_stats": use_sam_stats, 837 "use_mae_stats": use_mae_stats, "use_dino_stats": use_dino_stats, 838 "use_imagenet_stats": use_imagenet_stats, "resize_input": resize_input, 839 "final_activation": final_activation, "perform_range_checks": perform_range_checks, **kwargs, 840 } 841 842 self.decoder = decoder_module 843 self.out_channels = getattr(decoder_module, "out_channels", out_channels) 844 845 def init_skip_projections(self, conv_s0: nn.Module, conv_s1: nn.Module) -> None: 846 """Initialize the projections of the stride-4 and stride-8 features in the decoder from other modules. 847 848 This copies the weights, the modules are not shared. For SAM2, pass `sam_mask_decoder.conv_s0` and 849 `sam_mask_decoder.conv_s1` of the SAM2 model. 850 851 Args: 852 conv_s0: The projection of the stride-4 features. 853 conv_s1: The projection of the stride-8 features. 854 """ 855 proj_s4, proj_s8 = getattr(self.decoder, "proj_s4", None), getattr(self.decoder, "proj_s8", None) 856 if proj_s4 is None or proj_s8 is None: 857 raise RuntimeError("The decoder does not have projections for the stride-4 and stride-8 features.") 858 proj_s4.load_state_dict(conv_s0.state_dict()) 859 proj_s8.load_state_dict(conv_s1.state_dict()) 860 861 @property 862 def decoder_config(self) -> dict: 863 """The arguments that rebuild the decoder. They can be serialized to JSON, e.g. to store them in checkpoints. 864 """ 865 decoder = self.init_kwargs["decoder"] 866 if not isinstance(decoder, str): 867 raise RuntimeError("The decoder_config is only available for a decoder that is given by name.") 868 return { 869 "decoder": decoder, "decoder_kwargs": deepcopy(self.init_kwargs["decoder_kwargs"] or {}), 870 "out_channels": self.out_channels, 871 } 872 873 def encode(self, x: torch.Tensor) -> Tuple[Dict[str, Union[List[torch.Tensor], torch.Tensor, int]], Tuple]: 874 """Preprocess the input and run the image encoder on all slices. 875 876 Args: 877 x: The input tensor with shape (B, C, Z, Y, X) or (B, C, Y, X). 878 879 Returns: 880 The features to pass to `decode`: a dictionary with the encoder features at stride 4, 8 and 16 881 ('features'), the preprocessed image ('image'), both with z folded into the batch, and the 882 number of slices ('n_z'). 883 The spatial shape (Z, Y, X) after preprocessing. 884 """ 885 if x.ndim == 4: # An image is processed as a volume with a single slice. 886 x = x[:, :, None] 887 elif x.ndim != 5: 888 raise ValueError(f"Expected 4d or 5d inputs, got {tuple(x.shape)}.") 889 890 height, width = x.shape[-2:] 891 encoder_size = self.encoder.img_size 892 if not self.resize_input and max(height, width) > encoder_size: 893 raise ValueError( 894 f"Input size {(height, width)} exceeds the encoder size {(encoder_size, encoder_size)} " 895 "with resize_input=False." 896 ) 897 898 n_z = x.shape[2] 899 # The slices are preprocessed as images, so that images and volumes are resized in the same way. 900 image, input_shape = self.preprocess(fold_z(x)) 901 input_shape = (n_z, *input_shape) 902 _, levels = self._encode_image(image) 903 if levels is None or len(levels) != 3: 904 raise ValueError( 905 "The encoder must return a tuple with the list of features at stride 4, 8 and 16 as second element." 906 ) 907 return {"features": list(levels), "image": image, "n_z": n_z}, input_shape 908 909 def decode( 910 self, features, input_shape: Tuple[int, ...], original_shape: Tuple[int, ...] 911 ) -> Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]: 912 """Run the decoder on the encoder features. 913 914 Args: 915 features: The dictionary returned by `encode`. 916 input_shape: The spatial shape (Z, Y, X) after preprocessing, returned by `encode`. 917 original_shape: The spatial shape of the original input, (Z, Y, X) or (Y, X). 918 919 Returns: 920 The output, resized to `original_shape`. It has no z axis if `original_shape` is (Y, X). 921 During deep-supervision training, return `(prediction, auxiliary_outputs)` at the same spatial size. 922 """ 923 is_2d = len(original_shape) == 2 924 n_z = features["n_z"] 925 _, height, width = input_shape 926 output_size = tuple(original_shape[-2:]) 927 928 def _postprocess(x): 929 x = x[..., :height, :width] 930 if self.final_activation is not None: 931 x = self.final_activation(x) if is_2d else fold_z(self.final_activation(unfold_z(x, n_z))) 932 if tuple(x.shape[-2:]) != output_size: 933 x = F.interpolate(x, output_size, mode="bilinear", align_corners=False) 934 return x if is_2d else unfold_z(x, n_z) 935 936 levels, image = _crop_padding(features["features"], features["image"], height, width) 937 outputs = self.decoder(levels, image, n_z) 938 if isinstance(outputs, tuple): 939 prediction, auxiliary_logits = outputs 940 return _postprocess(prediction), [_postprocess(aux) for aux in auxiliary_logits] 941 return _postprocess(outputs)
42def fold_z(x: torch.Tensor) -> torch.Tensor: 43 """Fold z into the batch: (B, C, Z, H, W) to (B * Z, C, H, W). 44 45 Args: 46 x: The input tensor. 47 48 Returns: 49 The folded tensor. 50 """ 51 b, c, z, h, w = x.shape 52 return x.transpose(1, 2).reshape(b * z, c, h, w)
Fold z into the batch: (B, C, Z, H, W) to (B * Z, C, H, W).
Arguments:
- x: The input tensor.
Returns:
The folded tensor.
55def unfold_z(x: torch.Tensor, n_z: int) -> torch.Tensor: 56 """Unfold z from the batch: (B * Z, C, H, W) to (B, C, Z, H, W). 57 58 Args: 59 x: The folded tensor. 60 n_z: The number of slices Z. 61 62 Returns: 63 The unfolded tensor. 64 """ 65 bz, c, h, w = x.shape 66 return x.reshape(bz // n_z, n_z, c, h, w).transpose(1, 2)
Unfold z from the batch: (B * Z, C, H, W) to (B, C, Z, H, W).
Arguments:
- x: The folded tensor.
- n_z: The number of slices Z.
Returns:
The unfolded tensor.
118class ZResidual(nn.Module): 119 """A residual branch along z: x + pointwise(GELU(depthwise_z(x))). 120 121 The pointwise convolution is zero-initialized, so the branch starts as the identity. 122 It is skipped for a single slice, so 2D inputs never see it. 123 124 Args: 125 channels: The number of channels. 126 kernel_size: The kernel size along z. It must be odd. 127 """ 128 def __init__(self, channels: int, kernel_size: int = 3): 129 super().__init__() 130 self.depthwise = nn.Conv3d( 131 channels, channels, kernel_size=(kernel_size, 1, 1), padding=(kernel_size // 2, 0, 0), groups=channels, 132 ) 133 self.act = nn.GELU() 134 self.pointwise = nn.Conv3d(channels, channels, kernel_size=1) 135 nn.init.zeros_(self.pointwise.weight) 136 nn.init.zeros_(self.pointwise.bias) 137 138 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 139 if n_z == 1: 140 return x 141 volume = unfold_z(x, n_z) 142 return x + fold_z(self.pointwise(self.act(self.depthwise(volume))))
A residual branch along z: x + pointwise(GELU(depthwise_z(x))).
The pointwise convolution is zero-initialized, so the branch starts as the identity. It is skipped for a single slice, so 2D inputs never see it.
Arguments:
- channels: The number of channels.
- kernel_size: The kernel size along z. It must be odd.
128 def __init__(self, channels: int, kernel_size: int = 3): 129 super().__init__() 130 self.depthwise = nn.Conv3d( 131 channels, channels, kernel_size=(kernel_size, 1, 1), padding=(kernel_size // 2, 0, 0), groups=channels, 132 ) 133 self.act = nn.GELU() 134 self.pointwise = nn.Conv3d(channels, channels, kernel_size=1) 135 nn.init.zeros_(self.pointwise.weight) 136 nn.init.zeros_(self.pointwise.bias)
Initialize internal Module state, shared by both nn.Module and ScriptModule.
138 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 139 if n_z == 1: 140 return x 141 volume = unfold_z(x, n_z) 142 return x + fold_z(self.pointwise(self.act(self.depthwise(volume))))
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
145class ZAttention(nn.Module): 146 """Residual self-attention along z at every xy position, with a learned relative position bias. 147 148 The output projection is zero-initialized, so the block starts as the identity. 149 It is skipped for a single slice. 150 151 Args: 152 channels: The number of channels. 153 n_heads: The number of attention heads. By default, it uses one head per 64 channels. 154 max_distance: The largest z distance with its own position bias. Larger distances share the last one. 155 """ 156 def __init__(self, channels: int, n_heads: Optional[int] = None, max_distance: int = 16): 157 super().__init__() 158 self.n_heads = n_heads or max(1, channels // 64) 159 if channels % self.n_heads != 0: 160 raise ValueError(f"{channels} channels cannot be split into {self.n_heads} heads.") 161 self.norm = nn.LayerNorm(channels) 162 self.qkv = nn.Linear(channels, 3 * channels) 163 self.proj = nn.Linear(channels, channels) 164 nn.init.zeros_(self.proj.weight) 165 nn.init.zeros_(self.proj.bias) 166 self.max_distance = max_distance 167 self.position_bias = nn.Parameter(torch.zeros(self.n_heads, 2 * max_distance + 1)) 168 169 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 170 if n_z == 1: 171 return x 172 bz, c, h, w = x.shape 173 b = bz // n_z 174 tokens = x.reshape(b, n_z, c, h, w).permute(0, 3, 4, 1, 2).reshape(b * h * w, n_z, c) 175 qkv = self.qkv(self.norm(tokens)).reshape(-1, n_z, 3, self.n_heads, c // self.n_heads) 176 q, k, v = qkv.permute(2, 0, 3, 1, 4) 177 index = torch.arange(n_z, device=x.device) 178 distance = (index[None] - index[:, None]).clamp(-self.max_distance, self.max_distance) + self.max_distance 179 bias = self.position_bias[:, distance].to(q.dtype)[None] 180 out = F.scaled_dot_product_attention(q, k, v, attn_mask=bias) 181 out = self.proj(out.transpose(1, 2).reshape(-1, n_z, c)) 182 out = out.reshape(b, h, w, n_z, c).permute(0, 3, 4, 1, 2).reshape(bz, c, h, w) 183 return x + out
Residual self-attention along z at every xy position, with a learned relative position bias.
The output projection is zero-initialized, so the block starts as the identity. It is skipped for a single slice.
Arguments:
- channels: The number of channels.
- n_heads: The number of attention heads. By default, it uses one head per 64 channels.
- max_distance: The largest z distance with its own position bias. Larger distances share the last one.
156 def __init__(self, channels: int, n_heads: Optional[int] = None, max_distance: int = 16): 157 super().__init__() 158 self.n_heads = n_heads or max(1, channels // 64) 159 if channels % self.n_heads != 0: 160 raise ValueError(f"{channels} channels cannot be split into {self.n_heads} heads.") 161 self.norm = nn.LayerNorm(channels) 162 self.qkv = nn.Linear(channels, 3 * channels) 163 self.proj = nn.Linear(channels, channels) 164 nn.init.zeros_(self.proj.weight) 165 nn.init.zeros_(self.proj.bias) 166 self.max_distance = max_distance 167 self.position_bias = nn.Parameter(torch.zeros(self.n_heads, 2 * max_distance + 1))
Initialize internal Module state, shared by both nn.Module and ScriptModule.
169 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 170 if n_z == 1: 171 return x 172 bz, c, h, w = x.shape 173 b = bz // n_z 174 tokens = x.reshape(b, n_z, c, h, w).permute(0, 3, 4, 1, 2).reshape(b * h * w, n_z, c) 175 qkv = self.qkv(self.norm(tokens)).reshape(-1, n_z, 3, self.n_heads, c // self.n_heads) 176 q, k, v = qkv.permute(2, 0, 3, 1, 4) 177 index = torch.arange(n_z, device=x.device) 178 distance = (index[None] - index[:, None]).clamp(-self.max_distance, self.max_distance) + self.max_distance 179 bias = self.position_bias[:, distance].to(q.dtype)[None] 180 out = F.scaled_dot_product_attention(q, k, v, attn_mask=bias) 181 out = self.proj(out.transpose(1, 2).reshape(-1, n_z, c)) 182 out = out.reshape(b, h, w, n_z, c).permute(0, 3, 4, 1, 2).reshape(bz, c, h, w) 183 return x + out
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
186class HybridBlock(nn.Module): 187 """A residual 2D block with per-slice GroupNorm and an optional zero-initialized z branch. 188 189 Args: 190 in_channels: The number of input channels. 191 out_channels: The number of output channels. 192 with_z: Whether to add the z branch. 193 """ 194 def __init__(self, in_channels: int, out_channels: int, with_z: bool = True): 195 super().__init__() 196 self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1, bias=False) 197 self.norm1 = _group_norm(out_channels) 198 self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False) 199 self.norm2 = _group_norm(out_channels) 200 self.shortcut = nn.Identity() if in_channels == out_channels else nn.Conv2d(in_channels, out_channels, 1) 201 self.act = nn.GELU() 202 self.z_branch = ZResidual(out_channels) if with_z else None 203 204 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 205 y = self.act(self.norm1(self.conv1(x))) 206 y = self.norm2(self.conv2(y)) 207 y = self.act(y + self.shortcut(x)) 208 if self.z_branch is not None: 209 y = self.z_branch(y, n_z) 210 return y
A residual 2D block with per-slice GroupNorm and an optional zero-initialized z branch.
Arguments:
- in_channels: The number of input channels.
- out_channels: The number of output channels.
- with_z: Whether to add the z branch.
194 def __init__(self, in_channels: int, out_channels: int, with_z: bool = True): 195 super().__init__() 196 self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1, bias=False) 197 self.norm1 = _group_norm(out_channels) 198 self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False) 199 self.norm2 = _group_norm(out_channels) 200 self.shortcut = nn.Identity() if in_channels == out_channels else nn.Conv2d(in_channels, out_channels, 1) 201 self.act = nn.GELU() 202 self.z_branch = ZResidual(out_channels) if with_z else None
Initialize internal Module state, shared by both nn.Module and ScriptModule.
204 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 205 y = self.act(self.norm1(self.conv1(x))) 206 y = self.norm2(self.conv2(y)) 207 y = self.act(y + self.shortcut(x)) 208 if self.z_branch is not None: 209 y = self.z_branch(y, n_z) 210 return y
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
213class NeXtBlock(nn.Module): 214 """A ConvNeXt block in xy (7x7 depthwise, per-slice norm, inverted bottleneck), then an optional z module. 215 216 Args: 217 channels: The number of channels. 218 z_mode: The z module: 'attention' (`ZAttention`), 'conv' (`ZResidual`) or None. 219 """ 220 def __init__(self, channels: int, z_mode: Optional[str] = None): 221 super().__init__() 222 self.depthwise = nn.Conv2d(channels, channels, 7, padding=3, groups=channels) 223 self.norm = nn.GroupNorm(1, channels) 224 self.mlp = nn.Sequential( 225 nn.Conv2d(channels, 4 * channels, 1), nn.GELU(), nn.Conv2d(4 * channels, channels, 1), 226 ) 227 if z_mode == "attention": 228 self.z_module = ZAttention(channels) 229 elif z_mode == "conv": 230 self.z_module = ZResidual(channels) 231 elif z_mode is None: 232 self.z_module = None 233 else: 234 raise ValueError(f"Invalid z_mode {z_mode}") 235 236 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 237 x = x + self.mlp(self.norm(self.depthwise(x))) 238 return x if self.z_module is None else self.z_module(x, n_z)
A ConvNeXt block in xy (7x7 depthwise, per-slice norm, inverted bottleneck), then an optional z module.
Arguments:
- channels: The number of channels.
- z_mode: The z module: 'attention' (
ZAttention), 'conv' (ZResidual) or None.
220 def __init__(self, channels: int, z_mode: Optional[str] = None): 221 super().__init__() 222 self.depthwise = nn.Conv2d(channels, channels, 7, padding=3, groups=channels) 223 self.norm = nn.GroupNorm(1, channels) 224 self.mlp = nn.Sequential( 225 nn.Conv2d(channels, 4 * channels, 1), nn.GELU(), nn.Conv2d(4 * channels, channels, 1), 226 ) 227 if z_mode == "attention": 228 self.z_module = ZAttention(channels) 229 elif z_mode == "conv": 230 self.z_module = ZResidual(channels) 231 elif z_mode is None: 232 self.z_module = None 233 else: 234 raise ValueError(f"Invalid z_mode {z_mode}")
Initialize internal Module state, shared by both nn.Module and ScriptModule.
236 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 237 x = x + self.mlp(self.norm(self.depthwise(x))) 238 return x if self.z_module is None else self.z_module(x, n_z)
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
246class HybridDecoder(nn.Module): 247 """Base class of the hybrid decoders. 248 249 It holds the projections of the stride-4 and stride-8 encoder features and the image stem, which computes 250 the skips at stride 1 (`stem1`) and stride 2 (`stem2`). A decoder implements 251 `forward(features, image, n_z)`, with all tensors folded: 252 - features: The encoder features at stride 4, 8 and 16, each of shape (B * Z, C_l, H_l, W_l). 253 - image: The preprocessed image of shape (B * Z, 3, H, W). 254 - n_z: The number of slices Z. 255 It returns logits of shape (B * Z, out_channels, H, W). During deep-supervision training it returns 256 `(logits, auxiliary_logits)`, with the auxiliary predictions in a list. 257 258 Args: 259 out_channels: The number of output channels. 260 stem_widths: The widths of the image stem at strides 1 and 2. 261 in_channels: The channels of the encoder features at stride 4, 8 and 16. 262 skip_projections: The output channels of the 1x1 projections of the stride-4 and stride-8 features. 263 The defaults correspond to `conv_s0` and `conv_s1` of the SAM2 mask decoder. 264 norm: The function that creates the normalization layer of the image stem for a number of channels. 265 activation: The activation of the image stem. 266 skip_activation: The activation applied after the skip projections. Decoders whose next layer on the 267 skips is another 1x1 convolution use it, so that the two convolutions do not collapse into one 268 linear map. 269 """ 270 def __init__( 271 self, 272 out_channels: int, 273 stem_widths: Sequence[int] = (16, 32), 274 in_channels: Sequence[int] = (256, 256, 256), 275 skip_projections: Sequence[int] = (32, 64), 276 norm: Callable[[int], nn.Module] = _group_norm, 277 activation: Callable[[], nn.Module] = nn.GELU, 278 skip_activation: Optional[Callable[[], nn.Module]] = None, 279 ): 280 super().__init__() 281 if len(in_channels) != 3: 282 raise ValueError(f"Expected the channels of three feature levels, got {in_channels}.") 283 self.out_channels = out_channels 284 self.in_channels = tuple(in_channels) 285 st1, st2 = stem_widths 286 self.stem1 = nn.Sequential(nn.Conv2d(3, st1, 3, padding=1, bias=False), norm(st1), activation()) 287 self.stem2 = nn.Sequential(nn.Conv2d(st1, st2, 3, stride=2, padding=1, bias=False), norm(st2), activation()) 288 self.skip_channels = tuple(skip_projections) 289 self.proj_s4 = nn.Conv2d(self.in_channels[0], self.skip_channels[0], 1) 290 self.proj_s8 = nn.Conv2d(self.in_channels[1], self.skip_channels[1], 1) 291 self.skip_act = None if skip_activation is None else skip_activation() 292 293 def _project(self, features: Sequence[torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 294 s4, s8, s16 = features 295 s4, s8 = self.proj_s4(s4), self.proj_s8(s8) 296 if self.skip_act is not None: 297 s4, s8 = self.skip_act(s4), self.skip_act(s8) 298 return s4, s8, s16
Base class of the hybrid decoders.
It holds the projections of the stride-4 and stride-8 encoder features and the image stem, which computes
the skips at stride 1 (stem1) and stride 2 (stem2). A decoder implements
forward(features, image, n_z), with all tensors folded:
- features: The encoder features at stride 4, 8 and 16, each of shape (B * Z, C_l, H_l, W_l).
- image: The preprocessed image of shape (B * Z, 3, H, W).
- n_z: The number of slices Z.
It returns logits of shape (B * Z, out_channels, H, W). During deep-supervision training it returns
(logits, auxiliary_logits), with the auxiliary predictions in a list.
Arguments:
- out_channels: The number of output channels.
- stem_widths: The widths of the image stem at strides 1 and 2.
- in_channels: The channels of the encoder features at stride 4, 8 and 16.
- skip_projections: The output channels of the 1x1 projections of the stride-4 and stride-8 features.
The defaults correspond to
conv_s0andconv_s1of the SAM2 mask decoder. - norm: The function that creates the normalization layer of the image stem for a number of channels.
- activation: The activation of the image stem.
- skip_activation: The activation applied after the skip projections. Decoders whose next layer on the skips is another 1x1 convolution use it, so that the two convolutions do not collapse into one linear map.
270 def __init__( 271 self, 272 out_channels: int, 273 stem_widths: Sequence[int] = (16, 32), 274 in_channels: Sequence[int] = (256, 256, 256), 275 skip_projections: Sequence[int] = (32, 64), 276 norm: Callable[[int], nn.Module] = _group_norm, 277 activation: Callable[[], nn.Module] = nn.GELU, 278 skip_activation: Optional[Callable[[], nn.Module]] = None, 279 ): 280 super().__init__() 281 if len(in_channels) != 3: 282 raise ValueError(f"Expected the channels of three feature levels, got {in_channels}.") 283 self.out_channels = out_channels 284 self.in_channels = tuple(in_channels) 285 st1, st2 = stem_widths 286 self.stem1 = nn.Sequential(nn.Conv2d(3, st1, 3, padding=1, bias=False), norm(st1), activation()) 287 self.stem2 = nn.Sequential(nn.Conv2d(st1, st2, 3, stride=2, padding=1, bias=False), norm(st2), activation()) 288 self.skip_channels = tuple(skip_projections) 289 self.proj_s4 = nn.Conv2d(self.in_channels[0], self.skip_channels[0], 1) 290 self.proj_s8 = nn.Conv2d(self.in_channels[1], self.skip_channels[1], 1) 291 self.skip_act = None if skip_activation is None else skip_activation()
Initialize internal Module state, shared by both nn.Module and ScriptModule.
301class HieraUDecoder(HybridDecoder): 302 """A plain skip U-decoder on the encoder features at stride 4, 8 and 16 and an image stem. 303 304 All spatial operations are 2D on the slices folded into the batch. The z branches of the blocks at 305 strides 16 to 2 carry the 3D context. The full-resolution block is 2D only. 306 307 Args: 308 out_channels: The number of output channels. 309 widths: The decoder widths at strides 16, 8, 4, 2 and 1. 310 stem_widths: The widths of the image stem at strides 1 and 2. 311 in_channels: The channels of the encoder features at stride 4, 8 and 16. 312 skip_projections: The output channels of the 1x1 projections of the stride-4 and stride-8 features. 313 """ 314 def __init__( 315 self, 316 out_channels: int = 5, 317 widths: Sequence[int] = (192, 128, 64, 32, 16), 318 stem_widths: Sequence[int] = (16, 32), 319 in_channels: Sequence[int] = (256, 256, 256), 320 skip_projections: Sequence[int] = (32, 64), 321 ): 322 super().__init__(out_channels, stem_widths, in_channels, skip_projections) 323 w16, w8, w4, w2, w1 = widths 324 st1, st2 = stem_widths 325 c4, c8 = self.skip_channels 326 self.block16 = HybridBlock(self.in_channels[2], w16) 327 self.block8 = HybridBlock(w16 + c8, w8) 328 self.block4 = HybridBlock(w8 + c4, w4) 329 self.block2 = HybridBlock(w4 + st2, w2) 330 self.block1 = HybridBlock(w2 + st1, w1, with_z=False) 331 self.out_conv = nn.Conv2d(w1, out_channels, 1) 332 333 def forward(self, features: Sequence[torch.Tensor], image: torch.Tensor, n_z: int) -> torch.Tensor: 334 """Apply the decoder, see `HybridDecoder`.""" 335 s4, s8, s16 = self._project(features) 336 stem1 = self.stem1(image) 337 stem2 = self.stem2(stem1) 338 x = self.block16(s16, n_z) 339 x = self.block8(_resize_cat(x, s8), n_z) 340 x = self.block4(_resize_cat(x, s4), n_z) 341 x = self.block2(_resize_cat(x, stem2), n_z) 342 x = self.block1(_resize_cat(x, stem1), n_z) 343 return self.out_conv(x)
A plain skip U-decoder on the encoder features at stride 4, 8 and 16 and an image stem.
All spatial operations are 2D on the slices folded into the batch. The z branches of the blocks at strides 16 to 2 carry the 3D context. The full-resolution block is 2D only.
Arguments:
- out_channels: The number of output channels.
- widths: The decoder widths at strides 16, 8, 4, 2 and 1.
- stem_widths: The widths of the image stem at strides 1 and 2.
- in_channels: The channels of the encoder features at stride 4, 8 and 16.
- skip_projections: The output channels of the 1x1 projections of the stride-4 and stride-8 features.
314 def __init__( 315 self, 316 out_channels: int = 5, 317 widths: Sequence[int] = (192, 128, 64, 32, 16), 318 stem_widths: Sequence[int] = (16, 32), 319 in_channels: Sequence[int] = (256, 256, 256), 320 skip_projections: Sequence[int] = (32, 64), 321 ): 322 super().__init__(out_channels, stem_widths, in_channels, skip_projections) 323 w16, w8, w4, w2, w1 = widths 324 st1, st2 = stem_widths 325 c4, c8 = self.skip_channels 326 self.block16 = HybridBlock(self.in_channels[2], w16) 327 self.block8 = HybridBlock(w16 + c8, w8) 328 self.block4 = HybridBlock(w8 + c4, w4) 329 self.block2 = HybridBlock(w4 + st2, w2) 330 self.block1 = HybridBlock(w2 + st1, w1, with_z=False) 331 self.out_conv = nn.Conv2d(w1, out_channels, 1)
Initialize internal Module state, shared by both nn.Module and ScriptModule.
333 def forward(self, features: Sequence[torch.Tensor], image: torch.Tensor, n_z: int) -> torch.Tensor: 334 """Apply the decoder, see `HybridDecoder`.""" 335 s4, s8, s16 = self._project(features) 336 stem1 = self.stem1(image) 337 stem2 = self.stem2(stem1) 338 x = self.block16(s16, n_z) 339 x = self.block8(_resize_cat(x, s8), n_z) 340 x = self.block4(_resize_cat(x, s4), n_z) 341 x = self.block2(_resize_cat(x, stem2), n_z) 342 x = self.block1(_resize_cat(x, stem1), n_z) 343 return self.out_conv(x)
Apply the decoder, see HybridDecoder.
Inherited Members
346class C3F2Decoder(HybridDecoder): 347 """A coarse-3D / fine-2D fusion head on the encoder features at stride 4, 8 and 16 and an image stem. 348 349 Stride 16: two ConvNeXt blocks, each followed by attention along z. All long-range z reasoning happens here. 350 Stride 8 and 4: additive top-down fusion with the lateral features and ConvNeXt blocks with z convolutions 351 (the last block at stride 4 is 2D). Finer: two transposed convolutions to full resolution, each fused with the 352 image stem, in 2D only. 353 354 Args: 355 out_channels: The number of output channels. 356 widths: The widths at strides 16, 8 and 4. 357 head_width: The width of the stride-2 head. The stride-1 head uses the stride-1 stem width. 358 stem_widths: The widths of the image stem at strides 1 and 2. 359 in_channels: The channels of the encoder features at stride 4, 8 and 16. 360 skip_projections: The output channels of the 1x1 projections of the stride-4 and stride-8 features. 361 They are followed by a GELU, since the lateral convolutions are also 1x1. 362 """ 363 def __init__( 364 self, 365 out_channels: int = 5, 366 widths: Sequence[int] = (256, 128, 64), 367 head_width: int = 32, 368 stem_widths: Sequence[int] = (16, 32), 369 in_channels: Sequence[int] = (256, 256, 256), 370 skip_projections: Sequence[int] = (32, 64), 371 ): 372 super().__init__(out_channels, stem_widths, in_channels, skip_projections, skip_activation=nn.GELU) 373 w16, w8, w4 = widths 374 st1, st2 = stem_widths 375 c4, c8 = self.skip_channels 376 self.lateral16 = nn.Conv2d(self.in_channels[2], w16, 1) 377 self.blocks16 = nn.ModuleList([NeXtBlock(w16, "attention"), NeXtBlock(w16, "attention")]) 378 self.lateral8 = nn.Conv2d(c8, w8, 1) 379 self.reduce8 = nn.Conv2d(w16, w8, 1) 380 self.blocks8 = nn.ModuleList([NeXtBlock(w8, "conv"), NeXtBlock(w8, "conv")]) 381 self.lateral4 = nn.Conv2d(c4, w4, 1) 382 self.reduce4 = nn.Conv2d(w8, w4, 1) 383 self.blocks4 = nn.ModuleList([NeXtBlock(w4, "conv"), NeXtBlock(w4, None)]) 384 self.up2 = nn.Sequential(nn.ConvTranspose2d(w4, head_width, 2, stride=2), _group_norm(head_width), nn.GELU()) 385 self.fuse2 = nn.Sequential( 386 nn.Conv2d(head_width + st2, head_width, 3, padding=1, bias=False), _group_norm(head_width), nn.GELU(), 387 ) 388 self.up1 = nn.Sequential(nn.ConvTranspose2d(head_width, st1, 2, stride=2), _group_norm(st1), nn.GELU()) 389 self.fuse1 = nn.Sequential( 390 nn.Conv2d(2 * st1, st1, 3, padding=1, bias=False), _group_norm(st1), nn.GELU(), 391 ) 392 self.out_conv = nn.Conv2d(st1, out_channels, 1) 393 394 @staticmethod 395 def _run(blocks, x, n_z): 396 for block in blocks: 397 x = block(x, n_z) 398 return x 399 400 def forward(self, features: Sequence[torch.Tensor], image: torch.Tensor, n_z: int) -> torch.Tensor: 401 """Apply the decoder, see `HybridDecoder`.""" 402 s4, s8, s16 = self._project(features) 403 stem1 = self.stem1(image) 404 stem2 = self.stem2(stem1) 405 x = self._run(self.blocks16, self.lateral16(s16), n_z) 406 lateral = self.lateral8(s8) 407 x = self._run(self.blocks8, _resize_to(self.reduce8(x), lateral) + lateral, n_z) 408 lateral = self.lateral4(s4) 409 x = self._run(self.blocks4, _resize_to(self.reduce4(x), lateral) + lateral, n_z) 410 x = self.fuse2(_resize_cat(self.up2(x), stem2)) 411 x = self.fuse1(_resize_cat(self.up1(x), stem1)) 412 return self.out_conv(x)
A coarse-3D / fine-2D fusion head on the encoder features at stride 4, 8 and 16 and an image stem.
Stride 16: two ConvNeXt blocks, each followed by attention along z. All long-range z reasoning happens here. Stride 8 and 4: additive top-down fusion with the lateral features and ConvNeXt blocks with z convolutions (the last block at stride 4 is 2D). Finer: two transposed convolutions to full resolution, each fused with the image stem, in 2D only.
Arguments:
- out_channels: The number of output channels.
- widths: The widths at strides 16, 8 and 4.
- head_width: The width of the stride-2 head. The stride-1 head uses the stride-1 stem width.
- stem_widths: The widths of the image stem at strides 1 and 2.
- in_channels: The channels of the encoder features at stride 4, 8 and 16.
- skip_projections: The output channels of the 1x1 projections of the stride-4 and stride-8 features. They are followed by a GELU, since the lateral convolutions are also 1x1.
363 def __init__( 364 self, 365 out_channels: int = 5, 366 widths: Sequence[int] = (256, 128, 64), 367 head_width: int = 32, 368 stem_widths: Sequence[int] = (16, 32), 369 in_channels: Sequence[int] = (256, 256, 256), 370 skip_projections: Sequence[int] = (32, 64), 371 ): 372 super().__init__(out_channels, stem_widths, in_channels, skip_projections, skip_activation=nn.GELU) 373 w16, w8, w4 = widths 374 st1, st2 = stem_widths 375 c4, c8 = self.skip_channels 376 self.lateral16 = nn.Conv2d(self.in_channels[2], w16, 1) 377 self.blocks16 = nn.ModuleList([NeXtBlock(w16, "attention"), NeXtBlock(w16, "attention")]) 378 self.lateral8 = nn.Conv2d(c8, w8, 1) 379 self.reduce8 = nn.Conv2d(w16, w8, 1) 380 self.blocks8 = nn.ModuleList([NeXtBlock(w8, "conv"), NeXtBlock(w8, "conv")]) 381 self.lateral4 = nn.Conv2d(c4, w4, 1) 382 self.reduce4 = nn.Conv2d(w8, w4, 1) 383 self.blocks4 = nn.ModuleList([NeXtBlock(w4, "conv"), NeXtBlock(w4, None)]) 384 self.up2 = nn.Sequential(nn.ConvTranspose2d(w4, head_width, 2, stride=2), _group_norm(head_width), nn.GELU()) 385 self.fuse2 = nn.Sequential( 386 nn.Conv2d(head_width + st2, head_width, 3, padding=1, bias=False), _group_norm(head_width), nn.GELU(), 387 ) 388 self.up1 = nn.Sequential(nn.ConvTranspose2d(head_width, st1, 2, stride=2), _group_norm(st1), nn.GELU()) 389 self.fuse1 = nn.Sequential( 390 nn.Conv2d(2 * st1, st1, 3, padding=1, bias=False), _group_norm(st1), nn.GELU(), 391 ) 392 self.out_conv = nn.Conv2d(st1, out_channels, 1)
Initialize internal Module state, shared by both nn.Module and ScriptModule.
400 def forward(self, features: Sequence[torch.Tensor], image: torch.Tensor, n_z: int) -> torch.Tensor: 401 """Apply the decoder, see `HybridDecoder`.""" 402 s4, s8, s16 = self._project(features) 403 stem1 = self.stem1(image) 404 stem2 = self.stem2(stem1) 405 x = self._run(self.blocks16, self.lateral16(s16), n_z) 406 lateral = self.lateral8(s8) 407 x = self._run(self.blocks8, _resize_to(self.reduce8(x), lateral) + lateral, n_z) 408 lateral = self.lateral4(s4) 409 x = self._run(self.blocks4, _resize_to(self.reduce4(x), lateral) + lateral, n_z) 410 x = self.fuse2(_resize_cat(self.up2(x), stem2)) 411 x = self.fuse1(_resize_cat(self.up1(x), stem1)) 412 return self.out_conv(x)
Apply the decoder, see HybridDecoder.
Inherited Members
428class ECA(nn.Module): 429 """Efficient channel attention of MedCAGD with a learned temperature, pooled per slice. 430 431 MedCAGD averages three convolutions of the global mean (its pooling scales 1, 2, 4 all reduce to the global 432 mean). This is linear and thus equal to one convolution, which is used here. 433 434 Args: 435 channels: The number of channels. 436 is_encoder: Whether to use the kernel size rule of MedCAGD for encoder (skip) or for decoder features. 437 """ 438 def __init__(self, channels: int, is_encoder: bool = True): 439 super().__init__() 440 gamma, b = (2.0, 1.0) if is_encoder else (2.4, 0.8) 441 k = int(abs(math.log2(channels) / gamma + b)) 442 k = k + 1 if k % 2 == 0 else k 443 self.conv = nn.Conv1d(1, 1, kernel_size=k, padding=(k - 1) // 2, bias=False) 444 self.log_tau = nn.Parameter(torch.zeros(())) 445 self.tau_min, self.tau_max = 0.5, 2.0 446 447 def forward(self, x: torch.Tensor) -> torch.Tensor: 448 logits = self.conv(x.mean(dim=(2, 3))[:, None])[:, 0] # (N, C), N = slices 449 tau = self.log_tau.exp().clamp(self.tau_min, self.tau_max) 450 attention = torch.sigmoid(logits / tau) 451 attention = attention / (attention.mean(dim=1, keepdim=True) + 1e-6) 452 return x * attention[..., None, None]
Efficient channel attention of MedCAGD with a learned temperature, pooled per slice.
MedCAGD averages three convolutions of the global mean (its pooling scales 1, 2, 4 all reduce to the global mean). This is linear and thus equal to one convolution, which is used here.
Arguments:
- channels: The number of channels.
- is_encoder: Whether to use the kernel size rule of MedCAGD for encoder (skip) or for decoder features.
438 def __init__(self, channels: int, is_encoder: bool = True): 439 super().__init__() 440 gamma, b = (2.0, 1.0) if is_encoder else (2.4, 0.8) 441 k = int(abs(math.log2(channels) / gamma + b)) 442 k = k + 1 if k % 2 == 0 else k 443 self.conv = nn.Conv1d(1, 1, kernel_size=k, padding=(k - 1) // 2, bias=False) 444 self.log_tau = nn.Parameter(torch.zeros(())) 445 self.tau_min, self.tau_max = 0.5, 2.0
Initialize internal Module state, shared by both nn.Module and ScriptModule.
447 def forward(self, x: torch.Tensor) -> torch.Tensor: 448 logits = self.conv(x.mean(dim=(2, 3))[:, None])[:, 0] # (N, C), N = slices 449 tau = self.log_tau.exp().clamp(self.tau_min, self.tau_max) 450 attention = torch.sigmoid(logits / tau) 451 attention = attention / (attention.mean(dim=1, keepdim=True) + 1e-6) 452 return x * attention[..., None, None]
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
455class GlobalContext(nn.Module): 456 """The residual global-context attention of MedCAGD (a GCNet block), pooled per slice. 457 458 Args: 459 channels: The number of channels. 460 reduction: The channel reduction of the transform. 461 """ 462 def __init__(self, channels: int, reduction: int = 16): 463 super().__init__() 464 inter = max(4, channels // reduction) # MedCAGD: max(1, ...); same for the default widths (>= 64) 465 self.mask = nn.Conv2d(channels, 1, kernel_size=1) 466 self.transform = nn.Sequential( 467 nn.Conv2d(channels, inter, kernel_size=1, bias=False), 468 nn.GroupNorm(1, inter), # = LayerNorm([inter, 1, 1]) of MedCAGD 469 nn.ReLU(inplace=True), 470 nn.Conv2d(inter, channels, kernel_size=1, bias=False), 471 ) 472 473 def forward(self, x: torch.Tensor) -> torch.Tensor: 474 n, c, h, w = x.shape 475 weights = torch.softmax(self.mask(x).reshape(n, 1, h * w), dim=-1) 476 context = torch.bmm(x.reshape(n, c, h * w), weights.transpose(1, 2)).reshape(n, c, 1, 1) 477 return x + self.transform(context)
The residual global-context attention of MedCAGD (a GCNet block), pooled per slice.
Arguments:
- channels: The number of channels.
- reduction: The channel reduction of the transform.
462 def __init__(self, channels: int, reduction: int = 16): 463 super().__init__() 464 inter = max(4, channels // reduction) # MedCAGD: max(1, ...); same for the default widths (>= 64) 465 self.mask = nn.Conv2d(channels, 1, kernel_size=1) 466 self.transform = nn.Sequential( 467 nn.Conv2d(channels, inter, kernel_size=1, bias=False), 468 nn.GroupNorm(1, inter), # = LayerNorm([inter, 1, 1]) of MedCAGD 469 nn.ReLU(inplace=True), 470 nn.Conv2d(inter, channels, kernel_size=1, bias=False), 471 )
Initialize internal Module state, shared by both nn.Module and ScriptModule.
473 def forward(self, x: torch.Tensor) -> torch.Tensor: 474 n, c, h, w = x.shape 475 weights = torch.softmax(self.mask(x).reshape(n, 1, h * w), dim=-1) 476 context = torch.bmm(x.reshape(n, c, h * w), weights.transpose(1, 2)).reshape(n, c, 1, 1) 477 return x + self.transform(context)
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
480class SCAGate(nn.Module): 481 """The attention gate of MedCAGD (SCA-Gate): gates the skip features with guidance from the decoder. 482 483 Changed against MedCAGD: 484 - For large inputs: the spatial competition is a softmax over the H * W positions of a slice, with 485 values of about 1 / (H * W), which is numerically zero for inputs of size 1024. It is rescaled by H * W 486 (mean one) and clamped at `max_spatial`. 487 - The global channel modulation G is an SE-style bottleneck (conv, SiLU, conv, sigmoid). MedCAGD applies 488 the sigmoid directly after conv and SiLU, which limits the factor 1 + G to [1.43, 2). 489 490 Args: 491 guide_channels: The channels of the upsampled decoder features. 492 skip_channels: The channels of the skip features. 493 inter_channels: The latent width. 494 max_spatial: The maximum of the rescaled spatial attention. 495 """ 496 def __init__(self, guide_channels: int, skip_channels: int, inter_channels: int, max_spatial: float = 4.0): 497 super().__init__() 498 self.eca_skip = ECA(skip_channels, is_encoder=True) 499 self.eca_guide = ECA(guide_channels, is_encoder=False) 500 501 def branch(channels): 502 return nn.Sequential( 503 nn.Conv2d(channels, inter_channels, 3, padding=1, bias=False), _cagd_group_norm(inter_channels), 504 nn.SiLU(), 505 nn.Conv2d(inter_channels, inter_channels, 3, padding=2, dilation=2, groups=inter_channels, 506 bias=False), 507 _cagd_group_norm(inter_channels), nn.SiLU(), 508 ) 509 self.theta, self.phi = branch(guide_channels), branch(skip_channels) 510 hidden_channels = max(8, inter_channels // 4) 511 self.global_fc = nn.Sequential( 512 nn.Conv2d(guide_channels + skip_channels, hidden_channels, 1), nn.SiLU(), 513 nn.Conv2d(hidden_channels, inter_channels, 1), nn.Sigmoid(), 514 ) 515 self.dw3 = nn.Conv2d(inter_channels, inter_channels, 3, padding=1, groups=inter_channels, bias=False) 516 self.dw5 = nn.Conv2d(inter_channels, inter_channels, 5, padding=2, groups=inter_channels, bias=False) 517 self.score = nn.Conv2d(inter_channels, 1, 1, bias=False) 518 self.log_tau = nn.Parameter(torch.tensor(0.7).log()) 519 self.tau_min, self.tau_max = 0.3, 2.0 520 self.max_spatial = max_spatial 521 self.att = nn.Sequential(nn.GroupNorm(1, inter_channels), nn.Conv2d(inter_channels, 1, 1), nn.Hardsigmoid()) 522 523 def forward(self, guide: torch.Tensor, skip: torch.Tensor) -> torch.Tensor: 524 skip = self.eca_skip(skip) 525 guide = self.eca_guide(guide) 526 fused = F.normalize(self.theta(guide) * self.phi(skip), p=2, dim=1) 527 fused = fused + self.global_fc(torch.cat([guide, skip], dim=1).mean(dim=(2, 3), keepdim=True)) * fused 528 score = self.score(self.dw3(fused) + self.dw5(fused)) 529 n, _, h, w = score.shape 530 tau = self.log_tau.exp().clamp(self.tau_min, self.tau_max) 531 spatial = torch.softmax(score.reshape(n, h * w) / tau, dim=-1).reshape(n, 1, h, w) * (h * w) 532 fused = fused * (1.0 + spatial.clamp(max=self.max_spatial)) 533 return skip * self.att(fused + 1e-5)
The attention gate of MedCAGD (SCA-Gate): gates the skip features with guidance from the decoder.
Changed against MedCAGD:
- For large inputs: the spatial competition is a softmax over the H * W positions of a slice, with
values of about 1 / (H * W), which is numerically zero for inputs of size 1024. It is rescaled by H * W
(mean one) and clamped at
max_spatial. - The global channel modulation G is an SE-style bottleneck (conv, SiLU, conv, sigmoid). MedCAGD applies the sigmoid directly after conv and SiLU, which limits the factor 1 + G to [1.43, 2).
Arguments:
- guide_channels: The channels of the upsampled decoder features.
- skip_channels: The channels of the skip features.
- inter_channels: The latent width.
- max_spatial: The maximum of the rescaled spatial attention.
496 def __init__(self, guide_channels: int, skip_channels: int, inter_channels: int, max_spatial: float = 4.0): 497 super().__init__() 498 self.eca_skip = ECA(skip_channels, is_encoder=True) 499 self.eca_guide = ECA(guide_channels, is_encoder=False) 500 501 def branch(channels): 502 return nn.Sequential( 503 nn.Conv2d(channels, inter_channels, 3, padding=1, bias=False), _cagd_group_norm(inter_channels), 504 nn.SiLU(), 505 nn.Conv2d(inter_channels, inter_channels, 3, padding=2, dilation=2, groups=inter_channels, 506 bias=False), 507 _cagd_group_norm(inter_channels), nn.SiLU(), 508 ) 509 self.theta, self.phi = branch(guide_channels), branch(skip_channels) 510 hidden_channels = max(8, inter_channels // 4) 511 self.global_fc = nn.Sequential( 512 nn.Conv2d(guide_channels + skip_channels, hidden_channels, 1), nn.SiLU(), 513 nn.Conv2d(hidden_channels, inter_channels, 1), nn.Sigmoid(), 514 ) 515 self.dw3 = nn.Conv2d(inter_channels, inter_channels, 3, padding=1, groups=inter_channels, bias=False) 516 self.dw5 = nn.Conv2d(inter_channels, inter_channels, 5, padding=2, groups=inter_channels, bias=False) 517 self.score = nn.Conv2d(inter_channels, 1, 1, bias=False) 518 self.log_tau = nn.Parameter(torch.tensor(0.7).log()) 519 self.tau_min, self.tau_max = 0.3, 2.0 520 self.max_spatial = max_spatial 521 self.att = nn.Sequential(nn.GroupNorm(1, inter_channels), nn.Conv2d(inter_channels, 1, 1), nn.Hardsigmoid())
Initialize internal Module state, shared by both nn.Module and ScriptModule.
523 def forward(self, guide: torch.Tensor, skip: torch.Tensor) -> torch.Tensor: 524 skip = self.eca_skip(skip) 525 guide = self.eca_guide(guide) 526 fused = F.normalize(self.theta(guide) * self.phi(skip), p=2, dim=1) 527 fused = fused + self.global_fc(torch.cat([guide, skip], dim=1).mean(dim=(2, 3), keepdim=True)) * fused 528 score = self.score(self.dw3(fused) + self.dw5(fused)) 529 n, _, h, w = score.shape 530 tau = self.log_tau.exp().clamp(self.tau_min, self.tau_max) 531 spatial = torch.softmax(score.reshape(n, h * w) / tau, dim=-1).reshape(n, 1, h, w) * (h * w) 532 fused = fused * (1.0 + spatial.clamp(max=self.max_spatial)) 533 return skip * self.att(fused + 1e-5)
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
536class DWBlock(nn.Module): 537 """The conv block of MedCAGD (depthwise 3x3 and pointwise, twice), followed by a zero-initialized z branch. 538 539 Args: 540 in_channels: The number of input channels. 541 out_channels: The number of output channels. 542 with_z: Whether to add the z branch. 543 """ 544 def __init__(self, in_channels: int, out_channels: int, with_z: bool = True): 545 super().__init__() 546 self.block = nn.Sequential( 547 nn.Conv2d(in_channels, in_channels, 3, padding=1, groups=in_channels, bias=False), 548 _cagd_group_norm(in_channels), nn.SiLU(), 549 nn.Conv2d(in_channels, out_channels, 1, bias=False), _cagd_group_norm(out_channels), nn.SiLU(), 550 nn.Conv2d(out_channels, out_channels, 3, padding=1, groups=out_channels, bias=False), 551 _cagd_group_norm(out_channels), nn.SiLU(), 552 nn.Conv2d(out_channels, out_channels, 1, bias=False), _cagd_group_norm(out_channels), nn.SiLU(), 553 ) 554 self.z_branch = ZResidual(out_channels) if with_z else None 555 556 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 557 x = self.block(x) 558 return x if self.z_branch is None else self.z_branch(x, n_z)
The conv block of MedCAGD (depthwise 3x3 and pointwise, twice), followed by a zero-initialized z branch.
Arguments:
- in_channels: The number of input channels.
- out_channels: The number of output channels.
- with_z: Whether to add the z branch.
544 def __init__(self, in_channels: int, out_channels: int, with_z: bool = True): 545 super().__init__() 546 self.block = nn.Sequential( 547 nn.Conv2d(in_channels, in_channels, 3, padding=1, groups=in_channels, bias=False), 548 _cagd_group_norm(in_channels), nn.SiLU(), 549 nn.Conv2d(in_channels, out_channels, 1, bias=False), _cagd_group_norm(out_channels), nn.SiLU(), 550 nn.Conv2d(out_channels, out_channels, 3, padding=1, groups=out_channels, bias=False), 551 _cagd_group_norm(out_channels), nn.SiLU(), 552 nn.Conv2d(out_channels, out_channels, 1, bias=False), _cagd_group_norm(out_channels), nn.SiLU(), 553 ) 554 self.z_branch = ZResidual(out_channels) if with_z else None
Initialize internal Module state, shared by both nn.Module and ScriptModule.
556 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 557 x = self.block(x) 558 return x if self.z_branch is None else self.z_branch(x, n_z)
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
561class RefinementBlock(nn.Module): 562 """The refinement block of MedCAGD: conv block, optional depthwise spatial conv and channel recalibration. 563 564 Args: 565 channels: The number of channels. 566 spatial_focus: Whether to add the depthwise spatial convolution. 567 with_z: Whether to add the z branch to the conv block. 568 """ 569 def __init__(self, channels: int, spatial_focus: bool, with_z: bool = True): 570 super().__init__() 571 self.conv = DWBlock(channels, channels, with_z=with_z) 572 self.spatial = nn.Conv2d(channels, channels, 3, padding=1, groups=channels) if spatial_focus else None 573 self.eca = ECA(channels) 574 575 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 576 x = self.conv(x, n_z) 577 if self.spatial is not None: 578 x = self.spatial(x) 579 return self.eca(x)
The refinement block of MedCAGD: conv block, optional depthwise spatial conv and channel recalibration.
Arguments:
- channels: The number of channels.
- spatial_focus: Whether to add the depthwise spatial convolution.
- with_z: Whether to add the z branch to the conv block.
569 def __init__(self, channels: int, spatial_focus: bool, with_z: bool = True): 570 super().__init__() 571 self.conv = DWBlock(channels, channels, with_z=with_z) 572 self.spatial = nn.Conv2d(channels, channels, 3, padding=1, groups=channels) if spatial_focus else None 573 self.eca = ECA(channels)
Initialize internal Module state, shared by both nn.Module and ScriptModule.
575 def forward(self, x: torch.Tensor, n_z: int) -> torch.Tensor: 576 x = self.conv(x, n_z) 577 if self.spatial is not None: 578 x = self.spatial(x) 579 return self.eca(x)
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
582class CAGDStage(nn.Module): 583 """The decoder block of MedCAGD: transposed-conv upsampling, gated skip fusion and the conv block. 584 585 The skips are gated only if they have more than 64 channels, as in MedCAGD. 586 587 Args: 588 in_channels: The number of input channels. 589 skip_channels: The channels of the skip features. 590 out_channels: The number of output channels. 591 with_z: Whether to add the z branch to the conv block. 592 """ 593 def __init__(self, in_channels: int, skip_channels: int, out_channels: int, with_z: bool = True): 594 super().__init__() 595 self.up = nn.ConvTranspose2d(in_channels, out_channels, kernel_size=2, stride=2) 596 self.gate = SCAGate(out_channels, skip_channels, max(1, skip_channels // 2)) if skip_channels > 64 else None 597 self.conv = DWBlock(out_channels + skip_channels, out_channels, with_z=with_z) 598 599 def forward(self, x: torch.Tensor, skip: torch.Tensor, n_z: int) -> torch.Tensor: 600 x = _resize_to(self.up(x), skip) 601 if self.gate is not None: 602 skip = self.gate(x, skip) 603 return self.conv(torch.cat([x, skip], dim=1), n_z)
The decoder block of MedCAGD: transposed-conv upsampling, gated skip fusion and the conv block.
The skips are gated only if they have more than 64 channels, as in MedCAGD.
Arguments:
- in_channels: The number of input channels.
- skip_channels: The channels of the skip features.
- out_channels: The number of output channels.
- with_z: Whether to add the z branch to the conv block.
593 def __init__(self, in_channels: int, skip_channels: int, out_channels: int, with_z: bool = True): 594 super().__init__() 595 self.up = nn.ConvTranspose2d(in_channels, out_channels, kernel_size=2, stride=2) 596 self.gate = SCAGate(out_channels, skip_channels, max(1, skip_channels // 2)) if skip_channels > 64 else None 597 self.conv = DWBlock(out_channels + skip_channels, out_channels, with_z=with_z)
Initialize internal Module state, shared by both nn.Module and ScriptModule.
599 def forward(self, x: torch.Tensor, skip: torch.Tensor, n_z: int) -> torch.Tensor: 600 x = _resize_to(self.up(x), skip) 601 if self.gate is not None: 602 skip = self.gate(x, skip) 603 return self.conv(torch.cat([x, skip], dim=1), n_z)
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
606class ContextAggregator(nn.Module): 607 """The context aggregator of MedCAGD: all pyramid levels projected, resized and averaged, plus global context. 608 609 Args: 610 in_channels: The channels of the pyramid levels. 611 out_channels: The number of output channels. 612 """ 613 def __init__(self, in_channels: Sequence[int], out_channels: int): 614 super().__init__() 615 self.proj = nn.ModuleList([nn.Conv2d(c, out_channels, kernel_size=1) for c in in_channels]) 616 self.global_context = GlobalContext(out_channels) 617 618 def forward(self, features: Sequence[torch.Tensor], reference: torch.Tensor) -> torch.Tensor: 619 fused = sum(_resize_to(proj(f), reference) for f, proj in zip(features, self.proj)) 620 return self.global_context(fused / len(features))
The context aggregator of MedCAGD: all pyramid levels projected, resized and averaged, plus global context.
Arguments:
- in_channels: The channels of the pyramid levels.
- out_channels: The number of output channels.
613 def __init__(self, in_channels: Sequence[int], out_channels: int): 614 super().__init__() 615 self.proj = nn.ModuleList([nn.Conv2d(c, out_channels, kernel_size=1) for c in in_channels]) 616 self.global_context = GlobalContext(out_channels)
Initialize internal Module state, shared by both nn.Module and ScriptModule.
618 def forward(self, features: Sequence[torch.Tensor], reference: torch.Tensor) -> torch.Tensor: 619 fused = sum(_resize_to(proj(f), reference) for f, proj in zip(features, self.proj)) 620 return self.global_context(fused / len(features))
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
623class CAGD3DDecoder(HybridDecoder): 624 """The decoder of MedCAGD on the encoder features at stride 4, 8 and 16, adapted to the hybrid 2D/3D recipe. 625 626 MedCAGD: Wazir et al., arXiv 2607.00409, https://github.com/saadwazir/MedCAGD. 627 628 Pyramid: 1x1 projections of the features at stride 4, 8 and 16. The stride-32 level is a strided 3x3 convolution 629 of the stride-16 features. The bottleneck (conv, attention along z, global context) and the stages at strides 630 16, 8 and 4 (gated fusion, context aggregator, refinement) follow MedCAGD. All global pooling is per slice 631 and the blocks have zero-initialized z branches. 632 633 Changed against MedCAGD: the last stage runs at stride 2 with an image-stem skip instead of at full resolution 634 (the full-resolution stage of MedCAGD costs 1.7x the FLOPs). It is followed by a transposed convolution to 635 full resolution, fused with the stride-1 stem. 636 637 Deep supervision (optional): 1x1 heads on the stages at strides 16, 8 and 4 predict all output channels. 638 During training the auxiliary logits are upsampled to the image size and returned with the main logits. 639 The loss should use all three auxiliary outputs, ordered from deepest to shallowest. 640 With `deep_supervision=True`, the model returns the tuple `(prediction, auxiliary_outputs)` in training mode. 641 Train it with `HybridUNETRDeepSupervisionTrainer` from `torch_em.trainer.hybrid_unetr_trainer`. 642 `DefaultTrainer`, or other code that calls the model in training mode (e.g. the self-training trainers), 643 receives the tuple instead of a tensor and fails. 644 645 Args: 646 out_channels: The number of output channels. 647 widths: The pyramid widths at strides 4, 8, 16 and 32. 648 stem_widths: The widths of the image stem at strides 1 and 2. 649 deep_supervision: Whether to build the deep supervision heads. 650 in_channels: The channels of the encoder features at stride 4, 8 and 16. 651 skip_projections: The output channels of the 1x1 projections of the stride-4 and stride-8 features. 652 They are followed by a SiLU, since the pyramid convolutions are also 1x1. The defaults match the 653 pyramid widths (256 -> 64 -> SiLU -> 64 and 256 -> 128 -> SiLU -> 128), so they are wider than 654 `conv_s0` and `conv_s1` of SAM2 and `HybridUNETR.init_skip_projections` does not apply to them. 655 """ 656 def __init__( 657 self, 658 out_channels: int = 5, 659 widths: Sequence[int] = (64, 128, 320, 512), 660 stem_widths: Sequence[int] = (16, 32), 661 deep_supervision: bool = False, 662 in_channels: Sequence[int] = (256, 256, 256), 663 skip_projections: Sequence[int] = (64, 128), 664 ): 665 super().__init__( 666 out_channels, stem_widths, in_channels, skip_projections, 667 norm=_cagd_group_norm, activation=nn.SiLU, skip_activation=nn.SiLU, 668 ) 669 w4, w8, w16, w32 = widths 670 st1, st2 = stem_widths 671 c4, c8 = self.skip_channels 672 c16 = self.in_channels[2] 673 self.p4 = nn.Conv2d(c4, w4, 1) 674 self.p8 = nn.Conv2d(c8, w8, 1) 675 self.p16 = nn.Conv2d(c16, w16, 1) 676 self.p32 = nn.Conv2d(c16, w32, 3, stride=2, padding=1) 677 678 self.bottleneck_conv = nn.Sequential(nn.Conv2d(w32, w32, 3, padding=1), _cagd_group_norm(w32), nn.SiLU()) 679 self.bottleneck_z = ZAttention(w32) 680 self.bottleneck_context = GlobalContext(w32) 681 682 levels = (w4, w8, w16, w32) 683 self.stage16, self.context16, self.ref16 = ( 684 CAGDStage(w32, w16, w16), ContextAggregator(levels, w16), RefinementBlock(w16, spatial_focus=False), 685 ) 686 self.stage8, self.context8, self.ref8 = ( 687 CAGDStage(w16, w8, w8), ContextAggregator(levels, w8), RefinementBlock(w8, spatial_focus=True), 688 ) 689 self.stage4, self.context4, self.ref4 = ( 690 CAGDStage(w8, w4, w4), ContextAggregator(levels, w4), RefinementBlock(w4, spatial_focus=True), 691 ) 692 self.stage2 = CAGDStage(w4, st2, st2) 693 self.ref2 = RefinementBlock(st2, spatial_focus=True) 694 695 self.head_up = nn.Sequential( 696 nn.ConvTranspose2d(st2, st1, kernel_size=2, stride=2), _cagd_group_norm(st1), nn.SiLU(), 697 ) 698 self.head_fuse = nn.Sequential( 699 nn.Conv2d(2 * st1, st1, 3, padding=1, bias=False), _cagd_group_norm(st1), nn.SiLU(), 700 ) 701 self.out_conv = nn.Conv2d(st1, out_channels, 1) 702 self.aux_heads = nn.ModuleList( 703 [nn.Conv2d(c, out_channels, 1) for c in (w16, w8, w4)] 704 ) if deep_supervision else None 705 706 def forward( 707 self, features: Sequence[torch.Tensor], image: torch.Tensor, n_z: int 708 ) -> Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]: 709 """Apply the decoder, see `HybridDecoder`.""" 710 s4, s8, s16 = self._project(features) 711 stem1 = self.stem1(image) 712 stem2 = self.stem2(stem1) 713 p4, p8, p16 = self.p4(s4), self.p8(s8), self.p16(s16) 714 b = self.bottleneck_conv(self.p32(s16)) 715 b = self.bottleneck_context(self.bottleneck_z(b, n_z)) 716 levels = [p4, p8, p16, b] 717 718 d16 = self.stage16(b, p16, n_z) 719 d16 = self.ref16(d16 + self.context16(levels, d16), n_z) 720 d8 = self.stage8(d16, p8, n_z) 721 d8 = self.ref8(d8 + self.context8(levels, d8), n_z) 722 d4 = self.stage4(d8, p4, n_z) 723 d4 = self.ref4(d4 + self.context4(levels, d4), n_z) 724 d2 = self.ref2(self.stage2(d4, stem2, n_z), n_z) 725 726 out = self.out_conv(self.head_fuse(_resize_cat(self.head_up(d2), stem1))) 727 728 if self.training and self.aux_heads is not None: 729 auxiliary_logits = [ 730 _resize_to(head(d), image) for head, d in zip(self.aux_heads, (d16, d8, d4)) 731 ] 732 return out, auxiliary_logits 733 return out
The decoder of MedCAGD on the encoder features at stride 4, 8 and 16, adapted to the hybrid 2D/3D recipe.
MedCAGD: Wazir et al., arXiv 2607.00409, https://github.com/saadwazir/MedCAGD.
Pyramid: 1x1 projections of the features at stride 4, 8 and 16. The stride-32 level is a strided 3x3 convolution of the stride-16 features. The bottleneck (conv, attention along z, global context) and the stages at strides 16, 8 and 4 (gated fusion, context aggregator, refinement) follow MedCAGD. All global pooling is per slice and the blocks have zero-initialized z branches.
Changed against MedCAGD: the last stage runs at stride 2 with an image-stem skip instead of at full resolution (the full-resolution stage of MedCAGD costs 1.7x the FLOPs). It is followed by a transposed convolution to full resolution, fused with the stride-1 stem.
Deep supervision (optional): 1x1 heads on the stages at strides 16, 8 and 4 predict all output channels.
During training the auxiliary logits are upsampled to the image size and returned with the main logits.
The loss should use all three auxiliary outputs, ordered from deepest to shallowest.
With deep_supervision=True, the model returns the tuple (prediction, auxiliary_outputs) in training mode.
Train it with HybridUNETRDeepSupervisionTrainer from torch_em.trainer.hybrid_unetr_trainer.
DefaultTrainer, or other code that calls the model in training mode (e.g. the self-training trainers),
receives the tuple instead of a tensor and fails.
Arguments:
- out_channels: The number of output channels.
- widths: The pyramid widths at strides 4, 8, 16 and 32.
- stem_widths: The widths of the image stem at strides 1 and 2.
- deep_supervision: Whether to build the deep supervision heads.
- in_channels: The channels of the encoder features at stride 4, 8 and 16.
- skip_projections: The output channels of the 1x1 projections of the stride-4 and stride-8 features.
They are followed by a SiLU, since the pyramid convolutions are also 1x1. The defaults match the
pyramid widths (256 -> 64 -> SiLU -> 64 and 256 -> 128 -> SiLU -> 128), so they are wider than
conv_s0andconv_s1of SAM2 andHybridUNETR.init_skip_projectionsdoes not apply to them.
656 def __init__( 657 self, 658 out_channels: int = 5, 659 widths: Sequence[int] = (64, 128, 320, 512), 660 stem_widths: Sequence[int] = (16, 32), 661 deep_supervision: bool = False, 662 in_channels: Sequence[int] = (256, 256, 256), 663 skip_projections: Sequence[int] = (64, 128), 664 ): 665 super().__init__( 666 out_channels, stem_widths, in_channels, skip_projections, 667 norm=_cagd_group_norm, activation=nn.SiLU, skip_activation=nn.SiLU, 668 ) 669 w4, w8, w16, w32 = widths 670 st1, st2 = stem_widths 671 c4, c8 = self.skip_channels 672 c16 = self.in_channels[2] 673 self.p4 = nn.Conv2d(c4, w4, 1) 674 self.p8 = nn.Conv2d(c8, w8, 1) 675 self.p16 = nn.Conv2d(c16, w16, 1) 676 self.p32 = nn.Conv2d(c16, w32, 3, stride=2, padding=1) 677 678 self.bottleneck_conv = nn.Sequential(nn.Conv2d(w32, w32, 3, padding=1), _cagd_group_norm(w32), nn.SiLU()) 679 self.bottleneck_z = ZAttention(w32) 680 self.bottleneck_context = GlobalContext(w32) 681 682 levels = (w4, w8, w16, w32) 683 self.stage16, self.context16, self.ref16 = ( 684 CAGDStage(w32, w16, w16), ContextAggregator(levels, w16), RefinementBlock(w16, spatial_focus=False), 685 ) 686 self.stage8, self.context8, self.ref8 = ( 687 CAGDStage(w16, w8, w8), ContextAggregator(levels, w8), RefinementBlock(w8, spatial_focus=True), 688 ) 689 self.stage4, self.context4, self.ref4 = ( 690 CAGDStage(w8, w4, w4), ContextAggregator(levels, w4), RefinementBlock(w4, spatial_focus=True), 691 ) 692 self.stage2 = CAGDStage(w4, st2, st2) 693 self.ref2 = RefinementBlock(st2, spatial_focus=True) 694 695 self.head_up = nn.Sequential( 696 nn.ConvTranspose2d(st2, st1, kernel_size=2, stride=2), _cagd_group_norm(st1), nn.SiLU(), 697 ) 698 self.head_fuse = nn.Sequential( 699 nn.Conv2d(2 * st1, st1, 3, padding=1, bias=False), _cagd_group_norm(st1), nn.SiLU(), 700 ) 701 self.out_conv = nn.Conv2d(st1, out_channels, 1) 702 self.aux_heads = nn.ModuleList( 703 [nn.Conv2d(c, out_channels, 1) for c in (w16, w8, w4)] 704 ) if deep_supervision else None
Initialize internal Module state, shared by both nn.Module and ScriptModule.
706 def forward( 707 self, features: Sequence[torch.Tensor], image: torch.Tensor, n_z: int 708 ) -> Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]: 709 """Apply the decoder, see `HybridDecoder`.""" 710 s4, s8, s16 = self._project(features) 711 stem1 = self.stem1(image) 712 stem2 = self.stem2(stem1) 713 p4, p8, p16 = self.p4(s4), self.p8(s8), self.p16(s16) 714 b = self.bottleneck_conv(self.p32(s16)) 715 b = self.bottleneck_context(self.bottleneck_z(b, n_z)) 716 levels = [p4, p8, p16, b] 717 718 d16 = self.stage16(b, p16, n_z) 719 d16 = self.ref16(d16 + self.context16(levels, d16), n_z) 720 d8 = self.stage8(d16, p8, n_z) 721 d8 = self.ref8(d8 + self.context8(levels, d8), n_z) 722 d4 = self.stage4(d8, p4, n_z) 723 d4 = self.ref4(d4 + self.context4(levels, d4), n_z) 724 d2 = self.ref2(self.stage2(d4, stem2, n_z), n_z) 725 726 out = self.out_conv(self.head_fuse(_resize_cat(self.head_up(d2), stem1))) 727 728 if self.training and self.aux_heads is not None: 729 auxiliary_logits = [ 730 _resize_to(head(d), image) for head, d in zip(self.aux_heads, (d16, d8, d4)) 731 ] 732 return out, auxiliary_logits 733 return out
Apply the decoder, see HybridDecoder.
Inherited Members
The hybrid decoders by name.
745class HybridUNETR(UNETRBase): 746 """A UNETR for 2D and 3D inputs with a multi-scale encoder and a hybrid 2D/3D decoder. 747 748 The model applies the encoder to each slice and decodes all slices together. The same weights process 749 images of shape (B, C, Y, X) and volumes of shape (B, C, Z, Y, X). An image is processed like a volume 750 with a single slice. 751 752 Each slice is resized (if `resize_input`) and zero-padded to the input size of the encoder. Before decoding, 753 the padding is cropped from the image and the encoder features, rounded up to the stride-32 grid, so that the 754 per-slice normalization and global pooling in the decoder see (almost) no padding. The encoder itself still 755 sees the padding. 756 757 The forward pass returns the prediction. During training with deep supervision (see `CAGD3DDecoder`), it 758 returns `(prediction, auxiliary_outputs)` instead. The training loss should use the tensors from this pair, 759 including under DistributedDataParallel. 760 761 The state of the model has the two prefixes 'encoder.' and 'decoder.'. 762 763 Args: 764 img_size: The input size of the image encoder, used to build it if it is given by name. Preprocessing 765 resizes and pads the slices to `encoder.img_size`, so for an encoder module this argument does not 766 change the preprocessing. 767 backbone: The name of the vision transformer implementation. The model was designed for 'sam2'. 768 encoder: The image encoder. Can either be a name, such as 'hvit_t', or a torch module. 769 A module must have the attribute `img_size` and return a tuple, with the list of features 770 at stride 4, 8 and 16 as second element, like `torch_em.model.vit.ViT_Sam2`. 771 decoder: The decoder. Can either be a name from `HYBRID_DECODERS` ('hiera_u', 'c3f2' or 'cagd_3d') or 772 a torch module that implements the interface of `HybridDecoder` and has the attribute `in_channels`. 773 decoder_kwargs: The keyword arguments for the decoder, if it is given by name. 774 out_channels: The number of output channels. It is ignored if the decoder is a torch module. 775 use_sam_stats: Whether to normalize the input data with the statistics of the pretrained SAM2 model. 776 use_mae_stats: Whether to normalize the input data with the statistics of the pretrained MAE model. 777 use_dino_stats: Whether to normalize the input data with the statistics of the pretrained DINO models. 778 use_imagenet_stats: Whether to normalize with standard ImageNet statistics. 779 resize_input: Whether to resize each slice so that its longest side matches `encoder.img_size`. 780 If False, slices must not be larger than `encoder.img_size` and are only padded. 781 encoder_checkpoint: Checkpoint for initializing the image encoder. 782 Can either be a filepath or an already loaded checkpoint. It does not initialize the projections 783 of the stride-4 and stride-8 features in the decoder, see `init_skip_projections`. 784 final_activation: The activation to apply before resizing the output. It receives a 4D tensor for an image 785 and a 5D tensor for a volume. 786 perform_range_checks: Whether to validate the input value range before normalization on each forward pass. 787 kwargs: Keyword arguments for `torch_em.model.vit.get_vision_transformer`, if the encoder is given by name. 788 """ 789 def __init__( 790 self, 791 img_size: int = 1024, 792 backbone: str = "sam2", 793 encoder: Union[nn.Module, str] = "hvit_t", 794 decoder: Union[nn.Module, str] = "hiera_u", 795 decoder_kwargs: Optional[dict] = None, 796 out_channels: int = 1, 797 use_sam_stats: bool = False, 798 use_mae_stats: bool = False, 799 use_dino_stats: bool = False, 800 use_imagenet_stats: bool = False, 801 resize_input: bool = True, 802 encoder_checkpoint: Optional[Union[str, PathLike, Mapping]] = None, 803 final_activation: Optional[Union[str, nn.Module]] = None, 804 perform_range_checks: bool = True, 805 **kwargs 806 ) -> None: 807 if isinstance(decoder, str): 808 if decoder not in HYBRID_DECODERS: 809 raise ValueError(f"Invalid decoder '{decoder}', choose from {list(HYBRID_DECODERS)}.") 810 decoder_module = HYBRID_DECODERS[decoder](out_channels=out_channels, **(decoder_kwargs or {})) 811 elif isinstance(decoder, nn.Module): 812 if decoder_kwargs: 813 raise ValueError("The decoder_kwargs are only supported for a decoder that is given by name.") 814 decoder_module = decoder 815 else: 816 raise TypeError("The decoder must be a decoder name or a torch module.") 817 818 super().__init__( 819 img_size=img_size, 820 backbone=backbone, 821 encoder=encoder, 822 out_channels=out_channels, 823 use_sam_stats=use_sam_stats, 824 use_mae_stats=use_mae_stats, 825 use_dino_stats=use_dino_stats, 826 use_imagenet_stats=use_imagenet_stats, 827 resize_input=resize_input, 828 encoder_checkpoint=encoder_checkpoint, 829 final_activation=final_activation, 830 # Read the stride-16 width from the decoder to support custom encoders. 831 embed_dim=decoder_module.in_channels[-1], 832 perform_range_checks=perform_range_checks, 833 **kwargs, 834 ) 835 self.init_kwargs = { 836 "img_size": img_size, "backbone": backbone, "encoder": encoder, "decoder": decoder, 837 "decoder_kwargs": deepcopy(decoder_kwargs), "out_channels": out_channels, "use_sam_stats": use_sam_stats, 838 "use_mae_stats": use_mae_stats, "use_dino_stats": use_dino_stats, 839 "use_imagenet_stats": use_imagenet_stats, "resize_input": resize_input, 840 "final_activation": final_activation, "perform_range_checks": perform_range_checks, **kwargs, 841 } 842 843 self.decoder = decoder_module 844 self.out_channels = getattr(decoder_module, "out_channels", out_channels) 845 846 def init_skip_projections(self, conv_s0: nn.Module, conv_s1: nn.Module) -> None: 847 """Initialize the projections of the stride-4 and stride-8 features in the decoder from other modules. 848 849 This copies the weights, the modules are not shared. For SAM2, pass `sam_mask_decoder.conv_s0` and 850 `sam_mask_decoder.conv_s1` of the SAM2 model. 851 852 Args: 853 conv_s0: The projection of the stride-4 features. 854 conv_s1: The projection of the stride-8 features. 855 """ 856 proj_s4, proj_s8 = getattr(self.decoder, "proj_s4", None), getattr(self.decoder, "proj_s8", None) 857 if proj_s4 is None or proj_s8 is None: 858 raise RuntimeError("The decoder does not have projections for the stride-4 and stride-8 features.") 859 proj_s4.load_state_dict(conv_s0.state_dict()) 860 proj_s8.load_state_dict(conv_s1.state_dict()) 861 862 @property 863 def decoder_config(self) -> dict: 864 """The arguments that rebuild the decoder. They can be serialized to JSON, e.g. to store them in checkpoints. 865 """ 866 decoder = self.init_kwargs["decoder"] 867 if not isinstance(decoder, str): 868 raise RuntimeError("The decoder_config is only available for a decoder that is given by name.") 869 return { 870 "decoder": decoder, "decoder_kwargs": deepcopy(self.init_kwargs["decoder_kwargs"] or {}), 871 "out_channels": self.out_channels, 872 } 873 874 def encode(self, x: torch.Tensor) -> Tuple[Dict[str, Union[List[torch.Tensor], torch.Tensor, int]], Tuple]: 875 """Preprocess the input and run the image encoder on all slices. 876 877 Args: 878 x: The input tensor with shape (B, C, Z, Y, X) or (B, C, Y, X). 879 880 Returns: 881 The features to pass to `decode`: a dictionary with the encoder features at stride 4, 8 and 16 882 ('features'), the preprocessed image ('image'), both with z folded into the batch, and the 883 number of slices ('n_z'). 884 The spatial shape (Z, Y, X) after preprocessing. 885 """ 886 if x.ndim == 4: # An image is processed as a volume with a single slice. 887 x = x[:, :, None] 888 elif x.ndim != 5: 889 raise ValueError(f"Expected 4d or 5d inputs, got {tuple(x.shape)}.") 890 891 height, width = x.shape[-2:] 892 encoder_size = self.encoder.img_size 893 if not self.resize_input and max(height, width) > encoder_size: 894 raise ValueError( 895 f"Input size {(height, width)} exceeds the encoder size {(encoder_size, encoder_size)} " 896 "with resize_input=False." 897 ) 898 899 n_z = x.shape[2] 900 # The slices are preprocessed as images, so that images and volumes are resized in the same way. 901 image, input_shape = self.preprocess(fold_z(x)) 902 input_shape = (n_z, *input_shape) 903 _, levels = self._encode_image(image) 904 if levels is None or len(levels) != 3: 905 raise ValueError( 906 "The encoder must return a tuple with the list of features at stride 4, 8 and 16 as second element." 907 ) 908 return {"features": list(levels), "image": image, "n_z": n_z}, input_shape 909 910 def decode( 911 self, features, input_shape: Tuple[int, ...], original_shape: Tuple[int, ...] 912 ) -> Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]: 913 """Run the decoder on the encoder features. 914 915 Args: 916 features: The dictionary returned by `encode`. 917 input_shape: The spatial shape (Z, Y, X) after preprocessing, returned by `encode`. 918 original_shape: The spatial shape of the original input, (Z, Y, X) or (Y, X). 919 920 Returns: 921 The output, resized to `original_shape`. It has no z axis if `original_shape` is (Y, X). 922 During deep-supervision training, return `(prediction, auxiliary_outputs)` at the same spatial size. 923 """ 924 is_2d = len(original_shape) == 2 925 n_z = features["n_z"] 926 _, height, width = input_shape 927 output_size = tuple(original_shape[-2:]) 928 929 def _postprocess(x): 930 x = x[..., :height, :width] 931 if self.final_activation is not None: 932 x = self.final_activation(x) if is_2d else fold_z(self.final_activation(unfold_z(x, n_z))) 933 if tuple(x.shape[-2:]) != output_size: 934 x = F.interpolate(x, output_size, mode="bilinear", align_corners=False) 935 return x if is_2d else unfold_z(x, n_z) 936 937 levels, image = _crop_padding(features["features"], features["image"], height, width) 938 outputs = self.decoder(levels, image, n_z) 939 if isinstance(outputs, tuple): 940 prediction, auxiliary_logits = outputs 941 return _postprocess(prediction), [_postprocess(aux) for aux in auxiliary_logits] 942 return _postprocess(outputs)
A UNETR for 2D and 3D inputs with a multi-scale encoder and a hybrid 2D/3D decoder.
The model applies the encoder to each slice and decodes all slices together. The same weights process images of shape (B, C, Y, X) and volumes of shape (B, C, Z, Y, X). An image is processed like a volume with a single slice.
Each slice is resized (if resize_input) and zero-padded to the input size of the encoder. Before decoding,
the padding is cropped from the image and the encoder features, rounded up to the stride-32 grid, so that the
per-slice normalization and global pooling in the decoder see (almost) no padding. The encoder itself still
sees the padding.
The forward pass returns the prediction. During training with deep supervision (see CAGD3DDecoder), it
returns (prediction, auxiliary_outputs) instead. The training loss should use the tensors from this pair,
including under DistributedDataParallel.
The state of the model has the two prefixes 'encoder.' and 'decoder.'.
Arguments:
- img_size: The input size of the image encoder, used to build it if it is given by name. Preprocessing
resizes and pads the slices to
encoder.img_size, so for an encoder module this argument does not change the preprocessing. - backbone: The name of the vision transformer implementation. The model was designed for 'sam2'.
- encoder: The image encoder. Can either be a name, such as 'hvit_t', or a torch module.
A module must have the attribute
img_sizeand return a tuple, with the list of features at stride 4, 8 and 16 as second element, liketorch_em.model.vit.ViT_Sam2. - decoder: The decoder. Can either be a name from
HYBRID_DECODERS('hiera_u', 'c3f2' or 'cagd_3d') or a torch module that implements the interface ofHybridDecoderand has the attributein_channels. - decoder_kwargs: The keyword arguments for the decoder, if it is given by name.
- out_channels: The number of output channels. It is ignored if the decoder is a torch module.
- use_sam_stats: Whether to normalize the input data with the statistics of the pretrained SAM2 model.
- use_mae_stats: Whether to normalize the input data with the statistics of the pretrained MAE model.
- use_dino_stats: Whether to normalize the input data with the statistics of the pretrained DINO models.
- use_imagenet_stats: Whether to normalize with standard ImageNet statistics.
- resize_input: Whether to resize each slice so that its longest side matches
encoder.img_size. If False, slices must not be larger thanencoder.img_sizeand are only padded. - encoder_checkpoint: Checkpoint for initializing the image encoder.
Can either be a filepath or an already loaded checkpoint. It does not initialize the projections
of the stride-4 and stride-8 features in the decoder, see
init_skip_projections. - final_activation: The activation to apply before resizing the output. It receives a 4D tensor for an image and a 5D tensor for a volume.
- perform_range_checks: Whether to validate the input value range before normalization on each forward pass.
- kwargs: Keyword arguments for
torch_em.model.vit.get_vision_transformer, if the encoder is given by name.
789 def __init__( 790 self, 791 img_size: int = 1024, 792 backbone: str = "sam2", 793 encoder: Union[nn.Module, str] = "hvit_t", 794 decoder: Union[nn.Module, str] = "hiera_u", 795 decoder_kwargs: Optional[dict] = None, 796 out_channels: int = 1, 797 use_sam_stats: bool = False, 798 use_mae_stats: bool = False, 799 use_dino_stats: bool = False, 800 use_imagenet_stats: bool = False, 801 resize_input: bool = True, 802 encoder_checkpoint: Optional[Union[str, PathLike, Mapping]] = None, 803 final_activation: Optional[Union[str, nn.Module]] = None, 804 perform_range_checks: bool = True, 805 **kwargs 806 ) -> None: 807 if isinstance(decoder, str): 808 if decoder not in HYBRID_DECODERS: 809 raise ValueError(f"Invalid decoder '{decoder}', choose from {list(HYBRID_DECODERS)}.") 810 decoder_module = HYBRID_DECODERS[decoder](out_channels=out_channels, **(decoder_kwargs or {})) 811 elif isinstance(decoder, nn.Module): 812 if decoder_kwargs: 813 raise ValueError("The decoder_kwargs are only supported for a decoder that is given by name.") 814 decoder_module = decoder 815 else: 816 raise TypeError("The decoder must be a decoder name or a torch module.") 817 818 super().__init__( 819 img_size=img_size, 820 backbone=backbone, 821 encoder=encoder, 822 out_channels=out_channels, 823 use_sam_stats=use_sam_stats, 824 use_mae_stats=use_mae_stats, 825 use_dino_stats=use_dino_stats, 826 use_imagenet_stats=use_imagenet_stats, 827 resize_input=resize_input, 828 encoder_checkpoint=encoder_checkpoint, 829 final_activation=final_activation, 830 # Read the stride-16 width from the decoder to support custom encoders. 831 embed_dim=decoder_module.in_channels[-1], 832 perform_range_checks=perform_range_checks, 833 **kwargs, 834 ) 835 self.init_kwargs = { 836 "img_size": img_size, "backbone": backbone, "encoder": encoder, "decoder": decoder, 837 "decoder_kwargs": deepcopy(decoder_kwargs), "out_channels": out_channels, "use_sam_stats": use_sam_stats, 838 "use_mae_stats": use_mae_stats, "use_dino_stats": use_dino_stats, 839 "use_imagenet_stats": use_imagenet_stats, "resize_input": resize_input, 840 "final_activation": final_activation, "perform_range_checks": perform_range_checks, **kwargs, 841 } 842 843 self.decoder = decoder_module 844 self.out_channels = getattr(decoder_module, "out_channels", out_channels)
Initialize internal Module state, shared by both nn.Module and ScriptModule.
846 def init_skip_projections(self, conv_s0: nn.Module, conv_s1: nn.Module) -> None: 847 """Initialize the projections of the stride-4 and stride-8 features in the decoder from other modules. 848 849 This copies the weights, the modules are not shared. For SAM2, pass `sam_mask_decoder.conv_s0` and 850 `sam_mask_decoder.conv_s1` of the SAM2 model. 851 852 Args: 853 conv_s0: The projection of the stride-4 features. 854 conv_s1: The projection of the stride-8 features. 855 """ 856 proj_s4, proj_s8 = getattr(self.decoder, "proj_s4", None), getattr(self.decoder, "proj_s8", None) 857 if proj_s4 is None or proj_s8 is None: 858 raise RuntimeError("The decoder does not have projections for the stride-4 and stride-8 features.") 859 proj_s4.load_state_dict(conv_s0.state_dict()) 860 proj_s8.load_state_dict(conv_s1.state_dict())
Initialize the projections of the stride-4 and stride-8 features in the decoder from other modules.
This copies the weights, the modules are not shared. For SAM2, pass sam_mask_decoder.conv_s0 and
sam_mask_decoder.conv_s1 of the SAM2 model.
Arguments:
- conv_s0: The projection of the stride-4 features.
- conv_s1: The projection of the stride-8 features.
862 @property 863 def decoder_config(self) -> dict: 864 """The arguments that rebuild the decoder. They can be serialized to JSON, e.g. to store them in checkpoints. 865 """ 866 decoder = self.init_kwargs["decoder"] 867 if not isinstance(decoder, str): 868 raise RuntimeError("The decoder_config is only available for a decoder that is given by name.") 869 return { 870 "decoder": decoder, "decoder_kwargs": deepcopy(self.init_kwargs["decoder_kwargs"] or {}), 871 "out_channels": self.out_channels, 872 }
The arguments that rebuild the decoder. They can be serialized to JSON, e.g. to store them in checkpoints.
874 def encode(self, x: torch.Tensor) -> Tuple[Dict[str, Union[List[torch.Tensor], torch.Tensor, int]], Tuple]: 875 """Preprocess the input and run the image encoder on all slices. 876 877 Args: 878 x: The input tensor with shape (B, C, Z, Y, X) or (B, C, Y, X). 879 880 Returns: 881 The features to pass to `decode`: a dictionary with the encoder features at stride 4, 8 and 16 882 ('features'), the preprocessed image ('image'), both with z folded into the batch, and the 883 number of slices ('n_z'). 884 The spatial shape (Z, Y, X) after preprocessing. 885 """ 886 if x.ndim == 4: # An image is processed as a volume with a single slice. 887 x = x[:, :, None] 888 elif x.ndim != 5: 889 raise ValueError(f"Expected 4d or 5d inputs, got {tuple(x.shape)}.") 890 891 height, width = x.shape[-2:] 892 encoder_size = self.encoder.img_size 893 if not self.resize_input and max(height, width) > encoder_size: 894 raise ValueError( 895 f"Input size {(height, width)} exceeds the encoder size {(encoder_size, encoder_size)} " 896 "with resize_input=False." 897 ) 898 899 n_z = x.shape[2] 900 # The slices are preprocessed as images, so that images and volumes are resized in the same way. 901 image, input_shape = self.preprocess(fold_z(x)) 902 input_shape = (n_z, *input_shape) 903 _, levels = self._encode_image(image) 904 if levels is None or len(levels) != 3: 905 raise ValueError( 906 "The encoder must return a tuple with the list of features at stride 4, 8 and 16 as second element." 907 ) 908 return {"features": list(levels), "image": image, "n_z": n_z}, input_shape
Preprocess the input and run the image encoder on all slices.
Arguments:
- x: The input tensor with shape (B, C, Z, Y, X) or (B, C, Y, X).
Returns:
The features to pass to
decode: a dictionary with the encoder features at stride 4, 8 and 16 ('features'), the preprocessed image ('image'), both with z folded into the batch, and the number of slices ('n_z'). The spatial shape (Z, Y, X) after preprocessing.
910 def decode( 911 self, features, input_shape: Tuple[int, ...], original_shape: Tuple[int, ...] 912 ) -> Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]: 913 """Run the decoder on the encoder features. 914 915 Args: 916 features: The dictionary returned by `encode`. 917 input_shape: The spatial shape (Z, Y, X) after preprocessing, returned by `encode`. 918 original_shape: The spatial shape of the original input, (Z, Y, X) or (Y, X). 919 920 Returns: 921 The output, resized to `original_shape`. It has no z axis if `original_shape` is (Y, X). 922 During deep-supervision training, return `(prediction, auxiliary_outputs)` at the same spatial size. 923 """ 924 is_2d = len(original_shape) == 2 925 n_z = features["n_z"] 926 _, height, width = input_shape 927 output_size = tuple(original_shape[-2:]) 928 929 def _postprocess(x): 930 x = x[..., :height, :width] 931 if self.final_activation is not None: 932 x = self.final_activation(x) if is_2d else fold_z(self.final_activation(unfold_z(x, n_z))) 933 if tuple(x.shape[-2:]) != output_size: 934 x = F.interpolate(x, output_size, mode="bilinear", align_corners=False) 935 return x if is_2d else unfold_z(x, n_z) 936 937 levels, image = _crop_padding(features["features"], features["image"], height, width) 938 outputs = self.decoder(levels, image, n_z) 939 if isinstance(outputs, tuple): 940 prediction, auxiliary_logits = outputs 941 return _postprocess(prediction), [_postprocess(aux) for aux in auxiliary_logits] 942 return _postprocess(outputs)
Run the decoder on the encoder features.
Arguments:
- features: The dictionary returned by
encode. - input_shape: The spatial shape (Z, Y, X) after preprocessing, returned by
encode. - original_shape: The spatial shape of the original input, (Z, Y, X) or (Y, X).
Returns:
The output, resized to
original_shape. It has no z axis iforiginal_shapeis (Y, X). During deep-supervision training, return(prediction, auxiliary_outputs)at the same spatial size.