Modern Apps git

← Modern-Apps.git

ml: gemma4 maps the embed file for row reads, distinct-token rows -30%

Commit
d528a45f45f8f49389a040691097a49d40433c86
Author
vayun-mathur <[email protected]>
When
2026-10-26 20:29 UTC (1 month ago)
Parents
d4510bf

Diff

Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 528657a524..f0c2db5f65 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3512,6 +3512,7 @@ version = "0.1.0" dependencies = [  "ash",  "jni",+ "libc", ]  [[package]]
library/ml/src/main/rust/Cargo.toml
diff --git a/library/ml/src/main/rust/Cargo.toml b/library/ml/src/main/rust/Cargo.tomlindex 92acb3138e..a2e459e2dd 100644--- a/library/ml/src/main/rust/Cargo.toml+++ b/library/ml/src/main/rust/Cargo.toml@@ -41,3 +41,7 @@ jni.workspace = true # anyway. It is not android-gated: `loaded` finds the platform loader on the host too, # which is the only way the shaders ever get executed before they reach a phone. ash = { workspace = true, default-features = false, features = ["loaded"] }++# mmap for host row reads out of large weight files (`weights_part9.rs`).+[target.'cfg(unix)'.dependencies]+libc.workspace = true
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 a68db08f56..4fd60be475 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -151,10 +151,11 @@ fn main() {     };     FUSED.store(gemma4::combines_in_plan(&weights.offsets()), std::sync::atomic::Ordering::Relaxed);     println!("text plans combine the per-layer rows: {}", fused());-    let embed_weights = match open_streamed(&embed, graph::GEMMA4_EMBED) {+    let mut embed_weights = match open_streamed(&embed, graph::GEMMA4_EMBED) {         Ok(w) => w,         Err(why) => return println!("the embedding does not stream: {why}"),     };+    println!("embed rows mapped: {}", embed_weights.map());     let head_weights: Option<Streamed> = match &args.head {         Some(path) => match open_streamed(path, graph::GEMMA4_HEAD) {             Ok(w) => Some(w),
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 a4ecb633e3..0f9db4390d 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -168,7 +168,10 @@ fn build_gemma4<'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)?;+    let mut embed = Streamed::open(embed, embed_at, embed_len, graph::GEMMA4_EMBED)?;+    if !embed.map() {+        log("gemma4 reads embedding rows with pread: the embed file did not map");+    }     // 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.
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 c499d0ca72..fe0a6f9fee 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -487,4 +487,5 @@ include!("weights_part4.rs"); include!("weights_part5.rs"); include!("weights_part6.rs"); include!("weights_part7.rs");-include!("weights_part8.rs");\ No newline at end of file+include!("weights_part8.rs");+include!("weights_part9.rs");\ No newline at end of file
library/ml/src/main/rust/src/weights_part1.rs
diff --git a/library/ml/src/main/rust/src/weights_part1.rs b/library/ml/src/main/rust/src/weights_part1.rsindex 1f4daa4ed5..4120c50ddf 100644--- a/library/ml/src/main/rust/src/weights_part1.rs+++ b/library/ml/src/main/rust/src/weights_part1.rs@@ -239,6 +239,8 @@ pub struct Streamed {     /// header and table. Every [`Blob::read_at`] adds it, so callers index the data section.     data_at: u64,     data_len: u64,+    /// Set by [`Streamed::map`]: host reads copy out of a mapping instead of calling pread.+    mapping: Option<Mapping>, }  impl Streamed {@@ -278,6 +280,7 @@ impl Streamed {             file,             data_at: at + data_at,             data_len: header.data_len as u64,+            mapping: None,         })     } @@ -324,6 +327,9 @@ impl Blob for Streamed {                 self.data_len             ));         }+        if let Some(mapped) = self.mapping.as_ref().and_then(|m| m.read_at(offset, into)) {+            return Ok(mapped);+        }         read_exact_at(&self.file, into, self.data_at + offset)             .map_err(|e| format!("reading {} bytes at {offset}: {e}", into.len()))     }
library/ml/src/main/rust/src/weights_part9.rs
diff --git a/library/ml/src/main/rust/src/weights_part9.rs b/library/ml/src/main/rust/src/weights_part9.rsnew file mode 100644index 0000000000..349a98b8bd--- /dev/null+++ b/library/ml/src/main/rust/src/weights_part9.rs@@ -0,0 +1,144 @@+// A read-only memory mapping of a `.maml` data section, for files the host reads a row at a time.+//+// Gemma's 3.6 GB EMBED file is read two small ranges per table row, ~70 rows a token: as `pread`+// calls that is thousands of syscalls for a prompt. Mapped, a row is a `memcpy` out of the page+// cache. Pages stay file-backed, so the kernel drops them under pressure like any cached file.++/// The mapped data section of a [`Streamed`]. See [`Streamed::map`].+#[cfg(unix)]+struct Mapping {+    /// Page-aligned base `mmap` returned.+    addr: *mut libc::c_void,+    /// Bytes mapped from `addr`, including `slack`.+    len: usize,+    /// Bytes from `addr` to the data section's first byte.+    slack: usize,+}++// SAFETY: the mapping is PROT_READ and never written through, and it lives until `Drop`, so+// shared references from any thread read immutable memory.+#[cfg(unix)]+unsafe impl Send for Mapping {}+// SAFETY: as for `Send`: nothing mutates the mapped bytes.+#[cfg(unix)]+unsafe impl Sync for Mapping {}++#[cfg(unix)]+impl Mapping {+    /// Map `len` bytes of `file` from `offset`, or `None` when the kernel refuses (e.g. a 32-bit+    /// address space too small for the file), in which case the caller keeps reading with pread.+    fn new(file: &File, offset: u64, len: u64) -> Option<Mapping> {+        use std::os::unix::io::AsRawFd;+        // SAFETY: sysconf has no preconditions.+        let page = u64::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }).ok()?;+        if page == 0 || len == 0 {+            return None;+        }+        let aligned = offset - offset % page;+        let slack = usize::try_from(offset - aligned).ok()?;+        let len = slack.checked_add(usize::try_from(len).ok()?)?;+        let at = libc::off_t::try_from(aligned).ok()?;+        // SAFETY: a fresh read-only private mapping of a descriptor this process owns; the kernel+        // picks the address, so nothing existing is replaced. Checked against MAP_FAILED below.+        let addr = unsafe {+            libc::mmap(std::ptr::null_mut(), len, libc::PROT_READ, libc::MAP_PRIVATE, file.as_raw_fd(), at)+        };+        if addr == libc::MAP_FAILED {+            return None;+        }+        // SAFETY: `addr..addr + len` is the mapping just created; advice cannot fault.+        unsafe { libc::madvise(addr, len, libc::MADV_RANDOM) };+        Some(Mapping { addr, len, slack })+    }++    /// Copy `into.len()` bytes from data-section offset `offset`. The caller has bounds-checked+    /// the range against the data section, which this mapping covers exactly.+    fn read_at(&self, offset: u64, into: &mut [u8]) -> Option<()> {+        let from = self.slack.checked_add(usize::try_from(offset).ok()?)?;+        if from.checked_add(into.len())? > self.len {+            return None;+        }+        // SAFETY: `from..from + into.len()` lies inside the live read-only mapping (checked+        // above), and `into` is a distinct heap buffer, so the ranges cannot overlap.+        unsafe {+            std::ptr::copy_nonoverlapping((self.addr as *const u8).add(from), into.as_mut_ptr(), into.len());+        }+        Some(())+    }+}++#[cfg(unix)]+impl Drop for Mapping {+    fn drop(&mut self) {+        // SAFETY: `addr`/`len` are exactly what `mmap` returned, and no reference into the+        // mapping outlives `self`: `read_at` copies out rather than lending slices.+        unsafe { libc::munmap(self.addr, self.len) };+    }+}++/// Non-unix hosts read with positional reads only.+#[cfg(not(unix))]+struct Mapping;++#[cfg(not(unix))]+impl Mapping {+    fn new(_file: &File, _offset: u64, _len: u64) -> Option<Mapping> {+        None+    }++    fn read_at(&self, _offset: u64, _into: &mut [u8]) -> Option<()> {+        None+    }+}++impl Streamed {+    /// Serve later host reads from a memory mapping of the data section. Returns whether it+    /// mapped; on failure (or off unix) reads stay positional, so this never fails the caller.+    ///+    /// For files read a row at a time (Gemma's EMBED). Not for files a net uploads whole, which+    /// gain nothing from it.+    pub fn map(&mut self) -> bool {+        self.mapping = Mapping::new(&self.file, self.data_at, self.data_len);+        self.mapping.is_some()+    }+}++#[cfg(test)]+mod mapping_tests {+    use super::*;++    /// A mapped read returns exactly the bytes a positional read does, for a file that starts at+    /// an unaligned offset inside a larger one (an APK asset), and `map` never breaks reads.+    #[test]+    fn mapped_rows_equal_positional_rows() {+        let blob = write_mixed(+            graph::GEMMA4_EMBED,+            &[+                Fixture::I4(vec![64, 32], (0..64 * 32).map(|i| (i % 15) as i8 - 7).collect()),+                Fixture::F16(vec![64, 1], (0..64).map(|i| 0.01 * i as f32).collect()),+            ],+        );+        let lead = 4099usize;+        let mut bytes = vec![0xA5u8; lead];+        bytes.extend_from_slice(&blob);+        let path = std::env::temp_dir().join(format!("mapping_test_{}.bin", std::process::id()));+        std::fs::write(&path, &bytes).expect("the fixture writes");+        let open = || {+            let file = File::open(&path).expect("the fixture opens");+            Streamed::open(file, lead as u64, blob.len() as u64, graph::GEMMA4_EMBED).expect("it parses")+        };+        let plain = open();+        let mut mapped = open();+        let did_map = mapped.map();+        assert_eq!(did_map, cfg!(unix), "map() maps exactly on unix");+        for row in [0u32, 1, 31, 63] {+            let a = plain.reader().int4_row(0, 1, &[64, 32], row).expect("pread row");+            let b = mapped.reader().int4_row(0, 1, &[64, 32], row).expect("mapped row");+            assert_eq!(a, b, "row {row}");+        }+        let mut past = [0u8; 4];+        assert!(mapped.read_at(mapped.data_len() - 2, &mut past).is_err(), "reads past the end still fail");+        drop(mapped);+        let _ = std::fs::remove_file(&path);+    }+}