"""SI4World 第 4 课 注意力机制：完整代码

和网页上用的是同一组数字。运行：
    pip install torch
    python attention.py
"""

# ============================================================
# 第 2 步：词向量与点积
# ============================================================
import torch

# 固定、未训练的教学参数；本实验只验证遮罩是否阻断未来信息。
def future_word_probe(changed=False, causal=False):
    X = torch.tensor([[1., 0.], [0., 1.], [2. if changed else 1., 1.]], dtype=torch.float64)
    WQ = torch.tensor([[1., 0.], [0., 2.]], dtype=torch.float64)
    WK = torch.tensor([[0., 1.], [1., 0.]], dtype=torch.float64)
    WV = torch.tensor([[2., 0.], [0., 1.]], dtype=torch.float64)
    Q, K, V = X @ WQ, X @ WK, X @ WV
    scores = Q @ K.T / (2 ** 0.5)
    if causal:
        mask = torch.triu(torch.ones(3, 3, dtype=torch.bool), diagonal=1)
        scores = scores.masked_fill(mask, float("-inf"))
    weights = torch.softmax(scores, dim=-1)
    output = weights @ V
    return {"Q": Q.tolist(), "K": K.tolist(), "V": V.tolist(), "A": weights.tolist(), "O": output.tolist()}

# 用于网页与 PyTorch 的数值核对；默认运行仍显示完整教学过程。
import sys
if "--probe-json" in sys.argv:
    import json
    print(json.dumps([dict(changed=changed, masked=causal, **future_word_probe(changed, causal))
                      for causal in (False, True) for changed in (False, True)]))
    sys.exit(0)

# 句子“苹果 发布 了 新 手机”，每个词两个数：(和科技多相关, 和食物多相关)
words = ["苹果", "发布", "了", "新", "手机"]
X = torch.tensor([[0.50, 0.50],
                  [0.90, 0.05],
                  [0.10, 0.08],
                  [0.35, 0.15],
                  [1.00, 0.12]])

# 点积：对应位置相乘再相加。@ 就是点积 / 矩阵乘法
print(X[4] @ X[1])   # 手机 · 发布
print(X[4] @ X[2])   # 手机 · 了

# ============================================================
# 第 3 步：苹果的 Query
# ============================================================
# 苹果的 Query：想找“能说明我是哪种苹果”的词
q = torch.tensor([0.75, 0.75])

# 为了好画，这里每个词的 Key 和 Value 都直接用它的词向量
K = X
V = X

# ============================================================
# 第 4 步：打分
# ============================================================
# 用 Query 和每个词的 Key 做点积，一次算完 5 个分数
scores = K @ q
print(scores)

# ============================================================
# 第 5 步：softmax 换算成权重
# ============================================================
# softmax：先乘锐度 3，再换算成加起来等于 1 的比例
weights = torch.softmax(3 * scores, dim=0)
print(weights)
print(weights.sum())

# ============================================================
# 第 6 步：按权重读取 Value
# ============================================================
# 按权重把每个词的 Value 加起来：新的“苹果”
new_apple = weights @ V
print(new_apple)

# ============================================================
# 第 7 步：换一个句子
# ============================================================
# 换一个句子：“我 吃 了 甜 苹果”，Query 不变
X2 = torch.tensor([[0.12, 0.10],
                   [0.05, 0.90],
                   [0.10, 0.08],
                   [0.12, 1.00],
                   [0.50, 0.50]])
w2 = torch.softmax(3 * (X2 @ q), dim=0)
print(w2 @ X2)

# ============================================================
# 写成矩阵：一次算完所有词
# ============================================================
import math

# 三个词“我 吃 苹果”，每个词 2 个数
X = torch.tensor([[1., 0.], [0., 1.], [1., 1.]])
W_Q = torch.tensor([[1., 0.], [0., 2.]])
W_K = torch.tensor([[0., 1.], [1., 0.]])
W_V = torch.tensor([[2., 0.], [0., 1.]])

Q, K, V = X @ W_Q, X @ W_K, X @ W_V
scores = Q @ K.T / math.sqrt(2)           # 3×3：每个词对每个词的分数
weights = torch.softmax(scores, dim=-1)   # 每一行加起来等于 1
out = weights @ V
print(out)

# ============================================================
# 因果遮罩
# ============================================================
# 因果遮罩：上三角（看后面的位置）设为负无穷
mask = torch.triu(torch.ones(3, 3), diagonal=1).bool()
masked = scores.masked_fill(mask, float("-inf"))
print(torch.softmax(masked, dim=-1))

# ============================================================
# 对照 PyTorch 自带的注意力
# ============================================================
import torch.nn.functional as F

# PyTorch 自带的注意力函数，结果和我们手写的一模一样
print(F.scaled_dot_product_attention(Q, K, V))

# ============================================================
# 为什么要除以 √d
# ============================================================
# 128 维的随机 Query 和 Key，看点积有多大
torch.manual_seed(0)
d = 128
q_rand = torch.randn(10000, d)
k_rand = torch.randn(10000, d)
dots = (q_rand * k_rand).sum(dim=1)
print(dots.std())                   # 约等于 √128 ≈ 11.3
print((dots / math.sqrt(d)).std())  # 除以 √d 之后约等于 1

# ============================================================
# 只换未来词：比较“我”和“吃”的输出
# ============================================================
for causal in (False, True):
    before = torch.tensor(future_word_probe(False, causal)["O"])
    after = torch.tensor(future_word_probe(True, causal)["O"])
    delta = (before[:2] - after[:2]).abs().max().item()
    print(f"causal={causal}, first_two_max_change={delta:.6f}")
# 无遮罩：前两行会变；有遮罩：前两行差值恰好为 0。
