speech: run whisper-base on the in-house runtime
- Commit
5063779e5ac3ffa91a064e6a6fdc9c5480f1b45c- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-29 06:35 UTC (3 months ago)
- Parents
0749dbf
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 d3c0fdc45c..adc61300e5 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@@ -246,6 +246,70 @@ internal object MlNative { */ external fun destroyTinyclip(handle: Long) + /**+ * Bring up whisper-base from its one `.maml` and the ids read from `generation_config.json`.+ * Returns 0 on failure.+ *+ * One graph, not two, as [createSmall100] is: the 51,865-row embedding is **tied** — the+ * decoder's input table and the logits kernel — so an encoder file and a decoder file would+ * upload 26.6 MB of it twice. Native selects between the encoder pass and a decode step by+ * re-recording one net.+ *+ * The plan arrives as a **file descriptor** because it is a bundled asset: [offset] and [length]+ * are the `AssetFileDescriptor`'s, since an asset is a *range of the APK* rather than a file of+ * its own. `AssetManager.openFd` throws for a deflated entry, which is what `noCompress +=+ * "maml"` in `speech/build.gradle.kts` is for. Native keeps the descriptor open for the life of+ * the handle, because the tied embedding is gathered a row at a time on the host.+ *+ * **The descriptor must be detached.** Native takes ownership and closes it, on the failure+ * paths as much as the successful one.+ *+ * The four id arrays come straight out of `generation_config.json`, because that file is the+ * model's and hardcoding its ids here would be a second place to get them wrong:+ * - [special] is exactly five values: `decoder_start_token_id`, `eos_token_id`,+ * `task_to_id.transcribe`, `no_timestamps_token_id`, `max_length`.+ * - [languages] is the 99 `<|xx|>` ids from `lang_to_id`, used to detect a language when none is+ * named. The **code to id** mapping stays in Kotlin.+ * - [suppress] is `suppress_tokens` and [suppressAtBegin] is `begin_suppress_tokens`.+ *+ * All four are validated here rather than per transcription, so a broken asset reports an+ * unavailable recogniser instead of producing wrong text.+ *+ * Freed by [destroyWhisper], not [destroy], [destroyOcr], [destroySupertonic],+ * [destroySmall100] or [destroyTinyclip].+ */+ external fun createWhisper(+ fd: Int,+ offset: Long,+ length: Long,+ special: IntArray,+ languages: IntArray,+ suppress: IntArray,+ suppressAtBegin: IntArray,+ ): Long++ /**+ * Transcribe one log-mel window into token ids, or null on failure.+ *+ * [mel] is `80 * 3000` floats row-major, from `WhisperFeatures.logMel` — 30 seconds at a+ * 160-sample hop, padded or truncated. [languageToken] is a `<|xx|>` id the caller resolved from+ * a code, or **negative** to let the model detect it.+ *+ * The ids come back **raw**, including any special or timestamp token the model emitted:+ * `WhisperTokenizer` is what skips the ids at or above 50,257 that have no text form. An empty+ * array means the window held nothing to transcribe, which is not a failure.+ *+ * Greedy decoding, capped at 224 tokens. Every step re-records the network, so this is slow+ * relative to a single forward pass and must not be called concurrently on one handle.+ */+ external fun transcribeWhisper(handle: Long, mel: FloatArray, languageToken: Int): IntArray?++ /**+ * Free whisper's network, its open weights file and both of its caches.+ * Exactly once per non-zero handle from [createWhisper].+ */+ external fun destroyWhisper(handle: Long)+ /** * Detect faces in [pixels] and return them flattened, nine floats per face. *
library/ml/src/main/java/com/vayunmathur/library/ml/WhisperHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/WhisperHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/WhisperHandle.ktnew file mode 100644index 0000000000..a72d1bb2c6--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/WhisperHandle.kt@@ -0,0 +1,182 @@+package com.vayunmathur.library.ml++import android.content.res.AssetManager+import android.os.ParcelFileDescriptor+import android.util.Log++/**+ * On-device speech recognition in ~99 languages: whisper-base on the Vulkan compute runtime.+ *+ * A two-convolution stem that turns `[80, 3000]` log-mel frames into 1500 positions, 6 encoder+ * layers, and 6 decoder layers with self and cross attention; `d_model` 512, 8 heads of 64, and a+ * 51,865-entry vocabulary tied between the input embedding and the logits projection. 72.6 million+ * parameters. See `library/ml/src/main/rust/src/nets/whisper.rs`.+ *+ * # One bundled asset, 70.6 MiB+ *+ * `whisper_base.maml` ships inside the APK, so this has an [inAssets] and no download. Everything+ * but the layer norms, the biases and the two position tables is int8, quantised per output channel+ * from `openai/whisper-base`'s fp32 checkpoint.+ *+ * It replaces `onnxruntime-android` running two int8 ONNX exports totalling 76.9 MB, and is **four+ * times closer** to the fp32 checkpoint than they were: over the encoder's output, mean absolute+ * error 0.029 against their 0.110, on a tensor whose largest value is 22.8. The APK loses ~27 MB of+ * arm64 `.so` with the runtime.+ *+ * 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 `speech/build.gradle.kts` is for.+ *+ * # The special ids come from the asset, not from here+ *+ * [inAssets] takes them as arguments rather than hardcoding them, because they live in the model's+ * own `generation_config.json` and a second copy would be a second thing to get wrong. The+ * `<|notimestamps|>` id in particular is part of the decoder prompt, and dropping it turns the+ * output into timestamped text rather than failing.+ *+ * # Latency+ *+ * The encoder is ~43.7 GMAC per 30-second window regardless of how much speech is in it, and every+ * decode step re-records the network because the self-attention cache grows. This is not a real-time+ * recogniser; call it from a worker.+ *+ * # Availability+ *+ * Construction never throws. [isAvailable] is false when `libmodelrunner.so` is missing for this+ * ABI, when the asset is absent, compressed or malformed, when the ids do not describe this model,+ * or when the device cannot give us a Vulkan device with fp16 compute — and then [transcribe]+ * returns null.+ *+ * # Threading+ *+ * Not thread-safe, and more sharply than most handles here: a transcription re-records the network+ * once per decoded token, so two concurrent calls would interleave recordings of the same command+ * buffer. A caller must hold a lock across [transcribe] and [close].+ */+class WhisperHandle private constructor(private val source: String) : AutoCloseable {+ private var handle: Long = 0L++ /** True if the graph came up and the ids describe the model it was built from. */+ val isAvailable: Boolean get() = handle != 0L++ /**+ * Transcribe one 30-second log-mel window into token ids, or null on failure.+ *+ * [mel] is `MELS * FRAMES` floats row-major. [languageToken] is a `<|xx|>` id, or negative to let+ * the model detect the language. The ids are raw — the caller's tokenizer skips the special and+ * timestamp ones.+ */+ fun transcribe(mel: FloatArray, languageToken: Int): IntArray? {+ if (handle == 0L) return null+ if (mel.size != MELS * FRAMES) return null+ return MlNative.transcribeWhisper(handle, mel, languageToken)+ }++ /** Free the network and close the weights file. Idempotent. */+ override fun close() {+ val live = handle+ handle = 0L+ if (live != 0L) MlNative.destroyWhisper(live)+ }++ override fun toString(): String = "whisper-base from $source"++ companion object {+ private const val TAG = "WhisperHandle"++ /** Mel bins the front end produces. */+ const val MELS = 80++ /** Mel frames in one 30-second window at a 160-sample hop. */+ const val FRAMES = 3000++ /** The one graph. Native checks its graph id, so a wrong file fails at load. */+ const val GRAPH = "whisper-base/whisper_base.maml"++ /**+ * The five values [inAssets] wants in `special`, in order:+ * `decoder_start_token_id`, `eos_token_id`, `transcribe`, `no_timestamps_token_id`,+ * `max_length`.+ */+ const val SPECIAL_IDS = 5++ /**+ * The model from the APK's assets, which is the only place it lives.+ *+ * `special`, `languages`, `suppress` and `suppressAtBegin` all come from the bundled+ * `generation_config.json`; see the class docs for why they are arguments.+ */+ fun inAssets(+ assets: AssetManager,+ special: IntArray,+ languages: IntArray,+ suppress: IntArray,+ suppressAtBegin: IntArray,+ path: String = GRAPH,+ ): WhisperHandle {+ val instance = WhisperHandle("the APK's $path")+ instance.handle = if (!MlNative.isAvailable || special.size != SPECIAL_IDS) {+ if (special.size != SPECIAL_IDS) {+ Log.e(TAG, "${special.size} special ids, not $SPECIAL_IDS")+ }+ 0L+ } else {+ try {+ create(assets, path, special, languages, suppress, suppressAtBegin)+ } catch (e: Throwable) {+ Log.e(TAG, "cannot open $path", e)+ 0L+ }+ }+ return instance+ }++ /**+ * Open the asset and hand the descriptor over.+ *+ * `use` rather than a bare `close`, and it is load-bearing in both directions — the same+ * argument [SupertonicSynthesizer]'s asset path makes. On the happy path the descriptor has+ * already been detached and `AssetFileDescriptor.close` 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.+ *+ * The inner `finally` covers the remaining window: after the descriptor has been given up+ * but before native has adopted it.+ */+ private fun create(+ assets: AssetManager,+ path: String,+ special: IntArray,+ languages: IntArray,+ suppress: IntArray,+ suppressAtBegin: IntArray,+ ): Long = assets.openFd(path).use { afd ->+ val fd = afd.parcelFileDescriptor.detachFd()+ var handed = false+ try {+ val handle = MlNative.createWhisper(+ fd,+ afd.startOffset,+ afd.length,+ special,+ languages,+ suppress,+ suppressAtBegin,+ )+ handed = true+ handle+ } finally {+ if (!handed) closeFd(fd)+ }+ }++ /**+ * Close a bare descriptor.+ *+ * Adopting it into a [ParcelFileDescriptor] is the only way to reach `close(2)` from Kotlin.+ * Failures are swallowed because the caller is already on an error path.+ */+ 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 692faee29b..4807d7a273 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -30,12 +30,12 @@ use std::fs::File; use std::os::fd::FromRawFd; use jni::objects::{JByteArray, JClass, JFloatArray, JIntArray, JLongArray, JString};-use jni::sys::{jfloatArray, jint, jlong, jstring};+use jni::sys::{jfloatArray, jint, jintArray, jlong, jstring}; use jni::JNIEnv; use crate::nets::{ mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, small100, supertonic_duration,- supertonic_sampler, supertonic_text, supertonic_vocoder, tinyclip, u2netp, Plan,+ supertonic_sampler, supertonic_text, supertonic_vocoder, tinyclip, u2netp, whisper, Plan, }; use crate::post::ctc::Dictionary; use crate::post::nms::{self, Face, Maps};@@ -43,6 +43,7 @@ use crate::post::ocr::{self, Line}; use crate::post::sentencepiece::Table; use crate::post::supertonic; use crate::post::translate;+use crate::post::whisper as whisper_post; use crate::preprocess::{ Letterbox, FACE_EMBED, IMAGENET, PPOCR_DET, PPOCR_REC, RESCALE_ONLY, SCRFD, };@@ -1604,6 +1605,324 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyTi drop(unsafe { Box::from_raw(handle as *mut TinyclipHandle) }); } +/// whisper-base, as `:speech` holds it. Handed to Kotlin as an opaque `jlong`.+///+/// # One net, two plans, and two kinds of cache+///+/// [`Reshaped`] keyed by [`whisper::Mode`]. The encoder runs once per utterance; a decode step is+/// re-recorded every token because its self-attention cache grows by one position, which is a+/// `device_wait_idle` and a re-record per token — the same known cost `Small100Handle` documents.+///+/// The **cross-attention** caches are the difference. Whisper's decoder cross-attends over 1500+/// encoder positions through each layer's own key and value projections, so recomputing them per+/// step would be 4.7 GMAC against the logits head's 26.5 MMAC. [`whisper::Mode::Encode`] computes+/// them once, they are held here, and each step passes them back in. See `nets::whisper`.+///+/// # The weights file stays open+///+/// [`whisper::embed_positions`] gathers a 1 KB embedding row per token out of the 26.6 MB tied table+/// on the host, so the [`Streamed`] is retained for the same reason SMaLL-100's is.+struct WhisperHandle {+ net: Reshaped<whisper::Mode>,+ weights: Streamed,+ /// Read from `generation_config.json` by Kotlin and checked once at construction.+ decoding: whisper_post::Decoding,+}++fn whisper_plan(offsets: &Offsets, mode: whisper::Mode) -> Result<Plan, String> {+ whisper::build(offsets, mode)+}++/// Cross-attention caches per decoder layer, K then V. See [`WhisperHandle`].+const WHISPER_CROSS: usize = whisper::DECODER_LAYERS * 2;++/// Self-attention caches per decoder layer, K then V.+const WHISPER_SELF: usize = whisper::DECODER_LAYERS * 2;++/// The two GPU passes, as [`whisper_post::Nets`] wants them, plus both kinds of cache.+///+/// Built per transcription and dropped with it, so neither cache can leak into the next utterance.+struct WhisperNets<'a> {+ net: &'a mut Reshaped<whisper::Mode>,+ weights: &'a Streamed,+ /// Each layer's cross-attention K then V, `[512 * 1500]` each, channel-major and constant for+ /// the whole transcript.+ cross: Vec<Vec<f32>>,+ /// Each layer's self-attention K then V for every position decoded so far, position-major and+ /// concatenated, `[step * 512]` each.+ past: Vec<Vec<f32>>,+}++impl WhisperNets<'_> {+ fn new<'a>(handle: &'a mut WhisperHandle) -> WhisperNets<'a> {+ WhisperNets {+ net: &mut handle.net,+ weights: &handle.weights,+ cross: Vec::new(),+ past: vec![Vec::new(); WHISPER_SELF],+ }+ }+}++impl whisper_post::Nets for WhisperNets<'_> {+ fn encode(&mut self, mel: &[f32]) -> Result<(), String> {+ let expected = whisper::MELS as usize * whisper::MEL_FRAMES as usize;+ if mel.len() != expected {+ return Err(format!("{} mel values, not {expected}", mel.len()));+ }+ let net = self.net.at(whisper::Mode::Encode)?;+ let mut out = net.infer_raw_many(&[mel])?;+ // Output 0 is the hidden states, which only the parity script reads; the twelve cross+ // caches follow, in layer order.+ if out.len() != 1 + WHISPER_CROSS {+ return Err(format!("the encoder returned {} tensors, not {}", out.len(), 1 + WHISPER_CROSS));+ }+ self.cross = out.split_off(1);+ Ok(())+ }++ fn decode_step(&mut self, token: u32, step: usize) -> Result<Vec<f32>, String> {+ if self.cross.len() != WHISPER_CROSS {+ return Err("a decode step before the encoder ran".into());+ }+ let width = whisper::D_MODEL as usize;+ let cache_len = u32::try_from(step).map_err(|_| "a step past u32")?;+ // The embedding row and the learned position, both on the host and summed in f32.+ let embedded = whisper::embed_positions(self.weights.reader(), &[token], cache_len)?;++ let net = self.net.at(whisper::Mode::DecodeStep { cache_len })?;+ // Declaration order: the token, the twelve cross caches, then the twelve self caches. The+ // self pairs are absent at step 0, where there is nothing before this token.+ let mut inputs: Vec<&[f32]> = Vec::with_capacity(1 + WHISPER_CROSS + WHISPER_SELF);+ inputs.push(&embedded);+ for held in &self.cross {+ inputs.push(held);+ }+ if cache_len > 0 {+ for held in &self.past {+ inputs.push(held);+ }+ }+ let out = net.infer_raw_many(&inputs)?;++ // The logits, then this step's K and V per layer.+ let expected = 1 + WHISPER_SELF;+ if out.len() != expected {+ return Err(format!("a decode step returned {} tensors, not {expected}", out.len()));+ }+ let mut out = out.into_iter();+ let logits = out.next().ok_or("no logits")?;+ if logits.len() != whisper::VOCAB as usize {+ return Err(format!("{} logits, not {}", logits.len(), whisper::VOCAB));+ }+ for (held, row) in self.past.iter_mut().zip(out) {+ if row.len() != width {+ return Err(format!("a cache row of {} values, not {width}", row.len()));+ }+ // Position-major, so appending is a plain extend and the plan's own concatenation of it+ // is one contiguous copy.+ held.extend_from_slice(&row);+ }+ Ok(logits)+ }+}++/// Bring up whisper-base from its one `.maml` and the ids read from `generation_config.json`.+///+/// Returns 0 on failure. The descriptor is an `AssetFileDescriptor`'s, so it carries an offset and a+/// length: the file is a range of the APK rather than a file of its own.+///+/// # Safety+///+/// Called only by the JVM, with a valid `env`, arrays it owns, and a descriptor nothing else holds.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createWhisper<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ fd: jint,+ offset: jlong,+ length: jlong,+ special: JIntArray<'l>,+ languages: JIntArray<'l>,+ suppress: JIntArray<'l>,+ suppress_at_begin: JIntArray<'l>,+) -> jlong {+ // The descriptor first, and adopted into an owning `File` before anything else may fail: the+ // caller detached it, so a path that returns without wrapping it leaks it for the life of the+ // process.+ if fd < 0 {+ log(&format!("whisper is unavailable: descriptor {fd} is not open"));+ return 0;+ }+ // SAFETY: the caller detached the descriptor, so nothing else owns it, and `File` closes it on+ // drop — including on every failure path below.+ let file = unsafe { File::from_raw_fd(fd) };+ let built = build_whisper(+ &mut env,+ file,+ offset,+ length,+ &special,+ &languages,+ &suppress,+ &suppress_at_begin,+ );+ match built {+ Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,+ Err(e) => {+ log(&format!("whisper is unavailable: {e}"));+ 0+ }+ }+}++/// The five scalars `createWhisper` takes in its `special` array, in order.+///+/// An array rather than five `jint` parameters because the JNI signature is already eight arguments+/// wide, and because these five arrive together out of one JSON file.+const WHISPER_SPECIAL: usize = 5;++#[allow(clippy::too_many_arguments)]+fn build_whisper<'l>(+ env: &mut JNIEnv<'l>,+ file: File,+ offset: jlong,+ length: jlong,+ special: &JIntArray<'l>,+ languages: &JIntArray<'l>,+ suppress: &JIntArray<'l>,+ suppress_at_begin: &JIntArray<'l>,+) -> Result<WhisperHandle, String> {+ let (at, len) = match (u64::try_from(offset), u64::try_from(length)) {+ (Ok(at), Ok(len)) => (at, len),+ _ => return Err(format!("the graph spans {offset}+{length}")),+ };+ let weights = Streamed::open(file, at, len, graph::WHISPER)?;+ if weights.len() != whisper::TENSORS {+ return Err(format!("a file of {} tensors, not {}", weights.len(), whisper::TENSORS));+ }++ let mut ids = |array: &JIntArray<'l>| -> Result<Vec<u32>, String> {+ read_int_array(env, array)?+ .into_iter()+ .map(|id| u32::try_from(id).map_err(|_| format!("{id} is not a token")))+ .collect()+ };+ let special = ids(special)?;+ let [start_of_transcript, end_of_text, transcribe, no_timestamps, max_length] =+ <[u32; WHISPER_SPECIAL]>::try_from(special.as_slice())+ .map_err(|_| format!("{} special ids, not {WHISPER_SPECIAL}", special.len()))?;+ let decoding = whisper_post::Decoding {+ start_of_transcript,+ end_of_text,+ transcribe,+ no_timestamps,+ max_length: max_length as usize,+ languages: ids(languages)?,+ suppress: ids(suppress)?,+ suppress_at_begin: ids(suppress_at_begin)?,+ };+ // Checked here rather than per transcription, so a broken `generation_config.json` fails at+ // construction — when the UI can still report the recogniser as unavailable.+ decoding.check(whisper::VOCAB)?;++ // Recorded on the encoder, which is what every transcription runs first.+ let net = Reshaped::streamed(+ context::shared()?,+ weights.offsets(),+ &weights,+ whisper::Mode::Encode,+ whisper_plan,+ )?;+ Ok(WhisperHandle { net, weights, decoding })+}++/// Transcribe one log-mel window into token ids, or null on failure.+///+/// `mel` is `[80 * 3000]` row-major, from `WhisperFeatures.logMel`. `language` is a `<|xx|>` token+/// the caller resolved from a code, or **negative** to detect.+///+/// The ids come back raw, including any special or timestamp token the model emitted:+/// `WhisperTokenizer` is what skips those, and it is unchanged by this port.+///+/// # Safety+///+/// `handle` must be a non-zero value from `createWhisper` that has not been destroyed.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_transcribeWhisper<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+ mel: JFloatArray<'l>,+ language: jint,+) -> jintArray {+ let null = std::ptr::null_mut();+ if handle == 0 {+ return null;+ }+ // SAFETY: the caller guarantees the handle came from `createWhisper` and is still live. It is+ // `&mut` because every step re-records the net, and Kotlin serialises calls on one handle.+ let handle = unsafe { &mut *(handle as *mut WhisperHandle) };+ let wanted = if language < 0 { None } else { u32::try_from(language).ok() };+ let ids = match read_float_array(&mut env, &mel) {+ Ok(values) => run_whisper(handle, &values, wanted),+ Err(e) => Err(e),+ };+ match ids.and_then(|ids| new_int_array(&mut env, &ids)) {+ Ok(array) => array,+ Err(e) => {+ log(&format!("whisper failed: {e}"));+ null+ }+ }+}++fn run_whisper(+ handle: &mut WhisperHandle,+ mel: &[f32],+ language: Option<u32>,+) -> Result<Vec<i32>, String> {+ // Cloned so the config can be read while the nets borrow the handle mutably. A hundred-odd ids+ // against a transcription that reads a 70 MiB file.+ let decoding = handle.decoding.clone();+ let mut nets = WhisperNets::new(handle);+ let ids = whisper_post::transcribe(&mut nets, &decoding, mel, language)?;+ ids.into_iter()+ .map(|id| i32::try_from(id).map_err(|_| format!("token {id} does not fit an int")))+ .collect()+}++/// Free whisper's net, its open weights file and both caches.+///+/// Exactly once per non-zero handle from `createWhisper`. When it is the last user of the shared+/// `VkDevice`, the device goes away with it.+///+/// # Safety+///+/// `handle` must be a non-zero value from `createWhisper`, and must not be used again.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyWhisper<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+) {+ if handle == 0 {+ return;+ }+ // SAFETY: the caller guarantees this handle came from `createWhisper` and has not been+ // destroyed. `Net`'s Drop waits for the device to go idle before freeing.+ drop(unsafe { Box::from_raw(handle as *mut WhisperHandle) });+}++fn new_int_array(env: &mut JNIEnv, values: &[i32]) -> Result<jintArray, String> {+ let array: JIntArray = env+ .new_int_array(values.len() as jint)+ .map_err(|e| format!("new_int_array: {e}"))?;+ env.set_int_array_region(&array, 0, values)+ .map_err(|e| format!("set_int_array_region: {e}"))?;+ Ok(array.into_raw())+}+ fn read_float_array(env: &mut JNIEnv, array: &JFloatArray) -> Result<Vec<f32>, String> { let len = env.get_array_length(array).map_err(|e| format!("array length: {e}"))?; let mut out = vec![0.0f32; len.max(0) as usize];
library/ml/src/main/rust/src/nets/whisper.rs
diff --git a/library/ml/src/main/rust/src/nets/whisper.rs b/library/ml/src/main/rust/src/nets/whisper.rsindex 93b166ceb0..12f307820b 100644--- a/library/ml/src/main/rust/src/nets/whisper.rs+++ b/library/ml/src/main/rust/src/nets/whisper.rs@@ -931,14 +931,15 @@ mod tests { out }; - let mut expected: Vec<Vec<u32>> = Vec::new();- expected.push(vec![D_MODEL, MELS, 1, CONV_KERNEL]);- expected.push(vec![D_MODEL]);- expected.push(vec![D_MODEL]);- expected.push(vec![D_MODEL, D_MODEL, 1, CONV_KERNEL]);- expected.push(vec![D_MODEL]);- expected.push(vec![D_MODEL]);- expected.push(vec![D_MODEL, 1, SOURCE_POSITIONS]);+ let mut expected: Vec<Vec<u32>> = vec![+ vec![D_MODEL, MELS, 1, CONV_KERNEL],+ vec![D_MODEL],+ vec![D_MODEL],+ vec![D_MODEL, D_MODEL, 1, CONV_KERNEL],+ vec![D_MODEL],+ vec![D_MODEL],+ vec![D_MODEL, 1, SOURCE_POSITIONS],+ ]; for _ in 0..ENCODER_LAYERS { expected.extend(layer(false)); }
library/ml/src/main/rust/src/post/mod.rs
diff --git a/library/ml/src/main/rust/src/post/mod.rs b/library/ml/src/main/rust/src/post/mod.rsindex 3a7fd86935..944624e749 100644--- a/library/ml/src/main/rust/src/post/mod.rs+++ b/library/ml/src/main/rust/src/post/mod.rs@@ -17,4 +17,5 @@ pub mod nms; pub mod sentencepiece; pub mod supertonic; pub mod translate;+pub mod whisper; pub mod ocr;
library/ml/src/main/rust/src/post/whisper.rs
diff --git a/library/ml/src/main/rust/src/post/whisper.rs b/library/ml/src/main/rust/src/post/whisper.rsnew file mode 100644index 0000000000..4cc59361a4--- /dev/null+++ b/library/ml/src/main/rust/src/post/whisper.rs@@ -0,0 +1,498 @@+//! whisper's decode loop: a log-mel window to a list of token ids, one token at a time.+//!+//! # Why this is here rather than in Kotlin+//!+//! It was in Kotlin, inside `WhisperOnnxEngine`, threading nineteen ONNX tensors per step. The two+//! GPU stages arrive here as a **trait** instead so the sequencing is host-testable against a+//! scripted stub — the pattern [`super::translate`], [`super::ocr`] and [`super::supertonic`] all+//! use — because the order of the special tokens is where the mistakes are and none of them needs a+//! device to catch.+//!+//! # The prompt is four tokens, and `<|notimestamps|>` is one of them+//!+//! ```text+//! <|startoftranscript|> <|xx|> <|transcribe|> <|notimestamps|>+//! 50258 lang 50359 50363+//! ```+//!+//! Dropping the last one does not fail: it changes the output from plain text to `<|0.00|>`-style+//! timestamped text, because the model was trained to predict a timestamp first unless told not to.+//! That is the same shape of hazard as SMaLL-100's "the target language goes on the source side",+//! and [`tests::the_prompt_is_four_tokens_ending_in_no_timestamps`] is what pins it.+//!+//! The reference feeds all four at once with `use_cache_branch=false`. This feeds them one at a+//! time, because [`crate::nets::whisper::Mode::DecodeStep`] is one query per step — and for a+//! causal decoder those are the same thing: token `t`'s hidden state depends only on tokens+//! `0..=t`, whichever order they were presented in. It costs three extra steps out of ~30.+//!+//! # Language detection is the first step's logits, not an extra pass+//!+//! With only `<|startoftranscript|>` fed, the highest-scoring **language token** is the detected+//! language — that is how whisper's own detection works. So step 0 is run whether or not the caller+//! named a language, and its logits are simply ignored when they did. No extra forward pass.+//!+//! The code-to-token table stays with the caller, as [`super::translate`]'s does: Kotlin already+//! reads `lang_to_id` out of `generation_config.json`, and duplicating 99 entries here would be two+//! places to get wrong.+//!+//! # Greedy, and the ids come back raw+//!+//! No beam search, matching the engine this replaces. And [`transcribe`] returns **token ids**, not+//! text: `WhisperTokenizer` is Kotlin, it is what skips the ids at or above 50,257 that have no text+//! form, and it stays untouched by this port.++/// Tokens the loop will emit before giving up.+///+/// One 30-second window cannot say more than this. It is the guard against a greedy decode that+/// never emits `<|endoftext|>`, which it can do by repeating itself, and it is the same 224 the+/// engine this replaces used.+pub const MAX_NEW_TOKENS: usize = 224;++/// Tokens the prompt occupies before the first generated one. See the module docs.+pub const PROMPT_TOKENS: usize = 4;++/// The special ids and suppression lists a decode needs, all read from `generation_config.json`.+///+/// Carried as a struct rather than as eight arguments because the caller builds it once, at+/// construction, and a decode is then one call. Every field is a `u32` id in the model's 51,865-entry+/// vocabulary; [`Decoding::check`] refuses anything outside it.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Decoding {+ /// `<|startoftranscript|>`, 50258. `decoder_start_token_id`.+ pub start_of_transcript: u32,+ /// `<|endoftext|>`, 50257. `eos_token_id`, and what ends the loop.+ pub end_of_text: u32,+ /// `<|transcribe|>`, 50359. **Not** `<|translate|>`, which is the id one lower and would+ /// produce English for every language.+ pub transcribe: u32,+ /// `<|notimestamps|>`, 50363. See the module docs for what dropping it does.+ pub no_timestamps: u32,+ /// `max_length`, 448, which is also the decoder's position table.+ pub max_length: usize,+ /// The 99 `<|xx|>` language ids, in any order. Scored against each other when the caller did+ /// not name a language.+ pub languages: Vec<u32>,+ /// Never-emit ids — music notes and formatting artefacts — that upstream masks out.+ pub suppress: Vec<u32>,+ /// Additionally suppressed at the **first generated position only**: a leading space and+ /// `<|endoftext|>`, so a window with speech in it cannot return nothing.+ pub suppress_at_begin: Vec<u32>,+}++impl Decoding {+ /// Refuse a configuration that cannot have come from this model's `generation_config.json`.+ ///+ /// Checked at construction rather than per decode, and loudly: every one of these is an id the+ /// loop feeds or compares against, so a wrong one produces confident wrong text.+ pub fn check(&self, vocabulary: u32) -> Result<(), String> {+ let named = [+ ("start_of_transcript", self.start_of_transcript),+ ("end_of_text", self.end_of_text),+ ("transcribe", self.transcribe),+ ("no_timestamps", self.no_timestamps),+ ];+ for (what, id) in named {+ if id >= vocabulary {+ return Err(format!("{what} is {id}, past the {vocabulary}-entry vocabulary"));+ }+ }+ if self.languages.is_empty() {+ return Err("no language tokens, so a language can be neither named nor detected".into());+ }+ if let Some(&id) = self.languages.iter().find(|&&id| id >= vocabulary) {+ return Err(format!("language token {id} is past the vocabulary"));+ }+ if self.max_length <= PROMPT_TOKENS {+ return Err(format!(+ "max_length {} leaves nothing after the {PROMPT_TOKENS}-token prompt",+ self.max_length+ ));+ }+ Ok(())+ }++ /// Tokens the loop may generate: whatever the position table has left, capped at+ /// [`MAX_NEW_TOKENS`].+ fn budget(&self) -> usize {+ self.max_length.saturating_sub(PROMPT_TOKENS).min(MAX_NEW_TOKENS)+ }+}++/// The two GPU stages, as a trait, so the loop below is host-testable.+pub trait Nets {+ /// The encoder over one 30-second log-mel window, `[80 * 3000]` row-major.+ ///+ /// Run once. It also computes every decoder layer's cross-attention keys and values, which the+ /// implementation retains — so unlike [`super::translate::Nets`] nothing is handed back here.+ fn encode(&mut self, mel: &[f32]) -> Result<(), String>;++ /// One decoder step: the token in, the logits over the whole vocabulary out.+ ///+ /// `step` is the position, so the implementation knows how long its self-attention cache should+ /// be and where to append this token's key and value.+ fn decode_step(&mut self, token: u32, step: usize) -> Result<Vec<f32>, String>;+}++/// Transcribe one log-mel window into token ids, for the caller's tokenizer to decode.+///+/// `language` is a `<|xx|>` token the caller resolved from a code, or `None` to detect. An unknown+/// code should arrive as `None` rather than as a guess: detection is what whisper does by default+/// and is better than the wrong language.+///+/// An empty result means the window held nothing the model would transcribe, which is not a failure.+pub fn transcribe(+ nets: &mut dyn Nets,+ config: &Decoding,+ mel: &[f32],+ language: Option<u32>,+) -> Result<Vec<u32>, String> {+ if let Some(id) = language {+ if !config.languages.contains(&id) {+ return Err(format!("{id} is not one of the {} language tokens", config.languages.len()));+ }+ }+ nets.encode(mel)?;++ // Step 0 is `<|startoftranscript|>` alone, and its logits are the language distribution — which+ // is run whether or not the caller named a language, because the token has to be fed either way.+ let mut logits = nets.decode_step(config.start_of_transcript, 0)?;+ let language = match language {+ Some(id) => id,+ None => best_of(&logits, &config.languages)+ .ok_or("the decoder scored no language token at step 0")?,+ };+ // The rest of the prompt. Each of these three positions' logits is discarded: the model is+ // predicting the next *prompt* token, which is already decided.+ for (offset, token) in [language, config.transcribe, config.no_timestamps].into_iter().enumerate()+ {+ logits = nets.decode_step(token, 1 + offset)?;+ }++ // `logits` now predicts the first token of the transcript.+ let mut produced: Vec<u32> = Vec::new();+ let budget = config.budget();+ for index in 0..budget {+ let begin: &[u32] = if index == 0 { &config.suppress_at_begin } else { &[] };+ let next = argmax(&logits, &config.suppress, begin).ok_or_else(|| {+ format!("the decoder returned {} usable logits at token {index}", logits.len())+ })?;+ if next == config.end_of_text {+ break;+ }+ produced.push(next);+ if produced.len() == budget {+ // The budget is spent, so there is no next token to predict and no step to run for it.+ break;+ }+ logits = nets.decode_step(next, PROMPT_TOKENS + index)?;+ }+ Ok(produced)+}++/// The highest-scoring id among `candidates`, or `None` if none of them is in range.+///+/// Used for language detection, which scores the 99 language tokens against each other and ignores+/// every other logit — including the far larger text ones, which is why this is not an `argmax` with+/// a mask.+fn best_of(logits: &[f32], candidates: &[u32]) -> Option<u32> {+ let mut best: Option<(u32, f32)> = None;+ for &id in candidates {+ let Some(&value) = logits.get(id as usize) else {+ continue;+ };+ if value.is_nan() {+ continue;+ }+ if best.is_none_or(|(_, top)| value > top) {+ best = Some((id, value));+ }+ }+ best.map(|(id, _)| id)+}++/// The index of the largest value, skipping every id in `suppress` or `also`.+///+/// Ties take the lowest index, which is what `argmax` does everywhere else here and what makes a+/// greedy decode reproducible. NaN never wins, so a net that produced one degrades to picking some+/// other token rather than to whichever comparison happened first.+fn argmax(logits: &[f32], suppress: &[u32], also: &[u32]) -> Option<u32> {+ let mut best: Option<(usize, f32)> = None;+ for (index, &value) in logits.iter().enumerate() {+ if value.is_nan() {+ continue;+ }+ let id = index as u32;+ if suppress.contains(&id) || also.contains(&id) {+ continue;+ }+ if best.is_none_or(|(_, top)| value > top) {+ best = Some((index, value));+ }+ }+ best.map(|(index, _)| index as u32)+}++#[cfg(test)]+mod tests {+ use super::*;++ /// The real ids, from `generation_config.json`, so the fixtures below are the shipping prompt.+ const SOT: u32 = 50_258;+ const EOT: u32 = 50_257;+ const TRANSCRIBE: u32 = 50_359;+ const NO_TIMESTAMPS: u32 = 50_363;+ const EN: u32 = 50_259;+ const FR: u32 = 50_265;++ fn config() -> Decoding {+ Decoding {+ start_of_transcript: SOT,+ end_of_text: EOT,+ transcribe: TRANSCRIBE,+ no_timestamps: NO_TIMESTAMPS,+ max_length: 448,+ languages: vec![EN, FR],+ // 220 is the leading space and 50257 the end of text, which is `begin_suppress_tokens`.+ suppress: vec![1, 2, 7],+ suppress_at_begin: vec![220, EOT],+ }+ }++ /// Records what the loop asked for, and answers with a scripted sequence of tokens.+ struct Scripted {+ /// One winning token per *generated* position; the prompt's three discarded steps are not+ /// scripted, because their logits are never read.+ script: Vec<u32>,+ /// Every `(token, step)` the decoder saw, in order.+ steps: Vec<(u32, usize)>,+ /// The mel the encoder was given, so a test can assert it ran exactly once.+ encoded: usize,+ /// Scores for the language tokens at step 0, so detection can be steered.+ language_scores: Vec<(u32, f32)>,+ vocabulary: usize,+ }++ impl Nets for Scripted {+ fn encode(&mut self, mel: &[f32]) -> Result<(), String> {+ assert_eq!(mel.len(), 80 * 3000, "the mel window is a fixed size");+ self.encoded += 1;+ Ok(())+ }++ fn decode_step(&mut self, token: u32, step: usize) -> Result<Vec<f32>, String> {+ self.steps.push((token, step));+ let mut logits = vec![0.0f32; self.vocabulary];+ if step == 0 {+ for &(id, score) in &self.language_scores {+ logits[id as usize] = score;+ }+ return Ok(logits);+ }+ // Positions 1 and 2 are prompt steps whose logits are discarded; position 3 predicts+ // the first transcript token, and position `3 + n` the token after the nth.+ let wanted = step.saturating_sub(PROMPT_TOKENS - 1);+ let token = self.script.get(wanted).copied().unwrap_or(EOT);+ logits[token as usize] = 1.0;+ Ok(logits)+ }+ }++ fn scripted(script: &[u32]) -> Scripted {+ Scripted {+ script: script.to_vec(),+ steps: Vec::new(),+ encoded: 0,+ // English wins unless a test says otherwise.+ language_scores: vec![(EN, 2.0), (FR, 1.0)],+ vocabulary: 51_865,+ }+ }++ fn mel() -> Vec<f32> {+ vec![0.25; 80 * 3000]+ }++ #[test]+ fn the_prompt_is_four_tokens_ending_in_no_timestamps() {+ // The trap this module exists to document. `<|notimestamps|>` last, at position 3, is what+ // keeps the output plain text; dropping it produces `<|0.00|>`-style output that still+ // decodes and still reads like a transcript.+ let mut nets = scripted(&[100, EOT]);+ let out = transcribe(&mut nets, &config(), &mel(), None).expect("transcribes");+ assert_eq!(out, vec![100]);+ let prompt: Vec<(u32, usize)> = nets.steps.iter().take(PROMPT_TOKENS).copied().collect();+ assert_eq!(+ prompt,+ vec![(SOT, 0), (EN, 1), (TRANSCRIBE, 2), (NO_TIMESTAMPS, 3)],+ "{:?}",+ nets.steps+ );+ }++ #[test]+ fn the_language_is_detected_from_step_zero_and_needs_no_extra_pass() {+ // With only `<|startoftranscript|>` fed, the highest-scoring language token is the answer.+ // Step 0 runs either way, so detection is free.+ let mut nets = scripted(&[EOT]);+ nets.language_scores = vec![(EN, 0.5), (FR, 3.0)];+ transcribe(&mut nets, &config(), &mel(), None).expect("transcribes");+ assert_eq!(nets.steps[1], (FR, 1));+ // One encoder run, and the language was fed exactly once: detection cost no extra pass.+ assert_eq!(nets.encoded, 1);+ let languages = nets+ .steps+ .iter()+ .filter(|(token, _)| config().languages.contains(token))+ .count();+ assert_eq!(languages, 1, "{:?}", nets.steps);+ }++ #[test]+ fn a_named_language_wins_over_the_scores() {+ // An explicit code beats detection, and the detection logits are simply ignored — which is+ // why step 0 still runs.+ let mut nets = scripted(&[EOT]);+ nets.language_scores = vec![(EN, 9.0), (FR, 0.0)];+ transcribe(&mut nets, &config(), &mel(), Some(FR)).expect("transcribes");+ assert_eq!(nets.steps[1], (FR, 1));+ }++ #[test]+ fn a_language_token_the_model_does_not_have_is_refused() {+ // The caller resolves a code to a token, so a wrong table there would otherwise feed a text+ // id into the prompt and produce confident nonsense.+ let mut nets = scripted(&[EOT]);+ let error = transcribe(&mut nets, &config(), &mel(), Some(42)).expect_err("a text id");+ assert!(error.contains("language tokens"), "{error}");+ assert_eq!(nets.encoded, 0, "the encoder ran before the check");+ }++ #[test]+ fn each_step_feeds_the_previous_token_back_after_the_prompt() {+ // Greedy decoding is a chain, and the step numbering continues from the prompt: the first+ // generated token is fed at position 4, not at 0.+ let mut nets = scripted(&[100, 101, 102, EOT]);+ let out = transcribe(&mut nets, &config(), &mel(), Some(EN)).expect("transcribes");+ assert_eq!(out, vec![100, 101, 102]);+ assert_eq!(+ nets.steps,+ vec![+ (SOT, 0),+ (EN, 1),+ (TRANSCRIBE, 2),+ (NO_TIMESTAMPS, 3),+ (100, 4),+ (101, 5),+ (102, 6),+ ]+ );+ }++ #[test]+ fn end_of_text_ends_the_loop_and_is_not_emitted() {+ let mut nets = scripted(&[100, 101, EOT, 102]);+ let out = transcribe(&mut nets, &config(), &mel(), Some(EN)).expect("transcribes");+ assert_eq!(out, vec![100, 101]);+ // Four prompt steps plus two generated ones: the step that would have fed `EOT` never ran.+ assert_eq!(nets.steps.len(), PROMPT_TOKENS + 2);+ }++ #[test]+ fn end_of_text_at_the_first_position_is_suppressed() {+ // `begin_suppress_tokens` is `[220, 50257]`, so a window with speech in it cannot come back+ // empty because the model was unsure. Without it this returns nothing.+ let mut nets = scripted(&[EOT]);+ // Make `EOT` the strongest and 100 the runner-up at the first position only.+ nets.script = vec![EOT];+ let mut config = config();+ config.suppress_at_begin = vec![220, EOT];+ let out = transcribe(&mut nets, &config, &mel(), Some(EN)).expect("transcribes");+ // Suppressed, so the loop picks *something* rather than stopping immediately.+ assert!(!out.is_empty(), "the first position returned nothing");+ assert_ne!(out[0], EOT);+ // And a leading space is suppressed there too.+ assert_ne!(out[0], 220);+ }++ #[test]+ fn a_suppressed_id_is_never_emitted_at_any_position() {+ let mut config = config();+ config.suppress = vec![100];+ let mut nets = scripted(&[100, 100, EOT]);+ let out = transcribe(&mut nets, &config, &mel(), Some(EN)).expect("transcribes");+ assert!(!out.contains(&100), "{out:?}");+ }++ #[test]+ fn a_decoder_that_never_stops_is_capped() {+ // Greedy decoding can loop forever by repeating itself, and the position table is only 448+ // deep, so the loop stops rather than running past it.+ let mut nets = scripted(&vec![100u32; MAX_NEW_TOKENS + 50]);+ let out = transcribe(&mut nets, &config(), &mel(), Some(EN)).expect("transcribes");+ assert_eq!(out.len(), MAX_NEW_TOKENS);+ // And it did not run a step for a token it had no room to predict from.+ assert_eq!(nets.steps.len(), PROMPT_TOKENS + MAX_NEW_TOKENS - 1);+ // The last step is at position `3 + 223`, comfortably inside the 448-entry table.+ assert!(nets.steps.last().expect("a step").1 < 448);+ }++ #[test]+ fn a_short_max_length_caps_the_loop_before_the_token_budget_does() {+ // `max_length` is the position table, and the prompt spends four of it. A configuration that+ // shrank it must shorten the transcript rather than overrun the table.+ let mut config = config();+ config.max_length = PROMPT_TOKENS + 3;+ assert_eq!(config.budget(), 3);+ let mut nets = scripted(&vec![100u32; 50]);+ let out = transcribe(&mut nets, &config, &mel(), Some(EN)).expect("transcribes");+ assert_eq!(out.len(), 3);+ }++ #[test]+ fn a_configuration_outside_the_vocabulary_is_refused() {+ let vocabulary = 51_865;+ config().check(vocabulary).expect("the real ids are in range");++ let mut wrong = config();+ wrong.no_timestamps = vocabulary;+ let error = wrong.check(vocabulary).expect_err("past the vocabulary");+ assert!(error.contains("no_timestamps"), "{error}");++ let mut wrong = config();+ wrong.languages.clear();+ let error = wrong.check(vocabulary).expect_err("no languages");+ assert!(error.contains("language tokens"), "{error}");++ let mut wrong = config();+ wrong.max_length = PROMPT_TOKENS;+ let error = wrong.check(vocabulary).expect_err("no room");+ assert!(error.contains("max_length"), "{error}");+ }++ #[test]+ fn argmax_takes_the_lowest_index_of_a_tie_and_skips_nan() {+ assert_eq!(argmax(&[1.0, 3.0, 3.0, 2.0], &[], &[]), Some(1));+ assert_eq!(argmax(&[f32::NAN, 1.0], &[], &[]), Some(1));+ assert_eq!(argmax(&[f32::NAN], &[], &[]), None);+ assert_eq!(argmax(&[], &[], &[]), None);+ // Negative logits are normal — a softmax was never taken.+ assert_eq!(argmax(&[-5.0, -1.0, -9.0], &[], &[]), Some(1));+ // Suppression applies before the comparison, not after.+ assert_eq!(argmax(&[1.0, 9.0, 2.0], &[1], &[]), Some(2));+ assert_eq!(argmax(&[1.0, 9.0, 2.0], &[], &[1, 2]), Some(0));+ }++ #[test]+ fn language_detection_ignores_every_non_language_logit() {+ // A text token will always outscore a language token on a real window, so scoring the+ // language ids against *each other* is the whole of the method.+ let mut logits = vec![0.0f32; 51_865];+ logits[100] = 99.0;+ logits[EN as usize] = 1.0;+ logits[FR as usize] = 2.0;+ assert_eq!(best_of(&logits, &[EN, FR]), Some(FR));+ // An id past the end is skipped rather than panicking.+ assert_eq!(best_of(&logits, &[EN, 99_999]), Some(EN));+ assert_eq!(best_of(&logits, &[]), None);+ }+}
speech/build.gradle.kts
diff --git a/speech/build.gradle.kts b/speech/build.gradle.ktsindex 3a1e68f892..a8c41adb91 100644--- a/speech/build.gradle.kts+++ b/speech/build.gradle.kts@@ -16,30 +16,26 @@ android { } androidResources {- // ORT mmaps the model out of the APK; a deflated asset would have to be inflated to- // a 40 MB heap buffer first. Storing them uncompressed costs nothing on download size- // either - int8 weights are already incompressible.- noCompress += "onnx" // Load-bearing, not an optimisation. `AssetManager.openFd` throws for a deflated entry,- // and the fd is how Supertonic's ~105 MB of weights reach the GPU without being copied- // through the Java heap three times - see SupertonicSynthesizer.inAssets.+ // and the fd is how Supertonic's ~105 MB and whisper-base's 70.6 MiB of weights reach the+ // GPU without being copied through the Java heap three times - see+ // SupertonicSynthesizer.inAssets and WhisperHandle.inAssets. It costs nothing on download+ // size either: int8 and fp16 weights are already incompressible. noCompress += "maml" } } dependencies {- // Text-to-speech is Supertonic 3 on :library:ml, our own Vulkan compute runtime. Four networks- // for all 31 languages, every one of them on the GPU: the duration predictor, the text encoder,- // a flow-matching sampler and a ConvNeXt vocoder. The bundle ships in `assets/supertonic/` and- // is streamed from a file descriptor, which is what `noCompress += "maml"` above is for.- implementation(project(":library:ml"))- // Speech-to-text is whisper-base int8 ONNX (bundled in assets, see WhisperOnnxEngine).- // It is not ncnn: onnx2ncnn has no DynamicQuantizeLinear/MatMulInteger/ConvInteger- // support, and the AAR's Whisper expects a six-net decomposition HF does not export.+ // Both directions run on :library:ml, our own Vulkan compute runtime, and this app links no+ // third-party inference runtime at all.+ //+ // Text-to-speech is Supertonic 3: four networks for all 31 languages, every one of them on the+ // GPU - the duration predictor, the text encoder, a flow-matching sampler and a ConvNeXt+ // vocoder. Speech-to-text is whisper-base, one 70.6 MiB `.maml` holding a 6-layer audio encoder+ // and a 6-layer KV-cached decoder, with the decode loop in `post::whisper`. //- // Reduced ORT build (10 MB native, vs 28 MB for the full one). Its operator set is- // generated from the two bundled .onnx files, so if they are ever re-exported with- // different ops the session will fail to create - regenerate the AAR, don't work around it.- implementation(libs.onnxruntime.reduced)+ // Both bundles ship in `assets/` and are streamed from a file descriptor, which is what+ // `noCompress += "maml"` above is for.+ implementation(project(":library:ml")) // No `:library:downloadservice` and no DataStore: both models ship in the APK, so this app // downloads nothing and stores no preferences. They went when Piper's 1,834 MB of voices did. }
speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.kt b/speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.ktindex 2091273cd3..978e5df7a4 100644--- a/speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.kt+++ b/speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.kt@@ -1,33 +1,191 @@ package com.vayunmathur.speech.util import android.content.Context+import android.util.Log+import com.vayunmathur.library.ml.WhisperHandle+import org.json.JSONObject /** * Speech-to-text entry point for [com.vayunmathur.speech.service.WhisperRecognitionService]. *- * Kept as a thin seam over [WhisperOnnxEngine] so the recognition service is agnostic about the- * backend: swapping the int8 ONNX path back for the ncnn AAR (or forward to a larger model) is a- * change to this one file. Not thread-safe — call [transcribe] from a single worker thread.+ * A thin seam over [WhisperHandle], which runs **whisper-base** on `:library:ml`'s Vulkan compute+ * runtime. It replaced `WhisperOnnxEngine` and with it the last `onnxruntime-android` dependency in+ * the tree: the two int8 ONNX exports (76.9 MB) became one 70.6 MiB `.maml`, and ~27 MB of arm64+ * `.so` left the APK.+ *+ * The port is also **four times closer** to the fp32 checkpoint than the exports were — mean absolute+ * error 0.029 against 0.110 over the encoder's output — because it quantises per output channel where+ * onnxruntime's dynamic quantiser did it per tensor. See+ * `library/ml/src/main/rust/src/nets/whisper.rs`.+ *+ * # What stayed in Kotlin+ *+ * [WhisperFeatures] (the mel front end) and [WhisperTokenizer] (byte-level decode), both unchanged.+ * The mel is pinned against HuggingFace by `WhisperFeaturesTest` and a wrong one produces confident+ * nonsense rather than an error, so it was not worth reimplementing. The **decode loop** did move:+ * it is `post::whisper` now, host-tested against a scripted stub.+ *+ * # The ids come out of the asset+ *+ * [GenerationConfig] reads `generation_config.json`, as the ONNX engine did, and hands the ids to+ * native. Nothing here hardcodes them — `<|notimestamps|>` especially, because dropping it turns the+ * transcript into timestamped text rather than failing.+ *+ * Not thread-safe: a transcription re-records the network once per token. Call [transcribe] from a+ * single worker thread. */ class WhisperEngine(context: Context) {+ private val app = context.applicationContext+ private val lock = Any()++ private var whisper: WhisperHandle? = null+ private var tokenizer: WhisperTokenizer? = null+ private var config: GenerationConfig? = null+ private var loadFailed = false++ /** Ids and token maps read from `generation_config.json` rather than hardcoded. */+ private class GenerationConfig(json: JSONObject) {+ val startOfTranscript = json.optInt("decoder_start_token_id", 50258)+ val endOfText = json.optInt("eos_token_id", 50257)+ val noTimestamps = json.optInt("no_timestamps_token_id", 50363)+ val maxLength = json.optInt("max_length", 448)++ /** `<|transcribe|>`; `<|translate|>` is the id one lower and unused here. */+ val transcribe: Int =+ json.optJSONObject("task_to_id")?.optInt("transcribe", 50359) ?: 50359++ /** ISO-639-1 code to its `<|xx|>` token id, e.g. `en` to 50259. */+ val langToId: Map<String, Int> = buildMap {+ val obj = json.optJSONObject("lang_to_id") ?: return@buildMap+ for (key in obj.keys()) {+ // Keys arrive as "<|en|>"; store the bare code.+ put(key.removePrefix("<|").removeSuffix("|>"), obj.optInt(key))+ }+ } - private val engine = WhisperOnnxEngine(context.applicationContext)+ /** Never-emit ids (music notes, formatting artefacts) that upstream masks out. */+ val suppress: IntArray = ids(json, "suppress_tokens")++ /** Additionally suppressed at the very first generated position (leading space, EOT). */+ val suppressAtBegin: IntArray = ids(json, "begin_suppress_tokens")++ /** The five scalars native wants, in [WhisperHandle]'s documented order. */+ val special: IntArray =+ intArrayOf(startOfTranscript, endOfText, transcribe, noTimestamps, maxLength)++ private companion object {+ fun ids(json: JSONObject, key: String): IntArray {+ val array = json.optJSONArray(key) ?: return IntArray(0)+ return IntArray(array.length()) { array.optInt(it) }+ }+ }+ } /**- * Whether the recogniser can run. The models ship in the APK, so this is now only false if- * they fail to load — never because something still needs downloading.+ * Whether the recogniser can run. The model ships in the APK, so this is only false if it fails+ * to load — never because something still needs downloading. */- fun isModelPresent(): Boolean = engine.isAvailable()+ fun isModelPresent(): Boolean = ensure() /** Load the model now (e.g. to warm up off the main thread). Returns true if ready. */- fun preload(): Boolean = engine.isAvailable()+ fun preload(): Boolean = ensure()++ @Synchronized+ private fun ensure(): Boolean {+ whisper?.let { return true }+ if (loadFailed) return false+ loadFailed = true+ val cfg = try {+ GenerationConfig(+ JSONObject(+ app.assets.open("${WhisperModel.DIR}/$GEN_CONFIG").use {+ it.bufferedReader().readText()+ },+ ),+ )+ } catch (t: Throwable) {+ Log.e(TAG, "cannot read $GEN_CONFIG", t)+ return false+ }+ val tok = try {+ app.assets.open("${WhisperModel.DIR}/$VOCAB").use { WhisperTokenizer.load(it) }+ } catch (t: Throwable) {+ Log.e(TAG, "cannot read $VOCAB", t)+ return false+ }+ // Construction never throws: an absent, compressed or malformed asset, a missing+ // `libmodelrunner.so`, ids that do not describe this model, and a device without fp16+ // compute all come back unavailable.+ val handle = WhisperHandle.inAssets(+ app.assets,+ cfg.special,+ cfg.langToId.values.toIntArray(),+ cfg.suppress,+ cfg.suppressAtBegin,+ )+ if (!handle.isAvailable) {+ Log.e(TAG, "cannot bring up $handle")+ handle.close()+ return false+ }+ whisper = handle+ tokenizer = tok+ config = cfg+ loadFailed = false+ Log.i(TAG, "whisper-base ready (${cfg.langToId.size} languages)")+ return true+ } /** * Transcribe [pcm16k] (16 kHz mono). [language] is ISO-639-1 or null/"auto" for automatic- * detection. Returns the text, or null if the model isn't ready/failed.+ * detection. Returns the text, or null if the model isn't ready or inference failed. */- fun transcribe(pcm16k: ShortArray, language: String?): String? =- engine.transcribe(pcm16k, language)+ fun transcribe(pcm16k: ShortArray, language: String?): String? {+ if (!ensure()) return null+ val cfg = config ?: return null+ val tok = tokenizer ?: return null+ return try {+ val mel = WhisperFeatures.logMel(pcm16k)+ val ids = synchronized(lock) { whisper?.transcribe(mel, languageToken(cfg, language)) }+ ?: return null+ tok.decode(ids.toList())+ } catch (t: Throwable) {+ Log.e(TAG, "transcribe failed", t)+ null+ }+ }++ /**+ * The `<|xx|>` id for [requested], or **-1** to let the model detect the language.+ *+ * An unrecognised code detects rather than falling back to English: whisper's own detection is+ * what it does by default, and it beats confidently transcribing Japanese as English.+ */+ private fun languageToken(cfg: GenerationConfig, requested: String?): Int {+ val code = requested?.substringBefore('-')?.lowercase()+ if (code == null || code == "auto") return DETECT+ cfg.langToId[code]?.let { return it }+ Log.w(TAG, "no Whisper language token for '$requested', detecting instead")+ return DETECT+ }++ @Synchronized+ fun close() {+ synchronized(lock) {+ runCatching { whisper?.close() }+ whisper = null+ }+ tokenizer = null+ config = null+ loadFailed = false+ }++ private companion object {+ const val TAG = "WhisperEngine"+ const val VOCAB = "vocab.json"+ const val GEN_CONFIG = "generation_config.json" - fun close() = engine.close()+ /** What native reads as "detect the language yourself". */+ const val DETECT = -1+ } }
speech/src/main/java/com/vayunmathur/speech/util/WhisperModel.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/util/WhisperModel.kt b/speech/src/main/java/com/vayunmathur/speech/util/WhisperModel.ktindex 04e9786ff6..94027637d9 100644--- a/speech/src/main/java/com/vayunmathur/speech/util/WhisperModel.kt+++ b/speech/src/main/java/com/vayunmathur/speech/util/WhisperModel.kt@@ -3,23 +3,26 @@ package com.vayunmathur.speech.util import android.content.Context /**- * Asset location of the offline **Whisper-base** (multilingual, ~99 languages) recogniser.+ * Asset location of the offline **whisper-base** (multilingual, ~99 languages) recogniser. *- * These files used to be a 117 MB runtime download of the ncnn conversion. They are now the int8- * ONNX export bundled in the APK under `assets/`[DIR] and read by [WhisperOnnxEngine], so there- * is no download, no progress and no mirror involved — see- * `scripts/speech/fetch_whisper_onnx.sh` for how the vendored copies are refreshed.+ * These files used to be a 117 MB runtime download of an ncnn conversion, then two int8 ONNX exports+ * bundled in the APK. They are now one 70.6 MiB `whisper_base.maml`, read by [WhisperEngine] through+ * `:library:ml` — see `scripts/ml/fetch_whisper.py` for how it is rebuilt from+ * `openai/whisper-base`'s pinned checkpoint. */ object WhisperModel { const val DIR = "whisper-base" + /** The graph, relative to [DIR]. The two `generation_config.json`/`vocab.json` sit beside it. */+ const val GRAPH = "whisper_base.maml"+ /**- * True if the bundled models are readable. Barring a corrupt install this is always true;- * it exists so the setup screen can report a broken build rather than silently failing to+ * True if the bundled model is readable. Barring a corrupt install this is always true; it+ * exists so the setup screen can report a broken build rather than silently failing to * transcribe. */ fun isReady(context: Context): Boolean = try {- context.assets.list(DIR)?.contains("encoder_model_int8.onnx") == true+ context.assets.list(DIR)?.contains(GRAPH) == true } catch (_: Throwable) { false }
speech/src/main/java/com/vayunmathur/speech/util/WhisperOnnxEngine.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/util/WhisperOnnxEngine.kt b/speech/src/main/java/com/vayunmathur/speech/util/WhisperOnnxEngine.ktdeleted file mode 100644index 5500f43ac7..0000000000--- a/speech/src/main/java/com/vayunmathur/speech/util/WhisperOnnxEngine.kt+++ /dev/null@@ -1,357 +0,0 @@-package com.vayunmathur.speech.util--import ai.onnxruntime.OnnxTensor-import ai.onnxruntime.OrtEnvironment-import ai.onnxruntime.OrtSession-import android.content.Context-import android.util.Log-import java.nio.FloatBuffer-import java.nio.LongBuffer-import org.json.JSONObject--/**- * Offline **whisper-base** speech recognition on ONNX Runtime, reading the int8 models straight- * out of the APK's assets (see `speech/src/main/assets/whisper-base/`, refreshed by- * `scripts/speech/fetch_whisper_onnx.sh`).- *- * Replaces the old ncnn `Whisper` AAR path, which needed a 117 MB runtime download. `onnx2ncnn`- * cannot consume this model — it has no `DynamicQuantizeLinear`/`MatMulInteger`/`ConvInteger`- * support — and the AAR expects a six-net decomposition (`fbank`, `embed_token`, `proj_out`, .)- * that HuggingFace does not export, so the feature extraction ([WhisperFeatures]) and the decode- * loop below live in Kotlin instead.- *- * Not thread-safe; [transcribe] is called from a single worker thread by- * [com.vayunmathur.speech.service.WhisperRecognitionService].- */-class WhisperOnnxEngine(private val context: Context) {-- private val env: OrtEnvironment by lazy { OrtEnvironment.getEnvironment() }-- private var encoder: OrtSession? = null- private var decoder: OrtSession? = null- private var tokenizer: WhisperTokenizer? = null- private var config: GenerationConfig? = null- private var loadFailed = false-- /** Ids and token maps read from `generation_config.json` rather than hardcoded. */- private class GenerationConfig(json: JSONObject) {- val startOfTranscript = json.optInt("decoder_start_token_id", 50258)- val endOfText = json.optInt("eos_token_id", 50257)- val noTimestamps = json.optInt("no_timestamps_token_id", 50363)- val maxLength = json.optInt("max_length", 448)-- /** ISO-639-1 code to its `<|xx|>` token id, e.g. `en` to 50259. */- val langToId: Map<String, Int> = buildMap {- val obj = json.optJSONObject("lang_to_id") ?: return@buildMap- for (key in obj.keys()) {- // Keys arrive as "<|en|>"; store the bare code.- put(key.removePrefix("<|").removeSuffix("|>"), obj.optInt(key))- }- }-- /** Never-emit ids (music notes, formatting artefacts) that upstream masks out. */- val suppress: Set<Int> = buildSet {- json.optJSONArray("suppress_tokens")?.let { a ->- for (i in 0 until a.length()) add(a.optInt(i))- }- }-- /** Additionally suppressed at the very first generated position (leading space, EOT). */- val suppressAtBegin: Set<Int> = buildSet {- json.optJSONArray("begin_suppress_tokens")?.let { a ->- for (i in 0 until a.length()) add(a.optInt(i))- }- }-- /** `<|transcribe|>`; `<|translate|>` is the id one lower and unused here. */- val transcribe: Int = json.optJSONObject("task_to_id")?.optInt("transcribe", 50359) ?: 50359- }-- /** Assets are always present, so this only reports whether loading succeeded. */- fun isAvailable(): Boolean = ensure()-- @Synchronized- private fun ensure(): Boolean {- if (encoder != null && decoder != null) return true- if (loadFailed) return false- return try {- val opts = OrtSession.SessionOptions().apply {- // Whisper-base is still small; two threads is a reasonable latency/battery balance.- setIntraOpNumThreads(2)- setInterOpNumThreads(1)- }- // createSession(bytes) rather than createSession(path): the models stay mapped in- // the APK instead of being copied into filesDir.- encoder = env.createSession(asset(ENCODER), opts)- decoder = env.createSession(asset(DECODER), opts)- tokenizer = context.assets.open("$DIR/$VOCAB").use { WhisperTokenizer.load(it) }- config = GenerationConfig(- JSONObject(context.assets.open("$DIR/$GEN_CONFIG").use { it.bufferedReader().readText() }),- )- true- } catch (t: Throwable) {- Log.e(TAG, "Whisper ONNX load failed", t)- loadFailed = true- closeInternal()- false- }- }-- private fun asset(name: String): ByteArray =- context.assets.open("$DIR/$name").use { it.readBytes() }-- /**- * Transcribe [pcm16k] (16 kHz mono). [language] is ISO-639-1, or null/"auto" to detect.- * Returns the text, or null if the model could not be loaded or inference failed.- */- fun transcribe(pcm16k: ShortArray, language: String?): String? {- if (!ensure()) return null- val dec = decoder ?: return null- val cfg = config ?: return null- val tok = tokenizer ?: return null-- return try {- val mel = WhisperFeatures.logMel(pcm16k)- encode(mel).use { hidden ->- val lang = resolveLanguage(dec, cfg, hidden, language)- val prompt = intArrayOf(cfg.startOfTranscript, lang, cfg.transcribe, cfg.noTimestamps)- val ids = greedyDecode(dec, cfg, hidden, prompt)- tok.decode(ids)- }- } catch (t: Throwable) {- Log.e(TAG, "transcribe failed", t)- null- }- }-- /** Run the audio encoder once per utterance; its output is reused by every decode step. */- private fun encode(mel: FloatArray): OnnxTensor {- val enc = encoder ?: error("encoder not loaded")- val shape = longArrayOf(1, WhisperFeatures.N_MELS.toLong(), WhisperFeatures.N_FRAMES.toLong())- return OnnxTensor.createTensor(env, FloatBuffer.wrap(mel), shape).use { input ->- enc.run(mapOf("input_features" to input)).use { result ->- val out = result.get(0) as OnnxTensor- // Copy into a tensor we own; the result closes its own values.- val buf = FloatArray(out.info.shape.fold(1L) { a, b -> a * b }.toInt())- out.floatBuffer.get(buf)- OnnxTensor.createTensor(env, FloatBuffer.wrap(buf), out.info.shape)- }- }- }-- /**- * Pick the language token. An explicit [requested] code wins; otherwise one decoder step on- * the bare `<|startoftranscript|>` prompt is scored over just the language tokens, which is- * how Whisper's own detection works.- */- private fun resolveLanguage(- dec: OrtSession,- cfg: GenerationConfig,- hidden: OnnxTensor,- requested: String?,- ): Int {- val code = requested?.substringBefore('-')?.lowercase()- if (code != null && code != "auto") {- cfg.langToId[code]?.let { return it }- Log.w(TAG, "no Whisper language token for '$requested', detecting instead")- }- val fallback = cfg.langToId["en"] ?: 50259- if (cfg.langToId.isEmpty()) return fallback-- return try {- emptyPast().use { past ->- val ids = OnnxTensor.createTensor(- env, LongBuffer.wrap(longArrayOf(cfg.startOfTranscript.toLong())), longArrayOf(1, 1),- )- ids.use {- dec.run(feeds(hidden, past, ids, useCache = false)).use { result ->- val logits = result.get(0) as OnnxTensor- val vocab = logits.info.shape.last().toInt()- val row = FloatArray(vocab)- logits.floatBuffer.position(0)- logits.floatBuffer.get(row)- var best = fallback- var bestScore = -Float.MAX_VALUE- for (id in cfg.langToId.values) {- if (id < vocab && row[id] > bestScore) {- bestScore = row[id]- best = id- }- }- best- }- }- }- } catch (t: Throwable) {- Log.w(TAG, "language detection failed, assuming en", t)- fallback- }- }-- /**- * Greedy argmax decode threading the KV cache.- *- * `decoder_model_merged` requires all 16 `past_key_values` inputs on every call. On the- * first call they are zero-length and `use_cache_branch` is false, which makes the graph- * compute cross-attention K/V from `encoder_hidden_states`; those come back as- * `present.*.encoder.*` and stay constant, while `present.*.decoder.*` grow by one per step.- */- private fun greedyDecode(- dec: OrtSession,- cfg: GenerationConfig,- hidden: OnnxTensor,- prompt: IntArray,- ): List<Int> {- val out = ArrayList<Int>()- val limit = (cfg.maxLength - prompt.size).coerceAtMost(MAX_NEW_TOKENS)-- var past = emptyPast()- var step = 0- var next = -1- try {- while (step < limit) {- val ids = if (step == 0) prompt else intArrayOf(next)- val longIds = LongArray(ids.size) { ids[it].toLong() }- val idTensor = OnnxTensor.createTensor(- env, LongBuffer.wrap(longIds), longArrayOf(1, ids.size.toLong()),- )- val result = idTensor.use { dec.run(feeds(hidden, past, it, useCache = step > 0)) }- // ORT has consumed the inputs; the previous cache can go now.- past.close()-- next = argmax(- result.get(0) as OnnxTensor,- suppress = cfg.suppress,- alsoSuppress = if (step == 0) cfg.suppressAtBegin else emptySet(),- )- past = Past(result)- step++-- if (next == cfg.endOfText) break- out.add(next)- }- } finally {- past.close()- }- return out- }-- /** Argmax over the final position's logits, with masked ids excluded. */- private fun argmax(logits: OnnxTensor, suppress: Set<Int>, alsoSuppress: Set<Int>): Int {- val shape = logits.info.shape- val seqLen = shape[1].toInt()- val vocab = shape[2].toInt()- val row = FloatArray(vocab)- val buf = logits.floatBuffer- buf.position((seqLen - 1) * vocab)- buf.get(row)- var best = 0- var bestScore = -Float.MAX_VALUE- for (i in 0 until vocab) {- if (i in suppress || i in alsoSuppress) continue- if (row[i] > bestScore) {- bestScore = row[i]- best = i- }- }- return best- }-- /** Build the full 19-input feed map for one decoder call. */- private fun feeds(- hidden: OnnxTensor,- past: Past,- ids: OnnxTensor,- useCache: Boolean,- ): Map<String, OnnxTensor> {- val map = LinkedHashMap<String, OnnxTensor>(20)- map["input_ids"] = ids- map["encoder_hidden_states"] = hidden- for ((name, tensor) in past.tensors()) map[name] = tensor- map["use_cache_branch"] = if (useCache) past.cacheTrue else past.cacheFalse- return map- }-- private fun emptyPast(): Past = Past(null)-- /**- * One generation's worth of KV cache. Wraps either the zero-length starting state or the- * `present.*` outputs of the previous step, which are handed straight back as inputs rather- * than copied — the encoder halves alone are 4 x 2 x 6 x 1500 x 64 floats.- */- private inner class Past(private val result: OrtSession.Result?) {- val cacheFalse: OnnxTensor = OnnxTensor.createTensor(env, booleanArrayOf(false))- val cacheTrue: OnnxTensor = OnnxTensor.createTensor(env, booleanArrayOf(true))-- private val empties = ArrayList<OnnxTensor>()-- fun tensors(): List<Pair<String, OnnxTensor>> = PAST_NAMES.map { name ->- val tensor = if (result == null) {- OnnxTensor.createTensor(env, FloatBuffer.allocate(0), EMPTY_SHAPE)- .also { empties.add(it) }- } else {- result.get(name.replace("past_key_values", "present")).get() as OnnxTensor- }- name to tensor- }-- inline fun <T> use(block: (Past) -> T): T = try {- block(this)- } finally {- close()- }-- fun close() {- empties.forEach { runCatching { it.close() } }- empties.clear()- runCatching { cacheFalse.close() }- runCatching { cacheTrue.close() }- runCatching { result?.close() }- }- }-- @Synchronized- fun close() {- closeInternal()- }-- private fun closeInternal() {- runCatching { encoder?.close() }- runCatching { decoder?.close() }- encoder = null- decoder = null- tokenizer = null- config = null- }-- private companion object {- const val TAG = "WhisperOnnxEngine"-- const val DIR = "whisper-base"- const val ENCODER = "encoder_model_int8.onnx"- const val DECODER = "decoder_model_merged_int8.onnx"- const val VOCAB = "vocab.json"- const val GEN_CONFIG = "generation_config.json"-- // whisper-base: 6 encoder and 6 decoder layers, 8 heads of 64. These size the KV cache- // buffers below, so a stale value does not fail cleanly - it feeds the session a- // wrong-shaped past and the decode wanders. Read from the export''s config.json:- // d_model 512, encoder_layers 6, decoder_layers 6, attention heads 8.- const val N_LAYERS = 6- const val N_HEADS = 8L- const val HEAD_DIM = 64L-- /** One 30 s window cannot say more than this; guards against a runaway loop. */- const val MAX_NEW_TOKENS = 224-- val EMPTY_SHAPE = longArrayOf(1, N_HEADS, 0, HEAD_DIM)-- val PAST_NAMES: List<String> = buildList {- for (i in 0 until N_LAYERS) {- for (kind in listOf("decoder", "encoder")) {- for (kv in listOf("key", "value")) add("past_key_values.$i.$kind.$kv")- }- }- }- }-}