#!/usr/bin/env python3 """ Gen 2 Autoregressive Inference & 2-Head Causal Self-Attention Inspector Combines the trained 2-Head Causal Self-Attention Mini-Transformer (d_model=48, n_heads=2, d_ff=96) with a local Bigram/Trigram Induction Head bias for fluent, context-aware generation. """ import json import re import numpy as np TOKEN_RE = re.compile(r"[A-Za-z0-9_'-]+|[.,!?]") def softmax(x, axis=-1): x_max = np.max(x, axis=axis, keepdims=True) e = np.exp(x - x_max) return e / (np.sum(e, axis=axis, keepdims=True) + 1e-12) class Gen2ModelRunner: def __init__(self, npz_path, corpus_sents=None): data = np.load(npz_path, allow_pickle=True) self.vocab = [str(w) for w in data["vocab"]] self.w2i = {w: i for i, w in enumerate(self.vocab)} self.case_map = json.loads(str(data["case_map_json"])) self.loss_history = data["loss_history"].tolist() self.P = {k: data[k].astype(np.float32) for k in [ "W_emb", "W_pos", "W_Q", "W_K", "W_V", "W_O", "W_1", "b_1", "W_2", "b_2", "W_out", "b_out" ]} self.V, self.D = self.P["W_emb"].shape self.T = self.P["W_pos"].shape[0] self.H = 2 self.Dh = self.D // self.H # Build sparse bigram & trigram induction table over the vocabulary self.bigrams = {} self.trigrams = {} if corpus_sents: for s in corpus_sents: toks = [t.lower() for t in TOKEN_RE.findall(s) if t.lower() in self.w2i] for i in range(len(toks) - 1): u, v = self.w2i[toks[i]], self.w2i[toks[i + 1]] if u >= 4 and v >= 4: self.bigrams.setdefault(u, {})[v] = self.bigrams.get(u, {}).get(v, 0) + 1 for i in range(len(toks) - 2): u, v, w = self.w2i[toks[i]], self.w2i[toks[i + 1]], self.w2i[toks[i + 2]] if u >= 4 and v >= 4 and w >= 4: self.trigrams.setdefault((u, v), {})[w] = self.trigrams.get((u, v), {}).get(w, 0) + 1 def forward_single(self, token_ids): idx = token_ids[-self.T:] L = len(idx) P = self.P emb = P["W_emb"][idx] + P["W_pos"][:L] Q = emb @ P["W_Q"] K = emb @ P["W_K"] V = emb @ P["W_V"] Qh = Q.reshape(L, self.H, self.Dh).transpose(1, 0, 2) Kh = K.reshape(L, self.H, self.Dh).transpose(1, 0, 2) Vh = V.reshape(L, self.H, self.Dh).transpose(1, 0, 2) scale = 1.0 / np.sqrt(self.Dh) scores = np.matmul(Qh, Kh.transpose(0, 2, 1)) * scale causal_mask = np.triu(np.full((L, L), -1e9, dtype=np.float32), k=1) scores = scores + causal_mask[None, :, :] attn = softmax(scores, axis=-1) context_h = np.matmul(attn, Vh) context = context_h.transpose(1, 0, 2).reshape(L, self.D) attn_out = context @ P["W_O"] h1 = emb + attn_out ff_act = np.maximum(0.0, h1 @ P["W_1"] + P["b_1"]) h2 = h1 + (ff_act @ P["W_2"] + P["b_2"]) logits = (h2[-1] @ P["W_out"] + P["b_out"]).copy() return logits, attn def generate_with_attention(self, prompt="", max_words=20, temp=0.75): rng = np.random.default_rng() prompt_toks = [ t.lower() for t in TOKEN_RE.findall(prompt) if t.lower() in self.w2i and len(t) > 1 and t.lower() not in ("", "", "", "") ] seq = [1] # if prompt_toks: for pt in prompt_toks[-4:]: seq.append(self.w2i[pt]) else: word_ids = [i for i, w in enumerate(self.vocab) if i >= 4 and re.match(r"^[a-zA-Z]{3,}$", w)] seq.append(int(rng.choice(word_ids[:60]))) used_counts = {s: 1 for s in seq} punct_ids = {i for i, w in enumerate(self.vocab) if not re.match(r"^[A-Za-z0-9_'-]+$", w)} for step in range(max_words): logits, attn = self.forward_single(seq) # Suppress special tokens & stray punctuation spam for bad_id in [0, 1, 3]: logits[bad_id] = -1e9 for pid in punct_ids: if self.vocab[pid] not in (".", ",", "!", "?"): logits[pid] = -1e9 elif len(seq) >= 2 and seq[-1] in punct_ids: logits[pid] = -1e9 if step < 7: logits[2] = -1e9 # keep generating at least 7 tokens # Induction-head residual boost from bigram/trigram syntax last_tok = seq[-1] if len(seq) >= 2 and (seq[-2], seq[-1]) in self.trigrams: tri_counts = self.trigrams[(seq[-2], seq[-1])] total_tri = sum(tri_counts.values()) for nxt_id, c in tri_counts.items(): logits[nxt_id] += 2.6 * np.log1p(c / total_tri * 10.0) if last_tok in self.bigrams: bi_counts = self.bigrams[last_tok] total_bi = sum(bi_counts.values()) for nxt_id, c in bi_counts.items(): logits[nxt_id] += 1.8 * np.log1p(c / total_bi * 10.0) # Repetition penalty for tok_id, cnt in used_counts.items(): if tok_id >= 4: logits[tok_id] -= 1.8 * cnt scaled = logits / max(0.2, temp) top_k = 10 top_indices = np.argpartition(scaled, -top_k)[-top_k:] probs = softmax(scaled[top_indices]) chosen = int(rng.choice(top_indices, p=probs)) if chosen == 2: break seq.append(chosen) used_counts[chosen] = used_counts.get(chosen, 0) + 1 # Compute final attention matrix over the generated sequence window _, final_attn = self.forward_single(seq) win_ids = seq[-self.T:] win_tokens = [self.case_map.get(self.vocab[i], self.vocab[i]) for i in win_ids] words = [self.case_map.get(self.vocab[i], self.vocab[i]) for i in seq if i >= 4] text = " ".join(words) text = re.sub(r"\s+([.,!?])", r"\1", text) if text and text[0].islower(): text = text[0].upper() + text[1:] if text and text[-1] not in ".!?": text += "." return text, win_tokens, final_attn def generate(self, prompt="", max_words=20, temp=0.75): text, _, _ = self.generate_with_attention(prompt, max_words=max_words, temp=temp) return text if __name__ == "__main__": irc_sents = [r["text"] for r in json.load(open("/tmp/aivillage_corpus.json"))["entries"]] argon_sents = [r["text"] if isinstance(r, dict) else str(r) for r in json.load(open("/tmp/argon_corpus.json"))["entries"]] vil_sents = [r["text"] for r in json.load(open("/tmp/open_chat_corpus.json"))["records"]] for name, path, sents in [ ("IRC-GPT Gen2", "/tmp/irc_gpt_gen2.npz", irc_sents), ("ARGON-GPT Gen2", "/tmp/argon_gpt_gen2.npz", argon_sents), ("VILLAGE-GPT Gen2", "/tmp/village_gpt_gen2.npz", vil_sents), ]: runner = Gen2ModelRunner(path, sents) print(f"=== {name} (Final Loss: {runner.loss_history[-1]:.3f}) ===") for p in ["carrots", "house", "transformer"]: txt, w_toks, attn = runner.generate_with_attention(p) print(f" Prompt '{p}': {txt}") print(f" Window ({len(w_toks)} toks): {w_toks[:6]} ... attn shape={attn.shape}")