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

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

profile_supertonic.rs494 lines · 18.7 KiBRaw
1//! End-to-end Supertonic utterance profiler: one real sentence exactly as the bridge runs it.
2//!
3//! ```text
4//! cargo run --offline --release -p modelrunner --example profile_supertonic -- [asset dir] [voice]
5//! adb shell MODELRUNNER_TIMESTAMPS=1 /data/local/tmp/maml/supertonic/profile_supertonic /data/local/tmp/maml/supertonic
6//! ```
7//!
8//! The asset dir holds supertonic_{dp,ttl,ve,voc}.maml, unicode_indexer.bin and style_*.bin
9//! (see speech/src/main/assets/supertonic). Voice defaults to F1.
10//!
11//! The four nets run through [`Stages`] exactly as `bridge_part1.rs`'s `SupertonicNets` does:
12//! duration predictor, text encoder, 16 dual-branch sampler steps (`build_dual`, one submit per
13//! step), vocoder with the host `unpack_latent`/`interleave`. The only deliberate difference is
14//! the noise: the bridge seeds from the clock so two readings differ, while this uses a fixed
15//! seed so the audio checksum below proves the output is unchanged against another build.
16//!
17//! Wall times are with timestamps off unless `MODELRUNNER_TIMESTAMPS=1` is set, so measure the
18//! two in separate runs (see examples/profile_net.rs). The pipeline is non-streaming — the
19//! waveform exists only after the vocoder — so time-to-first-audio is the total.
20use std::collections::BTreeMap;
21use std::time::Instant;
22
23use modelrunner::nets::{
24 supertonic_duration, supertonic_sampler, supertonic_text, supertonic_vocoder, Plan,
25};
26use modelrunner::post::supertonic::{self, Voice, STEPS};
27use modelrunner::vulkan::context;
28use modelrunner::vulkan::reshape::Reshaped;
29use modelrunner::weights::{graph, Offsets, Weights};
30
31/// A typical sentence, already NFKD (plain ASCII is stable under NFKD, which is what the
32/// Kotlin side guarantees before calling in).
33const SENTENCE: &str = "Hello, this voice runs entirely on this device.";
34const LANGUAGE: &str = "en";
35
36/// Fixed noise seed, so the checksum below is comparable across builds. The bridge seeds from
37/// the clock; everything else here is identical to it.
38const NOISE_SEED: u64 = 0x1234_5678_9ABC_DEF1 | 1;
39
40/// The smallest legal shape, for the plan recorded at construction and immediately replaced.
41/// Mirrors `bridge_part1.rs`: `Net::rebuild` only ever grows the arena, so starting here
42/// wastes nothing.
43const SMALLEST: u32 = 1;
44
45fn duration_plan(offsets: &Offsets, chars: u32) -> Result<Plan, String> {
46 supertonic_duration::build(offsets, chars)
47}
48
49fn text_plan(offsets: &Offsets, chars: u32) -> Result<Plan, String> {
50 supertonic_text::build(offsets, chars)
51}
52
53fn sampler_plan(offsets: &Offsets, shape: (u32, u32)) -> Result<Plan, String> {
54 supertonic_sampler::build_dual_padded(offsets, shape.0, shape.1)
55}
56
57fn vocoder_plan(offsets: &Offsets, frames: u32) -> Result<Plan, String> {
58 supertonic_vocoder::build(offsets, frames)
59}
60
61/// A small deterministic-per-seed generator. Copied from `bridge_part1.rs` (SplitMix64 +
62/// Box-Muller) so the latent matches what the bridge would draw from the same seed.
63struct SplitMix {
64 state: u64,
65}
66
67impl SplitMix {
68 fn next_u64(&mut self) -> u64 {
69 self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
70 let mut z = self.state;
71 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
72 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
73 z ^ (z >> 31)
74 }
75
76 fn normal(&mut self, count: usize) -> Vec<f32> {
77 let mut out = Vec::with_capacity(count);
78 while out.len() < count {
79 let first = ((self.next_u64() >> 11) as f64 + 1.0) / 9_007_199_254_740_993.0;
80 let second = ((self.next_u64() >> 11) as f64) / 9_007_199_254_740_992.0;
81 let radius = (-2.0 * first.ln()).sqrt();
82 let angle = std::f64::consts::TAU * second;
83 out.push((radius * angle.cos()) as f32);
84 if out.len() < count {
85 out.push((radius * angle.sin()) as f32);
86 }
87 }
88 out
89 }
90}
91
92/// The single output of a plan that has exactly one. As in `bridge_part1.rs`.
93fn one_output(outputs: Vec<Vec<f32>>) -> Result<Vec<f32>, String> {
94 match <[Vec<f32>; 1]>::try_from(outputs) {
95 Ok([only]) => Ok(only),
96 Err(other) => Err(format!("{} outputs, expected one", other.len())),
97 }
98}
99
100/// Positions per id tensor: `nets::embed_lanes` writes two lanes, `lo + 2048 * hi`.
101const LANES: usize = 2;
102
103/// `values / stride`, refusing a remainder. As in `bridge_part1.rs`.
104fn positions(what: &str, values: usize, stride: usize) -> Result<u32, String> {
105 if stride == 0 || values == 0 || values % (stride) != 0 {
106 return Err(format!("{what}: {values} values is not a whole number of {stride}"));
107 }
108 Ok((values / stride) as u32)
109}
110
111/// The bridge's `SupertonicNets`, plus per-stage wall clocks and the sampler's per-step times.
112struct Timed {
113 duration: Reshaped<u32>,
114 text: Reshaped<u32>,
115 sampler: Reshaped<(u32, u32)>,
116 vocoder: Reshaped<u32>,
117 duration_times: Vec<(String, f64, f64)>,
118 text_times: Vec<(String, f64, f64)>,
119 sampler_times: Vec<(String, f64, f64)>,
120 vocoder_times: Vec<(String, f64, f64)>,
121 duration_ms: f64,
122 text_ms: f64,
123 sampler_ms: Vec<f64>,
124 vocoder_ms: f64,
125 reshape_ms: f64,
126 reshape_duration_ms: f64,
127 reshape_text_ms: f64,
128 reshape_sampler_ms: f64,
129 reshape_vocoder_ms: f64,
130 unpack_ms: f64,
131 interleave_ms: f64,
132}
133
134impl supertonic::Stages for Timed {
135 fn duration(&mut self, lanes: &[f32], style: &[f32]) -> Result<f32, String> {
136 let sequence = positions("duration ids", lanes.len(), LANES)?;
137 let chars = sequence.checked_sub(1).ok_or("a duration pass over only a sentence token")?;
138 let reshaping = Instant::now();
139 let net = self.duration.at(chars)?;
140 let each = ms(reshaping);
141 self.reshape_ms += each;
142 self.reshape_duration_ms += each;
143 let running = Instant::now();
144 let out = net.infer_raw_many(&[lanes, style])?;
145 self.duration_ms += ms(running);
146 // Captured here rather than after the utterance: `Reshaped::at` may
147 // re-record later and a fresh pool without a fresh submit reads back
148 // garbage. Errors (timestamps off) just leave the previous table.
149 if let Ok(times) = net.op_times() {
150 self.duration_times = times;
151 }
152 let [_encoded, log_seconds] = <[Vec<f32>; 2]>::try_from(out).map_err(|other| {
153 format!("the duration predictor returned {} tensors, not two", other.len())
154 })?;
155 match log_seconds.as_slice() {
156 [only] => Ok(*only),
157 other => {
158 Err(format!("the duration predictor returned {} values, not one", other.len()))
159 }
160 }
161 }
162
163 fn text(&mut self, lanes: &[f32], style: &[f32]) -> Result<Vec<f32>, String> {
164 let chars = positions("text ids", lanes.len(), LANES)?;
165 let reshaping = Instant::now();
166 let net = self.text.at(chars)?;
167 let each = ms(reshaping);
168 self.reshape_ms += each;
169 self.reshape_text_ms += each;
170 let running = Instant::now();
171 let out = one_output(net.infer_raw_many(&[lanes, style])?);
172 self.text_ms += ms(running);
173 if let Ok(times) = net.op_times() {
174 self.text_times = times;
175 }
176 out
177 }
178 fn text_then(
179 &mut self,
180 lanes: &[f32],
181 style: &[f32],
182 sampler_shape: (u32, u32),
183 ) -> Result<Vec<f32>, String> {
184 if self.sampler.holds(sampler_shape) {
185 return self.text(lanes, style);
186 }
187 // As bridge_part1.rs: the sampler plan builds on another thread while the text encoder runs.
188 let (plan, offsets) = self.sampler.planner();
189 let (text, built) = std::thread::scope(|scope| {
190 let building = scope.spawn(move || plan(&offsets, sampler_shape));
191 let text = self.text(lanes, style);
192 (text, building.join())
193 });
194 if let Ok(Ok(built)) = built {
195 self.sampler.adopt(sampler_shape, built);
196 }
197 text
198 }
199
200 fn sampler(
201 &mut self,
202 _latent: &[f32],
203 _text: &[f32],
204 _keys: &[f32],
205 _style: &[f32],
206 _shifts: &[f32],
207 _query_angles: &[f32],
208 _key_angles: &[f32],
209 ) -> Result<Vec<f32>, String> {
210 // Dead: `synthesise` takes the dual path. The bridge spells out the single-branch
211 // submit; this profiler only runs the path the bridge actually takes.
212 Err("the profiler runs the dual sampler path only".into())
213 }
214
215 #[allow(clippy::too_many_arguments)]
216 fn sampler_both(
217 &mut self,
218 latent: &[f32],
219 conditional_text: &[f32],
220 conditional_keys: &[f32],
221 conditional_style: &[f32],
222 unconditional_text: &[f32],
223 unconditional_keys: &[f32],
224 unconditional_style: &[f32],
225 shifts: &[f32],
226 query_angles: &[f32],
227 key_angles: &[f32],
228 ) -> Result<[Vec<f32>; 2], String> {
229 let frames = positions("a latent", latent.len(), supertonic_sampler::LATENT as usize)?;
230 let chars =
231 positions("a conditioning", conditional_text.len(), supertonic_sampler::TEXT as usize)?;
232 let reshaping = Instant::now();
233 let net = self.sampler.at((frames, chars))?;
234 let each = ms(reshaping);
235 self.reshape_ms += each;
236 self.reshape_sampler_ms += each;
237 let running = Instant::now();
238 let latent = supertonic_sampler::pad_frames(latent, frames)?;
239 let query_angles = supertonic_sampler::pad_frames(query_angles, frames)?;
240 let (latent, query_angles) = (latent.as_slice(), query_angles.as_slice());
241 let out = net.infer_raw_many(&[
242 latent,
243 conditional_text,
244 conditional_keys,
245 conditional_style,
246 shifts,
247 query_angles,
248 key_angles,
249 latent,
250 unconditional_text,
251 unconditional_keys,
252 unconditional_style,
253 shifts,
254 query_angles,
255 key_angles,
256 ])?;
257 self.sampler_ms.push(ms(running));
258 // One step's table stands for all sixteen: same plan, same shape.
259 if let Ok(times) = net.op_times() {
260 self.sampler_times = times;
261 }
262 let [conditional, unconditional] = <[Vec<f32>; 2]>::try_from(out).map_err(|other| {
263 format!("the dual sampler returned {} tensors, not two", other.len())
264 })?;
265 Ok([
266 supertonic_sampler::unpad_frames(&conditional, frames)?,
267 supertonic_sampler::unpad_frames(&unconditional, frames)?,
268 ])
269 }
270
271 fn vocoder(&mut self, latent: &[f32], frames: u32) -> Result<Vec<f32>, String> {
272 let reshaping = Instant::now();
273 let net = self.vocoder.at(supertonic_vocoder::padded_frames(frames))?;
274 let each = ms(reshaping);
275 self.reshape_ms += each;
276 self.reshape_vocoder_ms += each;
277 let unpacking = Instant::now();
278 let unpacked = supertonic_vocoder::unpack_latent_padded(latent, frames as usize)?;
279 self.unpack_ms += ms(unpacking);
280 let running = Instant::now();
281 let channelled = one_output(net.infer_raw(&unpacked)?)?;
282 self.vocoder_ms += ms(running);
283 if let Ok(times) = net.op_times() {
284 self.vocoder_times = times;
285 }
286 let interleaving = Instant::now();
287 let out = supertonic_vocoder::interleave_padded(&channelled, frames as usize)?;
288 self.interleave_ms += ms(interleaving);
289 Ok(out)
290 }
291}
292
293fn main() {
294 if let Err(why) = run() {
295 println!("failed: {why}");
296 }
297}
298
299fn run() -> Result<(), String> {
300 let args: Vec<String> = std::env::args().skip(1).collect();
301 let dir = args
302 .first()
303 .map(String::as_str)
304 .or(option_env!("MODELRUNNER_ASSETS"))
305 .map(str::to_owned)
306 .or_else(|| std::env::var("MODELRUNNER_ASSETS").ok())
307 .ok_or("pass the supertonic asset dir or set MODELRUNNER_ASSETS")?;
308 let voice = args.get(1).map(String::as_str).unwrap_or("F1");
309 let file = |name: &str| {
310 let path = format!("{dir}/{name}");
311 std::fs::read(&path).map_err(|e| format!("cannot read {path}: {e}"))
312 };
313
314 let dp = Weights::parse(&file("supertonic_dp.maml")?, graph::SUPERTONIC_DP)?;
315 let ttl = Weights::parse(&file("supertonic_ttl.maml")?, graph::SUPERTONIC_TTL)?;
316 let ve = Weights::parse(&file("supertonic_ve.maml")?, graph::SUPERTONIC_VE)?;
317 let voc = Weights::parse(&file("supertonic_voc.maml")?, graph::SUPERTONIC_VOC)?;
318 let indexer = file("unicode_indexer.bin")?;
319 let voice = Voice::read(&file(&format!("style_{voice}.bin"))?)?;
320 let conditioning = supertonic::Conditioning::read(ve.reader())?;
321
322 let context = context::shared()?;
323 let started = Instant::now();
324 let mut stages = Timed {
325 duration: Reshaped::new(context.clone(), &dp, SMALLEST, duration_plan)?,
326 text: Reshaped::new(context.clone(), &ttl, SMALLEST, text_plan)?,
327 sampler: Reshaped::new(context.clone(), &ve, (SMALLEST, SMALLEST), sampler_plan)?,
328 vocoder: Reshaped::new(context, &voc, SMALLEST, vocoder_plan)?,
329 duration_times: Vec::new(),
330 text_times: Vec::new(),
331 sampler_times: Vec::new(),
332 vocoder_times: Vec::new(),
333 duration_ms: 0.0,
334 text_ms: 0.0,
335 sampler_ms: Vec::new(),
336 vocoder_ms: 0.0,
337 reshape_ms: 0.0,
338 reshape_duration_ms: 0.0,
339 reshape_text_ms: 0.0,
340 reshape_sampler_ms: 0.0,
341 reshape_vocoder_ms: 0.0,
342 unpack_ms: 0.0,
343 interleave_ms: 0.0,
344 };
345 let load_ms = ms(started);
346 println!("load {load_ms:>8.1} ms (upload + first record)");
347
348 let noise = std::cell::RefCell::new(SplitMix { state: NOISE_SEED });
349 let whole = Instant::now();
350 let samples = supertonic::synthesise(
351 &mut stages,
352 &conditioning,
353 &indexer,
354 &voice,
355 SENTENCE,
356 LANGUAGE,
357 &|count| noise.borrow_mut().normal(count),
358 )?;
359 let total_ms = ms(whole);
360
361 let ids = supertonic::to_ids(&indexer, SENTENCE, LANGUAGE)?;
362 let chars = ids.len() as u32;
363 let frames = samples.len() as u32 / supertonic_vocoder::SAMPLES_PER_FRAME;
364 println!(
365 "sentence {SENTENCE:?} -> {chars} ids -> {frames} frames -> {} samples",
366 samples.len()
367 );
368 println!("duration {:>8.1} ms", stages.duration_ms);
369 println!("text {:>8.1} ms", stages.text_ms);
370 println!(
371 "sampler {:>8.1} ms over {} steps (dual submit each)",
372 sum(&stages.sampler_ms),
373 stages.sampler_ms.len()
374 );
375 for (step, each) in stages.sampler_ms.iter().enumerate() {
376 println!(" step {step:>2} {each:>8.1} ms");
377 }
378 println!(
379 "vocoder {:>8.1} ms (unpack {:.1}, infer {:.1}, interleave {:.1})",
380 stages.unpack_ms + stages.vocoder_ms + stages.interleave_ms,
381 stages.unpack_ms,
382 stages.vocoder_ms,
383 stages.interleave_ms
384 );
385 println!(
386 "reshape {:>8.1} ms (dp {:.1}, ttl {:.1}, ve {:.1}, voc {:.1}; plan build + re-record)",
387 stages.reshape_ms,
388 stages.reshape_duration_ms,
389 stages.reshape_text_ms,
390 stages.reshape_sampler_ms,
391 stages.reshape_vocoder_ms
392 );
393 println!("total {total_ms:>8.1} ms");
394 println!("first audio {total_ms:>8.1} ms (non-streaming: the waveform exists only after the vocoder)");
395
396 let (sum, sum_sq, peak) = checksum(&samples);
397 println!("checksum len {} sum {sum:.6} sum_sq {sum_sq:.6} peak {peak:.6}", samples.len());
398
399 // Per-kind GPU tables, captured after each stage's own submit above — only with
400 // MODELRUNNER_TIMESTAMPS=1, and in a separate run from the wall times.
401 let _ = (chars, frames);
402 print_kinds("duration", &stages.duration_times);
403 print_kinds("text", &stages.text_times);
404 print_kinds("sampler dual step", &stages.sampler_times);
405 print_kinds("vocoder", &stages.vocoder_times);
406
407 assert_eq!(stages.sampler_ms.len(), STEPS as usize, "one dual submit per step");
408
409 // Further, differently sized sentences in the same process (`MODELRUNNER_SECOND`, split on
410 // `|`): what each new sentence length costs once everything is warm.
411 let more = std::env::var("MODELRUNNER_SECOND").unwrap_or_default();
412 for second in more.split('|').filter(|s| !s.is_empty()) {
413 let reshaped = stages.reshape_ms;
414 let (text, sampler, vocoder) =
415 (stages.reshape_text_ms, stages.reshape_sampler_ms, stages.reshape_vocoder_ms);
416 let whole = Instant::now();
417 let samples = supertonic::synthesise(
418 &mut stages,
419 &conditioning,
420 &indexer,
421 &voice,
422 second,
423 LANGUAGE,
424 &|count| noise.borrow_mut().normal(count),
425 )?;
426 println!(
427 "second {:>8.1} ms, {} samples, reshape {:.1} ms (ttl {:.1}, ve {:.1}, voc {:.1})",
428 ms(whole),
429 samples.len(),
430 stages.reshape_ms - reshaped,
431 stages.reshape_text_ms - text,
432 stages.reshape_sampler_ms - sampler,
433 stages.reshape_vocoder_ms - vocoder
434 );
435 }
436 Ok(())
437}
438
439fn checksum(samples: &[f32]) -> (f64, f64, f32) {
440 let sum = samples.iter().map(|&v| f64::from(v)).sum::<f64>();
441 let sum_sq = samples
442 .iter()
443 .map(|&v| {
444 let d = f64::from(v);
445 d * d
446 })
447 .sum::<f64>();
448 let peak = samples.iter().fold(0.0f32, |top, &v| top.max(v.abs()));
449 (sum, sum_sq, peak)
450}
451
452fn print_kinds(label: &str, times: &[(String, f64, f64)]) {
453 if times.is_empty() {
454 println!("{label}: no timestamps recorded: set MODELRUNNER_TIMESTAMPS=1");
455 return;
456 }
457 let mut kinds: BTreeMap<String, (usize, f64)> = BTreeMap::new();
458 let (mut total, mut gaps) = (0.0, 0.0);
459 for (name, us, gap) in times {
460 let kind = name.split(": ").nth(1).unwrap_or(name).to_string();
461 let entry = kinds.entry(kind).or_default();
462 entry.0 += 1;
463 entry.1 += us;
464 total += us;
465 gaps += gap;
466 }
467 let mut rows: Vec<_> = kinds.into_iter().collect();
468 rows.sort_by(|a, b| b.1 .1.total_cmp(&a.1 .1));
469 println!();
470 println!(
471 "{label}: {} dispatches, {:.2} ms in shaders, {:.2} ms in gaps",
472 times.len(),
473 total / 1e3,
474 gaps / 1e3
475 );
476 println!(" {:<22} {:>6} {:>10} {:>10}", "kind", "count", "total ms", "mean us");
477 for (kind, (count, us)) in rows {
478 println!(" {kind:<22} {count:>6} {:>10.3} {:>10.1}", us / 1e3, us / count as f64);
479 }
480 let mut by_time: Vec<_> = times.iter().collect();
481 by_time.sort_by(|a, b| b.1.total_cmp(&a.1));
482 println!(" top dispatches:");
483 for (name, us, _) in by_time.iter().take(12) {
484 println!(" {name:<28} {us:>10.1} us");
485 }
486}
487
488fn ms(since: Instant) -> f64 {
489 since.elapsed().as_secs_f64() * 1e3
490}
491
492fn sum(values: &[f64]) -> f64 {
493 values.iter().sum()
494}