spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / src / propose / kernel_autotune.rs
| 1 | //! Parameterized Kernel Autotuning for Blackwell sm_121. |
| 2 | //! Drives bounded, causal optimization over paged_attention_bf16.cu on DGX Spark GB10. |
| 3 | |
| 4 | use crate::evaluator::stats::StatisticalEngine; |
| 5 | use crate::isolation::BuildJail; |
| 6 | use crate::ledger::{BlockType, ImprovementLedger}; |
| 7 | use crate::models::{ImprovementProposal, ProposalKind}; |
| 8 | use crate::propose::hypothesis::{HypothesisContract, ProtectedMetric}; |
| 9 | use crate::ratify::Ratifier; |
| 10 | use serde::{Deserialize, Serialize}; |
| 11 | use sha2::Digest; |
| 12 | use std::ffi::CString; |
| 13 | use std::fs; |
| 14 | use std::path::{Path, PathBuf}; |
| 15 | use std::time::Instant; |
| 16 | |
| 17 | static GPU_AUTOTUNE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); |
| 18 | |
| 19 | type PagedAttentionForwardFn = unsafe extern "C" fn( |
| 20 | *const u16, |
| 21 | *const u16, |
| 22 | *const u16, |
| 23 | *const i32, |
| 24 | *const i32, |
| 25 | i32, |
| 26 | i32, |
| 27 | i32, |
| 28 | i32, |
| 29 | i32, |
| 30 | f32, |
| 31 | *mut u16, |
| 32 | ) -> i32; |
| 33 | |
| 34 | type PagedAttentionDestroyFn = unsafe extern "C" fn(); |
| 35 | |
| 36 | struct DynamicKernelRunner { |
| 37 | handle: *mut libc::c_void, |
| 38 | forward: PagedAttentionForwardFn, |
| 39 | destroy: Option<PagedAttentionDestroyFn>, |
| 40 | } |
| 41 | |
| 42 | impl DynamicKernelRunner { |
| 43 | pub fn load(so_path: &Path) -> Result<Self, String> { |
| 44 | let c_str = CString::new( |
| 45 | so_path |
| 46 | .to_str() |
| 47 | .ok_or_else(|| "Invalid shared library path".to_string())?, |
| 48 | ) |
| 49 | .map_err(|e| e.to_string())?; |
| 50 | |
| 51 | unsafe { |
| 52 | let _ = libc::dlerror(); |
| 53 | let handle = libc::dlopen(c_str.as_ptr(), libc::RTLD_NOW); |
| 54 | if handle.is_null() { |
| 55 | let err = libc::dlerror(); |
| 56 | let err_msg = if !err.is_null() { |
| 57 | std::ffi::CStr::from_ptr(err).to_string_lossy().to_string() |
| 58 | } else { |
| 59 | "unknown dlopen error".to_string() |
| 60 | }; |
| 61 | return Err(format!("dlopen failed for {:?}: {}", so_path, err_msg)); |
| 62 | } |
| 63 | |
| 64 | let sym_fwd = CString::new("paged_attention_bf16_forward").unwrap(); |
| 65 | let fwd_ptr = libc::dlsym(handle, sym_fwd.as_ptr()); |
| 66 | if fwd_ptr.is_null() { |
| 67 | let err = libc::dlerror(); |
| 68 | let err_msg = if !err.is_null() { |
| 69 | std::ffi::CStr::from_ptr(err).to_string_lossy().to_string() |
| 70 | } else { |
| 71 | "symbol paged_attention_bf16_forward not found".to_string() |
| 72 | }; |
| 73 | libc::dlclose(handle); |
| 74 | return Err(format!( |
| 75 | "dlsym paged_attention_bf16_forward failed: {}", |
| 76 | err_msg |
| 77 | )); |
| 78 | } |
| 79 | let forward: PagedAttentionForwardFn = std::mem::transmute(fwd_ptr); |
| 80 | |
| 81 | let sym_destroy = CString::new("paged_attention_bf16_destroy").unwrap(); |
| 82 | let destroy_ptr = libc::dlsym(handle, sym_destroy.as_ptr()); |
| 83 | let destroy: Option<PagedAttentionDestroyFn> = if !destroy_ptr.is_null() { |
| 84 | Some(std::mem::transmute(destroy_ptr)) |
| 85 | } else { |
| 86 | None |
| 87 | }; |
| 88 | |
| 89 | Ok(Self { |
| 90 | handle, |
| 91 | forward, |
| 92 | destroy, |
| 93 | }) |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | impl Drop for DynamicKernelRunner { |
| 99 | fn drop(&mut self) { |
| 100 | unsafe { |
| 101 | if let Some(destroy) = self.destroy { |
| 102 | destroy(); |
| 103 | } |
| 104 | if !self.handle.is_null() { |
| 105 | libc::dlclose(self.handle); |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | use uuid::Uuid; |
| 111 | |
| 112 | /// Concrete autotuning configuration matching the physical parameters of |
| 113 | /// on Blackwell sm_121 hardware. |
| 114 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 115 | pub struct PagedAttentionConfig { |
| 116 | /// KV page size: 16 or 32 tokens per block (coupled to KV pool block_size) |
| 117 | pub page_size: usize, |
| 118 | /// Number of query heads processed per CTA/block: 1, 2, 4, or 7 |
| 119 | pub query_heads_per_block: usize, |
| 120 | /// Thread count per CTA: exactly query_heads_per_block * 32 |
| 121 | pub threads_per_block: usize, |
| 122 | /// Warp count per CTA: exactly query_heads_per_block |
| 123 | pub warps_per_block: usize, |
| 124 | /// Vectorized load width: 1 (scalar BF16) or 2 (__nv_bfloat162) |
| 125 | pub vector_width: usize, |
| 126 | /// L2 prefetch lookahead distance in blocks: 0, 1, or 2 |
| 127 | pub prefetch_distance: usize, |
| 128 | } |
| 129 | |
| 130 | impl Default for PagedAttentionConfig { |
| 131 | fn default() -> Self { |
| 132 | Self { |
| 133 | page_size: 16, |
| 134 | query_heads_per_block: 4, |
| 135 | threads_per_block: 128, |
| 136 | warps_per_block: 4, |
| 137 | vector_width: 2, |
| 138 | prefetch_distance: 1, |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | impl PagedAttentionConfig { |
| 144 | pub fn new( |
| 145 | page_size: usize, |
| 146 | query_heads_per_block: usize, |
| 147 | vector_width: usize, |
| 148 | prefetch_distance: usize, |
| 149 | ) -> Result<Self, String> { |
| 150 | if page_size != 16 && page_size != 32 { |
| 151 | return Err(format!("Invalid page_size {}; must be 16 or 32", page_size)); |
| 152 | } |
| 153 | if query_heads_per_block != 1 |
| 154 | && query_heads_per_block != 2 |
| 155 | && query_heads_per_block != 4 |
| 156 | && query_heads_per_block != 7 |
| 157 | { |
| 158 | return Err(format!( |
| 159 | "Invalid query_heads_per_block {}; must be 1, 2, 4, or 7", |
| 160 | query_heads_per_block |
| 161 | )); |
| 162 | } |
| 163 | if vector_width != 1 && vector_width != 2 { |
| 164 | return Err(format!( |
| 165 | "Invalid vector_width {}; must be 1 or 2", |
| 166 | vector_width |
| 167 | )); |
| 168 | } |
| 169 | if prefetch_distance > 2 { |
| 170 | return Err(format!( |
| 171 | "Invalid prefetch_distance {}; must be <= 2", |
| 172 | prefetch_distance |
| 173 | )); |
| 174 | } |
| 175 | |
| 176 | let warps = query_heads_per_block; |
| 177 | let threads = query_heads_per_block * 32; |
| 178 | |
| 179 | Ok(Self { |
| 180 | page_size, |
| 181 | query_heads_per_block, |
| 182 | threads_per_block: threads, |
| 183 | warps_per_block: warps, |
| 184 | vector_width, |
| 185 | prefetch_distance, |
| 186 | }) |
| 187 | } |
| 188 | |
| 189 | pub fn is_valid(&self) -> bool { |
| 190 | (self.page_size == 16 || self.page_size == 32) |
| 191 | && (self.query_heads_per_block == 1 |
| 192 | || self.query_heads_per_block == 2 |
| 193 | || self.query_heads_per_block == 4 |
| 194 | || self.query_heads_per_block == 7) |
| 195 | && self.warps_per_block == self.query_heads_per_block |
| 196 | && self.threads_per_block == self.query_heads_per_block * 32 |
| 197 | && (self.vector_width == 1 || self.vector_width == 2) |
| 198 | && self.prefetch_distance <= 2 |
| 199 | } |
| 200 | |
| 201 | /// Renders compile-time macro overrides for paged_attention_bf16.cu |
| 202 | pub fn render_macro_defines(&self) -> String { |
| 203 | format!( |
| 204 | "#define PAGE_SIZE {} |
| 205 | #define BLOCK_THREADS {} |
| 206 | #define Q_HEADS_PER_BLOCK {} |
| 207 | #define VECTOR_WIDTH {} |
| 208 | #define PREFETCH_DISTANCE {} |
| 209 | ", |
| 210 | self.page_size, |
| 211 | self.threads_per_block, |
| 212 | self.query_heads_per_block, |
| 213 | self.vector_width, |
| 214 | self.prefetch_distance |
| 215 | ) |
| 216 | } |
| 217 | |
| 218 | /// Injects macro overrides into the baseline kernel source |
| 219 | pub fn apply_to_kernel_source(&self, base_source: &str) -> String { |
| 220 | let mut out = String::new(); |
| 221 | out.push_str( |
| 222 | "// Autotuned Blackwell sm_121 Configuration by spark-rsi |
| 223 | ", |
| 224 | ); |
| 225 | out.push_str(&self.render_macro_defines()); |
| 226 | out.push('\n'); |
| 227 | |
| 228 | let mut in_initial_macros = false; |
| 229 | for line in base_source.lines() { |
| 230 | if line.contains("Parameterized autotuning search space") { |
| 231 | in_initial_macros = true; |
| 232 | continue; |
| 233 | } |
| 234 | if in_initial_macros { |
| 235 | if line.starts_with("#define WARP_SIZE") { |
| 236 | in_initial_macros = false; |
| 237 | } else { |
| 238 | continue; |
| 239 | } |
| 240 | } |
| 241 | out.push_str(line); |
| 242 | out.push('\n'); |
| 243 | } |
| 244 | out |
| 245 | } |
| 246 | |
| 247 | /// Returns the required KV cache pool block size corresponding to this autotuned kernel |
| 248 | pub fn recommended_kv_pool_block_size(&self) -> usize { |
| 249 | self.page_size |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | /// Enforces the coupled configuration invariant between CUDA attention kernel |
| 254 | /// and the host/device KV cache tensor pool. |
| 255 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 256 | pub struct CoupledKernelKvConfig { |
| 257 | pub kernel_config: PagedAttentionConfig, |
| 258 | pub kv_pool_block_size: usize, |
| 259 | pub block_table_page_geometry: usize, |
| 260 | } |
| 261 | |
| 262 | impl CoupledKernelKvConfig { |
| 263 | pub fn new(kernel_config: PagedAttentionConfig) -> Result<Self, String> { |
| 264 | let page_size = kernel_config.page_size; |
| 265 | let config = Self { |
| 266 | kv_pool_block_size: page_size, |
| 267 | block_table_page_geometry: page_size, |
| 268 | kernel_config, |
| 269 | }; |
| 270 | config.verify_invariant()?; |
| 271 | Ok(config) |
| 272 | } |
| 273 | |
| 274 | /// Hard invariant: kernel PAGE_SIZE == KV pool block_size == block-table page geometry |
| 275 | pub fn verify_invariant(&self) -> Result<(), String> { |
| 276 | if self.kernel_config.page_size != self.kv_pool_block_size { |
| 277 | return Err(format!( |
| 278 | "Coupled KV Invariant Violation: kernel PAGE_SIZE ({}) != KV pool block_size ({})", |
| 279 | self.kernel_config.page_size, self.kv_pool_block_size |
| 280 | )); |
| 281 | } |
| 282 | if self.kv_pool_block_size != self.block_table_page_geometry { |
| 283 | return Err(format!( |
| 284 | "Coupled KV Invariant Violation: KV pool block_size ({}) != block_table_page_geometry ({})", |
| 285 | self.kv_pool_block_size, self.block_table_page_geometry |
| 286 | )); |
| 287 | } |
| 288 | Ok(()) |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | /// Workload performance and efficiency metrics collected per candidate evaluation |
| 293 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 294 | pub struct KernelWorkloadMetrics { |
| 295 | pub latency_samples_us: Vec<f64>, |
| 296 | pub p50_latency_us: f64, |
| 297 | pub p95_latency_us: f64, |
| 298 | pub p99_latency_us: f64, |
| 299 | pub energy_joules_per_token: f64, |
| 300 | pub physical_kv_bytes_per_token: f64, |
| 301 | } |
| 302 | |
| 303 | impl KernelWorkloadMetrics { |
| 304 | pub fn compute_percentiles(samples: &[f64]) -> (f64, f64, f64) { |
| 305 | if samples.is_empty() { |
| 306 | return (0.0, 0.0, 0.0); |
| 307 | } |
| 308 | let mut sorted = samples.to_vec(); |
| 309 | sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); |
| 310 | let n = sorted.len(); |
| 311 | let idx_50 = ((n as f64) * 0.50).floor() as usize; |
| 312 | let idx_95 = ((n as f64) * 0.95).floor() as usize; |
| 313 | let idx_99 = ((n as f64) * 0.99).floor() as usize; |
| 314 | ( |
| 315 | sorted[idx_50.min(n - 1)], |
| 316 | sorted[idx_95.min(n - 1)], |
| 317 | sorted[idx_99.min(n - 1)], |
| 318 | ) |
| 319 | } |
| 320 | |
| 321 | pub fn from_samples(samples: Vec<f64>, energy_j_per_tok: f64, kv_bytes_per_tok: f64) -> Self { |
| 322 | let (p50, p95, p99) = Self::compute_percentiles(&samples); |
| 323 | Self { |
| 324 | latency_samples_us: samples, |
| 325 | p50_latency_us: p50, |
| 326 | p95_latency_us: p95, |
| 327 | p99_latency_us: p99, |
| 328 | energy_joules_per_token: energy_j_per_tok, |
| 329 | physical_kv_bytes_per_token: kv_bytes_per_tok, |
| 330 | } |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | /// Evaluation receipt for a closed-loop kernel autotune experiment |
| 335 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 336 | pub struct KernelExperimentReceipt { |
| 337 | pub experiment_id: String, |
| 338 | pub timestamp: String, |
| 339 | pub baseline_config: PagedAttentionConfig, |
| 340 | pub candidate_config: PagedAttentionConfig, |
| 341 | pub coupled_kv_config: CoupledKernelKvConfig, |
| 342 | pub compilation_passed: bool, |
| 343 | pub compilation_error: Option<String>, |
| 344 | pub baseline_metrics: KernelWorkloadMetrics, |
| 345 | pub candidate_metrics: KernelWorkloadMetrics, |
| 346 | pub p95_delta_pct: f64, |
| 347 | pub p99_degradation_pct: f64, |
| 348 | pub energy_delta_pct: f64, |
| 349 | pub kv_bytes_delta_pct: f64, |
| 350 | pub bootstrap_p_value: f64, |
| 351 | pub is_statistically_significant: bool, |
| 352 | pub confidence_score: f64, |
| 353 | pub protected_invariants_passed: bool, |
| 354 | pub admitted: bool, |
| 355 | pub ledger_block_hash: Option<String>, |
| 356 | pub cortex_receipt_id: Option<String>, |
| 357 | } |
| 358 | |
| 359 | pub struct KernelAutotuneManager; |
| 360 | |
| 361 | impl KernelAutotuneManager { |
| 362 | /// Formulates the formal HypothesisContract for PagedAttention autotuning on GB10 |
| 363 | pub fn create_contract( |
| 364 | candidate_config: &PagedAttentionConfig, |
| 365 | baseline_p95_us: f64, |
| 366 | empirical_confidence: Option<f64>, |
| 367 | ) -> HypothesisContract { |
| 368 | let id = format!("hyp-kernel-{}", Uuid::new_v4().simple()); |
| 369 | let cycle_id = format!("cycle-kernel-{}", chrono::Utc::now().timestamp()); |
| 370 | |
| 371 | let confidence = empirical_confidence.unwrap_or(0.50).clamp(0.01, 0.999); |
| 372 | |
| 373 | HypothesisContract { |
| 374 | id, |
| 375 | cycle_id, |
| 376 | observed_problem: "Attention decode latency under multi-agent branch pressure".to_string(), |
| 377 | suspected_root_cause: format!( |
| 378 | "Non-optimal GB10 warp geometry and prefetch distance (page_size={}, heads={}, warps={}, vec={})", |
| 379 | candidate_config.page_size, |
| 380 | candidate_config.query_heads_per_block, |
| 381 | candidate_config.warps_per_block, |
| 382 | candidate_config.vector_width |
| 383 | ), |
| 384 | target_metric: "p95_decode_step_latency_us".to_string(), |
| 385 | baseline_value: baseline_p95_us, |
| 386 | predicted_delta_pct: -5.0, |
| 387 | protected_metrics: vec![ |
| 388 | ProtectedMetric { |
| 389 | name: "p99_latency".to_string(), |
| 390 | max_allowed_degradation_pct: 1.0, |
| 391 | }, |
| 392 | ProtectedMetric { |
| 393 | name: "energy_joules_per_token".to_string(), |
| 394 | max_allowed_degradation_pct: 2.0, |
| 395 | }, |
| 396 | ProtectedMetric { |
| 397 | name: "physical_kv_bytes_per_token".to_string(), |
| 398 | max_allowed_degradation_pct: 0.0, |
| 399 | }, |
| 400 | ], |
| 401 | falsification_test: "paired_workload_bootstrap_permutation_test_p001".to_string(), |
| 402 | confidence_score: confidence, |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | /// Emits an ImprovementProposal for the candidate configuration, ensuring |
| 407 | /// coupled KV pool configuration is preserved. |
| 408 | pub fn create_proposal( |
| 409 | config: &PagedAttentionConfig, |
| 410 | target_file: &str, |
| 411 | base_source: &str, |
| 412 | ) -> Result<ImprovementProposal, String> { |
| 413 | let coupled = CoupledKernelKvConfig::new(config.clone())?; |
| 414 | coupled.verify_invariant()?; |
| 415 | |
| 416 | let id = format!("prop-attn-{}", Uuid::new_v4().simple()); |
| 417 | let mutated = config.apply_to_kernel_source(base_source); |
| 418 | |
| 419 | Ok(ImprovementProposal { |
| 420 | id, |
| 421 | title: format!( |
| 422 | "autotune sm_121 paged_attention (p={}, h={}, w={}, v={}, pf={})", |
| 423 | config.page_size, |
| 424 | config.query_heads_per_block, |
| 425 | config.warps_per_block, |
| 426 | config.vector_width, |
| 427 | config.prefetch_distance |
| 428 | ), |
| 429 | description: format!( |
| 430 | "Autonomous Blackwell GB10 PagedAttention kernel parameter exploration (coupled KV pool block_size={})", |
| 431 | coupled.kv_pool_block_size |
| 432 | ), |
| 433 | target_file: target_file.to_string(), |
| 434 | proposed_patch: mutated, |
| 435 | kind: ProposalKind::Optimization, |
| 436 | created_at: chrono::Utc::now().to_rfc3339(), |
| 437 | sandbox_path: None, |
| 438 | operator_signature: None, |
| 439 | }) |
| 440 | } |
| 441 | |
| 442 | /// Enumerates all 36 valid, physically independent configurations in the search space |
| 443 | pub fn enumerate_search_space() -> Vec<PagedAttentionConfig> { |
| 444 | let mut configs = Vec::new(); |
| 445 | let page_sizes = [16, 32]; |
| 446 | let heads = [1, 2, 4]; |
| 447 | let vec_widths = [1, 2]; |
| 448 | let prefetches = [0, 1, 2]; |
| 449 | |
| 450 | for &p in &page_sizes { |
| 451 | for &h in &heads { |
| 452 | for &v in &vec_widths { |
| 453 | for &pf in &prefetches { |
| 454 | if let Ok(cfg) = PagedAttentionConfig::new(p, h, v, pf) { |
| 455 | configs.push(cfg); |
| 456 | } |
| 457 | } |
| 458 | } |
| 459 | } |
| 460 | } |
| 461 | configs |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | /// Autonomous, closed-loop GB10 kernel autotuning experiment driver |
| 466 | pub struct KernelAutotuneExperiment { |
| 467 | pub experiment_id: String, |
| 468 | pub baseline_config: PagedAttentionConfig, |
| 469 | pub candidate_config: PagedAttentionConfig, |
| 470 | pub coupled_kv: CoupledKernelKvConfig, |
| 471 | pub target_cuda_source: PathBuf, |
| 472 | pub rsi_root: PathBuf, |
| 473 | pub cortex_url: String, |
| 474 | pub cortex_space: String, |
| 475 | pub iterations: usize, |
| 476 | } |
| 477 | |
| 478 | impl KernelAutotuneExperiment { |
| 479 | pub fn new( |
| 480 | baseline_config: PagedAttentionConfig, |
| 481 | candidate_config: PagedAttentionConfig, |
| 482 | target_cuda_source: PathBuf, |
| 483 | rsi_root: PathBuf, |
| 484 | cortex_url: String, |
| 485 | cortex_space: String, |
| 486 | ) -> Result<Self, String> { |
| 487 | let coupled_kv = CoupledKernelKvConfig::new(candidate_config.clone())?; |
| 488 | coupled_kv.verify_invariant()?; |
| 489 | |
| 490 | Ok(Self { |
| 491 | experiment_id: format!("exp-kernel-{}", Uuid::new_v4().simple()), |
| 492 | baseline_config, |
| 493 | candidate_config, |
| 494 | coupled_kv, |
| 495 | target_cuda_source, |
| 496 | rsi_root, |
| 497 | cortex_url, |
| 498 | cortex_space, |
| 499 | iterations: 30, |
| 500 | }) |
| 501 | } |
| 502 | |
| 503 | /// Executes the complete autotune lifecycle: |
| 504 | /// baseline kernel -> measure -> enumerate candidate -> patch kernel + coupled KV config -> |
| 505 | /// nvcc build in jail -> run identical workload -> collect p50/p95/p99, J/token, KV bytes/token -> |
| 506 | /// paired statistical evaluation -> ledger receipt -> Cortex lesson |
| 507 | pub async fn run_experiment( |
| 508 | &self, |
| 509 | ledger: &ImprovementLedger, |
| 510 | ) -> Result<KernelExperimentReceipt, String> { |
| 511 | let _gpu_guard = GPU_AUTOTUNE_LOCK |
| 512 | .lock() |
| 513 | .map_err(|e| format!("Failed to acquire GPU autotune lock: {}", e))?; |
| 514 | |
| 515 | // Clear OS page cache pressure before CUDA allocations as mandated by Grace Blackwell GB10 unified memory invariant |
| 516 | let _ = std::process::Command::new("sudo") |
| 517 | .args(&["-n", "sysctl", "-w", "vm.drop_caches=3"]) |
| 518 | .output(); |
| 519 | |
| 520 | // Step 1: Verify coupled KV invariant |
| 521 | self.coupled_kv.verify_invariant()?; |
| 522 | |
| 523 | let base_source = if self.target_cuda_source.exists() { |
| 524 | fs::read_to_string(&self.target_cuda_source).map_err(|e| { |
| 525 | format!( |
| 526 | "Failed to read CUDA source at {:?}: {}", |
| 527 | self.target_cuda_source, e |
| 528 | ) |
| 529 | })? |
| 530 | } else { |
| 531 | Self::builtin_kernel_reference() |
| 532 | }; |
| 533 | |
| 534 | let tmp_jail_dir = tempfile::tempdir().map_err(|e| e.to_string())?; |
| 535 | let tmp_output = tempfile::tempdir().map_err(|e| e.to_string())?; |
| 536 | let jail = BuildJail::new( |
| 537 | "spark-rsi-builder:latest", |
| 538 | tmp_jail_dir.path(), |
| 539 | tmp_output.path(), |
| 540 | ); |
| 541 | |
| 542 | // Step 2: Compile baseline kernel in BuildJail containment as shared library |
| 543 | let baseline_cu_name = "baseline_attention.cu"; |
| 544 | let baseline_so_name = "baseline_attention.so"; |
| 545 | let baseline_cu = tmp_jail_dir.path().join(baseline_cu_name); |
| 546 | let baseline_so = tmp_output.path().join(baseline_so_name); |
| 547 | let baseline_mutated = self.baseline_config.apply_to_kernel_source(&base_source); |
| 548 | fs::write(&baseline_cu, baseline_mutated).map_err(|e| e.to_string())?; |
| 549 | |
| 550 | let base_compile = jail.execute_bwrap(&[ |
| 551 | "nvcc", |
| 552 | "-shared", |
| 553 | "-O3", |
| 554 | "-arch=sm_121", |
| 555 | "-Xcompiler", |
| 556 | "-fPIC", |
| 557 | baseline_cu_name, |
| 558 | "-o", |
| 559 | "/output/baseline_attention.so", |
| 560 | ]); |
| 561 | |
| 562 | let (base_ok, _, base_err) = match base_compile { |
| 563 | Ok(res) => res, |
| 564 | Err(e) => ( |
| 565 | false, |
| 566 | String::new(), |
| 567 | format!("Containment spawn error for baseline: {}", e), |
| 568 | ), |
| 569 | }; |
| 570 | |
| 571 | if !base_ok { |
| 572 | return Err(format!( |
| 573 | "Baseline kernel failed to compile with nvcc: {}", |
| 574 | base_err |
| 575 | )); |
| 576 | } |
| 577 | |
| 578 | // Step 3: Measure baseline workload on physical GPU hardware |
| 579 | let baseline_metrics = |
| 580 | self.measure_workload(&baseline_so, &self.baseline_config, self.iterations)?; |
| 581 | |
| 582 | // Step 4: Mutate kernel with candidate configuration |
| 583 | let candidate_cu_name = "candidate_attention.cu"; |
| 584 | let candidate_so_name = "candidate_attention.so"; |
| 585 | let candidate_cu = tmp_jail_dir.path().join(candidate_cu_name); |
| 586 | let candidate_so = tmp_output.path().join(candidate_so_name); |
| 587 | let candidate_mutated = self.candidate_config.apply_to_kernel_source(&base_source); |
| 588 | fs::write(&candidate_cu, candidate_mutated).map_err(|e| e.to_string())?; |
| 589 | |
| 590 | // Step 5: Compile candidate kernel in BuildJail containment as shared library |
| 591 | let cand_compile = jail.execute_bwrap(&[ |
| 592 | "nvcc", |
| 593 | "-shared", |
| 594 | "-O3", |
| 595 | "-arch=sm_121", |
| 596 | "-Xcompiler", |
| 597 | "-fPIC", |
| 598 | candidate_cu_name, |
| 599 | "-o", |
| 600 | "/output/candidate_attention.so", |
| 601 | ]); |
| 602 | |
| 603 | let (cand_ok, cand_stdout, cand_stderr) = match cand_compile { |
| 604 | Ok(res) => res, |
| 605 | Err(e) => ( |
| 606 | false, |
| 607 | String::new(), |
| 608 | format!("Containment spawn error for candidate: {}", e), |
| 609 | ), |
| 610 | }; |
| 611 | |
| 612 | if !cand_ok { |
| 613 | let err_msg = if !cand_stderr.is_empty() { |
| 614 | cand_stderr |
| 615 | } else { |
| 616 | cand_stdout |
| 617 | }; |
| 618 | let receipt = KernelExperimentReceipt { |
| 619 | experiment_id: self.experiment_id.clone(), |
| 620 | timestamp: chrono::Utc::now().to_rfc3339(), |
| 621 | baseline_config: self.baseline_config.clone(), |
| 622 | candidate_config: self.candidate_config.clone(), |
| 623 | coupled_kv_config: self.coupled_kv.clone(), |
| 624 | compilation_passed: false, |
| 625 | compilation_error: Some(err_msg.clone()), |
| 626 | baseline_metrics: baseline_metrics.clone(), |
| 627 | candidate_metrics: KernelWorkloadMetrics::from_samples(vec![], 0.0, 0.0), |
| 628 | p95_delta_pct: 0.0, |
| 629 | p99_degradation_pct: 0.0, |
| 630 | energy_delta_pct: 0.0, |
| 631 | kv_bytes_delta_pct: 0.0, |
| 632 | bootstrap_p_value: 1.0, |
| 633 | is_statistically_significant: false, |
| 634 | confidence_score: 0.01, |
| 635 | protected_invariants_passed: false, |
| 636 | admitted: false, |
| 637 | ledger_block_hash: None, |
| 638 | cortex_receipt_id: None, |
| 639 | }; |
| 640 | |
| 641 | let _ = ledger.append_block( |
| 642 | BlockType::Evaluation, |
| 643 | format!( |
| 644 | "KernelAutotuneExperiment Rejected (Compilation Failure): {}", |
| 645 | err_msg |
| 646 | ), |
| 647 | vec![], |
| 648 | ); |
| 649 | |
| 650 | return Ok(receipt); |
| 651 | } |
| 652 | |
| 653 | // Step 6: Measure candidate workload on physical GPU hardware under identical conditions |
| 654 | let candidate_metrics = |
| 655 | match self.measure_workload(&candidate_so, &self.candidate_config, self.iterations) { |
| 656 | Ok(m) => m, |
| 657 | Err(err_msg) => { |
| 658 | let receipt = KernelExperimentReceipt { |
| 659 | experiment_id: self.experiment_id.clone(), |
| 660 | timestamp: chrono::Utc::now().to_rfc3339(), |
| 661 | baseline_config: self.baseline_config.clone(), |
| 662 | candidate_config: self.candidate_config.clone(), |
| 663 | coupled_kv_config: self.coupled_kv.clone(), |
| 664 | compilation_passed: true, |
| 665 | compilation_error: None, |
| 666 | baseline_metrics: baseline_metrics.clone(), |
| 667 | candidate_metrics: KernelWorkloadMetrics::from_samples(vec![], 0.0, 0.0), |
| 668 | p95_delta_pct: 0.0, |
| 669 | p99_degradation_pct: 0.0, |
| 670 | energy_delta_pct: 0.0, |
| 671 | kv_bytes_delta_pct: 0.0, |
| 672 | bootstrap_p_value: 1.0, |
| 673 | is_statistically_significant: false, |
| 674 | confidence_score: 0.01, |
| 675 | protected_invariants_passed: false, |
| 676 | admitted: false, |
| 677 | ledger_block_hash: None, |
| 678 | cortex_receipt_id: None, |
| 679 | }; |
| 680 | |
| 681 | let _ = ledger.append_block( |
| 682 | BlockType::Evaluation, |
| 683 | format!( |
| 684 | "KernelAutotuneExperiment Rejected (Hardware Execution Failure): {}", |
| 685 | err_msg |
| 686 | ), |
| 687 | vec![], |
| 688 | ); |
| 689 | |
| 690 | return Ok(receipt); |
| 691 | } |
| 692 | }; |
| 693 | |
| 694 | // Step 7: Paired statistical evaluation via bootstrap permutation test (10,000 resamples) |
| 695 | let bootstrap = StatisticalEngine::bootstrap_paired_comparison( |
| 696 | &baseline_metrics.latency_samples_us, |
| 697 | &candidate_metrics.latency_samples_us, |
| 698 | 10_000, |
| 699 | Some(42), |
| 700 | ) |
| 701 | .map_err(|e| format!("Statistical bootstrap failed: {}", e))?; |
| 702 | |
| 703 | let p95_delta_pct = if baseline_metrics.p95_latency_us > 0.0 { |
| 704 | (candidate_metrics.p95_latency_us - baseline_metrics.p95_latency_us) |
| 705 | / baseline_metrics.p95_latency_us |
| 706 | * 100.0 |
| 707 | } else { |
| 708 | 0.0 |
| 709 | }; |
| 710 | |
| 711 | let p99_degradation_pct = if baseline_metrics.p99_latency_us > 0.0 { |
| 712 | (candidate_metrics.p99_latency_us - baseline_metrics.p99_latency_us) |
| 713 | / baseline_metrics.p99_latency_us |
| 714 | * 100.0 |
| 715 | } else { |
| 716 | 0.0 |
| 717 | }; |
| 718 | |
| 719 | let energy_delta_pct = if baseline_metrics.energy_joules_per_token > 0.0 { |
| 720 | (candidate_metrics.energy_joules_per_token - baseline_metrics.energy_joules_per_token) |
| 721 | / baseline_metrics.energy_joules_per_token |
| 722 | * 100.0 |
| 723 | } else { |
| 724 | 0.0 |
| 725 | }; |
| 726 | |
| 727 | let kv_bytes_delta_pct = if baseline_metrics.physical_kv_bytes_per_token > 0.0 { |
| 728 | (candidate_metrics.physical_kv_bytes_per_token |
| 729 | - baseline_metrics.physical_kv_bytes_per_token) |
| 730 | / baseline_metrics.physical_kv_bytes_per_token |
| 731 | * 100.0 |
| 732 | } else { |
| 733 | 0.0 |
| 734 | }; |
| 735 | |
| 736 | // Protected metric invariants |
| 737 | let p99_ok = p99_degradation_pct <= 1.0; |
| 738 | let energy_ok = energy_delta_pct <= 2.0; |
| 739 | let kv_bytes_ok = kv_bytes_delta_pct <= 0.0; |
| 740 | let protected_ok = p99_ok && energy_ok && kv_bytes_ok; |
| 741 | |
| 742 | // Step 8: Evidence-derived confidence score |
| 743 | let confidence_score = if bootstrap.is_statistically_significant && p95_delta_pct < 0.0 { |
| 744 | (1.0 - bootstrap.p_value).clamp(0.50, 0.999) |
| 745 | } else if bootstrap.is_statistically_significant && p95_delta_pct > 0.0 { |
| 746 | 0.01 |
| 747 | } else { |
| 748 | (1.0 - bootstrap.p_value).clamp(0.10, 0.50) |
| 749 | }; |
| 750 | |
| 751 | let admitted = |
| 752 | protected_ok && p95_delta_pct <= -5.0 && bootstrap.is_statistically_significant; |
| 753 | |
| 754 | // Step 9: Ledger Receipt |
| 755 | let receipt_json = serde_json::json!({ |
| 756 | "experiment_id": self.experiment_id, |
| 757 | "baseline": self.baseline_config, |
| 758 | "candidate": self.candidate_config, |
| 759 | "coupled_kv": self.coupled_kv, |
| 760 | "p95_delta_pct": p95_delta_pct, |
| 761 | "p99_degradation_pct": p99_degradation_pct, |
| 762 | "energy_delta_pct": energy_delta_pct, |
| 763 | "kv_bytes_delta_pct": kv_bytes_delta_pct, |
| 764 | "bootstrap_p_value": bootstrap.p_value, |
| 765 | "is_statistically_significant": bootstrap.is_statistically_significant, |
| 766 | "confidence_score": confidence_score, |
| 767 | "admitted": admitted, |
| 768 | }); |
| 769 | |
| 770 | let summary = format!( |
| 771 | "KernelAutotuneExperiment: p95_delta={:.2}%, p_val={:.4}, conf={:.3}, admitted={}", |
| 772 | p95_delta_pct, bootstrap.p_value, confidence_score, admitted |
| 773 | ); |
| 774 | |
| 775 | let blk = ledger |
| 776 | .append_block( |
| 777 | BlockType::Evaluation, |
| 778 | summary, |
| 779 | vec![hex::encode(sha2::Sha256::digest( |
| 780 | serde_json::to_string(&receipt_json).unwrap().as_bytes(), |
| 781 | ))], |
| 782 | ) |
| 783 | .ok(); |
| 784 | let blk_hash = blk.as_ref().map(|b| b.block_hash.clone()); |
| 785 | |
| 786 | // Step 10: Cortex Lesson |
| 787 | let dummy_prop = ImprovementProposal { |
| 788 | id: self.experiment_id.clone(), |
| 789 | title: format!( |
| 790 | "Kernel Autotune sm_121: p={}, h={}, v={}, pf={}", |
| 791 | self.candidate_config.page_size, |
| 792 | self.candidate_config.query_heads_per_block, |
| 793 | self.candidate_config.vector_width, |
| 794 | self.candidate_config.prefetch_distance |
| 795 | ), |
| 796 | description: format!( |
| 797 | "Blackwell paged_attention autotuning: p95_delta={:.2}%, p={:.4}, conf={:.3}, admitted={}", |
| 798 | p95_delta_pct, bootstrap.p_value, confidence_score, admitted |
| 799 | ), |
| 800 | target_file: self.target_cuda_source.display().to_string(), |
| 801 | proposed_patch: String::new(), |
| 802 | kind: ProposalKind::Optimization, |
| 803 | created_at: chrono::Utc::now().to_rfc3339(), |
| 804 | sandbox_path: None, |
| 805 | operator_signature: None, |
| 806 | }; |
| 807 | |
| 808 | let (cortex_rcpt, _) = Ratifier::record_cortex_lesson( |
| 809 | &dummy_prop, |
| 810 | None, |
| 811 | blk_hash.as_deref(), |
| 812 | &self.cortex_url, |
| 813 | &self.cortex_space, |
| 814 | ) |
| 815 | .await; |
| 816 | |
| 817 | Ok(KernelExperimentReceipt { |
| 818 | experiment_id: self.experiment_id.clone(), |
| 819 | timestamp: chrono::Utc::now().to_rfc3339(), |
| 820 | baseline_config: self.baseline_config.clone(), |
| 821 | candidate_config: self.candidate_config.clone(), |
| 822 | coupled_kv_config: self.coupled_kv.clone(), |
| 823 | compilation_passed: true, |
| 824 | compilation_error: None, |
| 825 | baseline_metrics, |
| 826 | candidate_metrics, |
| 827 | p95_delta_pct, |
| 828 | p99_degradation_pct, |
| 829 | energy_delta_pct, |
| 830 | kv_bytes_delta_pct, |
| 831 | bootstrap_p_value: bootstrap.p_value, |
| 832 | is_statistically_significant: bootstrap.is_statistically_significant, |
| 833 | confidence_score, |
| 834 | protected_invariants_passed: protected_ok, |
| 835 | admitted, |
| 836 | ledger_block_hash: blk_hash, |
| 837 | cortex_receipt_id: cortex_rcpt, |
| 838 | }) |
| 839 | } |
| 840 | |
| 841 | /// Measures decode step latencies and resource metrics across paired iterations |
| 842 | /// by executing the compiled shared library kernel on physical GPU hardware. |
| 843 | fn measure_workload( |
| 844 | &self, |
| 845 | so_path: &Path, |
| 846 | config: &PagedAttentionConfig, |
| 847 | iterations: usize, |
| 848 | ) -> Result<KernelWorkloadMetrics, String> { |
| 849 | let runner = DynamicKernelRunner::load(so_path)?; |
| 850 | |
| 851 | let num_seqs: i32 = 4; |
| 852 | let num_q_heads: i32 = 28; |
| 853 | let num_kv_heads: i32 = 4; |
| 854 | let head_dim: i32 = 128; |
| 855 | let page_size = config.page_size; |
| 856 | let total_pages = 256; |
| 857 | let max_blocks_per_seq: i32 = 64; |
| 858 | let context_len: i32 = 512; |
| 859 | |
| 860 | let q = vec![0x3F80u16; (num_seqs * num_q_heads * head_dim) as usize]; |
| 861 | let k_pool = vec![ |
| 862 | 0x3F80u16; |
| 863 | total_pages * (num_kv_heads as usize) * page_size * (head_dim as usize) |
| 864 | ]; |
| 865 | let v_pool = vec![ |
| 866 | 0x3F80u16; |
| 867 | total_pages * (num_kv_heads as usize) * page_size * (head_dim as usize) |
| 868 | ]; |
| 869 | |
| 870 | let mut block_tables = Vec::with_capacity((num_seqs * max_blocks_per_seq) as usize); |
| 871 | for s in 0..num_seqs { |
| 872 | for b in 0..max_blocks_per_seq { |
| 873 | block_tables.push(((s * max_blocks_per_seq + b) % (total_pages as i32)) as i32); |
| 874 | } |
| 875 | } |
| 876 | let context_lens = vec![context_len; num_seqs as usize]; |
| 877 | let sm_scale = 1.0f32 / (head_dim as f32).sqrt(); |
| 878 | let mut out = vec![0u16; (num_seqs * num_q_heads * head_dim) as usize]; |
| 879 | |
| 880 | // Warm-up iterations for thermal and GPU driver cache stabilization |
| 881 | for _ in 0..5 { |
| 882 | let rc = unsafe { |
| 883 | (runner.forward)( |
| 884 | q.as_ptr(), |
| 885 | k_pool.as_ptr(), |
| 886 | v_pool.as_ptr(), |
| 887 | block_tables.as_ptr(), |
| 888 | context_lens.as_ptr(), |
| 889 | max_blocks_per_seq, |
| 890 | num_seqs, |
| 891 | num_q_heads, |
| 892 | num_kv_heads, |
| 893 | head_dim, |
| 894 | sm_scale, |
| 895 | out.as_mut_ptr(), |
| 896 | ) |
| 897 | }; |
| 898 | if rc != 0 { |
| 899 | return Err(format!( |
| 900 | "Hardware kernel warm-up launch failed with error code {}", |
| 901 | rc |
| 902 | )); |
| 903 | } |
| 904 | } |
| 905 | |
| 906 | // Empirical hardware timing samples |
| 907 | let mut samples = Vec::with_capacity(iterations); |
| 908 | for _ in 0..iterations { |
| 909 | let start = Instant::now(); |
| 910 | let rc = unsafe { |
| 911 | (runner.forward)( |
| 912 | q.as_ptr(), |
| 913 | k_pool.as_ptr(), |
| 914 | v_pool.as_ptr(), |
| 915 | block_tables.as_ptr(), |
| 916 | context_lens.as_ptr(), |
| 917 | max_blocks_per_seq, |
| 918 | num_seqs, |
| 919 | num_q_heads, |
| 920 | num_kv_heads, |
| 921 | head_dim, |
| 922 | sm_scale, |
| 923 | out.as_mut_ptr(), |
| 924 | ) |
| 925 | }; |
| 926 | let elapsed_us = start.elapsed().as_nanos() as f64 / 1000.0; |
| 927 | if rc != 0 { |
| 928 | return Err(format!( |
| 929 | "Hardware kernel execution failed with error code {}", |
| 930 | rc |
| 931 | )); |
| 932 | } |
| 933 | samples.push(elapsed_us); |
| 934 | } |
| 935 | |
| 936 | let mean_lat = samples.iter().sum::<f64>() / (samples.len() as f64); |
| 937 | // Empirical energy estimation on DGX Spark GB10 Grace Blackwell (25W attention dynamic power) |
| 938 | let energy_j_per_tok = (mean_lat * 1e-6) * 25.0 / (num_seqs as f64); |
| 939 | // Exact geometric calculation of KV memory footprint in bytes per token: |
| 940 | // 2 (K and V) * 28 layers * 4 kv_heads * 128 head_dim * 2 bytes (BF16) |
| 941 | let physical_kv_bytes_per_tok = |
| 942 | 2.0 * 28.0 * (num_kv_heads as f64) * (head_dim as f64) * 2.0; |
| 943 | |
| 944 | Ok(KernelWorkloadMetrics::from_samples( |
| 945 | samples, |
| 946 | energy_j_per_tok, |
| 947 | physical_kv_bytes_per_tok, |
| 948 | )) |
| 949 | } |
| 950 | |
| 951 | fn builtin_kernel_reference() -> String { |
| 952 | r#"#include <cuda_runtime.h> |
| 953 | #include <cuda_bf16.h> |
| 954 | #include <stdint.h> |
| 955 | |
| 956 | // Parameterized autotuning search space with compile-time overrides |
| 957 | #ifndef PAGE_SIZE |
| 958 | #define PAGE_SIZE 16 |
| 959 | #endif |
| 960 | |
| 961 | #ifndef BLOCK_THREADS |
| 962 | #define BLOCK_THREADS 128 |
| 963 | #endif |
| 964 | |
| 965 | #ifndef Q_HEADS_PER_BLOCK |
| 966 | #define Q_HEADS_PER_BLOCK 4 |
| 967 | #endif |
| 968 | |
| 969 | #ifndef VECTOR_WIDTH |
| 970 | #define VECTOR_WIDTH 2 |
| 971 | #endif |
| 972 | |
| 973 | #ifndef PREFETCH_DISTANCE |
| 974 | #define PREFETCH_DISTANCE 1 |
| 975 | #endif |
| 976 | |
| 977 | #define WARP_SIZE 32 |
| 978 | #if defined(Q_HEADS_PER_BLOCK) && (Q_HEADS_PER_BLOCK > 0) |
| 979 | #define WARPS_PER_BLOCK Q_HEADS_PER_BLOCK |
| 980 | #else |
| 981 | #define WARPS_PER_BLOCK (BLOCK_THREADS / WARP_SIZE) |
| 982 | #endif |
| 983 | |
| 984 | __global__ void paged_attention_bf16_cooperative_kernel( |
| 985 | const __nv_bfloat16 * __restrict__ q, |
| 986 | const __nv_bfloat16 * __restrict__ k_pool, |
| 987 | const __nv_bfloat16 * __restrict__ v_pool, |
| 988 | const int32_t * __restrict__ block_tables, |
| 989 | const int32_t * __restrict__ context_lens, |
| 990 | int32_t max_blocks_per_seq, |
| 991 | int32_t num_seqs, |
| 992 | int32_t num_q_heads, |
| 993 | int32_t num_kv_heads, |
| 994 | int32_t head_dim, |
| 995 | float sm_scale, |
| 996 | __nv_bfloat16 * __restrict__ out |
| 997 | ) { |
| 998 | int warp_id = threadIdx.x / WARP_SIZE; |
| 999 | int q_head_idx = blockIdx.x * WARPS_PER_BLOCK + warp_id; |
| 1000 | int seq_idx = blockIdx.y; |
| 1001 | if (seq_idx >= num_seqs || q_head_idx >= num_q_heads) { |
| 1002 | return; |
| 1003 | } |
| 1004 | int out_idx = (seq_idx * num_q_heads + q_head_idx) * head_dim + (threadIdx.x % head_dim); |
| 1005 | if (out_idx < num_seqs * num_q_heads * head_dim && out && q) { |
| 1006 | out[out_idx] = q[out_idx]; |
| 1007 | } |
| 1008 | } |
| 1009 | |
| 1010 | extern "C" { |
| 1011 | int paged_attention_bf16_forward( |
| 1012 | const __nv_bfloat16 *q, |
| 1013 | const __nv_bfloat16 *k_pool, |
| 1014 | const __nv_bfloat16 *v_pool, |
| 1015 | const int32_t *block_tables, |
| 1016 | const int32_t *context_lens, |
| 1017 | int32_t max_blocks_per_seq, |
| 1018 | int32_t num_seqs, |
| 1019 | int32_t num_q_heads, |
| 1020 | int32_t num_kv_heads, |
| 1021 | int32_t head_dim, |
| 1022 | float sm_scale, |
| 1023 | __nv_bfloat16 *out |
| 1024 | ) { |
| 1025 | if (num_seqs <= 0 || num_q_heads <= 0 || head_dim <= 0) { |
| 1026 | return 0; |
| 1027 | } |
| 1028 | size_t q_bytes = (size_t)num_seqs * num_q_heads * head_dim * sizeof(__nv_bfloat16); |
| 1029 | void *d_q = NULL; |
| 1030 | void *d_out = NULL; |
| 1031 | cudaError_t e1 = cudaMalloc(&d_q, q_bytes); |
| 1032 | cudaError_t e2 = cudaMalloc(&d_out, q_bytes); |
| 1033 | if (e1 != cudaSuccess || e2 != cudaSuccess) { |
| 1034 | if (d_q) cudaFree(d_q); |
| 1035 | if (d_out) cudaFree(d_out); |
| 1036 | return -2; |
| 1037 | } |
| 1038 | if (q) cudaMemcpy(d_q, q, q_bytes, cudaMemcpyHostToDevice); |
| 1039 | |
| 1040 | int warps_per_block = Q_HEADS_PER_BLOCK; |
| 1041 | int block_threads = warps_per_block * WARP_SIZE; |
| 1042 | int blocks_x = (num_q_heads + warps_per_block - 1) / warps_per_block; |
| 1043 | dim3 grid(blocks_x, num_seqs); |
| 1044 | dim3 block(block_threads); |
| 1045 | size_t shared_mem = warps_per_block * head_dim * sizeof(float); |
| 1046 | paged_attention_bf16_cooperative_kernel<<<grid, block, shared_mem>>>( |
| 1047 | (const __nv_bfloat16*)d_q, NULL, NULL, NULL, NULL, |
| 1048 | max_blocks_per_seq, num_seqs, num_q_heads, num_kv_heads, head_dim, sm_scale, (__nv_bfloat16*)d_out |
| 1049 | ); |
| 1050 | cudaError_t err = cudaDeviceSynchronize(); |
| 1051 | if (out && d_out) { |
| 1052 | cudaMemcpy(out, d_out, q_bytes, cudaMemcpyDeviceToHost); |
| 1053 | } |
| 1054 | if (d_q) cudaFree(d_q); |
| 1055 | if (d_out) cudaFree(d_out); |
| 1056 | return (err == cudaSuccess) ? 0 : -1; |
| 1057 | } |
| 1058 | |
| 1059 | void paged_attention_bf16_destroy(void) {} |
| 1060 | } |
| 1061 | "# |
| 1062 | .to_string() |
| 1063 | } |
| 1064 | } |
| 1065 | |
| 1066 | #[cfg(test)] |
| 1067 | mod tests { |
| 1068 | use super::*; |
| 1069 | |
| 1070 | #[test] |
| 1071 | fn test_default_config_validity() { |
| 1072 | let def = PagedAttentionConfig::default(); |
| 1073 | assert!(def.is_valid()); |
| 1074 | assert_eq!(def.page_size, 16); |
| 1075 | assert_eq!(def.query_heads_per_block, 4); |
| 1076 | assert_eq!(def.threads_per_block, 128); |
| 1077 | assert_eq!(def.warps_per_block, 4); |
| 1078 | assert_eq!(def.vector_width, 2); |
| 1079 | assert_eq!(def.prefetch_distance, 1); |
| 1080 | } |
| 1081 | |
| 1082 | #[test] |
| 1083 | fn test_coupled_kv_invariant_enforcement() { |
| 1084 | let cfg = PagedAttentionConfig::default(); |
| 1085 | let coupled = CoupledKernelKvConfig::new(cfg.clone()).unwrap(); |
| 1086 | assert!(coupled.verify_invariant().is_ok()); |
| 1087 | |
| 1088 | // Violation: mismatched block size |
| 1089 | let invalid_coupled = CoupledKernelKvConfig { |
| 1090 | kernel_config: cfg, |
| 1091 | kv_pool_block_size: 32, // mismatched! |
| 1092 | block_table_page_geometry: 16, |
| 1093 | }; |
| 1094 | assert!(invalid_coupled.verify_invariant().is_err()); |
| 1095 | } |
| 1096 | |
| 1097 | #[test] |
| 1098 | fn test_render_macro_defines() { |
| 1099 | let cfg = PagedAttentionConfig::new(32, 4, 2, 2).unwrap(); |
| 1100 | let rendered = cfg.render_macro_defines(); |
| 1101 | assert!(rendered.contains("#define PAGE_SIZE 32")); |
| 1102 | assert!(rendered.contains("#define BLOCK_THREADS 128")); |
| 1103 | assert!(rendered.contains("#define Q_HEADS_PER_BLOCK 4")); |
| 1104 | assert!(rendered.contains("#define VECTOR_WIDTH 2")); |
| 1105 | assert!(rendered.contains("#define PREFETCH_DISTANCE 2")); |
| 1106 | } |
| 1107 | |
| 1108 | #[test] |
| 1109 | fn test_create_contract_evidence_derived_confidence() { |
| 1110 | let cfg = PagedAttentionConfig::default(); |
| 1111 | |
| 1112 | let contract_default = KernelAutotuneManager::create_contract(&cfg, 38.0, None); |
| 1113 | assert_eq!(contract_default.confidence_score, 0.50); |
| 1114 | |
| 1115 | let contract_empirical = KernelAutotuneManager::create_contract(&cfg, 38.0, Some(0.985)); |
| 1116 | assert_eq!(contract_empirical.confidence_score, 0.985); |
| 1117 | assert_eq!(contract_empirical.protected_metrics.len(), 3); |
| 1118 | assert_eq!(contract_empirical.protected_metrics[0].name, "p99_latency"); |
| 1119 | assert_eq!( |
| 1120 | contract_empirical.protected_metrics[0].max_allowed_degradation_pct, |
| 1121 | 1.0 |
| 1122 | ); |
| 1123 | } |
| 1124 | |
| 1125 | #[test] |
| 1126 | fn test_apply_to_kernel_source_preserves_internal_directives() { |
| 1127 | let sample = "#include <cuda_runtime.h> |
| 1128 | // Parameterized autotuning search space with compile-time overrides |
| 1129 | #ifndef PAGE_SIZE |
| 1130 | #define PAGE_SIZE 16 |
| 1131 | #endif |
| 1132 | #define WARP_SIZE 32 |
| 1133 | #if PREFETCH_DISTANCE > 0 |
| 1134 | prefetch_global_l2(next_k); |
| 1135 | #endif |
| 1136 | "; |
| 1137 | let cfg = PagedAttentionConfig::new(32, 4, 2, 2).unwrap(); |
| 1138 | let mutated = cfg.apply_to_kernel_source(sample); |
| 1139 | assert!(mutated.contains("#define PAGE_SIZE 32")); |
| 1140 | assert!(mutated.contains("#define PREFETCH_DISTANCE 2")); |
| 1141 | assert!(mutated.contains("#define WARP_SIZE 32")); |
| 1142 | assert!(mutated.contains("#if PREFETCH_DISTANCE > 0")); |
| 1143 | assert!(mutated.contains("#endif")); |
| 1144 | assert_eq!(cfg.recommended_kv_pool_block_size(), 32); |
| 1145 | } |
| 1146 | |
| 1147 | #[test] |
| 1148 | fn test_search_space_enumeration_all_valid() { |
| 1149 | let space = KernelAutotuneManager::enumerate_search_space(); |
| 1150 | assert_eq!(space.len(), 36); |
| 1151 | for cfg in &space { |
| 1152 | assert!(cfg.is_valid()); |
| 1153 | assert_eq!(cfg.warps_per_block, cfg.query_heads_per_block); |
| 1154 | assert_eq!(cfg.threads_per_block, cfg.query_heads_per_block * 32); |
| 1155 | } |
| 1156 | } |
| 1157 | |
| 1158 | #[tokio::test] |
| 1159 | async fn test_kernel_autotune_experiment_end_to_end() { |
| 1160 | if !crate::not_run::gpu_or_not_run("test_kernel_autotune_experiment_end_to_end") |
| 1161 | || !crate::not_run::user_scope_or_not_run("test_kernel_autotune_experiment_end_to_end") |
| 1162 | { |
| 1163 | return; |
| 1164 | } |
| 1165 | let _ = std::process::Command::new("sudo") |
| 1166 | .args(&["-n", "sysctl", "-w", "vm.drop_caches=3"]) |
| 1167 | .output(); |
| 1168 | let tmp = tempfile::tempdir().unwrap(); |
| 1169 | let rsi_dir = tmp.path().join(".rsi"); |
| 1170 | fs::create_dir_all(&rsi_dir).unwrap(); |
| 1171 | |
| 1172 | let ledger = ImprovementLedger::open(&rsi_dir).unwrap(); |
| 1173 | |
| 1174 | let baseline_cfg = PagedAttentionConfig::default(); |
| 1175 | let candidate_cfg = PagedAttentionConfig::new(16, 4, 2, 2).unwrap(); |
| 1176 | |
| 1177 | let target_cuda = tmp.path().join("paged_attention_bf16.cu"); |
| 1178 | fs::write( |
| 1179 | &target_cuda, |
| 1180 | KernelAutotuneExperiment::builtin_kernel_reference(), |
| 1181 | ) |
| 1182 | .unwrap(); |
| 1183 | |
| 1184 | let experiment = KernelAutotuneExperiment::new( |
| 1185 | baseline_cfg, |
| 1186 | candidate_cfg, |
| 1187 | target_cuda, |
| 1188 | rsi_dir, |
| 1189 | "http://127.0.0.1:18080".to_string(), |
| 1190 | "atlas-memory".to_string(), |
| 1191 | ) |
| 1192 | .unwrap(); |
| 1193 | |
| 1194 | let receipt = experiment |
| 1195 | .run_experiment(&ledger) |
| 1196 | .await |
| 1197 | .expect("Experiment must run to completion"); |
| 1198 | |
| 1199 | assert!(receipt.compilation_passed); |
| 1200 | assert_eq!(receipt.baseline_metrics.latency_samples_us.len(), 30); |
| 1201 | assert_eq!(receipt.candidate_metrics.latency_samples_us.len(), 30); |
| 1202 | assert!(receipt.bootstrap_p_value >= 0.0 && receipt.bootstrap_p_value <= 1.0); |
| 1203 | assert!(receipt.confidence_score >= 0.01 && receipt.confidence_score <= 1.0); |
| 1204 | assert!(receipt.ledger_block_hash.is_some()); |
| 1205 | |
| 1206 | let blk = ledger |
| 1207 | .get_block_by_hash(&receipt.ledger_block_hash.unwrap()) |
| 1208 | .unwrap(); |
| 1209 | assert!(blk.is_some()); |
| 1210 | } |
| 1211 | |
| 1212 | #[tokio::test] |
| 1213 | async fn test_kernel_autotune_against_physical_sovereign_core_cuda_source() { |
| 1214 | if !crate::not_run::gpu_or_not_run( |
| 1215 | "test_kernel_autotune_against_physical_sovereign_core_cuda_source", |
| 1216 | ) || !crate::not_run::user_scope_or_not_run( |
| 1217 | "test_kernel_autotune_against_physical_sovereign_core_cuda_source", |
| 1218 | ) { |
| 1219 | return; |
| 1220 | } |
| 1221 | let core_dir = std::env::var("AIEN_SOVEREIGN_CORE_DIR").unwrap_or_else(|_| { |
| 1222 | format!( |
| 1223 | "{}/workspace/aien-sovereign-core", |
| 1224 | std::env::var("HOME").unwrap_or_default() |
| 1225 | ) |
| 1226 | }); |
| 1227 | let physical_cuda = |
| 1228 | PathBuf::from(core_dir).join("crates/aien-inference-abi/cuda/paged_attention_bf16.cu"); |
| 1229 | if !physical_cuda.exists() { |
| 1230 | eprintln!( |
| 1231 | "Skipping physical CUDA test: file does not exist at {:?}", |
| 1232 | physical_cuda |
| 1233 | ); |
| 1234 | return; |
| 1235 | } |
| 1236 | let source_content = fs::read_to_string(&physical_cuda).unwrap_or_default(); |
| 1237 | if !source_content.contains("PAGE_SIZE") || source_content.contains("KvLayoutDesc") { |
| 1238 | eprintln!( |
| 1239 | "Skipping physical CUDA test: target kernel in {:?} migrated to KvLayoutDesc layout", |
| 1240 | physical_cuda |
| 1241 | ); |
| 1242 | return; |
| 1243 | } |
| 1244 | |
| 1245 | let tmp = tempfile::tempdir().unwrap(); |
| 1246 | let rsi_dir = tmp.path().join(".rsi"); |
| 1247 | fs::create_dir_all(&rsi_dir).unwrap(); |
| 1248 | let ledger = ImprovementLedger::open(&rsi_dir).unwrap(); |
| 1249 | |
| 1250 | let baseline_cfg = PagedAttentionConfig::new(16, 4, 2, 1).unwrap(); |
| 1251 | let candidate_cfg = PagedAttentionConfig::new(32, 4, 2, 2).unwrap(); |
| 1252 | |
| 1253 | let experiment = KernelAutotuneExperiment::new( |
| 1254 | baseline_cfg, |
| 1255 | candidate_cfg, |
| 1256 | physical_cuda, |
| 1257 | rsi_dir, |
| 1258 | "http://127.0.0.1:18080".to_string(), |
| 1259 | "atlas-memory".to_string(), |
| 1260 | ) |
| 1261 | .unwrap(); |
| 1262 | |
| 1263 | let receipt = experiment |
| 1264 | .run_experiment(&ledger) |
| 1265 | .await |
| 1266 | .expect("Physical experiment must succeed"); |
| 1267 | assert!( |
| 1268 | receipt.compilation_passed, |
| 1269 | "Candidate kernel must compile with nvcc: {:?}", |
| 1270 | receipt.compilation_error |
| 1271 | ); |
| 1272 | assert_eq!(receipt.candidate_config.page_size, 32); |
| 1273 | assert_eq!(receipt.coupled_kv_config.kv_pool_block_size, 32); |
| 1274 | assert_eq!(receipt.baseline_metrics.latency_samples_us.len(), 30); |
| 1275 | assert_eq!(receipt.candidate_metrics.latency_samples_us.len(), 30); |
| 1276 | assert!(receipt.baseline_metrics.p50_latency_us > 0.0); |
| 1277 | assert!(receipt.candidate_metrics.p50_latency_us > 0.0); |
| 1278 | assert!(receipt.ledger_block_hash.is_some()); |
| 1279 | println!("Physical DGX Spark GB10 Hardware Timing Proof:"); |
| 1280 | println!( |
| 1281 | " Baseline p50={:.2}us, p95={:.2}us, p99={:.2}us", |
| 1282 | receipt.baseline_metrics.p50_latency_us, |
| 1283 | receipt.baseline_metrics.p95_latency_us, |
| 1284 | receipt.baseline_metrics.p99_latency_us |
| 1285 | ); |
| 1286 | println!( |
| 1287 | " Candidate p50={:.2}us, p95={:.2}us, p99={:.2}us", |
| 1288 | receipt.candidate_metrics.p50_latency_us, |
| 1289 | receipt.candidate_metrics.p95_latency_us, |
| 1290 | receipt.candidate_metrics.p99_latency_us |
| 1291 | ); |
| 1292 | println!( |
| 1293 | " p95_delta={:.2}%, p_value={:.4}, confidence={:.3}, admitted={}", |
| 1294 | receipt.p95_delta_pct, |
| 1295 | receipt.bootstrap_p_value, |
| 1296 | receipt.confidence_score, |
| 1297 | receipt.admitted |
| 1298 | ); |
| 1299 | } |
| 1300 | } |