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
aien-sovereign-core-mv / crates / aien-inference-abi / src / omega_backend.rs
| 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 | //! `OmegaGb10Backend` (FB-1 cuts 3b, 3c, 3d): all ten `TensorBackend` ops run on our own |
| 17 | //! native GPU engine (`libomega_gpu.a`, no CUDA) through the `aien-omega-gpu` crate. |
| 18 | //! |
| 19 | //! Native mask: `matmul_vec`, `matmul_batch`, `compute_logits`, `rmsnorm`, `rmsnorm_heads`, |
| 20 | //! `apply_rope`, `swiglu`, `gqa_attention`, `paged_attention`, `paged_attention_batch`. |
| 21 | //! Paged attention over a bf16 pool uses omega's paged kernel; over any other pool dtype |
| 22 | //! (the model builds Fp32 pools) the sequence's K/V are gathered on the host into |
| 23 | //! contiguous f32 exactly as the reference reads them, then run on the f32 gqa kernel. |
| 24 | //! omega attention needs head_dim 64 (TinyLlama, Llama-3.2-1B) or 128 (Qwen3-4B, since omega |
| 25 | //! b564bf4). Qwen3 at any other head_dim is always refused; at 128 it is refused when the |
| 26 | //! switch is off (see `omega_model_refusal`). |
| 27 | //! |
| 28 | //! A chip error in one of those ops is a fallback of a claimed-native op: it is counted, goes through |
| 29 | //! `OpAccounting::reference_path` (fatal in a production build, see `strict.rs`) |
| 30 | //! and, in a dev build only, the reference result is computed so the run goes on. |
| 31 | //! |
| 32 | //! Weights: the trait hands weights as `&[f32]` slices per call (row-major |
| 33 | //! `[out_dim, in_dim]`, computing `x * W^T`). The first call for a slice uploads |
| 34 | //! `W^T` (k = in_dim, n = out_dim, rounded to bf16 by omega) once and keeps it |
| 35 | //! resident; later calls move only activations. The cache key is |
| 36 | //! (pointer, length, in_dim, out_dim) plus a sampled content fingerprint. |
| 37 | //! |
| 38 | //! INVARIANT: weight slices are immutable and outlive the backend's use of them. |
| 39 | //! Checked for the model path: `TransformerWeights` (weights.rs:35) owns plain |
| 40 | //! `Vec<f32>` fields; the forward passes borrow it as `&TransformerWeights` |
| 41 | //! (transformer_backend.rs:287, :399) and nothing in the crate mutates a loaded |
| 42 | //! checkpoint after construction (UNVERIFIED for external callers: `weights` is a |
| 43 | //! `pub` field, so a caller that mutates it in place gets stale device weights; |
| 44 | //! the fingerprint catches a freed-and-reused address or a changed sample point, |
| 45 | //! not every in-place edit). Use one backend per weight set, or call |
| 46 | //! [`OmegaGb10Backend::clear_resident`] after changing weights. |
| 47 | use crate::backend::{ReferenceCpuBackend, TensorBackend}; |
| 48 | use crate::native_ops::{NativeOpMask, OpAccounting, OpReport, TensorOp}; |
| 49 | use aien_abi_core::{ModelConfig, RopeParams}; |
| 50 | use aien_omega_gpu::ResidentTensor; |
| 51 | use std::collections::HashMap; |
| 52 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 53 | use std::sync::{Arc, Mutex}; |
| 54 | use std::time::Instant; |
| 55 | |
| 56 | /// `AIEN_GPU_BACKEND=omega` demands this backend: a build without the Omega engine linked |
| 57 | /// refuses to start instead of falling back to the CPU reference. It is the only GPU backend. |
| 58 | pub const GPU_BACKEND_ENV: &str = "AIEN_GPU_BACKEND"; |
| 59 | |
| 60 | /// True when the environment asks for the Omega backend. |
| 61 | pub fn omega_backend_selected() -> bool { |
| 62 | std::env::var(GPU_BACKEND_ENV) |
| 63 | .map(|v| v.trim().eq_ignore_ascii_case("omega")) |
| 64 | .unwrap_or(false) |
| 65 | } |
| 66 | |
| 67 | const BACKEND_NAME: &str = "OmegaGb10Backend"; |
| 68 | |
| 69 | type Key = (usize, usize, usize, usize); |
| 70 | |
| 71 | /// Rope cos/sin table for one position: `head_dim / 2` values each. |
| 72 | type RopeTable = Arc<(Vec<f32>, Vec<f32>)>; |
| 73 | |
| 74 | /// Cache key: (head_dim, rope parameter bits, position). Drop everything past this many entries. |
| 75 | type RopeKey = (usize, [u64; 5], usize); |
| 76 | const ROPE_CACHE_MAX: usize = 16384; |
| 77 | |
| 78 | /// Single-token elementwise ops run on the host (sc#384 decode speed): a one-row rmsnorm, one |
| 79 | /// token's q/k head norms and its rope are 1 to 4 us of arithmetic on the host (measured on the |
| 80 | /// X925) against 11 to 34 us as a chip launch with its copies, and their data already lives in |
| 81 | /// host memory. At or under this many f32 values the op runs on the reference implementation |
| 82 | /// (the golden maths), tallied as `<op>_host` in the timing table and counted in `host_ops`, |
| 83 | /// not a fallback. Prefill rows (128 x 4096 and more) stay on the chip. swiglu stays on the chip |
| 84 | /// at every size (host f64 exp over 12288 values 26 us against 28 us on the chip: no gain). |
| 85 | pub const HOST_ELEMENTWISE_MAX: usize = 16384; |
| 86 | |
| 87 | struct Resident { |
| 88 | fingerprint: u64, |
| 89 | tensor: ResidentTensor, |
| 90 | } |
| 91 | |
| 92 | /// Native backend on the Omega GPU engine (matmuls and elementwise ops). |
| 93 | pub struct OmegaGb10Backend { |
| 94 | reference: ReferenceCpuBackend, |
| 95 | acct: OpAccounting, |
| 96 | /// One lock serializes every chip call and guards the resident cache |
| 97 | /// (omega's resident-call thread safety is not documented). |
| 98 | chip: Mutex<HashMap<Key, Resident>>, |
| 99 | rope_tables: Mutex<HashMap<RopeKey, RopeTable>>, |
| 100 | chip_errors: AtomicU64, |
| 101 | /// Elementwise ops routed to the host by size (`HOST_ELEMENTWISE_MAX`), not fallbacks. |
| 102 | host_ops: AtomicU64, |
| 103 | chip_calls: AtomicU64, |
| 104 | chip_ns: AtomicU64, |
| 105 | /// OM-2 staging counters summed over every chip attention call. |
| 106 | kv_bytes_staged: AtomicU64, |
| 107 | kv_bytes_naive: AtomicU64, |
| 108 | /// Chip attention calls that read the resident KV pool in place (cut E, omega#411). |
| 109 | kv_resident_calls: AtomicU64, |
| 110 | last_error: Mutex<String>, |
| 111 | /// Wall and chip time per operation kind (resident matmul keyed by shape), for the |
| 112 | /// decode-speed receipts (sc#384); read with `op_timing_lines`, cleared with `reset_op_times`. |
| 113 | op_times: Mutex<HashMap<String, OpTime>>, |
| 114 | } |
| 115 | |
| 116 | /// One row of the per-operation timing table. |
| 117 | #[derive(Default, Clone, Copy, Debug)] |
| 118 | pub struct OpTime { |
| 119 | pub calls: u64, |
| 120 | pub wall_ns: u64, |
| 121 | pub chip_ns: u64, |
| 122 | } |
| 123 | |
| 124 | impl Default for OmegaGb10Backend { |
| 125 | fn default() -> Self { |
| 126 | Self::new() |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | /// Cheap content check: FNV-1a over up to 64 evenly spaced elements plus the last one. |
| 131 | fn fingerprint(w: &[f32]) -> u64 { |
| 132 | let mut h: u64 = 0xcbf29ce484222325; |
| 133 | let step = (w.len() / 64).max(1); |
| 134 | let mut i = 0; |
| 135 | while i < w.len() { |
| 136 | h = (h ^ w[i].to_bits() as u64).wrapping_mul(0x100000001b3); |
| 137 | i += step; |
| 138 | } |
| 139 | if let Some(last) = w.last() { |
| 140 | h = (h ^ last.to_bits() as u64).wrapping_mul(0x100000001b3); |
| 141 | } |
| 142 | h |
| 143 | } |
| 144 | |
| 145 | impl OmegaGb10Backend { |
| 146 | pub fn new() -> Self { |
| 147 | Self { |
| 148 | reference: ReferenceCpuBackend::new(), |
| 149 | acct: OpAccounting::new(NativeOpMask::from_ops(&[ |
| 150 | TensorOp::MatmulVec, |
| 151 | TensorOp::MatmulBatch, |
| 152 | TensorOp::ComputeLogits, |
| 153 | TensorOp::Rmsnorm, |
| 154 | TensorOp::RmsnormHeads, |
| 155 | TensorOp::ApplyRope, |
| 156 | TensorOp::Swiglu, |
| 157 | TensorOp::GqaAttention, |
| 158 | TensorOp::PagedAttention, |
| 159 | TensorOp::PagedAttentionBatch, |
| 160 | ])), |
| 161 | chip: Mutex::new(HashMap::new()), |
| 162 | rope_tables: Mutex::new(HashMap::new()), |
| 163 | chip_errors: AtomicU64::new(0), |
| 164 | host_ops: AtomicU64::new(0), |
| 165 | chip_calls: AtomicU64::new(0), |
| 166 | chip_ns: AtomicU64::new(0), |
| 167 | kv_bytes_staged: AtomicU64::new(0), |
| 168 | kv_bytes_naive: AtomicU64::new(0), |
| 169 | kv_resident_calls: AtomicU64::new(0), |
| 170 | last_error: Mutex::new(String::new()), |
| 171 | op_times: Mutex::new(HashMap::new()), |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | fn tally(&self, key: String, wall_ns: u64, chip_ns: u64) { |
| 176 | if let Ok(mut m) = self.op_times.lock() { |
| 177 | let e = m.entry(key).or_default(); |
| 178 | e.calls += 1; |
| 179 | e.wall_ns += wall_ns; |
| 180 | e.chip_ns += chip_ns; |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | /// One host-routed elementwise op: run it, tally its wall time under `key` (chip time 0). |
| 185 | fn host_op(&self, key: &str, op: impl FnOnce()) { |
| 186 | let t0 = Instant::now(); |
| 187 | op(); |
| 188 | self.host_ops.fetch_add(1, Ordering::Relaxed); |
| 189 | self.tally(key.to_string(), t0.elapsed().as_nanos() as u64, 0); |
| 190 | } |
| 191 | |
| 192 | /// The per-operation timing table as text, heaviest wall time first. |
| 193 | pub fn op_timing_lines(&self) -> String { |
| 194 | let mut rows: Vec<(String, OpTime)> = self |
| 195 | .op_times |
| 196 | .lock() |
| 197 | .map(|m| m.iter().map(|(k, v)| (k.clone(), *v)).collect()) |
| 198 | .unwrap_or_default(); |
| 199 | rows.sort_by_key(|(_, t)| std::cmp::Reverse(t.wall_ns)); |
| 200 | if rows.is_empty() { |
| 201 | return String::new(); |
| 202 | } |
| 203 | rows.iter() |
| 204 | .map(|(k, t)| { |
| 205 | format!( |
| 206 | "{k} calls={} wall_ms={:.1} chip_ms={:.1}", |
| 207 | t.calls, |
| 208 | t.wall_ns as f64 / 1e6, |
| 209 | t.chip_ns as f64 / 1e6 |
| 210 | ) |
| 211 | }) |
| 212 | .collect::<Vec<_>>() |
| 213 | .join("; ") |
| 214 | + &format!( |
| 215 | "; kv_staged_bytes_total={} kv_resident_calls_total={}", |
| 216 | self.kv_bytes_staged(), |
| 217 | self.kv_resident_calls() |
| 218 | ) |
| 219 | } |
| 220 | |
| 221 | pub fn reset_op_times(&self) { |
| 222 | if let Ok(mut m) = self.op_times.lock() { |
| 223 | m.clear(); |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | /// True when the real native library is linked (not the CI stub). |
| 228 | pub fn is_available(&self) -> bool { |
| 229 | aien_omega_gpu::is_native() |
| 230 | } |
| 231 | |
| 232 | pub fn chip_calls(&self) -> u64 { |
| 233 | self.chip_calls.load(Ordering::Relaxed) |
| 234 | } |
| 235 | |
| 236 | pub fn chip_errors(&self) -> u64 { |
| 237 | self.chip_errors.load(Ordering::Relaxed) |
| 238 | } |
| 239 | |
| 240 | /// Sum of chip launch-to-completion time reported by omega, in nanoseconds. |
| 241 | pub fn chip_ns(&self) -> u64 { |
| 242 | self.chip_ns.load(Ordering::Relaxed) |
| 243 | } |
| 244 | |
| 245 | /// KV bytes omega copied into its staging buffer over every chip attention call (OM-2: |
| 246 | /// one copy per physical block per launch) and what per-reference staging would have |
| 247 | /// copied. Equal when no block is shared inside a launch. |
| 248 | pub fn kv_bytes_staged(&self) -> u64 { |
| 249 | self.kv_bytes_staged.load(Ordering::Relaxed) |
| 250 | } |
| 251 | |
| 252 | pub fn kv_bytes_naive(&self) -> u64 { |
| 253 | self.kv_bytes_naive.load(Ordering::Relaxed) |
| 254 | } |
| 255 | |
| 256 | /// Chip attention calls whose KV came from the resident pool (no staging copy). |
| 257 | pub fn kv_resident_calls(&self) -> u64 { |
| 258 | self.kv_resident_calls.load(Ordering::Relaxed) |
| 259 | } |
| 260 | |
| 261 | /// Elementwise ops routed to the host by size (`HOST_ELEMENTWISE_MAX`), never fallbacks. |
| 262 | pub fn host_ops(&self) -> u64 { |
| 263 | self.host_ops.load(Ordering::Relaxed) |
| 264 | } |
| 265 | |
| 266 | pub fn last_error(&self) -> String { |
| 267 | self.last_error |
| 268 | .lock() |
| 269 | .map(|s| s.clone()) |
| 270 | .unwrap_or_default() |
| 271 | } |
| 272 | |
| 273 | /// Drop every resident weight (call after changing weights in place). |
| 274 | pub fn clear_resident(&self) { |
| 275 | if let Ok(mut c) = self.chip.lock() { |
| 276 | c.clear(); |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | /// Number of resident weight matrices (for tests and receipts). |
| 281 | pub fn resident_count(&self) -> usize { |
| 282 | self.chip.lock().map(|c| c.len()).unwrap_or(0) |
| 283 | } |
| 284 | |
| 285 | /// `out[m x out_dim] = x[m x in_dim] * W^T`, W row-major `[out_dim, in_dim]`. |
| 286 | /// Returns false on any chip error (already recorded). |
| 287 | fn chip_matmul( |
| 288 | &self, |
| 289 | out: &mut [f32], |
| 290 | x: &[f32], |
| 291 | weight: &[f32], |
| 292 | m: usize, |
| 293 | in_dim: usize, |
| 294 | out_dim: usize, |
| 295 | ) -> bool { |
| 296 | if x.len() != m * in_dim || out.len() != m * out_dim || weight.len() != out_dim * in_dim { |
| 297 | return self.fail(format!( |
| 298 | "shape mismatch: x={} out={} w={} for m={m} in={in_dim} out_dim={out_dim}", |
| 299 | x.len(), |
| 300 | out.len(), |
| 301 | weight.len() |
| 302 | )); |
| 303 | } |
| 304 | let key: Key = (weight.as_ptr() as usize, weight.len(), in_dim, out_dim); |
| 305 | let fp = fingerprint(weight); |
| 306 | let mut cache = match self.chip.lock() { |
| 307 | Ok(g) => g, |
| 308 | Err(_) => return self.fail("chip lock poisoned".into()), |
| 309 | }; |
| 310 | if cache.get(&key).is_some_and(|r| r.fingerprint != fp) { |
| 311 | cache.remove(&key); |
| 312 | } |
| 313 | if let std::collections::hash_map::Entry::Vacant(slot) = cache.entry(key) { |
| 314 | // W is [out, in]; the engine wants B = W^T as [k = in, n = out]. |
| 315 | let mut wt = vec![0.0f32; weight.len()]; |
| 316 | for o in 0..out_dim { |
| 317 | let row = &weight[o * in_dim..(o + 1) * in_dim]; |
| 318 | for (i, v) in row.iter().enumerate() { |
| 319 | wt[i * out_dim + o] = *v; |
| 320 | } |
| 321 | } |
| 322 | match ResidentTensor::upload_f32(in_dim, out_dim, &wt) { |
| 323 | Ok(tensor) => { |
| 324 | slot.insert(Resident { |
| 325 | fingerprint: fp, |
| 326 | tensor, |
| 327 | }); |
| 328 | } |
| 329 | Err(e) => { |
| 330 | let msg = format!("upload {in_dim}x{out_dim}: {e}"); |
| 331 | return self.fail(msg); |
| 332 | } |
| 333 | } |
| 334 | } |
| 335 | let res = &cache[&key]; |
| 336 | match res.tensor.matmul_f32(m, x, out) { |
| 337 | Ok(info) => { |
| 338 | self.chip_calls.fetch_add(1, Ordering::Relaxed); |
| 339 | self.chip_ns |
| 340 | .fetch_add(info.raw.elapsed_ns, Ordering::Relaxed); |
| 341 | true |
| 342 | } |
| 343 | Err(e) => { |
| 344 | drop(cache); |
| 345 | self.fail(format!("matmul m={m} k={in_dim} n={out_dim}: {e}")) |
| 346 | } |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | /// `out[m x out_dim] = x[m x in_dim] * W^T` for a device-resident weight. The weight has no |
| 351 | /// host values, so a chip failure cannot fall back to the CPU: it is recorded and then |
| 352 | /// refused by name (panic), in every build. |
| 353 | fn chip_resident_matmul( |
| 354 | &self, |
| 355 | out: &mut [f32], |
| 356 | x: &[f32], |
| 357 | w: &crate::resident::ResidentWeight, |
| 358 | m: usize, |
| 359 | in_dim: usize, |
| 360 | out_dim: usize, |
| 361 | ) { |
| 362 | let refuse = |this: &Self, why: String| -> ! { |
| 363 | this.fail(why.clone()); |
| 364 | crate::resident::refuse_resident(&why) |
| 365 | }; |
| 366 | if w.k() != in_dim || w.n() != out_dim || x.len() != m * in_dim || out.len() != m * out_dim |
| 367 | { |
| 368 | refuse( |
| 369 | self, |
| 370 | format!( |
| 371 | "resident weight is {}x{} but the call is m={m} in={in_dim} out={out_dim} (x={} out={})", |
| 372 | w.k(), |
| 373 | w.n(), |
| 374 | x.len(), |
| 375 | out.len() |
| 376 | ), |
| 377 | ); |
| 378 | } |
| 379 | // One lock serializes every chip call (same lock as `chip_matmul`). |
| 380 | let guard = match self.chip.lock() { |
| 381 | Ok(g) => g, |
| 382 | Err(_) => refuse(self, "chip lock poisoned".into()), |
| 383 | }; |
| 384 | let t0 = Instant::now(); |
| 385 | let res = w.matmul_f32(m, x, out); |
| 386 | drop(guard); |
| 387 | match res { |
| 388 | Ok(ns) => { |
| 389 | self.chip_calls.fetch_add(1, Ordering::Relaxed); |
| 390 | self.chip_ns.fetch_add(ns, Ordering::Relaxed); |
| 391 | self.tally( |
| 392 | format!("matmul m={m} k={in_dim} n={out_dim}"), |
| 393 | t0.elapsed().as_nanos() as u64, |
| 394 | ns, |
| 395 | ); |
| 396 | } |
| 397 | Err(e) => refuse( |
| 398 | self, |
| 399 | format!("resident matmul m={m} k={in_dim} n={out_dim}: {e}"), |
| 400 | ), |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | /// Rope cos/sin table for `pos`, built exactly as the reference does |
| 405 | /// (`tensor::apply_rope`, tensor.rs:101): f64 frequency and angle, then cast to f32. |
| 406 | /// Cached per (head_dim, rope parameters, pos). |
| 407 | fn rope_table(&self, head_dim: usize, rope: &RopeParams, pos: usize) -> RopeTable { |
| 408 | let key: RopeKey = (head_dim, rope.cache_key(), pos); |
| 409 | let mut cache = self |
| 410 | .rope_tables |
| 411 | .lock() |
| 412 | .unwrap_or_else(|poisoned| poisoned.into_inner()); |
| 413 | if let Some(t) = cache.get(&key) { |
| 414 | return Arc::clone(t); |
| 415 | } |
| 416 | let (cos, sin) = crate::tensor::rope_cos_sin(rope, head_dim, pos); |
| 417 | if cache.len() >= ROPE_CACHE_MAX { |
| 418 | cache.clear(); |
| 419 | } |
| 420 | let t: RopeTable = Arc::new((cos, sin)); |
| 421 | cache.insert(key, Arc::clone(&t)); |
| 422 | t |
| 423 | } |
| 424 | |
| 425 | /// Run one elementwise chip call under the chip lock. False on any error (recorded). |
| 426 | fn chip_elementwise( |
| 427 | &self, |
| 428 | what: &str, |
| 429 | call: impl FnOnce() -> Result<aien_omega_gpu::OmegaGpuEwInfo, aien_omega_gpu::OmegaGpuError>, |
| 430 | ) -> bool { |
| 431 | let guard = match self.chip.lock() { |
| 432 | Ok(g) => g, |
| 433 | Err(_) => return self.fail("chip lock poisoned".into()), |
| 434 | }; |
| 435 | let t0 = Instant::now(); |
| 436 | let res = call(); |
| 437 | drop(guard); |
| 438 | match res { |
| 439 | Ok(info) => { |
| 440 | self.chip_calls.fetch_add(1, Ordering::Relaxed); |
| 441 | self.chip_ns.fetch_add(info.elapsed_ns, Ordering::Relaxed); |
| 442 | self.tally( |
| 443 | what.split_whitespace().next().unwrap_or(what).to_string(), |
| 444 | t0.elapsed().as_nanos() as u64, |
| 445 | info.elapsed_ns, |
| 446 | ); |
| 447 | true |
| 448 | } |
| 449 | Err(e) => self.fail(format!("{what}: {e}")), |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | fn chip_rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) -> bool { |
| 454 | let dim = x.len(); |
| 455 | self.chip_elementwise(&format!("rmsnorm dim={dim}"), || { |
| 456 | aien_omega_gpu::rmsnorm_f32(1, dim, x, weight, eps, out) |
| 457 | }) |
| 458 | } |
| 459 | |
| 460 | /// `rows` rows of `weight.len()` in one launch (omega's rmsnorm is row-wise already). |
| 461 | fn chip_rmsnorm_rows( |
| 462 | &self, |
| 463 | out: &mut [f32], |
| 464 | x: &[f32], |
| 465 | weight: &[f32], |
| 466 | rows: usize, |
| 467 | eps: f32, |
| 468 | ) -> bool { |
| 469 | let dim = weight.len(); |
| 470 | if dim == 0 || x.len() != rows * dim || out.len() != rows * dim { |
| 471 | return self.fail(format!( |
| 472 | "rmsnorm_rows shape mismatch: x={} out={} rows={rows} dim={dim}", |
| 473 | x.len(), |
| 474 | out.len() |
| 475 | )); |
| 476 | } |
| 477 | self.chip_elementwise(&format!("rmsnorm rows={rows} dim={dim}"), || { |
| 478 | aien_omega_gpu::rmsnorm_f32(rows, dim, x, weight, eps, out) |
| 479 | }) |
| 480 | } |
| 481 | |
| 482 | /// Every head is one row of omega's row-wise rmsnorm (same weight for each row), one launch. |
| 483 | fn chip_rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) -> bool { |
| 484 | if head_dim == 0 || !x.len().is_multiple_of(head_dim) || weight.len() != head_dim { |
| 485 | return self.fail(format!( |
| 486 | "rmsnorm_heads shape mismatch: x={} weight={} head_dim={head_dim}", |
| 487 | x.len(), |
| 488 | weight.len() |
| 489 | )); |
| 490 | } |
| 491 | let rows = x.len() / head_dim; |
| 492 | let input = x.to_vec(); |
| 493 | self.chip_elementwise(&format!("rmsnorm_heads rows={rows} dim={head_dim}"), || { |
| 494 | aien_omega_gpu::rmsnorm_f32(rows, head_dim, &input, weight, eps, x) |
| 495 | }) |
| 496 | } |
| 497 | |
| 498 | /// q then k go to the chip as one `heads` run (the table is the same for every head). |
| 499 | #[allow(clippy::too_many_arguments)] |
| 500 | fn chip_rope( |
| 501 | &self, |
| 502 | q: &mut [f32], |
| 503 | k: &mut [f32], |
| 504 | pos: usize, |
| 505 | head_dim: usize, |
| 506 | num_q_heads: usize, |
| 507 | num_kv_heads: usize, |
| 508 | rope: &RopeParams, |
| 509 | ) -> bool { |
| 510 | if head_dim == 0 |
| 511 | || !head_dim.is_multiple_of(2) |
| 512 | || q.len() != num_q_heads * head_dim |
| 513 | || k.len() != num_kv_heads * head_dim |
| 514 | { |
| 515 | return self.fail(format!( |
| 516 | "rope shape mismatch: q={} k={} head_dim={head_dim} q_heads={num_q_heads} kv_heads={num_kv_heads}", |
| 517 | q.len(), |
| 518 | k.len() |
| 519 | )); |
| 520 | } |
| 521 | let table = self.rope_table(head_dim, rope, pos); |
| 522 | let mut both = Vec::with_capacity(q.len() + k.len()); |
| 523 | both.extend_from_slice(q); |
| 524 | both.extend_from_slice(k); |
| 525 | let mut rotated = vec![0.0f32; both.len()]; |
| 526 | let heads = num_q_heads + num_kv_heads; |
| 527 | let ok = self.chip_elementwise(&format!("rope heads={heads} head_dim={head_dim}"), || { |
| 528 | aien_omega_gpu::rope_f32(heads, head_dim, &both, &table.0, &table.1, &mut rotated) |
| 529 | }); |
| 530 | if ok { |
| 531 | let (rq, rk) = rotated.split_at(q.len()); |
| 532 | q.copy_from_slice(rq); |
| 533 | k.copy_from_slice(rk); |
| 534 | } |
| 535 | ok |
| 536 | } |
| 537 | |
| 538 | fn chip_swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) -> bool { |
| 539 | // The reference uses min(len) of the three; the chip path demands equal lengths. |
| 540 | if gate.len() != up.len() || gate.len() != out.len() { |
| 541 | return self.fail(format!( |
| 542 | "swiglu shape mismatch: gate={} up={} out={}", |
| 543 | gate.len(), |
| 544 | up.len(), |
| 545 | out.len() |
| 546 | )); |
| 547 | } |
| 548 | self.chip_elementwise(&format!("swiglu n={}", gate.len()), || { |
| 549 | aien_omega_gpu::swiglu_f32(gate, up, out) |
| 550 | }) |
| 551 | } |
| 552 | |
| 553 | fn chip_attention( |
| 554 | &self, |
| 555 | what: &str, |
| 556 | call: impl FnOnce() -> Result<aien_omega_gpu::OmegaGpuAttnInfo, aien_omega_gpu::OmegaGpuError>, |
| 557 | ) -> bool { |
| 558 | let guard = match self.chip.lock() { |
| 559 | Ok(g) => g, |
| 560 | Err(_) => return self.fail("chip lock poisoned".into()), |
| 561 | }; |
| 562 | let t0 = Instant::now(); |
| 563 | let res = call(); |
| 564 | drop(guard); |
| 565 | match res { |
| 566 | Ok(info) => { |
| 567 | self.chip_calls.fetch_add(1, Ordering::Relaxed); |
| 568 | self.chip_ns.fetch_add(info.elapsed_ns, Ordering::Relaxed); |
| 569 | self.tally( |
| 570 | what.split_whitespace().next().unwrap_or(what).to_string(), |
| 571 | t0.elapsed().as_nanos() as u64, |
| 572 | info.elapsed_ns, |
| 573 | ); |
| 574 | self.kv_bytes_staged |
| 575 | .fetch_add(info.kv_bytes_staged, Ordering::Relaxed); |
| 576 | self.kv_bytes_naive |
| 577 | .fetch_add(info.kv_bytes_naive, Ordering::Relaxed); |
| 578 | if info.kv_source == aien_omega_gpu::KV_SOURCE_RESIDENT { |
| 579 | self.kv_resident_calls.fetch_add(1, Ordering::Relaxed); |
| 580 | } |
| 581 | true |
| 582 | } |
| 583 | Err(e) => self.fail(format!("{what}: {e}")), |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | /// One sequence of paged attention on the chip. A bf16 pool goes straight to the |
| 588 | /// paged kernel; any other dtype (the model builds Fp32 pools) is gathered on the host |
| 589 | /// into contiguous `[t][kv_head][head_dim]` f32 K and V exactly as the reference reads |
| 590 | /// them (tokens past the block table are dropped), then runs the f32 gqa kernel. |
| 591 | #[allow(clippy::too_many_arguments)] |
| 592 | fn chip_paged_one( |
| 593 | &self, |
| 594 | out: &mut [f32], |
| 595 | q: &[f32], |
| 596 | pool: &aien_kv_cache::UnifiedKvTensorPool, |
| 597 | block_ids: &[usize], |
| 598 | context_len: usize, |
| 599 | layer_idx: usize, |
| 600 | num_q_heads: usize, |
| 601 | num_kv_heads: usize, |
| 602 | head_dim: usize, |
| 603 | ) -> bool { |
| 604 | // Geometry and pool layout are checked before any native code sees the pool. A refusal |
| 605 | // is counted like a chip error and the reference then refuses the same call loudly. |
| 606 | let geom = match aien_abi_core::AttentionGeometry::new(num_q_heads, num_kv_heads, head_dim) |
| 607 | { |
| 608 | Ok(g) => g, |
| 609 | Err(e) => return self.fail(format!("paged_attention geometry refused: {e}")), |
| 610 | }; |
| 611 | let cfg = pool.config(); |
| 612 | if let Err(e) = geom.check_kv_pool(cfg.num_kv_heads, cfg.head_dim) { |
| 613 | return self.fail(format!("paged_attention refused: {e}")); |
| 614 | } |
| 615 | if q.len() != geom.q_dim() || out.len() != geom.q_dim() { |
| 616 | return self.fail(format!( |
| 617 | "paged_attention refused: q={} out={} values, geometry needs {}", |
| 618 | q.len(), |
| 619 | out.len(), |
| 620 | geom.q_dim() |
| 621 | )); |
| 622 | } |
| 623 | if context_len == 0 || block_ids.is_empty() { |
| 624 | out.fill(0.0); |
| 625 | return true; |
| 626 | } |
| 627 | if pool.config().dtype == aien_kv_cache::KvDType::Bf16 { |
| 628 | let ids: Option<Vec<u32>> = block_ids.iter().map(|&b| u32::try_from(b).ok()).collect(); |
| 629 | let Some(ids) = ids else { |
| 630 | return self.fail("paged_attention: block id past u32".into()); |
| 631 | }; |
| 632 | let d = pool.layout_desc(); |
| 633 | let layout = aien_omega_gpu::OmegaGpuKvLayout { |
| 634 | block_stride_bytes: d.block_stride_bytes, |
| 635 | layer_stride_bytes: d.layer_stride_bytes, |
| 636 | kv_plane_stride_bytes: d.kv_plane_stride_bytes, |
| 637 | token_stride_bytes: d.token_stride_bytes, |
| 638 | head_stride_bytes: d.head_stride_bytes, |
| 639 | pool_bytes: d.pool_bytes, |
| 640 | num_blocks: d.num_blocks, |
| 641 | num_layers: d.num_layers, |
| 642 | block_size: d.block_size, |
| 643 | }; |
| 644 | // SAFETY: the pool owns total_bytes() readable bytes at base_ptr() for its lifetime, |
| 645 | // and we hold &pool for the whole call. |
| 646 | let bytes = unsafe { std::slice::from_raw_parts(pool.base_ptr(), pool.total_bytes()) }; |
| 647 | return self.chip_attention(&format!("paged_attention_bf16 ctx={context_len}"), || { |
| 648 | aien_omega_gpu::paged_attention_bf16( |
| 649 | q, |
| 650 | bytes, |
| 651 | &layout, |
| 652 | &ids, |
| 653 | context_len, |
| 654 | layer_idx, |
| 655 | num_q_heads, |
| 656 | num_kv_heads, |
| 657 | head_dim, |
| 658 | out, |
| 659 | ) |
| 660 | }); |
| 661 | } |
| 662 | let block_size = pool.config().block_size; |
| 663 | let n = context_len.min(block_ids.len().saturating_mul(block_size)); |
| 664 | let row = num_kv_heads * head_dim; |
| 665 | let mut k = vec![0.0f32; n * row]; |
| 666 | let mut v = vec![0.0f32; n * row]; |
| 667 | for t in 0..n { |
| 668 | let blk = block_ids[t / block_size]; |
| 669 | let slot = t % block_size; |
| 670 | for kh in 0..num_kv_heads { |
| 671 | let at = t * row + kh * head_dim; |
| 672 | k[at..at + head_dim].copy_from_slice(&crate::backend::read_kv_head( |
| 673 | pool, blk, layer_idx, false, slot, kh, head_dim, |
| 674 | )); |
| 675 | v[at..at + head_dim].copy_from_slice(&crate::backend::read_kv_head( |
| 676 | pool, blk, layer_idx, true, slot, kh, head_dim, |
| 677 | )); |
| 678 | } |
| 679 | } |
| 680 | self.chip_attention(&format!("paged_attention(gathered) ctx={n}"), || { |
| 681 | aien_omega_gpu::gqa_attention_f32( |
| 682 | q, |
| 683 | &k, |
| 684 | &v, |
| 685 | n, |
| 686 | num_q_heads, |
| 687 | num_kv_heads, |
| 688 | head_dim, |
| 689 | out, |
| 690 | ) |
| 691 | }) |
| 692 | } |
| 693 | |
| 694 | fn fail(&self, msg: String) -> bool { |
| 695 | self.chip_errors.fetch_add(1, Ordering::Relaxed); |
| 696 | let stage = aien_omega_gpu::last_error(); |
| 697 | let full = if stage.is_empty() { |
| 698 | msg |
| 699 | } else { |
| 700 | format!("{msg} (stage: {stage})") |
| 701 | }; |
| 702 | eprintln!("OMEGA_BACKEND chip error: {full}"); |
| 703 | if let Ok(mut l) = self.last_error.lock() { |
| 704 | *l = full; |
| 705 | } |
| 706 | false |
| 707 | } |
| 708 | |
| 709 | fn reference_for(&self, op: TensorOp) { |
| 710 | self.acct.reference_path(BACKEND_NAME, op); |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | /// Why the GB10 engine refuses `config`, if it does. Qwen3 (`qk_norm`) runs its per-head q/k |
| 715 | /// norm as `rmsnorm_heads`, one row per head on omega's row-wise rmsnorm, which needs |
| 716 | /// `head_dim % 128 == 0` (omega `omega_gpu_elementwise_api.h`); attention takes `head_dim` 64 or |
| 717 | /// 128 (omega `omega_gpu_attention_api.h`, since b564bf4). So a Qwen3 model runs on the engine |
| 718 | /// only with `head_dim` 128 (Qwen3-4B) and is refused up front otherwise, before any chip work. |
| 719 | /// Llama-architecture models are not touched by this check. |
| 720 | /// |
| 721 | /// Evidence limits: the #277 attempt 3 pass (issue comment 6059774846) covers a Linux-hosted |
| 722 | /// GB10 only (not native Aienux), one prompt, context 4096, no endurance run and no failing |
| 723 | /// baseline. So the default (switch unset) enables Qwen3 only on a production-strict run; under |
| 724 | /// `AIEN_DEV_FALLBACK=1` it is refused unless the switch is explicitly `1`. |
| 725 | /// |
| 726 | /// Qwen3 at `head_dim` 128 runs on the GB10 by default since the qualified path passed |
| 727 | /// (sovereign-core #277, declared attempt 3): the daemon streams the weights to the device |
| 728 | /// and reserves, prepares and seals the serving buffers once, and refuses by name with no |
| 729 | /// fallback if that fails. Before that, the driver's channel and weight allocations failed |
| 730 | /// with NV_ERR_NO_MEMORY when MemFree was low after the f32 weight load (omega#327). The |
| 731 | /// explicit refusal is [`GB10_QWEN3_OPT_IN_ENV`]` = 0`; see [`omega_model_refusal_with`]. |
| 732 | pub fn omega_model_refusal(config: &ModelConfig) -> Option<String> { |
| 733 | omega_model_refusal_with(config, gb10_qwen3_enabled()) |
| 734 | } |
| 735 | |
| 736 | /// Environment switch for the GB10 Qwen3 path (rule, one place): |
| 737 | /// - exactly `1`: enabled (the old declared-attempt opt-in, any build); |
| 738 | /// - unset: enabled only on the path the evidence covers, a production-strict run |
| 739 | /// ([`crate::strict::production_strict`], so no `AIEN_DEV_FALLBACK=1`); the native engine and |
| 740 | /// the streamed resident load that go with it are checked by `check_model` and |
| 741 | /// [`crate::resident::resident_load_wanted`]; |
| 742 | /// - `0`, or any other value including non-UTF8: refused by name (fail closed). |
| 743 | pub const GB10_QWEN3_OPT_IN_ENV: &str = "AIEN_GB10_QWEN3_DECLARED_ATTEMPT"; |
| 744 | |
| 745 | /// Whether the GB10 Qwen3 path is enabled, read from [`GB10_QWEN3_OPT_IN_ENV`] and the |
| 746 | /// process strictness. |
| 747 | pub fn gb10_qwen3_enabled() -> bool { |
| 748 | gb10_qwen3_enabled_from_os( |
| 749 | std::env::var_os(GB10_QWEN3_OPT_IN_ENV).as_deref(), |
| 750 | crate::strict::production_strict(), |
| 751 | ) |
| 752 | } |
| 753 | |
| 754 | /// [`gb10_qwen3_enabled`] on an explicit value and strictness (`strict` is true when |
| 755 | /// fallbacks are not allowed). |
| 756 | pub fn gb10_qwen3_enabled_from(value: Option<&str>, strict: bool) -> bool { |
| 757 | match value { |
| 758 | None => strict, |
| 759 | Some(v) => v == "1", |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | /// Same rule on a raw OS value: non-UTF8 refuses. |
| 764 | pub fn gb10_qwen3_enabled_from_os(value: Option<&std::ffi::OsStr>, strict: bool) -> bool { |
| 765 | match value { |
| 766 | None => gb10_qwen3_enabled_from(None, strict), |
| 767 | Some(v) => gb10_qwen3_enabled_from(Some(v.to_str().unwrap_or("<non-utf8>")), strict), |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | /// [`omega_model_refusal`] with the switch passed explicitly instead of read from the |
| 772 | /// environment (`qwen3_enabled` is true when the Qwen3 path is enabled). |
| 773 | pub fn omega_model_refusal_with(config: &ModelConfig, qwen3_enabled: bool) -> Option<String> { |
| 774 | if !config.qk_norm { |
| 775 | return None; |
| 776 | } |
| 777 | if config.head_dim != 128 { |
| 778 | return Some(format!( |
| 779 | "OmegaGb10Backend refuses model {:?}: Qwen3 (per-head q/k norm) with head_dim {} is \ |
| 780 | unsupported on the GB10 engine, which runs Qwen3 only at head_dim 128 (rmsnorm_heads \ |
| 781 | needs head_dim % 128 == 0); run it on the CPU reference backend", |
| 782 | config.model_id, config.head_dim |
| 783 | )); |
| 784 | } |
| 785 | (!qwen3_enabled).then(|| { |
| 786 | format!( |
| 787 | "OmegaGb10Backend refuses model {:?}: the GB10 Qwen3 path is switched off by \ |
| 788 | {GB10_QWEN3_OPT_IN_ENV} (only 1, or unset on a production-strict run, enables it); run it on the CPU \ |
| 789 | reference backend, or unset {GB10_QWEN3_OPT_IN_ENV} on a strict run (no \ |
| 790 | AIEN_DEV_FALLBACK) to use the qualified GB10 path (sovereign-core#277)", |
| 791 | config.model_id |
| 792 | ) |
| 793 | }) |
| 794 | } |
| 795 | |
| 796 | impl OmegaGb10Backend { |
| 797 | /// [`TensorBackend::check_model`] with the Qwen3 switch passed explicitly (the real call reads |
| 798 | /// [`gb10_qwen3_enabled`]); refuses Qwen3 on a stub build whatever the switch says. |
| 799 | pub fn check_model_with( |
| 800 | &self, |
| 801 | config: &ModelConfig, |
| 802 | qwen3_enabled: bool, |
| 803 | ) -> Result<(), String> { |
| 804 | omega_model_refusal_with(config, qwen3_enabled).map_or(Ok(()), Err)?; |
| 805 | if config.qk_norm && !self.is_available() { |
| 806 | return Err(format!( |
| 807 | "OmegaGb10Backend refuses model {:?}: Qwen3 needs the linked GB10 engine for its \ |
| 808 | streamed weights and serving reservation, and this is a stub build (no chip); \ |
| 809 | run it on the CPU reference backend", |
| 810 | config.model_id |
| 811 | )); |
| 812 | } |
| 813 | if config.qk_norm { |
| 814 | eprintln!( |
| 815 | "OMEGA_BACKEND NOTE: running Qwen3 {:?} on GB10 via the qualified path \ |
| 816 | (streamed resident weights, reserve+prepare+seal once, no on-demand fallback; \ |
| 817 | sovereign-core#277). Set {GB10_QWEN3_OPT_IN_ENV}=0 to refuse it", |
| 818 | config.model_id |
| 819 | ); |
| 820 | } |
| 821 | Ok(()) |
| 822 | } |
| 823 | } |
| 824 | |
| 825 | impl TensorBackend for OmegaGb10Backend { |
| 826 | fn check_model(&self, config: &ModelConfig) -> Result<(), String> { |
| 827 | self.check_model_with(config, gb10_qwen3_enabled()) |
| 828 | } |
| 829 | |
| 830 | fn name(&self) -> &'static str { |
| 831 | if self.is_available() { |
| 832 | "OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" |
| 833 | } else { |
| 834 | "OmegaGb10Backend (stub, no chip)" |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | fn fallback_count(&self) -> u64 { |
| 839 | self.acct.fallback_count() |
| 840 | } |
| 841 | |
| 842 | fn native_ops(&self) -> NativeOpMask { |
| 843 | self.acct.mask() |
| 844 | } |
| 845 | |
| 846 | fn op_report(&self) -> OpReport { |
| 847 | self.acct.report() |
| 848 | } |
| 849 | |
| 850 | /// sc#402: the chip calls so far, only when the real engine is linked (the stub has |
| 851 | /// no chip, so it makes no claim). |
| 852 | fn gpu_executions(&self) -> Option<u64> { |
| 853 | self.is_available().then(|| self.chip_calls()) |
| 854 | } |
| 855 | |
| 856 | fn op_timing_report(&self) -> Option<String> { |
| 857 | Some(self.op_timing_lines()) |
| 858 | } |
| 859 | |
| 860 | fn reset_op_timing(&self) { |
| 861 | self.reset_op_times() |
| 862 | } |
| 863 | |
| 864 | fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) { |
| 865 | if x.len() <= HOST_ELEMENTWISE_MAX { |
| 866 | self.host_op("rmsnorm_host", || { |
| 867 | self.reference.rmsnorm(out, x, weight, eps) |
| 868 | }); |
| 869 | return; |
| 870 | } |
| 871 | if !self.chip_rmsnorm(out, x, weight, eps) { |
| 872 | self.reference_for(TensorOp::Rmsnorm); |
| 873 | self.reference.rmsnorm(out, x, weight, eps); |
| 874 | } |
| 875 | } |
| 876 | |
| 877 | fn rmsnorm_rows(&self, out: &mut [f32], x: &[f32], weight: &[f32], rows: usize, eps: f32) { |
| 878 | if rows == 0 { |
| 879 | return; |
| 880 | } |
| 881 | if x.len() <= HOST_ELEMENTWISE_MAX { |
| 882 | self.host_op("rmsnorm_host", || { |
| 883 | self.reference.rmsnorm_rows(out, x, weight, rows, eps) |
| 884 | }); |
| 885 | return; |
| 886 | } |
| 887 | if !self.chip_rmsnorm_rows(out, x, weight, rows, eps) { |
| 888 | self.reference_for(TensorOp::Rmsnorm); |
| 889 | self.reference.rmsnorm_rows(out, x, weight, rows, eps); |
| 890 | } |
| 891 | } |
| 892 | |
| 893 | fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) { |
| 894 | if x.len() <= HOST_ELEMENTWISE_MAX { |
| 895 | self.host_op("rmsnorm_heads_host", || { |
| 896 | self.reference.rmsnorm_heads(x, weight, head_dim, eps) |
| 897 | }); |
| 898 | return; |
| 899 | } |
| 900 | if !self.chip_rmsnorm_heads(x, weight, head_dim, eps) { |
| 901 | self.reference_for(TensorOp::RmsnormHeads); |
| 902 | self.reference.rmsnorm_heads(x, weight, head_dim, eps); |
| 903 | } |
| 904 | } |
| 905 | |
| 906 | fn apply_rope( |
| 907 | &self, |
| 908 | q: &mut [f32], |
| 909 | k: &mut [f32], |
| 910 | pos: usize, |
| 911 | head_dim: usize, |
| 912 | num_q_heads: usize, |
| 913 | num_kv_heads: usize, |
| 914 | rope: &RopeParams, |
| 915 | ) { |
| 916 | if q.len() + k.len() <= HOST_ELEMENTWISE_MAX { |
| 917 | self.host_op("rope_host", || { |
| 918 | self.reference |
| 919 | .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, rope) |
| 920 | }); |
| 921 | return; |
| 922 | } |
| 923 | if !self.chip_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, rope) { |
| 924 | self.reference_for(TensorOp::ApplyRope); |
| 925 | self.reference |
| 926 | .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, rope); |
| 927 | } |
| 928 | } |
| 929 | |
| 930 | fn matmul_vec( |
| 931 | &self, |
| 932 | out: &mut [f32], |
| 933 | x: &[f32], |
| 934 | weight: &[f32], |
| 935 | out_dim: usize, |
| 936 | in_dim: usize, |
| 937 | ) { |
| 938 | if !self.chip_matmul(out, x, weight, 1, in_dim, out_dim) { |
| 939 | self.reference_for(TensorOp::MatmulVec); |
| 940 | self.reference.matmul_vec(out, x, weight, out_dim, in_dim); |
| 941 | } |
| 942 | } |
| 943 | |
| 944 | fn matmul_batch( |
| 945 | &self, |
| 946 | out: &mut [f32], |
| 947 | x: &[f32], |
| 948 | weight: &[f32], |
| 949 | batch_size: usize, |
| 950 | in_dim: usize, |
| 951 | out_dim: usize, |
| 952 | ) { |
| 953 | if !self.chip_matmul(out, x, weight, batch_size, in_dim, out_dim) { |
| 954 | self.reference_for(TensorOp::MatmulBatch); |
| 955 | self.reference |
| 956 | .matmul_batch(out, x, weight, batch_size, in_dim, out_dim); |
| 957 | } |
| 958 | } |
| 959 | |
| 960 | fn matmul_vec_w( |
| 961 | &self, |
| 962 | out: &mut [f32], |
| 963 | x: &[f32], |
| 964 | weight: crate::resident::MatrixRef<'_>, |
| 965 | out_dim: usize, |
| 966 | in_dim: usize, |
| 967 | ) { |
| 968 | match weight { |
| 969 | crate::resident::MatrixRef::Host(w) => self.matmul_vec(out, x, w, out_dim, in_dim), |
| 970 | crate::resident::MatrixRef::Resident(r) => { |
| 971 | self.chip_resident_matmul(out, x, r, 1, in_dim, out_dim) |
| 972 | } |
| 973 | } |
| 974 | } |
| 975 | |
| 976 | fn matmul_batch_w( |
| 977 | &self, |
| 978 | out: &mut [f32], |
| 979 | x: &[f32], |
| 980 | weight: crate::resident::MatrixRef<'_>, |
| 981 | batch_size: usize, |
| 982 | in_dim: usize, |
| 983 | out_dim: usize, |
| 984 | ) { |
| 985 | match weight { |
| 986 | crate::resident::MatrixRef::Host(w) => { |
| 987 | self.matmul_batch(out, x, w, batch_size, in_dim, out_dim) |
| 988 | } |
| 989 | crate::resident::MatrixRef::Resident(r) => { |
| 990 | self.chip_resident_matmul(out, x, r, batch_size, in_dim, out_dim) |
| 991 | } |
| 992 | } |
| 993 | } |
| 994 | |
| 995 | fn compute_logits_w( |
| 996 | &self, |
| 997 | logits: &mut [f32], |
| 998 | hidden: &[f32], |
| 999 | head: crate::resident::MatrixRef<'_>, |
| 1000 | vocab_size: usize, |
| 1001 | hidden_dim: usize, |
| 1002 | ) { |
| 1003 | match head { |
| 1004 | crate::resident::MatrixRef::Host(w) => { |
| 1005 | self.compute_logits(logits, hidden, w, vocab_size, hidden_dim) |
| 1006 | } |
| 1007 | crate::resident::MatrixRef::Resident(r) => { |
| 1008 | self.chip_resident_matmul(logits, hidden, r, 1, hidden_dim, vocab_size) |
| 1009 | } |
| 1010 | } |
| 1011 | } |
| 1012 | |
| 1013 | fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) { |
| 1014 | if !self.chip_swiglu(out, gate, up) { |
| 1015 | self.reference_for(TensorOp::Swiglu); |
| 1016 | self.reference.swiglu(out, gate, up); |
| 1017 | } |
| 1018 | } |
| 1019 | |
| 1020 | fn gqa_attention( |
| 1021 | &self, |
| 1022 | out: &mut [f32], |
| 1023 | q: &[f32], |
| 1024 | k_cache: &[f32], |
| 1025 | v_cache: &[f32], |
| 1026 | seq_len: usize, |
| 1027 | num_q_heads: usize, |
| 1028 | num_kv_heads: usize, |
| 1029 | head_dim: usize, |
| 1030 | ) { |
| 1031 | // The reference reads only the first seq_len rows; causal prefill passes the whole |
| 1032 | // prompt's cache with a shorter seq_len, so hand omega exactly those rows. |
| 1033 | let geom = aien_abi_core::AttentionGeometry::new(num_q_heads, num_kv_heads, head_dim); |
| 1034 | let need = geom.as_ref().map_or(0, |g| seq_len * g.kv_dim()); |
| 1035 | let shapes_ok = match &geom { |
| 1036 | Ok(g) => { |
| 1037 | q.len() == g.q_dim() |
| 1038 | && out.len() == g.q_dim() |
| 1039 | && k_cache.len() >= need |
| 1040 | && v_cache.len() >= need |
| 1041 | } |
| 1042 | Err(e) => self.fail(format!("gqa_attention geometry refused: {e}")), |
| 1043 | }; |
| 1044 | let k_rows = &k_cache[..need.min(k_cache.len())]; |
| 1045 | let v_rows = &v_cache[..need.min(v_cache.len())]; |
| 1046 | let native = shapes_ok |
| 1047 | && self.chip_attention(&format!("gqa_attention seq={seq_len}"), || { |
| 1048 | aien_omega_gpu::gqa_attention_f32( |
| 1049 | q, |
| 1050 | k_rows, |
| 1051 | v_rows, |
| 1052 | seq_len, |
| 1053 | num_q_heads, |
| 1054 | num_kv_heads, |
| 1055 | head_dim, |
| 1056 | out, |
| 1057 | ) |
| 1058 | }); |
| 1059 | if native { |
| 1060 | return; |
| 1061 | } |
| 1062 | self.reference_for(TensorOp::GqaAttention); |
| 1063 | self.reference.gqa_attention( |
| 1064 | out, |
| 1065 | q, |
| 1066 | k_cache, |
| 1067 | v_cache, |
| 1068 | seq_len, |
| 1069 | num_q_heads, |
| 1070 | num_kv_heads, |
| 1071 | head_dim, |
| 1072 | ); |
| 1073 | } |
| 1074 | |
| 1075 | fn gqa_attention_rows( |
| 1076 | &self, |
| 1077 | out: &mut [f32], |
| 1078 | q: &[f32], |
| 1079 | k_cache: &[f32], |
| 1080 | v_cache: &[f32], |
| 1081 | base_len: usize, |
| 1082 | num_rows: usize, |
| 1083 | num_q_heads: usize, |
| 1084 | num_kv_heads: usize, |
| 1085 | head_dim: usize, |
| 1086 | ) { |
| 1087 | if num_rows == 0 { |
| 1088 | return; |
| 1089 | } |
| 1090 | // omega wants exactly base_len + num_rows tokens of cache; the prompt read hands the |
| 1091 | // sequence's whole cache, which is that long right after the chunk's KV writes. |
| 1092 | let geom = aien_abi_core::AttentionGeometry::new(num_q_heads, num_kv_heads, head_dim); |
| 1093 | let total = base_len + num_rows; |
| 1094 | let need = geom.as_ref().map_or(0, |g| total * g.kv_dim()); |
| 1095 | let shapes_ok = match &geom { |
| 1096 | Ok(g) => { |
| 1097 | q.len() == num_rows * g.q_dim() |
| 1098 | && out.len() == num_rows * g.q_dim() |
| 1099 | && k_cache.len() >= need |
| 1100 | && v_cache.len() >= need |
| 1101 | } |
| 1102 | Err(e) => self.fail(format!("gqa_attention_rows geometry refused: {e}")), |
| 1103 | }; |
| 1104 | let k_rows = &k_cache[..need.min(k_cache.len())]; |
| 1105 | let v_rows = &v_cache[..need.min(v_cache.len())]; |
| 1106 | let native = shapes_ok |
| 1107 | && self.chip_attention( |
| 1108 | &format!("gqa_attention_rows base={base_len} rows={num_rows}"), |
| 1109 | || { |
| 1110 | aien_omega_gpu::gqa_attention_rows_f32( |
| 1111 | q, |
| 1112 | k_rows, |
| 1113 | v_rows, |
| 1114 | base_len, |
| 1115 | num_rows, |
| 1116 | num_q_heads, |
| 1117 | num_kv_heads, |
| 1118 | head_dim, |
| 1119 | out, |
| 1120 | ) |
| 1121 | }, |
| 1122 | ); |
| 1123 | if native { |
| 1124 | return; |
| 1125 | } |
| 1126 | self.reference_for(TensorOp::GqaAttention); |
| 1127 | self.reference.gqa_attention_rows( |
| 1128 | out, |
| 1129 | q, |
| 1130 | k_cache, |
| 1131 | v_cache, |
| 1132 | base_len, |
| 1133 | num_rows, |
| 1134 | num_q_heads, |
| 1135 | num_kv_heads, |
| 1136 | head_dim, |
| 1137 | ); |
| 1138 | } |
| 1139 | |
| 1140 | fn alloc_kv_pool(&self, bytes: usize) -> Option<aien_kv_cache::DefaultUnifiedBuffer> { |
| 1141 | // omega's resident KV pool: the paged attention reads it in place (no per-call staging of |
| 1142 | // the layer slices). A refusal falls back to the host-mapped pool, which stays correct. |
| 1143 | let (ptr, len) = match aien_omega_gpu::resident_kv_pool_alloc(bytes) { |
| 1144 | Ok(p) => p, |
| 1145 | Err(e) => { |
| 1146 | self.fail(format!( |
| 1147 | "resident KV pool of {bytes} bytes: {e:?}; host-mapped pool, staged attention" |
| 1148 | )); |
| 1149 | return None; |
| 1150 | } |
| 1151 | }; |
| 1152 | // SAFETY: omega owns `len` bytes at `ptr` until `resident_kv_pool_free`, which the release |
| 1153 | // callback runs exactly once; omega's allocations have chip address == host address. |
| 1154 | let wrapped = unsafe { |
| 1155 | aien_kv_cache::external_default_buffer( |
| 1156 | ptr, |
| 1157 | len, |
| 1158 | ptr as u64, |
| 1159 | Box::new(aien_omega_gpu::resident_kv_pool_free), |
| 1160 | ) |
| 1161 | }; |
| 1162 | match wrapped { |
| 1163 | Ok(b) => Some(b), |
| 1164 | Err(e) => { |
| 1165 | aien_omega_gpu::resident_kv_pool_free(); |
| 1166 | self.fail(e); |
| 1167 | None |
| 1168 | } |
| 1169 | } |
| 1170 | } |
| 1171 | |
| 1172 | fn paged_attention( |
| 1173 | &self, |
| 1174 | out: &mut [f32], |
| 1175 | q: &[f32], |
| 1176 | pool: &aien_kv_cache::UnifiedKvTensorPool, |
| 1177 | block_ids: &[usize], |
| 1178 | context_len: usize, |
| 1179 | layer_idx: usize, |
| 1180 | num_q_heads: usize, |
| 1181 | num_kv_heads: usize, |
| 1182 | head_dim: usize, |
| 1183 | ) { |
| 1184 | if self.chip_paged_one( |
| 1185 | out, |
| 1186 | q, |
| 1187 | pool, |
| 1188 | block_ids, |
| 1189 | context_len, |
| 1190 | layer_idx, |
| 1191 | num_q_heads, |
| 1192 | num_kv_heads, |
| 1193 | head_dim, |
| 1194 | ) { |
| 1195 | return; |
| 1196 | } |
| 1197 | self.reference_for(TensorOp::PagedAttention); |
| 1198 | self.reference.paged_attention( |
| 1199 | out, |
| 1200 | q, |
| 1201 | pool, |
| 1202 | block_ids, |
| 1203 | context_len, |
| 1204 | layer_idx, |
| 1205 | num_q_heads, |
| 1206 | num_kv_heads, |
| 1207 | head_dim, |
| 1208 | ); |
| 1209 | } |
| 1210 | |
| 1211 | fn paged_attention_batch( |
| 1212 | &self, |
| 1213 | out: &mut [f32], |
| 1214 | q: &[f32], |
| 1215 | pool: &aien_kv_cache::UnifiedKvTensorPool, |
| 1216 | block_tables: &[i32], |
| 1217 | context_lens: &[i32], |
| 1218 | max_blocks_per_seq: usize, |
| 1219 | num_seqs: usize, |
| 1220 | layer_idx: usize, |
| 1221 | num_q_heads: usize, |
| 1222 | num_kv_heads: usize, |
| 1223 | head_dim: usize, |
| 1224 | ) { |
| 1225 | // Per sequence, the same row handling as the TensorBackend default (context_lens <= 0 |
| 1226 | // means 0, a row past the array is empty, negative entries are removed), each row on |
| 1227 | // the chip. Any failed row sends the whole batch to the reference, counted once as a |
| 1228 | // batch op (the reference batch calls the reference single path, not ours). |
| 1229 | let q_stride = num_q_heads * head_dim; |
| 1230 | let mut all_native = q.len() >= num_seqs * q_stride && out.len() >= num_seqs * q_stride; |
| 1231 | for s in 0..num_seqs { |
| 1232 | if !all_native { |
| 1233 | break; |
| 1234 | } |
| 1235 | let ctx = context_lens |
| 1236 | .get(s) |
| 1237 | .copied() |
| 1238 | .filter(|&c| c > 0) |
| 1239 | .map_or(0, |c| c as usize); |
| 1240 | let (b0, b1) = (s * max_blocks_per_seq, (s + 1) * max_blocks_per_seq); |
| 1241 | let row: Vec<usize> = if b1 <= block_tables.len() { |
| 1242 | block_tables[b0..b1] |
| 1243 | .iter() |
| 1244 | .filter(|&&b| b >= 0) |
| 1245 | .map(|&b| b as usize) |
| 1246 | .collect() |
| 1247 | } else { |
| 1248 | Vec::new() |
| 1249 | }; |
| 1250 | all_native = self.chip_paged_one( |
| 1251 | &mut out[s * q_stride..(s + 1) * q_stride], |
| 1252 | &q[s * q_stride..(s + 1) * q_stride], |
| 1253 | pool, |
| 1254 | &row, |
| 1255 | ctx, |
| 1256 | layer_idx, |
| 1257 | num_q_heads, |
| 1258 | num_kv_heads, |
| 1259 | head_dim, |
| 1260 | ); |
| 1261 | } |
| 1262 | if all_native { |
| 1263 | return; |
| 1264 | } |
| 1265 | self.reference_for(TensorOp::PagedAttentionBatch); |
| 1266 | self.reference.paged_attention_batch( |
| 1267 | out, |
| 1268 | q, |
| 1269 | pool, |
| 1270 | block_tables, |
| 1271 | context_lens, |
| 1272 | max_blocks_per_seq, |
| 1273 | num_seqs, |
| 1274 | layer_idx, |
| 1275 | num_q_heads, |
| 1276 | num_kv_heads, |
| 1277 | head_dim, |
| 1278 | ); |
| 1279 | } |
| 1280 | |
| 1281 | fn compute_logits( |
| 1282 | &self, |
| 1283 | logits: &mut [f32], |
| 1284 | hidden: &[f32], |
| 1285 | embed_weight: &[f32], |
| 1286 | vocab_size: usize, |
| 1287 | hidden_dim: usize, |
| 1288 | ) { |
| 1289 | if !self.chip_matmul(logits, hidden, embed_weight, 1, hidden_dim, vocab_size) { |
| 1290 | self.reference_for(TensorOp::ComputeLogits); |
| 1291 | self.reference |
| 1292 | .compute_logits(logits, hidden, embed_weight, vocab_size, hidden_dim); |
| 1293 | } |
| 1294 | } |
| 1295 | } |
| 1296 | |
| 1297 | // ---- bounded GPU session open (issue #239, diagnostics for #236) ---- |
| 1298 | |
| 1299 | /// Attempts the daemon makes to open the GPU session before it refuses to start. |
| 1300 | pub const GPU_SESSION_OPEN_ATTEMPTS: u32 = 3; |
| 1301 | |
| 1302 | /// Pause between two session-open attempts. |
| 1303 | pub const GPU_SESSION_RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(500); |
| 1304 | |
| 1305 | /// Wall-clock budget for the whole GPU session open (probe plus retries). It is checked |
| 1306 | /// only BETWEEN attempts: no new attempt starts once it has passed. An attempt already |
| 1307 | /// running is never interrupted, aborted or killed (standing rule: a GPU job is not |
| 1308 | /// killed mid-launch), so a single probe that hangs forever still blocks startup; the |
| 1309 | /// bound guarantees only that a slow-failing sequence of attempts cannot go on past |
| 1310 | /// the deadline plus one attempt. |
| 1311 | pub const GPU_SESSION_OPEN_DEADLINE: std::time::Duration = std::time::Duration::from_secs(30); |
| 1312 | |
| 1313 | /// Why one session-open attempt failed. |
| 1314 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1315 | pub struct SessionAttemptError { |
| 1316 | /// Return code and omega stage, as the chip-error log prints them. |
| 1317 | pub message: String, |
| 1318 | /// True once omega has latched the process (every later chip call fails), so a |
| 1319 | /// further attempt cannot succeed and is not made. |
| 1320 | pub latched: bool, |
| 1321 | } |
| 1322 | |
| 1323 | /// Runs `attempt(n)` for `n = 1..=attempts` (at least once) until one succeeds and |
| 1324 | /// returns its value with the attempt number. Each failure goes to `on_failure` |
| 1325 | /// (the caller logs it); `pause(n)` runs between failed attempt `n` and the next. A |
| 1326 | /// latched failure stops at once. Never loops past `attempts`. |
| 1327 | pub fn retry_bounded<T>( |
| 1328 | attempts: u32, |
| 1329 | attempt: impl FnMut(u32) -> Result<T, SessionAttemptError>, |
| 1330 | on_failure: impl FnMut(u32, u32, &SessionAttemptError), |
| 1331 | pause: impl FnMut(u32), |
| 1332 | ) -> Result<(T, u32), String> { |
| 1333 | retry_bounded_within( |
| 1334 | attempts, |
| 1335 | None, |
| 1336 | || std::time::Duration::ZERO, |
| 1337 | attempt, |
| 1338 | on_failure, |
| 1339 | pause, |
| 1340 | ) |
| 1341 | } |
| 1342 | |
| 1343 | /// [`retry_bounded`] with a wall-clock bound. `elapsed()` is the time since the whole |
| 1344 | /// startup began (the caller's injected clock). `deadline` is checked only BETWEEN |
| 1345 | /// attempts, after the pause: once `elapsed() >= deadline` no further attempt starts |
| 1346 | /// and the error names the attempts made and the elapsed time. Attempt 1 always runs. |
| 1347 | /// An attempt already in flight is never interrupted: `attempt` is called to |
| 1348 | /// completion, because a GPU launch must not be cancelled or killed mid-way. So the |
| 1349 | /// deadline is a bound on starting attempts, not a timeout on a single hung attempt. |
| 1350 | pub fn retry_bounded_within<T>( |
| 1351 | attempts: u32, |
| 1352 | deadline: Option<std::time::Duration>, |
| 1353 | mut elapsed: impl FnMut() -> std::time::Duration, |
| 1354 | mut attempt: impl FnMut(u32) -> Result<T, SessionAttemptError>, |
| 1355 | mut on_failure: impl FnMut(u32, u32, &SessionAttemptError), |
| 1356 | mut pause: impl FnMut(u32), |
| 1357 | ) -> Result<(T, u32), String> { |
| 1358 | let attempts = attempts.max(1); |
| 1359 | let mut last = String::new(); |
| 1360 | for n in 1..=attempts { |
| 1361 | if n > 1 { |
| 1362 | if let Some(limit) = deadline { |
| 1363 | let now = elapsed(); |
| 1364 | if now >= limit { |
| 1365 | return Err(format!( |
| 1366 | "GPU session open timed out: deadline {} ms passed after {} of {attempts} attempts, elapsed {} ms (an attempt in flight is never interrupted; the deadline applies between attempts); last error: {last}", |
| 1367 | limit.as_millis(), |
| 1368 | n - 1, |
| 1369 | now.as_millis() |
| 1370 | )); |
| 1371 | } |
| 1372 | } |
| 1373 | } |
| 1374 | match attempt(n) { |
| 1375 | Ok(v) => return Ok((v, n)), |
| 1376 | Err(e) => { |
| 1377 | on_failure(n, attempts, &e); |
| 1378 | if e.latched { |
| 1379 | return Err(format!( |
| 1380 | "GPU session open failed on attempt {n}/{attempts} and omega latched the process (not retried): {}", |
| 1381 | e.message |
| 1382 | )); |
| 1383 | } |
| 1384 | last = e.message; |
| 1385 | if n < attempts { |
| 1386 | pause(n); |
| 1387 | } |
| 1388 | } |
| 1389 | } |
| 1390 | } |
| 1391 | Err(format!( |
| 1392 | "GPU session did not open after {attempts} attempts; last error: {last}" |
| 1393 | )) |
| 1394 | } |
| 1395 | |
| 1396 | fn fmt_mem(bytes: Option<u64>) -> String { |
| 1397 | match bytes { |
| 1398 | Some(b) => format!("{b} bytes ({:.2} GiB)", b as f64 / (1u64 << 30) as f64), |
| 1399 | None => "unknown".to_string(), |
| 1400 | } |
| 1401 | } |
| 1402 | |
| 1403 | /// Opens the GPU session before serving, with up to `attempts` tries `delay` apart. |
| 1404 | /// |
| 1405 | /// omega opens its device and channel lazily on the first chip call, and a failed |
| 1406 | /// open leaves the session closed but not latched (omega c0369e6 |
| 1407 | /// src/omega_gpu_session.c:101-109: `m16_native_create_channel` failure closes and |
| 1408 | /// returns NULL without setting `g_blocked`), so the next call opens again. The |
| 1409 | /// probe is one 1 x 128 rmsnorm called on `aien_omega_gpu` directly, outside the |
| 1410 | /// `TensorBackend` accounting, so a failure here is a clear start-up refusal |
| 1411 | /// instead of the strict-fallback panic at warm-up (#236). Every attempt logs its |
| 1412 | /// number, the omega status and stage, and `MemAvailable` from `mem_available`. |
| 1413 | /// `deadline` bounds the whole open between attempts only; see [`retry_bounded_within`] |
| 1414 | /// (an in-flight probe is never interrupted). |
| 1415 | /// Returns the attempt number that opened the session. |
| 1416 | pub fn open_gpu_session_with_retry( |
| 1417 | attempts: u32, |
| 1418 | delay: std::time::Duration, |
| 1419 | deadline: std::time::Duration, |
| 1420 | mem_available: &dyn Fn() -> Option<u64>, |
| 1421 | ) -> Result<u32, String> { |
| 1422 | if !aien_omega_gpu::is_native() { |
| 1423 | return Err( |
| 1424 | "GPU session open: the Omega GPU engine is not linked (stub build)".to_string(), |
| 1425 | ); |
| 1426 | } |
| 1427 | const PROBE_DIM: usize = 128; // omega rmsnorm needs dim % 128 == 0 |
| 1428 | let ones = [1.0f32; PROBE_DIM]; |
| 1429 | let started = std::time::Instant::now(); |
| 1430 | let (_, n) = retry_bounded_within( |
| 1431 | attempts, |
| 1432 | Some(deadline), |
| 1433 | || started.elapsed(), |
| 1434 | |_| { |
| 1435 | let mut out = [0.0f32; PROBE_DIM]; |
| 1436 | aien_omega_gpu::rmsnorm_f32(1, PROBE_DIM, &ones, &ones, 1e-5, &mut out) |
| 1437 | .map(|_| ()) |
| 1438 | .map_err(|e| { |
| 1439 | let stage = aien_omega_gpu::last_error(); |
| 1440 | SessionAttemptError { |
| 1441 | message: if stage.is_empty() { |
| 1442 | e.to_string() |
| 1443 | } else { |
| 1444 | format!("{e} (stage: {stage})") |
| 1445 | }, |
| 1446 | latched: aien_omega_gpu::is_blocked(), |
| 1447 | } |
| 1448 | }) |
| 1449 | }, |
| 1450 | |n, of, e| { |
| 1451 | eprintln!( |
| 1452 | "OMEGA_BACKEND GPU session open attempt {n}/{of} failed: {}; latched={}; MemAvailable {}", |
| 1453 | e.message, |
| 1454 | e.latched, |
| 1455 | fmt_mem(mem_available()) |
| 1456 | ) |
| 1457 | }, |
| 1458 | |_| std::thread::sleep(delay), |
| 1459 | )?; |
| 1460 | println!( |
| 1461 | " GPU session: open on attempt {n}/{} (MemAvailable {})", |
| 1462 | attempts.max(1), |
| 1463 | fmt_mem(mem_available()) |
| 1464 | ); |
| 1465 | Ok(n) |
| 1466 | } |
| 1467 | |
| 1468 | #[cfg(test)] |
| 1469 | mod tests { |
| 1470 | use super::*; |
| 1471 | |
| 1472 | fn qwen3_4b_shape() -> ModelConfig { |
| 1473 | let mut c = ModelConfig::tinyllama_1_1b(); |
| 1474 | c.model_id = "qwen3-shape-test".to_string(); |
| 1475 | c.qk_norm = true; |
| 1476 | c.head_dim = 128; |
| 1477 | c |
| 1478 | } |
| 1479 | |
| 1480 | #[test] |
| 1481 | fn stub_backend_refuses_qwen3_with_switch_unset_or_one() { |
| 1482 | let b = OmegaGb10Backend::new(); |
| 1483 | if b.is_available() { |
| 1484 | return; // chip build: the stub refusal does not apply |
| 1485 | } |
| 1486 | let q = qwen3_4b_shape(); |
| 1487 | // Unset on a strict run is "enabled"; `1` is enabled. A stub build still refuses. |
| 1488 | for enabled in [ |
| 1489 | gb10_qwen3_enabled_from(None, true), |
| 1490 | gb10_qwen3_enabled_from(Some("1"), true), |
| 1491 | ] { |
| 1492 | assert!(enabled); |
| 1493 | let err = b.check_model_with(&q, enabled).unwrap_err(); |
| 1494 | assert!(err.contains("stub build (no chip)"), "{err}"); |
| 1495 | } |
| 1496 | // Llama-architecture models are unchanged. |
| 1497 | assert!(b |
| 1498 | .check_model_with(&ModelConfig::tinyllama_1_1b(), false) |
| 1499 | .is_ok()); |
| 1500 | } |
| 1501 | |
| 1502 | #[test] |
| 1503 | fn non_utf8_switch_value_refuses() { |
| 1504 | use std::os::unix::ffi::OsStrExt; |
| 1505 | let bad = std::ffi::OsStr::from_bytes(&[0x31, 0xff]); |
| 1506 | for strict in [true, false] { |
| 1507 | assert!(!gb10_qwen3_enabled_from_os(Some(bad), strict)); |
| 1508 | } |
| 1509 | assert!(gb10_qwen3_enabled_from_os( |
| 1510 | Some(std::ffi::OsStr::new("1")), |
| 1511 | false |
| 1512 | )); |
| 1513 | assert!(!gb10_qwen3_enabled_from_os( |
| 1514 | Some(std::ffi::OsStr::new("0")), |
| 1515 | true |
| 1516 | )); |
| 1517 | } |
| 1518 | |
| 1519 | #[test] |
| 1520 | fn unset_switch_needs_a_strict_run_but_one_always_enables() { |
| 1521 | // Rule: AIEN_DEV_FALLBACK=1 (non-strict) with the switch unset is refused by name. |
| 1522 | assert!(!gb10_qwen3_enabled_from(None, false)); |
| 1523 | let q = qwen3_4b_shape(); |
| 1524 | let msg = omega_model_refusal_with(&q, gb10_qwen3_enabled_from(None, false)) |
| 1525 | .expect("unset + non-strict must refuse"); |
| 1526 | assert!(msg.contains(GB10_QWEN3_OPT_IN_ENV), "{msg}"); |
| 1527 | let b = OmegaGb10Backend::new(); |
| 1528 | assert!(b |
| 1529 | .check_model_with(&q, gb10_qwen3_enabled_from(None, false)) |
| 1530 | .unwrap_err() |
| 1531 | .contains(GB10_QWEN3_OPT_IN_ENV)); |
| 1532 | // Explicit 1 keeps the declared-attempt opt-in; no resident load without strict. |
| 1533 | assert!(omega_model_refusal_with(&q, gb10_qwen3_enabled_from(Some("1"), false)).is_none()); |
| 1534 | assert!(!crate::resident::resident_load_wanted( |
| 1535 | true, |
| 1536 | false, |
| 1537 | gb10_qwen3_enabled_from(Some("1"), false), |
| 1538 | &q |
| 1539 | )); |
| 1540 | assert!(!crate::resident::resident_load_wanted( |
| 1541 | true, |
| 1542 | false, |
| 1543 | gb10_qwen3_enabled_from(None, false), |
| 1544 | &q |
| 1545 | )); |
| 1546 | assert!(crate::resident::resident_load_wanted( |
| 1547 | true, |
| 1548 | true, |
| 1549 | gb10_qwen3_enabled_from(None, true), |
| 1550 | &q |
| 1551 | )); |
| 1552 | } |
| 1553 | |
| 1554 | fn lcg(s: &mut u32) -> f32 { |
| 1555 | *s = s.wrapping_mul(1664525).wrapping_add(1013904223); |
| 1556 | ((*s >> 8) as f32 / (1u32 << 24) as f32) - 0.5 |
| 1557 | } |
| 1558 | |
| 1559 | #[test] |
| 1560 | fn mask_is_all_ten_ops() { |
| 1561 | let b = OmegaGb10Backend::new(); |
| 1562 | let names: Vec<_> = b |
| 1563 | .native_ops() |
| 1564 | .native_ops() |
| 1565 | .iter() |
| 1566 | .map(|o| o.name()) |
| 1567 | .collect(); |
| 1568 | assert_eq!( |
| 1569 | names, |
| 1570 | [ |
| 1571 | "rmsnorm", |
| 1572 | "apply_rope", |
| 1573 | "matmul_vec", |
| 1574 | "matmul_batch", |
| 1575 | "swiglu", |
| 1576 | "gqa_attention", |
| 1577 | "paged_attention", |
| 1578 | "paged_attention_batch", |
| 1579 | "compute_logits", |
| 1580 | "rmsnorm_heads" |
| 1581 | ] |
| 1582 | ); |
| 1583 | } |
| 1584 | |
| 1585 | #[test] |
| 1586 | fn attention_chip_error_is_a_counted_fallback() { |
| 1587 | if aien_omega_gpu::is_native() || !crate::strict::dev_fallback_active() { |
| 1588 | return; // native: nothing fails here; production: it would (correctly) panic |
| 1589 | } |
| 1590 | let b = OmegaGb10Backend::new(); |
| 1591 | let (q, k, v) = ( |
| 1592 | [0.5f32, -1.0], |
| 1593 | [1.0f32, 2.0, -1.0, 0.25], |
| 1594 | [3.0f32, 4.0, 5.0, 6.0], |
| 1595 | ); |
| 1596 | let mut got = [0.0f32; 2]; |
| 1597 | let mut want = [0.0f32; 2]; |
| 1598 | b.gqa_attention(&mut got, &q, &k, &v, 2, 1, 1, 2); |
| 1599 | ReferenceCpuBackend::new().gqa_attention(&mut want, &q, &k, &v, 2, 1, 1, 2); |
| 1600 | assert_eq!(got, want); |
| 1601 | assert_eq!(b.fallback_count(), 1); |
| 1602 | assert!(b |
| 1603 | .op_report() |
| 1604 | .line() |
| 1605 | .contains("native_fallbacks=[gqa_attention:1]")); |
| 1606 | } |
| 1607 | |
| 1608 | /// Stub build only: a chip error on a claimed-native op is a counted fallback |
| 1609 | /// (dev build) with the reference result, never silent. |
| 1610 | #[test] |
| 1611 | fn chip_error_is_a_counted_fallback() { |
| 1612 | if aien_omega_gpu::is_native() || !crate::strict::dev_fallback_active() { |
| 1613 | return; // native: nothing fails here; production: it would (correctly) panic |
| 1614 | } |
| 1615 | let b = OmegaGb10Backend::new(); |
| 1616 | let mut s = 7u32; |
| 1617 | let (m, k, n) = (3usize, 32usize, 16usize); |
| 1618 | let x: Vec<f32> = (0..m * k).map(|_| lcg(&mut s)).collect(); |
| 1619 | let w: Vec<f32> = (0..n * k).map(|_| lcg(&mut s)).collect(); |
| 1620 | let mut got = vec![0.0f32; m * n]; |
| 1621 | let mut want = vec![0.0f32; m * n]; |
| 1622 | b.matmul_batch(&mut got, &x, &w, m, k, n); |
| 1623 | ReferenceCpuBackend::new().matmul_batch(&mut want, &x, &w, m, k, n); |
| 1624 | assert_eq!(got, want); |
| 1625 | assert_eq!(b.fallback_count(), 1); |
| 1626 | assert_eq!(b.chip_errors(), 1); |
| 1627 | assert!(b |
| 1628 | .op_report() |
| 1629 | .line() |
| 1630 | .contains("native_fallbacks=[matmul_batch:1]")); |
| 1631 | } |
| 1632 | |
| 1633 | /// Negative control for stub and native builds alike. The engine refuses a |
| 1634 | /// claimed-native op before any launch (swiglu with unequal gate/up lengths; the |
| 1635 | /// reference path accepts it and uses the shorter length). In a strict process that |
| 1636 | /// refusal must be fatal; in a dev process it must be a counted fallback with the |
| 1637 | /// reference result. This replaces a `should_panic` test whose skip branch panicked |
| 1638 | /// with the expected text, so it passed without testing anything in dev and native runs. |
| 1639 | #[test] |
| 1640 | fn chip_refusal_is_fatal_in_strict_and_counted_in_dev() { |
| 1641 | let b = OmegaGb10Backend::new(); |
| 1642 | let gate = [0.5f32, 2.0, -1.0]; |
| 1643 | let up = [3.0f32, -0.25]; |
| 1644 | let mut out = [0.0f32; 2]; |
| 1645 | let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 1646 | b.swiglu(&mut out, &gate, &up) |
| 1647 | })); |
| 1648 | assert_eq!(b.chip_errors(), 1, "{}", b.last_error()); |
| 1649 | assert_eq!(b.fallback_count(), 1); |
| 1650 | assert!( |
| 1651 | b.op_report().line().contains("native_fallbacks=[swiglu:1]"), |
| 1652 | "{}", |
| 1653 | b.op_report().line() |
| 1654 | ); |
| 1655 | if crate::strict::production_strict() { |
| 1656 | let err = r.expect_err("a strict process must refuse a claimed-native fallback"); |
| 1657 | let msg = err |
| 1658 | .downcast_ref::<String>() |
| 1659 | .cloned() |
| 1660 | .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string())) |
| 1661 | .unwrap_or_default(); |
| 1662 | assert!( |
| 1663 | msg.contains(crate::strict::STRICT_VIOLATION_PREFIX) && msg.contains("swiglu"), |
| 1664 | "{msg}" |
| 1665 | ); |
| 1666 | } else { |
| 1667 | r.expect("a dev process continues on the reference path"); |
| 1668 | let mut want = [0.0f32; 2]; |
| 1669 | ReferenceCpuBackend::new().swiglu(&mut want, &gate, &up); |
| 1670 | assert_eq!(out, want); |
| 1671 | } |
| 1672 | } |
| 1673 | |
| 1674 | /// The cached cos/sin table, applied on the host with the same f32 formulas as the |
| 1675 | /// chip kernel (FMUL, FMUL, FADD), must equal the reference rope bit for bit. |
| 1676 | #[test] |
| 1677 | fn rope_table_reproduces_reference_rope() { |
| 1678 | let b = OmegaGb10Backend::new(); |
| 1679 | let (head_dim, nq, nkv, pos) = (64usize, 4usize, 2usize, 37usize); |
| 1680 | let theta = &RopeParams::plain(10000.0); |
| 1681 | let mut s = 99u32; |
| 1682 | let q0: Vec<f32> = (0..nq * head_dim).map(|_| lcg(&mut s)).collect(); |
| 1683 | let k0: Vec<f32> = (0..nkv * head_dim).map(|_| lcg(&mut s)).collect(); |
| 1684 | let (mut qr, mut kr) = (q0.clone(), k0.clone()); |
| 1685 | ReferenceCpuBackend::new().apply_rope(&mut qr, &mut kr, pos, head_dim, nq, nkv, theta); |
| 1686 | let t = b.rope_table(head_dim, theta, pos); |
| 1687 | let half = head_dim / 2; |
| 1688 | let rot = |v: &[f32]| -> Vec<f32> { |
| 1689 | let mut o = v.to_vec(); |
| 1690 | for h in 0..v.len() / head_dim { |
| 1691 | for i in 0..half { |
| 1692 | let (a, c) = (v[h * head_dim + i], v[h * head_dim + i + half]); |
| 1693 | o[h * head_dim + i] = a * t.0[i] - c * t.1[i]; |
| 1694 | o[h * head_dim + i + half] = a * t.1[i] + c * t.0[i]; |
| 1695 | } |
| 1696 | } |
| 1697 | o |
| 1698 | }; |
| 1699 | assert_eq!(rot(&q0), qr); |
| 1700 | assert_eq!(rot(&k0), kr); |
| 1701 | // cached: same allocation on the second ask |
| 1702 | assert!(Arc::ptr_eq(&t, &b.rope_table(head_dim, theta, pos))); |
| 1703 | } |
| 1704 | |
| 1705 | /// sc#402: the chip-call total is reported only when the real engine is linked; the |
| 1706 | /// stub has no chip and makes no claim (None, never a zero that reads as "ran, no calls"). |
| 1707 | #[test] |
| 1708 | fn op_timing_table_tallies_sorts_and_resets() { |
| 1709 | let b = OmegaGb10Backend::new(); |
| 1710 | assert_eq!(b.op_timing_lines(), ""); |
| 1711 | assert_eq!(b.op_timing_report(), Some(String::new())); |
| 1712 | b.tally("rmsnorm".into(), 2_000_000, 1_500_000); |
| 1713 | b.tally("matmul m=1 k=4096 n=4096".into(), 10_000_000, 9_000_000); |
| 1714 | b.tally("rmsnorm".into(), 1_000_000, 500_000); |
| 1715 | assert_eq!( |
| 1716 | b.op_timing_lines(), |
| 1717 | "matmul m=1 k=4096 n=4096 calls=1 wall_ms=10.0 chip_ms=9.0; rmsnorm calls=2 wall_ms=3.0 chip_ms=2.0; kv_staged_bytes_total=0 kv_resident_calls_total=0" |
| 1718 | ); |
| 1719 | b.reset_op_timing(); |
| 1720 | assert_eq!(b.op_timing_lines(), ""); |
| 1721 | } |
| 1722 | |
| 1723 | #[test] |
| 1724 | fn gpu_executions_is_the_chip_call_total_or_absent() { |
| 1725 | let b = OmegaGb10Backend::new(); |
| 1726 | let got = TensorBackend::gpu_executions(&b); |
| 1727 | if b.is_available() { |
| 1728 | assert_eq!(got, Some(b.chip_calls())); |
| 1729 | } else { |
| 1730 | assert_eq!(got, None); |
| 1731 | } |
| 1732 | } |
| 1733 | |
| 1734 | /// Stub build only: each newly native elementwise op is a counted fallback with the |
| 1735 | /// reference result when the chip is unavailable, never silent. |
| 1736 | #[test] |
| 1737 | fn single_token_norms_and_rope_run_on_the_host_without_a_fallback() { |
| 1738 | // Any build: the host route never touches the chip. One row of 4096 (the model width), |
| 1739 | // 32 + 8 heads of 128, one token of rope: reference results, host_ops counts, no fallback. |
| 1740 | let b = OmegaGb10Backend::new(); |
| 1741 | let r = ReferenceCpuBackend::new(); |
| 1742 | let mut s = 9u32; |
| 1743 | let x: Vec<f32> = (0..4096).map(|_| lcg(&mut s)).collect(); |
| 1744 | let w: Vec<f32> = (0..4096).map(|_| lcg(&mut s)).collect(); |
| 1745 | let (mut got, mut want) = (vec![0.0f32; 4096], vec![0.0f32; 4096]); |
| 1746 | b.rmsnorm(&mut got, &x, &w, 1e-6); |
| 1747 | r.rmsnorm(&mut want, &x, &w, 1e-6); |
| 1748 | assert_eq!(got, want); |
| 1749 | b.rmsnorm_rows(&mut got, &x, &w, 1, 1e-6); |
| 1750 | assert_eq!(got, want); |
| 1751 | let wh: Vec<f32> = (0..128).map(|_| lcg(&mut s)).collect(); |
| 1752 | let (mut hq, mut hw) = (x.clone(), x.clone()); |
| 1753 | b.rmsnorm_heads(&mut hq, &wh, 128, 1e-6); |
| 1754 | r.rmsnorm_heads(&mut hw, &wh, 128, 1e-6); |
| 1755 | assert_eq!(hq, hw); |
| 1756 | let (mut q, mut k) = (x.clone(), x[..1024].to_vec()); |
| 1757 | let (mut qw, mut kw) = (q.clone(), k.clone()); |
| 1758 | let rope = RopeParams::plain(1_000_000.0); |
| 1759 | b.apply_rope(&mut q, &mut k, 1268, 128, 32, 8, &rope); |
| 1760 | r.apply_rope(&mut qw, &mut kw, 1268, 128, 32, 8, &rope); |
| 1761 | assert_eq!((q, k), (qw, kw)); |
| 1762 | assert_eq!(b.host_ops(), 4); |
| 1763 | assert_eq!(b.fallback_count(), 0); |
| 1764 | assert_eq!(b.gpu_executions().unwrap_or(0), 0); |
| 1765 | let table = b.op_timing_lines(); |
| 1766 | assert!( |
| 1767 | table.contains("rmsnorm_host calls=2") && table.contains("rope_host calls=1"), |
| 1768 | "{table}" |
| 1769 | ); |
| 1770 | } |
| 1771 | |
| 1772 | #[test] |
| 1773 | fn elementwise_chip_errors_are_counted_fallbacks() { |
| 1774 | if aien_omega_gpu::is_native() || !crate::strict::dev_fallback_active() { |
| 1775 | return; |
| 1776 | } |
| 1777 | let b = OmegaGb10Backend::new(); |
| 1778 | let r = ReferenceCpuBackend::new(); |
| 1779 | let mut s = 5u32; |
| 1780 | let x: Vec<f32> = (0..128).map(|_| lcg(&mut s)).collect(); |
| 1781 | let w: Vec<f32> = (0..128).map(|_| lcg(&mut s)).collect(); |
| 1782 | let (mut got, mut want) = (vec![0.0f32; 128], vec![0.0f32; 128]); |
| 1783 | b.rmsnorm(&mut got, &x, &w, 1e-5); |
| 1784 | r.rmsnorm(&mut want, &x, &w, 1e-5); |
| 1785 | assert_eq!(got, want); |
| 1786 | b.swiglu(&mut got, &x, &w); |
| 1787 | r.swiglu(&mut want, &x, &w); |
| 1788 | assert_eq!(got, want); |
| 1789 | let (mut q, mut k) = (x[..64].to_vec(), x[64..].to_vec()); |
| 1790 | let (mut qw, mut kw) = (q.clone(), k.clone()); |
| 1791 | b.apply_rope(&mut q, &mut k, 3, 32, 2, 2, &RopeParams::plain(10000.0)); |
| 1792 | r.apply_rope(&mut qw, &mut kw, 3, 32, 2, 2, &RopeParams::plain(10000.0)); |
| 1793 | assert_eq!((q, k), (qw, kw)); |
| 1794 | // the one-row rmsnorm and the one-token rope run on the host by size (HOST_ELEMENTWISE_MAX): |
| 1795 | // the golden maths, not fallbacks; swiglu stays a chip op and is the one counted fallback |
| 1796 | assert_eq!(b.host_ops(), 2); |
| 1797 | assert_eq!(b.fallback_count(), 1); |
| 1798 | let line = b.op_report().line(); |
| 1799 | assert!(line.contains("native_fallbacks=[swiglu:1]"), "{line}"); |
| 1800 | } |
| 1801 | |
| 1802 | #[test] |
| 1803 | fn fingerprint_changes_with_content() { |
| 1804 | let a = vec![1.0f32; 1000]; |
| 1805 | let mut b = a.clone(); |
| 1806 | b[999] = 2.0; |
| 1807 | assert_ne!(fingerprint(&a), fingerprint(&b)); |
| 1808 | } |
| 1809 | |
| 1810 | fn fail_msg(n: u32, latched: bool) -> SessionAttemptError { |
| 1811 | SessionAttemptError { |
| 1812 | message: format!("omega_gpu rc=-4 (CHIP_FAIL) try {n}"), |
| 1813 | latched, |
| 1814 | } |
| 1815 | } |
| 1816 | |
| 1817 | #[test] |
| 1818 | fn retry_stops_at_the_bound_and_logs_every_attempt() { |
| 1819 | let (mut calls, mut logged, mut pauses) = (0u32, Vec::new(), Vec::new()); |
| 1820 | let err = retry_bounded::<()>( |
| 1821 | 3, |
| 1822 | |n| { |
| 1823 | calls += 1; |
| 1824 | Err(fail_msg(n, false)) |
| 1825 | }, |
| 1826 | |n, of, e| logged.push(format!("{n}/{of}: {}", e.message)), |
| 1827 | |n| pauses.push(n), |
| 1828 | ) |
| 1829 | .unwrap_err(); |
| 1830 | assert_eq!(calls, 3); |
| 1831 | assert_eq!(pauses, vec![1, 2]); |
| 1832 | assert_eq!(logged.len(), 3); |
| 1833 | assert!(logged[2].starts_with("3/3")); |
| 1834 | assert!( |
| 1835 | err.contains("after 3 attempts") && err.contains("try 3"), |
| 1836 | "{err}" |
| 1837 | ); |
| 1838 | } |
| 1839 | |
| 1840 | #[test] |
| 1841 | fn retry_returns_the_attempt_that_succeeded() { |
| 1842 | let mut pauses = 0; |
| 1843 | let r = retry_bounded( |
| 1844 | 3, |
| 1845 | |n| { |
| 1846 | if n < 2 { |
| 1847 | Err(fail_msg(n, false)) |
| 1848 | } else { |
| 1849 | Ok(n * 10) |
| 1850 | } |
| 1851 | }, |
| 1852 | |_, _, _| {}, |
| 1853 | |_| pauses += 1, |
| 1854 | ); |
| 1855 | assert_eq!(r, Ok((20, 2))); |
| 1856 | assert_eq!(pauses, 1); |
| 1857 | } |
| 1858 | |
| 1859 | #[test] |
| 1860 | fn retry_does_not_repeat_a_latched_failure_and_runs_at_least_once() { |
| 1861 | let mut calls = 0; |
| 1862 | let err = retry_bounded::<()>( |
| 1863 | 3, |
| 1864 | |n| { |
| 1865 | calls += 1; |
| 1866 | Err(fail_msg(n, true)) |
| 1867 | }, |
| 1868 | |_, _, _| {}, |
| 1869 | |_| panic!("no pause after a latched failure"), |
| 1870 | ) |
| 1871 | .unwrap_err(); |
| 1872 | assert_eq!(calls, 1); |
| 1873 | assert!(err.contains("latched") && err.contains("1/3"), "{err}"); |
| 1874 | |
| 1875 | let mut zero_calls = 0; |
| 1876 | let _ = retry_bounded::<()>( |
| 1877 | 0, |
| 1878 | |n| { |
| 1879 | zero_calls += 1; |
| 1880 | Err(fail_msg(n, false)) |
| 1881 | }, |
| 1882 | |_, _, _| {}, |
| 1883 | |_| {}, |
| 1884 | ); |
| 1885 | assert_eq!(zero_calls, 1); |
| 1886 | } |
| 1887 | |
| 1888 | #[test] |
| 1889 | fn deadline_passed_between_attempts_stops_with_a_timeout_error() { |
| 1890 | // Injected clock: each attempt "takes" 400 ms; deadline 1000 ms. |
| 1891 | let clock = std::cell::Cell::new(0u64); |
| 1892 | let mut calls = 0; |
| 1893 | let err = retry_bounded_within::<()>( |
| 1894 | 10, |
| 1895 | Some(std::time::Duration::from_millis(1000)), |
| 1896 | || std::time::Duration::from_millis(clock.get()), |
| 1897 | |n| { |
| 1898 | calls += 1; |
| 1899 | clock.set(clock.get() + 400); |
| 1900 | Err(fail_msg(n, false)) |
| 1901 | }, |
| 1902 | |_, _, _| {}, |
| 1903 | |_| {}, |
| 1904 | ) |
| 1905 | .unwrap_err(); |
| 1906 | // Attempts at t=0, 400, 800 start; the check at t=1200 stops the fourth. |
| 1907 | assert_eq!(calls, 3, "{err}"); |
| 1908 | assert!(err.contains("timed out"), "{err}"); |
| 1909 | assert!(err.contains("after 3 of 10 attempts"), "{err}"); |
| 1910 | assert!(err.contains("elapsed 1200 ms"), "{err}"); |
| 1911 | assert!(err.contains("never interrupted"), "{err}"); |
| 1912 | } |
| 1913 | |
| 1914 | #[test] |
| 1915 | fn attempts_stay_bounded_when_the_deadline_never_passes() { |
| 1916 | let mut calls = 0; |
| 1917 | let err = retry_bounded_within::<()>( |
| 1918 | 3, |
| 1919 | Some(std::time::Duration::from_secs(3600)), |
| 1920 | || std::time::Duration::ZERO, |
| 1921 | |n| { |
| 1922 | calls += 1; |
| 1923 | Err(fail_msg(n, false)) |
| 1924 | }, |
| 1925 | |_, _, _| {}, |
| 1926 | |_| {}, |
| 1927 | ) |
| 1928 | .unwrap_err(); |
| 1929 | assert_eq!(calls, 3); |
| 1930 | assert!(err.contains("did not open after 3 attempts"), "{err}"); |
| 1931 | assert!(!err.contains("timed out"), "{err}"); |
| 1932 | } |
| 1933 | |
| 1934 | #[test] |
| 1935 | fn first_attempt_runs_even_if_the_deadline_is_already_zero() { |
| 1936 | let mut calls = 0; |
| 1937 | let _ = retry_bounded_within::<()>( |
| 1938 | 3, |
| 1939 | Some(std::time::Duration::ZERO), |
| 1940 | || std::time::Duration::from_secs(1), |
| 1941 | |n| { |
| 1942 | calls += 1; |
| 1943 | Err(fail_msg(n, false)) |
| 1944 | }, |
| 1945 | |_, _, _| {}, |
| 1946 | |_| {}, |
| 1947 | ); |
| 1948 | assert_eq!(calls, 1); |
| 1949 | } |
| 1950 | |
| 1951 | #[test] |
| 1952 | fn session_open_refuses_cleanly_in_a_stub_build() { |
| 1953 | if aien_omega_gpu::is_native() { |
| 1954 | return; // the native path is verified on the chip, not here |
| 1955 | } |
| 1956 | let err = open_gpu_session_with_retry( |
| 1957 | 3, |
| 1958 | std::time::Duration::ZERO, |
| 1959 | GPU_SESSION_OPEN_DEADLINE, |
| 1960 | &|| None, |
| 1961 | ) |
| 1962 | .unwrap_err(); |
| 1963 | assert!(err.contains("not linked"), "{err}"); |
| 1964 | } |
| 1965 | } |