Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / library / ml / src / main / rust / examples / check_nllb_parity.rs

check_nllb_parity.rs243 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.
28use std::path::PathBuf;
29
30use modelrunner::nets::nllb;
31use modelrunner::vulkan::context;
32use modelrunner::vulkan::reshape::Reshaped;
33use modelrunner::vulkan::run::StepParams;
34use modelrunner::weights::{graph, Weights};
35
36/// `</s>`, both the decoder's start token and its stop token.
37const EOS: u32 = 2;
38
39/// The cap `post::translate::MAX_TOKENS` applies.
40const MAX_TOKENS: usize = 128;
41
42fn 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> =
99 want.iter().copied().take_while(|&id| id != EOS).collect();
100 if got == want {
101 println!("ok {:?}", pair.text);
102 println!(" {} tokens", got.len());
103 } else {
104 failures += 1;
105 println!("FAIL {:?}", pair.text);
106 println!(" want {want:?}");
107 println!(" got {got:?}");
108 }
109 }
110 Err(why) => {
111 failures += 1;
112 println!("FAIL {:?}: {why}", pair.text);
113 }
114 }
115 }
116
117 println!();
118 if failures == 0 {
119 println!("all {} pairs match the recorded HuggingFace output", pairs.len());
120 } else {
121 println!("{failures} of {} pairs differ", pairs.len());
122 }
123}
124
125/// One sentence from the fixture.
126struct Pair {
127 text: String,
128 source: Vec<u32>,
129 target: u32,
130 expected: Vec<u32>,
131}
132
133/// Greedy-decode one pair on the device, returning the ids the loop would emit.
134fn decode(
135 context: &std::sync::Arc<context::Context>,
136 weights: &Weights,
137 pair: &Pair,
138) -> Result<Vec<u32>, String> {
139 let src_len = u32::try_from(pair.source.len()).map_err(|_| "a source longer than u32")?;
140 let mut net = Reshaped::new(
141 std::sync::Arc::clone(context),
142 weights,
143 nllb::Mode::Encode { len: src_len },
144 |offsets, mode| nllb::build(offsets, mode),
145 )?;
146
147 // The encoder, once. It leaves every layer's cross-attention K and V in the arena.
148 let embedded = nllb::embed_positions(weights.reader(), &pair.source, 0)?;
149 net.at(nllb::Mode::Encode { len: src_len })?.infer_raw(&embedded)?;
150
151 let mut produced = Vec::new();
152 let mut token = EOS;
153 for step in 0..MAX_TOKENS {
154 let cache_len = u32::try_from(step).map_err(|_| "a step past u32")?;
155 if cache_len >= nllb::MAX_DECODE_POSITIONS {
156 break;
157 }
158 let embedded = nllb::embed_positions(weights.reader(), &[token], cache_len)?;
159 // The same key every step, so this re-records once - on the switch out of `Encode` - and
160 // never again. The KV cache stays in the arena between submits.
161 let at = net.at(nllb::Mode::DecodeStep { src_len })?;
162 at.set_params(StepParams { prefix: cache_len, window_start: 0 })?;
163 let out = at.infer_raw(&embedded)?;
164 let pair_out = out.into_iter().next().ok_or("the step returned nothing")?;
165 let [lo, hi] = pair_out[..] else {
166 return Err(format!("the greedy id holds {} values, not 2", pair_out.len()));
167 };
168
169 // Step 0's argmax is discarded: HuggingFace forces the target language token there.
170 let next = if step == 0 { pair.target } else { hi as u32 * 2048 + lo as u32 };
171 if next == EOS {
172 break;
173 }
174 if step > 0 {
175 produced.push(next);
176 }
177 token = next;
178 }
179 Ok(produced)
180}
181
182/// Pull the pairs out of the fixture.
183///
184/// A hand-rolled reader rather than a JSON crate: this crate's only dependencies are `ash` and
185/// `jni`, and a diagnostic is not a reason to add a third. The fixture's shape is fixed and
186/// committed beside this, so the parsing does not have to be general - only honest about
187/// failing, which it does by returning fewer pairs than the file has.
188fn parse(text: &str) -> Vec<Pair> {
189 let mut pairs = Vec::new();
190 for block in text.split("\"input_text\"").skip(1) {
191 let Some(input) = string_after(block, "") else { continue };
192 let Some(source) = numbers_after(block, "\"encoder_input_ids\"") else { continue };
193 let Some(expected) = numbers_after(block, "\"greedy_output_ids\"") else { continue };
194 let Some(target) = numbers_after(block, "\"tgt_lang_id\"").and_then(|v| v.first().copied())
195 else {
196 continue;
197 };
198 pairs.push(Pair { text: input, source, target, expected });
199 }
200 pairs
201}
202
203/// The first quoted string in `block` after `key`.
204fn string_after(block: &str, key: &str) -> Option<String> {
205 let rest = block.split_once(key).map_or(block, |(_, rest)| rest);
206 let start = rest.find('"')? + 1;
207 let body = rest.get(start..)?;
208 let end = body.find('"')?;
209 body.get(..end).map(str::to_owned)
210}
211
212/// Every integer between the brackets that follow `key`, or the single value after it.
213fn numbers_after(block: &str, key: &str) -> Option<Vec<u32>> {
214 let (_, rest) = block.split_once(key)?;
215 let rest = rest.trim_start().strip_prefix(':')?.trim_start();
216 let body = match rest.strip_prefix('[') {
217 Some(list) => list.get(..list.find(']')?)?,
218 // A bare number, terminated by the next comma or brace.
219 None => rest.get(..rest.find([',', '\n', '}'])?)?,
220 };
221 let mut out = Vec::new();
222 for piece in body.split(',') {
223 let piece = piece.trim();
224 if piece.is_empty() {
225 continue;
226 }
227 out.push(piece.parse::<u32>().ok()?);
228 }
229 Some(out)
230}
231
232/// `variable` if it names a file, else the first of `candidates` under the repo root.
233fn find(candidates: &[&str], variable: &str) -> Option<PathBuf> {
234 if let Ok(path) = std::env::var(variable) {
235 let path = PathBuf::from(path);
236 return path.is_file().then_some(path);
237 }
238 let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
239 while !dir.join("settings.gradle.kts").is_file() {
240 dir = dir.parent()?.to_path_buf();
241 }
242 candidates.iter().map(|name| dir.join(name)).find(|path| path.is_file())
243}