python コピー
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiHeadAttention(nn.Module):
"""論文の式どおりのマルチヘッドアテンション(h 個の線形層を1つの大きな線形層にまとめた形)"""
def __init__(self, d_model=512, num_heads=8, dropout=0.1):
super().__init__()
assert d_model % num_heads == 0, "d_model はヘッドの数で割り切れる必要がある"
self.h = num_heads
self.d_k = d_model // num_heads
self.w_q = nn.Linear(d_model, d_model) # W_1^Q, ..., W_h^Q をまとめたもの
self.w_k = nn.Linear(d_model, d_model)
self.w_v = nn.Linear(d_model, d_model)
self.w_o = nn.Linear(d_model, d_model) # W^O
self.dropout = dropout
def split(self, x):
# [B, N, d_model] -> [B, h, N, d_k](ヘッドごとに切り分ける)
B, N, _ = x.shape
return x.view(B, N, self.h, self.d_k).transpose(1, 2)
def forward(self, q, k, v, is_causal=False):
q, k, v = self.split(self.w_q(q)), self.split(self.w_k(k)), self.split(self.w_v(v))
# ヘッドごとのスケール化内積アテンション。dropout は学習のときだけかける
# (F.scaled_dot_product_attention は model.eval() を見ないので、自分で 0 にする)
out = F.scaled_dot_product_attention(
q, k, v, dropout_p=self.dropout if self.training else 0.0, is_causal=is_causal
)
B, _, N, _ = out.shape
out = out.transpose(1, 2).reshape(B, N, self.h * self.d_k) # 連結 [B, N, h*d_k]
return self.w_o(out)
x = torch.randn(2, 10, 512) # [バッチ, 系列の長さ, d_model]
mha = MultiHeadAttention()
mha.eval()
print(mha(x, x, x, is_causal=True).shape) # torch.Size([2, 10, 512])
# PyTorch の組み込み:nn.MultiheadAttention
attn = nn.MultiheadAttention(embed_dim=512, num_heads=8, dropout=0.1, batch_first=True)
# batch_first の既定は False([系列, バッチ, d] の順)。[バッチ, 系列, d] で渡すなら True にする
attn.eval()
# attn_mask の True は「見せない」(F.scaled_dot_product_attention とは逆)
causal = torch.triu(torch.ones(10, 10, dtype=torch.bool), diagonal=1)
# key_padding_mask の True は「パディングなので見せない」キー [バッチ, 系列]
pad = torch.zeros(2, 10, dtype=torch.bool)
pad[1, 8:] = True
out, w = attn(x, x, x, attn_mask=causal, key_padding_mask=pad)
print(out.shape, w.shape) # [2, 10, 512] と [2, 10, 10](重みは既定でヘッドの平均)
out, w = attn(x, x, x, attn_mask=causal, need_weights=True, average_attn_weights=False)
print(w.shape) # [2, 8, 10, 10]:ヘッドごとの重み
# 重みが要らないときは need_weights=False(速い実装を使える)
out, w = attn(x, x, x, attn_mask=causal, need_weights=False)
print(w) # None