python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def relative_position_bucket(rel: torch.Tensor, bidirectional: bool = True,
num_buckets: int = 32, max_distance: int = 128) -> torch.Tensor:
"""距離 rel = j - i(キーの位置 - クエリの位置)をバケットの番号にする(Mesh TensorFlow の実装と同じ)"""
bucket = torch.zeros_like(rel)
if bidirectional: # エンコーダ:前と後ろで半分ずつ
num_buckets //= 2
bucket += (rel > 0).long() * num_buckets
n = rel.abs()
else: # デコーダ:前(j <= i)だけ
n = (-rel).clamp(min=0)
max_exact = num_buckets // 2 # 半分は距離 1 つずつ
is_small = n < max_exact
# 残りの半分は、距離の対数に比例して max_distance まで広がる
large = max_exact + (
torch.log(n.float().clamp(min=1) / max_exact) / math.log(max_distance / max_exact)
* (num_buckets - max_exact)
).long()
large = large.clamp(max=num_buckets - 1)
return bucket + torch.where(is_small, n, large)
class T5RelativeBias(nn.Module):
"""バケットごと・ヘッドごとの数値を学習し、[1, heads, n_q, n_k] のバイアスを返す。全層で 1 つを共有する"""
def __init__(self, n_heads: int, num_buckets: int = 32, max_distance: int = 128, bidirectional: bool = True):
super().__init__()
self.num_buckets, self.max_distance, self.bidirectional = num_buckets, max_distance, bidirectional
self.bias = nn.Embedding(num_buckets, n_heads)
def forward(self, n_q: int, n_k: int) -> torch.Tensor:
rel = torch.arange(n_k)[None, :] - torch.arange(n_q)[:, None] # j - i
b = relative_position_bucket(rel, self.bidirectional, self.num_buckets, self.max_distance)
return self.bias(b).permute(2, 0, 1).unsqueeze(0) # [1, heads, n_q, n_k]
# 距離 0, 1, 7, 8, 12, 20, 50, 100, 200 のバケット(後ろ側は 16 を足した番号になる)
print(relative_position_bucket(torch.tensor([0, 1, 7, 8, 12, 20, 50, 100, 200])))
# tensor([ 0, 17, 23, 24, 25, 26, 29, 31, 31])
# アテンションで使う:入力に位置の埋め込みは足さない
B, h, n, d = 2, 8, 16, 64
rel_bias = T5RelativeBias(n_heads=h) # モデル全体で 1 つ
q, k, v = (torch.randn(B, h, n, d) for _ in range(3))
# attn_mask に浮動小数の行列を渡すと、スコアに足される。T5 の実装に合わせて √d で割らない(scale=1.0)
out = F.scaled_dot_product_attention(q, k, v, attn_mask=rel_bias(n, n), scale=1.0)
print(out.shape) # torch.Size([2, 8, 16, 64])