"""Deterministic CPU/float64 self-attention and 2-head MHA comparison.

No training, corpus, positional encoding, mask, benchmark, or performance claim.
"""
from __future__ import annotations

import json
import platform
import numpy as np
import torch
from torch import nn


def softmax_last(scores: np.ndarray) -> np.ndarray:
    """Stable softmax over the final (key) axis."""
    shifted = scores - np.max(scores, axis=-1, keepdims=True)
    exp_scores = np.exp(shifted)
    return exp_scores / np.sum(exp_scores, axis=-1, keepdims=True)


def rounded(array, digits: int = 12):
    return np.round(np.asarray(array, dtype=np.float64), digits).tolist()


def shape(array):
    return list(np.asarray(array).shape)


def main() -> None:
    # Three token vectors, d_model=4. The same X is Q/K/V input: self-attention.
    x = np.array([
        [0.2, -0.4,  1.0,  0.5],
        [1.1,  0.3, -0.2,  0.8],
        [-0.7, 1.2,  0.4, -0.1],
    ], dtype=np.float64)

    # Dense, non-identity/non-diagonal matrices, stored as [out_features, in_features].
    w_q = np.array([
        [ 0.50, -0.20,  0.30,  0.10],
        [-0.40,  0.60,  0.20, -0.30],
        [ 0.10,  0.20, -0.50,  0.40],
        [ 0.30, -0.10,  0.60,  0.20],
    ], dtype=np.float64)
    w_k = np.array([
        [ 0.20,  0.40, -0.30,  0.10],
        [-0.10,  0.50,  0.20, -0.20],
        [ 0.60, -0.30,  0.10,  0.40],
        [-0.20,  0.10,  0.50,  0.30],
    ], dtype=np.float64)
    w_v = np.array([
        [ 0.40,  0.20, -0.10,  0.30],
        [ 0.10, -0.50,  0.60,  0.20],
        [-0.20,  0.30,  0.40, -0.10],
        [ 0.50,  0.10,  0.20, -0.40],
    ], dtype=np.float64)
    b_q = np.array([0.10, -0.05, 0.20, 0.15], dtype=np.float64)
    b_k = np.array([-0.10, 0.07, 0.03, 0.12], dtype=np.float64)
    b_v = np.array([0.02, 0.10, -0.08, 0.05], dtype=np.float64)
    w_o = np.array([
        [ 0.70, -0.20,  0.10,  0.30],
        [-0.30,  0.40,  0.50, -0.10],
        [ 0.20,  0.60, -0.40,  0.15],
        [ 0.10, -0.35,  0.20,  0.55],
    ], dtype=np.float64)
    b_o = np.array([0.05, -0.02, 0.07, -0.04], dtype=np.float64)

    seq_len, d_model = x.shape
    num_heads = 2
    head_dim = d_model // num_heads
    assert d_model % num_heads == 0

    # Linear projections: each token x_t maps independently to q_t, k_t, and v_t.
    q = x @ w_q.T + b_q
    k = x @ w_k.T + b_k
    v = x @ w_v.T + b_v
    # Split final feature dimension into heads: [T, H, Dh] -> [H, T, Dh].
    qh = q.reshape(seq_len, num_heads, head_dim).transpose(1, 0, 2)
    kh = k.reshape(seq_len, num_heads, head_dim).transpose(1, 0, 2)
    vh = v.reshape(seq_len, num_heads, head_dim).transpose(1, 0, 2)

    # Per-head scaled dot product: [H, T, Dh] @ [H, Dh, T] -> [H, T, T].
    raw_scores = qh @ kh.transpose(0, 2, 1)
    scores = raw_scores / np.sqrt(head_dim)
    weights = softmax_last(scores)
    contexts = weights @ vh                         # [H, T, Dh]
    concatenated = contexts.transpose(1, 0, 2).reshape(seq_len, d_model)
    output = concatenated @ w_o.T + b_o            # output projection W_O

    # PyTorch expects [batch, sequence, feature] when batch_first=True.
    torch.set_num_threads(1)
    tx = torch.tensor(x[None, :, :], dtype=torch.float64, device="cpu")
    mha = nn.MultiheadAttention(
        embed_dim=d_model,
        num_heads=num_heads,
        dropout=0.0,
        bias=True,
        batch_first=True,
        device="cpu",
        dtype=torch.float64,
    )
    with torch.no_grad():
        # PyTorch packs Q/K/V projection weights and biases as [3*E, E] / [3*E].
        mha.in_proj_weight.copy_(torch.tensor(np.concatenate([w_q, w_k, w_v], axis=0)))
        mha.in_proj_bias.copy_(torch.tensor(np.concatenate([b_q, b_k, b_v], axis=0)))
        mha.out_proj.weight.copy_(torch.tensor(w_o))
        mha.out_proj.bias.copy_(torch.tensor(b_o))
    mha.eval()
    with torch.no_grad():
        torch_output, torch_weights = mha(
            tx, tx, tx,
            need_weights=True,
            average_attn_weights=False,
        )
        projected = torch.nn.functional.linear(tx, mha.in_proj_weight, mha.in_proj_bias)
        tq, tk, tv = projected.chunk(3, dim=-1)
        tqh = tq.reshape(1, seq_len, num_heads, head_dim).permute(0, 2, 1, 3)
        tkh = tk.reshape(1, seq_len, num_heads, head_dim).permute(0, 2, 1, 3)
        torch_scores = torch.matmul(tqh, tkh.transpose(-2, -1)) / np.sqrt(head_dim)
        torch_head_weights = torch.softmax(torch_scores, dim=-1)

    # Independent numeric checks: this is a single deterministic hand-set case.
    max_score_diff = float(np.max(np.abs(scores - torch_scores[0].cpu().numpy())))
    max_weight_diff = float(np.max(np.abs(weights - torch_weights[0].cpu().numpy())))
    max_projected_q_diff = float(np.max(np.abs(q - tq[0].cpu().numpy())))
    max_projected_k_diff = float(np.max(np.abs(k - tk[0].cpu().numpy())))
    max_projected_v_diff = float(np.max(np.abs(v - tv[0].cpu().numpy())))
    max_output_diff = float(np.max(np.abs(output - torch_output[0].cpu().numpy())))
    tolerance = 1e-12
    assert max_score_diff < tolerance
    assert max_weight_diff < tolerance
    assert max_projected_q_diff < tolerance
    assert max_projected_k_diff < tolerance
    assert max_projected_v_diff < tolerance
    assert max_output_diff < tolerance
    assert shape(q) == [3, 4] and shape(qh) == [2, 3, 2]
    assert shape(scores) == [2, 3, 3] and shape(contexts) == [2, 3, 2]
    assert shape(concatenated) == [3, 4] and shape(output) == [3, 4]
    assert list(torch_weights.shape) == [1, 2, 3, 3]

    result = {
        "scope": "Three hand-set token vectors; self-attention with 2 heads; NumPy equations compared to torch.nn.MultiheadAttention. No training, corpus, positional encoding, mask, task metric, speed test, or benchmark.",
        "environment": {
            "python": platform.python_version(),
            "numpy": np.__version__,
            "torch": torch.__version__,
            "device": "cpu",
            "dtype": "float64",
            "batch_first": True,
            "dropout": 0.0,
            "module_eval": True,
            "need_weights": True,
            "average_attn_weights": False,
        },
        "dimensions": {
            "batch": 1,
            "sequence_length": seq_len,
            "d_model": d_model,
            "num_heads": num_heads,
            "head_dim": head_dim,
            "shapes": {
                "X": shape(x), "Q": shape(q), "K": shape(k), "V": shape(v),
                "Q_heads_K_heads_V_heads": shape(qh),
                "scores_per_head": shape(scores), "weights_per_head": shape(weights),
                "contexts_per_head": shape(contexts), "concat_heads": shape(concatenated),
                "output_after_WO": shape(output),
                "torch_output": list(torch_output.shape),
                "torch_weights_per_head": list(torch_weights.shape),
            },
            "meaning": "The first dimension of projected tensors is token position; the head axis holds 2 separate 2D subspaces. Each score/weight matrix is [head, query-token, key-token].",
        },
        "parameters_row_vectors_use_X_times_W_transpose": {
            "X": rounded(x),
            "W_Q_out_by_in": rounded(w_q), "b_Q": rounded(b_q),
            "W_K_out_by_in": rounded(w_k), "b_K": rounded(b_k),
            "W_V_out_by_in": rounded(w_v), "b_V": rounded(b_v),
            "W_O_out_by_in": rounded(w_o), "b_O": rounded(b_o),
            "note": "All Q/K/V and output matrices are dense, explicitly overwritten, and not identity or diagonal matrices. These are illustrative fixed parameters, not learned weights.",
        },
        "projected_Q_K_V": {"Q": rounded(q), "K": rounded(k), "V": rounded(v)},
        "per_head": [
            {
                "head": head,
                "Q": rounded(qh[head]),
                "K": rounded(kh[head]),
                "V": rounded(vh[head]),
                "raw_QK_transpose_scores": rounded(raw_scores[head]),
                "scaled_scores_divide_sqrt_head_dim": rounded(scores[head]),
                "softmax_over_key_token_axis": rounded(weights[head]),
                "weight_row_sums": rounded(weights[head].sum(axis=-1)),
                "weighted_value_context": rounded(contexts[head]),
            }
            for head in range(num_heads)
        ],
        "head_concat_and_output_projection": {
            "concatenated_heads_before_WO": rounded(concatenated),
            "W_O_times_concat_plus_b_O": rounded(output),
            "torch_mha_output": rounded(torch_output[0].cpu().numpy()),
            "torch_per_head_weights": rounded(torch_weights[0].cpu().numpy()),
            "torch_manual_scores_from_same_packed_QK": rounded(torch_scores[0].cpu().numpy()),
        },
        "max_abs_difference_numpy_vs_torch": {
            "Q": max_projected_q_diff,
            "K": max_projected_k_diff,
            "V": max_projected_v_diff,
            "scaled_scores": max_score_diff,
            "per_head_weights": max_weight_diff,
            "final_output_after_WO": max_output_diff,
            "assertion_tolerance": tolerance,
        },
        "checks": "PASS: dense hand-set Q/K/V and W_O projections, per-head scores/weights/contexts, concatenation and output projection match PyTorch MultiheadAttention in the single specified CPU/float64 case.",
    }
    print(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False))


if __name__ == "__main__":
    main()
