Views
No views yet
lr_embed / lr_cls; seed=123 held constant)| Metric | Mean ± Std | Threshold | Status |
|---|---|---|---|
| Task C Accuracy | 95.9% ± 0.8% | ≥80% | PASS |
| Combined Forgetting | -0.6% ± 2.8% | ≤10% | PASS |
| Anchor Memory | 96.00 KB | O(1) | PASS |
| Safety Constant Λ | 0.9785142874 | Invariant | PASS |
| Run | lr_embed / lr_cls | Acc A | Acc B | Acc C | Forgetting |
|---|---|---|---|---|---|
| Run 0 | 5e-03 / 1e-03 | 86.50% | 79.50% | 96.75% | +4.12% |
| Run 1 | 1e-03 / 5e-04 | 90.50% | 88.00% | 95.25% | -2.13% |
| Run 2 | 1e-02 / 2e-03 | 93.50% | 83.50% | 95.00% | -1.50% |
| Run 3 | 5e-03 / 5e-03 | 92.50% | 91.75% | 96.50% | -3.12% |
| Run 4 | 2e-03 / 1e-03 | 90.75% | 81.00% | 95.75% | -0.38% |
1
2# ============================================================================
3# 12. TOPO-2026 AGENTIC NEWS TRIAGE AGENT — FULLY STANDALONE
4# ============================================================================
5# Self-contained cell. Loads the certified Sarvam-30B FP8 checkpoint
6# directly from the HuggingFace Hub. Does NOT depend on Cell 11.
7#
8# Pipeline per news item:
9# PLAN -> keyword router selects task head (A / B / C)
10# ACT -> certified Sarvam-30B FP8 classifier -> label + confidence
11# DISPATCH -> threshold policy -> ALERT / LOG / ESCALATE / SKIP
12# LOG -> structured AgentDecision appended to agent.log
13# ============================================================================
14
15import torch, torch.nn as nn, torch.nn.functional as F
16import numpy as np, math, json as _json, datetime
17from dataclasses import dataclass, field, asdict
18from typing import List
19from collections import Counter
20from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedModel
21from huggingface_hub import hf_hub_download
22from unittest.mock import patch
23import warnings as _warnings
24
25# Suppress known harmless deprecation warnings from transformers internals
26# 1. Python warnings module (FutureWarning, DeprecationWarning)
27_warnings.filterwarnings('ignore', category=FutureWarning,
28 module='transformers.modeling_attn_mask_utils')
29_warnings.filterwarnings('ignore', category=FutureWarning)
30_warnings.filterwarnings('ignore', category=DeprecationWarning)
31# 2. HuggingFace transformers logger (torch_dtype, use_return_dict, etc.)
32import logging as _logging
33_logging.getLogger('transformers').setLevel(_logging.ERROR)
34_logging.getLogger('transformers.modeling_utils').setLevel(_logging.ERROR)
35_logging.getLogger('transformers.models').setLevel(_logging.ERROR)
36from transformers import logging as _hf_logging
37_hf_logging.set_verbosity_error()
38
39# -- Model / repo identifiers (same as Cells 10-11) --------------------------
40HF_REPO_ID = 'frankmorales2020/topological-ai-sarvam-30b-multirun'
41BASE_MODEL_ID = 'frankmorales2020/sarvam-30b-fp8-unesco-resilient'
42HIDDEN_SIZE = 4096
43MAX_LEN = 64
44
45# -- Coverage constant (recomputed from prime set, never hardcoded) -----------
46LAMBDA = 1.0 - math.prod(1.0 - p**-0.5 for p in [2, 3, 5, 7, 11, 13])
47FIXED_SEED = 123
48
49# Lock all random sources to FIXED_SEED for reproducibility
50import random as _random
51torch.manual_seed(FIXED_SEED)
52np.random.seed(FIXED_SEED)
53_random.seed(FIXED_SEED)
54if torch.cuda.is_available():
55 torch.cuda.manual_seed_all(FIXED_SEED)
56 torch.backends.cudnn.deterministic = True
57 torch.backends.cudnn.benchmark = False
58
59TASK_LABELS = {
60 'A': {0: 'World', 1: 'Sports'},
61 'B': {0: 'Business', 1: 'Sci/Tech'},
62 'C': {0: 'World', 1: 'Sci/Tech'},
63}
64
65# Confidence floor — Sarvam-30B outputs 90-100% on AG News; below 90% is noise
66CONF_FLOOR = 0.90 # < CONF_FLOOR -> SKIP regardless of priority
67CONF_CRITICAL = 0.999 # >= CONF_CRITICAL + high priority -> CRITICAL (highest tier)
68
69
70# ============================================================================
71# 12a. Model architecture (identical to Cell 11)
72# ============================================================================
73class TaskAwareInferenceModel(nn.Module):
74 def __init__(self, base):
75 super().__init__()
76 self.base_model = base
77 dev = next(base.parameters()).device
78 def _head():
79 return nn.Sequential(
80 nn.Linear(HIDDEN_SIZE, 512, dtype=torch.bfloat16),
81 nn.GELU(), nn.Dropout(0.2),
82 nn.Linear(512, 2, dtype=torch.bfloat16),
83 ).to(dev)
84 self.classifier_A = _head()
85 self.classifier_B = _head()
86 self.classifier_C = _head()
87 self.current_task = 'A'
88
89 def forward(self, input_ids, attention_mask=None):
90 hidden = self.base_model(
91 input_ids=input_ids, attention_mask=attention_mask,
92 output_hidden_states=True,
93 ).hidden_states[-1]
94 if attention_mask is not None:
95 mask = attention_mask.unsqueeze(-1).to(hidden.dtype)
96 pooled = (hidden * mask).sum(1) / mask.sum(1).clamp(min=1e-9)
97 else:
98 pooled = hidden.mean(1)
99 if pooled.dtype != torch.bfloat16:
100 pooled = pooled.to(torch.bfloat16)
101 return getattr(self, f'classifier_{self.current_task}')(pooled)
102
103 def switch_task(self, t):
104 self.current_task = t
105
106
107# ============================================================================
108# 12b. Load certified checkpoint from HuggingFace Hub
109# ============================================================================
110print('=' * 75)
111print(f'TOPO-2026 AGENTIC CELL 12 | {HF_REPO_ID}')
112print(f'Lambda (prime anchor coverage): {LAMBDA:.10f}')
113print('=' * 75)
114
115# ── GPU purge before independent load ───────────────────────────────────────
116# Cell 12 is fully independent. Free any model already on GPU so the
117# 30B FP8 backbone can load and decompress without OOM.
118import gc
119_purge_names = ['model', '_base_agent', '_agent_model']
120for _n in _purge_names:
121 _obj = globals().get(_n)
122 if _obj is not None:
123 try:
124 if hasattr(_obj, 'cpu'): _obj.cpu()
125 if hasattr(_obj, 'base_model') and hasattr(_obj.base_model, 'cpu'):
126 _obj.base_model.cpu()
127 except Exception:
128 pass
129 del _obj
130 globals().pop(_n, None)
131gc.collect()
132if torch.cuda.is_available():
133 torch.cuda.empty_cache()
134 torch.cuda.synchronize()
135 _free = torch.cuda.mem_get_info()[0] / 1024**3
136 print(f'[AGENT] GPU memory freed. Available: {_free:.2f} GiB')
137
138# ── Independent backbone load ────────────────────────────────────────────────
139_orig_init = PreTrainedModel._initialize_weights
140def _safe_init(self_hf, module, is_remote_code=False):
141 try:
142 _orig_init(self_hf, module)
143 except NotImplementedError as e:
144 if 'Float8_e4m3fn' in str(e) or 'normal_kernel_cpu' in str(e):
145 module._is_hf_initialized = True
146 else:
147 raise
148
149print('[AGENT] Loading Sarvam-30B FP8 backbone from Hub...')
150with patch.object(PreTrainedModel, '_initialize_weights', _safe_init):
151 _base_agent = AutoModelForCausalLM.from_pretrained(
152 BASE_MODEL_ID, trust_remote_code=True, low_cpu_mem_usage=True,
153 torch_dtype=torch.bfloat16, device_map='auto',
154 )
155for p in _base_agent.parameters():
156 p.requires_grad = False
157
158_tok_agent = AutoTokenizer.from_pretrained(BASE_MODEL_ID, trust_remote_code=True)
159_tok_agent.pad_token = _tok_agent.eos_token
160
161print('[AGENT] Loading certified checkpoint...')
162_ckpt_path = hf_hub_download(repo_id=HF_REPO_ID, filename='certified_topological_best.pt')
163_agent_model = TaskAwareInferenceModel(_base_agent)
164_agent_model.load_state_dict(
165 torch.load(_ckpt_path, map_location='cpu'), strict=False
166)
167_agent_model.eval()
168print(f'[AGENT] Certified checkpoint loaded. Lambda={LAMBDA:.10f}')
169
170
171# ============================================================================
172# 12c. Data structures
173# ============================================================================
174@dataclass
175class NewsItem:
176 text: str
177 source: str = 'unknown'
178 priority: str = 'normal' # 'high' | 'normal' | 'low'
179
180
181@dataclass
182class AgentDecision:
183 text: str
184 routed_task: str
185 label: str
186 confidence: float
187 action: str
188 rationale: str
189 timestamp: str = field(
190 default_factory=lambda: datetime.datetime.now(datetime.timezone.utc).isoformat()
191 )
192
193
194# ============================================================================
195# 12d. Planner: keyword-based task router
196# ============================================================================
197_TASK_B_KW = {
198 'earnings', 'revenue', 'profit', 'market', 'stock', 'gdp', 'economy',
199 'trade', 'inflation', 'nasdaq', 'dow', 'invest', 'startup', 'ipo',
200 'acquisition', 'merger', 'quarter', 'fiscal', 'fund', 'venture',
201}
202_TASK_C_KW = {
203 'quantum', 'ai', 'artificial intelligence', 'neural', 'robot', 'climate',
204 'research', 'study', 'science', 'space', 'nasa', 'lab', 'university',
205 'breakthrough', 'discovery', 'technology', 'tech', 'software', 'chip',
206 'semiconductor', 'genome', 'drug', 'vaccine', 'physics', 'experiment',
207}
208
209def plan_task(text: str) -> str:
210 lower = text.lower()
211 if any(kw in lower for kw in _TASK_B_KW):
212 return 'B'
213 if any(kw in lower for kw in _TASK_C_KW):
214 return 'C'
215 return 'A'
216
217
218# ============================================================================
219# 12e. Action dispatcher
220# ============================================================================
221def dispatch_action(confidence: float, priority: str):
222 """
223 Triage logic: action is determined by BOTH confidence AND priority.
224
225 CRITICAL : high priority AND confidence >= 99.9% (highest certainty — immediate escalation)
226 ALERT : high priority AND 90% <= conf < 99.9% (act now)
227 LOG : normal priority AND confidence >= 97% (store, review later)
228 ESCALATE : normal priority AND 90% <= conf < 97% (human review needed)
229 SKIP : confidence < 90% (model uncertain — discard)
230 """
231 if confidence < CONF_FLOOR:
232 return 'SKIP', f'conf={confidence:.1%} below floor ({CONF_FLOOR:.0%})'
233 if priority == 'high' and confidence >= CONF_CRITICAL:
234 return 'CRITICAL', f'HIGH priority + conf={confidence:.1%} — maximum certainty'
235 if priority == 'high':
236 return 'ALERT', f'HIGH priority + conf={confidence:.1%} — act immediately'
237 if confidence >= 0.97:
238 return 'LOG', f'conf={confidence:.1%} >= 97% — logged for review'
239 return 'ESCALATE', f'conf={confidence:.1%} in [90%,97%) — human review'
240
241
242# ============================================================================
243# 12f. Agent
244# ============================================================================
245class NewsTriageAgent:
246 """
247 Agentic loop wrapping the TOPO-2026 certified Sarvam-30B FP8 classifier.
248 Plan -> Act -> Dispatch -> Log.
249 """
250 def __init__(self, model, tokenizer, max_len: int = MAX_LEN):
251 self.model = model
252 self.tokenizer = tokenizer
253 self.max_len = max_len
254 self.log: List[AgentDecision] = []
255 self._device = next(model.base_model.parameters()).device
256 print(f'[AGENT] NewsTriageAgent ready | device={self._device}')
257 print(f'[AGENT] Thresholds: CRITICAL>=99.9% (high) | '
258 f'ALERT>=90% (high) | LOG>=97% (normal) | '
259 f'ESCALATE>=90% (normal) | SKIP<{CONF_FLOOR:.0%}')
260
261 def _classify(self, text: str, task: str):
262 inp = self.tokenizer(
263 text, return_tensors='pt',
264 max_length=self.max_len, padding='max_length', truncation=True,
265 )
266 inp = {k: v.to(self._device) for k, v in inp.items()}
267 self.model.switch_task(task)
268 with torch.no_grad():
269 logits = self.model(inp['input_ids'], inp['attention_mask'])
270 probs = F.softmax(logits.float(), dim=-1).squeeze().cpu().numpy()
271 idx = int(np.argmax(probs))
272 confidence = float(probs[idx])
273 label = TASK_LABELS[task][idx]
274 return label, confidence
275
276 def process(self, item: NewsItem) -> AgentDecision:
277 task = plan_task(item.text)
278 label, confidence = self._classify(item.text, task)
279 action, rationale = dispatch_action(confidence, item.priority)
280 decision = AgentDecision(
281 text = item.text,
282 routed_task = task,
283 label = label,
284 confidence = confidence,
285 action = action,
286 rationale = rationale,
287 )
288 self.log.append(decision)
289 return decision
290
291 def run_queue(self, queue: List[NewsItem]) -> None:
292 w = 74
293 print('\n' + '=' * w)
294 print(f' TOPO-2026 AGENTIC NEWS TRIAGE | {len(queue)} items')
295 print(f' Certified model: {HF_REPO_ID}')
296 print(f' Lambda={LAMBDA:.10f}')
297 print('=' * w)
298 print(f' {"#":>2} {"Task":>4} {"Label":>10} {"Conf":>6} '
299 f'{"Action":>9} Text')
300 print('-' * w)
301 for i, item in enumerate(queue):
302 d = self.process(item)
303 icons = {'CRITICAL': 'CRIT', 'ALERT': 'ALRT', 'LOG': 'LOG ', 'ESCALATE': 'ESC ', 'SKIP': 'SKIP'}
304 short = (d.text[:43] + '...') if len(d.text) > 46 else d.text
305 prio = ' [HIGH]' if item.priority == 'high' else ''
306 print(f' {i:>2} {d.routed_task:>4} {d.label:>10} '
307 f'{d.confidence:>5.1%} {icons[d.action]} {short}{prio}')
308 print('=' * w)
309 self._print_summary()
310
311 def _print_summary(self) -> None:
312 if not self.log:
313 return
314 actions = Counter(d.action for d in self.log)
315 tasks = Counter(d.routed_task for d in self.log)
316 avg_conf = sum(d.confidence for d in self.log) / len(self.log)
317 print(f'\n SUMMARY ({len(self.log)} decisions)')
318 for act in ['CRITICAL', 'ALERT', 'LOG', 'ESCALATE', 'SKIP']:
319 if actions[act]:
320 print(f' {act:<9} {actions[act]:>3} item(s)')
321 print(f' Task routing : {dict(sorted(tasks.items()))}')
322 print(f' Avg confidence: {avg_conf:.1%}')
323
324 def export_log(self, path: str = '/tmp/topo2026_agent_log.json') -> None:
325 with open(path, 'w') as f:
326 _json.dump([asdict(d) for d in self.log], f, indent=2)
327 print(f'\n [AGENT] Decision log -> {path}')
328
329
330# ============================================================================
331# 12g. Demo queue and run
332# ============================================================================
333DEMO_QUEUE = [
334 NewsItem('World leaders gather for emergency climate summit in Geneva',
335 source='Reuters', priority='high'),
336 NewsItem('Tech giant reports record $48B quarterly revenue on cloud growth',
337 source='Bloomberg', priority='high'),
338 NewsItem('New CRISPR therapy shows 94% efficacy in phase-3 cancer trial',
339 source='Nature', priority='normal'),
340 NewsItem('National football team advances to World Cup semi-finals',
341 source='AP', priority='normal'),
342 NewsItem('Central bank raises interest rates 50bps amid inflation surge',
343 source='FT', priority='high'),
344 NewsItem('Startup raises $800M Series D for quantum computing hardware',
345 source='TechCrunch', priority='normal'),
346 NewsItem('UN peacekeeping mission deployed to conflict zone in East Africa',
347 source='BBC', priority='high'),
348 NewsItem('Mars rover discovers subsurface water ice deposits near equator',
349 source='NASA', priority='normal'),
350 NewsItem('Major semiconductor fab announces $20B expansion in Arizona',
351 source='WSJ', priority='normal'),
352 NewsItem('Olympic sprinter breaks 100m world record at championships',
353 source='ESPN', priority='low'),
354 NewsItem('Parliament passes landmark data-privacy legislation',
355 source='Guardian', priority='normal'),
356 NewsItem('Neural scaling law paper challenges LLM training assumptions',
357 source='arXiv', priority='normal'),
358]
359
360agent = NewsTriageAgent(model=_agent_model, tokenizer=_tok_agent)
361agent.run_queue(DEMO_QUEUE)
362agent.export_log('/tmp/topo2026_agent_log.json')
363print(f'\n[AGENT] Complete. Lambda={LAMBDA:.10f}')
3641
2 ===========================================================================
3TOPO-2026 AGENTIC CELL 12 | frankmorales2020/topological-ai-sarvam-30b-multirun
4Lambda (prime anchor coverage): 0.9785142874
5===========================================================================
6[AGENT] GPU memory freed. Available: 78.83 GiB
7[AGENT] Loading Sarvam-30B FP8 backbone from Hub...
8Compressing model: 100%|██████████| 7007/7007 [00:11<00:00, 616.22it/s]
9Loading weights: 100% 14129/14129 [00:40<00:00, 925.08it/s][AGENT] Loading certified checkpoint...
10[AGENT] Certified checkpoint loaded. Lambda=0.9785142874
11[AGENT] NewsTriageAgent ready | device=cuda:0
12[AGENT] Thresholds: CRITICAL>=99.9% (high) | ALERT>=90% (high) | LOG>=97% (normal) | ESCALATE>=90% (normal) | SKIP<90%
13
14==========================================================================
15 TOPO-2026 AGENTIC NEWS TRIAGE | 12 items
16 Certified model: frankmorales2020/topological-ai-sarvam-30b-multirun
17 Lambda=0.9785142874
18==========================================================================
19 # Task Label Conf Action Text
20--------------------------------------------------------------------------
21Decompressing model: 100%|██████████| 7007/7007 [00:02<00:00, 2652.56it/s]
22 0 C World 91.8% ALRT World leaders gather for emergency climate ... [HIGH]
23 1 B Business 100.0% CRIT Tech giant reports record $48B quarterly re... [HIGH]
24 2 A World 100.0% LOG New CRISPR therapy shows 94% efficacy in ph...
25 3 A World 99.7% LOG National football team advances to World Cu...
26 4 B Business 100.0% CRIT Central bank raises interest rates 50bps am... [HIGH]
27 5 B Sci/Tech 99.3% LOG Startup raises $800M Series D for quantum c...
28 6 A World 100.0% CRIT UN peacekeeping mission deployed to conflic... [HIGH]
29 7 A Sports 92.4% ESC Mars rover discovers subsurface water ice d...
30 8 C World 99.9% LOG Major semiconductor fab announces $20B expa...
31 9 A Sports 90.2% ESC Olympic sprinter breaks 100m world record a...
32 10 A World 100.0% LOG Parliament passes landmark data-privacy leg...
33 11 C Sci/Tech 100.0% LOG Neural scaling law paper challenges LLM tra...
34==========================================================================
35
36 SUMMARY (12 decisions)
37 CRITICAL 3 item(s)
38 ALERT 1 item(s)
39 LOG 6 item(s)
40 ESCALATE 2 item(s)
41 Task routing : {'A': 6, 'B': 3, 'C': 3}
42 Avg confidence: 97.8%
43
44 [AGENT] Decision log -> /tmp/topo2026_agent_log.json
45
46[AGENT] Complete. Lambda=0.9785142874
47
48