"""A small GPT-style transformer in one file: tokenizer, model, training and sampling.

Read it top to bottom; every block has a comment explaining what it does and why.

    python gpt.py train  --data input.txt --preset tiny          # train (CPU-friendly preset)
    python gpt.py sample --ckpt out/ckpt.pt --prompt "Once upon"  # generate text
    python gpt.py info   --preset small                           # print parameter count

Requires Python 3.10+ and PyTorch 2.1+ (for nn.LayerNorm(bias=...) and
F.scaled_dot_product_attention). No other dependencies.
"""
from __future__ import annotations

import argparse
import math
import os
import time
from contextlib import nullcontext
from dataclasses import asdict, dataclass

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


# ---------------------------------------------------------------------------
# 1. Configuration
# ---------------------------------------------------------------------------
@dataclass
class GPTConfig:
    vocab_size: int = 256     # number of distinct tokens (set from the tokenizer)
    block_size: int = 128     # maximum context length in tokens
    n_layer: int = 4          # number of transformer blocks stacked on top of each other
    n_head: int = 4           # attention heads per block
    n_embd: int = 128         # width of every token vector (the "model dimension")
    dropout: float = 0.1      # regularization; use 0.0 for large datasets
    bias: bool = False        # biases in Linear/LayerNorm; False is slightly faster and works as well
    manual_attention: bool = False  # True = use the explicit attention math below (slower, for learning)


PRESETS = {
    # about 0.8M parameters: trains on a laptop CPU
    "tiny": dict(n_layer=4, n_head=4, n_embd=128, block_size=128, dropout=0.1),
    # about 10.8M parameters: wants a GPU or Apple-silicon GPU (MPS)
    "small": dict(n_layer=6, n_head=6, n_embd=384, block_size=256, dropout=0.2),
}


# ---------------------------------------------------------------------------
# 2. Tokenizers: text <-> integer ids
# ---------------------------------------------------------------------------
class CharTokenizer:
    """One token per distinct character in the training text. Tiny vocabulary, easy to read."""

    def __init__(self, chars: list[str]):
        self.chars = chars
        self.stoi = {c: i for i, c in enumerate(chars)}

    @classmethod
    def from_text(cls, text: str) -> "CharTokenizer":
        return cls(sorted(set(text)))

    @property
    def vocab_size(self) -> int:
        return len(self.chars)

    def encode(self, text: str) -> list[int]:
        unknown = set(text) - self.stoi.keys()
        if unknown:
            raise ValueError(f"characters not in vocabulary: {''.join(sorted(unknown))!r}")
        return [self.stoi[c] for c in text]

    def decode(self, ids: list[int]) -> str:
        return "".join(self.chars[i] for i in ids)

    def state(self) -> dict:
        return {"kind": "char", "chars": self.chars}


class ByteTokenizer:
    """One token per UTF-8 byte. Fixed vocabulary of 256, handles any text."""

    vocab_size = 256

    def encode(self, text: str) -> list[int]:
        return list(text.encode("utf-8"))

    def decode(self, ids: list[int]) -> str:
        return bytes(ids).decode("utf-8", errors="replace")

    def state(self) -> dict:
        return {"kind": "byte"}


def tokenizer_from_state(state: dict):
    return CharTokenizer(state["chars"]) if state["kind"] == "char" else ByteTokenizer()


# ---------------------------------------------------------------------------
# 3. The model
# ---------------------------------------------------------------------------
class CausalSelfAttention(nn.Module):
    """Every token looks at itself and earlier tokens and takes a weighted mix of their values."""

    def __init__(self, cfg: GPTConfig):
        super().__init__()
        assert cfg.n_embd % cfg.n_head == 0, "n_embd must be divisible by n_head"
        self.n_head = cfg.n_head
        self.head_size = cfg.n_embd // cfg.n_head
        self.dropout = cfg.dropout
        self.manual = cfg.manual_attention
        # One Linear produces queries, keys and values for all heads at once.
        self.qkv = nn.Linear(cfg.n_embd, 3 * cfg.n_embd, bias=cfg.bias)
        # Output projection mixes the heads back together.
        self.proj = nn.Linear(cfg.n_embd, cfg.n_embd, bias=cfg.bias)
        self.attn_drop = nn.Dropout(cfg.dropout)
        self.resid_drop = nn.Dropout(cfg.dropout)
        # Lower-triangular mask: position t may attend to positions 0..t only.
        mask = torch.tril(torch.ones(cfg.block_size, cfg.block_size, dtype=torch.bool))
        self.register_buffer("mask", mask.view(1, 1, cfg.block_size, cfg.block_size), persistent=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        B, T, C = x.shape  # batch, time (sequence length), channels (n_embd)
        q, k, v = self.qkv(x).split(C, dim=2)
        # Split channels into heads: (B, T, C) -> (B, n_head, T, head_size)
        q = q.view(B, T, self.n_head, self.head_size).transpose(1, 2)
        k = k.view(B, T, self.n_head, self.head_size).transpose(1, 2)
        v = v.view(B, T, self.n_head, self.head_size).transpose(1, 2)

        if self.manual:
            # The textbook formula: softmax(Q K^T / sqrt(d)) V, with future positions masked out.
            att = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_size)   # (B, nh, T, T)
            att = att.masked_fill(~self.mask[:, :, :T, :T], float("-inf"))
            att = F.softmax(att, dim=-1)
            att = self.attn_drop(att)
            y = att @ v                                                     # (B, nh, T, hs)
        else:
            # Same math, fused into one fast kernel (FlashAttention where available).
            y = F.scaled_dot_product_attention(
                q, k, v, dropout_p=self.dropout if self.training else 0.0, is_causal=True)

        # Put the heads side by side again: (B, nh, T, hs) -> (B, T, C)
        y = y.transpose(1, 2).contiguous().view(B, T, C)
        return self.resid_drop(self.proj(y))


class MLP(nn.Module):
    """A per-token feed-forward network: expand 4x, apply GELU, project back."""

    def __init__(self, cfg: GPTConfig):
        super().__init__()
        self.fc1 = nn.Linear(cfg.n_embd, 4 * cfg.n_embd, bias=cfg.bias)
        self.fc2 = nn.Linear(4 * cfg.n_embd, cfg.n_embd, bias=cfg.bias)
        self.drop = nn.Dropout(cfg.dropout)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.drop(self.fc2(F.gelu(self.fc1(x))))


class Block(nn.Module):
    """Pre-norm transformer block: x + attention(norm(x)), then x + mlp(norm(x))."""

    def __init__(self, cfg: GPTConfig):
        super().__init__()
        self.ln1 = nn.LayerNorm(cfg.n_embd, bias=cfg.bias)
        self.attn = CausalSelfAttention(cfg)
        self.ln2 = nn.LayerNorm(cfg.n_embd, bias=cfg.bias)
        self.mlp = MLP(cfg)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = x + self.attn(self.ln1(x))   # tokens exchange information
        x = x + self.mlp(self.ln2(x))    # each token processes what it gathered
        return x


class GPT(nn.Module):
    def __init__(self, cfg: GPTConfig):
        super().__init__()
        self.cfg = cfg
        self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.n_embd)   # token id -> vector
        self.pos_emb = nn.Embedding(cfg.block_size, cfg.n_embd)   # position -> vector (learned)
        self.drop = nn.Dropout(cfg.dropout)
        self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layer)])
        self.ln_f = nn.LayerNorm(cfg.n_embd, bias=cfg.bias)
        self.lm_head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False)  # vector -> score per token
        # Weight tying: the input embedding and output layer share one matrix.
        # Fewer parameters, and usually slightly better results for small models.
        self.tok_emb.weight = self.lm_head.weight
        self.apply(self._init_weights)
        # Scale down the layers that write into the residual stream, so its variance
        # does not grow with depth (as in GPT-2).
        for name, p in self.named_parameters():
            if name.endswith("proj.weight") or name.endswith("fc2.weight"):
                nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * cfg.n_layer))

    @staticmethod
    def _init_weights(module: nn.Module) -> None:
        if isinstance(module, nn.Linear):
            nn.init.normal_(module.weight, mean=0.0, std=0.02)
            if module.bias is not None:
                nn.init.zeros_(module.bias)
        elif isinstance(module, nn.Embedding):
            nn.init.normal_(module.weight, mean=0.0, std=0.02)

    def num_params(self, include_position: bool = True) -> int:
        n = sum(p.numel() for p in self.parameters())  # tied weights are counted once
        return n if include_position else n - self.pos_emb.weight.numel()

    def forward(self, idx: torch.Tensor, targets: torch.Tensor | None = None):
        B, T = idx.shape
        if T > self.cfg.block_size:
            raise ValueError(f"sequence length {T} exceeds block_size {self.cfg.block_size}")
        pos = torch.arange(T, device=idx.device)
        x = self.drop(self.tok_emb(idx) + self.pos_emb(pos))  # (B, T, C)
        for block in self.blocks:
            x = block(x)
        logits = self.lm_head(self.ln_f(x))                    # (B, T, vocab)
        loss = None
        if targets is not None:
            # Every position predicts the next token: average cross-entropy over all of them.
            loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
        return logits, loss

    @torch.no_grad()
    def generate(self, idx: torch.Tensor, max_new_tokens: int, temperature: float = 1.0,
                 top_k: int | None = None) -> torch.Tensor:
        """Append max_new_tokens tokens to idx, sampling one at a time."""
        for _ in range(max_new_tokens):
            idx_cond = idx[:, -self.cfg.block_size:]          # crop to the context window
            logits, _ = self(idx_cond)
            logits = logits[:, -1, :] / max(temperature, 1e-6)  # only the last position matters
            if top_k is not None:
                v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
                logits[logits < v[:, [-1]]] = float("-inf")      # keep only the k best tokens
            probs = F.softmax(logits, dim=-1)
            next_id = torch.multinomial(probs, num_samples=1)
            idx = torch.cat((idx, next_id), dim=1)
        return idx

    def configure_optimizer(self, lr: float, weight_decay: float, device_type: str):
        # Decay matrices (weights of Linear/Embedding), not biases or LayerNorm gains.
        decay = [p for p in self.parameters() if p.requires_grad and p.dim() >= 2]
        no_decay = [p for p in self.parameters() if p.requires_grad and p.dim() < 2]
        groups = [{"params": decay, "weight_decay": weight_decay},
                  {"params": no_decay, "weight_decay": 0.0}]
        extra = {"fused": True} if device_type == "cuda" else {}
        return torch.optim.AdamW(groups, lr=lr, betas=(0.9, 0.95), **extra)


# ---------------------------------------------------------------------------
# 4. Training utilities
# ---------------------------------------------------------------------------
def pick_device(requested: str = "auto") -> str:
    if requested != "auto":
        return requested
    if torch.cuda.is_available():
        return "cuda"
    if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
        return "mps"
    return "cpu"


def lr_at(it: int, max_lr: float, min_lr: float, warmup: int, max_iters: int) -> float:
    """Linear warmup, then cosine decay from max_lr to min_lr."""
    if it < warmup:
        return max_lr * (it + 1) / warmup
    if it >= max_iters:
        return min_lr
    progress = (it - warmup) / max(1, max_iters - warmup)
    return min_lr + 0.5 * (1.0 + math.cos(math.pi * progress)) * (max_lr - min_lr)


def get_batch(data: torch.Tensor, block_size: int, batch_size: int, device: str):
    """Random windows of block_size tokens; targets are the same windows shifted by one."""
    ix = torch.randint(len(data) - block_size - 1, (batch_size,))
    x = torch.stack([data[i:i + block_size] for i in ix])
    y = torch.stack([data[i + 1:i + 1 + block_size] for i in ix])
    if device == "cuda":
        return x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True)
    return x.to(device), y.to(device)


@torch.no_grad()
def estimate_loss(model: GPT, splits: dict, block_size: int, batch_size: int, device: str,
                  eval_iters: int, ctx) -> dict:
    model.eval()
    out = {}
    for name, data in splits.items():
        losses = torch.zeros(eval_iters)
        for k in range(eval_iters):
            x, y = get_batch(data, block_size, batch_size, device)
            with ctx:
                _, loss = model(x, y)
            losses[k] = loss.item()
        out[name] = losses.mean().item()
    model.train()
    return out


def save_checkpoint(path: str, model: GPT, tokenizer, it: int, val_loss: float) -> None:
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    raw = getattr(model, "_orig_mod", model)  # unwrap torch.compile
    torch.save({"model": raw.state_dict(), "config": asdict(raw.cfg), "tokenizer": tokenizer.state(),
                "iter": it, "val_loss": val_loss}, path)


def load_checkpoint(path: str, device: str):
    ckpt = torch.load(path, map_location=device, weights_only=True)
    model = GPT(GPTConfig(**ckpt["config"]))
    model.load_state_dict(ckpt["model"])
    return model.to(device), tokenizer_from_state(ckpt["tokenizer"]), ckpt


# ---------------------------------------------------------------------------
# 5. Commands
# ---------------------------------------------------------------------------
def train(args) -> None:
    torch.manual_seed(args.seed)
    device = pick_device(args.device)
    device_type = "cuda" if device.startswith("cuda") else device
    with open(args.data, encoding="utf-8") as fh:
        text = fh.read()
    tokenizer = CharTokenizer.from_text(text) if args.tokenizer == "char" else ByteTokenizer()
    data = torch.tensor(tokenizer.encode(text), dtype=torch.long)
    n = int(len(data) * 0.9)
    splits = {"train": data[:n], "val": data[n:]}

    cfg = GPTConfig(vocab_size=tokenizer.vocab_size, **PRESETS[args.preset])
    if args.block_size:
        cfg.block_size = args.block_size
    if len(splits["val"]) <= cfg.block_size + 1:
        raise SystemExit("not enough text: need at least ~10x block_size characters for a validation split")
    model = GPT(cfg).to(device)
    print(f"device={device} tokens={len(data):,} vocab={cfg.vocab_size} params={model.num_params():,}")

    optimizer = model.configure_optimizer(args.lr, args.weight_decay, device_type)
    if args.compile:
        model = torch.compile(model)
    # bfloat16 autocast on CUDA GPUs that support it; full precision elsewhere.
    use_bf16 = device_type == "cuda" and torch.cuda.is_bf16_supported()
    ctx = torch.autocast(device_type="cuda", dtype=torch.bfloat16) if use_bf16 else nullcontext()

    best_val = float("inf")
    t0 = time.time()
    for it in range(args.max_iters + 1):
        lr = lr_at(it, args.lr, args.lr / 10, args.warmup, args.max_iters)
        for group in optimizer.param_groups:
            group["lr"] = lr

        if it % args.eval_interval == 0 or it == args.max_iters:
            losses = estimate_loss(model, splits, cfg.block_size, args.batch_size, device, args.eval_iters, ctx)
            print(f"iter {it:5d} | train {losses['train']:.4f} | val {losses['val']:.4f} | "
                  f"lr {lr:.2e} | {time.time() - t0:.0f}s")
            if losses["val"] < best_val:
                best_val = losses["val"]
                save_checkpoint(args.out, model, tokenizer, it, best_val)

        if it == args.max_iters:
            break
        x, y = get_batch(splits["train"], cfg.block_size, args.batch_size, device)
        with ctx:
            _, loss = model(x, y)
        optimizer.zero_grad(set_to_none=True)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)  # avoid rare exploding updates
        optimizer.step()

    print(f"best val loss {best_val:.4f}, checkpoint saved to {args.out}")


def sample(args) -> None:
    torch.manual_seed(args.seed)
    device = pick_device(args.device)
    model, tokenizer, ckpt = load_checkpoint(args.ckpt, device)
    model.eval()
    prompt_ids = tokenizer.encode(args.prompt) if args.prompt else [0]
    idx = torch.tensor([prompt_ids], dtype=torch.long, device=device)
    out = model.generate(idx, args.tokens, temperature=args.temperature, top_k=args.top_k)
    print(tokenizer.decode(out[0].tolist()))


def info(args) -> None:
    cfg = GPTConfig(vocab_size=args.vocab_size, **PRESETS[args.preset])
    model = GPT(cfg)
    print(f"preset={args.preset} {asdict(cfg)}")
    print(f"parameters: {model.num_params():,} (without position embeddings: {model.num_params(False):,})")


def main(argv=None) -> None:
    p = argparse.ArgumentParser(description="Train and sample a small GPT.")
    sub = p.add_subparsers(dest="cmd", required=True)

    t = sub.add_parser("train")
    t.add_argument("--data", required=True, help="path to a UTF-8 text file")
    t.add_argument("--preset", choices=PRESETS, default="tiny")
    t.add_argument("--tokenizer", choices=["char", "byte"], default="char")
    t.add_argument("--block-size", type=int, default=0, help="override the preset's context length")
    t.add_argument("--batch-size", type=int, default=32)
    t.add_argument("--max-iters", type=int, default=3000)
    t.add_argument("--eval-interval", type=int, default=250)
    t.add_argument("--eval-iters", type=int, default=50)
    t.add_argument("--lr", type=float, default=1e-3)
    t.add_argument("--warmup", type=int, default=100)
    t.add_argument("--weight-decay", type=float, default=0.1)
    t.add_argument("--device", default="auto", help="auto, cpu, cuda, cuda:1 or mps")
    t.add_argument("--compile", action="store_true", help="use torch.compile (CUDA, PyTorch 2.x)")
    t.add_argument("--out", default="out/ckpt.pt")
    t.add_argument("--seed", type=int, default=1337)
    t.set_defaults(func=train)

    s = sub.add_parser("sample")
    s.add_argument("--ckpt", default="out/ckpt.pt")
    s.add_argument("--prompt", default="")
    s.add_argument("--tokens", type=int, default=500)
    s.add_argument("--temperature", type=float, default=0.8)
    s.add_argument("--top-k", type=int, default=50)
    s.add_argument("--device", default="auto")
    s.add_argument("--seed", type=int, default=1337)
    s.set_defaults(func=sample)

    i = sub.add_parser("info")
    i.add_argument("--preset", choices=PRESETS, default="tiny")
    i.add_argument("--vocab-size", type=int, default=256)
    i.set_defaults(func=info)

    args = p.parse_args(argv)
    args.func(args)


if __name__ == "__main__":
    main()
