python コピー
import torch
import torch.nn as nn
import torch.nn.functional as F
class LuongAttention(nn.Module):
"""Luong らの大域アテンション。score は "dot"(h_tᵀ h̄_s)か "general"(h_tᵀ W_a h̄_s)
PyTorch に組み込みのモジュールはないので、論文の式どおりに書く(ドロップアウトがないので train / eval で挙動は変わらない)"""
def __init__(self, dec_dim=1000, enc_dim=1000, score="dot"):
super().__init__()
self.score = score
if score == "dot":
assert dec_dim == enc_dim, "dot は h_t と h̄_s の長さが同じでないと計算できない"
else:
self.W_a = nn.Linear(enc_dim, dec_dim, bias=False) # W_a
self.W_c = nn.Linear(enc_dim + dec_dim, dec_dim, bias=False) # 式(5) の W_c
def forward(self, h_t, h_s, mask=None):
"""h_t: [B, T_y, d](デコーダの各時刻の状態)、h_s: [B, S, d_enc](エンコーダの状態)
mask: [B, S] の真偽値(True はパディングで見せない)"""
keys = h_s if self.score == "dot" else self.W_a(h_s)
scores = h_t @ keys.transpose(1, 2) # [B, T_y, S](行列積 1 回)
if mask is not None:
scores = scores.masked_fill(mask[:, None, :], float("-inf"))
a = torch.softmax(scores, dim=-1) # 重み a_t(s)
c = a @ h_s # 文脈ベクトル c_t [B, T_y, d_enc]
h_tilde = torch.tanh(self.W_c(torch.cat([c, h_t], dim=-1))) # 式(5)
return h_tilde, a
B, S, T_y, d = 2, 9, 4, 1000
h_s = torch.randn(B, S, d)
h_t = torch.randn(B, T_y, d)
pad = torch.zeros(B, S, dtype=torch.bool)
pad[1, 6:] = True
attn = LuongAttention(score="dot")
h_tilde, a = attn(h_t, h_s, mask=pad)
print(h_tilde.shape, a.shape) # torch.Size([2, 4, 1000]) torch.Size([2, 4, 9])
# dot のスコアと重み付きの平均は、割り算をしない内積アテンションと同じ。
# F.scaled_dot_product_attention は既定で 1/√d をかけるので、scale=1.0 を渡すと dot と一致する
# (attn_mask の True は「見せる」。nn.MultiheadAttention とは逆)
c_ref = F.scaled_dot_product_attention(h_t, h_s, h_s, attn_mask=~pad[:, None, :], scale=1.0)
print(torch.allclose(c_ref, a @ h_s, atol=1e-5)) # True になるはず