Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/openclaw-rs/blob/main/src/mojo_bridge.rs # openclaw-rs High-performance sovereign agent runtime in native Rust and Mojo for NVIDIA DGX Spark Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `openclaw-rs / src / mojo_bridge.rs` 446 lines ยท 15638 bytes Raw Blame History 1 use libloading::{Library, Symbol}; 2 use std::path::{Path, PathBuf}; 3 use std::sync::OnceLock; 4 5 pub const DEFAULT_SO_PATH: &str = 6 "/home/drakestapleton/workspace/openclaw-rs/mojo/libopenclaw_simd.so"; 7 8 pub fn default_so_path() -> PathBuf { 9 if let Ok(p) = std::env::var("OPENCLAW_SIMD_SO_PATH") { 10 let pb = PathBuf::from(p); 11 if pb.exists() { 12 return pb; 13 } 14 } 15 if let Some(p) = option_env!("OPENCLAW_SIMD_SO_BUILT") { 16 let pb = PathBuf::from(p); 17 if pb.exists() { 18 return pb; 19 } 20 } 21 let local = PathBuf::from("mojo/libopenclaw_simd.so"); 22 if local.exists() { 23 return local; 24 } 25 if let Ok(manifest) = std::env::var("CARGO_MANIFEST_DIR") { 26 let candidate = PathBuf::from(manifest).join("mojo/libopenclaw_simd.so"); 27 if candidate.exists() { 28 return candidate; 29 } 30 } 31 PathBuf::from(DEFAULT_SO_PATH) 32 } 33 34 type FnVersion = unsafe extern "C" fn() -> i32; 35 type FnCosineSim4d = unsafe extern "C" fn(f32, f32, f32, f32, f32, f32, f32, f32) -> f32; 36 type FnSimdAccumulate = unsafe extern "C" fn(f32, f32, i32) -> f32; 37 type FnTokenEntropy = unsafe extern "C" fn(f32, f32, f32, f32) -> f32; 38 type FnTokenProjection = unsafe extern "C" fn(f32, f32, f32, f32, f32, f32, f32, f32, f32) -> f32; 39 type FnTemperatureScale = unsafe extern "C" fn(f32, f32) -> f32; 40 41 pub struct MojoSimdBindings { 42 _lib: &'static Library, 43 pub version: FnVersion, 44 pub cosine_similarity_4d: FnCosineSim4d, 45 pub simd_accumulate: FnSimdAccumulate, 46 pub token_entropy_simd: FnTokenEntropy, 47 pub token_projection_simd: FnTokenProjection, 48 pub temperature_scale_simd: FnTemperatureScale, 49 } 50 51 static BINDINGS: OnceLock> = OnceLock::new(); 52 53 impl MojoSimdBindings { 54 pub fn load_from>(path: P) -> Result { 55 let p = path.as_ref(); 56 if !p.exists() { 57 return Err(format!("Mojo SIMD library not found at {:?}", p)); 58 } 59 60 unsafe { 61 let lib: &'static Library = Box::leak(Box::new( 62 Library::new(p).map_err(|e| format!("Failed to dlopen {:?}: {}", p, e))?, 63 )); 64 65 let version: Symbol = lib 66 .get(b"openclaw_simd_version\0") 67 .map_err(|e| format!("Missing symbol openclaw_simd_version: {}", e))?; 68 let cosine_similarity_4d: Symbol = lib 69 .get(b"openclaw_cosine_similarity_4d\0") 70 .map_err(|e| format!("Missing symbol openclaw_cosine_similarity_4d: {}", e))?; 71 let simd_accumulate: Symbol = lib 72 .get(b"openclaw_simd_accumulate\0") 73 .map_err(|e| format!("Missing symbol openclaw_simd_accumulate: {}", e))?; 74 let token_entropy_simd: Symbol = lib 75 .get(b"openclaw_token_entropy_simd\0") 76 .map_err(|e| format!("Missing symbol openclaw_token_entropy_simd: {}", e))?; 77 let token_projection_simd: Symbol = lib 78 .get(b"openclaw_token_projection_simd\0") 79 .map_err(|e| format!("Missing symbol openclaw_token_projection_simd: {}", e))?; 80 let temperature_scale_simd: Symbol = lib 81 .get(b"openclaw_temperature_scale_simd\0") 82 .map_err(|e| format!("Missing symbol openclaw_temperature_scale_simd: {}", e))?; 83 84 Ok(Self { 85 version: *version, 86 cosine_similarity_4d: *cosine_similarity_4d, 87 simd_accumulate: *simd_accumulate, 88 token_entropy_simd: *token_entropy_simd, 89 token_projection_simd: *token_projection_simd, 90 temperature_scale_simd: *temperature_scale_simd, 91 _lib: lib, 92 }) 93 } 94 } 95 96 pub fn global() -> Result<&'static Self, String> { 97 let res = BINDINGS.get_or_init(|| { 98 let path = default_so_path(); 99 Self::load_from(path) 100 }); 101 102 match res { 103 Ok(ref b) => Ok(b), 104 Err(ref e) => Err(e.clone()), 105 } 106 } 107 } 108 109 pub struct MojoSimdBridge; 110 111 impl MojoSimdBridge { 112 pub fn is_mojo_accelerated() -> bool { 113 MojoSimdBindings::global().is_ok() 114 } 115 116 pub fn version() -> i32 { 117 if let Ok(b) = MojoSimdBindings::global() { 118 unsafe { (b.version)() } 119 } else { 120 0 121 } 122 } 123 124 pub fn cosine_similarity_4d_fallback(a: [f32; 4], b: [f32; 4]) -> f32 { 125 for i in 0..4 { 126 if a[i].is_nan() || b[i].is_nan() || a[i].is_infinite() || b[i].is_infinite() { 127 return 0.0; 128 } 129 } 130 let dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; 131 let norm_a = a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3]; 132 let norm_b = b[0] * b[0] + b[1] * b[1] + b[2] * b[2] + b[3] * b[3]; 133 if norm_a <= 0.0 || norm_b <= 0.0 || norm_a.is_nan() || norm_b.is_nan() { 134 0.0 135 } else { 136 let denom = norm_a.sqrt() * norm_b.sqrt(); 137 if denom <= 0.0 || denom.is_nan() { 138 0.0 139 } else { 140 let res = dot / denom; 141 if res.is_nan() || res.is_infinite() { 142 0.0 143 } else { 144 res 145 } 146 } 147 } 148 } 149 150 pub fn cosine_similarity_fallback(a: &[f32], b: &[f32]) -> f32 { 151 if a.len() != b.len() || a.is_empty() { 152 return 0.0; 153 } 154 155 if a.len() == 4 { 156 let a_arr = [a[0], a[1], a[2], a[3]]; 157 let b_arr = [b[0], b[1], b[2], b[3]]; 158 return Self::cosine_similarity_4d_fallback(a_arr, b_arr); 159 } 160 161 let mut dot = 0.0f32; 162 let mut norm_a = 0.0f32; 163 let mut norm_b = 0.0f32; 164 165 for i in 0..a.len() { 166 if a[i].is_nan() || b[i].is_nan() || a[i].is_infinite() || b[i].is_infinite() { 167 return 0.0; 168 } 169 dot += a[i] * b[i]; 170 norm_a += a[i] * a[i]; 171 norm_b += b[i] * b[i]; 172 } 173 174 if norm_a <= 0.0 || norm_b <= 0.0 || norm_a.is_nan() || norm_b.is_nan() { 175 return 0.0; 176 } 177 178 let denom = norm_a.sqrt() * norm_b.sqrt(); 179 if denom <= 0.0 || denom.is_nan() { 180 return 0.0; 181 } 182 183 let res = dot / denom; 184 if res.is_nan() || res.is_infinite() { 185 0.0 186 } else { 187 res 188 } 189 } 190 191 pub fn simd_accumulate_fallback(base_val: f32, scale: f32, steps: i32) -> f32 { 192 if base_val.is_nan() || scale.is_nan() || steps <= 0 { 193 return 0.0; 194 } 195 let mut acc = [base_val, base_val * 1.5, base_val * 2.0, base_val * 2.5]; 196 let step_vec = [scale, scale * 1.1, scale * 1.2, scale * 1.3]; 197 let add_vec = [0.01f32, 0.02, 0.03, 0.04]; 198 for _ in 0..steps { 199 for i in 0..4 { 200 acc[i] = acc[i] * step_vec[i] + add_vec[i]; 201 } 202 } 203 acc.iter().sum() 204 } 205 206 pub fn token_entropy_fallback(probs: [f32; 4]) -> f32 { 207 let mut sum = 0.0f32; 208 for p in probs { 209 if p.is_nan() || p.is_infinite() { 210 continue; 211 } 212 if p > 0.00001 { 213 sum += p * (p - 1.0); 214 } 215 } 216 sum 217 } 218 219 pub fn token_projection_fallback(tokens: [f32; 4], weights: [f32; 4], bias: f32) -> f32 { 220 for i in 0..4 { 221 if tokens[i].is_nan() || weights[i].is_nan() || tokens[i].is_infinite() || weights[i].is_infinite() { 222 return 0.0; 223 } 224 } 225 if bias.is_nan() || bias.is_infinite() { 226 return 0.0; 227 } 228 tokens[0] * weights[0] 229 + tokens[1] * weights[1] 230 + tokens[2] * weights[2] 231 + tokens[3] * weights[3] 232 + bias 233 } 234 235 pub fn temperature_scale_fallback(logit: f32, temperature: f32) -> f32 { 236 if logit.is_nan() || temperature.is_nan() || logit.is_infinite() || temperature.is_infinite() { 237 return 0.0; 238 } 239 if temperature <= 0.0001 { 240 logit 241 } else { 242 let res = logit / temperature; 243 if res.is_nan() || res.is_infinite() { 244 logit 245 } else { 246 res 247 } 248 } 249 } 250 251 pub fn cosine_similarity_4d(a: [f32; 4], b: [f32; 4]) -> f32 { 252 if let Ok(bindings) = MojoSimdBindings::global() { 253 unsafe { 254 (bindings.cosine_similarity_4d)(a[0], a[1], a[2], a[3], b[0], b[1], b[2], b[3]) 255 } 256 } else { 257 Self::cosine_similarity_4d_fallback(a, b) 258 } 259 } 260 261 pub fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 { 262 if a.len() != b.len() || a.is_empty() { 263 return 0.0; 264 } 265 266 if a.len() == 4 { 267 let a_arr = [a[0], a[1], a[2], a[3]]; 268 let b_arr = [b[0], b[1], b[2], b[3]]; 269 return Self::cosine_similarity_4d(a_arr, b_arr); 270 } 271 272 Self::cosine_similarity_fallback(a, b) 273 } 274 275 pub fn simd_accumulate(base_val: f32, scale: f32, steps: i32) -> f32 { 276 if let Ok(bindings) = MojoSimdBindings::global() { 277 unsafe { (bindings.simd_accumulate)(base_val, scale, steps) } 278 } else { 279 Self::simd_accumulate_fallback(base_val, scale, steps) 280 } 281 } 282 283 pub fn token_entropy(probs: [f32; 4]) -> f32 { 284 if let Ok(bindings) = MojoSimdBindings::global() { 285 unsafe { (bindings.token_entropy_simd)(probs[0], probs[1], probs[2], probs[3]) } 286 } else { 287 Self::token_entropy_fallback(probs) 288 } 289 } 290 291 pub fn token_projection(tokens: [f32; 4], weights: [f32; 4], bias: f32) -> f32 { 292 if let Ok(bindings) = MojoSimdBindings::global() { 293 unsafe { 294 (bindings.token_projection_simd)( 295 tokens[0], tokens[1], tokens[2], tokens[3], weights[0], weights[1], weights[2], 296 weights[3], bias, 297 ) 298 } 299 } else { 300 Self::token_projection_fallback(tokens, weights, bias) 301 } 302 } 303 304 pub fn temperature_scale(logit: f32, temperature: f32) -> f32 { 305 if let Ok(bindings) = MojoSimdBindings::global() { 306 unsafe { (bindings.temperature_scale_simd)(logit, temperature) } 307 } else { 308 Self::temperature_scale_fallback(logit, temperature) 309 } 310 } 311 312 pub fn l2_norm(vec: &[f32]) -> f32 { 313 let sum: f32 = vec.iter().map(|v| v * v).sum(); 314 sum.sqrt() 315 } 316 } 317 318 #[cfg(test)] 319 mod tests { 320 use super::*; 321 322 #[test] 323 fn test_mojo_simd_version_or_fallback() { 324 let ver = MojoSimdBridge::version(); 325 assert!(ver == 101 || ver == 0); 326 } 327 328 #[test] 329 fn test_cosine_similarity() { 330 let v1 = vec![1.0, 0.0, 0.0, 0.0]; 331 let v2 = vec![1.0, 0.0, 0.0, 0.0]; 332 let sim = MojoSimdBridge::cosine_similarity(&v1, &v2); 333 assert!((sim - 1.0).abs() < 1e-4); 334 335 let v3 = vec![0.0, 1.0, 0.0, 0.0]; 336 let orthogonal = MojoSimdBridge::cosine_similarity(&v1, &v3); 337 assert!((orthogonal - 0.0).abs() < 1e-4); 338 } 339 340 #[test] 341 fn test_token_projection() { 342 let tokens = [1.0, 2.0, 3.0, 4.0]; 343 let weights = [0.5, 0.5, 0.5, 0.5]; 344 let bias = 1.0; 345 let proj = MojoSimdBridge::token_projection(tokens, weights, bias); 346 let expected = 1.0 * 0.5 + 2.0 * 0.5 + 3.0 * 0.5 + 4.0 * 0.5 + 1.0; 347 assert!((proj - expected).abs() < 1e-4); 348 } 349 350 #[test] 351 fn test_temperature_scale() { 352 let scaled = MojoSimdBridge::temperature_scale(2.0, 0.5); 353 assert!((scaled - 4.0).abs() < 1e-4); 354 } 355 356 #[test] 357 fn test_fallback_zero_vectors() { 358 let zero = [0.0f32, 0.0, 0.0, 0.0]; 359 let non_zero = [1.0f32, 2.0, 3.0, 4.0]; 360 let sim1 = MojoSimdBridge::cosine_similarity_4d_fallback(zero, non_zero); 361 assert_eq!(sim1, 0.0); 362 363 let sim2 = MojoSimdBridge::cosine_similarity_4d_fallback(zero, zero); 364 assert_eq!(sim2, 0.0); 365 366 let zero_slice = vec![0.0f32; 8]; 367 let non_zero_slice = vec![1.0f32; 8]; 368 assert_eq!(MojoSimdBridge::cosine_similarity_fallback(&zero_slice, &non_zero_slice), 0.0); 369 } 370 371 #[test] 372 fn test_fallback_identical_and_opposite_vectors() { 373 let v1 = [3.0f32, -4.0, 5.0, -1.0]; 374 let sim_ident = MojoSimdBridge::cosine_similarity_4d_fallback(v1, v1); 375 assert!((sim_ident - 1.0).abs() < 1e-4); 376 377 let v_opp = [-3.0f32, 4.0, -5.0, 1.0]; 378 let sim_opp = MojoSimdBridge::cosine_similarity_4d_fallback(v1, v_opp); 379 assert!((sim_opp - (-1.0)).abs() < 1e-4); 380 } 381 382 #[test] 383 fn test_fallback_orthogonal_vectors() { 384 let v1 = [1.0f32, 0.0, 0.0, 0.0]; 385 let v2 = [0.0f32, 1.0, 0.0, 0.0]; 386 let sim = MojoSimdBridge::cosine_similarity_4d_fallback(v1, v2); 387 assert_eq!(sim, 0.0); 388 389 let v3 = [0.0f32, 0.0, 1.0, 0.0]; 390 let v4 = [0.0f32, 0.0, 0.0, 1.0]; 391 assert_eq!(MojoSimdBridge::cosine_similarity_4d_fallback(v3, v4), 0.0); 392 } 393 394 #[test] 395 fn test_fallback_nan_and_inf_handling() { 396 let nan_vec = [f32::NAN, 1.0, 2.0, 3.0]; 397 let normal_vec = [1.0f32, 2.0, 3.0, 4.0]; 398 assert_eq!(MojoSimdBridge::cosine_similarity_4d_fallback(nan_vec, normal_vec), 0.0); 399 400 let inf_vec = [f32::INFINITY, 1.0, 2.0, 3.0]; 401 assert_eq!(MojoSimdBridge::cosine_similarity_4d_fallback(inf_vec, normal_vec), 0.0); 402 403 let neg_inf_vec = [f32::NEG_INFINITY, 1.0, 2.0, 3.0]; 404 assert_eq!(MojoSimdBridge::cosine_similarity_4d_fallback(neg_inf_vec, normal_vec), 0.0); 405 406 // Token projection with NaN/Inf 407 assert_eq!(MojoSimdBridge::token_projection_fallback(nan_vec, normal_vec, 1.0), 0.0); 408 assert_eq!(MojoSimdBridge::token_projection_fallback(normal_vec, normal_vec, f32::NAN), 0.0); 409 410 // Temperature scale with NaN/Inf 411 assert_eq!(MojoSimdBridge::temperature_scale_fallback(f32::NAN, 1.0), 0.0); 412 assert_eq!(MojoSimdBridge::temperature_scale_fallback(2.0, f32::NAN), 0.0); 413 assert_eq!(MojoSimdBridge::temperature_scale_fallback(2.0, f32::INFINITY), 0.0); 414 } 415 416 #[test] 417 fn test_fallback_temperature_scale_edge_cases() { 418 // Zero or near-zero temperature should return unscaled logit 419 assert_eq!(MojoSimdBridge::temperature_scale_fallback(5.0, 0.0), 5.0); 420 assert_eq!(MojoSimdBridge::temperature_scale_fallback(5.0, 0.00005), 5.0); 421 422 // Normal scaling 423 let scaled = MojoSimdBridge::temperature_scale_fallback(10.0, 2.0); 424 assert!((scaled - 5.0).abs() < 1e-4); 425 426 let low_temp = MojoSimdBridge::temperature_scale_fallback(10.0, 0.5); 427 assert!((low_temp - 20.0).abs() < 1e-4); 428 } 429 430 #[test] 431 fn test_fallback_token_projection_and_entropy() { 432 let tokens = [2.0f32, 4.0, 6.0, 8.0]; 433 let weights = [0.1f32, 0.2, 0.3, 0.4]; 434 let bias = 0.5f32; 435 let proj = MojoSimdBridge::token_projection_fallback(tokens, weights, bias); 436 let expected = 2.0 * 0.1 + 4.0 * 0.2 + 6.0 * 0.3 + 8.0 * 0.4 + 0.5; 437 assert!((proj - expected).abs() < 1e-4); 438 439 let entropy = MojoSimdBridge::token_entropy_fallback([0.5, 0.5, 0.0, 0.0]); 440 assert!(entropy < 0.0); 441 442 // Mismatched slice length 443 assert_eq!(MojoSimdBridge::cosine_similarity_fallback(&[1.0, 2.0], &[1.0]), 0.0); 444 assert_eq!(MojoSimdBridge::cosine_similarity_fallback(&[], &[]), 0.0); 445 } 446 }