Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / examples / check_gemma4_tokenizer.rs
check_gemma4_tokenizer.rs156 lines · 5.7 KiBRaw
| 1 | //! Checks `post::sentencepiece` against real HuggingFace `tokenizers` output for Gemma 4. |
| 2 | //! |
| 3 | //! ```text |
| 4 | //! cargo run --offline --release -p modelrunner --example check_gemma4_tokenizer -- \ |
| 5 | //! gemma4_tokenizer.spm1 tok_golden.json |
| 6 | //! ``` |
| 7 | //! |
| 8 | //! # Why a golden and not a unit test |
| 9 | //! |
| 10 | //! The merge loop is already unit-tested on a handful of hand-built pieces, and that catches an |
| 11 | //! algorithm that merges in the wrong order. It cannot catch the things that actually differ |
| 12 | //! between two tokenizers of the *same* algorithm: whether whitespace is collapsed, whether a |
| 13 | //! dummy prefix is added, how an unrepresentable byte is spelled, and whether the merge ranks |
| 14 | //! were inverted correctly on the way into the file. Those only show up against the real thing. |
| 15 | //! |
| 16 | //! The samples deliberately include runs of spaces and a code block, because Gemma's normaliser |
| 17 | //! is a bare `Replace(" ", metaspace)` with no trimming - the opposite of what fairseq's models |
| 18 | //! were trained with, and what `Flavour::tidy_whitespace` exists to distinguish. |
| 19 | use std::path::PathBuf; |
| 20 | |
| 21 | use modelrunner::post::sentencepiece::Table; |
| 22 | use modelrunner::post::sentencepiece_flavours::GEMMA; |
| 23 | |
| 24 | /// One `{ "text": ..., "ids": [...] }` from the golden file. |
| 25 | struct Case { |
| 26 | text: String, |
| 27 | ids: Vec<u32>, |
| 28 | } |
| 29 | |
| 30 | fn main() { |
| 31 | let mut args = std::env::args().skip(1); |
| 32 | let (Some(table_path), Some(golden_path)) = |
| 33 | (args.next().map(PathBuf::from), args.next().map(PathBuf::from)) |
| 34 | else { |
| 35 | println!("usage: check_gemma4_tokenizer <table.spm1> <golden.json>"); |
| 36 | return; |
| 37 | }; |
| 38 | let blob = match std::fs::read(&table_path) { |
| 39 | Ok(bytes) => bytes, |
| 40 | Err(why) => return println!("cannot read {}: {why}", table_path.display()), |
| 41 | }; |
| 42 | let table = match Table::parse_with(&blob, GEMMA) { |
| 43 | Ok(table) => table, |
| 44 | Err(why) => return println!("the table does not parse: {why}"), |
| 45 | }; |
| 46 | println!("{} pieces, byte fallback {}", table.len(), table.has_byte_fallback()); |
| 47 | if !table.has_byte_fallback() { |
| 48 | println!("FAIL: Gemma's vocabulary holds all 256 byte pieces and this one does not"); |
| 49 | return; |
| 50 | } |
| 51 | |
| 52 | let golden = match std::fs::read_to_string(&golden_path) { |
| 53 | Ok(text) => text, |
| 54 | Err(why) => return println!("cannot read {}: {why}", golden_path.display()), |
| 55 | }; |
| 56 | let cases = parse_golden(&golden); |
| 57 | println!("{} cases", cases.len()); |
| 58 | println!(); |
| 59 | |
| 60 | // The markers a chat template inserts. `<bos>` is the one the golden exercises; the rest are |
| 61 | // listed because the same call site will need them and an unknown entry is skipped. |
| 62 | let specials = [ |
| 63 | "<bos>", |
| 64 | "<eos>", |
| 65 | "<pad>", |
| 66 | "<unk>", |
| 67 | "<|tool>", |
| 68 | "<tool|>", |
| 69 | "<|tool_call>", |
| 70 | "<tool_call|>", |
| 71 | "<|tool_response>", |
| 72 | "<tool_response|>", |
| 73 | ]; |
| 74 | |
| 75 | let mut passed = 0; |
| 76 | for case in &cases { |
| 77 | let got = table.encode_with_specials(&case.text, &specials); |
| 78 | if got == case.ids { |
| 79 | passed += 1; |
| 80 | continue; |
| 81 | } |
| 82 | println!("MISMATCH for {:?}", case.text); |
| 83 | println!(" want {:?}", case.ids); |
| 84 | println!(" got {got:?}"); |
| 85 | let first = got.iter().zip(&case.ids).position(|(a, b)| a != b).unwrap_or(0); |
| 86 | println!(" first differs at {first}"); |
| 87 | } |
| 88 | println!(); |
| 89 | println!("{passed} of {} match HuggingFace", cases.len()); |
| 90 | |
| 91 | // Round-tripping matters as much as encoding: byte fallback is only useful if `decode` fuses |
| 92 | // the byte pieces back into characters rather than emitting one replacement each. |
| 93 | let mut round_tripped = 0; |
| 94 | for case in &cases { |
| 95 | let text = table.decode(&case.ids); |
| 96 | let want = case.text.trim(); |
| 97 | if text == want { |
| 98 | round_tripped += 1; |
| 99 | } else { |
| 100 | println!("ROUND TRIP {:?} -> {:?}", case.text, text); |
| 101 | } |
| 102 | } |
| 103 | println!("{round_tripped} of {} round-trip through decode", cases.len()); |
| 104 | } |
| 105 | |
| 106 | /// The golden file, parsed without pulling in a JSON crate for one shape. |
| 107 | fn parse_golden(text: &str) -> Vec<Case> { |
| 108 | let mut cases = Vec::new(); |
| 109 | let mut rest = text; |
| 110 | while let Some(at) = rest.find("\"text\":") { |
| 111 | rest = &rest[at + 7..]; |
| 112 | let Some(text_value) = read_string(&mut rest) else { break }; |
| 113 | let Some(at) = rest.find("\"ids\":") else { break }; |
| 114 | rest = &rest[at + 6..]; |
| 115 | let Some(open) = rest.find('[') else { break }; |
| 116 | let Some(close) = rest[open..].find(']') else { break }; |
| 117 | let ids = rest[open + 1..open + close] |
| 118 | .split(',') |
| 119 | .filter_map(|piece| piece.trim().parse::<u32>().ok()) |
| 120 | .collect(); |
| 121 | rest = &rest[open + close..]; |
| 122 | cases.push(Case { text: text_value, ids }); |
| 123 | } |
| 124 | cases |
| 125 | } |
| 126 | |
| 127 | /// The next JSON string in `rest`, advancing past it. Handles the escapes the writer emits. |
| 128 | fn read_string(rest: &mut &str) -> Option<String> { |
| 129 | let open = rest.find('"')?; |
| 130 | let mut out = String::new(); |
| 131 | let mut chars = rest[open + 1..].char_indices(); |
| 132 | while let Some((at, c)) = chars.next() { |
| 133 | match c { |
| 134 | '"' => { |
| 135 | *rest = &rest[open + 1 + at + 1..]; |
| 136 | return Some(out); |
| 137 | } |
| 138 | '\\' => { |
| 139 | let (_, escaped) = chars.next()?; |
| 140 | out.push(match escaped { |
| 141 | 'n' => '\n', |
| 142 | 't' => '\t', |
| 143 | 'r' => '\r', |
| 144 | 'u' => { |
| 145 | let hex: String = |
| 146 | (0..4).filter_map(|_| chars.next().map(|(_, c)| c)).collect(); |
| 147 | char::from_u32(u32::from_str_radix(&hex, 16).ok()?)? |
| 148 | } |
| 149 | other => other, |
| 150 | }); |
| 151 | } |
| 152 | other => out.push(other), |
| 153 | } |
| 154 | } |
| 155 | None |
| 156 | } |