python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
Autoformer の部品の小さな実装(論文 arXiv:2106.13008 の式 1・式 6・式 8 に沿う)
"""
class SeriesDecomp(nn.Module):
"""系列分解(式 1):傾向 = 移動平均、季節 = 元 − 傾向。長さが変わらないよう端の値で埋める"""
def __init__(self, kernel_size=25): # 移動平均の幅はハイパーパラメータ(ここでは例として 25)
super().__init__()
self.k = kernel_size
self.avg = nn.AvgPool1d(kernel_size, stride=1)
def forward(self, x): # x: [B, L, d]
front = x[:, :1].repeat(1, (self.k - 1) // 2, 1)
end = x[:, -1:].repeat(1, self.k // 2, 1)
trend = self.avg(torch.cat([front, x, end], dim=1).transpose(1, 2)).transpose(1, 2)
return x - trend, trend # 季節, 傾向
class AutoCorrelation(nn.Module):
"""自己相関(式 6・式 8):FFT で自己相関を求め、上位 k 個の遅れだけ V を回転させて重み付きで足す"""
def __init__(self, d_model=512, n_heads=8, c=3):
super().__init__()
self.h, self.c = n_heads, c
self.q, self.k, self.v = (nn.Linear(d_model, d_model) for _ in range(3))
self.out = nn.Linear(d_model, d_model)
def forward(self, xq, xkv):
B, L, D = xq.shape
# エンコーダの出力を参照するときは、K・V の長さをクエリの長さ L にそろえる(足りなければ 0 で埋める)
xkv = xkv[:, -L:] if xkv.size(1) >= L else F.pad(xkv, (0, 0, 0, L - xkv.size(1)))
q = self.q(xq).view(B, L, self.h, -1)
k = self.k(xkv).view(B, L, self.h, -1)
v = self.v(xkv).view(B, L, self.h, -1)
# ウィーナー・ヒンチンの定理:R(τ) = F^{-1}( F(Q) · conj(F(K)) )。すべての遅れを一度に出す
qf = torch.fft.rfft(q, dim=1)
kf = torch.fft.rfft(k, dim=1)
corr = torch.fft.irfft(qf * torch.conj(kf), n=L, dim=1) # [B, L(遅れ τ), h, dk]
# 上位 k = ⌊c·log L⌋ 個の遅れを選ぶ(ここではヘッドとチャネルで平均した自己相関で選ぶ)
top_k = max(1, int(self.c * math.log(L)))
mean_corr = corr.mean(dim=(2, 3)) # [B, L]
weights, delays = mean_corr.topk(top_k, dim=-1) # [B, k]
weights = torch.softmax(weights, dim=-1)
# 時間遅れの集約:V を τ だけ回転させ(Roll)、重みを掛けて足す
out = torch.zeros_like(v)
for b in range(B):
for i in range(top_k):
out[b] += torch.roll(v[b], shifts=-int(delays[b, i]), dims=0) * weights[b, i]
return self.out(out.reshape(B, L, D))
class EncoderLayer(nn.Module):
"""エンコーダの層(式 3):自己相関 + 残差 → 分解 → FF + 残差 → 分解。傾向は捨て、季節を返す"""
def __init__(self, d_model=512, d_ff=2048, dropout=0.05):
super().__init__()
self.attn = AutoCorrelation(d_model)
self.ff = nn.Sequential(nn.Linear(d_model, d_ff), nn.GELU(), nn.Dropout(dropout), nn.Linear(d_ff, d_model))
self.decomp1, self.decomp2 = SeriesDecomp(), SeriesDecomp()
self.drop = nn.Dropout(dropout)
def forward(self, x):
x, _ = self.decomp1(x + self.drop(self.attn(x, x)))
x, _ = self.decomp2(x + self.drop(self.ff(x)))
return x
# 使い方:デコーダの入力(式 2)を作り、エンコーダの層に通す
I, O, C, d = 96, 336, 7, 512
past = torch.randn(32, I, C) # 過去の窓 [B, I, 変数]
seasonal, trend = SeriesDecomp()(past[:, I // 2:]) # 過去の窓の後ろ半分を分解
seasonal_init = torch.cat([seasonal, torch.zeros(32, O, C)], dim=1) # 季節:0 で埋める
trend_init = torch.cat([trend, past.mean(dim=1, keepdim=True).repeat(1, O, 1)], dim=1) # 傾向:平均で埋める
embed = nn.Linear(C, d) # 簡単のため線形の埋め込み
layer = EncoderLayer(d)
layer.train() # ドロップアウトは学習のときだけ効く
enc_out = layer(embed(past)) # [32, 96, 512]
layer.eval()
with torch.no_grad():
enc_out = layer(embed(past))