python
import torch
import torch.nn as nn
"""
TSM(Lin, Gan, Han 2019、3.1〜3.3 節・4.1〜4.2 節)の実装例
2D の CNN はフレームをバッチ方向に並べて受け取る:x は (N*T, C, H, W)
"""
def temporal_shift(x, n_segment, fold_div=8):
"""双方向のずらし(オフライン)。チャネルの 1/8 を前へ、別の 1/8 を後ろへ 1 フレームずらす。"""
nt, c, h, w = x.shape
x = x.view(nt // n_segment, n_segment, c, h, w) # (N, T, C, H, W)
fold = c // fold_div
out = torch.zeros_like(x) # 空いた所は 0 で埋める
out[:, :-1, :fold] = x[:, 1:, :fold] # 各時刻に次の時刻の値(未来から)
out[:, 1:, fold:2 * fold] = x[:, :-1, fold:2 * fold] # 各時刻に前の時刻の値(過去から)
out[:, :, 2 * fold:] = x[:, :, 2 * fold:] # 残りの 3/4 はそのまま
return out.view(nt, c, h, w)
class ResidualShift(nn.Module):
"""残差の枝の中でずらす(3.3 節)。恒等写像は今のフレームの特徴量をそのまま運ぶ。"""
def __init__(self, branch: nn.Module, n_segment: int):
super().__init__()
self.branch = branch # 残差の枝(ResNet のボトルネックの畳み込みなど)
self.n_segment = n_segment
def forward(self, x):
return x + self.branch(temporal_shift(x, self.n_segment))
class OnlineShift(nn.Module):
"""一方向のずらし(オンライン、4.2 節)。前のフレームの最初の 1/8 のチャネルを覚えておき、
今のフレームの最初の 1/8 をそれで置き換える。1 フレームずつ (1, C, H, W) で呼ぶ。"""
def __init__(self, fold_div=8):
super().__init__()
self.fold_div = fold_div
self.cache = None
def forward(self, x):
fold = x.shape[1] // self.fold_div
prev = self.cache if self.cache is not None else torch.zeros_like(x[:, :fold])
self.cache = x[:, :fold].detach().clone() # 次のフレームのために残す
return torch.cat([prev, x[:, fold:]], dim=1)
# 使い方:8 フレームを 2D の CNN で処理し、ずらしを残差の枝に入れる
T, C = 8, 64
branch = nn.Sequential(nn.Conv2d(C, C, 3, padding=1), nn.BatchNorm2d(C), nn.ReLU())
block = ResidualShift(branch, n_segment=T)
frames = torch.randn(2 * T, C, 56, 56) # (N*T, C, H, W)
out = block(frames)
print(out.shape) # torch.Size([16, 64, 56, 56])
# 最後はフレームごとのスコアを T フレームで平均する(TSN と同じ)
# logits = head(features).view(N, T, -1).mean(dim=1)