"""Tiny deterministic example of causal attention and shifted next-token targets.

Standard library only. This is not a GPT checkpoint, training run, ICL test,
quality evaluation, or benchmark.
"""
from __future__ import annotations

import json
import math
import platform
from typing import Sequence


Vector = list[float]
Matrix = list[Vector]


def dot(left: Sequence[float], right: Sequence[float]) -> float:
    return sum(a * b for a, b in zip(left, right))


def softmax(logits: Sequence[float]) -> Vector:
    """Numerically stable softmax across the provided keys."""
    top = max(logits)
    exps = [math.exp(value - top) for value in logits]
    total = sum(exps)
    return [value / total for value in exps]


def attention(
    queries: Matrix, keys: Matrix, values: Matrix, causal: bool
) -> tuple[Matrix, Matrix]:
    """Return [query,key] weights and one weighted-value vector per query."""
    key_depth = len(queries[0])
    if any(len(row) != key_depth for row in queries + keys):
        raise ValueError("query/key vector depths must match")
    if len(keys) != len(values):
        raise ValueError("key and value sequence lengths must match")

    all_weights: Matrix = []
    outputs: Matrix = []
    for query_index, query in enumerate(queries):
        scores = [dot(query, key) / math.sqrt(key_depth) for key in keys]
        if causal:
            scores = [
                score if key_index <= query_index else float("-inf")
                for key_index, score in enumerate(scores)
            ]
        weights = softmax(scores)
        output = [
            sum(weights[j] * values[j][dim] for j in range(len(values)))
            for dim in range(len(values[0]))
        ]
        all_weights.append(weights)
        outputs.append(output)
    return all_weights, outputs


def logsumexp(logits: Sequence[float]) -> float:
    top = max(logits)
    return top + math.log(sum(math.exp(value - top) for value in logits))


def cross_entropy(logits: Sequence[float], label_index: int) -> float:
    return logsumexp(logits) - logits[label_index]


def rounded(values, digits: int = 12):
    if isinstance(values, (int, float)):
        return round(float(values), digits)
    return [rounded(value, digits) for value in values]


def main() -> None:
    # Hand-set three-token Q/K/V arrays. Row t is the vector for token t.
    # There are no learned parameters, corpus, or random draws in this example.
    queries: Matrix = [
        [1.0, 0.0],
        [0.0, 1.0],
        [1.0, 1.0],
    ]
    keys: Matrix = [
        [1.0, 0.0],
        [0.0, 1.0],
        [2.0, -1.0],
    ]
    values: Matrix = [
        [1.0, 0.0],
        [0.0, 1.0],
        [5.0, 4.0],
    ]

    causal_weights, causal_output = attention(queries, keys, values, causal=True)
    full_weights, full_output = attention(queries, keys, values, causal=False)

    # Change only the future (last-position) K and V vectors.
    changed_keys = [row[:] for row in keys]
    changed_values = [row[:] for row in values]
    changed_keys[-1] = [-1.5, 2.5]
    changed_values[-1] = [-3.0, 6.0]
    changed_causal_weights, changed_causal_output = attention(
        queries, changed_keys, changed_values, causal=True
    )
    changed_full_weights, changed_full_output = attention(
        queries, changed_keys, changed_values, causal=False
    )

    prefix_causal_diffs = [
        max(abs(a - b) for a, b in zip(causal_output[i], changed_causal_output[i]))
        for i in range(2)
    ]
    prefix_unmasked_diffs = [
        max(abs(a - b) for a, b in zip(full_output[i], changed_full_output[i]))
        for i in range(2)
    ]
    causal_future_weights = [
        causal_weights[q][k] for q in range(3) for k in range(q + 1, 3)
    ]
    row_sums = [sum(row) for row in causal_weights]
    assert all(abs(total - 1.0) < 1e-14 for total in row_sums)
    assert all(weight == 0.0 for weight in causal_future_weights)
    assert max(prefix_causal_diffs) < 1e-14
    assert min(prefix_unmasked_diffs) > 1e-6

    # Decoder inputs are shifted right by one relative to their next-token labels.
    teacher_forced_inputs = ["<BOS>", "A", "B"]
    targets = ["A", "B", "<EOS>"]
    assert len(teacher_forced_inputs) == len(targets)

    # One fixed position's vocabulary logits. This is a numeric CE illustration,
    # not a model prediction. Vocab order: BOS, A, B, EOS.
    vocabulary = ["<BOS>", "A", "B", "<EOS>"]
    position_zero_logits = [-0.2, 1.4, 0.3, -1.0]
    correct_target_index = vocabulary.index(targets[0])
    incorrect_unshifted_target_index = vocabulary.index(teacher_forced_inputs[0])
    log_z = logsumexp(position_zero_logits)
    correct_ce = cross_entropy(position_zero_logits, correct_target_index)
    unshifted_ce = cross_entropy(
        position_zero_logits, incorrect_unshifted_target_index
    )

    # Independent scalar check written directly from the log-sum-exp definition.
    max_logit = max(position_zero_logits)
    direct_log_z = max_logit + math.log(
        sum(math.exp(logit - max_logit) for logit in position_zero_logits)
    )
    direct_correct_ce = direct_log_z - position_zero_logits[1]
    direct_unshifted_ce = direct_log_z - position_zero_logits[0]
    assert abs(log_z - direct_log_z) < 1e-15
    assert abs(correct_ce - direct_correct_ce) < 1e-15
    assert abs(unshifted_ce - direct_unshifted_ce) < 1e-15
    assert correct_ce < unshifted_ce

    result = {
        "scope": (
            "Three fixed 2D Q/K/V vectors; scaled dot-product attention; causal "
            "mask and unmasked comparison; one teacher-forced target-shift CE "
            "example. No model, training, corpus, checkpoint, network, ICL "
            "evaluation, task-quality claim, or benchmark."
        ),
        "environment": {
            "python": platform.python_version(),
            "dependencies": "Python standard library only",
            "randomness": "none",
            "network_or_install": "none",
        },
        "attention": {
            "sequence_length": 3,
            "key_depth": 2,
            "scaling": "dot(Q_i,K_j) / sqrt(2)",
            "matrix_axes": "rows are query positions; columns are key positions",
            "Q": queries,
            "K": keys,
            "V": values,
            "causal_weights": rounded(causal_weights),
            "causal_weight_row_sums": rounded(row_sums),
            "causal_output": rounded(causal_output),
            "future_key_weights": rounded(causal_future_weights),
            "unmasked_weights": rounded(full_weights),
            "unmasked_output": rounded(full_output),
            "future_perturbation": {
                "changed_last_key": changed_keys[-1],
                "changed_last_value": changed_values[-1],
                "causal_output_first_two_before": rounded(causal_output[:2]),
                "causal_output_first_two_after": rounded(changed_causal_output[:2]),
                "max_abs_differences_first_two_causal": rounded(prefix_causal_diffs),
                "causal_weights_after": rounded(changed_causal_weights),
                "max_abs_differences_first_two_unmasked": rounded(prefix_unmasked_diffs),
                "unmasked_output_after": rounded(changed_full_output),
                "unmasked_weights_after": rounded(changed_full_weights),
            },
            "checks": {
                "every_causal_weight_row_sums_to_one": True,
                "future_key_weights_are_exactly_zero": True,
                "changing_future_KV_leaves_earlier_causal_outputs_unchanged": True,
                "same_perturbation_changes_earlier_unmasked_outputs": True,
            },
        },
        "teacher_forcing_shift": {
            "input_tokens": teacher_forced_inputs,
            "next_token_targets": targets,
            "alignment": [
                {"input": token, "target": target}
                for token, target in zip(teacher_forced_inputs, targets)
            ],
            "vocabulary_order": vocabulary,
            "position_zero_fixed_logits": position_zero_logits,
            "logsumexp": rounded(log_z),
            "correct_shifted_label": {
                "target": targets[0],
                "formula": "logsumexp(logits) - logit[target_index]",
                "cross_entropy": rounded(correct_ce),
            },
            "incorrect_unshifted_negative_control": {
                "wrong_target": teacher_forced_inputs[0],
                "why_wrong": "It asks the position consuming BOS to predict BOS, rather than the next token A.",
                "cross_entropy": rounded(unshifted_ce),
            },
            "independent_scalar_check": {
                "logsumexp": rounded(direct_log_z),
                "correct_shifted_ce": rounded(direct_correct_ce),
                "unshifted_negative_control_ce": rounded(direct_unshifted_ce),
                "matches_implementation_within_1e-15": True,
            },
        },
        "result_note": (
            "All values arise from explicitly fixed toy vectors/logits. The "
            "example isolates a causal information-flow rule and next-token "
            "label alignment; it does not model GPT training or behavior."
        ),
    }
    print(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False))


if __name__ == "__main__":
    main()
