ml: slim gemma4 embed export and loader
- Commit
52533ce1fab76970bdd89c93eb03717bb126a43b- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 21:34 UTC (1 month ago)
- Parents
cb4f684
Diff
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 13d15d3122..64910c4abe 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -600,7 +600,7 @@ struct PrefillTimes { /// plan builds on another thread, one device combine, the rotary rows, then the Prefill submit. fn prefill_app( net: &mut Reshaped<gemma4::Pass>,- gather: &mut Reshaped<u32>,+ gather: Option<&mut Reshaped<u32>>, embed: &modelrunner::weights::Reader<'_>, rotary: &modelrunner::weights::Reader<'_>, prompt: &[u32],@@ -609,6 +609,7 @@ fn prefill_app( use modelrunner::nets::gemma4_gather as g; use std::time::Instant; let mut times = PrefillTimes::default();+ let mut gather = gather; for (index, chunk) in prompt.chunks(CHUNK).enumerate() { let start = (index * CHUNK) as u32; let width = if pad { g::padded(chunk.len() as u32, TIER - start) } else { chunk.len() as u32 };@@ -634,6 +635,7 @@ fn prefill_app( let per_layer = if fused() { embedded } else {+ let gather = gather.as_deref_mut().ok_or("no gather net for an unfused text file")?; gather.at(width)?.infer_raw_many(&[&hidden, &embedded])?.into_iter().next().ok_or("no combine")? }; times.combine += tick.elapsed().as_secs_f64() * 1000.0;@@ -705,7 +707,7 @@ fn time_prefill( Ok(net) => net, Err(why) => return println!("the head does not build: {why}"), };- let mut gather = match gather_plan(context, embed) {+ let mut gather = match (!fused()).then(|| gather_plan(context, embed)).transpose() { Ok(net) => net, Err(why) => return println!("the gather net does not build: {why}"), };@@ -716,8 +718,10 @@ fn time_prefill( net.at(gemma4::Mode::PrefillFresh { tokens: 256 }.at(TIER))?; net.at(gemma4::Mode::Tail.at(TIER))?; net.at(gemma4::Mode::DecodeStep.at(TIER))?;- for width in [256, 1].into_iter().filter(|_| !fused()) {- gather.at(width)?;+ for width in [256, 1] {+ if let Some(gather) = gather.as_mut() {+ gather.at(width)?;+ } } if let Some(head) = head_net.as_mut() { for out in [HeadOut::Logits, HeadOut::TopK, HeadOut::Greedy] {@@ -746,7 +750,7 @@ fn time_prefill( let folded: Vec<u32> = prompt.iter().copied().chain([next]).collect(); for run in 0..2 { let start = Instant::now();- let mut p = match prefill_app(&mut net, &mut gather, &reader, &rotary, &folded, true) {+ let mut p = match prefill_app(&mut net, gather.as_mut(), &reader, &rotary, &folded, true) { Ok(p) => p, Err(why) => return println!("the prefill failed: {why}"), };@@ -771,16 +775,16 @@ fn time_prefill( } // The old flow once (prefill the prompt, then a decode step), for the token to match. let tick = Instant::now();- let unfolded = prefill_app(&mut net, &mut gather, &reader, &rotary, &prompt, true).and_then(|_| {+ let unfolded = prefill_app(&mut net, gather.as_mut(), &reader, &rotary, &prompt, true).and_then(|_| { let mut s = StepTimes::default();- decode_one(&mut net, head_net.as_mut(), Some(&mut gather), &reader, &rotary, next, width, HeadOut::Greedy, &mut s)+ decode_one(&mut net, head_net.as_mut(), gather.as_mut(), &reader, &rotary, next, width, HeadOut::Greedy, &mut s) }); println!(" decode-step flow: id {unfolded:?}, {:.0} ms", tick.elapsed().as_secs_f64() * 1000.0); let margins = (|| -> Result<String, String> { let head = head_net.as_mut().ok_or("no head")?;- let p = prefill_app(&mut net, &mut gather, &reader, &rotary, &folded, true)?;+ let p = prefill_app(&mut net, gather.as_mut(), &reader, &rotary, &folded, true)?; let a = softcapped(&head.at(HeadOut::Logits)?.infer_raw_many(&[&p.state])?)?;- prefill_app(&mut net, &mut gather, &reader, &rotary, &prompt, true)?;+ prefill_app(&mut net, gather.as_mut(), &reader, &rotary, &prompt, true)?; let b = last_logits(&mut net, head, &reader, &rotary, next, width)?; let top3 = |l: &[f32]| top10(l).into_iter().take(3).map(|i| (i, l[i as usize])).collect::<Vec<_>>(); Ok(format!("folded {:?} / decode-step {:?}", top3(&a), top3(&b)))@@ -933,16 +937,16 @@ fn split_check( ("batched head + batched tail", run("batched head + batched tail", true, true, false)?), ]; let want = top10(&reference);- let mut gather = gather_plan(context, embed)?;- prefill_app(&mut net, &mut gather, &reader, &rotary, body, false)?;+ let mut gather = if fused() { None } else { Some(gather_plan(context, embed)?) };+ prefill_app(&mut net, gather.as_mut(), &reader, &rotary, body, false)?; let exact = last_logits(&mut net, &mut head_net, &reader, &rotary, last, (n - 1) as u32)?; println!(" {:<32} top10 {:?}", "app path, unpadded", top10(&exact));- prefill_app(&mut net, &mut gather, &reader, &rotary, body, true)?;+ prefill_app(&mut net, gather.as_mut(), &reader, &rotary, body, true)?; let app = last_logits(&mut net, &mut head_net, &reader, &rotary, last, (n - 1) as u32)?; println!(" {:<32} top10 {:?}", "app path (rows + device combine)", top10(&app)); let pad_diff = app.iter().zip(&exact).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max); println!(" padding {} -> {}: max |logit diff| vs unpadded {pad_diff:.4}", body.len(), body.len().div_ceil(8) * 8);- let folded = prefill_app(&mut net, &mut gather, &reader, &rotary, prompt, true)?;+ let folded = prefill_app(&mut net, gather.as_mut(), &reader, &rotary, prompt, true)?; let folded = softcapped(&head_net.at(HeadOut::Logits)?.infer_raw_many(&[&folded.state])?)?; println!(" {:<32} top10 {:?}", "app path, last token folded", top10(&folded)); let variants = [
library/ml/src/main/rust/src/bridge_part11.rs
diff --git a/library/ml/src/main/rust/src/bridge_part11.rs b/library/ml/src/main/rust/src/bridge_part11.rsindex 41ee2d1d1f..3f805662d5 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -180,6 +180,17 @@ fn build_gemma4<'l>( Some(file) => Some(Streamed::open(file, head_at, head_len, graph::GEMMA4_HEAD)?), None => None, };+ // A slim embed file (`embed::SLIM_TENSORS`) has neither the combine weights nor the head+ // table, so it needs the text file's combine and the head file. Refused here rather than+ // at the first token, and never served by the ~2 s/token host head.+ let fused = weights.len() == gemma4::TENSORS_WITH_COMBINE;+ if !fused && !gemma4::embed::carries_combine(&embed.reader()) {+ return Err("neither the text file nor the embed file carries the per-layer combine".into());+ }+ let host_head = gemma4::embed::carries_head_table(embed.len());+ if head_file.is_none() && !host_head {+ return Err("the head file is missing and the embed file carries no head table".into());+ } let tokenizer = env .convert_byte_array(tokenizer) .map_err(|e| format!("cannot read the tokenizer table: {e}"))?;@@ -216,6 +227,9 @@ fn build_gemma4<'l>( // Never `Reshaped::streamed` over EMBED: it uploads the whole 3.6 GB file, which on top of // TEXT OOM-kills a Pixel 8. The gather net is windowed to the tensors it reads. let mut head = head_file.as_ref().and_then(gemma4_head_file_plan);+ if head.is_none() && !host_head {+ return Err("the head file did not build and the embed file carries no head table".into());+ } if let Some(head) = head.as_mut() { // Each mode's first recording costs ~70 ms on a Pixel 8; a sampled first token would pay // it. Logits first: it has the largest readback, so the staging grows once.@@ -225,7 +239,6 @@ fn build_gemma4<'l>( } } // A text file that carries the combine needs no gather net.- let fused = weights.len() == gemma4::TENSORS_WITH_COMBINE; let mut gather_net = if fused { None } else { gemma4_gather_plan(&embed) }; if let Some(gather) = gather_net.as_mut() { gather.at(CHUNK)?;
library/ml/src/main/rust/src/nets/gemma4_part4.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part4.rs b/library/ml/src/main/rust/src/nets/gemma4_part4.rsindex 04594e2349..9aea2941f1 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part4.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part4.rs@@ -76,6 +76,24 @@ pub mod embed { TABLES + i * 3 } + /// Tensors a SLIM embedding `.maml` holds (`s10_to_maml.py --slim-embed`): the working triple,+ /// four one-element fp16 placeholders where SHARED_PROJ and SHARED_NORM were, and the 35+ /// tables, so every index above holds. No head table: the head file carries the head, and+ /// the per-layer combine reads the text file's copy (`super::COMBINE_PROJ`).+ pub const SLIM_TENSORS: usize = TABLES + super::LAYERS * 3;++ /// Whether this embedding file carries the per-layer combine's projection and norm.+ pub fn carries_combine(embed: &crate::weights::Reader<'_>) -> bool {+ let rows = super::LAYERS as u32 * super::PER_LAYER;+ embed.describe(SHARED_PROJ, &[rows, super::D_MODEL, 1, 1]).is_ok()+ && embed.describe(SHARED_NORM, &[super::PER_LAYER]).is_ok()+ }++ /// Whether an embedding file of `tensors` entries carries the host head's table.+ pub const fn carries_head_table(tensors: usize) -> bool {+ tensors > HEAD_TABLE+ }+ /// Ids the export maps to row 0 of the per-layer table before gathering. /// /// The image and audio placeholders. They have no per-layer input of their own - their@@ -398,5 +416,20 @@ mod combine_cache_tests { assert_eq!(reread.len(), LAYERS * PER_LAYER as usize); assert_eq!(miss, reread); assert_eq!(hit, reread);+ assert!(embed::carries_combine(&reader));+ }++ #[test]+ fn a_slim_embed_keeps_every_index_and_carries_neither_combine_nor_head() {+ assert_eq!(embed::SLIM_TENSORS, 112);+ assert_eq!(embed::table(LAYERS - 1) + 3, embed::SLIM_TENSORS);+ assert!(!embed::carries_head_table(embed::SLIM_TENSORS));+ assert!(embed::carries_head_table(embed::TENSORS));+ let placeholders: Vec<_> =+ (0..embed::TABLES).map(|_| crate::weights::Fixture::F16(vec![1], vec![0.0])).collect();+ let blob = crate::weights::write_mixed(crate::weights::graph::GEMMA4_EMBED, &placeholders);+ let weights = crate::weights::Weights::parse(&blob, crate::weights::graph::GEMMA4_EMBED)+ .expect("the slim fixture parses");+ assert!(!embed::carries_combine(&weights.reader())); } }
scripts/ml/maml_convert.py
diff --git a/scripts/ml/maml_convert.py b/scripts/ml/maml_convert.pyindex af74f4add6..aca3f56d35 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -4299,6 +4299,31 @@ class Int4: self.size = self.codes.size +class Raw:+ """A tensor copied verbatim from another `.maml`: its table entry's dtype, shape and element+ count plus its payload bytes, so a re-packed file is bit-identical to its source."""++ def __init__(self, dtype, shape, size, payload):+ self.dtype_code = dtype+ self.shape = tuple(shape)+ self.ndim = len(self.shape)+ self.size = size+ self.payload = payload+++def payload_bytes(dtype, size):+ """Payload length of a tensor of `size` elements stored as `dtype` (mirrors `Dtype::bytes`)."""+ if dtype == DTYPE_F16:+ return size * 2+ if dtype == DTYPE_I8:+ return size+ if dtype == DTYPE_I4:+ return (size + 1) // 2+ if dtype == DTYPE_Q2K:+ return (size + Q2K_BLOCK - 1) // Q2K_BLOCK * Q2K_BYTES+ raise SystemExit(f"unknown dtype {dtype}")++ def build(layers, tensors, graph_id, onnx_sha256): """Serialise the tensor table and the data section. @@ -4315,7 +4340,12 @@ def build(layers, tensors, graph_id, onnx_sha256): while len(data) % ALIGNMENT: data.append(0) offset = len(data)- if isinstance(tensor, Int4):+ if isinstance(tensor, Raw):+ dtype = tensor.dtype_code+ if len(tensor.payload) != payload_bytes(dtype, tensor.size):+ raise SystemExit(f"a raw payload of {len(tensor.payload)} bytes for {tensor.size} taps")+ data.extend(tensor.payload)+ elif isinstance(tensor, Int4): dtype = DTYPE_I4 data.extend(pack_int4(tensor.codes)) elif isinstance(tensor, Q2K):
scripts/ml/s10_to_maml.py
diff --git a/scripts/ml/s10_to_maml.py b/scripts/ml/s10_to_maml.pyindex 1e9340cbf7..8a959825b9 100644--- a/scripts/ml/s10_to_maml.py+++ b/scripts/ml/s10_to_maml.py@@ -14,6 +14,18 @@ Usage: GEMMA4_EMBED_DUMP=analysis/maml-rebuild/embed_s2_fp32.bin \ python scripts/ml/s10_to_maml.py -o build/gemma4-s10 --print-digest (--text-only writes gemma4_text.maml alone and needs no dump.)++Slim embed (the shipped file):+ python scripts/ml/s10_to_maml.py -o build/gemma4-release \+ --slim-embed build/gemma4/gemma4_embed.maml+ copies the token table triple (0-2) and the 35 per-layer int4 tables+ (7+i*3) byte-for-byte out of a full embed file, with no S10 read and no+ re-quantisation. SHARED_PROJ/norm (3-6) become four one-element fp16+ placeholders so every index the runtime reads holds (nets::gemma4::embed::+ SLIM_TENSORS, 112 tensors): the per-layer combine reads the text file's+ copy (the 1094-tensor gemma4_text.maml, nets::gemma4::COMBINE_PROJ), and+ the head table + both head-chunk copies are dropped because+ gemma4_head.maml carries the head. ~1.4 GB instead of 3.6 GB. Then: cargo run --offline --release -p modelrunner --example check_gemma4_parity -- \ build/gemma4-s10/gemma4_text.maml build/gemma4-s10/gemma4_embed.maml \@@ -379,8 +391,13 @@ def main(): ap.add_argument('--print-digest', action='store_true') ap.add_argument('--text-only', action='store_true', help='write gemma4_text.maml only (no embed dump needed)')+ ap.add_argument('--slim-embed', metavar='FULL_EMBED',+ help='write only a slim gemma4_embed.maml copied from FULL_EMBED') args = ap.parse_args() os.makedirs(args.outdir, exist_ok=True)+ if args.slim_embed:+ write_slim_embed(args.slim_embed, os.path.join(args.outdir, 'gemma4_embed.maml'))+ return rdr = S10Reader(S10) layers, tensors = collect_text(rdr) digest = mc.layer_table_digest(layers)@@ -414,8 +431,81 @@ def main(): print(f'wrote {hout} ({len(hblob)} bytes)') +# Slim embed layout (see the module docstring): kept source entries, in order,+# with SLIM_PLACEHOLDERS one-element fp16 tensors standing in for 3-6.+SLIM_LAYERS = 35+SLIM_TABLES = 7+SLIM_PLACEHOLDERS = range(3, SLIM_TABLES)+SLIM_TENSORS = SLIM_TABLES + SLIM_LAYERS * 3+++def read_maml_table(path):+ """(graph_id, sha256, data_offset, entries) of a .maml; entry = (ndim, dims, dtype, offset, size)."""+ import struct+ with open(path, 'rb') as f:+ header = f.read(mc.HEADER_BYTES)+ if header[:4] != mc.MAGIC:+ raise SystemExit(f'{path}: not a .maml')+ _, graph_id, count = struct.unpack_from('<III', header, 4)+ sha = header[16:48]+ data_offset, _ = struct.unpack_from('<II', header, 48)+ table = f.read(count * mc.TENSOR_ENTRY_BYTES)+ entries = []+ for i in range(count):+ fields = struct.unpack_from('<I4IIII', table, i * mc.TENSOR_ENTRY_BYTES)+ ndim, dims, dtype, offset, size = fields[0], fields[1:5], fields[5], fields[6], fields[7]+ entries.append((ndim, dims[:ndim], dtype, offset, size))+ return graph_id, sha, data_offset, entries+++def read_payload(f, data_offset, entry):+ _, _, dtype, offset, size = entry+ f.seek(data_offset + offset)+ want = mc.payload_bytes(dtype, size)+ payload = f.read(want)+ if len(payload) != want:+ raise SystemExit(f'short read: {len(payload)} of {want} bytes')+ return payload+++def write_slim_embed(src, out):+ """Slim gemma4_embed.maml from a full one, tables bit-identical (re-read and compared)."""+ import hashlib+ graph_id, sha, data_offset, entries = read_maml_table(src)+ if graph_id != mc.GRAPHS['gemma4_embed']:+ raise SystemExit(f'{src}: graph {graph_id}, not gemma4_embed')+ if len(entries) < SLIM_TENSORS:+ raise SystemExit(f'{src}: {len(entries)} tensors, fewer than the {SLIM_TENSORS} kept')+ tensors = []+ with open(src, 'rb') as f:+ for i in range(SLIM_TENSORS):+ if i in SLIM_PLACEHOLDERS:+ tensors.append(np.zeros(1, dtype=np.float16))+ continue+ entry = entries[i]+ tensors.append(mc.Raw(entry[2], entry[1], entry[4], read_payload(f, data_offset, entry)))+ blob, _ = mc.build([], tensors, graph_id, sha)+ with open(out, 'wb') as f:+ f.write(blob)+ del blob, tensors+ _, _, out_data, out_entries = read_maml_table(out)+ assert len(out_entries) == SLIM_TENSORS, len(out_entries)+ with open(src, 'rb') as a, open(out, 'rb') as b:+ for i in range(SLIM_TENSORS):+ if i in SLIM_PLACEHOLDERS:+ continue+ want, got = entries[i], out_entries[i]+ if want[:3] != got[:3] or want[4] != got[4]:+ raise SystemExit(f'tensor {i}: entry {got} differs from {want}')+ if hashlib.sha256(read_payload(a, data_offset, want)).digest() != \+ hashlib.sha256(read_payload(b, out_data, got)).digest():+ raise SystemExit(f'tensor {i}: payload differs from the source')+ print(f'wrote {out} ({os.path.getsize(out)} bytes, {SLIM_TENSORS} tensors, '+ f'{SLIM_TENSORS - len(SLIM_PLACEHOLDERS)} bit-identical to {src})')++ def collect_embed(rdr):- """gemma4_embed from S10's own tensors (+ S2 dump for the working table).+ """gemma4_embed from S10's own tensors Layout matches the artisan path's embed file exactly (same tensor order, same layer kinds), so the runtime reads either file identically: