""" Model Architectures for Industrial Surface Defect Segmentation Directly derived from Kaggle / WandB Experiment Notebook (24f3005189) """ import os from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as tvm # Default Canvas & Preprocessing Constants IMG_H = 128 IMG_W = 800 NORM_MEAN = 0.449 NORM_STD = 0.226 DEFAULT_CLASSES = ["defect_a", "defect_b", "defect_c", "defect_d"] class ConvBlock(nn.Module): """Double 3x3 Conv with BatchNorm, SiLU activation, and a residual skip connection.""" def __init__(self, cin, cout): super().__init__() self.body = nn.Sequential( nn.Conv2d(cin, cout, 3, padding=1, bias=False), nn.BatchNorm2d(cout), nn.SiLU(inplace=True), nn.Conv2d(cout, cout, 3, padding=1, bias=False), nn.BatchNorm2d(cout) ) self.skip = nn.Identity() if cin == cout else nn.Sequential( nn.Conv2d(cin, cout, 1, bias=False), nn.BatchNorm2d(cout) ) self.act = nn.SiLU(inplace=True) def forward(self, x): return self.act(self.body(x) + self.skip(x)) class UpBlock(nn.Module): """Bilinear upsampling followed by skip concatenation and residual convolution.""" def __init__(self, cin, cskip, cout): super().__init__() self.conv = ConvBlock(cin + cskip, cout) def forward(self, x, skip): x = F.interpolate(x, size=skip.shape[2:], mode="bilinear", align_corners=False) return self.conv(torch.cat([x, skip], dim=1)) def to_one_channel(conv): """Converts a 3-channel input conv to 1-channel by summing RGB filter weights.""" new = nn.Conv2d(1, conv.out_channels, conv.kernel_size, conv.stride, conv.padding, bias=False) with torch.no_grad(): new.weight.copy_(conv.weight.sum(dim=1, keepdim=True)) return new def final_head(cin, n_cls): """Last 2x upsampling layer restoring original resolution followed by 1x1 classifier.""" return nn.Sequential( nn.ConvTranspose2d(cin, 32, 2, stride=2), ConvBlock(32, 32), nn.Conv2d(32, n_cls, 1) ) # ---- Model 1: U-Net from Scratch ---- class ScratchUNet(nn.Module): def __init__(self, n_cls=4, base=16): super().__init__() c = [base, base * 2, base * 4, base * 8, base * 16] self.e1 = ConvBlock(1, c[0]) self.e2 = ConvBlock(c[0], c[1]) self.e3 = ConvBlock(c[1], c[2]) self.e4 = ConvBlock(c[2], c[3]) self.pool = nn.MaxPool2d(2) self.mid = ConvBlock(c[3], c[4]) self.d4 = UpBlock(c[4], c[3], c[3]) self.d3 = UpBlock(c[3], c[2], c[2]) self.d2 = UpBlock(c[2], c[1], c[1]) self.d1 = UpBlock(c[1], c[0], c[0]) self.head = nn.Conv2d(c[0], n_cls, 1) def forward(self, x): s1 = self.e1(x) s2 = self.e2(self.pool(s1)) s3 = self.e3(self.pool(s2)) s4 = self.e4(self.pool(s3)) x = self.mid(self.pool(s4)) return self.head(self.d1(self.d2(self.d3(self.d4(x, s4), s3), s2), s1)) # ---- Model 2: ResNet-34 Encoder + U-Net Decoder ---- class ResNet34UNet(nn.Module): def __init__(self, n_cls=4, pretrained=False): super().__init__() r = tvm.resnet34(weights=tvm.ResNet34_Weights.DEFAULT if pretrained else None) self.stem = nn.Sequential(to_one_channel(r.conv1), r.bn1, r.relu) self.pool = r.maxpool self.l1, self.l2, self.l3, self.l4 = r.layer1, r.layer2, r.layer3, r.layer4 self.d4 = UpBlock(512, 256, 256) self.d3 = UpBlock(256, 128, 128) self.d2 = UpBlock(128, 64, 64) self.d1 = UpBlock(64, 64, 64) self.head = final_head(64, n_cls) def forward(self, x): s0 = self.stem(x) s1 = self.l1(self.pool(s0)) s2 = self.l2(s1) s3 = self.l3(s2) s4 = self.l4(s3) return self.head(self.d1(self.d2(self.d3(self.d4(s4, s3), s2), s1), s0)) # ---- Model 3: EfficientNet-B3 Encoder + U-Net Decoder ---- EFF_SPEC = { "b0": dict(builder=tvm.efficientnet_b0, weights=tvm.EfficientNet_B0_Weights, ch=(16, 24, 40, 112, 320), dec=(128, 64, 32, 32)), "b3": dict(builder=tvm.efficientnet_b3, weights=tvm.EfficientNet_B3_Weights, ch=(24, 32, 48, 136, 384), dec=(160, 80, 48, 32)) } class EffNetUNet(nn.Module): def __init__(self, n_cls=4, variant="b3", pretrained=False): super().__init__() sp = EFF_SPEC[variant] e = sp["builder"](weights=sp["weights"].DEFAULT if pretrained else None) e.features[0][0] = to_one_channel(e.features[0][0]) f = e.features self.s0, self.s1, self.s2, self.s3, self.s4 = f[0:2], f[2], f[3], f[4:6], f[6:8] c0, c1, c2, c3, c4 = sp["ch"] d4, d3, d2, d1 = sp["dec"] self.d4 = UpBlock(c4, c3, d4) self.d3 = UpBlock(d4, c2, d3) self.d2 = UpBlock(d3, c1, d2) self.d1 = UpBlock(d2, c0, d1) self.head = final_head(d1, n_cls) def forward(self, x): s0 = self.s0(x) s1 = self.s1(s0) s2 = self.s2(s1) s3 = self.s3(s2) s4 = self.s4(s3) return self.head(self.d1(self.d2(self.d3(self.d4(s4, s3), s2), s1), s0)) def build_model(name, n_cls=4, pretrained=False): if name in ("scratch_unet", "Scratch U-Net"): return ScratchUNet(n_cls=n_cls) elif name in ("resnet34_unet", "ResNet-34 U-Net"): return ResNet34UNet(n_cls=n_cls, pretrained=pretrained) elif name in ("effnet_b3_unet", "EfficientNet-B3 U-Net"): return EffNetUNet(n_cls=n_cls, variant="b3", pretrained=pretrained) elif name in ("effnet_b0_unet", "EfficientNet-B0 U-Net"): return EffNetUNet(n_cls=n_cls, variant="b0", pretrained=pretrained) else: raise ValueError(f"Unknown model name: {name}") def load_model_with_weights(model_name, ckpt_dir="models", device="cpu"): """ Instantiates the model and loads weights if checkpoint file is found. Fallback: Uses ImageNet-pretrained backbone weights if checkpoint is not found. """ ckpt_names = [ f"{model_name}.pth", f"best_{model_name}.pth", f"model-{model_name}.pth" ] ckpt_path = None for name in ckpt_names: candidate = Path(ckpt_dir) / name if candidate.is_file(): ckpt_path = candidate break # Also check current root if Path(name).is_file(): ckpt_path = Path(name) break if ckpt_path: model = build_model(model_name, pretrained=False) try: state = torch.load(ckpt_path, map_location=device, weights_only=True) except Exception: state = torch.load(ckpt_path, map_location=device) if isinstance(state, dict) and "state_dict" in state: state = state["state_dict"] model.load_state_dict(state, strict=False) status = f"Loaded fine-tuned checkpoint: {ckpt_path.name}" else: # Load ImageNet pretrained backbone weights for transfer learning inference model = build_model(model_name, pretrained=True) status = f"Loaded architecture with ImageNet backbone (place fine-tuned '{model_name}.pth' in models/ for best accuracy)" model.to(device).eval() return model, status