python コピー
import torch
import torch.nn as nn
"""
Universal Transformer のエンコーダ(論文の式 (4)〜(7))を小さく書いた例。
1つのエンコーダ層を T 回くり返し通し、毎ステップ「位置と時刻のエンコーディング」P^t を足す。
act=True にすると、付録 C の動的停止(ACT)で位置ごとに回数を決める。
"""
def coordinate_embedding(m, t, d, device=None):
# 式 (6)(7):位置 i と時刻 t の正弦波の埋め込みを足す(i, t は 1 から数える)
i = torch.arange(1, m + 1, device=device, dtype=torch.float32).unsqueeze(1) # [m, 1]
j = torch.arange(0, d, 2, device=device, dtype=torch.float32) # 2j
div = torch.pow(10000.0, j / d) # 10000^{2j/d}
tt = torch.tensor(float(t), device=device)
P = torch.zeros(m, d, device=device)
P[:, 0::2] = torch.sin(i / div) + torch.sin(tt / div)
P[:, 1::2] = torch.cos(i / div) + torch.cos(tt / div)
return P # [m, d]
class UTBlock(nn.Module):
"""1 ステップの計算:A^t = LN(x + MHSA(x))、H^t = LN(A^t + Transition(A^t))(x = H^{t-1} + P^t)"""
def __init__(self, d=512, heads=8, d_ff=2048, dropout=0.1):
super().__init__()
self.attn = nn.MultiheadAttention(d, heads, dropout=dropout, batch_first=True)
self.ln1 = nn.LayerNorm(d)
self.transition = nn.Sequential( # 全結合の遷移関数(ReLU を挟む 2 つのアフィン変換)
nn.Linear(d, d_ff), nn.ReLU(), nn.Linear(d_ff, d))
self.ln2 = nn.LayerNorm(d)
self.drop = nn.Dropout(dropout)
def forward(self, x, pad_mask=None):
a, _ = self.attn(x, x, x, key_padding_mask=pad_mask, need_weights=False)
A = self.ln1(x + self.drop(a))
return self.ln2(A + self.drop(self.transition(A)))
class UniversalTransformerEncoder(nn.Module):
def __init__(self, vocab_size, d=512, heads=8, d_ff=2048, T=6, act=False, threshold=0.99, dropout=0.1):
super().__init__()
self.embed = nn.Embedding(vocab_size, d)
self.block = UTBlock(d, heads, d_ff, dropout) # 重みは 1 組だけ。T 回くり返して使う
self.T, self.act, self.threshold, self.d = T, act, threshold, d
if act:
self.halt = nn.Linear(d, 1) # 停止の確率 p(全結合層 + シグモイド)
def forward(self, ids, pad_mask=None):
h = self.embed(ids) # H^0:[バッチ, m, d]
m = ids.size(1)
if not self.act:
for t in range(1, self.T + 1):
h = self.block(h + coordinate_embedding(m, t, self.d, h.device), pad_mask)
return h
# 動的停止(付録 C の手順)。T は最大の回数として使う
B = ids.size(0)
halting = torch.zeros(B, m, device=h.device)
remainders = torch.zeros(B, m, device=h.device)
n_updates = torch.zeros(B, m, device=h.device)
state = h
for t in range(1, self.T + 1):
if not ((halting < self.threshold).any()):
break
x = state + coordinate_embedding(m, t, self.d, h.device)
p = torch.sigmoid(self.halt(x)).squeeze(-1) # [B, m]
still = (halting < 1.0).float()
new_halted = ((halting + p * still) > self.threshold).float() * still
still = ((halting + p * still) <= self.threshold).float() * still
halting = halting + p * still
remainders = remainders + new_halted * (1 - halting)
halting = halting + new_halted * remainders
n_updates = n_updates + still + new_halted
w = (p * still + new_halted * remainders).unsqueeze(-1) # 0:止まった位置、p:続く位置、残り:今止まった位置
transformed = self.block(x, pad_mask)
state = transformed * w + state * (1 - w) # 止まった位置(w=0)は状態をそのまま写す
self.ponder = n_updates # 位置ごとの回数(ACT の罰則項などに使う)
return state
model = UniversalTransformerEncoder(vocab_size=1000, d=64, heads=4, d_ff=128, T=6, act=True)
model.train() # ドロップアウトが効く
ids = torch.randint(0, 1000, (2, 10))
out = model(ids)
print(out.shape) # torch.Size([2, 10, 64])
model.eval() # 推論ではドロップアウトを止める
# パラメータの数は T を変えても同じ(1 つのブロックを使い回すため)
print(sum(p.numel() for p in model.parameters()))