Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-inference-abi/src/resident.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-inference-abi / src / resident.rs` 349 lines ยท 13715 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! GB10 weight ownership (sovereign-core #277, cut C; design: docs/design/gb10-weight-ownership.md). 17 //! 18 //! On the GB10 production path a matmul weight lives on the device only: it is streamed from 19 //! the checkpoint's bf16 bytes straight into a resident tensor, and the process never holds an 20 //! f32 copy of it. [`MatrixWeight`] is the one type that says which of the two a weight is. 21 //! 22 //! * `Host`: the f32 values, for the CPU reference backend, dev builds, tests and every model 23 //! that is not on the GB10 resident path. Unchanged behaviour. 24 //! * `Resident`: a handle to the device copy. There are no host values; asking for them is a 25 //! named refusal (`RESIDENT_WEIGHT_REFUSED`), never a silent CPU computation. 26 27 use crate::checkpoint::{decode_bf16_to_fp32, CheckpointError, StreamedCheckpoint}; 28 use crate::weights::{TransformerLayerWeights, TransformerWeights}; 29 use aien_abi_core::ModelConfig; 30 use std::sync::{Arc, Mutex}; 31 32 /// Tag every refusal about a resident weight carries, so logs and receipts can be grepped. 33 pub const RESIDENT_REFUSAL_PREFIX: &str = "RESIDENT_WEIGHT_REFUSED"; 34 35 /// Panics with the named refusal. A resident weight has no host values, so there is nothing 36 /// a fallback could compute with; the failure must be loud. 37 #[cold] 38 pub(crate) fn refuse_resident(what: &str) -> ! { 39 panic!( 40 "{RESIDENT_REFUSAL_PREFIX}: {what}; the weight is resident on the device and has no host copy, so there is no CPU fallback" 41 ) 42 } 43 44 /// The device side of a resident weight. The omega implementation wraps a `ResidentTensor` 45 /// behind a lock; tests use a fake that never touches a device. 46 pub trait ResidentHandle: Send + Sync + std::fmt::Debug { 47 /// `c[m x n] = a[m x k] * W`, f32 `a`. Returns the chip time in nanoseconds. 48 fn matmul_f32(&self, m: usize, a: &[f32], c: &mut [f32]) -> Result; 49 } 50 51 impl ResidentHandle for Mutex { 52 fn matmul_f32(&self, m: usize, a: &[f32], c: &mut [f32]) -> Result { 53 let guard = self 54 .lock() 55 .map_err(|_| "resident tensor lock poisoned".to_string())?; 56 guard 57 .matmul_f32(m, a, c) 58 .map(|info| info.raw.elapsed_ns) 59 .map_err(|e| e.to_string()) 60 } 61 } 62 63 /// A matmul weight that lives on the device: `k` is the input width, `n` the output width. 64 /// Cloning shares the device copy; it is freed when the last clone drops. 65 #[derive(Clone, Debug)] 66 pub struct ResidentWeight { 67 k: usize, 68 n: usize, 69 handle: Arc, 70 } 71 72 impl ResidentWeight { 73 pub fn new(k: usize, n: usize, handle: Arc) -> Self { 74 Self { k, n, handle } 75 } 76 77 pub fn k(&self) -> usize { 78 self.k 79 } 80 81 pub fn n(&self) -> usize { 82 self.n 83 } 84 85 pub fn matmul_f32(&self, m: usize, a: &[f32], c: &mut [f32]) -> Result { 86 self.handle.matmul_f32(m, a, c) 87 } 88 } 89 90 /// A matmul weight, `[out_dim, in_dim]` row-major when on the host. 91 #[derive(Clone, Debug)] 92 pub enum MatrixWeight { 93 Host(Vec), 94 Resident(ResidentWeight), 95 } 96 97 /// A borrowed [`MatrixWeight`], as the backend sees it. 98 #[derive(Clone, Copy, Debug)] 99 pub enum MatrixRef<'a> { 100 Host(&'a [f32]), 101 Resident(&'a ResidentWeight), 102 } 103 104 impl<'a> MatrixRef<'a> { 105 /// The host values, or the named refusal when the weight is resident. 106 pub fn host_or_refuse(self, op: &str) -> &'a [f32] { 107 match self { 108 Self::Host(v) => v, 109 Self::Resident(r) => refuse_resident(&format!( 110 "{op} needs host f32 values of a {}x{} weight", 111 r.k, r.n 112 )), 113 } 114 } 115 } 116 117 impl MatrixWeight { 118 pub fn as_ref(&self) -> MatrixRef<'_> { 119 match self { 120 Self::Host(v) => MatrixRef::Host(v), 121 Self::Resident(r) => MatrixRef::Resident(r), 122 } 123 } 124 125 pub fn is_resident(&self) -> bool { 126 matches!(self, Self::Resident(_)) 127 } 128 } 129 130 impl From> for MatrixWeight { 131 fn from(v: Vec) -> Self { 132 Self::Host(v) 133 } 134 } 135 136 /// Host-slice view for the CPU reference code and tests. A resident weight is refused by name. 137 impl std::ops::Deref for MatrixWeight { 138 type Target = [f32]; 139 fn deref(&self) -> &[f32] { 140 self.as_ref().host_or_refuse("host slice access") 141 } 142 } 143 144 /// What omega's `omega_gpu_tensor_upload_f32` would store for the bf16 pattern `bits` after the 145 /// loader widened it to f32: its f32-to-bf16 step is `(__bf16)f` (src/omega_blackwell_matmul.c:98 146 /// at omega.lock), which rounds to nearest even and sets the quiet bit of a NaN. Widening a bf16 147 /// is exact, so every pattern comes back unchanged except the 126 signaling NaNs (exponent all 148 /// ones, quiet bit clear, mantissa non-zero), which come back with the quiet bit set. Checked 149 /// against the compiler's own cast for all 65536 patterns on this aarch64 host (see the test). 150 #[inline] 151 pub fn bf16_bits_as_uploaded_today(bits: u16) -> u16 { 152 let is_nan = bits & 0x7f80 == 0x7f80 && bits & 0x007f != 0; 153 if is_nan { 154 bits | 0x0040 155 } else { 156 bits 157 } 158 } 159 160 /// Transposes bf16 weight bytes `[n][k]` (little endian, as safetensors stores `[out][in]`) into 161 /// the `[k][n]` bf16 layout the engine wants, applying [`bf16_bits_as_uploaded_today`]. `dst` is 162 /// resized to `k * n` and reused across calls. 163 pub fn transpose_bf16_for_upload(raw: &[u8], n: usize, k: usize, dst: &mut Vec) { 164 debug_assert_eq!(raw.len(), n * k * 2); 165 dst.clear(); 166 dst.resize(n * k, 0); 167 const TILE: usize = 64; 168 for o0 in (0..n).step_by(TILE) { 169 let o1 = (o0 + TILE).min(n); 170 for i0 in (0..k).step_by(TILE) { 171 let i1 = (i0 + TILE).min(k); 172 for o in o0..o1 { 173 let row = &raw[o * k * 2..(o + 1) * k * 2]; 174 for i in i0..i1 { 175 let bits = u16::from_le_bytes([row[i * 2], row[i * 2 + 1]]); 176 dst[i * n + o] = bf16_bits_as_uploaded_today(bits); 177 } 178 } 179 } 180 } 181 } 182 183 /// Makes a `[k][n]` bf16 matrix resident. 184 pub trait ResidentUploader { 185 fn upload_bf16(&self, k: usize, n: usize, bits: &[u16]) -> Result; 186 } 187 188 /// The real uploader: omega's `omega_gpu_tensor_upload_bf16`. 189 pub struct OmegaUploader; 190 191 impl ResidentUploader for OmegaUploader { 192 fn upload_bf16(&self, k: usize, n: usize, bits: &[u16]) -> Result { 193 let tensor = 194 aien_omega_gpu::ResidentTensor::upload_bf16(k, n, bits).map_err(|e| e.to_string())?; 195 Ok(ResidentWeight::new(k, n, Arc::new(Mutex::new(tensor)))) 196 } 197 } 198 199 /// Whether the daemon loads weights resident: the native engine is linked, the build is 200 /// production-strict (no CPU fallback to need host values for), the GB10 Qwen3 path 201 /// is enabled (see `gb10_qwen3_enabled`), and the model is one the engine accepts. Anything else keeps the host f32 load. 202 pub fn resident_load_wanted( 203 native_linked: bool, 204 strict: bool, 205 qwen3_enabled: bool, 206 config: &ModelConfig, 207 ) -> bool { 208 native_linked 209 && strict 210 && config.qk_norm 211 && crate::omega_backend::omega_model_refusal_with(config, qwen3_enabled).is_none() 212 } 213 214 /// Streams a checkpoint straight to the device. For each of the seven matmul weights of each 215 /// layer (and the tied or separate output head) it reads that tensor's bf16 bytes, transposes 216 /// them into `[k][n]` bf16 and uploads. All uploads happen BEFORE the f32 embedding is decoded, 217 /// so the driver's pinned-memory requests land while the process holds almost nothing. The 218 /// returned weights hold resident matrices, the f32 embedding and the small f32 norm vectors. 219 /// 220 /// `progress` is called once per uploaded matrix with its tensor name. 221 pub fn load_resident_weights>( 222 path: P, 223 config: &ModelConfig, 224 uploader: &dyn ResidentUploader, 225 progress: &mut dyn FnMut(&str), 226 ) -> Result { 227 let catalog = crate::checkpoint::llama_catalog(config); 228 let ckpt = StreamedCheckpoint::open(path, &catalog)?; 229 let mut raw: Vec = Vec::new(); 230 let mut part: Vec = Vec::new(); 231 let mut bits: Vec = Vec::new(); 232 // One device matrix from one tensor, or from several `[n_i, k]` tensors stacked row-wise 233 // (the fused q/k/v and gate/up matrices, sc#384): bf16 rows are contiguous, so stacking is 234 // appending bytes; `n` is the total row count. 235 let mut upload = 236 |names: &[&str], n: usize, k: usize| -> Result { 237 raw.clear(); 238 for name in names { 239 ckpt.read_bf16_bytes(name, &mut part)?; 240 raw.extend_from_slice(&part); 241 } 242 let label = names.join("+"); 243 if raw.len() != n * k * 2 { 244 return Err(CheckpointError::ResidentUpload { 245 tensor: label, 246 message: format!( 247 "{} bf16 bytes read, {} expected for {n}x{k}", 248 raw.len(), 249 n * k * 2 250 ), 251 }); 252 } 253 transpose_bf16_for_upload(&raw, n, k, &mut bits); 254 let w = uploader.upload_bf16(k, n, &bits).map_err(|message| { 255 CheckpointError::ResidentUpload { 256 tensor: label.clone(), 257 message, 258 } 259 })?; 260 progress(&label); 261 Ok(MatrixWeight::Resident(w)) 262 }; 263 let hidden = config.hidden_dim(); 264 let inter = config.intermediate_dim(); 265 let q_dim = config.num_heads * config.head_dim; 266 let kv_dim = config.num_kv_heads * config.head_dim; 267 268 // Pass 1: every matmul weight to the device. Nothing large is held on the host. 269 let mut mats = Vec::with_capacity(config.num_layers); 270 for idx in 0..config.num_layers { 271 let p = format!("model.layers.{idx}"); 272 let q = format!("{p}.self_attn.q_proj.weight"); 273 let k = format!("{p}.self_attn.k_proj.weight"); 274 let v = format!("{p}.self_attn.v_proj.weight"); 275 let gate = format!("{p}.mlp.gate_proj.weight"); 276 let up = format!("{p}.mlp.up_proj.weight"); 277 mats.push([ 278 upload(&[&q], q_dim, hidden)?, 279 upload(&[&k], kv_dim, hidden)?, 280 upload(&[&v], kv_dim, hidden)?, 281 upload(&[&format!("{p}.self_attn.o_proj.weight")], hidden, q_dim)?, 282 upload(&[&gate], inter, hidden)?, 283 upload(&[&up], inter, hidden)?, 284 upload(&[&format!("{p}.mlp.down_proj.weight")], hidden, inter)?, 285 // The fused matrices the forward paths prefer (one launch each): q|k|v rows and 286 // gate|up rows. The single matrices above stay for every other reader. 287 upload(&[&q, &k, &v], q_dim + 2 * kv_dim, hidden)?, 288 upload(&[&gate, &up], 2 * inter, hidden)?, 289 ]); 290 } 291 let vocab = config.vocab_size(); 292 // Tied models project through the embedding: its own device copy, transposed. 293 let head_name = if config.tie_word_embeddings { 294 "model.embed_tokens.weight" 295 } else { 296 "lm_head.weight" 297 }; 298 let head = upload(&[head_name], vocab, hidden)?; 299 // Release the big transient buffers before the f32 embedding is allocated. 300 raw = Vec::new(); 301 drop(bits); 302 303 // Pass 2: the host-side f32 data the host really reads (embedding rows, norms). 304 let decode = |name: &str, raw: &mut Vec| -> Result, CheckpointError> { 305 ckpt.read_bf16_bytes(name, raw)?; 306 Ok(decode_bf16_to_fp32(raw)) 307 }; 308 let mut layers = Vec::with_capacity(config.num_layers); 309 for (idx, m) in mats.into_iter().enumerate() { 310 let p = format!("model.layers.{idx}"); 311 let [q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj, qkv_proj, gate_up_proj] = 312 m; 313 let (q_norm, k_norm) = if config.qk_norm { 314 ( 315 Some(decode(&format!("{p}.self_attn.q_norm.weight"), &mut raw)?), 316 Some(decode(&format!("{p}.self_attn.k_norm.weight"), &mut raw)?), 317 ) 318 } else { 319 (None, None) 320 }; 321 layers.push(TransformerLayerWeights { 322 input_layernorm: decode(&format!("{p}.input_layernorm.weight"), &mut raw)?, 323 q_proj, 324 k_proj, 325 v_proj, 326 o_proj, 327 post_attention_layernorm: decode( 328 &format!("{p}.post_attention_layernorm.weight"), 329 &mut raw, 330 )?, 331 gate_proj, 332 up_proj, 333 down_proj, 334 qkv_proj: Some(qkv_proj), 335 gate_up_proj: Some(gate_up_proj), 336 q_norm, 337 k_norm, 338 }); 339 } 340 let final_norm = decode("model.norm.weight", &mut raw)?; 341 let embed_tokens = decode("model.embed_tokens.weight", &mut raw)?; 342 Ok(TransformerWeights { 343 config: config.clone(), 344 embed_tokens, 345 layers, 346 final_norm, 347 lm_head: Some(head), 348 }) 349 }