python コピー
import math
import torch
import torch.nn.functional as F
def scaled_dot_product_attention(q, k, v, mask=None):
"""q: [..., n, d_k], k: [..., m, d_k], v: [..., m, d_v]
mask: [..., n, m] の真偽値。True の位置を見せない"""
d_k = q.size(-1)
scores = q @ k.transpose(-2, -1) / math.sqrt(d_k) # 1〜2. 行列積とスケール [..., n, m]
if mask is not None:
scores = scores.masked_fill(mask, float("-inf")) # 3. マスク
weights = torch.softmax(scores, dim=-1) # 4. 行ごとに合計 1
return weights @ v, weights # 5. 重みで V を足し合わせる [..., n, d_v]
# 本文の表の例(d_k = 4、クエリ1つ、キー・バリュー3組)
q = torch.tensor([[1.0, 0.0, 1.0, 0.0]])
k = torch.tensor([[1.0, 0.0, 1.0, 0.0],
[0.0, 1.0, 0.0, 1.0],
[1.0, 1.0, 0.0, 0.0]])
v = torch.tensor([[1.0, 0.0],
[0.0, 1.0],
[1.0, 1.0]])
out, w = scaled_dot_product_attention(q, k, v)
print(w) # 重みは約 [0.506, 0.186, 0.307]
print(out) # 出力は約 [0.814, 0.494]
# デコーダの自己アテンション:自分より後ろの位置を見せない(バッチ 2、ヘッド 8、長さ 10、d_k = 64)
x = torch.randn(2, 8, 10, 64)
causal = torch.triu(torch.ones(10, 10, dtype=torch.bool), diagonal=1)
out, _ = scaled_dot_product_attention(x, x, x, mask=causal)
print(out.shape) # torch.Size([2, 8, 10, 64])
# PyTorch 2.0 以降の組み込み関数(FlashAttention などの速い実装を自動で選ぶ)
out2 = F.scaled_dot_product_attention(x, x, x, is_causal=True)
print(torch.allclose(out, out2, atol=1e-5)) # 同じ計算なので True になるはず