Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-inference-abi/src/checkpoint.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-inference-abi / src / checkpoint.rs` 1485 lines ยท 57229 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 //! Strict Safetensors checkpoint loader with loud shape and dtype validation. 17 //! Ingests BF16 weights into one `ModelCapsule`. FP32 is decoded on demand. 18 19 use std::collections::HashMap; 20 use std::fmt; 21 use std::fs::{File, OpenOptions}; 22 use std::os::unix::fs::{FileExt, OpenOptionsExt}; 23 use std::path::{Component, Path, PathBuf}; 24 use std::sync::Arc; 25 26 /// Loud error enum describing checkpoint parsing and validation failures. 27 #[derive(Debug, Clone, PartialEq, Eq)] 28 pub enum CheckpointError { 29 /// A required tensor in the model catalog was not found in the checkpoint. 30 MissingTensor(String), 31 /// A tensor's shape in the checkpoint does not match the canonical model architecture. 32 ShapeMismatch { 33 tensor: String, 34 expected: Vec, 35 actual: Vec, 36 }, 37 /// A tensor's dtype is not BF16. 38 DtypeMismatch { 39 tensor: String, 40 expected: String, 41 actual: String, 42 }, 43 /// A tensor's byte range exceeds the binary payload or does not match shape element count. 44 OffsetOutOfBounds { 45 tensor: String, 46 offset: usize, 47 buffer_len: usize, 48 }, 49 /// Safetensors binary header is malformed, truncated, or invalid JSON. 50 InvalidHeader(String), 51 /// A capsule tensor could not be decoded. 52 Capsule(String), 53 /// A weight could not be made resident on the device (named, never a silent host copy). 54 ResidentUpload { tensor: String, message: String }, 55 } 56 57 impl fmt::Display for CheckpointError { 58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 59 match self { 60 Self::MissingTensor(name) => { 61 write!(f, "Missing required tensor in checkpoint: {}", name) 62 } 63 Self::ShapeMismatch { 64 tensor, 65 expected, 66 actual, 67 } => { 68 write!( 69 f, 70 "Shape mismatch for tensor {}: expected {:?}, got {:?}", 71 tensor, expected, actual 72 ) 73 } 74 Self::DtypeMismatch { 75 tensor, 76 expected, 77 actual, 78 } => { 79 write!( 80 f, 81 "Dtype mismatch for tensor {}: expected {}, got {}", 82 tensor, expected, actual 83 ) 84 } 85 Self::OffsetOutOfBounds { 86 tensor, 87 offset, 88 buffer_len, 89 } => { 90 write!( 91 f, 92 "Offset out of bounds for tensor {}: offset {} exceeds buffer length {}", 93 tensor, offset, buffer_len 94 ) 95 } 96 Self::InvalidHeader(err) => { 97 write!(f, "Invalid safetensors header: {}", err) 98 } 99 Self::Capsule(err) => write!(f, "Invalid capsule tensor: {}", err), 100 Self::ResidentUpload { tensor, message } => { 101 write!( 102 f, 103 "Resident upload of tensor {} failed: {}", 104 tensor, message 105 ) 106 } 107 } 108 } 109 } 110 111 impl std::error::Error for CheckpointError {} 112 113 /// Checkpoint stored as one capsule. Tensor bytes stay in `capsule.bytes`. 114 /// FP32 is produced by `decode_fp32` and is not retained. 115 #[derive(Debug, Clone)] 116 pub struct LoadedCheckpoint { 117 pub capsule: crate::capsule::ModelCapsule, 118 } 119 120 impl Default for LoadedCheckpoint { 121 fn default() -> Self { 122 Self::new() 123 } 124 } 125 126 impl LoadedCheckpoint { 127 /// Empty capsule: empty byte buffer, empty tensor map, digests of that empty input. 128 pub fn new() -> Self { 129 Self::from_bf16_tensors(Vec::new()) 130 } 131 132 /// Builds a checkpoint from BF16 payloads without a safetensors file. 133 /// Payloads are concatenated into one `Arc<[u8]>`. Each tensor records its range. 134 pub fn from_bf16_tensors(items: Vec<(String, Vec, Vec)>) -> Self { 135 let mut payload = Vec::new(); 136 let mut tensors = HashMap::with_capacity(items.len()); 137 for (name, shape, raw) in items { 138 let start = payload.len(); 139 payload.extend_from_slice(&raw); 140 let end = payload.len(); 141 let logical_strides = crate::capsule::row_major_strides(&shape); 142 tensors.insert( 143 name, 144 crate::capsule::CapsuleTensor { 145 dtype: crate::capsule::WeightDType::Bf16, 146 layout: crate::capsule::TensorLayout::RowMajor, 147 shape, 148 logical_strides, 149 byte_range: start..end, 150 quant: None, 151 }, 152 ); 153 } 154 Self::from_owned_bytes(Arc::from(payload), tensors) 155 } 156 157 pub fn tensor_count(&self) -> usize { 158 self.capsule.tensors.len() 159 } 160 161 pub fn contains_tensor(&self, name: &str) -> bool { 162 self.capsule.tensors.contains_key(name) 163 } 164 165 pub fn decode_fp32(&self, name: &str) -> Result, crate::capsule::CapsuleError> { 166 self.capsule.decode_fp32(name) 167 } 168 169 pub fn tensor_bytes(&self, name: &str) -> Result<&[u8], crate::capsule::CapsuleError> { 170 self.capsule.tensor_bytes(name) 171 } 172 173 pub fn get_shape(&self, name: &str) -> Option<&Vec> { 174 self.capsule.tensors.get(name).map(|tensor| &tensor.shape) 175 } 176 177 fn from_owned_bytes( 178 bytes: Arc<[u8]>, 179 tensors: HashMap, 180 ) -> Self { 181 let source_digest = crate::capsule::source_digest(&bytes); 182 let capsule_digest = crate::capsule::capsule_digest(&bytes, &tensors); 183 Self { 184 capsule: crate::capsule::ModelCapsule { 185 bytes, 186 source_digest, 187 tensors, 188 capsule_digest, 189 }, 190 } 191 } 192 } 193 194 /// Decodes little-endian bfloat16 raw bytes to single-precision f32. 195 /// Each 16-bit BF16 word occupies the upper 16 bits of the IEEE-754 32-bit float. 196 pub fn decode_bf16_to_fp32(bf16_bytes: &[u8]) -> Vec { 197 let count = bf16_bytes.len() / 2; 198 let mut out = Vec::with_capacity(count); 199 for chunk in bf16_bytes.chunks_exact(2) { 200 let bits = u16::from_le_bytes([chunk[0], chunk[1]]); 201 out.push(f32::from_bits((bits as u32) << 16)); 202 } 203 out 204 } 205 206 /// Encodes single-precision f32 to little-endian bfloat16 raw bytes by truncation of lower 16 bits. 207 pub fn encode_fp32_to_bf16(floats: &[f32]) -> Vec { 208 let mut out = Vec::with_capacity(floats.len() * 2); 209 for &val in floats { 210 let bits = val.to_bits(); 211 let bf16_bits = (bits >> 16) as u16; 212 out.extend_from_slice(&bf16_bits.to_le_bytes()); 213 } 214 out 215 } 216 217 /// Generates the canonical catalog of all 201 TinyLlama-1.1B tensors with their expected shapes. 218 pub fn tinyllama_catalog() -> Vec<(String, Vec)> { 219 let mut catalog = Vec::with_capacity(201); 220 221 catalog.push(("model.embed_tokens.weight".to_string(), vec![32000, 2048])); 222 223 for layer in 0..22 { 224 let prefix = format!("model.layers.{}", layer); 225 catalog.push((format!("{}.input_layernorm.weight", prefix), vec![2048])); 226 catalog.push(( 227 format!("{}.self_attn.q_proj.weight", prefix), 228 vec![2048, 2048], 229 )); 230 catalog.push(( 231 format!("{}.self_attn.k_proj.weight", prefix), 232 vec![256, 2048], 233 )); 234 catalog.push(( 235 format!("{}.self_attn.v_proj.weight", prefix), 236 vec![256, 2048], 237 )); 238 catalog.push(( 239 format!("{}.self_attn.o_proj.weight", prefix), 240 vec![2048, 2048], 241 )); 242 catalog.push(( 243 format!("{}.post_attention_layernorm.weight", prefix), 244 vec![2048], 245 )); 246 catalog.push((format!("{}.mlp.gate_proj.weight", prefix), vec![5632, 2048])); 247 catalog.push((format!("{}.mlp.up_proj.weight", prefix), vec![5632, 2048])); 248 catalog.push((format!("{}.mlp.down_proj.weight", prefix), vec![2048, 5632])); 249 } 250 251 catalog.push(("model.norm.weight".to_string(), vec![2048])); 252 catalog.push(("lm_head.weight".to_string(), vec![32000, 2048])); 253 254 catalog 255 } 256 257 /// The tensor catalog of a Llama-architecture checkpoint (`LlamaForCausalLM`, or Qwen3 with 258 /// per-layer `q_norm`/`k_norm` when `config.qk_norm`) described by 259 /// `config`: names and shapes of every tensor the forward pass reads. `lm_head.weight` is 260 /// left out when the model ties its output projection to `model.embed_tokens.weight`. 261 /// For `ModelConfig::tinyllama_1_1b()` this is exactly [`tinyllama_catalog`]. 262 pub fn llama_catalog(config: &aien_abi_core::ModelConfig) -> Vec<(String, Vec)> { 263 let hidden = config.hidden_dim(); 264 let inter = config.intermediate_dim(); 265 let vocab = config.vocab_size(); 266 let q_dim = config.num_heads * config.head_dim; 267 let kv_dim = config.num_kv_heads * config.head_dim; 268 let mut catalog = Vec::with_capacity(3 + 11 * config.num_layers); 269 catalog.push(("model.embed_tokens.weight".to_string(), vec![vocab, hidden])); 270 for layer in 0..config.num_layers { 271 let prefix = format!("model.layers.{}", layer); 272 catalog.push((format!("{}.input_layernorm.weight", prefix), vec![hidden])); 273 catalog.push(( 274 format!("{}.self_attn.q_proj.weight", prefix), 275 vec![q_dim, hidden], 276 )); 277 catalog.push(( 278 format!("{}.self_attn.k_proj.weight", prefix), 279 vec![kv_dim, hidden], 280 )); 281 catalog.push(( 282 format!("{}.self_attn.v_proj.weight", prefix), 283 vec![kv_dim, hidden], 284 )); 285 catalog.push(( 286 format!("{}.self_attn.o_proj.weight", prefix), 287 vec![hidden, q_dim], 288 )); 289 catalog.push(( 290 format!("{}.post_attention_layernorm.weight", prefix), 291 vec![hidden], 292 )); 293 catalog.push(( 294 format!("{}.mlp.gate_proj.weight", prefix), 295 vec![inter, hidden], 296 )); 297 catalog.push(( 298 format!("{}.mlp.up_proj.weight", prefix), 299 vec![inter, hidden], 300 )); 301 catalog.push(( 302 format!("{}.mlp.down_proj.weight", prefix), 303 vec![hidden, inter], 304 )); 305 if config.qk_norm { 306 for name in ["q_norm", "k_norm"] { 307 catalog.push(( 308 format!("{}.self_attn.{}.weight", prefix, name), 309 vec![config.head_dim], 310 )); 311 } 312 } 313 } 314 catalog.push(("model.norm.weight".to_string(), vec![hidden])); 315 if !config.tie_word_embeddings { 316 catalog.push(("lm_head.weight".to_string(), vec![vocab, hidden])); 317 } 318 catalog 319 } 320 321 /// Parses a safetensors binary buffer and strictly validates against a specified tensor catalog. 322 /// The file is copied once into the capsule. Tensor ranges point into that buffer. 323 pub fn parse_safetensors_with_catalog( 324 bytes: &[u8], 325 catalog: &[(String, Vec)], 326 ) -> Result { 327 let bytes: Arc<[u8]> = Arc::from(bytes.to_vec()); 328 parse_safetensors_arc(bytes, catalog) 329 } 330 331 fn parse_safetensors_arc( 332 bytes: Arc<[u8]>, 333 catalog: &[(String, Vec)], 334 ) -> Result { 335 let whole = 0..bytes.len(); 336 parse_shards(bytes, &[whole], catalog) 337 } 338 339 /// Validates `catalog` against one or more safetensors files laid end to end in `bytes` 340 /// (`shards` are their byte ranges). Every catalog tensor must appear in exactly one shard. 341 fn parse_shards( 342 bytes: Arc<[u8]>, 343 shards: &[std::ops::Range], 344 catalog: &[(String, Vec)], 345 ) -> Result { 346 let mut tensors = HashMap::with_capacity(catalog.len()); 347 for shard in shards { 348 index_shard(&bytes, shard.clone(), catalog, &mut tensors)?; 349 } 350 if let Some((name, _)) = catalog.iter().find(|(name, _)| !tensors.contains_key(name)) { 351 return Err(CheckpointError::MissingTensor(name.clone())); 352 } 353 Ok(LoadedCheckpoint::from_owned_bytes(bytes, tensors)) 354 } 355 356 /// Indexes the catalog tensors present in the safetensors file at `bytes[shard]`. 357 fn index_shard( 358 all_bytes: &[u8], 359 shard: std::ops::Range, 360 catalog: &[(String, Vec)], 361 tensors: &mut HashMap, 362 ) -> Result<(), CheckpointError> { 363 let base = shard.start; 364 let bytes = &all_bytes[shard]; 365 if bytes.len() < 8 { 366 return Err(CheckpointError::InvalidHeader( 367 "Buffer smaller than 8-byte header prefix".to_string(), 368 )); 369 } 370 371 let header_len_raw = 372 u64::from_le_bytes(bytes[0..8].try_into().map_err(|_| { 373 CheckpointError::InvalidHeader("Failed to read header size".to_string()) 374 })?); 375 let header_len = usize::try_from(header_len_raw).map_err(|_| { 376 CheckpointError::InvalidHeader("Header length exceeds address space".to_string()) 377 })?; 378 379 let header_end = 8usize.checked_add(header_len).ok_or_else(|| { 380 CheckpointError::InvalidHeader("Header length arithmetic overflow".to_string()) 381 })?; 382 383 if bytes.len() < header_end { 384 return Err(CheckpointError::InvalidHeader(format!( 385 "Header length {} exceeds total buffer size {}", 386 header_len, 387 bytes.len() 388 ))); 389 } 390 391 let header_str = std::str::from_utf8(&bytes[8..header_end]).map_err(|e| { 392 CheckpointError::InvalidHeader(format!("Header JSON is not valid UTF-8: {}", e)) 393 })?; 394 395 let header: serde_json::Value = serde_json::from_str(header_str).map_err(|e| { 396 CheckpointError::InvalidHeader(format!("Failed to parse header JSON: {}", e)) 397 })?; 398 399 let header_obj = header.as_object().ok_or_else(|| { 400 CheckpointError::InvalidHeader("Header JSON must be an object".to_string()) 401 })?; 402 403 index_header( 404 header_obj, 405 bytes.len() - header_end, 406 base + header_end, 407 catalog, 408 tensors, 409 ) 410 } 411 412 /// Validates the catalog tensors named in one safetensors header against their declared shape, 413 /// dtype and offsets. `data_len` is the size of the data blob after the header; `data_start` is 414 /// the absolute position of that blob in whatever buffer or file the ranges refer to. 415 fn index_header( 416 header_obj: &serde_json::Map, 417 data_len: usize, 418 data_start: usize, 419 catalog: &[(String, Vec)], 420 tensors: &mut HashMap, 421 ) -> Result<(), CheckpointError> { 422 for (name, expected_shape) in catalog { 423 let Some(info) = header_obj.get(name) else { 424 continue; 425 }; 426 if tensors.contains_key(name) { 427 return Err(CheckpointError::InvalidHeader(format!( 428 "tensor {} appears in more than one shard", 429 name 430 ))); 431 } 432 433 // 1. Verify dtype is BF16. This catalog parser does not accept other dtypes. 434 let dtype = info 435 .get("dtype") 436 .and_then(|v| v.as_str()) 437 .ok_or_else(|| CheckpointError::MissingTensor(format!("{}.dtype", name)))?; 438 439 if dtype != "BF16" { 440 return Err(CheckpointError::DtypeMismatch { 441 tensor: name.clone(), 442 expected: "BF16".to_string(), 443 actual: dtype.to_string(), 444 }); 445 } 446 447 // 2. Verify shape matches canonical architecture 448 let shape_arr = info 449 .get("shape") 450 .and_then(|v| v.as_array()) 451 .ok_or_else(|| CheckpointError::MissingTensor(format!("{}.shape", name)))?; 452 453 let actual_shape: Vec = shape_arr 454 .iter() 455 .map(|v| { 456 v.as_u64() 457 .and_then(|n| usize::try_from(n).ok()) 458 .ok_or_else(|| { 459 CheckpointError::InvalidHeader(format!( 460 "Invalid dimension in shape for {}", 461 name 462 )) 463 }) 464 }) 465 .collect::, CheckpointError>>()?; 466 467 if actual_shape != *expected_shape { 468 return Err(CheckpointError::ShapeMismatch { 469 tensor: name.clone(), 470 expected: expected_shape.clone(), 471 actual: actual_shape, 472 }); 473 } 474 475 // 3. Verify offsets and byte length. Safetensors offsets are relative to the data blob. 476 let offsets_arr = info 477 .get("data_offsets") 478 .and_then(|v| v.as_array()) 479 .ok_or_else(|| CheckpointError::MissingTensor(format!("{}.data_offsets", name)))?; 480 481 if offsets_arr.len() != 2 { 482 return Err(CheckpointError::InvalidHeader(format!( 483 "data_offsets for {} must have exactly 2 elements", 484 name 485 ))); 486 } 487 488 let start = offsets_arr[0] 489 .as_u64() 490 .and_then(|n| usize::try_from(n).ok()) 491 .ok_or_else(|| { 492 CheckpointError::InvalidHeader(format!("Invalid start offset for {}", name)) 493 })?; 494 let end = offsets_arr[1] 495 .as_u64() 496 .and_then(|n| usize::try_from(n).ok()) 497 .ok_or_else(|| { 498 CheckpointError::InvalidHeader(format!("Invalid end offset for {}", name)) 499 })?; 500 let expected_bytes = expected_shape 501 .iter() 502 .try_fold(1usize, |n, d| n.checked_mul(*d)) 503 .and_then(|n| n.checked_mul(2)) 504 .ok_or_else(|| { 505 CheckpointError::InvalidHeader(format!("Tensor {} byte count overflows", name)) 506 })?; 507 508 if start > end || (end - start) != expected_bytes || end > data_len { 509 return Err(CheckpointError::OffsetOutOfBounds { 510 tensor: name.clone(), 511 offset: end, 512 buffer_len: data_len, 513 }); 514 } 515 516 // Ranges are absolute inside the whole file, including the 8-byte length and JSON header. 517 let abs_start = data_start.checked_add(start).ok_or_else(|| { 518 CheckpointError::InvalidHeader(format!("Tensor {} offset overflows", name)) 519 })?; 520 let abs_end = data_start.checked_add(end).ok_or_else(|| { 521 CheckpointError::InvalidHeader(format!("Tensor {} offset overflows", name)) 522 })?; 523 let logical_strides = crate::capsule::row_major_strides(&actual_shape); 524 tensors.insert( 525 name.clone(), 526 crate::capsule::CapsuleTensor { 527 dtype: crate::capsule::WeightDType::Bf16, 528 layout: crate::capsule::TensorLayout::RowMajor, 529 shape: actual_shape, 530 logical_strides, 531 byte_range: abs_start..abs_end, 532 quant: None, 533 }, 534 ); 535 } 536 537 Ok(()) 538 } 539 540 /// Loads a TinyLlama safetensors checkpoint from an owned byte buffer. 541 /// The `Vec` is moved into one `Arc` and is not copied per tensor. 542 pub fn load_safetensors_from_bytes(bytes: Vec) -> Result { 543 let catalog = tinyllama_catalog(); 544 parse_safetensors_arc(Arc::from(bytes), &catalog) 545 } 546 547 /// Name of the shard index Hugging Face writes beside sharded safetensors files. 548 pub const SAFETENSORS_INDEX: &str = "model.safetensors.index.json"; 549 550 // Bounds apply to disk input, not to in-memory tensor/capsule construction. 551 // Large BF16 checkpoints may span many shards; keep the aggregate limit above 552 // production model sizes while refusing absurd metadata and sparse file lengths. 553 const MAX_INDEX_BYTES: u64 = 16 << 20; 554 const MAX_HEADER_BYTES: u64 = 256 << 20; 555 const MAX_SHARD_BYTES: u64 = 256 << 30; 556 const MAX_CHECKPOINT_BYTES: u64 = 1 << 40; 557 558 fn invalid_file(path: &Path, reason: impl fmt::Display) -> CheckpointError { 559 CheckpointError::InvalidHeader(format!("{}: {reason}", path.display())) 560 } 561 562 /// Reject special files before open; O_NONBLOCK and O_NOFOLLOW guard against 563 /// swaps to FIFOs and symlinks at open. Retain this fd through reads. 564 fn open_regular(path: &Path, limit: u64) -> Result<(File, usize), CheckpointError> { 565 let candidate = std::fs::symlink_metadata(path).map_err(|e| invalid_file(path, e))?; 566 if !candidate.file_type().is_file() { 567 return Err(invalid_file(path, "symlink or nonregular checkpoint file")); 568 } 569 let file = OpenOptions::new() 570 .read(true) 571 .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW) 572 .open(path) 573 .map_err(|e| invalid_file(path, e))?; 574 let meta = file.metadata().map_err(|e| invalid_file(path, e))?; 575 if !meta.is_file() { 576 return Err(invalid_file(path, "not a regular file")); 577 } 578 if meta.len() > limit { 579 return Err(invalid_file(path, format!("file exceeds {limit} bytes"))); 580 } 581 let len = usize::try_from(meta.len()) 582 .map_err(|_| invalid_file(path, "file length exceeds address space"))?; 583 Ok((file, len)) 584 } 585 586 fn read_header( 587 file: &File, 588 path: &Path, 589 file_len: usize, 590 data_base: usize, 591 catalog: &[(String, Vec)], 592 tensors: &mut HashMap, 593 ) -> Result<(), CheckpointError> { 594 if file_len < 8 { 595 return Err(invalid_file( 596 path, 597 "Buffer smaller than 8-byte header prefix", 598 )); 599 } 600 let mut prefix = [0u8; 8]; 601 file.read_exact_at(&mut prefix, 0) 602 .map_err(|e| invalid_file(path, e))?; 603 let header_len = u64::from_le_bytes(prefix); 604 if header_len > MAX_HEADER_BYTES || header_len > (file_len - 8) as u64 { 605 return Err(invalid_file( 606 path, 607 format!("invalid header length {header_len}"), 608 )); 609 } 610 let header_len = usize::try_from(header_len) 611 .map_err(|_| invalid_file(path, "header length exceeds address space"))?; 612 let header_end = 8 + header_len; 613 let mut header = vec![0u8; header_len]; 614 file.read_exact_at(&mut header, 8) 615 .map_err(|e| invalid_file(path, e))?; 616 let header: serde_json::Value = serde_json::from_slice(&header) 617 .map_err(|e| invalid_file(path, format!("invalid header JSON: {e}")))?; 618 let object = header 619 .as_object() 620 .ok_or_else(|| invalid_file(path, "header JSON must be an object"))?; 621 index_header( 622 object, 623 file_len - header_end, 624 data_base 625 .checked_add(header_end) 626 .ok_or_else(|| invalid_file(path, "checkpoint byte offset overflow"))?, 627 catalog, 628 tensors, 629 ) 630 } 631 632 fn validate_catalog( 633 tensors: &HashMap, 634 catalog: &[(String, Vec)], 635 ) -> Result<(), CheckpointError> { 636 if let Some((name, _)) = catalog.iter().find(|(name, _)| !tensors.contains_key(name)) { 637 return Err(CheckpointError::MissingTensor(name.clone())); 638 } 639 Ok(()) 640 } 641 642 fn shard_path(dir: &Path, name: &str) -> Result { 643 let mut components = Path::new(name).components(); 644 if !matches!( 645 (components.next(), components.next()), 646 (Some(Component::Normal(component)), None) if component == name 647 ) { 648 return Err(CheckpointError::InvalidHeader(format!( 649 "shard name {name:?} must be a plain file name" 650 ))); 651 } 652 let path = dir.join(name); 653 // A symlink inside the directory can itself lead outside. Reject it, 654 // including when a caller only asks for checkpoint_files/digest inputs. 655 let meta = std::fs::symlink_metadata(&path).map_err(|e| invalid_file(&path, e))?; 656 if !meta.file_type().is_file() { 657 return Err(invalid_file( 658 &path, 659 "shard is a symlink or not a regular file", 660 )); 661 } 662 Ok(path) 663 } 664 665 /// Digest the same bounded, regular checkpoint file that a loader may open. 666 /// Keep the descriptor pinned so a path swap cannot change the file mid-read. 667 pub fn checkpoint_sha256(path: &Path) -> Result<[u8; 32], CheckpointError> { 668 use sha2::{Digest, Sha256}; 669 let limit = if path.file_name().and_then(|n| n.to_str()) == Some(SAFETENSORS_INDEX) { 670 MAX_INDEX_BYTES 671 } else { 672 MAX_SHARD_BYTES 673 }; 674 let (file, len) = open_regular(path, limit)?; 675 let mut hasher = Sha256::new(); 676 let mut buf = vec![0u8; len.min(1 << 20)]; 677 let mut offset = 0usize; 678 while offset < len { 679 let count = (len - offset).min(buf.len()); 680 file.read_exact_at(&mut buf[..count], offset as u64) 681 .map_err(|e| invalid_file(path, e))?; 682 hasher.update(&buf[..count]); 683 offset += count; 684 } 685 if file.metadata().map_err(|e| invalid_file(path, e))?.len() != len as u64 { 686 return Err(invalid_file(path, "file length changed during digest")); 687 } 688 Ok(hasher.finalize().into()) 689 } 690 691 /// The files a checkpoint path names. 692 enum ResolvedFiles { 693 /// One `.safetensors` file. 694 Single(PathBuf), 695 /// The `model.safetensors.index.json` and the shard files it names, as `(name in the 696 /// index, path)`, sorted by name and de-duplicated. 697 Sharded { 698 index: PathBuf, 699 shards: Vec<(String, PathBuf)>, 700 }, 701 } 702 703 impl ResolvedFiles { 704 fn into_paths(self) -> Vec { 705 match self { 706 Self::Single(p) => vec![p], 707 Self::Sharded { shards, .. } => shards.into_iter().map(|(_, p)| p).collect(), 708 } 709 } 710 } 711 712 /// The files a checkpoint path names, exactly as the loaders read them (sc#338): what the 713 /// daemon digests so its record binds the weight bytes, not only the path it was given. 714 #[derive(Debug, Clone, PartialEq, Eq)] 715 pub struct CheckpointFiles { 716 /// The `model.safetensors.index.json` read; None for a single file. 717 pub index: Option, 718 /// Every weight file as `(name, path)`, sorted by name and de-duplicated: the name the 719 /// index's `weight_map` gives a shard, or the file name of a single file. 720 pub weights: Vec<(String, PathBuf)>, 721 } 722 723 /// Resolves `path` like [`load_checkpoint_with_catalog`] and [`StreamedCheckpoint::open`] 724 /// do: a `.safetensors` file, a `model.safetensors.index.json`, a model directory holding 725 /// either, or a shard file whose directory has an index (the whole sharded set). 726 pub fn checkpoint_files>(path: P) -> Result { 727 Ok(match resolve_checkpoint_files(path.as_ref())? { 728 ResolvedFiles::Single(p) => { 729 open_regular(&p, MAX_SHARD_BYTES)?; 730 CheckpointFiles { 731 index: None, 732 weights: vec![( 733 p.file_name() 734 .map(|n| n.to_string_lossy().into_owned()) 735 .unwrap_or_default(), 736 p, 737 )], 738 } 739 } 740 ResolvedFiles::Sharded { index, shards } => CheckpointFiles { 741 index: Some(index), 742 weights: shards, 743 }, 744 }) 745 } 746 747 /// Decides which files `path` names: a `.safetensors` file, a `model.safetensors.index.json` 748 /// (sharded), or a model directory holding either. A shard file whose directory has an index 749 /// names the whole sharded set. 750 fn resolve_checkpoint_files(p: &Path) -> Result { 751 let index = if p.is_dir() { 752 let single = p.join("model.safetensors"); 753 if single.is_file() { 754 return Ok(ResolvedFiles::Single(single)); 755 } 756 p.join(SAFETENSORS_INDEX) 757 } else if p.file_name().and_then(|n| n.to_str()) == Some(SAFETENSORS_INDEX) { 758 p.to_path_buf() 759 } else { 760 let sibling = p.with_file_name(SAFETENSORS_INDEX); 761 let is_shard = p.file_name().and_then(|n| n.to_str()) != Some("model.safetensors"); 762 if !(is_shard && sibling.is_file()) { 763 return Ok(ResolvedFiles::Single(p.to_path_buf())); 764 } 765 sibling 766 }; 767 let (index_file, index_len) = open_regular(&index, MAX_INDEX_BYTES)?; 768 let mut index_bytes = vec![0u8; index_len]; 769 index_file 770 .read_exact_at(&mut index_bytes, 0) 771 .map_err(|e| invalid_file(&index, e))?; 772 let index_json: serde_json::Value = serde_json::from_slice(&index_bytes) 773 .map_err(|e| invalid_file(&index, format!("invalid index JSON: {e}")))?; 774 let weight_map = index_json 775 .get("weight_map") 776 .and_then(|m| m.as_object()) 777 .ok_or_else(|| invalid_file(&index, "missing weight_map"))?; 778 let mut files: Vec<&str> = weight_map 779 .values() 780 .map(|v| { 781 v.as_str() 782 .ok_or_else(|| invalid_file(&index, "non-string shard name")) 783 }) 784 .collect::>()?; 785 files.sort_unstable(); 786 files.dedup(); 787 let dir = index.parent().unwrap_or(Path::new(".")); 788 let mut shards = Vec::with_capacity(files.len()); 789 let mut total = 0u64; 790 for name in files { 791 let path = shard_path(dir, name)?; 792 // checkpoint_files callers hash these paths, so reject nonregular or 793 // impossible disk lengths before handing any path to a caller. 794 let (_, len) = open_regular(&path, MAX_SHARD_BYTES)?; 795 total = total 796 .checked_add(len as u64) 797 .filter(|n| *n <= MAX_CHECKPOINT_BYTES) 798 .ok_or_else(|| invalid_file(&path, "checkpoint exceeds aggregate byte limit"))?; 799 shards.push((name.to_string(), path)); 800 } 801 Ok(ResolvedFiles::Sharded { index, shards }) 802 } 803 804 /// Loads and validates a checkpoint against `catalog`. `path` is a `.safetensors` file, a 805 /// `model.safetensors.index.json` (sharded), or a model directory holding either. A shard 806 /// file whose directory has an index loads the whole sharded set. 807 pub fn load_checkpoint_with_catalog>( 808 path: P, 809 catalog: &[(String, Vec)], 810 ) -> Result { 811 load_paths( 812 resolve_checkpoint_files(path.as_ref())?.into_paths(), 813 catalog, 814 ) 815 } 816 817 fn load_paths( 818 paths: Vec, 819 catalog: &[(String, Vec)], 820 ) -> Result { 821 let mut total = 0usize; 822 let mut tensors = HashMap::with_capacity(catalog.len()); 823 let mut opened = Vec::with_capacity(paths.len()); 824 let mut ranges = Vec::with_capacity(paths.len()); 825 for path in &paths { 826 let (file, len) = open_regular(path, MAX_SHARD_BYTES)?; 827 let end = total 828 .checked_add(len) 829 .filter(|n| (*n as u64) <= MAX_CHECKPOINT_BYTES) 830 .ok_or_else(|| invalid_file(path, "checkpoint exceeds aggregate byte limit"))?; 831 read_header(&file, path, len, total, catalog, &mut tensors)?; 832 ranges.push(total..end); 833 opened.push(file); 834 total = end; 835 } 836 validate_catalog(&tensors, catalog)?; 837 // A small catalog must not authorize a terabyte-sized sparse payload. 838 // Allow one header budget per shard and room for extra checkpoint tensors, 839 // but scale the eager read with the model this caller actually expects. 840 let expected = catalog 841 .iter() 842 .try_fold(0u64, |sum, (_, shape)| { 843 shape 844 .iter() 845 .try_fold(2u64, |bytes, dim| bytes.checked_mul(*dim as u64)) 846 .and_then(|bytes| sum.checked_add(bytes)) 847 }) 848 .ok_or_else(|| CheckpointError::InvalidHeader("catalog byte count overflows".into()))?; 849 let overhead = (paths.len() as u64).saturating_mul(MAX_HEADER_BYTES + 8); 850 let budget = expected 851 .saturating_mul(2) 852 .saturating_add(overhead) 853 .min(MAX_CHECKPOINT_BYTES); 854 if (total as u64) > budget { 855 return Err(CheckpointError::InvalidHeader(format!( 856 "checkpoint exceeds catalog byte budget {budget}" 857 ))); 858 } 859 // Nothing above has allocated a full shard: all required tensor headers 860 // and spans have been checked first, including cross-shard duplicates. 861 let mut bytes = Vec::new(); 862 bytes 863 .try_reserve_exact(total) 864 .map_err(|e| CheckpointError::InvalidHeader(format!("checkpoint allocation: {e}")))?; 865 bytes.resize(total, 0); 866 for ((path, file), range) in paths.iter().zip(opened.iter()).zip(ranges.iter()) { 867 file.read_exact_at(&mut bytes[range.clone()], 0) 868 .map_err(|e| invalid_file(path, e))?; 869 if file.metadata().map_err(|e| invalid_file(path, e))?.len() != range.len() as u64 { 870 return Err(invalid_file(path, "shard length changed during read")); 871 } 872 } 873 // Check headers again in case an open file was modified between preflight 874 // and payload read. The capsule must index exactly the bytes it owns. 875 parse_shards(Arc::from(bytes), &ranges, catalog) 876 } 877 878 /// A checkpoint indexed but not read: the catalog is validated against each shard's header 879 /// (the same checks as [`load_checkpoint_with_catalog`]) and tensor bytes are read one tensor 880 /// at a time with positioned reads, so no whole-file copy is ever held in process memory. 881 /// The shard pages stay in the kernel's page cache, which the kernel can reclaim. 882 #[derive(Debug)] 883 pub struct StreamedCheckpoint { 884 files: Vec<(PathBuf, File)>, 885 tensors: HashMap, 886 } 887 888 impl StreamedCheckpoint { 889 /// Indexes `path` (file, shard index, or model directory) against `catalog`. Reads only 890 /// each shard's header. Every catalog tensor must appear in exactly one shard. 891 pub fn open>( 892 path: P, 893 catalog: &[(String, Vec)], 894 ) -> Result { 895 let paths = resolve_checkpoint_files(path.as_ref())?.into_paths(); 896 let mut files = Vec::with_capacity(paths.len()); 897 let mut tensors = HashMap::with_capacity(catalog.len()); 898 let mut total = 0usize; 899 for path in paths { 900 let (file, len) = open_regular(&path, MAX_SHARD_BYTES)?; 901 total = total 902 .checked_add(len) 903 .filter(|n| (*n as u64) <= MAX_CHECKPOINT_BYTES) 904 .ok_or_else(|| invalid_file(&path, "checkpoint exceeds aggregate byte limit"))?; 905 let mut shard_tensors = HashMap::new(); 906 read_header(&file, &path, len, 0, catalog, &mut shard_tensors)?; 907 for (name, tensor) in shard_tensors { 908 if tensors 909 .insert(name.clone(), (files.len(), tensor)) 910 .is_some() 911 { 912 return Err(CheckpointError::InvalidHeader(format!( 913 "tensor {} appears in more than one shard", 914 name 915 ))); 916 } 917 } 918 files.push((path, file)); 919 } 920 if let Some((name, _)) = catalog.iter().find(|(name, _)| !tensors.contains_key(name)) { 921 return Err(CheckpointError::MissingTensor(name.clone())); 922 } 923 Ok(Self { files, tensors }) 924 } 925 926 /// Shape of `name` as the checkpoint declares it. 927 pub fn shape(&self, name: &str) -> Option<&[usize]> { 928 self.tensors.get(name).map(|(_, t)| t.shape.as_slice()) 929 } 930 931 /// Reads the raw little-endian bf16 bytes of `name` into `buf` (cleared first; its 932 /// capacity is reused across calls). Returns the number of bf16 values. 933 pub fn read_bf16_bytes(&self, name: &str, buf: &mut Vec) -> Result { 934 let (idx, tensor) = self 935 .tensors 936 .get(name) 937 .ok_or_else(|| CheckpointError::MissingTensor(name.to_string()))?; 938 let range = tensor.byte_range.clone(); 939 buf.clear(); 940 buf.try_reserve(range.len()) 941 .map_err(|e| CheckpointError::InvalidHeader(format!("tensor allocation: {e}")))?; 942 buf.resize(range.len(), 0); 943 let (path, file) = &self.files[*idx]; 944 file.read_exact_at(buf, range.start as u64) 945 .map_err(|e| invalid_file(path, format!("failed to read tensor {name}: {e}")))?; 946 Ok(range.len() / 2) 947 } 948 } 949 950 /// Loads and validates a TinyLlama safetensors checkpoint from a filesystem path. 951 pub fn load_safetensors_checkpoint>( 952 path: P, 953 ) -> Result { 954 load_paths(vec![path.as_ref().to_path_buf()], &tinyllama_catalog()) 955 } 956 957 #[cfg(test)] 958 mod tests { 959 use super::*; 960 use std::io::Write; 961 962 struct TestDir(PathBuf); 963 964 impl TestDir { 965 fn new() -> Self { 966 static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); 967 let path = std::env::temp_dir().join(format!( 968 "aien-checkpoint-security-{}-{}", 969 std::process::id(), 970 NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) 971 )); 972 std::fs::create_dir(&path).unwrap(); 973 Self(path) 974 } 975 976 fn index(&self, name: &str) { 977 let text = serde_json::json!({"weight_map": {"w": name}}).to_string(); 978 std::fs::write(self.0.join(SAFETENSORS_INDEX), text).unwrap(); 979 } 980 } 981 982 impl Drop for TestDir { 983 fn drop(&mut self) { 984 std::fs::remove_dir_all(&self.0).unwrap(); 985 } 986 } 987 988 fn security_catalog() -> Vec<(String, Vec)> { 989 vec![("w".to_string(), vec![1])] 990 } 991 992 fn security_loaders_reject(path: &Path) { 993 assert!(matches!( 994 load_checkpoint_with_catalog(path, &security_catalog()), 995 Err(CheckpointError::InvalidHeader(_)) 996 )); 997 assert!(matches!( 998 StreamedCheckpoint::open(path, &security_catalog()), 999 Err(CheckpointError::InvalidHeader(_)) 1000 )); 1001 } 1002 1003 fn security_files_reject(path: &Path) { 1004 security_loaders_reject(path); 1005 assert!(matches!( 1006 checkpoint_files(path), 1007 Err(CheckpointError::InvalidHeader(_)) 1008 )); 1009 } 1010 1011 #[test] 1012 fn single_checkpoint_rejects_nonregular_input() { 1013 let dir = TestDir::new(); 1014 let fifo = dir.0.join("model.safetensors"); 1015 let name = std::ffi::CString::new({ 1016 use std::os::unix::ffi::OsStrExt; 1017 fifo.as_os_str().as_bytes() 1018 }) 1019 .unwrap(); 1020 assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0); 1021 security_files_reject(&fifo); 1022 std::fs::remove_file(&fifo).unwrap(); 1023 std::os::unix::fs::symlink("/dev/zero", &fifo).unwrap(); 1024 security_files_reject(&fifo); 1025 } 1026 1027 #[test] 1028 fn shard_index_rejects_parent_absolute_and_symlink_escape() { 1029 let dir = TestDir::new(); 1030 let outside = dir.0.join("outside.safetensors"); 1031 let model = dir.0.join("model"); 1032 std::fs::create_dir(&model).unwrap(); 1033 std::fs::write( 1034 &outside, 1035 build_test_safetensors(&[("w", "BF16", &[1], &[0, 0])]), 1036 ) 1037 .unwrap(); 1038 let index = model.join(SAFETENSORS_INDEX); 1039 1040 std::fs::write(&index, r#"{"weight_map":{"w":"../outside.safetensors"}}"#).unwrap(); 1041 security_files_reject(&index); 1042 std::fs::write( 1043 &index, 1044 serde_json::json!({"weight_map": {"w": outside.to_str().unwrap()}}).to_string(), 1045 ) 1046 .unwrap(); 1047 security_files_reject(&index); 1048 std::os::unix::fs::symlink(&outside, model.join("link.safetensors")).unwrap(); 1049 std::fs::write(&index, r#"{"weight_map":{"w":"link.safetensors"}}"#).unwrap(); 1050 security_files_reject(&index); 1051 assert!(matches!( 1052 checkpoint_sha256(&model.join("link.safetensors")), 1053 Err(CheckpointError::InvalidHeader(_)) 1054 )); 1055 } 1056 1057 #[test] 1058 fn shard_index_rejects_nonregular_and_oversized_inputs_before_reading() { 1059 let dir = TestDir::new(); 1060 let index = dir.0.join(SAFETENSORS_INDEX); 1061 dir.index("directory.safetensors"); 1062 std::fs::create_dir(dir.0.join("directory.safetensors")).unwrap(); 1063 security_files_reject(&index); 1064 1065 // A FIFO would block on open without O_NONBLOCK; never open an endless device. 1066 let fifo = dir.0.join("fifo.safetensors"); 1067 let name = std::ffi::CString::new({ 1068 use std::os::unix::ffi::OsStrExt; 1069 fifo.as_os_str().as_bytes() 1070 }) 1071 .unwrap(); 1072 assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0); 1073 dir.index("fifo.safetensors"); 1074 security_files_reject(&index); 1075 1076 let oversized_index = std::fs::OpenOptions::new() 1077 .write(true) 1078 .open(&index) 1079 .unwrap(); 1080 oversized_index.set_len(MAX_INDEX_BYTES + 1).unwrap(); 1081 security_files_reject(&index); 1082 1083 dir.index("large.safetensors"); 1084 let shard = dir.0.join("large.safetensors"); 1085 let large = std::fs::File::create(&shard).unwrap(); 1086 large.set_len(MAX_SHARD_BYTES + 1).unwrap(); 1087 security_files_reject(&index); 1088 let mut header = std::fs::File::create(&shard).unwrap(); 1089 header 1090 .write_all(&(MAX_HEADER_BYTES + 1).to_le_bytes()) 1091 .unwrap(); 1092 security_loaders_reject(&index); 1093 } 1094 1095 #[test] 1096 fn sharded_loader_validates_before_allocating_and_preserves_valid_payload() { 1097 let dir = TestDir::new(); 1098 let index = dir.0.join(SAFETENSORS_INDEX); 1099 dir.index("a.safetensors"); 1100 let file = dir.0.join("a.safetensors"); 1101 let valid = build_test_safetensors(&[("w", "BF16", &[1], &[0, 0x3f])]); 1102 std::fs::write(&file, &valid).unwrap(); 1103 use sha2::Digest; 1104 assert_eq!( 1105 checkpoint_sha256(&file).unwrap().as_slice(), 1106 sha2::Sha256::digest(&valid).as_slice() 1107 ); 1108 assert_eq!( 1109 load_checkpoint_with_catalog(&index, &security_catalog()) 1110 .unwrap() 1111 .tensor_bytes("w") 1112 .unwrap(), 1113 &[0, 0x3f] 1114 ); 1115 let streamed = StreamedCheckpoint::open(&index, &security_catalog()).unwrap(); 1116 let mut raw = Vec::new(); 1117 streamed.read_bf16_bytes("w", &mut raw).unwrap(); 1118 assert_eq!(raw, &[0, 0x3f]); 1119 1120 // A sparse file advertises a large length, but an invalid required span must 1121 // be rejected from its header, before the whole-file loader allocates it. 1122 let invalid = br#"{"w":{"dtype":"BF16","shape":[1],"data_offsets":[0,999999]}}"#; 1123 let mut sparse = std::fs::File::create(&file).unwrap(); 1124 sparse 1125 .write_all(&(invalid.len() as u64).to_le_bytes()) 1126 .unwrap(); 1127 sparse.write_all(invalid).unwrap(); 1128 sparse.set_len(MAX_SHARD_BYTES).unwrap(); 1129 assert!(matches!( 1130 load_checkpoint_with_catalog(&index, &security_catalog()), 1131 Err(CheckpointError::OffsetOutOfBounds { .. }) 1132 )); 1133 // Even a plausible required span cannot authorize a giant unaccounted 1134 // payload when this catalog expects only one BF16 element. 1135 std::fs::write(&file, &valid).unwrap(); 1136 std::fs::OpenOptions::new() 1137 .write(true) 1138 .open(&file) 1139 .unwrap() 1140 .set_len(MAX_SHARD_BYTES) 1141 .unwrap(); 1142 assert!(matches!( 1143 load_checkpoint_with_catalog(&index, &security_catalog()), 1144 Err(CheckpointError::InvalidHeader(_)) 1145 )); 1146 } 1147 1148 #[test] 1149 fn sharded_loader_rejects_aggregate_sparse_length_before_payload_read() { 1150 let dir = TestDir::new(); 1151 let mut map = serde_json::Map::new(); 1152 for n in 0..=(MAX_CHECKPOINT_BYTES / MAX_SHARD_BYTES) { 1153 let name = format!("{n}.safetensors"); 1154 let path = dir.0.join(&name); 1155 let mut file = std::fs::File::create(&path).unwrap(); 1156 let header = if n == 0 { 1157 br#"{"w":{"dtype":"BF16","shape":[1],"data_offsets":[0,2]}}"#.as_slice() 1158 } else { 1159 b"{}".as_slice() 1160 }; 1161 file.write_all(&(header.len() as u64).to_le_bytes()) 1162 .unwrap(); 1163 file.write_all(header).unwrap(); 1164 file.set_len(MAX_SHARD_BYTES).unwrap(); 1165 map.insert(format!("tensor{n}"), serde_json::Value::String(name)); 1166 } 1167 std::fs::write( 1168 dir.0.join(SAFETENSORS_INDEX), 1169 serde_json::json!({"weight_map": map}).to_string(), 1170 ) 1171 .unwrap(); 1172 let index = dir.0.join(SAFETENSORS_INDEX); 1173 security_files_reject(&index); 1174 } 1175 1176 /// Constructs a minimal valid safetensors binary buffer for testing. 1177 fn build_test_safetensors(tensors: &[(&str, &str, &[usize], &[u8])]) -> Vec { 1178 let mut header_map = serde_json::Map::new(); 1179 let mut data_payload = Vec::new(); 1180 1181 for (name, dtype, shape, payload) in tensors { 1182 let start = data_payload.len(); 1183 data_payload.extend_from_slice(payload); 1184 let end = data_payload.len(); 1185 1186 let mut tensor_info = serde_json::Map::new(); 1187 tensor_info.insert( 1188 "dtype".to_string(), 1189 serde_json::Value::String(dtype.to_string()), 1190 ); 1191 let shape_val = shape 1192 .iter() 1193 .map(|&d| serde_json::Value::Number(serde_json::Number::from(d))) 1194 .collect(); 1195 tensor_info.insert("shape".to_string(), serde_json::Value::Array(shape_val)); 1196 let offsets_val = vec![ 1197 serde_json::Value::Number(serde_json::Number::from(start)), 1198 serde_json::Value::Number(serde_json::Number::from(end)), 1199 ]; 1200 tensor_info.insert( 1201 "data_offsets".to_string(), 1202 serde_json::Value::Array(offsets_val), 1203 ); 1204 1205 header_map.insert(name.to_string(), serde_json::Value::Object(tensor_info)); 1206 } 1207 1208 let header_json = serde_json::Value::Object(header_map).to_string(); 1209 let header_bytes = header_json.as_bytes(); 1210 let header_len = header_bytes.len() as u64; 1211 1212 let mut buffer = Vec::new(); 1213 buffer.extend_from_slice(&header_len.to_le_bytes()); 1214 buffer.extend_from_slice(header_bytes); 1215 buffer.extend_from_slice(&data_payload); 1216 buffer 1217 } 1218 1219 #[test] 1220 fn test_tinyllama_catalog_size_and_shapes() { 1221 let catalog = tinyllama_catalog(); 1222 assert_eq!(catalog.len(), 201); 1223 1224 assert_eq!(catalog[0].0, "model.embed_tokens.weight"); 1225 assert_eq!(catalog[0].1, vec![32000, 2048]); 1226 1227 assert_eq!(catalog[200].0, "lm_head.weight"); 1228 assert_eq!(catalog[200].1, vec![32000, 2048]); 1229 1230 assert_eq!(catalog[199].0, "model.norm.weight"); 1231 assert_eq!(catalog[199].1, vec![2048]); 1232 } 1233 1234 #[test] 1235 fn test_bf16_fp32_codec_roundtrip() { 1236 let floats = vec![0.0f32, 1.0f32, -1.0f32, 0.5f32, 64.0f32]; 1237 let bf16_bytes = encode_fp32_to_bf16(&floats); 1238 let decoded = decode_bf16_to_fp32(&bf16_bytes); 1239 1240 assert_eq!(decoded.len(), floats.len()); 1241 assert_eq!(decoded[0], 0.0); 1242 assert_eq!(decoded[1], 1.0); 1243 assert_eq!(decoded[2], -1.0); 1244 assert_eq!(decoded[3], 0.5); 1245 assert_eq!(decoded[4], 64.0); 1246 } 1247 1248 #[test] 1249 fn test_valid_custom_catalog_parsing() { 1250 let floats = vec![1.5f32, 2.5f32, -0.5f32, 4.0f32]; 1251 let bf16_bytes = encode_fp32_to_bf16(&floats); 1252 let buffer = build_test_safetensors(&[("test.weight", "BF16", &[2, 2], &bf16_bytes)]); 1253 1254 let catalog = vec![("test.weight".to_string(), vec![2, 2])]; 1255 let loaded = parse_safetensors_with_catalog(&buffer, &catalog).unwrap(); 1256 1257 assert_eq!(loaded.tensor_count(), 1); 1258 assert_eq!(loaded.capsule.tensors["test.weight"].shape, vec![2, 2]); 1259 assert_eq!(loaded.get_shape("test.weight").unwrap(), &vec![2, 2]); 1260 let fp32 = loaded.decode_fp32("test.weight").unwrap(); 1261 assert_eq!(fp32.len(), 4); 1262 assert_eq!(fp32[0], 1.5); 1263 assert_eq!(fp32[1], 2.5); 1264 assert_eq!(loaded.tensor_bytes("test.weight").unwrap(), &bf16_bytes[..]); 1265 assert!(matches!( 1266 loaded.capsule.tensors["test.weight"].dtype, 1267 crate::capsule::WeightDType::Bf16 1268 )); 1269 assert!(loaded.capsule.tensors["test.weight"].quant.is_none()); 1270 } 1271 1272 #[test] 1273 fn test_capsule_owns_file_bytes_and_byte_range_points_at_payload() { 1274 let floats = vec![1.0f32, -1.0f32, 0.5f32]; 1275 let bf16_bytes = encode_fp32_to_bf16(&floats); 1276 let file_bytes = build_test_safetensors(&[("w", "BF16", &[3], &bf16_bytes)]); 1277 let catalog = vec![("w".to_string(), vec![3])]; 1278 let loaded = parse_safetensors_with_catalog(&file_bytes, &catalog).unwrap(); 1279 1280 assert_eq!(loaded.capsule.owned_payload_len(), file_bytes.len()); 1281 assert_eq!(loaded.capsule.bytes.as_ref(), file_bytes.as_slice()); 1282 assert_eq!( 1283 loaded.capsule.source_digest, 1284 crate::capsule::source_digest(&file_bytes) 1285 ); 1286 1287 let range = loaded.capsule.tensors["w"].byte_range.clone(); 1288 assert!(range.start >= 8); 1289 assert_eq!(range.end - range.start, bf16_bytes.len()); 1290 assert_eq!(&loaded.capsule.bytes[range], bf16_bytes.as_slice()); 1291 assert_eq!(loaded.tensor_bytes("w").unwrap(), bf16_bytes.as_slice()); 1292 let decoded = loaded.decode_fp32("w").unwrap(); 1293 assert_eq!(decoded, decode_bf16_to_fp32(&bf16_bytes)); 1294 } 1295 1296 #[test] 1297 fn test_from_bf16_tensors_one_buffer() { 1298 let a = encode_fp32_to_bf16(&[1.0, 2.0]); 1299 let b = encode_fp32_to_bf16(&[0.5]); 1300 let loaded = LoadedCheckpoint::from_bf16_tensors(vec![ 1301 ("a".to_string(), vec![2], a.clone()), 1302 ("b".to_string(), vec![1], b.clone()), 1303 ]); 1304 1305 assert_eq!(loaded.capsule.owned_payload_len(), a.len() + b.len()); 1306 assert_eq!(loaded.tensor_bytes("a").unwrap(), a.as_slice()); 1307 assert_eq!(loaded.tensor_bytes("b").unwrap(), b.as_slice()); 1308 assert_eq!(loaded.decode_fp32("a").unwrap()[0], 1.0); 1309 assert_eq!(loaded.decode_fp32("b").unwrap()[0], 0.5); 1310 assert_eq!( 1311 loaded.capsule.tensors["a"].logical_strides, 1312 crate::capsule::row_major_strides(&[2]) 1313 ); 1314 assert!(loaded.capsule.tensors["b"].quant.is_none()); 1315 assert_eq!( 1316 loaded.capsule.source_digest, 1317 crate::capsule::source_digest(&loaded.capsule.bytes) 1318 ); 1319 assert_eq!( 1320 loaded.capsule.capsule_digest, 1321 crate::capsule::capsule_digest(&loaded.capsule.bytes, &loaded.capsule.tensors) 1322 ); 1323 1324 let empty = LoadedCheckpoint::new(); 1325 assert_eq!(empty.tensor_count(), 0); 1326 assert_eq!(empty.capsule.owned_payload_len(), 0); 1327 assert!(empty.capsule.tensors.is_empty()); 1328 assert_eq!( 1329 empty.capsule.source_digest, 1330 crate::capsule::source_digest(&[]) 1331 ); 1332 } 1333 1334 #[test] 1335 fn test_missing_tensor_loud_error() { 1336 let floats = vec![1.0f32, 2.0f32]; 1337 let bf16_bytes = encode_fp32_to_bf16(&floats); 1338 let buffer = build_test_safetensors(&[("present.weight", "BF16", &[2], &bf16_bytes)]); 1339 1340 let catalog = vec![ 1341 ("present.weight".to_string(), vec![2]), 1342 ("missing.weight".to_string(), vec![2]), 1343 ]; 1344 1345 let err = parse_safetensors_with_catalog(&buffer, &catalog).unwrap_err(); 1346 assert_eq!( 1347 err, 1348 CheckpointError::MissingTensor("missing.weight".to_string()) 1349 ); 1350 } 1351 1352 #[test] 1353 fn test_shape_mismatch_loud_error() { 1354 let floats = vec![1.0f32, 2.0f32]; 1355 let bf16_bytes = encode_fp32_to_bf16(&floats); 1356 let buffer = build_test_safetensors(&[("layer.weight", "BF16", &[2], &bf16_bytes)]); 1357 1358 let catalog = vec![("layer.weight".to_string(), vec![4])]; 1359 1360 let err = parse_safetensors_with_catalog(&buffer, &catalog).unwrap_err(); 1361 match err { 1362 CheckpointError::ShapeMismatch { 1363 tensor, 1364 expected, 1365 actual, 1366 } => { 1367 assert_eq!(tensor, "layer.weight"); 1368 assert_eq!(expected, vec![4]); 1369 assert_eq!(actual, vec![2]); 1370 } 1371 _ => panic!("Expected ShapeMismatch"), 1372 } 1373 } 1374 1375 #[test] 1376 fn test_dtype_mismatch_loud_error() { 1377 let raw_f32_bytes = vec![0u8; 16]; // 4 floats 1378 let buffer = build_test_safetensors(&[("layer.weight", "F32", &[4], &raw_f32_bytes)]); 1379 1380 let catalog = vec![("layer.weight".to_string(), vec![4])]; 1381 1382 let err = parse_safetensors_with_catalog(&buffer, &catalog).unwrap_err(); 1383 match err { 1384 CheckpointError::DtypeMismatch { 1385 tensor, 1386 expected, 1387 actual, 1388 } => { 1389 assert_eq!(tensor, "layer.weight"); 1390 assert_eq!(expected, "BF16"); 1391 assert_eq!(actual, "F32"); 1392 } 1393 _ => panic!("Expected DtypeMismatch"), 1394 } 1395 } 1396 1397 #[test] 1398 fn test_offset_out_of_bounds_loud_error() { 1399 // Create corrupted header where end offset exceeds payload 1400 let header_json = r#"{"weight":{"dtype":"BF16","shape":[4],"data_offsets":[0,100]}}"#; 1401 let header_bytes = header_json.as_bytes(); 1402 let header_len = header_bytes.len() as u64; 1403 1404 let mut buffer = Vec::new(); 1405 buffer.extend_from_slice(&header_len.to_le_bytes()); 1406 buffer.extend_from_slice(header_bytes); 1407 buffer.extend_from_slice(&[0u8; 8]); // only 8 bytes payload, offset requires 100 1408 1409 let catalog = vec![("weight".to_string(), vec![4])]; 1410 let err = parse_safetensors_with_catalog(&buffer, &catalog).unwrap_err(); 1411 match err { 1412 CheckpointError::OffsetOutOfBounds { 1413 tensor, 1414 offset, 1415 buffer_len, 1416 } => { 1417 assert_eq!(tensor, "weight"); 1418 assert_eq!(offset, 100); 1419 assert_eq!(buffer_len, 8); 1420 } 1421 _ => panic!("Expected OffsetOutOfBounds"), 1422 } 1423 } 1424 1425 #[test] 1426 fn test_invalid_header_truncated_buffer() { 1427 let buffer = vec![1, 2, 3]; 1428 let catalog = vec![("weight".to_string(), vec![2])]; 1429 let err = parse_safetensors_with_catalog(&buffer, &catalog).unwrap_err(); 1430 match err { 1431 CheckpointError::InvalidHeader(_) => {} 1432 _ => panic!("Expected InvalidHeader"), 1433 } 1434 } 1435 1436 #[test] 1437 fn test_header_len_arithmetic_overflow() { 1438 let mut buffer = Vec::new(); 1439 buffer.extend_from_slice(&u64::MAX.to_le_bytes()); 1440 buffer.extend_from_slice(b"payload"); 1441 let catalog = vec![("weight".to_string(), vec![2])]; 1442 let err = parse_safetensors_with_catalog(&buffer, &catalog).unwrap_err(); 1443 match err { 1444 CheckpointError::InvalidHeader(_) => {} 1445 _ => panic!("Expected InvalidHeader on arithmetic overflow"), 1446 } 1447 } 1448 1449 /// sc#338: the files the loader reads, named for the daemon's digest: the index and 1450 /// every shard it names (sorted, de-duplicated, by the index's name); a single file 1451 /// has no index. 1452 #[test] 1453 fn checkpoint_files_names_the_index_and_every_shard() { 1454 let dir = std::env::temp_dir().join(format!("aien-ckfiles-{}", std::process::id())); 1455 std::fs::create_dir_all(&dir).unwrap(); 1456 let index = dir.join(SAFETENSORS_INDEX); 1457 std::fs::write( 1458 &index, 1459 r#"{"weight_map":{"x":"b.safetensors","y":"a.safetensors","z":"b.safetensors"}}"#, 1460 ) 1461 .unwrap(); 1462 std::fs::write(dir.join("a.safetensors"), b"").unwrap(); 1463 std::fs::write(dir.join("b.safetensors"), b"").unwrap(); 1464 let files = checkpoint_files(&index).unwrap(); 1465 assert_eq!(files.index.as_deref(), Some(index.as_path())); 1466 assert_eq!( 1467 files.weights, 1468 vec![ 1469 ("a.safetensors".to_string(), dir.join("a.safetensors")), 1470 ("b.safetensors".to_string(), dir.join("b.safetensors")), 1471 ] 1472 ); 1473 // A shard file beside an index names the whole set, like the loader. 1474 assert_eq!(checkpoint_files(dir.join("a.safetensors")).unwrap(), files); 1475 let single = dir.join("model.safetensors"); 1476 std::fs::write(&single, b"").unwrap(); 1477 let files = checkpoint_files(&single).unwrap(); 1478 assert_eq!(files.index, None); 1479 assert_eq!( 1480 files.weights, 1481 vec![("model.safetensors".to_string(), single.clone())] 1482 ); 1483 std::fs::remove_dir_all(&dir).unwrap(); 1484 } 1485 }