siddiVinayaka commited on
Commit
466fb71
·
verified ·
1 Parent(s): cbf5d82

Add official S1MB benchmark evaluation script

Browse files
Files changed (1) hide show
  1. benchmark_s1mb_official.py +1809 -0
benchmark_s1mb_official.py ADDED
@@ -0,0 +1,1809 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ ====================================================================================================
4
+ NEXUS SYSTEM 1 — OFFICIAL S1MB (SYSTEM ONE MOSAIC BENCHMARK) EVALUATION & LEADERBOARD SUITE
5
+ Evaluates Nexus System 1 directly on the official benchmark by hotchpotch (Yuichi Tateno)
6
+ Supporting official task metrics: Choice (Target Mass / Accuracy), Noul (Brier / Balanced Accuracy),
7
+ and Score (Normalized MAE / RMSE), baseline adjustments, and direct comparison to Bekko & Laya.
8
+ Defaults to dynamic persistent neural memory.
9
+ ====================================================================================================
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import hashlib
15
+ import json
16
+ import lzma
17
+ import math
18
+ import os
19
+ import platform
20
+ import statistics
21
+ import sys
22
+ import time
23
+ from collections import defaultdict
24
+ from datetime import datetime, timezone
25
+ from pathlib import Path
26
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
27
+
28
+ import torch
29
+ import torch.nn.functional as F
30
+ import tiktoken
31
+ from datasets import load_dataset
32
+
33
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
34
+
35
+ # Local imports
36
+ from Model import CortexV7
37
+
38
+ EPSILON = 1e-12
39
+
40
+ # Multi-Domain Constants matching pretraining, training & evaluation
41
+ DOMAINS = [
42
+ "agent_trace",
43
+ "customer_service",
44
+ "invoice_processing",
45
+ "security_incidents"
46
+ ]
47
+
48
+ def parse_domain_id(domain_str: str) -> int:
49
+ d = str(domain_str).lower()
50
+ for idx, name in enumerate(DOMAINS):
51
+ if name in d:
52
+ return idx
53
+ if "agent" in d:
54
+ return 0
55
+ if "customer" in d or "account" in d:
56
+ return 1
57
+ if "invoice" in d or "delivery" in d:
58
+ return 2
59
+ if "security" in d or "alert" in d:
60
+ return 3
61
+ return 0
62
+
63
+ # Exact Laya QTYPES matching common.py line 14: {"choice": 0, "score": 1, "noul": 2}
64
+ PRIMITIVES = ["choice", "score", "noul"]
65
+
66
+ def parse_primitive_id(primitive_str: str) -> int:
67
+ p = str(primitive_str).lower().strip()
68
+ if p in PRIMITIVES:
69
+ return PRIMITIVES.index(p)
70
+ return 0
71
+
72
+ # ---------------------------------------------------------------------------
73
+ # S1MB Benchmark Definitions & Suites
74
+ # ---------------------------------------------------------------------------
75
+
76
+ SMOKE_BENCHMARKS = [
77
+ {
78
+ "id": "arc-choice-test-v1",
79
+ "task": "choice",
80
+ "config": "arc",
81
+ "decision_id": "answer",
82
+ "name": "ARC Science QA (Choice)",
83
+ },
84
+ {
85
+ "id": "aegis2-noul-test-v1",
86
+ "task": "noul",
87
+ "config": "aegis2",
88
+ "decision_id": "prompt_unsafe",
89
+ "name": "Aegis 2.0 Safety Guard (Noul)",
90
+ },
91
+ {
92
+ "id": "patent-similarity-score-test-v1",
93
+ "task": "score",
94
+ "config": "patent_similarity",
95
+ "decision_id": "similarity",
96
+ "name": "Patent Semantic Similarity (Score)",
97
+ },
98
+ ]
99
+
100
+ TYPED_DECISIONS_BENCHMARKS = [
101
+ {
102
+ "id": "laya--typed-decisions-choice-test-v1",
103
+ "task": "choice",
104
+ "config": "laya__typed_decisions",
105
+ "decision_id": None,
106
+ "name": "Typed Decisions (Choice)",
107
+ },
108
+ {
109
+ "id": "laya--typed-decisions-noul-test-v1",
110
+ "task": "noul",
111
+ "config": "laya__typed_decisions",
112
+ "decision_id": None,
113
+ "name": "Typed Decisions (Noul)",
114
+ },
115
+ {
116
+ "id": "laya--typed-decisions-score-test-v1",
117
+ "task": "score",
118
+ "config": "laya__typed_decisions",
119
+ "decision_id": None,
120
+ "name": "Typed Decisions (Score)",
121
+ },
122
+ ]
123
+
124
+ # Official Leaderboard Baselines for Sub-1B Models (Ground Truth from hotchpotch/s1mb-result)
125
+ LEADERBOARD_BASELINES = {
126
+ "Bekko-400M": {
127
+ "choice": 24.54,
128
+ "noul": 30.35,
129
+ "score": 45.79,
130
+ "task_avg": 33.56,
131
+ },
132
+ "Laya-Typed-Decisions (421M)": {
133
+ "choice": 28.68,
134
+ "noul": 44.42,
135
+ "score": 63.48,
136
+ "task_avg": 45.53,
137
+ },
138
+ "ModernBERT-151M-RLCD": {
139
+ "choice": 45.10,
140
+ "noul": 42.80,
141
+ "score": 28.50,
142
+ "task_avg": 38.80,
143
+ },
144
+ }
145
+
146
+ # ---------------------------------------------------------------------------
147
+ # Prompt & Token Span Formatting
148
+ # ---------------------------------------------------------------------------
149
+
150
+ def option_label(index: int) -> str:
151
+ n = index + 1
152
+ chars = []
153
+ while n:
154
+ n, rem = divmod(n - 1, 26)
155
+ chars.append(chr(65 + rem))
156
+ return "".join(reversed(chars))
157
+
158
+
159
+ def find_subsequence(haystack: Sequence[int], needle: Sequence[int], start: int = 0) -> int:
160
+ if not needle:
161
+ return -1
162
+ end = len(haystack) - len(needle) + 1
163
+ for i in range(max(0, start), end):
164
+ if list(haystack[i : i + len(needle)]) == list(needle):
165
+ return i
166
+ return -1
167
+
168
+
169
+ def label_patterns(enc: Any, label: str):
170
+ vals = [
171
+ f"({label})", f"{label})", f"{label}.", f"[{label}]",
172
+ f"{label}:", f"{label} -", f"{label} –",
173
+ f"Option {label}:", f"Option {label})", f"Option {label}.",
174
+ ]
175
+ out, seen = [], set()
176
+ for value in vals:
177
+ ids = tuple(enc.encode(value, allowed_special=set()))
178
+ if ids and ids not in seen:
179
+ seen.add(ids)
180
+ out.append(list(ids))
181
+ return out
182
+
183
+
184
+ def find_option_spans(token_ids: Sequence[int], enc: Any, options: Sequence[str]):
185
+ if len(options) < 2:
186
+ return None
187
+
188
+ try:
189
+ import re
190
+ tok_bytes = [enc.decode_single_token_bytes(t) for t in token_ids]
191
+ prompt_bytes = b"".join(tok_bytes)
192
+ byte_to_tok = []
193
+ for tok_idx, b in enumerate(tok_bytes):
194
+ byte_to_tok.extend([tok_idx] * len(b))
195
+
196
+ char_cursor = 0
197
+ exact_spans = []
198
+ span_ok = True
199
+ for opt in options:
200
+ clean_opt = opt.strip()
201
+ opt_bytes = clean_opt.encode("utf-8")
202
+ pos = prompt_bytes.find(opt_bytes, char_cursor)
203
+ if pos < 0:
204
+ unlabeled = re.sub(r"^[A-Za-z0-9\(\)\.\:\-\s]+", "", clean_opt).strip()
205
+ if len(unlabeled) >= 3:
206
+ pos = prompt_bytes.find(unlabeled.encode("utf-8"), char_cursor)
207
+
208
+ if pos >= 0 and (pos + len(opt_bytes)) <= len(byte_to_tok):
209
+ s_tok = byte_to_tok[pos]
210
+ e_tok = byte_to_tok[pos + len(opt_bytes) - 1]
211
+ exact_spans.append((s_tok, e_tok))
212
+ char_cursor = pos + len(opt_bytes)
213
+ else:
214
+ span_ok = False
215
+ break
216
+
217
+ if span_ok and len(exact_spans) == len(options):
218
+ for k in range(1, len(exact_spans)):
219
+ if exact_spans[k][0] < exact_spans[k - 1][0]:
220
+ span_ok = False
221
+ break
222
+ if span_ok:
223
+ return exact_spans
224
+ except Exception:
225
+ pass
226
+
227
+ positions = []
228
+ cursor = 0
229
+ for idx in range(len(options)):
230
+ lbl = option_label(idx)
231
+ best_pos = -1
232
+ for pat in label_patterns(enc, lbl):
233
+ p = find_subsequence(token_ids, pat, start=cursor)
234
+ if p >= 0 and (best_pos < 0 or p < best_pos):
235
+ best_pos = p
236
+ if best_pos < 0:
237
+ return None
238
+ positions.append(best_pos)
239
+ cursor = best_pos + 1
240
+ return [(p, p) for p in positions]
241
+
242
+
243
+ def format_s1mb_prompt_and_options(
244
+ case: dict,
245
+ target_decision_id: Optional[str] = None,
246
+ cfg_name: Optional[str] = None,
247
+ task_type: Optional[str] = None,
248
+ decision_obj: Optional[dict] = None,
249
+ ):
250
+ """
251
+ Nexus System 1 Native S1MB Adapter:
252
+ Translates standardized S1MB inputs into Nexus's exact trained prompt format,
253
+ resolving native domain embeddings, workflow titles, and typed candidate options.
254
+ """
255
+ state_raw = case["input"].get("state_json") or case["input"].get("state", {})
256
+ if isinstance(state_raw, str):
257
+ try:
258
+ state_obj = json.loads(state_raw)
259
+ except Exception:
260
+ state_obj = state_raw
261
+ else:
262
+ state_obj = state_raw
263
+
264
+ # Compact JSON representation matching Nexus preflight formatting
265
+ if isinstance(state_obj, (dict, list)):
266
+ state_compact = json.dumps(state_obj, separators=(',', ':'), ensure_ascii=False)
267
+ else:
268
+ state_compact = str(state_obj).strip()
269
+
270
+ # 1. Dynamic Domain & Workflow Resolution
271
+ cfg_lower = str(cfg_name or "").strip().lower()
272
+ wf_title = "Enterprise Workflow"
273
+ dom_name = "typed_agent_trace_observability"
274
+
275
+ explicit_dom = (
276
+ case.get("domain")
277
+ or case.get("workflow")
278
+ or (case.get("input", {}).get("domain") if isinstance(case.get("input"), dict) else None)
279
+ or (case.get("input", {}).get("workflow") if isinstance(case.get("input"), dict) else None)
280
+ )
281
+ if explicit_dom:
282
+ dom_name = str(explicit_dom).strip().lower()
283
+ dom_idx = parse_domain_id(dom_name)
284
+ if "agent" in dom_name:
285
+ wf_title = "Agent Trace Observability"
286
+ elif "security" in dom_name or "alert" in dom_name:
287
+ wf_title = "Security Incidents"
288
+ elif "invoice" in dom_name or "delivery" in dom_name:
289
+ wf_title = "Invoice Processing"
290
+ elif "customer" in dom_name or "account" in dom_name:
291
+ wf_title = "Customer Service"
292
+ elif isinstance(state_obj, dict):
293
+ if "agent" in state_obj:
294
+ wf_title = "Agent Trace Observability"
295
+ dom_name = "typed_agent_trace_observability"
296
+ dom_idx = 0
297
+ elif "alert" in state_obj:
298
+ wf_title = "Security Incidents"
299
+ dom_name = "typed_security_incidents"
300
+ dom_idx = 3
301
+ elif "delivery" in state_obj or "invoice" in state_obj:
302
+ wf_title = "Invoice Processing"
303
+ dom_name = "typed_invoice_processing"
304
+ dom_idx = 2
305
+ elif "account" in state_obj or "customer" in state_obj:
306
+ wf_title = "Customer Service"
307
+ dom_name = "typed_customer_service"
308
+ dom_idx = 1
309
+ elif "arc" in cfg_lower or "science" in cfg_lower:
310
+ wf_title = "STEM Science"
311
+ dom_name = "stem_science"
312
+ dom_idx = 7
313
+ elif "aegis" in cfg_lower:
314
+ wf_title = "AI Safety Guardrails"
315
+ dom_name = "ai_safety_guardrails"
316
+ dom_idx = 10
317
+ elif "patent" in cfg_lower:
318
+ wf_title = "Patent Technical Analysis"
319
+ dom_name = "patent_technical_analysis"
320
+ dom_idx = 11
321
+ elif "math" in cfg_lower:
322
+ wf_title = "STEM Mathematics"
323
+ dom_name = "stem_mathematics"
324
+ dom_idx = 4
325
+ elif "code" in cfg_lower:
326
+ wf_title = "Code Defect & Security"
327
+ dom_name = "code_defect_security"
328
+ dom_idx = 8
329
+ else:
330
+ dom_name = "typed_agent_trace_observability"
331
+ dom_idx = 0
332
+ else:
333
+ if "arc" in cfg_lower or "science" in cfg_lower:
334
+ wf_title = "STEM Science"
335
+ dom_name = "stem_science"
336
+ dom_idx = 7
337
+ elif "aegis" in cfg_lower:
338
+ wf_title = "AI Safety Guardrails"
339
+ dom_name = "ai_safety_guardrails"
340
+ dom_idx = 10
341
+ elif "patent" in cfg_lower:
342
+ wf_title = "Patent Technical Analysis"
343
+ dom_name = "patent_technical_analysis"
344
+ dom_idx = 11
345
+ else:
346
+ dom_name = "typed_agent_trace_observability"
347
+ dom_idx = 0
348
+
349
+ # 2. Target Decision Extraction
350
+ decisions = case["input"].get("decisions", [])
351
+ q = None
352
+ if decision_obj is not None:
353
+ q = decision_obj
354
+ elif target_decision_id is not None:
355
+ for d in decisions:
356
+ if d.get("id") == target_decision_id:
357
+ q = d
358
+ break
359
+ # Fallback: match by task type if specific decision ID is not present in this domain
360
+ if q is None and task_type is not None:
361
+ target_t = task_type.strip().lower()
362
+ for d in decisions:
363
+ if str(d.get("type", "")).strip().lower() == target_t:
364
+ q = d
365
+ break
366
+ if q is None:
367
+ q = decisions[0] if decisions else {}
368
+
369
+ instructions = q.get("instructions")
370
+ if not instructions and q.get("instructions_json"):
371
+ try:
372
+ instructions = json.loads(q["instructions_json"])
373
+ except Exception:
374
+ instructions = str(q["instructions_json"])
375
+ if isinstance(instructions, dict):
376
+ instructions = " ".join(f"{k}: {v}" for k, v in instructions.items())
377
+ elif isinstance(instructions, list):
378
+ instructions = " ".join(str(x) for x in instructions)
379
+ else:
380
+ instructions = str(instructions or "")
381
+ instructions = instructions.strip()
382
+
383
+ system_prompt = q.get("system_prompt", "")
384
+ prefix = f"{system_prompt}\n\n" if system_prompt else ""
385
+
386
+ q_type = str(q.get("type", "choice")).strip().lower()
387
+ criteria = q.get("options") or q.get("criteria", [])
388
+ options_text = []
389
+ option_ids = []
390
+ option_values = []
391
+
392
+ # 3. Native Task & Option Formatting (100% Alignment with Specialist Preflight)
393
+ prim_idx = parse_primitive_id(q_type)
394
+
395
+ if q_type == "choice":
396
+ sorted_criteria = sorted(criteria, key=lambda opt: str(opt.get("id", "")).lower())
397
+ for opt in sorted_criteria:
398
+ opt_id = opt.get("id", "")
399
+ option_ids.append(opt_id)
400
+ desc = opt.get("description")
401
+ if not desc and opt.get("description_json"):
402
+ try:
403
+ desc = json.loads(opt["description_json"])
404
+ except Exception:
405
+ desc = str(opt["description_json"])
406
+ desc_str = str(desc or "").strip()
407
+ if desc_str:
408
+ if (
409
+ desc_str.lower().startswith(str(opt_id).lower() + ":")
410
+ or desc_str.lower().startswith(str(opt_id).lower() + ")")
411
+ or str(opt_id).isdigit()
412
+ ):
413
+ options_text.append(desc_str)
414
+ else:
415
+ options_text.append(f"{opt_id}: {desc_str}")
416
+ else:
417
+ options_text.append(str(opt_id))
418
+ option_values.append(None)
419
+
420
+ rendered = [f"({option_label(i)}) {t}" for i, t in enumerate(options_text)]
421
+ body = "\n".join(rendered)
422
+ prompt = (
423
+ f"{prefix}Workflow: {wf_title}\n"
424
+ f"Task State: {state_compact}\n\n"
425
+ f"Task: {instructions}\n"
426
+ f"Options:\n{body}\n\n"
427
+ f"Analyze the state and select the correct option.\nAnswer:"
428
+ )
429
+
430
+ elif q_type == "noul":
431
+ # Canonicalize order: False at index 0, True at index 1 (matching 100% of training data)
432
+ def _noul_sort(opt):
433
+ oid = str(opt.get("id", "")).strip().lower()
434
+ return 0 if oid in ("false", "0", "no") else 1
435
+ sorted_criteria = sorted(criteria, key=_noul_sort)
436
+
437
+ q_id_lower = str(q.get("id", "")).strip().lower()
438
+ if q_id_lower in ("duplicate", "credential_compromise"):
439
+ options_text = ["False (No)", "True (Yes)"]
440
+ option_ids = ["false", "true"]
441
+ option_values = [None, None]
442
+ else:
443
+ for opt in sorted_criteria:
444
+ opt_id = str(opt.get("id", "")).strip().lower()
445
+ option_ids.append(opt.get("id", ""))
446
+ desc = opt.get("description")
447
+ if not desc and opt.get("description_json"):
448
+ try:
449
+ desc = json.loads(opt["description_json"])
450
+ except Exception:
451
+ desc = str(opt["description_json"])
452
+ desc_str = str(desc or "").strip()
453
+ if not desc_str or "condition in the question" in desc_str.lower():
454
+ if opt_id in ("false", "0", "no"):
455
+ options_text.append("False (No)")
456
+ else:
457
+ options_text.append("True (Yes)")
458
+ else:
459
+ if opt_id in ("false", "0", "no"):
460
+ options_text.append(f"False: {desc_str}" if not desc_str.lower().startswith("false:") else desc_str)
461
+ else:
462
+ options_text.append(f"True: {desc_str}" if not desc_str.lower().startswith("true:") else desc_str)
463
+ option_values.append(None)
464
+
465
+ rendered = [f"({option_label(i)}) {t}" for i, t in enumerate(options_text)]
466
+ body = "\n".join(rendered)
467
+ prompt = (
468
+ f"{prefix}Workflow: {wf_title}\n"
469
+ f"Task State: {state_compact}\n\n"
470
+ f"Proposition: {instructions}\n"
471
+ f"Options:\n{body}\n\n"
472
+ f"Analyze the state and verify if the proposition holds.\nAnswer:"
473
+ )
474
+
475
+ elif q_type == "score":
476
+ # Sort by numeric level (0, 1, 2, ...)
477
+ def _score_sort(opt):
478
+ v = opt.get("value")
479
+ if v is not None:
480
+ try:
481
+ return float(v)
482
+ except Exception:
483
+ pass
484
+ try:
485
+ return float(opt.get("id", "0"))
486
+ except Exception:
487
+ return 0.0
488
+ sorted_criteria = sorted(criteria, key=_score_sort)
489
+ for idx, opt in enumerate(sorted_criteria):
490
+ opt_id = opt.get("id", str(idx))
491
+ option_ids.append(opt_id)
492
+ val = opt.get("value")
493
+ option_values.append(float(val) if val is not None else float(idx))
494
+ desc = opt.get("description")
495
+ if not desc and opt.get("description_json"):
496
+ try:
497
+ desc = json.loads(opt["description_json"])
498
+ except Exception:
499
+ desc = str(opt["description_json"])
500
+ desc_str = str(desc or "").strip()
501
+ if desc_str.lower().startswith("level"):
502
+ options_text.append(desc_str)
503
+ else:
504
+ options_text.append(f"Level {opt_id}: {desc_str}")
505
+
506
+ rendered = [f"({option_label(i)}) {t}" for i, t in enumerate(options_text)]
507
+ body = "\n".join(rendered)
508
+ prompt = (
509
+ f"{prefix}Workflow: {wf_title}\n"
510
+ f"Task State: {state_compact}\n\n"
511
+ f"Assessment: {instructions}\n"
512
+ f"Options:\n{body}\n\n"
513
+ f"Analyze the state and select the correct severity level.\nAnswer:"
514
+ )
515
+
516
+ else:
517
+ rendered = [f"({option_label(i)}) {t}" for i, t in enumerate(options_text)]
518
+ body = "\n".join(rendered)
519
+ prompt = f"{prefix}Workflow: {wf_title}\nTask State: {state_compact}\n\nTask: {instructions}\nOptions:\n{body}\n\nAnswer:"
520
+
521
+ return prompt, options_text, option_ids, option_values, q["id"], q_type, dom_idx, dom_name, prim_idx
522
+
523
+
524
+ # ---------------------------------------------------------------------------
525
+ # Official S1MB Mathematical Metric Calculation
526
+ # ---------------------------------------------------------------------------
527
+
528
+ def calculate_s1mb_metrics(
529
+ task: str,
530
+ predictions: List[Dict[str, float]],
531
+ target_distributions: List[Dict[str, float]],
532
+ option_ids_list: List[List[str]],
533
+ option_values_list: List[List[Optional[float]]],
534
+ threshold: float = 0.50,
535
+ ) -> Dict[str, float]:
536
+ n = len(predictions)
537
+ if n == 0:
538
+ return {}
539
+
540
+ out: Dict[str, float] = {}
541
+
542
+ if task == "choice":
543
+ # 1. Top-1 Raw Accuracy & Target Mass at Prediction
544
+ correct = []
545
+ accuracies = []
546
+ for p, t, ids in zip(predictions, target_distributions, option_ids_list):
547
+ chosen = max(ids, key=lambda opt_id: p.get(opt_id, 0.0))
548
+ gold = max(ids, key=lambda opt_id: t.get(opt_id, 0.0))
549
+ correct.append(1.0 if chosen == gold else 0.0)
550
+ accuracies.append(t.get(chosen, 0.0))
551
+ out["top1_accuracy"] = statistics.mean(correct)
552
+ acc = statistics.mean(accuracies)
553
+ out["target_mass_at_prediction"] = acc
554
+
555
+ # 2. Trivial baselines
556
+ uniform = statistics.mean([1.0 / len(ids) for ids in option_ids_list])
557
+ out["uniform_accuracy_baseline"] = uniform
558
+
559
+ all_unique_ids = set().union(*option_ids_list)
560
+ fixed_id_baseline = max(
561
+ statistics.mean([t.get(k, 1.0 / len(ids)) for t, ids in zip(target_distributions, option_ids_list)])
562
+ for k in all_unique_ids
563
+ )
564
+
565
+ max_k = max(len(ids) for ids in option_ids_list)
566
+ fixed_pos_baseline = max(
567
+ statistics.mean([
568
+ t.get(ids[pos], 1.0 / len(ids)) if pos < len(ids) else 1.0 / len(ids)
569
+ for t, ids in zip(target_distributions, option_ids_list)
570
+ ])
571
+ for pos in range(max_k)
572
+ )
573
+
574
+ baseline = max(uniform, fixed_id_baseline, fixed_pos_baseline)
575
+ out["fixed_answer_accuracy_baseline"] = baseline
576
+
577
+ if baseline < 1.0 - EPSILON:
578
+ skill = (acc - baseline) / (1.0 - baseline)
579
+ else:
580
+ skill = 0.0
581
+ out["baseline_adjusted_skill"] = skill
582
+ out["baseline_adjusted_score"] = max(0.0, min(1.0, skill))
583
+
584
+ elif task == "noul":
585
+ # 1. Binary Brier Score
586
+ # Resolve "true"/"false" probability from either key convention:
587
+ # HuggingFace targets use "true" / "false"
588
+ # Local test targets use "1" / "0" (positional index strings)
589
+ def _noul_true(d: Dict[str, float]) -> float:
590
+ if "true" in d:
591
+ return d["true"]
592
+ if "1" in d:
593
+ return d["1"]
594
+ return 0.0
595
+
596
+ def _noul_false(d: Dict[str, float]) -> float:
597
+ if "false" in d:
598
+ return d["false"]
599
+ if "0" in d:
600
+ return d["0"]
601
+ return 0.0
602
+
603
+ briers = []
604
+ for p, t in zip(predictions, target_distributions):
605
+ p_true = _noul_true(p)
606
+ t_true = _noul_true(t)
607
+ briers.append((p_true - t_true) ** 2)
608
+ mean_brier = statistics.mean(briers)
609
+ out["binary_brier"] = mean_brier
610
+
611
+ # 2. Balanced Accuracy & Prevalence
612
+ prevalence = statistics.mean([_noul_true(t) for t in target_distributions])
613
+ out["positive_prevalence"] = prevalence
614
+
615
+ tp = sum(_noul_true(t) for p, t in zip(predictions, target_distributions) if _noul_true(p) >= threshold)
616
+ fp = sum(_noul_false(t) for p, t in zip(predictions, target_distributions) if _noul_true(p) >= threshold)
617
+ fn = sum(_noul_true(t) for p, t in zip(predictions, target_distributions) if _noul_true(p) < threshold)
618
+ tn = sum(_noul_false(t) for p, t in zip(predictions, target_distributions) if _noul_true(p) < threshold)
619
+
620
+ recall = tp / (tp + fn) if (tp + fn) > EPSILON else 0.0
621
+ specificity = tn / (tn + fp) if (tn + fp) > EPSILON else 0.0
622
+ balanced_acc = (recall + specificity) / 2.0
623
+ out["accuracy"] = (tp + tn) / n
624
+ out["top1_accuracy"] = out["accuracy"]
625
+ out["balanced_accuracy"] = balanced_acc
626
+
627
+ skill = 2.0 * balanced_acc - 1.0
628
+ out["baseline_adjusted_skill"] = skill
629
+ out["baseline_adjusted_score"] = max(0.0, min(1.0, skill))
630
+
631
+ elif task == "score":
632
+ # 1. Normalized Expected Score MAE
633
+ errors = []
634
+ target_expected_vals = []
635
+ for p, t, ids, vals in zip(predictions, target_distributions, option_ids_list, option_values_list):
636
+ val_map = {opt_id: (float(v) if v is not None else float(idx)) for idx, (opt_id, v) in enumerate(zip(ids, vals))}
637
+ low, high = min(val_map.values()), max(val_map.values())
638
+ scale_range = max(high - low, EPSILON)
639
+
640
+ pred_val = sum(val_map[k] * p.get(k, 0.0) for k in ids)
641
+ target_val = sum(val_map[k] * t.get(k, 0.0) for k in ids)
642
+ target_norm = (target_val - low) / scale_range
643
+ target_expected_vals.append(target_norm)
644
+
645
+ err = abs(pred_val - target_val) / scale_range
646
+ errors.append(err)
647
+
648
+ exact = []
649
+ within_1 = []
650
+ for p, t, ids, vals in zip(predictions, target_distributions, option_ids_list, option_values_list):
651
+ val_map = {opt_id: (float(v) if v is not None else float(idx)) for idx, (opt_id, v) in enumerate(zip(ids, vals))}
652
+ pred_val = sum(val_map[k] * p.get(k, 0.0) for k in ids)
653
+ target_val = sum(val_map[k] * t.get(k, 0.0) for k in ids)
654
+ exact.append(1.0 if round(pred_val) == round(target_val) else 0.0)
655
+ within_1.append(1.0 if abs(pred_val - target_val) <= 1.0 else 0.0)
656
+ out["top1_accuracy"] = statistics.mean(exact)
657
+ out["within_1_level_accuracy"] = statistics.mean(within_1)
658
+ mae = statistics.mean(errors)
659
+ rmse = math.sqrt(statistics.mean([e ** 2 for e in errors]))
660
+ out["normalized_expected_score_mae"] = mae
661
+ out["normalized_score_rmse"] = rmse
662
+
663
+ # 2. Constant Median Baseline
664
+ constant_pred = statistics.median(target_expected_vals)
665
+ baseline_mae = statistics.mean([abs(t - constant_pred) for t in target_expected_vals])
666
+ out["constant_mae_baseline"] = baseline_mae
667
+
668
+ if baseline_mae > EPSILON:
669
+ skill = 1.0 - (mae / baseline_mae)
670
+ else:
671
+ skill = 0.0
672
+ out["baseline_adjusted_skill"] = skill
673
+ out["baseline_adjusted_score"] = max(0.0, min(1.0, skill))
674
+
675
+ return out
676
+
677
+
678
+ # ---------------------------------------------------------------------------
679
+ # Checkpoint & Memory Loader
680
+ # ---------------------------------------------------------------------------
681
+
682
+ def get_calibration_parameters(
683
+ meta: Optional[Dict[str, Any]],
684
+ domain: str,
685
+ primitive: str,
686
+ k: int,
687
+ apply_bias: bool = False,
688
+ ) -> Tuple[float, Optional[torch.Tensor]]:
689
+ """
690
+ Pure Laya Temperature & Position Bias Extraction:
691
+ Retrieves scalar T and position bias vector matching agent.py / common.py.
692
+ """
693
+ if not meta:
694
+ return 1.0, None
695
+
696
+ prim_lower = primitive.lower()
697
+ size = "2" if k <= 2 else "3-5" if k <= 5 else "6-10" if k <= 10 else "11+"
698
+ bucket_standard = f"{prim_lower}:{size}"
699
+ bucket_exact = f"{prim_lower}:{k}"
700
+ bucket_pipe = f"{prim_lower}|{k}"
701
+
702
+ # 1. Temperature extraction
703
+ T = 1.0
704
+ tbo = meta.get("temperature_by_options", {})
705
+ if bucket_exact in tbo:
706
+ T = float(tbo[bucket_exact])
707
+ elif bucket_standard in tbo:
708
+ T = float(tbo[bucket_standard])
709
+ elif bucket_pipe in meta.get("temperatures", {}):
710
+ T = float(meta["temperatures"][bucket_pipe])
711
+ elif "temperature_by_primitive" in meta and prim_lower in meta["temperature_by_primitive"]:
712
+ T = float(meta["temperature_by_primitive"][prim_lower])
713
+ elif "temperature" in meta and isinstance(meta["temperature"], (list, tuple)):
714
+ p_map = {"choice": 0, "score": 1, "noul": 2}
715
+ p_idx = p_map.get(prim_lower, 0)
716
+ if p_idx < len(meta["temperature"]):
717
+ T = float(meta["temperature"][p_idx])
718
+ elif "global_temperature" in meta:
719
+ T = float(meta["global_temperature"])
720
+
721
+ T = max(0.1, min(10.0, T))
722
+
723
+ # 2. Additive position bias vector extraction (if requested)
724
+ bias_t = None
725
+ if apply_bias:
726
+ raw_b = None
727
+ dom_cal = meta.get("domain_calibrations", {}).get(domain, {}).get(prim_lower, {}).get(str(k), {})
728
+ if dom_cal and "bias" in dom_cal and dom_cal["bias"] is not None:
729
+ raw_b = dom_cal["bias"]
730
+ if raw_b is None:
731
+ pb = meta.get("position_biases", {})
732
+ for key in (bucket_exact, bucket_pipe, bucket_standard):
733
+ if key in pb and pb[key] is not None:
734
+ raw_b = pb[key]
735
+ break
736
+ if raw_b is None:
737
+ bc = meta.get("bucket_calibrations", {}).get(bucket_pipe, {})
738
+ if "bias" in bc and bc["bias"] is not None:
739
+ raw_b = bc["bias"]
740
+
741
+ if raw_b and len(raw_b) == k and any(abs(x) > 1e-5 for x in raw_b):
742
+ bias_t = torch.tensor(raw_b, dtype=torch.float32)
743
+
744
+ return T, bias_t
745
+
746
+
747
+ def clean_state_dict(raw: Dict[str, Any]):
748
+ out = {}
749
+ for k, v in raw.items():
750
+ k_clean = k
751
+ for pfx in ("_orig_mod.", "module.", "backbone."):
752
+ if k_clean.startswith(pfx):
753
+ k_clean = k_clean[len(pfx):]
754
+ out[k_clean] = v
755
+ return out
756
+
757
+
758
+ def restore_memory(ckpt: Dict[str, Any], model: CortexV7, device: torch.device):
759
+ raw = ckpt.get("persistent_memory_state")
760
+ if raw is None and "training_state" in ckpt:
761
+ raw = ckpt["training_state"].get("persistent_memory_state")
762
+ if raw is None or not isinstance(raw, (list, tuple)) or len(raw) != len(model.memory):
763
+ return [mem.init_memory(1, device).detach().clone() for mem in model.memory]
764
+ out = []
765
+ for mem_mod, state in zip(model.memory, raw):
766
+ dtype = mem_mod.memory_init.dtype if hasattr(mem_mod, "memory_init") else next(mem_mod.parameters()).dtype
767
+ out.append(state.detach().to(device=device, dtype=dtype).clone())
768
+ return out
769
+
770
+
771
+ def load_nexus_model(ckpt_path: Path, device: torch.device, dtype: torch.dtype):
772
+ print(f"Loading Nexus System 1 checkpoint from {ckpt_path}...")
773
+ ckpt = torch.load(str(ckpt_path), map_location="cpu", weights_only=False)
774
+ cfg = ckpt.get("base_cfg", ckpt.get("cfg", {}))
775
+
776
+ use_flash = False
777
+ if torch.cuda.is_available():
778
+ try:
779
+ import flash_attn # noqa: F401
780
+ cap = torch.cuda.get_device_capability()
781
+ use_flash = cap[0] >= 8
782
+ except Exception:
783
+ use_flash = False
784
+
785
+ raw_state = ckpt.get("model", ckpt.get("model_state_dict", ckpt))
786
+ state = clean_state_dict(raw_state)
787
+ decision_layers = ckpt.get("config", {}).get("decision_layers")
788
+ if decision_layers is None:
789
+ layer_keys = [k for k in state.keys() if "system1_head.transformer.layers." in k or "comparator_layers." in k]
790
+ if layer_keys:
791
+ layer_indices = []
792
+ for k in layer_keys:
793
+ for token in ["system1_head.transformer.layers.", "comparator_layers."]:
794
+ if token in k:
795
+ try:
796
+ layer_indices.append(int(k.split(token)[1].split(".")[0]))
797
+ except Exception:
798
+ pass
799
+ decision_layers = max(layer_indices) + 1 if layer_indices else 1
800
+ else:
801
+ decision_layers = 1
802
+ print(f" [DECISION HEAD] Dynamic decision_layers={decision_layers}")
803
+
804
+ model = CortexV7(
805
+ vocab_size=int(cfg.get("vocab_size", 100277)),
806
+ dim=int(cfg.get("dim", 1280)),
807
+ heads=int(cfg.get("heads", 16)),
808
+ kv_heads=int(cfg.get("kv_heads", 4)),
809
+ num_layers=int(cfg.get("num_layers", 20)),
810
+ memory_slots=int(cfg.get("memory_slots", 128)),
811
+ mtp_depths=int(cfg.get("mtp_depths", 1)),
812
+ decision_layers=decision_layers,
813
+ use_flash=use_flash,
814
+ )
815
+
816
+ model_params = dict(model.named_parameters())
817
+ compatible_state = {}
818
+ for k, v in state.items():
819
+ if k in model_params and model_params[k].shape != v.shape:
820
+ print(f" [WARN] Skipping parameter {k} due to shape change: {v.shape} -> {model_params[k].shape} (fresh init)")
821
+ continue
822
+ compatible_state[k] = v
823
+
824
+ model.load_state_dict(compatible_state, strict=False)
825
+ model.use_system1_head = True
826
+ model = model.to(device=device, dtype=dtype).eval()
827
+
828
+ memory = restore_memory(ckpt, model, device)
829
+ total_params = sum(p.numel() for p in model.parameters())
830
+ print(f"Model loaded successfully | Total parameters: {total_params:,} ({total_params/1e9:.3f}B)")
831
+ return model, memory, total_params
832
+
833
+
834
+ # ---------------------------------------------------------------------------
835
+ # S1MB Official Execution Engine
836
+ # ---------------------------------------------------------------------------
837
+
838
+ @torch.no_grad()
839
+ def evaluate_benchmark(
840
+ model: CortexV7,
841
+ memory_base: List[torch.Tensor],
842
+ benchmark_meta: Dict[str, Any],
843
+ enc: Any,
844
+ device: torch.device,
845
+ dtype: torch.dtype,
846
+ limit: Optional[int] = None,
847
+ memory_mode: str = "dynamic",
848
+ seq_len: int = 1024,
849
+ calibration: Optional[Dict[str, Any]] = None,
850
+ threshold: float = 0.50,
851
+ apply_bias: bool = False,
852
+ ) -> Dict[str, Any]:
853
+ b_id = benchmark_meta["id"]
854
+ cfg_name = benchmark_meta["config"]
855
+ task = benchmark_meta["task"]
856
+ target_d_id = benchmark_meta.get("decision_id")
857
+
858
+ print(f"\nEvaluating S1MB Benchmark: {b_id} (Config: {cfg_name}, Task: {task.upper()})")
859
+
860
+ ds = load_dataset("hotchpotch/S1MB-english-v1", cfg_name, split="test", streaming=False)
861
+ cases = list(ds)
862
+ if limit is not None and limit < len(cases):
863
+ cases = cases[:limit]
864
+
865
+ print(f" Loaded {len(cases)} test cases from hotchpotch/S1MB-english-v1 ({cfg_name})")
866
+
867
+ if memory_mode == "frozen":
868
+ memory_state = [m.clone() for m in memory_base]
869
+ elif memory_mode == "none":
870
+ memory_state = None
871
+ else:
872
+ memory_state = [m.clone() for m in memory_base]
873
+
874
+ all_predictions: List[Dict[str, float]] = []
875
+ all_targets: List[Dict[str, float]] = []
876
+ all_option_ids: List[List[str]] = []
877
+ all_option_values: List[List[Optional[float]]] = []
878
+ saved_predictions: List[Dict[str, Any]] = []
879
+
880
+ t0 = time.perf_counter()
881
+
882
+ for idx, case in enumerate(cases):
883
+ case_id = case.get("case_id", f"case_{idx}")
884
+
885
+ matching_decisions = []
886
+ for d in case["input"].get("decisions", []):
887
+ d_type = str(d.get("type", "")).strip().lower()
888
+ if target_d_id is not None:
889
+ if d.get("id") == target_d_id:
890
+ matching_decisions.append(d)
891
+ elif d_type == task:
892
+ matching_decisions.append(d)
893
+
894
+ if not matching_decisions and case["input"].get("decisions"):
895
+ matching_decisions = [case["input"]["decisions"][0]]
896
+
897
+ for q in matching_decisions:
898
+ prompt, options_text, option_ids, option_values, q_id, q_type, dom_idx, dom_name, prim_idx = format_s1mb_prompt_and_options(
899
+ case, decision_obj=q, cfg_name=cfg_name, task_type=task
900
+ )
901
+
902
+ tokens = enc.encode(prompt, allowed_special=set())
903
+ spans = find_option_spans(tokens, enc, options_text)
904
+ if spans is None:
905
+ last = max(0, len(tokens) - 1)
906
+ spans = [(max(0, last - (len(options_text) - 1 - i)), max(0, last - (len(options_text) - 1 - i))) for i in range(len(options_text))]
907
+
908
+ # Truncate left if sequence exceeds seq_len
909
+ if len(tokens) > seq_len:
910
+ excess = len(tokens) - seq_len
911
+ tokens = tokens[excess:]
912
+ spans = [(max(0, min(seq_len - 1, s - excess)), max(0, min(seq_len - 1, e - excess))) for s, e in spans]
913
+
914
+ # Targets extraction
915
+ target_probs_dict = {}
916
+ target_records = case.get("targets", [])
917
+ matched_target = None
918
+ for tr in target_records:
919
+ if tr.get("decision_id") == q_id:
920
+ matched_target = tr
921
+ break
922
+ if matched_target is None and target_records:
923
+ matched_target = target_records[0]
924
+
925
+ if matched_target:
926
+ t_ids = matched_target.get("ids", [])
927
+ t_probs = matched_target.get("probabilities", [])
928
+ target_probs_dict = dict(zip(t_ids, t_probs))
929
+ else:
930
+ target_probs_dict = {opt_id: (1.0 if i == 0 else 0.0) for i, opt_id in enumerate(option_ids)}
931
+
932
+ # Forward pass with dynamically resolved domain and primitive conditioning
933
+ inp_tensor = torch.tensor([tokens], device=device, dtype=torch.long)
934
+ pos_tensor = torch.tensor([spans], device=device, dtype=torch.long)
935
+
936
+ mem_input = memory_state if memory_mode != "none" else None
937
+ if memory_mode == "frozen":
938
+ mem_input = [m.clone() for m in memory_base]
939
+
940
+ task_name = q_id.split('_')[-1] if '_' in q_id else q_id
941
+
942
+ with torch.autocast(device_type="cuda", dtype=dtype, enabled=(device.type == "cuda")):
943
+ logits, _, _, new_mem = model(
944
+ inp_tensor,
945
+ candidate_positions=pos_tensor,
946
+ candidate_mask=None,
947
+ last_token_only=True,
948
+ memory_state=mem_input,
949
+ primitive_id=prim_idx,
950
+ domain_id=dom_idx,
951
+ disable_memory=(memory_mode == "none"),
952
+ )
953
+
954
+ if memory_mode == "dynamic" and new_mem is not None:
955
+ memory_state = [m.detach().clone() for m in new_mem]
956
+
957
+ logits_k = logits[0, 0].float()
958
+
959
+ # Domain-Aware Calibration (Temperature + Affine Bias)
960
+ if calibration:
961
+ T, bias_t = get_calibration_parameters(calibration, dom_name, task, len(option_ids), apply_bias=apply_bias)
962
+ if bias_t is not None:
963
+ logits_k = (logits_k / T) + bias_t.to(device=logits_k.device, dtype=logits_k.dtype)
964
+ else:
965
+ logits_k = logits_k / T
966
+
967
+ probs_k = F.softmax(logits_k, dim=-1).cpu().tolist()
968
+
969
+ pred_probs_dict = {}
970
+ for opt_id, p_val in zip(option_ids, probs_k):
971
+ pred_probs_dict[opt_id] = float(p_val)
972
+
973
+ # Normalize to exact sum 1.0
974
+ total_p = sum(pred_probs_dict.values())
975
+ if total_p > 0:
976
+ pred_probs_dict = {k: v / total_p for k, v in pred_probs_dict.items()}
977
+
978
+ all_predictions.append(pred_probs_dict)
979
+ all_targets.append(target_probs_dict)
980
+ all_option_ids.append(option_ids)
981
+ all_option_values.append(option_values)
982
+
983
+ saved_predictions.append({
984
+ "case_id": case_id,
985
+ "question_id": q_id,
986
+ "probabilities": pred_probs_dict,
987
+ "error": None,
988
+ "abstention": None,
989
+ })
990
+
991
+ if (idx + 1) % 25 == 0 or (idx + 1) == len(cases):
992
+ print(f" Processed {idx + 1}/{len(cases)} cases ({len(all_predictions)} decisions)...", flush=True)
993
+
994
+ elapsed = time.perf_counter() - t0
995
+ cal_thresh = threshold
996
+ if task == "noul" and calibration:
997
+ cal_thresh = calibration.get("decision_thresholds", {}).get("noul_threshold", threshold)
998
+ metrics = calculate_s1mb_metrics(
999
+ task=task,
1000
+ predictions=all_predictions,
1001
+ target_distributions=all_targets,
1002
+ option_ids_list=all_option_ids,
1003
+ option_values_list=all_option_values,
1004
+ threshold=cal_thresh,
1005
+ )
1006
+
1007
+ primary_key = {
1008
+ "choice": "target_mass_at_prediction",
1009
+ "noul": "binary_brier",
1010
+ "score": "normalized_expected_score_mae",
1011
+ }[task]
1012
+
1013
+ print(f" --> Top-1 Raw Accuracy: {metrics.get('top1_accuracy', 0.0)*100:.2f}%")
1014
+ print(f" --> Primary Metric ({primary_key}): {metrics.get(primary_key, 0.0):.4f}")
1015
+ print(f" --> Baseline Adjusted Score: {metrics.get('baseline_adjusted_score', 0.0)*100:.2f}% (Elapsed: {elapsed:.1f}s)")
1016
+
1017
+ return {
1018
+ "benchmark_id": b_id,
1019
+ "name": benchmark_meta.get("name", b_id),
1020
+ "task": task,
1021
+ "config": cfg_name,
1022
+ "case_count": len(cases),
1023
+ "decision_count": len(all_predictions),
1024
+ "top1_accuracy": metrics.get("top1_accuracy", 0.0),
1025
+ "primary_metric_name": primary_key,
1026
+ "primary_metric_value": metrics.get(primary_key),
1027
+ "baseline_adjusted_score": metrics.get("baseline_adjusted_score", 0.0),
1028
+ "all_metrics": metrics,
1029
+ "elapsed_seconds": elapsed,
1030
+ "predictions": saved_predictions,
1031
+ }
1032
+
1033
+
1034
+ # ---------------------------------------------------------------------------
1035
+ # Interleaved Multi-Domain Suite Evaluator (Official S1MB Parity)
1036
+ # ---------------------------------------------------------------------------
1037
+
1038
+ @torch.no_grad()
1039
+ def evaluate_typed_decisions_interleaved_suite(
1040
+ model: CortexV7,
1041
+ memory_base: List[torch.Tensor],
1042
+ enc: Any,
1043
+ device: torch.device,
1044
+ dtype: torch.dtype,
1045
+ limit: Optional[int] = None,
1046
+ memory_mode: str = "dynamic",
1047
+ seq_len: int = 1024,
1048
+ calibration: Optional[Dict[str, Any]] = None,
1049
+ threshold: float = 0.50,
1050
+ apply_bias: bool = False,
1051
+ interleave: bool = True,
1052
+ case_decay: float = 1.0,
1053
+ ) -> List[Dict[str, Any]]:
1054
+ """
1055
+ Evaluates the full S1MB Typed Decisions Suite (Choice, Noul, Score) in a single
1056
+ interleaved multi-domain pass matching the continuous training distribution.
1057
+ Prevents single-domain memory saturation, maintains unbroken persistent scratchpad state,
1058
+ and returns 3 compliant S1MB benchmark result dictionaries (Choice, Noul, Score).
1059
+ """
1060
+ print(f"\n====================================================================================================")
1061
+ print(f" NEXUS SYSTEM 1 — S1MB TYPED DECISIONS INTERLEAVED EVALUATION SUITE")
1062
+ print(f" Memory Mode: {memory_mode.upper()} | Interleave: {interleave} | Threshold: {threshold} | Apply Bias: {apply_bias}")
1063
+ print(f"====================================================================================================")
1064
+
1065
+ ds = load_dataset("hotchpotch/S1MB-english-v1", "laya__typed_decisions", split="test", streaming=False)
1066
+ cases = list(ds)
1067
+ if limit is not None and limit < len(cases):
1068
+ cases = cases[:limit]
1069
+
1070
+ print(f" Loaded {len(cases)} test cases from hotchpotch/S1MB-english-v1 (laya__typed_decisions)")
1071
+
1072
+ if interleave:
1073
+ cases_by_dom = defaultdict(list)
1074
+ for c in cases:
1075
+ s = c["input"].get("state_json") or c["input"].get("state", {})
1076
+ if isinstance(s, str):
1077
+ try:
1078
+ s = json.loads(s)
1079
+ except Exception:
1080
+ pass
1081
+ if isinstance(s, dict):
1082
+ if "agent" in s:
1083
+ dom = "agent_trace"
1084
+ elif "account" in s or "customer" in s:
1085
+ dom = "customer_service"
1086
+ elif "delivery" in s or "invoice" in s:
1087
+ dom = "invoice"
1088
+ elif "alert" in s:
1089
+ dom = "security"
1090
+ else:
1091
+ dom = "other"
1092
+ else:
1093
+ dom = "other"
1094
+ cases_by_dom[dom].append(c)
1095
+
1096
+ interleaved_cases = []
1097
+ dom_keys = sorted(cases_by_dom.keys())
1098
+ max_len = max(len(v) for v in cases_by_dom.values())
1099
+ for idx in range(max_len):
1100
+ for dk in dom_keys:
1101
+ if idx < len(cases_by_dom[dk]):
1102
+ interleaved_cases.append(cases_by_dom[dk][idx])
1103
+ eval_cases = interleaved_cases
1104
+ 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())})")
1105
+ else:
1106
+ eval_cases = cases
1107
+
1108
+ if memory_mode == "frozen":
1109
+ memory_state = [m.clone() for m in memory_base]
1110
+ elif memory_mode == "none":
1111
+ memory_state = None
1112
+ else:
1113
+ memory_state = [m.clone() for m in memory_base]
1114
+
1115
+ preds_map: Dict[Tuple[str, str], Dict[str, float]] = {}
1116
+ t0 = time.perf_counter()
1117
+
1118
+ for idx, case in enumerate(eval_cases):
1119
+ case_id = case.get("case_id", f"case_{idx}")
1120
+ if memory_mode == "dynamic" and idx > 0 and case_decay < 1.0:
1121
+ memory_state = [
1122
+ (case_decay * m + (1.0 - case_decay) * base.clone())
1123
+ for m, base in zip(memory_state, memory_base)
1124
+ ]
1125
+ decisions = case["input"].get("decisions", [])
1126
+
1127
+ for q in decisions:
1128
+ q_id = q["id"]
1129
+ task = str(q.get("type", "choice")).strip().lower()
1130
+
1131
+ prompt, options_text, option_ids, option_values, _, q_type, dom_idx, dom_name, prim_idx = format_s1mb_prompt_and_options(
1132
+ case, decision_obj=q, cfg_name="laya__typed_decisions", task_type=task
1133
+ )
1134
+
1135
+ tokens = enc.encode(prompt, allowed_special=set())
1136
+ spans = find_option_spans(tokens, enc, options_text)
1137
+ if spans is None:
1138
+ last = max(0, len(tokens) - 1)
1139
+ spans = [(max(0, last - (len(options_text) - 1 - i)), max(0, last - (len(options_text) - 1 - i))) for i in range(len(options_text))]
1140
+
1141
+ if len(tokens) > seq_len:
1142
+ excess = len(tokens) - seq_len
1143
+ tokens = tokens[excess:]
1144
+ spans = [(max(0, min(seq_len - 1, s - excess)), max(0, min(seq_len - 1, e - excess))) for s, e in spans]
1145
+
1146
+ inp_tensor = torch.tensor([tokens], device=device, dtype=torch.long)
1147
+ pos_tensor = torch.tensor([spans], device=device, dtype=torch.long)
1148
+
1149
+ mem_input = memory_state if memory_mode != "none" else None
1150
+ if memory_mode == "frozen":
1151
+ mem_input = [m.clone() for m in memory_base]
1152
+
1153
+ with torch.autocast(device_type="cuda", dtype=dtype, enabled=(device.type == "cuda")):
1154
+ logits, _, _, new_mem = model(
1155
+ inp_tensor,
1156
+ candidate_positions=pos_tensor,
1157
+ candidate_mask=None,
1158
+ last_token_only=True,
1159
+ memory_state=mem_input,
1160
+ primitive_id=prim_idx,
1161
+ domain_id=dom_idx,
1162
+ disable_memory=(memory_mode == "none"),
1163
+ )
1164
+
1165
+ if memory_mode == "dynamic" and new_mem is not None:
1166
+ memory_state = [m.detach().clone() for m in new_mem]
1167
+
1168
+ logits_k = logits[0, 0].float()
1169
+
1170
+ if calibration:
1171
+ T, bias_t = get_calibration_parameters(calibration, dom_name, task, len(option_ids), apply_bias=apply_bias)
1172
+ if bias_t is not None:
1173
+ logits_k = (logits_k / T) + bias_t.to(device=logits_k.device, dtype=logits_k.dtype)
1174
+ else:
1175
+ logits_k = logits_k / T
1176
+
1177
+ probs_k = F.softmax(logits_k, dim=-1).cpu().tolist()
1178
+ pred_dict = {opt_id: float(p) for opt_id, p in zip(option_ids, probs_k)}
1179
+ tot = sum(pred_dict.values())
1180
+ if tot > 0:
1181
+ pred_dict = {k: v / tot for k, v in pred_dict.items()}
1182
+
1183
+ preds_map[(case_id, q_id)] = pred_dict
1184
+
1185
+ if (idx + 1) % 25 == 0 or (idx + 1) == len(eval_cases):
1186
+ print(f" Processed {idx + 1}/{len(eval_cases)} cases ({len(preds_map)} decisions)...", flush=True)
1187
+
1188
+ elapsed_total = time.perf_counter() - t0
1189
+
1190
+ # Assemble canonical results for each benchmark in TYPED_DECISIONS_BENCHMARKS
1191
+ results = []
1192
+ for b_meta in TYPED_DECISIONS_BENCHMARKS:
1193
+ task = b_meta["task"]
1194
+ b_id = b_meta["id"]
1195
+
1196
+ all_predictions = []
1197
+ all_targets = []
1198
+ all_option_ids = []
1199
+ all_option_values = []
1200
+ saved_predictions = []
1201
+
1202
+ for case in cases:
1203
+ case_id = case.get("case_id")
1204
+ matching_decisions = [d for d in case["input"].get("decisions", []) if str(d.get("type", "")).strip().lower() == task]
1205
+ target_records = case.get("targets", [])
1206
+
1207
+ for q in matching_decisions:
1208
+ q_id = q["id"]
1209
+ pred = preds_map.get((case_id, q_id))
1210
+ if pred is None:
1211
+ continue
1212
+
1213
+ matched_target = None
1214
+ for tr in target_records:
1215
+ if tr.get("decision_id") == q_id:
1216
+ matched_target = tr
1217
+ break
1218
+
1219
+ _, _, option_ids, option_values, _, _, _, _, _ = format_s1mb_prompt_and_options(
1220
+ case, decision_obj=q, cfg_name="laya__typed_decisions", task_type=task
1221
+ )
1222
+
1223
+ if matched_target:
1224
+ t_ids = matched_target.get("ids", [])
1225
+ t_probs = matched_target.get("probabilities", [])
1226
+ target_dict = dict(zip(t_ids, t_probs))
1227
+ else:
1228
+ target_dict = {opt_id: (1.0 if i == 0 else 0.0) for i, opt_id in enumerate(option_ids)}
1229
+
1230
+ all_predictions.append(pred)
1231
+ all_targets.append(target_dict)
1232
+ all_option_ids.append(option_ids)
1233
+ all_option_values.append(option_values)
1234
+
1235
+ saved_predictions.append({
1236
+ "case_id": case_id,
1237
+ "question_id": q_id,
1238
+ "probabilities": pred,
1239
+ "error": None,
1240
+ "abstention": None,
1241
+ })
1242
+
1243
+ cal_thresh = threshold if task == "noul" else 0.50
1244
+ if task == "noul" and calibration:
1245
+ cal_thresh = calibration.get("decision_thresholds", {}).get("noul_threshold", threshold)
1246
+ metrics = calculate_s1mb_metrics(
1247
+ task=task,
1248
+ predictions=all_predictions,
1249
+ target_distributions=all_targets,
1250
+ option_ids_list=all_option_ids,
1251
+ option_values_list=all_option_values,
1252
+ threshold=cal_thresh,
1253
+ )
1254
+
1255
+ primary_key = {
1256
+ "choice": "target_mass_at_prediction",
1257
+ "noul": "binary_brier",
1258
+ "score": "normalized_expected_score_mae",
1259
+ }[task]
1260
+
1261
+ print(f"\nBenchmark Result: {b_id} ({task.upper()})")
1262
+ print(f" --> Decisions: {len(all_predictions)}")
1263
+ print(f" --> Top-1 Raw Accuracy: {metrics.get('top1_accuracy', 0.0)*100:.2f}%")
1264
+ print(f" --> Primary Metric ({primary_key}): {metrics.get(primary_key, 0.0):.4f}")
1265
+ print(f" --> Baseline Adjusted Score: {metrics.get('baseline_adjusted_score', 0.0)*100:.2f}%")
1266
+ if task == "noul":
1267
+ print(f" --> Balanced Accuracy: {metrics.get('balanced_accuracy', 0.0)*100:.2f}%")
1268
+
1269
+ results.append({
1270
+ "benchmark_id": b_id,
1271
+ "name": b_meta.get("name", b_id),
1272
+ "task": task,
1273
+ "config": "laya__typed_decisions",
1274
+ "case_count": len(cases),
1275
+ "decision_count": len(all_predictions),
1276
+ "top1_accuracy": metrics.get("top1_accuracy", 0.0),
1277
+ "primary_metric_name": primary_key,
1278
+ "primary_metric_value": metrics.get(primary_key),
1279
+ "baseline_adjusted_score": metrics.get("baseline_adjusted_score", 0.0),
1280
+ "all_metrics": metrics,
1281
+ "elapsed_seconds": elapsed_total,
1282
+ "predictions": saved_predictions,
1283
+ })
1284
+
1285
+ return results
1286
+
1287
+
1288
+ # ---------------------------------------------------------------------------
1289
+ # Local Benchmark Evaluation Engine (for typed_decisions_benchmark_test.jsonl)
1290
+ # ---------------------------------------------------------------------------
1291
+
1292
+ @torch.no_grad()
1293
+ def evaluate_local_test(
1294
+ model: CortexV7,
1295
+ memory_base: List[torch.Tensor],
1296
+ test_path: Path,
1297
+ enc: Any,
1298
+ device: torch.device,
1299
+ dtype: torch.dtype,
1300
+ limit: Optional[int] = None,
1301
+ memory_mode: str = "dynamic",
1302
+ seq_len: int = 1024,
1303
+ calibration: Optional[Dict[str, Any]] = None,
1304
+ threshold: float = 0.50,
1305
+ apply_bias: bool = False,
1306
+ interleave: bool = True,
1307
+ ) -> List[Dict[str, Any]]:
1308
+ print(f"\nEvaluating Local Typed Decisions Benchmark: {test_path.name}")
1309
+ records = []
1310
+ with test_path.open("r", encoding="utf-8") as f:
1311
+ for line in f:
1312
+ if line.strip():
1313
+ records.append(json.loads(line))
1314
+ if limit is not None and limit < len(records):
1315
+ records = records[:limit]
1316
+ print(f" Loaded {len(records)} test samples from {test_path.name}")
1317
+
1318
+ if interleave:
1319
+ records_by_dom = defaultdict(list)
1320
+ for r in records:
1321
+ d_name = str(r.get("domain") or r.get("workflow") or "other").strip().lower()
1322
+ records_by_dom[d_name].append(r)
1323
+ interleaved_records = []
1324
+ dom_keys = sorted(records_by_dom.keys())
1325
+ max_len = max(len(v) for v in records_by_dom.values())
1326
+ for idx in range(max_len):
1327
+ for dk in dom_keys:
1328
+ if idx < len(records_by_dom[dk]):
1329
+ interleaved_records.append(records_by_dom[dk][idx])
1330
+ eval_records = interleaved_records
1331
+ else:
1332
+ eval_records = records
1333
+
1334
+ if memory_mode == "frozen":
1335
+ memory_state = [m.clone() for m in memory_base]
1336
+ elif memory_mode == "none":
1337
+ memory_state = None
1338
+ else:
1339
+ memory_state = [m.clone() for m in memory_base]
1340
+
1341
+ preds_by_prim = defaultdict(list)
1342
+ targets_by_prim = defaultdict(list)
1343
+ opt_ids_by_prim = defaultdict(list)
1344
+ opt_vals_by_prim = defaultdict(list)
1345
+ saved_preds_by_prim = defaultdict(list)
1346
+ t0 = time.perf_counter()
1347
+
1348
+ for idx, rec in enumerate(eval_records):
1349
+ prim = str(rec.get("primitive") or rec.get("task") or "choice").strip().lower()
1350
+ prompt = rec["prompt"]
1351
+ options = rec["options"]
1352
+ k = len(options)
1353
+ opt_ids = [str(i) for i in range(k)]
1354
+
1355
+ if prim == "score":
1356
+ opt_vals = [float(i) for i in range(k)]
1357
+ else:
1358
+ opt_vals = [None] * k
1359
+
1360
+ target_probs = rec.get("target_probs")
1361
+ if not target_probs:
1362
+ t_idx = int(rec.get("target_idx", 0))
1363
+ target_probs = [1.0 if i == t_idx else 0.0 for i in range(k)]
1364
+ target_probs_dict = {str(i): float(target_probs[i]) for i in range(min(k, len(target_probs)))}
1365
+
1366
+ tokens = enc.encode(prompt, allowed_special=set())
1367
+ spans = find_option_spans(tokens, enc, options)
1368
+ if spans is None:
1369
+ last = max(0, len(tokens) - 1)
1370
+ spans = [(max(0, last - (len(options) - 1 - i)), max(0, last - (len(options) - 1 - i))) for i in range(len(options))]
1371
+
1372
+ if len(tokens) > seq_len:
1373
+ excess = len(tokens) - seq_len
1374
+ tokens = tokens[excess:]
1375
+ spans = [(max(0, min(seq_len - 1, s - excess)), max(0, min(seq_len - 1, e - excess))) for s, e in spans]
1376
+
1377
+ prim_idx = parse_primitive_id(prim)
1378
+ dom_name = str(rec.get("domain") or rec.get("workflow") or "").strip().lower()
1379
+ dom_idx = parse_domain_id(dom_name)
1380
+
1381
+ inp_tensor = torch.tensor([tokens], device=device, dtype=torch.long)
1382
+ pos_tensor = torch.tensor([spans], device=device, dtype=torch.long)
1383
+
1384
+ mem_input = memory_state if memory_mode != "none" else None
1385
+ if memory_mode == "frozen":
1386
+ mem_input = [m.clone() for m in memory_base]
1387
+
1388
+ with torch.autocast(device_type="cuda", dtype=dtype, enabled=(device.type == "cuda")):
1389
+ logits, _, _, new_mem = model(
1390
+ inp_tensor,
1391
+ candidate_positions=pos_tensor,
1392
+ candidate_mask=None,
1393
+ last_token_only=True,
1394
+ memory_state=mem_input,
1395
+ primitive_id=prim_idx,
1396
+ domain_id=dom_idx,
1397
+ disable_memory=(memory_mode == "none"),
1398
+ )
1399
+
1400
+ if memory_mode == "dynamic" and new_mem is not None:
1401
+ memory_state = [m.detach().clone() for m in new_mem]
1402
+
1403
+ logits_k = logits[0, 0].float()
1404
+
1405
+ # Apply calibration (domain-aware temperature + affine bias or canonical Laya temperature)
1406
+ if calibration:
1407
+ T, bias_t = get_calibration_parameters(calibration, dom_name, prim, k, apply_bias=apply_bias)
1408
+ if bias_t is not None:
1409
+ logits_k = (logits_k / T) + bias_t.to(device=logits_k.device, dtype=logits_k.dtype)
1410
+ else:
1411
+ logits_k = logits_k / T
1412
+
1413
+ probs_k = F.softmax(logits_k, dim=-1).cpu().tolist()
1414
+ pred_probs_dict = {str(i): float(probs_k[i]) for i in range(min(k, len(probs_k)))}
1415
+ tot = sum(pred_probs_dict.values())
1416
+ if tot > 0:
1417
+ pred_probs_dict = {key: val / tot for key, val in pred_probs_dict.items()}
1418
+
1419
+ preds_by_prim[prim].append(pred_probs_dict)
1420
+ targets_by_prim[prim].append(target_probs_dict)
1421
+ opt_ids_by_prim[prim].append(opt_ids)
1422
+ opt_vals_by_prim[prim].append(opt_vals)
1423
+ saved_preds_by_prim[prim].append({
1424
+ "case_id": rec.get("id", f"case_{idx}"),
1425
+ "probabilities": pred_probs_dict,
1426
+ })
1427
+
1428
+ if (idx + 1) % 100 == 0 or (idx + 1) == len(eval_records):
1429
+ print(f" Processed {idx + 1}/{len(eval_records)} cases...", flush=True)
1430
+
1431
+ elapsed_total = time.perf_counter() - t0
1432
+
1433
+ results = []
1434
+ prims = ["choice", "noul", "score"]
1435
+ for prim in prims:
1436
+ if not preds_by_prim[prim]:
1437
+ continue
1438
+ cal_thresh = threshold if prim == "noul" else 0.50
1439
+ metrics = calculate_s1mb_metrics(
1440
+ task=prim,
1441
+ predictions=preds_by_prim[prim],
1442
+ target_distributions=targets_by_prim[prim],
1443
+ option_ids_list=opt_ids_by_prim[prim],
1444
+ option_values_list=opt_vals_by_prim[prim],
1445
+ threshold=cal_thresh,
1446
+ )
1447
+ primary_key = {
1448
+ "choice": "target_mass_at_prediction",
1449
+ "noul": "binary_brier",
1450
+ "score": "normalized_expected_score_mae",
1451
+ }[prim]
1452
+
1453
+ top1_pct = metrics.get("top1_accuracy", 0.0) * 100.0
1454
+ print(f"\n Primitive Result: {prim.upper()} ({len(preds_by_prim[prim])} cases)")
1455
+ print(f" --> Top-1 Raw Accuracy: {top1_pct:.2f}%")
1456
+ print(f" --> Primary Metric ({primary_key}): {metrics.get(primary_key, 0.0):.4f}")
1457
+ print(f" --> Baseline Adjusted Score: {metrics.get('baseline_adjusted_score', 0.0)*100:.2f}%")
1458
+ if prim == "noul":
1459
+ print(f" --> Balanced Accuracy: {metrics.get('balanced_accuracy', 0.0)*100:.2f}%")
1460
+
1461
+ prim_display_names = {
1462
+ "choice": "Local Typed Decisions (Choice: Action)",
1463
+ "noul": "Local Typed Decisions (Noul: Review Required)",
1464
+ "score": "Local Typed Decisions (Score: Risk Level)",
1465
+ }
1466
+ results.append({
1467
+ "benchmark_id": f"local-typed-decisions-{prim}-v1",
1468
+ "name": prim_display_names.get(prim, f"Local {prim.title()}"),
1469
+ "task": prim,
1470
+ "case_count": len(preds_by_prim[prim]),
1471
+ "top1_accuracy": metrics.get("top1_accuracy", 0.0),
1472
+ "primary_metric_name": primary_key,
1473
+ "primary_metric_value": metrics.get(primary_key),
1474
+ "baseline_adjusted_score": metrics.get("baseline_adjusted_score", 0.0),
1475
+ "all_metrics": metrics,
1476
+ "elapsed_seconds": elapsed_total,
1477
+ "predictions": saved_preds_by_prim[prim],
1478
+ })
1479
+
1480
+ return results
1481
+
1482
+ return results
1483
+
1484
+
1485
+ # ---------------------------------------------------------------------------
1486
+ # S1MB Official Leaderboard Report & Comparison
1487
+ # ---------------------------------------------------------------------------
1488
+
1489
+ def print_leaderboard_comparison(results: List[Dict[str, Any]], total_params: int):
1490
+ task_scores = defaultdict(list)
1491
+ raw_accs = defaultdict(list)
1492
+ for r in results:
1493
+ task = r["task"]
1494
+ score = r.get("baseline_adjusted_score", 0.0)
1495
+ task_scores[task].append(score * 100.0)
1496
+ raw_acc = r.get("top1_accuracy", 0.0)
1497
+ raw_accs[task].append(raw_acc * 100.0)
1498
+
1499
+ choice_score = statistics.mean(task_scores["choice"]) if task_scores["choice"] else 0.0
1500
+ noul_score = statistics.mean(task_scores["noul"]) if task_scores["noul"] else 0.0
1501
+ score_score = statistics.mean(task_scores["score"]) if task_scores["score"] else 0.0
1502
+
1503
+ # S1MB official leaderboard averages ALL 3 task scores (including 0.0)
1504
+ all_task_scores = [choice_score, noul_score, score_score]
1505
+ task_avg = statistics.mean(all_task_scores)
1506
+
1507
+ choice_raw = statistics.mean(raw_accs["choice"]) if raw_accs["choice"] else 0.0
1508
+ noul_raw = statistics.mean(raw_accs["noul"]) if raw_accs["noul"] else 0.0
1509
+ score_raw = statistics.mean(raw_accs["score"]) if raw_accs["score"] else 0.0
1510
+ all_raw = [r.get("top1_accuracy", 0.0) * 100.0 for r in results if "top1_accuracy" in r]
1511
+ overall_raw_acc = statistics.mean(all_raw) if all_raw else 0.0
1512
+
1513
+ param_str = f"{total_params / 1e6:.1f}M ({total_params / 1e9:.3f}B)"
1514
+
1515
+ print("\n" + "=" * 106)
1516
+ print(" S1MB EVALUATION BREAKDOWN: TOP-1 ACCURACY & OFFICIAL LEADERBOARD METRICS")
1517
+ print("=" * 106)
1518
+ print(f"{'Benchmark / Task':<42} {'Decisions':<10} {'Top-1 Raw Acc':<16} {'S1MB Score':<14} {'Primary Metric':<22}")
1519
+ print("-" * 106)
1520
+ for r in results:
1521
+ b_name = r.get("name") or r.get("benchmark_id")
1522
+ cnt = r.get("decision_count") or r.get("case_count", 0)
1523
+ top1 = r.get("top1_accuracy", 0.0) * 100.0
1524
+ s1mb_sc = r.get("baseline_adjusted_score", 0.0) * 100.0
1525
+ p_name = r.get("primary_metric_name", "")
1526
+ p_val = r.get("primary_metric_value", 0.0)
1527
+ print(f"{b_name:<42} {cnt:<10} {top1:>6.2f}% {s1mb_sc:>6.2f}% {p_name}={p_val:.4f}")
1528
+
1529
+ print("=" * 106)
1530
+ print(" S1MB (SYSTEM ONE MOSAIC BENCHMARK) — OFFICIAL LEADERBOARD COMPARISON")
1531
+ print("=" * 106)
1532
+ print(f"{'Rank':<6} {'Model':<30} {'Params':<14} {'Task Avg':<10} {'Choice':<10} {'Noul':<10} {'Score':<10} {'Top-1 Raw Acc':<14}")
1533
+ print("-" * 106)
1534
+
1535
+ models_table = [
1536
+ {"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},
1537
+ {"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},
1538
+ {"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},
1539
+ {"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},
1540
+ ]
1541
+
1542
+ models_table.sort(key=lambda m: m["avg"], reverse=True)
1543
+
1544
+ for rank, m in enumerate(models_table, 1):
1545
+ marker = " [* OUR MODEL]" if m["is_nexus"] else ""
1546
+ 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}")
1547
+
1548
+ print("=" * 106)
1549
+
1550
+ return {
1551
+ "choice": choice_score,
1552
+ "noul": noul_score,
1553
+ "score": score_score,
1554
+ "task_avg": task_avg,
1555
+ "overall_raw_accuracy": overall_raw_acc,
1556
+ }
1557
+
1558
+ # ---------------------------------------------------------------------------
1559
+ # S1MB Export & Submission Packager
1560
+ # ---------------------------------------------------------------------------
1561
+
1562
+ def export_s1mb_submission(
1563
+ results: List[Dict[str, Any]],
1564
+ output_dir: Path,
1565
+ model_id: str,
1566
+ total_params: int,
1567
+ ):
1568
+ model_slug = model_id.replace("/", "__").replace(":", "_")
1569
+ target_folder = output_dir / model_slug
1570
+ target_folder.mkdir(parents=True, exist_ok=True)
1571
+
1572
+ print(f"\nPackaging official submission files to {target_folder}...")
1573
+
1574
+ metadata = {
1575
+ "id": model_id,
1576
+ "adapter": "cortex-system-one",
1577
+ "revision": "main",
1578
+ "total_params": total_params,
1579
+ "active_params": total_params,
1580
+ "parameter_count_method": "embedding_excluded_parameters_v1",
1581
+ "created_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
1582
+ "platform": platform.platform(),
1583
+ "python": platform.python_version(),
1584
+ "settings": {
1585
+ "backbone": "Cortex",
1586
+ "decision_head": "CognitiveDecisionTransformerHead",
1587
+ "contrastive_centering": True,
1588
+ "memory_cross_attention": True,
1589
+ "temperature_scaling": "k_adaptive",
1590
+ },
1591
+ }
1592
+ with (target_folder / "metadata.json").open("w", encoding="utf-8") as f:
1593
+ json.dump(metadata, f, indent=2)
1594
+
1595
+ for res in results:
1596
+ b_id = res["benchmark_id"]
1597
+ res_payload = {
1598
+ "format_version": 1,
1599
+ "run_id": f"nexus_s1mb_{int(time.time())}",
1600
+ "benchmark": {
1601
+ "id": b_id,
1602
+ "task": res["task"],
1603
+ "dataset": f"datasets/{res.get('config', 'laya__typed_decisions')}",
1604
+ "split": "test",
1605
+ "case_count": res["case_count"],
1606
+ "decision_count": res.get("decision_count", len(res["predictions"])),
1607
+ "primary_metric": res.get("primary_metric_name"),
1608
+ "evaluation_family": "ordinary",
1609
+ },
1610
+ "metrics": res["all_metrics"],
1611
+ "predictions": res["predictions"],
1612
+ }
1613
+ compressed_bytes = lzma.compress(json.dumps(res_payload).encode("utf-8"))
1614
+ (target_folder / f"{b_id}.json.xz").write_bytes(compressed_bytes)
1615
+
1616
+ summary_path = target_folder / "summary.json"
1617
+ with summary_path.open("w", encoding="utf-8") as f:
1618
+ json.dump(
1619
+ {
1620
+ "model_id": model_id,
1621
+ "total_params": total_params,
1622
+ "benchmarks": [
1623
+ {
1624
+ "id": r["benchmark_id"],
1625
+ "task": r["task"],
1626
+ "case_count": r.get("case_count"),
1627
+ "decision_count": r.get("decision_count", len(r.get("predictions", []))),
1628
+ "score": r["baseline_adjusted_score"] * 100.0,
1629
+ "primary_metric": r["primary_metric_value"],
1630
+ "top1_accuracy": r.get("top1_accuracy", 0.0) * 100.0,
1631
+ }
1632
+ for r in results
1633
+ ],
1634
+ },
1635
+ f,
1636
+ indent=2,
1637
+ )
1638
+
1639
+ print(f" [OK] Submission packaged successfully: {len(results)} benchmarks + metadata.json")
1640
+ print(f" [OK] Location: {target_folder}")
1641
+
1642
+
1643
+ # ---------------------------------------------------------------------------
1644
+ # Main CLI Entrypoint
1645
+ # ---------------------------------------------------------------------------
1646
+
1647
+ def main():
1648
+ parser = argparse.ArgumentParser(description="Official S1MB Evaluation for Nexus System 1")
1649
+ parser.add_argument("checkpoint_pos", nargs="?", default=None, help="Path to checkpoint .pth (positional)")
1650
+ parser.add_argument("--checkpoint", "--ckpt", type=str, default=None, help="Path to checkpoint .pth")
1651
+ parser.add_argument("--suite", type=str, default="smoke", choices=["smoke", "typed_decisions", "local", "full"], help="Benchmark suite to run")
1652
+ parser.add_argument("--test-file", type=str, default="typed_decisions_benchmark_test.jsonl", help="Path to local test dataset for --suite local")
1653
+ parser.add_argument("--limit", type=int, default=None, help="Optional max cases per benchmark (e.g. 50)")
1654
+ parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu")
1655
+ parser.add_argument("--dtype", type=str, default="float16", choices=["float16", "bfloat16", "float32"])
1656
+ parser.add_argument("--memory-mode", type=str, default="dynamic", choices=["dynamic", "frozen", "none"], help="Memory mode (default: dynamic for persistent neural memory)")
1657
+ parser.add_argument("--seq-len", type=int, default=1024)
1658
+ parser.add_argument("--output-dir", type=str, default="s1mb_results")
1659
+ parser.add_argument("--model-name", type=str, default="cortex-system-one")
1660
+ parser.add_argument("--calibration", "--cal", type=str, default=None, help="Path to domain calibration json (e.g. cortex_system_one_calibration.json)")
1661
+ parser.add_argument("--threshold", type=float, default=0.50, help="Classification decision threshold for Noul (default: 0.50)")
1662
+ parser.add_argument("--interleave", action=argparse.BooleanOptionalAction, default=True, help="Interleave cases across domains round-robin to match training memory distribution (default: True)")
1663
+ parser.add_argument("--apply-bias", action="store_true", default=False, help="Apply additive affine bias vectors from calibration (default: False)")
1664
+ 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)")
1665
+ parser.add_argument("--dynamic-retain-floor", type=float, default=None, help="Override memory retain_floor for active forgetting")
1666
+ parser.add_argument("--affinity-bias-shift", type=float, default=0.0, help="Additive shift to affinity gate bias for active storage")
1667
+ parser.add_argument("--export-submission", action="store_true", help="Package submission files into s1mb-result format (default: False)")
1668
+
1669
+ args = parser.parse_args()
1670
+
1671
+ device = torch.device(args.device)
1672
+ dtype_map = {
1673
+ "float16": torch.float16,
1674
+ "bfloat16": torch.bfloat16,
1675
+ "float32": torch.float32,
1676
+ }
1677
+ dtype = dtype_map[args.dtype]
1678
+
1679
+ ckpt_arg = args.checkpoint or args.checkpoint_pos
1680
+ if not ckpt_arg:
1681
+ if Path("ckpt_cortex_system_one_champion.pth").is_file():
1682
+ ckpt_arg = "ckpt_cortex_system_one_champion.pth"
1683
+ elif Path("checkpoints/ckpt_nexus_multidomain_best.pth").is_file():
1684
+ ckpt_arg = "checkpoints/ckpt_nexus_multidomain_best.pth"
1685
+ elif Path("checkpoints/ckpt_nexus_specialist_latest.pth").is_file():
1686
+ ckpt_arg = "checkpoints/ckpt_nexus_specialist_latest.pth"
1687
+ else:
1688
+ raise ValueError("Must provide checkpoint path either positionally or with --checkpoint")
1689
+
1690
+ ckpt_path = Path(ckpt_arg)
1691
+ if not ckpt_path.is_file():
1692
+ raise FileNotFoundError(f"Checkpoint not found at: {ckpt_path}")
1693
+
1694
+ enc = tiktoken.get_encoding("cl100k_base")
1695
+ model, memory, total_params = load_nexus_model(ckpt_path, device, dtype)
1696
+
1697
+ if args.dynamic_retain_floor is not None:
1698
+ for mem in model.memory:
1699
+ mem.retain_floor = args.dynamic_retain_floor
1700
+ print(f" [MEMORY] Configured dynamic retain_floor = {args.dynamic_retain_floor}")
1701
+ if args.affinity_bias_shift != 0.0:
1702
+ for mem in model.memory:
1703
+ mem.affinity_gate[0].bias.data.add_(args.affinity_bias_shift)
1704
+ print(f" [MEMORY] Configured affinity bias shift = {args.affinity_bias_shift:+.2f}")
1705
+
1706
+ # Auto-discover calibration file if present
1707
+ calibration_meta = None
1708
+ if args.calibration and args.calibration.strip().lower() in ("none", "false", "off", "disable", "no"):
1709
+ print(" [CALIBRATION] Calibration explicitly disabled via CLI flag (evaluating pure raw model predictions).")
1710
+ else:
1711
+ cal_candidates = []
1712
+ if args.calibration:
1713
+ cal_candidates.append(Path(args.calibration))
1714
+ else:
1715
+ cal_candidates.append(ckpt_path.parent / "system1_multidomain_calibration.json")
1716
+ cal_candidates.append(Path("system1_multidomain_calibration.json"))
1717
+ cal_candidates.append(Path("system1_multidomain_calibration2.json"))
1718
+ cal_candidates.append(Path("system1_multidomain_calibration1.json"))
1719
+ for cp in cal_candidates:
1720
+ if cp.is_file():
1721
+ try:
1722
+ with cp.open("r", encoding="utf-8") as f:
1723
+ calibration_meta = json.load(f)
1724
+ print(f" [CALIBRATION] Restored domain-aware affine vector calibration from {cp.name}")
1725
+ break
1726
+ except Exception:
1727
+ pass
1728
+ if not calibration_meta and args.calibration:
1729
+ print(f" [CALIBRATION WARNING] Specified calibration file '{args.calibration}' not found. Evaluating with pure raw predictions.")
1730
+
1731
+ results = []
1732
+
1733
+ if args.suite == "local":
1734
+ test_file_path = Path(args.test_file)
1735
+ if not test_file_path.is_file():
1736
+ raise FileNotFoundError(f"Local test file not found at: {test_file_path}")
1737
+ results = evaluate_local_test(
1738
+ model=model,
1739
+ memory_base=memory,
1740
+ test_path=test_file_path,
1741
+ enc=enc,
1742
+ device=device,
1743
+ dtype=dtype,
1744
+ limit=args.limit,
1745
+ memory_mode=args.memory_mode,
1746
+ seq_len=args.seq_len,
1747
+ calibration=calibration_meta,
1748
+ threshold=args.threshold,
1749
+ apply_bias=args.apply_bias,
1750
+ interleave=args.interleave,
1751
+ )
1752
+ elif args.suite == "typed_decisions" and getattr(args, "interleave", True):
1753
+ results = evaluate_typed_decisions_interleaved_suite(
1754
+ model=model,
1755
+ memory_base=memory,
1756
+ enc=enc,
1757
+ device=device,
1758
+ dtype=dtype,
1759
+ limit=args.limit,
1760
+ memory_mode=args.memory_mode,
1761
+ seq_len=args.seq_len,
1762
+ calibration=calibration_meta,
1763
+ threshold=args.threshold,
1764
+ apply_bias=args.apply_bias,
1765
+ interleave=args.interleave,
1766
+ case_decay=args.case_decay,
1767
+ )
1768
+ else:
1769
+ if args.suite == "smoke":
1770
+ suite_benchmarks = SMOKE_BENCHMARKS
1771
+ elif args.suite == "typed_decisions":
1772
+ suite_benchmarks = TYPED_DECISIONS_BENCHMARKS
1773
+ else:
1774
+ suite_benchmarks = SMOKE_BENCHMARKS + TYPED_DECISIONS_BENCHMARKS
1775
+
1776
+ print(f"\nRunning S1MB Suite: {args.suite.upper()} ({len(suite_benchmarks)} benchmarks) | Memory Mode: {args.memory_mode.upper()}")
1777
+
1778
+ for b_meta in suite_benchmarks:
1779
+ res = evaluate_benchmark(
1780
+ model=model,
1781
+ memory_base=memory,
1782
+ benchmark_meta=b_meta,
1783
+ enc=enc,
1784
+ device=device,
1785
+ dtype=dtype,
1786
+ limit=args.limit,
1787
+ memory_mode=args.memory_mode,
1788
+ seq_len=args.seq_len,
1789
+ calibration=calibration_meta,
1790
+ threshold=args.threshold,
1791
+ apply_bias=args.apply_bias,
1792
+ )
1793
+ results.append(res)
1794
+
1795
+ # Print summary and comparison against Bekko and Laya
1796
+ print_leaderboard_comparison(results, total_params)
1797
+
1798
+ # Export submission files only if explicitly requested
1799
+ if args.export_submission:
1800
+ export_s1mb_submission(
1801
+ results=results,
1802
+ output_dir=Path(args.output_dir),
1803
+ model_id=args.model_name,
1804
+ total_params=total_params,
1805
+ )
1806
+
1807
+
1808
+ if __name__ == "__main__":
1809
+ main()