"""SI4World: same data, same split, same evaluation as lm02_gpt.py; only model size and training amount change.

  python lm04_scale.py --layers 1 --dim 16 --heads 2 --ff 32 --steps 2400 --batch 12      # the lesson's small model
  python lm04_scale.py --layers 4 --dim 128 --heads 4 --ff 512 --steps 6000 --batch 32
"""
import argparse, json, math, random, time
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
from lm02_gpt import prepare, BOS, EOS, UNK

CONTEXT = 32


class Block(nn.Module):
    def __init__(self, d, heads, ff):
        super().__init__()
        self.heads = heads
        self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
        self.q, self.k, self.v, self.o = (nn.Linear(d, d, bias=False) for _ in range(4))
        self.ff1, self.ff2 = nn.Linear(d, ff), nn.Linear(ff, d)

    def forward(self, x, mask):
        b, n, d = x.shape
        u = self.ln1(x)
        split = lambda z: z.view(b, n, self.heads, d // self.heads).transpose(1, 2)
        q, k, v = split(self.q(u)), split(self.k(u)), split(self.v(u))
        a = ((q @ k.transpose(-1, -2)) / math.sqrt(d // self.heads)).masked_fill(mask[:n, :n], float('-inf')).softmax(-1)
        x = x + self.o((a @ v).transpose(1, 2).reshape(b, n, d))
        return x + self.ff2(F.relu(self.ff1(self.ln2(x))))


class Poet(nn.Module):
    def __init__(self, vocab, layers, d, heads, ff):
        super().__init__()
        self.embedding, self.position = nn.Embedding(vocab, d), nn.Embedding(CONTEXT, d)
        self.blocks = nn.ModuleList(Block(d, heads, ff) for _ in range(layers))
        self.final = nn.LayerNorm(d)
        self.register_buffer('mask', torch.triu(torch.ones(CONTEXT, CONTEXT, dtype=torch.bool), 1))
        for m in self.modules():
            if isinstance(m, (nn.Linear, nn.Embedding)):
                nn.init.normal_(m.weight, std=.02)
                if isinstance(m, nn.Linear) and m.bias is not None:
                    nn.init.zeros_(m.bias)

    def forward(self, ids):
        x = self.embedding(ids) + self.position(torch.arange(ids.shape[1]))
        for blk in self.blocks:
            x = blk(x, self.mask)
        return F.linear(self.final(x), self.embedding.weight)


def make_batch(seqs, idx, rng=None):
    x = torch.full((len(idx), CONTEXT), BOS, dtype=torch.long)
    y = torch.full_like(x, -100)
    for r, i in enumerate(idx):
        s = seqs[i]
        st = rng.randrange(max(1, len(s) - 1)) if rng else 0
        seg = s[st:st + CONTEXT + 1]
        x[r, :len(seg) - 1] = torch.tensor(seg[:-1])
        y[r, :len(seg) - 1] = torch.tensor(seg[1:])
    return x, y


@torch.no_grad()
def evaluate(model, seqs, idx):
    model.eval(); tot = cnt = 0
    for s in range(0, len(idx), 32):
        x, y = make_batch(seqs, idx[s:s + 32])
        lg = model(x)
        tot += F.cross_entropy(lg.reshape(-1, lg.shape[-1]), y.reshape(-1), reduction='sum').item()
        cnt += (y != -100).sum().item()
    return tot / cnt


@torch.no_grad()
def generate(model, vocab, prefix, k, temperature, seed, greedy=False):
    lookup = {c: i for i, c in enumerate(vocab)}
    ids = [BOS] + [lookup.get(c, UNK) for c in prefix]
    g = torch.Generator().manual_seed(seed)
    model.eval()
    while len(ids) < CONTEXT:
        z = model(torch.tensor([ids]))[0, -1]
        z[BOS] = z[UNK] = -float('inf')
        if greedy:
            nxt = int(z.argmax())
        else:
            top = torch.topk(z / temperature, k)
            nxt = int(top.indices[torch.multinomial(top.values.softmax(-1), 1, generator=g)])
        if nxt == EOS:
            break
        ids.append(nxt)
    return ''.join(vocab[i] for i in ids[1:])


def main():
    p = argparse.ArgumentParser()
    for name, default in [('layers', 1), ('dim', 16), ('heads', 2), ('ff', 32), ('steps', 2400), ('batch', 12), ('seed', 20261108), ('threads', 2)]:
        p.add_argument('--' + name, type=int, default=default)
    p.add_argument('--lr', type=float, default=.004)
    p.add_argument('--cosine', action='store_true', help='cosine-decay the learning rate to 10%')
    p.add_argument('--save', type=Path)
    a = p.parse_args()
    torch.set_num_threads(a.threads); torch.manual_seed(a.seed); random.seed(a.seed)
    _, _, vocab, train, val = prepare(Path(__file__).resolve().parent)
    model = Poet(len(vocab), a.layers, a.dim, a.heads, a.ff)
    params = sum(t.numel() for t in model.parameters())
    opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=.01)
    rng = random.Random(a.seed)
    t0 = time.perf_counter()
    for step in range(a.steps):
        if a.cosine:
            for gr in opt.param_groups:
                gr['lr'] = a.lr * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * step / a.steps)))
        model.train()
        x, y = make_batch(train, [rng.randrange(len(train)) for _ in range(a.batch)], rng)
        loss = F.cross_entropy(model(x).reshape(-1, len(vocab)), y.reshape(-1))
        opt.zero_grad(set_to_none=True); loss.backward()
        nn.utils.clip_grad_norm_(model.parameters(), 1.); opt.step()
        if (step + 1) % max(1, a.steps // 10) == 0:
            print(json.dumps(dict(step=step + 1, trainBatchLoss=round(loss.item(), 3), seconds=round(time.perf_counter() - t0, 1))), flush=True)
    secs = time.perf_counter() - t0
    full_val = evaluate(model, val, list(range(len(val))))
    train_probe = evaluate(model, train, random.Random(41).sample(range(len(train)), 316))
    samples = dict(greedy=[generate(model, vocab, s, 1, 1, 0, True) for s in ['春风', '明月', '山中']],
                   top8=[generate(model, vocab, s, 8, 0.8, sd) for s in ['春风', '明月', '山中'] for sd in (1, 2)])
    out = dict(layers=a.layers, dim=a.dim, heads=a.heads, ff=a.ff, steps=a.steps, batch=a.batch, lr=a.lr, cosine=a.cosine,
               params=params, embeddingParams=len(vocab) * a.dim, seconds=round(secs, 1), fullValidationLoss=round(full_val, 4),
               train316Loss=round(train_probe, 4), perplexity=round(math.exp(full_val), 1), samples=samples)
    print(json.dumps(out, ensure_ascii=False), flush=True)
    if a.save:
        torch.save(dict(state=model.state_dict(), args=vars(a), vocab=vocab), a.save)


if __name__ == '__main__':
    main()
