crates/format/vocab/tests/vocab.rs 12.3 KiB 348 lines Raw
1 //! The vocabulary against GGUF files that this test builds byte by byte.2 3 use inf3r_gguf::Gguf;4 use inf3r_text::token::Token;5 use inf3r_vocab::{Vocab, VocabError};6 7 /// The alignment that the GGUF reader uses when the metadata has no key.8 const ALIGN: usize = 32;9 10 /// One metadata entry that the builder writes.11 enum Entry {12     /// A string under a key.13     Str(&'static str, &'static str),14     /// An array of strings under a key.15     Strings(&'static str, Vec<&'static str>),16     /// An array of `u32` under a key.17     U32s(&'static str, Vec<u32>),18     /// An array of `f32` under a key.19     F32s(&'static str, Vec<f32>),20     /// A bool under a key.21     Bool(&'static str, bool),22 }23 24 /// The five tokens of the standard GPT-2 test vocabulary.25 ///26 /// `ab` is the merge. The last two are the two bytes of `é`.27 const TOKENS: [&str; 5] = ["a", "b", "ab", "<0xC3>", "<0xA9>"];28 29 /// The pieces of the Llama test vocabulary.30 ///31 /// Every word piece starts with the metaspace. The merge list is the pieces32 /// that SentencePiece BPE can form on the way to the two words, plus the two33 /// single characters that stay after the merges. The last piece is a byte token34 /// for a newline, which has no text of its own.35 const LLAMA_TOKENS: [&str; 19] = [36     "▁", "h", "e", "l", "o", "▁h", "▁he", "▁hel", "▁hell", "▁hello", "▁world", "w", "r", "d", "▁w",37     "▁wo", "▁wor", "▁worl", "<0x0a>",38 ];39 40 /// The scores of the Llama test vocabulary. Zero ties every piece, so the41 /// merged piece with the lowest id wins a tie.42 const LLAMA_SCORES: [f32; 19] = [0.0; 19];43 44 /// Writes a length-prefixed string.45 fn push_str(out: &mut Vec<u8>, text: &str) {46     out.extend_from_slice(&(text.len() as u64).to_le_bytes());47     out.extend_from_slice(text.as_bytes());48 }49 50 /// Builds a whole GGUF file with no tensors.51 fn build(entries: &[Entry]) -> Vec<u8> {52     let mut out = Vec::new();53     out.extend_from_slice(b"GGUF");54     out.extend_from_slice(&3u32.to_le_bytes());55     out.extend_from_slice(&0u64.to_le_bytes());56     out.extend_from_slice(&(entries.len() as u64).to_le_bytes());57 58     for entry in entries {59         match entry {60             Entry::Str(key, value) => {61                 push_str(&mut out, key);62                 out.extend_from_slice(&11u32.to_le_bytes());63                 push_str(&mut out, value);64             }65             Entry::Strings(key, values) => {66                 push_str(&mut out, key);67                 out.extend_from_slice(&12u32.to_le_bytes());68                 out.extend_from_slice(&11u32.to_le_bytes());69                 out.extend_from_slice(&(values.len() as u64).to_le_bytes());70                 for value in values {71                     push_str(&mut out, value);72                 }73             }74             Entry::U32s(key, values) => {75                 push_str(&mut out, key);76                 out.extend_from_slice(&12u32.to_le_bytes());77                 out.extend_from_slice(&4u32.to_le_bytes());78                 out.extend_from_slice(&(values.len() as u64).to_le_bytes());79                 for value in values {80                     out.extend_from_slice(&value.to_le_bytes());81                 }82             }83             Entry::F32s(key, values) => {84                 push_str(&mut out, key);85                 out.extend_from_slice(&12u32.to_le_bytes());86                 out.extend_from_slice(&8u32.to_le_bytes());87                 out.extend_from_slice(&(values.len() as u64).to_le_bytes());88                 for value in values {89                     out.extend_from_slice(&value.to_le_bytes());90                 }91             }92             Entry::Bool(key, value) => {93                 push_str(&mut out, key);94                 out.extend_from_slice(&10u32.to_le_bytes());95                 out.push(u8::from(*value));96             }97         }98     }99 100     let rem = out.len() % ALIGN;101     if rem != 0 {102         out.resize(out.len() + (ALIGN - rem), 0);103     }104     out105 }106 107 /// Parses a file and reads its vocabulary.108 fn vocab(bytes: &[u8]) -> Vocab {109     let gguf = Gguf::parse(bytes).expect("the test file parses");110     Vocab::from_gguf(&gguf).expect("the test file has a vocabulary")111 }112 113 /// The standard GPT-2 vocabulary, with an optional template.114 fn generation(template: Option<&'static str>) -> Vocab {115     let mut entries = vec![116         Entry::Strings("tokenizer.ggml.tokens", TOKENS.to_vec()),117         Entry::Strings("tokenizer.ggml.merges", vec!["a b"]),118         Entry::U32s("tokenizer.ggml.token_type", vec![1, 1, 1, 6, 6]),119         Entry::Str("tokenizer.ggml.model", "gpt2"),120     ];121     if let Some(text) = template {122         entries.push(Entry::Str("tokenizer.chat_template", text));123     }124     vocab(&build(&entries))125 }126 127 /// A Llama vocabulary from the given pieces and scores, with no merge list.128 fn llama(tokens: &[&'static str], scores: &[f32]) -> Vocab {129     let entries = vec![130         Entry::Strings("tokenizer.ggml.tokens", tokens.to_vec()),131         Entry::F32s("tokenizer.ggml.scores", scores.to_vec()),132         Entry::Str("tokenizer.ggml.model", "llama"),133     ];134     vocab(&build(&entries))135 }136 137 #[test]138 fn a_merge_turns_two_bytes_into_one_token_and_back() {139     let vocab = generation(None);140     let tokens = vocab.encode("ab").unwrap();141     assert_eq!(tokens, vec![Token(2)]);142     assert_eq!(vocab.decode(&tokens).unwrap(), "ab");143 }144 145 #[test]146 fn two_tokens_that_split_a_character_decode_to_one_character() {147     let vocab = generation(None);148     assert_eq!(vocab.decode(&[Token(3), Token(4)]).unwrap(), "é");149     assert_eq!(vocab.encode("é").unwrap(), vec![Token(3), Token(4)]);150 }151 152 #[test]153 fn a_byte_with_no_token_is_an_error() {154     let vocab = generation(None);155     assert_eq!(vocab.encode("z"), Err(VocabError::Byte(b'z')));156 }157 158 #[test]159 fn a_file_without_a_vocabulary_names_the_missing_key() {160     let bytes = build(&[Entry::Str("tokenizer.ggml.model", "llama")]);161     let gguf = Gguf::parse(&bytes).unwrap();162     let err = Vocab::from_gguf(&gguf).unwrap_err();163     assert_eq!(err, VocabError::Missing("tokenizer.ggml.tokens"));164     assert!(err.to_string().contains("tokenizer.ggml.tokens"));165 }166 167 #[test]168 fn the_lower_merge_rank_wins() {169     let bytes = build(&[170         Entry::Strings("tokenizer.ggml.tokens", vec!["a", "b", "c", "ab", "bc"]),171         Entry::Strings("tokenizer.ggml.merges", vec!["a b", "b c"]),172         Entry::U32s("tokenizer.ggml.token_type", vec![1, 1, 1, 1, 1]),173         Entry::Str("tokenizer.ggml.model", "gpt2"),174     ]);175     let vocab = vocab(&bytes);176     let tokens = vocab.encode("abc").unwrap();177     // `a b` has the lower rank, so `ab` holds the first two bytes and `b c`178     // no longer has a pair to join.179     assert_eq!(tokens, vec![Token(3), Token(2)]);180     assert_eq!(vocab.decode(&tokens).unwrap(), "abc");181 }182 183 #[test]184 fn a_new_pair_is_queued_after_a_merge() {185     let bytes = build(&[186         Entry::Strings("tokenizer.ggml.tokens", vec!["a", "b", "c", "bc", "abc"]),187         Entry::Strings("tokenizer.ggml.merges", vec!["b c", "a bc"]),188         Entry::U32s("tokenizer.ggml.token_type", vec![1, 1, 1, 1, 1]),189         Entry::Str("tokenizer.ggml.model", "gpt2"),190     ]);191     let vocab = vocab(&bytes);192     // `b c` merges first, then the newly adjacent `a bc` merges.193     assert_eq!(vocab.encode("abc").unwrap(), vec![Token(4)]);194     assert_eq!(vocab.decode(&[Token(4)]).unwrap(), "abc");195 }196 197 #[test]198 fn a_user_defined_token_is_matched_like_a_control_token() {199     let bytes = build(&[200         Entry::Strings("tokenizer.ggml.tokens", vec!["a", "[SPECIAL]", "Ġ"]),201         Entry::U32s("tokenizer.ggml.token_type", vec![1, 4, 1]),202         Entry::Str("tokenizer.ggml.model", "gpt2"),203     ]);204     let vocab = vocab(&bytes);205     assert_eq!(206         vocab.encode("a[SPECIAL] a").unwrap(),207         vec![Token(0), Token(1), Token(2), Token(0)]208     );209     assert_eq!(210         vocab211             .decode(&[Token(0), Token(1), Token(2), Token(0)])212             .unwrap(),213         "a[SPECIAL] a"214     );215 }216 217 #[test]218 fn the_template_is_read_when_the_key_is_present() {219     assert_eq!(220         generation(Some("{{ prompt }}")).template(),221         Some("{{ prompt }}")222     );223     assert_eq!(generation(None).template(), None);224 }225 226 #[test]227 fn a_llama_prompt_uses_the_metaspace_pieces() {228     let vocab = llama(&LLAMA_TOKENS, &LLAMA_SCORES);229     assert_eq!(230         vocab.encode("hello world").unwrap(),231         vec![Token(9), Token(10)]232     );233     assert_eq!(vocab.decode(&[Token(9), Token(10)]).unwrap(), "hello world");234 }235 236 #[test]237 fn empty_text_has_no_tokens() {238     let vocab = llama(&LLAMA_TOKENS, &LLAMA_SCORES);239     assert!(vocab.encode("").unwrap().is_empty());240 }241 242 #[test]243 fn a_character_with_no_piece_or_byte_is_an_error() {244     let vocab = llama(&LLAMA_TOKENS, &LLAMA_SCORES);245     // The `▁hello` piece consumes the prefix and the word; `!` has no piece246     // and no byte token.247     assert_eq!(vocab.encode("hello!").unwrap_err(), VocabError::Byte(b'!'));248 }249 250 #[test]251 fn the_better_scored_pair_is_merged_first() {252     let bytes = build(&[253         Entry::Strings("tokenizer.ggml.tokens", vec!["a", "b", "c", "ab", "bc"]),254         Entry::F32s("tokenizer.ggml.scores", vec![0.0, 0.0, 0.0, -1.0, 1.0]),255         Entry::Str("tokenizer.ggml.model", "llama"),256         Entry::Bool("tokenizer.ggml.add_space_prefix", false),257     ]);258     let vocab = vocab(&bytes);259     // `b c` scores above `a b`, so it merges first and `a` stays alone.260     assert_eq!(vocab.encode("abc").unwrap(), vec![Token(0), Token(4)]);261     assert_eq!(vocab.decode(&[Token(0), Token(4)]).unwrap(), "abc");262 }263 264 #[test]265 fn a_llama_vocabulary_can_turn_the_space_prefix_off() {266     let entries = |prefix: bool| {267         let mut entries = vec![268             Entry::Strings("tokenizer.ggml.tokens", vec!["a", "▁a", "▁"]),269             Entry::F32s("tokenizer.ggml.scores", vec![0.0, 0.0, 0.0]),270             Entry::U32s("tokenizer.ggml.token_type", vec![1, 1, 1]),271             Entry::Str("tokenizer.ggml.model", "llama"),272         ];273         entries.push(Entry::Bool("tokenizer.ggml.add_space_prefix", prefix));274         entries275     };276     let with_prefix = vocab(&build(&entries(true)));277     let without_prefix = vocab(&build(&entries(false)));278     assert_eq!(with_prefix.encode("a").unwrap(), vec![Token(1)]);279     assert_eq!(without_prefix.encode("a").unwrap(), vec![Token(0)]);280     assert_eq!(with_prefix.decode(&[Token(1)]).unwrap(), "a");281     assert_eq!(without_prefix.decode(&[Token(0)]).unwrap(), "a");282 }283 284 #[test]285 fn gpt2_spells_space_and_newline_as_unicode_characters() {286     let bytes = build(&[287         Entry::Strings(288             "tokenizer.ggml.tokens",289             vec!["a", "b", "ab", "Ġ", "Ċ", "<|end|>"],290         ),291         Entry::Strings("tokenizer.ggml.merges", vec!["a b"]),292         Entry::U32s("tokenizer.ggml.token_type", vec![1, 1, 1, 1, 1, 3]),293         Entry::Str("tokenizer.ggml.model", "gpt2"),294     ]);295     let vocab = vocab(&bytes);296     assert_eq!(vocab.encode("ab").unwrap(), vec![Token(2)]);297     assert_eq!(vocab.encode(" a").unwrap(), vec![Token(3), Token(0)]);298     assert_eq!(vocab.encode("\n").unwrap(), vec![Token(4)]);299     assert_eq!(vocab.decode(&[Token(3), Token(0)]).unwrap(), " a");300     assert_eq!(vocab.decode(&[Token(4)]).unwrap(), "\n");301 }302 303 #[test]304 fn a_control_token_crosses_every_family_as_one_id() {305     let gpt2 = build(&[306         Entry::Strings(307             "tokenizer.ggml.tokens",308             vec!["a", "<|im_start|>", "<|im_end|>"],309         ),310         Entry::U32s("tokenizer.ggml.token_type", vec![1, 3, 3]),311         Entry::Str("tokenizer.ggml.model", "gpt2"),312     ]);313     let gpt2_vocab = vocab(&gpt2);314     assert_eq!(315         gpt2_vocab.encode("a<|im_start|>a<|im_end|>").unwrap(),316         vec![Token(0), Token(1), Token(0), Token(2)]317     );318     assert_eq!(319         gpt2_vocab.decode(&[Token(1), Token(0), Token(2)]).unwrap(),320         "<|im_start|>a<|im_end|>"321     );322 323     let llama = build(&[324         Entry::Strings(325             "tokenizer.ggml.tokens",326             vec!["<|im_start|>", "a", "<|im_end|>", "▁"],327         ),328         Entry::U32s("tokenizer.ggml.token_type", vec![3, 1, 3, 1]),329         Entry::Str("tokenizer.ggml.model", "llama"),330     ]);331     let llama_vocab = vocab(&llama);332     assert_eq!(333         llama_vocab.encode("<|im_start|>a<|im_end|>").unwrap(),334         vec![Token(0), Token(1), Token(2)]335     );336     assert_eq!(337         llama_vocab.decode(&[Token(0), Token(1), Token(2)]).unwrap(),338         "<|im_start|>a<|im_end|>"339     );340     assert_eq!(341         llama_vocab.encode("<|im_start|> a").unwrap(),342         vec![Token(0), Token(3), Token(1)]343     );344     assert_eq!(345         llama_vocab.decode(&[Token(0), Token(3), Token(1)]).unwrap(),346         "<|im_start|> a"347     );348 }