ml: standalone GPU head file (402MB upload, P8 OOM fix)
- Commit
e5cdf7a92e4d5dba580b16c4b60796f44a2f8727- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-27 02:50 UTC (2 months ago)
- Parents
ea3e2c9
Diff
library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.ktindex e3c04ffe14..cd4bd92839 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt@@ -570,12 +570,20 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose /** The two embedding tables, host-gathered. */ const val EMBED = "gemma4_embed.maml" + /** The GPU logits head (16 int8 chunks alone). Optional: native falls+ * back to the host head when it is absent, so old downloads without+ * it keep working — they just pay the ~2 s/token host SGEMV. */+ const val HEAD = "gemma4_head.maml"+ /** `scripts/ml/gemma4_tokenizer.py`'s output. */ const val TOKENIZER = "gemma4_tokenizer.spm1" /** The files [inDirectory] needs, for a caller checking a download is complete. */ val FILES: List<String> = listOf(TEXT, EMBED, TOKENIZER) + /** The full set including the optional head, for a caller warming the download. */+ val FILES_WITH_HEAD: List<String> = listOf(TEXT, EMBED, HEAD, TOKENIZER)+ /** Positions the runtime offers. Mirrors `nets::gemma4::MAX_CONTEXT`. */ const val MAX_CONTEXT = 16384
library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.ktindex e5557a70a4..449516d7ab 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.kt@@ -103,6 +103,24 @@ internal fun createGemma4Handle(directory: File): Long { return 0L } }+ // Optional GPU head (third file). Absent on old downloads — native falls+ // back to the host head, so this stays warning-free by design.+ val head = File(directory, Gemma4Handle.HEAD)+ val headFd: Int+ val headLen: Long+ if (head.isFile) {+ headFd = runCatching {+ ParcelFileDescriptor.open(head, ParcelFileDescriptor.MODE_READ_ONLY)+ .use { it.detachFd() }+ }.getOrElse {+ Log.w(Gemma4Handle.TAG, "cannot open ${Gemma4Handle.HEAD}: $it")+ return 0L+ }+ headLen = head.length()+ } else {+ headFd = -1+ headLen = 0L+ } val table = runCatching { tokenizer.readBytes() }.getOrElse { Log.w(Gemma4Handle.TAG, "cannot read ${Gemma4Handle.TOKENIZER}: $it") return 0L@@ -127,6 +145,7 @@ internal fun createGemma4Handle(directory: File): Long { val live = MlNative.createGemma4( textFd, 0L, text.length(), embedFd, 0L, embed.length(),+ headFd, 0L, headLen, table, gemma4CacheBudget(), )@@ -136,6 +155,7 @@ internal fun createGemma4Handle(directory: File): Long { if (!handed) { closeGemma4Fd(textFd) closeGemma4Fd(embedFd)+ if (headFd >= 0) closeGemma4Fd(headFd) } } }
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 fff55c83d5..70a3e540f7 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@@ -593,13 +593,15 @@ internal object MlNative { external fun destroySupertonic(handle: Long) /**- * Bring up Gemma 4 E2B from its two `.maml`s and its tokenizer table. Returns 0 on failure.+ * Bring up Gemma 4 E2B from its `.maml`s and its tokenizer table. Returns 0 on failure. * * The decoder and the embedding are separate files (graph ids 20 and 21) because nothing on * the device reads the embedding: a decode step needs one row of a 262144-row table, so it- * is gathered on the host and streamed, exactly as NLLB's tied embedding is. Native adopts- * **both** descriptors and closes them on every path including failure, so the caller must- * detach both and must not close either. [tokenizer] stays a byte array.+ * is gathered on the host and streamed, exactly as NLLB's tied embedding is. The GPU+ * logits head is an optional third file (graph id 26, `gemma4_head.maml`): pass -1/0/0+ * when it is absent and native falls back to the host head. Native adopts **all**+ * descriptors and closes them on every path including failure, so the caller must+ * detach all and must not close any. [tokenizer] stays a byte array. * * Freed by [destroyGemma4], not [destroy], [destroyOcr], [destroySupertonic], * [destroyTinyclip] or [destroyNllb].@@ -611,6 +613,9 @@ internal object MlNative { embedFd: Int, embedOffset: Long, embedLength: Long,+ headFd: Int,+ headOffset: Long,+ headLength: Long, tokenizer: ByteArray, cacheBudgetBytes: Long, ): Long
library/ml/src/main/rust/examples/check_gemma4_parity.rs
diff --git a/library/ml/src/main/rust/examples/check_gemma4_parity.rs b/library/ml/src/main/rust/examples/check_gemma4_parity.rsindex d1350b4ab6..5253a884fb 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -57,7 +57,7 @@ fn main() { let (Some(text), Some(embed), Some(golden)) = (args.next().map(PathBuf::from), args.next().map(PathBuf::from), args.next()) else {- println!("usage: check_gemma4_parity <text.maml> <embed.maml> <golden.json>");+ println!("usage: check_gemma4_parity <text.maml> <embed.maml> <golden.json> [head.maml]"); return; }; let weights = match open_streamed(&text, graph::GEMMA4_TEXT) {@@ -68,6 +68,17 @@ fn main() { Ok(w) => w, Err(why) => return println!("the embedding does not stream: {why}"), };+ // Optional standalone head file (4th arg): the 48 int8 triples alone+ // (~402 MB upload instead of the whole EMBED file). Absent on old flows+ // — the EMBED-resident chunks (or host head) cover those.+ let head_path: Option<PathBuf> = std::env::args().nth(6).map(PathBuf::from);+ let head_weights: Option<Streamed> = match &head_path {+ Some(path) => match open_streamed(path, graph::GEMMA4_HEAD) {+ Ok(w) => Some(w),+ Err(why) => return println!("the head file does not stream: {why}"),+ },+ None => None,+ }; let golden = match std::fs::read_to_string(&golden) { Ok(text) => text, Err(why) => return println!("cannot read the golden: {why}"),@@ -82,7 +93,7 @@ fn main() { Ok(context) => context, Err(why) => return println!("no Vulkan device: {why}"), };- match run(&context, &weights, &embed_weights, &tokens) {+ match run(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens) { Ok(logits) => report(&logits, &want_ids, &want_logits), Err(why) => println!("the decode failed: {why}"), }@@ -253,6 +264,7 @@ fn run( context: &Arc<context::Context>, weights: &Streamed, embed: &Streamed,+ head: Option<&Streamed>, tokens: &[u32], ) -> Result<Vec<f32>, String> { let mut net = Reshaped::streamed(@@ -293,23 +305,53 @@ fn run( if hidden.len() != gemma4::D_MODEL as usize { return Err(format!("hidden state of {} values, not {}", hidden.len(), gemma4::D_MODEL)); }- Ok(gpu_or_host_logits(context, embed, &reader, &hidden)?)+ Ok(gpu_or_host_logits(context, embed, head, &reader, &hidden)?) } -/// Logits for `hidden`: the GPU head when the EMBED file carries chunks.+/// Logits for `hidden`: the standalone head file first, then the GPU head+/// in EMBED, then the host tied head. ///-/// The device runs the 16 fp16 chunk projections; the host concatenates the-/// splits and softcaps. Falls back to the host tied head (`hidden @-/// HEAD_TABLE^T` in `HEAD_SPLITS` quarters) on files without chunks, so this-/// example keeps working against pre-head-split converts. Both paths must-/// agree: the parity gate below compares against the golden either way.+/// The standalone head file (4th CLI arg, ~402 MB upload instead of the+/// whole EMBED file) is preferred whenever present — same numerics as the+/// EMBED-resident int8 chunks, one-ninth the upload bytes. Falls back to the+/// EMBED-resident chunks (`hidden @ chunks`), then the host tied head+/// (`hidden @ HEAD_TABLE^T` in `HEAD_SPLITS` quarters) on files without+/// chunks, so this example keeps working against pre-head-split converts.+/// All paths must agree: the parity gate below compares against the golden+/// either way. fn gpu_or_host_logits( context: &Arc<context::Context>, embed: &Streamed,+ head: Option<&Streamed>, reader: &modelrunner::weights::Reader<'_>, hidden: &[f32], ) -> Result<Vec<f32>, String> { use modelrunner::nets::gemma4_head;+ if let Some(head_file) = head {+ if head_file.offsets().len() == gemma4_head::HEAD_FILE_TENSORS {+ let mut net = Reshaped::streamed(+ Arc::clone(context),+ head_file.offsets(),+ head_file,+ (),+ |offsets, ()| gemma4_head::build_plan_standalone(offsets, false),+ )?;+ let at = net.at(())?;+ let out = at.infer_raw_many(&[hidden])?;+ if out.len() == gemma4_head::HEAD_CHUNKS+ && out.iter().all(|s| s.len() == gemma4_head::CLASSES_PER_CHUNK as usize)+ {+ let mut logits = Vec::with_capacity(gemma4::VOCAB as usize);+ for split in &out {+ for &value in split {+ logits.push(gemma4::LOGIT_CAP * (value / gemma4::LOGIT_CAP).tanh());+ }+ }+ return Ok(logits);+ }+ // Wrong shape: fall through to the EMBED-resident chunks.+ }+ } if embed.offsets().len() >= gemma4_head::TENSORS_WITH_HEAD { let mut head = Reshaped::streamed( Arc::clone(context),
library/ml/src/main/rust/src/bridge_part5.rs
diff --git a/library/ml/src/main/rust/src/bridge_part5.rs b/library/ml/src/main/rust/src/bridge_part5.rsindex 0b0353ff74..162fa76268 100644--- a/library/ml/src/main/rust/src/bridge_part5.rs+++ b/library/ml/src/main/rust/src/bridge_part5.rs@@ -419,6 +419,13 @@ struct Gemma4Handle { weights: Streamed, /// The two embedding tables. embed: Streamed,+ /// The standalone GPU head file (48 int8 triples, ~402 MB). `None` on+ /// old downloads — the EMBED-resident chunks (or host head) cover those.+ /// Retained so the head `Net`s' uploads stay valid for the handle's life:+ /// `Reshaped::streamed` copies the blob to device memory at construction,+ /// but the `Offsets` table borrows nothing — retention is for clarity+ /// and for future re-record paths, matching `weights`/`embed`.+ head_file: Option<Streamed>, /// `scripts/ml/gemma4_tokenizer.py`'s table. tokenizer: Vec<u8>, /// Rotary angles for the sliding layers, `[MAX_CONTEXT, HEAD_DIM]`, read once.
library/ml/src/main/rust/src/bridge_part6.rs
diff --git a/library/ml/src/main/rust/src/bridge_part6.rs b/library/ml/src/main/rust/src/bridge_part6.rsindex a7572adc57..ccedadb61f 100644--- a/library/ml/src/main/rust/src/bridge_part6.rs+++ b/library/ml/src/main/rust/src/bridge_part6.rs@@ -282,52 +282,7 @@ impl Gemma4Handle { } Ok(logits) }-} -/// Host `combine`: projection + grouped-norm + scaled add over rows the-/// caller already gathered. Mirrors `gemma4_part4::combine` exactly (which-/// is private to that module): `projected = W @ hidden` per 256-wide group-/// of the int8 `SHARED_PROJ`, grouped RMS norm with `SHARED_NORM` gamma,-/// `combined = (16 * embedded + normed) / sqrt(2)`. The device combine plan-/// (`gemma4_gather::build_plan`) must agree bit-for-bit — the-/// `--gather-parity` gate in `run_gemma4` enforces it.-fn gather_combine_host(- embed: &Streamed,- hidden: &[f32],- embedded: &[f32],-) -> Result<Vec<f32>, String> {- use gemma4::{EPSILON, LAYERS, PER_LAYER};- let reader = embed.reader();- let proj = reader.int8_all(- gemma4::embed::SHARED_PROJ,- gemma4::embed::SHARED_PROJ + 1,- &[LAYERS as u32 * PER_LAYER, gemma4::D_MODEL, 1, 1],- )?;- let gamma = reader.fp16(gemma4::embed::SHARED_NORM, &[PER_LAYER])?;- let rows = LAYERS;- let wide = PER_LAYER as usize;- const GATHER_SCALE: f32 = 16.0;- let inv_sqrt_2 = 1.0 / std::f32::consts::SQRT_2;- let mut out = Vec::with_capacity(rows * wide);- for r in 0..rows {- let row = &proj[r * wide * gemma4::D_MODEL as usize..(r + 1) * wide * gemma4::D_MODEL as usize];- let emb = &embedded[r * wide..(r + 1) * wide];- let mut group = vec![0f32; wide];- for (o, wrow) in group.iter_mut().zip(row.chunks_exact(gemma4::D_MODEL as usize)) {- *o = wrow.iter().zip(hidden.iter()).map(|(a, b)| a * b).sum::<f32>();- }- let mean_sq = group.iter().map(|v| v * v).sum::<f32>() / wide as f32;- let norm = 1.0 / (mean_sq + EPSILON).sqrt();- for (v, &g) in group.iter_mut().zip(gamma.iter()) {- *v = *v * norm * g;- }- for (v, &e) in group.iter_mut().zip(emb.iter()) {- *v = (*v + GATHER_SCALE * e) * inv_sqrt_2;- }- out.extend_from_slice(&group);- }- Ok(out)-} /// Reallocate the caches so at least `needed` positions fit. Returns the new capacity. ///@@ -464,11 +419,56 @@ fn gather_combine_host( )); self.position += width; }-fn gemma4_plan(offsets: &Offsets, pass: gemma4::Pass) -> Result<Plan, String> {- gemma4::build(offsets, pass)+ Ok(())+ }+} // close impl Gemma4Handle: everything below is a free function.++/// Host `combine`: projection + grouped-norm + scaled add over rows the+/// caller already gathered. Mirrors `gemma4_part4::combine` exactly (which+/// is private to that module): `projected = W @ hidden` per 256-wide group+/// of the int8 `SHARED_PROJ`, grouped RMS norm with `SHARED_NORM` gamma,+/// `combined = (16 * embedded + normed) / sqrt(2)`. The device combine plan+/// (`gemma4_gather::build_plan`) must agree bit-for-bit — the+/// `--gather-parity` gate in `run_gemma4` enforces it.+fn gather_combine_host(+ embed: &Streamed,+ hidden: &[f32],+ embedded: &[f32],+) -> Result<Vec<f32>, String> {+ use gemma4::{EPSILON, LAYERS, PER_LAYER};+ let reader = embed.reader();+ let proj = reader.int8_all(+ gemma4::embed::SHARED_PROJ,+ gemma4::embed::SHARED_PROJ + 1,+ &[LAYERS as u32 * PER_LAYER, gemma4::D_MODEL, 1, 1],+ )?;+ let gamma = reader.fp16(gemma4::embed::SHARED_NORM, &[PER_LAYER])?;+ let rows = LAYERS;+ let wide = PER_LAYER as usize;+ const GATHER_SCALE: f32 = 16.0;+ let inv_sqrt_2 = 1.0 / std::f32::consts::SQRT_2;+ let mut out = Vec::with_capacity(rows * wide);+ for r in 0..rows {+ let row = &proj[r * wide * gemma4::D_MODEL as usize..(r + 1) * wide * gemma4::D_MODEL as usize];+ let emb = &embedded[r * wide..(r + 1) * wide];+ let mut group = vec![0f32; wide];+ for (o, wrow) in group.iter_mut().zip(row.chunks_exact(gemma4::D_MODEL as usize)) {+ *o = wrow.iter().zip(hidden.iter()).map(|(a, b)| a * b).sum::<f32>();+ }+ let mean_sq = group.iter().map(|v| v * v).sum::<f32>() / wide as f32;+ let norm = 1.0 / (mean_sq + EPSILON).sqrt();+ for (v, &g) in group.iter_mut().zip(gamma.iter()) {+ *v = *v * norm * g;+ }+ for (v, &e) in group.iter_mut().zip(emb.iter()) {+ *v = (*v + GATHER_SCALE * e) * inv_sqrt_2;+ }+ out.extend_from_slice(&group);+ }+ Ok(out) } -fn gemma4_head_plan_greedy(offsets: &Offsets, _: ()) -> Result<Plan, String> {+fn gemma4_head_greedy_plan(offsets: &Offsets, _: ()) -> Result<Plan, String> { crate::nets::gemma4_head::build_plan_greedy(offsets) } @@ -489,8 +489,52 @@ fn gemma4_gather_plan(embed: &Streamed) -> Option<Reshaped<()>> { .ok() } +/// The standalone head plan over a head file (`graph::GEMMA4_HEAD`).+///+/// `None` when no head file was opened. The head file holds ONLY the 48+/// int8 triples (~402 MB), so this upload replaces the 3.6 GB EMBED upload+/// on memory-constrained devices (Pixel 8 OOM-reboot, twice, 2026-09-26:+/// TEXT 1.1 GB + EMBED 3.6 GB vs ~2.6 GB free). Preferred over+/// `gemma4_head_plan` whenever present — same numerics, one-ninth the bytes.+fn gemma4_head_file_plan(head: &Streamed) -> Option<Reshaped<()>> {+ let offsets = head.offsets();+ if offsets.len() != crate::nets::gemma4_head::HEAD_FILE_TENSORS {+ return None;+ }+ Reshaped::streamed(+ context::shared().ok()?,+ offsets,+ head,+ (),+ |offsets, ()| crate::nets::gemma4_head::build_plan_standalone(offsets, false),+ )+ .ok()+}++/// The greedy standalone head plan: 16 splits + device argmax id.+/// See `gemma4_head_file_plan` (file-size rationale) and `build_plan_greedy`.+fn gemma4_head_file_plan_greedy(head: &Streamed) -> Option<Reshaped<()>> {+ let offsets = head.offsets();+ if offsets.len() != crate::nets::gemma4_head::HEAD_FILE_TENSORS {+ return None;+ }+ Reshaped::streamed(+ context::shared().ok()?,+ offsets,+ head,+ (),+ |offsets, ()| crate::nets::gemma4_head::build_plan_standalone(offsets, true),+ )+ .ok()+}+ /// The GPU tied-head plan over an EMBED file, or `None` when the file has /// no head chunks (see `nets::gemma4_head`).+///+/// Prefer the standalone head file when one was opened (see+/// `gemma4_head_file_plan`): its 402 MB upload replaces the 3.6 GB EMBED+/// upload the EMBED-resident chunks would force. Falls back to the+/// EMBED-resident chunks (host flow) when no head file is present. fn gemma4_head_plan(embed: &Streamed) -> Option<Reshaped<()>> { let offsets = embed.offsets(); if offsets.len() < crate::nets::gemma4_head::TENSORS_WITH_HEAD {@@ -523,7 +567,7 @@ fn gemma4_head_plan_greedy(embed: &Streamed) -> Option<Reshaped<()>> { offsets, embed, (),- gemma4_head_plan_greedy,+ gemma4_head_greedy_plan, ) .ok() }@@ -592,13 +636,16 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createGemma4<'l> embed_fd: jint, embed_offset: jlong, embed_length: jlong,+ head_fd: jint,+ head_offset: jlong,+ head_length: jlong, tokenizer: JByteArray<'l>, // Bytes of KV cache this device will spend. See `gemma4::tier_for`. budget: jlong, ) -> jlong { // Both descriptors are adopted before anything may fail. The caller detached them, so a path- // that returns without wrapping one leaks it for the life of the process - and there are two- // here, so the usual single-`fd` shape is not enough.+ // that returns without wrapping one leaks it for the life of the process - and there are+ // three here (the head is optional), so the usual single-`fd` shape is not enough. if text_fd < 0 || embed_fd < 0 { log(&format!("gemma4 is unavailable: descriptors {text_fd} and {embed_fd}")); return 0;@@ -607,15 +654,25 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createGemma4<'l> // including on every failure path below. let text = unsafe { File::from_raw_fd(text_fd) }; let embed = unsafe { File::from_raw_fd(embed_fd) };+ // The head file is optional: -1 means absent (old downloads), and native+ // falls back to the host head. A non-negative fd is adopted like the rest.+ let head: Option<File> = if head_fd >= 0 {+ // SAFETY: same contract as text/embed above.+ Some(unsafe { File::from_raw_fd(head_fd) })+ } else {+ None+ }; let spans = ( u64::try_from(text_offset), u64::try_from(text_length), u64::try_from(embed_offset), u64::try_from(embed_length),+ u64::try_from(head_offset),+ u64::try_from(head_length), ); let built = match spans {- (Ok(ta), Ok(tl), Ok(ea), Ok(el)) => {- build_gemma4(&mut env, text, ta, tl, embed, ea, el, &tokenizer, budget.max(0) as u64)+ (Ok(ta), Ok(tl), Ok(ea), Ok(el), Ok(ha), Ok(hl)) => {+ build_gemma4(&mut env, text, ta, tl, embed, ea, el, head, ha, hl, &tokenizer, budget.max(0) as u64) } _ => Err("a graph span that is not a positive offset and length".to_string()), };@@ -637,11 +694,21 @@ fn build_gemma4<'l>( embed: File, embed_at: u64, embed_len: u64,+ head: Option<File>,+ head_at: u64,+ head_len: u64, tokenizer: &JByteArray<'l>, budget: u64, ) -> Result<Gemma4Handle, String> { let weights = Streamed::open(text, text_at, text_len, graph::GEMMA4_TEXT)?; let embed = Streamed::open(embed, embed_at, embed_len, graph::GEMMA4_EMBED)?;+ // The optional head file: opened (header-checked against GEMMA4_HEAD)+ // only when the caller passed a live descriptor. `None` keeps the old+ // two-file behavior exactly — host head, no third upload.+ let head_file: Option<Streamed> = match head {+ Some(file) => Some(Streamed::open(file, head_at, head_len, graph::GEMMA4_HEAD)?),+ None => None,+ }; let tokenizer = env .convert_byte_array(tokenizer) .map_err(|e| format!("cannot read the tokenizer table: {e}"))?;@@ -674,13 +741,15 @@ fn build_gemma4<'l>( gemma4::Mode::DecodeStep.at(gemma4::CONTEXT_TIERS[0]), gemma4_plan, )?;- // The GPU tied head, upload-once: a second net over the EMBED file that- // runs the 16 chunked fp16 head projections per token. `None` on files- // without the chunks (pre-head-split converts) — the caller falls back- // to the host head. Uploading the whole EMBED file is the price: there- // is no partial-upload path, so this is ~2.4 GB resident alongside TEXT.- let head = gemma4_head_plan(&embed);- let head_greedy = gemma4_head_plan_greedy(&embed);+ // The GPU tied head, upload-once. Prefer the standalone head file when+ // one was opened: its ~402 MB upload replaces the 3.6 GB EMBED upload+ // (TEXT 1.1 GB + EMBED 3.6 GB = OOM-reboot on a Pixel 8, twice,+ // 2026-09-26). Falls back to the EMBED-resident chunks, then the host+ // head, when no head file is present.+ let (head, head_greedy) = match &head_file {+ Some(file) => (gemma4_head_file_plan(file), gemma4_head_file_plan_greedy(file)),+ None => (gemma4_head_plan(&embed), gemma4_head_plan_greedy(&embed)),+ }; // The device combine: built (plan verified by unit tests) but NOT YET // WIRED into the step path — `gather_net: None` until the parity gate // below passes. The recording is cheap; the behavior change is not, so@@ -698,6 +767,7 @@ fn build_gemma4<'l>( gather_net, weights, embed,+ head_file, tokenizer, local, global,
library/ml/src/main/rust/src/nets/gemma4_head.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_head.rs b/library/ml/src/main/rust/src/nets/gemma4_head.rsindex 309fca78a8..05e4625459 100644--- a/library/ml/src/main/rust/src/nets/gemma4_head.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_head.rs@@ -55,6 +55,9 @@ pub const TENSORS_WITH_HEAD: usize = embed::TENSORS_WITH_HEAD; /// Layout after the fp16 chunks: chunk `s` owns `HEAD8_BASE + s * 3` (int8 /// kernel `[CLASSES_PER_CHUNK, 1536, 1, 1]`), `+ 1` (fp16 per-channel scale /// `[CLASSES_PER_CHUNK]`), `+ 2` (fp16 zero bias `[CLASSES_PER_CHUNK]`).+///+/// In the standalone head file (`graph::GEMMA4_HEAD`, 48 tensors) the chunks+/// start at 0: chunk `s` owns `s * 3 .. s * 3 + 2`. See `build_plan_standalone`. pub const HEAD8_BASE: usize = embed::HEAD8_CHUNKS; /// Tensors the int8 chunked head adds: kernel + scale + bias per chunk.@@ -124,6 +127,9 @@ fn build_plan_inner(weights: &dyn WeightSource, greedy: bool) -> Result<Plan, St build_plan_fp16(weights, greedy) } +/// Tensors the standalone head file holds: 16 int8 triples, nothing else.+pub const HEAD_FILE_TENSORS: usize = HEAD_CHUNKS * 3;+ /// The int8 head pass. See [`build_plan`]. fn build_plan8(weights: &dyn WeightSource, greedy: bool) -> Result<Plan, String> { let mut builder = Builder::new(weights);@@ -147,17 +153,24 @@ fn build_plan8(weights: &dyn WeightSource, greedy: bool) -> Result<Plan, String> return Err(format!("the int8 head claims {} tensors, not {HEAD8_CHUNK_TENSORS}", next - HEAD8_BASE)); } if greedy {- // Concatenate the 16 splits on-device (channel Concat lowers to- // copies within the arena — no extra allocation) and reduce to one- // greedy id. The split outputs stay too, so the Kotlin sampling path- // keeps working from the same recording.- let row = b.concat(&outs);- let id = b.argmax(row);- outs.push(id);+ finish_greedy(b, &mut outs); } builder.finish(&outs) } +/// Append the on-device concat + argmax to `outs`. Shared by the int8,+/// fp16 and standalone passes (the tail is identical; only the chunk base+/// differs).+fn finish_greedy(b: &mut Builder, outs: &mut Vec<Id>) {+ // Concatenate the 16 splits on-device (channel Concat lowers to+ // copies within the arena — no extra allocation) and reduce to one+ // greedy id. The split outputs stay too, so the Kotlin sampling path+ // keeps working from the same recording.+ let row = b.concat(&outs);+ let id = b.argmax(row);+ outs.push(id);+}+ /// The fp16 head pass. See [`build_plan`]. fn build_plan_fp16(weights: &dyn WeightSource, greedy: bool) -> Result<Plan, String> { let mut builder = Builder::new(weights);@@ -182,9 +195,27 @@ fn build_plan_fp16(weights: &dyn WeightSource, greedy: bool) -> Result<Plan, Str return Err(format!("the head claims {} tensors, not {HEAD_CHUNK_TENSORS}", next - HEAD_BASE)); } if greedy {- let row = b.concat(&outs);- let id = b.argmax(row);- outs.push(id);+ finish_greedy(b, &mut outs);+ }+ builder.finish(&outs)+}++/// The standalone head pass over the head file (`graph::GEMMA4_HEAD`).+///+/// Same 16 int8 triples as `build_plan8`, but the file holds NOTHING else:+/// chunk `s` owns tensors `s * 3 .. s * 3 + 2` (no `host_tensor` companions+/// needed — `finish` sees every tensor read). `greedy` appends the same+/// on-device concat + argmax tail.+pub fn build_plan_standalone(weights: &dyn WeightSource, greedy: bool) -> Result<Plan, String> {+ let mut builder = Builder::new(weights);+ let b = &mut builder;+ let x = b.input(Shape::new(D_MODEL, 1, 1));+ let mut outs = Vec::with_capacity(HEAD_CHUNKS);+ for s in 0..HEAD_CHUNKS {+ outs.push(point8(b, s * 3, x, CLASSES_PER_CHUNK));+ }+ if greedy {+ finish_greedy(b, &mut outs); } builder.finish(&outs) }
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 7b255f2d28..ebb2c4734a 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -240,6 +240,17 @@ pub mod graph { /// after Gemma 4's audio tower at 24, with 7..10 and 15 staying retired. /// `maml_convert.py` has `GRAPHS["madlad400"]` at the same number. pub const MADLAD: u32 = 25;++ /// Gemma 4's GPU logits head: the 16 int8 head chunks alone in their own file.+ ///+ /// The next free id after MADLAD's 25, with 7..10 and 15 staying retired.+ /// `maml_convert.py` has `GRAPHS["gemma4_head"]` at the same number. See+ /// [`crate::nets::gemma4_head`].+ ///+ /// Its own file because the head `Net` uploads its whole `Blob` verbatim:+ /// with the chunks inside EMBED that upload was 3.6 GB (TEXT 1.1 GB ++ /// EMBED 3.6 GB = OOM-reboot on a Pixel 8). The head file is ~402 MB.+ pub const GEMMA4_HEAD: u32 = 26; } /// One tensor's entry in the table: where it is and what shape it is.
scripts/ml/maml_convert.py
diff --git a/scripts/ml/maml_convert.py b/scripts/ml/maml_convert.pyindex a27c94eee6..ba3d4f8b0c 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -220,6 +220,18 @@ GRAPHS = { # id after Gemma 4's audio tower at 24, with 7..10 and 15 staying retired. # `weights.rs` has `graph::MADLAD` at the same number. "madlad400": 25,+ # Gemma 4's GPU logits head: the 16 int8 head chunks (kernel, scale, bias+ # each) ALONE in their own file. Next free id after MADLAD's 25, with 7..10+ # and 15 staying retired. `weights.rs` has `graph::GEMMA4_HEAD` at the same+ # number.+ #+ # Why a third file: the head `Net` uploads its whole `Blob` verbatim, and+ # the EMBED file grew to 3.6 GB with the chunks inside (TEXT 1.1 GB + EMBED+ # 3.6 GB = 4.7 GB uploaded vs ~2.6 GB free on a Pixel 8 = OOM-reboot,+ # twice, 2026-09-26). The head file is ~402 MB: TEXT + HEAD = ~1.5 GB+ # uploaded, back under the 3.5 GB the old harness proved safe. The EMBED+ # file itself is never uploaded — host gathers only, as before.+ "gemma4_head": 26, # The Q2_K port of the same net, from `model-q2k.gguf`. SAME graph id: the tensor # order is identical (684 layers, 1724 tensors, same names) and only the payloads # differ (Q2_K verbatim vs int8 requantised), so the Rust forward pass reads either@@ -260,10 +272,13 @@ EXPECTED_DIGEST = { "gemma4_vision": "a942080007f7ca9d8fa38a0812a4f858ff1c31afb7c4e94d105428da5fa56f19", # Gemma 4 E2B text decoder converted DIRECTLY from the litertlm GPU bundle # (scripts/ml/litertlm_to_maml.py; the ONNX export is a different model).- # 538 layers, 1088 tensors (rotary thetas read off the base bundle's own+ # 540 layers, 1090 tensors (rotary thetas read off the base bundle's own # Section 10 `maybe_rope` constants: 1e4 sliding / 1e6 full;- # --rope-theta overrides both; per-layer `skip` whole-residual scalars),- # fidelity worst 0.9988. Pinned 2026-09-17.+ # --rope-theta overrides both; per-layer `skip` whole-residual scalars;+ # plus the two shared ones-vectors), fidelity worst 0.9988.+ # Pinned 2026-09-25 (full-scale O/PL; the 2026-09-17 pin was 538/1088,+ # pre-ones-vectors and pre-fullfix — see+ # build/gemma4-s10-fullfix/BLESSED.txt). "gemma4_text": "20262c74605b0c121220cdb25f4c92d8f26607b4d548781035dcdc91209a2c26", # Gemma 4 E2B embedder from the same bundle: 2-bit working table + shared # [8960,1536] INT8 + 35xINT4 mmap tables. 38 layers, 112 tensors,
scripts/ml/s10_to_maml.py
diff --git a/scripts/ml/s10_to_maml.py b/scripts/ml/s10_to_maml.pyindex ea50868011..8b9486c34a 100644--- a/scripts/ml/s10_to_maml.py+++ b/scripts/ml/s10_to_maml.py@@ -342,6 +342,18 @@ def main(): eout = os.path.join(args.outdir, 'gemma4_embed.maml') open(eout, 'wb').write(eblob) print(f'wrote {eout} ({len(eblob)} bytes)')+ # GPU head file (2026-09-27 OOM fix): the 48 int8 head triples ALONE.+ # The head `Net` uploads its whole `Blob` verbatim; with the chunks inside+ # EMBED that upload was 3.6 GB (TEXT 1.1 + EMBED 3.6 = OOM-reboot on P8).+ # The head file is ~402 MB. `collect_head` re-derives the chunks from the+ # same S10 table (no new numerics — same `fid.quantise` calls, same rows).+ hlayers, htensors = collect_head(rdr)+ hdigest = mc.layer_table_digest(hlayers)+ print(f's10_head: {len(hlayers)} layers, {len(htensors)} tensors, digest {hdigest}')+ hblob, _ = mc.build(hlayers, htensors, mc.GRAPHS['gemma4_head'], sha)+ hout = os.path.join(args.outdir, 'gemma4_head.maml')+ open(hout, 'wb').write(hblob)+ print(f'wrote {hout} ({len(hblob)} bytes)') def collect_embed(rdr):@@ -478,5 +490,36 @@ def collect_embed(rdr): return layers, tensors +def collect_head(rdr):+ """gemma4_head: the 48 int8 head triples ALONE (OOM fix, 2026-09-27).++ Same S10 t2698 source, same `fid.quantise` calls, same row order as the+ int8 chunks `collect_embed` appends — factored so the head `Net` uploads+ ~402 MB instead of the whole 3.6 GB EMBED file. Chunk `s` owns tensors+ `s * 3 .. s * 3 + 2` (kernel `[per, 1536, 1, 1]` int8, scale `[per]`+ fp16, bias `[per]` fp16); vocab order preserved.+ """+ layers, tensors = [], []+ fid = mc.Fidelity()+ head = rdr.dequant2(2698, 262144, 1536)+ n = head.shape[0]+ assert n == 262144, n+ per = n // HEAD_SPLITS+ assert per * HEAD_SPLITS == n, (n, HEAD_SPLITS)+ for s in range(HEAD_SPLITS):+ rows = head[s * per:(s + 1) * per].astype(np.float32)+ kernel8, scale8 = fid.quantise(f'head_split8_{s}',+ np.ascontiguousarray(rows).reshape(per, 1536, 1, 1))+ bias8 = np.zeros(per, dtype=np.float32)+ tensors.extend([kernel8, scale8, bias8])+ layers.append(mc.Layer(len(layers), 'Linear8', f'head_split8_{s}',+ f'Linear8 w=[{per}, 1536, 1, 1] dtype=int8 b=[{per}]',+ len(tensors) - 3, 3))+ print(f'head file: {HEAD_SPLITS} int8 chunks of [{per}, 1536, 1, 1] '+ f'(+ [per] scale, zero bias)')+ fid.report(mc.MIN_INT4_COSINE)+ return layers, tensors++ if __name__ == '__main__': main()