diff --git a/.crumb b/.crumb index 5a5bb992..5eaa7d33 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:2773d5ada0e6ae8b446499314f4a704361ab91a14a35259a62607b7c731d0ab9", - "compiled_at": "2026-10-08T04:40:27Z", + "compiled_at": "2026-10-08T04:50:36Z", "compiler": "crumb-compile/1", - "digest": "sha256:85279ff903a1f2a9d0e02907fe8973949efc945cb2219cf0e5101e876f7298a2", + "digest": "sha256:ff69289f391ef90d3e32979ebf67189eafba997a84eb53cb55717d504dc8f927", "evidence_files": 187, "evidence_root": "sha256:27ee0353cb4d4aae2b7dbce2bfe0d9f4ef2a94cd7a4555b84684d59372503280", - "files": 1354, - "generated_at_commit": "20e976a55907c12fbfb65c32198bea55713f4eb4", - "source_tree": "sha256:d7c4f0132aa911c95f8e6f49e88883c7a948c75983b8fb2555892195982222b8" + "files": 1357, + "generated_at_commit": "2010f3d7d0bbbff9a83bfa2e7990dfbc285cf1ab", + "source_tree": "sha256:c61692a41d9cbf270c1d9382f45440b140baf8d3273ff69d2e63d5410b9af555" } }, "history": [], diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb index 249b8216..2bfe8d24 100644 --- a/crates/aien-cli/.crumb +++ b/crates/aien-cli/.crumb @@ -34,21 +34,21 @@ "generated": { "children": [ { - "digest": "48d2f54653f8fa475db1fbfcd2471a54bfb9f9df1d186ebbc5bf04cd7b031238", - "last_commit": "9b84bb5", + "digest": "bda1cf3ea7725b89dcc8c0a6f9019ca8f8a98e9173b99f48c434a6ff7e7b857d", + "last_commit": "2010f3d", "name": "src", "purpose": "" } ], - "children_root": "sha256:beb8815bbfa7560638ea9f42f268ac6fdc52611dcca61092bb487e645c2b4178", - "compiled_at": "2026-10-08T04:29:50Z", + "children_root": "sha256:79480b7c03456483de758f44f99f3f3661cb24bf829761bf11b58a04e27d8d18", + "compiled_at": "2026-10-08T04:50:36Z", "compiler": "crumb-compile/1", - "digest": "sha256:67a8418774bb6965ee07da0a9cff8e74a76b09d29ed8534eef59249280b39d73", + "digest": "sha256:2613d61b92b3c31c80423a0f4a4ba57c84f22014d7fe737b33464f30f81de1b3", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 31, - "generated_at_commit": "45074e89b1d48f92f29e8b8bc99b1faaf5cced97", - "source_tree": "sha256:cde8d6c8cbfebf82cd1d8a92d1292fe747403c49a2ae16fddf41e4c343129915" + "generated_at_commit": "2010f3d7d0bbbff9a83bfa2e7990dfbc285cf1ab", + "source_tree": "sha256:c54c329521dab8d8d4a7a896d5087a4f6f738bca543aa0eca1debda2124affba" } }, "history": [ diff --git a/crates/aien-cli/src/.crumb b/crates/aien-cli/src/.crumb index 4e43d3d6..456d9467 100644 --- a/crates/aien-cli/src/.crumb +++ b/crates/aien-cli/src/.crumb @@ -64,14 +64,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-08T04:29:50Z", + "compiled_at": "2026-10-08T04:50:36Z", "compiler": "crumb-compile/1", - "digest": "sha256:48d2f54653f8fa475db1fbfcd2471a54bfb9f9df1d186ebbc5bf04cd7b031238", + "digest": "sha256:bda1cf3ea7725b89dcc8c0a6f9019ca8f8a98e9173b99f48c434a6ff7e7b857d", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 26, - "generated_at_commit": "45074e89b1d48f92f29e8b8bc99b1faaf5cced97", - "source_tree": "sha256:0cd55b8e17fc8fdcf77a99cd19a867784106dab7f3eb4284e7e6ed458e322614" + "generated_at_commit": "2010f3d7d0bbbff9a83bfa2e7990dfbc285cf1ab", + "source_tree": "sha256:99eb9e7c645d419b534a39fc490c26c671de6c3cb0cb999a3f643ab62e6a4ffa" } }, "history": [ diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs index ce0f9385..6fb51064 100644 --- a/crates/aien-cli/src/commands.rs +++ b/crates/aien-cli/src/commands.rs @@ -1203,9 +1203,30 @@ fn reference_fallback( }) } +/// How the daemon makes the GB10 Qwen3 weights resident instead of holding host f32 copies +/// (sovereign-core #277 cut C). `None` anywhere means the unchanged host f32 load. +struct ResidentLoad<'a> { + native_linked: bool, + strict: bool, + qwen3_opted_in: bool, + uploader: &'a dyn aien_inference_abi::ResidentUploader, + /// Opens the GPU session (bounded retry) so every driver allocation of the upload happens + /// while the process holds almost no memory. + open_session: &'a dyn Fn() -> Result<(), String>, +} + +#[cfg(test)] fn load_daemon_model( + manifest: DaemonModelManifest, + require_checkpoint: bool, +) -> Result { + load_daemon_model_with(manifest, require_checkpoint, None) +} + +fn load_daemon_model_with( mut manifest: DaemonModelManifest, require_checkpoint: bool, + resident: Option<&ResidentLoad<'_>>, ) -> Result { let Some(path) = manifest.checkpoint_path.clone() else { let reason = manifest @@ -1236,19 +1257,53 @@ fn load_daemon_model( } else { aien_inference_abi::ModelConfig::tinyllama_1_1b() }; - let weights = - match aien_inference_abi::TransformerWeights::load_from_safetensors(&path, &config) { - Ok(weights) => weights, - Err(error) => { - let reason = format!( - "checkpoint {} failed to load against the {} config: {}", - path.display(), - config.model_id, - error - ); - return reference_fallback(manifest, require_checkpoint, reason); + let resident = resident.filter(|r| { + aien_inference_abi::resident_load_wanted( + r.native_linked, + r.strict, + r.qwen3_opted_in, + &config, + ) + }); + let loaded = match resident { + None => aien_inference_abi::TransformerWeights::load_from_safetensors(&path, &config), + Some(r) => { + (r.open_session)()?; + let mut count = 0usize; + let loaded = aien_inference_abi::load_resident_weights( + &path, + &config, + r.uploader, + &mut |_name| count += 1, + ); + match loaded { + // An upload that fails is fatal here: the weights have no host copy to degrade to. + Err(e @ aien_inference_abi::CheckpointError::ResidentUpload { .. }) => { + return Err(format!("GB10_RESIDENT_LOAD failed: {e}")); + } + other => { + if other.is_ok() { + println!( + " GB10_RESIDENT_LOAD: {count} matmul weights streamed from the bf16 shards to the device; no host f32 copy of any matmul weight" + ); + } + other + } } - }; + } + }; + let weights = match loaded { + Ok(weights) => weights, + Err(error) => { + let reason = format!( + "checkpoint {} failed to load against the {} config: {}", + path.display(), + config.model_id, + error + ); + return reference_fallback(manifest, require_checkpoint, reason); + } + }; manifest.model_sha256 = Some(model_sha256); let mut tokenizer = None; @@ -1362,7 +1417,26 @@ fn build_native_daemon_backend() -> Result { label: model_label, manifest, .. - } = load_daemon_model(manifest, policy.require_checkpoint)?; + } = { + let open_session = || { + aien_inference_abi::open_gpu_session_with_retry( + aien_inference_abi::GPU_SESSION_OPEN_ATTEMPTS, + aien_inference_abi::GPU_SESSION_RETRY_DELAY, + aien_inference_abi::GPU_SESSION_OPEN_DEADLINE, + &aien_runtime::shared_kv::read_mem_available, + ) + .map(|_| ()) + }; + let resident = ResidentLoad { + native_linked: aien_omega_gpu::is_native(), + strict: aien_inference_abi::strict::production_strict(), + qwen3_opted_in: std::env::var(aien_inference_abi::GB10_QWEN3_OPT_IN_ENV) + .is_ok_and(|v| v == "1"), + uploader: &aien_inference_abi::OmegaUploader, + open_session: &open_session, + }; + load_daemon_model_with(manifest, policy.require_checkpoint, Some(&resident))? + }; let identity = model_identity(&manifest, tokenizer.is_some()); // FB-1 cut 6: the native Omega engine is the only GPU backend (no CUDA). The env names // AIEN_REQUIRE_BLACKWELL (the GB10 chip, campaign spec) and AIEN_GPU_BACKEND=omega both diff --git a/crates/aien-inference-abi/examples/load_rss.rs b/crates/aien-inference-abi/examples/load_rss.rs new file mode 100644 index 00000000..e1bca3e0 --- /dev/null +++ b/crates/aien-inference-abi/examples/load_rss.rs @@ -0,0 +1,84 @@ +//! Host-only measurement of the checkpoint load path (no GPU, no chip): peak and final resident +//! memory of the process for the unchanged host f32 load and for the GB10 resident load +//! (sovereign-core #277 cut C) with a stub uploader that only checksums the bf16 bits. +//! +//! load_rss host|resident +use aien_inference_abi::{ + load_model_config, load_resident_weights, ResidentHandle, ResidentUploader, ResidentWeight, + TransformerWeights, +}; +use std::sync::{Arc, Mutex}; + +fn status_kib(key: &str) -> u64 { + std::fs::read_to_string("/proc/self/status") + .unwrap() + .lines() + .find_map(|l| l.strip_prefix(key)) + .and_then(|v| v.trim().trim_end_matches("kB").trim().parse().ok()) + .unwrap_or(0) +} + +fn gib(kib: u64) -> f64 { + kib as f64 / 1024.0 / 1024.0 +} + +#[derive(Debug)] +struct Stub; +impl ResidentHandle for Stub { + fn matmul_f32(&self, _: usize, _: &[f32], _: &mut [f32]) -> Result { + Err("stub".into()) + } +} + +struct StubUploader { + log: Mutex>, + bytes: Mutex, +} +impl ResidentUploader for StubUploader { + fn upload_bf16(&self, k: usize, n: usize, bits: &[u16]) -> Result { + let sum = bits.iter().fold(0u64, |a, b| a.wrapping_add(*b as u64)); + std::hint::black_box(sum); + *self.bytes.lock().unwrap() += (k * n * 2) as u64; + self.log.lock().unwrap().push((k * n, status_kib("VmRSS:"))); + Ok(ResidentWeight::new(k, n, Arc::new(Stub))) + } +} + +fn main() { + let args: Vec = std::env::args().collect(); + let (mode, dir) = (args[1].as_str(), std::path::PathBuf::from(&args[2])); + let config = load_model_config(&dir).expect("config.json"); + let t = std::time::Instant::now(); + let weights = match mode { + "host" => TransformerWeights::load_from_safetensors(&dir, &config).expect("host load"), + "resident" => { + let up = StubUploader { + log: Mutex::new(Vec::new()), + bytes: Mutex::new(0), + }; + let w = load_resident_weights(&dir, &config, &up, &mut |_| {}).expect("resident load"); + let log = up.log.lock().unwrap(); + let max_during_uploads = log.iter().map(|x| x.1).max().unwrap_or(0); + println!( + "uploads={} bf16_uploaded={:.3} GiB max_VmRSS_during_uploads={:.3} GiB", + log.len(), + gib(*up.bytes.lock().unwrap() / 1024), + gib(max_during_uploads) + ); + w + } + other => panic!("mode must be host or resident, got {other}"), + }; + let resident = weights + .layers + .iter() + .filter(|l| l.q_proj.is_resident()) + .count(); + println!( + "mode={mode} load_secs={:.1} VmHWM(peak)={:.3} GiB VmRSS(after load)={:.3} GiB resident_layers={resident}/{}", + t.elapsed().as_secs_f64(), + gib(status_kib("VmHWM:")), + gib(status_kib("VmRSS:")), + weights.layers.len() + ); +} diff --git a/crates/aien-inference-abi/src/backend.rs b/crates/aien-inference-abi/src/backend.rs index 384b5675..3bb02024 100644 --- a/crates/aien-inference-abi/src/backend.rs +++ b/crates/aien-inference-abi/src/backend.rs @@ -363,6 +363,65 @@ pub trait TensorBackend: Send + Sync { vocab_size: usize, hidden_dim: usize, ); + + /// [`Self::matmul_vec`] for a weight that may be device-resident. Host weights go to + /// `matmul_vec`; a resident weight is refused by name unless the backend overrides this (only + /// the Omega GB10 backend can use one). Never a silent CPU fallback. + fn matmul_vec_w( + &self, + out: &mut [f32], + x: &[f32], + weight: crate::resident::MatrixRef<'_>, + out_dim: usize, + in_dim: usize, + ) { + let w = self.resident_refusal_or_host(weight, "matmul_vec"); + self.matmul_vec(out, x, w, out_dim, in_dim); + } + + /// [`Self::matmul_batch`] for a weight that may be device-resident (see [`Self::matmul_vec_w`]). + fn matmul_batch_w( + &self, + out: &mut [f32], + x: &[f32], + weight: crate::resident::MatrixRef<'_>, + batch_size: usize, + in_dim: usize, + out_dim: usize, + ) { + let w = self.resident_refusal_or_host(weight, "matmul_batch"); + self.matmul_batch(out, x, w, batch_size, in_dim, out_dim); + } + + /// [`Self::compute_logits`] for a head that may be device-resident (see [`Self::matmul_vec_w`]). + fn compute_logits_w( + &self, + logits: &mut [f32], + hidden: &[f32], + head: crate::resident::MatrixRef<'_>, + vocab_size: usize, + hidden_dim: usize, + ) { + let w = self.resident_refusal_or_host(head, "compute_logits"); + self.compute_logits(logits, hidden, w, vocab_size, hidden_dim); + } + + /// Host values of `weight`, or the named refusal when it is resident and this backend + /// cannot use a device copy. + #[doc(hidden)] + fn resident_refusal_or_host<'a>( + &self, + weight: crate::resident::MatrixRef<'a>, + op: &str, + ) -> &'a [f32] { + match weight { + crate::resident::MatrixRef::Host(v) => v, + crate::resident::MatrixRef::Resident(_) => crate::resident::refuse_resident(&format!( + "backend {} cannot run {op} on a device-resident weight", + self.name() + )), + } + } } /// Pure Rust FP32 reference implementation satisfying TensorBackend. diff --git a/crates/aien-inference-abi/src/checkpoint.rs b/crates/aien-inference-abi/src/checkpoint.rs index b782ac33..8caf4c54 100644 --- a/crates/aien-inference-abi/src/checkpoint.rs +++ b/crates/aien-inference-abi/src/checkpoint.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use std::fmt; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::Arc; /// Loud error enum describing checkpoint parsing and validation failures. @@ -33,6 +33,8 @@ pub enum CheckpointError { InvalidHeader(String), /// A capsule tensor could not be decoded. Capsule(String), + /// A weight could not be made resident on the device (named, never a silent host copy). + ResidentUpload { tensor: String, message: String }, } impl fmt::Display for CheckpointError { @@ -78,6 +80,13 @@ impl fmt::Display for CheckpointError { write!(f, "Invalid safetensors header: {}", err) } Self::Capsule(err) => write!(f, "Invalid capsule tensor: {}", err), + Self::ResidentUpload { tensor, message } => { + write!( + f, + "Resident upload of tensor {} failed: {}", + tensor, message + ) + } } } } @@ -374,8 +383,25 @@ fn index_shard( CheckpointError::InvalidHeader("Header JSON must be an object".to_string()) })?; - let data_len = bytes.len() - header_end; + index_header( + header_obj, + bytes.len() - header_end, + base + header_end, + catalog, + tensors, + ) +} +/// Validates the catalog tensors named in one safetensors header against their declared shape, +/// dtype and offsets. `data_len` is the size of the data blob after the header; `data_start` is +/// the absolute position of that blob in whatever buffer or file the ranges refer to. +fn index_header( + header_obj: &serde_json::Map, + data_len: usize, + data_start: usize, + catalog: &[(String, Vec)], + tensors: &mut HashMap, +) -> Result<(), CheckpointError> { for (name, expected_shape) in catalog { let Some(info) = header_obj.get(name) else { continue; @@ -460,8 +486,8 @@ fn index_shard( } // Ranges are absolute inside the whole file, including the 8-byte length and JSON header. - let abs_start = base + header_end + start; - let abs_end = base + header_end + end; + let abs_start = data_start + start; + let abs_end = data_start + end; let logical_strides = crate::capsule::row_major_strides(&actual_shape); tensors.insert( name.clone(), @@ -489,27 +515,31 @@ pub fn load_safetensors_from_bytes(bytes: Vec) -> Result>( - path: P, - catalog: &[(String, Vec)], -) -> Result { - let p = path.as_ref(); - let read = |file: &Path| { - std::fs::read(file).map_err(|e| { - CheckpointError::InvalidHeader(format!( - "Failed to read checkpoint at {}: {}", - file.display(), - e - )) - }) - }; +/// The files a checkpoint path names. +enum ResolvedFiles { + /// One `.safetensors` file. + Single(PathBuf), + /// The shard files named by a `model.safetensors.index.json`, sorted and de-duplicated. + Sharded(Vec), +} + +impl ResolvedFiles { + fn into_paths(self) -> Vec { + match self { + Self::Single(p) => vec![p], + Self::Sharded(v) => v, + } + } +} + +/// Decides which files `path` names: a `.safetensors` file, a `model.safetensors.index.json` +/// (sharded), or a model directory holding either. A shard file whose directory has an index +/// names the whole sharded set. +fn resolve_checkpoint_files(p: &Path) -> Result { let index = if p.is_dir() { let single = p.join("model.safetensors"); if single.is_file() { - return parse_safetensors_arc(Arc::from(read(&single)?), catalog); + return Ok(ResolvedFiles::Single(single)); } p.join(SAFETENSORS_INDEX) } else if p.file_name().and_then(|n| n.to_str()) == Some(SAFETENSORS_INDEX) { @@ -518,7 +548,7 @@ pub fn load_checkpoint_with_catalog>( let sibling = p.with_file_name(SAFETENSORS_INDEX); let is_shard = p.file_name().and_then(|n| n.to_str()) != Some("model.safetensors"); if !(is_shard && sibling.is_file()) { - return parse_safetensors_arc(Arc::from(read(p)?), catalog); + return Ok(ResolvedFiles::Single(p.to_path_buf())); } sibling }; @@ -538,11 +568,36 @@ pub fn load_checkpoint_with_catalog>( files.sort_unstable(); files.dedup(); let dir = index.parent().unwrap_or(Path::new(".")); - let mut paths = Vec::with_capacity(files.len()); + Ok(ResolvedFiles::Sharded( + files.into_iter().map(|file| dir.join(file)).collect(), + )) +} + +/// Loads and validates a checkpoint against `catalog`. `path` is a `.safetensors` file, a +/// `model.safetensors.index.json` (sharded), or a model directory holding either. A shard +/// file whose directory has an index loads the whole sharded set. +pub fn load_checkpoint_with_catalog>( + path: P, + catalog: &[(String, Vec)], +) -> Result { + let read = |file: &Path| { + std::fs::read(file).map_err(|e| { + CheckpointError::InvalidHeader(format!( + "Failed to read checkpoint at {}: {}", + file.display(), + e + )) + }) + }; + let paths = match resolve_checkpoint_files(path.as_ref())? { + ResolvedFiles::Single(file) => { + return parse_safetensors_arc(Arc::from(read(&file)?), catalog); + } + ResolvedFiles::Sharded(paths) => paths, + }; let mut total = 0usize; - for file in files { - let shard = dir.join(file); - let len = std::fs::metadata(&shard) + for shard in &paths { + let len = std::fs::metadata(shard) .map_err(|e| { CheckpointError::InvalidHeader(format!( "Failed to stat shard {}: {}", @@ -552,7 +607,6 @@ pub fn load_checkpoint_with_catalog>( })? .len() as usize; total += len; - paths.push(shard); } let mut bytes = Vec::with_capacity(total); let mut ranges = Vec::with_capacity(paths.len()); @@ -573,6 +627,118 @@ pub fn load_checkpoint_with_catalog>( parse_shards(Arc::from(bytes), &ranges, catalog) } +/// A checkpoint indexed but not read: the catalog is validated against each shard's header +/// (the same checks as [`load_checkpoint_with_catalog`]) and tensor bytes are read one tensor +/// at a time with positioned reads, so no whole-file copy is ever held in process memory. +/// The shard pages stay in the kernel's page cache, which the kernel can reclaim. +#[derive(Debug)] +pub struct StreamedCheckpoint { + files: Vec, + tensors: HashMap, +} + +impl StreamedCheckpoint { + /// Indexes `path` (file, shard index, or model directory) against `catalog`. Reads only + /// each shard's header. Every catalog tensor must appear in exactly one shard. + pub fn open>( + path: P, + catalog: &[(String, Vec)], + ) -> Result { + use std::io::Read; + let files = resolve_checkpoint_files(path.as_ref())?.into_paths(); + let mut tensors = HashMap::with_capacity(catalog.len()); + for (idx, file) in files.iter().enumerate() { + let fail = |what: &str, e: std::io::Error| { + CheckpointError::InvalidHeader(format!("{what} {}: {e}", file.display())) + }; + let mut f = std::fs::File::open(file).map_err(|e| fail("Failed to open", e))?; + let file_len = f.metadata().map_err(|e| fail("Failed to stat", e))?.len() as usize; + let mut prefix = [0u8; 8]; + if file_len < 8 { + return Err(CheckpointError::InvalidHeader( + "Buffer smaller than 8-byte header prefix".to_string(), + )); + } + f.read_exact(&mut prefix) + .map_err(|e| fail("Failed to read header of", e))?; + let header_len = usize::try_from(u64::from_le_bytes(prefix)).map_err(|_| { + CheckpointError::InvalidHeader("Header length exceeds address space".to_string()) + })?; + let header_end = 8usize.checked_add(header_len).ok_or_else(|| { + CheckpointError::InvalidHeader("Header length arithmetic overflow".to_string()) + })?; + if file_len < header_end { + return Err(CheckpointError::InvalidHeader(format!( + "Header length {} exceeds total buffer size {}", + header_len, file_len + ))); + } + let mut header = vec![0u8; header_len]; + f.read_exact(&mut header) + .map_err(|e| fail("Failed to read header of", e))?; + let header_str = std::str::from_utf8(&header).map_err(|e| { + CheckpointError::InvalidHeader(format!("Header JSON is not valid UTF-8: {}", e)) + })?; + let header: serde_json::Value = serde_json::from_str(header_str).map_err(|e| { + CheckpointError::InvalidHeader(format!("Failed to parse header JSON: {}", e)) + })?; + let header_obj = header.as_object().ok_or_else(|| { + CheckpointError::InvalidHeader("Header JSON must be an object".to_string()) + })?; + let mut shard_tensors = HashMap::new(); + index_header( + header_obj, + file_len - header_end, + header_end, + catalog, + &mut shard_tensors, + )?; + for (name, tensor) in shard_tensors { + if tensors.insert(name.clone(), (idx, tensor)).is_some() { + return Err(CheckpointError::InvalidHeader(format!( + "tensor {} appears in more than one shard", + name + ))); + } + } + } + if let Some((name, _)) = catalog.iter().find(|(name, _)| !tensors.contains_key(name)) { + return Err(CheckpointError::MissingTensor(name.clone())); + } + Ok(Self { files, tensors }) + } + + /// Shape of `name` as the checkpoint declares it. + pub fn shape(&self, name: &str) -> Option<&[usize]> { + self.tensors.get(name).map(|(_, t)| t.shape.as_slice()) + } + + /// Reads the raw little-endian bf16 bytes of `name` into `buf` (cleared first; its + /// capacity is reused across calls). Returns the number of bf16 values. + pub fn read_bf16_bytes(&self, name: &str, buf: &mut Vec) -> Result { + use std::os::unix::fs::FileExt; + let (idx, tensor) = self + .tensors + .get(name) + .ok_or_else(|| CheckpointError::MissingTensor(name.to_string()))?; + let range = tensor.byte_range.clone(); + buf.clear(); + buf.resize(range.len(), 0); + let file = &self.files[*idx]; + std::fs::File::open(file) + .and_then(|f| f.read_exact_at(buf, range.start as u64)) + .map_err(|e| { + CheckpointError::InvalidHeader(format!( + "Failed to read tensor {} from {}: {}", + name, + file.display(), + e + )) + })?; + Ok(range.len() / 2) + } +} + /// Loads and validates a TinyLlama safetensors checkpoint from a filesystem path. pub fn load_safetensors_checkpoint>( path: P, diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index 8de3ba18..733cdf51 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -18,6 +18,7 @@ pub mod omega_backend; pub mod qwen3_coder; pub mod qwen3_moe; pub mod qwen3_serve; +pub mod resident; pub mod strict; pub mod tensor; pub mod tensor_abi; @@ -43,6 +44,7 @@ pub use omega_backend::{ pub use qwen3_coder::*; pub use qwen3_moe::*; pub use qwen3_serve::*; +pub use resident::*; pub use tensor::*; pub use tensor_abi::*; pub use tokenizer::*; diff --git a/crates/aien-inference-abi/src/omega_backend.rs b/crates/aien-inference-abi/src/omega_backend.rs index ea1c9137..3303eb71 100644 --- a/crates/aien-inference-abi/src/omega_backend.rs +++ b/crates/aien-inference-abi/src/omega_backend.rs @@ -241,6 +241,54 @@ impl OmegaGb10Backend { } } + /// `out[m x out_dim] = x[m x in_dim] * W^T` for a device-resident weight. The weight has no + /// host values, so a chip failure cannot fall back to the CPU: it is recorded and then + /// refused by name (panic), in every build. + fn chip_resident_matmul( + &self, + out: &mut [f32], + x: &[f32], + w: &crate::resident::ResidentWeight, + m: usize, + in_dim: usize, + out_dim: usize, + ) { + let refuse = |this: &Self, why: String| -> ! { + this.fail(why.clone()); + crate::resident::refuse_resident(&why) + }; + if w.k() != in_dim || w.n() != out_dim || x.len() != m * in_dim || out.len() != m * out_dim + { + refuse( + self, + format!( + "resident weight is {}x{} but the call is m={m} in={in_dim} out={out_dim} (x={} out={})", + w.k(), + w.n(), + x.len(), + out.len() + ), + ); + } + // One lock serializes every chip call (same lock as `chip_matmul`). + let guard = match self.chip.lock() { + Ok(g) => g, + Err(_) => refuse(self, "chip lock poisoned".into()), + }; + let res = w.matmul_f32(m, x, out); + drop(guard); + match res { + Ok(ns) => { + self.chip_calls.fetch_add(1, Ordering::Relaxed); + self.chip_ns.fetch_add(ns, Ordering::Relaxed); + } + Err(e) => refuse( + self, + format!("resident matmul m={m} k={in_dim} n={out_dim}: {e}"), + ), + } + } + /// Rope cos/sin table for `pos`, built exactly as the reference does /// (`tensor::apply_rope`, tensor.rs:101): f64 frequency and angle, then cast to f32. /// Cached per (head_dim, rope parameters, pos). @@ -659,6 +707,59 @@ impl TensorBackend for OmegaGb10Backend { } } + fn matmul_vec_w( + &self, + out: &mut [f32], + x: &[f32], + weight: crate::resident::MatrixRef<'_>, + out_dim: usize, + in_dim: usize, + ) { + match weight { + crate::resident::MatrixRef::Host(w) => self.matmul_vec(out, x, w, out_dim, in_dim), + crate::resident::MatrixRef::Resident(r) => { + self.chip_resident_matmul(out, x, r, 1, in_dim, out_dim) + } + } + } + + fn matmul_batch_w( + &self, + out: &mut [f32], + x: &[f32], + weight: crate::resident::MatrixRef<'_>, + batch_size: usize, + in_dim: usize, + out_dim: usize, + ) { + match weight { + crate::resident::MatrixRef::Host(w) => { + self.matmul_batch(out, x, w, batch_size, in_dim, out_dim) + } + crate::resident::MatrixRef::Resident(r) => { + self.chip_resident_matmul(out, x, r, batch_size, in_dim, out_dim) + } + } + } + + fn compute_logits_w( + &self, + logits: &mut [f32], + hidden: &[f32], + head: crate::resident::MatrixRef<'_>, + vocab_size: usize, + hidden_dim: usize, + ) { + match head { + crate::resident::MatrixRef::Host(w) => { + self.compute_logits(logits, hidden, w, vocab_size, hidden_dim) + } + crate::resident::MatrixRef::Resident(r) => { + self.chip_resident_matmul(logits, hidden, r, 1, hidden_dim, vocab_size) + } + } + } + fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) { if !self.chip_swiglu(out, gate, up) { self.reference_for(TensorOp::Swiglu); diff --git a/crates/aien-inference-abi/src/resident.rs b/crates/aien-inference-abi/src/resident.rs new file mode 100644 index 00000000..94b2ef4f --- /dev/null +++ b/crates/aien-inference-abi/src/resident.rs @@ -0,0 +1,302 @@ +//! GB10 weight ownership (sovereign-core #277, cut C; design: docs/design/gb10-weight-ownership.md). +//! +//! On the GB10 production path a matmul weight lives on the device only: it is streamed from +//! the checkpoint's bf16 bytes straight into a resident tensor, and the process never holds an +//! f32 copy of it. [`MatrixWeight`] is the one type that says which of the two a weight is. +//! +//! * `Host`: the f32 values, for the CPU reference backend, dev builds, tests and every model +//! that is not on the GB10 resident path. Unchanged behaviour. +//! * `Resident`: a handle to the device copy. There are no host values; asking for them is a +//! named refusal (`RESIDENT_WEIGHT_REFUSED`), never a silent CPU computation. + +use crate::checkpoint::{decode_bf16_to_fp32, CheckpointError, StreamedCheckpoint}; +use crate::weights::{TransformerLayerWeights, TransformerWeights}; +use aien_abi_core::ModelConfig; +use std::sync::{Arc, Mutex}; + +/// Tag every refusal about a resident weight carries, so logs and receipts can be grepped. +pub const RESIDENT_REFUSAL_PREFIX: &str = "RESIDENT_WEIGHT_REFUSED"; + +/// Panics with the named refusal. A resident weight has no host values, so there is nothing +/// a fallback could compute with; the failure must be loud. +#[cold] +pub(crate) fn refuse_resident(what: &str) -> ! { + panic!( + "{RESIDENT_REFUSAL_PREFIX}: {what}; the weight is resident on the device and has no host copy, so there is no CPU fallback" + ) +} + +/// The device side of a resident weight. The omega implementation wraps a `ResidentTensor` +/// behind a lock; tests use a fake that never touches a device. +pub trait ResidentHandle: Send + Sync + std::fmt::Debug { + /// `c[m x n] = a[m x k] * W`, f32 `a`. Returns the chip time in nanoseconds. + fn matmul_f32(&self, m: usize, a: &[f32], c: &mut [f32]) -> Result; +} + +impl ResidentHandle for Mutex { + fn matmul_f32(&self, m: usize, a: &[f32], c: &mut [f32]) -> Result { + let guard = self + .lock() + .map_err(|_| "resident tensor lock poisoned".to_string())?; + guard + .matmul_f32(m, a, c) + .map(|info| info.raw.elapsed_ns) + .map_err(|e| e.to_string()) + } +} + +/// A matmul weight that lives on the device: `k` is the input width, `n` the output width. +/// Cloning shares the device copy; it is freed when the last clone drops. +#[derive(Clone, Debug)] +pub struct ResidentWeight { + k: usize, + n: usize, + handle: Arc, +} + +impl ResidentWeight { + pub fn new(k: usize, n: usize, handle: Arc) -> Self { + Self { k, n, handle } + } + + pub fn k(&self) -> usize { + self.k + } + + pub fn n(&self) -> usize { + self.n + } + + pub fn matmul_f32(&self, m: usize, a: &[f32], c: &mut [f32]) -> Result { + self.handle.matmul_f32(m, a, c) + } +} + +/// A matmul weight, `[out_dim, in_dim]` row-major when on the host. +#[derive(Clone, Debug)] +pub enum MatrixWeight { + Host(Vec), + Resident(ResidentWeight), +} + +/// A borrowed [`MatrixWeight`], as the backend sees it. +#[derive(Clone, Copy, Debug)] +pub enum MatrixRef<'a> { + Host(&'a [f32]), + Resident(&'a ResidentWeight), +} + +impl<'a> MatrixRef<'a> { + /// The host values, or the named refusal when the weight is resident. + pub fn host_or_refuse(self, op: &str) -> &'a [f32] { + match self { + Self::Host(v) => v, + Self::Resident(r) => refuse_resident(&format!( + "{op} needs host f32 values of a {}x{} weight", + r.k, r.n + )), + } + } +} + +impl MatrixWeight { + pub fn as_ref(&self) -> MatrixRef<'_> { + match self { + Self::Host(v) => MatrixRef::Host(v), + Self::Resident(r) => MatrixRef::Resident(r), + } + } + + pub fn is_resident(&self) -> bool { + matches!(self, Self::Resident(_)) + } +} + +impl From> for MatrixWeight { + fn from(v: Vec) -> Self { + Self::Host(v) + } +} + +/// Host-slice view for the CPU reference code and tests. A resident weight is refused by name. +impl std::ops::Deref for MatrixWeight { + type Target = [f32]; + fn deref(&self) -> &[f32] { + self.as_ref().host_or_refuse("host slice access") + } +} + +/// What omega's `omega_gpu_tensor_upload_f32` would store for the bf16 pattern `bits` after the +/// loader widened it to f32: its f32-to-bf16 step is `(__bf16)f` (src/omega_blackwell_matmul.c:98 +/// at omega.lock), which rounds to nearest even and sets the quiet bit of a NaN. Widening a bf16 +/// is exact, so every pattern comes back unchanged except the 126 signaling NaNs (exponent all +/// ones, quiet bit clear, mantissa non-zero), which come back with the quiet bit set. Checked +/// against the compiler's own cast for all 65536 patterns on this aarch64 host (see the test). +#[inline] +pub fn bf16_bits_as_uploaded_today(bits: u16) -> u16 { + let is_nan = bits & 0x7f80 == 0x7f80 && bits & 0x007f != 0; + if is_nan { + bits | 0x0040 + } else { + bits + } +} + +/// Transposes bf16 weight bytes `[n][k]` (little endian, as safetensors stores `[out][in]`) into +/// the `[k][n]` bf16 layout the engine wants, applying [`bf16_bits_as_uploaded_today`]. `dst` is +/// resized to `k * n` and reused across calls. +pub fn transpose_bf16_for_upload(raw: &[u8], n: usize, k: usize, dst: &mut Vec) { + debug_assert_eq!(raw.len(), n * k * 2); + dst.clear(); + dst.resize(n * k, 0); + const TILE: usize = 64; + for o0 in (0..n).step_by(TILE) { + let o1 = (o0 + TILE).min(n); + for i0 in (0..k).step_by(TILE) { + let i1 = (i0 + TILE).min(k); + for o in o0..o1 { + let row = &raw[o * k * 2..(o + 1) * k * 2]; + for i in i0..i1 { + let bits = u16::from_le_bytes([row[i * 2], row[i * 2 + 1]]); + dst[i * n + o] = bf16_bits_as_uploaded_today(bits); + } + } + } + } +} + +/// Makes a `[k][n]` bf16 matrix resident. +pub trait ResidentUploader { + fn upload_bf16(&self, k: usize, n: usize, bits: &[u16]) -> Result; +} + +/// The real uploader: omega's `omega_gpu_tensor_upload_bf16`. +pub struct OmegaUploader; + +impl ResidentUploader for OmegaUploader { + fn upload_bf16(&self, k: usize, n: usize, bits: &[u16]) -> Result { + let tensor = + aien_omega_gpu::ResidentTensor::upload_bf16(k, n, bits).map_err(|e| e.to_string())?; + Ok(ResidentWeight::new(k, n, Arc::new(Mutex::new(tensor)))) + } +} + +/// Whether the daemon loads weights resident: the native engine is linked, the build is +/// production-strict (no CPU fallback to need host values for), the declared GB10 Qwen3 attempt +/// is on, and the model is one the engine accepts. Anything else keeps the host f32 load. +pub fn resident_load_wanted( + native_linked: bool, + strict: bool, + qwen3_opted_in: bool, + config: &ModelConfig, +) -> bool { + native_linked + && strict + && config.qk_norm + && crate::omega_backend::omega_model_refusal_with(config, qwen3_opted_in).is_none() +} + +/// Streams a checkpoint straight to the device. For each of the seven matmul weights of each +/// layer (and the tied or separate output head) it reads that tensor's bf16 bytes, transposes +/// them into `[k][n]` bf16 and uploads. All uploads happen BEFORE the f32 embedding is decoded, +/// so the driver's pinned-memory requests land while the process holds almost nothing. The +/// returned weights hold resident matrices, the f32 embedding and the small f32 norm vectors. +/// +/// `progress` is called once per uploaded matrix with its tensor name. +pub fn load_resident_weights>( + path: P, + config: &ModelConfig, + uploader: &dyn ResidentUploader, + progress: &mut dyn FnMut(&str), +) -> Result { + let catalog = crate::checkpoint::llama_catalog(config); + let ckpt = StreamedCheckpoint::open(path, &catalog)?; + let mut raw: Vec = Vec::new(); + let mut bits: Vec = Vec::new(); + let mut upload = |name: &str, n: usize, k: usize| -> Result { + ckpt.read_bf16_bytes(name, &mut raw)?; + transpose_bf16_for_upload(&raw, n, k, &mut bits); + let w = uploader.upload_bf16(k, n, &bits).map_err(|message| { + CheckpointError::ResidentUpload { + tensor: name.to_string(), + message, + } + })?; + progress(name); + Ok(MatrixWeight::Resident(w)) + }; + let hidden = config.hidden_dim(); + let inter = config.intermediate_dim(); + let q_dim = config.num_heads * config.head_dim; + let kv_dim = config.num_kv_heads * config.head_dim; + + // Pass 1: every matmul weight to the device. Nothing large is held on the host. + let mut mats = Vec::with_capacity(config.num_layers); + for idx in 0..config.num_layers { + let p = format!("model.layers.{idx}"); + mats.push([ + upload(&format!("{p}.self_attn.q_proj.weight"), q_dim, hidden)?, + upload(&format!("{p}.self_attn.k_proj.weight"), kv_dim, hidden)?, + upload(&format!("{p}.self_attn.v_proj.weight"), kv_dim, hidden)?, + upload(&format!("{p}.self_attn.o_proj.weight"), hidden, q_dim)?, + upload(&format!("{p}.mlp.gate_proj.weight"), inter, hidden)?, + upload(&format!("{p}.mlp.up_proj.weight"), inter, hidden)?, + upload(&format!("{p}.mlp.down_proj.weight"), hidden, inter)?, + ]); + } + let vocab = config.vocab_size(); + // Tied models project through the embedding: its own device copy, transposed. + let head_name = if config.tie_word_embeddings { + "model.embed_tokens.weight" + } else { + "lm_head.weight" + }; + let head = upload(head_name, vocab, hidden)?; + // Release the big transient buffers before the f32 embedding is allocated. + raw = Vec::new(); + drop(bits); + + // Pass 2: the host-side f32 data the host really reads (embedding rows, norms). + let decode = |name: &str, raw: &mut Vec| -> Result, CheckpointError> { + ckpt.read_bf16_bytes(name, raw)?; + Ok(decode_bf16_to_fp32(raw)) + }; + let mut layers = Vec::with_capacity(config.num_layers); + for (idx, m) in mats.into_iter().enumerate() { + let p = format!("model.layers.{idx}"); + let [q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj] = m; + let (q_norm, k_norm) = if config.qk_norm { + ( + Some(decode(&format!("{p}.self_attn.q_norm.weight"), &mut raw)?), + Some(decode(&format!("{p}.self_attn.k_norm.weight"), &mut raw)?), + ) + } else { + (None, None) + }; + layers.push(TransformerLayerWeights { + input_layernorm: decode(&format!("{p}.input_layernorm.weight"), &mut raw)?, + q_proj, + k_proj, + v_proj, + o_proj, + post_attention_layernorm: decode( + &format!("{p}.post_attention_layernorm.weight"), + &mut raw, + )?, + gate_proj, + up_proj, + down_proj, + q_norm, + k_norm, + }); + } + let final_norm = decode("model.norm.weight", &mut raw)?; + let embed_tokens = decode("model.embed_tokens.weight", &mut raw)?; + Ok(TransformerWeights { + config: config.clone(), + embed_tokens, + layers, + final_norm, + lm_head: Some(head), + }) +} diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index 565c8ce0..4bffa9a3 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -776,9 +776,9 @@ impl NativeTransformerBackend { for (layer_idx, layer_w) in weights.layers.iter().enumerate() { backend.rmsnorm(&mut x_norm, &x, &layer_w.input_layernorm, eps); - backend.matmul_vec(&mut q, &x_norm, &layer_w.q_proj, q_dim, hidden_dim); - backend.matmul_vec(&mut k, &x_norm, &layer_w.k_proj, kv_dim, hidden_dim); - backend.matmul_vec(&mut v, &x_norm, &layer_w.v_proj, kv_dim, hidden_dim); + backend.matmul_vec_w(&mut q, &x_norm, layer_w.q_proj.as_ref(), q_dim, hidden_dim); + backend.matmul_vec_w(&mut k, &x_norm, layer_w.k_proj.as_ref(), kv_dim, hidden_dim); + backend.matmul_vec_w(&mut v, &x_norm, layer_w.v_proj.as_ref(), kv_dim, hidden_dim); layer_w.apply_qk_norm_on(backend, &mut q, &mut k, head_dim, eps); backend.apply_rope( @@ -845,10 +845,10 @@ impl NativeTransformerBackend { ); } - backend.matmul_vec( + backend.matmul_vec_w( &mut attn_proj, &attn_out, - &layer_w.o_proj, + layer_w.o_proj.as_ref(), hidden_dim, q_dim, ); @@ -857,25 +857,25 @@ impl NativeTransformerBackend { } backend.rmsnorm(&mut post_norm, &x, &layer_w.post_attention_layernorm, eps); - backend.matmul_vec( + backend.matmul_vec_w( &mut gate, &post_norm, - &layer_w.gate_proj, + layer_w.gate_proj.as_ref(), intermediate_dim, hidden_dim, ); - backend.matmul_vec( + backend.matmul_vec_w( &mut up, &post_norm, - &layer_w.up_proj, + layer_w.up_proj.as_ref(), intermediate_dim, hidden_dim, ); backend.swiglu(&mut activated, &gate, &up); - backend.matmul_vec( + backend.matmul_vec_w( &mut mlp_out, &activated, - &layer_w.down_proj, + layer_w.down_proj.as_ref(), hidden_dim, intermediate_dim, ); @@ -898,10 +898,10 @@ impl NativeTransformerBackend { let vocab_size = weights.config.vocab_size(); let hidden_dim = weights.config.hidden_dim(); let mut logits = vec![0.0f32; vocab_size]; - backend.compute_logits( + backend.compute_logits_w( &mut logits, hidden_state, - weights.output_projection(), + weights.output_matrix(), vocab_size, hidden_dim, ); @@ -1081,26 +1081,26 @@ impl NativeTransformerBackend { backend.rmsnorm(out_slice, &states[t], &layer_w.input_layernorm, eps); } - backend.matmul_batch( + backend.matmul_batch_w( &mut q_batch, &x_norm_batch, - &layer_w.q_proj, + layer_w.q_proj.as_ref(), n, hidden_dim, q_dim, ); - backend.matmul_batch( + backend.matmul_batch_w( &mut k_batch, &x_norm_batch, - &layer_w.k_proj, + layer_w.k_proj.as_ref(), n, hidden_dim, kv_dim, ); - backend.matmul_batch( + backend.matmul_batch_w( &mut v_batch, &x_norm_batch, - &layer_w.v_proj, + layer_w.v_proj.as_ref(), n, hidden_dim, kv_dim, @@ -1151,10 +1151,10 @@ impl NativeTransformerBackend { ); } - backend.matmul_batch( + backend.matmul_batch_w( &mut attn_proj_batch, &attn_out_batch, - &layer_w.o_proj, + layer_w.o_proj.as_ref(), n, q_dim, hidden_dim, @@ -1176,18 +1176,18 @@ impl NativeTransformerBackend { ); } - backend.matmul_batch( + backend.matmul_batch_w( &mut gate_batch, &post_norm_batch, - &layer_w.gate_proj, + layer_w.gate_proj.as_ref(), n, hidden_dim, intermediate_dim, ); - backend.matmul_batch( + backend.matmul_batch_w( &mut up_batch, &post_norm_batch, - &layer_w.up_proj, + layer_w.up_proj.as_ref(), n, hidden_dim, intermediate_dim, @@ -1200,10 +1200,10 @@ impl NativeTransformerBackend { backend.swiglu(act_t, gate_t, up_t); } - backend.matmul_batch( + backend.matmul_batch_w( &mut mlp_out_batch, &act_batch, - &layer_w.down_proj, + layer_w.down_proj.as_ref(), n, intermediate_dim, hidden_dim, @@ -1406,26 +1406,26 @@ impl NativeTransformerBackend { } // b. Batched Q, K, V projections (M = D) - self.tensor_backend.matmul_batch( + self.tensor_backend.matmul_batch_w( &mut q_batch, &x_norm, - &layer_w.q_proj, + layer_w.q_proj.as_ref(), d, hidden_dim, q_dim, ); - self.tensor_backend.matmul_batch( + self.tensor_backend.matmul_batch_w( &mut k_batch, &x_norm, - &layer_w.k_proj, + layer_w.k_proj.as_ref(), d, hidden_dim, kv_dim, ); - self.tensor_backend.matmul_batch( + self.tensor_backend.matmul_batch_w( &mut v_batch, &x_norm, - &layer_w.v_proj, + layer_w.v_proj.as_ref(), d, hidden_dim, kv_dim, @@ -1546,10 +1546,10 @@ impl NativeTransformerBackend { } // f. Attention output projection (M = D) - self.tensor_backend.matmul_batch( + self.tensor_backend.matmul_batch_w( &mut attn_proj_batch, &attn_out_batch, - &layer_w.o_proj, + layer_w.o_proj.as_ref(), d, q_dim, hidden_dim, @@ -1571,18 +1571,18 @@ impl NativeTransformerBackend { } // i. MLP Gate & Up projections (M = D) - self.tensor_backend.matmul_batch( + self.tensor_backend.matmul_batch_w( &mut gate_batch, &post_norm_batch, - &layer_w.gate_proj, + layer_w.gate_proj.as_ref(), d, hidden_dim, intermediate_dim, ); - self.tensor_backend.matmul_batch( + self.tensor_backend.matmul_batch_w( &mut up_batch, &post_norm_batch, - &layer_w.up_proj, + layer_w.up_proj.as_ref(), d, hidden_dim, intermediate_dim, @@ -1598,10 +1598,10 @@ impl NativeTransformerBackend { } // k. MLP Down projection (M = D) - self.tensor_backend.matmul_batch( + self.tensor_backend.matmul_batch_w( &mut mlp_out_batch, &act_batch, - &layer_w.down_proj, + layer_w.down_proj.as_ref(), d, intermediate_dim, hidden_dim, @@ -1624,10 +1624,10 @@ impl NativeTransformerBackend { } // 7. Batched Vocabulary Logits Projection (M = D) - self.tensor_backend.matmul_batch( + self.tensor_backend.matmul_batch_w( &mut logits_batch, &x_norm, - self.weights.output_projection(), + self.weights.output_matrix(), d, hidden_dim, vocab_size, diff --git a/crates/aien-inference-abi/src/weights.rs b/crates/aien-inference-abi/src/weights.rs index 8e690734..22ab478e 100644 --- a/crates/aien-inference-abi/src/weights.rs +++ b/crates/aien-inference-abi/src/weights.rs @@ -1,5 +1,6 @@ //! Native weight data structures and zero-dependency loaders for transformer models. +use crate::resident::{MatrixRef, MatrixWeight}; use crate::tensor::{ apply_rope_params, matmul_vec, rmsnorm, rmsnorm_heads_in_place, scaled_dot_product_attention_single, swiglu, @@ -24,14 +25,14 @@ pub struct SequenceState { #[derive(Debug, Clone)] pub struct TransformerLayerWeights { pub input_layernorm: Vec, - pub q_proj: Vec, - pub k_proj: Vec, - pub v_proj: Vec, - pub o_proj: Vec, + pub q_proj: MatrixWeight, + pub k_proj: MatrixWeight, + pub v_proj: MatrixWeight, + pub o_proj: MatrixWeight, pub post_attention_layernorm: Vec, - pub gate_proj: Vec, - pub up_proj: Vec, - pub down_proj: Vec, + pub gate_proj: MatrixWeight, + pub up_proj: MatrixWeight, + pub down_proj: MatrixWeight, /// Qwen3 per-head RMSNorm weights `[head_dim]` for Q and K (`config.qk_norm`); `None` for /// Llama-architecture models. pub q_norm: Option>, @@ -77,10 +78,11 @@ pub struct TransformerWeights { pub embed_tokens: Vec, pub layers: Vec, pub final_norm: Vec, - /// Output projection `[vocab, hidden]`. `None` when `config.tie_word_embeddings`: - /// the projection is `embed_tokens` itself (no second copy). Read it through - /// [`TransformerWeights::output_projection`]. - pub lm_head: Option>, + /// Output projection `[vocab, hidden]`. `None` when `config.tie_word_embeddings` on the host + /// path: the projection is `embed_tokens` itself (no second copy). On the GB10 resident path + /// it is `Some(Resident)` even for tied models (the embedding's own device copy). Read it + /// through [`TransformerWeights::output_matrix`]. + pub lm_head: Option, } /// Diagnostic capture of intermediate activations and shapes across all transformer layers. @@ -95,9 +97,15 @@ impl TransformerWeights { /// `lm_head`, or `embed_tokens` for a model with tied word embeddings. #[inline] pub fn output_projection(&self) -> &[f32] { + self.output_matrix().host_or_refuse("output_projection") + } + + /// [`Self::output_projection`] as host values or a device handle; what the backends take. + #[inline] + pub fn output_matrix(&self) -> MatrixRef<'_> { match &self.lm_head { - Some(lm_head) => lm_head, - None => &self.embed_tokens, + Some(lm_head) => lm_head.as_ref(), + None => MatrixRef::Host(&self.embed_tokens), } } @@ -192,14 +200,14 @@ impl TransformerWeights { layers.push(TransformerLayerWeights { input_layernorm, - q_proj, - k_proj, - v_proj, - o_proj, + q_proj: q_proj.into(), + k_proj: k_proj.into(), + v_proj: v_proj.into(), + o_proj: o_proj.into(), post_attention_layernorm, - gate_proj, - up_proj, - down_proj, + gate_proj: gate_proj.into(), + up_proj: up_proj.into(), + down_proj: down_proj.into(), q_norm: config.qk_norm.then(|| vec![1.0f32; config.head_dim]), k_norm: config.qk_norm.then(|| vec![1.0f32; config.head_dim]), }); @@ -223,7 +231,7 @@ impl TransformerWeights { embed_tokens, layers, final_norm, - lm_head, + lm_head: lm_head.map(Into::into), } } @@ -712,29 +720,29 @@ impl TransformerWeights { layer.input_layernorm = t; } if let Some(t) = extract_tensor(&format!("{}.self_attn.q_proj.weight", prefix)) { - layer.q_proj = t; + layer.q_proj = t.into(); } if let Some(t) = extract_tensor(&format!("{}.self_attn.k_proj.weight", prefix)) { - layer.k_proj = t; + layer.k_proj = t.into(); } if let Some(t) = extract_tensor(&format!("{}.self_attn.v_proj.weight", prefix)) { - layer.v_proj = t; + layer.v_proj = t.into(); } if let Some(t) = extract_tensor(&format!("{}.self_attn.o_proj.weight", prefix)) { - layer.o_proj = t; + layer.o_proj = t.into(); } if let Some(t) = extract_tensor(&format!("{}.post_attention_layernorm.weight", prefix)) { layer.post_attention_layernorm = t; } if let Some(t) = extract_tensor(&format!("{}.mlp.gate_proj.weight", prefix)) { - layer.gate_proj = t; + layer.gate_proj = t.into(); } if let Some(t) = extract_tensor(&format!("{}.mlp.up_proj.weight", prefix)) { - layer.up_proj = t; + layer.up_proj = t.into(); } if let Some(t) = extract_tensor(&format!("{}.mlp.down_proj.weight", prefix)) { - layer.down_proj = t; + layer.down_proj = t.into(); } if config.qk_norm { layer.q_norm = extract_tensor(&format!("{}.self_attn.q_norm.weight", prefix)); @@ -748,7 +756,7 @@ impl TransformerWeights { if !config.tie_word_embeddings { if let Some(t) = extract_tensor("lm_head.weight") { - weights.lm_head = Some(t); + weights.lm_head = Some(t.into()); } } @@ -797,14 +805,14 @@ impl TransformerWeights { layers.push(TransformerLayerWeights { input_layernorm, - q_proj, - k_proj, - v_proj, - o_proj, + q_proj: q_proj.into(), + k_proj: k_proj.into(), + v_proj: v_proj.into(), + o_proj: o_proj.into(), post_attention_layernorm, - gate_proj, - up_proj, - down_proj, + gate_proj: gate_proj.into(), + up_proj: up_proj.into(), + down_proj: down_proj.into(), q_norm, k_norm, }); @@ -822,7 +830,7 @@ impl TransformerWeights { embed_tokens, layers, final_norm, - lm_head, + lm_head: lm_head.map(Into::into), }) } diff --git a/crates/aien-inference-abi/tests/resident_weights.rs b/crates/aien-inference-abi/tests/resident_weights.rs new file mode 100644 index 00000000..10c41918 --- /dev/null +++ b/crates/aien-inference-abi/tests/resident_weights.rs @@ -0,0 +1,489 @@ +//! GB10 weight ownership (sovereign-core #277 cut C): resident bf16 upload straight from the +//! checkpoint, no host f32 copy of any matmul weight. +//! +//! No chip is used. The "device" is a fake that keeps the uploaded `[k][n]` bf16 bits and +//! computes with the same host arithmetic as the reference backend, so a Host load and a +//! Resident load of the same checkpoint must give bit-identical logits if (and only if) the +//! streaming, the transpose and the dispatch are right. + +use aien_abi_core::RopeParams; +use aien_inference_abi::{ + bf16_bits_as_uploaded_today, load_model_config, load_resident_weights, resident_load_wanted, + transpose_bf16_for_upload, CheckpointError, MatrixRef, MatrixWeight, NativeTransformerBackend, + ReferenceCpuBackend, ResidentHandle, ResidentUploader, ResidentWeight, TensorBackend, + TransformerWeights, +}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +fn tiny_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures/qwen3-tiny") +} + +// ---- numerics: bf16 -> f32 -> bf16 over every pattern ---- + +/// Independent software model of `(__bf16)f` on aarch64 (round to nearest even, NaN quieted), +/// not sharing code with the loader. It was checked against gcc's own `(__bf16)` cast for all +/// 65536 patterns on this host: 126 differences, all signaling NaNs (see the PR text). +fn narrow_like_omega(f: f32) -> u16 { + let bits = f.to_bits(); + if f.is_nan() { + return ((bits >> 16) as u16) | 0x0040; + } + let lsb = (bits >> 16) & 1; + (bits.wrapping_add(0x7fff + lsb) >> 16) as u16 +} + +#[test] +fn bf16_widen_then_narrow_is_exact_except_signaling_nans_which_omega_quiets() { + let mut changed = Vec::new(); + let (mut denormals, mut nans, mut infs) = (0u32, 0u32, 0u32); + for p in 0..=u16::MAX { + let widened = f32::from_bits((p as u32) << 16); + let via_omega = narrow_like_omega(widened); + // What the loader sends must equal what omega's f32 path stores today, for every pattern. + assert_eq!( + bf16_bits_as_uploaded_today(p), + via_omega, + "pattern {p:#06x}" + ); + if via_omega != p { + changed.push(p); + } + let exp = (p >> 7) & 0xff; + let man = p & 0x7f; + if exp == 0 && man != 0 { + denormals += 1; + } + if exp == 0xff && man != 0 { + nans += 1; + } + if exp == 0xff && man == 0 { + infs += 1; + } + } + // Every NaN payload, every denormal, both infinities and both zeros are in the sweep. + assert_eq!((denormals, nans, infs), (254, 254, 2)); + // The only patterns that change: signaling NaNs (quiet bit clear), 63 per sign. + assert_eq!(changed.len(), 126); + for p in &changed { + assert_eq!(p & 0x7f80, 0x7f80); + assert_eq!(p & 0x0040, 0, "{p:#06x} is not a signaling NaN"); + assert_ne!(p & 0x007f, 0); + assert_eq!(bf16_bits_as_uploaded_today(*p), p | 0x0040); + } + // Everything else, including all denormals and the quiet NaN payloads, is bit-identical. + assert!(!changed.contains(&0x0001) && !changed.contains(&0x7fc1) && !changed.contains(&0x8000)); +} + +#[test] +fn transpose_puts_w_out_in_into_k_by_n() { + let (n, k) = (3usize, 5usize); + let src: Vec = (0..(n * k) as u16).map(|i| 0x3f80 + i).collect(); // finite bf16 values + let raw: Vec = src.iter().flat_map(|b| b.to_le_bytes()).collect(); + let mut dst = vec![9u16; 4]; + transpose_bf16_for_upload(&raw, n, k, &mut dst); + assert_eq!(dst.len(), n * k); + for o in 0..n { + for i in 0..k { + assert_eq!(dst[i * n + o], src[o * k + i], "o={o} i={i}"); + } + } + // Larger than one 64x64 tile in both directions, odd sizes. + let (n, k) = (131usize, 70usize); + let src: Vec = (0..(n * k)).map(|i| (i as u16) | 0x4000).collect(); + let raw: Vec = src.iter().flat_map(|b| b.to_le_bytes()).collect(); + transpose_bf16_for_upload(&raw, n, k, &mut dst); + for o in 0..n { + for i in 0..k { + assert_eq!(dst[i * n + o], src[o * k + i]); + } + } +} + +// ---- a fake device ---- + +#[derive(Debug)] +struct FakeDevice { + k: usize, + n: usize, + /// W as `[n][k]` f32, rebuilt from the uploaded `[k][n]` bf16 bits. + w: Vec, + calls: Mutex, +} + +impl ResidentHandle for FakeDevice { + fn matmul_f32(&self, m: usize, a: &[f32], c: &mut [f32]) -> Result { + assert_eq!(a.len(), m * self.k); + assert_eq!(c.len(), m * self.n); + for r in 0..m { + aien_inference_abi::tensor::matmul_vec( + &a[r * self.k..(r + 1) * self.k], + &self.w, + &mut c[r * self.n..(r + 1) * self.n], + self.k, + self.n, + ); + } + *self.calls.lock().unwrap() += 1; + Ok(1) + } +} + +#[derive(Default)] +struct FakeUploader { + shapes: Mutex>, + /// Zero the first uploaded matrix (negative control). + corrupt_first: bool, + /// Fail on the Nth upload (0-based). + fail_at: Option, +} + +impl ResidentUploader for FakeUploader { + fn upload_bf16(&self, k: usize, n: usize, bits: &[u16]) -> Result { + let idx = { + let mut s = self.shapes.lock().unwrap(); + s.push((k, n)); + s.len() - 1 + }; + if self.fail_at == Some(idx) { + return Err("NV_ERR_NO_MEMORY (fake)".to_string()); + } + assert_eq!(bits.len(), k * n); + let mut w = vec![0.0f32; n * k]; + for i in 0..k { + for o in 0..n { + w[o * k + i] = f32::from_bits((bits[i * n + o] as u32) << 16); + } + } + if self.corrupt_first && idx == 0 { + w.iter_mut().for_each(|v| *v = 0.0); + } + Ok(ResidentWeight::new( + k, + n, + Arc::new(FakeDevice { + k, + n, + w, + calls: Mutex::new(0), + }), + )) + } +} + +/// The reference backend plus the one thing the real GB10 backend adds: it can run a resident +/// weight. Everything else delegates, so a difference can only come from the weights. +struct DeviceLikeBackend(ReferenceCpuBackend); + +impl TensorBackend for DeviceLikeBackend { + fn name(&self) -> &'static str { + "DeviceLikeBackend (test)" + } + fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) { + self.0.rmsnorm(out, x, weight, eps) + } + fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { + self.0.rmsnorm_heads(x, weight, head_dim, eps) + } + fn apply_rope( + &self, + q: &mut [f32], + k: &mut [f32], + pos: usize, + head_dim: usize, + nq: usize, + nkv: usize, + rope: &RopeParams, + ) { + self.0.apply_rope(q, k, pos, head_dim, nq, nkv, rope) + } + fn matmul_vec(&self, out: &mut [f32], x: &[f32], w: &[f32], out_dim: usize, in_dim: usize) { + self.0.matmul_vec(out, x, w, out_dim, in_dim) + } + fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) { + self.0.swiglu(out, gate, up) + } + fn gqa_attention( + &self, + out: &mut [f32], + q: &[f32], + kc: &[f32], + vc: &[f32], + seq_len: usize, + nq: usize, + nkv: usize, + head_dim: usize, + ) { + self.0 + .gqa_attention(out, q, kc, vc, seq_len, nq, nkv, head_dim) + } + fn compute_logits(&self, l: &mut [f32], h: &[f32], e: &[f32], v: usize, hd: usize) { + self.0.compute_logits(l, h, e, v, hd) + } + fn matmul_batch_w( + &self, + out: &mut [f32], + x: &[f32], + w: MatrixRef<'_>, + batch: usize, + in_dim: usize, + out_dim: usize, + ) { + match w { + MatrixRef::Host(h) => self.0.matmul_batch(out, x, h, batch, in_dim, out_dim), + MatrixRef::Resident(r) => { + assert_eq!((r.k(), r.n()), (in_dim, out_dim)); + r.matmul_f32(batch, x, out).unwrap(); + } + } + } + fn matmul_vec_w( + &self, + out: &mut [f32], + x: &[f32], + w: MatrixRef<'_>, + out_dim: usize, + in_dim: usize, + ) { + self.matmul_batch_w(out, x, w, 1, in_dim, out_dim) + } + fn compute_logits_w( + &self, + l: &mut [f32], + h: &[f32], + w: MatrixRef<'_>, + vocab: usize, + hidden: usize, + ) { + self.matmul_batch_w(l, h, w, 1, hidden, vocab) + } +} + +fn host_weights() -> TransformerWeights { + let dir = tiny_dir(); + let config = load_model_config(&dir).unwrap(); + TransformerWeights::load_from_safetensors(dir.join("model.safetensors"), &config).unwrap() +} + +fn resident_weights(up: &FakeUploader) -> Result { + let dir = tiny_dir(); + let config = load_model_config(&dir).unwrap(); + load_resident_weights(dir.join("model.safetensors"), &config, up, &mut |_| {}) +} + +fn max_abs(a: &[f32], b: &[f32]) -> f32 { + assert_eq!(a.len(), b.len()); + a.iter() + .zip(b) + .map(|(x, y)| (x - y).abs()) + .fold(0.0, f32::max) +} + +const IDS: [u32; 6] = [3, 17, 5, 9, 1, 22]; + +fn prefill_logits(weights: TransformerWeights) -> Vec { + let mut be = NativeTransformerBackend::with_backend( + weights, + Arc::new(DeviceLikeBackend(Default::default())), + ); + be.prefill_sequence(1, &IDS).expect("prefill") +} + +#[test] +fn resident_load_holds_no_host_matmul_weight_and_matches_host_logits_exactly() { + let up = FakeUploader::default(); + let w = resident_weights(&up).expect("resident load"); + let layers = w.layers.len(); + // Every one of the seven matmul weights per layer, plus the (tied) head, is resident. + for l in &w.layers { + for m in [ + &l.q_proj, + &l.k_proj, + &l.v_proj, + &l.o_proj, + &l.gate_proj, + &l.up_proj, + &l.down_proj, + ] { + assert!(m.is_resident()); + } + } + assert!(w.config.tie_word_embeddings); + assert!(matches!(w.lm_head, Some(MatrixWeight::Resident(_)))); + assert_eq!(up.shapes.lock().unwrap().len(), layers * 7 + 1); + // The host keeps what the host reads: embedding rows and norms (readers: see the PR text). + assert_eq!(w.embed_tokens, host_weights().embed_tokens); + assert_eq!(w.final_norm, host_weights().final_norm); + + let got = prefill_logits(w); + let want = prefill_logits(host_weights()); + assert_eq!( + got, want, + "resident logits must be bit-identical to host logits" + ); +} + +#[test] +fn negative_control_a_wrong_resident_matrix_moves_the_logits() { + let up = FakeUploader { + corrupt_first: true, + ..Default::default() + }; + let got = prefill_logits(resident_weights(&up).unwrap()); + let want = prefill_logits(host_weights()); + assert!(max_abs(&got, &want) > 1e-3, "comparison would be vacuous"); +} + +#[test] +fn uploads_run_layer_by_layer_then_the_head() { + let dir = tiny_dir(); + let config = load_model_config(&dir).unwrap(); + let mut names = Vec::new(); + load_resident_weights( + dir.join("model.safetensors"), + &config, + &FakeUploader::default(), + &mut |n| names.push(n.to_string()), + ) + .unwrap(); + assert_eq!( + names.first().unwrap(), + "model.layers.0.self_attn.q_proj.weight" + ); + assert_eq!(names.last().unwrap(), "model.embed_tokens.weight"); + assert_eq!(names.len(), config.num_layers * 7 + 1); +} + +#[test] +fn an_upload_failure_is_a_named_error_never_a_host_copy() { + let up = FakeUploader { + fail_at: Some(3), + ..Default::default() + }; + match resident_weights(&up) { + Err(CheckpointError::ResidentUpload { tensor, message }) => { + assert_eq!(tensor, "model.layers.0.self_attn.o_proj.weight"); + assert!(message.contains("NV_ERR_NO_MEMORY")); + } + other => panic!("expected ResidentUpload, got {:?}", other.map(|_| ())), + } +} + +#[test] +fn a_missing_tensor_is_refused_before_any_upload() { + let dir = tiny_dir(); + let mut config = load_model_config(&dir).unwrap(); + config.num_layers += 1; // the file has no layer N + let up = FakeUploader::default(); + let r = load_resident_weights(dir.join("model.safetensors"), &config, &up, &mut |_| {}); + assert!(matches!(r, Err(CheckpointError::MissingTensor(_)))); + assert!( + up.shapes.lock().unwrap().is_empty(), + "uploaded before validating" + ); +} + +#[test] +#[should_panic(expected = "RESIDENT_WEIGHT_REFUSED")] +fn the_cpu_reference_backend_refuses_a_resident_weight_by_name() { + let w = resident_weights(&FakeUploader::default()).unwrap(); + let be = ReferenceCpuBackend::new(); + let mut out = vec![0.0; w.config.num_heads * w.config.head_dim]; + let x = vec![0.0; w.config.hidden_dim()]; + let (od, id) = (out.len(), x.len()); + be.matmul_vec_w(&mut out, &x, w.layers[0].q_proj.as_ref(), od, id); +} + +#[test] +#[should_panic(expected = "RESIDENT_WEIGHT_REFUSED")] +fn host_slice_access_to_a_resident_weight_is_refused_by_name() { + let w = resident_weights(&FakeUploader::default()).unwrap(); + let _ = w.layers[0].q_proj.len(); +} + +#[test] +fn resident_load_is_chosen_only_on_the_native_strict_opted_in_qwen3_path() { + let dir = tiny_dir(); + let tiny = load_model_config(&dir).unwrap(); // qk_norm, head_dim 16 + let mut q4b = tiny.clone(); + q4b.head_dim = 128; // the head_dim the GB10 engine accepts for Qwen3 + // (native, strict, opted in, accepted Qwen3) -> resident + assert!(resident_load_wanted(true, true, true, &q4b)); + // each condition off -> host f32 load, unchanged + assert!(!resident_load_wanted(false, true, true, &q4b)); // stub build / no GB10 + assert!(!resident_load_wanted(true, false, true, &q4b)); // dev-fallback needs host values + assert!(!resident_load_wanted(true, true, false, &q4b)); // default refusal of Qwen3 stays + assert!(!resident_load_wanted(true, true, true, &tiny)); // engine refuses head_dim 16 + let mut llama = q4b.clone(); + llama.qk_norm = false; // other models keep their path + assert!(!resident_load_wanted(true, true, true, &llama)); +} + +#[test] +fn streamed_checkpoint_reads_the_same_bytes_as_the_whole_file_loader() { + let dir = tiny_dir(); + let config = load_model_config(&dir).unwrap(); + let catalog = aien_inference_abi::llama_catalog(&config); + let path = dir.join("model.safetensors"); + let whole = aien_inference_abi::load_checkpoint_with_catalog(&path, &catalog).unwrap(); + let streamed = aien_inference_abi::StreamedCheckpoint::open(&path, &catalog).unwrap(); + let mut buf = Vec::new(); + for (name, shape) in &catalog { + let n = streamed.read_bf16_bytes(name, &mut buf).unwrap(); + assert_eq!(n, shape.iter().product::(), "{name}"); + assert_eq!(buf.as_slice(), whole.tensor_bytes(name).unwrap(), "{name}"); + assert_eq!(streamed.shape(name).unwrap(), shape.as_slice()); + } + // A catalog tensor the file lacks is refused when the checkpoint is opened. + let mut bad = catalog.clone(); + bad.push(("model.layers.9.mlp.up_proj.weight".to_string(), vec![4, 4])); + assert!(matches!( + aien_inference_abi::StreamedCheckpoint::open(&path, &bad), + Err(CheckpointError::MissingTensor(_)) + )); +} + +fn fake_resident(k: usize, n: usize) -> (ResidentWeight, Vec) { + // W [n][k] with bf16-exact values, and its resident twin built through the real transpose. + let w: Vec = (0..n * k) + .map(|i| f32::from_bits((0x3f00 + (i % 200) as u32) << 16)) + .collect(); + let raw: Vec = w + .iter() + .flat_map(|v| ((v.to_bits() >> 16) as u16).to_le_bytes()) + .collect(); + let mut bits = Vec::new(); + transpose_bf16_for_upload(&raw, n, k, &mut bits); + (FakeUploader::default().upload_bf16(k, n, &bits).unwrap(), w) +} + +#[test] +fn omega_backend_runs_a_resident_weight_through_the_resident_handle() { + let (k, n) = (16usize, 24usize); + let (r, w) = fake_resident(k, n); + let be = aien_inference_abi::OmegaGb10Backend::new(); // stub build: no chip, no host path used + let x: Vec = (0..3 * k).map(|i| (i % 7) as f32 * 0.25).collect(); + let mut got = vec![0.0; 3 * n]; + be.matmul_batch_w(&mut got, &x, MatrixRef::Resident(&r), 3, k, n); + let mut want = vec![0.0; 3 * n]; + ReferenceCpuBackend::new().matmul_batch(&mut want, &x, &w, 3, k, n); + assert_eq!(got, want); + assert_eq!(be.chip_calls(), 1); + assert_eq!(be.fallback_count(), 0); + let mut one = vec![0.0; n]; + be.matmul_vec_w(&mut one, &x[..k], MatrixRef::Resident(&r), n, k); + assert_eq!(one, want[..n]); + be.compute_logits_w(&mut one, &x[..k], MatrixRef::Resident(&r), n, k); + assert_eq!(one, want[..n]); + assert_eq!(be.chip_calls(), 3); +} + +#[test] +#[should_panic(expected = "RESIDENT_WEIGHT_REFUSED")] +fn omega_backend_refuses_a_resident_weight_of_the_wrong_shape() { + let (r, _) = fake_resident(16, 24); + let be = aien_inference_abi::OmegaGb10Backend::new(); + let mut out = vec![0.0; 32]; + be.matmul_vec_w(&mut out, &[0.0; 16], MatrixRef::Resident(&r), 32, 16); +} diff --git a/crates/aien-omega-gpu/src/lib.rs b/crates/aien-omega-gpu/src/lib.rs index d3163612..38225aab 100644 --- a/crates/aien-omega-gpu/src/lib.rs +++ b/crates/aien-omega-gpu/src/lib.rs @@ -262,6 +262,33 @@ impl ResidentTensor { } } + /// Upload a row-major k x n matrix of bf16 bit patterns exactly as given (no rounding). + /// The resident data equals `upload_f32` of the widened values, except that omega's + /// f32-to-bf16 step quiets signaling NaNs (see `aien-inference-abi` `resident.rs`). + pub fn upload_bf16(k: usize, n: usize, b: &[u16]) -> Result { + check_len("b", k * n, b.len())?; + let (_, ku, nu) = dims(1, k, n)?; + #[cfg(has_omega_gpu)] + { + let mut ptr: *mut ffi::OmegaGpuTensor = std::ptr::null_mut(); + // SAFETY: b has k*n elements (checked); ptr is a valid out-pointer. + let rc = unsafe { ffi::omega_gpu_tensor_upload_bf16(ku, nu, b.as_ptr(), &mut ptr) }; + if rc != ffi::OMEGA_GPU_MATMUL_OK || ptr.is_null() { + return Err(rc_error(if rc == 0 { + ffi::OMEGA_GPU_MATMUL_BAD_ARGS + } else { + rc + })); + } + Ok(Self { ptr, k, n }) + } + #[cfg(not(has_omega_gpu))] + { + let _ = (ku, nu); + Err(OmegaGpuError::Unavailable) + } + } + pub fn k(&self) -> usize { self.k } diff --git a/docs/design/gb10-weight-ownership.md b/docs/design/gb10-weight-ownership.md index e8065a6b..eccd4223 100644 --- a/docs/design/gb10-weight-ownership.md +++ b/docs/design/gb10-weight-ownership.md @@ -55,6 +55,12 @@ layers, 32 query heads, 8 KV heads, head_dim 128, vocab 151936, tied embeddings, In attempt 2 the low-memory state was present at launch, but the scripted cache fill reclaimed memory before the baseline ran. A protocol amendment that skips the fill when the trigger already holds is proposed on #277 and not applied. +## Update 2026-10-07 (cut C written, host-measured, not run on the chip) + +- Cut C is in draft PR "Part of #277 (cut C), stacked on #311": `MatrixWeight` (host f32 or a device handle) replaces the seven per-layer f32 matmul weights and the output head; `aien-inference-abi/src/resident.rs` streams each matrix from the bf16 shard (positioned reads, one tensor at a time, `checkpoint.rs` `StreamedCheckpoint`) into `omega_gpu_tensor_upload_bf16`, and the daemon does it only on the native, production-strict, opted-in GB10 Qwen3 path, after opening the GPU session. Every other load is the unchanged host f32 load. +- Numerics: bf16 widened to f32 and narrowed again by omega (`(__bf16)f`, omega_blackwell_matmul.c:98 at omega.lock) is exact for 65410 of 65536 patterns and quiets the 126 signaling NaNs; the loader applies the same quieting, so the uploaded bits equal today's for every pattern. +- Host measurement (stub uploader, real Qwen3-4B checkpoint): peak 22.479 GiB before, 2.176 GiB after; steady 14.988 GiB before, 1.452 GiB after. The chip effect on #277 is NOT measured. + ## 1. Allocation audit All GPU-side allocations go through `omega_gpu_session_alloc` (omega `src/omega_gpu_session.c:78-82`)