Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / examples / check_nllb_parity.rs
check_nllb_parity.rs242 lines · 9.1 KiBRaw
| 1 | //! Greedy-decodes NLLB against the recorded HuggingFace token sequence. |
| 2 | //! |
| 3 | //! ```text |
| 4 | //! cargo run --offline --release -p modelrunner --example check_nllb_parity |
| 5 | //! ``` |
| 6 | //! |
| 7 | //! # Why this exists |
| 8 | //! |
| 9 | //! `library/ml/src/main/rust/tests/assets.rs` cannot cover NLLB: the weights are a 617 MB runtime |
| 10 | //! download, not a committed asset, so nothing in `cargo test` ever runs the real model. The |
| 11 | //! device-side parity fixtures check one op at a time against the CPU interpreter, which says |
| 12 | //! nothing about whether twelve decoder layers and a KV cache produce the right *tokens*. |
| 13 | //! |
| 14 | //! `scripts/ml/nllb_parity_fixture.json` holds what fp32 HuggingFace produced for a handful of |
| 15 | //! sentences, at a pinned revision. This drives the same greedy loop `post::translate` runs, on |
| 16 | //! the device, and compares ids. |
| 17 | //! |
| 18 | //! # What it is for |
| 19 | //! |
| 20 | //! Changing how the decoder holds its KV cache is a change that keeps every shape and every op |
| 21 | //! count identical while making the numbers wrong - which is precisely the class of change the |
| 22 | //! per-op fixtures cannot catch. Run this before such a change and after it; the ids must not |
| 23 | //! move. |
| 24 | //! |
| 25 | //! The loop here is a transcription of `post::translate::translate`, not a call to it, because |
| 26 | //! that takes a `Table` to tokenise with and the fixture already carries token ids. Keeping the |
| 27 | //! tokenizer out means a mismatch here is the *model*, which is the point. |
| 28 | use std::path::PathBuf; |
| 29 | |
| 30 | use modelrunner::nets::nllb; |
| 31 | use modelrunner::vulkan::context; |
| 32 | use modelrunner::vulkan::reshape::Reshaped; |
| 33 | use modelrunner::vulkan::run::StepParams; |
| 34 | use modelrunner::weights::{graph, Weights}; |
| 35 | |
| 36 | /// `</s>`, both the decoder's start token and its stop token. |
| 37 | const EOS: u32 = 2; |
| 38 | |
| 39 | /// The cap `post::translate::MAX_TOKENS` applies. |
| 40 | const MAX_TOKENS: usize = 128; |
| 41 | |
| 42 | fn main() { |
| 43 | let Some(weights_path) = find(&["build/nllb600/nllb600.maml"], "MODELRUNNER_NLLB") else { |
| 44 | println!("no nllb600.maml found. Set MODELRUNNER_NLLB, or run scripts/ml/fetch_nllb600.py"); |
| 45 | return; |
| 46 | }; |
| 47 | let Some(fixture_path) = find(&["scripts/ml/nllb_parity_fixture.json"], "MODELRUNNER_FIXTURE") |
| 48 | else { |
| 49 | println!("scripts/ml/nllb_parity_fixture.json is missing"); |
| 50 | return; |
| 51 | }; |
| 52 | println!("weights {}", weights_path.display()); |
| 53 | println!("fixture {}", fixture_path.display()); |
| 54 | |
| 55 | let fixture = match std::fs::read_to_string(&fixture_path) { |
| 56 | Ok(text) => text, |
| 57 | Err(why) => { |
| 58 | println!("cannot read the fixture: {why}"); |
| 59 | return; |
| 60 | } |
| 61 | }; |
| 62 | let pairs = parse(&fixture); |
| 63 | if pairs.is_empty() { |
| 64 | println!("the fixture has no pairs this can read"); |
| 65 | return; |
| 66 | } |
| 67 | |
| 68 | let bytes = match std::fs::read(&weights_path) { |
| 69 | Ok(bytes) => bytes, |
| 70 | Err(why) => { |
| 71 | println!("cannot read the weights: {why}"); |
| 72 | return; |
| 73 | } |
| 74 | }; |
| 75 | let weights = match Weights::parse(&bytes, graph::NLLB) { |
| 76 | Ok(weights) => weights, |
| 77 | Err(why) => { |
| 78 | println!("cannot parse the weights: {why}"); |
| 79 | return; |
| 80 | } |
| 81 | }; |
| 82 | let context = match context::shared() { |
| 83 | Ok(context) => context, |
| 84 | Err(why) => { |
| 85 | println!("no usable Vulkan device: {why}"); |
| 86 | return; |
| 87 | } |
| 88 | }; |
| 89 | println!(); |
| 90 | |
| 91 | let mut failures = 0; |
| 92 | for pair in &pairs { |
| 93 | match decode(&context, &weights, pair) { |
| 94 | Ok(got) => { |
| 95 | // The fixture's sequence opens with `</s>` and the forced language token, which |
| 96 | // the loop consumes as framing rather than emitting. Compare against the rest. |
| 97 | let want: Vec<u32> = pair.expected.iter().copied().skip(2).collect(); |
| 98 | let want: Vec<u32> = want.iter().copied().take_while(|&id| id != EOS).collect(); |
| 99 | if got == want { |
| 100 | println!("ok {:?}", pair.text); |
| 101 | println!(" {} tokens", got.len()); |
| 102 | } else { |
| 103 | failures += 1; |
| 104 | println!("FAIL {:?}", pair.text); |
| 105 | println!(" want {want:?}"); |
| 106 | println!(" got {got:?}"); |
| 107 | } |
| 108 | } |
| 109 | Err(why) => { |
| 110 | failures += 1; |
| 111 | println!("FAIL {:?}: {why}", pair.text); |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | println!(); |
| 117 | if failures == 0 { |
| 118 | println!("all {} pairs match the recorded HuggingFace output", pairs.len()); |
| 119 | } else { |
| 120 | println!("{failures} of {} pairs differ", pairs.len()); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | /// One sentence from the fixture. |
| 125 | struct Pair { |
| 126 | text: String, |
| 127 | source: Vec<u32>, |
| 128 | target: u32, |
| 129 | expected: Vec<u32>, |
| 130 | } |
| 131 | |
| 132 | /// Greedy-decode one pair on the device, returning the ids the loop would emit. |
| 133 | fn decode( |
| 134 | context: &std::sync::Arc<context::Context>, |
| 135 | weights: &Weights, |
| 136 | pair: &Pair, |
| 137 | ) -> Result<Vec<u32>, String> { |
| 138 | let src_len = u32::try_from(pair.source.len()).map_err(|_| "a source longer than u32")?; |
| 139 | let mut net = Reshaped::new( |
| 140 | std::sync::Arc::clone(context), |
| 141 | weights, |
| 142 | nllb::Mode::Encode { len: src_len }, |
| 143 | |offsets, mode| nllb::build(offsets, mode), |
| 144 | )?; |
| 145 | |
| 146 | // The encoder, once. It leaves every layer's cross-attention K and V in the arena. |
| 147 | let embedded = nllb::embed_positions(weights.reader(), &pair.source, 0)?; |
| 148 | net.at(nllb::Mode::Encode { len: src_len })?.infer_raw(&embedded)?; |
| 149 | |
| 150 | let mut produced = Vec::new(); |
| 151 | let mut token = EOS; |
| 152 | for step in 0..MAX_TOKENS { |
| 153 | let cache_len = u32::try_from(step).map_err(|_| "a step past u32")?; |
| 154 | if cache_len >= nllb::MAX_DECODE_POSITIONS { |
| 155 | break; |
| 156 | } |
| 157 | let embedded = nllb::embed_positions(weights.reader(), &[token], cache_len)?; |
| 158 | // The same key every step, so this re-records once - on the switch out of `Encode` - and |
| 159 | // never again. The KV cache stays in the arena between submits. |
| 160 | let at = net.at(nllb::Mode::DecodeStep { src_len })?; |
| 161 | at.set_params(StepParams { prefix: cache_len, window_start: 0 })?; |
| 162 | let out = at.infer_raw(&embedded)?; |
| 163 | let pair_out = out.into_iter().next().ok_or("the step returned nothing")?; |
| 164 | let [lo, hi] = pair_out[..] else { |
| 165 | return Err(format!("the greedy id holds {} values, not 2", pair_out.len())); |
| 166 | }; |
| 167 | |
| 168 | // Step 0's argmax is discarded: HuggingFace forces the target language token there. |
| 169 | let next = if step == 0 { pair.target } else { hi as u32 * 2048 + lo as u32 }; |
| 170 | if next == EOS { |
| 171 | break; |
| 172 | } |
| 173 | if step > 0 { |
| 174 | produced.push(next); |
| 175 | } |
| 176 | token = next; |
| 177 | } |
| 178 | Ok(produced) |
| 179 | } |
| 180 | |
| 181 | /// Pull the pairs out of the fixture. |
| 182 | /// |
| 183 | /// A hand-rolled reader rather than a JSON crate: this crate's only dependencies are `ash` and |
| 184 | /// `jni`, and a diagnostic is not a reason to add a third. The fixture's shape is fixed and |
| 185 | /// committed beside this, so the parsing does not have to be general - only honest about |
| 186 | /// failing, which it does by returning fewer pairs than the file has. |
| 187 | fn parse(text: &str) -> Vec<Pair> { |
| 188 | let mut pairs = Vec::new(); |
| 189 | for block in text.split("\"input_text\"").skip(1) { |
| 190 | let Some(input) = string_after(block, "") else { continue }; |
| 191 | let Some(source) = numbers_after(block, "\"encoder_input_ids\"") else { continue }; |
| 192 | let Some(expected) = numbers_after(block, "\"greedy_output_ids\"") else { continue }; |
| 193 | let Some(target) = numbers_after(block, "\"tgt_lang_id\"").and_then(|v| v.first().copied()) |
| 194 | else { |
| 195 | continue; |
| 196 | }; |
| 197 | pairs.push(Pair { text: input, source, target, expected }); |
| 198 | } |
| 199 | pairs |
| 200 | } |
| 201 | |
| 202 | /// The first quoted string in `block` after `key`. |
| 203 | fn string_after(block: &str, key: &str) -> Option<String> { |
| 204 | let rest = block.split_once(key).map_or(block, |(_, rest)| rest); |
| 205 | let start = rest.find('"')? + 1; |
| 206 | let body = rest.get(start..)?; |
| 207 | let end = body.find('"')?; |
| 208 | body.get(..end).map(str::to_owned) |
| 209 | } |
| 210 | |
| 211 | /// Every integer between the brackets that follow `key`, or the single value after it. |
| 212 | fn numbers_after(block: &str, key: &str) -> Option<Vec<u32>> { |
| 213 | let (_, rest) = block.split_once(key)?; |
| 214 | let rest = rest.trim_start().strip_prefix(':')?.trim_start(); |
| 215 | let body = match rest.strip_prefix('[') { |
| 216 | Some(list) => list.get(..list.find(']')?)?, |
| 217 | // A bare number, terminated by the next comma or brace. |
| 218 | None => rest.get(..rest.find([',', '\n', '}'])?)?, |
| 219 | }; |
| 220 | let mut out = Vec::new(); |
| 221 | for piece in body.split(',') { |
| 222 | let piece = piece.trim(); |
| 223 | if piece.is_empty() { |
| 224 | continue; |
| 225 | } |
| 226 | out.push(piece.parse::<u32>().ok()?); |
| 227 | } |
| 228 | Some(out) |
| 229 | } |
| 230 | |
| 231 | /// `variable` if it names a file, else the first of `candidates` under the repo root. |
| 232 | fn find(candidates: &[&str], variable: &str) -> Option<PathBuf> { |
| 233 | if let Ok(path) = std::env::var(variable) { |
| 234 | let path = PathBuf::from(path); |
| 235 | return path.is_file().then_some(path); |
| 236 | } |
| 237 | let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); |
| 238 | while !dir.join("settings.gradle.kts").is_file() { |
| 239 | dir = dir.parent()?.to_path_buf(); |
| 240 | } |
| 241 | candidates.iter().map(|name| dir.join(name)).find(|path| path.is_file()) |
| 242 | } |