library:ml: stream weights from a descriptor instead of copying them thrice
- Commit
a95c288cf5f250deba8766712102a153b61afeed- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 21:45 UTC (3 months ago)
- Parents
8e7afdb
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 d29bfe8c09..cd81f91864 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@@ -128,21 +128,35 @@ internal object MlNative { * 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.+ * 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.+ * The four plans arrive as **file descriptors** rather than byte arrays. A `ByteArray` would+ * allocate the model three times over - the Java array, the `Vec<u8>` JNI hands Rust, and the+ * reader's own copy of the data section - which for a ~105 MB bundle is ~300 MB of transient+ * heap and an out-of-memory kill rather than a slow load. Native reads the header and tensor+ * table only, then streams the weights into the GPU through a fixed-size staging buffer.+ *+ * [fds], [offsets] and [lengths] are parallel and in a fixed order: duration predictor, text+ * encoder, sampler, vocoder. All three are needed because an `AssetFileDescriptor` describes a+ * *range of the APK* rather than a file of its own; for a file on disk the offset is 0 and the+ * length is the file's size.+ *+ * **Each descriptor must be detached.** Native takes ownership and closes it, on the failure+ * paths as much as the successful one, so a caller must not close them itself. An asset also has+ * to be stored uncompressed for `openFd` to work at all - `noCompress += "maml"`.+ *+ * [indexer] and [style] stay byte arrays: 128 KB and 25 KB, where streaming saves nothing.+ * [style] is separate from the plans and swappable through [setSupertonicVoice]. * * Freed by [destroySupertonic], not [destroy], [destroyOcr] or [destroyPiper]. */ external fun createSupertonic(- duration: ByteArray,- text: ByteArray,- sampler: ByteArray,- vocoder: ByteArray,+ fds: IntArray,+ offsets: LongArray,+ lengths: LongArray, indexer: ByteArray, style: ByteArray, ): 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.ktindex 2a9db79430..0b205bfb43 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.kt@@ -1,16 +1,18 @@ package com.vayunmathur.library.ml +import android.content.res.AssetManager+import android.os.ParcelFileDescriptor import android.util.Log+import java.io.Closeable 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`:+ * Replaces [PiperSynthesizer]. One 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.@@ -26,6 +28,19 @@ import java.text.Normalizer * 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. *+ * # Two places the bundle can live+ *+ * [inAssets] reads it out of the APK and [inDirectory] out of a folder on disk. Both go to native+ * as **file descriptors** rather than byte arrays, which is not an optimisation: reading the weights+ * into a `ByteArray` allocates them three times over — the Java array, the copy JNI hands Rust, and+ * the reader's own — so a bundle of this size would need several hundred megabytes of transient+ * heap and be killed for it on a low-RAM device. Native reads each file's header and tensor table,+ * a few kilobytes, then streams the weights into the GPU a chunk at a time.+ *+ * An asset must be stored **uncompressed** for this to work at all: `AssetManager.openFd` throws+ * for a deflated entry. That is what `noCompress += "maml"` in the app's Gradle configuration is+ * for, and it costs nothing on download size since fp16 and int8 weights barely compress.+ * * # Voices * * A voice is two small style tensors, not a model, so [voice] switches without re-uploading@@ -33,7 +48,7 @@ import java.text.Normalizer * * # Availability *- * The constructor never throws. [isAvailable] is false when `libmodelrunner.so` is missing for+ * Construction 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. *@@ -42,9 +57,9 @@ import java.text.Normalizer * 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,+class SupertonicSynthesizer private constructor(+ private val bundle: Bundle,+ voice: String, ) : AutoCloseable { private var handle: Long = 0L @@ -56,16 +71,9 @@ class SupertonicSynthesizer( 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)),- )+ create(bundle, voice) } catch (e: Throwable) {- Log.e(TAG, "cannot open the Supertonic bundle in $directory", e)+ Log.e(TAG, "cannot open the Supertonic bundle in $bundle", e) 0L } }@@ -78,14 +86,14 @@ class SupertonicSynthesizer( * 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.+ * this is a 25 KB read rather than a whole-bundle one. */ fun voice(name: String): Boolean { if (handle == 0L) return false return try {- MlNative.setSupertonicVoice(handle, read(directory, styleName(name)))+ MlNative.setSupertonicVoice(handle, bundle.read(styleName(name))) } catch (e: Throwable) {- Log.e(TAG, "cannot read the voice $name in $directory", e)+ Log.e(TAG, "cannot read the voice $name in $bundle", e) false } }@@ -115,21 +123,165 @@ class SupertonicSynthesizer( if (live != 0L) MlNative.destroySupertonic(live) } - private companion object {+ /**+ * Where a bundle's six files are, abstracted over the APK and the filesystem.+ *+ * Both answer the same two questions — open a descriptor for a `.maml`, and read a small file+ * whole — and they differ only in that an asset is a range of the APK rather than a file, which+ * is why [open] returns an offset and a length alongside the descriptor.+ */+ internal interface Bundle {+ /** An open descriptor for [name] and the byte range within it that the file occupies. */+ fun open(name: String): Piece++ /** All of [name], for the two files small enough that streaming buys nothing. */+ fun read(name: String): ByteArray+ }++ /**+ * One file's descriptor and its range, owned until [release] hands it to native.+ *+ * The ownership matters because a raw descriptor has no destructor. If any of the six files+ * fails to open, the ones already opened have to be closed here or they are leaked for the life+ * of the process; if all six succeed, native takes them and closing here would shut the+ * descriptors it is about to read.+ */+ internal class Piece(private val fd: Int, val at: Long, val length: Long) : Closeable {+ private var owned = true++ /** Give the descriptor up to native, which closes it. */+ fun release(): Int {+ owned = false+ return fd+ }++ /** Close the descriptor, unless [release] already gave it away. */+ override fun close() {+ if (!owned) return+ owned = false+ closeFd(fd)+ }+ }++ private class Assets(private val assets: AssetManager, private val path: String) : Bundle {+ // `use` rather than a bare `close`, and it is load-bearing in both directions. On the happy+ // path the descriptor has already been detached, and `AssetFileDescriptor.close` is then a+ // no-op on it - it only releases the wrapper. If `detachFd` throws instead, the close is the+ // real one, and a leaked descriptor onto the APK would last the life of the process.+ override fun open(name: String): Piece = assets.openFd("$path/$name").use { afd ->+ Piece(afd.parcelFileDescriptor.detachFd(), afd.startOffset, afd.length)+ }++ override fun read(name: String): ByteArray =+ assets.open("$path/$name").use { it.readBytes() }++ override fun toString(): String = "the APK's $path/"+ }++ private class Directory(private val directory: File) : Bundle {+ // Offset 0 and the whole file: only an asset needs a range, because only an asset shares+ // its descriptor with the rest of the APK. `use` for the same reason as in [Assets].+ override fun open(name: String): Piece {+ val file = file(name)+ return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY).use {+ Piece(it.detachFd(), 0L, file.length())+ }+ }++ override fun read(name: String): ByteArray = file(name).readBytes()++ private fun file(name: String): File {+ val file = File(directory, name)+ require(file.isFile) { "$name is missing from $directory" }+ return file+ }++ override fun toString(): String = directory.toString()+ }++ 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. */+ /** The voice used when a caller does not name one. */ const val DEFAULT_VOICE = "F1" + /** Where [inAssets] looks unless told otherwise. */+ const val ASSET_PATH = "supertonic"++ /**+ * The four plans, in the order [MlNative.createSupertonic]'s parallel arrays want them.+ *+ * Native checks each file's graph id against the slot it arrived in, so a reordering here+ * fails at load rather than running the vocoder's weights through the text encoder.+ */+ private val GRAPHS = listOf(+ "supertonic_dp.maml",+ "supertonic_ttl.maml",+ "supertonic_ve.maml",+ "supertonic_voc.maml",+ )++ private const val INDEXER = "unicode_indexer.bin"++ /** The bundle shipped inside the APK. */+ fun inAssets(+ assets: AssetManager,+ path: String = ASSET_PATH,+ voice: String = DEFAULT_VOICE,+ ): SupertonicSynthesizer = SupertonicSynthesizer(Assets(assets, path), voice)++ /** The bundle in a folder on disk, as a downloaded one is. */+ fun inDirectory(+ directory: File,+ voice: String = DEFAULT_VOICE,+ ): SupertonicSynthesizer = SupertonicSynthesizer(Directory(directory), voice)+ 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()+ /**+ * Open all four plans, read the two small files, and hand the descriptors over.+ *+ * The two `finally`s are what make the descriptors safe rather than merely usually safe. A+ * raw descriptor has no destructor, so every path out of here has to close what it opened:+ * the outer one covers a file that is missing, an asset that turned out to be compressed or+ * a voice that does not exist, and the inner one covers the window after [Piece.release] has+ * given the descriptors up but before native has adopted them.+ */+ private fun create(bundle: Bundle, voice: String): Long {+ val pieces = ArrayList<Piece>(GRAPHS.size)+ try {+ GRAPHS.forEach { pieces.add(bundle.open(it)) }+ val indexer = bundle.read(INDEXER)+ val style = bundle.read(styleName(voice))+ val offsets = LongArray(pieces.size) { pieces[it].at }+ val lengths = LongArray(pieces.size) { pieces[it].length }+ val fds = IntArray(pieces.size) { pieces[it].release() }+ var handed = false+ try {+ val handle =+ MlNative.createSupertonic(fds, offsets, lengths, indexer, style)+ handed = true+ return handle+ } finally {+ if (!handed) fds.forEach { closeFd(it) }+ }+ } finally {+ pieces.forEach { it.close() }+ }+ }++ /**+ * Close a bare descriptor.+ *+ * Adopting it into a [ParcelFileDescriptor] is the only way to reach `close(2)` from Kotlin.+ * Failures are swallowed because every caller is already on an error path and there is+ * nothing useful to do about a descriptor that will not close.+ */+ private fun closeFd(fd: Int) {+ runCatching { ParcelFileDescriptor.adoptFd(fd).close() } } } }
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 9b2bdc499c..0dea3a8513 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -26,7 +26,10 @@ //! and every entry point tolerates it, so a device without fp16 compute degrades to "no //! bokeh" rather than to a crash. -use jni::objects::{JByteArray, JClass, JFloatArray, JIntArray, JString};+use std::fs::File;+use std::os::fd::FromRawFd;++use jni::objects::{JByteArray, JClass, JFloatArray, JIntArray, JLongArray, JString}; use jni::sys::{jfloat, jfloatArray, jint, jlong, jstring}; use jni::JNIEnv; @@ -44,7 +47,7 @@ use crate::preprocess::{ use crate::vulkan::context; use crate::vulkan::reshape::Reshaped; use crate::vulkan::run::Net;-use crate::weights::{graph, Offsets, Weights};+use crate::weights::{graph, Offsets, Streamed, Weights}; /// One segmenter. Handed to Kotlin as an opaque `jlong`. struct Handle {@@ -974,28 +977,48 @@ impl supertonic::Stages for SupertonicNets<'_> { /// `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+/// Six assets, in two kinds. The four `.maml` plans arrive as **file descriptors** with a byte+/// range each; the codepoint table and one voice's style file arrive as byte arrays, because they+/// are 128 KB and 25 KB and nothing is saved by streaming them.+///+/// 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.+/// the plans' ~105 MB and re-uploading those to change voice would be absurd.+///+/// # Why the plans are descriptors and not arrays+///+/// A `ByteArray` path allocates the model **three times**: the Java `byte[]`, the `Vec<u8>`+/// [`JNIEnv::convert_byte_array`] hands back, and [`Weights::parse`]'s own copy of the data+/// section. At the size a bundled Supertonic comes to that is ~300 MB of transient heap for a+/// ~105 MB model, which is an out-of-memory kill on a low-RAM device rather than a slow load.+///+/// [`Streamed`] reads the header and table only — a few kilobytes — and the upload then pulls the+/// data section through a fixed-size staging buffer, so the peak is one chunk.+///+/// `fds`, `offsets` and `lengths` are parallel, in the order the four graphs are listed below:+/// duration predictor, text encoder, sampler, vocoder. An `AssetFileDescriptor` carries all three+/// because an asset is a *range of the APK* rather than a file of its own.+///+/// # Ownership+///+/// Each descriptor must be **detached** by the caller: this takes ownership and closes it, on the+/// failure paths as much as the successful one. `AssetManager.openFd` also requires the asset to be+/// stored uncompressed, which is what `noCompress += "maml"` is for. /// /// # Safety ///-/// Called only by the JVM, with a valid `env` and arrays it owns.+/// Called only by the JVM, with a valid `env`, arrays it owns, and descriptors nothing else holds. #[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>,+ fds: JIntArray<'l>,+ offsets: JLongArray<'l>,+ lengths: JLongArray<'l>, indexer: JByteArray<'l>, style: JByteArray<'l>, ) -> jlong {- let assets = [duration, text, sampler, vocoder, indexer, style];- match build_supertonic(&mut env, assets) {+ match build_supertonic(&mut env, &fds, &offsets, &lengths, &indexer, &style) { Ok(handle) => Box::into_raw(Box::new(handle)) as jlong, Err(e) => { log(&format!("supertonic is unavailable: {e}"));@@ -1004,44 +1027,126 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createSupertonic } } +/// The four `.maml` graphs, in the order `createSupertonic`'s parallel arrays list them.+const SUPERTONIC_GRAPHS: [u32; 4] =+ [graph::SUPERTONIC_DP, graph::SUPERTONIC_TTL, graph::SUPERTONIC_VE, graph::SUPERTONIC_VOC];+ fn build_supertonic<'l>( env: &mut JNIEnv<'l>,- assets: [JByteArray<'l>; 6],+ fds: &JIntArray<'l>,+ offsets: &JLongArray<'l>,+ lengths: &JLongArray<'l>,+ indexer: &JByteArray<'l>,+ style: &JByteArray<'l>, ) -> 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 count = SUPERTONIC_GRAPHS.len();+ // The descriptors first, and adopted into owning `File`s before anything else may fail. The+ // caller detached them, so a path that returns without wrapping one leaks it for the life of+ // the process — and one of the four is a descriptor onto the APK itself. Every check below the+ // adoption loop is therefore free to fail; nothing above it is.+ let opened = env+ .get_array_length(fds)+ .map_err(|e| format!("cannot size the descriptors: {e}"))? as usize;+ let mut raw = vec![0i32; opened];+ env.get_int_array_region(fds, 0, &mut raw)+ .map_err(|e| format!("cannot read the descriptors: {e}"))?;+ let mut files = Vec::with_capacity(opened);+ let mut unopened = None;+ for &fd in &raw {+ if fd < 0 {+ // Recorded rather than returned on, so the descriptors after it are still adopted.+ unopened = unopened.or(Some(fd));+ continue;+ }+ // SAFETY: the caller detached each descriptor, so nothing else owns it, and `File` closes+ // it on drop.+ files.push(unsafe { File::from_raw_fd(fd) }); }- 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()));+ if let Some(fd) = unopened {+ return Err(format!("descriptor {fd} is not open"));+ }+ if opened != count {+ return Err(format!("{opened} descriptors for {count} graphs")); }- 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 mut at = vec![0i64; count];+ let mut len = vec![0i64; count];+ for (what, length) in [+ ("asset offsets", env.get_array_length(offsets)),+ ("asset lengths", env.get_array_length(lengths)),+ ] {+ let length = length.map_err(|e| format!("cannot size the {what}: {e}"))?;+ if length as usize != count {+ return Err(format!("{length} {what} for {count} graphs"));+ }+ }+ env.get_long_array_region(offsets, 0, &mut at)+ .map_err(|e| format!("cannot read the asset offsets: {e}"))?;+ env.get_long_array_region(lengths, 0, &mut len)+ .map_err(|e| format!("cannot read the asset lengths: {e}"))?;++ let mut streams = Vec::with_capacity(count);+ for (i, (file, graph_id)) in files.into_iter().zip(SUPERTONIC_GRAPHS).enumerate() {+ let (at, len) = (at.get(i).copied().unwrap_or(0), len.get(i).copied().unwrap_or(0));+ let (at, len) = match (u64::try_from(at), u64::try_from(len)) {+ (Ok(at), Ok(len)) => (at, len),+ _ => return Err(format!("graph {graph_id} spans {at}+{len}")),+ };+ streams.push(Streamed::open(file, at, len, graph_id)?);+ }+ let [duration_weights, text_weights, sampler_weights, vocoder_weights] =+ <[Streamed; 4]>::try_from(streams).map_err(|_| "four graphs were opened".to_string())?;++ let indexer = env+ .convert_byte_array(indexer)+ .map_err(|e| format!("cannot read the codepoint table: {e}"))?;+ if indexer.len() != supertonic::INDEXER_ENTRIES * 2 {+ return Err(format!("a codepoint table of {} bytes", indexer.len()));+ }+ let style =+ env.convert_byte_array(style).map_err(|e| format!("cannot read the style: {e}"))?;+ let voice = supertonic::Voice::read(&style)?;+ // The sampler's timestep shifts, rotary frequencies and folded style keys are all tensors in+ // its file that no shader ever reads, so they are read here rather than uploaded.+ let conditioning = supertonic::Conditioning::read(sampler_weights.reader())?; 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(+ duration: Reshaped::streamed(+ shared.clone(),+ duration_weights.offsets(),+ &duration_weights,+ SMALLEST,+ duration_plan,+ )?,+ text: Reshaped::streamed( shared.clone(),+ text_weights.offsets(),+ &text_weights,+ SMALLEST,+ text_plan,+ )?,+ sampler: Reshaped::streamed(+ shared.clone(),+ sampler_weights.offsets(), &sampler_weights, (SMALLEST, SMALLEST), sampler_plan, )?,- vocoder: Reshaped::new(shared, &vocoder_weights, SMALLEST, vocoder_plan)?,+ vocoder: Reshaped::streamed(+ shared,+ vocoder_weights.offsets(),+ &vocoder_weights,+ SMALLEST,+ vocoder_plan,+ )?, conditioning,- indexer: std::mem::take(&mut bytes[4]),+ indexer, voice, rng: SplitMix { state: seed() }, };+ // The four `Streamed` drop here, closing their descriptors: every byte they held is either in+ // device memory or in `conditioning`. Ok(handle) }
library/ml/src/main/rust/src/nets/reference.rs
diff --git a/library/ml/src/main/rust/src/nets/reference.rs b/library/ml/src/main/rust/src/nets/reference.rsindex 94a18b7d4c..52a9c4b0a8 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -2863,8 +2863,10 @@ mod tests { let style = read("style.f32"); use crate::post::supertonic as post; let (current, total) = (5u32, 16u32);- let conditioning = post::Conditioning::read(&weights).expect("the conditioning");- let shifts = post::time_shifts(&weights, current, total).expect("the timestep shifts");+ let conditioning =+ post::Conditioning::read(weights.reader()).expect("the conditioning");+ let shifts =+ post::time_shifts(weights.reader(), current, total).expect("the timestep shifts"); let query_angles = post::rotary_angles(&conditioning.theta, width).expect("the query angles"); let key_angles =
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 8303b4ca5c..c0a1599a24 100644--- a/library/ml/src/main/rust/src/post/supertonic.rs+++ b/library/ml/src/main/rust/src/post/supertonic.rs@@ -30,26 +30,11 @@ use crate::nets::embed_lanes; use crate::nets::supertonic_duration as duration_net; use crate::nets::supertonic_sampler as net; use crate::preprocess::f16_to_f32;-use crate::weights::Weights;+use crate::weights::Reader; /// The frequency multiplier the export applies before the sinusoids: `t * 1000 * frequency`. const TIME_SCALE: f32 = 1000.0; -/// One tensor of the `.maml` as `f32`, in the file's order.-fn tensor(weights: &Weights, index: usize, dims: &[u32]) -> Result<Vec<f32>, String> {- let found = weights.shaped(index, dims)?;- let bytes = weights.data();- let start = found.offset as usize;- let end = start + (found.len as usize) * 2;- let raw = bytes- .get(start..end)- .ok_or_else(|| format!("tensor {index} runs past the file"))?;- Ok(raw- .chunks_exact(2)- .map(|c| f16_to_f32(u16::from_le_bytes([c[0], c[1]])))- .collect())-}- /// `out[o] = sum_i weight[o][i] * x[i] + bias[o]`, over a row-major `[out, in]` weight. fn linear(weight: &[f32], bias: &[f32], x: &[f32]) -> Vec<f32> { let inputs = x.len();@@ -75,11 +60,11 @@ fn mish(x: f32) -> f32 { /// /// The plan reads them as one `[2048, 1, 1]` input and [`crate::nets::Builder::slice_channels`] /// hands each main block its own 512.-pub fn time_shifts(weights: &Weights, current: u32, total: u32) -> Result<Vec<f32>, String> {+pub fn time_shifts(weights: Reader, current: u32, total: u32) -> Result<Vec<f32>, String> { if total == 0 { return Err("a sampler step out of no steps".into()); }- let frequencies = tensor(weights, net::HOST_FREQUENCIES, &[net::FREQUENCIES])?;+ let frequencies = weights.fp16(net::HOST_FREQUENCIES, &[net::FREQUENCIES])?; let progress = current as f32 / total as f32; // Sines then cosines, which is the order of the export's `Concat`.@@ -90,19 +75,19 @@ pub fn time_shifts(weights: &Weights, current: u32, total: u32) -> Result<Vec<f3 .chain(angles.iter().map(|a| a.cos())) .collect(); - let in_weight = tensor(weights, net::HOST_MLP_IN, &[net::TIME_INNER, net::TIME])?;- let in_bias = tensor(weights, net::HOST_MLP_IN + 1, &[net::TIME_INNER])?;+ let in_weight = weights.fp16(net::HOST_MLP_IN, &[net::TIME_INNER, net::TIME])?;+ let in_bias = weights.fp16(net::HOST_MLP_IN + 1, &[net::TIME_INNER])?; let hidden: Vec<f32> = linear(&in_weight, &in_bias, &embedding).into_iter().map(mish).collect(); - let out_weight = tensor(weights, net::HOST_MLP_OUT, &[net::TIME, net::TIME_INNER])?;- let out_bias = tensor(weights, net::HOST_MLP_OUT + 1, &[net::TIME])?;+ let out_weight = weights.fp16(net::HOST_MLP_OUT, &[net::TIME, net::TIME_INNER])?;+ let out_bias = weights.fp16(net::HOST_MLP_OUT + 1, &[net::TIME])?; let time = linear(&out_weight, &out_bias, &hidden); let mut shifts = Vec::with_capacity(net::MAIN_BLOCKS * net::CHANNELS as usize); for block in 0..net::MAIN_BLOCKS { let index = net::HOST_TIME_LINEARS + block * 2;- let weight = tensor(weights, index, &[net::CHANNELS, net::TIME])?;- let bias = tensor(weights, index + 1, &[net::CHANNELS])?;+ let weight = weights.fp16(index, &[net::CHANNELS, net::TIME])?;+ let bias = weights.fp16(index + 1, &[net::CHANNELS])?; shifts.extend(linear(&weight, &bias, &time)); } Ok(shifts)@@ -150,8 +135,8 @@ pub fn unconditional_text(token: &[f32], chars: u32) -> Result<Vec<f32>, String> } /// The unconditional branch's style values, `[256, 1, 50]` and already transposed in the file.-pub fn unconditional_style(weights: &Weights) -> Result<Vec<f32>, String> {- tensor(weights, net::HOST_STYLE_TOKEN, &[net::STYLE, net::STYLE_TOKENS])+pub fn unconditional_style(weights: Reader) -> Result<Vec<f32>, String> {+ weights.fp16(net::HOST_STYLE_TOKEN, &[net::STYLE, net::STYLE_TOKENS]) } /// The folded style keys for one guidance branch, `[4 * 256, 1, 50]`.@@ -161,17 +146,13 @@ pub fn unconditional_style(weights: &Weights) -> Result<Vec<f32>, String> { /// blocks stacked; the plan slices its own out. The two branches have different `style_key`s, /// which is the only structural difference between them — everything else is an input, so one /// plan serves both.-pub fn style_keys(weights: &Weights, conditional: bool) -> Result<Vec<f32>, String> {+pub fn style_keys(weights: Reader, conditional: bool) -> Result<Vec<f32>, String> { let index = if conditional { net::HOST_KEYS_CONDITIONAL } else { net::HOST_KEYS_UNCONDITIONAL };- tensor(- weights,- index,- &[net::STYLE * net::MAIN_BLOCKS as u32, net::STYLE_TOKENS],- )+ weights.fp16(index, &[net::STYLE * net::MAIN_BLOCKS as u32, net::STYLE_TOKENS]) } /// Entries in the codepoint table: every code unit of the Basic Multilingual Plane.@@ -261,7 +242,7 @@ pub trait Stages { /// Everything the sampler needs from the weights file that a shader never sees, read once. ///-/// [`synthesise`] takes this rather than a [`Weights`] so the sequencing can be tested against+/// [`synthesise`] takes this rather than a [`Reader`] so the sequencing can be tested against /// stubs, and so the file is walked once per voice instead of once per step. pub struct Conditioning { /// The rotary `theta`, `[32]`.@@ -280,15 +261,15 @@ pub struct Conditioning { impl Conditioning { /// Read all of it, for a sampler run of [`STEPS`] steps.- pub fn read(weights: &Weights) -> Result<Conditioning, String> {+ pub fn read(weights: Reader) -> Result<Conditioning, String> { Ok(Conditioning {- theta: tensor(weights, net::HOST_THETA, &[net::FREQUENCIES])?,+ theta: weights.fp16(net::HOST_THETA, &[net::FREQUENCIES])?, shifts: (0..STEPS) .map(|step| time_shifts(weights, step, STEPS)) .collect::<Result<_, _>>()?, conditional_keys: style_keys(weights, true)?, unconditional_keys: style_keys(weights, false)?,- text_token: tensor(weights, net::HOST_TEXT_TOKEN, &[net::TEXT])?,+ text_token: weights.fp16(net::HOST_TEXT_TOKEN, &[net::TEXT])?, unconditional_style: unconditional_style(weights)?, }) }
library/ml/src/main/rust/src/vulkan/parity.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity.rs b/library/ml/src/main/rust/src/vulkan/parity.rsindex 11377f0b05..78dc596ea2 100644--- a/library/ml/src/main/rust/src/vulkan/parity.rs+++ b/library/ml/src/main/rust/src/vulkan/parity.rs@@ -31,7 +31,7 @@ use std::sync::{Arc, OnceLock}; use crate::nets::reference::{run_multi, Given, Invented}; use crate::nets::{embed_lanes, Act, Builder, Id, Plan, Shape, WeightSource}; use crate::preprocess::RESCALE_ONLY;-use crate::weights::{graph, write_mixed, Fixture, Weights};+use crate::weights::{graph, write_mixed, Fixture, Streamed, Weights}; use super::context::{self, Context}; use super::run::Net;@@ -495,6 +495,66 @@ fn report_the_tiled_int8_convolution_against_the_tiled_fp16_one() { } } +#[test]+#[ignore = "needs a Vulkan device"]+fn a_net_uploaded_from_a_file_agrees_with_one_uploaded_from_memory() {+ // The bundled path end to end: the same plan, the same weights, uploaded once from a `Vec<u8>`+ // and once by streaming a file in chunks. The two must produce identical output, because a+ // wrong `dst_offset` on any chunk but the first gives a net whose early layers are right and+ // whose later ones read whatever the buffer was allocated with — plausible-looking audio, not+ // an error.+ //+ // The blob is deliberately larger than the chunk size the upload uses, so more than one copy is+ // issued. A single-chunk fixture exercises none of the arithmetic that can be wrong.+ const CHANNELS: u32 = 1024;+ const LAYERS: usize = 6;+ let taps = (CHANNELS * CHANNELS) as usize;+ let kernel: Vec<f32> = (0..taps).map(|i| ((i % 11) as f32 - 5.0) / 1024.0).collect();+ let bias = vec![0.0f32; CHANNELS as usize];+ let mut tensors = Vec::new();+ for _ in 0..LAYERS {+ tensors.push(Fixture::F16(vec![CHANNELS, CHANNELS, 1, 1], kernel.clone()));+ tensors.push(Fixture::F16(vec![CHANNELS], bias.clone()));+ }+ let blob = write_mixed(graph::SUPERTONIC_VE, &tensors);+ assert!(+ blob.len() as u64 > Net::CHUNK_BYTES,+ "{} bytes fits in one {}-byte chunk, so nothing is being tested",+ blob.len(),+ Net::CHUNK_BYTES,+ );++ let input = spread((CHANNELS * 8) as usize, 0.25);+ let plan_for = |source: &dyn WeightSource| -> Plan {+ let mut builder = Builder::new(source);+ let mut x = builder.input(Shape::new(CHANNELS, 1, 8));+ for layer in 0..LAYERS {+ x = builder.conv_same(x, layer * 2, CHANNELS, 1, 1, Act::Relu);+ }+ builder.finish(&[x]).expect("the upload fixture plan builds")+ };++ let parsed = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");+ let mut from_memory = Net::new(device(), plan_for(&parsed), &parsed, RESCALE_ONLY)+ .expect("the in-memory plan records");+ let want = from_memory.infer_raw(&input).expect("the in-memory net runs");++ // A leading pad, so the file's data section does not start where the file does — which is what+ // an asset inside an APK looks like, and the one thing an offset-free reader gets wrong.+ let path = std::env::temp_dir().join("modelrunner-upload-parity.maml");+ let mut staged = vec![0x5Au8; 8192];+ staged.extend_from_slice(&blob);+ std::fs::write(&path, &staged).expect("the fixture file writes");+ let file = std::fs::File::open(&path).expect("the fixture file reopens");+ let streamed = Streamed::open(file, 8192, blob.len() as u64, graph::SUPERTONIC_VE)+ .expect("the fixture file streams");+ let mut from_file = Net::new(device(), plan_for(&parsed), &streamed, RESCALE_ONLY)+ .expect("the streamed plan records");+ let got = from_file.infer_raw(&input).expect("the streamed net runs");++ matches("a net uploaded from a file", &want, &got);+}+ #[test] #[ignore = "needs a Vulkan device"] fn a_rebuilt_net_agrees_with_the_reference_at_each_shape() {
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.rsindex 715ccb5765..bc34094eb0 100644--- a/library/ml/src/main/rust/src/vulkan/reshape.rs+++ b/library/ml/src/main/rust/src/vulkan/reshape.rs@@ -15,7 +15,7 @@ use std::sync::Arc; use crate::nets::Plan; use crate::preprocess::RESCALE_ONLY;-use crate::weights::{Offsets, Weights};+use crate::weights::{Blob, Offsets, Weights}; use super::context::Context; use super::run::Net;@@ -40,18 +40,32 @@ impl<S: Copy + PartialEq> Reshaped<S> { /// 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.+ pub fn new(+ context: Arc<Context>,+ weights: &Weights,+ shape: S,+ plan: fn(&Offsets, S) -> Result<Plan, String>,+ ) -> Result<Reshaped<S>, String> {+ Self::streamed(context, weights.offsets(), weights, shape, plan)+ }++ /// [`Reshaped::new`] against a table and a data section that need not be the same object.+ ///+ /// The bundled path: a [`crate::weights::Streamed`] hands over its table and streams its data+ /// section out of the APK, so the 105 MB is never resident at all. The `Weights` path above is+ /// this with both halves coming from the same in-memory parse. /// /// [`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(+ pub fn streamed( context: Arc<Context>,- weights: &Weights,+ offsets: Offsets,+ data: &dyn Blob, 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)?;+ let net = Net::new(context, plan(&offsets, shape)?, data, RESCALE_ONLY)?; Ok(Reshaped { net, offsets, at: shape, plan }) }
library/ml/src/main/rust/src/vulkan/run.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run.rs b/library/ml/src/main/rust/src/vulkan/run.rsindex db36a95cea..6e8c1739d0 100644--- a/library/ml/src/main/rust/src/vulkan/run.rs+++ b/library/ml/src/main/rust/src/vulkan/run.rs@@ -34,7 +34,7 @@ use ash::vk; use crate::nets::{Op, Plan}; use crate::preprocess::{self, Normalise};-use crate::weights::Weights;+use crate::weights::Blob; use super::buffers::Buffer; use super::context::Context;@@ -79,13 +79,17 @@ pub struct Net { impl Net { /// Allocate, upload the weights and record the plan. ///- /// `weights` is consumed for its data but not retained: once the blob is in+ /// `weights` is read for its data section but not retained: once the blob is in /// device-local memory the host copy is dropped, which for U^2-Netp gives back 2.1 MB /// of heap.+ ///+ /// A [`Blob`] rather than a [`crate::weights::Weights`] so that a bundled net can stream+ /// straight out of the APK. Nothing here reads the tensor table — the [`Plan`] already carries+ /// every resolved offset — which is what makes the two interchangeable. pub fn new( context: Arc<Context>, plan: Plan,- weights: &Weights,+ weights: &dyn Blob, normalise: Normalise, ) -> Result<Net, String> { let arena_bytes = (plan.arena_elems as vk::DeviceSize) * 2;@@ -93,7 +97,7 @@ impl Net { // the weights binding whether or not any shader reads it. A plan can legitimately read // no weights at all — a purely elementwise one does — so this floors the allocation // rather than refusing the plan.- let weights_bytes = (weights.data().len() as vk::DeviceSize).max(2);+ let weights_bytes = (weights.data_len() as vk::DeviceSize).max(2); let input_elems = binding_elems(&plan.inputs); let output_elems = binding_elems(&plan.outputs); // One staging buffer for both directions: the inputs and the outputs are never in@@ -138,7 +142,7 @@ impl Net { output_scratch: vec![0u16; output_elems], }; - net.upload_weights(weights.data())?;+ net.upload_weights(weights)?; net.command_buffer = net.allocate_command_buffer()?; net.fence = net.create_fence()?; net.record()?;@@ -219,46 +223,93 @@ impl Net { Ok(()) } - /// Copy the weights blob to device-local memory through the staging buffer.+ /// Staging bytes per copy. Large enough that the per-chunk round trip is noise against the+ /// transfer, small enough to be an unremarkable allocation on a low-RAM device.+ ///+ /// `pub(crate)` only so the parity fixture can assert its blob is bigger than one chunk. A+ /// fixture that fits in a single copy exercises none of the `dst_offset` arithmetic.+ pub(crate) const CHUNK_BYTES: u64 = 8 * 1024 * 1024;++ /// Copy the weights blob to device-local memory through the staging buffer, in chunks.+ ///+ /// Its own staging allocation and its own one-shot command buffer, because the permanent+ /// staging buffer is sized for one input and the weights are ten times that. Both are freed+ /// before returning; this happens once per net. ///- /// Its own one-shot command buffer and its own staging allocation, because the- /// permanent staging buffer is sized for one input and the weights are ten times- /// that. Both are freed before returning; this happens once per net.- fn upload_weights(&self, data: &[u8]) -> Result<(), String> {- if data.is_empty() {+ /// # Why chunked, and why this small+ ///+ /// A single copy needs a staging buffer the size of the whole blob. For Supertonic's 127 MB+ /// sampler that is 127 MB of `HOST_VISIBLE` memory on top of the 127 MB device-local+ /// destination, at the moment of load — and it defeats the point of streaming the data section+ /// out of the APK, since the peak would be the whole file again just in a different allocation.+ ///+ /// [`Net::CHUNK_BYTES`] instead, one `cmd_copy_buffer` per chunk at the right `dst_offset`.+ /// Each is submitted and waited on before the next is written, because the staging buffer is+ /// reused and overwriting it while a copy is still reading it is a race. That costs one round+ /// trip per chunk — 16 for that sampler — against a transfer that is bandwidth-bound anyway,+ /// and it happens once per net rather than once per inference.+ fn upload_weights(&self, weights: &dyn Blob) -> Result<(), String> {+ let total = weights.data_len();+ if total == 0 { return Ok(()); }- let staging = Buffer::staging(&self.context, data.len() as vk::DeviceSize)?;- staging.write(data)?;+ let chunk = total.min(Self::CHUNK_BYTES);+ let staging = Buffer::staging(&self.context, chunk as vk::DeviceSize)?;+ let mut buffer = vec![0u8; usize::try_from(chunk).map_err(|_| "a chunk overflowed")?]; let command_buffer = self.allocate_command_buffer()?; // SAFETY: the command buffer was just allocated from this device's pool and is- // freed on every path below; the copy is bounds-checked by construction, since both- // buffers are exactly `data.len()` bytes.+ // freed on every path below; each copy is bounds-checked by the loop, which never asks+ // for more than `chunk` bytes of staging or writes past `total` of the destination. unsafe { let device = &self.context.device;- let record = || -> Result<(), String> {- device- .begin_command_buffer(+ let mut written = 0u64;+ let outcome = loop {+ if written >= total {+ break Ok(());+ }+ let size = chunk.min(total - written);+ let piece = match buffer.get_mut(..size as usize) {+ Some(piece) => piece,+ None => break Err("a chunk is larger than its buffer".to_string()),+ };+ if let Err(e) = weights.read_at(written, piece) {+ break Err(e);+ }+ if let Err(e) = staging.write(piece) {+ break Err(e);+ }+ let copy = || -> Result<(), String> {+ device+ .begin_command_buffer(+ command_buffer,+ &vk::CommandBufferBeginInfo::default()+ .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT),+ )+ .map_err(|e| format!("begin_command_buffer {e:?}"))?;+ let region = vk::BufferCopy::default()+ .dst_offset(written as vk::DeviceSize)+ .size(size as vk::DeviceSize);+ device.cmd_copy_buffer( command_buffer,- &vk::CommandBufferBeginInfo::default()- .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT),- )- .map_err(|e| format!("begin_command_buffer {e:?}"))?;- let region = vk::BufferCopy::default().size(data.len() as vk::DeviceSize);- device.cmd_copy_buffer(- command_buffer,- staging.buffer,- self.weights.buffer,- std::slice::from_ref(®ion),- );- device- .end_command_buffer(command_buffer)- .map_err(|e| format!("end_command_buffer {e:?}"))?;- self.submit_and_wait(command_buffer)+ staging.buffer,+ self.weights.buffer,+ std::slice::from_ref(®ion),+ );+ device+ .end_command_buffer(command_buffer)+ .map_err(|e| format!("end_command_buffer {e:?}"))?;+ // Waited on before the next chunk overwrites the staging buffer. The pool was+ // created with `RESET_COMMAND_BUFFER`, so re-beginning the same buffer is+ // legal once its submission has completed.+ self.submit_and_wait(command_buffer)+ };+ if let Err(e) = copy() {+ break Err(e);+ }+ written += size; };- let outcome = record(); device.free_command_buffers(self.command_pool, &[command_buffer]);- // `staging` drops here, after the fence has been waited on.+ // `staging` drops here, after the last fence has been waited on. outcome } }
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 5e0eceee92..7524b71642 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -15,6 +15,10 @@ //! in the file and its offset in device memory. That is the reason the format is //! one contiguous blob. +use std::fs::File;++use crate::preprocess::f16_to_f32;+ /// `b"MAML"`, little-endian, at offset 0. const MAGIC: [u8; 4] = *b"MAML"; /// Bumped when the layout below changes incompatibly.@@ -28,9 +32,9 @@ const DTYPE_F16: u32 = 0; /// Used only where the weights dominate the download and fp16 would double it: SMaLL-100 is /// 330 million parameters, which is 660 MB at fp16 and 330 MB here. ///-/// The quantisation is symmetric — zero point 0 — and the scale is per tensor, both read from-/// the export rather than assumed. So a value is `int8 * scale`, and because the scale is one-/// number for the whole tensor it multiplies the *accumulator* once rather than every tap. The+/// The quantisation is symmetric — zero point 0 — and the scale is per output channel, both read+/// from the export rather than assumed. So a value is `int8 * scale`, and because the scale+/// applies to a whole output row it multiplies the *accumulator* once rather than every tap. The /// scale lives in its own fp16 tensor because a table entry is already 32 bytes with no room /// for it, and a companion tensor needs no format version bump. ///@@ -115,6 +119,135 @@ impl Tensor { } } +/// A `.maml`'s data section, readable a piece at a time.+///+/// [`crate::vulkan::run::Net::new`] needs the data section and nothing else: the [`Plan`] it is+/// handed already carries every resolved offset. It does *not* need the section in one host+/// allocation, and for a bundled Supertonic it must not — the current path allocates the model+/// three times over, as a Java `byte[]`, as the `Vec<u8>` JNI hands Rust, and as [`Weights`]'s own+/// copy. At the ~105 MB an int8 bundle comes to, that is ~300 MB of transient heap and an+/// out-of-memory kill on a low-RAM device.+///+/// So the upload asks for ranges instead, and two implementations answer: [`Weights`], which has+/// the bytes already, and [`Streamed`], which leaves them in the APK and reads them positionally.+/// Neither is faster than the other in device time — both end up doing the same+/// `cmd_copy_buffer`s — and the second has a peak host cost of one chunk.+///+/// [`Plan`]: crate::nets::Plan+pub trait Blob {+ /// Bytes in the data section.+ fn data_len(&self) -> u64;++ /// Fill `into` from `offset` bytes into the data section.+ ///+ /// A short read is an error rather than a partial fill: every caller here knows exactly how+ /// many bytes it wants, and silently uploading a half-read chunk would leave one tensor of a+ /// net holding whatever the buffer was allocated with.+ fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String>;+}++/// A `.maml` header and tensor table, without the data section.+///+/// Parsed by [`parse_header`] from the first `HEADER_BYTES + count * 32` bytes of a file, which is+/// a few kilobytes for even the largest net here. Both [`Weights::parse`] and [`Streamed::open`]+/// go through it, so there is one implementation of the format's bounds checks rather than two+/// that have to agree.+struct Header {+ graph_id: u32,+ source_sha256: [u8; 32],+ tensors: Vec<Tensor>,+ data_offset: usize,+ data_len: usize,+}++/// Parse the header and tensor table out of `bytes`, which must reach at least the table's end.+///+/// Every offset and length in the table is bounds-checked here rather than at use, so a truncated+/// or hand-edited asset fails at load with a message instead of dispatching a shader that reads+/// past the end of a device buffer — where the symptom would be a driver reset, not an error.+///+/// The one thing this does *not* check is that the file ends where the data section does: a+/// [`Streamed`] read only has the prefix in hand, and an asset inside an APK is followed by the+/// next asset. [`Weights::parse`] checks it separately, because there the whole file is the slice+/// and a length mismatch means a truncated download.+fn parse_header(bytes: &[u8], expect_graph: u32) -> Result<Header, String> {+ if bytes.len() < HEADER_BYTES {+ return Err(format!("{} bytes is shorter than a .maml header", bytes.len()));+ }+ if bytes[0..4] != MAGIC {+ return Err("not a .maml file (bad magic)".into());+ }+ let version = u32(bytes, 4);+ if version != FORMAT_VERSION {+ return Err(format!("format version {version}, expected {FORMAT_VERSION}"));+ }+ let graph_id = u32(bytes, 8);+ if graph_id != expect_graph {+ return Err(format!(+ "this file is for graph {graph_id}, but graph {expect_graph} asked for it"+ ));+ }+ let count = u32(bytes, 12) as usize;+ let mut source_sha256 = [0u8; 32];+ source_sha256.copy_from_slice(&bytes[16..48]);+ let data_offset = u32(bytes, 48) as usize;+ let data_len = u32(bytes, 52) as usize;++ let table_bytes = count+ .checked_mul(TENSOR_ENTRY_BYTES)+ .ok_or_else(|| format!("{count} tensors overflows the table size"))?;+ if data_offset != HEADER_BYTES + table_bytes {+ return Err(format!(+ "data starts at {data_offset}, but {count} tensors put it at {}",+ HEADER_BYTES + table_bytes+ ));+ }+ data_offset+ .checked_add(data_len)+ .ok_or_else(|| "data section overflows".to_string())?;+ if bytes.len() < data_offset {+ return Err(format!(+ "{} bytes does not reach the end of a {count}-tensor table at {data_offset}",+ bytes.len()+ ));+ }++ let mut tensors = Vec::with_capacity(count);+ for i in 0..count {+ let at = HEADER_BYTES + i * TENSOR_ENTRY_BYTES;+ let rank = u32(bytes, at);+ if rank == 0 || rank > 4 {+ return Err(format!("tensor {i} has rank {rank}"));+ }+ let dims =+ [u32(bytes, at + 4), u32(bytes, at + 8), u32(bytes, at + 12), u32(bytes, at + 16)];+ let dtype = u32(bytes, at + 20);+ let stride = match dtype {+ DTYPE_F16 => 2u64,+ DTYPE_I8 => 1,+ other => return Err(format!("tensor {i} has dtype {other}, expected fp16 or int8")),+ };+ let offset = u32(bytes, at + 24);+ let len = u32(bytes, at + 28);++ let expected: u64 = dims[..rank as usize].iter().map(|&d| d as u64).product();+ if expected != len as u64 {+ return Err(format!("tensor {i} has dims {dims:?} but len {len}"));+ }+ if !offset.is_multiple_of(ALIGNMENT) {+ return Err(format!("tensor {i} is at {offset}, not {ALIGNMENT}-aligned"));+ }+ let end = (offset as u64) + (len as u64) * stride;+ if end > data_len as u64 {+ return Err(format!(+ "tensor {i} spans {offset}..{end} of a {data_len}-byte data section"+ ));+ }+ tensors.push(Tensor { rank, dims, offset, len, int8: dtype == DTYPE_I8 });+ }+ Ok(Header { graph_id, source_sha256, tensors, data_offset, data_len })+}+ /// 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@@ -178,95 +311,24 @@ pub struct Weights { impl Weights { /// Parse `bytes`, rejecting anything not built for `expect_graph`. ///- /// Every offset and length in the table is bounds-checked here rather than at- /// use, so a truncated or hand-edited asset fails at load with a message instead- /// of dispatching a shader that reads past the end of a device buffer — where- /// the symptom would be a driver reset, not an error.+ /// The header and table go through `parse_header`, which does every bounds check; the one+ /// thing added here is that the file must end exactly where its data section does, since with+ /// the whole slice in hand a mismatch means a truncated or padded download. pub fn parse(bytes: &[u8], expect_graph: u32) -> Result<Weights, String> {- if bytes.len() < HEADER_BYTES {- return Err(format!("{} bytes is shorter than a .maml header", bytes.len()));- }- if bytes[0..4] != MAGIC {- return Err("not a .maml file (bad magic)".into());- }- let version = u32(bytes, 4);- if version != FORMAT_VERSION {- return Err(format!("format version {version}, expected {FORMAT_VERSION}"));- }- let graph_id = u32(bytes, 8);- if graph_id != expect_graph {- return Err(format!(- "this file is for graph {graph_id}, but graph {expect_graph} asked for it"- ));- }- let count = u32(bytes, 12) as usize;- let mut source_sha256 = [0u8; 32];- source_sha256.copy_from_slice(&bytes[16..48]);- let data_offset = u32(bytes, 48) as usize;- let data_len = u32(bytes, 52) as usize;-- let table_bytes = count- .checked_mul(TENSOR_ENTRY_BYTES)- .ok_or_else(|| format!("{count} tensors overflows the table size"))?;- if data_offset != HEADER_BYTES + table_bytes {- return Err(format!(- "data starts at {data_offset}, but {count} tensors put it at {}",- HEADER_BYTES + table_bytes- ));- }- let data_end = data_offset- .checked_add(data_len)- .ok_or_else(|| "data section overflows".to_string())?;+ let header = parse_header(bytes, expect_graph)?;+ let data_end = header.data_offset + header.data_len; if data_end != bytes.len() { return Err(format!( "data section ends at {data_end} but the file is {} bytes", bytes.len() )); }-- let mut tensors = Vec::with_capacity(count);- for i in 0..count {- let at = HEADER_BYTES + i * TENSOR_ENTRY_BYTES;- let rank = u32(bytes, at);- if rank == 0 || rank > 4 {- return Err(format!("tensor {i} has rank {rank}"));- }- let dims = [- u32(bytes, at + 4),- u32(bytes, at + 8),- u32(bytes, at + 12),- u32(bytes, at + 16),- ];- let dtype = u32(bytes, at + 20);- let stride = match dtype {- DTYPE_F16 => 2u64,- DTYPE_I8 => 1,- other => return Err(format!("tensor {i} has dtype {other}, expected fp16 or int8")),- };- let offset = u32(bytes, at + 24);- let len = u32(bytes, at + 28);-- let expected: u64 = dims[..rank as usize].iter().map(|&d| d as u64).product();- if expected != len as u64 {- return Err(format!("tensor {i} has dims {dims:?} but len {len}"));- }- if !offset.is_multiple_of(ALIGNMENT) {- return Err(format!("tensor {i} is at {offset}, not {ALIGNMENT}-aligned"));- }- let end = (offset as u64) + (len as u64) * stride;- if end > data_len as u64 {- return Err(format!(- "tensor {i} spans {offset}..{end} of a {data_len}-byte data section"- ));- }- tensors.push(Tensor { rank, dims, offset, len, int8: dtype == DTYPE_I8 });- }-+ let data = bytes.get(header.data_offset..).unwrap_or(&[]).to_vec(); Ok(Weights {- graph_id,- source_sha256,- table: Offsets { tensors },- data: bytes[data_offset..].to_vec(),+ graph_id: header.graph_id,+ source_sha256: header.source_sha256,+ table: Offsets { tensors: header.tensors },+ data, }) } @@ -295,6 +357,11 @@ impl Weights { self.table.clone() } + /// This file's table and bytes, for the tensors the host reads itself. See [`Reader`].+ pub fn reader(&self) -> Reader<'_> {+ Reader::new(&self.table, self)+ }+ /// How many tensors the table holds. pub fn len(&self) -> usize { self.table.len()@@ -321,6 +388,210 @@ impl Weights { } } +impl Blob for Weights {+ fn data_len(&self) -> u64 {+ self.data.len() as u64+ }++ fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String> {+ let start = usize::try_from(offset).map_err(|_| "a data offset overflowed usize")?;+ let end = start+ .checked_add(into.len())+ .ok_or("a data range overflowed")?;+ let from = self+ .data+ .get(start..end)+ .ok_or_else(|| format!("{start}..{end} of a {}-byte data section", self.data.len()))?;+ into.copy_from_slice(from);+ Ok(())+ }+}++/// A `.maml` whose table is in memory and whose data section is still in a file.+///+/// The counterpart of [`Weights`], and the whole of what bundling Supertonic needs: its table is a+/// few kilobytes, and its data section is the ~105 MB that must not be resident three times over.+/// See [`Blob`] for why that mattered enough to add a second implementation.+///+/// # Not `mmap`+///+/// `memmap2` was deliberately removed from this repo, and nothing here needs it back. A mapping+/// would let the upload read the data as a slice, but the upload does not want a slice: it wants+/// to hand fixed-size pieces to a staging buffer, and a positional read does that with no+/// unsafety, no dependency, and no page-fault behaviour to reason about on an unknown filesystem.+///+/// # The offset, and why it is not always zero+///+/// An asset inside an APK is a *range* of the APK, so `AssetManager.openFd` returns a descriptor+/// alongside a `startOffset` and a `length` rather than a file of its own. This holds that range+/// and adds it to every read, so a bundled asset and a downloaded file are one code path. It also+/// means `openFd` must succeed, which is what `noCompress += "maml"` in the app's Gradle+/// configuration is load-bearing for: `openFd` throws for a deflated asset.+pub struct Streamed {+ /// Which network this file is for. See [`graph`].+ pub graph_id: u32,+ /// SHA-256 of the ONNX it was converted from, for tracing a shipped asset.+ pub source_sha256: [u8; 32],+ table: Offsets,+ file: File,+ /// Byte offset of the **data section** within `file`, i.e. the asset's own start plus the+ /// header and table. Every [`Blob::read_at`] adds it, so callers index the data section.+ data_at: u64,+ data_len: u64,+}++impl Streamed {+ /// Read the header and table of the `.maml` occupying `at..at + len` of `file`.+ ///+ /// Only the prefix is read — the header plus the tensor table, a few kilobytes — so this costs+ /// nothing whatever the size of the net. `file` is retained; the data section is read later, by+ /// the upload.+ ///+ /// `len` is what the caller was told the asset is, and is checked against the header rather+ /// than trusted: a `.maml` claiming a data section past the end of its own range would+ /// otherwise be caught only by the first read that ran off the end, or not at all if a+ /// neighbouring asset happened to follow it.+ pub fn open(file: File, at: u64, len: u64, expect_graph: u32) -> Result<Streamed, String> {+ // A generous prefix read: one page covers the header and a 128-tensor table, and the+ // largest net here has 605. Reading `min(len, PREFIX)` rather than exactly the table means+ // one syscall instead of two, since the table's size is in the header being read.+ const PREFIX: u64 = 64 * 1024;+ let want = usize::try_from(len.min(PREFIX)).map_err(|_| "a .maml prefix overflowed")?;+ let mut prefix = vec![0u8; want];+ read_exact_at(&file, &mut prefix, at)+ .map_err(|e| format!("reading a .maml header at {at}: {e}"))?;+ let header = parse_header(&prefix, expect_graph)?;+ let data_at = header.data_offset as u64;+ let end = data_at+ .checked_add(header.data_len as u64)+ .ok_or("data section overflows")?;+ if end > len {+ return Err(format!(+ "the data section ends at {end} but this .maml is only {len} bytes"+ ));+ }+ Ok(Streamed {+ graph_id: header.graph_id,+ source_sha256: header.source_sha256,+ table: Offsets { tensors: header.tensors },+ file,+ data_at: at + data_at,+ data_len: header.data_len as u64,+ })+ }++ /// The tensor table alone, for building and rebuilding plans. See [`Offsets`].+ pub fn offsets(&self) -> Offsets {+ self.table.clone()+ }++ /// This file's table and bytes, for the tensors the host reads itself. See [`Reader`].+ ///+ /// Each read is a positional read of a few kilobytes out of the APK, which is what makes this+ /// affordable: the sampler's host block is 0.44% of its 127 MB.+ pub fn reader(&self) -> Reader<'_> {+ Reader::new(&self.table, self)+ }++ /// How many tensors the table holds.+ pub fn len(&self) -> usize {+ self.table.len()+ }++ /// Whether the table is empty. Only ever true for a hand-made file.+ pub fn is_empty(&self) -> bool {+ self.table.is_empty()+ }+}++impl Blob for Streamed {+ fn data_len(&self) -> u64 {+ self.data_len+ }++ fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String> {+ let end = offset+ .checked_add(into.len() as u64)+ .ok_or("a data range overflowed")?;+ if end > self.data_len {+ return Err(format!(+ "{offset}..{end} of a {}-byte data section",+ self.data_len+ ));+ }+ read_exact_at(&self.file, into, self.data_at + offset)+ .map_err(|e| format!("reading {} bytes at {offset}: {e}", into.len()))+ }+}++/// A tensor table and the bytes it indexes, for the reads the host does itself.+///+/// A handful of Supertonic's tensors never reach a shader: the sampler's timestep MLP depends on+/// the step number, its rotary `theta` on the sequence length, and its folded style keys are+/// inputs to other nets. `post::supertonic` reads those on the host, and needed a [`Weights`] to+/// do it — which is exactly the 105 MB allocation the bundled path exists to avoid.+///+/// So it takes one of these instead. Both halves come from the same file either way; keeping them+/// as one argument rather than two means a caller cannot pair one net's table with another's bytes.+#[derive(Clone, Copy)]+pub struct Reader<'a> {+ table: &'a Offsets,+ data: &'a dyn Blob,+}++impl<'a> Reader<'a> {+ /// A reader over `table` and `data`, which must describe the same file.+ pub fn new(table: &'a Offsets, data: &'a dyn Blob) -> Reader<'a> {+ Reader { table, data }+ }++ /// Tensor `index` as `f32`, in the file's order, checked against `dims`.+ ///+ /// fp16 only: every tensor the host reads is fp16, and an int8 one would need its companion+ /// scale, which is a caller's decision rather than something to guess at here.+ pub fn fp16(&self, index: usize, dims: &[u32]) -> Result<Vec<f32>, String> {+ let found = self.table.shaped(index, dims)?;+ if found.int8 {+ return Err(format!("tensor {index} is int8, and the host reads fp16"));+ }+ let mut bytes = vec![0u8; (found.len as usize) * 2];+ self.data+ .read_at(found.offset as u64, &mut bytes)+ .map_err(|e| format!("tensor {index}: {e}"))?;+ Ok(bytes+ .chunks_exact(2)+ .map(|c| f16_to_f32(u16::from_le_bytes([c[0], c[1]])))+ .collect())+ }+}++/// Fill `buf` from `offset` without moving the file's cursor.+///+/// The same helper as `library/tilecodec`'s `pmtiles::read_exact_at`, and copied rather than shared+/// because these two crates have no dependency between them and this is six lines. Both platforms+/// expose a positional read; neither is guaranteed to return everything at once, hence the loop.+///+/// Positional rather than seek-then-read because the cursor is shared with whatever else holds this+/// descriptor — on Android the descriptor came out of `AssetManager`, and moving its cursor is not+/// this module's business.+fn read_exact_at(file: &File, mut buf: &mut [u8], mut offset: u64) -> std::io::Result<()> {+ while !buf.is_empty() {+ #[cfg(windows)]+ let n = std::os::windows::fs::FileExt::seek_read(file, buf, offset)?;+ #[cfg(unix)]+ let n = std::os::unix::fs::FileExt::read_at(file, buf, offset)?;+ if n == 0 {+ return Err(std::io::Error::new(+ std::io::ErrorKind::UnexpectedEof,+ "the file ended mid-tensor",+ ));+ }+ buf = buf.get_mut(n..).unwrap_or(&mut []);+ offset += n as u64;+ }+ Ok(())+}+ /// One tensor for [`write_mixed`]: fp16 values, or the int8 payload of a quantised kernel. #[cfg(test)] pub(crate) enum Fixture {@@ -457,6 +728,99 @@ mod tests { sign | ((exponent as u16) << 10) | ((mantissa >> 13) as u16) } + /// Write `bytes` into a temp file after `pad` bytes of filler, and return the file.+ ///+ /// The padding is the point: a `.maml` bundled as an asset is a *range* of the APK, not a file,+ /// so [`Streamed`] adds a base offset to every read. A fixture at offset 0 passes whether or not+ /// that offset is applied, which is the one thing worth checking here.+ fn on_disk(name: &str, pad: usize, bytes: &[u8]) -> (File, u64, u64) {+ use std::io::Write;+ let path = std::env::temp_dir().join(format!("modelrunner-{name}.maml"));+ let mut file = std::fs::File::create(&path).expect("a temp file");+ file.write_all(&vec![0xABu8; pad]).expect("the padding writes");+ file.write_all(bytes).expect("the blob writes");+ // Trailing filler as well, so the file does not end where the data section does: an asset+ // is followed by the next asset, and `Streamed` must not require otherwise.+ file.write_all(&[0xCDu8; 7]).expect("the trailer writes");+ drop(file);+ let opened = std::fs::File::open(&path).expect("the temp file reopens");+ (opened, pad as u64, bytes.len() as u64)+ }++ #[test]+ fn a_streamed_file_answers_exactly_as_a_parsed_one() {+ // The bundled path: the table is read from the file's prefix and the data section stays on+ // disk. Both halves must match what `Weights::parse` produces from the same bytes, because+ // `Net::new` uploads one and the plan was resolved against the other.+ let bytes = write(+ graph::SUPERTONIC_VE,+ &[(vec![2, 3], vec![1.0, 2.0, 4.0, 8.0, 16.0, 32.0]), (vec![2], vec![0.5, 0.25])],+ );+ let parsed = Weights::parse(&bytes, graph::SUPERTONIC_VE).expect("parses");+ let (file, at, len) = on_disk("streamed", 4096, &bytes);+ let streamed =+ Streamed::open(file, at, len, graph::SUPERTONIC_VE).expect("the file streams");++ assert_eq!(streamed.graph_id, parsed.graph_id);+ assert_eq!(streamed.len(), parsed.len());+ assert_eq!(streamed.data_len(), parsed.data_len());+ for index in 0..parsed.len() {+ assert_eq!(+ streamed.offsets().tensor(index).expect("in range"),+ parsed.tensor(index).expect("in range")+ );+ }+ // Byte for byte, and read in pieces rather than whole: the upload asks for chunks, so a+ // base offset applied once at open rather than per read would pass a single-read fixture.+ let mut got = vec![0u8; parsed.data_len() as usize];+ for (chunk, into) in got.chunks_mut(7).enumerate() {+ streamed.read_at((chunk * 7) as u64, into).expect("the chunk reads");+ }+ let mut want = vec![0u8; parsed.data_len() as usize];+ parsed.read_at(0, &mut want).expect("the whole section reads");+ assert_eq!(got, want);++ // And the host-side reads go through the same table and the same bytes.+ assert_eq!(+ streamed.reader().fp16(0, &[2, 3]).expect("the streamed tensor"),+ parsed.reader().fp16(0, &[2, 3]).expect("the parsed tensor")+ );+ }++ #[test]+ fn a_streamed_read_past_the_data_section_is_refused() {+ let bytes = write(graph::SUPERTONIC_DP, &[(vec![4], vec![1.0, 2.0, 3.0, 4.0])]);+ let (file, at, len) = on_disk("streamed-bounds", 16, &bytes);+ let streamed = Streamed::open(file, at, len, graph::SUPERTONIC_DP).expect("streams");++ let mut into = [0u8; 8];+ assert!(streamed.read_at(streamed.data_len() - 4, &mut into).is_err());+ assert!(streamed.read_at(u64::MAX, &mut into).is_err());+ // The trailing filler `on_disk` wrote is past the data section and must stay unreachable,+ // or a truncated `.maml` would upload whatever followed it in the APK.+ assert!(streamed.read_at(streamed.data_len(), &mut into[..1]).is_err());+ }++ #[test]+ fn a_streamed_file_shorter_than_its_own_header_says_is_refused() {+ // A length the caller was told, against a header that claims more. `AssetManager` reports+ // the range it will serve, so a disagreement means the asset was truncated at build time —+ // and the reads that ran off the end would land in the next asset rather than failing.+ let bytes = write(graph::SUPERTONIC_VOC, &[(vec![8], vec![1.0; 8])]);+ let (file, at, len) = on_disk("streamed-short", 0, &bytes);+ assert!(Streamed::open(file, at, len - 8, graph::SUPERTONIC_VOC).is_err());+ }++ #[test]+ fn a_streamed_file_for_another_graph_is_refused() {+ // The same check `Weights::parse` makes, and it has to happen here too: the four Supertonic+ // plans arrive as four descriptors in a fixed order, so a caller that swapped two would+ // otherwise upload the vocoder's weights into the text encoder's buffer.+ let bytes = write(graph::SUPERTONIC_TTL, &[(vec![2], vec![1.0, 2.0])]);+ let (file, at, len) = on_disk("streamed-wrong-graph", 32, &bytes);+ assert!(Streamed::open(file, at, len, graph::SUPERTONIC_VE).is_err());+ }+ #[test] fn the_table_outlives_the_blob_and_answers_identically() { // What `Net::rebuild` depends on: the offsets a plan resolves against do not come from the