Skip to main content

engram_parser/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Pure-Rust checkpoint and tensor inspection for GGUF and Safetensors.
4//!
5//! The primary contract is the format-independent
6//! [`checkpoint`] module: [`open_checkpoint`] detects the container
7//! format and returns a [`Checkpoint`] handle that inventories tensors
8//! ([`TensorInfo`], [`TensorShape`], [`TensorDType`],
9//! [`TensorLocation`]), reads metadata, and fetches raw payload bytes
10//! without the caller branching on GGUF vs. Safetensors.
11//!
12//! Beneath that contract, [`gguf`] and (feature-gated) `safetensors`
13//! are format-specific backends: each exposes its own full parsing
14//! surface for callers that need format semantics — GGML wire types,
15//! K-quant dequant, Safetensors manifests and MoE candidate discovery.
16//!
17//! Model-analysis specializations live under [`analysis`]. Today that
18//! is [`analysis::moe`]: per-expert raw-weight extraction over a parsed
19//! [`GgufLayout`]. MoE is one analysis specialization built above the
20//! parsers, not the identity of the crate.
21//!
22//! # Features
23//!
24//! - **No dependencies enabled by default**: the default path is pure Rust.
25//!   The optional `mmap` feature adds `memmap2`; `safetensors` adds the
26//!   upstream `safetensors` crate.
27//! - **Parse limits**: [`ParseLimits`] is a documented budget for KV/tensor
28//!   counts, string sizes, array work, tensor rank, and metadata bytes.
29//!   File-declared `u64` sizes convert with [`HostSizeField`] errors.
30//!   Defaults stay generous; trusted callers override explicitly.
31//! - **GGUF v3 support**: Full parsing of headers, metadata, and tensor directories
32//! - **GGUF wire-type metadata**: labels + packed `byte_len` for known quant
33//!   codes (F32/F16/BF16, Q*/IQ*, integers, historical wire 31 = `Q4_0_4_4`).
34//!   Packed dequant is implemented for Q8_0, Q5_K, Q6_K, and the internal
35//!   IQ3_M block layout. No GGML kernels, no ggml runtime, no CUDA.
36//! - **Type labels**: Human-readable names via [`ggml_type_label`] (maps the
37//!   on-wire `ggml_type` integer used by GGUF)
38//! - **MoE analysis**: Extract expert **raw** weights (byte buffers + shape)
39//!   via [`analysis::moe`]; GGUF-specific.
40//! - **Metadata helpers**: Architecture-aware convenience methods for common fields
41//! - **Optional Safetensors**: enable `--features safetensors` for
42//!   inspection, deterministic manifests, MoE candidate discovery, and raw
43//!   tensor payload access via the upstream `safetensors` crate. Combine
44//!   with `--features mmap` for borrowed mmap-backed payload slices. No
45//!   Hugging Face `config.json` policy.
46//! - **Format-independent access**: [`Checkpoint`] + [`open_checkpoint`]
47//!   inventory tensors, read metadata, and fetch raw payloads from GGUF
48//!   or Safetensors without branching on format. See [`checkpoint`].
49//!
50//! # Example
51//!
52//! Format-agnostic inventory:
53//!
54//! ```no_run
55//! use engram_parser::{Checkpoint, open_checkpoint};
56//!
57//! let ckpt = open_checkpoint("model.gguf").unwrap();
58//! for t in ckpt.tensors() {
59//!     println!("{} {} {:?} {}B", t.name, t.dtype, t.shape.dims(), t.byte_len);
60//! }
61//! ```
62//!
63//! MoE expert analysis (GGUF-specific) uses the canonical
64//! [`analysis::moe`] path:
65//!
66//! ```no_run
67//! use engram_parser::analysis::moe::{extract_expert, list_experts};
68//! use engram_parser::load_gguf;
69//!
70//! let layout = load_gguf("moe-model.gguf").unwrap();
71//! for (block, expert) in list_experts(&layout) {
72//!     let weights = extract_expert(&layout, block, expert).unwrap();
73//!     println!("blk.{block} expert {expert}: complete={}", weights.is_complete());
74//! }
75//! ```
76//!
77//! # Compatibility
78//!
79//! The legacy `engram_parser::moe` module and the crate-root MoE
80//! symbols ([`extract_expert`], [`list_experts`], [`MoeExpertWeights`],
81//! [`RawTensor`]) remain as re-exports of [`analysis::moe`] and keep
82//! compiling unchanged.
83
84pub mod analysis;
85pub mod checkpoint;
86pub mod error;
87pub mod gguf;
88pub mod moe;
89#[cfg(feature = "safetensors")]
90pub mod safetensors;
91
92// Re-export commonly used types at the crate root for convenience.
93#[cfg(feature = "safetensors")]
94pub use checkpoint::SafetensorsBackend;
95#[cfg(all(feature = "safetensors", feature = "mmap"))]
96pub use checkpoint::SafetensorsMmapBackend;
97pub use checkpoint::{
98    AnyCheckpoint, Checkpoint, CheckpointFormat, CheckpointMetadata, CheckpointSource, DimOrder,
99    GgufBackend, MetadataValue, SourceKind, TensorDType, TensorInfo, TensorLocation, TensorShape,
100    open_checkpoint,
101};
102#[cfg(feature = "mmap")]
103pub use checkpoint::{GgufMmapBackend, open_checkpoint_mmap};
104pub use error::{HostSizeField, ParseLimitKind, ParserError, Result};
105pub use gguf::{
106    DType,
107    // GGML type constants
108    GGML_TYPE_BF16,
109    GGML_TYPE_F16,
110    GGML_TYPE_F32,
111    GGML_TYPE_F64,
112    GGML_TYPE_I8,
113    GGML_TYPE_I16,
114    GGML_TYPE_I32,
115    GGML_TYPE_I64,
116    GGML_TYPE_IQ1_M,
117    GGML_TYPE_IQ1_S,
118    GGML_TYPE_IQ2_S,
119    GGML_TYPE_IQ2_XS,
120    GGML_TYPE_IQ2_XXS,
121    GGML_TYPE_IQ3_M_BLOCK,
122    GGML_TYPE_IQ3_S,
123    GGML_TYPE_IQ3_XXS,
124    GGML_TYPE_IQ4_NL,
125    GGML_TYPE_IQ4_XS,
126    GGML_TYPE_Q2_K,
127    GGML_TYPE_Q3_K,
128    GGML_TYPE_Q4_0,
129    GGML_TYPE_Q4_0_4_4,
130    GGML_TYPE_Q4_1,
131    GGML_TYPE_Q4_K,
132    GGML_TYPE_Q5_0,
133    GGML_TYPE_Q5_1,
134    GGML_TYPE_Q5_K,
135    GGML_TYPE_Q6_K,
136    GGML_TYPE_Q8_0,
137    GGML_TYPE_Q8_1,
138    GGML_TYPE_Q8_K,
139    // Metadata value type constants
140    GGUF_VALUE_TYPE_ARRAY,
141    GGUF_VALUE_TYPE_BOOL,
142    GGUF_VALUE_TYPE_FLOAT32,
143    GGUF_VALUE_TYPE_FLOAT64,
144    GGUF_VALUE_TYPE_INT8,
145    GGUF_VALUE_TYPE_INT16,
146    GGUF_VALUE_TYPE_INT32,
147    GGUF_VALUE_TYPE_INT64,
148    GGUF_VALUE_TYPE_STRING,
149    GGUF_VALUE_TYPE_UINT8,
150    GGUF_VALUE_TYPE_UINT16,
151    GGUF_VALUE_TYPE_UINT32,
152    GGUF_VALUE_TYPE_UINT64,
153    GgufLayout,
154    GgufMetadata,
155    ParseLimits,
156    Tensor,
157    dequantize_iq3_m,
158    dequantize_packed,
159    dequantize_q5_k,
160    dequantize_q6_k,
161    dequantize_q8_0,
162    f16_bits_to_f32,
163    ggml_type_label,
164    load_gguf,
165    load_gguf_with_limits,
166    packed_row_size,
167    parse_bytes,
168    parse_bytes_with_limits,
169};
170#[cfg(feature = "mmap")]
171pub use gguf::{
172    GgufLayoutMmap, PageAlignedTensorBytes, load_gguf_mmap, load_gguf_mmap_with_limits,
173    os_page_size,
174};
175// MoE analysis result types and extractors, re-exported for
176// compatibility; the canonical path is `analysis::moe`.
177pub use analysis::moe::{MoeExpertWeights, RawTensor, extract_expert, list_experts};