"""A whole LLM pipeline on a corpus of ONE sentence.

Every stage of the real plan (tokenizer -> training data -> transformer ->
training -> generation) runs here in a few seconds, printing what it does.
The model can only memorise the sentence; seeing that is part of the lesson.

Run:  python one_sentence_llm.py   (needs torch)
"""
import math
import re
from collections import Counter

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

torch.manual_seed(0)

CORPUS = "the cat sat on the mat and the cat was happy."
NUM_GLUES = 12
show = lambda b: b.decode("utf-8", "replace").replace(" ", "␣")


def banner(title):
    print(f"\n{'=' * 70}\n{title}\n{'=' * 70}")


# ---------------------------------------------------------------- 1. corpus
banner("1. CORPUS")
print(repr(CORPUS), f"({len(CORPUS)} characters)")

# ------------------------------------------------------------- 2. tokenizer
banner(f"2. TOKENIZER: 256 bytes + {NUM_GLUES} glue rules")
words = Counter(re.findall(r" ?\w+| ?[^\s\w]+", CORPUS))
seqs = {w: list(w.encode()) for w in words}
vocab = {i: bytes([i]) for i in range(256)}
merges = []
for r in range(NUM_GLUES):
    pairs = Counter()
    for w, s in seqs.items():
        for a, b in zip(s, s[1:]):
            pairs[(a, b)] += words[w]
    if not pairs:
        break
    (a, b), n = pairs.most_common(1)[0]
    new = 256 + r
    vocab[new] = vocab[a] + vocab[b]
    merges.append((a, b))
    print(f"   rule {r + 1:2}: {show(vocab[a])!r:7} + {show(vocab[b])!r:7} -> {new} {show(vocab[new])!r:9} (seen {n}x)")
    for w, s in seqs.items():
        out, i = [], 0
        while i < len(s):
            if i + 1 < len(s) and (s[i], s[i + 1]) == (a, b):
                out.append(new)
                i += 2
            else:
                out.append(s[i])
                i += 1
        seqs[w] = out
VOCAB_SIZE = 256 + len(merges)


def encode(text):
    ids = []
    for w in re.findall(r" ?\w+| ?[^\s\w]+", text):
        s = list(w.encode())
        for k, (a, b) in enumerate(merges):
            out, i = [], 0
            while i < len(s):
                if i + 1 < len(s) and (s[i], s[i + 1]) == (a, b):
                    out.append(256 + k)
                    i += 2
                else:
                    out.append(s[i])
                    i += 1
            s = out
        ids += s
    return ids


def decode(ids):
    return b"".join(vocab[i] for i in ids).decode("utf-8", "replace")


ids = encode(CORPUS)
assert decode(ids) == CORPUS
print(f"\n   sentence -> {len(ids)} bricks: " + " | ".join(show(vocab[i]) for i in ids))
print(f"   numbers  -> {ids}")

# --------------------------------------------------------- 3. training data
banner("3. TRAINING DATA: every position is one 'guess the next brick' lesson")
x = torch.tensor(ids[:-1]).unsqueeze(0)   # what the model sees
y = torch.tensor(ids[1:]).unsqueeze(0)    # what it should guess next
for t in range(4):
    print(f"   sees {decode(ids[:t + 1])!r:22} -> should guess {show(vocab[ids[t + 1]])!r}")
print(f"   ... {x.shape[1]} lessons in total from one sentence")

# ------------------------------------------------------------------ 4. model
banner("4. MODEL: a tiny transformer (same parts as the real one, much smaller)")
D, HEADS, BLOCKS, CTX = 32, 2, 1, len(ids)


class Block(nn.Module):
    def __init__(self):
        super().__init__()
        self.ln1, self.ln2 = nn.LayerNorm(D), nn.LayerNorm(D)
        self.attn = nn.MultiheadAttention(D, HEADS, batch_first=True)
        self.mlp = nn.Sequential(nn.Linear(D, 4 * D), nn.GELU(), nn.Linear(4 * D, D))

    def forward(self, h):
        T = h.shape[1]
        no_peeking = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=1)
        a = self.ln1(h)
        h = h + self.attn(a, a, a, attn_mask=no_peeking, need_weights=False)[0]
        return h + self.mlp(self.ln2(h))


class TinyGPT(nn.Module):
    def __init__(self):
        super().__init__()
        self.tok = nn.Embedding(VOCAB_SIZE, D)   # brick number -> 32 numbers
        self.pos = nn.Embedding(CTX, D)          # position -> 32 numbers
        self.blocks = nn.Sequential(*[Block() for _ in range(BLOCKS)])
        self.ln = nn.LayerNorm(D)
        # Start with small numbers, as GPT-2 does. PyTorch's default (std 1.0)
        # makes the first scores huge: first loss ~20 instead of ~ln(vocab).
        nn.init.normal_(self.tok.weight, std=0.02)
        nn.init.normal_(self.pos.weight, std=0.02)

    def forward(self, idx):
        h = self.tok(idx) + self.pos(torch.arange(idx.shape[1]))
        h = self.ln(self.blocks(h))
        return h @ self.tok.weight.T            # a score for every brick (weight tying)


model = TinyGPT()
print(f"   vocab {VOCAB_SIZE}, width {D}, heads {HEADS}, blocks {BLOCKS}, context {CTX}")
print(f"   parameters: {sum(p.numel() for p in model.parameters()):,}")


@torch.no_grad()
def generate(prompt, n):
    seq = encode(prompt)
    for _ in range(n):
        logits = model(torch.tensor(seq[-CTX:]).unsqueeze(0))[0, -1]
        seq.append(int(logits.argmax()))          # greedy: always the top score
    return decode(seq)


def loss_now():
    logits = model(x)
    return F.cross_entropy(logits.view(-1, VOCAB_SIZE), y.view(-1))


# --------------------------------------------------------------- 5. training
banner("5. TRAINING: show -> guess -> score (loss) -> nudge, repeated")
print(f"   expected first loss for pure guessing: ln({VOCAB_SIZE}) = {math.log(VOCAB_SIZE):.2f}")
opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
for step in range(301):
    loss = loss_now()
    if step in (0, 25, 50, 100, 200, 300):
        out = generate("the", len(ids) - 1)
        print(f"   step {step:3}  loss {loss.item():5.2f}   writes: {out!r}")
    opt.zero_grad()
    loss.backward()
    opt.step()

# ------------------------------------------------------------- 6. try it out
banner("6. TRY IT: what did it learn?")
for prompt in ["the", "the cat", "the mat", "the dog"]:
    print(f"   prompt {prompt!r:10} -> {generate(prompt, 8)!r}")
