Buckets:
| """The four E2 arms behind one interface (SPEC.md section 7). | |
| model = make_arm("A" | "B" | "C" | "D", widths=...) | |
| logits = model(x, spacing) # x: [1, 1, X, Y, Z] at the scan's native spacing (mm, per axis) | |
| - A, spacing-blind: GeometryUNet + fixed_geometry(spacing) (dilation 1, symmetric pooling). | |
| - B, FiLM: the same fixed geometry; a small MLP maps log-spacing to per-channel scale/shift after every block. It has | |
| exactly the information C has, but may only modulate features, not change geometry: the attribution control. | |
| The last MLP layer is zero-initialised, so B starts identical to A. Parameter overhead is asserted < 1%. | |
| - C, spacing-conditioned: GeometryUNet + geometry(spacing) (the proposal). | |
| - D, resample-to-isotropic: trilinear resample of the input to TARGET spacing, A's network, logits resampled back to | |
| the native grid. Its extra memory/FLOPs on thick slices are a real cost, reported, not hidden. | |
| A, C and D share one parameter set shape; B adds the MLP. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from geometry.spacing_geometry import fixed_geometry, geometry | |
| from models.unet3d import GeometryUNet | |
| class FiLMUNet(GeometryUNet): | |
| def __init__(self, *a, hidden=8, **kw): | |
| super().__init__(*a, **kw) | |
| self.film_ch = list(self.widths) + list(self.widths[:-1])[::-1] # encoder levels, then decoder in run order | |
| self.mlp = nn.Sequential(nn.Linear(3, hidden), nn.SiLU(), nn.Linear(hidden, 2 * sum(self.film_ch))) | |
| nn.init.zeros_(self.mlp[-1].weight); nn.init.zeros_(self.mlp[-1].bias) | |
| def forward(self, x, levels, spacing): | |
| s = torch.log(torch.as_tensor(spacing, dtype=x.dtype, device=x.device)).reshape(1, 3) | |
| gb = self.mlp(s)[0] | |
| film, o = [], 0 | |
| for c in self.film_ch: | |
| film.append((1 + gb[o:o + c], gb[o + c:o + 2 * c])); o += 2 * c | |
| mod = lambda h, k: h * film[k][0].view(1, -1, 1, 1, 1) + film[k][1].view(1, -1, 1, 1, 1) | |
| skips, k = [], 0 | |
| for blk, lv in zip(self.enc, levels): | |
| x = mod(blk(x, lv.dilation), k); k += 1 | |
| skips.append(x) | |
| if any(st > 1 for st 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 = mod(self.dec[i](torch.cat([skips[i], x], 1), levels[i].dilation), k); k += 1 | |
| return self.head(x) | |
| class Arm(nn.Module): | |
| def __init__(self, name, widths=(16, 32, 64, 128), target_spacing=None): | |
| super().__init__() | |
| self.name = name | |
| self.net = FiLMUNet(widths=widths) if name == "B" else GeometryUNet(widths=widths) | |
| self.n_levels = len(widths) | |
| self.target = tuple(target_spacing) if target_spacing is not None else None | |
| assert name != "D" or self.target is not None, "arm D needs target_spacing" | |
| def ladder(self, spacing): | |
| sp = tuple(float(s) for s in spacing) | |
| if self.name == "C": | |
| return geometry(sp, n_levels=self.n_levels) | |
| return fixed_geometry(sp, n_levels=self.n_levels) | |
| def forward(self, x, spacing): | |
| if self.name == "D": | |
| native = x.shape[2:] | |
| size = [max(4, int(round(n * s / t))) for n, s, t in zip(native, spacing, self.target)] | |
| y = F.interpolate(x, size=size, mode="trilinear", align_corners=False) | |
| y = self.net(y, fixed_geometry(self.target, n_levels=self.n_levels)) | |
| return F.interpolate(y, size=native, mode="trilinear", align_corners=False) | |
| if self.name == "B": | |
| return self.net(x, self.ladder(spacing), spacing) | |
| return self.net(x, self.ladder(spacing)) | |
| def make_arm(name, widths=(16, 32, 64, 128), target_spacing=None): | |
| m = Arm(name, widths, target_spacing) | |
| if name == "B": | |
| base = sum(p.numel() for n, p in m.named_parameters() if not n.startswith("net.mlp")) | |
| extra = sum(p.numel() for p in m.net.mlp.parameters()) | |
| assert extra / base < 0.01, f"FiLM MLP is {100 * extra / base:.2f}% of the network (> 1%, SPEC section 7)" | |
| return m | |
| def n_params(m): | |
| return sum(p.numel() for p in m.parameters()) | |
| if __name__ == "__main__": # quick shape / parameter report | |
| torch.manual_seed(0) | |
| for a in "ABCD": | |
| m = make_arm(a, target_spacing=(0.7, 0.7, 1.25)) | |
| for sp, shape in (((0.7, 0.7, 1.25), (92, 92, 52)), ((0.7, 0.7, 3.0), (92, 92, 22))): | |
| y = m(torch.randn(1, 1, *shape), sp) | |
| assert y.shape[2:] == torch.Size(shape), (a, sp, y.shape) | |
| print(a, n_params(m), "params; shapes preserved at thin and thick spacing") | |
Xet Storage Details
- Size:
- 4.82 kB
- Xet hash:
- 9f459475b73abea9230a8c235e9a088fa3ec581f40cd0eb4309eb7b4616fd65a
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.