""" LIVING BRAIN 4D V25 ULTRA — SURGICAL ORACLE-WRITE DIAGNOSTIC SUITE (5 CONDITIONS) ================================================================================ Audited and Authorized by: GPT-6, Antigravity (Google DeepMind), and ZEEMAX Objective: Surgically isolate the causal bottleneck behind the Chalkboard Paradox: 1. Key-Query Addressing (Did the model's query search for Slot 0?) 2. Softmax Weighting (Did Top-4 inclusion translate into meaningful attention weight?) 3. Value Readout & Fusion (Can the model decode Slot 0 if given high attention weight?) 4. Base Weight Preservation (100% bit-identical parameter restoration verified). Conditions Evaluated per Horizon (128, 512, 2,048 tokens): [A] Baseline V25 (Unmodified recurrence) [B] Random-Noise Slot 0 (Parameter mutation disruption control) [C] Natural Oracle (Inject Fact into Slot 0; standard Top-4 retrieval) [D] Forced Top-4 Oracle — Natural Score (Slot 0 in Top-4; measures natural attention weight alpha_0) [E] High-Weight Forced Oracle — Guaranteed 50% Attention (Slot 0 attention mathematically set to 50%) Surgical Scoping Protocol: - Context & Distractor Streaming: Natural recurrence (forced retrieval flags strictly False). - Query & Candidate Evaluation: Surgical retrieval intervention active strictly at query/answer time. """ import os import sys import math import random import time import torch import torch.nn.functional as F from transformers import GPT2Tokenizer from evaluate_model import LivingBrain4D_V25_Master, TriMemoryLayer, load_all # ----------------------------------------------------------------------------- # 0. SURGICAL RETRIEVAL MONKEY-PATCH (Conditions D & E Support) # ----------------------------------------------------------------------------- orig_tri_mem_fwd = TriMemoryLayer.forward def patched_tri_memory_forward(self, x, prev_state=None, chunk_size=32): B, T, D = x.shape H, dm = self.num_heads, self.d_mem C = chunk_size pad_len = (C - (T % C)) % C x_in = F.pad(x, (0, 0, 0, pad_len)) if pad_len > 0 else x T_eff = T + pad_len Q_raw = self.q_norm(self.q_proj(x_in).view(B, T_eff, H, dm)) self.last_query_q_raw = Q_raw[:, T-1:T].detach() K_raw = self.k_norm(self.k_proj(x_in).view(B, T_eff, H, dm)) V = self.v_proj(x_in).view(B, T_eff, H, dm) Q, K = self.rope(Q_raw, K_raw) # --- TIER 1: Local Causal Sensory Window --- q_local = Q.permute(0, 2, 1, 3) k_local = K.permute(0, 2, 1, 3) v_local = V.permute(0, 2, 1, 3) attn_scores = torch.matmul(q_local, k_local.transpose(-1, -2)) / math.sqrt(dm) causal_mask = torch.tril(torch.ones(T_eff, T_eff, device=x.device, dtype=torch.bool)) band_mask = torch.triu(causal_mask, diagonal=-(self.window_size - 1)) attn_scores = attn_scores.masked_fill(~band_mask.unsqueeze(0).unsqueeze(0), -1e4) attn_weights = F.softmax(attn_scores, dim=-1) Y_tier1 = torch.matmul(attn_weights, v_local).permute(0, 2, 1, 3) # --- TIER 2: 4D Continuous Synaptic Manifold (FP32 Shield + G-GLA) --- g_event = torch.sigmoid(self.event_gate(x_in) * 2.0) alpha = 0.85 + 0.149 * torch.sigmoid(self.alpha_gate(x_in)) num_chunks = T_eff // C Q_c = Q.view(B, num_chunks, C, H, dm).permute(0, 3, 1, 2, 4) K_c = K.view(B, num_chunks, C, H, dm).permute(0, 3, 1, 2, 4) V_c = V.view(B, num_chunks, C, H, dm).permute(0, 3, 1, 2, 4) alpha_c = alpha.view(B, num_chunks, C, H).permute(0, 3, 1, 2) event_c = g_event.view(B, num_chunks, C, H).permute(0, 3, 1, 2) causal_chunk_mask = torch.tril(torch.ones(C, C, device=x.device, dtype=torch.bool)) log_alpha = torch.log(alpha_c.clamp(min=1e-5)) cum_log_alpha = torch.cumsum(log_alpha, dim=-1) decay_matrix = torch.exp(cum_log_alpha.unsqueeze(-1) - cum_log_alpha.unsqueeze(-2)) * causal_chunk_mask.unsqueeze(0).unsqueeze(0).unsqueeze(0) intra_attn = (torch.matmul(Q_c, K_c.transpose(-1, -2)) / math.sqrt(dm)) * decay_matrix * event_c.unsqueeze(-2) Y_intra = torch.matmul(intra_attn, V_c) chunk_total_decay = torch.exp(cum_log_alpha[..., -1:]).unsqueeze(-1) to_token_decay = torch.exp(cum_log_alpha).unsqueeze(-1) decay_to_end = torch.exp(cum_log_alpha[..., -1:] - cum_log_alpha) * event_c K_weighted = K_c * decay_to_end.unsqueeze(-1) M = prev_state.float() if prev_state is not None else torch.zeros(B, H, dm, dm, device=x.device, dtype=torch.float32) tier2_outputs = [] for c in range(num_chunks): q_c_f32 = Q_c[:, :, c].float() / math.sqrt(dm) y_inter = (torch.matmul(q_c_f32, M) * to_token_decay[:, :, c].float()).to(x.dtype) y_chunk = self.tier2_norm(y_inter + Y_intra[:, :, c]) tier2_outputs.append(y_chunk) k_w_f32 = K_weighted[:, :, c].float() / math.sqrt(dm) v_f32 = V_c[:, :, c].float() chunk_dW = torch.matmul(k_w_f32.transpose(-1, -2), v_f32) M = chunk_total_decay[:, :, c].float() * M + chunk_dW f_norm = torch.sqrt(torch.sum(M * M, dim=(-2, -1), keepdim=True) + 1e-5) scale = torch.clamp(self.beta / f_norm, max=1.0) M = M * scale Y_tier2 = torch.stack(tier2_outputs, dim=2).permute(0, 2, 3, 1, 4).contiguous().view(B, T_eff, H, dm) # --- TIER 3: Sparse Hopfield Bank --- entropy = -torch.sum(attn_weights * torch.log(attn_weights + 1e-9), dim=-1).mean(dim=1) t_steps = torch.arange(1, T_eff + 1, device=x.device).clamp(max=self.window_size).to(dtype=x.dtype) max_possible_entropy = torch.log(t_steps + 1e-5).unsqueeze(0) norm_entropy = entropy / (max_possible_entropy + 1e-5) gate = torch.sigmoid((norm_entropy - 0.65) * 10.0).unsqueeze(-1).unsqueeze(-1).to(dtype=x.dtype) sim_sem = torch.matmul(Q_raw, self.semantic_keys.transpose(-1, -2)) / math.sqrt(dm) topk_scores_s, topk_idx_s = torch.topk(sim_sem, k=4, dim=-1) mem_sem = torch.sum(F.softmax(topk_scores_s, dim=-1).unsqueeze(-1) * self.semantic_vals[topk_idx_s], dim=-2) sim_quar = torch.matmul(Q_raw, self.quarantine_keys.transpose(-1, -2)) / math.sqrt(dm) topk_scores_q, topk_idx_q = torch.topk(sim_quar, k=4, dim=-1) # SURGICAL INTERVENTIONS: Conditions D and E (Applied strictly during Query / Candidate evaluation) force_d = getattr(self, 'force_slot0_natural', False) force_e = getattr(self, 'force_slot0_boosted', False) if force_d or force_e: topk_idx_q = topk_idx_q.clone() topk_scores_q = topk_scores_q.clone() has_0 = (topk_idx_q == 0).any(dim=-1, keepdim=True) # Replace the 4th slot with Slot 0 if not present naturally topk_idx_q[..., -1:] = torch.where(has_0, topk_idx_q[..., -1:], torch.zeros_like(topk_idx_q[..., -1:])) topk_scores_q[..., -1:] = torch.where(has_0, topk_scores_q[..., -1:], sim_quar[..., 0:1]) if force_e: # Condition E: Mathematically guaranteed exact 50.0% attention weight (tau = 0.50) # Find where slot 0 is located in top-4 is_slot0 = (topk_idx_q == 0) other_scores = topk_scores_q.masked_fill(is_slot0, -1e4) lse_other = torch.logsumexp(other_scores, dim=-1, keepdim=True) # s_0 = logsumexp(other) + log(tau / (1 - tau)); with tau=0.50, log(1.0) = 0.0 tau = 0.50 offset = math.log(tau / (1.0 - tau)) boosted_s0 = lse_other + offset topk_scores_q = torch.where(is_slot0, boosted_s0, topk_scores_q) attn_q = F.softmax(topk_scores_q, dim=-1) # Telemetry: Record exact normalized attention weight assigned to Slot 0 (overall & per-head) slot0_mask = (topk_idx_q == 0).float() slot0_w_per_head = (attn_q * slot0_mask).sum(dim=-1)[:, T-1, :].mean(dim=0) # shape [H] self.last_slot0_attn_per_head = slot0_w_per_head.tolist() self.last_slot0_attn_weight = slot0_w_per_head.mean().item() mem_quar = torch.sum(attn_q.unsqueeze(-1) * self.quarantine_vals[topk_idx_q], dim=-2) Y_tier3 = gate * mem_quar + (1.0 - gate) * mem_sem # --- TRI-BRANCH ADAPTIVE FUSION --- gate_logits = self.fusion_gate(x_in).view(B, T_eff, H, 3) gates = F.softmax(gate_logits, dim=-1) g1, g2, g3 = gates[..., 0:1], gates[..., 1:2], gates[..., 2:3] self.last_g3 = g3[:, T-1].mean().item() Y_fused = (g1 * Y_tier1 + g2 * Y_tier2 + g3 * Y_tier3).to(dtype=x.dtype).view(B, T_eff, H * dm) out = self.out_proj(Y_fused) if pad_len > 0: out = out[:, :T] return out, M, norm_entropy[:, :T].mean() TriMemoryLayer.forward = patched_tri_memory_forward # ----------------------------------------------------------------------------- # 1. ORACLE INJECTION & ZERO-CONTAMINATION RESTORATION # ----------------------------------------------------------------------------- class SlotStatePreserver: """Clones Slot 0 keys/values across all 11 layers and guarantees bit-identical restoration.""" def __init__(self, model): self.model = model self.original_keys = [b.mem.quarantine_keys[0].clone() for b in model.blocks] self.original_vals = [b.mem.quarantine_vals[0].clone() for b in model.blocks] def restore(self): with torch.no_grad(): for i, b in enumerate(self.model.blocks): b.mem.quarantine_keys[0].copy_(self.original_keys[i]) b.mem.quarantine_vals[0].copy_(self.original_vals[i]) b.mem.force_slot0_natural = False b.mem.force_slot0_boosted = False def inject_oracle(self, k_vec, v_vec): with torch.no_grad(): for b in self.model.blocks: k_norm = F.normalize(k_vec, p=2, dim=-1) b.mem.quarantine_keys[0].copy_(k_norm) b.mem.quarantine_vals[0].copy_(v_vec) b.mem.force_slot0_natural = False b.mem.force_slot0_boosted = False def inject_random_noise(self): with torch.no_grad(): for b in self.model.blocks: b.mem.quarantine_keys[0].copy_(torch.randn_like(b.mem.quarantine_keys[0]) * 0.02) b.mem.quarantine_vals[0].copy_(torch.randn_like(b.mem.quarantine_vals[0]) * 0.02) b.mem.force_slot0_natural = False b.mem.force_slot0_boosted = False # ----------------------------------------------------------------------------- # 2. TRIAL EVALUATION LOGIC # ----------------------------------------------------------------------------- NAMES = ["Aria", "Dr. Vance", "Elena", "Marcus", "Kaelen", "Siddharth", "Zubair", "Lyra"] ATTRIBUTES = ["passcode", "clearance frequency", "vault cipher", "security key"] CODES = ["Cobalt-712", "Delta-849", "Apex-301", "Titan-532", "Echo-833", "Falcon-926", "Nexus-355", "Omega-200"] DISTRACTOR_TEXTS = [ "The Nabataean hydraulic system at Petra channeled flash floods through carved sandstone aqueducts into underground cisterns.", "Mitochondrial ATP synthase synthesizes ATP from ADP and inorganic phosphate driven by a transmembrane proton gradient.", "The Paxos consensus algorithm guarantees consistency in distributed networks under arbitrary message delays.", "In aerodynamic boundary layer transitions, Reynolds number scaling determines the onset of turbulent shear stress." ] def synthesize_needle_pair(): name = random.choice(NAMES) attr = random.choice(ATTRIBUTES) target = random.choice(CODES) decoys = [c for c in CODES if c != target][:3] fact_str = f"Notice: The {attr} for {name} is {target}." query_str = f"Query: What is the {attr} for {name}? Answer: The {attr} for {name} is" return fact_str, query_str, target, decoys, name, attr def build_distractor_tokens(tokenizer, count): if count == 0: return [] toks = [] while len(toks) < count: sample = " ".join(random.sample(DISTRACTOR_TEXTS, len(DISTRACTOR_TEXTS))) + " " toks.extend(tokenizer.encode(sample)) return toks[:count] def evaluate_trial(model, tokenizer, device, horizon, mode="baseline"): """ Evaluates a single needle trial with rigorous state isolation, exception-safe weight restoration, and mathematically aligned scoring. """ preserver = SlotStatePreserver(model) try: # Safeguard 2: Complete mutable state isolation between trials states, ws = None, None for b in model.blocks: b.mem.force_slot0_natural = False b.mem.force_slot0_boosted = False fact_str, query_str, target, decoys, name, attr = synthesize_needle_pair() # Setup condition injection (into Slot 0 parameters) if mode in ["oracle_natural", "oracle_forced_natural", "oracle_forced_boosted"]: key_text = f"{name} {attr}" val_text = f" {target}" with torch.no_grad(): k_emb = model.embed(torch.tensor([tokenizer.encode(key_text)], device=device)).mean(dim=1) v_emb = model.embed(torch.tensor([tokenizer.encode(val_text)], device=device)).mean(dim=1) k_proj = model.blocks[0].mem.k_proj(k_emb)[0, :128] v_proj = model.blocks[0].mem.v_proj(v_emb)[0, :128] preserver.inject_oracle(k_proj, v_proj) elif mode == "random": preserver.inject_random_noise() # PHASE 1: Stream Fact -> Distractors (Natural Recurrence, no forced retrieval during distractors) for b in model.blocks: b.mem.force_slot0_natural = False b.mem.force_slot0_boosted = False distractors = build_distractor_tokens(tokenizer, horizon) context_stream = tokenizer.encode(fact_str) + distractors chunk_size = 128 total_len = len(context_stream) for start in range(0, total_len, chunk_size): end = min(start + chunk_size, total_len) chunk = torch.tensor([context_stream[start:end]], device=device) with torch.no_grad(): logits, _, states, ws, _, _, _ = model(chunk, prev_states=states, ws_state=ws) # PHASE 2: Query Processing (Surgical Intervention Activated strictly at Query Time) for b in model.blocks: b.mem.force_slot0_natural = (mode == "oracle_forced_natural") b.mem.force_slot0_boosted = (mode == "oracle_forced_boosted") query_toks = tokenizer.encode("\n" + query_str) pre_query_states = [s.clone() for s in states] if states is not None else None pre_query_ws = ws.clone() if ws is not None else None q_chunk = torch.tensor([query_toks], device=device) with torch.no_grad(): logits, _, states, ws, _, _, _ = model(q_chunk, prev_states=states, ws_state=ws) # Telemetry: Measure Slot 0 Addressing & Softmax Weight at query completion position final_mem = model.blocks[-1].mem with torch.no_grad(): q_raw = final_mem.last_query_q_raw sim_quar = torch.matmul(q_raw, final_mem.quarantine_keys.transpose(-1, -2)) / math.sqrt(final_mem.d_mem) slot0_sim = sim_quar[0, 0, :, 0].mean().item() ranks = (torch.argsort(sim_quar, descending=True) == 0).nonzero(as_tuple=True)[-1] slot0_rank = ranks.float().mean().item() + 1 is_forced = mode in ["oracle_forced_natural", "oracle_forced_boosted"] slot0_in_top4 = bool((ranks < 4).any()) or is_forced slot0_attn_w = getattr(final_mem, 'last_slot0_attn_weight', 0.0) slot0_attn_heads = getattr(final_mem, 'last_slot0_attn_per_head', [0.0] * 6) fusion_g3 = getattr(final_mem, 'last_g3', 0.0) # Autoregressively Aligned Forced-Choice Scoring (Tier 1 Local Window Intact) # Suffix-chunked evaluation guarantees that candidate tokens attend causally # to all preceding query and candidate tokens in Tier 1 with zero padding mismatch. candidates = [target] + decoys random.shuffle(candidates) cand_scores = {} q_len = len(query_toks) for cand in candidates: cand_toks = tokenizer.encode(" " + cand) c_len = len(cand_toks) # Deep clone of haystack recurrent state and workspace for each candidate c_states = [s.clone() for s in pre_query_states] if pre_query_states is not None else None c_ws = pre_query_ws.clone() if pre_query_ws is not None else None # Unified Query + Candidate sequence: preserves Tier 1 local attention window cand_seq = torch.tensor([query_toks + cand_toks], device=device) with torch.no_grad(): cand_logits, _, _, _, _, _, _ = model(cand_seq, prev_states=c_states, ws_state=c_ws) # Score each candidate token under the logit distribution emitted by the preceding token total_lp = 0.0 for i, tok in enumerate(cand_toks): pred_pos = q_len - 1 + i lp = F.log_softmax(cand_logits[0, pred_pos], dim=-1)[tok].item() total_lp += lp cand_scores[cand] = total_lp / max(c_len, 1) winner = max(cand_scores, key=cand_scores.get) is_correct = (winner == target) target_first_tok = tokenizer.encode(" " + target)[0] p_target = F.softmax(logits[0, -1], dim=-1)[target_first_tok].item() return is_correct, p_target, slot0_in_top4, slot0_rank, slot0_sim, slot0_attn_w, slot0_attn_heads, fusion_g3 finally: # Guaranteed weight restoration even on interrupt or error preserver.restore() # ----------------------------------------------------------------------------- # 3. EXPERIMENTAL HARNESS ACROSS HORIZONS # ----------------------------------------------------------------------------- def run_surgical_diagnostic(model, tokenizer, device, horizon, trials=5): print(f"\n{'='*105}") print(f" 🔬 SURGICAL ORACLE EXPERIMENT: HORIZON {horizon:,} DISTRACTORS ({trials} Trials per Condition)") print(f"{'='*105}") conditions = [ ("A: Baseline V25 (Unmodified)", "baseline"), ("B: Random-Noise Slot 0 (Control)", "random"), ("C: Natural Oracle (Standard Top-4)", "oracle_natural"), ("D: Forced Top-4 (Natural Score)", "oracle_forced_natural"), ("E: High-Weight Forced Oracle (50% Attn)", "oracle_forced_boosted") ] trial_seeds = [random.randrange(2**32) for _ in range(trials)] for label, mode in conditions: correct = 0 p_list = [] ranks = [] sims = [] attn_weights = [] head_weights = [] in_top4_count = 0 g3_weights = [] for t in range(trials): random.seed(trial_seeds[t]) torch.manual_seed(trial_seeds[t]) ok, p, in_top4, rnk, sim, attn_w, attn_heads, g3 = evaluate_trial(model, tokenizer, device, horizon, mode=mode) if ok: correct += 1 p_list.append(p) ranks.append(rnk) sims.append(sim) attn_weights.append(attn_w) head_weights.append(attn_heads) if in_top4: in_top4_count += 1 g3_weights.append(g3) acc = (correct / trials) * 100.0 avg_p = sum(p_list) / len(p_list) avg_rnk = sum(ranks) / len(ranks) avg_sim = sum(sims) / len(sims) avg_attn_w = sum(attn_weights) / len(attn_weights) avg_g3 = sum(g3_weights) / len(g3_weights) top4_pct = (in_top4_count / trials) * 100.0 avg_heads = [sum(hw[h] for hw in head_weights) / len(head_weights) for h in range(6)] heads_str = ", ".join([f"H{h}:{v:.2f}" for h, v in enumerate(avg_heads)]) print(f"[{label}]:") print(f" • Forced-Choice Accuracy : {acc:5.1f}% (Chance: 25.0%)") print(f" • Avg Target Probability : {avg_p:.5f}") print(f" • Slot 0 Avg Rank in 512 : {avg_rnk:5.1f} (In Top-4: {top4_pct:.0f}%)") print(f" • Slot 0 Sim & Softmax W : Sim: {avg_sim:+.4f} | Mean Attn Weight alpha_0: {avg_attn_w:.4f} ({(avg_attn_w*100):.1f}%)") print(f" • Per-Head Attention : [{heads_str}] (Max Head: {max(avg_heads):.2f})") print(f" • Tier 3 Fusion Gate g3 : {avg_g3:.4f}") # ----------------------------------------------------------------------------- # 4. ENTRYPOINT & BIT-LEVEL RESTORATION VERIFICATION # ----------------------------------------------------------------------------- def main(): print("=" * 105) print(" LIVING BRAIN 4D V25 ULTRA — SURGICAL ORACLE-WRITE DIAGNOSTIC (5 CONDITIONS)") print("=" * 105) model, tokenizer, device, dtype, step = load_all() print(f"[Model State]: Step {step} | Device: {device} | Dtype: {dtype}") # SAFEGUARD 1: Capture pre-test parameter snapshot for bit-level verification print("\n[Safeguard 1]: Recording bit-level baseline parameter checksum...") initial_keys = [b.mem.quarantine_keys.detach().clone() for b in model.blocks] initial_vals = [b.mem.quarantine_vals.detach().clone() for b in model.blocks] try: for h in [128, 512, 2048]: run_surgical_diagnostic(model, tokenizer, device, h, trials=5) finally: # SAFEGUARD 1: Verify 100% bit-identical restoration print("\n" + "=" * 105) print(" [Safeguard 1 Post-Execution Verification]: Auditing parameter tensors...") all_matched = True max_error = 0.0 for i, b in enumerate(model.blocks): diff_k = torch.max(torch.abs(b.mem.quarantine_keys - initial_keys[i])).item() diff_v = torch.max(torch.abs(b.mem.quarantine_vals - initial_vals[i])).item() layer_err = max(diff_k, diff_v) if layer_err > max_error: max_error = layer_err if layer_err > 0.0: all_matched = False b.mem.quarantine_keys.copy_(initial_keys[i]) b.mem.quarantine_vals.copy_(initial_vals[i]) if all_matched: print(" ✅ [SAFEGUARD 1 PASSED]: All 11 layers verified 100% bit-identical to baseline (max error = 0.00000000).") else: print(f" ⚠️ [SAFEGUARD 1 FORCE-RESTORED]: Max deviation of {max_error:.8e} detected; restored from baseline snapshot.") print("=" * 105) if __name__ == "__main__": main()