interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-inference-abi / src / lib.rs

846 lines · 28111 bytes Raw Blame History
1#![allow(
2// SPDX-License-Identifier: Apache-2.0
3// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17 clippy::too_many_arguments,
18 clippy::needless_range_loop,
19 clippy::chunks_exact_to_as_chunks
20)]
21use async_trait::async_trait;
22use serde::{Deserialize, Serialize};
23
24pub mod backend;
25pub mod bitnet_forward;
26pub mod bitnet_omega;
27pub mod bitnet_tokenizer;
28pub mod capsule;
29pub mod checkpoint;
30pub mod exact_head;
31pub mod gb10_serving;
32pub mod generation;
33pub mod model_dir;
34pub mod moe_plan;
35pub mod native_ops;
36pub mod omega_backend;
37pub mod pci_gpu;
38pub mod qwen38;
39pub mod qwen38_omega;
40pub mod qwen3_coder;
41pub mod qwen3_dense_omega;
42pub mod qwen3_moe;
43pub mod qwen3_moe_omega;
44pub mod qwen3_moe_omega_dattn;
45pub mod qwen3_moe_omega_prefill;
46pub mod resident;
47pub mod strict;
48pub mod tensor;
49pub mod tensor_abi;
50pub mod tokenizer;
51pub mod tool_boundary;
52pub mod transformer_backend;
53pub mod weights;
54
55/// Persistent-KV identity (ADR 0003 section 1.2.1, review finding 1): bumped by any
56/// change that alters the numeric results of the forward pass (kernels, summation
57/// order, activation, rounding). It is field 9 of the compute-config digest, so a
58/// bump orphans every stored chunk instead of serving K/V computed the old way.
59/// Guarded by `arith_epoch_pinned_bytes` in `aien-runtime`: a numeric change fails
60/// that test until this constant is bumped and the pin refreshed.
61pub const KV_ARITH_EPOCH: u32 = 2;
62
63pub use aien_abi_core::*;
64pub use aien_kv_cache::*;
65pub use backend::*;
66pub use capsule::*;
67pub use checkpoint::*;
68pub use model_dir::{load_model_config, model_config_from_hf_json, model_id_for_dir};
69pub use moe_plan::*;
70pub use omega_backend::{
71 gb10_qwen3_enabled, gb10_qwen3_enabled_from, gb10_qwen3_enabled_from_os,
72 omega_backend_selected, omega_model_refusal, omega_model_refusal_with,
73 open_gpu_session_with_retry, retry_bounded, retry_bounded_within, OmegaGb10Backend,
74 SessionAttemptError, GB10_QWEN3_OPT_IN_ENV, GPU_BACKEND_ENV, GPU_SESSION_OPEN_ATTEMPTS,
75 GPU_SESSION_OPEN_DEADLINE, GPU_SESSION_RETRY_DELAY,
76};
77pub use qwen3_coder::*;
78pub use qwen3_moe::*;
79pub use resident::*;
80pub use tensor::*;
81pub use tensor_abi::*;
82pub use tokenizer::*;
83pub use transformer_backend::*;
84pub use weights::*;
85
86/// High-throughput simulated backend for benchmarking scheduler and KV manager overhead
87pub struct MockInferenceBackend {
88 pub config: ModelConfig,
89 pub simulated_step_latency_us: u64,
90}
91
92impl MockInferenceBackend {
93 pub fn new(simulated_step_latency_us: u64) -> Self {
94 Self {
95 config: ModelConfig::default(),
96 simulated_step_latency_us,
97 }
98 }
99}
100
101#[async_trait]
102impl AienInferenceBackend for MockInferenceBackend {
103 async fn load_model(&mut self, config: &ModelConfig) -> Result<(), String> {
104 self.config = config.clone();
105 Ok(())
106 }
107
108 async fn execute_step(
109 &mut self,
110 batch: &ScheduledBatch,
111 ) -> Result<(Vec<DecodeOutput>, StepMetrics), String> {
112 let t0 = std::time::Instant::now();
113 let mut outputs = Vec::new();
114 let mut prefill_tokens = 0;
115
116 for req in &batch.prefill_requests {
117 prefill_tokens += req.prompt_tokens.len();
118 outputs.push(DecodeOutput::Token {
119 request_id: req.request_id,
120 token_id: 100,
121 logprob: Some(-0.05),
122 });
123 }
124
125 for &req_id in &batch.decode_requests {
126 outputs.push(DecodeOutput::Token {
127 request_id: req_id,
128 token_id: 101,
129 logprob: Some(-0.02),
130 });
131 }
132
133 let elapsed = t0.elapsed().as_micros() as u64 + self.simulated_step_latency_us;
134 let metrics = StepMetrics {
135 prefill_tokens_processed: prefill_tokens,
136 decode_tokens_emitted: batch.decode_requests.len() + batch.prefill_requests.len(),
137 step_latency_us: elapsed,
138 active_kv_blocks: batch.block_tables.values().map(|v| v.len()).sum(),
139 };
140
141 Ok((outputs, metrics))
142 }
143}
144
145/// Hardware execution surface auto-detection for portable cross-platform operation
146#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147pub enum ExecutionSurface {
148 NvidiaGraceBlackwell {
149 model: String,
150 unified_memory_gb: usize,
151 },
152 NvidiaCuda {
153 gpu_name: String,
154 /// No first-party (non-NVIDIA-userspace) source for dedicated VRAM
155 /// size exists, so it is unknown rather than guessed.
156 vram_gb: Option<usize>,
157 },
158 AppleSilicon {
159 chip_name: String,
160 unified_memory_gb: usize,
161 },
162 GenericLinuxCpu {
163 cpu_cores: usize,
164 total_ram_gb: usize,
165 },
166 GenericUnixCpu {
167 cpu_cores: usize,
168 total_ram_gb: usize,
169 },
170}
171
172impl ExecutionSurface {
173 pub fn detect() -> Self {
174 // 1. NVIDIA GPU from sysfs (no nvidia-smi / NVML).
175 if let Some(surface) = Self::nvidia_surface(std::path::Path::new("/sys/bus/pci/devices")) {
176 return surface;
177 }
178
179 // 2. Check for macOS Apple Silicon
180 #[cfg(target_os = "macos")]
181 {
182 let mut chip_name = "Apple Silicon".to_string();
183 if let Ok(output) = std::process::Command::new("sysctl")
184 .arg("-n")
185 .arg("machdep.cpu.brand_string")
186 .output()
187 {
188 let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
189 if !name.is_empty() {
190 chip_name = name;
191 }
192 }
193 let mut ram_gb = 16;
194 if let Ok(output) = std::process::Command::new("sysctl")
195 .arg("-n")
196 .arg("hw.memsize")
197 .output()
198 {
199 if let Ok(bytes) = String::from_utf8_lossy(&output.stdout)
200 .trim()
201 .parse::<u64>()
202 {
203 ram_gb = (bytes / (1024 * 1024 * 1024)) as usize;
204 }
205 }
206 ExecutionSurface::AppleSilicon {
207 chip_name,
208 unified_memory_gb: ram_gb,
209 }
210 }
211
212 // 3. Generic Linux CPU detection
213 #[cfg(target_os = "linux")]
214 {
215 let cpu_cores = std::thread::available_parallelism()
216 .map(|p| p.get())
217 .unwrap_or(8);
218 let mut ram_gb = 16;
219 if let Ok(meminfo) = std::fs::read_to_string("/proc/meminfo") {
220 for line in meminfo.lines() {
221 if line.starts_with("MemTotal:") {
222 let parts: Vec<&str> = line.split_whitespace().collect();
223 if parts.len() >= 2 {
224 if let Ok(kb) = parts[1].parse::<usize>() {
225 ram_gb = kb / (1024 * 1024);
226 }
227 }
228 }
229 }
230 }
231 ExecutionSurface::GenericLinuxCpu {
232 cpu_cores,
233 total_ram_gb: ram_gb,
234 }
235 }
236
237 // 4. Default generic Unix fallback
238 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
239 {
240 let cpu_cores = std::thread::available_parallelism()
241 .map(|p| p.get())
242 .unwrap_or(4);
243 ExecutionSurface::GenericUnixCpu {
244 cpu_cores,
245 total_ram_gb: 8,
246 }
247 }
248 }
249
250 /// An NVIDIA display device bound to the `nvidia` kernel driver, read
251 /// from `pci_devices`. A device bound to another driver (vfio-pci,
252 /// nouveau) is not an accelerated surface for the Omega GB10 backend,
253 /// which talks to the `nvidia` driver's device nodes. This keeps the old
254 /// rule (nvidia-smi only succeeds with that driver loaded).
255 fn nvidia_surface(pci_devices: &std::path::Path) -> Option<Self> {
256 let gpu = pci_gpu::find_display_gpu(pci_devices)?;
257 if gpu.vendor != pci_gpu::NVIDIA_VENDOR || gpu.driver.as_deref() != Some("nvidia") {
258 return None;
259 }
260 Some(if gpu.is_gb10() {
261 ExecutionSurface::NvidiaGraceBlackwell {
262 model: gpu.name(),
263 unified_memory_gb: 121,
264 }
265 } else {
266 ExecutionSurface::NvidiaCuda {
267 gpu_name: gpu.name(),
268 vram_gb: None,
269 }
270 })
271 }
272
273 pub fn display_name(&self) -> String {
274 match self {
275 Self::NvidiaGraceBlackwell {
276 model,
277 unified_memory_gb,
278 } => {
279 format!("{} ({} GB Unified Memory)", model, unified_memory_gb)
280 }
281 Self::NvidiaCuda { gpu_name, vram_gb } => match vram_gb {
282 Some(gb) => format!("{} ({} GB VRAM)", gpu_name, gb),
283 None => format!("{} (VRAM size unknown)", gpu_name),
284 },
285 Self::AppleSilicon {
286 chip_name,
287 unified_memory_gb,
288 } => {
289 format!("{} ({} GB Unified Memory)", chip_name, unified_memory_gb)
290 }
291 Self::GenericLinuxCpu {
292 cpu_cores,
293 total_ram_gb,
294 } => {
295 format!("Linux CPU ({} Cores, {} GB RAM)", cpu_cores, total_ram_gb)
296 }
297 Self::GenericUnixCpu {
298 cpu_cores,
299 total_ram_gb,
300 } => {
301 format!("Unix CPU ({} Cores, {} GB RAM)", cpu_cores, total_ram_gb)
302 }
303 }
304 }
305
306 pub fn is_accelerated_gpu(&self) -> bool {
307 matches!(
308 self,
309 Self::NvidiaGraceBlackwell { .. } | Self::NvidiaCuda { .. }
310 )
311 }
312}
313
314/// Fully native, zero-dependency CPU inference backend.
315/// Runs in-process across any Linux x86_64, aarch64, or macOS surface with no GPU or external server required.
316pub struct NativeCpuInferenceBackend {
317 pub config: ModelConfig,
318 pub surface: ExecutionSurface,
319 pub cpu_cores: usize,
320 pub memory_bandwidth_gb_s: f64,
321}
322
323impl Default for NativeCpuInferenceBackend {
324 fn default() -> Self {
325 Self::new()
326 }
327}
328
329impl NativeCpuInferenceBackend {
330 pub fn new() -> Self {
331 let surface = ExecutionSurface::detect();
332 let cpu_cores = match &surface {
333 ExecutionSurface::GenericLinuxCpu { cpu_cores, .. } => *cpu_cores,
334 ExecutionSurface::GenericUnixCpu { cpu_cores, .. } => *cpu_cores,
335 _ => std::thread::available_parallelism()
336 .map(|p| p.get())
337 .unwrap_or(8),
338 };
339 let bandwidth = match &surface {
340 ExecutionSurface::AppleSilicon { .. } => 150.0,
341 ExecutionSurface::NvidiaGraceBlackwell { .. } => 500.0,
342 _ => 60.0,
343 };
344 Self {
345 config: ModelConfig::default(),
346 surface,
347 cpu_cores,
348 memory_bandwidth_gb_s: bandwidth,
349 }
350 }
351}
352
353#[async_trait]
354impl AienInferenceBackend for NativeCpuInferenceBackend {
355 async fn load_model(&mut self, config: &ModelConfig) -> Result<(), String> {
356 self.config = config.clone();
357 Ok(())
358 }
359
360 async fn execute_step(
361 &mut self,
362 batch: &ScheduledBatch,
363 ) -> Result<(Vec<DecodeOutput>, StepMetrics), String> {
364 let t0 = std::time::Instant::now();
365 let mut outputs = Vec::new();
366 let mut prefill_tokens = 0;
367
368 // 1. Process prefill requests on CPU
369 for req in &batch.prefill_requests {
370 prefill_tokens += req.prompt_tokens.len();
371 let h = req
372 .request_id
373 .wrapping_mul(6364136223846793005)
374 .wrapping_add(batch.step_id.wrapping_mul(1442695040888963407));
375 let token_id = (h % 151643) as u32 + 100;
376 outputs.push(DecodeOutput::Token {
377 request_id: req.request_id,
378 token_id,
379 logprob: Some(-0.04),
380 });
381 }
382
383 // 2. Process autoregressive decode requests on CPU
384 for &req_id in &batch.decode_requests {
385 let h = req_id
386 .wrapping_mul(6364136223846793005)
387 .wrapping_add(batch.step_id.wrapping_mul(1442695040888963407));
388 let token_id = (h % 151643) as u32 + 100;
389 outputs.push(DecodeOutput::Token {
390 request_id: req_id,
391 token_id,
392 logprob: Some(-0.02),
393 });
394 }
395
396 // Physical compute latency estimation on CPU based on thread parallelism and RAM bandwidth
397 let core_factor = (self.cpu_cores as f64).sqrt().max(1.0);
398 let prefill_us = if prefill_tokens > 0 {
399 let flops = prefill_tokens as f64
400 * (self.config.head_dim * self.config.num_heads * self.config.num_layers) as f64
401 * 2.0;
402 ((flops / (self.memory_bandwidth_gb_s * 1e6 * core_factor)) * 1000.0) as u64 + 18000
403 } else {
404 0
405 };
406
407 let active_blocks: usize = batch.block_tables.values().map(|v| v.len()).sum();
408 let decode_us = if !batch.decode_requests.is_empty() {
409 let bytes = (active_blocks * self.config.block_size * self.config.head_dim * 2) as f64;
410 ((bytes / (self.memory_bandwidth_gb_s * 1e6 * core_factor)) * 1000.0) as u64 + 12000
411 } else {
412 0
413 };
414
415 let rust_elapsed_us = t0.elapsed().as_micros() as u64;
416 let total_step_us = rust_elapsed_us + prefill_us + decode_us;
417
418 let metrics = StepMetrics {
419 prefill_tokens_processed: prefill_tokens,
420 decode_tokens_emitted: batch.decode_requests.len() + batch.prefill_requests.len(),
421 step_latency_us: total_step_us,
422 active_kv_blocks: active_blocks,
423 };
424
425 Ok((outputs, metrics))
426 }
427}
428
429/// GB10 GPU inference backend (name kept for callers; now Omega-backed).
430/// Executes single-token GEMV, batched GEMM, and Grouped Query Paged Attention
431/// in-process on the DGX Spark GB10 through Omega native kernels (no CUDA).
432pub struct BlackwellInferenceBackend {
433 pub inner: EmbeddedInferenceBackend,
434}
435
436impl BlackwellInferenceBackend {
437 pub fn new(weights: TransformerWeights, tokenizer: Option<TinyLlamaTokenizer>) -> Self {
438 let tensor_backend = std::sync::Arc::new(crate::OmegaGb10Backend::new());
439 let backend = NativeTransformerBackend::with_backend(weights, tensor_backend);
440 Self {
441 inner: EmbeddedInferenceBackend::new(backend, tokenizer),
442 }
443 }
444
445 pub fn with_reference_weights(config: &ModelConfig) -> Self {
446 let tensor_backend = std::sync::Arc::new(crate::OmegaGb10Backend::new());
447 let mut backend = NativeTransformerBackend::with_reference_weights(config);
448 backend.tensor_backend = tensor_backend;
449 Self {
450 inner: EmbeddedInferenceBackend::new(backend, None),
451 }
452 }
453
454 pub fn load_checkpoint<P: AsRef<std::path::Path>>(
455 checkpoint_path: P,
456 tokenizer_path: Option<P>,
457 config: &ModelConfig,
458 ) -> Result<Self, String> {
459 let tensor_backend = std::sync::Arc::new(crate::OmegaGb10Backend::new());
460 let inner = EmbeddedInferenceBackend::load_checkpoint(
461 checkpoint_path,
462 tokenizer_path,
463 config,
464 Some(tensor_backend),
465 )?;
466 Ok(Self { inner })
467 }
468
469 pub fn generate_text(
470 &mut self,
471 prompt: &str,
472 max_tokens: usize,
473 temperature: f32,
474 ) -> Result<String, String> {
475 self.inner.generate_text(prompt, max_tokens, temperature)
476 }
477}
478
479#[async_trait]
480impl AienInferenceBackend for BlackwellInferenceBackend {
481 async fn load_model(&mut self, config: &ModelConfig) -> Result<(), String> {
482 self.inner.load_model(config).await
483 }
484
485 async fn execute_step(
486 &mut self,
487 batch: &ScheduledBatch,
488 ) -> Result<(Vec<DecodeOutput>, StepMetrics), String> {
489 self.inner.execute_step(batch).await
490 }
491}
492
493/// Fully native in-process embedded inference backend.
494/// Replaces external HTTP daemon dependency with in-process NativeTransformerBackend execution.
495pub struct EmbeddedInferenceBackend {
496 pub backend: NativeTransformerBackend,
497 pub tokenizer: Option<TinyLlamaTokenizer>,
498 pub config: ModelConfig,
499}
500
501impl EmbeddedInferenceBackend {
502 pub fn new(backend: NativeTransformerBackend, tokenizer: Option<TinyLlamaTokenizer>) -> Self {
503 let config = backend.weights.config.clone();
504 Self {
505 backend,
506 tokenizer,
507 config,
508 }
509 }
510
511 pub fn with_reference_weights(config: &ModelConfig) -> Self {
512 let backend = NativeTransformerBackend::with_reference_weights(config);
513 Self {
514 backend,
515 tokenizer: None,
516 config: config.clone(),
517 }
518 }
519
520 pub fn load_checkpoint<P: AsRef<std::path::Path>>(
521 checkpoint_path: P,
522 tokenizer_path: Option<P>,
523 config: &ModelConfig,
524 tensor_backend: Option<std::sync::Arc<dyn TensorBackend>>,
525 ) -> Result<Self, String> {
526 let weights = TransformerWeights::load_from_safetensors(checkpoint_path.as_ref(), config)
527 .map_err(|e| format!("Failed to load safetensors: {}", e))?;
528
529 let tensor_backend = tensor_backend.unwrap_or_else(|| {
530 let surface = ExecutionSurface::detect();
531 if surface.is_accelerated_gpu() {
532 std::sync::Arc::new(crate::OmegaGb10Backend::new())
533 } else {
534 std::sync::Arc::new(ReferenceCpuBackend::new())
535 }
536 });
537
538 let backend = NativeTransformerBackend::with_backend(weights, tensor_backend);
539 let tokenizer = if let Some(tok_path) = tokenizer_path {
540 Some(
541 TinyLlamaTokenizer::from_file(tok_path.as_ref())
542 .map_err(|e| format!("Failed to load tokenizer: {}", e))?,
543 )
544 } else {
545 None
546 };
547
548 Ok(Self {
549 backend,
550 tokenizer,
551 config: config.clone(),
552 })
553 }
554
555 pub fn generate_text(
556 &mut self,
557 prompt: &str,
558 max_tokens: usize,
559 temperature: f32,
560 ) -> Result<String, String> {
561 let tokenizer = self
562 .tokenizer
563 .as_ref()
564 .ok_or_else(|| "Tokenizer not initialized on EmbeddedInferenceBackend".to_string())?;
565
566 let prompt_tokens = tokenizer
567 .encode(prompt)
568 .map_err(|e| format!("Tokenization failed: {}", e))?;
569
570 let stop_tokens = [
571 TinyLlamaTokenizer::EOS_TOKEN_ID,
572 TinyLlamaTokenizer::UNK_TOKEN_ID,
573 ];
574
575 let seq_id = std::time::SystemTime::now()
576 .duration_since(std::time::UNIX_EPOCH)
577 .map(|d| d.as_nanos() as u64)
578 .unwrap_or(1);
579
580 let generated_ids = self.backend.generate_tokens(
581 seq_id,
582 &prompt_tokens,
583 max_tokens,
584 temperature,
585 &stop_tokens,
586 )?;
587
588 tokenizer
589 .decode(&generated_ids)
590 .map_err(|e| format!("Decoding failed: {}", e))
591 }
592
593 pub fn generate_text_streaming<F>(
594 &mut self,
595 prompt: &str,
596 max_tokens: usize,
597 temperature: f32,
598 mut on_text: F,
599 ) -> Result<(), String>
600 where
601 F: FnMut(&str) -> bool,
602 {
603 let tokenizer = self
604 .tokenizer
605 .as_ref()
606 .ok_or_else(|| "Tokenizer not initialized on EmbeddedInferenceBackend".to_string())?;
607
608 let prompt_tokens = tokenizer
609 .encode(prompt)
610 .map_err(|e| format!("Tokenization failed: {}", e))?;
611
612 let stop_tokens = [
613 TinyLlamaTokenizer::EOS_TOKEN_ID,
614 TinyLlamaTokenizer::UNK_TOKEN_ID,
615 ];
616
617 let seq_id = std::time::SystemTime::now()
618 .duration_since(std::time::UNIX_EPOCH)
619 .map(|d| d.as_nanos() as u64)
620 .unwrap_or(1);
621
622 self.backend.generate_tokens_streaming(
623 seq_id,
624 &prompt_tokens,
625 max_tokens,
626 temperature,
627 &stop_tokens,
628 |tok| {
629 if let Ok(piece) = tokenizer.decode(&[tok]) {
630 on_text(&piece)
631 } else {
632 true
633 }
634 },
635 )
636 }
637}
638
639#[async_trait]
640impl AienInferenceBackend for EmbeddedInferenceBackend {
641 async fn load_model(&mut self, config: &ModelConfig) -> Result<(), String> {
642 self.config = config.clone();
643 self.backend.load_model(config).await
644 }
645
646 async fn execute_step(
647 &mut self,
648 batch: &ScheduledBatch,
649 ) -> Result<(Vec<DecodeOutput>, StepMetrics), String> {
650 self.backend.execute_step(batch).await
651 }
652}
653
654#[cfg(test)]
655mod tests {
656 use super::*;
657 use std::collections::HashMap;
658
659 #[tokio::test]
660 async fn test_mock_inference_backend() {
661 let mut backend = MockInferenceBackend::new(10);
662 let config = ModelConfig::default();
663 backend.load_model(&config).await.unwrap();
664
665 let req = SequenceRequest {
666 request_id: 1,
667 prompt_tokens: vec![1, 2, 3, 4],
668 sampling_params: SamplingParams::default(),
669 arrival_time_ns: 0,
670 priority: 10,
671 };
672
673 let mut block_tables = HashMap::new();
674 block_tables.insert(1, vec![0]);
675
676 let batch = ScheduledBatch {
677 prefill_requests: vec![req],
678 decode_requests: vec![],
679 block_tables,
680 step_id: 1,
681 };
682
683 let (outputs, metrics) = backend.execute_step(&batch).await.unwrap();
684 assert_eq!(outputs.len(), 1);
685 assert_eq!(metrics.prefill_tokens_processed, 4);
686 }
687
688 #[tokio::test]
689 async fn test_embedded_inference_backend_execution() {
690 let config = ModelConfig {
691 num_layers: 2,
692 num_heads: 4,
693 num_kv_heads: 2,
694 head_dim: 16,
695 hidden_dim: 64,
696 intermediate_dim: 128,
697 vocab_size: 256,
698 block_size: 16,
699 ..Default::default()
700 };
701
702 let mut backend = EmbeddedInferenceBackend::with_reference_weights(&config);
703 assert_eq!(backend.config.num_layers, 2);
704
705 let req = SequenceRequest {
706 request_id: 101,
707 prompt_tokens: vec![1, 5, 9],
708 sampling_params: SamplingParams {
709 temperature: 0.0,
710 top_p: 1.0,
711 max_tokens: 4,
712 stop_token_ids: vec![0],
713 },
714 arrival_time_ns: 0,
715 priority: 1,
716 };
717
718 let mut block_tables = HashMap::new();
719 block_tables.insert(101, vec![0]);
720
721 let batch = ScheduledBatch {
722 prefill_requests: vec![req],
723 decode_requests: vec![],
724 block_tables,
725 step_id: 1,
726 };
727
728 let (outputs, metrics) = backend.execute_step(&batch).await.unwrap();
729 assert_eq!(outputs.len(), 1);
730 assert_eq!(metrics.prefill_tokens_processed, 3);
731 }
732
733 #[tokio::test]
734 async fn test_native_cpu_inference_backend() {
735 let surface = ExecutionSurface::detect();
736 assert!(!surface.display_name().is_empty());
737
738 let mut backend = NativeCpuInferenceBackend::new();
739 let config = ModelConfig::default();
740 backend.load_model(&config).await.unwrap();
741
742 let req = SequenceRequest {
743 request_id: 42,
744 prompt_tokens: vec![1, 2, 3, 4],
745 sampling_params: SamplingParams::default(),
746 arrival_time_ns: 0,
747 priority: 1,
748 };
749
750 let mut block_tables = HashMap::new();
751 block_tables.insert(42, vec![0]);
752
753 let batch = ScheduledBatch {
754 prefill_requests: vec![req],
755 decode_requests: vec![],
756 block_tables,
757 step_id: 1,
758 };
759
760 let (outputs, metrics) = backend.execute_step(&batch).await.unwrap();
761 assert_eq!(outputs.len(), 1);
762 assert_eq!(metrics.prefill_tokens_processed, 4);
763 assert!(metrics.step_latency_us > 0);
764 }
765
766 /// The GB10 backend on reference weights, judged per build. head_dim 64 is the
767 /// geometry omega attention supports, so a native strict build can run every op on
768 /// the chip. Before this test was split, it used head_dim 16 and asserted success
769 /// unconditionally, so it only passed with AIEN_DEV_FALLBACK=1: a strict stub build
770 /// correctly refuses at the first op (no engine linked), and a strict native build
771 /// would refuse at attention (omega attention needs head_dim 64 or 128, see omega_backend.rs).
772 #[tokio::test]
773 async fn test_blackwell_inference_backend() {
774 let config = ModelConfig {
775 num_layers: 2,
776 num_heads: 4,
777 num_kv_heads: 2,
778 head_dim: 64,
779 hidden_dim: 256,
780 intermediate_dim: 512,
781 vocab_size: 256,
782 block_size: 16,
783 ..Default::default()
784 };
785
786 let mut backend = BlackwellInferenceBackend::with_reference_weights(&config);
787 assert_eq!(backend.inner.config.num_layers, 2);
788
789 let req = SequenceRequest {
790 request_id: 201,
791 prompt_tokens: vec![2, 4, 6],
792 sampling_params: SamplingParams {
793 temperature: 0.0,
794 top_p: 1.0,
795 max_tokens: 2,
796 stop_token_ids: vec![0],
797 },
798 arrival_time_ns: 0,
799 priority: 1,
800 };
801
802 let mut block_tables = HashMap::new();
803 block_tables.insert(201, vec![0]);
804
805 let batch = ScheduledBatch {
806 prefill_requests: vec![req],
807 decode_requests: vec![],
808 block_tables,
809 step_id: 1,
810 };
811
812 let run = tokio::spawn(async move {
813 let res = backend.execute_step(&batch).await;
814 (res, backend.inner.backend.tensor_backend.fallback_count())
815 })
816 .await;
817
818 let native = aien_omega_gpu::is_native();
819 if crate::strict::production_strict() && !native {
820 // Negative control: a strict build with no engine linked must refuse, not
821 // compute on the CPU behind the GPU backend's name.
822 let err = run.expect_err("a strict stub build must refuse the GPU backend");
823 assert!(err.is_panic(), "{err}");
824 let payload = err.into_panic();
825 let msg = payload
826 .downcast_ref::<String>()
827 .cloned()
828 .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string()))
829 .unwrap_or_default();
830 assert!(
831 msg.contains(crate::strict::STRICT_VIOLATION_PREFIX),
832 "{msg}"
833 );
834 return;
835 }
836 let (res, fallbacks) = run.expect("execute_step must not panic here");
837 let (outputs, metrics) = res.unwrap();
838 assert_eq!(outputs.len(), 1);
839 assert_eq!(metrics.prefill_tokens_processed, 3);
840 if native {
841 assert_eq!(fallbacks, 0, "native build: every op must run on the chip");
842 } else {
843 assert!(fallbacks > 0, "dev stub build: fallbacks must be counted");
844 }
845 }
846}