python コピー
import torch
import torch.nn as nn
"""
NAMMs の 1 回の実行(論文の Algorithm 1・2、式 (3)(4))を小さく書いた例。
基のモデルの 1 つの層・1 つのヘッドについて、アテンション行列から特徴を作り、BAM でスコアを出し、s_i < 0 のトークンを捨てる。
残差とかけ算による結合の細部は、論文の説明(出力を 2 倍の次元にして戻す)に沿った簡単な形にしている。
"""
N_UP, N_W, S_W, GAMMA, POS_DIM = 512, 32, 16, 0.9916, 8
N_FREQ = N_W // 2 + 1 # 17 個の周波数
def attention_spectrogram(A):
# A: [クエリ 512, キャッシュのトークン n]。列ごと(トークンごと)に STFT をかけ、周波数の大きさをとる
cols = A.T # [n, 512]
spec = torch.stft(cols, n_fft=N_W, hop_length=S_W, window=torch.hann_window(N_W),
center=False, return_complex=True).abs() # [n, 17, 区間の数]
return spec
def ema_reduce(spec, prev):
# 式 (4):区間の方向を指数移動平均でまとめ、前回の値 prev も割り引いて足す
n_t = spec.shape[-1]
w = GAMMA ** torch.arange(n_t, dtype=spec.dtype) # γ^{t-1}
return (spec * w).sum(-1) + (GAMMA ** n_t) * prev # [n, 17]
def oldness_features(age):
# 古さ(キャッシュに入ってから見たクエリの数)の 8 次元の正弦波の特徴
i = torch.arange(POS_DIM // 2, dtype=torch.float32)
freq = 1.0 / (10000 ** (2 * i / POS_DIM))
ang = age.float().unsqueeze(-1) * freq
return torch.cat([torch.sin(ang), torch.cos(ang)], dim=-1)
class BAM(nn.Module):
"""逆向きのマスクの自己アテンション(ヘッド 1 つ、レイヤー正規化なし)→ 残差とかけ算で結合 → 線形層"""
def __init__(self, d_in=N_FREQ + POS_DIM, d_hidden=16):
super().__init__()
self.q = nn.Linear(d_in, d_hidden)
self.k = nn.Linear(d_in, d_hidden)
self.v = nn.Linear(d_in, 2 * d_in) # 出力は特徴の 2 倍の次元
self.out = nn.Linear(d_in, 1)
self.d_hidden = d_hidden
def forward(self, x): # x: [n, d_in](古い順に並ぶ)
n = x.shape[0]
att = self.q(x) @ self.k(x).T / self.d_hidden ** 0.5
older = torch.tril(torch.ones(n, n, dtype=torch.bool), diagonal=-1)
att = att.masked_fill(older, float("-inf")) # 自分より古いトークンは見ない(自分と新しいトークンだけ)
o = torch.softmax(att, dim=-1) @ self.v(x) # [n, 2 * d_in]
add, mul = o.chunk(2, dim=-1)
h = x + add + x * mul # 残差とかけ算による結合
return self.out(h).squeeze(-1) # スコア s_i
@torch.no_grad()
def namm_step(A, k_cache, v_cache, prev_feat, age, bam):
# A: [512, n]、k_cache / v_cache: [n, d_head]、prev_feat: [n, 17]、age: [n]
feat = ema_reduce(attention_spectrogram(A), prev_feat)
x = torch.cat([feat, oldness_features(age)], dim=-1)
# 論文では特徴を学習データで分散 1 にそろえる(ここでは省略)
keep = bam(x) >= 0 # s_i < 0 のトークンを捨てる
return k_cache[keep], v_cache[keep], feat[keep], age[keep]
bam = BAM()
print(sum(p.numel() for p in bam.parameters())) # 数千ほどの小さなネットワーク
n, d_head = 1000, 128
A = torch.softmax(torch.randn(N_UP, n), dim=-1)
k, v = torch.randn(n, d_head), torch.randn(n, d_head)
k, v, feat, age = namm_step(A, k, v, torch.zeros(n, N_FREQ), torch.arange(n, 0, -1), bam)
print(k.shape) # 残ったトークンの数だけになる
# 学習は勾配を使わない CMA-ES(pip install cma)。evaluate は「NAMMs をつけた基のモデルの、正規化した成績」を返す関数
# import cma
# x0 = torch.nn.utils.parameters_to_vector(bam.parameters()).numpy()
# es = cma.CMAEvolutionStrategy(x0, 0.65, {"popsize": 32})
# while not es.stop():
# cands = es.ask()
# es.tell(cands, [-evaluate(c) for c in cands]) # cma は最小化するので符号を反転する