python
import math
import torch
import torch.nn as nn
"""
Perceiver(論文の 3 章・付録 C)の小さな実装。
クロスアテンション(潜在配列 → 入力)と潜在の Transformer を交互に重ね、2 回目以降は重みを共有する。
"""
def fourier_features(h, w, num_bands=64, max_res=224):
"""3.2 節のフーリエ特徴:[sin(f_k π x_d), cos(f_k π x_d)] と x_d をつなげる。戻り値は [h*w, d(2K+1)]"""
ys, xs = torch.linspace(-1, 1, h), torch.linspace(-1, 1, w) # 座標を [-1, 1] に
pos = torch.stack(torch.meshgrid(ys, xs, indexing="ij"), dim=-1).view(-1, 2) # [h*w, 2]
freqs = torch.linspace(1.0, max_res / 2, num_bands) # 1 〜 μ/2 を等間隔に
x = pos[..., None] * freqs * math.pi # [h*w, 2, K]
enc = torch.cat([x.sin(), x.cos()], dim=-1).view(pos.shape[0], -1) # [h*w, 2*2K]
return torch.cat([pos, enc], dim=-1) # [h*w, 2(2K+1)]
class MLP(nn.Module):
def __init__(self, dim):
super().__init__()
self.net = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, dim), nn.GELU(), nn.Linear(dim, dim))
def forward(self, x):
return x + self.net(x) # 残差接続
class CrossAttend(nn.Module):
"""クエリは潜在配列 [B, N, D]、キーとバリューは入力 [B, M, C]。計算量は O(MN)"""
def __init__(self, latent_dim, input_dim, heads=1):
super().__init__()
self.norm_q, self.norm_kv = nn.LayerNorm(latent_dim), nn.LayerNorm(input_dim)
self.attn = nn.MultiheadAttention(latent_dim, heads, kdim=input_dim, vdim=input_dim, batch_first=True)
self.mlp = MLP(latent_dim)
def forward(self, latent, data):
kv = self.norm_kv(data)
out, _ = self.attn(self.norm_q(latent), kv, kv, need_weights=False)
return self.mlp(latent + out) # 潜在配列に残差として足す
class LatentTransformer(nn.Module):
"""潜在配列の上の自己アテンション(マスクなし)。計算量は O(N^2)"""
def __init__(self, dim, depth=6, heads=8):
super().__init__()
layer = nn.TransformerEncoderLayer(dim, heads, dim, dropout=0.0, activation="gelu",
batch_first=True, norm_first=True)
self.blocks = nn.TransformerEncoder(layer, depth)
def forward(self, x):
return self.blocks(x)
class Perceiver(nn.Module):
def __init__(self, input_dim=261, num_latents=512, latent_dim=1024, num_iters=8, depth=6, num_classes=1000):
super().__init__()
self.latents = nn.Parameter(torch.empty(num_latents, latent_dim)) # 学習する潜在配列の初期値
nn.init.trunc_normal_(self.latents, std=0.02, a=-2, b=2)
self.first_cross = CrossAttend(latent_dim, input_dim) # 1 回目は共有しない
self.shared_cross = CrossAttend(latent_dim, input_dim) # 2 回目以降で共有
self.latent_tf = LatentTransformer(latent_dim, depth) # すべての回で共有
self.num_iters = num_iters
self.head = nn.Linear(latent_dim, num_classes)
def forward(self, data): # data:[B, M, C]
z = self.latents.expand(data.shape[0], -1, -1)
for i in range(self.num_iters):
z = (self.first_cross if i == 0 else self.shared_cross)(z, data)
z = self.latent_tf(z)
return self.head(z.mean(dim=1)) # N 個を平均して線形層
# 小さな例:32×32 の画像(M = 1024)、RGB + フーリエ特徴(K = 16 → 2×33 = 66 次元)
img = torch.randn(2, 32 * 32, 3)
pos = fourier_features(32, 32, num_bands=16, max_res=32).expand(2, -1, -1)
data = torch.cat([img, pos], dim=-1) # 足さずにつなげる:[2, 1024, 69]
model = Perceiver(input_dim=69, num_latents=64, latent_dim=128, num_iters=2, depth=2, num_classes=10)
model.train()
logits = model(data) # [2, 10]