"""SI4World 模型篇05：多头与位置。固定、未训练的参数；无因果遮罩。

Python 标准库即可运行：
    python m05_multihead.py
    python m05_multihead.py --json
安装 PyTorch 后可独立核对：
    python m05_multihead.py --torch-check
"""
import json
import math
import sys

TOKENS = ["猫", "吃", "鱼"]
EMBEDDING = [[1, 0, 1, 0], [0, 1, 0, 1], [1, 1, 0, 0]]
PARAMS = {
    "Wq": [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]],
    "Wk": [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]],
    "Wv": [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 2]],
    "Wo": [[1, 0, .5, 0], [0, 1, 0, .5], [.5, 0, 1, 0], [0, .5, 0, 1]],
}


def transpose(a):
    return list(map(list, zip(*a)))


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def matmul(a, b):
    return [[dot(row, col) for col in transpose(b)] for row in a]


def softmax(row):
    exp = [math.exp(x - max(row)) for x in row]
    total = sum(exp)
    return [x / total for x in exp]


def position(p):
    return [math.sin(p), math.cos(p), math.sin(p / 100), math.cos(p / 100)]


def forward(ids=None, mode="none", slots=None):
    ids = [0, 1, 2] if ids is None else ids
    slots = list(range(len(ids))) if slots is None else slots
    if mode not in {"none", "slots", "travel"}:
        raise ValueError("Unknown position mode")
    embed = [EMBEDDING[i][:] for i in ids]
    pe = [[0] * 4 if mode == "none" else position(p) for p in slots]
    x = [[a + b for a, b in zip(row, p)] for row, p in zip(embed, pe)]
    q, k, v = [matmul(x, PARAMS[name]) for name in ["Wq", "Wk", "Wv"]]
    heads = []
    for h in range(2):
        # 沿特征轴切分；词元数量不变。
        qh, kh, vh = [[[r[2*h], r[2*h+1]] for r in a] for a in [q, k, v]]
        scores = [[s / math.sqrt(2) for s in r] for r in matmul(qh, transpose(kh))]
        a = [softmax(r) for r in scores]
        heads.append(dict(q=qh, k=kh, v=vh, scores=scores, a=a, z=matmul(a, vh)))
    concat = [heads[0]["z"][i] + heads[1]["z"][i] for i in range(len(ids))]
    output = matmul(concat, PARAMS["Wo"])
    return dict(ids=ids, mode=mode, slots=slots, embed=embed, pe=pe, x=x,
                q=q, k=k, v=v, heads=heads, concat=concat, output=output)


def max_difference(a, b):
    return max(abs(x-y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def compare(mode):
    order = [2, 1, 0]
    base = forward([0, 1, 2], mode, [0, 1, 2])
    changed = forward(order, mode, order if mode == "travel" else [0, 1, 2])
    # 按同一个词元身份对齐；不能直接拿新第一行与原第一行比较。
    aligned = [changed["output"][order.index(i)] for i in range(3)]
    return dict(base=base, changed=changed, aligned=aligned,
                maxDifference=max_difference(base["output"], aligned))


def torch_check():
    try:
        import torch
    except ImportError:
        raise SystemExit("可选核对需要 PyTorch：pip install torch；不加 --torch-check 可直接运行。")
    biggest = 0
    for mode in ["none", "slots", "travel"]:
        for ids in [[0, 1, 2], [2, 1, 0]]:
            slots = ids if mode == "travel" else [0, 1, 2]
            expected = forward(ids, mode, slots)
            x = torch.tensor(expected["x"], dtype=torch.float64)
            q, k, v = [x @ torch.tensor(PARAMS[n], dtype=torch.float64) for n in ["Wq", "Wk", "Wv"]]
            outputs = []
            for h in range(2):
                qh, kh, vh = [a[:, 2*h:2*h+2] for a in [q, k, v]]
                a = torch.softmax(qh @ kh.T / math.sqrt(2), dim=-1)
                outputs.append(a @ vh)
                biggest = max(biggest, max_difference(a.tolist(), expected["heads"][h]["a"]))
            y = torch.cat(outputs, dim=-1) @ torch.tensor(PARAMS["Wo"], dtype=torch.float64)
            biggest = max(biggest, max_difference(y.tolist(), expected["output"]))
    assert biggest < 1e-12
    return dict(states=6, maxDifference=biggest)


def main():
    modes = {m: compare(m) for m in ["none", "slots", "travel"]}
    assert modes["none"]["maxDifference"] < 1e-12
    assert modes["travel"]["maxDifference"] < 1e-12
    assert modes["slots"]["maxDifference"] > .1
    for item in modes.values():
        for h in item["changed"]["heads"]:
            for row in h["a"]:
                assert abs(sum(row)-1) < 1e-12
    if "--torch-check" in sys.argv:
        print(json.dumps(torch_check()))
    elif "--json" in sys.argv:
        print(json.dumps(dict(default=forward(), comparisons=modes), ensure_ascii=False))
    else:
        print("默认：不加位置；固定参数，未训练；无因果遮罩")
        for word, values in zip(TOKENS, forward()["output"]):
            print(word + ": " + " ".join(f"{x:.6f}" for x in values))
        for mode, item in modes.items():
            print(f"{mode}: aligned_max_difference={item['maxDifference']:.12g}")
        print("数值断言通过；--torch-check 可另用 PyTorch 核对。")


if __name__ == "__main__":
    main()
