aien-local-stack
aien-dev/aien-local-stack
Brought by drakestapleton
aien-local-stack / src / sovereign_service.rs
| 1 | use crate::recipe::ContextRecipe; |
| 2 | use aien_inference_abi::transformer_backend::NativeTransformerBackend; |
| 3 | use aien_inference_abi::weights::TransformerWeights; |
| 4 | use aien_inference_abi::{BranchHandle, ContextHandle, ModelConfig}; |
| 5 | use aien_inference_protocol::*; |
| 6 | use aien_kv_cache::KvMetrics; |
| 7 | use aien_platform_linux::{LinuxComputeDevice, LinuxMemoryKind}; |
| 8 | use aien_protocol_types::{Digest32, ProtocolVersion}; |
| 9 | use aien_provenance::{compute_canonical_json_digest, compute_sha256}; |
| 10 | use async_trait::async_trait; |
| 11 | use parking_lot::Mutex; |
| 12 | use std::collections::HashMap; |
| 13 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 14 | use std::sync::Arc; |
| 15 | use uuid::Uuid; |
| 16 | |
| 17 | static NEXT_SEQ_COUNTER: AtomicU64 = AtomicU64::new(100); |
| 18 | |
| 19 | #[derive(Clone, Debug)] |
| 20 | pub struct BranchState { |
| 21 | pub handle: u64, |
| 22 | pub branch_id: Uuid, |
| 23 | pub context_id: Uuid, |
| 24 | pub generation: Generation, |
| 25 | pub token_count: u64, |
| 26 | pub tokens: Vec<u32>, |
| 27 | pub logical_state_digest: Digest32, |
| 28 | pub recipe_ref: ContextRecipeRef, |
| 29 | pub isolation: CacheIsolationKey, |
| 30 | pub lineage: ContextLineage, |
| 31 | } |
| 32 | |
| 33 | impl BranchState { |
| 34 | pub fn compute_digest(branch_id: &Uuid, tokens: &[u32]) -> Digest32 { |
| 35 | let mut bytes = Vec::with_capacity(16 + tokens.len() * 4); |
| 36 | bytes.extend_from_slice(branch_id.as_bytes()); |
| 37 | for &tok in tokens { |
| 38 | bytes.extend_from_slice(&tok.to_le_bytes()); |
| 39 | } |
| 40 | compute_sha256(&bytes) |
| 41 | } |
| 42 | |
| 43 | pub fn to_context_ref(&self, service: &SovereignInferenceService) -> InferenceContextRef { |
| 44 | InferenceContextRef { |
| 45 | abi_version: 1, |
| 46 | context_id: ContextId(self.context_id), |
| 47 | branch_id: BranchId(self.branch_id), |
| 48 | generation: self.generation, |
| 49 | model: service.model_fingerprint(), |
| 50 | tokenizer: service.tokenizer_fingerprint(), |
| 51 | kv_format: service.kv_format_fingerprint(), |
| 52 | logical_state_digest: self.logical_state_digest, |
| 53 | token_count: self.token_count, |
| 54 | lineage: self.lineage.clone(), |
| 55 | isolation: self.isolation, |
| 56 | binding: Some(OpaqueBindingRef { |
| 57 | engine_id: service.engine_id.clone(), |
| 58 | runtime_epoch: service.runtime_epoch(), |
| 59 | binding_id: self.branch_id, |
| 60 | lease_generation: 1, |
| 61 | }), |
| 62 | recovery: self.recipe_ref.clone(), |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | pub struct SovereignInferenceService { |
| 68 | runtime: Arc<Mutex<NativeTransformerBackend>>, |
| 69 | config: ModelConfig, |
| 70 | active_branches: Arc<Mutex<HashMap<Uuid, BranchState>>>, |
| 71 | epoch: Arc<AtomicU64>, |
| 72 | pub engine_id: String, |
| 73 | pub backend_name: String, |
| 74 | pub is_accelerated: bool, |
| 75 | pub memory_kind: String, |
| 76 | } |
| 77 | |
| 78 | impl SovereignInferenceService { |
| 79 | pub fn new_with_reference_weights(config: &ModelConfig, epoch: u64) -> Result<Self, String> { |
| 80 | let weights = TransformerWeights::reference_test_weights(config); |
| 81 | let runtime = NativeTransformerBackend::with_paged_kv(weights, 1024, config.block_size)?; |
| 82 | |
| 83 | let device = LinuxComputeDevice::new(); |
| 84 | let mem_kind = match device.preferred_memory_kind() { |
| 85 | LinuxMemoryKind::AtsSystem => "AtsSystem (Hardware Coherent Grace-Blackwell)", |
| 86 | LinuxMemoryKind::HmmSystem => "HmmSystem (Heterogeneous Memory Management)", |
| 87 | LinuxMemoryKind::External => "External (engine-owned host-visible pool)", |
| 88 | }; |
| 89 | |
| 90 | Ok(Self { |
| 91 | runtime: Arc::new(Mutex::new(runtime)), |
| 92 | config: config.clone(), |
| 93 | active_branches: Arc::new(Mutex::new(HashMap::new())), |
| 94 | epoch: Arc::new(AtomicU64::new(epoch)), |
| 95 | engine_id: "aien-sovereign-gb10".to_string(), |
| 96 | backend_name: "ReferenceCpuBackend (CPU Golden Oracle)".to_string(), |
| 97 | is_accelerated: false, |
| 98 | memory_kind: mem_kind.to_string(), |
| 99 | }) |
| 100 | } |
| 101 | |
| 102 | pub fn new_default() -> Result<Self, String> { |
| 103 | Self::new_with_epoch(1) |
| 104 | } |
| 105 | |
| 106 | pub fn new_with_epoch(epoch: u64) -> Result<Self, String> { |
| 107 | let config = ModelConfig { |
| 108 | num_layers: 2, |
| 109 | num_heads: 4, |
| 110 | num_kv_heads: 2, |
| 111 | head_dim: 16, |
| 112 | hidden_dim: 64, |
| 113 | intermediate_dim: 128, |
| 114 | vocab_size: 256, |
| 115 | block_size: 16, |
| 116 | ..Default::default() |
| 117 | }; |
| 118 | Self::new_with_reference_weights(&config, epoch) |
| 119 | } |
| 120 | |
| 121 | pub fn model_fingerprint(&self) -> ModelFingerprint { |
| 122 | let cfg_digest = compute_canonical_json_digest(&self.config).unwrap_or(Digest32::ZERO); |
| 123 | let mut w_bytes = Vec::new(); |
| 124 | w_bytes.extend_from_slice(&(self.config.hidden_dim as u64).to_le_bytes()); |
| 125 | w_bytes.extend_from_slice(&(self.config.num_layers as u64).to_le_bytes()); |
| 126 | w_bytes.extend_from_slice(&(self.config.vocab_size as u64).to_le_bytes()); |
| 127 | let w_digest = compute_sha256(&w_bytes); |
| 128 | |
| 129 | ModelFingerprint { |
| 130 | weights_digest: w_digest, |
| 131 | model_config_digest: cfg_digest, |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | pub fn tokenizer_fingerprint(&self) -> TokenizerFingerprint { |
| 136 | let mut t_bytes = Vec::new(); |
| 137 | t_bytes.extend_from_slice(&(self.config.vocab_size as u64).to_le_bytes()); |
| 138 | t_bytes.extend_from_slice(b"sovereign-reference-tokenizer-v1"); |
| 139 | TokenizerFingerprint { |
| 140 | tokenizer_digest: compute_sha256(&t_bytes), |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | pub fn kv_format_fingerprint(&self) -> KvFormatFingerprint { |
| 145 | KvFormatFingerprint { |
| 146 | format_version: 1, |
| 147 | dtype: "FP32".to_string(), |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | pub fn runtime_epoch(&self) -> u64 { |
| 152 | self.epoch.load(Ordering::SeqCst) |
| 153 | } |
| 154 | |
| 155 | pub fn bump_runtime_epoch(&self) -> u64 { |
| 156 | let new_epoch = self.epoch.fetch_add(1, Ordering::SeqCst) + 1; |
| 157 | self.active_branches.lock().clear(); |
| 158 | new_epoch |
| 159 | } |
| 160 | |
| 161 | pub fn create_root_context( |
| 162 | &self, |
| 163 | prompt_tokens: &[u32], |
| 164 | recipe: &ContextRecipe, |
| 165 | ) -> Result<(ContextHandle, InferenceContextRef), String> { |
| 166 | let mut runtime = self.runtime.lock(); |
| 167 | let handle = runtime.create_context(prompt_tokens)?; |
| 168 | |
| 169 | let root_ctx_id = Uuid::new_v4(); |
| 170 | let root_branch_id = Uuid::new_v4(); |
| 171 | let state_digest = BranchState::compute_digest(&root_branch_id, prompt_tokens); |
| 172 | |
| 173 | let branch_state = BranchState { |
| 174 | handle: handle.0, |
| 175 | branch_id: root_branch_id, |
| 176 | context_id: root_ctx_id, |
| 177 | generation: Generation(1), |
| 178 | token_count: prompt_tokens.len() as u64, |
| 179 | tokens: prompt_tokens.to_vec(), |
| 180 | logical_state_digest: state_digest, |
| 181 | recipe_ref: recipe.to_ref(), |
| 182 | isolation: CacheIsolationKey { |
| 183 | domain_id: Uuid::new_v4(), |
| 184 | domain_digest: compute_sha256(b"sovereign-tenant-root"), |
| 185 | }, |
| 186 | lineage: ContextLineage { |
| 187 | parent_context: None, |
| 188 | parent_branch: None, |
| 189 | parent_digest: None, |
| 190 | fork_token_index: None, |
| 191 | }, |
| 192 | }; |
| 193 | |
| 194 | let ctx_ref = branch_state.to_context_ref(self); |
| 195 | self.active_branches |
| 196 | .lock() |
| 197 | .insert(root_branch_id, branch_state); |
| 198 | |
| 199 | Ok((handle, ctx_ref)) |
| 200 | } |
| 201 | |
| 202 | pub fn reconstruct_from_recipe( |
| 203 | &self, |
| 204 | branch_id: Uuid, |
| 205 | recipe: &ContextRecipe, |
| 206 | ) -> Result<(ContextHandle, InferenceContextRef), String> { |
| 207 | let tokens = recipe.full_tokens_for_branch(&branch_id); |
| 208 | let mut runtime = self.runtime.lock(); |
| 209 | let handle = runtime.create_context(&tokens)?; |
| 210 | |
| 211 | let ctx_id = Uuid::new_v4(); |
| 212 | let state_digest = BranchState::compute_digest(&branch_id, &tokens); |
| 213 | |
| 214 | let branch_state = BranchState { |
| 215 | handle: handle.0, |
| 216 | branch_id, |
| 217 | context_id: ctx_id, |
| 218 | generation: Generation(1), |
| 219 | token_count: tokens.len() as u64, |
| 220 | tokens, |
| 221 | logical_state_digest: state_digest, |
| 222 | recipe_ref: recipe.to_ref(), |
| 223 | isolation: CacheIsolationKey { |
| 224 | domain_id: Uuid::new_v4(), |
| 225 | domain_digest: compute_sha256(b"sovereign-reconstruction-domain"), |
| 226 | }, |
| 227 | lineage: ContextLineage { |
| 228 | parent_context: None, |
| 229 | parent_branch: None, |
| 230 | parent_digest: None, |
| 231 | fork_token_index: None, |
| 232 | }, |
| 233 | }; |
| 234 | |
| 235 | let ctx_ref = branch_state.to_context_ref(self); |
| 236 | self.active_branches.lock().insert(branch_id, branch_state); |
| 237 | |
| 238 | Ok((handle, ctx_ref)) |
| 239 | } |
| 240 | |
| 241 | pub fn get_block_table(&self, id: Uuid) -> Option<Vec<usize>> { |
| 242 | let handle = self.active_branches.lock().get(&id).map(|b| b.handle)?; |
| 243 | let runtime = self.runtime.lock(); |
| 244 | let kv_mgr = runtime.kv_manager.as_ref()?; |
| 245 | let mgr = kv_mgr.read(); |
| 246 | let tbl = mgr.get_block_table(handle)?; |
| 247 | Some(tbl.block_ids.clone()) |
| 248 | } |
| 249 | |
| 250 | pub fn get_block_refcount(&self, block_id: usize) -> Option<usize> { |
| 251 | let runtime = self.runtime.lock(); |
| 252 | let kv_mgr = runtime.kv_manager.as_ref()?; |
| 253 | let mgr = kv_mgr.read(); |
| 254 | mgr.get_block(block_id).map(|b| b.ref_count) |
| 255 | } |
| 256 | |
| 257 | pub fn get_cow_faults(&self) -> usize { |
| 258 | let runtime = self.runtime.lock(); |
| 259 | runtime |
| 260 | .kv_manager |
| 261 | .as_ref() |
| 262 | .map(|m| m.read().cow_faults()) |
| 263 | .unwrap_or(0) |
| 264 | } |
| 265 | |
| 266 | pub fn get_kv_metrics(&self) -> Option<KvMetrics> { |
| 267 | let runtime = self.runtime.lock(); |
| 268 | runtime.kv_manager.as_ref().map(|m| m.read().metrics()) |
| 269 | } |
| 270 | |
| 271 | pub fn get_branch_tokens(&self, branch_id: Uuid) -> Option<Vec<u32>> { |
| 272 | let branches = self.active_branches.lock(); |
| 273 | branches.get(&branch_id).map(|s| s.tokens.clone()) |
| 274 | } |
| 275 | |
| 276 | pub fn snapshot_branch_recipe( |
| 277 | &self, |
| 278 | branch_id: Uuid, |
| 279 | recipe: &ContextRecipe, |
| 280 | ) -> Option<ContextRecipe> { |
| 281 | let branches = self.active_branches.lock(); |
| 282 | let state = branches.get(&branch_id)?; |
| 283 | let root_len = recipe.root_prompt_tokens.len(); |
| 284 | if state.tokens.len() >= root_len |
| 285 | && state.tokens[..root_len] == recipe.root_prompt_tokens[..] |
| 286 | { |
| 287 | let delta = state.tokens[root_len..].to_vec(); |
| 288 | Some(recipe.clone().with_branch_delta(branch_id, delta)) |
| 289 | } else { |
| 290 | None |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | pub fn select_branch( |
| 295 | &self, |
| 296 | selected_branch: Uuid, |
| 297 | sibling_branches: &[Uuid], |
| 298 | ) -> Result<(), String> { |
| 299 | let mut runtime = self.runtime.lock(); |
| 300 | let mut branches = self.active_branches.lock(); |
| 301 | |
| 302 | if !branches.contains_key(&selected_branch) { |
| 303 | return Err(format!("Selected branch {} not found", selected_branch)); |
| 304 | } |
| 305 | |
| 306 | for &sibling in sibling_branches { |
| 307 | if sibling == selected_branch { |
| 308 | continue; |
| 309 | } |
| 310 | if let Some(st) = branches.remove(&sibling) { |
| 311 | let _ = runtime.release_branch(BranchHandle(st.handle)); |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | Ok(()) |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | #[async_trait] |
| 320 | impl InferenceService for SovereignInferenceService { |
| 321 | async fn infer(&self, req: InferenceRequest) -> Result<InferenceResponse, InferenceError> { |
| 322 | if let Some(ctx) = &req.context { |
| 323 | if let Some(binding) = &ctx.binding { |
| 324 | let current_epoch = self.runtime_epoch(); |
| 325 | if binding.runtime_epoch != current_epoch { |
| 326 | return Err(InferenceError::StaleRuntimeEpoch); |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | if ctx.kv_format.dtype != "FP32" { |
| 331 | return Err(InferenceError::Internal(format!( |
| 332 | "KV format mismatch: expected FP32, got {}", |
| 333 | ctx.kv_format.dtype |
| 334 | ))); |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | let max_tokens = req.max_tokens as usize; |
| 339 | let mut runtime = self.runtime.lock(); |
| 340 | |
| 341 | let (generated_tokens, updated_ctx) = if let Some(ctx) = &req.context { |
| 342 | let mut branches = self.active_branches.lock(); |
| 343 | let state = branches |
| 344 | .get_mut(&ctx.branch_id.0) |
| 345 | .ok_or(InferenceError::ContextNotFound(ctx.context_id))?; |
| 346 | |
| 347 | if ctx.generation != state.generation { |
| 348 | return Err(InferenceError::StaleGeneration { |
| 349 | expected: state.generation, |
| 350 | actual: ctx.generation, |
| 351 | }); |
| 352 | } |
| 353 | |
| 354 | // Extract branch delta tokens from request messages |
| 355 | let mut delta_tokens = Vec::new(); |
| 356 | for msg in &req.messages { |
| 357 | for b in msg.content.as_bytes() { |
| 358 | delta_tokens.push((*b as u32) % self.config.vocab_size as u32); |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | // Ingest branch delta into physical KV cache (triggers CoW on shared block!) |
| 363 | if !delta_tokens.is_empty() { |
| 364 | runtime |
| 365 | .append_branch_tokens(BranchHandle(state.handle), &delta_tokens) |
| 366 | .map_err(|e| { |
| 367 | InferenceError::Internal(format!("Failed to append branch tokens: {}", e)) |
| 368 | })?; |
| 369 | state.tokens.extend_from_slice(&delta_tokens); |
| 370 | } |
| 371 | |
| 372 | // Autoregressively decode tokens |
| 373 | let mut tokens = Vec::with_capacity(max_tokens); |
| 374 | for _ in 0..max_tokens { |
| 375 | match runtime.decode_branch_step(BranchHandle(state.handle)) { |
| 376 | Ok((tok, _)) => tokens.push(tok), |
| 377 | Err(e) => { |
| 378 | return Err(InferenceError::Internal(format!( |
| 379 | "Decode step failed: {}", |
| 380 | e |
| 381 | ))) |
| 382 | } |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | // Ingest generated tokens into logical branch state so state.tokens, |
| 387 | // token_count, and logical_state_digest accurately reflect post-generation state |
| 388 | state.tokens.extend_from_slice(&tokens); |
| 389 | |
| 390 | // Advance branch state |
| 391 | state.generation = state.generation.next(); |
| 392 | state.token_count = state.tokens.len() as u64; |
| 393 | state.logical_state_digest = |
| 394 | BranchState::compute_digest(&state.branch_id, &state.tokens); |
| 395 | |
| 396 | let new_ctx_ref = state.to_context_ref(self); |
| 397 | (tokens, Some(new_ctx_ref)) |
| 398 | } else { |
| 399 | let mut prompt_tokens = vec![1u32]; |
| 400 | for msg in &req.messages { |
| 401 | for b in msg.content.as_bytes() { |
| 402 | prompt_tokens.push((*b as u32) % self.config.vocab_size as u32); |
| 403 | } |
| 404 | } |
| 405 | let seq_id = NEXT_SEQ_COUNTER.fetch_add(1, Ordering::SeqCst); |
| 406 | let toks = runtime |
| 407 | .generate_tokens(seq_id, &prompt_tokens, max_tokens, req.temperature, &[]) |
| 408 | .map_err(|e| InferenceError::Internal(format!("Generation failed: {}", e)))?; |
| 409 | (toks, None) |
| 410 | }; |
| 411 | |
| 412 | let content = String::from_utf8_lossy( |
| 413 | &generated_tokens |
| 414 | .iter() |
| 415 | .map(|t| (t % 128) as u8) |
| 416 | .collect::<Vec<u8>>(), |
| 417 | ) |
| 418 | .to_string(); |
| 419 | |
| 420 | Ok(InferenceResponse { |
| 421 | request_id: req.request_id, |
| 422 | content, |
| 423 | finish_reason: "stop".to_string(), |
| 424 | prompt_tokens: req.messages.iter().map(|m| m.content.len() as u32).sum(), |
| 425 | completion_tokens: generated_tokens.len() as u32, |
| 426 | context: updated_ctx, |
| 427 | }) |
| 428 | } |
| 429 | |
| 430 | async fn branch_context( |
| 431 | &self, |
| 432 | req: BranchContextRequest, |
| 433 | ) -> Result<BranchContextReceipt, InferenceError> { |
| 434 | let parent_state = { |
| 435 | let branches = self.active_branches.lock(); |
| 436 | branches |
| 437 | .get(&req.parent_context.branch_id.0) |
| 438 | .cloned() |
| 439 | .ok_or(InferenceError::ContextNotFound( |
| 440 | req.parent_context.context_id, |
| 441 | ))? |
| 442 | }; |
| 443 | |
| 444 | let mut runtime = self.runtime.lock(); |
| 445 | let child_handle = runtime |
| 446 | .fork_context(ContextHandle(parent_state.handle)) |
| 447 | .map_err(|e| InferenceError::Internal(format!("Fork context failed: {}", e)))?; |
| 448 | |
| 449 | let receipt = runtime |
| 450 | .get_usage_receipt(child_handle) |
| 451 | .map_err(|e| InferenceError::Internal(format!("Usage receipt failed: {}", e)))?; |
| 452 | |
| 453 | let child_state = BranchState { |
| 454 | handle: child_handle.0, |
| 455 | branch_id: req.child_branch_id.0, |
| 456 | context_id: parent_state.context_id, |
| 457 | generation: parent_state.generation.next(), |
| 458 | token_count: parent_state.token_count, |
| 459 | tokens: parent_state.tokens.clone(), |
| 460 | logical_state_digest: parent_state.logical_state_digest, |
| 461 | recipe_ref: parent_state.recipe_ref.clone(), |
| 462 | isolation: req.isolation, |
| 463 | lineage: ContextLineage { |
| 464 | parent_context: Some(req.parent_context.context_id), |
| 465 | parent_branch: Some(req.parent_context.branch_id), |
| 466 | parent_digest: Some(parent_state.logical_state_digest), |
| 467 | fork_token_index: Some(parent_state.token_count), |
| 468 | }, |
| 469 | }; |
| 470 | |
| 471 | let child_context_ref = child_state.to_context_ref(self); |
| 472 | self.active_branches |
| 473 | .lock() |
| 474 | .insert(req.child_branch_id.0, child_state); |
| 475 | |
| 476 | Ok(BranchContextReceipt { |
| 477 | operation_id: req.operation_id, |
| 478 | child_context: child_context_ref, |
| 479 | shared_pages: receipt.shared_pages as u32, |
| 480 | copied_pages: receipt.private_pages as u32, |
| 481 | lease_expires_at_monotonic: 9999999999, |
| 482 | }) |
| 483 | } |
| 484 | |
| 485 | async fn get_capabilities(&self) -> Result<InferenceCapabilities, InferenceError> { |
| 486 | Ok(InferenceCapabilities { |
| 487 | protocol: ProtocolVersion::new(1, 0), |
| 488 | context_branching: true, |
| 489 | physical_cow: true, |
| 490 | streaming: false, |
| 491 | cancellation: true, |
| 492 | max_context_tokens: Some(4096), |
| 493 | }) |
| 494 | } |
| 495 | } |