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.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 | //! BitNet b1.58 2B-4T on AIEN's own GPU engine (Omega), ternary stage T1: config, loader, |
| 17 | //! ternariser, packer, 8-bit word table builder. Host only: no launch, no chip. |
| 18 | //! |
| 19 | //! Design: `~/handoffs/2026-10-15-ternary-engine-design.md` (section 3.3, stage table row T1). |
| 20 | //! Model spec (the ground truth this file cites as `spec`): `~/.t3/projects/research/ternary-oracle/spec.md`. |
| 21 | //! This file is new beside `qwen3_dense_omega.rs` and `qwen3_moe_omega.rs`; it reuses their |
| 22 | //! tensor sources, RSS probe and FP8 upload rule and edits neither. |
| 23 | //! |
| 24 | //! - [`BitNetConfig`]: the shape from `config.json`, refused by name unless it is the BitNet |
| 25 | //! family this engine implements: `model_type` bitnet, `hidden_act` relu2, tied embeddings, |
| 26 | //! `torch_dtype` bfloat16, `quantization_config` exactly {bitnet, autobitlinear, online}. |
| 27 | //! - [`absmean_ternarise`]: the quantisation rule of the bf16 master as Microsoft's reference |
| 28 | //! converter computes it (spec 2.1, `REF/convert_checkpoint.py:23-27`, read only): every |
| 29 | //! intermediate a bf16 tensor, so every step rounded to bf16. The 21 scales the spec lists from |
| 30 | //! the reference int2 checkpoint equal ours (real-checkpoint test). Hugging Face's online mode |
| 31 | //! differs: `WeightQuant.forward` casts to f32 first (`HF/integrations/bitnet.py:211`), so a |
| 32 | //! weight near the half-scale boundary can ternarise differently there. One scale per |
| 33 | //! projection (q, k, v, o, gate, up, down: 7 per layer), never per fused matrix. |
| 34 | //! - [`pack_trits`]: omega's 2-bit trit code (`omega/src/algebra/oma_trit.h`: bit0 plus plane, |
| 35 | //! bit1 minus plane, 0b11 invalid), 16 trits per little-endian u32, row major |
| 36 | //! ([`TERN_LAYOUT_ID`]). q|k|v and gate|up are stacked row blocks, each block with its own |
| 37 | //! [`TernSegment`] scale, so a kernel never indexes scales by thirds (the reference decode |
| 38 | //! kernel's bug, spec 2.3). |
| 39 | //! - [`build_fp8_table`]: the 8-bit word table (design 3.1 KT4 option A): the tied bf16 |
| 40 | //! embedding quantised to e4m3 in 128x128 blocks, scale = amax / 448 rounded to bf16, |
| 41 | //! round-to-nearest-even, saturating (the rule of omega's `tests/gpu_lmhead_fp8_study.c`). |
| 42 | //! - The streaming loader: no f32 image of the model. Every projection is read as raw bf16 into |
| 43 | //! one reused buffer, ternarised and packed into two more reused buffers, and handed to a |
| 44 | //! [`TernUploader`]. The host keeps the bf16 embedding (the input lookup reads one row) and |
| 45 | //! the f32 norms. Peak host memory is the embedding plus the buffers: |
| 46 | //! [`bitnet_loader_transient_bytes`]. |
| 47 | //! |
| 48 | //! The Q and K rows stay in the checkpoint (Hugging Face) order: the engine rotates them with |
| 49 | //! half-split RoPE pairs (dim j with j + 64, spec 1.3). Microsoft's int2 checkpoint permutes them |
| 50 | //! for adjacent pairs instead; this loader does not. |
| 51 | |
| 52 | use std::path::Path; |
| 53 | use std::sync::Arc; |
| 54 | use std::time::Instant; |
| 55 | |
| 56 | use rayon::prelude::*; |
| 57 | |
| 58 | use crate::qwen3_dense_omega::{check_fp8_upload, DenseGemv}; |
| 59 | use crate::qwen3_moe::{bf16_to_f32, f32_to_bf16, f32_to_fp8_e4m3fn, Shard, FP8_BLOCK}; |
| 60 | use crate::qwen3_moe_omega::{ |
| 61 | peak_rss_bytes, KvGeometry, ShardSource, TensorSource, KV_BLOCK_SIZE, |
| 62 | }; |
| 63 | |
| 64 | #[cfg(any(test, feature = "host-test-engine"))] |
| 65 | pub mod test_support; |
| 66 | |
| 67 | #[cfg(test)] |
| 68 | mod gguf_ref; |
| 69 | |
| 70 | #[cfg(test)] |
| 71 | mod tests; |
| 72 | |
| 73 | // The loader reads little-endian bf16 words in place and packs little-endian u32 words. |
| 74 | const _: () = assert!( |
| 75 | cfg!(target_endian = "little"), |
| 76 | "the BitNet loader needs a little-endian host" |
| 77 | ); |
| 78 | |
| 79 | /// The packed weight layout every uploader receives, recorded in sealed goldens: omega's 2-bit |
| 80 | /// trit code, 16 trits per u32 word (trit `c % 16` at bits `2*(c % 16)`, plus plane low), |
| 81 | /// `[n][k / 16]` words row major, rows in checkpoint order (no RoPE permutation), q|k|v and |
| 82 | /// gate|up stacked as row blocks with one scale each. |
| 83 | pub const TERN_LAYOUT_ID: &str = "omega-trit2-rm16-hfrows-v1"; |
| 84 | |
| 85 | /// Trits per packed u32 word. |
| 86 | pub const TRITS_PER_WORD: usize = 16; |
| 87 | |
| 88 | /// sha256 of the bf16 master `model.safetensors` (microsoft/bitnet-b1.58-2B-4T-bf16 at revision |
| 89 | /// 276681394656abdadb8e80e5b2c3db5e5d7fcaff, `weights.md` section 1). Checked by the real |
| 90 | /// checkpoint runs, never silently skipped there. |
| 91 | pub const BITNET_2B4T_SAFETENSORS_SHA256: &str = |
| 92 | "529637ff6dab1f5890767356928693f69ffe61d3b6040a43de9306b37bfd5ae1"; |
| 93 | |
| 94 | /// sha256 of the same revision's `tokenizer.json`. |
| 95 | pub const BITNET_2B4T_TOKENIZER_SHA256: &str = |
| 96 | "e134af98b985517b4f068e3755ae90d4e9cd2d45d328325dc503f1c6b2d06cc7"; |
| 97 | |
| 98 | // --------------------------------------------------------------------------- |
| 99 | // Model shape, read from the checkpoint. |
| 100 | // --------------------------------------------------------------------------- |
| 101 | |
| 102 | /// The four ternary matrices of a layer, as the engine stacks them. |
| 103 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 104 | pub enum TernTensor { |
| 105 | /// `[q_dim + 2 * kv_dim][hidden]`: q rows, then k rows, then v rows. |
| 106 | Qkv, |
| 107 | /// `[hidden][q_dim]`. |
| 108 | O, |
| 109 | /// `[2 * intermediate][hidden]`: gate rows, then up rows. |
| 110 | GateUp, |
| 111 | /// `[hidden][intermediate]`. |
| 112 | Down, |
| 113 | } |
| 114 | |
| 115 | impl TernTensor { |
| 116 | pub const ALL: [TernTensor; 4] = [Self::Qkv, Self::O, Self::GateUp, Self::Down]; |
| 117 | |
| 118 | pub fn name(self) -> &'static str { |
| 119 | match self { |
| 120 | Self::Qkv => "qkv", |
| 121 | Self::O => "o", |
| 122 | Self::GateUp => "gate_up", |
| 123 | Self::Down => "down", |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | /// One checkpoint projection: the unit that owns a scale. |
| 129 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 130 | pub enum TernPart { |
| 131 | Q, |
| 132 | K, |
| 133 | V, |
| 134 | O, |
| 135 | Gate, |
| 136 | Up, |
| 137 | Down, |
| 138 | } |
| 139 | |
| 140 | impl TernPart { |
| 141 | /// The checkpoint tensor name of this projection in `layer`. |
| 142 | pub fn tensor_name(self, layer: usize) -> String { |
| 143 | let p = format!("model.layers.{layer}"); |
| 144 | match self { |
| 145 | Self::Q => format!("{p}.self_attn.q_proj.weight"), |
| 146 | Self::K => format!("{p}.self_attn.k_proj.weight"), |
| 147 | Self::V => format!("{p}.self_attn.v_proj.weight"), |
| 148 | Self::O => format!("{p}.self_attn.o_proj.weight"), |
| 149 | Self::Gate => format!("{p}.mlp.gate_proj.weight"), |
| 150 | Self::Up => format!("{p}.mlp.up_proj.weight"), |
| 151 | Self::Down => format!("{p}.mlp.down_proj.weight"), |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | pub fn name(self) -> &'static str { |
| 156 | match self { |
| 157 | Self::Q => "q", |
| 158 | Self::K => "k", |
| 159 | Self::V => "v", |
| 160 | Self::O => "o", |
| 161 | Self::Gate => "gate", |
| 162 | Self::Up => "up", |
| 163 | Self::Down => "down", |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | /// The BitNet shape, read from `config.json` and held to what this engine implements. |
| 169 | #[derive(Debug, Clone, PartialEq)] |
| 170 | pub struct BitNetConfig { |
| 171 | pub layers: usize, |
| 172 | pub hidden: usize, |
| 173 | pub q_heads: usize, |
| 174 | pub kv_heads: usize, |
| 175 | pub head_dim: usize, |
| 176 | pub intermediate: usize, |
| 177 | pub vocab: usize, |
| 178 | pub rms_eps: f32, |
| 179 | pub rope_theta: f32, |
| 180 | pub max_position: usize, |
| 181 | pub bos_token_id: u32, |
| 182 | /// Ids generation stops on (`generation_config.json` eos list, else `config.json` eos). |
| 183 | pub eos_token_ids: Vec<u32>, |
| 184 | } |
| 185 | |
| 186 | /// `config.json` keys this reader knows. Anything else is refused by name: a key it does not |
| 187 | /// understand could change the maths. |
| 188 | const KNOWN_KEYS: &[&str] = &[ |
| 189 | "architectures", |
| 190 | "auto_map", |
| 191 | "bos_token_id", |
| 192 | "eos_token_id", |
| 193 | "hidden_act", |
| 194 | "hidden_size", |
| 195 | "initializer_range", |
| 196 | "intermediate_size", |
| 197 | "max_position_embeddings", |
| 198 | "model_type", |
| 199 | "rms_norm_eps", |
| 200 | "num_attention_heads", |
| 201 | "num_hidden_layers", |
| 202 | "num_key_value_heads", |
| 203 | "rope_theta", |
| 204 | "tie_word_embeddings", |
| 205 | "torch_dtype", |
| 206 | "use_cache", |
| 207 | "vocab_size", |
| 208 | "quantization_config", |
| 209 | // Accepted only at their neutral values (checked below). |
| 210 | "attention_bias", |
| 211 | "attention_dropout", |
| 212 | "rope_scaling", |
| 213 | "head_dim", |
| 214 | "pad_token_id", |
| 215 | "transformers_version", |
| 216 | ]; |
| 217 | |
| 218 | fn refused(what: impl std::fmt::Display) -> String { |
| 219 | format!("config refused: {what}") |
| 220 | } |
| 221 | |
| 222 | fn eos_ids(v: &serde_json::Value) -> Option<Vec<u32>> { |
| 223 | match v { |
| 224 | serde_json::Value::Number(n) => Some(vec![u32::try_from(n.as_u64()?).ok()?]), |
| 225 | serde_json::Value::Array(a) => a |
| 226 | .iter() |
| 227 | .map(|x| x.as_u64().and_then(|x| u32::try_from(x).ok())) |
| 228 | .collect(), |
| 229 | _ => None, |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | impl BitNetConfig { |
| 234 | /// `config.json` and, when present, `generation_config.json` of a checkpoint directory. |
| 235 | pub fn from_checkpoint(dir: &Path) -> Result<Self, String> { |
| 236 | let path = dir.join("config.json"); |
| 237 | let text = |
| 238 | std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?; |
| 239 | let gen_path = dir.join("generation_config.json"); |
| 240 | let gen = match std::fs::read_to_string(&gen_path) { |
| 241 | Ok(t) => Some(t), |
| 242 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, |
| 243 | Err(e) => return Err(format!("{}: {e}", gen_path.display())), |
| 244 | }; |
| 245 | Self::from_json(&text, gen.as_deref()).map_err(|e| format!("{}: {e}", path.display())) |
| 246 | } |
| 247 | |
| 248 | pub fn from_json(config_json: &str, generation_json: Option<&str>) -> Result<Self, String> { |
| 249 | let raw: serde_json::Value = |
| 250 | serde_json::from_str(config_json).map_err(|e| format!("config.json: {e}"))?; |
| 251 | let obj = raw |
| 252 | .as_object() |
| 253 | .ok_or_else(|| refused("config.json is not an object"))?; |
| 254 | let get = |key: &str| obj.get(key).filter(|v| !v.is_null()); |
| 255 | |
| 256 | // The four family rules first, each refused by name with the value found. |
| 257 | let named = |key: &str, want: serde_json::Value, why: &str| -> Result<(), String> { |
| 258 | match get(key) { |
| 259 | Some(v) if *v == want => Ok(()), |
| 260 | other => Err(refused(format!( |
| 261 | "{key} {}, this engine implements {want} ({why})", |
| 262 | other.map_or("absent".to_string(), |v| v.to_string()) |
| 263 | ))), |
| 264 | } |
| 265 | }; |
| 266 | named( |
| 267 | "model_type", |
| 268 | serde_json::json!("bitnet"), |
| 269 | "BitNet b1.58 only", |
| 270 | )?; |
| 271 | named( |
| 272 | "hidden_act", |
| 273 | serde_json::json!("relu2"), |
| 274 | "squared ReLU on the gate", |
| 275 | )?; |
| 276 | named( |
| 277 | "tie_word_embeddings", |
| 278 | serde_json::json!(true), |
| 279 | "the embedding is the output head", |
| 280 | )?; |
| 281 | named( |
| 282 | "torch_dtype", |
| 283 | serde_json::json!("bfloat16"), |
| 284 | "the loader streams the bf16 master", |
| 285 | )?; |
| 286 | named( |
| 287 | "quantization_config", |
| 288 | serde_json::json!({ |
| 289 | "quant_method": "bitnet", |
| 290 | "linear_class": "autobitlinear", |
| 291 | "quantization_mode": "online" |
| 292 | }), |
| 293 | "ternary weights computed from the bf16 master at load", |
| 294 | )?; |
| 295 | if let Some(a) = get("architectures") { |
| 296 | if *a != serde_json::json!(["BitNetForCausalLM"]) { |
| 297 | return Err(refused(format!( |
| 298 | "architectures {a}, this engine implements [\"BitNetForCausalLM\"]" |
| 299 | ))); |
| 300 | } |
| 301 | } |
| 302 | for key in obj.keys() { |
| 303 | if !KNOWN_KEYS.contains(&key.as_str()) { |
| 304 | return Err(refused(format!("field {key:?} is not implemented"))); |
| 305 | } |
| 306 | } |
| 307 | // Neutral values only. |
| 308 | if get("attention_bias").is_some_and(|v| *v != serde_json::json!(false)) { |
| 309 | return Err(refused("attention_bias must be false (no biases)")); |
| 310 | } |
| 311 | if get("attention_dropout").is_some_and(|v| v.as_f64() != Some(0.0)) { |
| 312 | return Err(refused("attention_dropout must be 0")); |
| 313 | } |
| 314 | if let Some(r) = get("rope_scaling") { |
| 315 | return Err(refused(format!( |
| 316 | "rope_scaling {r} is not implemented (plain RoPE only)" |
| 317 | ))); |
| 318 | } |
| 319 | |
| 320 | let int = |key: &str| -> Result<usize, String> { |
| 321 | get(key) |
| 322 | .and_then(|v| v.as_u64()) |
| 323 | .map(|v| v as usize) |
| 324 | .ok_or_else(|| refused(format!("{key} missing or not a whole number"))) |
| 325 | }; |
| 326 | let float = |key: &str| -> Result<f64, String> { |
| 327 | get(key) |
| 328 | .and_then(|v| v.as_f64()) |
| 329 | .filter(|v| v.is_finite() && *v > 0.0) |
| 330 | .ok_or_else(|| refused(format!("{key} missing or not a positive number"))) |
| 331 | }; |
| 332 | let hidden = int("hidden_size")?; |
| 333 | let q_heads = int("num_attention_heads")?; |
| 334 | if q_heads == 0 || !hidden.is_multiple_of(q_heads) { |
| 335 | return Err(refused(format!( |
| 336 | "hidden_size {hidden} is not a whole number of {q_heads} heads" |
| 337 | ))); |
| 338 | } |
| 339 | let head_dim = hidden / q_heads; |
| 340 | if let Some(h) = get("head_dim") { |
| 341 | if h.as_u64() != Some(head_dim as u64) { |
| 342 | return Err(refused(format!( |
| 343 | "head_dim {h}, hidden_size / num_attention_heads is {head_dim}" |
| 344 | ))); |
| 345 | } |
| 346 | } |
| 347 | let bos_token_id = get("bos_token_id") |
| 348 | .and_then(|v| v.as_u64()) |
| 349 | .and_then(|v| u32::try_from(v).ok()) |
| 350 | .ok_or_else(|| refused("bos_token_id missing"))?; |
| 351 | let mut eos_token_ids = match get("eos_token_id") { |
| 352 | None => return Err(refused("eos_token_id missing")), |
| 353 | Some(v) => eos_ids(v).ok_or_else(|| { |
| 354 | refused(format!( |
| 355 | "eos_token_id {v} is not a token id or a list of them" |
| 356 | )) |
| 357 | })?, |
| 358 | }; |
| 359 | if let Some(g) = generation_json { |
| 360 | let g: serde_json::Value = |
| 361 | serde_json::from_str(g).map_err(|e| format!("generation_config.json: {e}"))?; |
| 362 | if let Some(v) = g.get("eos_token_id") { |
| 363 | eos_token_ids = eos_ids(v).ok_or_else(|| { |
| 364 | refused(format!( |
| 365 | "generation_config.json eos_token_id {v} is not a token id or a list of them" |
| 366 | )) |
| 367 | })?; |
| 368 | } |
| 369 | } |
| 370 | let cfg = Self { |
| 371 | layers: int("num_hidden_layers")?, |
| 372 | hidden, |
| 373 | q_heads, |
| 374 | kv_heads: int("num_key_value_heads")?, |
| 375 | head_dim, |
| 376 | intermediate: int("intermediate_size")?, |
| 377 | vocab: int("vocab_size")?, |
| 378 | rms_eps: float("rms_norm_eps")? as f32, |
| 379 | rope_theta: float("rope_theta")? as f32, |
| 380 | max_position: int("max_position_embeddings")?, |
| 381 | bos_token_id, |
| 382 | eos_token_ids, |
| 383 | }; |
| 384 | cfg.validate()?; |
| 385 | Ok(cfg) |
| 386 | } |
| 387 | |
| 388 | /// What this engine can pack and run: whole GQA groups, an even head width (RoPE pairs), |
| 389 | /// every `k` a whole number of packed words, the word table on omega's FP8 block grid. |
| 390 | pub fn validate(&self) -> Result<(), String> { |
| 391 | if self.layers == 0 || self.vocab == 0 || self.kv_heads == 0 || self.intermediate == 0 { |
| 392 | return Err(refused("zero layers, vocab, kv heads or intermediate")); |
| 393 | } |
| 394 | if self.q_heads * self.head_dim != self.hidden { |
| 395 | return Err(refused(format!( |
| 396 | "{} heads of {} is not hidden {}", |
| 397 | self.q_heads, self.head_dim, self.hidden |
| 398 | ))); |
| 399 | } |
| 400 | if !self.q_heads.is_multiple_of(self.kv_heads) { |
| 401 | return Err(refused(format!( |
| 402 | "{} query heads over {} kv heads is not a whole GQA group", |
| 403 | self.q_heads, self.kv_heads |
| 404 | ))); |
| 405 | } |
| 406 | if !self.head_dim.is_multiple_of(2) { |
| 407 | return Err(refused(format!( |
| 408 | "head_dim {} is odd (RoPE rotates pairs)", |
| 409 | self.head_dim |
| 410 | ))); |
| 411 | } |
| 412 | for (what, k) in [ |
| 413 | ("hidden_size", self.hidden), |
| 414 | ("intermediate_size", self.intermediate), |
| 415 | ] { |
| 416 | if !k.is_multiple_of(TRITS_PER_WORD) { |
| 417 | return Err(refused(format!( |
| 418 | "{what} {k} is not a multiple of {TRITS_PER_WORD} (trits per packed word)" |
| 419 | ))); |
| 420 | } |
| 421 | } |
| 422 | if self.eos_token_ids.is_empty() { |
| 423 | return Err(refused( |
| 424 | "eos_token_id is an empty list: generation could never stop", |
| 425 | )); |
| 426 | } |
| 427 | if self.bos_token_id as usize >= self.vocab |
| 428 | || self.eos_token_ids.iter().any(|&e| e as usize >= self.vocab) |
| 429 | { |
| 430 | return Err(refused("bos or eos id outside the vocabulary")); |
| 431 | } |
| 432 | aien_omega_fp8::check_shape(1, self.vocab, self.hidden) |
| 433 | .map_err(|e| refused(format!("word table [{}][{}]: {e}", self.vocab, self.hidden))) |
| 434 | } |
| 435 | |
| 436 | pub fn q_dim(&self) -> usize { |
| 437 | self.q_heads * self.head_dim |
| 438 | } |
| 439 | |
| 440 | pub fn kv_dim(&self) -> usize { |
| 441 | self.kv_heads * self.head_dim |
| 442 | } |
| 443 | |
| 444 | /// The projections stacked into `what`, in row order, with their row counts. |
| 445 | pub fn parts(&self, what: TernTensor) -> Vec<(TernPart, usize)> { |
| 446 | match what { |
| 447 | TernTensor::Qkv => vec![ |
| 448 | (TernPart::Q, self.q_dim()), |
| 449 | (TernPart::K, self.kv_dim()), |
| 450 | (TernPart::V, self.kv_dim()), |
| 451 | ], |
| 452 | TernTensor::O => vec![(TernPart::O, self.hidden)], |
| 453 | TernTensor::GateUp => vec![ |
| 454 | (TernPart::Gate, self.intermediate), |
| 455 | (TernPart::Up, self.intermediate), |
| 456 | ], |
| 457 | TernTensor::Down => vec![(TernPart::Down, self.hidden)], |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | /// `(n, k)` of a stacked matrix. |
| 462 | pub fn shape(&self, what: TernTensor) -> (usize, usize) { |
| 463 | let n = self.parts(what).iter().map(|p| p.1).sum(); |
| 464 | let k = match what { |
| 465 | TernTensor::Qkv | TernTensor::GateUp => self.hidden, |
| 466 | TernTensor::O => self.q_dim(), |
| 467 | TernTensor::Down => self.intermediate, |
| 468 | }; |
| 469 | (n, k) |
| 470 | } |
| 471 | |
| 472 | /// Packed bytes of one stacked matrix plus its segment scales (bf16 each). |
| 473 | pub fn ternary_bytes(&self, what: TernTensor) -> usize { |
| 474 | let (n, k) = self.shape(what); |
| 475 | n * k / 4 + 2 * self.parts(what).len() |
| 476 | } |
| 477 | |
| 478 | /// The e4m3 word table plus its bf16 block scales. |
| 479 | pub fn table_bytes(&self) -> usize { |
| 480 | self.vocab * self.hidden + 2 * (self.vocab / FP8_BLOCK) * (self.hidden / FP8_BLOCK) |
| 481 | } |
| 482 | |
| 483 | /// Everything handed to the uploader: every layer's packed matrices and scales, the table. |
| 484 | pub fn model_resident_bytes(&self) -> usize { |
| 485 | self.layers |
| 486 | * TernTensor::ALL |
| 487 | .iter() |
| 488 | .map(|&w| self.ternary_bytes(w)) |
| 489 | .sum::<usize>() |
| 490 | + self.table_bytes() |
| 491 | } |
| 492 | |
| 493 | /// The bf16 embedding the host keeps. |
| 494 | pub fn embed_host_bytes(&self) -> usize { |
| 495 | 2 * self.vocab * self.hidden |
| 496 | } |
| 497 | |
| 498 | /// Every tensor name the checkpoint must hold, and no other (332 for 2B-4T: the embedding, |
| 499 | /// 11 per layer, the final norm; no `lm_head`, no bias, no stored scale). |
| 500 | pub fn tensor_names(&self) -> Vec<String> { |
| 501 | let mut names = vec!["model.embed_tokens.weight".to_string()]; |
| 502 | for l in 0..self.layers { |
| 503 | let p = format!("model.layers.{l}"); |
| 504 | names.push(format!("{p}.input_layernorm.weight")); |
| 505 | names.push(format!("{p}.self_attn.attn_sub_norm.weight")); |
| 506 | names.push(format!("{p}.post_attention_layernorm.weight")); |
| 507 | names.push(format!("{p}.mlp.ffn_sub_norm.weight")); |
| 508 | for what in TernTensor::ALL { |
| 509 | names.extend(self.parts(what).into_iter().map(|(p, _)| p.tensor_name(l))); |
| 510 | } |
| 511 | } |
| 512 | names.push("model.norm.weight".into()); |
| 513 | names |
| 514 | } |
| 515 | |
| 516 | /// Refuses a checkpoint whose tensor names are not exactly [`Self::tensor_names`], naming |
| 517 | /// the first few unexpected and missing ones. |
| 518 | pub fn check_tensor_names(&self, present: &[String]) -> Result<(), String> { |
| 519 | let names = self.tensor_names(); |
| 520 | let want: std::collections::BTreeSet<&str> = names.iter().map(String::as_str).collect(); |
| 521 | let have: std::collections::BTreeSet<&str> = present.iter().map(String::as_str).collect(); |
| 522 | let extra: Vec<&str> = have.difference(&want).take(5).copied().collect(); |
| 523 | let missing: Vec<&str> = want.difference(&have).take(5).copied().collect(); |
| 524 | if extra.is_empty() && missing.is_empty() { |
| 525 | return Ok(()); |
| 526 | } |
| 527 | Err(format!( |
| 528 | "checkpoint tensors refused: {} present, {} expected; unexpected {extra:?}; missing {missing:?}", |
| 529 | have.len(), |
| 530 | want.len() |
| 531 | )) |
| 532 | } |
| 533 | |
| 534 | /// Largest stacked matrix, in elements. |
| 535 | pub fn max_matrix_elems(&self) -> usize { |
| 536 | TernTensor::ALL |
| 537 | .iter() |
| 538 | .map(|&w| { |
| 539 | let (n, k) = self.shape(w); |
| 540 | n * k |
| 541 | }) |
| 542 | .max() |
| 543 | .unwrap_or(0) |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | impl From<&BitNetConfig> for KvGeometry { |
| 548 | fn from(c: &BitNetConfig) -> Self { |
| 549 | Self { |
| 550 | layers: c.layers, |
| 551 | q_heads: c.q_heads, |
| 552 | kv_heads: c.kv_heads, |
| 553 | head_dim: c.head_dim, |
| 554 | rope_theta: c.rope_theta, |
| 555 | block_size: KV_BLOCK_SIZE, |
| 556 | } |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | /// Host bytes the loader holds beyond the model's own, at its peak: the larger of the two |
| 561 | /// phases, which never overlap. Phase 1 holds the bf16 read buffer, the trit buffer and the |
| 562 | /// packed-word buffer (each sized for the largest stacked matrix); they are dropped before |
| 563 | /// phase 2 builds the e4m3 table and its scales. |
| 564 | pub fn bitnet_loader_transient_bytes(c: &BitNetConfig) -> usize { |
| 565 | let m = c.max_matrix_elems(); |
| 566 | (2 * m + m + m / 4).max(c.table_bytes()) |
| 567 | } |
| 568 | |
| 569 | // --------------------------------------------------------------------------- |
| 570 | // The ternariser (spec 2.1). |
| 571 | // --------------------------------------------------------------------------- |
| 572 | |
| 573 | /// bf16 round-to-nearest-even of an f32, as PyTorch stores every bf16 op's result. |
| 574 | fn bf16(x: f32) -> f32 { |
| 575 | bf16_to_f32(f32_to_bf16(x)) |
| 576 | } |
| 577 | |
| 578 | /// The absmean scale of one projection, every step as PyTorch computes it on a bf16 tensor |
| 579 | /// (`REF/convert_checkpoint.py:23-27`): |
| 580 | /// `mean = bf16(mean |W|)`, `s = bf16(1 / max(mean, 1e-5))`, `w_scale = bf16(1 / s)`. |
| 581 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 582 | pub struct AbsmeanScale { |
| 583 | /// `bf16(mean |W|)`. |
| 584 | pub mean: f32, |
| 585 | /// `bf16(1 / mean)`: the multiplier the trits are rounded from. |
| 586 | pub s: f32, |
| 587 | /// `bf16(1 / s)`: the stored weight scale (`weight_scale` in the reference int2 checkpoint), |
| 588 | /// what a GEMV multiplies its integer sum by. |
| 589 | pub w_scale: f32, |
| 590 | } |
| 591 | |
| 592 | impl AbsmeanScale { |
| 593 | /// The stored scale as bf16 bits. |
| 594 | pub fn w_scale_bf16(&self) -> u16 { |
| 595 | f32_to_bf16(self.w_scale) |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | /// Elements per partial sum of the mean. Fixed, so the sum's order (and so its rounding) does |
| 600 | /// not depend on the thread count. |
| 601 | const MEAN_CHUNK: usize = 1 << 16; |
| 602 | |
| 603 | /// `bf16(mean |W|)` over bf16 words. The partial sums are f64 over fixed chunks, added in order; |
| 604 | /// the mean is rounded to f32 and then to bf16, as PyTorch's f32 reduction of a bf16 tensor |
| 605 | /// returns it. The f64 sum is exact for these weights (bf16 values of one projection span far |
| 606 | /// fewer than 53 bits), so the only rounding is PyTorch's own; spec 7 item 2 is resolved |
| 607 | /// against the reference int2 scales by the real-checkpoint test. |
| 608 | fn absmean(bits: &[u16]) -> f32 { |
| 609 | let sum: f64 = bits |
| 610 | .par_chunks(MEAN_CHUNK) |
| 611 | .map(|c| c.iter().map(|&b| bf16_to_f32(b).abs() as f64).sum::<f64>()) |
| 612 | .collect::<Vec<f64>>() |
| 613 | .into_iter() |
| 614 | .sum(); |
| 615 | bf16((sum / bits.len() as f64) as f32) |
| 616 | } |
| 617 | |
| 618 | /// The ternary value of one bf16 weight under multiplier `s`: `round(bf16(w * s))` with ties to |
| 619 | /// even (PyTorch `round`), clamped to [-1, 1]. The product of two bf16 values is exact in f32, |
| 620 | /// so `bf16(w * s)` is PyTorch's bf16 multiply. |
| 621 | #[inline] |
| 622 | pub fn trit_of(w_bits: u16, s: f32) -> i8 { |
| 623 | let p = bf16(bf16_to_f32(w_bits) * s); |
| 624 | // round-half-even then clamp: |p| <= 0.5 gives 0, above gives the sign. |
| 625 | if p > 0.5 { |
| 626 | 1 |
| 627 | } else if p < -0.5 { |
| 628 | -1 |
| 629 | } else { |
| 630 | 0 |
| 631 | } |
| 632 | } |
| 633 | |
| 634 | /// Ternarises one projection of bf16 words into `trits` (one i8 per weight, same order) and |
| 635 | /// returns its scale. A NaN or infinite weight is refused with its index; an empty projection |
| 636 | /// is refused. |
| 637 | pub fn absmean_ternarise(bits: &[u16], trits: &mut [i8]) -> Result<AbsmeanScale, String> { |
| 638 | if bits.is_empty() || bits.len() != trits.len() { |
| 639 | return Err(format!( |
| 640 | "ternarise: {} weights into {} trits", |
| 641 | bits.len(), |
| 642 | trits.len() |
| 643 | )); |
| 644 | } |
| 645 | if let Some(at) = bits.iter().position(|&b| b & 0x7f80 == 0x7f80) { |
| 646 | return Err(format!("weight {at} is NaN or infinite")); |
| 647 | } |
| 648 | // `clamp_(min=1e-5)` on a bf16 tensor: the bound is bf16(1e-5). |
| 649 | let mean = absmean(bits).max(bf16(1e-5)); |
| 650 | let s = bf16(1.0 / mean); |
| 651 | let w_scale = bf16(1.0 / s); |
| 652 | trits |
| 653 | .par_chunks_mut(MEAN_CHUNK) |
| 654 | .zip(bits.par_chunks(MEAN_CHUNK)) |
| 655 | .for_each(|(t, b)| { |
| 656 | for (t, &b) in t.iter_mut().zip(b) { |
| 657 | *t = trit_of(b, s); |
| 658 | } |
| 659 | }); |
| 660 | Ok(AbsmeanScale { mean, s, w_scale }) |
| 661 | } |
| 662 | |
| 663 | // --------------------------------------------------------------------------- |
| 664 | // The packer: omega's trit code, 16 per word. |
| 665 | // --------------------------------------------------------------------------- |
| 666 | |
| 667 | /// omega's 2-bit code of a trit (`oma_trit.h`): 0 -> 0b00, +1 -> 0b01 (plus plane), -1 -> 0b10 |
| 668 | /// (minus plane). 0b11 is never produced. |
| 669 | #[inline] |
| 670 | pub fn trit_code(t: i8) -> u32 { |
| 671 | match t { |
| 672 | 1 => 0b01, |
| 673 | -1 => 0b10, |
| 674 | _ => 0b00, |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | /// Decodes one 2-bit code; 0b11 is not a trit (`None`). |
| 679 | #[inline] |
| 680 | pub fn code_trit(code: u32) -> Option<i8> { |
| 681 | match code & 3 { |
| 682 | 0b00 => Some(0), |
| 683 | 0b01 => Some(1), |
| 684 | 0b10 => Some(-1), |
| 685 | _ => None, |
| 686 | } |
| 687 | } |
| 688 | |
| 689 | /// Packs `[n][k]` trits (row major, `k % 16 == 0`) into `[n][k / 16]` words of |
| 690 | /// [`TERN_LAYOUT_ID`]. |
| 691 | pub fn pack_trits(trits: &[i8], k: usize, words: &mut [u32]) -> Result<(), String> { |
| 692 | if !k.is_multiple_of(TRITS_PER_WORD) |
| 693 | || !trits.len().is_multiple_of(k) |
| 694 | || words.len() * TRITS_PER_WORD != trits.len() |
| 695 | { |
| 696 | return Err(format!( |
| 697 | "pack: {} trits of row width {k} into {} words", |
| 698 | trits.len(), |
| 699 | words.len() |
| 700 | )); |
| 701 | } |
| 702 | words |
| 703 | .par_chunks_mut(4096) |
| 704 | .zip(trits.par_chunks(4096 * TRITS_PER_WORD)) |
| 705 | .for_each(|(w, t)| { |
| 706 | for (word, group) in w.iter_mut().zip(t.chunks_exact(TRITS_PER_WORD)) { |
| 707 | *word = group |
| 708 | .iter() |
| 709 | .enumerate() |
| 710 | .fold(0, |acc, (i, &v)| acc | (trit_code(v) << (2 * i))); |
| 711 | } |
| 712 | }); |
| 713 | Ok(()) |
| 714 | } |
| 715 | |
| 716 | /// The first packed word holding a 0b11 code, if any, with the trit index inside it. |
| 717 | pub fn find_invalid_code(words: &[u32]) -> Option<(usize, usize)> { |
| 718 | words.iter().enumerate().find_map(|(i, &w)| { |
| 719 | let both = w & (w >> 1) & 0x5555_5555; |
| 720 | (both != 0).then(|| (i, both.trailing_zeros() as usize / 2)) |
| 721 | }) |
| 722 | } |
| 723 | |
| 724 | /// One row block of a stacked ternary matrix and its scale. |
| 725 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 726 | pub struct TernSegment { |
| 727 | pub part: TernPart, |
| 728 | pub rows: usize, |
| 729 | /// The stored weight scale, bf16 bits ([`AbsmeanScale::w_scale_bf16`]). |
| 730 | pub scale_bf16: u16, |
| 731 | } |
| 732 | |
| 733 | /// The ternary upload rule, checked on the host before anything is handed to a device: lengths |
| 734 | /// for `[n][k]` in [`TERN_LAYOUT_ID`], segments covering exactly `n` rows with finite positive |
| 735 | /// scales, and no 0b11 code. The first offender is named. |
| 736 | pub fn check_ternary_upload( |
| 737 | n: usize, |
| 738 | k: usize, |
| 739 | words: &[u32], |
| 740 | segments: &[TernSegment], |
| 741 | ) -> Result<(), String> { |
| 742 | if n == 0 || !k.is_multiple_of(TRITS_PER_WORD) || words.len() != n * k / TRITS_PER_WORD { |
| 743 | return Err(format!( |
| 744 | "{} words for [{n}][{k}] in {TERN_LAYOUT_ID}", |
| 745 | words.len() |
| 746 | )); |
| 747 | } |
| 748 | let rows: usize = segments.iter().map(|s| s.rows).sum(); |
| 749 | if rows != n || segments.iter().any(|s| s.rows == 0) { |
| 750 | return Err(format!("segments cover {rows} rows of {n}")); |
| 751 | } |
| 752 | if let Some(s) = segments.iter().find(|s| { |
| 753 | let v = bf16_to_f32(s.scale_bf16); |
| 754 | !(v.is_finite() && v > 0.0) |
| 755 | }) { |
| 756 | return Err(format!( |
| 757 | "segment {} scale {} is not finite and positive", |
| 758 | s.part.name(), |
| 759 | bf16_to_f32(s.scale_bf16) |
| 760 | )); |
| 761 | } |
| 762 | if let Some((w, t)) = find_invalid_code(words) { |
| 763 | let wpr = k / TRITS_PER_WORD; |
| 764 | return Err(format!( |
| 765 | "row {} column {}: code 0b11 is not a trit (refused at upload)", |
| 766 | w / wpr, |
| 767 | (w % wpr) * TRITS_PER_WORD + t |
| 768 | )); |
| 769 | } |
| 770 | Ok(()) |
| 771 | } |
| 772 | |
| 773 | // --------------------------------------------------------------------------- |
| 774 | // The 8-bit word table (design 3.1 KT4 option A). |
| 775 | // --------------------------------------------------------------------------- |
| 776 | |
| 777 | /// Quantises the `[n][k]` bf16 table to e4m3 in 128x128 blocks into `w` (`n * k` bytes) and |
| 778 | /// `scales` (`[n/128][k/128]` bf16): per block `scale = bf16(amax / 448)` (1.0 for an all-zero |
| 779 | /// block), each weight `e4m3(w / scale)` round-to-nearest-even and saturating, a negative zero |
| 780 | /// stored as +0 (omega's `gpu_lmhead_fp8_study.c` rule, byte for byte). |
| 781 | pub fn build_fp8_table( |
| 782 | table: &[u16], |
| 783 | n: usize, |
| 784 | k: usize, |
| 785 | w: &mut [u8], |
| 786 | scales: &mut [u16], |
| 787 | ) -> Result<(), String> { |
| 788 | let b = FP8_BLOCK; |
| 789 | if !n.is_multiple_of(b) |
| 790 | || !k.is_multiple_of(b) |
| 791 | || table.len() != n * k |
| 792 | || w.len() != n * k |
| 793 | || scales.len() != (n / b) * (k / b) |
| 794 | { |
| 795 | return Err(format!( |
| 796 | "fp8 table: [{n}][{k}] with {} words, {} bytes, {} scales", |
| 797 | table.len(), |
| 798 | w.len(), |
| 799 | scales.len() |
| 800 | )); |
| 801 | } |
| 802 | if let Some(at) = table.iter().position(|&x| x & 0x7f80 == 0x7f80) { |
| 803 | return Err(format!("word table element {at} is NaN or infinite")); |
| 804 | } |
| 805 | let kb = k / b; |
| 806 | // One block row (128 table rows) per task. |
| 807 | w.par_chunks_mut(b * k) |
| 808 | .zip(scales.par_chunks_mut(kb)) |
| 809 | .enumerate() |
| 810 | .for_each(|(bi, (wrows, srow))| { |
| 811 | let src = &table[bi * b * k..(bi + 1) * b * k]; |
| 812 | for bj in 0..kb { |
| 813 | let cols = bj * b..(bj + 1) * b; |
| 814 | let amax = (0..b) |
| 815 | .flat_map(|r| src[r * k + cols.start..r * k + cols.end].iter()) |
| 816 | .map(|&x| bf16_to_f32(x).abs()) |
| 817 | .fold(0.0f32, f32::max); |
| 818 | let sb = f32_to_bf16(if amax > 0.0 { amax / 448.0 } else { 1.0 }); |
| 819 | let s = bf16_to_f32(sb); |
| 820 | srow[bj] = sb; |
| 821 | for r in 0..b { |
| 822 | for c in cols.clone() { |
| 823 | let code = f32_to_fp8_e4m3fn(bf16_to_f32(src[r * k + c]) / s); |
| 824 | wrows[r * k + c] = if code == 0x80 { 0 } else { code }; |
| 825 | } |
| 826 | } |
| 827 | } |
| 828 | }); |
| 829 | Ok(()) |
| 830 | } |
| 831 | |
| 832 | // --------------------------------------------------------------------------- |
| 833 | // The device side, behind a trait so the loader runs without a chip. |
| 834 | // --------------------------------------------------------------------------- |
| 835 | |
| 836 | /// One resident stacked ternary matrix. The GEMV contract is omega's Omega-X |
| 837 | /// (`realize_common.h`): `acc[r] = sum_c W[r][c] * x[c]`, W in {-1, 0, 1}, x int8, exact int32. |
| 838 | /// The per-segment scaling is the caller's (it knows the activation scale). |
| 839 | pub trait TernMatrix: Send + Sync + std::fmt::Debug { |
| 840 | fn n(&self) -> usize; |
| 841 | fn k(&self) -> usize; |
| 842 | fn segments(&self) -> &[TernSegment]; |
| 843 | fn gemv_i8(&self, x: &[i8], acc: &mut [i32]) -> Result<(), String>; |
| 844 | |
| 845 | /// The same product for `t` tokens: `x` is `[t][k]`, `acc` is `[t][n]`. |
| 846 | fn gemm_i8(&self, x: &[i8], t: usize, acc: &mut [i32]) -> Result<(), String> { |
| 847 | let (n, k) = (self.n(), self.k()); |
| 848 | if x.len() != t * k || acc.len() != t * n { |
| 849 | return Err(format!( |
| 850 | "ternary gemm [{n}][{k}] for {t} tokens given x {} acc {}", |
| 851 | x.len(), |
| 852 | acc.len() |
| 853 | )); |
| 854 | } |
| 855 | for (xr, ar) in x.chunks_exact(k).zip(acc.chunks_exact_mut(n)) { |
| 856 | self.gemv_i8(xr, ar)?; |
| 857 | } |
| 858 | Ok(()) |
| 859 | } |
| 860 | } |
| 861 | |
| 862 | /// Makes packed ternary matrices and the e4m3 word table resident. The real one (omega's KT1 |
| 863 | /// `tensor_upload`) comes with stage T3; the loader is the same. |
| 864 | pub trait TernUploader { |
| 865 | /// `[n][k]` trits in [`TERN_LAYOUT_ID`], `segments` the row blocks in order. |
| 866 | fn upload_ternary( |
| 867 | &self, |
| 868 | layer: usize, |
| 869 | what: TernTensor, |
| 870 | n: usize, |
| 871 | k: usize, |
| 872 | words: &[u32], |
| 873 | segments: &[TernSegment], |
| 874 | ) -> Result<Arc<dyn TernMatrix>, String>; |
| 875 | |
| 876 | /// The `[n][k]` e4m3 word table with its `[n/128][k/128]` bf16 block scales. |
| 877 | fn upload_table_fp8( |
| 878 | &self, |
| 879 | n: usize, |
| 880 | k: usize, |
| 881 | w: &[u8], |
| 882 | scales: &[u16], |
| 883 | ) -> Result<Arc<dyn DenseGemv>, String>; |
| 884 | } |
| 885 | |
| 886 | /// A packed ternary matrix on the host: the exact int32 GEMV (the oracle contract) and the |
| 887 | /// unpacking the byte tests use. |
| 888 | #[derive(Debug)] |
| 889 | pub struct HostTernMatrix { |
| 890 | n: usize, |
| 891 | k: usize, |
| 892 | words: Vec<u32>, |
| 893 | segments: Vec<TernSegment>, |
| 894 | } |
| 895 | |
| 896 | impl HostTernMatrix { |
| 897 | /// Checked by [`check_ternary_upload`] first. |
| 898 | pub fn new( |
| 899 | n: usize, |
| 900 | k: usize, |
| 901 | words: Vec<u32>, |
| 902 | segments: Vec<TernSegment>, |
| 903 | ) -> Result<Self, String> { |
| 904 | check_ternary_upload(n, k, &words, &segments)?; |
| 905 | Ok(Self { |
| 906 | n, |
| 907 | k, |
| 908 | words, |
| 909 | segments, |
| 910 | }) |
| 911 | } |
| 912 | |
| 913 | pub fn words(&self) -> &[u32] { |
| 914 | &self.words |
| 915 | } |
| 916 | |
| 917 | /// Row `r` as trits. |
| 918 | pub fn row(&self, r: usize) -> Vec<i8> { |
| 919 | let wpr = self.k / TRITS_PER_WORD; |
| 920 | self.words[r * wpr..(r + 1) * wpr] |
| 921 | .iter() |
| 922 | .flat_map(|&w| (0..TRITS_PER_WORD).map(move |i| code_trit(w >> (2 * i)).unwrap_or(0))) |
| 923 | .collect() |
| 924 | } |
| 925 | } |
| 926 | |
| 927 | impl TernMatrix for HostTernMatrix { |
| 928 | fn n(&self) -> usize { |
| 929 | self.n |
| 930 | } |
| 931 | fn k(&self) -> usize { |
| 932 | self.k |
| 933 | } |
| 934 | fn segments(&self) -> &[TernSegment] { |
| 935 | &self.segments |
| 936 | } |
| 937 | fn gemv_i8(&self, x: &[i8], acc: &mut [i32]) -> Result<(), String> { |
| 938 | if x.len() != self.k || acc.len() != self.n { |
| 939 | return Err(format!( |
| 940 | "ternary gemv [{}][{}] given x {} acc {}", |
| 941 | self.n, |
| 942 | self.k, |
| 943 | x.len(), |
| 944 | acc.len() |
| 945 | )); |
| 946 | } |
| 947 | let wpr = self.k / TRITS_PER_WORD; |
| 948 | acc.par_iter_mut().enumerate().for_each(|(r, out)| { |
| 949 | let row = &self.words[r * wpr..(r + 1) * wpr]; |
| 950 | let mut sum = 0i32; |
| 951 | for (j, &w) in row.iter().enumerate() { |
| 952 | let xs = &x[j * TRITS_PER_WORD..(j + 1) * TRITS_PER_WORD]; |
| 953 | for (i, &xv) in xs.iter().enumerate() { |
| 954 | // plus plane adds, minus plane subtracts (validated: never both). |
| 955 | let code = (w >> (2 * i)) & 3; |
| 956 | sum += (code & 1) as i32 * xv as i32 - (code >> 1) as i32 * xv as i32; |
| 957 | } |
| 958 | } |
| 959 | *out = sum; |
| 960 | }); |
| 961 | Ok(()) |
| 962 | } |
| 963 | } |
| 964 | |
| 965 | // --------------------------------------------------------------------------- |
| 966 | // Checkpoint sources. |
| 967 | // --------------------------------------------------------------------------- |
| 968 | |
| 969 | /// One `model.safetensors` file (the BitNet master is not sharded), with the same validated |
| 970 | /// reader as the shard loader: dtype, shape and byte range checked per tensor. |
| 971 | pub struct SafetensorsFile(Shard); |
| 972 | |
| 973 | impl SafetensorsFile { |
| 974 | pub fn open(path: &Path) -> Result<Self, String> { |
| 975 | Shard::open(path).map(Self).map_err(|e| e.to_string()) |
| 976 | } |
| 977 | } |
| 978 | |
| 979 | impl TensorSource for SafetensorsFile { |
| 980 | fn read_into( |
| 981 | &mut self, |
| 982 | name: &str, |
| 983 | dtype: &str, |
| 984 | shape: &[usize], |
| 985 | dst: &mut [u8], |
| 986 | ) -> Result<(), String> { |
| 987 | self.0 |
| 988 | .read(name, dtype, shape, dst) |
| 989 | .map_err(|e| e.to_string()) |
| 990 | } |
| 991 | |
| 992 | fn dtype_of(&mut self, name: &str) -> Result<Option<String>, String> { |
| 993 | Ok(self.0.dtype(name).map(str::to_string)) |
| 994 | } |
| 995 | } |
| 996 | |
| 997 | /// The tensor names a checkpoint directory holds: the `weight_map` of |
| 998 | /// `model.safetensors.index.json` when present, else the header of `model.safetensors`. |
| 999 | pub fn checkpoint_tensor_names(dir: &Path) -> Result<Vec<String>, String> { |
| 1000 | use std::io::Read; |
| 1001 | let header: serde_json::Value = if dir.join("model.safetensors.index.json").exists() { |
| 1002 | let p = dir.join("model.safetensors.index.json"); |
| 1003 | let text = std::fs::read_to_string(&p).map_err(|e| format!("{}: {e}", p.display()))?; |
| 1004 | let index: serde_json::Value = |
| 1005 | serde_json::from_str(&text).map_err(|e| format!("{}: {e}", p.display()))?; |
| 1006 | index |
| 1007 | .get("weight_map") |
| 1008 | .cloned() |
| 1009 | .ok_or_else(|| format!("{}: no weight_map", p.display()))? |
| 1010 | } else { |
| 1011 | let p = dir.join("model.safetensors"); |
| 1012 | let io = |e: std::io::Error| format!("{}: {e}", p.display()); |
| 1013 | let mut f = std::fs::File::open(&p).map_err(io)?; |
| 1014 | let mut len = [0u8; 8]; |
| 1015 | f.read_exact(&mut len).map_err(io)?; |
| 1016 | let len = u64::from_le_bytes(len); |
| 1017 | if len > 100 << 20 { |
| 1018 | return Err(format!("{}: header of {len} bytes refused", p.display())); |
| 1019 | } |
| 1020 | let mut text = vec![0u8; len as usize]; |
| 1021 | f.read_exact(&mut text).map_err(io)?; |
| 1022 | serde_json::from_slice(&text).map_err(|e| format!("{}: header: {e}", p.display()))? |
| 1023 | }; |
| 1024 | let map = header |
| 1025 | .as_object() |
| 1026 | .ok_or("safetensors header is not an object")?; |
| 1027 | Ok(map |
| 1028 | .keys() |
| 1029 | .filter(|k| k.as_str() != "__metadata__") |
| 1030 | .cloned() |
| 1031 | .collect()) |
| 1032 | } |
| 1033 | |
| 1034 | /// The checkpoint's tensors: the shard index when there is one, else `model.safetensors`. |
| 1035 | pub fn open_checkpoint(dir: &Path) -> Result<Box<dyn TensorSource>, String> { |
| 1036 | if dir.join("model.safetensors.index.json").exists() { |
| 1037 | Ok(Box::new(ShardSource::open(dir)?)) |
| 1038 | } else { |
| 1039 | Ok(Box::new(SafetensorsFile::open( |
| 1040 | &dir.join("model.safetensors"), |
| 1041 | )?)) |
| 1042 | } |
| 1043 | } |
| 1044 | |
| 1045 | // --------------------------------------------------------------------------- |
| 1046 | // The loaded model. |
| 1047 | // --------------------------------------------------------------------------- |
| 1048 | |
| 1049 | #[derive(Debug)] |
| 1050 | pub struct BitNetLayer { |
| 1051 | /// RMSNorm before attention (`input_layernorm`), `[hidden]`. |
| 1052 | pub input_norm: Vec<f32>, |
| 1053 | /// RMSNorm on the attention output before o (`attn_sub_norm`), `[q_dim]`. |
| 1054 | pub attn_sub_norm: Vec<f32>, |
| 1055 | /// RMSNorm before the feed-forward (`post_attention_layernorm`), `[hidden]`. |
| 1056 | pub post_norm: Vec<f32>, |
| 1057 | /// RMSNorm on `relu(gate)^2 * up` before down (`ffn_sub_norm`), `[intermediate]`. |
| 1058 | pub ffn_sub_norm: Vec<f32>, |
| 1059 | pub qkv: Arc<dyn TernMatrix>, |
| 1060 | pub o: Arc<dyn TernMatrix>, |
| 1061 | pub gate_up: Arc<dyn TernMatrix>, |
| 1062 | pub down: Arc<dyn TernMatrix>, |
| 1063 | } |
| 1064 | |
| 1065 | impl BitNetLayer { |
| 1066 | pub fn matrix(&self, what: TernTensor) -> &Arc<dyn TernMatrix> { |
| 1067 | match what { |
| 1068 | TernTensor::Qkv => &self.qkv, |
| 1069 | TernTensor::O => &self.o, |
| 1070 | TernTensor::GateUp => &self.gate_up, |
| 1071 | TernTensor::Down => &self.down, |
| 1072 | } |
| 1073 | } |
| 1074 | } |
| 1075 | |
| 1076 | /// The whole model: packed matrices and the 8-bit table on the device, the bf16 embedding and |
| 1077 | /// f32 norms on the host. |
| 1078 | #[derive(Debug)] |
| 1079 | pub struct BitNetOmegaWeights { |
| 1080 | pub config: BitNetConfig, |
| 1081 | /// `[vocab][hidden]` bf16 bits: the input lookup (one row widened to f32) and, being tied, |
| 1082 | /// the 16-bit output head of the host reference. |
| 1083 | pub embed_bf16: Vec<u16>, |
| 1084 | pub layers: Vec<BitNetLayer>, |
| 1085 | pub final_norm: Vec<f32>, |
| 1086 | /// The e4m3 word table (the output head on the chip). |
| 1087 | pub table_fp8: Arc<dyn DenseGemv>, |
| 1088 | } |
| 1089 | |
| 1090 | impl BitNetOmegaWeights { |
| 1091 | /// The embedding row of `token` in f32; a token outside the vocabulary is refused. |
| 1092 | pub fn embed_row(&self, token: u32) -> Result<Vec<f32>, String> { |
| 1093 | let h = self.config.hidden; |
| 1094 | let t = token as usize; |
| 1095 | if t >= self.config.vocab { |
| 1096 | return Err(format!( |
| 1097 | "token {token} outside the vocabulary of {}", |
| 1098 | self.config.vocab |
| 1099 | )); |
| 1100 | } |
| 1101 | Ok(self.embed_bf16[t * h..(t + 1) * h] |
| 1102 | .iter() |
| 1103 | .map(|&b| bf16_to_f32(b)) |
| 1104 | .collect()) |
| 1105 | } |
| 1106 | |
| 1107 | /// Bytes the host keeps after the load (embedding and norms). |
| 1108 | pub fn host_bytes(&self) -> usize { |
| 1109 | self.embed_bf16.len() * 2 |
| 1110 | + self.final_norm.len() * 4 |
| 1111 | + self |
| 1112 | .layers |
| 1113 | .iter() |
| 1114 | .map(|l| { |
| 1115 | 4 * (l.input_norm.len() |
| 1116 | + l.attn_sub_norm.len() |
| 1117 | + l.post_norm.len() |
| 1118 | + l.ffn_sub_norm.len()) |
| 1119 | }) |
| 1120 | .sum::<usize>() |
| 1121 | } |
| 1122 | } |
| 1123 | |
| 1124 | /// What a load measured. |
| 1125 | #[derive(Debug, Clone, PartialEq)] |
| 1126 | pub struct BitNetLoadReport { |
| 1127 | /// Bytes handed to the uploader: packed words, segment scales, e4m3 table and its scales. |
| 1128 | pub resident_bytes: usize, |
| 1129 | pub host_bytes: usize, |
| 1130 | /// The loader's reused buffers, bytes ([`bitnet_loader_transient_bytes`]). |
| 1131 | pub transient_bytes: usize, |
| 1132 | pub uploads: usize, |
| 1133 | /// Every projection's scale, `[layer][q, k, v, o, gate, up, down]`. |
| 1134 | pub scales: Vec<[AbsmeanScale; 7]>, |
| 1135 | /// Process peak resident set (VmHWM) before and after the load, if `/proc` is readable. |
| 1136 | pub peak_rss_before_bytes: Option<u64>, |
| 1137 | pub peak_rss_bytes: Option<u64>, |
| 1138 | pub seconds: f64, |
| 1139 | } |
| 1140 | |
| 1141 | /// A u16 slice as bytes of twice the length. |
| 1142 | fn words_as_bytes_mut(words: &mut [u16]) -> &mut [u8] { |
| 1143 | // SAFETY: u8 has no alignment need and every byte pattern is a valid u16 half; the length |
| 1144 | // is exactly the slice's size in bytes. |
| 1145 | unsafe { std::slice::from_raw_parts_mut(words.as_mut_ptr().cast::<u8>(), words.len() * 2) } |
| 1146 | } |
| 1147 | |
| 1148 | /// Reads one bf16 tensor (dtype and shape checked by the source) into `dst` as words. |
| 1149 | fn read_bf16( |
| 1150 | source: &mut dyn TensorSource, |
| 1151 | name: &str, |
| 1152 | shape: &[usize], |
| 1153 | dst: &mut [u16], |
| 1154 | ) -> Result<(), String> { |
| 1155 | if shape.iter().product::<usize>() != dst.len() { |
| 1156 | return Err(format!( |
| 1157 | "{name}: shape {shape:?} does not fill {} words", |
| 1158 | dst.len() |
| 1159 | )); |
| 1160 | } |
| 1161 | source.read_into(name, "BF16", shape, words_as_bytes_mut(dst)) |
| 1162 | } |
| 1163 | |
| 1164 | /// The streaming loader's state: the source, the uploader, its reused buffers, the totals. |
| 1165 | struct Stream<'a> { |
| 1166 | config: &'a BitNetConfig, |
| 1167 | source: &'a mut dyn TensorSource, |
| 1168 | uploader: &'a dyn TernUploader, |
| 1169 | bf16: Vec<u16>, |
| 1170 | trits: Vec<i8>, |
| 1171 | words: Vec<u32>, |
| 1172 | resident: usize, |
| 1173 | uploads: usize, |
| 1174 | } |
| 1175 | |
| 1176 | impl Stream<'_> { |
| 1177 | fn norm(&mut self, name: &str, len: usize) -> Result<Vec<f32>, String> { |
| 1178 | read_bf16(self.source, name, &[len], &mut self.bf16[..len])?; |
| 1179 | let v: Vec<f32> = self.bf16[..len].iter().map(|&b| bf16_to_f32(b)).collect(); |
| 1180 | if v.iter().any(|x| !x.is_finite()) { |
| 1181 | return Err(format!("{name}: NaN or infinite norm weight")); |
| 1182 | } |
| 1183 | Ok(v) |
| 1184 | } |
| 1185 | |
| 1186 | /// Reads the parts of `what` back to back (so the stacked `[n][k]` is the parts in order with |
| 1187 | /// no copy), ternarises each part with its own scale, packs the stack and uploads it. |
| 1188 | fn matrix( |
| 1189 | &mut self, |
| 1190 | layer: usize, |
| 1191 | what: TernTensor, |
| 1192 | ) -> Result<(Arc<dyn TernMatrix>, Vec<AbsmeanScale>), String> { |
| 1193 | let (n, k) = self.config.shape(what); |
| 1194 | let at = format!("layer {layer} {} [{n}][{k}]", what.name()); |
| 1195 | let mut segments = Vec::new(); |
| 1196 | let mut scales = Vec::new(); |
| 1197 | let mut off = 0usize; |
| 1198 | for (part, rows) in self.config.parts(what) { |
| 1199 | let name = part.tensor_name(layer); |
| 1200 | let range = off..off + rows * k; |
| 1201 | read_bf16( |
| 1202 | self.source, |
| 1203 | &name, |
| 1204 | &[rows, k], |
| 1205 | &mut self.bf16[range.clone()], |
| 1206 | )?; |
| 1207 | let scale = absmean_ternarise(&self.bf16[range.clone()], &mut self.trits[range]) |
| 1208 | .map_err(|e| format!("{name}: {e}"))?; |
| 1209 | segments.push(TernSegment { |
| 1210 | part, |
| 1211 | rows, |
| 1212 | scale_bf16: scale.w_scale_bf16(), |
| 1213 | }); |
| 1214 | scales.push(scale); |
| 1215 | off += rows * k; |
| 1216 | } |
| 1217 | let words = &mut self.words[..n * k / TRITS_PER_WORD]; |
| 1218 | pack_trits(&self.trits[..n * k], k, words).map_err(|e| format!("{at}: {e}"))?; |
| 1219 | let m = self |
| 1220 | .uploader |
| 1221 | .upload_ternary(layer, what, n, k, words, &segments) |
| 1222 | .map_err(|e| format!("{at} upload: {e}"))?; |
| 1223 | if m.n() != n || m.k() != k { |
| 1224 | return Err(format!("{at} upload returned [{}][{}]", m.n(), m.k())); |
| 1225 | } |
| 1226 | self.resident += self.config.ternary_bytes(what); |
| 1227 | self.uploads += 1; |
| 1228 | Ok((m, scales)) |
| 1229 | } |
| 1230 | } |
| 1231 | |
| 1232 | /// Loads a checkpoint directory: `config.json` for the shape, `model.safetensors` (or shards) |
| 1233 | /// for the weights. |
| 1234 | pub fn load_bitnet_omega( |
| 1235 | dir: &Path, |
| 1236 | uploader: &dyn TernUploader, |
| 1237 | progress: &mut dyn FnMut(&str), |
| 1238 | ) -> Result<(BitNetOmegaWeights, BitNetLoadReport), String> { |
| 1239 | let config = BitNetConfig::from_checkpoint(dir)?; |
| 1240 | config.check_tensor_names(&checkpoint_tensor_names(dir)?)?; |
| 1241 | let mut source = open_checkpoint(dir)?; |
| 1242 | load_bitnet_omega_from(&config, source.as_mut(), uploader, progress) |
| 1243 | } |
| 1244 | |
| 1245 | /// The streaming load from any [`TensorSource`]. |
| 1246 | pub fn load_bitnet_omega_from( |
| 1247 | config: &BitNetConfig, |
| 1248 | source: &mut dyn TensorSource, |
| 1249 | uploader: &dyn TernUploader, |
| 1250 | progress: &mut dyn FnMut(&str), |
| 1251 | ) -> Result<(BitNetOmegaWeights, BitNetLoadReport), String> { |
| 1252 | config.validate()?; |
| 1253 | let t0 = Instant::now(); |
| 1254 | let peak_before = peak_rss_bytes(); |
| 1255 | let (h, i) = (config.hidden, config.intermediate); |
| 1256 | |
| 1257 | // Every tensor must be stored bf16 (the header decides, not the name). |
| 1258 | let mut embed_bf16 = vec![0u16; config.vocab * h]; |
| 1259 | read_bf16( |
| 1260 | source, |
| 1261 | "model.embed_tokens.weight", |
| 1262 | &[config.vocab, h], |
| 1263 | &mut embed_bf16, |
| 1264 | )?; |
| 1265 | if let Some(at) = embed_bf16.iter().position(|&x| x & 0x7f80 == 0x7f80) { |
| 1266 | return Err(format!( |
| 1267 | "model.embed_tokens.weight: element {at} is NaN or infinite" |
| 1268 | )); |
| 1269 | } |
| 1270 | if source.dtype_of("lm_head.weight")?.is_some() { |
| 1271 | return Err( |
| 1272 | "lm_head.weight present in a tied checkpoint: refused (the embedding is the head)" |
| 1273 | .into(), |
| 1274 | ); |
| 1275 | } |
| 1276 | |
| 1277 | let m = config.max_matrix_elems(); |
| 1278 | let mut s = Stream { |
| 1279 | config, |
| 1280 | source, |
| 1281 | uploader, |
| 1282 | bf16: vec![0; m], |
| 1283 | trits: vec![0; m], |
| 1284 | words: vec![0; m / TRITS_PER_WORD], |
| 1285 | resident: 0, |
| 1286 | uploads: 0, |
| 1287 | }; |
| 1288 | |
| 1289 | let mut layers = Vec::with_capacity(config.layers); |
| 1290 | let mut all_scales = Vec::with_capacity(config.layers); |
| 1291 | for layer in 0..config.layers { |
| 1292 | let p = format!("model.layers.{layer}"); |
| 1293 | let input_norm = s.norm(&format!("{p}.input_layernorm.weight"), h)?; |
| 1294 | let attn_sub_norm = s.norm( |
| 1295 | &format!("{p}.self_attn.attn_sub_norm.weight"), |
| 1296 | config.q_dim(), |
| 1297 | )?; |
| 1298 | let post_norm = s.norm(&format!("{p}.post_attention_layernorm.weight"), h)?; |
| 1299 | let ffn_sub_norm = s.norm(&format!("{p}.mlp.ffn_sub_norm.weight"), i)?; |
| 1300 | let (qkv, sq) = s.matrix(layer, TernTensor::Qkv)?; |
| 1301 | let (o, so) = s.matrix(layer, TernTensor::O)?; |
| 1302 | let (gate_up, sg) = s.matrix(layer, TernTensor::GateUp)?; |
| 1303 | let (down, sd) = s.matrix(layer, TernTensor::Down)?; |
| 1304 | all_scales.push([sq[0], sq[1], sq[2], so[0], sg[0], sg[1], sd[0]]); |
| 1305 | layers.push(BitNetLayer { |
| 1306 | input_norm, |
| 1307 | attn_sub_norm, |
| 1308 | post_norm, |
| 1309 | ffn_sub_norm, |
| 1310 | qkv, |
| 1311 | o, |
| 1312 | gate_up, |
| 1313 | down, |
| 1314 | }); |
| 1315 | progress(&format!("layer {}/{} packed", layer + 1, config.layers)); |
| 1316 | } |
| 1317 | let final_norm = s.norm("model.norm.weight", h)?; |
| 1318 | let (mut resident, uploads) = (s.resident, s.uploads + 1); |
| 1319 | drop(s); |
| 1320 | |
| 1321 | // The 8-bit word table from the embedding the host already holds. |
| 1322 | let (n, b) = (config.vocab, FP8_BLOCK); |
| 1323 | let mut table = vec![0u8; n * h]; |
| 1324 | let mut table_scales = vec![0u16; (n / b) * (h / b)]; |
| 1325 | build_fp8_table(&embed_bf16, n, h, &mut table, &mut table_scales)?; |
| 1326 | let table_fp8 = uploader |
| 1327 | .upload_table_fp8(n, h, &table, &table_scales) |
| 1328 | .map_err(|e| format!("word table [{n}][{h}] upload: {e}"))?; |
| 1329 | if table_fp8.n() != n || table_fp8.k() != h { |
| 1330 | return Err(format!( |
| 1331 | "word table upload returned [{}][{}]", |
| 1332 | table_fp8.n(), |
| 1333 | table_fp8.k() |
| 1334 | )); |
| 1335 | } |
| 1336 | resident += config.table_bytes(); |
| 1337 | drop((table, table_scales)); |
| 1338 | progress("word table packed"); |
| 1339 | |
| 1340 | let weights = BitNetOmegaWeights { |
| 1341 | config: config.clone(), |
| 1342 | embed_bf16, |
| 1343 | layers, |
| 1344 | final_norm, |
| 1345 | table_fp8, |
| 1346 | }; |
| 1347 | let report = BitNetLoadReport { |
| 1348 | resident_bytes: resident, |
| 1349 | host_bytes: weights.host_bytes(), |
| 1350 | transient_bytes: bitnet_loader_transient_bytes(config), |
| 1351 | uploads, |
| 1352 | scales: all_scales, |
| 1353 | peak_rss_before_bytes: peak_before, |
| 1354 | peak_rss_bytes: peak_rss_bytes(), |
| 1355 | seconds: t0.elapsed().as_secs_f64(), |
| 1356 | }; |
| 1357 | Ok((weights, report)) |
| 1358 | } |
| 1359 | |
| 1360 | /// The upload rule of the word table: omega's FP8 check (lengths, no e4m3 NaN code, finite |
| 1361 | /// scales). Re-exported for uploaders. |
| 1362 | pub fn check_table_upload(n: usize, k: usize, w: &[u8], scales: &[u16]) -> Result<(), String> { |
| 1363 | check_fp8_upload(n, k, w, scales) |
| 1364 | } |
| 1365 | |
| 1366 | /// sha256 of a file, lowercase hex. |
| 1367 | pub fn sha256_file(path: &Path) -> Result<String, String> { |
| 1368 | use sha2::{Digest, Sha256}; |
| 1369 | use std::io::Read; |
| 1370 | let mut f = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; |
| 1371 | let mut h = Sha256::new(); |
| 1372 | let mut buf = vec![0u8; 1 << 22]; |
| 1373 | loop { |
| 1374 | let got = f |
| 1375 | .read(&mut buf) |
| 1376 | .map_err(|e| format!("{}: {e}", path.display()))?; |
| 1377 | if got == 0 { |
| 1378 | break; |
| 1379 | } |
| 1380 | h.update(&buf[..got]); |
| 1381 | } |
| 1382 | Ok(h.finalize() |
| 1383 | .iter() |
| 1384 | .map(|b| format!("{b:02x}")) |
| 1385 | .collect::<String>()) |
| 1386 | } |