Spaces:
Running
Running
File size: 5,581 Bytes
e99a83c | 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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | import torch
import torch.nn as nn
import torch.nn.functional as F
try:
import timm
except ImportError as e:
raise ImportError(
"timm is required for models/vit.py. Install with: pip install timm"
) from e
class ViTSegmentationModel(nn.Module):
"""
Simple ViT segmentation model using a timm Vision Transformer backbone.
The model:
image -> ViT patch tokens -> reshape to feature map -> conv head -> upsample
Output:
logits of shape [B, num_classes, H, W]
For binary vessel segmentation:
num_classes = 1
For multi-class lesion segmentation:
num_classes = number of lesion/background classes
"""
def __init__(
self,
model_name="vit_base_patch16_224",
num_classes=1,
pretrained=True,
in_chans=3,
img_size=512,
decoder_dim=256,
dropout=0.0,
):
super().__init__()
self.model_name = model_name
self.num_classes = num_classes
self.img_size = img_size
self.backbone = timm.create_model(
model_name,
pretrained=pretrained,
num_classes=0,
global_pool="",
in_chans=in_chans,
img_size=img_size,
)
self.embed_dim = self.backbone.num_features
self.patch_size = self.backbone.patch_embed.patch_size
if isinstance(self.patch_size, tuple):
self.patch_size = self.patch_size[0]
self.decoder = nn.Sequential(
nn.Conv2d(self.embed_dim, decoder_dim, kernel_size=1),
nn.BatchNorm2d(decoder_dim),
nn.ReLU(inplace=True),
nn.Dropout2d(dropout),
nn.Conv2d(decoder_dim, decoder_dim, kernel_size=3, padding=1),
nn.BatchNorm2d(decoder_dim),
nn.ReLU(inplace=True),
nn.Conv2d(decoder_dim, num_classes, kernel_size=1),
)
def forward_features_as_map(self, x):
"""
Convert ViT patch tokens into a spatial feature map.
Input:
x: [B, C, H, W]
Output:
feature_map: [B, embed_dim, H // patch_size, W // patch_size]
"""
b, _, h, w = x.shape
tokens = self.backbone.forward_features(x)
# Some timm models return a tuple/list. Usually the first item is token features.
if isinstance(tokens, (tuple, list)):
tokens = tokens[0]
# For standard ViT:
# tokens: [B, 1 + num_patches, C], where the first token is CLS.
if tokens.ndim == 3:
expected_num_patches = (h // self.patch_size) * (w // self.patch_size)
if tokens.shape[1] == expected_num_patches + 1:
tokens = tokens[:, 1:, :] # remove CLS token
feature_h = h // self.patch_size
feature_w = w // self.patch_size
tokens = tokens.transpose(1, 2)
feature_map = tokens.reshape(b, self.embed_dim, feature_h, feature_w)
# Some backbones may already return [B, C, H, W].
elif tokens.ndim == 4:
feature_map = tokens
else:
raise RuntimeError(f"Unexpected ViT feature shape: {tokens.shape}")
return feature_map
def forward(self, x):
input_size = x.shape[-2:]
feature_map = self.forward_features_as_map(x)
logits = self.decoder(feature_map)
logits = F.interpolate(
logits,
size=input_size,
mode="bilinear",
align_corners=False,
)
return logits
def build_vit(
variant="base",
num_classes=1,
pretrained=True,
in_chans=3,
img_size=512,
decoder_dim=256,
dropout=0.0,
):
"""
Build a timm ViT segmentation model.
Parameters
----------
variant:
One of:
"tiny"
"small"
"base"
"large"
Or directly pass a timm model name, e.g.:
"vit_base_patch16_224"
"vit_small_patch16_224"
"vit_large_patch16_224"
num_classes:
Number of output channels.
Binary segmentation:
num_classes=1
Multi-class segmentation:
num_classes=N
pretrained:
Whether to load ImageNet-pretrained timm weights.
img_size:
Input image size. For DRIVE, 512 is a reasonable default.
Returns
-------
model:
ViTSegmentationModel
"""
variants = {
"tiny": "vit_tiny_patch16_224",
"small": "vit_small_patch16_224",
"base": "vit_base_patch16_224",
"large": "vit_large_patch16_224",
}
model_name = variants.get(variant, variant)
model = ViTSegmentationModel(
model_name=model_name,
num_classes=num_classes,
pretrained=pretrained,
in_chans=in_chans,
img_size=img_size,
decoder_dim=decoder_dim,
dropout=dropout,
)
return model
if __name__ == "__main__":
# Smoke test:
# python models/vit.py
device = "cuda" if torch.cuda.is_available() else "cpu"
model = build_vit(
variant="base",
num_classes=1,
pretrained=False,
img_size=512,
).to(device)
x = torch.randn(2, 3, 512, 512).to(device)
with torch.no_grad():
y = model(x)
print("Model:", model.model_name)
print("Input shape:", x.shape)
print("Output shape:", y.shape)
print("Output min/max:", y.min().item(), y.max().item())
assert y.shape == (2, 1, 512, 512)
print("Smoke test passed.") |