"""One deterministic pre-LN causal Transformer block; Python standard library.

Same inputs/parameters as SI4World's Transformer lesson. This is a forward
demonstration, NOT a trained language model. Run: python m06_transformer.py
Machine-readable output and checks: python m06_transformer.py --json
"""
import json
import math
import sys

TOKENS = ["猫", "吃", "鱼", "草"]
EMBEDDING = [[1, 0, 1, 0], [0, 1, 0, 1], [1, 1, 0, 0], [0, 0, 1, 1]]


def weights(rows, cols, seed):
    return [[((i * 13 + j * 7 + seed * 3) % 17 - 8) / 12
             for j in range(cols)] for i in range(rows)]


WQ, WK, WV, WO = [weights(4, 4, seed) for seed in range(1, 5)]
W1, W2 = weights(4, 6, 5), weights(6, 4, 6)
B1, B2 = [0.1, -0.1, 0.05, 0, 0.15, -0.05], [0, 0.05, -0.05, 0.1]


def transpose(a):
    return [list(col) for col in zip(*a)]


def mm(a, b):
    return [[sum(x * y for x, y in zip(row, col))
             for col in transpose(b)] for row in a]


def add(a, b):
    return [[x + y for x, y in zip(r, s)] for r, s in zip(a, b)]


def layer_norm(a):
    # Per token, over four features. gamma=1, beta=0, epsilon=1e-5.
    result = []
    for row in a:
        mean = sum(row) / len(row)
        variance = sum((x - mean) ** 2 for x in row) / len(row)
        result.append([(x - mean) / math.sqrt(variance + 1e-5) for x in row])
    return result


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


def forward(ids=(0, 1, 2), position=True, causal=True):
    embedding = [EMBEDDING[i][:] for i in ids]
    pe = [[math.sin(i), math.cos(i), math.sin(i / 100), math.cos(i / 100)]
          if position else [0, 0, 0, 0] for i in range(len(ids))]
    x = add(embedding, pe)
    u = layer_norm(x)
    q, k, v = mm(u, WQ), mm(u, WK), mm(u, WV)
    heads = []
    for head in range(2):
        qh, kh, vh = [[r[head * 2:head * 2 + 2] for r in a] for a in (q, k, v)]
        scores = [[s / math.sqrt(2) for s in row] for row in mm(qh, transpose(kh))]
        masked = [[-math.inf if causal and j > i else s
                   for j, s in enumerate(row)] for i, row in enumerate(scores)]
        attention = [softmax(row) for row in masked]
        heads.append({"a": attention, "z": mm(attention, vh)})
    concat = [heads[0]["z"][i] + heads[1]["z"][i] for i in range(len(ids))]
    attention = mm(concat, WO)
    residual = add(x, attention)
    n2 = layer_norm(residual)
    hidden = [[max(0, x + B1[j]) for j, x in enumerate(row)] for row in mm(n2, W1)]
    ffn = [[x + B2[j] for j, x in enumerate(row)] for row in mm(hidden, W2)]
    return {"output": add(residual, ffn), "heads": heads, "x": x, "u": u,
            "q": q, "k": k, "v": v, "attention": attention,
            "residual": residual, "n2": n2, "hidden": hidden, "ffn": ffn}


def max_diff(a, b):
    return max(abs(x - y) for r, s in zip(a, b) for x, y in zip(r, s))


def checks():
    base, changed = forward(), forward((0, 1, 3))
    masked = max_diff(base["output"][:2], changed["output"][:2])
    unmasked = max_diff(forward(causal=False)["output"][:2],
                        forward((0, 1, 3), causal=False)["output"][:2])
    order = [2, 1, 0]
    no_position = forward(position=False, causal=False)["output"]
    permutation = max_diff([no_position[i] for i in order],
                           forward(order, position=False, causal=False)["output"])
    positioned = forward(causal=False)["output"]
    with_position = max_diff([positioned[i] for i in order],
                             forward(order, causal=False)["output"])
    assert masked < 1e-12, "Future token leaked into the prefix."
    assert unmasked > 1e-6, "This contrast should change without the mask."
    assert permutation < 1e-12, "Permutation equivariance failed."
    assert with_position > 1e-6, "Position encoding should change the contrast."
    for h in base["heads"]:
        for i, row in enumerate(h["a"]):
            assert abs(sum(row) - 1) < 1e-12
            assert all(row[j] == 0 for j in range(i + 1, len(row)))
    return {"maskedPrefix": masked, "openPrefix": unmasked,
            "noPositionPermutation": permutation,
            "withPositionPermutation": with_position}


if __name__ == "__main__":
    result = {"output": forward()["output"], "checks": checks()}
    if "--json" in sys.argv:
        print(json.dumps(result))
    else:
        print("Y (rows: cat, eats, fish), pre-LN / position on / causal mask on:")
        for row in result["output"]:
            print("[" + ", ".join(f"{v:.6f}" for v in row) + "]")
        print("All numerical checks passed:")
        for key, value in result["checks"].items():
            print(f"  {key}: {value:.12g}")
