python
import torch
import torch.nn as nn
"""
SlowFast(Feichtenhofer ら 2019、3.1〜3.4 節・Table 1)の骨組みの実装例
入力:64 フレームのクリップ (N, 3, 64, H, W)。各段の中身(ResNet のブロック)は簡略にしている。
"""
def sample_pathways(clip, tau=16, alpha=8):
"""Slow は tau フレームおきに T 枚、Fast は tau/alpha フレームおきに alpha*T 枚を取る。"""
slow = clip[:, :, ::tau] # (N, 3, T, H, W) T = 64 / 16 = 4
fast = clip[:, :, ::tau // alpha] # (N, 3, alpha*T, H, W) = 32 フレーム
return slow, fast
def stage(cin, cout, t_kernel):
"""1 つの段の代わり。t_kernel = 1 なら実質 2D、3 なら時間方向にも畳み込む。
時間方向のストライドは 1(Fast の経路は時間方向に縮めない)。"""
return nn.Sequential(
nn.Conv3d(cin, cout, (t_kernel, 3, 3), stride=(1, 2, 2), padding=(t_kernel // 2, 1, 1), bias=False),
nn.BatchNorm3d(cout), nn.ReLU(inplace=True),
)
class Lateral(nn.Module):
"""横の接続(時間方向のストライド付き畳み込み):5×1²、出力 2βC、時間方向のストライド α。"""
def __init__(self, c_fast, alpha=8):
super().__init__()
self.conv = nn.Conv3d(c_fast, 2 * c_fast, (5, 1, 1), stride=(alpha, 1, 1), padding=(2, 0, 0), bias=False)
def forward(self, x_slow, x_fast):
return torch.cat([x_slow, self.conv(x_fast)], dim=1) # Slow に連結する
class SlowFast(nn.Module):
def __init__(self, num_classes=400, alpha=8, beta_inv=8):
super().__init__()
cs = [64, 256, 512, 1024, 2048] # Slow の各段の出力チャネル(Table 1)
cf = [c // beta_inv for c in cs] # Fast は β = 1/8 倍
tk_slow = [1, 1, 1, 3, 3] # Slow:res4・res5 だけ時間方向の畳み込み
tk_fast = [5, 3, 3, 3, 3] # Fast:conv1 は 5、ほかの段も時間方向の畳み込み
self.slow, self.fast, self.lat = nn.ModuleList(), nn.ModuleList(), nn.ModuleList()
s_in, f_in = 3, 3
for i in range(5):
self.slow.append(stage(s_in, cs[i], tk_slow[i]))
self.fast.append(stage(f_in, cf[i], tk_fast[i]))
s_in, f_in = cs[i], cf[i]
if i < 4: # conv1(pool1)・res2・res3・res4 の直後に横の接続
self.lat.append(Lateral(cf[i], alpha))
s_in += 2 * cf[i] # 連結した分だけ Slow の次の段の入力が増える
self.pool = nn.AdaptiveAvgPool3d(1)
self.dropout = nn.Dropout(0.5) # 分類層の前(付録)
self.fc = nn.Linear(cs[-1] + cf[-1], num_classes)
def forward(self, clip):
xs, xf = sample_pathways(clip)
for i in range(5):
xs, xf = self.slow[i](xs), self.fast[i](xf)
if i < 4:
xs = self.lat[i](xs, xf) # Fast から Slow への一方向
feat = torch.cat([self.pool(xs).flatten(1), self.pool(xf).flatten(1)], dim=1)
return self.fc(self.dropout(feat))
model = SlowFast(num_classes=400)
model.eval() # ドロップアウトを止め、BN は学習済みの統計を使う(学習では model.train())
with torch.no_grad():
print(model(torch.randn(1, 3, 64, 224, 224)).shape) # torch.Size([1, 400])