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 / bitnet_omega / gguf_ref.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 | //! Test tool only, never product: reads the ternary tensors of Microsoft's I2_S gguf |
| 17 | //! (`~/models/BitNet-b1.58-2B-4T/ggml-model-i2_s.gguf`) so the T1 test can count how many of our |
| 18 | //! trits agree with theirs. Nothing of theirs is run; the file is parsed here. |
| 19 | //! |
| 20 | //! The I2_S layout, read from their source (spec 7 item 3, resolved by reading): |
| 21 | //! - `3rdparty/llama.cpp/ggml/src/ggml-cpu/quants.c:1333-1354` (`dequantize_row_i2_s`) and |
| 22 | //! `src/ggml-bitnet-mad.cpp:51-96` (`quantize_i2_s`, x86 branch, `QK_I2_S 128` at `:12`): |
| 23 | //! the flat element stream is cut into blocks of 128 (64 on an ARM build, `:14`); block `b` is |
| 24 | //! 32 bytes; element `j` of the block sits in byte `b*32 + j%32` at bits `6 - 2*(j/32)`. |
| 25 | //! - Codes: 0 -> -1, 1 -> 0, 2 -> +1 (`quants.c:1334` `map2bit`, `ggml-bitnet-mad.cpp:68-70`). |
| 26 | //! - Tail: one f32 scale at byte `n/4` (`ggml-bitnet-mad.cpp:90-91`), padded to 32 bytes. |
| 27 | //! - Element order: ggml row major, `ne0` (the input dimension) fastest, so row `r` of the |
| 28 | //! `[out][in]` matrix is elements `r*in .. (r+1)*in`. |
| 29 | |
| 30 | use std::collections::HashMap; |
| 31 | use std::io::Read; |
| 32 | use std::path::Path; |
| 33 | |
| 34 | /// One tensor's entry in the gguf header. |
| 35 | #[derive(Debug, Clone)] |
| 36 | pub struct GgufTensor { |
| 37 | pub ggml_type: u32, |
| 38 | pub dims: Vec<u64>, |
| 39 | /// Absolute byte offset in the file. |
| 40 | pub offset: u64, |
| 41 | } |
| 42 | |
| 43 | /// ggml type id of I2_S (spec 3.3, read from the header's tensor table). |
| 44 | pub const GGML_TYPE_I2_S: u32 = 36; |
| 45 | |
| 46 | struct Cursor<R: Read> { |
| 47 | r: R, |
| 48 | pos: u64, |
| 49 | } |
| 50 | |
| 51 | impl<R: Read> Cursor<R> { |
| 52 | fn bytes(&mut self, n: usize) -> Result<Vec<u8>, String> { |
| 53 | let mut b = vec![0u8; n]; |
| 54 | self.r.read_exact(&mut b).map_err(|e| e.to_string())?; |
| 55 | self.pos += n as u64; |
| 56 | Ok(b) |
| 57 | } |
| 58 | fn u32(&mut self) -> Result<u32, String> { |
| 59 | Ok(u32::from_le_bytes(self.bytes(4)?.try_into().unwrap())) |
| 60 | } |
| 61 | fn u64(&mut self) -> Result<u64, String> { |
| 62 | Ok(u64::from_le_bytes(self.bytes(8)?.try_into().unwrap())) |
| 63 | } |
| 64 | fn string(&mut self) -> Result<String, String> { |
| 65 | let n = self.u64()? as usize; |
| 66 | String::from_utf8(self.bytes(n)?).map_err(|e| e.to_string()) |
| 67 | } |
| 68 | /// Skips one value of gguf type `t`, returning it as u64 when it is a scalar integer. |
| 69 | fn value(&mut self, t: u32) -> Result<Option<u64>, String> { |
| 70 | Ok(match t { |
| 71 | 0 | 1 | 7 => Some(self.bytes(1)?[0] as u64), |
| 72 | 2 | 3 => Some(u16::from_le_bytes(self.bytes(2)?.try_into().unwrap()) as u64), |
| 73 | 4 | 5 => Some(self.u32()? as u64), |
| 74 | 6 => { |
| 75 | self.bytes(4)?; |
| 76 | None |
| 77 | } |
| 78 | 8 => { |
| 79 | self.string()?; |
| 80 | None |
| 81 | } |
| 82 | 9 => { |
| 83 | let (et, n) = (self.u32()?, self.u64()?); |
| 84 | for _ in 0..n { |
| 85 | self.value(et)?; |
| 86 | } |
| 87 | None |
| 88 | } |
| 89 | 10 | 11 => Some(self.u64()?), |
| 90 | 12 => { |
| 91 | self.bytes(8)?; |
| 92 | None |
| 93 | } |
| 94 | other => return Err(format!("gguf value type {other} unknown")), |
| 95 | }) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | /// The tensor table of a gguf v3 file. |
| 100 | pub fn read_header(path: &Path) -> Result<HashMap<String, GgufTensor>, String> { |
| 101 | let f = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; |
| 102 | let mut c = Cursor { |
| 103 | r: std::io::BufReader::new(f), |
| 104 | pos: 0, |
| 105 | }; |
| 106 | if c.bytes(4)? != b"GGUF" { |
| 107 | return Err("not a gguf file".into()); |
| 108 | } |
| 109 | let version = c.u32()?; |
| 110 | if version != 3 { |
| 111 | return Err(format!("gguf version {version}, expected 3")); |
| 112 | } |
| 113 | let (n_tensors, n_kv) = (c.u64()?, c.u64()?); |
| 114 | let mut alignment = 32u64; |
| 115 | for _ in 0..n_kv { |
| 116 | let key = c.string()?; |
| 117 | let t = c.u32()?; |
| 118 | let v = c.value(t)?; |
| 119 | if key == "general.alignment" { |
| 120 | alignment = v.ok_or("general.alignment is not an integer")?; |
| 121 | } |
| 122 | } |
| 123 | let mut infos = Vec::new(); |
| 124 | for _ in 0..n_tensors { |
| 125 | let name = c.string()?; |
| 126 | let n_dims = c.u32()?; |
| 127 | let dims = (0..n_dims) |
| 128 | .map(|_| c.u64()) |
| 129 | .collect::<Result<Vec<_>, _>>()?; |
| 130 | let ggml_type = c.u32()?; |
| 131 | let offset = c.u64()?; |
| 132 | infos.push((name, dims, ggml_type, offset)); |
| 133 | } |
| 134 | let data_start = c.pos.div_ceil(alignment) * alignment; |
| 135 | Ok(infos |
| 136 | .into_iter() |
| 137 | .map(|(name, dims, ggml_type, offset)| { |
| 138 | ( |
| 139 | name, |
| 140 | GgufTensor { |
| 141 | ggml_type, |
| 142 | dims, |
| 143 | offset: data_start + offset, |
| 144 | }, |
| 145 | ) |
| 146 | }) |
| 147 | .collect()) |
| 148 | } |
| 149 | |
| 150 | /// The trits and the f32 scale of one I2_S tensor of `n` elements, decoded with block size |
| 151 | /// `block` (128 on x86, 64 on ARM). |
| 152 | pub fn read_i2s(path: &Path, t: &GgufTensor, block: usize) -> Result<(Vec<i8>, f32), String> { |
| 153 | use std::os::unix::fs::FileExt; |
| 154 | if t.ggml_type != GGML_TYPE_I2_S { |
| 155 | return Err(format!("ggml type {}, not I2_S", t.ggml_type)); |
| 156 | } |
| 157 | let n = t.dims.iter().product::<u64>() as usize; |
| 158 | let f = std::fs::File::open(path).map_err(|e| e.to_string())?; |
| 159 | let mut raw = vec![0u8; n / 4 + 4]; |
| 160 | f.read_exact_at(&mut raw, t.offset) |
| 161 | .map_err(|e| e.to_string())?; |
| 162 | let scale = f32::from_le_bytes(raw[n / 4..n / 4 + 4].try_into().unwrap()); |
| 163 | let group = block / 4; |
| 164 | let mut trits = vec![0i8; n]; |
| 165 | for (i, out) in trits.iter_mut().enumerate() { |
| 166 | let (b, j) = (i / block, i % block); |
| 167 | let byte = raw[b * group + j % group]; |
| 168 | let code = (byte >> (6 - 2 * (j / group))) & 3; |
| 169 | *out = match code { |
| 170 | 0 => -1, |
| 171 | 1 => 0, |
| 172 | 2 => 1, |
| 173 | _ => return Err(format!("element {i}: code 3 is not a trit")), |
| 174 | }; |
| 175 | } |
| 176 | Ok((trits, scale)) |
| 177 | } |