"""LLM Daily Lab: CPU exercises for tensors, autograd and a small causal decoder.

This is an educational character LM, not a reproduction of a paper's benchmark.
The decoder uses one pre-norm block, learned positions and GELU. The original
Transformer paper uses an encoder-decoder, post-norm blocks and ReLU.
Sources: https://arxiv.org/abs/1706.03762v7 and https://docs.pytorch.org/docs/2.14/
No external dataset, model download or API key is needed after installing torch.
"""
import argparse
import json
import math
import platform
import random
import time
from pathlib import Path

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


class TinyDecoder(nn.Module):
    def __init__(self, vocab_size, width=32, heads=4, context=32, positions=True):
        super().__init__()
        self.width, self.heads, self.context = width, heads, context
        self.positions = positions
        self.token = nn.Embedding(vocab_size, width)
        self.position = nn.Embedding(context, width)
        self.norm1, self.norm2 = nn.LayerNorm(width), nn.LayerNorm(width)
        self.qkv = nn.Linear(width, 3 * width)
        self.project = nn.Linear(width, width)
        self.mlp = nn.Sequential(nn.Linear(width, 4 * width), nn.GELU(), nn.Linear(4 * width, width))
        self.final_norm = nn.LayerNorm(width)
        self.output = nn.Linear(width, vocab_size)

    def forward(self, tokens, causal=True):
        batch, length = tokens.shape
        if length > self.context:
            raise ValueError("Input exceeds the context window")
        x = self.token(tokens)
        if self.positions:
            x = x + self.position(torch.arange(length, device=tokens.device))
        q, k, v = self.qkv(self.norm1(x)).chunk(3, dim=-1)
        q, k, v = [t.view(batch, length, self.heads, self.width // self.heads).transpose(1, 2) for t in (q, k, v)]
        scores = q @ k.transpose(-2, -1) / math.sqrt(self.width // self.heads)
        if causal:
            mask = torch.ones(length, length, device=tokens.device, dtype=torch.bool).tril()
            scores = scores.masked_fill(~mask, float("-inf"))
        weights = scores.softmax(dim=-1)
        attention = (weights @ v).transpose(1, 2).contiguous().view(batch, length, self.width)
        x = x + self.project(attention)
        x = x + self.mlp(self.norm2(x))
        return self.output(self.final_norm(x))


def make_data(seed=100, context=32):
    rng = random.Random(seed)
    colors = ["red", "blue", "green", "gold"]
    animals = ["fox", "owl", "cat", "dog", "ant", "bee"]
    verbs = ["sees", "helps", "follows"]
    # Split unique whole sentences before sampling windows: no cross-split windows.
    sentences = [f"the {a} {b} {v} the {c} {d}.\n" for a in colors for b in animals for v in verbs for c in colors for d in animals]
    rng.shuffle(sentences)
    training, validation = sentences[:600], sentences[600:800]
    assert not set(training) & set(validation)
    vocabulary = sorted(set("".join(sentences)))
    encode = {char: i for i, char in enumerate(vocabulary)}

    def windows(examples):
        result = []
        for sentence in examples:
            ids = [encode[c] for c in sentence]
            for start in range(0, len(ids) - context):
                result.append(ids[start:start + context + 1])
        return torch.tensor(result, dtype=torch.long)
    return windows(training), windows(validation), vocabulary


def batch(data, generator, size=16):
    indices = torch.randint(len(data), (size,), generator=generator)
    rows = data[indices]
    return rows[:, :-1], rows[:, 1:]


def loss_for(model, x, y):
    logits = model(x)
    return F.cross_entropy(logits.reshape(-1, logits.size(-1)), y.reshape(-1))


@torch.no_grad()
def evaluate(model, data):
    model.eval()
    total, count = 0.0, 0
    for chunk in data.split(64):
        x, y = chunk[:, :-1], chunk[:, 1:]
        total += loss_for(model, x, y).item() * y.numel()
        count += y.numel()
    return total / count


def checks():
    torch.manual_seed(7)
    w = torch.tensor(2.0, dtype=torch.float64, requires_grad=True)
    loss = (w * 3 - 5) ** 2
    loss.backward()
    epsilon = 1e-5
    numeric = (((2 + epsilon) * 3 - 5) ** 2 - ((2 - epsilon) * 3 - 5) ** 2) / (2 * epsilon)
    assert abs(w.grad.item() - numeric) < 1e-6
    model = TinyDecoder(20)
    x = torch.randint(20, (2, 12))
    changed = x.clone(); changed[:, 7:] = (changed[:, 7:] + 1) % 20
    with torch.no_grad():
        prefix_error = (model(x)[:, :7] - model(changed)[:, :7]).abs().max().item()
        unmasked_error = (model(x, causal=False)[:, :7] - model(changed, causal=False)[:, :7]).abs().max().item()
    assert prefix_error < 1e-6, "A future token changed a causal prefix"
    assert unmasked_error > 1e-5, "Negative control did not expose the missing mask"
    x, y = torch.randint(20, (4, 12)), torch.randint(20, (4, 12))
    optimizer = torch.optim.AdamW(model.parameters(), lr=0.008)
    initial = loss_for(model, x, y).item()
    for _ in range(100):
        optimizer.zero_grad(set_to_none=True)
        loss = loss_for(model, x, y); loss.backward(); optimizer.step()
    final = loss_for(model, x, y).item()
    assert final < initial * 0.15, "Cannot overfit one batch; inspect labels or gradients"
    return {"autograd": w.grad.item(), "finite_difference": numeric,
            "causal_prefix_max_error": prefix_error, "unmasked_negative_control_error": unmasked_error,
            "one_batch_initial_loss": initial, "one_batch_final_loss": final,
            "logits_shape": list(model(x).shape)}


def train(seed, steps, positions=True):
    torch.manual_seed(seed)
    training, validation, vocabulary = make_data()
    model = TinyDecoder(len(vocabulary), positions=positions)
    optimizer = torch.optim.AdamW(model.parameters(), lr=0.003)
    sampler = torch.Generator().manual_seed(seed + 1000)
    initial = evaluate(model, validation)
    curve = []
    for step in range(steps):
        model.train()
        x, y = batch(training, sampler)
        optimizer.zero_grad(set_to_none=True)
        loss = loss_for(model, x, y); loss.backward()
        nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        optimizer.step()
        if step == 0 or (step + 1) % max(1, steps // 5) == 0:
            curve.append({"step": step + 1, "training_batch_loss": loss.item(), "validation_loss": evaluate(model, validation)})
    model.eval()
    tokens = torch.tensor([[vocabulary.index(c) for c in "the red "]])
    generator = torch.Generator().manual_seed(seed + 2000)
    with torch.no_grad():
        for _ in range(48):
            probs = model(tokens[:, -model.context:])[:, -1].softmax(-1)
            tokens = torch.cat([tokens, torch.multinomial(probs, 1, generator=generator)], dim=1)
    return {"seed": seed, "positions": positions, "steps": steps, "batch_size": 16,
            "context": model.context, "width": model.width, "heads": model.heads,
            "allocated_parameters": sum(p.numel() for p in model.parameters()),
            "used_parameters": sum(p.numel() for p in model.parameters()) - (0 if positions else model.position.weight.numel()),
            "data_seed": 100, "training_sentences": 600, "validation_sentences": 200,
            "initial_validation_loss": initial, "final_validation_loss": evaluate(model, validation),
            "curve": curve, "sample": "".join(vocabulary[i] for i in tokens[0].tolist())}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--mode", choices=["check", "train", "compare"], default="check")
    parser.add_argument("--steps", type=int, default=120)
    parser.add_argument("--seed", type=int, default=7)
    parser.add_argument("--threads", type=int, default=2)
    parser.add_argument("--output", default="research-result.json")
    args = parser.parse_args()
    if not 1 <= args.steps <= 10000 or not 1 <= args.threads <= 16:
        parser.error("Use 1–10000 steps and 1–16 CPU threads")
    torch.set_num_threads(args.threads)
    started = time.perf_counter()
    result = {"format": "llm-daily-lab-experiment-v1", "mode": args.mode,
              "torch": torch.__version__, "python": platform.python_version(),
              "platform": platform.platform(), "device": "cpu", "threads": args.threads,
              "limits": "Synthetic character LM; validation informs exploration and is not an untouched final test set. No paper benchmark is reproduced."}
    if args.mode == "check": result["checks"] = checks()
    elif args.mode == "train": result["runs"] = [train(args.seed, args.steps)]
    else:
        result["comparison"] = "Same sentences, sampling seeds and initial weights; only learned positional embeddings are switched off. Allocated and used parameters are reported separately."
        result["runs"] = [train(seed, args.steps, positions) for seed in [args.seed, args.seed + 1, args.seed + 2] for positions in [True, False]]
    result["seconds"] = round(time.perf_counter() - started, 3)
    Path(args.output).write_text(json.dumps(result, indent=2) + "\n")
    print(json.dumps(result, indent=2))


if __name__ == "__main__": main()
