Spaces:
Runtime error
Runtime error
File size: 21,535 Bytes
010a8b2 |
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 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 |
'''
Implementing Mobilenet v3 as seen in
"Searching for MobileNetV3" for video classification,
note that balls are 0 and strikes are 1.
'''
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
class SEBlock3D(nn.Module):
def __init__(self,channels):
super().__init__()
self.se = nn.Sequential(
nn.AdaptiveAvgPool3d(1),
nn.Conv3d(channels,channels//4,kernel_size=1),
nn.ReLU(inplace=True),
nn.Conv3d(channels//4,channels,kernel_size=1),
nn.Hardsigmoid()
)
def forward(self,x):
w = self.se(x)
x = x * w
return x
class SEBlock2D(nn.Module):
def __init__(self,channels):
super().__init__()
self.se = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(channels,channels//4,kernel_size=1),
nn.ReLU(inplace=True),
nn.Conv2d(channels//4,channels,kernel_size=1),
nn.Hardsigmoid()
)
def forward(self,x):
w = self.se(x)
x = x * w
return x
#Bottleneck for Mobilenets
class Bottleneck3D(nn.Module):
def __init__(self, in_channels, out_channels, expanded_channels, stride=1, use_se=False, kernel_size=3,nonlinearity=nn.Hardswish(),batchnorm=True,dropout=0,bias=False):
super().__init__()
#pointwise conv1x1x1 (reduce channels)
self.pointwise_conv1 = nn.Conv3d(in_channels,expanded_channels,kernel_size=1,bias=bias)
#depthwise (spatial filtering)
#groups to preserve channel-wise information
self.depthwise_conv = nn.Conv3d(
expanded_channels,#in channels
expanded_channels,#out channels
groups=expanded_channels,
kernel_size=(1,kernel_size,kernel_size),
stride=stride,
padding=kernel_size//2,
bias=bias
)
#squeeze-and-excite (recalibrate channel wise)
self.squeeze_excite = SEBlock3D(expanded_channels) if use_se else None
#pointwise conv1x1x1 (expansion to increase channels)
self.pointwise_conv2 = nn.Conv3d(expanded_channels,out_channels,kernel_size=1,bias=bias)
self.batchnorm = nn.BatchNorm3d(out_channels) if batchnorm else None
self.nonlinearity = nonlinearity
self.dropout = nn.Dropout3d(p=dropout)
def forward(self,x):
x = self.pointwise_conv1(x)
x = self.depthwise_conv(x)
if self.squeeze_excite is not None:
x = self.squeeze_excite(x)
x = self.pointwise_conv2(x)
x = self.batchnorm(x)
x = self.nonlinearity(x)
x = self.dropout(x)
return x
#2D bottleneck for our 2d convnet with LSTM
class Bottleneck2D(nn.Module):
def __init__(self, in_channels, out_channels, expanded_channels, stride=1, use_se=False, kernel_size=3,nonlinearity=nn.Hardswish(),batchnorm=True,dropout=0,bias=False):
super().__init__()
#pointwise conv1x1x1 (reduce channels)
self.pointwise_conv1 = nn.Conv2d(in_channels,expanded_channels,kernel_size=1,bias=bias)
#depthwise (spatial filtering)
#groups to preserve channel-wise information
self.depthwise_conv = nn.Conv2d(
expanded_channels,#in channels
expanded_channels,#out channels
groups=expanded_channels,
kernel_size=kernel_size,
stride=stride,
padding=kernel_size//2,
bias=bias
)
#squeeze-and-excite (recalibrate channel wise)
self.squeeze_excite = SEBlock2D(expanded_channels) if use_se else None
#pointwise conv1x1x1 (expansion to increase channels)
self.pointwise_conv2 = nn.Conv2d(expanded_channels,out_channels,kernel_size=1,bias=bias)
self.batchnorm = nn.BatchNorm2d(out_channels) if batchnorm else None
self.nonlinearity = nonlinearity
self.dropout = nn.Dropout2d(p=dropout)
def forward(self,x):
x = self.pointwise_conv1(x)
x = self.depthwise_conv(x)
if self.squeeze_excite is not None:
x = self.squeeze_excite(x)
x = self.pointwise_conv2(x)
x = self.batchnorm(x)
x = self.nonlinearity(x)
return x
#mobilenet large 3d convolutions
class MobileNetLarge3D(nn.Module):
def __init__(self,num_classes=2):
super().__init__()
self.num_classes = num_classes
#conv3d (h-swish): 224x224x3 -> 112x112x16
self.block1 = nn.Sequential(
nn.Conv3d(in_channels=3,out_channels=16,stride=2,kernel_size=3,padding=1),
nn.BatchNorm3d(16),
nn.Hardswish()
)
#3x3 bottlenecks1 (3, ReLU): 112x112x16 -> 56x56x24
self.block2 = nn.Sequential(
Bottleneck3D(in_channels=16,out_channels=16,expanded_channels=16,stride=1,nonlinearity=nn.ReLU(),dropout=0.2),
Bottleneck3D(in_channels=16,out_channels=24,expanded_channels=64,stride=2,nonlinearity=nn.ReLU(),dropout=0.2),
Bottleneck3D(in_channels=24,out_channels=24,expanded_channels=72,stride=1,nonlinearity=nn.ReLU(),dropout=0.2)
)
#5x5 bottlenecks1 (3, ReLU, squeeze-excite): 56x56x24 -> 28x28x40
self.block3 = nn.Sequential(
Bottleneck3D(in_channels=24,out_channels=40,expanded_channels=72,stride=2,use_se=True,kernel_size=5,nonlinearity=nn.ReLU(),dropout=0.2),
Bottleneck3D(in_channels=40,out_channels=40,expanded_channels=120,stride=1,use_se=True,kernel_size=5,nonlinearity=nn.ReLU(),dropout=0.2),
Bottleneck3D(in_channels=40,out_channels=40,expanded_channels=120,stride=1,use_se=True,kernel_size=5,nonlinearity=nn.ReLU(),dropout=0.2)
)
#3x3 bottlenecks2 (6, h-swish, last two get squeeze-excite): 28x28x40 -> 14x14x112
self.block4 = nn.Sequential(
Bottleneck3D(in_channels=40,out_channels=80,expanded_channels=240,stride=2,dropout=0.2),
Bottleneck3D(in_channels=80,out_channels=80,expanded_channels=240,stride=1,dropout=0.2),
Bottleneck3D(in_channels=80,out_channels=80,expanded_channels=184,stride=1,dropout=0.2),
Bottleneck3D(in_channels=80,out_channels=80,expanded_channels=184,stride=1,dropout=0.2),
Bottleneck3D(in_channels=80,out_channels=112,expanded_channels=480,stride=1,use_se=True,dropout=0.2),
Bottleneck3D(in_channels=112,out_channels=112,expanded_channels=672,stride=1,use_se=True,dropout=0.2)
)
#5x5 bottlenecks2 (3, h-swish, squeeze-excite): 14x14x112 -> 7x7x160
self.block5 = nn.Sequential(
Bottleneck3D(in_channels=112,out_channels=160,expanded_channels=672,stride=2,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck3D(in_channels=160,out_channels=160,expanded_channels=960,stride=1,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck3D(in_channels=160,out_channels=160,expanded_channels=960,stride=1,use_se=True,kernel_size=5,dropout=0.2)
)
#conv3d (h-swish), avg pool 7x7: 7x7x960 -> 1x1x960
self.block6 = nn.Sequential(
nn.Conv3d(in_channels=160,out_channels=960,stride=1,kernel_size=1),
nn.BatchNorm3d(960),
nn.Hardswish()
)
#classifier: conv3d 1x1 NBN (2, first uses h-swish): 1x1x960
self.classifier = nn.Sequential(
nn.AdaptiveAvgPool3d((1,1,1)),
nn.Conv3d(in_channels=960,out_channels=1280,kernel_size=1,stride=1,padding=0), #2 classes for ball/strike
nn.Hardswish(),
nn.Conv3d(in_channels=1280,out_channels=self.num_classes,kernel_size=1,stride=1,padding=0)
)
def forward(self,x):
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
x = self.block4(x)
x = self.block5(x)
x = self.block6(x)
x = self.classifier(x)
x = x.view(x.shape[0], self.num_classes)
return x
def initialize_weights(self):
for module in self.modules():
if isinstance(module, nn.Conv3d) or isinstance(module, nn.Linear):
if hasattr(module, "nonlinearity"):
if module.nonlinearity == 'relu':
init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu')
elif module.nonlinearity == 'hardswish':
init.xavier_uniform_(module.weight)
elif isinstance(module, nn.BatchNorm3d):
init.constant_(module.weight, 1)
init.constant_(module.bias, 0)
#mobilenet small 3d convolutions
class MobileNetSmall3D(nn.Module):
def __init__(self,num_classes=2):
super().__init__()
self.num_classes = num_classes
#conv3d (h-swish): 224x224x3 -> 112x112x16
self.block1 = nn.Sequential(
nn.Conv3d(in_channels=3,out_channels=16,kernel_size=3,stride=2,padding=1),
nn.BatchNorm3d(16),
nn.Hardswish()
)
#3x3 bottlenecks (3, ReLU, first gets squeeze-excite): 112x112x16 -> 28x28x24
self.block2 = nn.Sequential(
Bottleneck3D(in_channels=16,out_channels=16,expanded_channels=16,stride=2,use_se=True,nonlinearity=nn.LeakyReLU(),dropout=0.2),
Bottleneck3D(in_channels=16,out_channels=24,expanded_channels=72,stride=2,nonlinearity=nn.LeakyReLU(),dropout=0.2),
Bottleneck3D(in_channels=24,out_channels=24,expanded_channels=88,stride=1,nonlinearity=nn.LeakyReLU(),dropout=0.2)
)
#5x5 bottlenecks (8, h-swish, squeeze-excite): 28x28x24 -> 7x7x96
self.block3 = nn.Sequential(
Bottleneck3D(in_channels=24,out_channels=40,expanded_channels=96,stride=2,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck3D(in_channels=40,out_channels=40,expanded_channels=240,stride=1,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck3D(in_channels=40,out_channels=40,expanded_channels=240,stride=1,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck3D(in_channels=40,out_channels=48,expanded_channels=120,stride=1,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck3D(in_channels=48,out_channels=48,expanded_channels=144,stride=1,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck3D(in_channels=48,out_channels=96,expanded_channels=288,stride=2,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck3D(in_channels=96,out_channels=96,expanded_channels=576,stride=1,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck3D(in_channels=96,out_channels=96,expanded_channels=576,stride=1,use_se=True,kernel_size=5,dropout=0.2)
)
#conv3d (h-swish), avg pool 7x7: 7x7x96 -> 1x1x576
self.block4 = nn.Sequential(
nn.Conv3d(in_channels=96,out_channels=576,kernel_size=1,stride=1,padding=0),
SEBlock3D(channels=576),
nn.BatchNorm3d(576),
nn.Hardswish()
)
#conv3d 1x1, NBN, (2, first uses h-swish): 1x1x576
self.classifier = nn.Sequential(
nn.AdaptiveAvgPool3d((1,1,1)),
nn.Conv3d(in_channels=576,out_channels=1024,kernel_size=1,stride=1,padding=0),
nn.Hardswish(),
nn.Conv3d(in_channels=1024,out_channels=self.num_classes,kernel_size=1,stride=1,padding=0),
)
def forward(self,x):
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
x = self.block4(x)
x = self.classifier(x)
x = x.view(x.shape[0], self.num_classes)
return x
def initialize_weights(self):
for module in self.modules():
if isinstance(module, nn.Conv3d) or isinstance(module, nn.Linear):
if hasattr(module, "nonlinearity"):
if module.nonlinearity == 'relu' or 'leaky_relu':
init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu')
elif module.nonlinearity == 'hardswish':
init.xavier_uniform_(module.weight)
elif isinstance(module, nn.BatchNorm3d):
init.constant_(module.weight, 1)
init.constant_(module.bias, 0)
#MobileNetV3-Large 2D + LSTM for helping with the temporal dimension
class MobileNetLarge2D(nn.Module):
def __init__(self, num_classes=2):
super().__init__()
self.num_classes = num_classes
def initialize_weights(self):
for module in self.modules():
if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):
if hasattr(module, "nonlinearity"):
if module.nonlinearity == 'relu':
init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu')
elif module.nonlinearity == 'hardswish':
init.xavier_uniform_(module.weight)
elif isinstance(module, nn.BatchNorm2d):
init.constant_(module.weight, 1)
init.constant_(module.bias, 0)
#conv2d (h-swish): 224x224x3 -> 112x112x16
self.block1 = nn.Sequential(
nn.Conv2d(in_channels=3,out_channels=16,stride=2,kernel_size=3,padding=1),
nn.BatchNorm2d(16),
nn.Hardswish()
)
#3x3 bottlenecks1 (3, ReLU): 112x112x16 -> 56x56x24
self.block2 = nn.Sequential(
Bottleneck2D(in_channels=16,out_channels=16,expanded_channels=16,stride=1,nonlinearity=nn.ReLU(),dropout=0.2),
Bottleneck2D(in_channels=16,out_channels=24,expanded_channels=64,stride=2,nonlinearity=nn.ReLU()),
Bottleneck2D(in_channels=24,out_channels=24,expanded_channels=72,stride=1,nonlinearity=nn.ReLU(),dropout=0.2)
)
#5x5 bottlenecks1 (3, ReLU, squeeze-excite): 56x56x24 -> 28x28x40
self.block3 = nn.Sequential(
Bottleneck2D(in_channels=24,out_channels=40,expanded_channels=72,stride=2,use_se=True,kernel_size=5,nonlinearity=nn.ReLU(),dropout=0.2),
Bottleneck2D(in_channels=40,out_channels=40,expanded_channels=120,stride=1,use_se=True,kernel_size=5,nonlinearity=nn.ReLU()),
Bottleneck2D(in_channels=40,out_channels=40,expanded_channels=120,stride=1,use_se=True,kernel_size=5,nonlinearity=nn.ReLU(),dropout=0.2)
)
#3x3 bottlenecks2 (6, h-swish, last two get squeeze-excite): 28x28x40 -> 14x14x112
self.block4 = nn.Sequential(
Bottleneck2D(in_channels=40,out_channels=80,expanded_channels=240,stride=2,dropout=0.2),
Bottleneck2D(in_channels=80,out_channels=80,expanded_channels=240,stride=1),
Bottleneck2D(in_channels=80,out_channels=80,expanded_channels=184,stride=1,dropout=0.2),
Bottleneck2D(in_channels=80,out_channels=80,expanded_channels=184,stride=1),
Bottleneck2D(in_channels=80,out_channels=112,expanded_channels=480,stride=1,use_se=True,dropout=0.2),
Bottleneck2D(in_channels=112,out_channels=112,expanded_channels=672,stride=1,use_se=True,dropout=0.2)
)
#5x5 bottlenecks2 (3, h-swish, squeeze-excite): 14x14x112 -> 7x7x160
self.block5 = nn.Sequential(
Bottleneck2D(in_channels=112,out_channels=160,expanded_channels=672,stride=2,use_se=True,kernel_size=5),
Bottleneck2D(in_channels=160,out_channels=160,expanded_channels=960,stride=1,use_se=True,kernel_size=5),
Bottleneck2D(in_channels=160,out_channels=160,expanded_channels=960,stride=1,use_se=True,kernel_size=5)
)
#conv3d (h-swish), avg pool 7x7: 7x7x960 -> 1x1x960
self.block6 = nn.Sequential(
nn.Conv2d(in_channels=160,out_channels=960,stride=1,kernel_size=1),
nn.BatchNorm2d(960),
nn.Hardswish(),
nn.AvgPool2d(kernel_size=7,stride=1)
)
#LSTM: 1x1x960 ->
self.lstm = nn.LSTM(input_size=960,hidden_size=32,num_layers=5,batch_first=True)
#classifier: conv3d 1x1 NBN (2, first uses h-swish): 1x1x960
self.classifier = nn.Sequential(
nn.Linear(32,self.num_classes) #2 classes for ball/strike
)
def forward(self,x):
#x is shape (batch_size, timesteps, C, H, W)
batch_size,timesteps,C,H,W = x.size()
cnn_out = torch.zeros(batch_size,timesteps,960).to(x.device) #assuming the output of block6 is 960
#we're looping through the frames in the video
for i in range(timesteps):
# Select the frame at the ith position
frame = x[:, i, :, :, :]
frame = self.block1(frame)
frame = self.block2(frame)
frame = self.block3(frame)
frame = self.block4(frame)
frame = self.block5(frame)
frame = self.block6(frame)
# Flatten the frame (minus the batch dimension)
frame = frame.view(frame.size(0), -1)
cnn_out[:, i, :] = frame
# reshape for LSTM
x = cnn_out
x, _ = self.lstm(x)
# get the output from the last timestep only
x = x[:, -1, :]
x = self.classifier(x)
return x
#MobileNetV3-Small 2d with lstm for helping with the temporal dimension
class MobileNetSmall2D(nn.Module):
def __init__(self,num_classes=2):
super().__init__()
self.num_classes = num_classes
#conv3d (h-swish): 224x224x3 -> 112x112x16
self.block1 = nn.Sequential(
nn.Conv2d(in_channels=3,out_channels=16,kernel_size=3,stride=2,padding=1),
nn.BatchNorm2d(16),
nn.Hardswish()
)
#3x3 bottlenecks (3, ReLU, first gets squeeze-excite): 112x112x16 -> 28x28x24
self.block2 = nn.Sequential(
Bottleneck2D(in_channels=16,out_channels=16,expanded_channels=16,stride=2,use_se=True,nonlinearity=nn.ReLU(),dropout=0.2),
Bottleneck2D(in_channels=16,out_channels=24,expanded_channels=72,stride=2,nonlinearity=nn.ReLU(),dropout=0.2),
Bottleneck2D(in_channels=24,out_channels=24,expanded_channels=88,stride=1,nonlinearity=nn.ReLU(),dropout=0.2)
)
#5x5 bottlenecks (8, h-swish, squeeze-excite): 28x28x24 -> 7x7x96
self.block3 = nn.Sequential(
Bottleneck2D(in_channels=24,out_channels=40,expanded_channels=96,stride=2,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck2D(in_channels=40,out_channels=40,expanded_channels=240,stride=1,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck2D(in_channels=40,out_channels=40,expanded_channels=240,stride=1,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck2D(in_channels=40,out_channels=48,expanded_channels=120,stride=1,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck2D(in_channels=48,out_channels=48,expanded_channels=144,stride=1,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck2D(in_channels=48,out_channels=96,expanded_channels=288,stride=2,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck2D(in_channels=96,out_channels=96,expanded_channels=576,stride=1,use_se=True,kernel_size=5,dropout=0.2),
Bottleneck2D(in_channels=96,out_channels=96,expanded_channels=576,stride=1,use_se=True,kernel_size=5,dropout=0.2)
)
#conv2d (h-swish), avg pool 7x7: 7x7x96 -> 1x1x576
self.block4 = nn.Sequential(
nn.Conv2d(in_channels=96,out_channels=576,kernel_size=1,stride=1,padding=0),
SEBlock2D(channels=576),
nn.BatchNorm2d(576),
nn.Hardswish(),
nn.AvgPool2d(kernel_size=7,stride=1)
)
#LSTM: 1x1x576 ->
self.lstm = nn.LSTM(input_size=576,hidden_size=64,num_layers=1,batch_first=True)
#classifier: conv3d 1x1 NBN (2, first uses h-swish): 1x1x576
self.classifier = nn.Sequential(
nn.Linear(64,self.num_classes) #2 classes for ball/strike
)
def forward(self,x):
# x is of shape (batch_size, timesteps, C, H, W)
batch_size, timesteps, C, H, W = x.size()
cnn_out = torch.zeros(batch_size, timesteps, 576).to(x.device) #assuming the output of block4 is 576
#we're looping through the frames in the video
for i in range(timesteps):
# Select the frame at the ith position
frame = x[:, i, :, :, :]
frame = self.block1(frame)
frame = self.block2(frame)
frame = self.block3(frame)
frame = self.block4(frame)
# Flatten the frame (minus the batch dimension)
frame = frame.view(frame.size(0), -1)
cnn_out[:, i, :] = frame
# reshape for LSTM
x = cnn_out
x, _ = self.lstm(x)
# get the output from the last timestep only
x = x[:, -1, :]
x = self.classifier(x)
return x
def initialize_weights(self):
for module in self.modules():
if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):
if hasattr(module, "nonlinearity"):
if module.nonlinearity == 'relu':
init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu')
elif module.nonlinearity == 'hardswish':
init.xavier_uniform_(module.weight)
elif isinstance(module, nn.BatchNorm2d):
init.constant_(module.weight, 1)
init.constant_(module.bias, 0)
|