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

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

profile_supertonic.rs476 lines · 18.6 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.is_multiple_of(stride) {
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 = positions(
231 "a conditioning",
232 conditional_text.len(),
233 supertonic_sampler::TEXT as usize,
234 )?;
235 let reshaping = Instant::now();
236 let net = self.sampler.at((frames, chars))?;
237 let each = ms(reshaping);
238 self.reshape_ms += each;
239 self.reshape_sampler_ms += each;
240 let running = Instant::now();
241 let latent = supertonic_sampler::pad_frames(latent, frames)?;
242 let query_angles = supertonic_sampler::pad_frames(query_angles, frames)?;
243 let (latent, query_angles) = (latent.as_slice(), query_angles.as_slice());
244 let out = net.infer_raw_many(&[
245 latent,
246 conditional_text,
247 conditional_keys,
248 conditional_style,
249 shifts,
250 query_angles,
251 key_angles,
252 latent,
253 unconditional_text,
254 unconditional_keys,
255 unconditional_style,
256 shifts,
257 query_angles,
258 key_angles,
259 ])?;
260 self.sampler_ms.push(ms(running));
261 // One step's table stands for all sixteen: same plan, same shape.
262 if let Ok(times) = net.op_times() {
263 self.sampler_times = times;
264 }
265 let [conditional, unconditional] =
266 <[Vec<f32>; 2]>::try_from(out).map_err(|other| {
267 format!("the dual sampler returned {} tensors, not two", other.len())
268 })?;
269 Ok([
270 supertonic_sampler::unpad_frames(&conditional, frames)?,
271 supertonic_sampler::unpad_frames(&unconditional, frames)?,
272 ])
273 }
274
275 fn vocoder(&mut self, latent: &[f32], frames: u32) -> Result<Vec<f32>, String> {
276 let reshaping = Instant::now();
277 let net = self.vocoder.at(supertonic_vocoder::padded_frames(frames))?;
278 let each = ms(reshaping);
279 self.reshape_ms += each;
280 self.reshape_vocoder_ms += each;
281 let unpacking = Instant::now();
282 let unpacked = supertonic_vocoder::unpack_latent_padded(latent, frames as usize)?;
283 self.unpack_ms += ms(unpacking);
284 let running = Instant::now();
285 let channelled = one_output(net.infer_raw(&unpacked)?)?;
286 self.vocoder_ms += ms(running);
287 if let Ok(times) = net.op_times() {
288 self.vocoder_times = times;
289 }
290 let interleaving = Instant::now();
291 let out = supertonic_vocoder::interleave_padded(&channelled, frames as usize)?;
292 self.interleave_ms += ms(interleaving);
293 Ok(out)
294 }
295}
296
297fn main() {
298 if let Err(why) = run() {
299 println!("failed: {why}");
300 }
301}
302
303fn run() -> Result<(), String> {
304 let args: Vec<String> = std::env::args().skip(1).collect();
305 let dir = args
306 .first()
307 .map(String::as_str)
308 .or_else(|| option_env!("MODELRUNNER_ASSETS"))
309 .map(str::to_owned)
310 .or_else(|| std::env::var("MODELRUNNER_ASSETS").ok())
311 .ok_or("pass the supertonic asset dir or set MODELRUNNER_ASSETS")?;
312 let voice = args.get(1).map(String::as_str).unwrap_or("F1");
313 let file = |name: &str| {
314 let path = format!("{dir}/{name}");
315 std::fs::read(&path).map_err(|e| format!("cannot read {path}: {e}"))
316 };
317
318 let dp = Weights::parse(&file("supertonic_dp.maml")?, graph::SUPERTONIC_DP)?;
319 let ttl = Weights::parse(&file("supertonic_ttl.maml")?, graph::SUPERTONIC_TTL)?;
320 let ve = Weights::parse(&file("supertonic_ve.maml")?, graph::SUPERTONIC_VE)?;
321 let voc = Weights::parse(&file("supertonic_voc.maml")?, graph::SUPERTONIC_VOC)?;
322 let indexer = file("unicode_indexer.bin")?;
323 let voice = Voice::read(&file(&format!("style_{voice}.bin"))?)?;
324 let conditioning = supertonic::Conditioning::read(ve.reader())?;
325
326 let context = context::shared()?;
327 let started = Instant::now();
328 let mut stages = Timed {
329 duration: Reshaped::new(context.clone(), &dp, SMALLEST, duration_plan)?,
330 text: Reshaped::new(context.clone(), &ttl, SMALLEST, text_plan)?,
331 sampler: Reshaped::new(context.clone(), &ve, (SMALLEST, SMALLEST), sampler_plan)?,
332 vocoder: Reshaped::new(context, &voc, SMALLEST, vocoder_plan)?,
333 duration_times: Vec::new(),
334 text_times: Vec::new(),
335 sampler_times: Vec::new(),
336 vocoder_times: Vec::new(),
337 duration_ms: 0.0,
338 text_ms: 0.0,
339 sampler_ms: Vec::new(),
340 vocoder_ms: 0.0,
341 reshape_ms: 0.0,
342 reshape_duration_ms: 0.0,
343 reshape_text_ms: 0.0,
344 reshape_sampler_ms: 0.0,
345 reshape_vocoder_ms: 0.0,
346 unpack_ms: 0.0,
347 interleave_ms: 0.0,
348 };
349 let load_ms = ms(started);
350 println!("load {load_ms:>8.1} ms (upload + first record)");
351
352 let noise = std::cell::RefCell::new(SplitMix { state: NOISE_SEED });
353 let whole = Instant::now();
354 let samples = supertonic::synthesise(
355 &mut stages,
356 &conditioning,
357 &indexer,
358 &voice,
359 SENTENCE,
360 LANGUAGE,
361 &|count| noise.borrow_mut().normal(count),
362 )?;
363 let total_ms = ms(whole);
364
365 let ids = supertonic::to_ids(&indexer, SENTENCE, LANGUAGE)?;
366 let chars = ids.len() as u32;
367 let frames = samples.len() as u32 / supertonic_vocoder::SAMPLES_PER_FRAME;
368 println!("sentence {SENTENCE:?} -> {chars} ids -> {frames} frames -> {} samples", samples.len());
369 println!("duration {:>8.1} ms", stages.duration_ms);
370 println!("text {:>8.1} ms", stages.text_ms);
371 println!("sampler {:>8.1} ms over {} steps (dual submit each)", sum(&stages.sampler_ms), stages.sampler_ms.len());
372 for (step, each) in stages.sampler_ms.iter().enumerate() {
373 println!(" step {step:>2} {each:>8.1} ms");
374 }
375 println!("vocoder {:>8.1} ms (unpack {:.1}, infer {:.1}, interleave {:.1})",
376 stages.unpack_ms + stages.vocoder_ms + stages.interleave_ms,
377 stages.unpack_ms,
378 stages.vocoder_ms,
379 stages.interleave_ms);
380 println!("reshape {:>8.1} ms (dp {:.1}, ttl {:.1}, ve {:.1}, voc {:.1}; plan build + re-record)",
381 stages.reshape_ms,
382 stages.reshape_duration_ms,
383 stages.reshape_text_ms,
384 stages.reshape_sampler_ms,
385 stages.reshape_vocoder_ms);
386 println!("total {total_ms:>8.1} ms");
387 println!("first audio {total_ms:>8.1} ms (non-streaming: the waveform exists only after the vocoder)");
388
389 let (sum, sum_sq, peak) = checksum(&samples);
390 println!("checksum len {} sum {sum:.6} sum_sq {sum_sq:.6} peak {peak:.6}", samples.len());
391
392 // Per-kind GPU tables, captured after each stage's own submit above — only with
393 // MODELRUNNER_TIMESTAMPS=1, and in a separate run from the wall times.
394 let _ = (chars, frames);
395 print_kinds("duration", &stages.duration_times);
396 print_kinds("text", &stages.text_times);
397 print_kinds("sampler dual step", &stages.sampler_times);
398 print_kinds("vocoder", &stages.vocoder_times);
399
400 assert_eq!(stages.sampler_ms.len(), STEPS as usize, "one dual submit per step");
401
402 // Further, differently sized sentences in the same process (`MODELRUNNER_SECOND`, split on
403 // `|`): what each new sentence length costs once everything is warm.
404 let more = std::env::var("MODELRUNNER_SECOND").unwrap_or_default();
405 for second in more.split('|').filter(|s| !s.is_empty()) {
406 let reshaped = stages.reshape_ms;
407 let (text, sampler, vocoder) =
408 (stages.reshape_text_ms, stages.reshape_sampler_ms, stages.reshape_vocoder_ms);
409 let whole = Instant::now();
410 let samples = supertonic::synthesise(
411 &mut stages,
412 &conditioning,
413 &indexer,
414 &voice,
415 second,
416 LANGUAGE,
417 &|count| noise.borrow_mut().normal(count),
418 )?;
419 println!(
420 "second {:>8.1} ms, {} samples, reshape {:.1} ms (ttl {:.1}, ve {:.1}, voc {:.1})",
421 ms(whole),
422 samples.len(),
423 stages.reshape_ms - reshaped,
424 stages.reshape_text_ms - text,
425 stages.reshape_sampler_ms - sampler,
426 stages.reshape_vocoder_ms - vocoder
427 );
428 }
429 Ok(())
430}
431
432fn checksum(samples: &[f32]) -> (f64, f64, f32) {
433 let sum = samples.iter().map(|&v| f64::from(v)).sum::<f64>();
434 let sum_sq = samples.iter().map(|&v| { let d = f64::from(v); d * d }).sum::<f64>();
435 let peak = samples.iter().fold(0.0f32, |top, &v| top.max(v.abs()));
436 (sum, sum_sq, peak)
437}
438
439fn print_kinds(label: &str, times: &[(String, f64, f64)]) {
440 if times.is_empty() {
441 println!("{label}: no timestamps recorded: set MODELRUNNER_TIMESTAMPS=1");
442 return;
443 }
444 let mut kinds: BTreeMap<String, (usize, f64)> = BTreeMap::new();
445 let (mut total, mut gaps) = (0.0, 0.0);
446 for (name, us, gap) in times {
447 let kind = name.split(": ").nth(1).unwrap_or(name).to_string();
448 let entry = kinds.entry(kind).or_default();
449 entry.0 += 1;
450 entry.1 += us;
451 total += us;
452 gaps += gap;
453 }
454 let mut rows: Vec<_> = kinds.into_iter().collect();
455 rows.sort_by(|a, b| b.1 .1.total_cmp(&a.1 .1));
456 println!();
457 println!("{label}: {} dispatches, {:.2} ms in shaders, {:.2} ms in gaps", times.len(), total / 1e3, gaps / 1e3);
458 println!(" {:<22} {:>6} {:>10} {:>10}", "kind", "count", "total ms", "mean us");
459 for (kind, (count, us)) in rows {
460 println!(" {kind:<22} {count:>6} {:>10.3} {:>10.1}", us / 1e3, us / count as f64);
461 }
462 let mut by_time: Vec<_> = times.iter().collect();
463 by_time.sort_by(|a, b| b.1.total_cmp(&a.1));
464 println!(" top dispatches:");
465 for (name, us, _) in by_time.iter().take(12) {
466 println!(" {name:<28} {us:>10.1} us");
467 }
468}
469
470fn ms(since: Instant) -> f64 {
471 since.elapsed().as_secs_f64() * 1e3
472}
473
474fn sum(values: &[f64]) -> f64 {
475 values.iter().sum()
476}