"""NAFNet for unequal-channel translation; see NAFNET_NOTICE.md. Retains SimpleGate, simplified channel attention, zero-initialized beta/gamma, channel LayerNorm, additive skips and pixel-shuffle upsampling. No image residual is possible between 17-marker input and RGB output. The optional marker gate is an ORION-specific variant, not part of the published network. """ import torch from torch import nn from torch.nn import functional as F class LayerNorm2d(nn.Module): def __init__(self, channels, eps=1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(channels)) self.bias = nn.Parameter(torch.zeros(channels)) self.eps = eps def forward(self, x): # Native LayerNorm supplies the same channel-only normalization/autograd. return F.layer_norm(x.permute(0, 2, 3, 1), (x.shape[1],), self.weight, self.bias, self.eps).permute(0, 3, 1, 2) class SimpleGate(nn.Module): def forward(self, x): a, b = x.chunk(2, dim=1) return a * b class NAFBlock(nn.Module): def __init__(self, c, DW_Expand=2, FFN_Expand=2, drop_out_rate=0.): super().__init__() dw, ffn = c * DW_Expand, c * FFN_Expand self.conv1 = nn.Conv2d(c, dw, 1) self.conv2 = nn.Conv2d(dw, dw, 3, padding=1, groups=dw) self.conv3 = nn.Conv2d(dw // 2, c, 1) self.sca = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Conv2d(dw // 2, dw // 2, 1)) self.sg = SimpleGate() self.conv4, self.conv5 = nn.Conv2d(c, ffn, 1), nn.Conv2d(ffn // 2, c, 1) self.norm1, self.norm2 = LayerNorm2d(c), LayerNorm2d(c) self.dropout1 = nn.Dropout(drop_out_rate) if drop_out_rate else nn.Identity() self.dropout2 = nn.Dropout(drop_out_rate) if drop_out_rate else nn.Identity() self.beta = nn.Parameter(torch.zeros(1, c, 1, 1)) self.gamma = nn.Parameter(torch.zeros(1, c, 1, 1)) def forward(self, inp): x = self.sg(self.conv2(self.conv1(self.norm1(inp)))) x = self.conv3(x * self.sca(x)) y = inp + self.dropout1(x) * self.beta x = self.conv5(self.sg(self.conv4(self.norm2(y)))) return y + self.dropout2(x) * self.gamma class StainingNAFNet(nn.Module): def __init__(self, in_channels=17, width=32, middle_blk_num=1, enc_blk_nums=(1, 1, 1, 28), dec_blk_nums=(1, 1, 1, 1), marker_gating=False, bounded_output=False): super().__init__() if len(enc_blk_nums) != len(dec_blk_nums) or not enc_blk_nums: raise ValueError('NAFNet encoder/decoder stage counts must match') self.intro, self.ending = nn.Conv2d(in_channels, width, 3, padding=1), nn.Conv2d(width, 3, 3, padding=1) self.encoders, self.decoders = nn.ModuleList(), nn.ModuleList() self.downs, self.ups = nn.ModuleList(), nn.ModuleList() chan = width for n in enc_blk_nums: self.encoders.append(nn.Sequential(*[NAFBlock(chan) for _ in range(n)])) self.downs.append(nn.Conv2d(chan, chan * 2, 2, 2)) chan *= 2 self.middle_blks = nn.Sequential(*[NAFBlock(chan) for _ in range(middle_blk_num)]) for n in dec_blk_nums: self.ups.append(nn.Sequential(nn.Conv2d(chan, chan * 2, 1, bias=False), nn.PixelShuffle(2))) chan //= 2 self.decoders.append(nn.Sequential(*[NAFBlock(chan) for _ in range(n)])) self.padder_size = 2 ** len(enc_blk_nums) self.bounded_output = bounded_output self.gate = None if marker_gating: self.gate = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Conv2d(in_channels, in_channels, 1), nn.Sigmoid()) def forward(self, inp): h, w = inp.shape[-2:] if self.gate is not None: inp = inp * (2 * self.gate(inp)) inp = F.pad(inp, (0, -w % self.padder_size, 0, -h % self.padder_size)) x, skips = self.intro(inp), [] for encoder, down in zip(self.encoders, self.downs): x = encoder(x) skips.append(x) x = down(x) x = self.middle_blks(x) for decoder, up, skip in zip(self.decoders, self.ups, reversed(skips)): x = decoder(up(x) + skip) x = self.ending(x)[..., :h, :w] return x.sigmoid() if self.bounded_output else x