crates/format/vocab/src/lib.rs 39.6 KiB 1136 lines Raw
1 //! inf3r-vocab — the tokenizer that a GGUF declares.2 //!3 //! A GGUF holds the weights index and the metadata, but the index alone cannot4 //! turn a prompt into tokens. The token strings, the merge ranks, the token5 //! kinds, and the chat template live in the metadata table, so this crate reads6 //! them there. A runtime that links no model format keeps out of the way: it7 //! links this crate and gets one vocabulary shape.8 //!9 //! Two families have two layouts. A GPT-2 file maps bytes to tokens and then10 //! merges them by rank. A Llama file holds SentencePiece pieces, where a space11 //! is the metaspace symbol and no merge list exists. The family word in the12 //! metadata chooses the path; guessing from the pieces would encode a prompt13 //! with the wrong rules.14 //!15 //! The reader does not trust a claimed count. Every vector is sized from the16 //! values that were actually read, not from a length in the file.17 18 use std::cmp::{Ordering, Reverse};19 use std::collections::{BinaryHeap, HashMap};20 use std::fmt;21 22 use inf3r_gguf::{Gguf, Value};23 use inf3r_text::token::{Token, TokenStream};24 25 /// The metadata key that holds the token strings. A file without it has no26 /// vocabulary, so no prompt can become tokens.27 const TOKENS_KEY: &str = "tokenizer.ggml.tokens";28 29 /// The metadata key that holds the BPE merges. A model with no BPE omits it,30 /// and a missing key is not an error.31 const MERGES_KEY: &str = "tokenizer.ggml.merges";32 33 /// The metadata key that holds one kind number per token. An absent key means34 /// every token is [`TokenKind::Normal`].35 const KINDS_KEY: &str = "tokenizer.ggml.token_type";36 37 /// The metadata key that names the tokenizer family. The family decides which38 /// vocabulary layout the token strings follow.39 const MODEL_KEY: &str = "tokenizer.ggml.model";40 41 /// The metadata key that holds one score per token. SentencePiece needs the42 /// score to break a tie between pieces, and a missing key means every score is43 /// zero.44 const SCORES_KEY: &str = "tokenizer.ggml.scores";45 46 /// The metadata key that holds the chat template. A model without one falls47 /// back to the layout in `inf3r-text`.48 const TEMPLATE_KEY: &str = "tokenizer.chat_template";49 50 /// The metadata key that says whether SentencePiece adds its dummy metaspace51 /// before the first ordinary piece. The default is true, which is the layout52 /// that the first SentencePiece models used.53 const ADD_SPACE_PREFIX_KEY: &str = "tokenizer.ggml.add_space_prefix";54 55 /// The GPT-2 family word, which this crate implements.56 const MODEL_GPT2: &str = "gpt2";57 58 /// The LLaMA family word, which this crate implements.59 const MODEL_LLAMA: &str = "llama";60 61 /// The prefix of a byte token. LLaMA spells byte `0xAB` as `<0xAB>`.62 const BYTE_PREFIX: &str = "<0x";63 64 /// The suffix of a byte token.65 const BYTE_SUFFIX: char = '>';66 67 /// One byte in hex uses two digits.68 const BYTE_DIGITS: usize = 2;69 70 /// The radix of a hex digit.71 const HEX_RADIX: u32 = 16;72 73 /// The SentencePiece metaspace in UTF-8. A piece spells a space with it, so74 /// the encoder and the decoder must use the same three bytes.75 const METASPACE: &[u8] = b"\xE2\x96\x81";76 77 /// The byte that a metaspace stands for.78 const SPACE: u8 = b' ';79 80 /// One BPE merge: the two pieces that join, in rank order.81 ///82 /// The pair is a type of its own because clippy counts the inline form as too83 /// complex to read in the struct and in the reader.84 type Merge = (Vec<u8>, Vec<u8>);85 86 /// The layout of the token strings in a file.87 #[derive(Clone, Copy, PartialEq, Eq, Debug)]88 enum Family {89     /// GPT-2 byte tokens plus a merge list.90     Gpt2,91     /// SentencePiece pieces, with no merge list.92     Llama,93 }94 95 /// The kind that GGUF assigns to one token.96 #[derive(Clone, Copy, PartialEq, Eq, Debug)]97 pub enum TokenKind {98     /// An ordinary token that the merges may produce.99     Normal,100     /// A token that stands for text the vocabulary does not know.101     Unknown,102     /// A token that carries control text and is not part of the reply.103     Control,104     /// A token that a user added to the vocabulary.105     UserDefined,106     /// A token that the vocabulary reserves and no text maps to.107     Unused,108     /// A token that holds one raw byte, spelled `<0xYY>` by LLaMA.109     Byte,110 }111 112 /// The reason a vocabulary operation failed.113 #[derive(Clone, PartialEq, Eq, Debug)]114 pub enum VocabError {115     /// The metadata table lacks a key that the vocabulary needs.116     Missing(&'static str),117     /// A family word, a token kind, or a count that the vocabulary cannot use.118     Kind(String),119     /// No token holds this byte, so the text has no encoding.120     Byte(u8),121     /// A token id is past the end of the table.122     Id(u32),123     /// Token bytes end in a fragment that is not a whole character.124     Piece(String),125 }126 127 impl fmt::Display for VocabError {128     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {129         match self {130             VocabError::Missing(key) => write!(f, "the GGUF has no {key}"),131             VocabError::Kind(why) => write!(f, "{why}"),132             VocabError::Byte(b) => write!(f, "no token holds byte {b:#04x}"),133             VocabError::Id(n) => write!(f, "token id {n} is past the table"),134             VocabError::Piece(text) => write!(f, "the tokens end in the fragment {text:?}"),135         }136     }137 }138 139 impl std::error::Error for VocabError {}140 141 /// The vocabulary of one model file.142 #[derive(Clone, Debug)]143 pub struct Vocab {144     /// The bytes of each token, indexed by token id.145     tokens: Vec<Vec<u8>>,146     /// The kind of each token, the same length as `tokens`.147     kinds: Vec<TokenKind>,148     /// The layout that the model's family word chooses.149     family: Family,150     /// The chat template that the model declares, when it declares one.151     template: Option<String>,152     /// The token id that holds each byte, when the family can spell one.153     byte_tokens: [Option<u32>; 256],154     /// The GPT-2 merge ranks. A key is a pair of token ids; the value is the155     /// rank and the id of the piece that the pair becomes.156     merge_ranks: HashMap<(u32, u32), (usize, u32)>,157     /// The SentencePiece pieces and their scores, keyed by the bytes of the158     /// piece. A special token is not a merge candidate.159     llama_pieces: HashMap<Vec<u8>, (u32, f32)>,160     /// The control and user-defined tokens, longest first, so a prompt can161     /// name one without splitting it into bytes.162     specials: Vec<(Vec<u8>, u32)>,163     /// Whether SentencePiece adds a dummy metaspace before the first piece.164     add_space_prefix: bool,165 }166 167 impl Vocab {168     /// Reads the vocabulary from a parsed GGUF.169     pub fn from_gguf(g: &Gguf) -> Result<Vocab, VocabError> {170         let tokens = read_tokens(g)?;171         let merges = read_merges(g)?;172         let kinds = read_kinds(g, tokens.len())?;173         let scores = read_scores(g, tokens.len())?;174         let family = read_family(g)?;175         let template = g176             .meta177             .get(TEMPLATE_KEY)178             .and_then(Value::as_str)179             .map(str::to_string);180         let by_piece = by_piece(&tokens);181         let byte_tokens = byte_tokens(family, &tokens, &by_piece);182         let merge_ranks = if family == Family::Gpt2 {183             merge_ranks(&merges, &by_piece)184         } else {185             HashMap::new()186         };187         let llama_pieces = if family == Family::Llama {188             llama_pieces(&tokens, &kinds, &scores)189         } else {190             HashMap::new()191         };192         let specials = special_tokens(&tokens, &kinds);193         let add_space_prefix = if family == Family::Llama {194             read_add_space_prefix(g)?195         } else {196             true197         };198         Ok(Vocab {199             tokens,200             kinds,201             family,202             template,203             byte_tokens,204             merge_ranks,205             llama_pieces,206             specials,207             add_space_prefix,208         })209     }210 211     /// The number of tokens. A caller uses it to check an output id.212     pub fn len(&self) -> usize {213         self.tokens.len()214     }215 216     /// True when the model file declared no tokens.217     pub fn is_empty(&self) -> bool {218         self.tokens.is_empty()219     }220 221     /// The chat template that the model declares, when it declares one.222     pub fn template(&self) -> Option<&str> {223         self.template.as_deref()224     }225 226     /// Turns text into tokens.227     ///228     /// The family word decides the path. A GPT-2 file maps each byte and then229     /// merges; a Llama file matches SentencePiece pieces. A caller cannot mix230     /// the two, because a prompt encoded by the wrong rules does not decode231     /// back to the prompt.232     pub fn encode(&self, text: &str) -> Result<Vec<Token>, VocabError> {233         match self.family {234             Family::Gpt2 => self.encode_gpt2(text),235             Family::Llama => {236                 if text.is_empty() {237                     return Ok(Vec::new());238                 }239                 self.encode_llama(text)240             }241         }242     }243 244     /// The byte-BPE path: each byte to its token, then merges by rank.245     ///246     /// A control or user-defined token is matched before the text is split.247     /// The ordinary text between those tokens is pre-tokenized into the chunks248     /// that GPT-2 trains on, and each chunk is merged on its own.249     fn encode_gpt2(&self, text: &str) -> Result<Vec<Token>, VocabError> {250         let mut ids = Vec::new();251         let mut plain = 0;252         let mut at = 0;253         while at < text.len() {254             if let Some((id, len)) = self.special_at(text, at) {255                 self.encode_gpt2_plain(&text[plain..at], &mut ids)?;256                 ids.push(id);257                 at += len;258                 plain = at;259             } else if let Some(ch) = text[at..].chars().next() {260                 at += ch.len_utf8();261             } else {262                 break;263             }264         }265         self.encode_gpt2_plain(&text[plain..], &mut ids)?;266         Ok(ids.into_iter().map(Token).collect())267     }268 269     /// One ordinary GPT-2 chunk: bytes to ids, then the lowest-rank merge.270     fn encode_gpt2_plain(&self, text: &str, ids: &mut Vec<u32>) -> Result<(), VocabError> {271         for part in gpt2_parts(text) {272             let mut part_ids = Vec::with_capacity(part.len());273             for byte in part.as_bytes() {274                 let id = self.byte_tokens[usize::from(*byte)].ok_or(VocabError::Byte(*byte))?;275                 part_ids.push(id);276             }277             ids.extend(bpe(&part_ids, &self.merge_ranks));278         }279         Ok(())280     }281 282     /// The SentencePiece path: each character to a piece, then the pair with283     /// the best score is merged until no pair forms a piece.284     ///285     /// The pair score is the score of the piece that the pair becomes, which is286     /// how SentencePiece BPE orders its merges. A byte fallback symbol never287     /// takes part in a merge. A control or user-defined token is matched before288     /// the metaspace normalisation.289     fn encode_llama(&self, text: &str) -> Result<Vec<Token>, VocabError> {290         let mut ids = Vec::new();291         let mut plain = 0;292         let mut at = 0;293         while at < text.len() {294             if let Some((id, len)) = self.special_at(text, at) {295                 self.encode_llama_plain(&text[plain..at], plain == 0, &mut ids)?;296                 ids.push(id);297                 at += len;298                 plain = at;299             } else if let Some(ch) = text[at..].chars().next() {300                 at += ch.len_utf8();301             } else {302                 break;303             }304         }305         self.encode_llama_plain(&text[plain..], plain == 0, &mut ids)?;306         Ok(ids.into_iter().map(Token).collect())307     }308 309     /// One ordinary SentencePiece chunk between special tokens.310     fn encode_llama_plain(311         &self,312         text: &str,313         prefix: bool,314         ids: &mut Vec<u32>,315     ) -> Result<(), VocabError> {316         if text.is_empty() {317             return Ok(());318         }319         let input = normalize(text, prefix && self.add_space_prefix);320         match self.llama_bpe(&input) {321             Ok(pieces) => ids.extend(pieces),322             // A vocabulary that lacks a character and its bytes cannot BPE the323             // chunk. Fall back to the piece table, which is the only path that324             // an incomplete file gives us. A complete file never takes it.325             Err(VocabError::Byte(_)) => ids.extend(self.llama_fallback(&input)?),326             Err(why) => return Err(why),327         }328         Ok(())329     }330 331     /// The SentencePiece BPE path over bytes that are already normalized.332     fn llama_bpe(&self, input: &[u8]) -> Result<Vec<u32>, VocabError> {333         let input_text = std::str::from_utf8(input)334             .map_err(|_| VocabError::Piece(String::from_utf8_lossy(input).into_owned()))?;335         let mut symbols = Vec::new();336         for (at, ch) in input_text.char_indices() {337             let end = at + ch.len_utf8();338             let piece = &input[at..end];339             if let Some(&(id, _)) = self.llama_pieces.get(piece) {340                 symbols.push(Symbol {341                     text: piece.to_vec(),342                     id,343                     byte: false,344                 });345             } else {346                 for byte in piece {347                     let id = self.byte_tokens[usize::from(*byte)].ok_or(VocabError::Byte(*byte))?;348                     symbols.push(Symbol {349                         text: vec![*byte],350                         id,351                         byte: true,352                     });353                 }354             }355         }356         Ok(llama_merge(&mut symbols, &self.llama_pieces))357     }358 359     /// The piece-table fallback for a file that lacks a character. It is the360     /// old greedy path, used only after BPE cannot even seed its symbols.361     fn llama_fallback(&self, input: &[u8]) -> Result<Vec<u32>, VocabError> {362         let mut ids = Vec::new();363         let mut at = 0;364         while at < input.len() {365             if let Some((id, len)) = self.best_piece(&input[at..]) {366                 ids.push(id);367                 at += len;368                 continue;369             }370             let byte = input[at];371             let id = self.byte_tokens[usize::from(byte)].ok_or(VocabError::Byte(byte))?;372             ids.push(id);373             at += 1;374         }375         Ok(ids)376     }377 378     /// The best piece that starts at the front of `input`, with its length.379     /// This is only the fallback for an incomplete file.380     fn best_piece(&self, input: &[u8]) -> Option<(u32, usize)> {381         let mut best: Option<(u32, usize, f32)> = None;382         for (piece, &(id, score)) in &self.llama_pieces {383             if piece.is_empty() || !input.starts_with(piece) {384                 continue;385             }386             let better = match best {387                 None => true,388                 Some((best_id, best_len, best_score)) => match score.total_cmp(&best_score) {389                     Ordering::Greater => true,390                     Ordering::Less => false,391                     Ordering::Equal => {392                         piece.len() > best_len || (piece.len() == best_len && id < best_id)393                     }394                 },395             };396             if better {397                 best = Some((id, piece.len(), score));398             }399         }400         best.map(|(id, len, _)| (id, len))401     }402 403     /// The longest control or user-defined token at `at`, and its byte length.404     fn special_at(&self, text: &str, at: usize) -> Option<(u32, usize)> {405         let rest = text.as_bytes().get(at..)?;406         self.specials407             .iter()408             .find(|(piece, _)| rest.starts_with(piece))409             .map(|(piece, id)| (*id, piece.len()))410     }411 412     /// Turns tokens back into text.413     ///414     /// The bytes go through [`TokenStream`] because a token boundary can fall415     /// inside a character. The stream reports a fragment that never became one.416     pub fn decode(&self, tokens: &[Token]) -> Result<String, VocabError> {417         let mut stream = TokenStream::new();418         let mut out = String::new();419         let mut strip_prefix = self.family == Family::Llama && self.add_space_prefix;420         for (position, token) in tokens.iter().enumerate() {421             let id = token.0;422             let index = usize::try_from(id).map_err(|_| VocabError::Id(id))?;423             let piece = self.tokens.get(index).ok_or(VocabError::Id(id))?;424             let kind = self.kinds.get(index).copied().ok_or(VocabError::Id(id))?;425             if position == 0426                 && matches!(427                     kind,428                     TokenKind::Control | TokenKind::UserDefined | TokenKind::Unknown429                 )430             {431                 // The encoder does not add its dummy space before a special432                 // token, so the decoder must not remove one after it.433                 strip_prefix = false;434             }435 436             let bytes = match self.family {437                 Family::Gpt2 => match kind {438                     TokenKind::Control | TokenKind::UserDefined | TokenKind::Unknown => {439                         piece.clone()440                     }441                     TokenKind::Byte => match parse_byte_token(piece) {442                         Some(byte) => vec![byte],443                         // Some families spell a byte token with its raw byte, so444                         // the piece itself is the byte.445                         None => piece.clone(),446                     },447                     _ => gpt2_bytes(piece)?,448                 },449                 Family::Llama => match kind {450                     TokenKind::Control | TokenKind::UserDefined | TokenKind::Unknown => {451                         piece.clone()452                     }453                     _ => match parse_byte_token(piece) {454                         Some(byte) => vec![byte],455                         None => spaces(piece),456                     },457                 },458             };459             out.push_str(&stream.push(&bytes));460         }461 462         stream.finish().map_err(|incomplete| {463             VocabError::Piece(String::from_utf8_lossy(&incomplete.bytes).into_owned())464         })?;465         // The encoder adds a leading metaspace as the dummy prefix. Decoding466         // removes that one space, so `hello` and ` hello` stay apart.467         if strip_prefix && let Some(rest) = out.strip_prefix(' ') {468             out = rest.to_string();469         }470         Ok(out)471     }472 }473 474 /// The SentencePiece input: an optional dummy prefix, then every space as475 /// metaspace.476 ///477 /// The prefix says that the model expects a space before the first ordinary478 /// piece. A space that the caller wrote at the start stays as its own479 /// metaspace, so the decoder can remove only the prefix again.480 fn normalize(text: &str, prefix: bool) -> Vec<u8> {481     let mut out = Vec::with_capacity(text.len() + METASPACE.len());482     if prefix {483         out.extend_from_slice(METASPACE);484     }485     for byte in text.bytes() {486         if byte == SPACE {487             out.extend_from_slice(METASPACE);488         } else {489             out.push(byte);490         }491     }492     out493 }494 495 /// The payload of a Llama token, with every metaspace back to a space.496 fn spaces(piece: &[u8]) -> Vec<u8> {497     let mut out = Vec::with_capacity(piece.len());498     let mut at = 0;499     while at < piece.len() {500         if piece[at..].starts_with(METASPACE) {501             out.push(SPACE);502             at += METASPACE.len();503         } else {504             out.push(piece[at]);505             at += 1;506         }507     }508     out509 }510 511 /// The byte that a `<0xYY>` token spells, or `None` for any other piece.512 fn parse_byte_token(piece: &[u8]) -> Option<u8> {513     let text = std::str::from_utf8(piece).ok()?;514     let hex = text.strip_prefix(BYTE_PREFIX)?.strip_suffix(BYTE_SUFFIX)?;515     if hex.len() != BYTE_DIGITS {516         return None;517     }518     u8::from_str_radix(hex, HEX_RADIX).ok()519 }520 521 /// One symbol while a SentencePiece merge is in progress.522 #[derive(Clone, Debug)]523 struct Symbol {524     /// The bytes that the symbol covers.525     text: Vec<u8>,526     /// The token id that the symbol already has.527     id: u32,528     /// True when the symbol is a byte fallback and must not merge.529     byte: bool,530 }531 532 /// One possible SentencePiece merge. The heap orders the merged piece's score.533 #[derive(Clone, Copy, Debug)]534 struct Candidate {535     /// The score of the piece that the pair would become.536     score: f32,537     /// The left symbol.538     left: usize,539     /// The right symbol.540     right: usize,541     /// The id and length that the left symbol had when the pair was queued.542     left_id: u32,543     left_len: usize,544     /// The id and length that the right symbol had when the pair was queued.545     right_id: u32,546     right_len: usize,547     /// The token id that the joined text would have.548     merged: u32,549 }550 551 impl PartialEq for Candidate {552     fn eq(&self, other: &Candidate) -> bool {553         self.cmp(other) == Ordering::Equal554     }555 }556 557 impl Eq for Candidate {}558 559 impl PartialOrd for Candidate {560     fn partial_cmp(&self, other: &Candidate) -> Option<Ordering> {561         Some(self.cmp(other))562     }563 }564 565 impl Ord for Candidate {566     fn cmp(&self, other: &Candidate) -> Ordering {567         // A higher score wins. On a tie the lower merged id wins, and then the568         // earlier pair, so a heap with equal scores still has one order.569         self.score570             .total_cmp(&other.score)571             .then_with(|| other.merged.cmp(&self.merged))572             .then_with(|| other.left.cmp(&self.left))573     }574 }575 576 /// A map from a token's bytes to its id. A merge produces a piece, and the map577 /// turns that piece back into the token that holds it.578 fn by_piece(tokens: &[Vec<u8>]) -> HashMap<Vec<u8>, u32> {579     let mut map = HashMap::with_capacity(tokens.len());580     for (index, piece) in tokens.iter().enumerate() {581         let Ok(id) = u32::try_from(index) else {582             continue;583         };584         map.insert(piece.clone(), id);585     }586     map587 }588 589 /// The token id for each byte.590 ///591 /// GPT-2 spells a byte as a Unicode character, because the merge list is a list592 /// of strings. The spelling is tried first, then a raw one-byte piece, then a593 /// `<0xYY>` byte token. Llama tries `<0xYY>` first and then a raw byte.594 fn byte_tokens(595     family: Family,596     tokens: &[Vec<u8>],597     by_piece: &HashMap<Vec<u8>, u32>,598 ) -> [Option<u32>; 256] {599     let mut out = [None; 256];600     if family == Family::Gpt2 {601         for byte in 0..=u8::MAX {602             let mut buf = [0u8; 4];603             let text = gpt2_byte_char(byte).encode_utf8(&mut buf);604             if let Some(&id) = by_piece.get(text.as_bytes()) {605                 out[usize::from(byte)] = Some(id);606             }607         }608     }609     for (index, piece) in tokens.iter().enumerate() {610         let Ok(id) = u32::try_from(index) else {611             continue;612         };613         if family == Family::Llama614             && let Some(byte) = parse_byte_token(piece)615         {616             out[usize::from(byte)] = Some(id);617         }618     }619     for (index, piece) in tokens.iter().enumerate() {620         let Ok(id) = u32::try_from(index) else {621             continue;622         };623         if let [byte] = piece.as_slice()624             && out[usize::from(*byte)].is_none()625         {626             out[usize::from(*byte)] = Some(id);627         }628     }629     if family == Family::Gpt2 {630         for (index, piece) in tokens.iter().enumerate() {631             let Ok(id) = u32::try_from(index) else {632                 continue;633             };634             if let Some(byte) = parse_byte_token(piece)635                 && out[usize::from(byte)].is_none()636             {637                 out[usize::from(byte)] = Some(id);638             }639         }640     }641     out642 }643 644 /// The GPT-2 merge table, keyed by the two token ids that the merge joins.645 fn merge_ranks(646     merges: &[Merge],647     by_piece: &HashMap<Vec<u8>, u32>,648 ) -> HashMap<(u32, u32), (usize, u32)> {649     let mut out = HashMap::with_capacity(merges.len());650     for (rank, (left, right)) in merges.iter().enumerate() {651         let Some(&left_id) = by_piece.get(left) else {652             continue;653         };654         let Some(&right_id) = by_piece.get(right) else {655             continue;656         };657         let mut merged = Vec::with_capacity(left.len() + right.len());658         merged.extend_from_slice(left);659         merged.extend_from_slice(right);660         let Some(&merged_id) = by_piece.get(&merged) else {661             continue;662         };663         out.entry((left_id, right_id)).or_insert((rank, merged_id));664     }665     out666 }667 668 /// The SentencePiece pieces that a merge may produce. A control, user-defined,669 /// unused, or byte token is not a merge candidate.670 fn llama_pieces(671     tokens: &[Vec<u8>],672     kinds: &[TokenKind],673     scores: &[f32],674 ) -> HashMap<Vec<u8>, (u32, f32)> {675     let mut out = HashMap::with_capacity(tokens.len());676     for (index, (piece, kind)) in tokens.iter().zip(kinds).enumerate() {677         if *kind != TokenKind::Normal {678             continue;679         }680         let Ok(id) = u32::try_from(index) else {681             continue;682         };683         out.insert(684             piece.clone(),685             (id, scores.get(index).copied().unwrap_or(0.0)),686         );687     }688     out689 }690 691 /// Every control and user-defined token, longest first.692 fn special_tokens(tokens: &[Vec<u8>], kinds: &[TokenKind]) -> Vec<(Vec<u8>, u32)> {693     let mut out = Vec::new();694     for (index, (piece, kind)) in tokens.iter().zip(kinds).enumerate() {695         if piece.is_empty() || !matches!(kind, TokenKind::Control | TokenKind::UserDefined) {696             continue;697         }698         let Ok(id) = u32::try_from(index) else {699             continue;700         };701         out.push((piece.clone(), id));702     }703     out.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then_with(|| a.1.cmp(&b.1)));704     out705 }706 707 /// The GPT-2 byte-to-character spelling. The printable bytes stand for708 /// themselves and every other byte takes the next code point above U+00FF.709 /// The mapping is a bijection, so decoding is exact.710 fn gpt2_byte_char(byte: u8) -> char {711     let printable =712         (33..=126).contains(&byte) || (161..=172).contains(&byte) || (174..=255).contains(&byte);713     if printable {714         return char::from(byte);715     }716     let missing = if byte <= 32 {717         u32::from(byte)718     } else if (127..=160).contains(&byte) {719         33 + u32::from(byte - 127)720     } else {721         // Byte 173 is the only gap between the second and third ranges.722         67723     };724     char::from_u32(256 + missing).unwrap_or('\u{FFFD}')725 }726 727 /// The byte that a GPT-2 spelling stands for.728 fn gpt2_char_byte(ch: char) -> Option<u8> {729     let n = u32::from(ch);730     if (33..=126).contains(&n) || (161..=172).contains(&n) || (174..=255).contains(&n) {731         return u8::try_from(n).ok();732     }733     let offset = n.checked_sub(256)?;734     match offset {735         0..=32 => u8::try_from(offset).ok(),736         33..=66 => u8::try_from(127 + (offset - 33)).ok(),737         67 => Some(173),738         _ => None,739     }740 }741 742 /// The bytes of a normal GPT-2 piece, one byte for each spelling character.743 fn gpt2_bytes(piece: &[u8]) -> Result<Vec<u8>, VocabError> {744     let text = std::str::from_utf8(piece)745         .map_err(|_| VocabError::Piece(String::from_utf8_lossy(piece).into_owned()))?;746     let mut out = Vec::with_capacity(text.len());747     for ch in text.chars() {748         match gpt2_char_byte(ch) {749             Some(byte) => out.push(byte),750             None => {751                 let mut buf = [0u8; 4];752                 out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());753             }754         }755     }756     Ok(out)757 }758 759 /// The chunks that GPT-2 merges on its own. A word, a number, and a run of760 /// punctuation are separate; a single space belongs to the piece after it.761 fn gpt2_parts(text: &str) -> Vec<&str> {762     let mut out = Vec::new();763     let mut at = 0;764     while at < text.len() {765         let rest = &text[at..];766         let Some(first) = rest.chars().next() else {767             break;768         };769         if first == '\''770             && let Some(suffix) = ["'s", "'t", "'re", "'ve", "'m", "'ll", "'d"]771                 .into_iter()772                 .find(|suffix| rest.starts_with(suffix))773         {774             out.push(&rest[..suffix.len()]);775             at += suffix.len();776             continue;777         }778         if first.is_whitespace() {779             let end = rest780                 .char_indices()781                 .find(|(_, ch)| !ch.is_whitespace())782                 .map_or(rest.len(), |(index, _)| index);783             if end == rest.len() {784                 out.push(rest);785                 break;786             }787             let run = &rest[..end];788             let last = run.char_indices().next_back().map_or(0, |(index, _)| index);789             if last > 0 && run[last..].starts_with(' ') {790                 out.push(&run[..last]);791                 at += last;792                 continue;793             }794             if last > 0 || !run.starts_with(' ') {795                 out.push(run);796                 at += end;797                 continue;798             }799             // One literal space before a word: it belongs to the next piece.800         }801         let mut offset = 0;802         let mut start = first;803         if first == ' '804             && let Some(next) = rest[1..].chars().next()805             && !next.is_whitespace()806         {807             offset = 1;808             start = next;809         }810         if start.is_alphabetic() || start.is_numeric() {811             let mut end = offset;812             for (index, ch) in rest[offset..].char_indices() {813                 if ch.is_alphabetic() == start.is_alphabetic()814                     && ch.is_numeric() == start.is_numeric()815                 {816                     end = offset + index + ch.len_utf8();817                 } else {818                     break;819                 }820             }821             out.push(&rest[..end]);822             at += end;823             continue;824         }825         if !start.is_whitespace() {826             let mut end = offset;827             for (index, ch) in rest[offset..].char_indices() {828                 if !ch.is_whitespace() && !ch.is_alphabetic() && !ch.is_numeric() {829                     end = offset + index + ch.len_utf8();830                 } else {831                     break;832                 }833             }834             out.push(&rest[..end]);835             at += end;836             continue;837         }838         out.push(&rest[..first.len_utf8()]);839         at += first.len_utf8();840     }841     out842 }843 844 /// GPT-2 BPE: repeatedly merge the adjacent pair with the lowest rank.845 ///846 /// The heap holds one entry for each adjacent pair that a merge can join. A847 /// linked list makes one merge O(1), so a prompt costs O(tokens log tokens)848 /// rather than one full pass for every merge in the file.849 fn bpe(ids: &[u32], ranks: &HashMap<(u32, u32), (usize, u32)>) -> Vec<u32> {850     if ids.len() < 2 {851         return ids.to_vec();852     }853     let mut ids = ids.to_vec();854     let length = ids.len();855     let mut alive = vec![true; length];856     let mut next: Vec<Option<usize>> = (1..=length)857         .map(|index| (index < length).then_some(index))858         .collect();859     let mut prev: Vec<Option<usize>> = (0..length).map(|index| index.checked_sub(1)).collect();860     let mut heap = BinaryHeap::new();861     for left in 0..length - 1 {862         if let Some(&(rank, _)) = ranks.get(&(ids[left], ids[left + 1])) {863             heap.push(Reverse((rank, left)));864         }865     }866     while let Some(Reverse((entry_rank, left))) = heap.pop() {867         let Some(right) = next[left] else {868             continue;869         };870         if !alive[left] || !alive[right] {871             continue;872         }873         let Some(&(rank, merged)) = ranks.get(&(ids[left], ids[right])) else {874             continue;875         };876         if rank != entry_rank {877             continue;878         }879         ids[left] = merged;880         alive[right] = false;881         let after = next[right];882         next[left] = after;883         if let Some(after) = after {884             prev[after] = Some(left);885         }886         if let Some(before) = prev[left]887             && let Some(&(rank, _)) = ranks.get(&(ids[before], ids[left]))888         {889             heap.push(Reverse((rank, before)));890         }891         if let Some(after) = after892             && let Some(&(rank, _)) = ranks.get(&(ids[left], ids[after]))893         {894             heap.push(Reverse((rank, left)));895         }896     }897     ids.into_iter()898         .zip(alive)899         .filter_map(|(id, alive)| alive.then_some(id))900         .collect()901 }902 903 /// SentencePiece BPE: merge the neighbouring pair whose joined piece has the904 /// best score, until no pair forms a piece.905 fn llama_merge(symbols: &mut [Symbol], pieces: &HashMap<Vec<u8>, (u32, f32)>) -> Vec<u32> {906     let length = symbols.len();907     if length == 0 {908         return Vec::new();909     }910     let mut alive = vec![true; length];911     let mut next: Vec<Option<usize>> = (1..=length)912         .map(|index| (index < length).then_some(index))913         .collect();914     let mut prev: Vec<Option<usize>> = (0..length).map(|index| index.checked_sub(1)).collect();915     let mut heap = BinaryHeap::new();916     for left in 0..length - 1 {917         push_llama_candidate(&mut heap, symbols, pieces, left, left + 1);918     }919     while let Some(candidate) = heap.pop() {920         let left = candidate.left;921         let right = candidate.right;922         if !alive[left] || !alive[right] || next[left] != Some(right) {923             continue;924         }925         if symbols[left].byte || symbols[right].byte {926             continue;927         }928         if symbols[left].id != candidate.left_id929             || symbols[left].text.len() != candidate.left_len930             || symbols[right].id != candidate.right_id931             || symbols[right].text.len() != candidate.right_len932         {933             continue;934         }935         let mut joined = Vec::with_capacity(symbols[left].text.len() + symbols[right].text.len());936         joined.extend_from_slice(&symbols[left].text);937         joined.extend_from_slice(&symbols[right].text);938         let Some(&(merged, _)) = pieces.get(&joined) else {939             continue;940         };941         let right_text = std::mem::take(&mut symbols[right].text);942         symbols[left].text.extend_from_slice(&right_text);943         symbols[left].id = merged;944         symbols[left].byte = false;945         alive[right] = false;946         let after = next[right];947         next[left] = after;948         if let Some(after) = after {949             prev[after] = Some(left);950         }951         if let Some(before) = prev[left] {952             push_llama_candidate(&mut heap, symbols, pieces, before, left);953         }954         if let Some(after) = after {955             push_llama_candidate(&mut heap, symbols, pieces, left, after);956         }957     }958     let mut out = Vec::new();959     let mut at = Some(0);960     while let Some(index) = at {961         if alive[index] {962             out.push(symbols[index].id);963         }964         at = next[index];965     }966     out967 }968 969 /// Queue the merge of two adjacent SentencePiece symbols, when their joined970 /// bytes are a piece that may take part in a merge.971 fn push_llama_candidate(972     heap: &mut BinaryHeap<Candidate>,973     symbols: &[Symbol],974     pieces: &HashMap<Vec<u8>, (u32, f32)>,975     left: usize,976     right: usize,977 ) {978     if symbols[left].byte || symbols[right].byte {979         return;980     }981     let mut joined = Vec::with_capacity(symbols[left].text.len() + symbols[right].text.len());982     joined.extend_from_slice(&symbols[left].text);983     joined.extend_from_slice(&symbols[right].text);984     let Some(&(merged, score)) = pieces.get(&joined) else {985         return;986     };987     heap.push(Candidate {988         score,989         left,990         right,991         left_id: symbols[left].id,992         left_len: symbols[left].text.len(),993         right_id: symbols[right].id,994         right_len: symbols[right].text.len(),995         merged,996     });997 }998 999 /// The token strings, which every vocabulary needs.1000 fn read_tokens(g: &Gguf) -> Result<Vec<Vec<u8>>, VocabError> {1001     let value = g1002         .meta1003         .get(TOKENS_KEY)1004         .ok_or(VocabError::Missing(TOKENS_KEY))?;1005     let items = value1006         .as_array()1007         .ok_or_else(|| VocabError::Kind(format!("{TOKENS_KEY} is not an array of strings")))?;1008     let mut tokens = Vec::with_capacity(items.len());1009     for item in items {1010         let text = item1011             .as_str()1012             .ok_or_else(|| VocabError::Kind(format!("{TOKENS_KEY} is not an array of strings")))?;1013         tokens.push(text.as_bytes().to_vec());1014     }1015     Ok(tokens)1016 }1017 1018 /// The merge ranks, or an empty list when the model has no BPE.1019 fn read_merges(g: &Gguf) -> Result<Vec<Merge>, VocabError> {1020     let Some(value) = g.meta.get(MERGES_KEY) else {1021         return Ok(Vec::new());1022     };1023     let items = value1024         .as_array()1025         .ok_or_else(|| VocabError::Kind(format!("{MERGES_KEY} is not an array of strings")))?;1026     let mut merges = Vec::with_capacity(items.len());1027     for item in items {1028         let text = item1029             .as_str()1030             .ok_or_else(|| VocabError::Kind(format!("{MERGES_KEY} is not an array of strings")))?;1031         let (left, right) = text1032             .split_once(' ')1033             .ok_or_else(|| VocabError::Kind(format!("merge {text:?} is not two pieces")))?;1034         if left.is_empty() || right.is_empty() {1035             return Err(VocabError::Kind(format!(1036                 "merge {text:?} is not two pieces"1037             )));1038         }1039         merges.push((left.as_bytes().to_vec(), right.as_bytes().to_vec()));1040     }1041     Ok(merges)1042 }1043 1044 /// One kind per token, or `Normal` for every token when the key is absent.1045 fn read_kinds(g: &Gguf, tokens: usize) -> Result<Vec<TokenKind>, VocabError> {1046     let Some(value) = g.meta.get(KINDS_KEY) else {1047         return Ok(vec![TokenKind::Normal; tokens]);1048     };1049     let items = value1050         .as_array()1051         .ok_or_else(|| VocabError::Kind(format!("{KINDS_KEY} is not an array of u32")))?;1052     // The count is checked against the tokens that were read, not against a1053     // length in the file.1054     if items.len() != tokens {1055         return Err(VocabError::Kind(format!(1056             "{KINDS_KEY} has {} kinds for {tokens} tokens",1057             items.len()1058         )));1059     }1060     let mut kinds = Vec::with_capacity(items.len());1061     for item in items {1062         let kind = item1063             .as_u64()1064             .ok_or_else(|| VocabError::Kind(format!("{KINDS_KEY} is not an array of u32")))?;1065         kinds.push(token_kind(kind)?);1066     }1067     Ok(kinds)1068 }1069 1070 /// One score per token, or an empty list when the key is absent. A count that1071 /// does not match the tokens is a broken file, not a guess.1072 fn read_scores(g: &Gguf, tokens: usize) -> Result<Vec<f32>, VocabError> {1073     let Some(value) = g.meta.get(SCORES_KEY) else {1074         return Ok(Vec::new());1075     };1076     let items = value1077         .as_array()1078         .ok_or_else(|| VocabError::Kind(format!("{SCORES_KEY} is not an array of f32")))?;1079     if items.len() != tokens {1080         return Err(VocabError::Kind(format!(1081             "{SCORES_KEY} has {} scores for {tokens} tokens",1082             items.len()1083         )));1084     }1085     let mut scores = Vec::with_capacity(items.len());1086     for item in items {1087         match item {1088             Value::F32(score) => scores.push(*score),1089             _ => {1090                 return Err(VocabError::Kind(format!(1091                     "{SCORES_KEY} is not an array of f32"1092                 )));1093             }1094         }1095     }1096     Ok(scores)1097 }1098 1099 /// Whether SentencePiece adds its dummy prefix. The key is optional; when it1100 /// is present it must be a bool, because a string is not a quiet false.1101 fn read_add_space_prefix(g: &Gguf) -> Result<bool, VocabError> {1102     match g.meta.get(ADD_SPACE_PREFIX_KEY) {1103         None => Ok(true),1104         Some(Value::Bool(value)) => Ok(*value),1105         Some(_) => Err(VocabError::Kind(format!(1106             "{ADD_SPACE_PREFIX_KEY} is not a bool"1107         ))),1108     }1109 }1110 1111 /// The family that the model word names.1112 fn read_family(g: &Gguf) -> Result<Family, VocabError> {1113     let model = g1114         .meta1115         .get(MODEL_KEY)1116         .and_then(Value::as_str)1117         .ok_or(VocabError::Missing(MODEL_KEY))?;1118     match model {1119         MODEL_GPT2 => Ok(Family::Gpt2),1120         MODEL_LLAMA => Ok(Family::Llama),1121         other => Err(VocabError::Kind(format!("unknown tokenizer {other}"))),1122     }1123 }1124 1125 /// The kind that GGUF numbers `n`. Zero is unspecified and reads as `Normal`.1126 fn token_kind(n: u64) -> Result<TokenKind, VocabError> {1127     Ok(match n {1128         0 | 1 => TokenKind::Normal,1129         2 => TokenKind::Unknown,1130         3 => TokenKind::Control,1131         4 => TokenKind::UserDefined,1132         5 => TokenKind::Unused,1133         6 => TokenKind::Byte,1134         other => return Err(VocabError::Kind(format!("token type {other}"))),1135     })1136 }