aien-sovereign-core
Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark
Brought by drakestapleton
aien-sovereign-core / crates / cortex-encoder-rs / src / main.rs
| 1 | use axum::{ |
| 2 | extract::State, |
| 3 | http::StatusCode, |
| 4 | response::IntoResponse, |
| 5 | routing::{get, post}, |
| 6 | Json, Router, |
| 7 | }; |
| 8 | use clap::Parser; |
| 9 | use ort::session::{builder::GraphOptimizationLevel, Session}; |
| 10 | use serde::{Deserialize, Serialize}; |
| 11 | use serde_json::json; |
| 12 | use std::net::SocketAddr; |
| 13 | use std::sync::Arc; |
| 14 | use std::time::Instant; |
| 15 | use tokio::sync::Mutex; |
| 16 | use tokenizers::Tokenizer; |
| 17 | use tower_http::cors::CorsLayer; |
| 18 | use tracing::info; |
| 19 | use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; |
| 20 | |
| 21 | pub const MODEL_ID: &str = "BAAI/bge-base-en-v1.5"; |
| 22 | pub const MODEL_REVISION: &str = "cortex-bge-base-en-v1.5-768-v1"; |
| 23 | pub const ONNX_RUNTIME_LIB: &str = |
| 24 | "/home/drakestapleton/max-env/lib/python3.12/site-packages/onnxruntime/capi/libonnxruntime.so.1.30.0"; |
| 25 | pub const EMBED_DIR: &str = |
| 26 | "/home/drakestapleton/.cache/huggingface/hub/models--Xenova--bge-base-en-v1.5/snapshots/4d6cd88e18e51a5e020c2c305726d76ada9c03cf"; |
| 27 | pub const RERANK_DIR: &str = |
| 28 | "/home/drakestapleton/.cache/huggingface/hub/models--Xenova--bge-reranker-base/snapshots/280bcc27a84e0b898c251e06fddb25171bd9b101"; |
| 29 | |
| 30 | #[derive(Parser, Debug)] |
| 31 | #[command(name = "cortex-encoder-rs", about = "Native Rust and ONNX Runtime C-API embedding and reranking engine")] |
| 32 | pub struct Cli { |
| 33 | #[arg(short, long, default_value = "18081")] |
| 34 | pub port: u16, |
| 35 | |
| 36 | #[arg(long, default_value = "127.0.0.1")] |
| 37 | pub host: String, |
| 38 | } |
| 39 | |
| 40 | #[derive(Clone)] |
| 41 | pub struct AppState { |
| 42 | pub embed_session: Arc<Mutex<Session>>, |
| 43 | pub embed_tokenizer: Arc<Tokenizer>, |
| 44 | pub rerank_session: Arc<Mutex<Session>>, |
| 45 | pub rerank_tokenizer: Arc<Tokenizer>, |
| 46 | } |
| 47 | |
| 48 | #[derive(Debug, Deserialize)] |
| 49 | pub struct EmbedRequest { |
| 50 | pub text: String, |
| 51 | #[serde(rename = "modelId")] |
| 52 | pub _model_id: Option<String>, |
| 53 | #[serde(rename = "modelRevision")] |
| 54 | pub _model_revision: Option<String>, |
| 55 | #[serde(rename = "priority")] |
| 56 | pub _priority: Option<String>, |
| 57 | } |
| 58 | |
| 59 | #[derive(Debug, Serialize)] |
| 60 | pub struct EmbedResponse { |
| 61 | pub embedding: Vec<f32>, |
| 62 | #[serde(rename = "modelId")] |
| 63 | pub model_id: &'static str, |
| 64 | #[serde(rename = "modelRevision")] |
| 65 | pub model_revision: &'static str, |
| 66 | #[serde(rename = "elapsedMs")] |
| 67 | pub elapsed_ms: f64, |
| 68 | } |
| 69 | |
| 70 | #[derive(Debug, Deserialize)] |
| 71 | pub struct RerankRequest { |
| 72 | pub query: String, |
| 73 | pub passages: Vec<String>, |
| 74 | } |
| 75 | |
| 76 | #[derive(Debug, Serialize)] |
| 77 | pub struct RerankResponse { |
| 78 | pub scores: Vec<f32>, |
| 79 | pub count: usize, |
| 80 | #[serde(rename = "elapsedMs")] |
| 81 | pub elapsed_ms: f64, |
| 82 | } |
| 83 | |
| 84 | #[derive(Debug, Deserialize)] |
| 85 | pub struct SalienceRequest { |
| 86 | pub user: String, |
| 87 | pub assistant: String, |
| 88 | } |
| 89 | |
| 90 | #[derive(Debug, Serialize)] |
| 91 | pub struct SalienceResponse { |
| 92 | #[serde(rename = "isDurable")] |
| 93 | pub is_durable: bool, |
| 94 | #[serde(rename = "durabilityScore")] |
| 95 | pub durability_score: f64, |
| 96 | #[serde(rename = "elapsedMs")] |
| 97 | pub elapsed_ms: f64, |
| 98 | } |
| 99 | |
| 100 | pub fn l2_normalize(vec: &[f32]) -> Vec<f32> { |
| 101 | let mut sum_sq = 0.0f32; |
| 102 | for &val in vec { |
| 103 | sum_sq += val * val; |
| 104 | } |
| 105 | let norm = sum_sq.sqrt(); |
| 106 | if norm > 0.0 { |
| 107 | vec.iter().map(|&v| v / norm).collect() |
| 108 | } else { |
| 109 | vec.to_vec() |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | pub fn calculate_sigmoid(raw_score: f32) -> f32 { |
| 114 | 1.0f32 / (1.0f32 + (-raw_score).exp()) |
| 115 | } |
| 116 | |
| 117 | pub async fn handle_health() -> impl IntoResponse { |
| 118 | Json(json!({ |
| 119 | "ok": true, |
| 120 | "modelId": MODEL_ID, |
| 121 | "modelRevision": MODEL_REVISION, |
| 122 | "backend": "ONNX Runtime 1.30.0 (Native Rust Axum INT8 CPU)", |
| 123 | "models": { |
| 124 | "embeddings": "Xenova/bge-base-en-v1.5 (ONNX INT8)", |
| 125 | "reranker": "Xenova/bge-reranker-base (ONNX INT8)", |
| 126 | "salience": "Xenova/bge-reranker-base (ONNX INT8)" |
| 127 | }, |
| 128 | "features": ["embed", "rerank", "classify_salience"] |
| 129 | })) |
| 130 | } |
| 131 | |
| 132 | pub async fn handle_embed( |
| 133 | State(state): State<AppState>, |
| 134 | Json(req): Json<EmbedRequest>, |
| 135 | ) -> Result<Json<EmbedResponse>, (StatusCode, String)> { |
| 136 | let trimmed = req.text.trim(); |
| 137 | if trimmed.is_empty() { |
| 138 | return Err((StatusCode::BAD_REQUEST, "text must not be empty".to_string())); |
| 139 | } |
| 140 | |
| 141 | let t0 = Instant::now(); |
| 142 | |
| 143 | let encoding = state |
| 144 | .embed_tokenizer |
| 145 | .encode(trimmed, true) |
| 146 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Tokenization failed: {}", e)))?; |
| 147 | |
| 148 | let input_ids: Vec<i64> = encoding.get_ids().iter().map(|&x| x as i64).collect(); |
| 149 | let attention_mask: Vec<i64> = encoding.get_attention_mask().iter().map(|&x| x as i64).collect(); |
| 150 | let token_type_ids: Vec<i64> = encoding.get_type_ids().iter().map(|&x| x as i64).collect(); |
| 151 | let seq_len = input_ids.len(); |
| 152 | |
| 153 | let input_ids_tensor = ort::value::Tensor::from_array(([1, seq_len], input_ids)) |
| 154 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Tensor creation error: {}", e)))?; |
| 155 | let attention_mask_tensor = ort::value::Tensor::from_array(([1, seq_len], attention_mask)) |
| 156 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Tensor creation error: {}", e)))?; |
| 157 | let token_type_ids_tensor = ort::value::Tensor::from_array(([1, seq_len], token_type_ids)) |
| 158 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Tensor creation error: {}", e)))?; |
| 159 | |
| 160 | let mut session = state.embed_session.lock().await; |
| 161 | let outputs = session |
| 162 | .run(ort::inputs![ |
| 163 | "input_ids" => input_ids_tensor, |
| 164 | "attention_mask" => attention_mask_tensor, |
| 165 | "token_type_ids" => token_type_ids_tensor, |
| 166 | ]) |
| 167 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Inference error: {}", e)))?; |
| 168 | |
| 169 | let (_shape, data) = outputs[0] |
| 170 | .try_extract_tensor::<f32>() |
| 171 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Tensor extraction error: {}", e)))?; |
| 172 | |
| 173 | if data.len() < 768 { |
| 174 | return Err(( |
| 175 | StatusCode::INTERNAL_SERVER_ERROR, |
| 176 | format!("Output tensor dim too small: {}", data.len()), |
| 177 | )); |
| 178 | } |
| 179 | |
| 180 | let cls_token = &data[0..768]; |
| 181 | let normalized = l2_normalize(cls_token); |
| 182 | let elapsed = t0.elapsed().as_secs_f64() * 1000.0; |
| 183 | |
| 184 | Ok(Json(EmbedResponse { |
| 185 | embedding: normalized, |
| 186 | model_id: MODEL_ID, |
| 187 | model_revision: MODEL_REVISION, |
| 188 | elapsed_ms: (elapsed * 100.0).round() / 100.0, |
| 189 | })) |
| 190 | } |
| 191 | |
| 192 | pub async fn handle_rerank( |
| 193 | State(state): State<AppState>, |
| 194 | Json(req): Json<RerankRequest>, |
| 195 | ) -> Result<Json<RerankResponse>, (StatusCode, String)> { |
| 196 | if req.passages.is_empty() { |
| 197 | return Ok(Json(RerankResponse { |
| 198 | scores: Vec::new(), |
| 199 | count: 0, |
| 200 | elapsed_ms: 0.0, |
| 201 | })); |
| 202 | } |
| 203 | |
| 204 | let t0 = Instant::now(); |
| 205 | let mut scores = Vec::with_capacity(req.passages.len()); |
| 206 | |
| 207 | let mut session = state.rerank_session.lock().await; |
| 208 | |
| 209 | for passage in &req.passages { |
| 210 | let max_len = passage.len().min(512); |
| 211 | let trimmed_passage = &passage[..max_len]; |
| 212 | |
| 213 | let encoding = state |
| 214 | .rerank_tokenizer |
| 215 | .encode((req.query.as_str(), trimmed_passage), true) |
| 216 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Tokenization failed: {}", e)))?; |
| 217 | |
| 218 | let input_ids: Vec<i64> = encoding.get_ids().iter().map(|&x| x as i64).collect(); |
| 219 | let attention_mask: Vec<i64> = encoding.get_attention_mask().iter().map(|&x| x as i64).collect(); |
| 220 | let seq_len = input_ids.len(); |
| 221 | |
| 222 | let input_ids_tensor = ort::value::Tensor::from_array(([1, seq_len], input_ids)) |
| 223 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Tensor error: {}", e)))?; |
| 224 | let attention_mask_tensor = ort::value::Tensor::from_array(([1, seq_len], attention_mask)) |
| 225 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Tensor error: {}", e)))?; |
| 226 | |
| 227 | let outputs = session |
| 228 | .run(ort::inputs![ |
| 229 | "input_ids" => input_ids_tensor, |
| 230 | "attention_mask" => attention_mask_tensor, |
| 231 | ]) |
| 232 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Rerank inference error: {}", e)))?; |
| 233 | |
| 234 | let (_shape, data) = outputs[0] |
| 235 | .try_extract_tensor::<f32>() |
| 236 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Extraction error: {}", e)))?; |
| 237 | |
| 238 | let raw_score = data[0]; |
| 239 | scores.push(calculate_sigmoid(raw_score)); |
| 240 | } |
| 241 | |
| 242 | let count = scores.len(); |
| 243 | let elapsed = t0.elapsed().as_secs_f64() * 1000.0; |
| 244 | |
| 245 | Ok(Json(RerankResponse { |
| 246 | scores, |
| 247 | count, |
| 248 | elapsed_ms: (elapsed * 100.0).round() / 100.0, |
| 249 | })) |
| 250 | } |
| 251 | |
| 252 | pub async fn handle_classify_salience( |
| 253 | State(state): State<AppState>, |
| 254 | Json(req): Json<SalienceRequest>, |
| 255 | ) -> Result<Json<SalienceResponse>, (StatusCode, String)> { |
| 256 | let t0 = Instant::now(); |
| 257 | |
| 258 | let user_slice = &req.user[..req.user.len().min(300)]; |
| 259 | let asst_slice = &req.assistant[..req.assistant.len().min(300)]; |
| 260 | let text = format!("User: {}\nAssistant: {}", user_slice, asst_slice); |
| 261 | let anchor = "Important architectural decision, user preference mandate, or permanent system configuration change."; |
| 262 | |
| 263 | let encoding = state |
| 264 | .rerank_tokenizer |
| 265 | .encode((anchor, text.as_str()), true) |
| 266 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Tokenization failed: {}", e)))?; |
| 267 | |
| 268 | let input_ids: Vec<i64> = encoding.get_ids().iter().map(|&x| x as i64).collect(); |
| 269 | let attention_mask: Vec<i64> = encoding.get_attention_mask().iter().map(|&x| x as i64).collect(); |
| 270 | let seq_len = input_ids.len(); |
| 271 | |
| 272 | let input_ids_tensor = ort::value::Tensor::from_array(([1, seq_len], input_ids)) |
| 273 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Tensor error: {}", e)))?; |
| 274 | let attention_mask_tensor = ort::value::Tensor::from_array(([1, seq_len], attention_mask)) |
| 275 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Tensor error: {}", e)))?; |
| 276 | |
| 277 | let mut session = state.rerank_session.lock().await; |
| 278 | let outputs = session |
| 279 | .run(ort::inputs![ |
| 280 | "input_ids" => input_ids_tensor, |
| 281 | "attention_mask" => attention_mask_tensor, |
| 282 | ]) |
| 283 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Salience inference error: {}", e)))?; |
| 284 | |
| 285 | let (_shape, data) = outputs[0] |
| 286 | .try_extract_tensor::<f32>() |
| 287 | .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Extraction error: {}", e)))?; |
| 288 | |
| 289 | let raw_score = data[0]; |
| 290 | let score = calculate_sigmoid(raw_score) as f64; |
| 291 | let is_durable = score >= 0.20; |
| 292 | let elapsed = t0.elapsed().as_secs_f64() * 1000.0; |
| 293 | |
| 294 | Ok(Json(SalienceResponse { |
| 295 | is_durable, |
| 296 | durability_score: (score * 10000.0).round() / 10000.0, |
| 297 | elapsed_ms: (elapsed * 100.0).round() / 100.0, |
| 298 | })) |
| 299 | } |
| 300 | |
| 301 | #[tokio::main] |
| 302 | async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 303 | tracing_subscriber::registry() |
| 304 | .with(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into())) |
| 305 | .with(tracing_subscriber::fmt::layer()) |
| 306 | .init(); |
| 307 | |
| 308 | let cli = Cli::parse(); |
| 309 | |
| 310 | info!("Initializing ONNX Runtime from {}", ONNX_RUNTIME_LIB); |
| 311 | ort::init_from(ONNX_RUNTIME_LIB) |
| 312 | .map_err(|e| format!("Failed to init ONNX runtime: {}", e))? |
| 313 | .commit(); |
| 314 | |
| 315 | let embed_tok_path = format!("{}/tokenizer.json", EMBED_DIR); |
| 316 | let embed_model_path = format!("{}/onnx/model_quantized.onnx", EMBED_DIR); |
| 317 | info!("Loading embedding tokenizer from {}", embed_tok_path); |
| 318 | let embed_tokenizer = Arc::new(Tokenizer::from_file(&embed_tok_path).map_err(|e| e.to_string())?); |
| 319 | info!("Loading embedding ONNX session from {}", embed_model_path); |
| 320 | let embed_session = Arc::new(Mutex::new( |
| 321 | Session::builder()? |
| 322 | .with_optimization_level(GraphOptimizationLevel::Level3)? |
| 323 | .with_intra_threads(4)? |
| 324 | .commit_from_file(&embed_model_path)?, |
| 325 | )); |
| 326 | |
| 327 | let rerank_tok_path = format!("{}/tokenizer.json", RERANK_DIR); |
| 328 | let rerank_model_path = format!("{}/onnx/model_quantized.onnx", RERANK_DIR); |
| 329 | info!("Loading reranker tokenizer from {}", rerank_tok_path); |
| 330 | let rerank_tokenizer = Arc::new(Tokenizer::from_file(&rerank_tok_path).map_err(|e| e.to_string())?); |
| 331 | info!("Loading reranker ONNX session from {}", rerank_model_path); |
| 332 | let rerank_session = Arc::new(Mutex::new( |
| 333 | Session::builder()? |
| 334 | .with_optimization_level(GraphOptimizationLevel::Level3)? |
| 335 | .with_intra_threads(4)? |
| 336 | .commit_from_file(&rerank_model_path)?, |
| 337 | )); |
| 338 | |
| 339 | let state = AppState { |
| 340 | embed_session, |
| 341 | embed_tokenizer, |
| 342 | rerank_session, |
| 343 | rerank_tokenizer, |
| 344 | }; |
| 345 | |
| 346 | let app = Router::new() |
| 347 | .route("/health", get(handle_health)) |
| 348 | .route("/embed", post(handle_embed)) |
| 349 | .route("/rerank", post(handle_rerank)) |
| 350 | .route("/classify_salience", post(handle_classify_salience)) |
| 351 | .layer(CorsLayer::permissive()) |
| 352 | .with_state(state); |
| 353 | |
| 354 | let addr: SocketAddr = format!("{}:{}", cli.host, cli.port).parse()?; |
| 355 | info!("cortex-encoder-rs listening on http://{}", addr); |
| 356 | |
| 357 | let listener = tokio::net::TcpListener::bind(addr).await?; |
| 358 | axum::serve(listener, app).await?; |
| 359 | |
| 360 | Ok(()) |
| 361 | } |
| 362 | |
| 363 | #[cfg(test)] |
| 364 | mod tests { |
| 365 | use super::*; |
| 366 | |
| 367 | #[test] |
| 368 | fn test_l2_normalize() { |
| 369 | let vec = vec![3.0f32, 4.0f32]; |
| 370 | let norm = l2_normalize(&vec); |
| 371 | assert!((norm[0] - 0.6).abs() < 1e-5); |
| 372 | assert!((norm[1] - 0.8).abs() < 1e-5); |
| 373 | |
| 374 | let sum_sq: f32 = norm.iter().map(|x| x * x).sum(); |
| 375 | assert!((sum_sq - 1.0).abs() < 1e-5); |
| 376 | } |
| 377 | |
| 378 | #[test] |
| 379 | fn test_l2_normalize_zero() { |
| 380 | let vec = vec![0.0f32, 0.0f32]; |
| 381 | let norm = l2_normalize(&vec); |
| 382 | assert_eq!(norm, vec); |
| 383 | } |
| 384 | |
| 385 | #[test] |
| 386 | fn test_sigmoid_calculation() { |
| 387 | let zero_score = calculate_sigmoid(0.0); |
| 388 | assert!((zero_score - 0.5).abs() < 1e-5); |
| 389 | |
| 390 | let high_score = calculate_sigmoid(10.0); |
| 391 | assert!(high_score > 0.999); |
| 392 | |
| 393 | let low_score = calculate_sigmoid(-10.0); |
| 394 | assert!(low_score < 0.001); |
| 395 | } |
| 396 | |
| 397 | #[test] |
| 398 | fn test_model_constants() { |
| 399 | assert_eq!(MODEL_ID, "BAAI/bge-base-en-v1.5"); |
| 400 | assert_eq!(MODEL_REVISION, "cortex-bge-base-en-v1.5-768-v1"); |
| 401 | } |
| 402 | } |