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/aien-sovereign-core-mv/blob/main/crates/cortex-rs/src/embeddings.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / cortex-rs / src / embeddings.rs` 287 lines ยท 9769 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 use aien_localhttp::Client; 17 use serde_json::json; 18 use std::time::Duration; 19 20 pub const EMBEDDING_DIMENSIONS: usize = 768; 21 22 pub fn embedding_to_bytes(v: &[f32]) -> Vec { 23 let mut bytes = Vec::with_capacity(v.len() * 4); 24 for &f in v { 25 bytes.extend_from_slice(&f.to_le_bytes()); 26 } 27 bytes 28 } 29 30 #[allow(clippy::chunks_exact_to_as_chunks)] 31 pub fn bytes_to_embedding(b: &[u8]) -> Vec { 32 let mut v = Vec::with_capacity(b.len() / 4); 33 for chunk in b.chunks_exact(4) { 34 let arr: [u8; 4] = [chunk[0], chunk[1], chunk[2], chunk[3]]; 35 v.push(f32::from_le_bytes(arr)); 36 } 37 v 38 } 39 40 pub fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 { 41 if a.len() != b.len() || a.is_empty() { 42 return 0.0; 43 } 44 let mut dot = 0.0f32; 45 let mut norm_a = 0.0f32; 46 let mut norm_b = 0.0f32; 47 for i in 0..a.len() { 48 dot += a[i] * b[i]; 49 norm_a += a[i] * a[i]; 50 norm_b += b[i] * b[i]; 51 } 52 let denom = norm_a.sqrt() * norm_b.sqrt(); 53 if denom > 0.0 { 54 dot / denom 55 } else { 56 0.0 57 } 58 } 59 60 #[allow(dead_code)] 61 pub fn cosine_distance(a: &[f32], b: &[f32]) -> f32 { 62 1.0 - cosine_similarity(a, b) 63 } 64 65 /// Checks that `encoder_url` is a plain `http://` URL the encoder client can 66 /// call. An `https://` URL is refused: the client never speaks TLS. 67 pub fn validate_encoder_url(encoder_url: &str) -> Result<(), String> { 68 aien_localhttp::Url::parse(&format!("{}/embed", encoder_url.trim_end_matches("/"))) 69 .map(|_| ()) 70 .map_err(|e| format!("--encoder-url {encoder_url:?} is not usable: {e}")) 71 } 72 73 pub async fn fetch_embedding( 74 client: &Client, 75 text: &str, 76 encoder_url: &str, 77 ) -> Result, String> { 78 let payload = json!({ 79 "text": text, 80 "modelId": "BAAI/bge-base-en-v1.5", 81 "modelRevision": "cortex-bge-base-en-v1.5-768-v1", 82 "priority": "recall" 83 }); 84 85 let resp = client 86 .post(format!("{}/embed", encoder_url.trim_end_matches("/"))) 87 .timeout(Duration::from_millis(1500)) 88 .json(&payload) 89 .send() 90 .await 91 .map_err(|e| { 92 format!( 93 "Failed to connect to embedding encoder on {}: {}", 94 encoder_url, e 95 ) 96 })?; 97 98 if !resp.status().is_success() { 99 let status = resp.status(); 100 let body = resp.text().await.unwrap_or_default(); 101 return Err(format!("Encoder returned error HTTP {}: {}", status, body)); 102 } 103 104 let val: serde_json::Value = resp 105 .json() 106 .await 107 .map_err(|e| format!("Failed to parse embedding response JSON: {}", e))?; 108 109 if let Some(arr) = val.get("embedding").and_then(|v| v.as_array()) { 110 let mut emb = Vec::with_capacity(arr.len()); 111 for num in arr { 112 if let Some(f) = num.as_f64() { 113 emb.push(f as f32); 114 } 115 } 116 if emb.len() == EMBEDDING_DIMENSIONS { 117 return Ok(emb); 118 } else { 119 return Err(format!( 120 "Expected {} dimensions, got {}", 121 EMBEDDING_DIMENSIONS, 122 emb.len() 123 )); 124 } 125 } 126 127 Err("Invalid embedding payload structure from encoder service".to_string()) 128 } 129 130 #[cfg(test)] 131 mod tests { 132 use super::*; 133 134 #[test] 135 fn test_embedding_bytes_roundtrip() { 136 let orig = vec![0.123f32, -0.456, 0.789, 1.0]; 137 let bytes = embedding_to_bytes(&orig); 138 assert_eq!(bytes.len(), 16); 139 let recovered = bytes_to_embedding(&bytes); 140 assert_eq!(orig, recovered); 141 } 142 143 #[test] 144 fn test_cosine_similarity() { 145 let a = vec![1.0f32, 0.0, 0.0]; 146 let b = vec![1.0f32, 0.0, 0.0]; 147 assert!((cosine_similarity(&a, &b) - 1.0).abs() < 1e-5); 148 149 let c = vec![0.0f32, 1.0, 0.0]; 150 assert!((cosine_similarity(&a, &c) - 0.0).abs() < 1e-5); 151 } 152 153 #[test] 154 fn test_cosine_distance_and_empty_handling() { 155 let a = vec![1.0f32, 0.0, 0.0]; 156 let b = vec![1.0f32, 0.0, 0.0]; 157 assert!((cosine_distance(&a, &b) - 0.0).abs() < 1e-5); 158 159 let orthogonal = vec![0.0f32, 1.0, 0.0]; 160 assert!((cosine_distance(&a, &orthogonal) - 1.0).abs() < 1e-5); 161 162 let opposite = vec![-1.0f32, 0.0, 0.0]; 163 assert!((cosine_distance(&a, &opposite) - 2.0).abs() < 1e-5); 164 165 let empty: Vec = vec![]; 166 assert_eq!(cosine_similarity(&empty, &empty), 0.0); 167 assert_eq!(cosine_distance(&empty, &empty), 1.0); 168 169 let mismatched = vec![1.0f32, 0.0]; 170 assert_eq!(cosine_similarity(&a, &mismatched), 0.0); 171 assert_eq!(cosine_distance(&a, &mismatched), 1.0); 172 173 let zeros = vec![0.0f32, 0.0, 0.0]; 174 assert_eq!(cosine_similarity(&zeros, &zeros), 0.0); 175 assert_eq!(cosine_distance(&zeros, &zeros), 1.0); 176 } 177 178 use aien_localhttp::test_server::{closed_port, response, serve_once, serve_silent}; 179 180 fn embedding_body(dims: usize) -> String { 181 let values = vec!["0.5"; dims].join(","); 182 format!("{{\"embedding\":[{values}]}}") 183 } 184 185 #[tokio::test] 186 async fn fetch_embedding_posts_the_same_request_and_reads_768_dims() { 187 let (base, server) = 188 serve_once(response("200 OK", "application/json", &embedding_body(768))).await; 189 // A trailing slash is trimmed before /embed, as before. 190 let emb = fetch_embedding(&Client::new(), "hello", &format!("{base}/")) 191 .await 192 .unwrap(); 193 assert_eq!(emb.len(), EMBEDDING_DIMENSIONS); 194 assert_eq!(emb[0], 0.5); 195 let request = server.await.unwrap(); 196 assert!(request.starts_with("POST /embed HTTP/1.1\r\n"), "{request}"); 197 assert!(request.contains("\r\nContent-Type: application/json\r\n")); 198 let body: serde_json::Value = 199 serde_json::from_str(request.split("\r\n\r\n").nth(1).unwrap()).unwrap(); 200 assert_eq!( 201 body, 202 json!({ 203 "text": "hello", 204 "modelId": "BAAI/bge-base-en-v1.5", 205 "modelRevision": "cortex-bge-base-en-v1.5-768-v1", 206 "priority": "recall" 207 }) 208 ); 209 } 210 211 #[tokio::test] 212 async fn fetch_embedding_error_status_keeps_the_old_message() { 213 let (base, _server) = 214 serve_once(response("503 Service Unavailable", "text/plain", "busy")).await; 215 let error = fetch_embedding(&Client::new(), "x", &base) 216 .await 217 .unwrap_err(); 218 assert_eq!( 219 error, 220 "Encoder returned error HTTP 503 Service Unavailable: busy" 221 ); 222 } 223 224 #[tokio::test] 225 async fn fetch_embedding_rejects_wrong_dimensions_and_bad_json() { 226 let (base, _server) = 227 serve_once(response("200 OK", "application/json", &embedding_body(3))).await; 228 let error = fetch_embedding(&Client::new(), "x", &base) 229 .await 230 .unwrap_err(); 231 assert_eq!(error, "Expected 768 dimensions, got 3"); 232 233 let (base, _server) = serve_once(response("200 OK", "application/json", "nope")).await; 234 let error = fetch_embedding(&Client::new(), "x", &base) 235 .await 236 .unwrap_err(); 237 assert!( 238 error.starts_with("Failed to parse embedding response JSON"), 239 "{error}" 240 ); 241 242 let (base, _server) = 243 serve_once(response("200 OK", "application/json", "{\"other\":1}")).await; 244 let error = fetch_embedding(&Client::new(), "x", &base) 245 .await 246 .unwrap_err(); 247 assert_eq!( 248 error, 249 "Invalid embedding payload structure from encoder service" 250 ); 251 } 252 253 #[tokio::test] 254 async fn fetch_embedding_reports_refused_and_timed_out_encoders() { 255 let base = closed_port().await; 256 let error = fetch_embedding(&Client::new(), "x", &base) 257 .await 258 .unwrap_err(); 259 assert!( 260 error.starts_with(&format!("Failed to connect to embedding encoder on {base}")), 261 "{error}" 262 ); 263 264 // The 1500 ms per-request timeout still bounds a silent encoder. 265 let (base, _server) = serve_silent().await; 266 let started = std::time::Instant::now(); 267 let error = fetch_embedding(&Client::new(), "x", &base) 268 .await 269 .unwrap_err(); 270 assert!(error.contains("timed out"), "{error}"); 271 assert!(started.elapsed() < Duration::from_secs(5)); 272 } 273 274 #[tokio::test] 275 async fn https_encoder_is_refused_at_validation_and_at_call_time() { 276 assert!(validate_encoder_url("http://127.0.0.1:18081").is_ok()); 277 assert!(validate_encoder_url("http://127.0.0.1:18081/").is_ok()); 278 let error = validate_encoder_url("https://encoder.example").unwrap_err(); 279 assert!(error.contains("https is refused"), "{error}"); 280 assert!(validate_encoder_url("127.0.0.1:18081").is_err()); 281 282 let error = fetch_embedding(&Client::new(), "x", "https://127.0.0.1:1") 283 .await 284 .unwrap_err(); 285 assert!(error.contains("https is refused"), "{error}"); 286 } 287 }