python
import torch
import torch.nn as nn
"""
X3D(Feichtenhofer 2020、3.1 節・Table 1・Table 3(b)・付録 A.3)の小さな実装例。
X3D-M の設定:入力 (N, 3, 16, 224, 224)、γb = 2.25、各段のブロック数 3・5・11・7。
"""
class SE(nn.Module):
"""Squeeze-and-Excitation。全体平均 → 縮める → 広げる → シグモイドでチャネルに重みを掛ける。"""
def __init__(self, c, ratio=1 / 16):
super().__init__()
h = max(8, int(c * ratio))
self.fc = nn.Sequential(nn.AdaptiveAvgPool3d(1), nn.Conv3d(c, h, 1), nn.ReLU(inplace=True),
nn.Conv3d(h, c, 1), nn.Sigmoid())
def forward(self, x):
return x * self.fc(x)
class X3DBlock(nn.Module):
"""1×1² で広げる → 3×3² のチャネルごとの 3D 畳み込み(→ SE)→ 1×1² で戻す → 残差の和。"""
def __init__(self, cin, cmid, cout, stride, use_se):
super().__init__()
self.a = nn.Sequential(nn.Conv3d(cin, cmid, 1, bias=False), nn.BatchNorm3d(cmid), nn.SiLU()) # 3×3² の前の swish
# groups=cmid でチャネルごと。時間方向のストライドは 1(時間方向に縮めない)
self.b = nn.Sequential(nn.Conv3d(cmid, cmid, 3, stride=(1, stride, stride), padding=1, groups=cmid, bias=False),
nn.BatchNorm3d(cmid))
self.se = SE(cmid) if use_se else nn.Identity()
self.act = nn.SiLU() # 3×3² の後の swish(swish はこの前後だけ、ほかは ReLU。付録 A.3)
self.c = nn.Sequential(nn.Conv3d(cmid, cout, 1, bias=False), nn.BatchNorm3d(cout))
self.short = nn.Identity() if (cin == cout and stride == 1) else nn.Sequential(
nn.Conv3d(cin, cout, 1, stride=(1, stride, stride), bias=False), nn.BatchNorm3d(cout))
self.out = nn.ReLU(inplace=True)
def forward(self, x):
y = self.c(self.act(self.se(self.b(self.a(x)))))
return self.out(y + self.short(x))
class X3D(nn.Module):
def __init__(self, num_classes=400, widths=(24, 48, 96, 192), depths=(3, 5, 11, 7), gamma_b=2.25):
super().__init__()
c0 = widths[0]
self.conv1 = nn.Sequential(
nn.Conv3d(3, c0, (1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1), bias=False), # 空間の 1×3²
nn.Conv3d(c0, c0, (3, 1, 1), padding=(1, 0, 0), groups=c0, bias=False), # 時間方向の 3×1、チャネルごと
nn.BatchNorm3d(c0), nn.ReLU(inplace=True))
blocks, cin = [], c0
for w, n in zip(widths, depths):
for i in range(n):
blocks.append(X3DBlock(cin, int(w * gamma_b), w, stride=2 if i == 0 else 1, use_se=(i % 2 == 0)))
cin = w
self.stages = nn.Sequential(*blocks)
c5 = int(widths[-1] * gamma_b) # conv5:432
self.conv5 = nn.Sequential(nn.Conv3d(cin, c5, 1, bias=False), nn.BatchNorm3d(c5), nn.ReLU(inplace=True))
self.pool = nn.AdaptiveAvgPool3d(1) # pool5
self.head = nn.Sequential(nn.Flatten(), nn.Linear(c5, 2048), nn.ReLU(inplace=True), # fc1
nn.Dropout(0.5), nn.Linear(2048, num_classes)) # fc2 の前に dropout 0.5
def forward(self, clip): # clip: (N, 3, T, H, W)
x = self.conv5(self.stages(self.conv1(clip)))
return self.head(self.pool(x))
model = X3D(num_classes=400)
model.eval() # dropout を止め、BN は学習済みの統計を使う(学習では model.train())
with torch.no_grad():
clip = torch.randn(1, 3, 16, 224, 224) # 5 フレームおきに取った 16 枚(X3D-M)
print(model(clip).shape) # torch.Size([1, 400])