Cortex-System-One / benchmark_s1mb_official.py
siddiVinayaka's picture
Fix Model import path resolution in benchmark_s1mb_official.py
734f83b verified
Raw History Blame Contribute Delete
77.1 kB
#!/usr/bin/env python3 """ ==================================================================================================== NEXUS SYSTEM 1 — OFFICIAL S1MB (SYSTEM ONE MOSAIC BENCHMARK) EVALUATION & LEADERBOARD SUITE Evaluates Nexus System 1 directly on the official benchmark by hotchpotch (Yuichi Tateno) Supporting official task metrics: Choice (Target Mass / Accuracy), Noul (Brier / Balanced Accuracy), and Score (Normalized MAE / RMSE), baseline adjustments, and direct comparison to Bekko & Laya. Defaults to dynamic persistent neural memory. ==================================================================================================== """ from __future__ import annotations import argparse import hashlib import json import lzma import math import os import platform import statistics import sys import time from collections import defaultdict from datetime import datetime, timezone from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Tuple import torch import torch.nn.functional as F import tiktoken from datasets import load_dataset # Add script directory, current directory, and any checkpoint parent directories to sys.path sys.path.insert(0, str(Path(__file__).resolve().parent)) sys.path.insert(0, str(Path.cwd())) for arg in sys.argv: try: p = Path(arg).resolve() if p.is_file() and (p.parent / "Model.py").is_file(): sys.path.insert(0, str(p.parent)) elif p.is_dir() and (p / "Model.py").is_file(): sys.path.insert(0, str(p)) except Exception: pass # Local imports try: from Model import CortexV7 except ImportError: try: from Model import Cortex as CortexV7 except ImportError as e: raise ImportError( f"Could not find Model.py in sys.path: {sys.path[:3]}. " "Please ensure Model.py is in your working directory or PYTHONPATH." ) from e EPSILON = 1e-12 # Multi-Domain Constants matching pretraining, training & evaluation DOMAINS = [ "agent_trace", "customer_service", "invoice_processing", "security_incidents" ] def parse_domain_id(domain_str: str) -> int: d = str(domain_str).lower() for idx, name in enumerate(DOMAINS): if name in d: return idx if "agent" in d: return 0 if "customer" in d or "account" in d: return 1 if "invoice" in d or "delivery" in d: return 2 if "security" in d or "alert" in d: return 3 return 0 # Exact Laya QTYPES matching common.py line 14: {"choice": 0, "score": 1, "noul": 2} PRIMITIVES = ["choice", "score", "noul"] def parse_primitive_id(primitive_str: str) -> int: p = str(primitive_str).lower().strip() if p in PRIMITIVES: return PRIMITIVES.index(p) return 0 # --------------------------------------------------------------------------- # S1MB Benchmark Definitions & Suites # --------------------------------------------------------------------------- SMOKE_BENCHMARKS = [ { "id": "arc-choice-test-v1", "task": "choice", "config": "arc", "decision_id": "answer", "name": "ARC Science QA (Choice)", }, { "id": "aegis2-noul-test-v1", "task": "noul", "config": "aegis2", "decision_id": "prompt_unsafe", "name": "Aegis 2.0 Safety Guard (Noul)", }, { "id": "patent-similarity-score-test-v1", "task": "score", "config": "patent_similarity", "decision_id": "similarity", "name": "Patent Semantic Similarity (Score)", }, ] TYPED_DECISIONS_BENCHMARKS = [ { "id": "laya--typed-decisions-choice-test-v1", "task": "choice", "config": "laya__typed_decisions", "decision_id": None, "name": "Typed Decisions (Choice)", }, { "id": "laya--typed-decisions-noul-test-v1", "task": "noul", "config": "laya__typed_decisions", "decision_id": None, "name": "Typed Decisions (Noul)", }, { "id": "laya--typed-decisions-score-test-v1", "task": "score", "config": "laya__typed_decisions", "decision_id": None, "name": "Typed Decisions (Score)", }, ] # Official Leaderboard Baselines for Sub-1B Models (Ground Truth from hotchpotch/s1mb-result) LEADERBOARD_BASELINES = { "Bekko-400M": { "choice": 24.54, "noul": 30.35, "score": 45.79, "task_avg": 33.56, }, "Laya-Typed-Decisions (421M)": { "choice": 28.68, "noul": 44.42, "score": 63.48, "task_avg": 45.53, }, "ModernBERT-151M-RLCD": { "choice": 45.10, "noul": 42.80, "score": 28.50, "task_avg": 38.80, }, } # --------------------------------------------------------------------------- # Prompt & Token Span Formatting # --------------------------------------------------------------------------- def option_label(index: int) -> str: n = index + 1 chars = [] while n: n, rem = divmod(n - 1, 26) chars.append(chr(65 + rem)) return "".join(reversed(chars)) def find_subsequence(haystack: Sequence[int], needle: Sequence[int], start: int = 0) -> int: if not needle: return -1 end = len(haystack) - len(needle) + 1 for i in range(max(0, start), end): if list(haystack[i : i + len(needle)]) == list(needle): return i return -1 def label_patterns(enc: Any, label: str): vals = [ f"({label})", f"{label})", f"{label}.", f"[{label}]", f"{label}:", f"{label} -", f"{label} –", f"Option {label}:", f"Option {label})", f"Option {label}.", ] out, seen = [], set() for value in vals: ids = tuple(enc.encode(value, allowed_special=set())) if ids and ids not in seen: seen.add(ids) out.append(list(ids)) return out def find_option_spans(token_ids: Sequence[int], enc: Any, options: Sequence[str]): if len(options) < 2: return None try: import re tok_bytes = [enc.decode_single_token_bytes(t) for t in token_ids] prompt_bytes = b"".join(tok_bytes) byte_to_tok = [] for tok_idx, b in enumerate(tok_bytes): byte_to_tok.extend([tok_idx] * len(b)) char_cursor = 0 exact_spans = [] span_ok = True for opt in options: clean_opt = opt.strip() opt_bytes = clean_opt.encode("utf-8") pos = prompt_bytes.find(opt_bytes, char_cursor) if pos < 0: unlabeled = re.sub(r"^[A-Za-z0-9\(\)\.\:\-\s]+", "", clean_opt).strip() if len(unlabeled) >= 3: pos = prompt_bytes.find(unlabeled.encode("utf-8"), char_cursor) if pos >= 0 and (pos + len(opt_bytes)) <= len(byte_to_tok): s_tok = byte_to_tok[pos] e_tok = byte_to_tok[pos + len(opt_bytes) - 1] exact_spans.append((s_tok, e_tok)) char_cursor = pos + len(opt_bytes) else: span_ok = False break if span_ok and len(exact_spans) == len(options): for k in range(1, len(exact_spans)): if exact_spans[k][0] < exact_spans[k - 1][0]: span_ok = False break if span_ok: return exact_spans except Exception: pass positions = [] cursor = 0 for idx in range(len(options)): lbl = option_label(idx) best_pos = -1 for pat in label_patterns(enc, lbl): p = find_subsequence(token_ids, pat, start=cursor) if p >= 0 and (best_pos < 0 or p < best_pos): best_pos = p if best_pos < 0: return None positions.append(best_pos) cursor = best_pos + 1 return [(p, p) for p in positions] def format_s1mb_prompt_and_options( case: dict, target_decision_id: Optional[str] = None, cfg_name: Optional[str] = None, task_type: Optional[str] = None, decision_obj: Optional[dict] = None, ): """ Nexus System 1 Native S1MB Adapter: Translates standardized S1MB inputs into Nexus's exact trained prompt format, resolving native domain embeddings, workflow titles, and typed candidate options. """ state_raw = case["input"].get("state_json") or case["input"].get("state", {}) if isinstance(state_raw, str): try: state_obj = json.loads(state_raw) except Exception: state_obj = state_raw else: state_obj = state_raw # Compact JSON representation matching Nexus preflight formatting if isinstance(state_obj, (dict, list)): state_compact = json.dumps(state_obj, separators=(',', ':'), ensure_ascii=False) else: state_compact = str(state_obj).strip() # 1. Dynamic Domain & Workflow Resolution cfg_lower = str(cfg_name or "").strip().lower() wf_title = "Enterprise Workflow" dom_name = "typed_agent_trace_observability" explicit_dom = ( case.get("domain") or case.get("workflow") or (case.get("input", {}).get("domain") if isinstance(case.get("input"), dict) else None) or (case.get("input", {}).get("workflow") if isinstance(case.get("input"), dict) else None) ) if explicit_dom: dom_name = str(explicit_dom).strip().lower() dom_idx = parse_domain_id(dom_name) if "agent" in dom_name: wf_title = "Agent Trace Observability" elif "security" in dom_name or "alert" in dom_name: wf_title = "Security Incidents" elif "invoice" in dom_name or "delivery" in dom_name: wf_title = "Invoice Processing" elif "customer" in dom_name or "account" in dom_name: wf_title = "Customer Service" elif isinstance(state_obj, dict): if "agent" in state_obj: wf_title = "Agent Trace Observability" dom_name = "typed_agent_trace_observability" dom_idx = 0 elif "alert" in state_obj: wf_title = "Security Incidents" dom_name = "typed_security_incidents" dom_idx = 3 elif "delivery" in state_obj or "invoice" in state_obj: wf_title = "Invoice Processing" dom_name = "typed_invoice_processing" dom_idx = 2 elif "account" in state_obj or "customer" in state_obj: wf_title = "Customer Service" dom_name = "typed_customer_service" dom_idx = 1 elif "arc" in cfg_lower or "science" in cfg_lower: wf_title = "STEM Science" dom_name = "stem_science" dom_idx = 7 elif "aegis" in cfg_lower: wf_title = "AI Safety Guardrails" dom_name = "ai_safety_guardrails" dom_idx = 10 elif "patent" in cfg_lower: wf_title = "Patent Technical Analysis" dom_name = "patent_technical_analysis" dom_idx = 11 elif "math" in cfg_lower: wf_title = "STEM Mathematics" dom_name = "stem_mathematics" dom_idx = 4 elif "code" in cfg_lower: wf_title = "Code Defect & Security" dom_name = "code_defect_security" dom_idx = 8 else: dom_name = "typed_agent_trace_observability" dom_idx = 0 else: if "arc" in cfg_lower or "science" in cfg_lower: wf_title = "STEM Science" dom_name = "stem_science" dom_idx = 7 elif "aegis" in cfg_lower: wf_title = "AI Safety Guardrails" dom_name = "ai_safety_guardrails" dom_idx = 10 elif "patent" in cfg_lower: wf_title = "Patent Technical Analysis" dom_name = "patent_technical_analysis" dom_idx = 11 else: dom_name = "typed_agent_trace_observability" dom_idx = 0 # 2. Target Decision Extraction decisions = case["input"].get("decisions", []) q = None if decision_obj is not None: q = decision_obj elif target_decision_id is not None: for d in decisions: if d.get("id") == target_decision_id: q = d break # Fallback: match by task type if specific decision ID is not present in this domain if q is None and task_type is not None: target_t = task_type.strip().lower() for d in decisions: if str(d.get("type", "")).strip().lower() == target_t: q = d break if q is None: q = decisions[0] if decisions else {} instructions = q.get("instructions") if not instructions and q.get("instructions_json"): try: instructions = json.loads(q["instructions_json"]) except Exception: instructions = str(q["instructions_json"]) if isinstance(instructions, dict): instructions = " ".join(f"{k}: {v}" for k, v in instructions.items()) elif isinstance(instructions, list): instructions = " ".join(str(x) for x in instructions) else: instructions = str(instructions or "") instructions = instructions.strip() system_prompt = q.get("system_prompt", "") prefix = f"{system_prompt}\n\n" if system_prompt else "" q_type = str(q.get("type", "choice")).strip().lower() criteria = q.get("options") or q.get("criteria", []) options_text = [] option_ids = [] option_values = [] # 3. Native Task & Option Formatting (100% Alignment with Specialist Preflight) prim_idx = parse_primitive_id(q_type) if q_type == "choice": sorted_criteria = sorted(criteria, key=lambda opt: str(opt.get("id", "")).lower()) for opt in sorted_criteria: opt_id = opt.get("id", "") option_ids.append(opt_id) desc = opt.get("description") if not desc and opt.get("description_json"): try: desc = json.loads(opt["description_json"]) except Exception: desc = str(opt["description_json"]) desc_str = str(desc or "").strip() if desc_str: if ( desc_str.lower().startswith(str(opt_id).lower() + ":") or desc_str.lower().startswith(str(opt_id).lower() + ")") or str(opt_id).isdigit() ): options_text.append(desc_str) else: options_text.append(f"{opt_id}: {desc_str}") else: options_text.append(str(opt_id)) option_values.append(None) rendered = [f"({option_label(i)}) {t}" for i, t in enumerate(options_text)] body = "\n".join(rendered) prompt = ( f"{prefix}Workflow: {wf_title}\n" f"Task State: {state_compact}\n\n" f"Task: {instructions}\n" f"Options:\n{body}\n\n" f"Analyze the state and select the correct option.\nAnswer:" ) elif q_type == "noul": # Canonicalize order: False at index 0, True at index 1 (matching 100% of training data) def _noul_sort(opt): oid = str(opt.get("id", "")).strip().lower() return 0 if oid in ("false", "0", "no") else 1 sorted_criteria = sorted(criteria, key=_noul_sort) q_id_lower = str(q.get("id", "")).strip().lower() if q_id_lower in ("duplicate", "credential_compromise"): options_text = ["False (No)", "True (Yes)"] option_ids = ["false", "true"] option_values = [None, None] else: for opt in sorted_criteria: opt_id = str(opt.get("id", "")).strip().lower() option_ids.append(opt.get("id", "")) desc = opt.get("description") if not desc and opt.get("description_json"): try: desc = json.loads(opt["description_json"]) except Exception: desc = str(opt["description_json"]) desc_str = str(desc or "").strip() if not desc_str or "condition in the question" in desc_str.lower(): if opt_id in ("false", "0", "no"): options_text.append("False (No)") else: options_text.append("True (Yes)") else: if opt_id in ("false", "0", "no"): options_text.append(f"False: {desc_str}" if not desc_str.lower().startswith("false:") else desc_str) else: options_text.append(f"True: {desc_str}" if not desc_str.lower().startswith("true:") else desc_str) option_values.append(None) rendered = [f"({option_label(i)}) {t}" for i, t in enumerate(options_text)] body = "\n".join(rendered) prompt = ( f"{prefix}Workflow: {wf_title}\n" f"Task State: {state_compact}\n\n" f"Proposition: {instructions}\n" f"Options:\n{body}\n\n" f"Analyze the state and verify if the proposition holds.\nAnswer:" ) elif q_type == "score": # Sort by numeric level (0, 1, 2, ...) def _score_sort(opt): v = opt.get("value") if v is not None: try: return float(v) except Exception: pass try: return float(opt.get("id", "0")) except Exception: return 0.0 sorted_criteria = sorted(criteria, key=_score_sort) for idx, opt in enumerate(sorted_criteria): opt_id = opt.get("id", str(idx)) option_ids.append(opt_id) val = opt.get("value") option_values.append(float(val) if val is not None else float(idx)) desc = opt.get("description") if not desc and opt.get("description_json"): try: desc = json.loads(opt["description_json"]) except Exception: desc = str(opt["description_json"]) desc_str = str(desc or "").strip() if desc_str.lower().startswith("level"): options_text.append(desc_str) else: options_text.append(f"Level {opt_id}: {desc_str}") rendered = [f"({option_label(i)}) {t}" for i, t in enumerate(options_text)] body = "\n".join(rendered) prompt = ( f"{prefix}Workflow: {wf_title}\n" f"Task State: {state_compact}\n\n" f"Assessment: {instructions}\n" f"Options:\n{body}\n\n" f"Analyze the state and select the correct severity level.\nAnswer:" ) else: rendered = [f"({option_label(i)}) {t}" for i, t in enumerate(options_text)] body = "\n".join(rendered) prompt = f"{prefix}Workflow: {wf_title}\nTask State: {state_compact}\n\nTask: {instructions}\nOptions:\n{body}\n\nAnswer:" return prompt, options_text, option_ids, option_values, q["id"], q_type, dom_idx, dom_name, prim_idx # --------------------------------------------------------------------------- # Official S1MB Mathematical Metric Calculation # --------------------------------------------------------------------------- def calculate_s1mb_metrics( task: str, predictions: List[Dict[str, float]], target_distributions: List[Dict[str, float]], option_ids_list: List[List[str]], option_values_list: List[List[Optional[float]]], threshold: float = 0.50, ) -> Dict[str, float]: n = len(predictions) if n == 0: return {} out: Dict[str, float] = {} if task == "choice": # 1. Top-1 Raw Accuracy & Target Mass at Prediction correct = [] accuracies = [] for p, t, ids in zip(predictions, target_distributions, option_ids_list): chosen = max(ids, key=lambda opt_id: p.get(opt_id, 0.0)) gold = max(ids, key=lambda opt_id: t.get(opt_id, 0.0)) correct.append(1.0 if chosen == gold else 0.0) accuracies.append(t.get(chosen, 0.0)) out["top1_accuracy"] = statistics.mean(correct) acc = statistics.mean(accuracies) out["target_mass_at_prediction"] = acc # 2. Trivial baselines uniform = statistics.mean([1.0 / len(ids) for ids in option_ids_list]) out["uniform_accuracy_baseline"] = uniform all_unique_ids = set().union(*option_ids_list) fixed_id_baseline = max( statistics.mean([t.get(k, 1.0 / len(ids)) for t, ids in zip(target_distributions, option_ids_list)]) for k in all_unique_ids ) max_k = max(len(ids) for ids in option_ids_list) fixed_pos_baseline = max( statistics.mean([ t.get(ids[pos], 1.0 / len(ids)) if pos < len(ids) else 1.0 / len(ids) for t, ids in zip(target_distributions, option_ids_list) ]) for pos in range(max_k) ) baseline = max(uniform, fixed_id_baseline, fixed_pos_baseline) out["fixed_answer_accuracy_baseline"] = baseline if baseline < 1.0 - EPSILON: skill = (acc - baseline) / (1.0 - baseline) else: skill = 0.0 out["baseline_adjusted_skill"] = skill out["baseline_adjusted_score"] = max(0.0, min(1.0, skill)) elif task == "noul": # 1. Binary Brier Score # Resolve "true"/"false" probability from either key convention: # HuggingFace targets use "true" / "false" # Local test targets use "1" / "0" (positional index strings) def _noul_true(d: Dict[str, float]) -> float: if "true" in d: return d["true"] if "1" in d: return d["1"] return 0.0 def _noul_false(d: Dict[str, float]) -> float: if "false" in d: return d["false"] if "0" in d: return d["0"] return 0.0 briers = [] for p, t in zip(predictions, target_distributions): p_true = _noul_true(p) t_true = _noul_true(t) briers.append((p_true - t_true) ** 2) mean_brier = statistics.mean(briers) out["binary_brier"] = mean_brier # 2. Balanced Accuracy & Prevalence prevalence = statistics.mean([_noul_true(t) for t in target_distributions]) out["positive_prevalence"] = prevalence tp = sum(_noul_true(t) for p, t in zip(predictions, target_distributions) if _noul_true(p) >= threshold) fp = sum(_noul_false(t) for p, t in zip(predictions, target_distributions) if _noul_true(p) >= threshold) fn = sum(_noul_true(t) for p, t in zip(predictions, target_distributions) if _noul_true(p) < threshold) tn = sum(_noul_false(t) for p, t in zip(predictions, target_distributions) if _noul_true(p) < threshold) recall = tp / (tp + fn) if (tp + fn) > EPSILON else 0.0 specificity = tn / (tn + fp) if (tn + fp) > EPSILON else 0.0 balanced_acc = (recall + specificity) / 2.0 out["accuracy"] = (tp + tn) / n out["top1_accuracy"] = out["accuracy"] out["balanced_accuracy"] = balanced_acc skill = 2.0 * balanced_acc - 1.0 out["baseline_adjusted_skill"] = skill out["baseline_adjusted_score"] = max(0.0, min(1.0, skill)) elif task == "score": # 1. Normalized Expected Score MAE errors = [] target_expected_vals = [] for p, t, ids, vals in zip(predictions, target_distributions, option_ids_list, option_values_list): val_map = {opt_id: (float(v) if v is not None else float(idx)) for idx, (opt_id, v) in enumerate(zip(ids, vals))} low, high = min(val_map.values()), max(val_map.values()) scale_range = max(high - low, EPSILON) pred_val = sum(val_map[k] * p.get(k, 0.0) for k in ids) target_val = sum(val_map[k] * t.get(k, 0.0) for k in ids) target_norm = (target_val - low) / scale_range target_expected_vals.append(target_norm) err = abs(pred_val - target_val) / scale_range errors.append(err) exact = [] within_1 = [] for p, t, ids, vals in zip(predictions, target_distributions, option_ids_list, option_values_list): val_map = {opt_id: (float(v) if v is not None else float(idx)) for idx, (opt_id, v) in enumerate(zip(ids, vals))} pred_val = sum(val_map[k] * p.get(k, 0.0) for k in ids) target_val = sum(val_map[k] * t.get(k, 0.0) for k in ids) exact.append(1.0 if round(pred_val) == round(target_val) else 0.0) within_1.append(1.0 if abs(pred_val - target_val) <= 1.0 else 0.0) out["top1_accuracy"] = statistics.mean(exact) out["within_1_level_accuracy"] = statistics.mean(within_1) mae = statistics.mean(errors) rmse = math.sqrt(statistics.mean([e ** 2 for e in errors])) out["normalized_expected_score_mae"] = mae out["normalized_score_rmse"] = rmse # 2. Constant Median Baseline constant_pred = statistics.median(target_expected_vals) baseline_mae = statistics.mean([abs(t - constant_pred) for t in target_expected_vals]) out["constant_mae_baseline"] = baseline_mae if baseline_mae > EPSILON: skill = 1.0 - (mae / baseline_mae) else: skill = 0.0 out["baseline_adjusted_skill"] = skill out["baseline_adjusted_score"] = max(0.0, min(1.0, skill)) return out # --------------------------------------------------------------------------- # Checkpoint & Memory Loader # --------------------------------------------------------------------------- def get_calibration_parameters( meta: Optional[Dict[str, Any]], domain: str, primitive: str, k: int, apply_bias: bool = False, ) -> Tuple[float, Optional[torch.Tensor]]: """ Pure Laya Temperature & Position Bias Extraction: Retrieves scalar T and position bias vector matching agent.py / common.py. """ if not meta: return 1.0, None prim_lower = primitive.lower() size = "2" if k <= 2 else "3-5" if k <= 5 else "6-10" if k <= 10 else "11+" bucket_standard = f"{prim_lower}:{size}" bucket_exact = f"{prim_lower}:{k}" bucket_pipe = f"{prim_lower}|{k}" # 1. Temperature extraction T = 1.0 tbo = meta.get("temperature_by_options", {}) if bucket_exact in tbo: T = float(tbo[bucket_exact]) elif bucket_standard in tbo: T = float(tbo[bucket_standard]) elif bucket_pipe in meta.get("temperatures", {}): T = float(meta["temperatures"][bucket_pipe]) elif "temperature_by_primitive" in meta and prim_lower in meta["temperature_by_primitive"]: T = float(meta["temperature_by_primitive"][prim_lower]) elif "temperature" in meta and isinstance(meta["temperature"], (list, tuple)): p_map = {"choice": 0, "score": 1, "noul": 2} p_idx = p_map.get(prim_lower, 0) if p_idx < len(meta["temperature"]): T = float(meta["temperature"][p_idx]) elif "global_temperature" in meta: T = float(meta["global_temperature"]) T = max(0.1, min(10.0, T)) # 2. Additive position bias vector extraction (if requested) bias_t = None if apply_bias: raw_b = None dom_cal = meta.get("domain_calibrations", {}).get(domain, {}).get(prim_lower, {}).get(str(k), {}) if dom_cal and "bias" in dom_cal and dom_cal["bias"] is not None: raw_b = dom_cal["bias"] if raw_b is None: pb = meta.get("position_biases", {}) for key in (bucket_exact, bucket_pipe, bucket_standard): if key in pb and pb[key] is not None: raw_b = pb[key] break if raw_b is None: bc = meta.get("bucket_calibrations", {}).get(bucket_pipe, {}) if "bias" in bc and bc["bias"] is not None: raw_b = bc["bias"] if raw_b and len(raw_b) == k and any(abs(x) > 1e-5 for x in raw_b): bias_t = torch.tensor(raw_b, dtype=torch.float32) return T, bias_t def clean_state_dict(raw: Dict[str, Any]): out = {} for k, v in raw.items(): k_clean = k for pfx in ("_orig_mod.", "module.", "backbone."): if k_clean.startswith(pfx): k_clean = k_clean[len(pfx):] out[k_clean] = v return out def restore_memory(ckpt: Dict[str, Any], model: CortexV7, device: torch.device): raw = ckpt.get("persistent_memory_state") if raw is None and "training_state" in ckpt: raw = ckpt["training_state"].get("persistent_memory_state") if raw is None or not isinstance(raw, (list, tuple)) or len(raw) != len(model.memory): return [mem.init_memory(1, device).detach().clone() for mem in model.memory] out = [] for mem_mod, state in zip(model.memory, raw): dtype = mem_mod.memory_init.dtype if hasattr(mem_mod, "memory_init") else next(mem_mod.parameters()).dtype out.append(state.detach().to(device=device, dtype=dtype).clone()) return out def load_nexus_model(ckpt_path: Path, device: torch.device, dtype: torch.dtype): print(f"Loading Nexus System 1 checkpoint from {ckpt_path}...") ckpt = torch.load(str(ckpt_path), map_location="cpu", weights_only=False) cfg = ckpt.get("base_cfg", ckpt.get("cfg", {})) use_flash = False if torch.cuda.is_available(): try: import flash_attn # noqa: F401 cap = torch.cuda.get_device_capability() use_flash = cap[0] >= 8 except Exception: use_flash = False raw_state = ckpt.get("model", ckpt.get("model_state_dict", ckpt)) state = clean_state_dict(raw_state) decision_layers = ckpt.get("config", {}).get("decision_layers") if decision_layers is None: layer_keys = [k for k in state.keys() if "system1_head.transformer.layers." in k or "comparator_layers." in k] if layer_keys: layer_indices = [] for k in layer_keys: for token in ["system1_head.transformer.layers.", "comparator_layers."]: if token in k: try: layer_indices.append(int(k.split(token)[1].split(".")[0])) except Exception: pass decision_layers = max(layer_indices) + 1 if layer_indices else 1 else: decision_layers = 1 print(f" [DECISION HEAD] Dynamic decision_layers={decision_layers}") model = CortexV7( vocab_size=int(cfg.get("vocab_size", 100277)), dim=int(cfg.get("dim", 1280)), heads=int(cfg.get("heads", 16)), kv_heads=int(cfg.get("kv_heads", 4)), num_layers=int(cfg.get("num_layers", 20)), memory_slots=int(cfg.get("memory_slots", 128)), mtp_depths=int(cfg.get("mtp_depths", 1)), decision_layers=decision_layers, use_flash=use_flash, ) model_params = dict(model.named_parameters()) compatible_state = {} for k, v in state.items(): if k in model_params and model_params[k].shape != v.shape: print(f" [WARN] Skipping parameter {k} due to shape change: {v.shape} -> {model_params[k].shape} (fresh init)") continue compatible_state[k] = v model.load_state_dict(compatible_state, strict=False) model.use_system1_head = True model = model.to(device=device, dtype=dtype).eval() memory = restore_memory(ckpt, model, device) total_params = sum(p.numel() for p in model.parameters()) print(f"Model loaded successfully | Total parameters: {total_params:,} ({total_params/1e9:.3f}B)") return model, memory, total_params # --------------------------------------------------------------------------- # S1MB Official Execution Engine # --------------------------------------------------------------------------- @torch.no_grad() def evaluate_benchmark( model: CortexV7, memory_base: List[torch.Tensor], benchmark_meta: Dict[str, Any], enc: Any, device: torch.device, dtype: torch.dtype, limit: Optional[int] = None, memory_mode: str = "dynamic", seq_len: int = 1024, calibration: Optional[Dict[str, Any]] = None, threshold: float = 0.50, apply_bias: bool = False, ) -> Dict[str, Any]: b_id = benchmark_meta["id"] cfg_name = benchmark_meta["config"] task = benchmark_meta["task"] target_d_id = benchmark_meta.get("decision_id") print(f"\nEvaluating S1MB Benchmark: {b_id} (Config: {cfg_name}, Task: {task.upper()})") ds = load_dataset("hotchpotch/S1MB-english-v1", cfg_name, split="test", streaming=False) cases = list(ds) if limit is not None and limit < len(cases): cases = cases[:limit] print(f" Loaded {len(cases)} test cases from hotchpotch/S1MB-english-v1 ({cfg_name})") if memory_mode == "frozen": memory_state = [m.clone() for m in memory_base] elif memory_mode == "none": memory_state = None else: memory_state = [m.clone() for m in memory_base] all_predictions: List[Dict[str, float]] = [] all_targets: List[Dict[str, float]] = [] all_option_ids: List[List[str]] = [] all_option_values: List[List[Optional[float]]] = [] saved_predictions: List[Dict[str, Any]] = [] t0 = time.perf_counter() for idx, case in enumerate(cases): case_id = case.get("case_id", f"case_{idx}") matching_decisions = [] for d in case["input"].get("decisions", []): d_type = str(d.get("type", "")).strip().lower() if target_d_id is not None: if d.get("id") == target_d_id: matching_decisions.append(d) elif d_type == task: matching_decisions.append(d) if not matching_decisions and case["input"].get("decisions"): matching_decisions = [case["input"]["decisions"][0]] for q in matching_decisions: prompt, options_text, option_ids, option_values, q_id, q_type, dom_idx, dom_name, prim_idx = format_s1mb_prompt_and_options( case, decision_obj=q, cfg_name=cfg_name, task_type=task ) tokens = enc.encode(prompt, allowed_special=set()) spans = find_option_spans(tokens, enc, options_text) if spans is None: last = max(0, len(tokens) - 1) spans = [(max(0, last - (len(options_text) - 1 - i)), max(0, last - (len(options_text) - 1 - i))) for i in range(len(options_text))] # Truncate left if sequence exceeds seq_len if len(tokens) > seq_len: excess = len(tokens) - seq_len tokens = tokens[excess:] spans = [(max(0, min(seq_len - 1, s - excess)), max(0, min(seq_len - 1, e - excess))) for s, e in spans] # Targets extraction target_probs_dict = {} target_records = case.get("targets", []) matched_target = None for tr in target_records: if tr.get("decision_id") == q_id: matched_target = tr break if matched_target is None and target_records: matched_target = target_records[0] if matched_target: t_ids = matched_target.get("ids", []) t_probs = matched_target.get("probabilities", []) target_probs_dict = dict(zip(t_ids, t_probs)) else: target_probs_dict = {opt_id: (1.0 if i == 0 else 0.0) for i, opt_id in enumerate(option_ids)} # Forward pass with dynamically resolved domain and primitive conditioning inp_tensor = torch.tensor([tokens], device=device, dtype=torch.long) pos_tensor = torch.tensor([spans], device=device, dtype=torch.long) mem_input = memory_state if memory_mode != "none" else None if memory_mode == "frozen": mem_input = [m.clone() for m in memory_base] task_name = q_id.split('_')[-1] if '_' in q_id else q_id with torch.autocast(device_type="cuda", dtype=dtype, enabled=(device.type == "cuda")): logits, _, _, new_mem = model( inp_tensor, candidate_positions=pos_tensor, candidate_mask=None, last_token_only=True, memory_state=mem_input, primitive_id=prim_idx, domain_id=dom_idx, disable_memory=(memory_mode == "none"), ) if memory_mode == "dynamic" and new_mem is not None: memory_state = [m.detach().clone() for m in new_mem] logits_k = logits[0, 0].float() # Domain-Aware Calibration (Temperature + Affine Bias) if calibration: T, bias_t = get_calibration_parameters(calibration, dom_name, task, len(option_ids), apply_bias=apply_bias) if bias_t is not None: logits_k = (logits_k / T) + bias_t.to(device=logits_k.device, dtype=logits_k.dtype) else: logits_k = logits_k / T probs_k = F.softmax(logits_k, dim=-1).cpu().tolist() pred_probs_dict = {} for opt_id, p_val in zip(option_ids, probs_k): pred_probs_dict[opt_id] = float(p_val) # Normalize to exact sum 1.0 total_p = sum(pred_probs_dict.values()) if total_p > 0: pred_probs_dict = {k: v / total_p for k, v in pred_probs_dict.items()} all_predictions.append(pred_probs_dict) all_targets.append(target_probs_dict) all_option_ids.append(option_ids) all_option_values.append(option_values) saved_predictions.append({ "case_id": case_id, "question_id": q_id, "probabilities": pred_probs_dict, "error": None, "abstention": None, }) if (idx + 1) % 25 == 0 or (idx + 1) == len(cases): print(f" Processed {idx + 1}/{len(cases)} cases ({len(all_predictions)} decisions)...", flush=True) elapsed = time.perf_counter() - t0 cal_thresh = threshold if task == "noul" and calibration: cal_thresh = calibration.get("decision_thresholds", {}).get("noul_threshold", threshold) metrics = calculate_s1mb_metrics( task=task, predictions=all_predictions, target_distributions=all_targets, option_ids_list=all_option_ids, option_values_list=all_option_values, threshold=cal_thresh, ) primary_key = { "choice": "target_mass_at_prediction", "noul": "binary_brier", "score": "normalized_expected_score_mae", }[task] print(f" --> Top-1 Raw Accuracy: {metrics.get('top1_accuracy', 0.0)*100:.2f}%") print(f" --> Primary Metric ({primary_key}): {metrics.get(primary_key, 0.0):.4f}") print(f" --> Baseline Adjusted Score: {metrics.get('baseline_adjusted_score', 0.0)*100:.2f}% (Elapsed: {elapsed:.1f}s)") return { "benchmark_id": b_id, "name": benchmark_meta.get("name", b_id), "task": task, "config": cfg_name, "case_count": len(cases), "decision_count": len(all_predictions), "top1_accuracy": metrics.get("top1_accuracy", 0.0), "primary_metric_name": primary_key, "primary_metric_value": metrics.get(primary_key), "baseline_adjusted_score": metrics.get("baseline_adjusted_score", 0.0), "all_metrics": metrics, "elapsed_seconds": elapsed, "predictions": saved_predictions, } # --------------------------------------------------------------------------- # Interleaved Multi-Domain Suite Evaluator (Official S1MB Parity) # --------------------------------------------------------------------------- @torch.no_grad() def evaluate_typed_decisions_interleaved_suite( model: CortexV7, memory_base: List[torch.Tensor], enc: Any, device: torch.device, dtype: torch.dtype, limit: Optional[int] = None, memory_mode: str = "dynamic", seq_len: int = 1024, calibration: Optional[Dict[str, Any]] = None, threshold: float = 0.50, apply_bias: bool = False, interleave: bool = True, case_decay: float = 1.0, ) -> List[Dict[str, Any]]: """ Evaluates the full S1MB Typed Decisions Suite (Choice, Noul, Score) in a single interleaved multi-domain pass matching the continuous training distribution. Prevents single-domain memory saturation, maintains unbroken persistent scratchpad state, and returns 3 compliant S1MB benchmark result dictionaries (Choice, Noul, Score). """ print(f"\n====================================================================================================") print(f" NEXUS SYSTEM 1 — S1MB TYPED DECISIONS INTERLEAVED EVALUATION SUITE") print(f" Memory Mode: {memory_mode.upper()} | Interleave: {interleave} | Threshold: {threshold} | Apply Bias: {apply_bias}") print(f"====================================================================================================") ds = load_dataset("hotchpotch/S1MB-english-v1", "laya__typed_decisions", split="test", streaming=False) cases = list(ds) if limit is not None and limit < len(cases): cases = cases[:limit] print(f" Loaded {len(cases)} test cases from hotchpotch/S1MB-english-v1 (laya__typed_decisions)") if interleave: cases_by_dom = defaultdict(list) for c in cases: s = c["input"].get("state_json") or c["input"].get("state", {}) if isinstance(s, str): try: s = json.loads(s) except Exception: pass if isinstance(s, dict): if "agent" in s: dom = "agent_trace" elif "account" in s or "customer" in s: dom = "customer_service" elif "delivery" in s or "invoice" in s: dom = "invoice" elif "alert" in s: dom = "security" else: dom = "other" else: dom = "other" cases_by_dom[dom].append(c) interleaved_cases = [] dom_keys = sorted(cases_by_dom.keys()) max_len = max(len(v) for v in cases_by_dom.values()) for idx in range(max_len): for dk in dom_keys: if idx < len(cases_by_dom[dk]): interleaved_cases.append(cases_by_dom[dk][idx]) eval_cases = interleaved_cases print(f" [STREAM] Interleaved {len(eval_cases)} cases across {len(dom_keys)} domains ({dict((k, len(v)) for k, v in cases_by_dom.items())})") else: eval_cases = cases if memory_mode == "frozen": memory_state = [m.clone() for m in memory_base] elif memory_mode == "none": memory_state = None else: memory_state = [m.clone() for m in memory_base] preds_map: Dict[Tuple[str, str], Dict[str, float]] = {} t0 = time.perf_counter() for idx, case in enumerate(eval_cases): case_id = case.get("case_id", f"case_{idx}") if memory_mode == "dynamic" and idx > 0 and case_decay < 1.0: memory_state = [ (case_decay * m + (1.0 - case_decay) * base.clone()) for m, base in zip(memory_state, memory_base) ] decisions = case["input"].get("decisions", []) for q in decisions: q_id = q["id"] task = str(q.get("type", "choice")).strip().lower() prompt, options_text, option_ids, option_values, _, q_type, dom_idx, dom_name, prim_idx = format_s1mb_prompt_and_options( case, decision_obj=q, cfg_name="laya__typed_decisions", task_type=task ) tokens = enc.encode(prompt, allowed_special=set()) spans = find_option_spans(tokens, enc, options_text) if spans is None: last = max(0, len(tokens) - 1) spans = [(max(0, last - (len(options_text) - 1 - i)), max(0, last - (len(options_text) - 1 - i))) for i in range(len(options_text))] if len(tokens) > seq_len: excess = len(tokens) - seq_len tokens = tokens[excess:] spans = [(max(0, min(seq_len - 1, s - excess)), max(0, min(seq_len - 1, e - excess))) for s, e in spans] inp_tensor = torch.tensor([tokens], device=device, dtype=torch.long) pos_tensor = torch.tensor([spans], device=device, dtype=torch.long) mem_input = memory_state if memory_mode != "none" else None if memory_mode == "frozen": mem_input = [m.clone() for m in memory_base] with torch.autocast(device_type="cuda", dtype=dtype, enabled=(device.type == "cuda")): logits, _, _, new_mem = model( inp_tensor, candidate_positions=pos_tensor, candidate_mask=None, last_token_only=True, memory_state=mem_input, primitive_id=prim_idx, domain_id=dom_idx, disable_memory=(memory_mode == "none"), ) if memory_mode == "dynamic" and new_mem is not None: memory_state = [m.detach().clone() for m in new_mem] logits_k = logits[0, 0].float() if calibration: T, bias_t = get_calibration_parameters(calibration, dom_name, task, len(option_ids), apply_bias=apply_bias) if bias_t is not None: logits_k = (logits_k / T) + bias_t.to(device=logits_k.device, dtype=logits_k.dtype) else: logits_k = logits_k / T probs_k = F.softmax(logits_k, dim=-1).cpu().tolist() pred_dict = {opt_id: float(p) for opt_id, p in zip(option_ids, probs_k)} tot = sum(pred_dict.values()) if tot > 0: pred_dict = {k: v / tot for k, v in pred_dict.items()} preds_map[(case_id, q_id)] = pred_dict if (idx + 1) % 25 == 0 or (idx + 1) == len(eval_cases): print(f" Processed {idx + 1}/{len(eval_cases)} cases ({len(preds_map)} decisions)...", flush=True) elapsed_total = time.perf_counter() - t0 # Assemble canonical results for each benchmark in TYPED_DECISIONS_BENCHMARKS results = [] for b_meta in TYPED_DECISIONS_BENCHMARKS: task = b_meta["task"] b_id = b_meta["id"] all_predictions = [] all_targets = [] all_option_ids = [] all_option_values = [] saved_predictions = [] for case in cases: case_id = case.get("case_id") matching_decisions = [d for d in case["input"].get("decisions", []) if str(d.get("type", "")).strip().lower() == task] target_records = case.get("targets", []) for q in matching_decisions: q_id = q["id"] pred = preds_map.get((case_id, q_id)) if pred is None: continue matched_target = None for tr in target_records: if tr.get("decision_id") == q_id: matched_target = tr break _, _, option_ids, option_values, _, _, _, _, _ = format_s1mb_prompt_and_options( case, decision_obj=q, cfg_name="laya__typed_decisions", task_type=task ) if matched_target: t_ids = matched_target.get("ids", []) t_probs = matched_target.get("probabilities", []) target_dict = dict(zip(t_ids, t_probs)) else: target_dict = {opt_id: (1.0 if i == 0 else 0.0) for i, opt_id in enumerate(option_ids)} all_predictions.append(pred) all_targets.append(target_dict) all_option_ids.append(option_ids) all_option_values.append(option_values) saved_predictions.append({ "case_id": case_id, "question_id": q_id, "probabilities": pred, "error": None, "abstention": None, }) cal_thresh = threshold if task == "noul" else 0.50 if task == "noul" and calibration: cal_thresh = calibration.get("decision_thresholds", {}).get("noul_threshold", threshold) metrics = calculate_s1mb_metrics( task=task, predictions=all_predictions, target_distributions=all_targets, option_ids_list=all_option_ids, option_values_list=all_option_values, threshold=cal_thresh, ) primary_key = { "choice": "target_mass_at_prediction", "noul": "binary_brier", "score": "normalized_expected_score_mae", }[task] print(f"\nBenchmark Result: {b_id} ({task.upper()})") print(f" --> Decisions: {len(all_predictions)}") print(f" --> Top-1 Raw Accuracy: {metrics.get('top1_accuracy', 0.0)*100:.2f}%") print(f" --> Primary Metric ({primary_key}): {metrics.get(primary_key, 0.0):.4f}") print(f" --> Baseline Adjusted Score: {metrics.get('baseline_adjusted_score', 0.0)*100:.2f}%") if task == "noul": print(f" --> Balanced Accuracy: {metrics.get('balanced_accuracy', 0.0)*100:.2f}%") results.append({ "benchmark_id": b_id, "name": b_meta.get("name", b_id), "task": task, "config": "laya__typed_decisions", "case_count": len(cases), "decision_count": len(all_predictions), "top1_accuracy": metrics.get("top1_accuracy", 0.0), "primary_metric_name": primary_key, "primary_metric_value": metrics.get(primary_key), "baseline_adjusted_score": metrics.get("baseline_adjusted_score", 0.0), "all_metrics": metrics, "elapsed_seconds": elapsed_total, "predictions": saved_predictions, }) return results # --------------------------------------------------------------------------- # Local Benchmark Evaluation Engine (for typed_decisions_benchmark_test.jsonl) # --------------------------------------------------------------------------- @torch.no_grad() def evaluate_local_test( model: CortexV7, memory_base: List[torch.Tensor], test_path: Path, enc: Any, device: torch.device, dtype: torch.dtype, limit: Optional[int] = None, memory_mode: str = "dynamic", seq_len: int = 1024, calibration: Optional[Dict[str, Any]] = None, threshold: float = 0.50, apply_bias: bool = False, interleave: bool = True, ) -> List[Dict[str, Any]]: print(f"\nEvaluating Local Typed Decisions Benchmark: {test_path.name}") records = [] with test_path.open("r", encoding="utf-8") as f: for line in f: if line.strip(): records.append(json.loads(line)) if limit is not None and limit < len(records): records = records[:limit] print(f" Loaded {len(records)} test samples from {test_path.name}") if interleave: records_by_dom = defaultdict(list) for r in records: d_name = str(r.get("domain") or r.get("workflow") or "other").strip().lower() records_by_dom[d_name].append(r) interleaved_records = [] dom_keys = sorted(records_by_dom.keys()) max_len = max(len(v) for v in records_by_dom.values()) for idx in range(max_len): for dk in dom_keys: if idx < len(records_by_dom[dk]): interleaved_records.append(records_by_dom[dk][idx]) eval_records = interleaved_records else: eval_records = records if memory_mode == "frozen": memory_state = [m.clone() for m in memory_base] elif memory_mode == "none": memory_state = None else: memory_state = [m.clone() for m in memory_base] preds_by_prim = defaultdict(list) targets_by_prim = defaultdict(list) opt_ids_by_prim = defaultdict(list) opt_vals_by_prim = defaultdict(list) saved_preds_by_prim = defaultdict(list) t0 = time.perf_counter() for idx, rec in enumerate(eval_records): prim = str(rec.get("primitive") or rec.get("task") or "choice").strip().lower() prompt = rec["prompt"] options = rec["options"] k = len(options) opt_ids = [str(i) for i in range(k)] if prim == "score": opt_vals = [float(i) for i in range(k)] else: opt_vals = [None] * k target_probs = rec.get("target_probs") if not target_probs: t_idx = int(rec.get("target_idx", 0)) target_probs = [1.0 if i == t_idx else 0.0 for i in range(k)] target_probs_dict = {str(i): float(target_probs[i]) for i in range(min(k, len(target_probs)))} tokens = enc.encode(prompt, allowed_special=set()) spans = find_option_spans(tokens, enc, options) if spans is None: last = max(0, len(tokens) - 1) spans = [(max(0, last - (len(options) - 1 - i)), max(0, last - (len(options) - 1 - i))) for i in range(len(options))] if len(tokens) > seq_len: excess = len(tokens) - seq_len tokens = tokens[excess:] spans = [(max(0, min(seq_len - 1, s - excess)), max(0, min(seq_len - 1, e - excess))) for s, e in spans] prim_idx = parse_primitive_id(prim) dom_name = str(rec.get("domain") or rec.get("workflow") or "").strip().lower() dom_idx = parse_domain_id(dom_name) inp_tensor = torch.tensor([tokens], device=device, dtype=torch.long) pos_tensor = torch.tensor([spans], device=device, dtype=torch.long) mem_input = memory_state if memory_mode != "none" else None if memory_mode == "frozen": mem_input = [m.clone() for m in memory_base] with torch.autocast(device_type="cuda", dtype=dtype, enabled=(device.type == "cuda")): logits, _, _, new_mem = model( inp_tensor, candidate_positions=pos_tensor, candidate_mask=None, last_token_only=True, memory_state=mem_input, primitive_id=prim_idx, domain_id=dom_idx, disable_memory=(memory_mode == "none"), ) if memory_mode == "dynamic" and new_mem is not None: memory_state = [m.detach().clone() for m in new_mem] logits_k = logits[0, 0].float() # Apply calibration (domain-aware temperature + affine bias or canonical Laya temperature) if calibration: T, bias_t = get_calibration_parameters(calibration, dom_name, prim, k, apply_bias=apply_bias) if bias_t is not None: logits_k = (logits_k / T) + bias_t.to(device=logits_k.device, dtype=logits_k.dtype) else: logits_k = logits_k / T probs_k = F.softmax(logits_k, dim=-1).cpu().tolist() pred_probs_dict = {str(i): float(probs_k[i]) for i in range(min(k, len(probs_k)))} tot = sum(pred_probs_dict.values()) if tot > 0: pred_probs_dict = {key: val / tot for key, val in pred_probs_dict.items()} preds_by_prim[prim].append(pred_probs_dict) targets_by_prim[prim].append(target_probs_dict) opt_ids_by_prim[prim].append(opt_ids) opt_vals_by_prim[prim].append(opt_vals) saved_preds_by_prim[prim].append({ "case_id": rec.get("id", f"case_{idx}"), "probabilities": pred_probs_dict, }) if (idx + 1) % 100 == 0 or (idx + 1) == len(eval_records): print(f" Processed {idx + 1}/{len(eval_records)} cases...", flush=True) elapsed_total = time.perf_counter() - t0 results = [] prims = ["choice", "noul", "score"] for prim in prims: if not preds_by_prim[prim]: continue cal_thresh = threshold if prim == "noul" else 0.50 metrics = calculate_s1mb_metrics( task=prim, predictions=preds_by_prim[prim], target_distributions=targets_by_prim[prim], option_ids_list=opt_ids_by_prim[prim], option_values_list=opt_vals_by_prim[prim], threshold=cal_thresh, ) primary_key = { "choice": "target_mass_at_prediction", "noul": "binary_brier", "score": "normalized_expected_score_mae", }[prim] top1_pct = metrics.get("top1_accuracy", 0.0) * 100.0 print(f"\n Primitive Result: {prim.upper()} ({len(preds_by_prim[prim])} cases)") print(f" --> Top-1 Raw Accuracy: {top1_pct:.2f}%") print(f" --> Primary Metric ({primary_key}): {metrics.get(primary_key, 0.0):.4f}") print(f" --> Baseline Adjusted Score: {metrics.get('baseline_adjusted_score', 0.0)*100:.2f}%") if prim == "noul": print(f" --> Balanced Accuracy: {metrics.get('balanced_accuracy', 0.0)*100:.2f}%") prim_display_names = { "choice": "Local Typed Decisions (Choice: Action)", "noul": "Local Typed Decisions (Noul: Review Required)", "score": "Local Typed Decisions (Score: Risk Level)", } results.append({ "benchmark_id": f"local-typed-decisions-{prim}-v1", "name": prim_display_names.get(prim, f"Local {prim.title()}"), "task": prim, "case_count": len(preds_by_prim[prim]), "top1_accuracy": metrics.get("top1_accuracy", 0.0), "primary_metric_name": primary_key, "primary_metric_value": metrics.get(primary_key), "baseline_adjusted_score": metrics.get("baseline_adjusted_score", 0.0), "all_metrics": metrics, "elapsed_seconds": elapsed_total, "predictions": saved_preds_by_prim[prim], }) return results return results # --------------------------------------------------------------------------- # S1MB Official Leaderboard Report & Comparison # --------------------------------------------------------------------------- def print_leaderboard_comparison(results: List[Dict[str, Any]], total_params: int): task_scores = defaultdict(list) raw_accs = defaultdict(list) for r in results: task = r["task"] score = r.get("baseline_adjusted_score", 0.0) task_scores[task].append(score * 100.0) raw_acc = r.get("top1_accuracy", 0.0) raw_accs[task].append(raw_acc * 100.0) choice_score = statistics.mean(task_scores["choice"]) if task_scores["choice"] else 0.0 noul_score = statistics.mean(task_scores["noul"]) if task_scores["noul"] else 0.0 score_score = statistics.mean(task_scores["score"]) if task_scores["score"] else 0.0 # S1MB official leaderboard averages ALL 3 task scores (including 0.0) all_task_scores = [choice_score, noul_score, score_score] task_avg = statistics.mean(all_task_scores) choice_raw = statistics.mean(raw_accs["choice"]) if raw_accs["choice"] else 0.0 noul_raw = statistics.mean(raw_accs["noul"]) if raw_accs["noul"] else 0.0 score_raw = statistics.mean(raw_accs["score"]) if raw_accs["score"] else 0.0 all_raw = [r.get("top1_accuracy", 0.0) * 100.0 for r in results if "top1_accuracy" in r] overall_raw_acc = statistics.mean(all_raw) if all_raw else 0.0 param_str = f"{total_params / 1e6:.1f}M ({total_params / 1e9:.3f}B)" print("\n" + "=" * 106) print(" S1MB EVALUATION BREAKDOWN: TOP-1 ACCURACY & OFFICIAL LEADERBOARD METRICS") print("=" * 106) print(f"{'Benchmark / Task':<42} {'Decisions':<10} {'Top-1 Raw Acc':<16} {'S1MB Score':<14} {'Primary Metric':<22}") print("-" * 106) for r in results: b_name = r.get("name") or r.get("benchmark_id") cnt = r.get("decision_count") or r.get("case_count", 0) top1 = r.get("top1_accuracy", 0.0) * 100.0 s1mb_sc = r.get("baseline_adjusted_score", 0.0) * 100.0 p_name = r.get("primary_metric_name", "") p_val = r.get("primary_metric_value", 0.0) print(f"{b_name:<42} {cnt:<10} {top1:>6.2f}% {s1mb_sc:>6.2f}% {p_name}={p_val:.4f}") print("=" * 106) print(" S1MB (SYSTEM ONE MOSAIC BENCHMARK) — OFFICIAL LEADERBOARD COMPARISON") print("=" * 106) print(f"{'Rank':<6} {'Model':<30} {'Params':<14} {'Task Avg':<10} {'Choice':<10} {'Noul':<10} {'Score':<10} {'Top-1 Raw Acc':<14}") print("-" * 106) models_table = [ {"name": "Nexus System 1 (CortexV7)", "params": param_str, "avg": task_avg, "choice": choice_score, "noul": noul_score, "score": score_score, "raw_acc": f"{overall_raw_acc:.2f}%", "is_nexus": True}, {"name": "Bekko-400M (hotchpotch)", "params": "400M (0.400B)", "avg": LEADERBOARD_BASELINES["Bekko-400M"]["task_avg"], "choice": LEADERBOARD_BASELINES["Bekko-400M"]["choice"], "noul": LEADERBOARD_BASELINES["Bekko-400M"]["noul"], "score": LEADERBOARD_BASELINES["Bekko-400M"]["score"], "raw_acc": "N/A", "is_nexus": False}, {"name": "ModernBERT-151M-RLCD", "params": "151M (0.151B)", "avg": LEADERBOARD_BASELINES["ModernBERT-151M-RLCD"]["task_avg"], "choice": LEADERBOARD_BASELINES["ModernBERT-151M-RLCD"]["choice"], "noul": LEADERBOARD_BASELINES["ModernBERT-151M-RLCD"]["noul"], "score": LEADERBOARD_BASELINES["ModernBERT-151M-RLCD"]["score"], "raw_acc": "N/A", "is_nexus": False}, {"name": "Laya-Typed-Decisions", "params": "421M (0.421B)", "avg": LEADERBOARD_BASELINES["Laya-Typed-Decisions (421M)"]["task_avg"], "choice": LEADERBOARD_BASELINES["Laya-Typed-Decisions (421M)"]["choice"], "noul": LEADERBOARD_BASELINES["Laya-Typed-Decisions (421M)"]["noul"], "score": LEADERBOARD_BASELINES["Laya-Typed-Decisions (421M)"]["score"], "raw_acc": "N/A", "is_nexus": False}, ] models_table.sort(key=lambda m: m["avg"], reverse=True) for rank, m in enumerate(models_table, 1): marker = " [* OUR MODEL]" if m["is_nexus"] else "" print(f"#{rank:<5} {m['name'] + marker:<30} {m['params']:<14} {m['avg']:>6.2f}% {m['choice']:>6.2f}% {m['noul']:>6.2f}% {m['score']:>6.2f}% {m['raw_acc']:>10}") print("=" * 106) return { "choice": choice_score, "noul": noul_score, "score": score_score, "task_avg": task_avg, "overall_raw_accuracy": overall_raw_acc, } # --------------------------------------------------------------------------- # S1MB Export & Submission Packager # --------------------------------------------------------------------------- def export_s1mb_submission( results: List[Dict[str, Any]], output_dir: Path, model_id: str, total_params: int, ): model_slug = model_id.replace("/", "__").replace(":", "_") target_folder = output_dir / model_slug target_folder.mkdir(parents=True, exist_ok=True) print(f"\nPackaging official submission files to {target_folder}...") metadata = { "id": model_id, "adapter": "cortex-system-one", "revision": "main", "total_params": total_params, "active_params": total_params, "parameter_count_method": "embedding_excluded_parameters_v1", "created_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "platform": platform.platform(), "python": platform.python_version(), "settings": { "backbone": "Cortex", "decision_head": "CognitiveDecisionTransformerHead", "contrastive_centering": True, "memory_cross_attention": True, "temperature_scaling": "k_adaptive", }, } with (target_folder / "metadata.json").open("w", encoding="utf-8") as f: json.dump(metadata, f, indent=2) for res in results: b_id = res["benchmark_id"] res_payload = { "format_version": 1, "run_id": f"nexus_s1mb_{int(time.time())}", "benchmark": { "id": b_id, "task": res["task"], "dataset": f"datasets/{res.get('config', 'laya__typed_decisions')}", "split": "test", "case_count": res["case_count"], "decision_count": res.get("decision_count", len(res["predictions"])), "primary_metric": res.get("primary_metric_name"), "evaluation_family": "ordinary", }, "metrics": res["all_metrics"], "predictions": res["predictions"], } compressed_bytes = lzma.compress(json.dumps(res_payload).encode("utf-8")) (target_folder / f"{b_id}.json.xz").write_bytes(compressed_bytes) summary_path = target_folder / "summary.json" with summary_path.open("w", encoding="utf-8") as f: json.dump( { "model_id": model_id, "total_params": total_params, "benchmarks": [ { "id": r["benchmark_id"], "task": r["task"], "case_count": r.get("case_count"), "decision_count": r.get("decision_count", len(r.get("predictions", []))), "score": r["baseline_adjusted_score"] * 100.0, "primary_metric": r["primary_metric_value"], "top1_accuracy": r.get("top1_accuracy", 0.0) * 100.0, } for r in results ], }, f, indent=2, ) print(f" [OK] Submission packaged successfully: {len(results)} benchmarks + metadata.json") print(f" [OK] Location: {target_folder}") # --------------------------------------------------------------------------- # Main CLI Entrypoint # --------------------------------------------------------------------------- def main(): parser = argparse.ArgumentParser(description="Official S1MB Evaluation for Nexus System 1") parser.add_argument("checkpoint_pos", nargs="?", default=None, help="Path to checkpoint .pth (positional)") parser.add_argument("--checkpoint", "--ckpt", type=str, default=None, help="Path to checkpoint .pth") parser.add_argument("--suite", type=str, default="smoke", choices=["smoke", "typed_decisions", "local", "full"], help="Benchmark suite to run") parser.add_argument("--test-file", type=str, default="typed_decisions_benchmark_test.jsonl", help="Path to local test dataset for --suite local") parser.add_argument("--limit", type=int, default=None, help="Optional max cases per benchmark (e.g. 50)") parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu") parser.add_argument("--dtype", type=str, default="float16", choices=["float16", "bfloat16", "float32"]) parser.add_argument("--memory-mode", type=str, default="dynamic", choices=["dynamic", "frozen", "none"], help="Memory mode (default: dynamic for persistent neural memory)") parser.add_argument("--seq-len", type=int, default=1024) parser.add_argument("--output-dir", type=str, default="s1mb_results") parser.add_argument("--model-name", type=str, default="cortex-system-one") parser.add_argument("--calibration", "--cal", type=str, default=None, help="Path to domain calibration json (e.g. cortex_system_one_calibration.json)") parser.add_argument("--threshold", type=float, default=0.50, help="Classification decision threshold for Noul (default: 0.50)") parser.add_argument("--interleave", action=argparse.BooleanOptionalAction, default=True, help="Interleave cases across domains round-robin to match training memory distribution (default: True)") parser.add_argument("--apply-bias", action="store_true", default=False, help="Apply additive affine bias vectors from calibration (default: False)") parser.add_argument("--case-decay", type=float, default=1.0, help="Dynamic memory decay factor at case boundary (default: 1.0 = unbroken dynamic, < 1.0 blends with base init)") parser.add_argument("--dynamic-retain-floor", type=float, default=None, help="Override memory retain_floor for active forgetting") parser.add_argument("--affinity-bias-shift", type=float, default=0.0, help="Additive shift to affinity gate bias for active storage") parser.add_argument("--export-submission", action="store_true", help="Package submission files into s1mb-result format (default: False)") args = parser.parse_args() device = torch.device(args.device) dtype_map = { "float16": torch.float16, "bfloat16": torch.bfloat16, "float32": torch.float32, } dtype = dtype_map[args.dtype] ckpt_arg = args.checkpoint or args.checkpoint_pos if not ckpt_arg: if Path("ckpt_cortex_system_one_champion.pth").is_file(): ckpt_arg = "ckpt_cortex_system_one_champion.pth" elif Path("checkpoints/ckpt_nexus_multidomain_best.pth").is_file(): ckpt_arg = "checkpoints/ckpt_nexus_multidomain_best.pth" elif Path("checkpoints/ckpt_nexus_specialist_latest.pth").is_file(): ckpt_arg = "checkpoints/ckpt_nexus_specialist_latest.pth" else: raise ValueError("Must provide checkpoint path either positionally or with --checkpoint") ckpt_path = Path(ckpt_arg) if not ckpt_path.is_file(): raise FileNotFoundError(f"Checkpoint not found at: {ckpt_path}") enc = tiktoken.get_encoding("cl100k_base") model, memory, total_params = load_nexus_model(ckpt_path, device, dtype) if args.dynamic_retain_floor is not None: for mem in model.memory: mem.retain_floor = args.dynamic_retain_floor print(f" [MEMORY] Configured dynamic retain_floor = {args.dynamic_retain_floor}") if args.affinity_bias_shift != 0.0: for mem in model.memory: mem.affinity_gate[0].bias.data.add_(args.affinity_bias_shift) print(f" [MEMORY] Configured affinity bias shift = {args.affinity_bias_shift:+.2f}") # Auto-discover calibration file if present calibration_meta = None if args.calibration and args.calibration.strip().lower() in ("none", "false", "off", "disable", "no"): print(" [CALIBRATION] Calibration explicitly disabled via CLI flag (evaluating pure raw model predictions).") else: cal_candidates = [] if args.calibration: cal_candidates.append(Path(args.calibration)) else: cal_candidates.append(ckpt_path.parent / "system1_multidomain_calibration.json") cal_candidates.append(Path("system1_multidomain_calibration.json")) cal_candidates.append(Path("system1_multidomain_calibration2.json")) cal_candidates.append(Path("system1_multidomain_calibration1.json")) for cp in cal_candidates: if cp.is_file(): try: with cp.open("r", encoding="utf-8") as f: calibration_meta = json.load(f) print(f" [CALIBRATION] Restored domain-aware affine vector calibration from {cp.name}") break except Exception: pass if not calibration_meta and args.calibration: print(f" [CALIBRATION WARNING] Specified calibration file '{args.calibration}' not found. Evaluating with pure raw predictions.") results = [] if args.suite == "local": test_file_path = Path(args.test_file) if not test_file_path.is_file(): raise FileNotFoundError(f"Local test file not found at: {test_file_path}") results = evaluate_local_test( model=model, memory_base=memory, test_path=test_file_path, enc=enc, device=device, dtype=dtype, limit=args.limit, memory_mode=args.memory_mode, seq_len=args.seq_len, calibration=calibration_meta, threshold=args.threshold, apply_bias=args.apply_bias, interleave=args.interleave, ) elif args.suite == "typed_decisions" and getattr(args, "interleave", True): results = evaluate_typed_decisions_interleaved_suite( model=model, memory_base=memory, enc=enc, device=device, dtype=dtype, limit=args.limit, memory_mode=args.memory_mode, seq_len=args.seq_len, calibration=calibration_meta, threshold=args.threshold, apply_bias=args.apply_bias, interleave=args.interleave, case_decay=args.case_decay, ) else: if args.suite == "smoke": suite_benchmarks = SMOKE_BENCHMARKS elif args.suite == "typed_decisions": suite_benchmarks = TYPED_DECISIONS_BENCHMARKS else: suite_benchmarks = SMOKE_BENCHMARKS + TYPED_DECISIONS_BENCHMARKS print(f"\nRunning S1MB Suite: {args.suite.upper()} ({len(suite_benchmarks)} benchmarks) | Memory Mode: {args.memory_mode.upper()}") for b_meta in suite_benchmarks: res = evaluate_benchmark( model=model, memory_base=memory, benchmark_meta=b_meta, enc=enc, device=device, dtype=dtype, limit=args.limit, memory_mode=args.memory_mode, seq_len=args.seq_len, calibration=calibration_meta, threshold=args.threshold, apply_bias=args.apply_bias, ) results.append(res) # Print summary and comparison against Bekko and Laya print_leaderboard_comparison(results, total_params) # Export submission files only if explicitly requested if args.export_submission: export_s1mb_submission( results=results, output_dir=Path(args.output_dir), model_id=args.model_name, total_params=total_params, ) if __name__ == "__main__": main()
#!/usr/bin/env python3
"""
====================================================================================================
NEXUS SYSTEM 1 — OFFICIAL S1MB (SYSTEM ONE MOSAIC BENCHMARK) EVALUATION & LEADERBOARD SUITE
Evaluates Nexus System 1 directly on the official benchmark by hotchpotch (Yuichi Tateno)
Supporting official task metrics: Choice (Target Mass / Accuracy), Noul (Brier / Balanced Accuracy),
and Score (Normalized MAE / RMSE), baseline adjustments, and direct comparison to Bekko & Laya.
Defaults to dynamic persistent neural memory.
====================================================================================================
"""
from __future__ import annotations
import argparse
import hashlib
import json
import lzma
import math
import os
import platform
import statistics
import sys
import time
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple
import torch
import torch.nn.functional as F
import tiktoken
from datasets import load_dataset
# Add script directory, current directory, and any checkpoint parent directories to sys.path
sys.path.insert(0, str(Path(__file__).resolve().parent))
sys.path.insert(0, str(Path.cwd()))
for arg in sys.argv:
try:
p = Path(arg).resolve()
if p.is_file() and (p.parent / "Model.py").is_file():
sys.path.insert(0, str(p.parent))
elif p.is_dir() and (p / "Model.py").is_file():
sys.path.insert(0, str(p))
except Exception:
pass
# Local imports
try:
from Model import CortexV7
except ImportError:
try:
from Model import Cortex as CortexV7
except ImportError as e:
raise ImportError(
f"Could not find Model.py in sys.path: {sys.path[:3]}. "
"Please ensure Model.py is in your working directory or PYTHONPATH."
) from e
EPSILON = 1e-12
# Multi-Domain Constants matching pretraining, training & evaluation
DOMAINS = [
"agent_trace",
"customer_service",
"invoice_processing",
"security_incidents"
]
def parse_domain_id(domain_str: str) -> int:
d = str(domain_str).lower()
for idx, name in enumerate(DOMAINS):
if name in d:
return idx
if "agent" in d:
return 0
if "customer" in d or "account" in d:
return 1
if "invoice" in d or "delivery" in d:
return 2
if "security" in d or "alert" in d:
return 3
return 0
# Exact Laya QTYPES matching common.py line 14: {"choice": 0, "score": 1, "noul": 2}
PRIMITIVES = ["choice", "score", "noul"]
def parse_primitive_id(primitive_str: str) -> int:
p = str(primitive_str).lower().strip()
if p in PRIMITIVES:
return PRIMITIVES.index(p)
return 0
# ---------------------------------------------------------------------------
# S1MB Benchmark Definitions & Suites
# ---------------------------------------------------------------------------
SMOKE_BENCHMARKS = [
{
"id": "arc-choice-test-v1",
"task": "choice",
"config": "arc",