interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-inference-abi / src / capsule.rs

362 lines · 12425 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Weight capsule: raw payload bytes plus a tensor index and canonical digests.
17
18use sha2::{Digest, Sha256};
19use std::collections::HashMap;
20use std::fmt;
21use std::ops::Range;
22use std::sync::Arc;
23
24use crate::checkpoint::decode_bf16_to_fp32;
25
26/// Element type stored in a capsule tensor payload.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28pub enum WeightDType {
29 F32,
30 Bf16,
31 Fp16,
32 Fp8E4M3Fn,
33 Fp8E5M2,
34 Int8,
35 Int4,
36}
37
38impl WeightDType {
39 fn label(self) -> &'static str {
40 match self {
41 WeightDType::F32 => "f32",
42 WeightDType::Bf16 => "bf16",
43 WeightDType::Fp16 => "fp16",
44 WeightDType::Fp8E4M3Fn => "fp8e4m3fn",
45 WeightDType::Fp8E5M2 => "fp8e5m2",
46 WeightDType::Int8 => "int8",
47 WeightDType::Int4 => "int4",
48 }
49 }
50}
51
52/// Logical tensor layout, independent of packed byte encoding.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
54pub enum TensorLayout {
55 RowMajor,
56 ColumnMajor,
57 Strided,
58}
59
60impl TensorLayout {
61 fn label(self) -> &'static str {
62 match self {
63 Self::RowMajor => "row-major",
64 Self::ColumnMajor => "column-major",
65 Self::Strided => "strided",
66 }
67 }
68}
69
70/// Quantization metadata. IEEE dtypes use packing `"none"`.
71#[derive(Debug, Clone, PartialEq)]
72pub struct QuantizationDescriptor {
73 pub scheme: String,
74 pub axis: usize,
75 pub group_size: usize,
76 pub scales: Vec<f32>,
77 pub zero_points: Vec<i32>,
78 pub packing: String, // "none" for IEEE dtypes; INT4 uses an explicit nibble order and sign
79}
80
81/// One named tensor view into [`ModelCapsule::bytes`].
82#[derive(Debug, Clone, PartialEq)]
83pub struct CapsuleTensor {
84 pub dtype: WeightDType,
85 pub layout: TensorLayout,
86 pub shape: Vec<usize>,
87 pub logical_strides: Vec<usize>, // element strides for the selected layout
88 pub byte_range: Range<usize>, // into ModelCapsule::bytes, the whole file
89 pub quant: Option<QuantizationDescriptor>,
90}
91
92/// Immutable model payload plus its tensor index.
93#[derive(Debug, Clone, PartialEq)]
94pub struct ModelCapsule {
95 pub bytes: Arc<[u8]>,
96 pub source_digest: String, // lowercase hex sha256 of bytes
97 pub tensors: HashMap<String, CapsuleTensor>,
98 pub capsule_digest: String,
99}
100
101/// Failures when reading a tensor out of a capsule.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub enum CapsuleError {
104 MissingTensor(String),
105 UnsupportedDtype(String),
106 BadRange(String),
107}
108
109impl fmt::Display for CapsuleError {
110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111 match self {
112 CapsuleError::MissingTensor(name) => write!(f, "missing tensor {name}"),
113 CapsuleError::UnsupportedDtype(dtype) => write!(f, "unsupported dtype {dtype}"),
114 CapsuleError::BadRange(detail) => write!(f, "bad range {detail}"),
115 }
116 }
117}
118
119impl std::error::Error for CapsuleError {}
120
121impl ModelCapsule {
122 pub fn tensor(&self, name: &str) -> Result<&CapsuleTensor, CapsuleError> {
123 self.tensors
124 .get(name)
125 .ok_or_else(|| CapsuleError::MissingTensor(name.to_string()))
126 }
127
128 pub fn tensor_bytes(&self, name: &str) -> Result<&[u8], CapsuleError> {
129 let tensor = self.tensor(name)?;
130 let range = &tensor.byte_range;
131 if range.start > range.end || range.end > self.bytes.len() {
132 return Err(CapsuleError::BadRange(format!(
133 "{name} range {}-{} outside payload length {}",
134 range.start,
135 range.end,
136 self.bytes.len()
137 )));
138 }
139 Ok(&self.bytes[range.start..range.end])
140 }
141
142 /// Allocates. BF16 uses the existing decode_bf16_to_fp32 from checkpoint.rs (crate::checkpoint::decode_bf16_to_fp32). F32 interprets little-endian f32. Other dtypes return UnsupportedDtype. Do not store a decoded copy on the struct.
143 pub fn decode_fp32(&self, name: &str) -> Result<Vec<f32>, CapsuleError> {
144 let tensor = self.tensor(name)?;
145 let raw = self.tensor_bytes(name)?;
146 match tensor.dtype {
147 WeightDType::F32 => {
148 if raw.len() % 4 != 0 {
149 return Err(CapsuleError::BadRange(format!(
150 "{name} f32 payload length {} is not a multiple of 4",
151 raw.len()
152 )));
153 }
154 let mut out = Vec::with_capacity(raw.len() / 4);
155 for chunk in raw.chunks_exact(4) {
156 let bits = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
157 out.push(f32::from_bits(bits));
158 }
159 Ok(out)
160 }
161 WeightDType::Bf16 => Ok(decode_bf16_to_fp32(raw)),
162 other => Err(CapsuleError::UnsupportedDtype(other.label().to_string())),
163 }
164 }
165
166 pub fn owned_payload_len(&self) -> usize {
167 self.bytes.len()
168 }
169}
170
171fn sha256_hex(parts: &[&[u8]]) -> String {
172 let mut hasher = Sha256::new();
173 for part in parts {
174 hasher.update(part);
175 }
176 let digest = hasher.finalize();
177 let mut hex = String::with_capacity(digest.len() * 2);
178 for byte in digest {
179 hex.push_str(&format!("{byte:02x}"));
180 }
181 hex
182}
183
184/// Lowercase hex SHA-256 of `bytes`.
185pub fn source_digest(bytes: &[u8]) -> String {
186 sha256_hex(&[bytes])
187}
188
189/// Canonical capsule digest over the stored bytes and every tensor descriptor.
190/// The length-prefixed binary manifest is sorted by tensor name and versioned.
191pub fn capsule_digest(bytes: &[u8], tensors: &HashMap<String, CapsuleTensor>) -> String {
192 let mut names: Vec<&String> = tensors.keys().collect();
193 names.sort();
194 let mut manifest = Vec::new();
195 manifest.extend_from_slice(b"AIEN-CAPSULE-V1\0");
196 push_len(&mut manifest, names.len());
197 for name in names {
198 let tensor = &tensors[name];
199 push_bytes(&mut manifest, name.as_bytes());
200 push_bytes(&mut manifest, tensor.dtype.label().as_bytes());
201 push_bytes(&mut manifest, tensor.layout.label().as_bytes());
202 push_len(&mut manifest, tensor.shape.len());
203 for dim in &tensor.shape {
204 push_len(&mut manifest, *dim);
205 }
206 push_len(&mut manifest, tensor.logical_strides.len());
207 for stride in &tensor.logical_strides {
208 push_len(&mut manifest, *stride);
209 }
210 push_len(&mut manifest, tensor.byte_range.start);
211 push_len(&mut manifest, tensor.byte_range.end);
212 match &tensor.quant {
213 None => manifest.push(0),
214 Some(quant) => {
215 manifest.push(1);
216 push_bytes(&mut manifest, quant.scheme.as_bytes());
217 push_len(&mut manifest, quant.axis);
218 push_len(&mut manifest, quant.group_size);
219 push_len(&mut manifest, quant.scales.len());
220 for scale in &quant.scales {
221 manifest.extend_from_slice(&scale.to_bits().to_le_bytes());
222 }
223 push_len(&mut manifest, quant.zero_points.len());
224 for zero_point in &quant.zero_points {
225 manifest.extend_from_slice(&zero_point.to_le_bytes());
226 }
227 push_bytes(&mut manifest, quant.packing.as_bytes());
228 }
229 }
230 }
231 sha256_hex(&[&manifest, bytes])
232}
233
234fn push_len(buf: &mut Vec<u8>, value: usize) {
235 buf.extend_from_slice(&(value as u64).to_le_bytes());
236}
237
238fn push_bytes(buf: &mut Vec<u8>, value: &[u8]) {
239 push_len(buf, value.len());
240 buf.extend_from_slice(value);
241}
242
243/// Element strides for row-major (C) layout. The last axis has stride 1.
244pub fn row_major_strides(shape: &[usize]) -> Vec<usize> {
245 let rank = shape.len();
246 let mut strides = vec![0; rank];
247 if rank == 0 {
248 return strides;
249 }
250 strides[rank - 1] = 1;
251 for index in (0..rank - 1).rev() {
252 strides[index] = strides[index + 1] * shape[index + 1];
253 }
254 strides
255}
256
257#[cfg(test)]
258mod tests {
259 use super::*;
260
261 #[test]
262 fn source_digest_of_abc_matches_well_known_sha256() {
263 let digest = source_digest(b"abc");
264 assert_eq!(
265 digest,
266 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
267 );
268 }
269
270 fn sample_tensor(
271 dtype: WeightDType,
272 shape: Vec<usize>,
273 byte_range: Range<usize>,
274 ) -> CapsuleTensor {
275 let logical_strides = row_major_strides(&shape);
276 CapsuleTensor {
277 dtype,
278 layout: TensorLayout::RowMajor,
279 shape,
280 logical_strides,
281 byte_range,
282 quant: None,
283 }
284 }
285
286 #[test]
287 fn capsule_digest_is_stable_across_hashmap_insertion_order() {
288 let bytes = b"raw-payload-bytes";
289 let tensor_a = sample_tensor(WeightDType::Bf16, vec![2], 0..2);
290 let tensor_b = sample_tensor(WeightDType::F32, vec![1, 1], 2..6);
291
292 let mut first = HashMap::new();
293 first.insert("zeta".to_string(), tensor_a.clone());
294 first.insert("alpha".to_string(), tensor_b.clone());
295
296 let mut second = HashMap::new();
297 second.insert("alpha".to_string(), tensor_b.clone());
298 second.insert("zeta".to_string(), tensor_a.clone());
299
300 let digest_first = capsule_digest(bytes, &first);
301 let digest_second = capsule_digest(bytes, &second);
302 assert_eq!(digest_first, digest_second);
303
304 let mut changed = second.clone();
305 changed.get_mut("alpha").unwrap().logical_strides = vec![2, 1];
306 assert_ne!(digest_first, capsule_digest(bytes, &changed));
307
308 let mut changed = second;
309 changed.get_mut("zeta").unwrap().quant = Some(QuantizationDescriptor {
310 scheme: "test".to_string(),
311 axis: 0,
312 group_size: 2,
313 scales: vec![1.0],
314 zero_points: vec![0],
315 packing: "none".to_string(),
316 });
317 assert_ne!(digest_first, capsule_digest(bytes, &changed));
318 }
319
320 #[test]
321 fn decode_fp32_bf16_one_and_owned_len_and_missing_tensor() {
322 let raw = [0x80u8, 0x3f];
323 let bytes: Arc<[u8]> = Arc::from(raw.as_slice());
324 let mut tensors = HashMap::new();
325 tensors.insert(
326 "w".to_string(),
327 sample_tensor(WeightDType::Bf16, vec![1], 0..2),
328 );
329 let capsule = ModelCapsule {
330 source_digest: source_digest(&bytes),
331 capsule_digest: capsule_digest(&bytes, &tensors),
332 bytes: Arc::clone(&bytes),
333 tensors,
334 };
335
336 let decoded = capsule.decode_fp32("w").unwrap();
337 assert_eq!(decoded.len(), 1);
338 assert!((decoded[0] - 1.0).abs() < 1e-6);
339 assert_eq!(capsule.owned_payload_len(), capsule.bytes.len());
340 assert_eq!(capsule.owned_payload_len(), 2);
341
342 match capsule.tensor("missing") {
343 Err(CapsuleError::MissingTensor(name)) => assert_eq!(name, "missing"),
344 other => panic!("expected MissingTensor, got {other:?}"),
345 }
346 match capsule.decode_fp32("missing") {
347 Err(CapsuleError::MissingTensor(name)) => assert_eq!(name, "missing"),
348 other => panic!("expected MissingTensor, got {other:?}"),
349 }
350 match capsule.tensor_bytes("missing") {
351 Err(CapsuleError::MissingTensor(name)) => assert_eq!(name, "missing"),
352 other => panic!("expected MissingTensor, got {other:?}"),
353 }
354 }
355
356 #[test]
357 fn row_major_strides_match_c_order() {
358 assert_eq!(row_major_strides(&[]), Vec::<usize>::new());
359 assert_eq!(row_major_strides(&[4]), vec![1]);
360 assert_eq!(row_major_strides(&[2, 3, 4]), vec![12, 4, 1]);
361 }
362}