Chucks90's picture
download
raw
3.08 kB
"""Geometry-parameterised 3D U-Net shared by arms A (spacing-blind) and C (spacing-conditioned).
Weights never depend on geometry. Each forward pass takes a per-scan level ladder (from `geometry()` or
`fixed_geometry()` in geometry/spacing_geometry.py) and applies it functionally:
- every conv is a 3-tap kernel run with the level's per-axis dilation (padding = dilation keeps the shape);
- pooling is a per-axis max-pool with the level's stride (kernel = stride; 1 on held axes);
- the decoder upsamples to the skip's exact shape (trilinear), so no layer shape depends on the stride.
Consequence: arms A and C are parameter-identical (SPEC.md section 7). On a scan where `geometry()` equals
`fixed_geometry()` (isotropic or near-isotropic), arm C computes exactly what arm A computes: the E1 sanity gate.
Arm B (FiLM) and arm D (resample) attach here later; they are not needed for E1.
"""
from __future__ import annotations
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBlock(nn.Module):
"""convs_per_level x [3x3x3 conv (dilation from the ladder) -> InstanceNorm -> LeakyReLU]."""
def __init__(self, cin, cout, n=2):
super().__init__()
self.w = nn.ParameterList()
self.b = nn.ParameterList()
self.norms = nn.ModuleList()
for i in range(n):
conv = nn.Conv3d(cin if i == 0 else cout, cout, 3)
self.w.append(conv.weight); self.b.append(conv.bias)
self.norms.append(nn.InstanceNorm3d(cout, affine=True))
def forward(self, x, dilation):
for w, b, norm in zip(self.w, self.b, self.norms):
x = F.conv3d(x, w, b, padding=tuple(dilation), dilation=tuple(dilation))
x = F.leaky_relu(norm(x), 0.01)
return x
class GeometryUNet(nn.Module):
def __init__(self, in_ch=1, out_ch=1, widths=(16, 32, 64, 128), convs_per_level=2):
super().__init__()
self.widths = widths
self.enc = nn.ModuleList()
c = in_ch
for w in widths:
self.enc.append(ConvBlock(c, w, convs_per_level)); c = w
self.dec = nn.ModuleList(ConvBlock(widths[i] + widths[i + 1], widths[i], convs_per_level)
for i in range(len(widths) - 1))
self.head = nn.Conv3d(widths[0], out_ch, 1)
def forward(self, x, levels):
"""x: [B, C, X, Y, Z]; levels: list[Level] with len == len(widths). One ladder per batch (same spacing)."""
assert len(levels) == len(self.widths), "ladder depth must match encoder depth"
skips = []
for blk, lv in zip(self.enc, levels):
x = blk(x, lv.dilation)
skips.append(x)
if any(s > 1 for s in lv.stride):
x = F.max_pool3d(x, kernel_size=tuple(lv.stride), stride=tuple(lv.stride), ceil_mode=True)
for i in reversed(range(len(self.dec))):
x = F.interpolate(x, size=skips[i].shape[2:], mode="trilinear", align_corners=False)
x = self.dec[i](torch.cat([skips[i], x], 1), levels[i].dilation)
return self.head(x)

Xet Storage Details

Size:
3.08 kB
·
Xet hash:
7dfcaf087996dad2fa6e5b0a5964cfc6bb0e6cf6a164664ad1dd1926e3ee6450

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.