Modern Apps git

← Modern-Apps.git

library:ml: Supertonic's JNI surface, reshaping each net per utterance

Commit
fcd7be5a2068d00422ccddcaf3853b2229cddb9e
Author
vayun-mathur <[email protected]>
When
2026-08-28 19:25 UTC (3 months ago)
Parents
d9204a4

Diff

library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.ktindex de5c87c09e..d29bfe8c09 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt@@ -124,6 +124,50 @@ internal object MlNative {      */     external fun synthesize(handle: Long, text: String, speed: Float): FloatArray? +    /**+     * Bring up Supertonic 3 from its four `.maml` files, the codepoint table and one voice.+     * Returns 0 on failure.+     *+     * Six assets, and no shape arguments: unlike [createPiper], every Supertonic plan is+     * utterance-shaped, so each net is re-recorded per sentence rather than compiled once at a+     * padded width. There is also no phoneme dictionary - the front end is [indexer], a flat+     * 65,536-entry codepoint table, which is why [synthesizeSupertonic] insists on NFD.+     *+     * [style] is one voice's `style_<name>.bin`. It is separate from the plans and swappable+     * through [setSupertonicVoice], because a voice is 25 KB against the plans' 198 MB.+     *+     * Freed by [destroySupertonic], not [destroy], [destroyOcr] or [destroyPiper].+     */+    external fun createSupertonic(+        duration: ByteArray,+        text: ByteArray,+        sampler: ByteArray,+        vocoder: ByteArray,+        indexer: ByteArray,+        style: ByteArray,+    ): Long++    /**+     * Point a live handle at another voice, returning false on failure.+     *+     * Cheap, and the reason a voice change does not mean a new handle: the four networks stay+     * uploaded and only the two style tensors are replaced.+     */+    external fun setSupertonicVoice(handle: Long, style: ByteArray): Boolean++    /**+     * Synthesise [text] and return mono samples in `-1..1` at 44,100 Hz, or null on failure.+     *+     * [text] **must already be NFD**-decomposed - use `java.text.Normalizer.normalize(text,+     * Form.NFD)`. The model has no precomposed accents: `é` is unmapped while `e` and the+     * combining acute are both first-class tokens, so precomposed text silently loses+     * characters. Doing the decomposition natively would mean carrying Unicode tables in the+     * APK when the platform already has them.+     *+     * Two calls with the same text differ, as flow matching starts from a sampled latent.+     */+    external fun synthesizeSupertonic(handle: Long, text: String): FloatArray?+     /**      * Detect faces in [pixels] and return them flattened, nine floats per face.      *@@ -182,4 +226,13 @@ internal object MlNative {      * different things, and passing one to the wrong destroy is undefined.      */     external fun destroyPiper(handle: Long)++    /**+     * Free Supertonic's four networks, its conditioning, its codepoint table and its voice.+     * Exactly once per non-zero handle from [createSupertonic].+     *+     * A fourth destroy function, for the same reason there is a third: the handle types own+     * different things and passing one to the wrong destroy is undefined.+     */+    external fun destroySupertonic(handle: Long) }
library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.ktnew file mode 100644index 0000000000..2a9db79430--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.kt@@ -0,0 +1,135 @@+package com.vayunmathur.library.ml++import android.util.Log+import java.io.File+import java.text.Normalizer++/**+ * On-device text-to-speech: Supertonic 3 on the Vulkan compute runtime.+ *+ * Replaces [PiperSynthesizer]. One ~198 MB fp16 bundle covers 30 languages and 10 voices, where+ * Piper needed a separate model and phoneme dictionary per language. Four networks, all on the+ * GPU and all checked numerically against onnxruntime — see+ * `library/ml/src/main/rust/src/nets/supertonic_*.rs`:+ *+ * - **Duration predictor** returns one number, the utterance's length in seconds, which fixes+ *   every later shape.+ * - **Text encoder** turns the characters into a `[256, chars]` conditioning.+ * - **Flow-matching sampler** is the expensive one: 16 steps, each running two guidance branches,+ *   so 32 passes of 64 million parameters for one sentence.+ * - **ConvNeXt vocoder** turns the latent into 44,100 Hz samples.+ *+ * # There is no phonemiser+ *+ * The front end is a flat 65,536-entry codepoint table, not espeak-ng, so nothing has to be+ * generated per language on the build machine. The model does expect **NFD**-decomposed text,+ * which [synthesize] does itself through `java.text.Normalizer`: precomposed accents are unmapped+ * while combining marks are first-class tokens, so skipping it would quietly drop characters.+ *+ * # Voices+ *+ * A voice is two small style tensors, not a model, so [voice] switches without re-uploading+ * anything. That is why a voice change is a method here and was a new object in Piper.+ *+ * # Availability+ *+ * The constructor never throws. [isAvailable] is false when `libmodelrunner.so` is missing for+ * this ABI, when a file is absent, or when the device cannot give us a Vulkan device with fp16+ * compute — and then [synthesize] returns an empty array.+ *+ * # Threading+ *+ * Not thread-safe. A caller must hold a lock across [synthesize], [voice] and [close]: the handle+ * is freed by [close] and reading it afterwards is a use-after-free.+ */+class SupertonicSynthesizer(+    private val directory: File,+    voice: String = DEFAULT_VOICE,+) : AutoCloseable {+    private var handle: Long = 0L++    /** Supertonic's output rate, fixed by the vocoder rather than by the voice. */+    val sampleRate: Int = SAMPLE_RATE++    init {+        handle = if (!MlNative.isAvailable) {+            0L+        } else {+            try {+                MlNative.createSupertonic(+                    read(directory, "supertonic_dp.maml"),+                    read(directory, "supertonic_ttl.maml"),+                    read(directory, "supertonic_ve.maml"),+                    read(directory, "supertonic_voc.maml"),+                    read(directory, "unicode_indexer.bin"),+                    read(directory, styleName(voice)),+                )+            } catch (e: Throwable) {+                Log.e(TAG, "cannot open the Supertonic bundle in $directory", e)+                0L+            }+        }+    }++    /** True if all four networks came up, the codepoint table is the right size and a voice read. */+    val isAvailable: Boolean get() = handle != 0L++    /**+     * Switch to another voice, returning false if it could not be read.+     *+     * Cheap: the four networks stay on the GPU and only the two style tensors are replaced, so+     * this is a 25 KB read rather than a 198 MB one.+     */+    fun voice(name: String): Boolean {+        if (handle == 0L) return false+        return try {+            MlNative.setSupertonicVoice(handle, read(directory, styleName(name)))+        } catch (e: Throwable) {+            Log.e(TAG, "cannot read the voice $name in $directory", e)+            false+        }+    }++    /**+     * Synthesise [text] and return mono samples in `-1..1` at [sampleRate].+     *+     * Returns an empty array when there is nothing in the model's vocabulary, when the engine is+     * unavailable, or when the pass failed — all three are "no audio" to a caller, and the reason+     * is in logcat under `ModelRunner`.+     *+     * Long text should be split into sentences first. Nothing refuses a paragraph, but every+     * shape here scales with the utterance and the sampler runs 32 passes over all of it.+     *+     * Two calls with the same text differ, as flow matching starts from a sampled latent.+     */+    fun synthesize(text: String): FloatArray {+        if (handle == 0L || text.isBlank()) return FloatArray(0)+        val decomposed = Normalizer.normalize(text, Normalizer.Form.NFD)+        return MlNative.synthesizeSupertonic(handle, decomposed) ?: FloatArray(0)+    }++    /** Free all four networks. Idempotent. */+    override fun close() {+        val live = handle+        handle = 0L+        if (live != 0L) MlNative.destroySupertonic(live)+    }++    private companion object {+        private const val TAG = "SupertonicSynthesizer"++        /** The vocoder's rate: 44,100 Hz, at 3,072 samples per latent frame. */+        const val SAMPLE_RATE = 44_100++        /** The one voice style that ships with the bundle; the other nine are downloaded. */+        const val DEFAULT_VOICE = "F1"++        fun styleName(voice: String): String = "style_$voice.bin"++        fun read(directory: File, name: String): ByteArray {+            val file = File(directory, name)+            require(file.isFile) { "$name is missing from $directory" }+            return file.readBytes()+        }+    }+}
library/ml/src/main/rust/src/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsindex 6874b48740..9b2bdc499c 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -31,18 +31,20 @@ use jni::sys::{jfloat, jfloatArray, jint, jlong, jstring}; use jni::JNIEnv;  use crate::nets::{-    mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, u2netp, vits_dec, vits_enc, vits_flow,+    mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration, supertonic_sampler,+    supertonic_text, supertonic_vocoder, u2netp, vits_dec, vits_enc, vits_flow, Plan, }; use crate::post::ctc::Dictionary; use crate::post::nms::{self, Face, Maps}; use crate::post::ocr::{self, Line};-use crate::post::{phonemes, speech};+use crate::post::{phonemes, speech, supertonic}; use crate::preprocess::{     Letterbox, FACE_EMBED, IMAGENET, PPOCR_DET, PPOCR_REC, RESCALE_ONLY, SCRFD, }; use crate::vulkan::context;+use crate::vulkan::reshape::Reshaped; use crate::vulkan::run::Net;-use crate::weights::{graph, Weights};+use crate::weights::{graph, Offsets, Weights};  /// One segmenter. Handed to Kotlin as an opaque `jlong`. struct Handle {@@ -549,10 +551,12 @@ impl SplitMix {         z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);         z ^ (z >> 31)     }-} -impl speech::Noise for SplitMix {     /// Box-Muller over two uniforms, which is exact rather than an approximation of normal.+    ///+    /// Inherent rather than only a [`speech::Noise`] method because Supertonic needs the same+    /// generator and does not go through that trait — its flow matching samples one starting+    /// latent per utterance, where VITS samples a prior and its durations.     fn normal(&mut self, count: usize) -> Vec<f32> {         let mut out = Vec::with_capacity(count);         while out.len() < count {@@ -570,6 +574,12 @@ impl speech::Noise for SplitMix {     } } +impl speech::Noise for SplitMix {+    fn normal(&mut self, count: usize) -> Vec<f32> {+        SplitMix::normal(self, count)+    }+}+ /// The three plans, as `post::speech` wants them. struct SpeechNets<'a> {     encoder: &'a mut Net,@@ -838,6 +848,328 @@ fn trim(values: &[f32], channels: usize, wide: usize, keep: usize) -> Vec<f32> {     out } +/// Supertonic's four nets, the conditioning read once, and the voice bundle.+///+/// Its own handle type for the same reason [`OcrHandle`] and [`SpeechHandle`] are: it owns a+/// different set of things, and one `destroy` guessing between them would be type confusion+/// waiting for a caller to mix them up.+///+/// Each net is a [`Reshaped`] rather than a [`Net`], because every Supertonic plan is+/// utterance-shaped and there is no width to compile once and pad to — unlike Piper, whose+/// encoder is built at the longest phoneme count a voice allows.+struct SupertonicHandle {+    duration: Reshaped<u32>,+    text: Reshaped<u32>,+    /// Frames and characters, which vary independently.+    sampler: Reshaped<(u32, u32)>,+    vocoder: Reshaped<u32>,+    /// What the sampler needs from its weights file that no shader sees, walked once per handle.+    conditioning: supertonic::Conditioning,+    /// The 65,536-entry codepoint table, read as bytes with no parsing.+    indexer: Vec<u8>,+    voice: supertonic::Voice,+    rng: SplitMix,+}++/// The smallest legal shape, for the plan recorded at construction and immediately replaced.+///+/// [`Net::new`] needs a plan, and the real one is not known until an utterance arrives. Recording+/// the smallest is cheapest, and [`Net::rebuild`] only ever grows the arena, so nothing is wasted+/// by starting here.+const SMALLEST: u32 = 1;++fn duration_plan(offsets: &Offsets, chars: u32) -> Result<Plan, String> {+    supertonic_duration::build(offsets, chars)+}++fn text_plan(offsets: &Offsets, chars: u32) -> Result<Plan, String> {+    supertonic_text::build(offsets, chars)+}++fn sampler_plan(offsets: &Offsets, shape: (u32, u32)) -> Result<Plan, String> {+    supertonic_sampler::build(offsets, shape.0, shape.1)+}++fn vocoder_plan(offsets: &Offsets, frames: u32) -> Result<Plan, String> {+    supertonic_vocoder::build(offsets, frames)+}++/// The four nets, as `post::supertonic` wants them.+struct SupertonicNets<'a> {+    duration: &'a mut Reshaped<u32>,+    text: &'a mut Reshaped<u32>,+    sampler: &'a mut Reshaped<(u32, u32)>,+    vocoder: &'a mut Reshaped<u32>,+}++/// Positions per id tensor: `crate::nets::embed_lanes` writes two lanes, `lo + 2048 * hi`.+const LANES: usize = 2;++/// `values / stride`, refusing a remainder.+///+/// Every shape below is recovered from an input's length rather than passed alongside it, so the+/// net is always recorded at what the data actually is and cannot drift from what `synthesise`+/// computed. A remainder means the caller and the forward pass disagree about a channel count,+/// which is worth an error rather than a truncating division.+fn positions(what: &str, values: usize, stride: usize) -> Result<u32, String> {+    if stride == 0 || values == 0 || !values.is_multiple_of(stride) {+        return Err(format!("{what}: {values} values is not a whole number of {stride}"));+    }+    Ok((values / stride) as u32)+}++impl supertonic::Stages for SupertonicNets<'_> {+    fn duration(&mut self, lanes: &[f32], style: &[f32]) -> Result<f32, String> {+        // This sequence leads with the sentence token, which `build` adds itself, so it is given+        // the character count without it.+        let sequence = positions("duration ids", lanes.len(), LANES)?;+        let chars = sequence.checked_sub(1).ok_or("a duration pass over only a sentence token")?;+        let net = self.duration.at(chars)?;+        let out = one_output(net.infer_raw_many(&[lanes, style])?)?;+        match out.as_slice() {+            [only] => Ok(*only),+            other => {+                Err(format!("the duration predictor returned {} values, not one", other.len()))+            }+        }+    }++    fn text(&mut self, lanes: &[f32], style: &[f32]) -> Result<Vec<f32>, String> {+        let chars = positions("text ids", lanes.len(), LANES)?;+        let net = self.text.at(chars)?;+        one_output(net.infer_raw_many(&[lanes, style])?)+    }++    fn sampler(+        &mut self,+        latent: &[f32],+        text: &[f32],+        keys: &[f32],+        style: &[f32],+        shifts: &[f32],+        query_angles: &[f32],+        key_angles: &[f32],+    ) -> Result<Vec<f32>, String> {+        let frames = positions("a latent", latent.len(), supertonic_sampler::LATENT as usize)?;+        let chars = positions("a conditioning", text.len(), supertonic_sampler::TEXT as usize)?;+        let net = self.sampler.at((frames, chars))?;+        // Declaration order, which `infer_raw_many` checks each of against its own binding — the+        // seven are all fp16 planes and a swapped pair would be the right size.+        one_output(net.infer_raw_many(&[+            latent,+            text,+            keys,+            style,+            shifts,+            query_angles,+            key_angles,+        ])?)+    }++    fn vocoder(&mut self, latent: &[f32], frames: u32) -> Result<Vec<f32>, String> {+        let net = self.vocoder.at(frames)?;+        one_output(net.infer_raw(latent)?)+    }+}++/// `SupertonicSynthesizer`'s constructor. Returns 0 on failure, having logged why.+///+/// Six assets: the four `.maml` plans, the codepoint table and one voice's style file. The voice+/// is separate from the plans and swappable through+/// [`Java_com_vayunmathur_library_ml_MlNative_setSupertonicVoice`], because it is 25 KB against+/// the plans' 198 MB and re-uploading those to change voice would be absurd.+///+/// # Safety+///+/// Called only by the JVM, with a valid `env` and arrays it owns.+#[no_mangle]+#[allow(clippy::too_many_arguments)]+pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createSupertonic<'l>(+    mut env: JNIEnv<'l>,+    _class: JClass<'l>,+    duration: JByteArray<'l>,+    text: JByteArray<'l>,+    sampler: JByteArray<'l>,+    vocoder: JByteArray<'l>,+    indexer: JByteArray<'l>,+    style: JByteArray<'l>,+) -> jlong {+    let assets = [duration, text, sampler, vocoder, indexer, style];+    match build_supertonic(&mut env, assets) {+        Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,+        Err(e) => {+            log(&format!("supertonic is unavailable: {e}"));+            0+        }+    }+}++fn build_supertonic<'l>(+    env: &mut JNIEnv<'l>,+    assets: [JByteArray<'l>; 6],+) -> Result<SupertonicHandle, String> {+    let mut bytes = Vec::with_capacity(assets.len());+    for asset in &assets {+        bytes.push(+            env.convert_byte_array(asset).map_err(|e| format!("cannot read an asset: {e}"))?,+        );+    }+    let duration_weights = Weights::parse(&bytes[0], graph::SUPERTONIC_DP)?;+    let text_weights = Weights::parse(&bytes[1], graph::SUPERTONIC_TTL)?;+    let sampler_weights = Weights::parse(&bytes[2], graph::SUPERTONIC_VE)?;+    let vocoder_weights = Weights::parse(&bytes[3], graph::SUPERTONIC_VOC)?;+    if bytes[4].len() != supertonic::INDEXER_ENTRIES * 2 {+        return Err(format!("a codepoint table of {} bytes", bytes[4].len()));+    }+    let voice = supertonic::Voice::read(&bytes[5])?;+    // Read before the weights are dropped: the sampler's timestep shifts, rotary frequencies and+    // folded style keys are all tensors in its file that no shader ever reads.+    let conditioning = supertonic::Conditioning::read(&sampler_weights)?;++    let shared = context::shared()?;+    let handle = SupertonicHandle {+        duration: Reshaped::new(shared.clone(), &duration_weights, SMALLEST, duration_plan)?,+        text: Reshaped::new(shared.clone(), &text_weights, SMALLEST, text_plan)?,+        sampler: Reshaped::new(+            shared.clone(),+            &sampler_weights,+            (SMALLEST, SMALLEST),+            sampler_plan,+        )?,+        vocoder: Reshaped::new(shared, &vocoder_weights, SMALLEST, vocoder_plan)?,+        conditioning,+        indexer: std::mem::take(&mut bytes[4]),+        voice,+        rng: SplitMix { state: seed() },+    };+    Ok(handle)+}++/// Point an existing handle at another voice. Returns false on failure, having logged why.+///+/// # Safety+///+/// `handle` must be `0` or a live value from+/// [`Java_com_vayunmathur_library_ml_MlNative_createSupertonic`].+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_setSupertonicVoice<'l>(+    env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+    style: JByteArray<'l>,+) -> jni::sys::jboolean {+    if handle == 0 {+        return 0;+    }+    // SAFETY: as `synthesizeSupertonic` — the caller guarantees the handle is live and serialises+    // this against `destroySupertonic`.+    let state = unsafe { &mut *(handle as *mut SupertonicHandle) };+    let read = env+        .convert_byte_array(&style)+        .map_err(|e| format!("cannot read the voice: {e}"))+        .and_then(|bytes| supertonic::Voice::read(&bytes));+    match read {+        Ok(voice) => {+            state.voice = voice;+            1+        }+        Err(e) => {+            log(&format!("cannot change voice: {e}"));+            0+        }+    }+}++/// Free the four networks and everything beside them.+///+/// # Safety+///+/// `handle` must be `0` or a value from+/// [`Java_com_vayunmathur_library_ml_MlNative_createSupertonic`], and must not be used again.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroySupertonic<'l>(+    _env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+) {+    if handle == 0 {+        return;+    }+    // SAFETY: the caller guarantees this came from `createSupertonic` and has not been destroyed.+    drop(unsafe { Box::from_raw(handle as *mut SupertonicHandle) });+}++/// Synthesise `text` and return the waveform, or null on failure.+///+/// `text` must already be **NFD**-decomposed. That is the Kotlin side's job, through+/// `java.text.Normalizer`, because the model has no precomposed accents and doing the+/// decomposition here would mean carrying Unicode tables in the APK — see+/// [`supertonic::to_ids`].+///+/// The samples are mono `-1..1` at 44,100 Hz. Two calls with the same text differ: flow matching+/// starts from a sampled latent, which it is meant to.+///+/// # Safety+///+/// `handle` must be `0` or a live value from+/// [`Java_com_vayunmathur_library_ml_MlNative_createSupertonic`].+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_synthesizeSupertonic<'l>(+    mut env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+    text: JString<'l>,+) -> jfloatArray {+    let null = std::ptr::null_mut();+    if handle == 0 {+        return null;+    }+    // SAFETY: as `segment` — the caller guarantees the handle is live and serialises this against+    // `destroySupertonic`.+    let state = unsafe { &mut *(handle as *mut SupertonicHandle) };+    let words: String = match env.get_string(&text) {+        Ok(found) => found.into(),+        Err(e) => {+            log(&format!("cannot read the text: {e}"));+            return null;+        }+    };+    match speak_supertonic(state, &words) {+        Ok(samples) => match new_float_array(&mut env, &samples) {+            Ok(array) => array,+            Err(e) => {+                log(&e);+                null+            }+        },+        Err(e) => {+            log(&format!("synthesis failed: {e}"));+            null+        }+    }+}++/// The whole pipeline for one utterance.+fn speak_supertonic(state: &mut SupertonicHandle, text: &str) -> Result<Vec<f32>, String> {+    let SupertonicHandle {+        duration,+        text: encoder,+        sampler,+        vocoder,+        conditioning,+        indexer,+        voice,+        rng,+    } = state;+    // `synthesise` draws the starting latent once, after the duration predictor has settled the+    // frame count, so the generator has to be reachable from a `Fn` rather than pre-drawn.+    let noise = std::cell::RefCell::new(rng);+    let mut nets = SupertonicNets { duration, text: encoder, sampler, vocoder };+    supertonic::synthesise(&mut nets, conditioning, indexer, voice, text, &|count| {+        noise.borrow_mut().normal(count)+    })+}+ /// Copy a Java `int[]` of ARGB pixels into `into`, checking it against `width` x `height`. fn read_pixels<'l>(     env: &mut JNIEnv<'l>,
library/ml/src/main/rust/src/post/supertonic.rs
diff --git a/library/ml/src/main/rust/src/post/supertonic.rs b/library/ml/src/main/rust/src/post/supertonic.rsindex eafd03eafa..8303b4ca5c 100644--- a/library/ml/src/main/rust/src/post/supertonic.rs+++ b/library/ml/src/main/rust/src/post/supertonic.rs@@ -302,6 +302,34 @@ pub struct Voice {     pub text: Vec<f32>, } +impl Voice {+    /// Read one `style_<name>.bin` from the voice bundle.+    ///+    /// `style_ttl` transposed to `[256, 50]` first, then `style_dp` flattened to 128, both as+    /// little-endian fp16 and nothing else — no header, because the two shapes are fixed by the+    /// architecture and a length check is therefore as strong as a table would be.+    ///+    /// Not a `.maml`: these are **inputs**, one pair per voice, handed to+    /// [`crate::vulkan::run::Net::infer_raw_many`] per utterance rather than living in a plan's+    /// weights buffer. `scripts/ml/supertonic_bundle.py` writes them, and does the transpose+    /// there because the export stores `style_ttl` position-major and this runtime is+    /// channel-major.+    pub fn read(bytes: &[u8]) -> Result<Voice, String> {+        let text_values = (net::STYLE * net::STYLE_TOKENS) as usize;+        let duration_values = duration_net::STYLE as usize;+        let wanted = (text_values + duration_values) * 2;+        if bytes.len() != wanted {+            return Err(format!("a voice file of {} bytes, not {wanted}", bytes.len()));+        }+        let values: Vec<f32> = bytes+            .chunks_exact(2)+            .map(|pair| f16_to_f32(u16::from_le_bytes([pair[0], pair[1]])))+            .collect();+        let (text, duration) = values.split_at(text_values);+        Ok(Voice { duration: duration.to_vec(), text: text.to_vec() })+    }+}+ /// Synthesise one utterance. /// /// `text` must already be NFD; see [`to_ids`]. `noise` supplies the flow's starting latent, one@@ -434,6 +462,33 @@ mod tests {         assert!(error.contains("codepoint table"), "{error}");     } +    #[test]+    fn a_voice_file_splits_into_the_two_style_tensors() {+        // The order is style_ttl then style_dp, and the two are 12,800 and 128 values, so a file+        // read in the wrong order is exactly the right length. Only the values catch it — hence a+        // fixture where each tensor holds a constant of its own.+        let text_values = (net::STYLE * net::STYLE_TOKENS) as usize;+        let duration_values = duration_net::STYLE as usize;+        let mut bytes = Vec::new();+        for _ in 0..text_values {+            bytes.extend_from_slice(&crate::preprocess::f32_to_f16(0.25).to_le_bytes());+        }+        for _ in 0..duration_values {+            bytes.extend_from_slice(&crate::preprocess::f32_to_f16(-0.5).to_le_bytes());+        }++        let voice = Voice::read(&bytes).expect("the declared length");+        assert_eq!(voice.text.len(), text_values);+        assert_eq!(voice.duration.len(), duration_values);+        assert!(voice.text.iter().all(|&v| v == 0.25), "style_ttl comes first");+        assert!(voice.duration.iter().all(|&v| v == -0.5), "style_dp comes second");++        // A truncated or padded file is refused rather than read short: the shapes are fixed by+        // the architecture, so a length that disagrees means the wrong file, not a shorter voice.+        assert!(Voice::read(&bytes[..bytes.len() - 2]).is_err());+        assert!(Voice::read(&[]).is_err());+    }+     /// Records what the pipeline asked of each stage, and answers with fixed shapes.     struct Recording {         seconds: f32,
library/ml/src/main/rust/src/vulkan/mod.rs
diff --git a/library/ml/src/main/rust/src/vulkan/mod.rs b/library/ml/src/main/rust/src/vulkan/mod.rsindex 4222179aa5..35b50048fa 100644--- a/library/ml/src/main/rust/src/vulkan/mod.rs+++ b/library/ml/src/main/rust/src/vulkan/mod.rs@@ -18,6 +18,7 @@ pub mod buffers; pub mod context; pub mod pipeline;+pub mod reshape; pub mod run;  #[cfg(test)]
library/ml/src/main/rust/src/vulkan/reshape.rs
diff --git a/library/ml/src/main/rust/src/vulkan/reshape.rs b/library/ml/src/main/rust/src/vulkan/reshape.rsnew file mode 100644index 0000000000..715ccb5765--- /dev/null+++ b/library/ml/src/main/rust/src/vulkan/reshape.rs@@ -0,0 +1,71 @@+//! A [`Net`] that re-records itself when the utterance changes length.+//!+//! Every Supertonic net is utterance-shaped: the duration predictor and the text encoder run at+//! the character count, the sampler at the latent length and the character count, the vocoder at+//! the latent length. A [`Plan`] is one command buffer recorded at fixed shapes, so a plan is only+//! ever right for one utterance, and [`Net::rebuild`] is how the next one gets its own.+//!+//! Doing that by hand needs two things kept in step per net — the table to rebuild from, and the+//! shape it is currently recorded at — and getting the second wrong is silent: a net left at the+//! previous sentence's length runs this sentence's data through it and returns the wrong number of+//! frames, or the right number computed over positions the arena happened to hold. So they live+//! together here, and a caller asks for the net *at a shape* rather than asking for the net.++use std::sync::Arc;++use crate::nets::Plan;+use crate::preprocess::RESCALE_ONLY;+use crate::weights::{Offsets, Weights};++use super::context::Context;+use super::run::Net;++/// A net, the table to rebuild its plan from, and the shape it is recorded at.+///+/// `S` is whatever identifies a shape for this net — `u32` for the three that depend only on a+/// length, `(u32, u32)` for the sampler, which depends on the frame count and the character count+/// independently. It is compared, not interpreted, so a net cannot be reshaped to a shape it is+/// already at and cannot be left at one it is not.+pub struct Reshaped<S> {+    net: Net,+    offsets: Offsets,+    at: S,+    plan: fn(&Offsets, S) -> Result<Plan, String>,+}++impl<S: Copy + PartialEq> Reshaped<S> {+    /// Upload `weights`, record at `shape`, and keep only the table.+    ///+    /// The `Weights` is borrowed rather than held: [`Net::new`] copies the blob to device memory+    /// and [`Weights::offsets`] keeps the few kilobytes a rebuild actually reads, so the caller can+    /// drop 127 MB of host allocation the moment this returns. That is the whole reason rebuilding+    /// beats constructing a second net per utterance.+    ///+    /// [`RESCALE_ONLY`] because no bitmap ever reaches these nets — every input is a tensor a+    /// previous stage computed, handed over by [`Net::infer_raw_many`], so the preprocessing the+    /// vision nets need has nothing to do here.+    pub fn new(+        context: Arc<Context>,+        weights: &Weights,+        shape: S,+        plan: fn(&Offsets, S) -> Result<Plan, String>,+    ) -> Result<Reshaped<S>, String> {+        let offsets = weights.offsets();+        let net = Net::new(context, plan(&offsets, shape)?, weights, RESCALE_ONLY)?;+        Ok(Reshaped { net, offsets, at: shape, plan })+    }++    /// The net recorded at `shape`, re-recording it first if it is not already.+    ///+    /// Cheap when the shape is unchanged, which is the common case and the one that matters: the+    /// sampler is called `2 * STEPS` times at one shape for a single sentence, and the vocoder once+    /// per chunk at one shape, so re-recording per call would build thirty-odd command buffers+    /// where one is needed.+    pub fn at(&mut self, shape: S) -> Result<&mut Net, String> {+        if shape != self.at {+            self.net.rebuild((self.plan)(&self.offsets, shape)?)?;+            self.at = shape;+        }+        Ok(&mut self.net)+    }+}
library/ml/src/main/rust/src/weights.rs
diff --git a/library/ml/src/main/rust/src/weights.rs b/library/ml/src/main/rust/src/weights.rsindex a32e9ff2e6..3e9849a1f4 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -118,9 +118,9 @@ impl Tensor { /// The tensor table on its own, without the data section. /// /// [`crate::vulkan::run::Net::rebuild`] re-records a net at a new shape, and that means building a-/// fresh [`crate::nets::Plan`] — which needs a [`WeightSource`]. It does not need the blob: a-/// builder only ever consults offsets and shapes, and the blob is already in device memory by-/// then. Holding a whole [`Weights`] alive to rebuild from would keep 127 MB of host RSS for the+/// fresh [`crate::nets::Plan`] — which needs a [`crate::nets::WeightSource`]. It does not need the+/// blob: a builder only ever consults offsets and shapes, and the blob is already in device memory+/// by then. Holding a whole [`Weights`] alive to rebuild from would keep 127 MB of host RSS for the /// Supertonic sampler alone, beside the copy the device has, where the table is a few kilobytes. /// /// So a caller that means to rebuild takes one of these first and lets the `Weights` go.