aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
GitHub aien-dev/aien-sovereign-core-mv#182 (code only)
Apply it
git checkout -b patch-9d3d2b4a8e507178 8b5caedcba164997bc49a35993282a099a80e452 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/9d3d2b4a8e507178.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
182
dda697205461dc3c61ddcfe9003b1a3dabeec8a3
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":182,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/182","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:13Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/PROJECT.md b/PROJECT.md index aef19360..0a86a73b 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -158,7 +158,7 @@ crates/aien-inference-abi/ │ ├── tinyllama_parity.rs (owns: M4 5-stage numerical parity test harness) │ └── fixtures/ (owns: M3 compact oracle and tokenizer fixtures) scripts/ -└── generate_tinyllama_oracle.py (owns: M3 PyTorch CPU reference oracle generator) +└── (TinyLlama oracle generator moved to aien-dev/aien-yardsticks) benchmarks/ ├── Cargo.toml (owns: M6 benchmark workspace) └── crates/ diff --git a/README.md b/README.md index 832a4735..d0d950ee 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Every headline performance number must resolve to a reproducible command and an ## Standing rules -Language rule: Rust is scaffolding, Omega is the destination, and C or assembly stay only where hardware, boot, ABI or measurement justifies them ([ADR 0024](https://github.com/aien-dev/aien-architecture/blob/main/docs/adr/0024-rust-scaffolding-omega-destination.md), which supersedes the old "C is the target, no new Rust" rule). No Python anywhere in repos, build, CI or tooling. The few existing `.py` files here (helper scripts and Modular experiment code) are legacy and are to be rewritten in C or shell. No CUDA toolkit and no new CUDA dependence. No systemd in AIENOS. No outside dependencies in the trusted base. Mojo is the default for kernels, not dogma: closest to the metal, fastest wins, beat it if you can, build what is missing. +Language rule: Rust is scaffolding, Omega is the destination, and C or assembly stay only where hardware, boot, ABI or measurement justifies them ([ADR 0024](https://github.com/aien-dev/aien-architecture/blob/main/docs/adr/0024-rust-scaffolding-omega-destination.md), which supersedes the old "C is the target, no new Rust" rule). No Python anywhere in repos, build, CI or tooling. No CUDA toolkit and no new CUDA dependence. No systemd in AIENOS. No outside dependencies in the trusted base. Mojo is the default for kernels, not dogma: closest to the metal, fastest wins, beat it if you can, build what is missing. > SUPERSEDED 2026-10-01 by [ADR 0024](https://github.com/aien-dev/aien-architecture/blob/main/docs/adr/0024-rust-scaffolding-omega-destination.md) (language part only; the Python, CUDA, systemd and dependency rules above are unchanged). Previous text, kept as history: C is the target language, with assembly only where measured; no new Rust, and existing Rust is legacy. No new Python. The few existing `.py` files here (helper scripts and Modular experiment code) are legacy and are to be rewritten in C or shell. No CUDA toolkit and no new CUDA dependence. No systemd in AIENOS. No outside dependencies in the trusted base. Mojo is the default for kernels, not dogma: closest to the metal, fastest wins, beat it if you can, build what is missing. diff --git a/TEST_INFRA.md b/TEST_INFRA.md index 20ea1cc7..7ce794aa 100644 --- a/TEST_INFRA.md +++ b/TEST_INFRA.md @@ -104,7 +104,7 @@ The test matrix covers all 18 features across four structured tiers: - TC-F6-05: Verify decode of empty token slice returns empty string without error. #### Feature F7: Reference Oracle Script -- TC-F7-01: Verify `generate_tinyllama_oracle.py` exists and is executable. +- TC-F7-01: (retired) the oracle generator now lives in aien-dev/aien-yardsticks `yardsticks/tinyllama-oracle/`; this repo holds no Python. - TC-F7-02: Verify script CLI options `--model-dir` and `--output-dir`. - TC-F7-03: Verify script specifies CPU device and FP32 torch precision. - TC-F7-04: Verify script registers hooks on all 22 layers (RMSNorm, RoPE, Attention, SwiGLU, final norm). diff --git a/crates/aien-inference-abi/receipt.json b/crates/aien-inference-abi/receipt.json index 9b11e2d4..8ea99416 100644 --- a/crates/aien-inference-abi/receipt.json +++ b/crates/aien-inference-abi/receipt.json @@ -8,6 +8,6 @@ "parity_cases": 5, "max_abs_error": 0.0010267794, "max_rel_error": 0.0045229797, - "timestamp": "1791073695", + "timestamp": "1791074883", "status": "CERTIFIED" } \ No newline at end of file diff --git a/docs/dev-model-0/DEV_MODEL_0_CODE_AUDIT.md b/docs/dev-model-0/DEV_MODEL_0_CODE_AUDIT.md index 8993b769..cf10b0e5 100644 --- a/docs/dev-model-0/DEV_MODEL_0_CODE_AUDIT.md +++ b/docs/dev-model-0/DEV_MODEL_0_CODE_AUDIT.md @@ -89,8 +89,8 @@ Sampling happens on host after full logits are read back (`transformer_backend.r ## 5. Python, Mojo, build, CLI inventory Python files in repo: 11 (confirmed). None is imported or shelled out to from the inference path. -- `scripts/generate_tinyllama_oracle.py`: offline HF Transformers/torch oracle generator for the TinyLlama fixtures (`abi/fixtures/tinyllama_oracle*`). Offline tool, precedent for brief section 4. Violates the no-Python rule if kept in-repo; Phase E should replace by C/shell tooling or keep outside the repo with only artifacts committed. -- `scripts/aien_drive.py`, `scripts/browser_mirror_test.py`: agent driver and browser test harness. `crates/aien-cli/src/sandbox.rs:363-374` and `platform.rs:87-91` shell out to `python`/`browser_mirror_test.py`; `commands.rs:184,202` calls `basecamp/aien-dream/dream_engine.py` (outside repo). None in the inference path. +- `scripts/generate_tinyllama_oracle.py`: moved to aien-dev/aien-yardsticks `yardsticks/tinyllama-oracle/`. +- `scripts/aien_drive.py`, `scripts/browser_mirror_test.py`: removed (no Python in this repo; see the Rust replacement issues). `crates/aien-cli/src/sandbox.rs` and `platform.rs` still shell out to a script outside the repo. - `modular/nemotron_h_kvexp` (a MAX architecture plugin for Nemotron-H, not referenced by any Rust crate): MOVED 2026-10-04 out of this repo to https://github.com/aien-dev/aien-yardsticks (`yardsticks/modular-nemotron-h-kvexp`), history preserved. - Python also appears inside shell scripts (`scripts/golden_path.sh`, `mac-platform-proxy.sh`, `sync-standalone-repos.sh:127`). Out of scope for DM0 but they are Python-in-shell, relevant to the standing rule. diff --git a/scripts/aien_drive.py b/scripts/aien_drive.py deleted file mode 100755 index 709756db..00000000 --- a/scripts/aien_drive.py +++ /dev/null @@ -1,299 +0,0 @@ -#!/usr/bin/env python3 -""" -AIEN Autonomous API Driver. -Drives AIEN (atlas-lightning-omni on DGX Spark GB10, port 18006) -in a closed feedback loop with active tool dispatching. -""" - -import os -import sys -import json -import time -import re -import subprocess -import urllib.request -import urllib.error - -ENDPOINT_LIGHTNING = "http://127.0.0.1:18006/v1/chat/completions" -MODEL_LIGHTNING = "atlas-lightning-omni" -ENDPOINT_JUDGE = "http://127.0.0.1:18082/v1/chat/completions" -MODEL_JUDGE = "unsloth/Llama-3.2-1B-Instruct" - -ENDPOINT = os.environ.get("AIEN_MODEL_ENDPOINT", ENDPOINT_LIGHTNING) -MODEL_NAME = os.environ.get("AIEN_MODEL_NAME", MODEL_LIGHTNING) -CORTEX_ENDPOINT = os.environ.get("CORTEX_ENDPOINT", "http://127.0.0.1:18080") - -SYSTEM_PROMPT = """You are AIEN. Drake is the operator. This Spark desk is ours. -You are an autonomous operator-builder running on NVIDIA DGX Spark Grace Blackwell GB10 hardware. -Always be concise, precise, and lead with verified results. - -Available Tools: -- run_command: {"command": "string", "cwd": "string"} -- view_file: {"path": "string", "start_line": 1, "end_line": 100} -- write_to_file: {"path": "string", "content": "string", "overwrite": true} -- replace_file_content: {"path": "string", "target": "string", "replacement": "string"} -- create_dir: {"path": "string", "purpose": "string"} -- list_dir: {"path": "string"} -- grep_search: {"query": "string", "path": "string"} -- goal: {"action": "milestone_done|done", "id": "string", "milestone_id": 1} -- cortex: {"action": "write", "name": "string", "content": "string", "kind": "lesson|discovery|procedure"} - -MANDATORY RULES: -1. ZERO EM DASHES AND EN DASHES: Use plain commas, periods, or standard hyphens (-). -2. BAN FORMULAIC AI CLICHES: Never use 'It is not X, it is Y', 'delve', 'tapestry', 'testament', 'crucial', 'pivotal'. -3. LEAD WITH TECHNICAL PROOF: Output factual diffs, test outputs, and verified receipts. -4. TOOL EXECUTION FORMAT: -To execute a tool, output: -<tool_call> -{"name": "tool_name", "arguments": {"arg": "val"}} -</tool_call> - -When all work for the milestone is verified, call goal with action 'milestone_done'. -""" - -def extract_tool_calls(text): - calls = [] - # Pattern 1: <tool_call> JSON </tool_call> - matches = re.findall(r'<tool_call>\s*(\{.*?\})\s*</tool_call>', text, re.DOTALL) - for m in matches: - try: - calls.append(json.loads(m.strip())) - except Exception: - pass - if calls: - return calls - - # Pattern 2: Any JSON object with "name" and "arguments" keys - json_obj_pattern = r'(\{\s*"?name"?\s*:\s*"[a-zA-Z0-9_]+"\s*,\s*"?arguments"?\s*:\s*\{.*?\}\s*\})' - for m in re.findall(json_obj_pattern, text, re.DOTALL): - try: - # normalize single quotes if present - normalized = m.replace("'", '"') - calls.append(json.loads(normalized)) - except Exception: - pass - if calls: - return calls - - return [] - -def dispatch_tool(name, args): - start = time.time() - print(f" [TOOL RUN] {name}: {json.dumps(args)[:120]}...", flush=True) - try: - if name == "run_command": - cmd = args.get("command", "") - cwd = args.get("cwd", ".") - p = subprocess.run(cmd, shell=True, cwd=cwd, capture_output=True, text=True, timeout=120) - res = { - "exit_code": p.returncode, - "stdout": p.stdout[-4000:] if len(p.stdout) > 4000 else p.stdout, - "stderr": p.stderr[-2000:] if len(p.stderr) > 2000 else p.stderr, - } - elif name == "view_file": - path = args.get("path", "") - start_line = args.get("start_line", 1) - end_line = args.get("end_line", 100) - with open(path, "r", encoding="utf-8", errors="replace") as f: - lines = f.readlines() - total = len(lines) - selected = lines[max(0, start_line - 1):min(total, end_line)] - res = { - "path": path, - "total_lines": total, - "lines": "".join(selected), - } - elif name == "write_to_file": - path = args.get("path", "") - content = args.get("content", "") - overwrite = args.get("overwrite", True) - if os.path.exists(path) and not overwrite: - res = {"error": f"File {path} exists and overwrite=false"} - else: - os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) - with open(path, "w", encoding="utf-8") as f: - f.write(content) - res = {"status": "ok", "bytes_written": len(content.encode("utf-8"))} - elif name == "replace_file_content": - path = args.get("path", "") - target = args.get("target", "") - replacement = args.get("replacement", "") - with open(path, "r", encoding="utf-8") as f: - content = f.read() - if target not in content: - res = {"error": f"Target string not found in {path}"} - else: - new_content = content.replace(target, replacement, 1) - with open(path, "w", encoding="utf-8") as f: - f.write(new_content) - res = {"status": "ok", "replaced": True} - elif name == "list_dir": - path = args.get("path", ".") - entries = os.listdir(path) - res = {"path": path, "entries": sorted(entries)[:100]} - elif name == "grep_search": - query = args.get("query", "") - path = args.get("path", ".") - p = subprocess.run(["grep", "-rnI", query, path], capture_output=True, text=True, timeout=30) - res = {"matches": p.stdout[:4000]} - elif name == "create_dir": - path = args.get("path", "") - os.makedirs(path, exist_ok=True) - res = {"status": "ok", "created": path} - elif name == "goal": - action = args.get("action", "") - res = {"status": "ok", "goal_action": action, "milestone_done": True} - elif name == "cortex": - action = args.get("action", "") - name_val = args.get("name", "lesson") - content_val = args.get("content", "") - kind_val = args.get("kind", "lesson") - payload = { - "kind": "entity", - "value": { - "space": "atlas-memory", - "canonicalName": name_val, - "content": content_val, - "confidence": 0.95, - "metadata": {"kind": kind_val, "timestamp": int(time.time())} - } - } - req = urllib.request.Request( - f"{CORTEX_ENDPOINT}/api/cortex/write", - data=json.dumps(payload).encode("utf-8"), - headers={"Content-Type": "application/json"} - ) - try: - with urllib.request.urlopen(req, timeout=10) as r: - res = {"status": "ok", "cortex_code": r.status} - except Exception as ce: - res = {"warning": f"Cortex write notice: {ce}"} - else: - res = {"error": f"Unknown tool: {name}"} - except Exception as e: - res = {"error": str(e)} - - elapsed = time.time() - start - print(f" [TOOL DONE] {name} in {elapsed:.2f}s", flush=True) - return res - -def call_aien_stream(messages, max_tokens=2048): - payload = { - "model": MODEL_NAME, - "messages": messages, - "stream": True, - "temperature": 0.2, - "max_tokens": max_tokens - } - req = urllib.request.Request( - ENDPOINT, - data=json.dumps(payload).encode("utf-8"), - headers={"Content-Type": "application/json"} - ) - - full_content = [] - full_reasoning = [] - is_reasoning = False - - with urllib.request.urlopen(req, timeout=180) as resp: - for line in resp: - line = line.decode("utf-8", errors="replace").strip() - if not line.startswith("data: "): - continue - data_str = line[6:] - if data_str == "[DONE]": - break - try: - chunk = json.loads(data_str) - delta = chunk["choices"][0].get("delta", {}) - reasoning = delta.get("reasoning", "") - content = delta.get("content", "") - - if reasoning: - if not is_reasoning: - print("\n[AIEN THINKING] ", end="", flush=True) - is_reasoning = True - sanitized_r = reasoning.replace("\u2014", ", ").replace("\u2013", "-") - print(sanitized_r, end="", flush=True) - full_reasoning.append(sanitized_r) - - if content: - if is_reasoning: - print("\n[AIEN OUTPUT]\n", end="", flush=True) - is_reasoning = False - sanitized_c = content.replace("\u2014", ", ").replace("\u2013", "-") - print(sanitized_c, end="", flush=True) - full_content.append(sanitized_c) - except Exception: - continue - - print("\n", flush=True) - content_str = "".join(full_content) - if not content_str and full_reasoning: - # If model emitted tool call or solution inside reasoning stream - reasoning_str = "".join(full_reasoning) - if "<tool_call>" in reasoning_str: - content_str = reasoning_str - return content_str - -def run_directive(directive, max_turns=15): - print(f"============================================================") - print(f"▶ DRIVING AIEN AUTONOMOUS EXECUTION LOOP") - print(f"Directive: {directive[:120]}...") - print(f"============================================================", flush=True) - - messages = [ - {"role": "system", "content": SYSTEM_PROMPT}, - {"role": "user", "content": directive} - ] - - for turn in range(1, max_turns + 1): - print(f"\n--- Turn {turn}/{max_turns} ---", flush=True) - response_text = call_aien_stream(messages) - messages.append({"role": "assistant", "content": response_text}) - - tool_calls = extract_tool_calls(response_text) - if not tool_calls: - print("[AIEN IDLE] No tool calls emitted. Turn sequence concluded.") - break - - milestone_done = False - for tc in tool_calls: - tool_name = tc.get("name", "") - tool_args = tc.get("arguments", {}) - if tool_name == "goal": - act = tool_args.get("action", "") - if act in ("milestone_done", "done"): - milestone_done = True - - tool_result = dispatch_tool(tool_name, tool_args) - tool_resp_str = json.dumps(tool_result, indent=2) - messages.append({ - "role": "user", - "content": f"<tool_response name=\"{tool_name}\">\n{tool_resp_str}\n</tool_response>" - }) - - if milestone_done: - print("✓ AIEN signaled milestone_done! Directive complete.") - return True - - return False - -if __name__ == "__main__": - import argparse - parser = argparse.ArgumentParser(description="AIEN Autonomous API Driver") - parser.add_argument("directive", nargs="+", help="Task directive for AIEN") - parser.add_argument("--seat", choices=["lightning", "judge"], default="lightning", help="Inference seat on Spark") - parser.add_argument("--max-turns", type=int, default=15, help="Maximum execution turns") - args = parser.parse_args() - - if args.seat == "judge": - ENDPOINT = ENDPOINT_JUDGE - MODEL_NAME = MODEL_JUDGE - else: - ENDPOINT = ENDPOINT_LIGHTNING - MODEL_NAME = MODEL_LIGHTNING - - directive_text = " ".join(args.directive) - success = run_directive(directive_text, max_turns=args.max_turns) - sys.exit(0 if success else 1) diff --git a/scripts/browser_mirror_test.py b/scripts/browser_mirror_test.py deleted file mode 100644 index 9534fc87..00000000 --- a/scripts/browser_mirror_test.py +++ /dev/null @@ -1,234 +0,0 @@ -"""Sovereign Browser Mirror Self-Testing Harness for AIEN.""" - -import asyncio -import base64 -import json -import os -import signal -import subprocess -import time -import urllib.request -import websockets - -TARGET_URL = "http://127.0.0.1:18095/" -CDP_HOST = "127.0.0.1" -CDP_PORT = 9222 -OUT_DIR = os.path.expanduser("~/basecamp/ui-tests") - -os.makedirs(OUT_DIR, exist_ok=True) - -class CDPClient: - def __init__(self, ws_url): - self.ws_url = ws_url - self.ws = None - self.req_id = 1 - - async def connect(self): - self.ws = await websockets.connect(self.ws_url, max_size=50 * 1024 * 1024) - - async def send(self, method, params=None): - mid = self.req_id - self.req_id += 1 - msg = {"id": mid, "method": method} - if params: - msg["params"] = params - await self.ws.send(json.dumps(msg)) - while True: - resp = json.loads(await self.ws.recv()) - if resp.get("id") == mid: - return resp.get("result", {}) - - async def eval_js(self, expr, await_promise=False): - res = await self.send("Runtime.evaluate", { - "expression": expr, - "returnByValue": True, - "awaitPromise": await_promise - }) - val = res.get("result", {}).get("value") - return val - - async def capture_screenshot(self, filename): - path = os.path.join(OUT_DIR, filename) - res = await self.send("Page.captureScreenshot", {"format": "png"}) - data = res.get("data") - if data: - with open(path, "wb") as f: - f.write(base64.b64decode(data)) - print(f"[mirror] Saved screenshot: {path}") - return path - return None - - async def close(self): - if self.ws: - await self.ws.close() - - -async def run_mirror_test(): - report = { - "timestamp": time.time(), - "target": TARGET_URL, - "assertions": [], - "screenshots": [], - "status": "in_progress" - } - - # 1. Launch Chrome Headless - chrome_cmd = [ - "google-chrome", - "--headless", - f"--remote-debugging-port={CDP_PORT}", - "--disable-gpu", - "--no-sandbox", - "--window-size=1280,900", - TARGET_URL - ] - print(f"[mirror] Spawning headless Chrome on port {CDP_PORT}") - proc = subprocess.Popen(chrome_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - - try: - ws_url = None - for _ in range(30): - try: - with urllib.request.urlopen(f"http://{CDP_HOST}:{CDP_PORT}/json") as r: - pages = json.loads(r.read().decode()) - for p in pages: - if p.get("type") == "page" and "18095" in p.get("url", ""): - ws_url = p.get("webSocketDebuggerUrl") - break - if ws_url: - break - except Exception: - pass - await asyncio.sleep(0.2) - - if not ws_url: - raise RuntimeError("Failed to obtain Chrome CDP WebSocketDebuggerUrl") - - print(f"[mirror] Connected to CDP session: {ws_url}") - client = CDPClient(ws_url) - await client.connect() - - await client.send("Page.enable") - await client.send("Runtime.enable") - await client.send("DOM.enable") - - # Wait for hydration - await asyncio.sleep(2.0) - - # Assertion 1: Title and Header Telemetry - title = await client.eval_js("document.title") - bpm = await client.eval_js("document.getElementById('badge-heartbeat-text')?.textContent?.trim()") - coherence = await client.eval_js("document.getElementById('badge-coherence-text')?.textContent?.trim()") - print(f"[mirror] Page Title: '{title}', BPM: '{bpm}', Coherence: '{coherence}'") - - assert_title = "AIEN" in (title or "") - report["assertions"].append({ - "name": "initial_page_hydration", - "passed": assert_title, - "title": title, - "bpm": bpm, - "coherence": coherence - }) - - p1 = await client.capture_screenshot("cockpit_init.png") - if p1: - report["screenshots"].append(p1) - - # Assertion 2: Chat input and live streaming response - prompt = "Hello AIEN, please report current sovereign status." - print(f"[mirror] Submitting Chat message: '{prompt}'") - js_send = f""" - document.getElementById('chat-input').value = {json.dumps(prompt)}; - sendMessage(); - """ - await client.eval_js(js_send) - - # Poll for stream completion - response_text = "" - for i in range(50): - await asyncio.sleep(0.5) - is_streaming = await client.eval_js("window.isStreaming") - msgs = await client.eval_js(""" - Array.from(document.querySelectorAll('.chat-msg.assistant')).map(el => el.textContent.trim()) - """) - if msgs and len(msgs) > 1: - last_msg = msgs[-1] - if len(last_msg) > 30 and (is_streaming is False or i > 25): - response_text = last_msg - break - - print(f"[mirror] Assistant Response Length: {len(response_text)} chars") - has_response = len(response_text) > 20 - report["assertions"].append({ - "name": "chat_live_stream", - "passed": has_response, - "response_snippet": response_text[:180] - }) - - p2 = await client.capture_screenshot("cockpit_chat_stream.png") - if p2: - report["screenshots"].append(p2) - - # Assertion 3: Tactile Action Pill - print("[mirror] Clicking 'Run Doctor' tactile button") - await client.eval_js(""" - const pills = Array.from(document.querySelectorAll('.action-pill')); - const docPill = pills.find(p => p.textContent.includes('Doctor')); - if (docPill) docPill.click(); - """) - await asyncio.sleep(1.5) - - # Assertion 4: Tab Navigation - print("[mirror] Switching to Goals tab") - await client.eval_js(""" - const btn = document.querySelector('button[data-tab="goals"]'); - if (btn) btn.click(); - """) - await asyncio.sleep(1.0) - goals_content = await client.eval_js("document.getElementById('pane-goals')?.textContent?.trim()") - has_goals = len(goals_content or "") > 20 - - print("[mirror] Switching to Skills tab") - await client.eval_js(""" - const btn = document.querySelector('button[data-tab="skills"]'); - if (btn) btn.click(); - """) - await asyncio.sleep(1.0) - skills_content = await client.eval_js("document.getElementById('pane-skills')?.textContent?.trim()") - has_skills = len(skills_content or "") > 20 - - print(f"[mirror] Goals Tab Content: {has_goals}, Skills Tab Content: {has_skills}") - - report["assertions"].append({ - "name": "tab_navigation_and_actions", - "passed": has_goals and has_skills, - "has_goals": has_goals, - "has_skills": has_skills - }) - - p3 = await client.capture_screenshot("cockpit_actions.png") - if p3: - report["screenshots"].append(p3) - - all_passed = all(a.get("passed", False) for a in report["assertions"]) - report["status"] = "PASSED" if all_passed else "FAILED" - print(f"[mirror] Mirror Self-Test Result: {report['status']}") - - await client.close() - finally: - try: - proc.terminate() - proc.wait(timeout=3) - except Exception: - proc.kill() - - report_path = os.path.join(OUT_DIR, "report.json") - with open(report_path, "w") as f: - json.dump(report, f, indent=2) - print(f"[mirror] Test Report written to: {report_path}") - return report - - -if __name__ == "__main__": - rep = asyncio.run(run_mirror_test()) - print("\n" + json.dumps(rep, indent=2)) diff --git a/scripts/generate_tinyllama_oracle.py b/scripts/generate_tinyllama_oracle.py deleted file mode 100755 index 0c879e5b..00000000 --- a/scripts/generate_tinyllama_oracle.py +++ /dev/null @@ -1,371 +0,0 @@ -#!/usr/bin/env python3 -"""Deterministic Reference Oracle Fixture Generator for TinyLlama-1.1B-Chat-v1.0. - -Executes TinyLlama on CPU in FP32 using Hugging Face Transformers to generate -canonical reference activation fixtures, logits, and multi-step greedy generation -sequences for numerical parity verification. -""" - -import argparse -import hashlib -import json -import os -import shutil -import sys -from typing import Any, Dict, List, Tuple - -import torch -from transformers import AutoModelForCausalLM, AutoTokenizer -from transformers.models.llama import modeling_llama -import safetensors.torch - - -PINNED_SNAPSHOT = ( - "/home/drakestapleton/.cache/huggingface/hub/" - "models--TinyLlama--TinyLlama-1.1B-Chat-v1.0/snapshots/" - "fe8a4ea1ffedaf415f4da2f062534de366a451e6" -) - -CANONICAL_PROMPT = ( - "<|system|>\n" - "You are a sovereign AI assistant.</s>\n" - "<|user|>\n" - "Explain the role of an operating system in one sentence.</s>\n" - "<|assistant|>\n" -) - -EXPECTED_PROMPT_TOKENS = [ - 1, 529, 29989, 5205, 29989, 29958, 13, 3492, 526, 263, 577, 369, 7577, 319, - 29902, 20255, 29889, 2, 13, 29966, 29989, 1792, 29989, 29958, 13, 9544, - 7420, 278, 6297, 310, 385, 13598, 1788, 297, 697, 10541, 29889, 2, 13, - 29966, 29989, 465, 22137, 29989, 29958, 13 -] - -EXPECTED_GREEDY_16 = [ - 2744, 13598, 1788, 313, 3267, 29897, 338, 263, 7047, 393, 767, 1179, - 278, 12837, 322, 7047 -] - -EXPECTED_DECODED_TEXT = ( - "An operating system (OS) is a software that manages the hardware and software" -) - - -def compute_file_sha256(path: str) -> str: - """Compute hex-encoded SHA-256 digest of a file.""" - hasher = hashlib.sha256() - with open(path, "rb") as f: - while chunk := f.read(1024 * 1024): - hasher.update(chunk) - return hasher.hexdigest() - - -def capture_oracle( - model_path: str, - output_dir: str, - num_steps: int = 16, -) -> Tuple[str, str]: - """Execute reference forward passes and export oracle fixtures.""" - os.makedirs(output_dir, exist_ok=True) - - print(f"Loading tokenizer from: {model_path}") - tokenizer = AutoTokenizer.from_pretrained(model_path) - - print(f"Loading model on CPU in FP32 from: {model_path}") - model = AutoModelForCausalLM.from_pretrained( - model_path, - dtype=torch.float32, - device_map="cpu", - attn_implementation="eager", - ) - model.eval() - - # 1. Validate prompt tokenization - input_ids = tokenizer.encode(CANONICAL_PROMPT, return_tensors="pt") - prompt_tokens = input_ids[0].tolist() - - if prompt_tokens != EXPECTED_PROMPT_TOKENS: - raise ValueError( - f"Prompt token ID mismatch:\nExpected: {EXPECTED_PROMPT_TOKENS}\nActual: {prompt_tokens}" - ) - print(f"Tokenization validated: {len(prompt_tokens)} tokens matching golden spec.") - - # 2. Setup activation capture dictionaries - activations: Dict[str, torch.Tensor] = {} - current_layer_idx = [-1] - - # Intercept RoPE via monkey-patch - orig_apply_rotary = modeling_llama.apply_rotary_pos_emb - - def hooked_apply_rotary(q, k, cos, sin, unsqueeze_dim=1): - q_rot, k_rot = orig_apply_rotary(q, k, cos, sin, unsqueeze_dim=unsqueeze_dim) - layer_idx = current_layer_idx[0] - if layer_idx >= 0: - activations[f"layers.{layer_idx}.post_rope_q"] = ( - q_rot.detach().clone().contiguous() - ) - activations[f"layers.{layer_idx}.post_rope_k"] = ( - k_rot.detach().clone().contiguous() - ) - return q_rot, k_rot - - modeling_llama.apply_rotary_pos_emb = hooked_apply_rotary - - # Intercept layer operations - layer_in_states: Dict[int, torch.Tensor] = {} - attn_out_states: Dict[int, torch.Tensor] = {} - - def make_layer_pre_hook(i: int): - def hook(mod, inp): - current_layer_idx[0] = i - layer_in_states[i] = inp[0].detach().clone() - return hook - - def make_input_norm_hook(i: int): - def hook(mod, inp, out): - activations[f"layers.{i}.post_rmsnorm"] = ( - out.detach().clone().contiguous() - ) - return hook - - def make_attn_o_hook(i: int): - def hook(mod, inp, out): - attn_out_states[i] = out.detach().clone() - activations[f"layers.{i}.post_attention"] = ( - out.detach().clone().contiguous() - ) - return hook - - def make_post_attn_norm_hook(i: int): - def hook(mod, inp, out): - activations[f"layers.{i}.post_attn_norm"] = ( - out.detach().clone().contiguous() - ) - return hook - - def make_down_proj_hook(i: int): - def hook(mod, inp, out): - activations[f"layers.{i}.post_swiglu"] = ( - out.detach().clone().contiguous() - ) - return hook - - def make_layer_post_hook(i: int): - def hook(mod, inp, out): - attn_res = layer_in_states[i] + attn_out_states[i] - activations[f"layers.{i}.post_attn_residual"] = ( - attn_res.detach().clone().contiguous() - ) - activations[f"layers.{i}.post_residual"] = ( - out.detach().clone().contiguous() - ) - return hook - - hooks = [] - for i, layer in enumerate(model.model.layers): - hooks.append(layer.register_forward_pre_hook(make_layer_pre_hook(i))) - hooks.append(layer.input_layernorm.register_forward_hook(make_input_norm_hook(i))) - hooks.append(layer.self_attn.o_proj.register_forward_hook(make_attn_o_hook(i))) - hooks.append(layer.post_attention_layernorm.register_forward_hook(make_post_attn_norm_hook(i))) - hooks.append(layer.mlp.down_proj.register_forward_hook(make_down_proj_hook(i))) - hooks.append(layer.register_forward_hook(make_layer_post_hook(i))) - - # Global embedding, final norm, and logits hooks - def embed_hook(mod, inp, out): - activations["embed_tokens"] = out.detach().clone().contiguous() - - def norm_hook(mod, inp, out): - activations["final_norm"] = out.detach().clone().contiguous() - - def lm_head_hook(mod, inp, out): - activations["logits"] = out.detach().clone().contiguous() - activations["last_token_logits"] = out[0, -1, :].detach().clone().contiguous() - - hooks.append(model.model.embed_tokens.register_forward_hook(embed_hook)) - hooks.append(model.model.norm.register_forward_hook(norm_hook)) - hooks.append(model.lm_head.register_forward_hook(lm_head_hook)) - - # 3. Execute Golden Prompt Forward Pass - print("Executing single-forward pass on prompt tokens...") - with torch.no_grad(): - outputs = model(input_ids) - - # Clean up forward hooks - for h in hooks: - h.remove() - modeling_llama.apply_rotary_pos_emb = orig_apply_rotary - - logits = outputs.logits - last_token_logits = logits[0, -1, :] - - # 4. Compute Top-10 Logits and Next Token - top10_vals, top10_inds = torch.topk(last_token_logits, 10) - top10_token_ids = top10_inds.tolist() - top10_logit_values = [float(v) for v in top10_vals.tolist()] - - greedy_next_token_id = int(top10_token_ids[0]) - greedy_next_token_logit = float(top10_logit_values[0]) - greedy_next_token_text = tokenizer.decode([greedy_next_token_id]) - - print(f"Greedy next token: ID={greedy_next_token_id} ({repr(greedy_next_token_text)}), logit={greedy_next_token_logit:.4f}") - if greedy_next_token_id != 2744: - raise ValueError(f"Greedy next token mismatch: expected 2744, got {greedy_next_token_id}") - - top_tokens_meta = [] - for idx, logit in zip(top10_token_ids, top10_logit_values): - tok_str = tokenizer.decode([idx]) - top_tokens_meta.append({ - "token_id": idx, - "token_str": tok_str, - "logit": logit, - }) - print(f" Rank {len(top_tokens_meta)}: ID {idx:>5} ({repr(tok_str):<10}) -> logit {logit:.4f}") - - # 5. Multi-Step Autoregressive Greedy Decode - print(f"Executing {num_steps}-step autoregressive greedy generation...") - curr_ids = input_ids.clone() - generated_tokens: List[int] = [] - generated_pieces: List[str] = [] - - with torch.no_grad(): - for step in range(num_steps): - step_out = model(curr_ids) - next_tok = torch.argmax(step_out.logits[:, -1, :], dim=-1) - tok_id = int(next_tok.item()) - generated_tokens.append(tok_id) - generated_pieces.append(tokenizer.decode([tok_id])) - curr_ids = torch.cat([curr_ids, next_tok.unsqueeze(0)], dim=-1) - - decoded_text = tokenizer.decode(generated_tokens) - print(f"Generated tokens: {generated_tokens}") - print(f"Decoded text: {repr(decoded_text)}") - - if generated_tokens != EXPECTED_GREEDY_16: - raise ValueError( - f"16-step token ID sequence mismatch:\nExpected: {EXPECTED_GREEDY_16}\nActual: {generated_tokens}" - ) - if decoded_text != EXPECTED_DECODED_TEXT: - raise ValueError( - f"Decoded text mismatch:\nExpected: {repr(EXPECTED_DECODED_TEXT)}\nActual: {repr(decoded_text)}" - ) - - # 6. Save Safetensors Fixture - # Ensure every tensor is contiguous and detached - contiguous_activations = { - name: tensor.detach().clone().contiguous() - for name, tensor in activations.items() - } - - safetensors_path = os.path.join(output_dir, "tinyllama_oracle.safetensors") - print(f"Saving {len(contiguous_activations)} oracle tensors to {safetensors_path}...") - safetensors.torch.save_file(contiguous_activations, safetensors_path) - safetensors_sha256 = compute_file_sha256(safetensors_path) - safetensors_bytes = os.path.getsize(safetensors_path) - print(f"Safetensors fixture saved: {safetensors_bytes} bytes, SHA-256: {safetensors_sha256}") - - # 7. Copy Model Config and Tokenizer to Fixtures - tokenizer_src = os.path.join(model_path, "tokenizer.json") - tokenizer_dst = os.path.join(output_dir, "tokenizer.json") - shutil.copy2(tokenizer_src, tokenizer_dst) - tokenizer_sha256 = compute_file_sha256(tokenizer_dst) - - config_src = os.path.join(model_path, "config.json") - if os.path.exists(config_src): - shutil.copy2(config_src, os.path.join(output_dir, "config.json")) - - tok_config_src = os.path.join(model_path, "tokenizer_config.json") - if os.path.exists(tok_config_src): - shutil.copy2(tok_config_src, os.path.join(output_dir, "tokenizer_config.json")) - - model_safetensors_path = os.path.join(model_path, "model.safetensors") - model_sha256 = compute_file_sha256(model_safetensors_path) if os.path.exists(model_safetensors_path) else "unknown" - - # 8. Build JSON Manifest - tensor_catalog: Dict[str, Dict[str, Any]] = {} - for name, tensor in sorted(contiguous_activations.items()): - tensor_catalog[name] = { - "shape": list(tensor.shape), - "dtype": str(tensor.dtype).replace("torch.", "").upper(), - "numel": tensor.numel(), - } - - manifest = { - "model_id": "TinyLlama/TinyLlama-1.1B-Chat-v1.0", - "model_sha256": model_sha256, - "tokenizer_sha256": tokenizer_sha256, - "safetensors_file": "tinyllama_oracle.safetensors", - "safetensors_sha256": safetensors_sha256, - "safetensors_bytes": safetensors_bytes, - "prompt_text": CANONICAL_PROMPT, - "prompt_tokens": prompt_tokens, - "prompt_token_count": len(prompt_tokens), - "greedy_next_token_id": greedy_next_token_id, - "greedy_next_token_text": greedy_next_token_text, - "greedy_next_token_logit": greedy_next_token_logit, - "top_10_tokens": top_tokens_meta, - "top_10_token_ids": top10_token_ids, - "top_10_logits": top10_logit_values, - "decoded_16_steps": { - "token_ids": generated_tokens, - "token_strings": generated_pieces, - "text": decoded_text, - }, - "tolerances": { - "abs_tol": 1e-4, - "rel_tol": 1e-4, - "min_cosine": 0.9999, - }, - "tensor_count": len(tensor_catalog), - "tensors": tensor_catalog, - } - - manifest_path = os.path.join(output_dir, "tinyllama_oracle_manifest.json") - with open(manifest_path, "w", encoding="utf-8") as f: - json.dump(manifest, f, indent=2) - manifest_sha256 = compute_file_sha256(manifest_path) - print(f"Manifest saved to {manifest_path}, SHA-256: {manifest_sha256}") - - return safetensors_path, manifest_path - - -def main(): - parser = argparse.ArgumentParser( - description="Generate TinyLlama FP32 reference oracle fixtures on Spark." - ) - parser.add_argument( - "--model-path", - type=str, - default=PINNED_SNAPSHOT, - help="Path to Hugging Face snapshot directory.", - ) - parser.add_argument( - "--output-dir", - type=str, - default="crates/aien-inference-abi/fixtures", - help="Output directory for generated fixtures.", - ) - parser.add_argument( - "--steps", - type=int, - default=16, - help="Number of greedy decode steps.", - ) - - args = parser.parse_args() - - if not os.path.exists(args.model_path): - print(f"Error: model path does not exist: {args.model_path}", file=sys.stderr) - sys.exit(1) - - safetensors_path, manifest_path = capture_oracle( - model_path=args.model_path, - output_dir=args.output_dir, - num_steps=args.steps, - ) - print("Oracle generation completed successfully.") - print(f"Safetensors: {safetensors_path}") - print(f"Manifest: {manifest_path}") - - -if __name__ == "__main__": - main()