167 lines
7.9 KiB
Python
167 lines
7.9 KiB
Python
import torch
|
||
import torch.nn as nn
|
||
import torch.nn.functional as F
|
||
|
||
# -----------------------------------------------------------
|
||
# Basic DW‑Separable block (kept unchanged – in==out channel)
|
||
# -----------------------------------------------------------
|
||
class DepthWiseSeperableConv(nn.Module):
|
||
def __init__(self, channels, kernel_size, padding):
|
||
super().__init__()
|
||
self.depthwise = nn.Conv2d(
|
||
in_channels=channels,
|
||
out_channels=channels,
|
||
kernel_size=kernel_size,
|
||
padding=padding,
|
||
groups=channels, # ↯ one conv per channel / per tile
|
||
bias=False
|
||
)
|
||
self.bn_depth = nn.BatchNorm2d(channels)
|
||
self.pointwise = nn.Conv2d(channels, channels, kernel_size=1, bias=False)
|
||
self.bn_point = nn.BatchNorm2d(channels)
|
||
self.act = nn.ReLU(inplace=True)
|
||
|
||
def forward(self, x):
|
||
x = self.act(self.bn_depth(self.depthwise(x)))
|
||
x = self.act(self.bn_point(self.pointwise(x)))
|
||
return x
|
||
|
||
|
||
# -----------------------------------------------------------------
|
||
# Foreign‑object model that works on raw RGB and outputs per‑tile p̂
|
||
# -----------------------------------------------------------------
|
||
class ForeignObjectClassificationModel(nn.Module):
|
||
"""
|
||
Args
|
||
----
|
||
num_tiles_per_side : int
|
||
E.g. 4 → 4×4 grid → 16 tiles → 16 logits per image.
|
||
The input H and W must be divisible by this value.
|
||
kernel_size : int
|
||
DW‑separable kernel (odd number recommended).
|
||
num_conv_layers : int
|
||
How many DW‑separable blocks to stack.
|
||
pooling_after_each_conv : bool
|
||
Optional 2×2 pooling after every conv block.
|
||
conv_pooling_type : {'max', 'avg'}
|
||
Pool type if pooling_after_each_conv is True.
|
||
global_pooling_type : {'max', 'avg'}
|
||
1×1 pooling **inside each tile** before the final sigmoid.
|
||
"""
|
||
|
||
def __init__(self,
|
||
num_tiles_per_side: int,
|
||
kernel_size: int = 5,
|
||
num_conv_layers: int = 3,
|
||
pooling_after_each_conv: bool = False,
|
||
conv_pooling_type: str = 'max',
|
||
global_pooling_type: str = 'avg'):
|
||
super().__init__()
|
||
|
||
self.S = num_tiles_per_side # tiles per side
|
||
self.N = self.S ** 2 # total tiles / channels
|
||
|
||
# ------------------------------------------------------------------
|
||
# A single channel per tile → N channels after the tiling op
|
||
# ------------------------------------------------------------------
|
||
conv_blocks = []
|
||
pad = kernel_size // 2
|
||
for _ in range(num_conv_layers):
|
||
conv_blocks.append(DepthWiseSeperableConv(self.N, kernel_size, pad))
|
||
|
||
if pooling_after_each_conv: # optional spatial shrink
|
||
if conv_pooling_type == 'max':
|
||
conv_blocks.append(nn.MaxPool2d(2))
|
||
elif conv_pooling_type == 'avg':
|
||
conv_blocks.append(nn.AvgPool2d(2))
|
||
else:
|
||
raise ValueError("conv_pooling_type must be 'max' or 'avg'.")
|
||
|
||
self.conv_stack = nn.Sequential(*conv_blocks)
|
||
|
||
# 1×1 global pooling per tile/channel
|
||
if global_pooling_type == 'avg':
|
||
self.global_pool = nn.AdaptiveAvgPool2d(1)
|
||
elif global_pooling_type == 'max':
|
||
self.global_pool = nn.AdaptiveMaxPool2d(1)
|
||
else:
|
||
raise ValueError("global_pooling_type must be 'max' or 'avg'.")
|
||
|
||
# fixed grayscale weights registered as buffer (on same device)
|
||
rgb2gray = torch.tensor([0.299, 0.587, 0.114]).view(1, 3, 1, 1)
|
||
self.register_buffer("gray_w", rgb2gray, persistent=False)
|
||
|
||
# ------------------------------------------------------------------
|
||
# Helper: RGB → gray (B,1,H,W)
|
||
# ------------------------------------------------------------------
|
||
def rgb_to_gray(self, x):
|
||
# x : [B,3,H,W] – broadcast weights, then sum over channel dim
|
||
return (x * self.gray_w).sum(dim=1, keepdim=True)
|
||
|
||
# ------------------------------------------------------------------
|
||
# Helper: split grayscale image into S×S tiles -> (B,N,h,w)
|
||
# ------------------------------------------------------------------
|
||
def tile_image(self, x):
|
||
"""
|
||
x : [B,1,H,W] with H,W divisible by S
|
||
returns [B, N, h, w] where h = H/S and N = S²
|
||
"""
|
||
B, C, H, W = x.shape
|
||
h, w = H // self.S, W // self.S
|
||
# unfold → [B, C*h*w, N], then reshape/reorder → [B, N, h, w]
|
||
patches = F.unfold(x, kernel_size=(h, w), stride=(h, w)) # (B, h*w, N)
|
||
patches = patches.transpose(1, 2) # (B, N, h*w)
|
||
patches = patches.view(B, self.N, h, w)
|
||
return patches
|
||
|
||
# ------------------------------------------------------------------
|
||
# Forward: RGB → gray → tiles → convs → global pool → sigmoid
|
||
# ------------------------------------------------------------------
|
||
def forward(self, x):
|
||
"""
|
||
Input : x [B, 3, H, W] (RGB)
|
||
Output : p̂ [B, N] (sigmoid probability per tile)
|
||
"""
|
||
assert x.shape[1] == 3, "Input must be RGB image with 3 channels."
|
||
|
||
x = self.rgb_to_gray(x) # (B,1,H,W)
|
||
x = self.tile_image(x) # (B,N,h,w)
|
||
x = self.conv_stack(x) # (B,N,h',w')
|
||
x = self.global_pool(x) # (B,N,1,1)
|
||
x = x.view(x.size(0), -1) # (B,N)
|
||
return torch.sigmoid(x) # per‑tile probabilities
|
||
|
||
|
||
|
||
if __name__ == "__main__":
|
||
# ──────────────────────────────────────────────────────────────
|
||
# 1. Create a random RGB image (batch = 1)
|
||
# ──────────────────────────────────────────────────────────────
|
||
H = W = 256 # must be divisible by S
|
||
img = torch.rand(1, 3, H, W) # values in [0,1]
|
||
|
||
# ──────────────────────────────────────────────────────────────
|
||
# 2. Build the model
|
||
# S = tiles per side ⇒ N = S² outputs
|
||
# ──────────────────────────────────────────────────────────────
|
||
model = ForeignObjectClassificationModel(
|
||
num_tiles_per_side = 2, # 4 × 4 grid ⇒ 16 outputs
|
||
kernel_size = 5,
|
||
num_conv_layers = 3,
|
||
pooling_after_each_conv = False,
|
||
conv_pooling_type = 'max',
|
||
global_pooling_type = 'avg'
|
||
)
|
||
|
||
# ──────────────────────────────────────────────────────────────
|
||
# 3. Forward pass
|
||
# ──────────────────────────────────────────────────────────────
|
||
with torch.no_grad():
|
||
probs = model(img) # shape (1, 16)
|
||
|
||
# ──────────────────────────────────────────────────────────────
|
||
# 4. Show results
|
||
# ──────────────────────────────────────────────────────────────
|
||
print(f"Input shape: {img.shape}")
|
||
print(f"Output shape: {probs.shape}") # → torch.Size([1, 16])
|
||
print(f"Per‑tile probabilities:\n{probs}") |