python コピー
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import swin_t, Swin_T_Weights
"""
1) torchvision の学習済み Swin-T で画像を分類する例
2) 論文の 3.2 節(ウィンドウの自己アテンション・巡回シフトとマスク・相対位置のバイアス)の小さな実装
"""
# ---- 1) 学習済みモデルを使う ----
weights = Swin_T_Weights.IMAGENET1K_V1
model = swin_t(weights=weights).eval() # 推論では eval()(Stochastic Depth を止める)
preprocess = weights.transforms() # 縮小・切り出し・正規化(入力 224×224)
# logits = model(preprocess(img).unsqueeze(0))
# ---- 2) 論文の式どおりの小さな実装 ----
def window_partition(x, M):
"""[B, H, W, C] → [B*(H/M)*(W/M), M*M, C]。H と W は M の倍数とする"""
B, H, W, C = x.shape
x = x.view(B, H // M, M, W // M, M, C).permute(0, 1, 3, 2, 4, 5)
return x.reshape(-1, M * M, C)
def window_reverse(w, M, H, W):
"""window_partition の逆"""
B = w.shape[0] // ((H // M) * (W // M))
x = w.view(B, H // M, W // M, M, M, -1).permute(0, 1, 3, 2, 4, 5)
return x.reshape(B, H, W, -1)
class WindowAttention(nn.Module):
"""ウィンドウの中のマルチヘッド自己アテンション + 相対位置のバイアス(式 (4))"""
def __init__(self, dim, M, heads):
super().__init__()
self.M, self.heads = M, heads
self.scale = (dim // heads) ** -0.5
self.qkv = nn.Linear(dim, 3 * dim)
self.proj = nn.Linear(dim, dim)
# 学習するのは (2M-1)×(2M-1) の小さな表 B^(ヘッドごと)
self.bias_table = nn.Parameter(torch.zeros((2 * M - 1) ** 2, heads))
nn.init.trunc_normal_(self.bias_table, std=0.02)
# ウィンドウの中の 2 つのパッチの相対位置 → 表の番号
coords = torch.stack(torch.meshgrid(torch.arange(M), torch.arange(M), indexing="ij")).flatten(1) # [2, M*M]
rel = (coords[:, :, None] - coords[:, None, :]).permute(1, 2, 0) + (M - 1) # 0..2M-2
self.register_buffer("rel_index", rel[..., 0] * (2 * M - 1) + rel[..., 1]) # [M*M, M*M]
def forward(self, x, mask=None):
Bw, N, C = x.shape # Bw = バッチ × ウィンドウの数、N = M*M
q, k, v = self.qkv(x).view(Bw, N, 3, self.heads, C // self.heads).permute(2, 0, 3, 1, 4)
attn = (q * self.scale) @ k.transpose(-2, -1) # [Bw, heads, N, N]
bias = self.bias_table[self.rel_index].permute(2, 0, 1) # B:[heads, N, N]
attn = attn + bias.unsqueeze(0)
if mask is not None: # ずらしたウィンドウのマスク [nW, N, N]
nW = mask.shape[0]
attn = attn.view(-1, nW, self.heads, N, N) + mask[None, :, None]
attn = attn.view(Bw, self.heads, N, N)
out = attn.softmax(-1) @ v
return self.proj(out.transpose(1, 2).reshape(Bw, N, C))
class SwinBlock(nn.Module):
"""Swin Transformer ブロック(Pre-LN)。shift=0 なら W-MSA、shift=M//2 なら SW-MSA"""
def __init__(self, dim, H, W, heads, M=7, shift=0):
super().__init__()
self.H, self.W, self.M, self.shift = H, W, M, shift
self.norm1, self.norm2 = nn.LayerNorm(dim), nn.LayerNorm(dim)
self.attn = WindowAttention(dim, M, heads)
self.mlp = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim))
mask = None
if shift > 0:
# もとの位置で同じウィンドウだったパッチに同じ番号を振る(巡回シフト後に別の領域が混ざるのを防ぐ)
region = torch.zeros(1, H, W, 1)
cnt = 0
for hs in (slice(0, -M), slice(-M, -shift), slice(-shift, None)):
for ws in (slice(0, -M), slice(-M, -shift), slice(-shift, None)):
region[:, hs, ws, :] = cnt
cnt += 1
r = window_partition(region, M).squeeze(-1) # [nW, M*M]
mask = (r[:, None, :] != r[:, :, None]).float() * -100.0 # 違う領域どうしは見ない
self.register_buffer("mask", mask)
def forward(self, x): # x:[B, H*W, C]
B, L, C = x.shape
h = self.norm1(x).view(B, self.H, self.W, C)
if self.shift > 0: # 左上の方向に巡回シフト
h = torch.roll(h, shifts=(-self.shift, -self.shift), dims=(1, 2))
h = window_partition(h, self.M)
h = self.attn(h, self.mask)
h = window_reverse(h, self.M, self.H, self.W)
if self.shift > 0: # 逆向きの巡回シフトで戻す
h = torch.roll(h, shifts=(self.shift, self.shift), dims=(1, 2))
x = x + h.reshape(B, L, C) # 残差接続
return x + self.mlp(self.norm2(x))
class PatchMerging(nn.Module):
"""隣り合う 2×2 のパッチをつなげて 4C 次元 → 線形層で 2C 次元(解像度は縦横 1/2)"""
def __init__(self, dim, H, W):
super().__init__()
self.H, self.W = H, W
self.norm = nn.LayerNorm(4 * dim)
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
def forward(self, x):
B, L, C = x.shape
x = x.view(B, self.H, self.W, C)
x = torch.cat([x[:, 0::2, 0::2], x[:, 1::2, 0::2], x[:, 0::2, 1::2], x[:, 1::2, 1::2]], dim=-1)
return self.reduction(self.norm(x.view(B, -1, 4 * C)))
# ステージ 1 の 2 つのブロック(Swin-T:56×56 のトークン、C = 96、3 ヘッド)
stage1 = nn.Sequential(SwinBlock(96, 56, 56, heads=3, shift=0), # W-MSA
SwinBlock(96, 56, 56, heads=3, shift=3)) # SW-MSA(M // 2 = 3 ずらす)
merge = PatchMerging(96, 56, 56)
x = torch.randn(2, 56 * 56, 96)
y = merge(stage1(x))
print(y.shape) # torch.Size([2, 784, 192]):28×28 のトークン、2C = 192 次元