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 / tensor_abi.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 | //! C-compatible typed tensor boundary for capsule storage and accelerator residency. |
| 17 | |
| 18 | use crate::capsule::{ModelCapsule, TensorLayout, WeightDType}; |
| 19 | use std::ffi::c_void; |
| 20 | use std::marker::PhantomData; |
| 21 | |
| 22 | pub const MAX_TENSOR_RANK: usize = 4; |
| 23 | |
| 24 | /// Numeric values are part of the C ABI of this boundary (`#[repr]` below); keep them stable. |
| 25 | #[repr(u32)] |
| 26 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 27 | pub enum AbiDType { |
| 28 | F32 = 1, |
| 29 | Bf16 = 2, |
| 30 | Fp16 = 3, |
| 31 | Fp8E4M3Fn = 4, |
| 32 | Fp8E5M2 = 5, |
| 33 | Int8 = 6, |
| 34 | Int4 = 7, |
| 35 | } |
| 36 | |
| 37 | impl From<WeightDType> for AbiDType { |
| 38 | fn from(dtype: WeightDType) -> Self { |
| 39 | match dtype { |
| 40 | WeightDType::F32 => Self::F32, |
| 41 | WeightDType::Bf16 => Self::Bf16, |
| 42 | WeightDType::Fp16 => Self::Fp16, |
| 43 | WeightDType::Fp8E4M3Fn => Self::Fp8E4M3Fn, |
| 44 | WeightDType::Fp8E5M2 => Self::Fp8E5M2, |
| 45 | WeightDType::Int8 => Self::Int8, |
| 46 | WeightDType::Int4 => Self::Int4, |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | #[repr(u32)] |
| 52 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 53 | pub enum AbiLayout { |
| 54 | RowMajor = 1, |
| 55 | ColumnMajor = 2, |
| 56 | Strided = 3, |
| 57 | } |
| 58 | |
| 59 | impl From<TensorLayout> for AbiLayout { |
| 60 | fn from(layout: TensorLayout) -> Self { |
| 61 | match layout { |
| 62 | TensorLayout::RowMajor => Self::RowMajor, |
| 63 | TensorLayout::ColumnMajor => Self::ColumnMajor, |
| 64 | TensorLayout::Strided => Self::Strided, |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | #[repr(u32)] |
| 70 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 71 | pub enum AbiResidency { |
| 72 | Host = 1, |
| 73 | Device = 2, |
| 74 | } |
| 75 | |
| 76 | #[repr(u32)] |
| 77 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 78 | pub enum AbiQuantScheme { |
| 79 | None = 0, |
| 80 | Symmetric = 1, |
| 81 | Affine = 2, |
| 82 | } |
| 83 | |
| 84 | #[repr(u32)] |
| 85 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 86 | pub enum AbiPacking { |
| 87 | None = 0, |
| 88 | Int4LowNibbleFirstSigned = 1, |
| 89 | Int4HighNibbleFirstSigned = 2, |
| 90 | Int4LowNibbleFirstUnsigned = 3, |
| 91 | Int4HighNibbleFirstUnsigned = 4, |
| 92 | } |
| 93 | |
| 94 | #[repr(C)] |
| 95 | #[derive(Debug, Clone, Copy)] |
| 96 | pub struct AbiQuantization { |
| 97 | pub scheme: AbiQuantScheme, |
| 98 | pub axis: i32, |
| 99 | pub group_size: u32, |
| 100 | pub packing: AbiPacking, |
| 101 | pub scales: *const f32, |
| 102 | pub scale_count: u64, |
| 103 | pub zero_points: *const i32, |
| 104 | pub zero_point_count: u64, |
| 105 | } |
| 106 | |
| 107 | impl Default for AbiQuantization { |
| 108 | fn default() -> Self { |
| 109 | Self { |
| 110 | scheme: AbiQuantScheme::None, |
| 111 | axis: -1, |
| 112 | group_size: 0, |
| 113 | packing: AbiPacking::None, |
| 114 | scales: std::ptr::null(), |
| 115 | scale_count: 0, |
| 116 | zero_points: std::ptr::null(), |
| 117 | zero_point_count: 0, |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | #[repr(C)] |
| 123 | #[derive(Debug, Clone, Copy)] |
| 124 | pub struct TensorDescriptor { |
| 125 | pub dtype: AbiDType, |
| 126 | pub layout: AbiLayout, |
| 127 | pub rank: u32, |
| 128 | pub residency: AbiResidency, |
| 129 | pub shape: [u64; MAX_TENSOR_RANK], |
| 130 | pub strides: [u64; MAX_TENSOR_RANK], |
| 131 | pub byte_len: u64, |
| 132 | pub quant: AbiQuantization, |
| 133 | } |
| 134 | |
| 135 | #[repr(C)] |
| 136 | #[derive(Debug, Clone, Copy)] |
| 137 | pub struct TensorView { |
| 138 | pub address: *const c_void, |
| 139 | pub descriptor: TensorDescriptor, |
| 140 | } |
| 141 | |
| 142 | /// The device allocation owns `address`, `quant.scales`, and `quant.zero_points`. |
| 143 | /// Whoever allocates it on a device must release all three. |
| 144 | #[repr(C)] |
| 145 | #[derive(Debug, Clone, Copy)] |
| 146 | pub struct ResidentTensor { |
| 147 | pub address: *mut c_void, |
| 148 | pub descriptor: TensorDescriptor, |
| 149 | } |
| 150 | |
| 151 | /// Keeps the host bytes and quantization arrays alive during an FFI upload. |
| 152 | pub struct BorrowedTensorView<'a> { |
| 153 | view: TensorView, |
| 154 | _source: PhantomData<&'a [u8]>, |
| 155 | } |
| 156 | |
| 157 | impl BorrowedTensorView<'_> { |
| 158 | pub fn as_abi(&self) -> &TensorView { |
| 159 | &self.view |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | impl TensorView { |
| 164 | pub fn f32_contiguous<'a>( |
| 165 | data: &'a [f32], |
| 166 | shape: &[usize], |
| 167 | ) -> Result<BorrowedTensorView<'a>, String> { |
| 168 | let byte_len = data |
| 169 | .len() |
| 170 | .checked_mul(4) |
| 171 | .ok_or("F32 byte length overflow")?; |
| 172 | let descriptor = descriptor( |
| 173 | AbiDType::F32, |
| 174 | AbiLayout::RowMajor, |
| 175 | shape, |
| 176 | &row_major_strides(shape)?, |
| 177 | byte_len, |
| 178 | AbiQuantization::default(), |
| 179 | )?; |
| 180 | Ok(BorrowedTensorView { |
| 181 | view: Self { |
| 182 | address: data.as_ptr().cast(), |
| 183 | descriptor, |
| 184 | }, |
| 185 | _source: PhantomData, |
| 186 | }) |
| 187 | } |
| 188 | |
| 189 | pub fn from_capsule<'a>( |
| 190 | capsule: &'a ModelCapsule, |
| 191 | name: &str, |
| 192 | ) -> Result<BorrowedTensorView<'a>, String> { |
| 193 | let tensor = capsule.tensor(name).map_err(|err| err.to_string())?; |
| 194 | let bytes = capsule.tensor_bytes(name).map_err(|err| err.to_string())?; |
| 195 | let quant = match &tensor.quant { |
| 196 | None => AbiQuantization::default(), |
| 197 | Some(quant) => AbiQuantization { |
| 198 | scheme: match quant.scheme.as_str() { |
| 199 | "symmetric" => AbiQuantScheme::Symmetric, |
| 200 | "affine" => AbiQuantScheme::Affine, |
| 201 | other => return Err(format!("unsupported quantization scheme {other}")), |
| 202 | }, |
| 203 | axis: i32::try_from(quant.axis).map_err(|_| "quantization axis overflow")?, |
| 204 | group_size: u32::try_from(quant.group_size).map_err(|_| "group size overflow")?, |
| 205 | packing: match quant.packing.as_str() { |
| 206 | "none" => AbiPacking::None, |
| 207 | "int4-low-signed" => AbiPacking::Int4LowNibbleFirstSigned, |
| 208 | "int4-high-signed" => AbiPacking::Int4HighNibbleFirstSigned, |
| 209 | "int4-low-unsigned" => AbiPacking::Int4LowNibbleFirstUnsigned, |
| 210 | "int4-high-unsigned" => AbiPacking::Int4HighNibbleFirstUnsigned, |
| 211 | other => return Err(format!("unsupported packing {other}")), |
| 212 | }, |
| 213 | scales: quant.scales.as_ptr(), |
| 214 | scale_count: quant.scales.len() as u64, |
| 215 | zero_points: quant.zero_points.as_ptr(), |
| 216 | zero_point_count: quant.zero_points.len() as u64, |
| 217 | }, |
| 218 | }; |
| 219 | let descriptor = descriptor( |
| 220 | tensor.dtype.into(), |
| 221 | tensor.layout.into(), |
| 222 | &tensor.shape, |
| 223 | &tensor.logical_strides, |
| 224 | bytes.len(), |
| 225 | quant, |
| 226 | )?; |
| 227 | Ok(BorrowedTensorView { |
| 228 | view: Self { |
| 229 | address: bytes.as_ptr().cast(), |
| 230 | descriptor, |
| 231 | }, |
| 232 | _source: PhantomData, |
| 233 | }) |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | fn descriptor( |
| 238 | dtype: AbiDType, |
| 239 | layout: AbiLayout, |
| 240 | shape: &[usize], |
| 241 | strides: &[usize], |
| 242 | byte_len: usize, |
| 243 | quant: AbiQuantization, |
| 244 | ) -> Result<TensorDescriptor, String> { |
| 245 | if shape.len() > MAX_TENSOR_RANK || shape.len() != strides.len() { |
| 246 | return Err("tensor rank or stride count invalid".to_string()); |
| 247 | } |
| 248 | if shape.is_empty() || shape.contains(&0) { |
| 249 | return Err("tensor dimensions must be nonzero".to_string()); |
| 250 | } |
| 251 | let elements = shape |
| 252 | .iter() |
| 253 | .try_fold(1usize, |count, dim| count.checked_mul(*dim)) |
| 254 | .ok_or("tensor element count overflow")?; |
| 255 | let expected = match dtype { |
| 256 | AbiDType::F32 => elements.checked_mul(4), |
| 257 | AbiDType::Bf16 | AbiDType::Fp16 => elements.checked_mul(2), |
| 258 | AbiDType::Fp8E4M3Fn | AbiDType::Fp8E5M2 | AbiDType::Int8 => Some(elements), |
| 259 | AbiDType::Int4 => elements.checked_add(1).map(|count| count / 2), |
| 260 | } |
| 261 | .ok_or("tensor byte length overflow")?; |
| 262 | if layout == AbiLayout::RowMajor && strides != row_major_strides(shape)? { |
| 263 | return Err("row-major strides do not match shape".to_string()); |
| 264 | } |
| 265 | if layout == AbiLayout::RowMajor && byte_len != expected { |
| 266 | return Err(format!( |
| 267 | "tensor byte length {byte_len} does not match {expected}" |
| 268 | )); |
| 269 | } |
| 270 | if dtype == AbiDType::Int4 && quant.packing == AbiPacking::None { |
| 271 | return Err("INT4 requires explicit nibble packing".to_string()); |
| 272 | } |
| 273 | if quant.scheme != AbiQuantScheme::None && quant.scale_count == 0 { |
| 274 | return Err("quantized tensor needs scales".to_string()); |
| 275 | } |
| 276 | if quant.scheme == AbiQuantScheme::None |
| 277 | && (quant.scale_count != 0 || quant.zero_point_count != 0) |
| 278 | { |
| 279 | return Err("unquantized tensor has quantization arrays".to_string()); |
| 280 | } |
| 281 | if quant.scale_count > 0 && quant.scales.is_null() { |
| 282 | return Err("quantization scales missing".to_string()); |
| 283 | } |
| 284 | if quant.zero_point_count > 0 && quant.zero_points.is_null() { |
| 285 | return Err("quantization zero points missing".to_string()); |
| 286 | } |
| 287 | let mut abi_shape = [0; MAX_TENSOR_RANK]; |
| 288 | let mut abi_strides = [0; MAX_TENSOR_RANK]; |
| 289 | for (index, value) in shape.iter().enumerate() { |
| 290 | abi_shape[index] = *value as u64; |
| 291 | abi_strides[index] = strides[index] as u64; |
| 292 | } |
| 293 | Ok(TensorDescriptor { |
| 294 | dtype, |
| 295 | layout, |
| 296 | rank: shape.len() as u32, |
| 297 | residency: AbiResidency::Host, |
| 298 | shape: abi_shape, |
| 299 | strides: abi_strides, |
| 300 | byte_len: byte_len as u64, |
| 301 | quant, |
| 302 | }) |
| 303 | } |
| 304 | |
| 305 | fn row_major_strides(shape: &[usize]) -> Result<Vec<usize>, String> { |
| 306 | let mut strides = vec![1usize; shape.len()]; |
| 307 | for index in (0..shape.len().saturating_sub(1)).rev() { |
| 308 | strides[index] = strides[index + 1] |
| 309 | .checked_mul(shape[index + 1]) |
| 310 | .ok_or("tensor stride overflow")?; |
| 311 | } |
| 312 | Ok(strides) |
| 313 | } |
| 314 | |
| 315 | #[cfg(test)] |
| 316 | mod tests { |
| 317 | use super::*; |
| 318 | use crate::capsule::{capsule_digest, source_digest, CapsuleTensor, QuantizationDescriptor}; |
| 319 | use std::collections::HashMap; |
| 320 | use std::sync::Arc; |
| 321 | |
| 322 | #[test] |
| 323 | fn f32_view_records_shape_stride_and_host_residency() { |
| 324 | let data = [1.0f32; 6]; |
| 325 | let view = TensorView::f32_contiguous(&data, &[2, 3]).unwrap(); |
| 326 | let descriptor = view.as_abi().descriptor; |
| 327 | assert_eq!(descriptor.dtype, AbiDType::F32); |
| 328 | assert_eq!(descriptor.residency, AbiResidency::Host); |
| 329 | assert_eq!(descriptor.shape[..2], [2, 3]); |
| 330 | assert_eq!(descriptor.strides[..2], [3, 1]); |
| 331 | assert_eq!(descriptor.byte_len, 24); |
| 332 | assert!(TensorView::f32_contiguous(&data, &[3, 3]).is_err()); |
| 333 | } |
| 334 | |
| 335 | #[test] |
| 336 | fn capsule_views_preserve_typed_payload_and_quantization() { |
| 337 | let cases = [ |
| 338 | (WeightDType::Bf16, AbiDType::Bf16, vec![0_u8; 8], None), |
| 339 | (WeightDType::Fp16, AbiDType::Fp16, vec![0_u8; 8], None), |
| 340 | ( |
| 341 | WeightDType::Fp8E4M3Fn, |
| 342 | AbiDType::Fp8E4M3Fn, |
| 343 | vec![0_u8; 4], |
| 344 | None, |
| 345 | ), |
| 346 | (WeightDType::Fp8E5M2, AbiDType::Fp8E5M2, vec![0_u8; 4], None), |
| 347 | ( |
| 348 | WeightDType::Int4, |
| 349 | AbiDType::Int4, |
| 350 | vec![0_u8; 2], |
| 351 | Some(QuantizationDescriptor { |
| 352 | scheme: "symmetric".to_string(), |
| 353 | axis: 0, |
| 354 | group_size: 4, |
| 355 | scales: vec![0.5], |
| 356 | zero_points: vec![], |
| 357 | packing: "int4-low-signed".to_string(), |
| 358 | }), |
| 359 | ), |
| 360 | ]; |
| 361 | for (dtype, expected_dtype, bytes, quant) in cases { |
| 362 | let mut tensors = HashMap::new(); |
| 363 | tensors.insert( |
| 364 | "w".to_string(), |
| 365 | CapsuleTensor { |
| 366 | dtype, |
| 367 | layout: TensorLayout::RowMajor, |
| 368 | shape: vec![2, 2], |
| 369 | logical_strides: vec![2, 1], |
| 370 | byte_range: 0..bytes.len(), |
| 371 | quant, |
| 372 | }, |
| 373 | ); |
| 374 | let capsule = ModelCapsule { |
| 375 | source_digest: source_digest(&bytes), |
| 376 | capsule_digest: capsule_digest(&bytes, &tensors), |
| 377 | bytes: Arc::from(bytes), |
| 378 | tensors, |
| 379 | }; |
| 380 | let view = TensorView::from_capsule(&capsule, "w").unwrap(); |
| 381 | assert_eq!(view.as_abi().descriptor.dtype, expected_dtype); |
| 382 | assert_eq!( |
| 383 | view.as_abi().descriptor.byte_len as usize, |
| 384 | capsule.bytes.len() |
| 385 | ); |
| 386 | assert_eq!(view.as_abi().address as *const u8, capsule.bytes.as_ptr()); |
| 387 | if dtype == WeightDType::Int4 { |
| 388 | assert_eq!(view.as_abi().descriptor.quant.scale_count, 1); |
| 389 | assert_eq!( |
| 390 | view.as_abi().descriptor.quant.packing, |
| 391 | AbiPacking::Int4LowNibbleFirstSigned |
| 392 | ); |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | #[test] |
| 398 | fn c_abi_layout_is_stable() { |
| 399 | assert_eq!(std::mem::size_of::<AbiQuantization>(), 48); |
| 400 | assert_eq!(std::mem::size_of::<TensorDescriptor>(), 136); |
| 401 | assert_eq!(std::mem::size_of::<TensorView>(), 144); |
| 402 | assert_eq!(std::mem::size_of::<ResidentTensor>(), 144); |
| 403 | } |
| 404 | } |