use super::*;
use crate::backends::gguf::types::MetaValue;
use crate::backends::gguf::writer::GgufWriter;
const BOS: usize = 0;
const EOS: usize = 1;
const PAD: usize = 2;
const UNK: usize = 3;
const EOT: usize = 4;
const EOM: usize = 5;
const PROMPT: &str = "abc <tag> <|vision_pad|> é\n<|im_end|>";
#[derive(Clone)]
struct Fixture {
tokens: Vec<String>,
types: Option<Vec<i32>>,
merges: Vec<String>,
ids: [Option<u32>; 6],
pre: String,
}
impl Fixture {
fn new() -> Self {
let mut alphabet: Vec<char> = ByteLevel::alphabet().into_iter().collect();
alphabet.sort_unstable();
let mut tokens: Vec<String> = alphabet.into_iter().map(|ch| ch.to_string()).collect();
tokens.extend(
["ab", "bc", "<|im_end|>", "<|endoftext|>", "<tag>", "<|vision_pad|>", "[PAD]"]
.into_iter()
.map(str::to_owned),
);
let mut fixture = Self {
types: Some(vec![token_type::NORMAL; tokens.len()]),
tokens,
merges: vec!["a b".into(), "b c".into()],
ids: [None; 6],
pre: "qwen35".into(),
};
for name in ["<|im_end|>", "<|endoftext|>", "<tag>", "<|vision_pad|>"] {
let id = fixture.id(name) as usize;
fixture.types.as_mut().expect("types")[id] = token_type::CONTROL;
}
let unused = fixture.id("[PAD]") as usize;
fixture.types.as_mut().expect("types")[unused] = token_type::UNUSED;
let end = fixture.id("<|endoftext|>");
fixture.ids[BOS] = Some(end);
fixture.ids[EOS] = Some(fixture.id("<|im_end|>"));
fixture.ids[PAD] = Some(end);
fixture
}
fn id(&self, name: &str) -> u32 {
self.tokens.iter().position(|token| token == name).expect(name) as u32
}
fn open(&self) -> (tempfile::TempDir, GgufFile) {
let mut metadata = vec![
("general.architecture", MetaValue::String("qwen35".into())),
("tokenizer.ggml.model", MetaValue::String("gpt2".into())),
("tokenizer.ggml.pre", MetaValue::String(self.pre.clone())),
("tokenizer.ggml.tokens", MetaValue::ArrayString(self.tokens.clone())),
("tokenizer.ggml.merges", MetaValue::ArrayString(self.merges.clone())),
];
if let Some(types) = &self.types {
metadata.push(("tokenizer.ggml.token_type", MetaValue::ArrayI32(types.clone())));
}
for (key, id) in SPECIAL_TOKEN_ID_KEYS.into_iter().zip(self.ids) {
if let Some(id) = id {
metadata.push((key, MetaValue::U32(id)));
}
}
let mut writer = GgufWriter::new(std::io::Cursor::new(Vec::new()));
writer.write_header(0, metadata.len() as u64).expect("header");
for (key, value) in &metadata {
writer.write_metadata_kv(key, value).expect("metadata");
}
writer.pad_to_alignment().expect("alignment");
writer.finalize().expect("finalize");
let directory = tempfile::tempdir().expect("tempdir");
let path = directory.path().join("tokenizer.gguf");
std::fs::write(&path, writer.into_inner().into_inner()).expect("write GGUF");
let gguf = GgufFile::open(&path).expect("open GGUF");
(directory, gguf)
}
fn build(&self) -> (String, Tokenizer, Vec<u32>) {
let (_directory, gguf) = self.open();
(
tokenizer_identity(&gguf).expect("identity"),
build_tokenizer_from_gguf(&gguf).expect("production tokenizer"),
serving_stop_token_ids(&gguf),
)
}
fn snapshot(&self, prompt: &str) -> Snapshot {
let (identity, tokenizer, mut stops) = self.build();
let encoding = tokenizer.encode(prompt, false).expect("encode");
let ids = encoding.get_ids().to_vec();
let decoded = tokenizer.decode(&ids, false).expect("decode");
stops.sort_unstable();
Snapshot { identity, ids, decoded, stops }
}
}
#[derive(Debug, PartialEq, Eq)]
struct Snapshot {
identity: String,
ids: Vec<u32>,
decoded: String,
stops: Vec<u32>,
}
#[test]
fn tokenizer_identity_follows_the_special_tokens_the_builder_registers() {
let fixture = Fixture::new();
let expected = fixture.snapshot(PROMPT);
assert_eq!(expected.decoded, PROMPT);
assert!(expected.ids.contains(&fixture.id("<tag>")));
let mut user_defined = fixture.clone();
let tag = fixture.id("<tag>") as usize;
user_defined.types.as_mut().expect("types")[tag] = token_type::USER_DEFINED;
assert_eq!(user_defined.snapshot(PROMPT), expected);
let mut ordinary_type = fixture.clone();
let a = fixture.id("a") as usize;
ordinary_type.types.as_mut().expect("types")[a] = token_type::BYTE;
assert_eq!(ordinary_type.snapshot(PROMPT), expected);
let mut fallback = fixture.clone();
fallback.types = None;
fallback.ids[UNK] = Some(fixture.id("<tag>"));
fallback.ids[EOM] = Some(fixture.id("<|vision_pad|>"));
assert_eq!(fallback.snapshot(PROMPT), expected);
}
#[test]
fn tokenizer_identity_admits_the_reported_typed_pad_248055_conversion() {
let mut pinned = Fixture::new();
let mut types = pinned.types.take().expect("types");
for index in pinned.tokens.len()..=248_055 {
pinned.tokens.push(format!("[PAD{index}]"));
types.push(token_type::UNUSED);
}
for (name, target) in [
("<|endoftext|>", 248_044),
("<|im_end|>", 248_046),
("<|vision_pad|>", 248_055),
] {
let original = pinned.id(name) as usize;
pinned.tokens.swap(original, target);
types.swap(original, target);
}
pinned.types = Some(types);
pinned.ids[BOS] = Some(248_044);
pinned.ids[EOS] = Some(248_046);
pinned.ids[PAD] = Some(248_044);
let mut external = pinned.clone();
external.ids[PAD] = Some(248_055);
let expected = pinned.snapshot(PROMPT);
assert_eq!(expected.decoded, PROMPT);
assert!(expected.ids.contains(&248_055));
assert_eq!(expected.stops, [248_044, 248_046]);
assert_eq!(external.snapshot(PROMPT), expected);
}
#[test]
fn tokenizer_identity_ignores_unused_typed_special_ids() {
let fixture = Fixture::new();
let expected = fixture.snapshot(PROMPT);
for (slot, value) in [
(BOS, None),
(PAD, None),
(UNK, Some(fixture.id("a"))),
(EOM, Some(fixture.id("b"))),
] {
let mut equivalent = fixture.clone();
equivalent.ids[slot] = value;
assert_eq!(equivalent.snapshot(PROMPT), expected, "slot {slot}");
}
}
#[test]
fn tokenizer_identity_normalizes_redundant_canonical_stop_metadata() {
let fixture = Fixture::new();
let expected = fixture.snapshot(PROMPT);
for (slot, value) in [
(EOS, None),
(EOT, Some(fixture.id("<|im_end|>"))),
(EOS, Some(fixture.id("<|endoftext|>"))),
] {
let mut equivalent = fixture.clone();
equivalent.ids[slot] = value;
assert_eq!(equivalent.snapshot(PROMPT), expected, "slot {slot}");
}
}
#[test]
fn tokenizer_identity_preserves_runtime_stop_priority_and_legacy_fallback() {
let mut fixture = Fixture::new();
let end = fixture.id("<|endoftext|>");
let im_end = fixture.id("<|im_end|>");
let tag = fixture.id("<tag>");
fixture.ids[EOS] = Some(end);
fixture.ids[EOT] = Some(tag);
let (_, tokenizer, stops) = fixture.build();
assert_eq!(stops, [end, tag, im_end]);
assert_eq!(tokenizer.encode("<tag>", false).expect("encode").get_ids(), [tag]);
fixture.ids[EOT] = Some(end);
assert_eq!(fixture.build().2, [end, im_end]);
fixture.ids = [None; 6];
fixture.tokens[end as usize] = "former_endoftext".into();
fixture.tokens[im_end as usize] = "former_im_end".into();
let snapshot = fixture.snapshot("abc");
assert_eq!(snapshot.stops, [151_645]);
assert_eq!(snapshot.ids, [fixture.id("ab"), fixture.id("c")]);
assert_eq!(snapshot.decoded, "abc");
}
#[test]
fn tokenizer_identity_rejects_changed_effective_stop_membership() {
let fixture = Fixture::new();
let before = fixture.snapshot("<tag>");
let mut incompatible = fixture.clone();
let tag = fixture.id("<tag>");
incompatible.ids[EOT] = Some(tag);
let after = incompatible.snapshot("<tag>");
assert_eq!(before.ids, after.ids);
assert_eq!(before.decoded, after.decoded);
assert!(!before.stops.contains(&tag));
assert!(after.stops.contains(&tag));
assert_ne!(before.identity, after.identity);
}
#[test]
fn tokenizer_identity_rejects_changed_atomic_specials_and_missing_type_pad_semantics() {
let fixture = Fixture::new();
let before = fixture.snapshot("<tag>");
let mut ordinary = fixture.clone();
let tag = fixture.id("<tag>") as usize;
ordinary.types.as_mut().expect("types")[tag] = token_type::NORMAL;
let after = ordinary.snapshot("<tag>");
assert_eq!(before.ids, [tag as u32]);
assert_ne!(before.ids, after.ids);
assert_eq!(after.decoded, "<tag>");
assert_ne!(before.identity, after.identity);
let mut untyped = fixture.clone();
untyped.types = None;
let before = untyped.snapshot("<|vision_pad|>");
let vision = fixture.id("<|vision_pad|>");
untyped.ids[PAD] = Some(vision);
let after = untyped.snapshot("<|vision_pad|>");
assert_eq!(after.ids, [vision]);
assert_ne!(before.ids, after.ids);
assert_eq!(before.decoded, after.decoded);
assert_ne!(before.identity, after.identity);
}
#[test]
fn tokenizer_identity_rejects_changed_vocabulary_mapping_and_merge_priority() {
let fixture = Fixture::new();
let before = fixture.snapshot("a");
let mut remapped = fixture.clone();
let a = fixture.id("a") as usize;
let b = fixture.id("b") as usize;
remapped.tokens.swap(a, b);
let after = remapped.snapshot("a");
assert_ne!(before.ids, after.ids);
assert_eq!(before.decoded, after.decoded);
assert_ne!(before.identity, after.identity);
let before = fixture.snapshot("abc");
let mut reordered = fixture.clone();
reordered.merges.reverse();
let after = reordered.snapshot("abc");
assert_eq!(before.ids, [fixture.id("ab"), fixture.id("c")]);
assert_eq!(after.ids, [fixture.id("a"), fixture.id("bc")]);
assert_eq!(before.decoded, after.decoded);
assert_ne!(before.identity, after.identity);
}
#[test]
fn tokenizer_identity_preserves_unused_vocabulary_decode_semantics() {
let fixture = Fixture::new();
let id = fixture.id("[PAD]");
let (before_identity, before, _) = fixture.build();
let mut changed = fixture.clone();
changed.tokens[id as usize] = "[UNUSED]".into();
let (after_identity, after, _) = changed.build();
assert_eq!(before.decode(&[id], false).expect("decode"), "[PAD]");
assert_eq!(after.decode(&[id], false).expect("decode"), "[UNUSED]");
assert_ne!(before_identity, after_identity);
}
#[test]
fn tokenizer_identity_uses_the_builders_empty_token_normalization() {
let mut empty = Fixture::new();
let id = empty.tokens.len() as u32;
empty.tokens.push(String::new());
empty.types.as_mut().expect("types").push(token_type::UNUSED);
let mut literal = empty.clone();
let replacement = format!("[EMPTY_{id}]");
literal.tokens[id as usize] = replacement.clone();
let (empty_identity, empty_tokenizer, _) = empty.build();
let (literal_identity, literal_tokenizer, _) = literal.build();
assert_eq!(empty_tokenizer.decode(&[id], false).expect("decode"), replacement);
assert_eq!(literal_tokenizer.decode(&[id], false).expect("decode"), replacement);
assert_eq!(empty_identity, literal_identity);
assert_eq!(empty.snapshot(PROMPT), literal.snapshot(PROMPT));
}
#[test]
fn tokenizer_identity_refuses_unsupported_pretokenization_like_the_builder() {
let mut fixture = Fixture::new();
fixture.pre = "qwen2".into();
let (_directory, gguf) = fixture.open();
let identity_error = tokenizer_identity(&gguf).err().expect("unsupported identity");
let builder_error = build_tokenizer_from_gguf(&gguf).err().expect("unsupported builder");
assert!(identity_error.to_string().contains("qwen2"));
assert!(builder_error.to_string().contains("qwen2"));
assert!(identity_error.to_string().contains("not supported"));
assert!(builder_error.to_string().contains("not supported"));
}