File size: 8,696 Bytes
3799002 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | """Networks.
get_unet : MONAI 3D U-Net for Stage-1 semantic segmentation.
ImplicitNet : Stage-2 core. A 3D CNN encoder turns the ROI into a feature grid;
a coordinate MLP, conditioned on (position, interpolated feature,
per-instance latent code z), predicts TWO signed distances
(tooth outer surface, canal inner surface).
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
def trilinear_sample_feat(feat, p):
"""Hand-written differentiable trilinear sampling on a feature volume.
feat: [B, C, X, Y, Z] (channel-first, axis order x,y,z)
p : [B, N, 3] normalized coords in [-1, 1] in (x, y, z) order
Returns: [B, N, C]. Supports second-order autograd on `p`, which
PyTorch's grid_sample does not (grid_sampler_3d_backward has no derivative).
Out-of-bounds samples are clamped to the border.
"""
B, C, X, Y, Z = feat.shape
sizes = torch.tensor([X, Y, Z], device=p.device, dtype=p.dtype)
# map [-1,1] -> [0, size-1]
px = (p + 1.0) * 0.5 * (sizes - 1) # [B, N, 3]
px = torch.stack([px[..., k].clamp(0, sizes[k] - 1) for k in range(3)], -1)
x0 = px[..., 0].floor(); x1 = (x0 + 1).clamp(max=X - 1)
y0 = px[..., 1].floor(); y1 = (y0 + 1).clamp(max=Y - 1)
z0 = px[..., 2].floor(); z1 = (z0 + 1).clamp(max=Z - 1)
xd = (px[..., 0] - x0).unsqueeze(-1)
yd = (px[..., 1] - y0).unsqueeze(-1)
zd = (px[..., 2] - z0).unsqueeze(-1)
x0i, x1i = x0.long(), x1.long()
y0i, y1i = y0.long(), y1.long()
z0i, z1i = z0.long(), z1.long()
# gather corners: [B, N, C] each
feat_flat = feat.permute(0, 2, 3, 4, 1).contiguous() # [B, X, Y, Z, C]
bidx = torch.arange(B, device=p.device).view(B, 1).expand(-1, p.shape[1])
def g(xi, yi, zi):
return feat_flat[bidx, xi, yi, zi] # [B, N, C]
c00 = g(x0i, y0i, z0i) * (1 - xd) + g(x1i, y0i, z0i) * xd
c01 = g(x0i, y0i, z1i) * (1 - xd) + g(x1i, y0i, z1i) * xd
c10 = g(x0i, y1i, z0i) * (1 - xd) + g(x1i, y1i, z0i) * xd
c11 = g(x0i, y1i, z1i) * (1 - xd) + g(x1i, y1i, z1i) * xd
c0 = c00 * (1 - yd) + c10 * yd
c1 = c01 * (1 - yd) + c11 * yd
return c0 * (1 - zd) + c1 * zd # [B, N, C]
def get_unet(num_classes=3, channels=(16, 32, 64, 128, 256)):
from monai.networks.nets import UNet
return UNet(
spatial_dims=3, in_channels=1, out_channels=num_classes,
channels=channels, strides=(2,) * (len(channels) - 1),
num_res_units=2, norm="instance",
)
class Encoder3D(nn.Module):
"""U-Net-style ROI encoder producing TWO feature grids:
- feat_fine : high-resolution (1/2 of input) -> preserves local canal detail
- feat_coarse: low-resolution (1/8 of input) -> global tooth context
Per-point queries sample BOTH (ConvONet-style local implicit features), so thin
structures keep their detail instead of being averaged into one global vector."""
def __init__(self, ch=(32, 64, 128), feat_dim=64):
super().__init__()
c1, c2, c3 = ch
# encoder (downsampling)
self.e0 = nn.Sequential(nn.Conv3d(1, c1, 3, padding=1), nn.GroupNorm(8, c1), nn.SiLU(),
nn.Conv3d(c1, c1, 3, padding=1), nn.GroupNorm(8, c1), nn.SiLU())
self.d1 = nn.Conv3d(c1, c1, 3, stride=2, padding=1)
self.e1 = nn.Sequential(nn.Conv3d(c1, c2, 3, padding=1), nn.GroupNorm(8, c2), nn.SiLU(),
nn.Conv3d(c2, c2, 3, padding=1), nn.GroupNorm(8, c2), nn.SiLU())
self.d2 = nn.Conv3d(c2, c2, 3, stride=2, padding=1)
self.e2 = nn.Sequential(nn.Conv3d(c2, c3, 3, padding=1), nn.GroupNorm(8, c3), nn.SiLU(),
nn.Conv3d(c3, c3, 3, padding=1), nn.GroupNorm(8, c3), nn.SiLU())
self.d3 = nn.Conv3d(c3, c3, 3, stride=2, padding=1)
self.bott = nn.Sequential(nn.Conv3d(c3, c3, 3, padding=1), nn.GroupNorm(8, c3), nn.SiLU())
# heads: fine grid at 1/2 res (from e0 after one downsample skip), coarse at 1/8
self.head_fine = nn.Conv3d(c1, feat_dim, 1) # at 1/2 input res
self.head_coarse = nn.Conv3d(c3, feat_dim, 1) # at 1/8 input res
self.feat_dim = feat_dim
def forward(self, x):
h0 = self.e0(x) # [B,c1, V, V, V] (full res)
h1 = self.e1(self.d1(h0)) # [B,c2, V/2,...]
h2 = self.e2(self.d2(h1)) # [B,c3, V/4,...]
hb = self.bott(self.d3(h2)) # [B,c3, V/8,...]
# fine feature grid: downsample h0 once to 1/2 res to keep memory sane but local
fine = self.head_fine(F.avg_pool3d(h0, 2)) # [B,feat, V/2,...]
coarse = self.head_coarse(hb) # [B,feat, V/8,...]
return fine, coarse
class ImplicitDecoder(nn.Module):
def __init__(self, feat_dim=64, latent_dim=64, hidden=256, layers=5):
super().__init__()
# input = coords(3) + fine_feat + coarse_feat + global_latent
in_dim = 3 + feat_dim + feat_dim + latent_dim
net = [nn.Linear(in_dim, hidden), nn.SiLU()]
for _ in range(layers - 2):
net += [nn.Linear(hidden, hidden), nn.SiLU()]
self.backbone = nn.Sequential(*net)
self.out = nn.Linear(hidden, 2) # tooth sdf, canal sdf
def forward(self, feats):
return self.out(self.backbone(feats)) # [..., 2]
class ImplicitNet(nn.Module):
def __init__(self, num_instances, cfg):
super().__init__()
s2 = cfg["stage2"]
self.feat_dim = s2["feat_dim"]
self.latent_dim = s2["latent_dim"]
self.encoder = Encoder3D(tuple(s2["enc_channels"]), self.feat_dim)
self.decoder = ImplicitDecoder(self.feat_dim, self.latent_dim,
s2["mlp_hidden"], s2["mlp_layers"])
self.latents = nn.Embedding(max(num_instances, 1), self.latent_dim)
nn.init.normal_(self.latents.weight, 0.0, 0.01)
# P1-6: predict a latent from the ROI feature grid so new (test) cases get a
# latent from the image alone -- no GT, no per-instance table lookup needed.
self.use_encoder_latent = bool(s2.get("encoder_latent", False))
if self.use_encoder_latent:
self.latent_head = nn.Sequential(
nn.AdaptiveAvgPool3d(1), nn.Flatten(),
nn.Linear(self.feat_dim, self.latent_dim))
def encode(self, roi):
# returns (fine_grid, coarse_grid)
return self.encoder(roi)
def latent_from_feat(self, feat, gid=None):
"""Global latent (now just CONTEXT, secondary to local features). Pooled from
the coarse grid. With encoder_latent on, predicted from the image alone."""
fine, coarse = feat
if self.use_encoder_latent:
z = self.latent_head(coarse)
if gid is not None and self.training:
z = z + self.latents(gid)
return z
return self.latents(gid)
def query(self, feat, coords_mm, half_mm, z, compute_grad=False):
"""feat: (fine_grid, coarse_grid). For each query point we trilinearly sample
BOTH grids -> local detail (fine) + global context (coarse), concat with the
global latent z. This is the ConvONet-style local-implicit decode that keeps
thin canal detail instead of averaging it into one global vector."""
fine, coarse = feat
B, N = coords_mm.shape[0], coords_mm.shape[1]
if compute_grad:
coords_mm = coords_mm.clone().requires_grad_(True)
if torch.is_tensor(half_mm):
half = half_mm.view(B, 1, 1)
else:
half = half_mm
p = coords_mm / half # ~[-1,1]
f_fine = trilinear_sample_feat(fine, p) # [B,N,feat] local detail
f_coarse = trilinear_sample_feat(coarse, p) # [B,N,feat] context
zexp = z[:, None, :].expand(-1, N, -1)
inp = torch.cat([p, f_fine, f_coarse, zexp], dim=-1)
sdf = self.decoder(inp)
grads = None
if compute_grad:
grads = {}
for k, name in [(0, "tooth"), (1, "canal")]:
g = torch.autograd.grad(
sdf[..., k].sum(), coords_mm, create_graph=self.training,
retain_graph=True)[0]
grads[name] = g
return sdf, grads
def forward(self, roi, gid, coords_mm, half_mm, compute_grad=False):
feat = self.encode(roi)
z = self.latent_from_feat(feat, gid)
return self.query(feat, coords_mm, half_mm, z, compute_grad)
|