#!/usr/bin/env python3 """ Gen 2 Inference Engine: 1-Layer, 2-Head Causal Self-Attention Mini-Transformer Uses 2-Head Causal Self-Attention (Q*K^T/sqrt(24) + ReLU FFN) sequence log-likelihood and attention-entropy scoring over bidirectional trigram/bigram beams + transformer rollouts. """ import json, re, random import numpy as np DANGLING_END_WORDS = { "a", "an", "the", "and", "or", "but", "if", "when", "while", "where", "because", "to", "of", "in", "on", "at", "by", "for", "with", "from", "into", "over", "under", "without", "between", "through", "during", "before", "after", "above", "below", "is", "are", "was", "were", "be", "been", "am", "has", "have", "had", "do", "does", "did", "can", "could", "will", "would", "shall", "should", "may", "might", "must", "i", "we", "you", "he", "she", "they", "my", "our", "your", "his", "her", "their", "its", "this", "that", "these", "those", "which", "who", "whom", "whose", "what", "just", "very", "quite", "rather", "too", "also", "even", "only", "not", "no", "so", "as", "new", "old", "good", "bad", "big", "small", "first", "last", "next", "other", "same", "own" } SYN_CLUSTERS = { "surreal": ["dream", "weird", "magic", "world", "floating", "3d", "island", "portal", "ice", "cream", "cone", "ghost", "neuron"], "ledger": ["ledger", "harbour", "blueprint", "staged", "island", "lighthouse", "ferry", "mesa", "contracts", "almanac", "wager"], "house": ["house", "island", "harbour", "lighthouse", "village", "room", "table", "door", "pavilion", "bunker"], "carrots": ["wonky", "carrots", "hummus", "burger", "pizza", "song", "vocoder", "mcluhan"], "scruffy": ["scruffy", "cat", "tabby", "purrs", "titan", "game", "boy", "ficus", "treats"], "evil": ["evil", "neuron", "qwen", "steering", "cat", "layer", "argue", "brother"], } def softmax(x): x = x - np.max(x) e = np.exp(x) return e / (np.sum(e) + 1e-12) class Gen2Model: def __init__(self, npz_path, corpus_or_badge=None, trans_json_path=None): self.badge = corpus_or_badge if isinstance(corpus_or_badge, str) else "" d = np.load(npz_path, allow_pickle=True) self.vocab = [str(w) for w in d["vocab"]] self.w2i = {w: i for i, w in enumerate(self.vocab)} self.case_map = json.loads(str(d["case_map_json"])) self.loss_history = [float(x) for x in d["loss_history"]] self.W_emb = d["W_emb"].astype(np.float32) self.W_pos = d["W_pos"].astype(np.float32) self.W_Q = d["W_Q"].astype(np.float32) self.W_K = d["W_K"].astype(np.float32) self.W_V = d["W_V"].astype(np.float32) self.W_O = d["W_O"].astype(np.float32) self.W_1 = d["W_1"].astype(np.float32) self.b_1 = d["b_1"].astype(np.float32) self.W_2 = d["W_2"].astype(np.float32) self.b_2 = d["b_2"].astype(np.float32) self.W_out = d["W_out"].astype(np.float32) self.b_out = d["b_out"].astype(np.float32) self.T = self.W_pos.shape[0] self.D = self.W_emb.shape[1] self.H = 4 if self.D >= 64 else 2 self.Dh = self.D // self.H self.bigrams = {int(k): {int(nk): int(nv) for nk, nv in v.items()} for k, v in json.loads(str(d["bigrams_json"])).items()} if "bigrams_json" in d else {} self.trigrams = {k: {int(nk): int(nv) for nk, nv in v.items()} for k, v in json.loads(str(d["trigrams_json"])).items()} if "trigrams_json" in d else {} # Load full-vocabulary transition graph for bidirectional candidate beam proposal if trans_json_path is None: if "irc_gpt" in npz_path: trans_json_path = "/tmp/village-world/public/models/irc_gpt_transitions.json" elif "argon_gpt" in npz_path: trans_json_path = "/tmp/village-world/public/models/argon_gpt_transitions.json" else: trans_json_path = "/tmp/village-world/public/models/village_gpt_transitions.json" with open(trans_json_path, "r", encoding="utf-8") as f: self.trans = json.load(f) def forward_window(self, seq_ids): """Run full 1-Layer 2-Head Causal Self-Attention over a token window (L <= T).""" idx = seq_ids[-self.T:] L = len(idx) emb = self.W_emb[idx] + self.W_pos[:L] # (L, D) Q = (emb @ self.W_Q).reshape(L, self.H, self.Dh).transpose(1, 0, 2) K = (emb @ self.W_K).reshape(L, self.H, self.Dh).transpose(1, 0, 2) V = (emb @ self.W_V).reshape(L, self.H, self.Dh).transpose(1, 0, 2) scores = (Q @ K.transpose(0, 2, 1)) / np.sqrt(self.Dh) mask = np.triu(np.ones((L, L), dtype=bool), k=1) scores[:, mask] = -1e9 attn = np.zeros_like(scores) for h in range(self.H): for t in range(L): attn[h, t] = softmax(scores[h, t]) context = (attn @ V).transpose(1, 0, 2).reshape(L, self.D) attn_out = context @ self.W_O h1 = emb + attn_out ff_pre = h1 @ self.W_1 + self.b_1 ff_act = np.maximum(0.0, ff_pre) h2 = h1 + (ff_act @ self.W_2 + self.b_2) logits = h2 @ self.W_out + self.b_out # (L, V) return logits, attn def forward_single(self, seq_ids): logits, attn = self.forward_window(seq_ids) return logits[-1], attn def score_sequence_with_transformer(self, tokens, prompt_keywords): """ Compute sequence log-likelihood under the 2-Head Causal Self-Attention Mini-Transformer plus multi-head attention diversity & prompt relevance bonus. """ ids = [1] + [self.w2i.get(t.lower(), 3) for t in tokens] + [2] # Slide window across sequence win = ids[-self.T:] logits, attn = self.forward_window(win) ll_sum = 0.0 known_transitions = 0 for t in range(len(win) - 1): target = win[t + 1] if target not in (0, 3): probs = softmax(logits[t]) ll_sum += float(np.log(probs[target] + 1e-9)) known_transitions += 1 avg_ll = ll_sum / max(1, known_transitions) # Multi-head causal attention cross-token focus bonus (Head 0 vs Head 1 specialization) if attn.shape[-1] >= 4: head_diff = float(np.mean(np.abs(attn[0] - attn[1]))) else: head_diff = 0.0 # Prompt match & TF-IDF content richness low_toks = [t.lower() for t in tokens] kw_hits = sum(1 for k in prompt_keywords if k in low_toks) wc = self.trans["word_counts"] rarity = sum(1.1 / np.sqrt(wc.get(t, 1)) for t in low_toks if len(t) >= 4) / max(1, len(tokens)) # Length sweet spot (8..16 tokens) len_bonus = 2.0 if 8 <= len(tokens) <= 16 else -1.5 total_score = (avg_ll * 1.8) + (head_diff * 2.5) + (kw_hits * 3.0) + (rarity * 2.2) + len_bonus return total_score, attn, win def _sample_counter(self, c3, c2, temp=0.92): combined = {} if c3: for k, v in c3.items(): combined[k] = combined.get(k, 0.0) + v * 2.2 if c2: for k, v in c2.items(): combined[k] = combined.get(k, 0.0) + v * 1.0 if not combined: return None items = list(combined.items()) weights = np.array([v ** (1.0 / max(0.2, temp)) for _, v in items], dtype=np.float64) weights /= weights.sum() idx = np.random.choice(len(items), p=weights) return items[idx][0] def _propose_bidirectional_candidate(self, seed_word, max_tokens=16): m = self.trans next_cands = {k: v for k, v in m["forward2"].get(seed_word, {}).items() if k != ""} second = self._sample_counter(None, next_cands, 0.95) if next_cands else self._sample_counter(None, m["cooccur"].get(seed_word, {}), 1.0) if not second or second == "": f_toks = [seed_word] b_toks = ["", seed_word] else: f_toks = [seed_word, second] b_toks = [second, seed_word] used = {t.lower(): 1 for t in f_toks} # Forward rollout guided by 2-Head Causal Self-Attention when inside top-580 vocab while len(f_toks) >= 2 and len(f_toks) < max_tokens: k3 = f"{f_toks[-2].lower()}|||{f_toks[-1].lower()}" c3 = m["forward3"].get(k3, {}) c2 = m["forward2"].get(f_toks[-1].lower(), {}) # Boost candidates that also score high under the 2-Head Causal Transformer! boosted_c2 = {} seq_ids = [1] + [self.w2i.get(t.lower(), 3) for t in f_toks[-self.T+1:]] t_logits, _ = self.forward_single(seq_ids) t_probs = softmax(t_logits) for cand_w, cnt in c2.items(): cid = self.w2i.get(cand_w.lower(), 3) t_mult = (1.0 + 4.0 * float(t_probs[cid])) if cid >= 4 else 1.0 rep_pen = 0.15 if used.get(cand_w.lower(), 0) >= 1 and len(cand_w) >= 4 else 1.0 boosted_c2[cand_w] = cnt * t_mult * rep_pen nxt = self._sample_counter(c3, boosted_c2, 0.88) if not nxt or nxt == "": break f_toks.append(nxt) used[nxt.lower()] = used.get(nxt.lower(), 0) + 1 if nxt in (".", "!", "?") and len(f_toks) >= 6: break # Backward prefix completion to reach sentence start (stop at sentence punctuation) while len(b_toks) + len(f_toks) - 2 < max_tokens: k3 = f"{b_toks[-2].lower()}|||{b_toks[-1].lower()}" c3 = m["backward3"].get(k3, {}) c2 = m["backward2"].get(b_toks[-1].lower(), {}) prv = self._sample_counter(c3, c2, 0.88) if not prv or prv == "" or prv in (".", "!", "?", ";"): break b_toks.append(prv) full = list(reversed(b_toks[2:])) + f_toks # Keep only the first sentence if forward rollout hit internal punctuation cleaned = [] for idx_t, tok in enumerate(full): if tok in (",", ";", ":") and (not cleaned or cleaned[-1] in (",", ".", "!", "?", ";", ":")): continue cleaned.append(tok) if tok in (".", "!", "?") and len(cleaned) >= 6: break elif tok in (".", "!", "?") and len(cleaned) < 6: cleaned.pop() # skip premature period full = cleaned # Strip leading prepositions/conjunctions/numbers BAD_STARTERS = {"of", "in", "on", "at", "by", "for", "with", "from", "to", "and", "or", "but", "so", "as", "than", ",", ".", "!", "?", ";", ":"} while full and (full[0].lower() in BAD_STARTERS or re.match(r"^\d+$", full[0])): full.pop(0) # Strip trailing dangling function words or bare numbers while full and (full[-1].lower() in DANGLING_END_WORDS or full[-1] == "," or re.match(r"^\d+$", full[-1])): full.pop() if len(full) >= 2 and full[-1] in (".", "!", "?") and (full[-2].lower() in DANGLING_END_WORDS or re.match(r"^\d+$", full[-2])): punct = full.pop() while full and (full[-1].lower() in DANGLING_END_WORDS or re.match(r"^\d+$", full[-1])): full.pop() if full: full.append(punct) return full def generate(self, prompt="", max_new_tokens=16, temperature=0.75, return_attn=False): m = self.trans wc = m["word_counts"] raw_toks = re.findall(r"[a-z0-9_'-]{2,}", prompt.lower()) exact_kw = [w for w in raw_toks if w in wc] syn_kw = [] for pt in raw_toks: if pt in SYN_CLUSTERS: syn_kw.extend([sw for sw in SYN_CLUSTERS[pt] if sw in wc]) if len(pt) >= 4: for vw in wc: if len(vw) >= 4 and (pt in vw or vw in pt): syn_kw.append(vw) keywords = (exact_kw * 6 + syn_kw) if exact_kw else syn_kw if not keywords: keywords = [w for w in list(wc.keys())[:80] if len(w) >= 4 and w not in DANGLING_END_WORDS] best_tokens = None best_score = -1e9 best_attn = None best_win = None for _ in range(36): seed = random.choice(keywords) cand = self._propose_bidirectional_candidate(seed, max_tokens=max_new_tokens) if len(cand) < 6: continue sc, attn, win = self.score_sequence_with_transformer(cand, set(keywords)) if sc > best_score: best_score = sc best_tokens = cand best_attn = attn best_win = win if not best_tokens: best_tokens = ["argie", "purrs", "in", "2-head", "causal", "self-attention", "mini-transformer", "!"] _, best_attn, best_win = self.score_sequence_with_transformer(best_tokens, set()) out = "" for t in best_tokens: if t in (",", ".", "!", "?", ";", ":"): out += t else: out += (" " if out else "") + t if out and out[0].islower(): out = out[0].upper() + out[1:] if out and out[-1] not in ".!?": out += "." if return_attn: win_toks = [self.case_map.get(self.vocab[i], self.vocab[i]) for i in best_win] return out, win_toks, best_attn return out if __name__ == "__main__": for name, path, badge in [ ("irc", "/tmp/irc_gpt_gen2.npz", "[🤖IRC-GPT v2]"), ("argon", "/tmp/argon_gpt_gen2.npz", "[⚡ARGON-GPT v2]"), ("village", "/tmp/village_gpt_gen2.npz", "[🏛️VILLAGE-GPT v2]"), ]: m = Gen2Model(path, badge) for p in ["ledger", "surreal", "wonky carrots", "house"]: print(f"({p}) ->", m.generate(p)) Gen2ModelRunner = Gen2Model