engram-parser 0.3.0

Pure-Rust GGUF + Safetensors checkpoint/tensor substrate: format-independent tensor inventory, metadata, and raw payload access for ANN/SNN research. Default builds are zero-dependency (`fs::read` into `Vec<u8>`). Optional `mmap` feature adds memmap2. Packed dequant for Q8_0/Q5_K/Q6_K/IQ3_M. Off-by-default `safetensors` feature adds manifest/discovery plus raw tensor payload access via the upstream safetensors crate. MoE per-expert weight extraction ships as a GGUF model-analysis specialization.
Documentation
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Safetensors byte-range and output-path validation helpers.

use super::manifest::{
    INDEX_UNREFERENCED_SHARDS_KEY, SAFETENSORS_EXTENSION, SafetensorsManifest,
    SafetensorsTensorRecord, parse_unreferenced_shards_metadata,
};
use super::model_load;
use super::paths::{canonical_existing_or_parent, parent_or_current, paths_refer_to_same_file};
use crate::error::Result;
use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};

pub(super) fn reject_tensor_data_ranges(
    path: &Path,
    tensors: &[SafetensorsTensorRecord],
    data_len: u64,
) -> Result<()> {
    let data_len = usize::try_from(data_len).map_err(|_| {
        model_load(
            path,
            format!("Safetensors data section length {data_len} does not fit in usize"),
        )
    })?;
    let mut ranges = tensors
        .iter()
        .map(|tensor| {
            (
                tensor.data_offsets[0],
                tensor.data_offsets[1],
                tensor.name.as_str(),
            )
        })
        .collect::<Vec<_>>();
    ranges.sort_by_key(|(start, end, name)| (*start, *end, *name));

    let mut expected_start = 0usize;
    let mut previous_name: Option<&str> = None;
    for (start, end, name) in ranges {
        if start < expected_start {
            return Err(model_load(
                path,
                format!(
                    "tensor '{name}' data range overlaps tensor '{}'",
                    previous_name.unwrap_or("<unknown>")
                ),
            ));
        }
        if start > expected_start {
            return Err(model_load(
                path,
                format!("tensor '{name}' data range leaves a gap from {expected_start} to {start}"),
            ));
        }
        expected_start = end;
        previous_name = Some(name);
    }

    if expected_start != data_len {
        return Err(model_load(
            path,
            format!(
                "Safetensors tensor data ranges end at {expected_start}, but data section is {data_len} bytes"
            ),
        ));
    }

    Ok(())
}

pub(super) fn expected_tensor_byte_size(
    dtype: &str,
    shape: &[usize],
    path: &Path,
    tensor_name: &str,
) -> Result<usize> {
    let elements = shape.iter().try_fold(1usize, |acc, dim| {
        acc.checked_mul(*dim).ok_or_else(|| {
            model_load(
                path,
                format!("tensor '{tensor_name}' shape element count overflow"),
            )
        })
    })?;

    // Int4 is a packed format: 2 elements per byte.
    if dtype == "INT4" || dtype == "I4" || dtype == "U4" {
        return Ok(elements.div_ceil(2));
    }

    let element_size = dtype_size_bytes(dtype).ok_or_else(|| {
        model_load(
            path,
            format!("tensor '{tensor_name}' has unsupported Safetensors dtype '{dtype}'"),
        )
    })?;
    elements
        .checked_mul(element_size)
        .ok_or_else(|| model_load(path, format!("tensor '{tensor_name}' byte size overflow")))
}

/// Byte width of a Safetensors dtype, or `None` for packed/unknown types.
///
/// Packed 4-bit types (`INT4`/`I4`/`U4`) return `None`; callers must use
/// `div_ceil(2)` over the element count instead of `width * count`.
#[must_use]
pub fn dtype_size_bytes(dtype: &str) -> Option<usize> {
    match dtype {
        "C128" => Some(16),
        "F64" | "I64" | "U64" | "C64" => Some(8),
        "F32" | "TF32" | "I32" | "U32" => Some(4),
        "F16" | "BF16" | "I16" | "U16" => Some(2),
        "F8_E5M2" | "F8_E4M3" | "F8_E8M0" | "I8" | "U8" | "BOOL" => Some(1),
        "INT4" | "I4" | "U4" => None,
        _ => None,
    }
}

pub(super) fn reject_output_checkpoint_conflict(
    checkpoint_path: &Path,
    output_path: &Path,
    manifest: &SafetensorsManifest,
) -> Result<()> {
    let output = canonical_existing_or_parent(output_path)?;
    let input_metadata = fs::metadata(checkpoint_path)
        .map_err(|e| model_load(checkpoint_path, format!("stat checkpoint input: {e}")))?;
    let root = if input_metadata.is_dir() {
        checkpoint_path
    } else {
        parent_or_current(checkpoint_path)
    };

    let mut checkpoint_files = BTreeSet::new();
    if input_metadata.is_file() {
        checkpoint_files.insert(checkpoint_path.to_path_buf());
    }
    if input_metadata.is_dir() {
        checkpoint_files.extend(directory_safetensors_paths(checkpoint_path)?);
    }
    if let Some(index_file) = &manifest.checkpoint.index_file {
        checkpoint_files.insert(root.join(index_file));
    }
    for tensor in &manifest.tensors {
        checkpoint_files.insert(root.join(&tensor.source_shard));
    }
    if let Some(unreferenced_shards) = manifest
        .checkpoint
        .metadata
        .get(INDEX_UNREFERENCED_SHARDS_KEY)
    {
        for shard in parse_unreferenced_shards_metadata(unreferenced_shards) {
            checkpoint_files.insert(root.join(shard));
        }
    }

    for checkpoint_file in checkpoint_files {
        if paths_refer_to_same_file(&checkpoint_file, &output).map_err(|e| {
            model_load(
                &checkpoint_file,
                format!("compare checkpoint/output file identity: {e}"),
            )
        })? {
            return Err(model_load(
                output_path,
                "manifest output path must not overwrite a Safetensors checkpoint or index file"
                    .into(),
            ));
        }
    }

    Ok(())
}

fn directory_safetensors_paths(dir: &Path) -> Result<BTreeSet<PathBuf>> {
    let mut paths = BTreeSet::new();
    let entries = fs::read_dir(dir).map_err(|e| {
        model_load(
            dir,
            format!("read checkpoint directory for overwrite guard: {e}"),
        )
    })?;
    for entry in entries {
        let entry =
            entry.map_err(|e| model_load(dir, format!("read checkpoint directory entry: {e}")))?;
        let path = entry.path();
        if path.extension().and_then(|ext| ext.to_str()) == Some(SAFETENSORS_EXTENSION) {
            paths.insert(path);
        }
    }
    Ok(paths)
}