Files
vetta-infer/crates/vetta-infer-ld/src/lib.rs
T
adm 0929bde578 [LD] reusable GPU layer forward (ld::layer) with persistent per-layer state
- ld::layer (feature hip): LayerWeights (load_layer reads all attention + MoE
  weights + learned depth-mix queries for a physical step ip), LayerState
  (persistent KV cache + ShortConv history rings, new_state), Dims, and
  layer_forward_swa — a complete SWA layer step composing the verified
  microkernels with the exact Inkling deep-residual cadence:
    ip==0: in0=attn_norm(cur); ip>0: in0=attn_norm(mix(blocks,cur,attn_query))
    attention block -> asc; ip%block_size==0: snapshot cur->blocks, cur=asc
      else cur+=asc
    mlpin=mlp_norm(mix(blocks,cur,mlp_query)); MoE block; cur+=mlp_sconv(moeout)
  The depth-block snapshots are owned by the caller (the forward residual
  stream); experts loaded on demand (zero requantization).
- Refactored real_full_layer_end_to_end to drive the GPU side through
  layer_forward_swa; the unchanged full CPU oracle still verifies it
  (max_rel_err 6.6e-4, identical experts) AND asserts the ip=0 block snapshot.
  This is the reusable foundation for the multi-layer forward.

Scope: SWA layers without loop controllers (prelude). Full-attn 3-query split,
loop controllers (gain/forget/down) and multi-pass bank rollback come next.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; real full layer via reusable fn PASS
(--features hip, --ignored).
2026-12-01 14:46:05 +01:00

433 lines
16 KiB
Rust

//! `vetta-infer-ld`: loader & compiler (docs/ARCHITECTURE.md §3, §9).
//!
//! Checked `.safetensors` reader (index.json + directory fallback + `pread` +
//! overflow-safe slice checks) and the write-once `VTC1` atomic cache writer
//! (`.tmp.<pid>` + `fsync` + `rename`). The dual-step ModelImporter → IR →
//! BackendPacker pipeline lands here with M1; `cc` owns the `O_RDONLY` reload.
//!
//! Eliminates audit-05 F-02 (shard bounds, u64 slice overflow, missing
//! index.json) and F-05 (PID-isolated atomic commit) by construction.
pub mod bundle;
pub mod inkling;
pub mod inkling_ir;
pub mod inkling_plan;
pub mod inkling_graph;
#[cfg(feature = "hip")]
pub mod packer;
#[cfg(feature = "hip")]
pub mod layer;
use std::collections::{BTreeSet, HashMap};
use std::fs::{self, File, OpenOptions};
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use vetta_infer_abi::json::parse_json;
use vetta_infer_abi::vtc1::{
align_up, serialize_meta, CacheRecord, CACHE_ALIGN, CACHE_MAGIC, CACHE_VERSION, HEADER_SIZE,
};
// ============================================================================
// 1. Checked Safetensors Archive Reader (`pread`, `index.json`, strict bounds)
// ============================================================================
#[derive(Debug, Clone)]
pub struct TensorInfo {
pub shard_idx: usize,
pub dtype: String,
pub shape: Vec<u64>,
pub begin: u64,
pub end: u64,
}
impl TensorInfo {
pub fn byte_len(&self) -> u64 {
self.end - self.begin
}
}
pub struct SafetensorsShard {
pub path: PathBuf,
pub file: File,
pub file_size: u64,
pub data_start: u64,
}
pub struct SafetensorsArchive {
pub dir: PathBuf,
pub shards: Vec<SafetensorsShard>,
pub tensors: HashMap<String, TensorInfo>,
}
const MAX_HEADER_BYTES: u64 = 128 * 1024 * 1024;
impl SafetensorsArchive {
pub fn open(dir: impl AsRef<Path>) -> Result<Self, String> {
let dir = dir.as_ref().to_path_buf();
let shard_paths = discover_shards(&dir)?;
if shard_paths.is_empty() {
return Err(format!("no .safetensors shards found in {}", dir.display()));
}
let mut shards = Vec::with_capacity(shard_paths.len());
let mut tensors = HashMap::new();
for (shard_idx, path) in shard_paths.into_iter().enumerate() {
let file = OpenOptions::new()
.read(true)
.open(&path)
.map_err(|e| format!("open {}: {e}", path.display()))?;
let file_size = file
.metadata()
.map_err(|e| format!("stat {}: {e}", path.display()))?
.len();
if file_size < 8 {
return Err(format!("truncated safetensors file {}", path.display()));
}
let mut len_buf = [0u8; 8];
file.read_exact_at(&mut len_buf, 0)
.map_err(|e| format!("read header len {}: {e}", path.display()))?;
let hlen = u64::from_le_bytes(len_buf);
let data_start = 8u64
.checked_add(hlen)
.ok_or_else(|| format!("header length overflow in {}", path.display()))?;
if hlen == 0 || hlen > MAX_HEADER_BYTES || data_start > file_size {
return Err(format!(
"invalid header length {hlen} (file_size={file_size}) in {}",
path.display()
));
}
let mut hbytes = vec![0u8; hlen as usize];
file.read_exact_at(&mut hbytes, 8)
.map_err(|e| format!("read header {}: {e}", path.display()))?;
let hstr = std::str::from_utf8(&hbytes)
.map_err(|_| format!("non-UTF-8 header in {}", path.display()))?;
let root = parse_json(hstr)?;
let obj = root
.as_obj()
.ok_or_else(|| format!("header root is not JSON object in {}", path.display()))?;
let avail = file_size - data_start;
for (name, val) in obj {
if name == "__metadata__" {
continue;
}
let to = val
.as_obj()
.ok_or_else(|| format!("tensor '{name}' entry is not object"))?;
let dtype = to
.get("dtype")
.and_then(|v| v.as_str())
.ok_or_else(|| format!("tensor '{name}' missing dtype"))?
.to_string();
let shape_arr = to
.get("shape")
.and_then(|v| v.as_arr())
.ok_or_else(|| format!("tensor '{name}' missing shape"))?;
let mut shape = Vec::with_capacity(shape_arr.len());
for d in shape_arr {
shape.push(d.as_u64().ok_or_else(|| format!("tensor '{name}' bad dim"))?);
}
let offs = to
.get("data_offsets")
.and_then(|v| v.as_arr())
.ok_or_else(|| format!("tensor '{name}' missing data_offsets"))?;
if offs.len() != 2 {
return Err(format!("tensor '{name}' data_offsets len != 2"));
}
let begin = offs[0].as_u64().ok_or_else(|| format!("tensor '{name}' bad begin"))?;
let end = offs[1].as_u64().ok_or_else(|| format!("tensor '{name}' bad end"))?;
if end < begin || end > avail {
return Err(format!(
"tensor '{name}' out of shard bounds [{begin}, {end}) vs avail={avail} in {}",
path.display()
));
}
if tensors.contains_key(name) {
return Err(format!("duplicate tensor '{name}' across shards"));
}
tensors.insert(
name.clone(),
TensorInfo {
shard_idx,
dtype,
shape,
begin,
end,
},
);
}
shards.push(SafetensorsShard {
path,
file,
file_size,
data_start,
});
}
Ok(Self { dir, shards, tensors })
}
pub fn total_tensor_bytes(&self) -> u64 {
self.tensors.values().map(|t| t.byte_len()).sum()
}
pub fn read_slice(&self, name: &str, rel_off: u64, dst: &mut [u8]) -> Result<(), String> {
let info = self
.tensors
.get(name)
.ok_or_else(|| format!("tensor not found: {name}"))?;
let total = info.byte_len();
let req = dst.len() as u64;
if rel_off > total || req > total - rel_off {
return Err(format!(
"slice OOB for '{name}': rel_off={rel_off} len={req} total={total}"
));
}
let sh = &self.shards[info.shard_idx];
let file_off = sh
.data_start
.checked_add(info.begin)
.and_then(|v| v.checked_add(rel_off))
.ok_or_else(|| format!("file offset overflow for '{name}'"))?;
sh.file
.read_exact_at(dst, file_off)
.map_err(|e| format!("pread '{}' at {file_off}: {e}", sh.path.display()))
}
}
fn discover_shards(dir: &Path) -> Result<Vec<PathBuf>, String> {
let idx_path = dir.join("model.safetensors.index.json");
if idx_path.is_file() {
let raw = fs::read_to_string(&idx_path)
.map_err(|e| format!("read {}: {e}", idx_path.display()))?;
let root = parse_json(&raw)?;
let wm = root
.as_obj()
.and_then(|o| o.get("weight_map"))
.and_then(|v| v.as_obj())
.ok_or_else(|| format!("missing weight_map in {}", idx_path.display()))?;
let mut uniq = BTreeSet::new();
for v in wm.values() {
if let Some(fname) = v.as_str() {
if !fname.is_empty() {
uniq.insert(dir.join(fname));
}
}
}
return Ok(uniq.into_iter().collect());
}
let entries = fs::read_dir(dir).map_err(|e| format!("list {}: {e}", dir.display()))?;
let mut out = Vec::new();
for entry in entries {
let e = entry.map_err(|e| format!("dir entry {}: {e}", dir.display()))?;
let p = e.path();
if p.is_file() && p.extension().and_then(|x| x.to_str()) == Some("safetensors") {
out.push(p);
}
}
out.sort();
Ok(out)
}
// ============================================================================
// 2. Write-Once `VTC1` Atomic Cache Writer (`.tmp.<pid>` + fsync + rename)
// ============================================================================
pub struct DiskCacheWriter {
final_path: PathBuf,
tmp_path: PathBuf,
file: Option<File>,
fingerprint: u64,
cursor: u64,
records: Vec<CacheRecord>,
}
impl DiskCacheWriter {
pub fn begin(final_path: impl AsRef<Path>, fingerprint: u64) -> Result<Self, String> {
let final_path = final_path.as_ref().to_path_buf();
if let Some(parent) = final_path.parent() {
fs::create_dir_all(parent).map_err(|e| format!("mkdir {}: {e}", parent.display()))?;
}
let pid = std::process::id();
let tmp_path = PathBuf::from(format!("{}.tmp.{pid}", final_path.display()));
let file = OpenOptions::new()
.create(true)
.truncate(true)
.read(true)
.write(true)
.open(&tmp_path)
.map_err(|e| format!("create {}: {e}", tmp_path.display()))?;
Ok(Self {
final_path,
tmp_path,
file: Some(file),
fingerprint,
cursor: CACHE_ALIGN,
records: Vec::new(),
})
}
pub fn write_record(&mut self, mut rec: CacheRecord, payload: &[u8]) -> Result<u64, String> {
let f = self.file.as_ref().ok_or_else(|| "writer closed".to_string())?;
rec.data_offset = align_up(self.cursor, CACHE_ALIGN)?;
rec.data_bytes = payload.len() as u64;
self.cursor = align_up(
rec.data_offset
.checked_add(rec.data_bytes)
.ok_or_else(|| "cache offset overflow".to_string())?,
CACHE_ALIGN,
)?;
f.write_all_at(payload, rec.data_offset)
.map_err(|e| format!("write payload: {e}"))?;
let off = rec.data_offset;
self.records.push(rec);
Ok(off)
}
pub fn commit(mut self) -> Result<PathBuf, String> {
let f = self.file.take().ok_or_else(|| "writer closed".to_string())?;
let meta = serialize_meta(&self.records);
let meta_off = align_up(self.cursor, CACHE_ALIGN)?;
f.write_all_at(&meta, meta_off)
.map_err(|e| format!("write meta: {e}"))?;
let total_bytes = meta_off
.checked_add(meta.len() as u64)
.ok_or_else(|| "total_bytes overflow".to_string())?;
let mut hdr = [0u8; HEADER_SIZE];
hdr[0..8].copy_from_slice(&CACHE_MAGIC);
hdr[8..12].copy_from_slice(&CACHE_VERSION.to_le_bytes());
hdr[12..16].copy_from_slice(&(self.records.len() as u32).to_le_bytes());
hdr[16..24].copy_from_slice(&self.fingerprint.to_le_bytes());
hdr[24..32].copy_from_slice(&meta_off.to_le_bytes());
hdr[32..40].copy_from_slice(&(meta.len() as u64).to_le_bytes());
hdr[40..48].copy_from_slice(&total_bytes.to_le_bytes());
f.write_all_at(&hdr, 0).map_err(|e| format!("write hdr: {e}"))?;
f.sync_all().map_err(|e| format!("fsync cache: {e}"))?;
drop(f);
fs::rename(&self.tmp_path, &self.final_path)
.map_err(|e| format!("rename cache: {e}"))?;
Ok(self.final_path.clone())
}
}
impl Drop for DiskCacheWriter {
fn drop(&mut self) {
if self.file.take().is_some() {
let _ = fs::remove_file(&self.tmp_path);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn write_mini_st(path: &Path, name: &str, data: &[u8], truncate: bool, invert: bool) {
let (b, e) = if invert { (data.len(), 0) } else { (0, data.len()) };
let hdr = format!(
"{{\"{name}\":{{\"dtype\":\"F32\",\"shape\":[{}],\"data_offsets\":[{b},{e}]}}}}",
data.len() / 4
);
let mut f = File::create(path).unwrap();
f.write_all(&(hdr.len() as u64).to_le_bytes()).unwrap();
f.write_all(hdr.as_bytes()).unwrap();
let take = if truncate && !data.is_empty() { data.len() - 1 } else { data.len() };
f.write_all(&data[..take]).unwrap();
}
#[test]
fn safetensors_bounds_overflow_and_index_json() {
let root = std::env::temp_dir().join(format!("vetta_ld_test_{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
// Non-existent dir fails cleanly
assert!(SafetensorsArchive::open(root.join("missing")).is_err());
// Truncated shard rejected
let d_trunc = root.join("trunc");
fs::create_dir_all(&d_trunc).unwrap();
write_mini_st(&d_trunc.join("a.safetensors"), "w", &[1, 2, 3, 4, 5, 6, 7, 8], true, false);
assert!(SafetensorsArchive::open(&d_trunc).is_err());
// Inverted offsets rejected
let d_inv = root.join("inv");
fs::create_dir_all(&d_inv).unwrap();
write_mini_st(&d_inv.join("a.safetensors"), "w", &[1, 2, 3, 4], false, true);
assert!(SafetensorsArchive::open(&d_inv).is_err());
// Valid + index.json ignoring stray backup + u64 overflow slice check
let d_ok = root.join("ok");
fs::create_dir_all(&d_ok).unwrap();
let bytes = [10u8, 20, 30, 40, 50, 60, 70, 80];
write_mini_st(&d_ok.join("s1.safetensors"), "w", &bytes, false, false);
write_mini_st(&d_ok.join("backup.safetensors"), "w", &bytes, false, false);
fs::write(
d_ok.join("model.safetensors.index.json"),
r#"{"weight_map":{"w":"s1.safetensors"}}"#,
)
.unwrap();
let ar = SafetensorsArchive::open(&d_ok).unwrap();
assert_eq!(ar.shards.len(), 1);
let mut got = [0u8; 4];
ar.read_slice("w", 4, &mut got).unwrap();
assert_eq!(got, [50, 60, 70, 80]);
assert!(ar.read_slice("w", u64::MAX, &mut got).is_err());
let _ = fs::remove_dir_all(&root);
}
#[test]
fn writer_atomic_commit_and_drop_cleanup() {
let p = std::env::temp_dir().join(format!("vetta_ld_cache_{}.bin", std::process::id()));
let _ = fs::remove_file(&p);
let fp = 0x1234_5678_ABCD_EF01u64;
let payload = vec![0x5Au8; 8192];
let mut wr = DiskCacheWriter::begin(&p, fp).unwrap();
wr.write_record(
CacheRecord {
kind: 1,
i0: 128,
i1: 256,
i2: 0,
flags: 0,
u0: 4096,
u1: 0,
data_offset: 0,
data_bytes: 0,
name: "layer.0.q8".into(),
},
&payload,
)
.unwrap();
let committed = wr.commit().unwrap();
assert_eq!(committed, p);
assert!(p.is_file());
assert!(!PathBuf::from(format!("{}.tmp.{}", p.display(), std::process::id())).exists());
// An abandoned writer cleans up its .tmp (no ghost final file)
let p2 = std::env::temp_dir().join(format!("vetta_ld_cache2_{}.bin", std::process::id()));
{
let mut wr2 = DiskCacheWriter::begin(&p2, fp).unwrap();
wr2.write_record(
CacheRecord {
kind: 1, i0: 0, i1: 0, i2: 0, flags: 0, u0: 0, u1: 0,
data_offset: 0, data_bytes: 0, name: "x".into(),
},
&payload,
).unwrap();
}
assert!(!p2.exists());
let _ = fs::remove_file(&p);
}
}