diff --git a/control-plane/src/kar.rs b/control-plane/src/kar.rs index 26e36f9a..6e78b70a 100644 --- a/control-plane/src/kar.rs +++ b/control-plane/src/kar.rs @@ -36,6 +36,59 @@ pub struct TensorSource { pub digest: [u8; 32], pub offset: u64, pub section_bytes: u64, + pub storage_class: u8, + pub n_elements: u64, + pub planes_min: u8, + pub planes_max: u8, + pub section_offset: u64, + pub planes_offset: u64, + pub plane_stride_bytes: u32, +} + +impl TensorSource { + /// The bytes libkar::kar_reserve stages for this record at the requested + /// level. RAW records have no precision dial and always stage in full. + pub fn gpu_resident_bytes(&self, level: u8) -> Result { + if self.storage_class == 1 { + return Ok(self.section_bytes); + } + if !(1..=8).contains(&level) || level < self.planes_min || level > self.planes_max { + return Err(format!( + "{}: KAR level {level} is outside its supported dial", + self.name + )); + } + self.planes_offset + .checked_sub(self.section_offset) + .and_then(|prefix| { + prefix.checked_add(u64::from(level) * u64::from(self.plane_stride_bytes)) + }) + .filter(|bytes| *bytes <= self.section_bytes) + .ok_or_else(|| format!("{}: invalid KAR GPU prefix size", self.name)) + } + + pub fn gpu_decode_bytes(&self) -> Result { + self.n_elements + .checked_mul(4) + .ok_or_else(|| format!("{}: KAR F32 decode size overflow", self.name)) + } + + /// One-row output size for a geometrically addressable NESTED table. + /// Whether the model can consume only selected rows is a separate question. + pub fn gpu_one_row_decode_bytes(&self) -> Option { + let row_len = *self.dimensions.first()?; + if self.storage_class == 0 + && self.dimensions.len() >= 2 + && row_len.is_multiple_of(32) + && row_len <= u32::MAX as u64 + && self.n_elements > row_len + && self.n_elements.is_multiple_of(row_len) + { + row_len.checked_mul(4) + } else { + None + } + } } /// CPU quality oracle for repeated bounded reads from one verified archive. @@ -499,6 +552,13 @@ fn inspect_inner(path: &Path) -> Result<(Summary, File, Vec
, Vec, +} + +#[derive(Serialize)] +pub struct Report { + pub schema: &'static str, + pub level: u8, + pub budget_bytes: u64, + pub record_count: usize, + pub all_compressed_resident_bytes: u64, + pub largest_decode_scratch_bytes: u64, + pub all_resident_plus_scratch_bytes: u64, + pub largest_single_record_peak_bytes: u64, + pub records_exceeding_budget: usize, + pub full_decode_exceeds_but_one_row_fits: usize, + pub largest_records: Vec, + pub verification: &'static str, +} + +pub fn plan(path: &Path, level: u8, budget_bytes: u64) -> Result { + if !(1..=8).contains(&level) || budget_bytes == 0 { + return Err("KAR level must be 1..8 and GPU budget must be positive".into()); + } + let (summary, records) = kar::inspect_with_sources(path)?; + let mut compressed_total = 0u64; + let mut scratch_max = 0u64; + let mut peak_max = 0u64; + let mut exceeding = 0usize; + let mut row_fits = 0usize; + let mut largest = Vec::with_capacity(records.len()); + for record in records { + let compressed = record.gpu_resident_bytes(level)?; + let scratch = record.gpu_decode_bytes()?; + let peak = compressed + .checked_add(scratch) + .ok_or("KAR single-record GPU peak overflow")?; + compressed_total = compressed_total + .checked_add(compressed) + .ok_or("KAR total GPU residency overflow")?; + scratch_max = scratch_max.max(scratch); + peak_max = peak_max.max(peak); + if peak > budget_bytes { + exceeding += 1; + } + let one_row_peak = record + .gpu_one_row_decode_bytes() + .and_then(|row_bytes| compressed.checked_add(row_bytes)); + if peak > budget_bytes && one_row_peak.is_some_and(|bytes| bytes <= budget_bytes) { + row_fits += 1; + } + largest.push(RecordMemory { + name: record.name, + compressed_bytes: compressed, + decode_bytes: scratch, + single_record_peak_bytes: peak, + one_row_peak_bytes: one_row_peak, + }); + } + largest.sort_unstable_by(|a, b| { + b.single_record_peak_bytes + .cmp(&a.single_record_peak_bytes) + .then_with(|| a.name.cmp(&b.name)) + }); + largest.truncate(10); + let all_plus_scratch = compressed_total + .checked_add(scratch_max) + .ok_or("KAR all-resident GPU peak overflow")?; + Ok(Report { + schema: "strata-next/kar-gpu-memory-plan-v1", + level, + budget_bytes, + record_count: summary.tensor_count as usize, + all_compressed_resident_bytes: compressed_total, + largest_decode_scratch_bytes: scratch_max, + all_resident_plus_scratch_bytes: all_plus_scratch, + largest_single_record_peak_bytes: peak_max, + records_exceeding_budget: exceeding, + full_decode_exceeds_but_one_row_fits: row_fits, + largest_records: largest, + verification: "bounded KAR metadata only; payload CRCs, archive SHA-256, model quality, and GPU execution not checked", + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{SystemTime, UNIX_EPOCH}; + + #[test] + fn smoke_fixture_has_bounded_single_record_peak() { + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let path = std::env::temp_dir().join(format!( + "strata-kar-memory-{}-{nonce}.kar", + std::process::id() + )); + crate::kar_fixture::write(&path).unwrap(); + let report = plan(&path, 2, 1 << 20).unwrap(); + assert_eq!(report.record_count, 1); + assert_eq!(report.records_exceeding_budget, 0); + assert!(report.largest_single_record_peak_bytes <= 1 << 20); + assert_eq!(plan(&path, 2, 1).unwrap().records_exceeding_budget, 1); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index 9d559873..1fb559c3 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -11,6 +11,7 @@ mod iq3s_grid; pub mod kar; pub mod kar_codec; pub mod kar_fixture; +pub mod kar_memory; pub mod kar_overlay; pub mod kar_quality; pub mod kar_sample; diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index ecce6147..255d9e9b 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -3,8 +3,9 @@ use std::{env, io::Read, path::Path, sync::Arc}; use tokio::sync::{mpsc, watch}; use strata_control::{ - app, config::Config, derived_iq3, derived_mixed, doctor, gguf, kar, kar_fixture, kar_overlay, - kar_quality, model, model_pipeline, prepare_preview, tokenizer, tokenizer_assets, worker, + app, config::Config, derived_iq3, derived_mixed, doctor, gguf, kar, kar_fixture, kar_memory, + kar_overlay, kar_quality, model, model_pipeline, prepare_preview, tokenizer, tokenizer_assets, + worker, }; #[tokio::main] @@ -321,6 +322,16 @@ async fn main() -> Result<(), Box> { println!("bounded metadata checks passed; payload CRCs and padding not checked"); Ok(()) } + [model, action, path, level_flag, level, budget_flag, budget] + if model == "model" && action == "plan-kar-memory" + && level_flag == "--level" && budget_flag == "--budget-mib" => + { + let budget_mib: u64 = budget.parse()?; + let budget_bytes = budget_mib.checked_mul(1 << 20).ok_or("GPU budget overflow")?; + let report = kar_memory::plan(Path::new(path), level.parse()?, budget_bytes)?; + println!("{}", serde_json::to_string_pretty(&report)?); + Ok(()) + } [model, action, path] if model == "model" && action == "verify-kar" => { let summary = kar::verify(Path::new(path))?; println!("verified KAR-2 metadata and {} payload CRCs", summary.tensor_count); @@ -557,7 +568,7 @@ async fn main() -> Result<(), Box> { print!("{}", include_str!("../third_party/ggml/LICENSE")); Ok(()) } - _ => Err("usage: strata-next [serve|doctor|--ggml-license|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model inspect FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model inspect-kar FILE.kar|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model detokenize TOKENIZER_DIR IDS]".into()), + _ => Err("usage: strata-next [serve|doctor|--ggml-license|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model inspect FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model detokenize TOKENIZER_DIR IDS]".into()), } } diff --git a/docs/compressed-runtime.md b/docs/compressed-runtime.md index dab70a12..ec6f65f7 100644 --- a/docs/compressed-runtime.md +++ b/docs/compressed-runtime.md @@ -56,6 +56,10 @@ The streamed assembly now consumes private staged sections as it copies them int ## GPU path +`strata-next model plan-kar-memory FILE.kar --level 2 --budget-mib 24576` reads validated KAR metadata and reports compressed-prefix residency, full F32 decode scratch, the largest single-record peak, and records whose full decode exceeds the supplied VRAM slice. The budget must be the memory left after the engine, KV cache, and other allocations; it is not the card's advertised capacity. `one_row_peak_bytes` is only a geometric lower bound for records that `kar_decode_rows()` can address. It does not mean the model can compute from one row of an arbitrary expert or projection. This command does not scan payload CRCs or approve the archive for serving. + +On the verified Qwen3.8-Flash-Next IQ3_S level-2 archive, the metadata plan at a hypothetical 24,576 MiB slice reports 55,294,991,056 bytes if all compressed records were resident, so residency must be selective. Two split `per_layer_token_embd.weight` records exceed that slice for full F32 decode: their compressed-prefix-plus-output peaks are 138,000,000,016 and 82,801,059,856 bytes. Their one-row lower bounds are 10,000,000,656 and 6,000,077,456 bytes. `kar_decode_rows()` avoids the huge F32 output but `kar_reserve()` still stages the complete 10.0 GB or 6.0 GB compressed record. Efficient cold row lookup therefore needs smaller addressable PLE parts or a sparse staging kernel. The engine must not allocate the full decoded table on the target card. These are metadata arithmetic, not GPU measurements or quality results. + For the target compressed runtime, copy the selected KAR data to VRAM in compressed form. Keep at least the working layer and selected experts decoded or decode them into a bounded scratch buffer on a CUDA stream before multiply. Use `kar_decode_rows()` for sparse per-layer embedding lookups. The scheduler must account for archive residency, precision level, transfers, decode, and multiply, and measure cold misses separately from warm expert-cache hits. The archive format and decoded numerical values must be compared with the koference CPU oracle before an end-to-end speed claim. The user-facing Linux command checks the installed NVIDIA driver and starts the native engine. It does not carry the driver. The single-file GPU packaging goal still needs a real Linux CUDA build and loader test.