File size: 4,741 Bytes
76eb7b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)


@torch.no_grad()
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


@torch.inference_mode()
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)