"""
Tiny transformer LLM with every weight set by hand. No training.

Language (two sentences, chosen at random each time):
    . the cat sat on the mat .
    . the dog ran to the park .

A bigram model cannot finish the second "the" (mat or park?) because it only
sees the current token. This model fixes that with one attention head that
copies the previous token, plus an MLP that combines "current" and "previous".

Residual stream layout (d_model = 10 + T + 10 + 10):
    [ tok (10) | pos (T) | prev tok (10) | hint (10) ]

Usage:
    python tiny_llm.py                 # weights, attention map, samples, test
    python tiny_llm.py ". the dog"     # complete a prompt
"""
import sys
import numpy as np

np.set_printoptions(precision=2, suppress=True, linewidth=140)

VOCAB = [".", "the", "cat", "dog", "sat", "ran", "on", "to", "mat", "park"]
ID = {t: i for i, t in enumerate(VOCAB)}
V = len(VOCAB)
T = 64                      # max context length

# residual stream slices
TOK = slice(0, V)
POS = slice(V, V + T)
PREV = slice(V + T, V + T + V)
HINT = slice(V + T + V, V + T + 2 * V)
D = V + T + 2 * V           # d_model = 94

# ---------------------------------------------------------------- embeddings
W_E = np.zeros((V, D)); W_E[:, TOK] = np.eye(V)          # token -> tok slot
W_P = np.zeros((T, D)); W_P[:, POS] = np.eye(T)          # position -> pos slot

# ---------------------------------------------------------- attention head
# Goal: position i attends to position i-1.
# query(i) = one-hot(i), key(j) = one-hot(j+1)  ->  q.k = 1 only when j = i-1
SCALE = 30.0
W_Q = np.zeros((D, T)); W_Q[POS, :] = np.eye(T) * SCALE
W_K = np.zeros((D, T)); W_K[POS, :] = np.eye(T, k=1)     # pos j -> slot j+1
# value/output: copy the token one-hot into the "prev" slot
W_V = np.zeros((D, V)); W_V[TOK, :] = np.eye(V)
W_O = np.zeros((V, D)); W_O[:, PREV] = np.eye(V)

# --------------------------------------------------------------------- MLP
# Each hidden neuron is an AND gate: ReLU(cur + prev - 1) is 1 only if both on.
NEURONS = [  # (current, previous, next tokens to boost)
    ("the", ".",  ["cat", "dog"]),
    ("the", "on", ["mat"]),
    ("the", "to", ["park"]),
]
H = len(NEURONS)
W_in = np.zeros((D, H)); b_in = -np.ones(H)
W_out = np.zeros((H, D))
for n, (cur, prev, nxt) in enumerate(NEURONS):
    W_in[TOK.start + ID[cur], n] = 1.0
    W_in[PREV.start + ID[prev], n] = 1.0
    for t in nxt:
        W_out[n, HINT.start + ID[t]] = 1.0

# ------------------------------------------------------------- unembedding
# Bigram part (reads current token) + hint part (reads MLP output).
BIGRAM = {".": ["the"], "the": ["cat", "dog", "mat", "park"], "cat": ["sat"],
          "dog": ["ran"], "sat": ["on"], "ran": ["to"], "on": ["the"],
          "to": ["the"], "mat": ["."], "park": ["."]}
W_U = np.zeros((D, V))
for cur, nxts in BIGRAM.items():
    for t in nxts:
        W_U[TOK.start + ID[cur], ID[t]] = 20.0
W_U[HINT, :] = np.eye(V) * 20.0


def softmax(x, axis=-1):
    e = np.exp(x - x.max(axis=axis, keepdims=True))
    return e / e.sum(axis=axis, keepdims=True)


def forward(tokens, use_attention=True):
    """tokens: list[str]. Returns (next-token probs per position, attention)."""
    ids = [ID[t] for t in tokens][-T:]
    n = len(ids)
    x = W_E[ids] + W_P[:n]                          # (n, D)

    scores = (x @ W_Q) @ (x @ W_K).T                # (n, n)
    scores[np.triu(np.ones((n, n), bool), 1)] = -np.inf   # causal mask
    attn = softmax(scores)
    if use_attention:
        x = x + attn @ (x @ W_V) @ W_O              # residual add

    h = np.maximum(0, x @ W_in + b_in)              # MLP
    x = x + h @ W_out                               # residual add

    return softmax(x @ W_U), attn


def generate(prompt, max_new=40, rng=None, use_attention=True):
    rng = rng or np.random.default_rng()
    toks = list(prompt)
    for _ in range(max_new):
        p, _ = forward(toks, use_attention)
        toks.append(rng.choice(VOCAB, p=p[-1]))
        if len(toks) >= T:
            break
    return toks


def is_valid(toks):
    text = " ".join(toks)
    allowed = {"the cat sat on the mat", "the dog ran to the park"}
    sents = [s.strip() for s in text.split(".")]
    return all(s in allowed for s in sents[1:-1])   # ignore cut-off last one


def table(M, rows, cols, fmt="{:5.0f}"):
    out = "       " + " ".join(f"{c:>5}" for c in cols) + "\n"
    for r, row in zip(rows, M):
        out += f"{r:>6} " + " ".join(fmt.format(v) for v in row) + "\n"
    return out


if __name__ == "__main__":
    if len(sys.argv) > 1:
        prompt = sys.argv[1].split()
        print(" ".join(generate(prompt, max_new=20)))
        sys.exit()

    print("d_model =", D, "| total weights =",
          sum(w.size for w in [W_E, W_P, W_Q, W_K, W_V, W_O, W_in, b_in, W_out, W_U]))
    print("\nW_U, bigram part (rows = current token):")
    print(table(W_U[TOK], VOCAB, VOCAB))
    print("MLP neurons (AND gates):")
    for cur, prev, nxt in NEURONS:
        print(f"  current={cur!r} AND previous={prev!r}  ->  boost {nxt}")

    seq = ". the dog ran to the park .".split()
    p, attn = forward(seq)
    print("\nAttention map for:", " ".join(seq))
    print(table(attn, seq, seq, "{:5.2f}"))
    print("Next-token prediction at each position:")
    for i, t in enumerate(seq):
        top = np.argsort(-p[i])[:2]
        print(f"  after {' '.join(seq[:i+1]):<28} -> "
              + ", ".join(f"{VOCAB[j]} {p[i, j]:.3f}" for j in top))

    rng = np.random.default_rng(7)
    print("\nSamples (with attention):")
    for _ in range(3):
        print("  ", " ".join(generate(["."], 24, rng)))
    print("Samples (attention switched off = bigram):")
    for _ in range(3):
        print("  ", " ".join(generate(["."], 24, rng, use_attention=False)))

    N = 1000
    ok_attn = sum(is_valid(generate(["."], 40, rng)) for _ in range(N))
    ok_bi = sum(is_valid(generate(["."], 40, rng, use_attention=False)) for _ in range(N))
    print(f"\nTest: {N} generations of 40 tokens, all sentences valid?")
    print(f"  with attention:    {ok_attn}/{N}")
    print(f"  without attention: {ok_bi}/{N}")
