#!/usr/bin/env python3
"""Reproduce the constructed examples in Article 08 using only Python's stdlib.

Run: python3 verify.py

There are TWO independent demonstrations here:
1. The article supplies two 2D final vectors and a 7-by-2 output matrix. We
   reproduce their logits, probabilities, and greedy choices exactly as stated.
2. A separate, untrained 4D network has two causal, single-head Transformer
   blocks with Pre-RMSNorm, residual additions, and a ReLU FFN. We compare full
   prefix recomputation with incremental K/V caching. Its parameters are fixed
   teaching numbers, and it does NOT produce the article's supplied 2D vectors.

The cache experiment processes an already specified token sequence. It is not
a training experiment or a claim about the outputs of a pretrained model.
"""

from copy import deepcopy
import json
import math


VOCABULARY = ("Please", "pass", "the", "salt", "sugar", "water", ".")
W_OUT = ((0, -2), (0, -2), (0, -2), (1, 1), (1, 0), (0, 0), (-2, 1))
FINAL_VECTORS = ((1, 1), (-1, 1))
DIMENSION = 4
EPSILON = 1e-6
TOLERANCE = 1e-12


def dot(left, right):
    assert len(left) == len(right)
    return sum(a * b for a, b in zip(left, right))


def matvec(matrix, vector):
    """Matrices store rows; vectors are mathematical column vectors."""
    return [dot(row, vector) for row in matrix]


def add(left, right):
    assert len(left) == len(right)
    return [a + b for a, b in zip(left, right)]


def softmax(scores):
    maximum = max(scores)
    weights = [math.exp(score - maximum) for score in scores]
    total = sum(weights)
    return [weight / total for weight in weights]


def output_head_rounds():
    rounds = []
    for vector in FINAL_VECTORS:
        logits = matvec(W_OUT, vector)
        probabilities = softmax(logits)
        choice = VOCABULARY[max(range(len(VOCABULARY)), key=probabilities.__getitem__)]
        rounds.append({"h": vector, "logits": logits, "probabilities": probabilities, "greedy_token": choice})
    return rounds


def decode_read_counts(prefix_length, forward_steps):
    """M counts forwards after prefill, not the number of sampled output tokens."""
    if prefix_length < 1 or forward_steps < 0:
        raise ValueError("Use a nonempty prefix and a nonnegative number of decode steps")
    return [prefix_length + j for j in range(1, forward_steps + 1)]


def generation_timing():
    """Choosing a token alone does not append its K/V to any layer's cache."""
    return (
        {"stage": "prefill", "input_tokens": ("Please", "pass", "the"), "cache_length": 3, "chosen_token": "salt"},
        {"stage": "decode", "input_tokens": ("salt",), "cache_length": 4, "chosen_token": "."},
        {"stage": "if continued", "input_tokens": (".",), "cache_length": 5, "chosen_token": None},
    )


def causal_read_sets(length):
    """Zero-based positions readable by each position, including itself."""
    return tuple(tuple(range(position + 1)) for position in range(length))


def fixed_matrix(rows, columns, seed, scale=0.035):
    """Generate small fixed teaching parameters; no fitting or random sampling."""
    return [[(((row + 1) * (column + 2) + 3 * seed + row * seed) % 19 - 9) * scale
             for column in range(columns)] for row in range(rows)]


def layer_parameters(index):
    seed = 1 + 7 * index
    return {
        "q": fixed_matrix(4, 4, seed),
        "k": fixed_matrix(4, 4, seed + 1),
        "v": fixed_matrix(4, 4, seed + 2),
        "out": fixed_matrix(4, 4, seed + 3),
        "ffn_in": fixed_matrix(6, 4, seed + 4),
        "ffn_out": fixed_matrix(4, 6, seed + 5),
        "ffn_bias_in": [0.02 * (j - 2) for j in range(6)],
        "ffn_bias_out": [0.01 * (index - j) for j in range(4)],
        "norm_attention": [1.0 + 0.03 * (index + j) for j in range(4)],
        "norm_ffn": [1.0 - 0.02 * (index + j) for j in range(4)],
    }


LAYERS = tuple(layer_parameters(index) for index in range(2))
EMBEDDINGS = {
    "Please": [0.8, -0.3, 0.2, 0.1],
    "pass": [-0.2, 0.7, 0.3, -0.4],
    "the": [0.3, 0.1, -0.6, 0.8],
    "salt": [0.6, -0.4, 0.7, 0.2],
    "sugar": [-0.5, 0.3, 0.4, 0.7],
    "water": [0.2, 0.8, -0.1, 0.3],
    ".": [-0.1, 0.2, 0.6, -0.5],
}


def initial_representation(token, position):
    """A fixed additive position code for this demo, not RoPE or a trained code."""
    position_code = [0.04 * position, -0.02 * position, 0.03 * (position % 2), 0.01 * position]
    return add(EMBEDDINGS[token], position_code)


def rmsnorm(vector, gains):
    scale = math.sqrt(dot(vector, vector) / len(vector) + EPSILON)
    return [gain * value / scale for gain, value in zip(gains, vector)]


def project_qkv(vector, parameters):
    normalized = rmsnorm(vector, parameters["norm_attention"])
    return tuple(matvec(parameters[name], normalized) for name in ("q", "k", "v"))


def read_values(query, keys, values):
    """All supplied positions are allowed: masking is handled by the caller."""
    assert len(keys) == len(values) and keys
    weights = softmax([dot(query, key) / math.sqrt(len(query)) for key in keys])
    return [sum(weight * value[column] for weight, value in zip(weights, values))
            for column in range(len(values[0]))]


def finish_block(vector, attention_read, parameters):
    after_attention = add(vector, matvec(parameters["out"], attention_read))
    normalized = rmsnorm(after_attention, parameters["norm_ffn"])
    preactivation = add(matvec(parameters["ffn_in"], normalized), parameters["ffn_bias_in"])
    hidden = [max(0.0, value) for value in preactivation]
    update = add(matvec(parameters["ffn_out"], hidden), parameters["ffn_bias_out"])
    return add(after_attention, update)


def full_forward(tokens, causal=True):
    """Recompute all positions, layer by layer, without reusing an old prefix."""
    states = [initial_representation(token, position) for position, token in enumerate(tokens)]
    trace = []
    for parameters in LAYERS:
        projected = [project_qkv(vector, parameters) for vector in states]
        queries, keys, values = (list(items) for items in zip(*projected))
        outputs = []
        for position, (vector, query) in enumerate(zip(states, queries)):
            limit = position + 1 if causal else len(states)
            attention_read = read_values(query, keys[:limit], values[:limit])
            outputs.append(finish_block(vector, attention_read, parameters))
        trace.append({"keys": keys, "values": values, "outputs": outputs})
        states = outputs
    return trace


def prefill(tokens):
    trace = full_forward(tokens)
    # A layer's cache stores only that layer's K/V, not its output representations.
    caches = [{"keys": deepcopy(layer["keys"]), "values": deepcopy(layer["values"])} for layer in trace]
    return caches, trace


def decode_one(token, position, caches):
    """Compute only the new position; each layer appends its own new K and V."""
    assert len(caches) == len(LAYERS)
    vector = initial_representation(token, position)
    outputs = []
    for parameters, cache in zip(LAYERS, caches):
        assert len(cache["keys"]) == len(cache["values"]) == position
        query, key, value = project_qkv(vector, parameters)
        cache["keys"].append(key)
        cache["values"].append(value)
        vector = finish_block(vector, read_values(query, cache["keys"], cache["values"]), parameters)
        outputs.append(vector)
    return outputs


def max_difference(left, right):
    """Compare nested lists of the same shape, rejecting accidental truncation."""
    if isinstance(left, (list, tuple)):
        assert isinstance(right, (list, tuple)) and len(left) == len(right)
        return max((max_difference(a, b) for a, b in zip(left, right)), default=0.0)
    return abs(left - right)


def verify_output_head():
    rounds = output_head_rounds()
    assert rounds[0]["logits"] == [-2, -2, -2, 2, 1, 0, -1]
    assert rounds[1]["logits"] == [-2, -2, -2, 0, -1, 0, 3]
    assert [row["greedy_token"] for row in rounds] == ["salt", "."]
    assert [f"{100 * p:.2f}%" for p in rounds[0]["probabilities"]] == [
        "1.14%", "1.14%", "1.14%", "62.19%", "22.88%", "8.42%", "3.10%"]
    assert f"{100 * rounds[1]['probabilities'][-1]:.2f}%" == "87.87%"
    for row in rounds:
        assert math.isclose(sum(row["probabilities"]), 1.0, abs_tol=TOLERANCE)
    return rounds


def verify_timing_and_work():
    timeline = generation_timing()
    assert [step["cache_length"] for step in timeline] == [3, 4, 5]
    assert timeline[0]["chosen_token"] == timeline[1]["input_tokens"][0] == "salt"
    assert timeline[1]["chosen_token"] == timeline[2]["input_tokens"][0] == "."
    for prefix_length in (1, 3, 17):
        for forward_steps in (0, 1, 2, 9):
            counts = decode_read_counts(prefix_length, forward_steps)
            assert sum(counts) == prefix_length * forward_steps + forward_steps * (forward_steps + 1) // 2
    assert causal_read_sets(3) == ((0,), (0, 1), (0, 1, 2))
    return timeline


def verify_caching():
    tokens = ("Please", "pass", "the", "salt", ".")
    caches, previous = prefill(tokens[:3])
    assert all(len(cache["keys"]) == 3 for cache in caches)
    assert max_difference(caches[0]["keys"], caches[1]["keys"]) > 1e-6
    errors = {"cached_vs_full": 0.0, "old_positions": 0.0, "cached_keys_and_values": 0.0}
    for position in range(3, len(tokens)):
        old_caches = deepcopy(caches)
        incremental = decode_one(tokens[position], position, caches)
        recomputed = full_forward(tokens[:position + 1])
        for layer_index, (cache, before, after) in enumerate(zip(caches, previous, recomputed)):
            errors["cached_vs_full"] = max(errors["cached_vs_full"], max_difference(incremental[layer_index], after["outputs"][-1]))
            errors["old_positions"] = max(errors["old_positions"], max_difference(before["outputs"], after["outputs"][:-1]))
            for name in ("keys", "values"):
                assert cache[name][:-1] == old_caches[layer_index][name], "An existing cached vector was mutated"
                errors["cached_keys_and_values"] = max(errors["cached_keys_and_values"], max_difference(cache[name], after[name]))
            assert len(cache["keys"]) == len(cache["values"]) == position + 1
        previous = recomputed
    assert all(error <= TOLERANCE for error in errors.values()), errors

    # A negative control: this network really uses context. Allowing old positions
    # to see future tokens removes the invariance that justifies this cache.
    unmasked_short = full_forward(tokens[:3], causal=False)
    unmasked_long = full_forward(tokens[:4], causal=False)
    changed = max_difference(unmasked_short[-1]["outputs"], unmasked_long[-1]["outputs"][:3])
    assert changed > 1e-6, "The noncausal control should change old representations"
    return {**errors, "noncausal_old_position_change": changed, "final_cache_lengths": [len(c["keys"]) for c in caches]}


def verify_all():
    return {"output_head": verify_output_head(), "timing": verify_timing_and_work(), "separate_two_layer_cache_model": verify_caching()}


if __name__ == "__main__":
    result = verify_all()
    print("PASS Article 08: constructed output head, cache timing, and cumulative reads")
    print("PASS separate 4D two-layer causal model: cached and full computations agree")
    print("The cache model does not produce the article's supplied 2D final vectors.")
    print(json.dumps(result, indent=2))
