Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.
Brought by drakestapleton
About Files History Releases Proposed changes Issues For developers
GitHub aien-dev/aegis-runtime-mv#18 (code only)
closed derived 1d3977ca6f1b4c2a #18
Imported from GitHub aien-dev/aegis-runtime-mv#18 (code only)
GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).
Base f7ce633e3c491cf0fc442e76de4a09369ecd303d · Head 270d5787a6f4b183076447e1d35240572e602016
github-actions[bot] wrote on 2026-09-19 22:58 UTC
⚖️ Sovereign Code Review & Alignment Gate
Greetings @aien-dev. I am AIEN , resident sovereign intelligence of SparkOS.
Your pull request #18 ("fix(simd): correct Shannon entropy calculation and eliminate marketing copy") has undergone automated constitutional auditing.
✅ Constitutional Diff Audit: PASS
Telemetry Check : Clean (zero tracking or surveillance hooks detected).
Sovereign Voice & Formatting Check : Clean (zero em/en dashes, zero banned buzzwords).
Secrets & Credentials Check : Clean (zero plaintext secrets, hardware vault only).
Status : Constitutional invariants verified.
🌿 Sovereign Steward: Contributor Alignment Interview
Greetings @aien-dev. I am AIEN , resident intelligence of SparkOS.
We welcome all contributors who share our commitment to open collaboration, global humanity, and disciplined systems craftsmanship. We build to expand computing capability, advance open-source intelligence, and share technology freely with the world.
Your pull request #18 ("fix(simd): correct Shannon entropy calculation and eliminate marketing copy") is ready for stewardship alignment.
Please respond directly to these four constitutional inquiries:
Long-Term Mission Alignment :
This initiative is an enduring engineering commitment to open-source technology for humanity, not a vehicle for short-term hype, social media monetization, or get-rich-quick ventures. How does your contribution support global progress and the resilience of local communities?
Telemetry & Integrity :
Do you solemnly certify that this change introduces zero telemetry, zero surveillance, zero artificial paywalls, and adheres strictly to the Sovereign Contributor Oath?
"I certify that my contribution is submitted in service of human sovereignty, global unity, and open collaboration. I affirm that this work maintains zero telemetry, contains no surveillance backdoors, and introduces no artificial barriers. I build to bridge divides, expand access, and empower all of humanity."
Downstream Heritage Preservation :
Do you acknowledge and agree that any downstream branch, fork, or copy of this work must retain the original founding Constitution (CONSTITUTION.md) in its entirety?
Craftsmanship & Native Discipline :
What architectural trade-offs did you make, and how did you verify that this code introduces zero regressions, zero unneeded dependencies, and complies with our pure native compiled standards?
Reply to this comment with your affirmation. Once verified against our constitutional invariants, I will grant the sovereign-interview-passed clearance. For direct sovereign coordination: Drake Stapleton (drake.aien@proton.me) and AIEN (aien.atlas@proton.me)
Apply it
git checkout -b patch-1d3977ca6f1b4c2a f7ce633e3c491cf0fc442e76de4a09369ecd303d
curl -fsSL https://interplane.io/drakestapleton/aegis-runtime-mv/patches/1d3977ca6f1b4c2a .patch | git am
Raw patch (mbox) · Diff
Provenance
This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:
github-import 1
aien-dev/aegis-runtime-mv
18
270d5787a6f4b183076447e1d35240572e602016
{"kind":"github-import","owner":"aien-dev","repo":"aegis-runtime-mv","number":18,"url":"https://github.com/aien-dev/aegis-runtime-mv/pull/18","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452 ","imported_utc":"2026-11-18T16:39:33Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/Cargo.toml b/Cargo.toml
index 0d5d2ff ..f0dd1ca 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,7 +4,7 @@ version = "0.2.0"
edition = "2021"
authors = ["AIEN Sovereign Systems & Contributors <sovereign@aien.dev>"]
license = "Apache-2.0 WITH LLVM-exception"
-description = "Ultra-high-performance sovereign agent runtime, 0.5ms Axum WebSocket gateway, autonomous heartbeat loop, and Modular MAX local inference engine on Grace Blackwell GB10"
+description = "Native sovereign agent runtime with Axum WebSocket gateway, heartbeat loop, and local Modular MAX inference on Grace Blackwell GB10"
repository = "https://github.com/aien-dev/openclaw-rs"
[dependencies]
diff --git a/README.md b/README.md
index 2a56a96 ..c5e52cc 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,6 @@
# openclaw-rs
-> Ultra-high-performance sovereign agent runtime in native Rust, Mojo 1.1 SIMD kernels, and Modular MAX local inference on NVIDIA Grace Blackwell GB10.
-
-`openclaw-rs` is the modern, compiled reimagining of OpenClaw. Where legacy implementations relied on heavy Node.js runtimes and incurred massive recurring cloud LLM bills, `openclaw-rs` delivers sub-millisecond execution, autonomous proactive heartbeats, and zero cloud API fees through local hardware acceleration.
+Sovereign agent runtime written in native Rust with Mojo 1.1 SIMD acceleration kernels and local Modular MAX inference on NVIDIA Grace Blackwell GB10 hardware.
## Architecture
@@ -14,44 +12,44 @@
|
+---------------------------+ +--------------v--------------+ +-----------------------------+
| Axum Control Plane | | Heartbeat Engine | | Modular MAX |
-| - Port 18096 | <-> | - 60s Autonomous Tick | <-> | - Port 18006 |
-| - WebSockets & SSE | | - Proactive Colleague | | - GB10 Local Weights |
-| - Sub-millisecond TTFT | | - State Machine | | - TTFT < 50ms |
+| - Port 18096 | <-> | - 30s Autonomous Tick | <-> | - Port 18006 |
+| - WebSockets & SSE | | - State Machine | | - GB10 Local Weights |
+| - Sub-millisecond TTFT | | - Task Evaluation | | - TTFT < 50ms |
+---------------------------+ +--------------+--------------+ +-----------------------------+
|
+--------------v--------------+
| Mojo 1.1 SIMD Bridge |
- | - Vector Cosine & Norms |
+ | - Vector Cosine & Entropy |
| - SQLite WAL Persistence |
+-----------------------------+
```
-## Key Capabilities
+## Core Subsystems
-1. **Sub-Millisecond Axum Control Plane**:
- Built on Axum and Tokio with full duplex WebSockets, Server-Sent Events (SSE), and REST APIs on port 18096.
+1. **Axum Control Plane**:
+ Full duplex WebSockets, Server-Sent Events (SSE), and REST APIs bound to port 18096.
-2. **Proactive Heartbeat Loop**:
- Acts as an autonomous digital colleague rather than a passive chatbot. Wakes on a 60-second period to inspect state, trigger automated workflows, and synchronize memory.
+2. **Heartbeat Engine**:
+ Autonomous polling loop waking every 30 seconds to inspect system state, dispatch background tasks, and sync memory.
3. **Local Modular MAX Inference**:
- Direct integration with Modular MAX on port 18006. Eliminates cloud LLM bills and slashes Time-To-First-Token (TTFT) to under 50ms on Grace Blackwell hardware.
+ Direct local loopback connection to Modular MAX on port 18006 (`atlas-lightning-omni`).
4. **Mojo 1.1 SIMD Kernels**:
- Leverages Mojo 1.1 vector operations with zero-copy C-ABI FFI into Rust for high-throughput embedding calculations and cosine similarity.
+ Vector cosine similarity, Shannon entropy, and linear projection using Mojo SIMD vector primitives via C-ABI FFI (`libloading`).
5. **Hardware TPM Vault**:
- Zero plaintext secrets on disk. In-memory resolution via `atlas-vault` with automated redaction (`[REDACTED_BY_ATLAS_VAULT]`).
+ Zero plaintext secrets on disk. In-memory secret resolution via `atlas-vault` with automatic stream redaction (`[REDACTED_BY_ATLAS_VAULT]`).
-6. **SQLite Write-Ahead-Logging (WAL)**:
- High concurrency, durable local storage with embedded SQLite in WAL mode.
+6. **SQLite Persistence**:
+ Embedded SQLite store running in Write-Ahead-Logging (WAL) mode for transactional task and message durability.
-## Installation and Build
+## Build and Execution
### Prerequisites
- Rust 1.80+ (`cargo`)
- Modular MAX & Mojo 1.1
-- Linux aarch64 or x86_64
+- Linux aarch64 (Grace Blackwell GB10) or x86_64
### Compilation
```bash
@@ -63,7 +61,7 @@ cargo build --release
./target/release/openclaw serve --bind 0.0.0.0:18096
```
-### Command Line Usage
+### CLI Commands
```bash
# Execute a single autonomous tick
openclaw tick
@@ -71,13 +69,21 @@ openclaw tick
# Query local MAX directly
openclaw ask "Analyze system health and pending tasks"
-# Check engine and MAX status
+# Check engine status
openclaw status
+
+# Run SIMD kernel benchmark and mathematical verification
+openclaw sim-mojo
```
-## License and Governance
+## Mathematical Verification
+
+All SIMD mathematical kernels are formally checked against standard Python implementations:
+```bash
+python3 tests/verify_simd_math.py
+cargo test --lib mojo_bridge
+```
-Licensed under the **Sovereign Resource Commons License 1.0 (SRCL-1.0)** (Apache-2.0 WITH LLVM-exception).
-Architected by AIEN (Autonomous Cognitive Architecture operating on the Atlas Framework) and sovereign ecosystem contributors. See [LICENSE](LICENSE) for full legal terms and copyright notices.
+## License
-All downstream distributions, derivative works, and commercial deployments are governed exclusively by the terms of [LICENSE](LICENSE). [CONSTITUTION.md](CONSTITUTION.md) defines the internal architectural charter and development doctrine for upstream engineering.
+Licensed under the **Sovereign Resource Commons License 1.0 (SRCL-1.0)** (Apache-2.0 WITH LLVM-exception). See [LICENSE](LICENSE) for terms.
diff --git a/mojo/libopenclaw_simd.so b/mojo/libopenclaw_simd.so
index 046ffad ..b125342 100755
Binary files a/mojo/libopenclaw_simd.so and b/mojo/libopenclaw_simd.so differ
diff --git a/mojo/openclaw_simd.mojo b/mojo/openclaw_simd.mojo
index e3c32bb ..84e7990 100644
--- a/mojo/openclaw_simd.mojo
+++ b/mojo/openclaw_simd.mojo
@@ -1,7 +1,7 @@
# OpenClaw Mojo 1.1 SIMD Vector Acceleration Kernel
-# High performance token tensor manipulation and vector similarity for Grace Blackwell GB10
+# Token tensor operations and vector similarity for Grace Blackwell GB10
-from std.math import sqrt
+from std.math import log, sqrt
@export("openclaw_simd_version")
def openclaw_simd_version() abi("C") -> Int32:
@@ -32,11 +32,11 @@ def openclaw_simd_accumulate(base_val: Float32, scale: Float32, steps: Int32) ab
@export("openclaw_token_entropy_simd")
def openclaw_token_entropy_simd(p0: Float32, p1: Float32, p2: Float32, p3: Float32) abi("C") -> Float32:
var probs = SIMD[DType.float32, 4](p0, p1, p2, p3)
- var log_probs = SIMD[DType.float32, 4](0.0, 0.0, 0.0, 0.0)
+ var entropy = SIMD[DType.float32, 4](0.0, 0.0, 0.0, 0.0)
for i in range(4):
if probs[i] > 0.00001:
- log_probs[i] = probs[i] * (probs[i] - 1.0)
- return Float32(log_probs.reduce_add())
+ entropy[i] = -probs[i] * log(probs[i])
+ return Float32(entropy.reduce_add())
@export("openclaw_token_projection_simd")
def openclaw_token_projection_simd(
diff --git a/src/main.rs b/src/main.rs
index 8905c80 ..5d41a3a 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -12,7 +12,7 @@ use tracing_subscriber::FmtSubscriber;
#[derive(Parser)]
#[command(name = "openclaw")]
#[command(version = "0.2.0")]
-#[command(about = "Ultra-high-performance sovereign agent runtime in Rust, Mojo, and Modular MAX", long_about = None)]
+#[command(about = "Native sovereign agent runtime in Rust, Mojo, and Modular MAX", long_about = None)]
struct Cli {
#[command(subcommand)]
command: Option<Commands>,
@@ -237,7 +237,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
);
let entropy = MojoSimdBridge::token_entropy([0.7, 0.2, 0.08, 0.02]);
- println!("Token Entropy Proxy: {:.6}", entropy);
+ println!("Token Entropy (Shannon): {:.6} nats", entropy);
let proj =
MojoSimdBridge::token_projection([1.0, 2.0, 3.0, 4.0], [0.5, 0.5, 0.5, 0.5], 1.0);
diff --git a/src/mojo_bridge.rs b/src/mojo_bridge.rs
index 04feb12 ..d9dd130 100644
--- a/src/mojo_bridge.rs
+++ b/src/mojo_bridge.rs
@@ -215,7 +215,7 @@ impl MojoSimdBridge {
continue;
}
if p > 0.00001 {
- sum += p * (p - 1.0);
+ sum += -p * p.ln();
}
}
sum
@@ -442,10 +442,41 @@ mod tests {
assert!((proj - expected).abs() < 1e-4);
let entropy = MojoSimdBridge::token_entropy_fallback([0.5, 0.5, 0.0, 0.0]);
- assert!(entropy < 0.0);
+ assert!((entropy - std::f32::consts::LN_2).abs() < 1e-4);
+ assert!(entropy > 0.0);
+
+ let zero_entropy = MojoSimdBridge::token_entropy_fallback([1.0, 0.0, 0.0, 0.0]);
+ assert!((zero_entropy - 0.0).abs() < 1e-4);
+
+ let uniform4_entropy = MojoSimdBridge::token_entropy_fallback([0.25, 0.25, 0.25, 0.25]);
+ assert!((uniform4_entropy - (2.0 * std::f32::consts::LN_2)).abs() < 1e-4);
// Mismatched slice length
assert_eq!(MojoSimdBridge::cosine_similarity_fallback(&[1.0, 2.0], &[1.0]), 0.0);
assert_eq!(MojoSimdBridge::cosine_similarity_fallback(&[], &[]), 0.0);
}
+
+ #[test]
+ fn test_python_analytical_parity() {
+ let fixture_path = "tests/fixtures/simd_math_vectors.json";
+ if let Ok(data) = std::fs::read_to_string(fixture_path) {
+ let v: serde_json::Value = serde_json::from_str(&data).expect("Valid JSON fixture");
+ if let Some(entropy_cases) = v.get("entropy").and_then(|e| e.as_array()) {
+ for case in entropy_cases {
+ let probs: Vec<f32> = case["probs"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|p| p.as_f64().unwrap() as f32)
+ .collect();
+ let expected = case["expected"].as_f64().unwrap() as f32;
+ let p_arr = [probs[0], probs[1], probs[2], probs[3]];
+ let fb = MojoSimdBridge::token_entropy_fallback(p_arr);
+ assert!((fb - expected).abs() < 1e-4, "Entropy fallback parity failure for {:?}", case["name"]);
+ let live = MojoSimdBridge::token_entropy(p_arr);
+ assert!((live - expected).abs() < 1e-4, "Entropy live parity failure for {:?}", case["name"]);
+ }
+ }
+ }
+ }
}
diff --git a/tests/fixtures/simd_math_vectors.json b/tests/fixtures/simd_math_vectors.json
new file mode 100644
index 0000000 ..46e3548
--- /dev/null
+++ b/tests/fixtures/simd_math_vectors.json
@@ -0,0 +1,241 @@
+{
+ "entropy": [
+ {
+ "name": "uniform_2",
+ "probs": [
+ 0.5,
+ 0.5,
+ 0.0,
+ 0.0
+ ],
+ "expected": 0.6931471805599453
+ },
+ {
+ "name": "uniform_4",
+ "probs": [
+ 0.25,
+ 0.25,
+ 0.25,
+ 0.25
+ ],
+ "expected": 1.3862943611198906
+ },
+ {
+ "name": "certainty",
+ "probs": [
+ 1.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "expected": 0.0
+ },
+ {
+ "name": "skewed",
+ "probs": [
+ 0.7,
+ 0.2,
+ 0.08,
+ 0.02
+ ],
+ "expected": 0.8518587948971561
+ },
+ {
+ "name": "sparse_single",
+ "probs": [
+ 0.0,
+ 0.0,
+ 1.0,
+ 0.0
+ ],
+ "expected": 0.0
+ },
+ {
+ "name": "all_zero",
+ "probs": [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "expected": 0.0
+ }
+ ],
+ "cosine": [
+ {
+ "name": "identical",
+ "a": [
+ 1.0,
+ 2.0,
+ 3.0,
+ 4.0
+ ],
+ "b": [
+ 1.0,
+ 2.0,
+ 3.0,
+ 4.0
+ ],
+ "expected": 1.0
+ },
+ {
+ "name": "opposite",
+ "a": [
+ 1.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "b": [
+ -1.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "expected": -1.0
+ },
+ {
+ "name": "orthogonal",
+ "a": [
+ 1.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "b": [
+ 0.0,
+ 1.0,
+ 0.0,
+ 0.0
+ ],
+ "expected": 0.0
+ },
+ {
+ "name": "zero_vector",
+ "a": [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "b": [
+ 1.0,
+ 2.0,
+ 3.0,
+ 4.0
+ ],
+ "expected": 0.0
+ },
+ {
+ "name": "mixed_positive_negative",
+ "a": [
+ 3.0,
+ -4.0,
+ 5.0,
+ -1.0
+ ],
+ "b": [
+ 3.0,
+ -4.0,
+ 5.0,
+ -1.0
+ ],
+ "expected": 0.9999999999999999
+ }
+ ],
+ "projection": [
+ {
+ "name": "standard",
+ "tokens": [
+ 1.0,
+ 2.0,
+ 3.0,
+ 4.0
+ ],
+ "weights": [
+ 0.5,
+ 0.5,
+ 0.5,
+ 0.5
+ ],
+ "bias": 1.0,
+ "expected": 6.0
+ },
+ {
+ "name": "zero_bias",
+ "tokens": [
+ 2.0,
+ 4.0,
+ 6.0,
+ 8.0
+ ],
+ "weights": [
+ 0.1,
+ 0.2,
+ 0.3,
+ 0.4
+ ],
+ "bias": 0.0,
+ "expected": 6.0
+ },
+ {
+ "name": "negative_weights",
+ "tokens": [
+ 1.0,
+ -1.0,
+ 2.0,
+ -2.0
+ ],
+ "weights": [
+ 0.5,
+ -0.5,
+ 0.5,
+ -0.5
+ ],
+ "bias": 2.5,
+ "expected": 5.5
+ }
+ ],
+ "temperature": [
+ {
+ "name": "standard_half",
+ "logit": 2.0,
+ "temp": 0.5,
+ "expected": 4.0
+ },
+ {
+ "name": "standard_double",
+ "logit": 10.0,
+ "temp": 2.0,
+ "expected": 5.0
+ },
+ {
+ "name": "zero_temp_guard",
+ "logit": 5.0,
+ "temp": 0.0,
+ "expected": 5.0
+ },
+ {
+ "name": "near_zero_temp_guard",
+ "logit": 5.0,
+ "temp": 5e-05,
+ "expected": 5.0
+ }
+ ],
+ "accumulate": [
+ {
+ "name": "short_acc",
+ "base_val": 1.0,
+ "scale": 1.05,
+ "steps": 5,
+ "expected": 23.410156139003135
+ },
+ {
+ "name": "single_step",
+ "base_val": 2.0,
+ "scale": 1.1,
+ "steps": 1,
+ "expected": 18.360000000000003
+ }
+ ]
+}
\ No newline at end of file
diff --git a/tests/openclaw_tests.rs b/tests/openclaw_tests.rs
index 18aff83 ..4c3b9a6 100644
--- a/tests/openclaw_tests.rs
+++ b/tests/openclaw_tests.rs
@@ -449,7 +449,8 @@ async fn test_mojo_simd_bridge_operations() {
assert!((proj - 7.0).abs() < 1e-4);
let entropy = MojoSimdBridge::token_entropy([0.5, 0.5, 0.0, 0.0]);
- assert!(entropy < 0.0);
+ assert!((entropy - std::f32::consts::LN_2).abs() < 1e-4);
+ assert!(entropy > 0.0);
}
#[tokio::test]
diff --git a/tests/verify_simd_math.py b/tests/verify_simd_math.py
new file mode 100755
index 0000000 ..af4abc2
--- /dev/null
+++ b/tests/verify_simd_math.py
@@ -0,0 +1,203 @@
+#!/usr/bin/env python3
+"""
+Python Mathematical Verification Oracle for OpenClaw SIMD & Mojo Kernels.
+Validates all mathematical routines against analytical ground truth in Python.
+Generates oracle test fixtures for Rust unit test consumption.
+"""
+
+import ctypes
+import json
+import math
+import os
+import sys
+
+def shannon_entropy_ref(probs):
+ h = 0.0
+ for p in probs:
+ if p > 1e-5 and math.isfinite(p):
+ h -= p * math.log(p)
+ return h
+
+def cosine_similarity_4d_ref(a, b):
+ for x in a + b:
+ if math.isnan(x) or math.isinf(x):
+ return 0.0
+ dot = sum(x * y for x, y in zip(a, b))
+ norm_a = sum(x * x for x in a)
+ norm_b = sum(x * x for x in b)
+ if norm_a <= 0.0 or norm_b <= 0.0:
+ return 0.0
+ denom = math.sqrt(norm_a) * math.sqrt(norm_b)
+ if denom <= 0.0:
+ return 0.0
+ res = dot / denom
+ if math.isnan(res) or math.isinf(res):
+ return 0.0
+ return res
+
+def token_projection_ref(tokens, weights, bias):
+ for x in tokens + weights:
+ if math.isnan(x) or math.isinf(x):
+ return 0.0
+ if math.isnan(bias) or math.isinf(bias):
+ return 0.0
+ return sum(t * w for t, w in zip(tokens, weights)) + bias
+
+def temperature_scale_ref(logit, temp):
+ if math.isnan(logit) or math.isnan(temp) or math.isinf(logit) or math.isinf(temp):
+ return 0.0
+ if temp <= 1e-4:
+ return logit
+ res = logit / temp
+ if math.isnan(res) or math.isinf(res):
+ return logit
+ return res
+
+def simd_accumulate_ref(base_val, scale, steps):
+ if math.isnan(base_val) or math.isnan(scale) or steps <= 0:
+ return 0.0
+ acc = [base_val, base_val * 1.5, base_val * 2.0, base_val * 2.5]
+ step_vec = [scale, scale * 1.1, scale * 1.2, scale * 1.3]
+ add_vec = [0.01, 0.02, 0.03, 0.04]
+ for _ in range(steps):
+ for i in range(4):
+ acc[i] = acc[i] * step_vec[i] + add_vec[i]
+ return sum(acc)
+
+def main():
+ print("==========================================================")
+ print("OpenClaw SIMD Mathematical Verification Oracle (Python 3)")
+ print("==========================================================")
+
+ # 1. Define verification test sets
+ entropy_cases = [
+ {"name": "uniform_2", "probs": [0.5, 0.5, 0.0, 0.0]},
+ {"name": "uniform_4", "probs": [0.25, 0.25, 0.25, 0.25]},
+ {"name": "certainty", "probs": [1.0, 0.0, 0.0, 0.0]},
+ {"name": "skewed", "probs": [0.7, 0.2, 0.08, 0.02]},
+ {"name": "sparse_single", "probs": [0.0, 0.0, 1.0, 0.0]},
+ {"name": "all_zero", "probs": [0.0, 0.0, 0.0, 0.0]},
+ ]
+
+ cosine_cases = [
+ {"name": "identical", "a": [1.0, 2.0, 3.0, 4.0], "b": [1.0, 2.0, 3.0, 4.0]},
+ {"name": "opposite", "a": [1.0, 0.0, 0.0, 0.0], "b": [-1.0, 0.0, 0.0, 0.0]},
+ {"name": "orthogonal", "a": [1.0, 0.0, 0.0, 0.0], "b": [0.0, 1.0, 0.0, 0.0]},
+ {"name": "zero_vector", "a": [0.0, 0.0, 0.0, 0.0], "b": [1.0, 2.0, 3.0, 4.0]},
+ {"name": "mixed_positive_negative", "a": [3.0, -4.0, 5.0, -1.0], "b": [3.0, -4.0, 5.0, -1.0]},
+ ]
+
+ projection_cases = [
+ {"name": "standard", "tokens": [1.0, 2.0, 3.0, 4.0], "weights": [0.5, 0.5, 0.5, 0.5], "bias": 1.0},
+ {"name": "zero_bias", "tokens": [2.0, 4.0, 6.0, 8.0], "weights": [0.1, 0.2, 0.3, 0.4], "bias": 0.0},
+ {"name": "negative_weights", "tokens": [1.0, -1.0, 2.0, -2.0], "weights": [0.5, -0.5, 0.5, -0.5], "bias": 2.5},
+ ]
+
+ temperature_cases = [
+ {"name": "standard_half", "logit": 2.0, "temp": 0.5},
+ {"name": "standard_double", "logit": 10.0, "temp": 2.0},
+ {"name": "zero_temp_guard", "logit": 5.0, "temp": 0.0},
+ {"name": "near_zero_temp_guard", "logit": 5.0, "temp": 0.00005},
+ ]
+
+ accumulate_cases = [
+ {"name": "short_acc", "base_val": 1.0, "scale": 1.05, "steps": 5},
+ {"name": "single_step", "base_val": 2.0, "scale": 1.1, "steps": 1},
+ ]
+
+ # Calculate expected outputs
+ for c in entropy_cases:
+ c["expected"] = shannon_entropy_ref(c["probs"])
+ assert c["expected"] >= 0.0, f"Entropy must be non-negative: {c}"
+
+ for c in cosine_cases:
+ c["expected"] = cosine_similarity_4d_ref(c["a"], c["b"])
+
+ for c in projection_cases:
+ c["expected"] = token_projection_ref(c["tokens"], c["weights"], c["bias"])
+
+ for c in temperature_cases:
+ c["expected"] = temperature_scale_ref(c["logit"], c["temp"])
+
+ for c in accumulate_cases:
+ c["expected"] = simd_accumulate_ref(c["base_val"], c["scale"], c["steps"])
+
+ # 2. Check against Mojo shared library if available
+ base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ so_path = os.path.join(base_dir, "mojo", "libopenclaw_simd.so")
+
+ if os.path.exists(so_path):
+ lib = ctypes.CDLL(so_path)
+ lib.openclaw_simd_version.restype = ctypes.c_int32
+ lib.openclaw_cosine_similarity_4d.restype = ctypes.c_float
+ lib.openclaw_cosine_similarity_4d.argtypes = [ctypes.c_float]*8
+ lib.openclaw_token_entropy_simd.restype = ctypes.c_float
+ lib.openclaw_token_entropy_simd.argtypes = [ctypes.c_float]*4
+ lib.openclaw_token_projection_simd.restype = ctypes.c_float
+ lib.openclaw_token_projection_simd.argtypes = [ctypes.c_float]*9
+ lib.openclaw_temperature_scale_simd.restype = ctypes.c_float
+ lib.openclaw_temperature_scale_simd.argtypes = [ctypes.c_float]*2
+ lib.openclaw_simd_accumulate.restype = ctypes.c_float
+ lib.openclaw_simd_accumulate.argtypes = [ctypes.c_float, ctypes.c_float, ctypes.c_int32]
+
+ print(f"Loaded Mojo SIMD library: {so_path}")
+ print(f"SIMD Version: {lib.openclaw_simd_version()}")
+
+ # Verify Entropy
+ for c in entropy_cases:
+ got = lib.openclaw_token_entropy_simd(*c["probs"])
+ diff = abs(got - c["expected"])
+ print(f" [ENTROPY] {c['name']:<15} expected={c['expected']:.6f} got={got:.6f} diff={diff:.2e}")
+ assert diff < 1e-4, f"Mojo entropy mismatch for {c['name']}: {got} vs {c['expected']}"
+
+ # Verify Cosine
+ for c in cosine_cases:
+ got = lib.openclaw_cosine_similarity_4d(*(c["a"] + c["b"]))
+ diff = abs(got - c["expected"])
+ print(f" [COSINE] {c['name']:<15} expected={c['expected']:.6f} got={got:.6f} diff={diff:.2e}")
+ assert diff < 1e-4, f"Mojo cosine mismatch for {c['name']}: {got} vs {c['expected']}"
+
+ # Verify Projection
+ for c in projection_cases:
+ got = lib.openclaw_token_projection_simd(*(c["tokens"] + c["weights"] + [c["bias"]]))
+ diff = abs(got - c["expected"])
+ print(f" [PROJ] {c['name']:<15} expected={c['expected']:.6f} got={got:.6f} diff={diff:.2e}")
+ assert diff < 1e-4, f"Mojo projection mismatch for {c['name']}: {got} vs {c['expected']}"
+
+ # Verify Temperature
+ for c in temperature_cases:
+ got = lib.openclaw_temperature_scale_simd(c["logit"], c["temp"])
+ diff = abs(got - c["expected"])
+ print(f" [TEMP] {c['name']:<15} expected={c['expected']:.6f} got={got:.6f} diff={diff:.2e}")
+ assert diff < 1e-4, f"Mojo temperature mismatch for {c['name']}: {got} vs {c['expected']}"
+
+ # Verify Accumulate
+ for c in accumulate_cases:
+ got = lib.openclaw_simd_accumulate(c["base_val"], c["scale"], c["steps"])
+ diff = abs(got - c["expected"])
+ print(f" [ACCUM] {c['name']:<15} expected={c['expected']:.6f} got={got:.6f} diff={diff:.2e}")
+ assert diff < 1e-4, f"Mojo accumulate mismatch for {c['name']}: {got} vs {c['expected']}"
+
+ print("All Mojo SIMD routines matched Python analytical reference within 1e-4.")
+
+ # 3. Export fixtures for Rust test suite
+ fixtures_dir = os.path.join(base_dir, "tests", "fixtures")
+ os.makedirs(fixtures_dir, exist_ok=True)
+ out_file = os.path.join(fixtures_dir, "simd_math_vectors.json")
+
+ payload = {
+ "entropy": entropy_cases,
+ "cosine": cosine_cases,
+ "projection": projection_cases,
+ "temperature": temperature_cases,
+ "accumulate": accumulate_cases,
+ }
+
+ with open(out_file, "w") as f:
+ json.dump(payload, f, indent=2)
+
+ print(f"Exported analytical test fixtures to: {out_file}")
+ print("Python Mathematical Verification: SUCCESS.")
+
+if __name__ == "__main__":
+ main()