diff --git a/README.md b/README.md index 3e107e42..b0e3269b 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,8 @@ performance gain is claimed for Leleka until its real-model gates pass. - `crates/backend-api/` — Leleka's versioned Rust backend contract. - `crates/tokenizer/` — the Qwen35 byte-level BPE tokenizer extracted as a - backend-independent Rust crate. + backend-independent Rust crate, including a bounded GGUF v3 reader for its + tokenizer metadata. - `desktop/`, `desktop-core/` — current desktop application and its Rust core. - `control-plane/` — current Rust API, Responses handling, and worker supervisor. - `engine/strata/` — pinned upstream Strata reference; retained during migration. @@ -34,11 +35,13 @@ artifacts remain outside Git or under ignored paths. Leleka currently has a versioned backend contract and a standalone Qwen35 BPE tokenizer crate. The existing Rust control plane now consumes that shared -tokenizer crate instead of maintaining a second copy; its oracle-parity tests -remain in the workspace. Leleka still has no independent inference backend or -CUDA integration, so this does not yet serve a model independently. The -desktop app and the rest of the control plane remain available as migration -source in this repository. +tokenizer crate for both encoding and GGUF tokenizer metadata rather than +maintaining a second parser; its oracle-parity and malformed-header tests remain +in the workspace. The GGUF reader only supports the current Qwen35 GPT-2 BPE +metadata shape and does not inspect tensor payloads. Leleka still has no +independent inference backend or CUDA integration, so this does not yet serve a +model independently. The desktop app and the rest of the control plane remain +available as migration source in this repository. ## Development diff --git a/control-plane/src/gguf.rs b/control-plane/src/gguf.rs index ec052e4b..7664719e 100644 --- a/control-plane/src/gguf.rs +++ b/control-plane/src/gguf.rs @@ -41,16 +41,7 @@ pub struct TensorIndex { pub tensors: Vec, } -#[derive(Debug)] -pub struct TokenizerMetadata { - pub model: String, - pub pre: String, - pub tokens: Vec, - pub merges: Vec, - pub token_types: Option>, - pub special_ids: BTreeMap, - pub chat_template: String, -} +pub use leleka_tokenizer::GgufTokenizerMetadata as TokenizerMetadata; /// Metadata admission for the specialised engine, before expensive preparation. /// Mirrors artifact/gguf_reader.hpp::Qwen4ExpGuard; this does not inspect tensor values. @@ -109,86 +100,10 @@ pub fn check_flash_next_profile(path: &Path) -> Result<()> { Ok(()) } -/// Read only tokenizer fields after the complete GGUF header has passed inspection. +/// Read tokenizer fields after complete model-header inspection, using the shared Leleka parser. pub fn tokenizer_metadata(path: &Path) -> Result { inspect(path)?; - let file = File::open(path)?; - let size = file.metadata()?.len(); - let mut cursor = Cursor { file, size }; - cursor.skip(16)?; // magic, version, tensor count - let count = cursor.u64()?; - let mut model = None; - let mut pre = None; - let mut tokens = None; - let mut merges = None; - let mut token_types = None; - let mut special_ids = BTreeMap::new(); - let mut chat_template = None; - for _ in 0..count { - let key = cursor.string()?; - let kind = cursor.u32()?; - match key.as_str() { - "tokenizer.ggml.model" if kind == 8 => model = Some(cursor.string()?), - "tokenizer.ggml.pre" if kind == 8 => pre = Some(cursor.string()?), - "tokenizer.ggml.tokens" => tokens = Some(cursor.string_array(kind)?), - "tokenizer.ggml.merges" => merges = Some(cursor.string_array(kind)?), - "tokenizer.ggml.token_type" => token_types = Some(cursor.integer_array(kind)?), - "tokenizer.chat_template" if kind == 8 => chat_template = Some(cursor.string()?), - _ if key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id") => { - special_ids.insert(key, cursor.integer(kind)?); - } - _ => cursor.skip_value(kind)?, - } - } - let model = model.ok_or("GGUF is missing tokenizer.ggml.model")?; - let tokens = tokens.ok_or("GGUF is missing tokenizer.ggml.tokens")?; - let merges = merges.ok_or("GGUF is missing tokenizer.ggml.merges")?; - let chat_template = chat_template.ok_or("GGUF is missing tokenizer.chat_template")?; - if model != "gpt2" || pre.as_deref().is_some_and(|value| value != "qwen35") { - return Err("only the qwen35 byte-level BPE tokenizer is supported".into()); - } - if tokens.is_empty() || chat_template.is_empty() { - return Err("GGUF tokenizer has an empty vocabulary or chat template".into()); - } - if token_types - .as_ref() - .is_some_and(|types| types.len() != tokens.len()) - { - return Err("token_type length differs from vocabulary length".into()); - } - let vocab: HashSet<&str> = tokens.iter().map(String::as_str).collect(); - if vocab.len() != tokens.len() { - return Err("GGUF tokenizer has duplicate vocabulary entries".into()); - } - let mut seen_merges = HashSet::new(); - for merge in &merges { - let Some((left, right)) = merge.split_once(' ') else { - return Err("GGUF BPE merge is not a pair".into()); - }; - if left.is_empty() - || right.is_empty() - || right.contains(' ') - || !vocab.contains(left) - || !vocab.contains(right) - || !seen_merges.insert(merge) - { - return Err("GGUF BPE merge is invalid or duplicated".into()); - } - } - for &id in special_ids.values() { - if id as usize >= tokens.len() { - return Err("special token ID exceeds vocabulary".into()); - } - } - Ok(TokenizerMetadata { - model, - pre: pre.unwrap_or_else(|| "qwen35".to_owned()), - tokens, - merges, - token_types, - special_ids, - chat_template, - }) + Ok(leleka_tokenizer::read_gguf_tokenizer_metadata(path)?) } pub fn inspect(path: &Path) -> Result { @@ -495,45 +410,6 @@ impl Cursor { Ok(String::from_utf8(self.take(size as usize)?)?) } - fn string_array(&mut self, kind: u32) -> Result> { - if kind != 9 || self.u32()? != 8 { - return Err("expected a GGUF string array".into()); - } - let count = self.u64()?; - if count > 1_000_000 { - return Err("unreasonable GGUF tokenizer array count".into()); - } - let mut total = 0u64; - let mut values = Vec::with_capacity(count as usize); - for _ in 0..count { - let value = self.string()?; - total = total - .checked_add(value.len() as u64) - .ok_or("GGUF tokenizer array size overflow")?; - if total > 512 * 1024 * 1024 { - return Err("GGUF tokenizer array exceeds 512 MiB".into()); - } - values.push(value); - } - Ok(values) - } - - fn integer_array(&mut self, kind: u32) -> Result> { - if kind != 9 { - return Err("expected a GGUF integer array".into()); - } - let element = self.u32()?; - let count = self.u64()?; - if count > 1_000_000 { - return Err("unreasonable GGUF tokenizer array count".into()); - } - let mut values = Vec::with_capacity(count as usize); - for _ in 0..count { - values.push(self.integer(element)?); - } - Ok(values) - } - fn integer(&mut self, kind: u32) -> Result { match kind { 0 | 7 => Ok(u32::from(self.u8()?)), diff --git a/crates/tokenizer/src/lib.rs b/crates/tokenizer/src/lib.rs index 2f7ff08c..89abe67b 100644 --- a/crates/tokenizer/src/lib.rs +++ b/crates/tokenizer/src/lib.rs @@ -2,9 +2,10 @@ use std::{ cmp::Reverse, - collections::{BinaryHeap, HashMap}, + collections::{BTreeMap, BinaryHeap, HashMap, HashSet}, error::Error, - fs, + fs::{self, File}, + io::{Read, Seek, SeekFrom}, path::Path, }; @@ -303,6 +304,391 @@ impl Tokenizer { } } +/// The Qwen35 tokenizer fields read from a GGUF v3 metadata header. +#[derive(Debug, PartialEq, Eq)] +pub struct GgufTokenizerMetadata { + pub model: String, + pub pre: String, + pub tokens: Vec, + pub merges: Vec, + pub token_types: Option>, + pub special_ids: BTreeMap, + pub chat_template: String, +} + +/// A bounded GGUF tokenizer metadata parsing error. +#[derive(Debug)] +pub struct GgufTokenizerError(String); + +impl std::fmt::Display for GgufTokenizerError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.0) + } +} + +impl Error for GgufTokenizerError {} + +type GgufResult = std::result::Result; + +const MAX_GGUF_HEADER_BYTES: u64 = 1024 * 1024 * 1024; +const MAX_GGUF_METADATA_ENTRIES: u64 = 1_000_000; +const MAX_GGUF_STRING_BYTES: u64 = 1024 * 1024; +const MAX_TOKENIZER_ARRAY_ITEMS: u64 = 1_000_000; +const MAX_TOKENIZER_ARRAY_BYTES: u64 = 512 * 1024 * 1024; +const MAX_RELEVANT_TOKENIZER_FIELDS: usize = 128; + +/// Read Qwen35 GPT-2 BPE tokenizer metadata from a GGUF v3 file. +/// +/// This reads at most the first 1 GiB of the file as a metadata header, caps +/// each header string at 1 MiB, and caps tokenizer string arrays at 1,000,000 +/// elements and 512 MiB of aggregate string bytes. It never reads tensor +/// payloads. Callers that also require model/tensor validation must perform +/// that separately before using these tokenizer assets. +pub fn read_gguf_tokenizer_metadata(path: &Path) -> GgufResult { + let mut cursor = GgufCursor::open(path)?; + if cursor.take(4)? != b"GGUF" { + return Err(gguf_error("not a GGUF file")); + } + if cursor.u32()? != 3 { + return Err(gguf_error("only GGUF v3 is supported")); + } + cursor.skip(8)?; // tensor count; tensor inspection belongs to the model loader. + let count = cursor.u64()?; + if count > MAX_GGUF_METADATA_ENTRIES { + return Err(gguf_error("unreasonable GGUF metadata entry count")); + } + let minimum_bytes = count + .checked_mul(13) + .ok_or_else(|| gguf_error("GGUF metadata entry count overflow"))?; + if minimum_bytes > cursor.remaining()? { + return Err(gguf_error("GGUF metadata count exceeds bounded header")); + } + + let mut model = None; + let mut pre = None; + let mut tokens = None; + let mut merges = None; + let mut token_types = None; + let mut special_ids = BTreeMap::new(); + let mut chat_template = None; + let mut seen_fields = HashSet::new(); + for _ in 0..count { + let key = cursor.string()?; + let kind = cursor.u32()?; + let relevant = matches!( + key.as_str(), + "tokenizer.ggml.model" + | "tokenizer.ggml.pre" + | "tokenizer.ggml.tokens" + | "tokenizer.ggml.merges" + | "tokenizer.ggml.token_type" + | "tokenizer.chat_template" + ) || (key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id")); + if relevant { + if seen_fields.len() >= MAX_RELEVANT_TOKENIZER_FIELDS { + return Err(gguf_error("too many tokenizer metadata fields")); + } + if !seen_fields.insert(key.clone()) { + return Err(gguf_error("duplicate tokenizer metadata field")); + } + } + match key.as_str() { + "tokenizer.ggml.model" if kind == 8 => model = Some(cursor.string()?), + "tokenizer.ggml.pre" if kind == 8 => pre = Some(cursor.string()?), + "tokenizer.ggml.tokens" => tokens = Some(cursor.string_array(kind)?), + "tokenizer.ggml.merges" => merges = Some(cursor.string_array(kind)?), + "tokenizer.ggml.token_type" => token_types = Some(cursor.integer_array(kind)?), + "tokenizer.chat_template" if kind == 8 => chat_template = Some(cursor.string()?), + _ if key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id") => { + special_ids.insert(key, cursor.integer(kind)?); + } + _ => cursor.skip_value(kind)?, + } + } + + let model = model.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.model"))?; + let tokens = tokens.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.tokens"))?; + let merges = merges.ok_or_else(|| gguf_error("GGUF is missing tokenizer.ggml.merges"))?; + let chat_template = + chat_template.ok_or_else(|| gguf_error("GGUF is missing tokenizer.chat_template"))?; + if model != "gpt2" || pre.as_deref().is_some_and(|value| value != "qwen35") { + return Err(gguf_error( + "only the qwen35 byte-level BPE tokenizer is supported", + )); + } + if tokens.is_empty() || chat_template.is_empty() { + return Err(gguf_error( + "GGUF tokenizer has an empty vocabulary or chat template", + )); + } + if token_types + .as_ref() + .is_some_and(|types| types.len() != tokens.len()) + { + return Err(gguf_error( + "token_type length differs from vocabulary length", + )); + } + let vocab: HashSet<&str> = tokens.iter().map(String::as_str).collect(); + if vocab.len() != tokens.len() { + return Err(gguf_error( + "GGUF tokenizer has duplicate vocabulary entries", + )); + } + let mut seen_merges = HashSet::new(); + for merge in &merges { + let Some((left, right)) = merge.split_once(' ') else { + return Err(gguf_error("GGUF BPE merge is not a pair")); + }; + if left.is_empty() + || right.is_empty() + || right.contains(' ') + || !vocab.contains(left) + || !vocab.contains(right) + || !seen_merges.insert(merge) + { + return Err(gguf_error("GGUF BPE merge is invalid or duplicated")); + } + } + for &id in special_ids.values() { + if id as usize >= tokens.len() { + return Err(gguf_error("special token ID exceeds vocabulary")); + } + } + Ok(GgufTokenizerMetadata { + model, + pre: pre.unwrap_or_else(|| "qwen35".to_owned()), + tokens, + merges, + token_types, + special_ids, + chat_template, + }) +} + +fn gguf_error(message: impl Into) -> GgufTokenizerError { + GgufTokenizerError(message.into()) +} + +struct GgufCursor { + file: File, + size: u64, +} + +impl GgufCursor { + fn open(path: &Path) -> GgufResult { + let file = File::open(path).map_err(|error| gguf_error(error.to_string()))?; + let size = file + .metadata() + .map_err(|error| gguf_error(error.to_string()))? + .len() + .min(MAX_GGUF_HEADER_BYTES); + Ok(Self { file, size }) + } + + fn position(&mut self) -> GgufResult { + self.file + .stream_position() + .map_err(|error| gguf_error(error.to_string())) + } + + fn remaining(&mut self) -> GgufResult { + Ok(self.size.saturating_sub(self.position()?)) + } + + fn skip(&mut self, bytes: u64) -> GgufResult<()> { + let end = self + .position()? + .checked_add(bytes) + .ok_or_else(|| gguf_error("GGUF offset overflow"))?; + if end > self.size { + return Err(gguf_error("truncated or oversized GGUF metadata header")); + } + self.file + .seek(SeekFrom::Start(end)) + .map_err(|error| gguf_error(error.to_string()))?; + Ok(()) + } + + fn take(&mut self, size: usize) -> GgufResult> { + if self + .position()? + .checked_add(size as u64) + .is_none_or(|end| end > self.size) + { + return Err(gguf_error("truncated or oversized GGUF metadata header")); + } + let mut data = vec![0; size]; + self.file + .read_exact(&mut data) + .map_err(|error| gguf_error(error.to_string()))?; + Ok(data) + } + + fn u8(&mut self) -> GgufResult { + Ok(self.take(1)?[0]) + } + + fn u16(&mut self) -> GgufResult { + let bytes = self.take(2)?; + Ok(u16::from_le_bytes([bytes[0], bytes[1]])) + } + + fn u32(&mut self) -> GgufResult { + let bytes = self.take(4)?; + Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])) + } + + fn u64(&mut self) -> GgufResult { + let bytes = self.take(8)?; + Ok(u64::from_le_bytes([ + bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], + ])) + } + + fn string(&mut self) -> GgufResult { + let size = self.u64()?; + if size > MAX_GGUF_STRING_BYTES { + return Err(gguf_error("GGUF header string is too large")); + } + String::from_utf8(self.take(size as usize)?) + .map_err(|error| gguf_error(format!("GGUF header string is not UTF-8: {error}"))) + } + + fn string_array(&mut self, kind: u32) -> GgufResult> { + if kind != 9 || self.u32()? != 8 { + return Err(gguf_error("expected a GGUF string array")); + } + let count = self.u64()?; + self.check_tokenizer_array(count, 8)?; + let capacity = usize::try_from(count) + .map_err(|_| gguf_error("GGUF tokenizer array count exceeds platform limits"))?; + let mut total = 0u64; + let mut values = Vec::with_capacity(capacity); + for _ in 0..count { + let value = self.string()?; + total = total + .checked_add(value.len() as u64) + .ok_or_else(|| gguf_error("GGUF tokenizer array size overflow"))?; + if total > MAX_TOKENIZER_ARRAY_BYTES { + return Err(gguf_error("GGUF tokenizer array exceeds 512 MiB")); + } + values.push(value); + } + Ok(values) + } + + fn integer_array(&mut self, kind: u32) -> GgufResult> { + if kind != 9 { + return Err(gguf_error("expected a GGUF integer array")); + } + let element = self.u32()?; + let count = self.u64()?; + let width = value_width(element)?; + self.check_tokenizer_array(count, width)?; + let capacity = usize::try_from(count) + .map_err(|_| gguf_error("GGUF tokenizer array count exceeds platform limits"))?; + let mut values = Vec::with_capacity(capacity); + for _ in 0..count { + values.push(self.integer(element)?); + } + Ok(values) + } + + fn check_tokenizer_array(&mut self, count: u64, minimum_item_bytes: u64) -> GgufResult<()> { + if count > MAX_TOKENIZER_ARRAY_ITEMS { + return Err(gguf_error("unreasonable GGUF tokenizer array count")); + } + let minimum_bytes = count + .checked_mul(minimum_item_bytes) + .ok_or_else(|| gguf_error("GGUF tokenizer array size overflow"))?; + if minimum_bytes > self.remaining()? { + return Err(gguf_error("GGUF tokenizer array exceeds remaining header")); + } + Ok(()) + } + + fn integer(&mut self, kind: u32) -> GgufResult { + match kind { + 0 | 7 => Ok(u32::from(self.u8()?)), + 1 => u32::try_from(self.u8()? as i8) + .map_err(|_| gguf_error("negative GGUF integer is unsupported")), + 2 => Ok(u32::from(self.u16()?)), + 3 => u32::try_from(self.u16()? as i16) + .map_err(|_| gguf_error("negative GGUF integer is unsupported")), + 4 => self.u32(), + 5 => u32::try_from(self.u32()? as i32) + .map_err(|_| gguf_error("negative GGUF integer is unsupported")), + 10 => u32::try_from(self.u64()?) + .map_err(|_| gguf_error("GGUF integer exceeds 32-bit range")), + 11 => u32::try_from(self.u64()? as i64) + .map_err(|_| gguf_error("negative or oversized GGUF integer is unsupported")), + _ => Err(gguf_error(format!( + "GGUF metadata type {kind} is not an integer" + ))), + } + } + + fn skip_value(&mut self, kind: u32) -> GgufResult<()> { + match kind { + 0 | 1 | 7 => self.skip(1), + 2 | 3 => self.skip(2), + 4..=6 => self.skip(4), + 8 => { + let size = self.u64()?; + self.skip(size) + } + 9 => { + let element = self.u32()?; + let count = self.u64()?; + match element { + 8 => { + if count > MAX_GGUF_METADATA_ENTRIES { + return Err(gguf_error("unreasonable GGUF string array count")); + } + let minimum_bytes = count + .checked_mul(8) + .ok_or_else(|| gguf_error("GGUF string array size overflow"))?; + if minimum_bytes > self.remaining()? { + return Err(gguf_error("GGUF string array exceeds remaining header")); + } + for _ in 0..count { + let size = self.u64()?; + if size > MAX_GGUF_HEADER_BYTES { + return Err(gguf_error("GGUF string array element is too large")); + } + self.skip(size)?; + } + Ok(()) + } + 9 => Err(gguf_error("nested GGUF arrays are unsupported")), + _ => { + let width = value_width(element)?; + let bytes = count + .checked_mul(width) + .ok_or_else(|| gguf_error("GGUF array size overflow"))?; + self.skip(bytes) + } + } + } + 10..=12 => self.skip(8), + _ => Err(gguf_error(format!("unknown GGUF metadata type {kind}"))), + } + } +} + +fn value_width(kind: u32) -> GgufResult { + match kind { + 0 | 1 | 7 => Ok(1), + 2 | 3 => Ok(2), + 4..=6 => Ok(4), + 10..=12 => Ok(8), + _ => Err(gguf_error(format!( + "invalid GGUF array element type {kind}" + ))), + } +} + type HeapEntry = (usize, usize, usize, u64, u64); struct Node { @@ -494,3 +880,274 @@ mod tests { fs::remove_dir_all(root).unwrap(); } } + +#[cfg(test)] +mod gguf_metadata_tests { + use super::*; + use std::path::PathBuf; + use std::sync::atomic::{AtomicU64, Ordering}; + + static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + + fn fixture_path() -> PathBuf { + std::env::temp_dir().join(format!( + "leleka-tokenizer-gguf-{}-{}", + std::process::id(), + NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed) + )) + } + + fn gguf_string(bytes: &mut Vec, value: &str) { + bytes.extend_from_slice(&(value.len() as u64).to_le_bytes()); + bytes.extend_from_slice(value.as_bytes()); + } + + fn string_field(bytes: &mut Vec, key: &str, value: &str) { + gguf_string(bytes, key); + bytes.extend_from_slice(&8u32.to_le_bytes()); + gguf_string(bytes, value); + } + + fn string_array(bytes: &mut Vec, key: &str, values: &[&str]) { + gguf_string(bytes, key); + bytes.extend_from_slice(&9u32.to_le_bytes()); + bytes.extend_from_slice(&8u32.to_le_bytes()); + bytes.extend_from_slice(&(values.len() as u64).to_le_bytes()); + for value in values { + gguf_string(bytes, value); + } + } + + fn base() -> Vec { + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); // no tensors: metadata reader only. + bytes.extend_from_slice(&7u64.to_le_bytes()); + string_field(&mut bytes, "tokenizer.ggml.model", "gpt2"); + string_field(&mut bytes, "tokenizer.ggml.pre", "qwen35"); + string_array( + &mut bytes, + "tokenizer.ggml.tokens", + &["a", "b", "ab", "<|eos|>"], + ); + string_array(&mut bytes, "tokenizer.ggml.merges", &["a b"]); + gguf_string(&mut bytes, "tokenizer.ggml.token_type"); + bytes.extend_from_slice(&9u32.to_le_bytes()); + bytes.extend_from_slice(&4u32.to_le_bytes()); + bytes.extend_from_slice(&4u64.to_le_bytes()); + for value in [1u32, 1, 1, 3] { + bytes.extend_from_slice(&value.to_le_bytes()); + } + gguf_string(&mut bytes, "tokenizer.ggml.eos_token_id"); + bytes.extend_from_slice(&4u32.to_le_bytes()); + bytes.extend_from_slice(&3u32.to_le_bytes()); + string_field(&mut bytes, "tokenizer.chat_template", "{{ messages }}"); + bytes + } + + fn with_bytes(bytes: &[u8], check: impl FnOnce(&Path)) { + let path = fixture_path(); + fs::write(&path, bytes).unwrap(); + check(&path); + fs::remove_file(path).unwrap(); + } + + #[test] + fn reads_qwen35_tokenizer_metadata_with_control_plane_parity() { + with_bytes(&base(), |path| { + let metadata = read_gguf_tokenizer_metadata(path).unwrap(); + assert_eq!(metadata.model, "gpt2"); + assert_eq!(metadata.pre, "qwen35"); + assert_eq!(metadata.tokens, ["a", "b", "ab", "<|eos|>"]); + assert_eq!(metadata.merges, ["a b"]); + assert_eq!(metadata.token_types, Some(vec![1, 1, 1, 3])); + assert_eq!(metadata.special_ids["tokenizer.ggml.eos_token_id"], 3); + assert_eq!(metadata.chat_template, "{{ messages }}"); + }); + } + + #[test] + fn rejects_wrong_magic_version_truncation_and_excessive_metadata_count() { + let mut bytes = base(); + bytes[0] = b'X'; + with_bytes(&bytes, |path| { + assert!( + read_gguf_tokenizer_metadata(path) + .unwrap_err() + .to_string() + .contains("GGUF") + ); + }); + + let mut bytes = base(); + bytes[4..8].copy_from_slice(&2u32.to_le_bytes()); + with_bytes(&bytes, |path| { + assert!( + read_gguf_tokenizer_metadata(path) + .unwrap_err() + .to_string() + .contains("v3") + ); + }); + + let bytes = base(); + with_bytes(&bytes[..bytes.len() - 2], |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()); + }); + + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes.extend_from_slice(&u64::MAX.to_le_bytes()); + with_bytes(&bytes, |path| { + assert!( + read_gguf_tokenizer_metadata(path) + .unwrap_err() + .to_string() + .contains("entry count") + ); + }); + } + + #[test] + fn rejects_oversized_string_and_truncated_or_excessive_arrays_before_allocation() { + let mut bytes = b"GGUF".to_vec(); + bytes.extend_from_slice(&3u32.to_le_bytes()); + bytes.extend_from_slice(&0u64.to_le_bytes()); + bytes.extend_from_slice(&1u64.to_le_bytes()); + bytes.extend_from_slice(&(MAX_GGUF_STRING_BYTES + 1).to_le_bytes()); + bytes.extend_from_slice(&[0; 5]); // Keep the minimum metadata entry envelope intact. + with_bytes(&bytes, |path| { + assert!( + read_gguf_tokenizer_metadata(path) + .unwrap_err() + .to_string() + .contains("too large") + ); + }); + + let mut bytes = base(); + bytes.extend_from_slice(&[0; 0]); + // Replace the token array's count with a value above the explicit cap. + let marker = b"tokenizer.ggml.tokens"; + let at = bytes + .windows(marker.len()) + .position(|w| w == marker) + .unwrap(); + let count_at = at + 8 + marker.len() + 4 + 4; + bytes[count_at..count_at + 8] + .copy_from_slice(&(MAX_TOKENIZER_ARRAY_ITEMS + 1).to_le_bytes()); + with_bytes(&bytes, |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()); + }); + + let mut bytes = base(); + let at = bytes + .windows(marker.len()) + .position(|w| w == marker) + .unwrap(); + let count_at = at + 8 + marker.len() + 4 + 4; + bytes[count_at..count_at + 8].copy_from_slice(&u64::MAX.to_le_bytes()); + with_bytes(&bytes, |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()); + }); + } + + #[test] + fn rejects_duplicate_tokenizer_metadata_and_duplicate_vocabulary_tokens() { + let mut bytes = base(); + string_field(&mut bytes, "tokenizer.ggml.model", "gpt2"); + bytes[16..24].copy_from_slice(&8u64.to_le_bytes()); + with_bytes(&bytes, |path| { + assert!( + read_gguf_tokenizer_metadata(path) + .unwrap_err() + .to_string() + .contains("duplicate tokenizer metadata") + ); + }); + + let mut bytes = base(); + // Rewrite the third token "ab" to "a", preserving all offsets. + let marker = b"tokenizer.ggml.tokens"; + let at = bytes + .windows(marker.len()) + .position(|w| w == marker) + .unwrap(); + let third_token_len_at = at + 8 + marker.len() + 4 + 4 + 8 + 8 + 1 + 8 + 1; + bytes[third_token_len_at..third_token_len_at + 8].copy_from_slice(&1u64.to_le_bytes()); + bytes.copy_within(third_token_len_at + 8 + 2.., third_token_len_at + 8 + 1); + bytes.truncate(bytes.len() - 1); + with_bytes(&bytes, |path| { + let result = read_gguf_tokenizer_metadata(path); + assert!(result.is_err(), "unexpected parse result: {result:?}"); + }); + } + + #[test] + fn rejects_invalid_tokenizer_types_ids_merges_and_unknown_metadata_types() { + let mut bytes = base(); + let marker = b"tokenizer.ggml.eos_token_id"; + let at = bytes + .windows(marker.len()) + .position(|w| w == marker) + .unwrap(); + let value_at = at + 8 + marker.len() + 4; + bytes[value_at..value_at + 4].copy_from_slice(&99u32.to_le_bytes()); + with_bytes(&bytes, |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()) + }); + + let mut bytes = base(); + let marker = b"tokenizer.ggml.merges"; + let at = bytes + .windows(marker.len()) + .position(|w| w == marker) + .unwrap(); + let value_at = at + 8 + marker.len() + 4 + 4 + 8 + 8; + bytes[value_at..value_at + 3].copy_from_slice(b"x y"); + with_bytes(&bytes, |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()) + }); + + let mut bytes = base(); + let marker = b"tokenizer.ggml.token_type"; + let at = bytes + .windows(marker.len()) + .position(|w| w == marker) + .unwrap(); + let count_at = at + 8 + marker.len() + 4 + 4; + bytes[count_at..count_at + 8].copy_from_slice(&3u64.to_le_bytes()); + bytes.drain(count_at + 8 + 4 * 3..count_at + 8 + 4 * 4); + with_bytes(&bytes, |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()) + }); + + let mut bytes = base(); + bytes.extend_from_slice(&("x".len() as u64).to_le_bytes()); + bytes.extend_from_slice(b"x"); + bytes.extend_from_slice(&99u32.to_le_bytes()); + bytes.extend_from_slice(&8u64.to_le_bytes()); + bytes[16..24].copy_from_slice(&8u64.to_le_bytes()); + with_bytes(&bytes, |path| { + assert!(read_gguf_tokenizer_metadata(path).is_err()) + }); + } + + #[test] + fn missing_pre_tokenizer_uses_the_existing_qwen_default() { + let mut bytes = base(); + let marker = b"tokenizer.ggml.pre"; + let at = bytes + .windows(marker.len()) + .position(|w| w == marker) + .unwrap(); + let start = at - 8; + let end = at + marker.len() + 4 + 8 + b"qwen35".len(); + bytes.drain(start..end); + bytes[16..24].copy_from_slice(&6u64.to_le_bytes()); + with_bytes(&bytes, |path| { + assert_eq!(read_gguf_tokenizer_metadata(path).unwrap().pre, "qwen35"); + }); + } +} diff --git a/docs/model-assets.md b/docs/model-assets.md index 373a3c59..0a631219 100644 --- a/docs/model-assets.md +++ b/docs/model-assets.md @@ -39,6 +39,15 @@ The acquisition stage downloads GGUF files; the native tokenizer stage extracts `model inspect` reads the GGUF v3 header and tensor directory without mapping weight data. It checks metadata types, counts, alignment, duplicate keys/tensors, split numbering, and whether tensor start offsets fit the file. This is a structural check, not proof that all tensor bytes or quantization geometry are valid. +The public `leleka-tokenizer::read_gguf_tokenizer_metadata` API reads the +current Qwen35 GPT-2 BPE tokenizer fields directly from a GGUF v3 file. It +accepts a missing `tokenizer.ggml.pre` as `qwen35`, returns optional token +types and special-token IDs, and requires the vocabulary, merges, and chat +template. It bounds header reads to 1 GiB, individual strings to 1 MiB, and +tokenizer string arrays to 1,000,000 entries and 512 MiB of aggregate string +bytes. It reads no tensor payload; callers needing model structure or tensor +validation must separately use the GGUF inspector. + `model extract-tokenizer` validates the Qwen byte-level BPE metadata, then writes `tokenizer/` under the output directory through a staging directory. It requires a nonempty chat template and refuses to overwrite an existing tokenizer directory. The dense/expert pack is still pending. The extracted directory is accepted by the native `model tokenize` and `model detokenize` commands. `model tokenize TOKENIZER_DIR --stdin --special` reads UTF-8 text from standard input and prints a JSON array of token IDs; `--special` enables control tokens such as `<|im_end|>`. User-defined tokens remain literal in both modes. `model detokenize TOKENIZER_DIR 1,2,3` prints a JSON string. The native BPE path matched the pinned upstream tokenizer on 20 cases from the real verified first shard. The dense/expert pack and model startup remain pending.