Download proj2rep/models.py from markjiang1/Proj2Rep-CTFM: direct link, hf CLI and curl.
- Browser
- Download file 4.74 kB
-
https://huggingface.co/markjiang1/Proj2Rep-CTFM/resolve/main/proj2rep/models.py
- Command line
-
hf download hf://markjiang1/Proj2Rep-CTFM/proj2rep/models.py
-
curl -L -o models.py https://huggingface.co/markjiang1/Proj2Rep-CTFM/resolve/main/proj2rep/models.py
4.74 kB
| """Networks: measurement denoiser, frozen image teacher, and the measurement encoder. | |
| Teacher: the CT-FM image encoder (SegResNet encoder, 512 output features), frozen. | |
| Encoder: the same architecture, initialised from the teacher and trained to reproduce the | |
| teacher's embedding of the routine-dose image from back-projected measurements. | |
| Both return a slab embedding (B, 512) and a 4 x 4 grid of regional embeddings (B, 16, 512). | |
| """ | |
| import torch | |
| import torch.nn.functional as F | |
| from torch import nn | |
| DIM, GRID = 512, 4 | |
| CT_FM = {"spatial_dims": 3, "in_channels": 1, "init_filters": 32, "blocks_down": [1, 2, 2, 4, 4]} | |
| CLIP, SCALE = 12.0, 4.0 # line integrals are clipped to [-1, CLIP] and divided by SCALE in the denoiser | |
| def segres_encoder(): | |
| from monai.networks.nets.segresnet_ds import SegResEncoder | |
| return SegResEncoder(**CT_FM) | |
| def load_teacher(path, device): | |
| """Frozen CT-FM weights from a .safetensors file (see README for where to obtain them).""" | |
| from safetensors.torch import load_file | |
| model = segres_encoder() | |
| model.load_state_dict(load_file(str(path)), strict=True) | |
| return model.to(device).eval().requires_grad_(False) | |
| def pool(h, grid=GRID): | |
| return h.mean((2, 3, 4)), F.adaptive_avg_pool3d(h, (1, grid, grid)).flatten(2).transpose(1, 2) | |
| def teach(teacher, x): | |
| with torch.autocast("cuda", dtype=torch.bfloat16): | |
| h = teacher(x)[-1].float() | |
| return pool(h) | |
| class Encoder(nn.Module): | |
| """Back-projected measurements (B, 1, 24, 256, 256) -> teacher-space embeddings.""" | |
| def __init__(self, teacher_path=None): | |
| super().__init__() | |
| self.net = segres_encoder() | |
| if teacher_path: | |
| from safetensors.torch import load_file | |
| self.net.load_state_dict(load_file(str(teacher_path)), strict=True) | |
| def forward(self, x, grid=GRID): | |
| return pool(self.net(x)[-1].float(), grid) | |
| class _Block(nn.Module): | |
| def __init__(self, c): | |
| super().__init__() | |
| self.a, self.b = nn.Conv3d(c, c, 3, padding=1), nn.Conv3d(c, c, 3, padding=1) | |
| self.n1, self.n2 = nn.GroupNorm(8, c), nn.GroupNorm(8, c) | |
| def forward(self, x): | |
| return x + self.b(F.silu(self.n2(self.a(F.silu(self.n1(x)))))) | |
| class Denoiser(nn.Module): | |
| """Residual network over (views, detector rows, detector columns): reduced-dose -> routine-dose line integrals. | |
| Two levels; the coarse level halves views and columns, not rows. The output layer starts at | |
| zero, so an untrained denoiser is the identity. | |
| """ | |
| def __init__(self, c=48): | |
| super().__init__() | |
| self.stem = nn.Conv3d(1, c, 3, padding=1) | |
| self.fine1 = nn.Sequential(_Block(c), _Block(c)) | |
| self.down = nn.Conv3d(c, 2 * c, (2, 1, 2), stride=(2, 1, 2)) | |
| self.coarse = nn.Sequential(*[_Block(2 * c) for _ in range(4)]) | |
| self.up = nn.ConvTranspose3d(2 * c, c, (2, 1, 2), stride=(2, 1, 2)) | |
| self.fine2 = nn.Sequential(_Block(c), _Block(c)) | |
| self.head = nn.Conv3d(c, 1, 3, padding=1) | |
| nn.init.zeros_(self.head.weight) | |
| nn.init.zeros_(self.head.bias) | |
| def forward(self, x): | |
| u = x.clamp(-1, CLIP) / SCALE | |
| h = self.fine1(self.stem(u)) | |
| h = self.fine2(h + self.up(self.coarse(self.down(h)))) | |
| return (u + self.head(h)) * SCALE | |
| def denoise_scan(model, scan, device, chunk=96, margin=8): | |
| """Whole scan (V, rows, cols) -> denoised float16 array, processed in overlapping view chunks.""" | |
| import numpy as np | |
| v, _, c = scan.shape | |
| out = np.empty(scan.shape, np.float16) | |
| for a in range(0, v, chunk): | |
| lo, hi = max(a - margin, 0), min(a + chunk + margin, v) | |
| hi -= (hi - lo) % 2 | |
| if hi <= a: | |
| out[a:] = scan[a:] | |
| continue | |
| x = torch.from_numpy(np.asarray(scan[lo:hi], dtype=np.float32)).to(device)[None, None] | |
| if c % 2: | |
| x = F.pad(x, (0, 1)) | |
| with torch.autocast("cuda", dtype=torch.bfloat16): | |
| y = model(x)[0, 0, :, :, :c].float() | |
| stop = min(a + chunk, hi) | |
| out[a:stop] = y[a - lo : stop - lo].cpu().numpy() | |
| if stop < min(a + chunk, v): | |
| out[stop : min(a + chunk, v)] = scan[stop : min(a + chunk, v)] | |
| return out | |
| def short_ramp(device, n=31): | |
| """Short ramp kernel used in the denoiser loss (shape of what back-projection sees).""" | |
| k = torch.arange(-n, n + 1, device=device, dtype=torch.float32) | |
| w = torch.zeros_like(k) | |
| odd = k.abs() % 2 == 1 | |
| w[odd] = -1 / (torch.pi * k[odd]) ** 2 | |
| w[n] = 0.25 | |
| return w * 4 | |
| def ramp_columns(x, kernel): | |
| return F.conv1d(x.reshape(-1, 1, x.shape[-1]), kernel[None, None], padding=len(kernel) // 2).reshape(x.shape) | |