STRA-338 size: model-format: gguf cursor value readers, metadata snapshot builder, tokenizer validation, profile check (fn_lines 70->30, complexity 54->10)

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 13:41:16 +01:00
parent ac26f729ad
commit 328c4624ef
4 changed files with 365 additions and 246 deletions
+119 -103
View File
@@ -79,13 +79,18 @@ impl<R: Read + Seek> Cursor<R> {
if count > 1_000_000 {
return Err("unreasonable GGUF tokenizer array count".into());
}
self.strings(count, "GGUF tokenizer array size overflow", "GGUF tokenizer array exceeds 512 MiB")
}
/// `count` strings whose total length stays below 512 MiB; the messages name the array kind that failed.
fn strings(&mut self, count: u64, overflow: &'static str, exceeds: &'static str) -> Result<Vec<String>> {
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")?;
total = total.checked_add(value.len() as u64).ok_or(overflow)?;
if total > 512 * 1024 * 1024 {
return Err("GGUF tokenizer array exceeds 512 MiB".into());
return Err(exceeds.into());
}
values.push(value);
}
@@ -96,11 +101,7 @@ impl<R: Read + Seek> Cursor<R> {
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 (element, count) = self.array_header("unreasonable GGUF tokenizer array count")?;
let mut values = Vec::with_capacity(count as usize);
for _ in 0..count {
values.push(self.integer(element)?);
@@ -108,109 +109,101 @@ impl<R: Read + Seek> Cursor<R> {
Ok(values)
}
/// The element type and the element count of an array value; `too_many` is the refusal for more than 1M elements.
fn array_header(&mut self, too_many: &'static str) -> Result<(u32, u64)> {
let element = self.u32()?;
let count = self.u64()?;
if count > 1_000_000 {
return Err(too_many.into());
}
Ok((element, count))
}
pub(super) fn integer(&mut self, kind: u32) -> Result<u32> {
match kind {
0 | 7 => Ok(u32::from(self.u8()?)),
1 => u32::try_from(self.u8()? as i8).map_err(Into::into),
2 => Ok(u32::from(self.u16()?)),
3 => u32::try_from(self.u16()? as i16).map_err(Into::into),
4 => self.u32(),
5 => u32::try_from(self.u32()? as i32).map_err(Into::into),
1 | 3 | 5 | 11 => u32::try_from(self.signed_scalar(kind)?).map_err(Into::into),
10 => u32::try_from(self.u64()?).map_err(Into::into),
11 => u32::try_from(self.u64()? as i64).map_err(Into::into),
_ => Err(format!("GGUF metadata type {kind} is not an integer").into()),
}
}
pub(super) fn metadata_value(&mut self, kind: u32) -> Result<MetadataValue> {
/// An unsigned scalar of kind 0, 2, 4 or 10.
fn unsigned_scalar(&mut self, kind: u32) -> Result<u64> {
Ok(match kind {
0 => MetadataValue::Unsigned(u64::from(self.u8()?)),
7 => MetadataValue::Boolean(self.u8()? != 0),
1 => MetadataValue::Signed(i64::from(self.u8()? as i8)),
2 => MetadataValue::Unsigned(u64::from(self.u16()?)),
3 => MetadataValue::Signed(i64::from(self.u16()? as i16)),
4 => MetadataValue::Unsigned(u64::from(self.u32()?)),
5 => MetadataValue::Signed(i64::from(self.u32()? as i32)),
6 => MetadataValue::Float(f64::from(f32::from_bits(self.u32()?))),
8 => MetadataValue::Text(self.string()?),
9 => self.metadata_array()?,
10 => MetadataValue::Unsigned(self.u64()?),
11 => MetadataValue::Signed(self.u64()? as i64),
12 => MetadataValue::Float(f64::from_bits(self.u64()?)),
_ => return Err(format!("unknown GGUF metadata type {kind}").into()),
0 => u64::from(self.u8()?),
2 => u64::from(self.u16()?),
4 => u64::from(self.u32()?),
10 => self.u64()?,
_ => unreachable!(),
})
}
pub(super) fn metadata_array(&mut self) -> Result<MetadataValue> {
let element = self.u32()?;
let count = self.u64()?;
if count > 1_000_000 {
return Err("unreasonable GGUF metadata array count".into());
/// A signed scalar of kind 1, 3, 5 or 11.
fn signed_scalar(&mut self, kind: u32) -> Result<i64> {
Ok(match kind {
1 => i64::from(self.u8()? as i8),
3 => i64::from(self.u16()? as i16),
5 => i64::from(self.u32()? as i32),
11 => self.u64()? as i64,
_ => unreachable!(),
})
}
/// A float scalar of kind 6 (f32) or 12 (f64).
fn float_scalar(&mut self, kind: u32) -> Result<f64> {
Ok(if kind == 6 { f64::from(f32::from_bits(self.u32()?)) } else { f64::from_bits(self.u64()?) })
}
fn boolean(&mut self) -> Result<bool> {
Ok(self.u8()? != 0)
}
pub(super) fn metadata_value(&mut self, kind: u32) -> Result<MetadataValue> {
match kind {
0 | 2 | 4 | 10 => Ok(MetadataValue::Unsigned(self.unsigned_scalar(kind)?)),
1 | 3 | 5 | 11 => Ok(MetadataValue::Signed(self.signed_scalar(kind)?)),
6 | 12 => Ok(MetadataValue::Float(self.float_scalar(kind)?)),
7 => Ok(MetadataValue::Boolean(self.boolean()?)),
8 => Ok(MetadataValue::Text(self.string()?)),
9 => self.metadata_array(),
_ => Err(format!("unknown GGUF metadata type {kind}").into()),
}
let capacity = count as usize;
}
pub(super) fn metadata_array(&mut self) -> Result<MetadataValue> {
let (element, count) = self.array_header("unreasonable GGUF metadata array count")?;
match element {
7 => {
let mut values = Vec::with_capacity(capacity);
for _ in 0..count {
values.push(self.u8()? != 0);
}
Ok(MetadataValue::BooleanArray(values))
}
7 => Ok(MetadataValue::BooleanArray(self.repeat(count, Self::boolean)?)),
0 | 2 | 4 | 10 => {
let mut values = Vec::with_capacity(capacity);
for _ in 0..count {
values.push(match element {
0 => u64::from(self.u8()?),
2 => u64::from(self.u16()?),
4 => u64::from(self.u32()?),
10 => self.u64()?,
_ => unreachable!(),
});
}
Ok(MetadataValue::UnsignedArray(values))
}
1 | 3 | 5 | 11 => {
let mut values = Vec::with_capacity(capacity);
for _ in 0..count {
values.push(match element {
1 => i64::from(self.u8()? as i8),
3 => i64::from(self.u16()? as i16),
5 => i64::from(self.u32()? as i32),
11 => self.u64()? as i64,
_ => unreachable!(),
});
}
Ok(MetadataValue::SignedArray(values))
}
6 | 12 => {
let mut values = Vec::with_capacity(capacity);
for _ in 0..count {
values.push(if element == 6 {
f64::from(f32::from_bits(self.u32()?))
} else {
f64::from_bits(self.u64()?)
});
}
Ok(MetadataValue::FloatArray(values))
Ok(MetadataValue::UnsignedArray(self.repeat(count, |this| this.unsigned_scalar(element))?))
}
1 | 3 | 5 | 11 => Ok(MetadataValue::SignedArray(self.repeat(count, |this| this.signed_scalar(element))?)),
6 | 12 => Ok(MetadataValue::FloatArray(self.repeat(count, |this| this.float_scalar(element))?)),
8 => {
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("GGUF metadata array size overflow")?;
if total > 512 * 1024 * 1024 {
return Err("GGUF metadata string array exceeds 512 MiB".into());
}
values.push(value);
}
Ok(MetadataValue::TextArray(values))
let strings = self.strings(
count,
"GGUF metadata array size overflow",
"GGUF metadata string array exceeds 512 MiB",
);
Ok(MetadataValue::TextArray(strings?))
}
9 => Err("nested GGUF arrays are unsupported".into()),
_ => Err(format!("invalid GGUF metadata array element type {element}").into()),
}
}
/// `count` values, each read by `read`.
fn repeat<T>(&mut self, count: u64, mut read: impl FnMut(&mut Self) -> Result<T>) -> Result<Vec<T>> {
let mut values = Vec::with_capacity(count as usize);
for _ in 0..count {
values.push(read(self)?);
}
Ok(values)
}
pub(super) fn skip_value(&mut self, kind: u32) -> Result<()> {
match kind {
0 | 1 | 7 => self.skip(1),
@@ -220,26 +213,49 @@ impl<R: Read + Seek> Cursor<R> {
let size = self.u64()?;
self.skip(size)
}
9 => {
let element = self.u32()?;
let count = self.u64()?;
match element {
8 => {
if count > 10_000_000 {
return Err("unreasonable GGUF string array count".into());
}
for _ in 0..count {
let size = self.u64()?;
self.skip(size)?;
}
Ok(())
}
9 => Err("nested GGUF arrays are unsupported".into()),
_ => self.skip(count.checked_mul(value_width(element)?).ok_or("GGUF array size overflow")?),
}
}
9 => self.skip_array(),
10..=12 => self.skip(8),
_ => Err(format!("unknown GGUF metadata type {kind}").into()),
}
}
fn skip_array(&mut self) -> Result<()> {
let element = self.u32()?;
let count = self.u64()?;
match element {
8 => self.skip_strings(count),
9 => Err("nested GGUF arrays are unsupported".into()),
_ => self.skip(count.checked_mul(value_width(element)?).ok_or("GGUF array size overflow")?),
}
}
fn skip_strings(&mut self, count: u64) -> Result<()> {
if count > 10_000_000 {
return Err("unreasonable GGUF string array count".into());
}
for _ in 0..count {
let size = self.u64()?;
self.skip(size)?;
}
Ok(())
}
/// The number of metadata entries of the header, after the magic, the version and the tensor count.
pub(super) fn metadata_count(&mut self) -> Result<u64> {
self.skip(16)?; // magic, version, tensor count
let count = self.u64()?;
if count > 1_000_000 {
return Err("unreasonable GGUF header count".into());
}
Ok(count)
}
/// The key and the value type of the next metadata entry; a key that `seen` already holds is refused.
pub(super) fn entry_header(&mut self, seen: &mut HashSet<String>) -> Result<(String, u32)> {
let key = self.string()?;
if !seen.insert(key.clone()) {
return Err(format!("duplicate GGUF metadata key: {key}").into());
}
Ok((key, self.u32()?))
}
}
+40 -27
View File
@@ -67,6 +67,27 @@ impl MetadataFields {
Ok(())
}
fn into_summary(
self,
tensors: u64,
metadata: u64,
data_start: u64,
size: u64,
types: BTreeMap<u32, u64>,
) -> Summary {
Summary {
tensors,
metadata,
architecture: self.architecture,
split_no: self.split_no,
split_count: self.split_count,
split_tensors_count: self.split_tensors_count,
data_start,
file_size: size,
types,
}
}
fn check_split(&self) -> Result<()> {
if let (Some(no), Some(count)) = (self.split_no, self.split_count)
&& (count == 0 || no >= count)
@@ -83,17 +104,7 @@ pub(super) fn parse_index<R: Read + Seek>(
strict: bool,
rules: &IndexRules,
) -> Result<TensorIndex> {
if cursor.take(4)? != b"GGUF" {
return Err("not a GGUF file".into());
}
if cursor.u32()? != 3 {
return Err("only GGUF v3 is supported".into());
}
let tensors = cursor.u64()?;
let metadata = cursor.u64()?;
if !(rules.counts_ok)(tensors, metadata) {
return Err("unreasonable GGUF header count".into());
}
let (tensors, metadata) = read_counts(cursor, rules)?;
let fields = read_metadata(cursor, metadata, rules)?;
if !fields.alignment.is_power_of_two() || fields.alignment > 4096 {
return Err("invalid GGUF alignment".into());
@@ -105,20 +116,26 @@ pub(super) fn parse_index<R: Read + Seek>(
assign_byte_counts(&mut tensor_index, size, data_start, fields.alignment)?;
}
fields.check_split()?;
let summary = Summary {
tensors,
metadata,
architecture: fields.architecture,
split_no: fields.split_no,
split_count: fields.split_count,
split_tensors_count: fields.split_tensors_count,
data_start,
file_size: size,
types,
};
let summary = fields.into_summary(tensors, metadata, data_start, size, types);
Ok(TensorIndex { summary, tensors: tensor_index })
}
/// The magic, the version and the two counts: (tensors, metadata entries).
fn read_counts<R: Read + Seek>(cursor: &mut Cursor<R>, rules: &IndexRules) -> Result<(u64, u64)> {
if cursor.take(4)? != b"GGUF" {
return Err("not a GGUF file".into());
}
if cursor.u32()? != 3 {
return Err("only GGUF v3 is supported".into());
}
let tensors = cursor.u64()?;
let metadata = cursor.u64()?;
if !(rules.counts_ok)(tensors, metadata) {
return Err("unreasonable GGUF header count".into());
}
Ok((tensors, metadata))
}
fn read_split_tensors_count<R: Read + Seek>(cursor: &mut Cursor<R>) -> Result<u64> {
let count = cursor.u32()?;
if count > i32::MAX as u32 {
@@ -131,11 +148,7 @@ fn read_metadata<R: Read + Seek>(cursor: &mut Cursor<R>, count: u64, rules: &Ind
let mut fields = MetadataFields::new();
let mut keys = HashSet::new();
for _ in 0..count {
let key = cursor.string()?;
if !keys.insert(key.clone()) {
return Err(format!("duplicate GGUF metadata key: {key}").into());
}
let kind = cursor.u32()?;
let (key, kind) = cursor.entry_header(&mut keys)?;
fields.apply(cursor, &key, kind, rules)?;
}
Ok(fields)
@@ -93,33 +93,9 @@ pub(super) fn validate_flash_next_profile(snapshot: &MetadataSnapshot) -> Result
if snapshot.architecture.as_deref() != Some("qwen4exp") {
return Err("runtime_profile requires general.architecture=qwen4exp".into());
}
let required = [
("qwen4exp.block_count", Some(48)),
("qwen4exp.embedding_length", Some(2560)),
("qwen4exp.attention.head_count", Some(24)),
("qwen4exp.attention.head_count_kv", Some(2)),
("qwen4exp.expert_count", None),
("qwen4exp.expert_used_count", None),
];
let mut values = BTreeMap::new();
for (key, expected) in required {
let value = match snapshot.values.get(key) {
Some(MetadataValue::Unsigned(value)) => u32::try_from(*value)
.map_err(|_| format!("runtime_profile: {key} must be a nonnegative 32-bit integer"))?,
Some(MetadataValue::Signed(value)) => u32::try_from(*value)
.map_err(|_| format!("runtime_profile: {key} must be a nonnegative 32-bit integer"))?,
None => return Err(format!("runtime_profile: missing {key}").into()),
_ => return Err(format!("runtime_profile: {key} must be an integer").into()),
};
values.insert(key, value);
if value == 0 || value > i32::MAX as u32 {
return Err(format!("runtime_profile: {key} must be in 1..2147483647").into());
}
if let Some(expected) = expected
&& value != expected
{
return Err(format!("runtime_profile: {key}={value}, expected {expected}").into());
}
for (key, expected) in FLASH_NEXT_REQUIRED {
values.insert(key, profile_value(snapshot, key, expected)?);
}
if values["qwen4exp.expert_used_count"] > values["qwen4exp.expert_count"] {
return Err("runtime_profile: qwen4exp.expert_used_count exceeds qwen4exp.expert_count".into());
@@ -127,6 +103,35 @@ pub(super) fn validate_flash_next_profile(snapshot: &MetadataSnapshot) -> Result
Ok(())
}
/// The integer keys of the runtime profile and the value each must have (`None`: any value in range).
const FLASH_NEXT_REQUIRED: [(&str, Option<u32>); 6] = [
("qwen4exp.block_count", Some(48)),
("qwen4exp.embedding_length", Some(2560)),
("qwen4exp.attention.head_count", Some(24)),
("qwen4exp.attention.head_count_kv", Some(2)),
("qwen4exp.expert_count", None),
("qwen4exp.expert_used_count", None),
];
fn profile_value(snapshot: &MetadataSnapshot, key: &str, expected: Option<u32>) -> Result<u32> {
let not_u32 = |_| format!("runtime_profile: {key} must be a nonnegative 32-bit integer");
let value = match snapshot.values.get(key) {
Some(MetadataValue::Unsigned(value)) => u32::try_from(*value).map_err(not_u32)?,
Some(MetadataValue::Signed(value)) => u32::try_from(*value).map_err(not_u32)?,
None => return Err(format!("runtime_profile: missing {key}").into()),
_ => return Err(format!("runtime_profile: {key} must be an integer").into()),
};
if value == 0 || value > i32::MAX as u32 {
return Err(format!("runtime_profile: {key} must be in 1..2147483647").into());
}
if let Some(expected) = expected
&& value != expected
{
return Err(format!("runtime_profile: {key}={value}, expected {expected}").into());
}
Ok(value)
}
/// Every metadata key/value of a GGUF file, in file order, bounded like the other readers (1M entries, 1 MiB
/// strings, 1M-element arrays, 512 MiB of array text). Duplicate keys and nested arrays are refused, and so is a
/// string that is not valid UTF-8 (`tools/gguf_reader.py` replaces bad bytes instead). Tensor payloads are never read.
@@ -136,19 +141,11 @@ pub fn metadata_entries(path: &Path) -> Result<Vec<(String, MetadataValue)>> {
read_index_file(&mut file, size, false)?;
file.seek(SeekFrom::Start(0))?;
let mut cursor = Cursor::new(&mut file, size);
cursor.skip(16)?; // magic, version, tensor count
let count = cursor.u64()?;
if count > 1_000_000 {
return Err("unreasonable GGUF header count".into());
}
let count = cursor.metadata_count()?;
let mut seen = HashSet::new();
let mut entries = Vec::new();
for _ in 0..count {
let key = cursor.string()?;
if !seen.insert(key.clone()) {
return Err(format!("duplicate GGUF metadata key: {key}").into());
}
let kind = cursor.u32()?;
let (key, kind) = cursor.entry_header(&mut seen)?;
entries.push((key, cursor.metadata_value(kind)?));
}
Ok(entries)
@@ -3,6 +3,140 @@
#[allow(unused_imports)]
use super::*;
/// Which optional groups of keys a snapshot read keeps.
struct Wanted<'a> {
qwen_keys: Option<&'a [&'a str]>,
parse_tokenizer: bool,
parse_architecture: bool,
}
/// The fields a snapshot read collects while it walks the metadata.
#[derive(Default)]
struct SnapshotBuilder {
architecture: Option<String>,
split_no: Option<u64>,
split_count: Option<u64>,
split_tensors_count: Option<u64>,
model: Option<String>,
pre: Option<String>,
tokens: Option<Vec<String>>,
merges: Option<Vec<String>>,
token_types: Option<Vec<u32>>,
special_ids: BTreeMap<String, u32>,
chat_template: Option<String>,
values: BTreeMap<String, MetadataValue>,
}
impl SnapshotBuilder {
fn read_entry<R: Read + Seek>(
&mut self,
cursor: &mut Cursor<R>,
key: String,
kind: u32,
want: &Wanted,
) -> Result<()> {
if self.try_architecture(cursor, &key, kind, want)? || self.try_split(cursor, &key, kind)? {
return Ok(());
}
if want.parse_tokenizer && self.try_tokenizer(cursor, &key, kind)? {
return Ok(());
}
if want.qwen_keys.is_some_and(|keys| keys.contains(&key.as_str())) {
self.values.insert(key, cursor.metadata_value(kind)?);
return Ok(());
}
cursor.skip_value(kind)
}
fn try_architecture<R: Read + Seek>(
&mut self,
cursor: &mut Cursor<R>,
key: &str,
kind: u32,
want: &Wanted,
) -> Result<bool> {
if key != "general.architecture" || !want.parse_architecture || kind != 8 {
return Ok(false);
}
self.architecture = Some(cursor.string()?);
Ok(true)
}
fn try_split<R: Read + Seek>(&mut self, cursor: &mut Cursor<R>, key: &str, kind: u32) -> Result<bool> {
match (key, kind) {
("split.no", 2) => self.split_no = Some(u64::from(cursor.u16()?)),
("split.count", 2) => self.split_count = Some(u64::from(cursor.u16()?)),
("split.tensors.count", 5) => self.split_tensors_count = Some(u64::from(cursor.u32()?)),
("split.no" | "split.count" | "split.tensors.count", _) => {
return Err("GGUF split metadata has an invalid integer type".into());
}
_ => return Ok(false),
}
Ok(true)
}
fn try_tokenizer<R: Read + Seek>(&mut self, cursor: &mut Cursor<R>, key: &str, kind: u32) -> Result<bool> {
Ok(self.try_text(cursor, key, kind)?
|| self.try_arrays(cursor, key, kind)?
|| self.try_special_id(cursor, key, kind)?)
}
fn try_text<R: Read + Seek>(&mut self, cursor: &mut Cursor<R>, key: &str, kind: u32) -> Result<bool> {
let slot = match key {
"tokenizer.ggml.model" => &mut self.model,
"tokenizer.ggml.pre" => &mut self.pre,
"tokenizer.chat_template" => &mut self.chat_template,
_ => return Ok(false),
};
if kind != 8 {
return Ok(false);
}
*slot = Some(cursor.string()?);
Ok(true)
}
fn try_arrays<R: Read + Seek>(&mut self, cursor: &mut Cursor<R>, key: &str, kind: u32) -> Result<bool> {
match key {
"tokenizer.ggml.tokens" => self.tokens = Some(cursor.string_array(kind)?),
"tokenizer.ggml.merges" => self.merges = Some(cursor.string_array(kind)?),
"tokenizer.ggml.token_type" => self.token_types = Some(cursor.integer_array(kind)?),
_ => return Ok(false),
}
Ok(true)
}
fn try_special_id<R: Read + Seek>(&mut self, cursor: &mut Cursor<R>, key: &str, kind: u32) -> Result<bool> {
if !key.starts_with("tokenizer.ggml.") || !key.ends_with("_token_id") {
return Ok(false);
}
self.special_ids.insert(key.to_owned(), cursor.integer(kind)?);
Ok(true)
}
fn finish(self) -> MetadataSnapshot {
let tokenizer = match (self.model, self.tokens, self.merges, self.chat_template) {
(Some(model), Some(tokens), Some(merges), Some(chat_template)) => Some(TokenizerMetadata {
model,
pre: self.pre.unwrap_or_else(|| "qwen35".to_owned()),
tokens,
merges,
token_types: self.token_types,
special_ids: self.special_ids,
chat_template,
}),
_ => None,
};
MetadataSnapshot {
architecture: self.architecture,
split_no: self.split_no,
split_count: self.split_count,
split_tensors_count: self.split_tensors_count,
values: self.values,
tokenizer,
}
}
}
pub(super) fn read_metadata_snapshot_with_architecture(
file: &mut File,
size: u64,
@@ -12,85 +146,46 @@ pub(super) fn read_metadata_snapshot_with_architecture(
) -> Result<MetadataSnapshot> {
file.seek(SeekFrom::Start(0))?;
let mut cursor = Cursor::new(file, size);
cursor.skip(16)?; // magic, version, tensor count
let count = cursor.u64()?;
if count > 1_000_000 {
return Err("unreasonable GGUF header count".into());
}
let mut architecture = None;
let mut split_no = None;
let mut split_count = None;
let mut split_tensors_count = None;
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 values = BTreeMap::new();
let count = cursor.metadata_count()?;
let want = Wanted { qwen_keys, parse_tokenizer, parse_architecture };
let mut builder = SnapshotBuilder::default();
let mut seen = HashSet::new();
for _ in 0..count {
let key = cursor.string()?;
if !seen.insert(key.clone()) {
return Err(format!("duplicate GGUF metadata key: {key}").into());
}
let kind = cursor.u32()?;
match key.as_str() {
"general.architecture" if parse_architecture && kind == 8 => architecture = Some(cursor.string()?),
"split.no" if kind == 2 => split_no = Some(u64::from(cursor.u16()?)),
"split.count" if kind == 2 => split_count = Some(u64::from(cursor.u16()?)),
"split.tensors.count" if kind == 5 => split_tensors_count = Some(u64::from(cursor.u32()?)),
"split.no" | "split.count" | "split.tensors.count" => {
return Err("GGUF split metadata has an invalid integer type".into());
}
"tokenizer.ggml.model" if parse_tokenizer && kind == 8 => model = Some(cursor.string()?),
"tokenizer.ggml.pre" if parse_tokenizer && kind == 8 => pre = Some(cursor.string()?),
"tokenizer.ggml.tokens" if parse_tokenizer => tokens = Some(cursor.string_array(kind)?),
"tokenizer.ggml.merges" if parse_tokenizer => merges = Some(cursor.string_array(kind)?),
"tokenizer.ggml.token_type" if parse_tokenizer => token_types = Some(cursor.integer_array(kind)?),
"tokenizer.chat_template" if parse_tokenizer && kind == 8 => chat_template = Some(cursor.string()?),
_ if parse_tokenizer && key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id") => {
special_ids.insert(key, cursor.integer(kind)?);
}
_ if qwen_keys.is_some_and(|keys| keys.contains(&key.as_str())) => {
values.insert(key, cursor.metadata_value(kind)?);
}
_ => cursor.skip_value(kind)?,
}
let (key, kind) = cursor.entry_header(&mut seen)?;
builder.read_entry(&mut cursor, key, kind, &want)?;
}
let tokenizer = match (model, tokens, merges, chat_template) {
(Some(model), Some(tokens), Some(merges), Some(chat_template)) => Some(TokenizerMetadata {
model,
pre: pre.unwrap_or_else(|| "qwen35".to_owned()),
tokens,
merges,
token_types,
special_ids,
chat_template,
}),
_ => None,
};
Ok(MetadataSnapshot { architecture, split_no, split_count, split_tensors_count, values, tokenizer })
Ok(builder.finish())
}
pub(crate) fn validate_tokenizer_metadata(tokenizer: TokenizerMetadata) -> Result<TokenizerMetadata> {
let TokenizerMetadata { model, pre, tokens, merges, token_types, special_ids, chat_template } = tokenizer;
if model != "gpt2" || pre != "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() {
check_tokenizer_shape(&tokenizer)?;
let vocab: HashSet<&str> = tokenizer.tokens.iter().map(String::as_str).collect();
if vocab.len() != tokenizer.tokens.len() {
return Err("GGUF tokenizer has duplicate vocabulary entries".into());
}
check_merges(&tokenizer.merges, &vocab)?;
if tokenizer.special_ids.values().any(|&id| id as usize >= tokenizer.tokens.len()) {
return Err("special token ID exceeds vocabulary".into());
}
Ok(tokenizer)
}
fn check_tokenizer_shape(tokenizer: &TokenizerMetadata) -> Result<()> {
if tokenizer.model != "gpt2" || tokenizer.pre != "qwen35" {
return Err("only the qwen35 byte-level BPE tokenizer is supported".into());
}
if tokenizer.tokens.is_empty() || tokenizer.chat_template.is_empty() {
return Err("GGUF tokenizer has an empty vocabulary or chat template".into());
}
if tokenizer.token_types.as_ref().is_some_and(|types| types.len() != tokenizer.tokens.len()) {
return Err("token_type length differs from vocabulary length".into());
}
Ok(())
}
fn check_merges(merges: &[String], vocab: &HashSet<&str>) -> Result<()> {
let mut seen_merges = HashSet::new();
for merge in &merges {
for merge in merges {
let Some((left, right)) = merge.split_once(' ') else {
return Err("GGUF BPE merge is not a pair".into());
};
@@ -104,12 +199,7 @@ pub(crate) fn validate_tokenizer_metadata(tokenizer: TokenizerMetadata) -> Resul
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, tokens, merges, token_types, special_ids, chat_template })
Ok(())
}
pub fn inspect(path: &Path) -> Result<Summary> {
@@ -134,13 +224,16 @@ pub fn tensor_sha256(path: &Path, index: &TensorIndex, tensor_number: usize) ->
return Err("GGUF tensor exceeds indexed file".into());
}
let mut file = File::open(path)?;
if file.metadata()?.len() != index.summary.file_size {
return Err("GGUF source size changed after indexing".into());
}
ensure_size(&file, index.summary.file_size, "GGUF source size changed after indexing")?;
hash_span(&mut file, absolute, tensor.bytes)
}
/// SHA-256 of `bytes` bytes at `absolute`, read through a 1 MiB buffer.
fn hash_span(file: &mut File, absolute: u64, bytes: u64) -> Result<[u8; 32]> {
file.seek(SeekFrom::Start(absolute))?;
let mut digest = Sha256::new();
let mut buffer = vec![0u8; 1024 * 1024];
let mut remaining = tensor.bytes;
let mut remaining = bytes;
while remaining > 0 {
let count = remaining.min(buffer.len() as u64) as usize;
file.read_exact(&mut buffer[..count])?;