python コピー
import torch
import torch.nn.functional as F
"""
Mistral 7B のアテンションまわりの工夫を、論文の 2 章に沿って小さく書いた例
1. スライディングウィンドウの先を隠すマスク:位置 i は i-W < j <= i の j だけを見る
2. GQA:K・V のヘッドを、クエリのヘッドの数に合わせて繰り返す(32 / 8 = 4 回)
3. ローリングバッファキャッシュ:位置 i の K・V をキャッシュの i mod W 番目に書く
最後に、Hugging Face transformers で学習済みのモデルを使う例
"""
# --- 1. スライディングウィンドウのマスク ---
def sliding_window_mask(n, window):
i = torch.arange(n).unsqueeze(1)
j = torch.arange(n).unsqueeze(0)
return (j <= i) & (j > i - window) # True のところだけを見る
print(sliding_window_mask(6, 3).int()) # 頭の図の左下と同じ(W = 3)
# --- 2. GQA とスライディングウィンドウのアテンション ---
def sliding_window_gqa(q, k, v, window):
# q: [batch, 32, n, 128]、k・v: [batch, 8, n, 128]
rep = q.shape[1] // k.shape[1] # 1 つの K・V を共有するクエリのヘッドの数(4)
k = k.repeat_interleave(rep, dim=1)
v = v.repeat_interleave(rep, dim=1)
mask = sliding_window_mask(q.shape[2], window).to(q.device)
return F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
q = torch.randn(1, 32, 10, 128)
k, v = torch.randn(1, 8, 10, 128), torch.randn(1, 8, 10, 128)
print(sliding_window_gqa(q, k, v, window=4).shape) # torch.Size([1, 32, 10, 128])
# --- 3. ローリングバッファキャッシュ ---
class RollingKVCache:
def __init__(self, window, n_kv_heads=8, head_dim=128):
self.window = window
self.k = torch.zeros(window, n_kv_heads, head_dim)
self.v = torch.zeros(window, n_kv_heads, head_dim)
self.length = 0 # これまでに入れたトークンの数
def update(self, k_t, v_t):
slot = self.length % self.window # 位置 i は i mod W 番目に書く(古い値を上書き)
self.k[slot], self.v[slot] = k_t, v_t
self.length += 1
def get(self):
# 古い順に並べ直して返す。大きさは最大 W 個で、それ以上増えない
n = min(self.length, self.window)
order = [(self.length - n + t) % self.window for t in range(n)]
return self.k[order], self.v[order]
cache = RollingKVCache(window=4)
for t in range(6):
cache.update(torch.full((8, 128), float(t)), torch.full((8, 128), float(t)))
k_cached, _ = cache.get()
print(k_cached[:, 0, 0]) # tensor([2., 3., 4., 5.]):直前の 4 個だけが残る
# --- 4. 学習済みの Mistral 7B を使う ---
from transformers import AutoTokenizer, AutoModelForCausalLM
name = "mistralai/Mistral-7B-v0.1" # 論文のベースのモデル
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, torch_dtype=torch.float16, device_map="auto")
model.eval()
print(model.config.sliding_window, model.config.num_key_value_heads) # 4096 8
enc = tokenizer("Sliding window attention is", return_tensors="pt").to(model.device)
with torch.no_grad():
out = model.generate(**enc, max_new_tokens=40)
print(tokenizer.decode(out[0], skip_special_tokens=True))