"""Small, hand-set Transformer mechanics example for DS46.

CPU/float64 only. Demonstrates absolute sinusoidal positions, an explicit
causal mask, post-norm vs pre-norm residual forms, and prefix recomputation.
No training, corpus, cache implementation, or performance benchmark.
"""
from __future__ import annotations

import json
import math
import platform

import torch
from torch import nn


def sinusoidal_position_encoding(positions: torch.Tensor, d_model: int) -> torch.Tensor:
    """Return sinusoidal encodings for explicit absolute position indices."""
    if d_model <= 0 or d_model % 2:
        raise ValueError("this example requires a positive even d_model")
    positions = torch.as_tensor(positions, dtype=torch.float64, device="cpu")
    if positions.ndim != 1:
        raise ValueError("positions must be a one-dimensional list of absolute indices")
    if torch.any(positions < 0):
        raise ValueError("positions must be nonnegative")
    feature_pairs = torch.arange(0, d_model, 2, dtype=torch.float64, device="cpu")
    denominators = torch.pow(10000.0, feature_pairs / d_model)
    angles = positions[:, None] / denominators[None, :]
    result = torch.empty((positions.numel(), d_model), dtype=torch.float64, device="cpu")
    result[:, 0::2] = torch.sin(angles)
    result[:, 1::2] = torch.cos(angles)
    return result


def upper_triangle_causal_mask(length: int) -> torch.Tensor:
    """For nn.MultiheadAttention, True means that query-key pair is blocked."""
    if length < 1:
        raise ValueError("sequence length must be positive")
    return torch.triu(torch.ones((length, length), dtype=torch.bool), diagonal=1)


def rounded(tensor: torch.Tensor, digits: int = 10):
    values = tensor.detach().cpu().to(torch.float64)
    if values.ndim == 0:
        return round(float(values.item()), digits)
    if values.ndim == 1:
        return [round(float(x), digits) for x in values.tolist()]
    return [rounded(row, digits) for row in values]


def main() -> None:
    torch.set_num_threads(1)
    dtype = torch.float64
    d_model, num_heads, seq_len = 4, 2, 4
    head_dim = d_model // num_heads
    assert d_model % num_heads == 0

    # Four fixed token embeddings. These are illustrative inputs, not token IDs.
    embeddings = torch.tensor(
        [[[
            0.20, -0.10, 0.30, 0.40,
        ], [
            -0.30, 0.50, 0.10, -0.20,
        ], [
            0.40, 0.20, -0.50, 0.10,
        ], [
            -0.10, -0.40, 0.20, 0.30,
        ]]], dtype=dtype, device="cpu")

    # Explicit absolute position IDs. Match the common embedding scale + PE form.
    position_ids = torch.arange(seq_len, dtype=torch.long, device="cpu")
    pe = sinusoidal_position_encoding(position_ids, d_model)
    positioned = embeddings * math.sqrt(d_model) + pe.unsqueeze(0)

    # Verify a later chunk receives its absolute positions, not positions reset to 0.
    chunk_positions = torch.tensor([2, 3], dtype=torch.long, device="cpu")
    chunk_pe = sinusoidal_position_encoding(chunk_positions, d_model)
    chunk_pe_from_full = pe[2:4]
    reset_chunk_pe = sinusoidal_position_encoding(torch.tensor([0, 1]), d_model)
    offset_error = float(torch.max(torch.abs(chunk_pe - chunk_pe_from_full)).item())
    reset_error = float(torch.max(torch.abs(chunk_pe - reset_chunk_pe)).item())
    assert offset_error == 0.0
    assert reset_error > 1e-3

    # One explicit causal self-attention layer; all parameters are overwritten.
    mha = nn.MultiheadAttention(
        embed_dim=d_model,
        num_heads=num_heads,
        dropout=0.0,
        bias=True,
        batch_first=True,
        device="cpu",
        dtype=dtype,
    )
    w_q = torch.tensor([
        [0.40, -0.10, 0.20, 0.30],
        [0.10, 0.50, -0.20, 0.10],
        [-0.30, 0.20, 0.40, 0.10],
        [0.20, -0.40, 0.10, 0.50],
    ], dtype=dtype)
    w_k = torch.tensor([
        [0.30, 0.20, -0.10, 0.40],
        [-0.20, 0.40, 0.30, 0.10],
        [0.10, -0.30, 0.50, 0.20],
        [0.40, 0.10, 0.20, -0.20],
    ], dtype=dtype)
    w_v = torch.tensor([
        [0.50, 0.10, -0.20, 0.30],
        [0.20, -0.40, 0.30, 0.10],
        [-0.10, 0.30, 0.40, 0.20],
        [0.30, 0.20, 0.10, -0.50],
    ], dtype=dtype)
    b_q = torch.tensor([0.05, -0.02, 0.03, 0.01], dtype=dtype)
    b_k = torch.tensor([-0.03, 0.04, 0.02, -0.01], dtype=dtype)
    b_v = torch.tensor([0.01, 0.02, -0.04, 0.03], dtype=dtype)
    w_o = torch.tensor([
        [0.60, -0.20, 0.10, 0.30],
        [-0.10, 0.50, 0.20, -0.30],
        [0.20, 0.10, 0.70, -0.20],
        [0.30, -0.40, 0.10, 0.50],
    ], dtype=dtype)
    b_o = torch.tensor([0.02, -0.01, 0.03, -0.04], dtype=dtype)
    with torch.no_grad():
        mha.in_proj_weight.copy_(torch.cat([w_q, w_k, w_v], dim=0))
        mha.in_proj_bias.copy_(torch.cat([b_q, b_k, b_v], dim=0))
        mha.out_proj.weight.copy_(w_o)
        mha.out_proj.bias.copy_(b_o)
    mha.eval()

    causal_mask = upper_triangle_causal_mask(seq_len)
    with torch.no_grad():
        full_output, full_weights = mha(
            positioned,
            positioned,
            positioned,
            attn_mask=causal_mask,
            need_weights=True,
            average_attn_weights=False,
        )

        # Recompute each prefix from scratch. This is not a KV-cache implementation.
        prefix_last_outputs = []
        for end in range(1, seq_len + 1):
            prefix = positioned[:, :end, :]
            prefix_mask = upper_triangle_causal_mask(end)
            prefix_output, _ = mha(
                prefix,
                prefix,
                prefix,
                attn_mask=prefix_mask,
                need_weights=False,
            )
            prefix_last_outputs.append(prefix_output[0, -1])
        prefix_last_outputs = torch.stack(prefix_last_outputs, dim=0)

        # Change only a future token; earlier query outputs must remain unchanged.
        changed_embeddings = embeddings.clone()
        changed_embeddings[0, 3] += torch.tensor([9.0, -4.0, 3.0, 1.0], dtype=dtype)
        changed_positioned = changed_embeddings * math.sqrt(d_model) + pe.unsqueeze(0)
        changed_output, _ = mha(
            changed_positioned,
            changed_positioned,
            changed_positioned,
            attn_mask=causal_mask,
            need_weights=False,
        )

    prefix_max_diff = float(torch.max(torch.abs(full_output[0] - prefix_last_outputs)).item())
    earlier_future_change_max_diff = float(
        torch.max(torch.abs(full_output[:, :3] - changed_output[:, :3])).item()
    )
    future_attention_max = float(
        torch.max(torch.abs(full_weights.masked_select(causal_mask[None, None, :, :]))).item()
    )
    weight_row_sums = full_weights.sum(dim=-1)
    assert prefix_max_diff < 1e-12
    assert earlier_future_change_max_diff < 1e-12
    assert future_attention_max == 0.0
    assert torch.max(torch.abs(weight_row_sums - 1.0)).item() < 1e-12

    # Compare the post-norm and pre-norm residual forms; these are not interchangeable.
    eps = 1e-5
    gamma = torch.tensor([1.10, 0.90, 1.20, 0.80], dtype=dtype)
    beta = torch.tensor([0.10, -0.20, 0.05, 0.30], dtype=dtype)
    layer_norm = nn.LayerNorm(d_model, eps=eps, elementwise_affine=True, device="cpu", dtype=dtype)
    with torch.no_grad():
        layer_norm.weight.copy_(gamma)
        layer_norm.bias.copy_(beta)

    with torch.no_grad():
        postnorm_residual_sum = positioned + full_output
        postnorm = layer_norm(postnorm_residual_sum)
        prenorm_input = layer_norm(positioned)
        prenorm_attention, _ = mha(
            prenorm_input,
            prenorm_input,
            prenorm_input,
            attn_mask=causal_mask,
            need_weights=False,
        )
        prenorm = positioned + prenorm_attention

        last_dim_mean = postnorm_residual_sum.mean(dim=-1, keepdim=True)
        last_dim_var = postnorm_residual_sum.var(dim=-1, unbiased=False, keepdim=True)
        manual_postnorm = (
            (postnorm_residual_sum - last_dim_mean)
            / torch.sqrt(last_dim_var + eps)
            * gamma
            + beta
        )
    manual_layernorm_diff = float(torch.max(torch.abs(postnorm - manual_postnorm)).item())
    pre_post_difference = float(torch.max(torch.abs(prenorm - postnorm)).item())
    assert manual_layernorm_diff < 1e-12
    assert pre_post_difference > 1e-6

    result = {
        "scope": "Four hand-set token embeddings; sinusoidal absolute positions; one hand-parameterized causal MHA layer; LayerNorm/residual arithmetic. No training, corpus, KV cache, GPU, latency, or quality benchmark.",
        "environment": {
            "python": platform.python_version(),
            "torch": torch.__version__,
            "device": "cpu",
            "dtype": "float64",
            "torch_threads": torch.get_num_threads(),
            "batch_first": True,
            "mha_dropout": 0.0,
            "mha_eval": True,
            "mha_bool_attn_mask_true_means": "blocked",
            "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,
            "embeddings": list(embeddings.shape),
            "position_encoding": list(pe.shape),
            "positioned_embeddings": list(positioned.shape),
            "causal_mask": list(causal_mask.shape),
            "full_output": list(full_output.shape),
            "per_head_weights": list(full_weights.shape),
            "postnorm": list(postnorm.shape),
            "prenorm": list(prenorm.shape),
        },
        "position_encoding": {
            "absolute_position_ids": position_ids.tolist(),
            "formula": "PE[pos,2i]=sin(pos/10000^(2i/d_model)); PE[pos,2i+1]=cos(pos/10000^(2i/d_model))",
            "embedding_scale": "sqrt(d_model)",
            "pe_rows": rounded(pe),
            "positioned_input_first_token": rounded(positioned[0, 0]),
            "offset_check_positions": chunk_positions.tolist(),
            "offset_pe_max_diff_vs_full_sequence_rows_2_3": offset_error,
            "incorrect_reset_to_positions_0_1_max_diff": reset_error,
        },
        "causal_mask": {
            "true_means": "block this query-key pair for torch.nn.MultiheadAttention 2.3",
            "matrix": causal_mask.tolist(),
            "diagonal_is_visible": True,
            "full_sequence_output": rounded(full_output[0]),
            "per_head_attention_weights": rounded(full_weights[0]),
            "per_query_key_weight_sums": rounded(weight_row_sums[0]),
            "max_weight_on_blocked_future_positions": future_attention_max,
            "full_masked_pass_vs_independent_prefix_recomputation_max_diff": prefix_max_diff,
            "earlier_output_change_after_perturbing_future_token_max_diff": earlier_future_change_max_diff,
            "prefix_recomputation_note": "Each prefix is rerun from scratch at its original position IDs; this is not cached decoding or a speed comparison.",
        },
        "residual_and_layernorm": {
            "post_norm_formula": "LayerNorm(x + Sublayer(x))",
            "pre_norm_formula": "x + Sublayer(LayerNorm(x))",
            "chosen_demo_path": "post_norm",
            "residual_sum": rounded(postnorm_residual_sum[0]),
            "epsilon": eps,
            "normalized_axis": -1,
            "variance_convention": "biased variance (unbiased=False) across the final d_model feature axis for each token",
            "gamma": rounded(gamma),
            "beta": rounded(beta),
            "postnorm_output": rounded(postnorm[0]),
            "postnorm_feature_means_after_affine": rounded(postnorm.mean(dim=-1)[0]),
            "postnorm_feature_variances_after_affine_biased": rounded(postnorm.var(dim=-1, unbiased=False)[0]),
            "manual_layernorm_max_diff": manual_layernorm_diff,
            "pre_vs_post_norm_max_diff_same_demo_parameters": pre_post_difference,
        },
        "checks": "PASS: explicit positions retain absolute offsets; MHA future-mask weights are zero; full causal sequence rows match same-token prefix recomputation; changing a future token leaves earlier outputs unchanged; post-norm LayerNorm matches manual final-feature-axis biased-variance computation; pre-norm and post-norm outputs differ.",
    }
    print(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False))


if __name__ == "__main__":
    main()
