"""Train the password riddle models and export browser weights.

Run with: uv run --python 3.13 --with torch==2.15.0 --with numpy python train.py
"""

from itertools import product
import json
from math import sqrt
from pathlib import Path

import torch
from torch import nn
from torch.nn import functional as F

PASSWORDS = ("ember", "frost", "moss")
# Hold out whole password pairs across both knock assignments and both questions.
HELD_OUT_PAIRS = (("ember", "frost"), ("frost", "moss"), ("moss", "ember"))
VISITORS = ("Fox", "Raven")
KNOCKS = ("twice", "three times")
OUTPUTS = (*PASSWORDS, ".")
TOKENS = (
    "<pad>",
    *(f"{visitor} knocks {knocks}" for visitor, knocks in product(VISITORS, KNOCKS)),
    *(f"{visitor}’s password is {password}" for visitor, password in product(VISITORS, PASSWORDS)),
    *(f"Someone knocks {knocks}" for knocks in KNOCKS),
    *PASSWORDS,
)
CONTEXT_SIZE = 6
WIDTH = 16
TRAIN_STEPS = 600
LEARNING_RATE = 0.015
ATTENTION_FEEDBACK_WEIGHT = 0.25


def examples(*, held_out, pairs=HELD_OUT_PAIRS):
    for fox, raven, heard, swap in product(PASSWORDS, PASSWORDS, KNOCKS, (False, True)):
        if ((fox, raven) in pairs) != held_out:
            continue
        fox_knocks, raven_knocks = KNOCKS[::-1] if swap else KNOCKS
        prompt = (
            f"Fox knocks {fox_knocks}",
            f"Raven knocks {raven_knocks}",
            f"Fox’s password is {fox}",
            f"Raven’s password is {raven}",
            f"Someone knocks {heard}",
        )
        visitor_index = int(heard == raven_knocks)
        answer = (fox, raven)[visitor_index]
        yield prompt, answer, (visitor_index, visitor_index + 2)
        yield (*prompt, answer), ".", (-1, -1)


def batch(examples):
    prompts, outputs, clue_positions = zip(*examples)
    rows = [[TOKENS.index(token) for token in prompt] for prompt in prompts]
    tokens = torch.tensor([row + [0] * (CONTEXT_SIZE - len(row)) for row in rows])
    targets = torch.tensor([OUTPUTS.index(token) for token in outputs])
    return tokens, targets, torch.tensor(clue_positions)


class FixedSlots(nn.Sequential):
    def forward(self, tokens):
        # Padding becomes all zero. Each other token is a one-hot vector.
        slots = F.one_hot(tokens, len(TOKENS)).float()[..., 1:]
        return super().forward(slots.flatten(1))


class DecoderBlock(nn.Module):
    def __init__(self):
        super().__init__()
        self.query = nn.Linear(WIDTH, WIDTH, bias=False)
        self.key = nn.Linear(WIDTH, WIDTH, bias=False)
        self.value = nn.Linear(WIDTH, WIDTH, bias=False)
        self.attention_norm = nn.LayerNorm(WIDTH)
        self.mlp_in = nn.Linear(WIDTH, 2 * WIDTH)
        self.mlp_out = nn.Linear(2 * WIDTH, WIDTH)
        self.mlp_norm = nn.LayerNorm(WIDTH)

    def forward(self, x, future):
        scores = self.query(x) @ self.key(x).transpose(-2, -1) / sqrt(WIDTH)
        attention = scores.masked_fill(future, -torch.inf).softmax(dim=-1)
        x = self.attention_norm(x + attention @ self.value(x))
        x = self.mlp_norm(x + self.mlp_out(F.relu(self.mlp_in(x))))
        return x, attention


class TinyTransformer(nn.Module):
    def __init__(self):
        super().__init__()
        self.embedding = nn.Embedding(len(TOKENS), WIDTH, padding_idx=0)
        self.blocks = nn.ModuleList(DecoderBlock() for _ in range(2))
        self.readout = nn.Linear(WIDTH, len(OUTPUTS))

    def forward(self, tokens, *, return_attention=False):
        x = self.embedding(tokens)
        position = torch.arange(tokens.size(1))
        future = position[None, :] > position[:, None]
        last = tokens.ne(0).sum(dim=-1) - 1
        batch_indices = torch.arange(len(tokens))
        final_rows = []
        for block in self.blocks:
            x, attention = block(x, future)
            final_rows.append(attention[batch_indices, last])
        scores = self.readout(x[batch_indices, last])
        if return_attention:
            return scores, torch.stack(final_rows, dim=1)
        return scores


def measure(model, inputs):
    with torch.no_grad():
        tokens, targets, clues = inputs
        if isinstance(model, TinyTransformer):
            scores, attention = model(tokens, return_attention=True)
            hits = (attention[::2].argmax(dim=-1) == clues[::2]).sum(dim=0)
        else:
            scores = model(tokens)
            hits = None
        correct = scores.argmax(dim=-1) == targets
        result = {
            "password": int(correct[::2].sum()),
            "period": int(correct[1::2].sum()),
            "total": len(correct) // 2,
        }
        if hits is not None:
            result["attention_hits"] = hits.tolist()
        return result


def rounded(values):
    if isinstance(values, list):
        return [rounded(value) for value in values]
    return round(values, 7)


def build_models():
    slot_features = CONTEXT_SIZE * (len(TOKENS) - 1)
    return {
        "linear": FixedSlots(nn.Linear(slot_features, len(OUTPUTS))),
        "mlp": FixedSlots(
            nn.Linear(slot_features, 4 * WIDTH),
            nn.ReLU(),
            nn.Linear(4 * WIDTH, len(OUTPUTS)),
        ),
        "transformer": TinyTransformer(),
    }


def fit(model, train, *, attention_weight=0.0, observe=None):
    tokens, targets, clues = train
    optimizer = torch.optim.AdamW(model.parameters(), lr=LEARNING_RATE)
    for step in range(TRAIN_STEPS):
        if observe is not None:
            observe(model, step)
        optimizer.zero_grad()
        if attention_weight:
            scores, attention = model(tokens, return_attention=True)
            # Only the password-prediction rows have target attention positions.
            clue_weights = attention[::2].gather(-1, clues[::2, :, None])
            attention_loss = -clue_weights.clamp_min(1e-12).log().mean()
            loss = F.cross_entropy(scores, targets) + attention_weight * attention_loss
        else:
            loss = F.cross_entropy(model(tokens), targets)
        loss.backward()
        optimizer.step()
    if observe is not None:
        observe(model, TRAIN_STEPS)


def main():
    torch.set_num_threads(1)
    torch.manual_seed(0)
    train = batch(examples(held_out=False))
    test = batch(examples(held_out=True))
    result = {
        "tokens": TOKENS,
        "outputs": OUTPUTS,
        "contextSize": CONTEXT_SIZE,
        "heldOutPairs": HELD_OUT_PAIRS,
    }
    for name, model in build_models().items():
        attention_weight = ATTENTION_FEEDBACK_WEIGHT if name == "transformer" else 0.0
        fit(model, train, attention_weight=attention_weight)
        print(name, "training:", measure(model, train), "held out:", measure(model, test))
        result[name] = {
            key: rounded(value.tolist()) for key, value in model.state_dict().items()
        }

    js = "// Generated by train.py.\nconst passwordWeights = "
    Path(__file__).with_name("weights.js").write_text(
        js + json.dumps(result, separators=(",", ":")) + ";\n", encoding="utf-8"
    )


if __name__ == "__main__":
    main()
