"""Twilight-135M: a standalone PyTorch implementation for loading and sampling.

    pip install torch safetensors tokenizers
    python twilight.py "The heart is a muscle that"

Licensed under the Apache License, Version 2.0. See LICENSE.
"""
import json
import sys
from pathlib import Path

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

HERE = Path(__file__).parent


class Block(nn.Module):
    def __init__(self, c):
        super().__init__()
        w, hd = c["width"], c["head_dim"]
        self.q_heads, self.kv_heads, self.head_dim = c["query_heads"], c["key_value_heads"], hd
        self.qkv = nn.Linear(w, (c["query_heads"] + 2 * c["key_value_heads"]) * hd, bias=False)
        self.out = nn.Linear(w, w, bias=False)
        self.gate_up = nn.Linear(w, 2 * c["feed_forward"], bias=False)
        self.down = nn.Linear(c["feed_forward"], w, bias=False)
        self.n = nn.RMSNorm(w, eps=c["norm_eps"])  # before attention
        self.r = nn.RMSNorm(w, eps=c["norm_eps"])  # before feed-forward

    def forward(self, x, cos, sin):
        b, s, w = x.shape
        q, k, v = self.qkv(self.n(x)).split(
            [self.q_heads * self.head_dim, self.kv_heads * self.head_dim, self.kv_heads * self.head_dim], dim=-1)
        q, k, v = [z.view(b, s, -1, self.head_dim).transpose(1, 2) for z in (q, k, v)]
        q, k = rotate(q, cos, sin), rotate(k, cos, sin)
        a = F.scaled_dot_product_attention(q, k, v, is_causal=True, enable_gqa=True)
        x = x + self.out(a.transpose(1, 2).reshape(b, s, w))
        gate, up = self.gate_up(self.r(x)).chunk(2, dim=-1)
        return x + self.down(F.silu(gate) * up)


def rotate(z, cos, sin):
    a, b = z.chunk(2, dim=-1)
    return z * cos + torch.cat((-b, a), dim=-1) * sin


class Twilight(nn.Module):
    def __init__(self, c):
        super().__init__()
        self.config = c
        self.e = nn.Embedding(c["vocab_size"], c["width"])
        self.blocks = nn.ModuleList([Block(c) for _ in range(c["layers"])])
        self.norm = nn.RMSNorm(c["width"], eps=c["norm_eps"])
        hd = c["head_dim"]
        phase = torch.outer(torch.arange(c["context"]).float(),
                            c["rope_theta"] ** (-torch.arange(0, hd, 2).float() / hd)).repeat(1, 2)
        self.register_buffer("cos", phase.cos(), persistent=False)
        self.register_buffer("sin", phase.sin(), persistent=False)

    def forward(self, ids):
        """ids: (batch, seq) token ids, seq <= 512. Returns logits (batch, seq, vocab)."""
        n = ids.shape[1]
        x = self.e(ids)
        for block in self.blocks:
            x = block(x, self.cos[:n], self.sin[:n])
        return F.linear(self.norm(x), self.e.weight)  # input and output embeddings are tied


def load(path=HERE, device=None):
    from safetensors.torch import load_file
    from tokenizers import Tokenizer
    path = Path(path)
    device = device or ("cuda" if torch.cuda.is_available()
                        else "mps" if torch.backends.mps.is_available() else "cpu")
    model = Twilight(json.loads((path / "config.json").read_text()))
    # Weights are sharded; the index maps each tensor to its file.
    index = json.loads((path / "model.safetensors.index.json").read_text())
    state = {}
    for shard in sorted(set(index["weight_map"].values())):
        state.update(load_file(str(path / shard)))
    model.load_state_dict(state)
    return model.to(device).eval(), Tokenizer.from_file(str(path / "tokenizer.json"))


@torch.no_grad()
def generate(model, tokenizer, prompt, tokens=100, temperature=0.8, top_p=0.9, repetition_penalty=1.15):
    device = next(model.parameters()).device
    ids = tokenizer.encode(prompt, add_special_tokens=False).ids
    start = len(ids)
    for _ in range(tokens):
        z = model(torch.tensor([ids[-model.config["context"]:]], device=device))[0, -1].float()
        if len(ids) > start:
            seen = torch.tensor(sorted(set(ids[start:])), device=device)
            z[seen] = torch.where(z[seen] > 0, z[seen] / repetition_penalty, z[seen] * repetition_penalty)
        if temperature <= 0:
            nxt = int(z.argmax())
        else:
            p, order = torch.softmax(z / temperature, -1).sort(descending=True)
            p = p * (p.cumsum(0) - p < top_p)
            nxt = int(order[torch.multinomial(p / p.sum(), 1)])
        if nxt == model.config["eos_token_id"]:
            break
        ids.append(nxt)
    return tokenizer.decode(ids)


if __name__ == "__main__":
    model, tokenizer = load()
    print(generate(model, tokenizer, sys.argv[1] if len(sys.argv) > 1 else "The heart is a muscle that"))
