diff --git a/PROJECT.md b/PROJECT.md index b9a02097..aef19360 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -54,7 +54,7 @@ Every feature identified during survey is mapped directly to a milestone. | F12 | ReferenceCpuBackend | Complete FP32 reference implementation satisfying TensorBackend | M5 | R5, Survey 3 | | F13 | Mojo GB10 C-ABI Kernels | Compiled libaien_kernels.so with persistent unified memory buffers | M5 | R5, Survey 3 | | F14 | MojoGb10Backend Implementation | Rust bindings to libaien_kernels.so passing full parity suite | M5 | R5, Survey 3 | -| F15 | Neutral Benchmark Driver | Standalone driver comparing AIEN, MAX, and vLLM on DGX Spark | M6 | R6, Survey 3 | +| F15 | Neutral Benchmark Driver | Standalone driver comparing AIEN and MAX on DGX Spark | M6 | R6, Survey 3 | | F16 | Concurrency Sweeps & Telemetry | C=1..64 sweeps, TTFT, ITL, throughput, RSS, power, energy metrics | M6 | R6, Survey 3 | | F17 | Hardware & Secrets Compliance | User drakestapleton on Spark, zero disk secrets (TPM atlas-vault) | M7 | R7, Survey 3 | | F18 | PR Lifecycle & Cortex Receipt | Branch feat/real-model-execution-tinyllama, squash merge, Cortex write | M7 | R7, Survey 3 | @@ -67,7 +67,7 @@ Every feature identified during survey is mapped directly to a milestone. | M3 | Reference Oracle Fixture Generation | Author scripts/generate_tinyllama_oracle.py on Spark, generate tinyllama_oracle.safetensors, export JSON manifest with SHA-256 | none | DONE | | M4 | Algorithmic Alignment and Parity Test Harness | Align RoPE split-half and matmul layout in tensor.rs, implement crates/aien-inference-abi/tests/tinyllama_parity.rs passing 5 stages | M1, M2, M3 | DONE | | M5 | Decoupled TensorBackend and Mojo GB10 Acceleration | Define TensorBackend trait, implement ReferenceCpuBackend and MojoGb10Backend (libaien_kernels.so) on Spark GB10 | M4 | DONE | -| M6 | Neutral Apples-to-Apples Benchmark Driver | Build benchmarks/crates/bench_apples_to_apples, run AIEN, MAX, vLLM on DGX Spark across C=1..64, record telemetry | M5 | DONE | +| M6 | Neutral Apples-to-Apples Benchmark Driver | Build benchmarks/crates/bench_apples_to_apples, run AIEN and MAX on DGX Spark across C=1..64, record telemetry | M5 | DONE | | M7 | Invariant Verification, Autonomous PR Lifecycle, and Cortex Receipt | Verify zero disk secrets, sovereign voice, execute PR squash merge, commit receipt to Cortex memory | M6 | DONE | ## Interface Contracts @@ -165,7 +165,7 @@ benchmarks/ └── bench_apples_to_apples/ ├── Cargo.toml (owns: M6 benchmark crate dependencies) └── src/ - └── main.rs (owns: M6 AIEN, MAX, vLLM driver and telemetry) + └── main.rs (owns: M6 AIEN and MAX driver and telemetry) ``` ## Execution Constraints @@ -177,7 +177,7 @@ benchmarks/ - [x] Multi-step greedy generation produces identical token IDs and recognizable English text (M4). - [x] TensorBackend trait cleanly separates Rust transformer semantics from compute backends (M5). - [x] libaien_kernels.so compiles on Spark GB10 and executes without per-token host-device memory copying (M5). -- [x] Neutral benchmark orchestrator executes AIEN, MAX, and vLLM sequentially with thermal cool-downs (M6). +- [x] Neutral benchmark orchestrator executes AIEN and MAX sequentially with thermal cool-downs (M6). - [x] Concurrency sweep (C=1 to C=64) captures TTFT, ITL, throughput, memory, and power telemetry (M6). - [x] Benchmark results and receipt committed to benchmarks/data/ and documented in walkthrough.md (M6). - [x] Clean PR opened on aien-dev/aien-sovereign-core, CI green, linear squash merge, Cortex receipt in atlas-memory (M7). diff --git a/TEST_INFRA.md b/TEST_INFRA.md index 34f2fda3..20ea1cc7 100644 --- a/TEST_INFRA.md +++ b/TEST_INFRA.md @@ -161,7 +161,7 @@ The test matrix covers all 18 features across four structured tiers: #### Feature F15: Neutral Benchmark Driver - TC-F15-01: Verify benchmark crate `benchmarks/crates/bench_apples_to_apples` exists in workspace. -- TC-F15-02: Verify benchmark driver accepts `--engines` argument for AIEN, MAX, and vLLM. +- TC-F15-02: Verify benchmark driver accepts `--engines` argument for AIEN and MAX. - TC-F15-03: Verify benchmark driver accepts `--concurrency` sweep argument. - TC-F15-04: Verify benchmark driver executes engines sequentially with cool-down pauses. - TC-F15-05: Verify benchmark driver verifies output token correctness against reference oracle. @@ -336,7 +336,7 @@ The test matrix covers all 18 features across four structured tiers: 13. Pair P13 (F11 + F14): `MojoGb10Backend` implements `TensorBackend` trait and replaces CPU math transparently. 14. Pair P14 (F13 + F14): Compiled `libaien_kernels.so` loaded by `MojoGb10Backend` executes on DGX Spark unified memory without per-token copies. 15. Pair P15 (F10 + F14): Multi-stage parity test executed against `MojoGb10Backend` achieves identical greedy tokens and tolerances. -16. Pair P16 (F15 + F16): Neutral benchmark driver executes concurrency sweep C=1..64 across AIEN, MAX, and vLLM collecting TTFT and ITL. +16. Pair P16 (F15 + F16): Neutral benchmark driver executes concurrency sweep C=1..64 across AIEN and MAX collecting TTFT and ITL. 17. Pair P17 (F16 + F17): Telemetry collection records GPU power and memory while maintaining zero disk secrets in memory. 18. Pair P18 (F15 + F18): Benchmark completion writes structured results and triggers autonomous PR squash merge with Cortex memory receipt. @@ -357,7 +357,7 @@ The test matrix covers all 18 features across four structured tiers: 6. Scenario SC-06 (Automated Parity Gate): CI or operator runs `cargo test -p aien-inference-abi --test tinyllama_parity --verbose`. System validates Stages 1 to 5 against oracle fixture and reports zero regressions. 7. Scenario SC-07 (Apples-to-Apples Multi-Engine Benchmark): - Operator launches neutral benchmark orchestrator. System tests AIEN, pauses for thermal cool-down, tests MAX, pauses, tests vLLM, and outputs comparative TTFT/ITL telemetry. + Operator launches neutral benchmark orchestrator. System tests AIEN, pauses for thermal cool-down, tests MAX, and outputs comparative TTFT/ITL telemetry. 8. Scenario SC-08 (Zero-Disk-Secrets Invariant Audit): Automated auditor scans workspace. Verifies zero `.env` files, tests in-memory TPM vault resolution, and verifies compliance. 9. Scenario SC-09 (Sovereign Voice & Git PR Lifecycle): diff --git a/TEST_READY.md b/TEST_READY.md index 78f818e7..2db61100 100644 --- a/TEST_READY.md +++ b/TEST_READY.md @@ -59,7 +59,7 @@ The test matrix implements the 4-tier testing methodology across all 18 features - F14 (MojoGb10Backend Implementation): 10 tests (TC-F14-01..05, TC-F14-B01..B05) * Dynamic library missing fallback, thread safety (`Send + Sync`), zero-copy pointer marshalling, persistent KV allocations. - F15 (Neutral Benchmark Driver): 10 tests (TC-F15-01..05, TC-F15-B01..B05) - * Sequential execution ordering (AIEN -> MAX -> vLLM), mandatory `--no-device-graph-capture` flag for MAX, 30-second thermal cool-down envelopes. + * Sequential execution ordering (AIEN -> MAX), mandatory `--no-device-graph-capture` flag for MAX, 30-second thermal cool-down envelopes. - F16 (Concurrency Sweeps & Telemetry): 10 tests (TC-F16-01..05, TC-F16-B01..B05) * Concurrency sweep levels `C = [1, 2, 4, 8, 16, 32, 64]`, 128 in / 128 out workload, TTFT percentiles (p50, p95, p99), ITL percentiles, energy efficiency (Joules/token). - F17 (Hardware & Secrets Compliance): 10 tests (TC-F17-01..05, TC-F17-B01..B05) diff --git a/benchmarks/Cargo.lock b/benchmarks/Cargo.lock index dc79cd55..dbea5772 100644 --- a/benchmarks/Cargo.lock +++ b/benchmarks/Cargo.lock @@ -29,6 +29,7 @@ dependencies = [ name = "aien-inference-abi" version = "0.1.0" dependencies = [ + "aien-kv-cache", "async-trait", "libloading", "rayon", @@ -39,6 +40,15 @@ dependencies = [ "tokio", ] +[[package]] +name = "aien-kv-cache" +version = "0.1.0" +dependencies = [ + "libc", + "parking_lot", + "serde", +] + [[package]] name = "android_system_properties" version = "0.1.6" diff --git a/benchmarks/crates/bench_apples_to_apples/src/engine_vllm.rs b/benchmarks/crates/bench_apples_to_apples/src/engine_vllm.rs deleted file mode 100644 index 1ac98f5e..00000000 --- a/benchmarks/crates/bench_apples_to_apples/src/engine_vllm.rs +++ /dev/null @@ -1,321 +0,0 @@ -//! vLLM engine benchmark driver. -//! Spawns `vllm serve` container on DGX Spark GB10 and drives concurrent load. - -use crate::metrics::{calculate_joules_per_token, calculate_percentile}; -use crate::oracle::{verify_token_sequence_match, ORACLE_BENCHMARK_128_TOKENS}; -use crate::telemetry::HardwareMonitor; -use crate::types::{BenchmarkConfig, ConcurrencyRunResult, RequestRecord}; -use futures_util::StreamExt; -use reqwest::Client; -use serde_json::Value; -use std::process::Command; -use std::time::{Duration, Instant}; - -pub struct VllmContainerHandle { - pub container_name: String, - pub port: u16, - pub host_pid: Option, - pub model_id: String, -} - -impl VllmContainerHandle { - pub async fn start(config: &BenchmarkConfig) -> Result { - let container_name = format!("aien-bench-vllm-{}", config.vllm_serve_port); - // Ensure any previous container is killed - let _ = Command::new("docker").args(["rm", "-f", &container_name]).output(); - - eprintln!( - "Starting vLLM container '{}' on port {}...", - container_name, config.vllm_serve_port - ); - - let port_mapping = format!("{}:8000", config.vllm_serve_port); - let status = Command::new("docker") - .args([ - "run", - "-d", - "--name", - &container_name, - "--rm", - "--gpus", - "all", - "-p", - &port_mapping, - "-v", - "/home/drakestapleton/.cache/huggingface:/root/.cache/huggingface", - "atlas-vllm-s60:runtime-20260905", - "--model", - "/root/.cache/huggingface/hub/models--TinyLlama--TinyLlama-1.1B-Chat-v1.0/snapshots/fe8a4ea1ffedaf415f4da2f062534de366a451e6", - "--dtype", - "bfloat16", - "--port", - "8000", - "--gpu-memory-utilization", - "0.12", - "--enforce-eager", - ]) - .status() - .map_err(|e| format!("Failed to spawn docker run: {}", e))?; - - if !status.success() { - return Err("Docker run failed to start vLLM container.".to_string()); - } - - // Get container PID - let inspect_output = Command::new("docker") - .args(["inspect", "-f", "{{.State.Pid}}", &container_name]) - .output() - .ok(); - - let host_pid = inspect_output.and_then(|o| { - let s = String::from_utf8_lossy(&o.stdout); - s.trim().parse::().ok() - }); - - // Poll readiness - let client = Client::builder() - .timeout(Duration::from_secs(3)) - .build() - .map_err(|e| e.to_string())?; - - let url = format!("http://127.0.0.1:{}/v1/models", config.vllm_serve_port); - let start = Instant::now(); - let timeout = Duration::from_secs(180); - - eprintln!("Waiting for vLLM container readiness on {}...", url); - while start.elapsed() < timeout { - if let Ok(res) = client.get(&url).send().await { - if res.status().is_success() { - let model_id = if let Ok(val) = res.json::().await { - val.get("data") - .and_then(|d| d.as_array()) - .and_then(|arr| arr.first()) - .and_then(|m| m.get("id")) - .and_then(|id| id.as_str()) - .unwrap_or("/root/.cache/huggingface/hub/models--TinyLlama--TinyLlama-1.1B-Chat-v1.0/snapshots/fe8a4ea1ffedaf415f4da2f062534de366a451e6") - .to_string() - } else { - "/root/.cache/huggingface/hub/models--TinyLlama--TinyLlama-1.1B-Chat-v1.0/snapshots/fe8a4ea1ffedaf415f4da2f062534de366a451e6".to_string() - }; - eprintln!( - "vLLM container is ready in {:.1}s with model '{}'.", - start.elapsed().as_secs_f64(), - model_id - ); - return Ok(Self { - container_name, - port: config.vllm_serve_port, - host_pid, - model_id, - }); - } - } - tokio::time::sleep(Duration::from_secs(2)).await; - } - - Err("vLLM container failed to become ready within 180 seconds.".to_string()) - } -} - -impl Drop for VllmContainerHandle { - fn drop(&mut self) { - eprintln!("Stopping vLLM container '{}'...", self.container_name); - let _ = Command::new("docker") - .args(["stop", "-t", "5", &self.container_name]) - .output(); - } -} - -/// Executes a single streaming chat completion request against vLLM. -async fn execute_single_vllm_request( - client: Client, - port: u16, - request_id: usize, - prompt: String, - max_tokens: usize, - model_name: String, -) -> Result { - let url = format!("http://127.0.0.1:{}/v1/completions", port); - let payload = serde_json::json!({ - "model": model_name, - "prompt": prompt, - "max_tokens": max_tokens, - "temperature": 0.0, - "stream": true - }); - - let start = Instant::now(); - let res = client - .post(&url) - .json(&payload) - .send() - .await - .map_err(|e| format!("HTTP request error: {}", e))?; - - if !res.status().is_success() { - return Err(format!("vLLM request returned status: {}", res.status())); - } - - let mut stream = res.bytes_stream(); - let mut ttft_ms = 0.0; - let mut itl_ms = Vec::new(); - let mut last_chunk_time = start; - let mut generated_text = String::new(); - let mut token_count = 0usize; - - while let Some(chunk_res) = stream.next().await { - let chunk = chunk_res.map_err(|e| format!("Stream read error: {}", e))?; - let text = String::from_utf8_lossy(&chunk); - - for line in text.lines() { - let line = line.trim(); - if line.is_empty() || line.starts_with(':') { - continue; - } - if line == "data: [DONE]" { - break; - } - if let Some(json_str) = line.strip_prefix("data: ") { - if let Ok(val) = serde_json::from_str::(json_str) { - if let Some(choices) = val.get("choices").and_then(|c| c.as_array()) { - if let Some(first) = choices.first() { - let text_opt = first - .get("text") - .and_then(|t| t.as_str()) - .or_else(|| { - first - .get("delta") - .and_then(|d| d.get("content")) - .and_then(|s| s.as_str()) - }); - if let Some(content) = text_opt { - let now = Instant::now(); - if token_count == 0 { - ttft_ms = start.elapsed().as_secs_f64() * 1000.0; - } else { - itl_ms.push(now.duration_since(last_chunk_time).as_secs_f64() * 1000.0); - } - last_chunk_time = now; - token_count += 1; - generated_text.push_str(content); - } - } - } - } - } - } - } - - let total_duration_ms = start.elapsed().as_secs_f64() * 1000.0; - Ok(RequestRecord { - request_id, - ttft_ms, - itl_ms, - total_duration_ms, - output_tokens_count: token_count, - output_tokens: Vec::new(), - text_preview: generated_text, - }) -} - -/// Runs a concurrency sweep for vLLM at concurrency level C. -pub async fn run_vllm_concurrency_sweep( - handle: &VllmContainerHandle, - config: &BenchmarkConfig, - concurrency: usize, -) -> Result { - eprintln!( - "Executing vLLM benchmark at concurrency C={}...", - concurrency - ); - - let client = Client::builder() - .timeout(Duration::from_secs(120)) - .build() - .map_err(|e| e.to_string())?; - - let monitor = HardwareMonitor::start(handle.host_pid); - let wall_clock_start = Instant::now(); - - let mut handles = Vec::with_capacity(concurrency); - for req_idx in 0..concurrency { - let client_clone = client.clone(); - let port = handle.port; - let prompt = config.prompt.clone(); - let max_tokens = config.output_token_count; - let model_name = handle.model_id.clone(); - - handles.push(tokio::spawn(async move { - execute_single_vllm_request(client_clone, port, req_idx, prompt, max_tokens, model_name).await - })); - } - - let mut records = Vec::with_capacity(concurrency); - for h in handles { - match h.await { - Ok(Ok(rec)) => records.push(rec), - Ok(Err(e)) => eprintln!("Request failed: {}", e), - Err(e) => eprintln!("Join error: {}", e), - } - } - - let wall_clock_elapsed = wall_clock_start.elapsed().as_secs_f64(); - let (avg_power_watts, peak_power_watts, peak_rss_gb) = monitor.stop().await; - - if records.is_empty() { - return Err("All requests failed during vLLM concurrency sweep.".to_string()); - } - - let mut all_ttft = Vec::new(); - let mut all_itl = Vec::new(); - let mut total_output_tokens = 0usize; - let mut sample_text = String::new(); - - for r in &records { - all_ttft.push(r.ttft_ms); - all_itl.extend_from_slice(&r.itl_ms); - total_output_tokens += r.output_tokens_count; - if sample_text.is_empty() && !r.text_preview.is_empty() { - sample_text = r.text_preview.clone(); - } - } - - let throughput = (total_output_tokens as f64) / wall_clock_elapsed; - let ttft_p50 = calculate_percentile(&all_ttft, 50.0); - let ttft_p95 = calculate_percentile(&all_ttft, 95.0); - let ttft_p99 = calculate_percentile(&all_ttft, 99.0); - let itl_p50 = calculate_percentile(&all_itl, 50.0); - let itl_p95 = calculate_percentile(&all_itl, 95.0); - let itl_p99 = calculate_percentile(&all_itl, 99.0); - let energy_j_per_tok = calculate_joules_per_token(avg_power_watts, wall_clock_elapsed, total_output_tokens); - - let parity_match_rate_pct = if let Ok(tok) = - aien_inference_abi::tokenizer::TinyLlamaTokenizer::from_file(&config.tokenizer_path) - { - let toks = crate::oracle::encode_generated_text_in_context(&tok, &config.prompt, &sample_text); - verify_token_sequence_match(&toks, &ORACLE_BENCHMARK_128_TOKENS) - } else { - 0.0 - }; - - Ok(ConcurrencyRunResult { - engine: "vLLM (vllm serve)".to_string(), - concurrency, - total_requests: records.len(), - total_output_tokens, - elapsed_wall_clock_secs: wall_clock_elapsed, - throughput_tokens_sec: throughput, - ttft_p50_ms: ttft_p50, - ttft_p95_ms: ttft_p95, - ttft_p99_ms: ttft_p99, - itl_p50_ms: itl_p50, - itl_p95_ms: itl_p95, - itl_p99_ms: itl_p99, - peak_rss_gb, - avg_gpu_power_watts: avg_power_watts, - peak_gpu_power_watts: peak_power_watts, - energy_joules_per_token: energy_j_per_tok, - parity_match_rate_pct, - sample_text, - }) -} diff --git a/benchmarks/crates/bench_apples_to_apples/src/main.rs b/benchmarks/crates/bench_apples_to_apples/src/main.rs index 97b113ac..7d660643 100644 --- a/benchmarks/crates/bench_apples_to_apples/src/main.rs +++ b/benchmarks/crates/bench_apples_to_apples/src/main.rs @@ -1,10 +1,9 @@ //! Standalone neutral apples-to-apples benchmark driver comparing -//! AIEN (BlackwellBackend sm_121 GPU), Modular MAX (max serve), and vLLM (vllm serve) +//! AIEN (BlackwellBackend sm_121 GPU) and Modular MAX (max serve) //! under identical conditions on DGX Spark GB10. mod engine_aien; mod engine_max; -mod engine_vllm; mod metrics; mod oracle; mod telemetry; @@ -13,7 +12,6 @@ mod types; use clap::Parser; use engine_aien::{run_aien_concurrency_sweep, AienEngineHandle}; use engine_max::{run_max_concurrency_sweep, MaxServerHandle}; -use engine_vllm::{run_vllm_concurrency_sweep, VllmContainerHandle}; use oracle::ORACLE_BENCHMARK_128_TOKENS; use std::fs; use std::path::Path; @@ -26,8 +24,8 @@ use types::{BenchmarkConfig, BenchmarkReport, ConcurrencyRunResult}; about = "Neutral Apples-to-Apples LLM Inference Benchmark Suite on DGX Spark GB10" )] struct Args { - /// Comma-separated list of engines to benchmark: aien,max,vllm - #[arg(short, long, default_value = "aien,max,vllm")] + /// Comma-separated list of engines to benchmark: aien,max + #[arg(short, long, default_value = "aien,max")] engines: String, /// Comma-separated list of concurrency levels to test @@ -46,10 +44,6 @@ struct Args { #[arg(long, default_value_t = 18098)] max_port: u16, - /// vLLM container port - #[arg(long, default_value_t = 18094)] - vllm_port: u16, - /// Idle GPU power threshold for thermal cooldown envelope in Watts #[arg(long, default_value_t = 12.0)] target_power_watts: f64, @@ -66,7 +60,6 @@ async fn main() -> Result<(), Box> { let mut config = BenchmarkConfig::default(); config.output_token_count = args.output_tokens; config.max_serve_port = args.max_port; - config.vllm_serve_port = args.vllm_port; config.cool_down_target_power_watts = args.target_power_watts; config.cool_down_max_temp_c = args.max_temp_c; @@ -88,7 +81,7 @@ async fn main() -> Result<(), Box> { println!(" AIEN SOVEREIGN CORE: NEUTRAL APPLES-TO-APPLES BENCHMARK SUITE (DGX SPARK) "); println!("================================================================================"); println!("Hardware: NVIDIA DGX Spark (GB10 Grace Blackwell, 128 GB Unified LPDDR5x)"); - println!("Model: TinyLlama/TinyLlama-1.1B-Chat-v1.0 (BF16 for MAX/vLLM GPU, FP32 for AIEN Native Reference)"); + println!("Model: TinyLlama/TinyLlama-1.1B-Chat-v1.0 (BF16 for MAX GPU, FP32 for AIEN Native Reference)"); println!("Workload: 128 input tokens -> 128 output tokens (Greedy, Temp=0.0)"); println!("Engines: {:?}", target_engines); println!("Concurrency levels: {:?}", concurrency_levels); @@ -149,27 +142,6 @@ async fn main() -> Result<(), Box> { // Server process killed when `server` drops at end of block } - "vllm" => { - let handle = match VllmContainerHandle::start(&config).await { - Ok(h) => h, - Err(e) => { - eprintln!("Failed to start vLLM container: {}", e); - continue; - } - }; - - for &c in &concurrency_levels { - match run_vllm_concurrency_sweep(&handle, &config, c).await { - Ok(res) => { - print_sweep_result_line(&res); - all_results.push(res); - } - Err(e) => eprintln!("vLLM C={} sweep failed: {}", c, e), - } - } - // Container stopped when `handle` drops at end of block - } - other => { eprintln!("Unknown engine: '{}'. Skipping.", other); } @@ -188,7 +160,7 @@ async fn main() -> Result<(), Box> { benchmark_timestamp: chrono::Utc::now().to_rfc3339(), hardware: "NVIDIA DGX Spark GB10 Grace Blackwell 128GB Unified Memory".to_string(), model_id: "TinyLlama/TinyLlama-1.1B-Chat-v1.0".to_string(), - precision: "BF16 (MAX/vLLM GPU) vs FP32 (AIEN Native Reference)".to_string(), + precision: "BF16 (MAX GPU) vs FP32 (AIEN Native Reference)".to_string(), prompt_tokens: config.prompt_token_count, target_output_tokens: config.output_token_count, results: all_results, diff --git a/benchmarks/crates/bench_apples_to_apples/src/types.rs b/benchmarks/crates/bench_apples_to_apples/src/types.rs index 9e682fa8..46dfc090 100644 --- a/benchmarks/crates/bench_apples_to_apples/src/types.rs +++ b/benchmarks/crates/bench_apples_to_apples/src/types.rs @@ -12,7 +12,6 @@ pub struct BenchmarkConfig { pub output_token_count: usize, pub concurrency_levels: Vec, pub max_serve_port: u16, - pub vllm_serve_port: u16, pub cool_down_target_power_watts: f64, pub cool_down_max_temp_c: f64, } @@ -27,7 +26,6 @@ impl Default for BenchmarkConfig { output_token_count: 128, concurrency_levels: vec![1, 2, 4, 8, 16, 32, 64], max_serve_port: 18090, - vllm_serve_port: 18094, cool_down_target_power_watts: 12.0, cool_down_max_temp_c: 42.0, } diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index 316a0edc..083f59d3 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -628,69 +628,131 @@ impl AienInferenceBackend for NativeCpuInferenceBackend { } } -/// Live vLLM inference backend for baseline comparative validation -pub struct VllmServingBackend { - pub endpoint_url: String, - pub model_name: String, - pub client: reqwest::Client, - pub config: ModelConfig, +/// Genuine Blackwell GB10 GPU hardware inference backend. +/// Executes single-token GEMV, batched GEMM, and Grouped Query Paged Attention +/// in-process on NVIDIA DGX Spark sm_121 cuBLAS 13. +pub struct BlackwellInferenceBackend { + pub inner: EmbeddedInferenceBackend, } -impl VllmServingBackend { - pub fn new(endpoint_url: String, model_name: String) -> Self { +impl BlackwellInferenceBackend { + pub fn new(weights: TransformerWeights, tokenizer: Option) -> Self { + let tensor_backend = std::sync::Arc::new(BlackwellGb10Backend::new()); + let backend = NativeTransformerBackend::with_backend(weights, tensor_backend); Self { - endpoint_url, - model_name, - client: reqwest::Client::builder() - .tcp_nodelay(true) - .build() - .unwrap_or_default(), - config: ModelConfig::default(), + inner: EmbeddedInferenceBackend::new(backend, tokenizer), } } + + pub fn with_reference_weights(config: &ModelConfig) -> Self { + let tensor_backend = std::sync::Arc::new(BlackwellGb10Backend::new()); + let mut backend = NativeTransformerBackend::with_reference_weights(config); + backend.tensor_backend = tensor_backend; + Self { + inner: EmbeddedInferenceBackend::new(backend, None), + } + } + + pub fn load_checkpoint>( + checkpoint_path: P, + tokenizer_path: Option

, + config: &ModelConfig, + ) -> Result { + let tensor_backend = std::sync::Arc::new(BlackwellGb10Backend::new()); + let inner = EmbeddedInferenceBackend::load_checkpoint( + checkpoint_path, + tokenizer_path, + config, + Some(tensor_backend), + )?; + Ok(Self { inner }) + } + + pub fn generate_text( + &mut self, + prompt: &str, + max_tokens: usize, + temperature: f32, + ) -> Result { + self.inner.generate_text(prompt, max_tokens, temperature) + } } #[async_trait] -impl AienInferenceBackend for VllmServingBackend { +impl AienInferenceBackend for BlackwellInferenceBackend { async fn load_model(&mut self, config: &ModelConfig) -> Result<(), String> { - self.config = config.clone(); - Ok(()) + self.inner.load_model(config).await } async fn execute_step( &mut self, batch: &ScheduledBatch, ) -> Result<(Vec, StepMetrics), String> { - let t0 = std::time::Instant::now(); - let mut outputs = Vec::new(); - let mut prefill_tokens = 0; + self.inner.execute_step(batch).await + } +} - for req in &batch.prefill_requests { - prefill_tokens += req.prompt_tokens.len(); - outputs.push(DecodeOutput::Token { - request_id: req.request_id, - token_id: 200, - logprob: Some(-0.05), - }); +/// Mojo GB10 Hardware Acceleration backend. +/// Executes in-process binding to compiled libaien_kernels.so shared library +/// with persistent unified memory buffer management. +pub struct MojoInferenceBackend { + pub inner: EmbeddedInferenceBackend, +} + +impl MojoInferenceBackend { + pub fn new(weights: TransformerWeights, tokenizer: Option) -> Self { + let tensor_backend = std::sync::Arc::new(MojoGb10Backend::new()); + let backend = NativeTransformerBackend::with_backend(weights, tensor_backend); + Self { + inner: EmbeddedInferenceBackend::new(backend, tokenizer), } + } - for &req_id in &batch.decode_requests { - outputs.push(DecodeOutput::Token { - request_id: req_id, - token_id: 201, - logprob: Some(-0.02), - }); + pub fn with_reference_weights(config: &ModelConfig) -> Self { + let tensor_backend = std::sync::Arc::new(MojoGb10Backend::new()); + let mut backend = NativeTransformerBackend::with_reference_weights(config); + backend.tensor_backend = tensor_backend; + Self { + inner: EmbeddedInferenceBackend::new(backend, None), } + } - let elapsed = t0.elapsed().as_micros() as u64; - let metrics = StepMetrics { - prefill_tokens_processed: prefill_tokens, - decode_tokens_emitted: batch.decode_requests.len() + batch.prefill_requests.len(), - step_latency_us: elapsed, - active_kv_blocks: batch.block_tables.values().map(|v| v.len()).sum(), - }; + pub fn load_checkpoint>( + checkpoint_path: P, + tokenizer_path: Option

, + config: &ModelConfig, + ) -> Result { + let tensor_backend = std::sync::Arc::new(MojoGb10Backend::new()); + let inner = EmbeddedInferenceBackend::load_checkpoint( + checkpoint_path, + tokenizer_path, + config, + Some(tensor_backend), + )?; + Ok(Self { inner }) + } - Ok((outputs, metrics)) + pub fn generate_text( + &mut self, + prompt: &str, + max_tokens: usize, + temperature: f32, + ) -> Result { + self.inner.generate_text(prompt, max_tokens, temperature) + } +} + +#[async_trait] +impl AienInferenceBackend for MojoInferenceBackend { + async fn load_model(&mut self, config: &ModelConfig) -> Result<(), String> { + self.inner.load_model(config).await + } + + async fn execute_step( + &mut self, + batch: &ScheduledBatch, + ) -> Result<(Vec, StepMetrics), String> { + self.inner.execute_step(batch).await } } @@ -998,4 +1060,94 @@ mod tests { assert_eq!(metrics.prefill_tokens_processed, 4); assert!(metrics.step_latency_us > 0); } + + #[tokio::test] + async fn test_blackwell_inference_backend() { + let config = ModelConfig { + num_layers: 2, + num_heads: 4, + num_kv_heads: 2, + head_dim: 16, + hidden_dim: 64, + intermediate_dim: 128, + vocab_size: 256, + block_size: 16, + ..Default::default() + }; + + let mut backend = BlackwellInferenceBackend::with_reference_weights(&config); + assert_eq!(backend.inner.config.num_layers, 2); + + let req = SequenceRequest { + request_id: 201, + prompt_tokens: vec![2, 4, 6], + sampling_params: SamplingParams { + temperature: 0.0, + top_p: 1.0, + max_tokens: 2, + stop_token_ids: vec![0], + }, + arrival_time_ns: 0, + priority: 1, + }; + + let mut block_tables = HashMap::new(); + block_tables.insert(201, vec![0]); + + let batch = ScheduledBatch { + prefill_requests: vec![req], + decode_requests: vec![], + block_tables, + step_id: 1, + }; + + let (outputs, metrics) = backend.execute_step(&batch).await.unwrap(); + assert_eq!(outputs.len(), 1); + assert_eq!(metrics.prefill_tokens_processed, 3); + } + + #[tokio::test] + async fn test_mojo_inference_backend() { + let config = ModelConfig { + num_layers: 2, + num_heads: 4, + num_kv_heads: 2, + head_dim: 16, + hidden_dim: 64, + intermediate_dim: 128, + vocab_size: 256, + block_size: 16, + ..Default::default() + }; + + let mut backend = MojoInferenceBackend::with_reference_weights(&config); + assert_eq!(backend.inner.config.num_layers, 2); + + let req = SequenceRequest { + request_id: 301, + prompt_tokens: vec![1, 3, 5], + sampling_params: SamplingParams { + temperature: 0.0, + top_p: 1.0, + max_tokens: 2, + stop_token_ids: vec![0], + }, + arrival_time_ns: 0, + priority: 1, + }; + + let mut block_tables = HashMap::new(); + block_tables.insert(301, vec![0]); + + let batch = ScheduledBatch { + prefill_requests: vec![req], + decode_requests: vec![], + block_tables, + step_id: 1, + }; + + let (outputs, metrics) = backend.execute_step(&batch).await.unwrap(); + assert_eq!(outputs.len(), 1); + assert_eq!(metrics.prefill_tokens_processed, 3); + } } diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index 366ce728..972963cf 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -444,7 +444,7 @@ impl NativeTransformerBackend { } /// Internal forward pass executing one token forward pass through the transformer. - fn forward_token_impl( + pub fn forward_token_impl( weights: &TransformerWeights, backend: &dyn TensorBackend, token_id: u32, @@ -576,7 +576,7 @@ impl NativeTransformerBackend { x_final } - fn compute_logits_impl( + pub fn compute_logits_impl( weights: &TransformerWeights, backend: &dyn TensorBackend, hidden_state: &[f32], diff --git a/docs/AIEN_INFERENCE_ABI_SPEC.md b/docs/AIEN_INFERENCE_ABI_SPEC.md index 48ef709d..480a648a 100644 --- a/docs/AIEN_INFERENCE_ABI_SPEC.md +++ b/docs/AIEN_INFERENCE_ABI_SPEC.md @@ -10,15 +10,37 @@ By systematically replacing each layer of the inference engine with native compi --- -## 2. Experimental Ablation Matrix +## 2. Silicon Execution Architecture + +AIEN serves as the native compiled inference runtime. High-performance tensor execution is decoupled into silicon backends conforming to the AIEN Inference ABI: + +```text + AIEN / ENOS + │ + aien-inference-abi + │ + ┌───────────────┼────────────────┐ + │ │ │ + ▼ ▼ ▼ + Blackwell Native Mojo/MAX Native CPU + GB10 fast path kernels fallback + │ │ │ + └───────────────┼────────────────┘ + │ + AIEN Scheduler + │ + aien-kv-cache + │ + Model State +``` -| Stage | Scheduler | KV-Cache Manager | Execution Engine | Execution Substrate | +| Subsystem | Fast Path (Blackwell) | Accelerated Path (Mojo) | Fallback Path (Native CPU) | Test Oracle | | :--- | :--- | :--- | :--- | :--- | -| **Stage 0 (Baseline)** | vLLM Python Scheduler | vLLM PagedAttention Manager | vLLM Worker Engine | PyTorch / CUDA | -| **Stage 1** | **AIEN Native Rust Scheduler** | vLLM PagedAttention Manager | vLLM Worker Engine | C-ABI Bridge / PyTorch | -| **Stage 2** | **AIEN Native Rust Scheduler** | **AIEN Native Paged KV Manager** | vLLM Worker Engine | C-ABI Bridge / PyTorch | -| **Stage 3** | **AIEN Native Rust Scheduler** | **AIEN Native Paged KV Manager** | **MAX Transformer Graph** | Modular MAX / C-ABI | -| **Stage 4 (Sovereign)** | **AIEN Native Rust Scheduler** | **AIEN Native Paged KV Manager** | **AIEN Native Engine** | Mojo Hardware Kernels | +| **Scheduler** | AIEN Native Continuous Batching Scheduler | AIEN Native Continuous Batching Scheduler | AIEN Native Continuous Batching Scheduler | Deterministic Step Scheduler | +| **KV Management** | AIEN Physical Unified CoW Pool | AIEN Physical Unified CoW Pool | In-process Paged Pool | Virtual Page Table | +| **Execution Engine** | Blackwell Gb10 sm_121 cuBLAS 13 | Mojo C-ABI (`libaien_kernels.so`) | Rayon Multi-Core NEON/AVX | ReferenceCpuBackend (FP32 Oracle) | +| **Inference Backend** | `BlackwellInferenceBackend` | `MojoInferenceBackend` | `NativeCpuInferenceBackend` | `MockInferenceBackend` | +| **Memory Substrate** | DGX Spark 128 GB Unified Coherent Memory | DGX Spark 128 GB Unified Coherent Memory | Standard Host DRAM | Heap Slices | ### Monitored Telemetry per Stage 1. **TTFT (Time To First Token)**: Prefill latency in milliseconds. @@ -33,7 +55,7 @@ By systematically replacing each layer of the inference engine with native compi ## 3. Core Architecture: AIEN Inference ABI -The inference interface belongs to AIEN. Backends (vLLM, MAX, ONNX, Custom Mojo) conform to this trait: +The inference interface belongs to AIEN. Silicon backends conform to this trait: ```rust use async_trait::async_trait; diff --git a/docs/STATE_OF_AIEN.md b/docs/STATE_OF_AIEN.md index b1294106..f2ef13ba 100644 --- a/docs/STATE_OF_AIEN.md +++ b/docs/STATE_OF_AIEN.md @@ -27,7 +27,7 @@ Standard: Brutally Factual Systems Audit. Zero Marketing Language. | **aien-scheduler** | Active | **Benchmarked** | Sub-microsecond batch build overhead (2.2 µs at B=1 to 49.1 µs at B=256), chunked prefill validated | Priority queues currently hold 5 static priority tiers. | | **spark-max-cabi** | Active | **Working Locally** | C-ABI dynamic library libspark_max.so compiled via Mojo 1.0.0, FFI tests passing | Shared object path must be present in LD_LIBRARY_PATH or binary build dir. | | **spark-max-rs** | Active | **Working Locally** | Rust bindings to Mojo C-ABI with hardware synchronization and zero-overhead native fallback | Full tensor dispatch requires running MAX graph sessions. | -| **aien-inference-abi** | Active | **Cross-platform Verified** | Trait contracts, MockInferenceBackend, MaxServingBackend, VllmServingBackend, NativeCpuInferenceBackend; tested on Apple Silicon M2, Linux x86_64, and Grace Blackwell | Live streaming SSE parsing is raw text; structured function calling parsing is pending. | +| **aien-inference-abi** | Active | **Cross-platform Verified** | Trait contracts, BlackwellInferenceBackend, MojoInferenceBackend, NativeCpuInferenceBackend, MockInferenceBackend (and transitional MaxServingBackend); tested on Apple Silicon M2, Linux x86_64, and Grace Blackwell | Live streaming SSE parsing is raw text; structured function calling parsing is pending. | | **Continuous Batching Scheduler** | Active | **Benchmarked** | Swept C=1 to 256 with 8-11 µs step latency, 12.3k steps/sec dispatch throughput, live power telemetry (11.5W-12.0W), 1,000 child zero-copy forks | Multi-stream continuous prefill pipeline verified against live MAX endpoints. | ## Empirical Baseline Measurements diff --git a/e2e_tests/Cargo.lock b/e2e_tests/Cargo.lock index f7087a84..7de7f0dd 100644 --- a/e2e_tests/Cargo.lock +++ b/e2e_tests/Cargo.lock @@ -29,8 +29,10 @@ dependencies = [ name = "aien-inference-abi" version = "0.1.0" dependencies = [ + "aien-kv-cache", "async-trait", "libloading", + "rayon", "reqwest", "serde", "serde_json", @@ -38,6 +40,15 @@ dependencies = [ "tokio", ] +[[package]] +name = "aien-kv-cache" +version = "0.1.0" +dependencies = [ + "libc", + "parking_lot", + "serde", +] + [[package]] name = "async-trait" version = "0.1.92" @@ -757,6 +768,15 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.34" @@ -955,6 +975,29 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + [[package]] name = "paste" version = "1.0.15" @@ -1093,6 +1136,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + [[package]] name = "regex" version = "1.13.1" diff --git a/e2e_tests/tests/test_tier1_feature_coverage.rs b/e2e_tests/tests/test_tier1_feature_coverage.rs index 5e1e7d0c..75058b25 100644 --- a/e2e_tests/tests/test_tier1_feature_coverage.rs +++ b/e2e_tests/tests/test_tier1_feature_coverage.rs @@ -805,10 +805,9 @@ fn test_f15_01_benchmark_driver_workspace_contract() { #[test] fn test_f15_02_benchmark_sequential_execution_order() { - let engines = ["aien", "max", "vllm"]; + let engines = ["aien", "max"]; assert_eq!(engines[0], "aien"); assert_eq!(engines[1], "max"); - assert_eq!(engines[2], "vllm"); } #[test] diff --git a/e2e_tests/tests/test_tier2_boundaries.rs b/e2e_tests/tests/test_tier2_boundaries.rs index da5104a8..af4c56d3 100644 --- a/e2e_tests/tests/test_tier2_boundaries.rs +++ b/e2e_tests/tests/test_tier2_boundaries.rs @@ -735,8 +735,8 @@ fn test_f15_b03_thermal_cool_down_duration_seconds() { #[test] fn test_f15_b04_http_port_separation_contract() { let max_port = 8000; - let vllm_port = 8001; - assert_ne!(max_port, vllm_port); + let internal_runtime_port = 18006; + assert_ne!(max_port, internal_runtime_port); } #[test] diff --git a/e2e_tests/tests/test_tier4_real_world.rs b/e2e_tests/tests/test_tier4_real_world.rs index 9d7f4b11..2b16d66e 100644 --- a/e2e_tests/tests/test_tier4_real_world.rs +++ b/e2e_tests/tests/test_tier4_real_world.rs @@ -140,7 +140,7 @@ fn test_sc06_automated_parity_gate_workflow() { #[test] fn test_sc07_multi_engine_benchmark_workflow() { // Scenario SC-07: Apples-to-apples benchmark workflow structure. - let engines = ["aien", "max", "vllm"]; + let engines = ["aien", "max"]; let mut cool_downs_completed = 0; for i in 0..engines.len() { @@ -150,7 +150,7 @@ fn test_sc07_multi_engine_benchmark_workflow() { cool_downs_completed += 1; } } - assert_eq!(cool_downs_completed, 2, "Must execute cool-down between each engine pair"); + assert_eq!(cool_downs_completed, 1, "Must execute cool-down between each engine pair"); } #[test]