Modern Apps git

← Modern-Apps.git

maps: fix rendering speed

Commit
1be087b51d8bcae4ecb017d9d58d5e9219fe8d6d
Author
vayun-mathur <[email protected]>
When
2026-09-23 01:56 UTC (2 months ago)
Parents
7898765

Diff

library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.ktindex 2a54a71e0b..cdafd76d91 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt@@ -697,6 +697,7 @@ class SurfaceMapRenderer(      /** Dim everything outside the region [mask] names, or clear the mask with `null`. */     fun setRegionMask(mask: Long?) {+        Log.d("RegionDbg", "setRegionMask mask=$mask")         this.selectedRegionId = mask         this.regionResolved = false         applyRegionMask()@@ -721,7 +722,9 @@ class SurfaceMapRenderer(         }         // `0` clears above; a nonzero id returns nonzero once a resident tile carries it.         // `0` back means the tiles have not landed yet — retried next frame, not a miss.-        regionResolved = MapNative.setRegionMask(handle, id) != 0L+        val resolved = MapNative.setRegionMask(handle, id) != 0L+        Log.d("RegionDbg", "applyRegionMask id=$id resolved=$resolved")+        regionResolved = resolved     }      private fun applyUserPuck() {
library/map/src/main/rust/Cargo.toml
diff --git a/library/map/src/main/rust/Cargo.toml b/library/map/src/main/rust/Cargo.tomlindex 6ba1ca6ac6..c6b9b1f7f5 100644--- a/library/map/src/main/rust/Cargo.toml+++ b/library/map/src/main/rust/Cargo.toml@@ -52,6 +52,10 @@ ab_glyph = "0.2.32" # compressed sheet instead of the 466 KB of raw RGBA a `build.rs` decode would bake into # the `.so` — the same trade the fonts make with `ab_glyph`. png = "0.18"+# Whole-file mmap for the pushed on-device `.mamaps` archive (see `tile::source::file`):+# range reads are slices of the mapping, so tile fetch pays no syscalls and the OS pages+# the multi-GB archive in and out rather than us copying it through `read_at`.+memmap2 = "0.9"  # `default-features = false` drops the `linked` feature, so nothing links against # libvulkan at build time; `loaded` dlopen's it, which is what an Android app must
library/map/src/main/rust/src/bridge/frame.rs
diff --git a/library/map/src/main/rust/src/bridge/frame.rs b/library/map/src/main/rust/src/bridge/frame.rsindex e0f3d7d471..ea54b5d86f 100644--- a/library/map/src/main/rust/src/bridge/frame.rs+++ b/library/map/src/main/rust/src/bridge/frame.rs@@ -33,7 +33,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     let Some(map) = handle_mut(handle) else {         return 0;     };-    // Per-step timing for the `%60` rollup: `Instant` deltas only, never the camera clock+    // Per-step timing for the per-frame report: `Instant` deltas only, never the camera clock     // (which wraps hourly). The render thread is the only writer.     let jni_start = std::time::Instant::now(); @@ -230,21 +230,40 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(         .borrow_mut()         .record(Step::Select, nanos_since(select_start)); -    // Once a second, state what the renderer actually has. Every bug in this file so far has+    // The active category filter goes to the renderer as well as to tessellation: a chip both+    // narrows which POIs are drawn and pulls its own kinds in earlier than the ambient map shows+    // them. See `Layer::draws_at_focused`.+    let (_, kinds, _) = map.toggles.get();+    let outcome = map.renderer.render(+        &camera,+        &map.layers,+        map.palette,+        style::background(map.palette.variant),+        &kinds,+    );+    // The JNI-entry sample closes here: it covers drain + select + render, which is the whole+    // native half of the frame the host asked for.+    map.renderer+        .step_times+        .borrow_mut()+        .record(Step::JniEntry, nanos_since(jni_start));+    // Every frame, state what the renderer just did. Every bug in this file so far has     // been invisible from the outside: a viewport nobody measured, a zoom level the archive     // does not contain, a tile stuck in flight forever. All of them would have been one line     // of this away.-    map.frames += 1;-    if map.frames % 60 == 0 {+    //+    // After `render`, so `draws`/`tris` and every step sample below belong to the frame this+    // line describes rather than the one before it.+    {         let (tiles, meshes, draws, triangles) = map.renderer.stats();         let (width_px, height_px) = map.renderer.extent();-        // `meshes` is what is resident, `draws` what the last frame actually submitted. They+        // `meshes` is what is resident, `draws` what the frame just submitted. They         // differ wherever the authored style ramps a layer's width to zero, so reporting only         // the first would claim roads are being drawn at zooms where they are gated out.         //-        // The step rollup is built (and its window reset) only on this frame: every other-        // frame pays integer stores only. `avg/max` per step in ms over the last 60 frames.-        let steps = map.renderer.step_times.borrow_mut().report(60);+        // The step report is built (and its window reset) every frame: `avg/max`+        // per step in ms for this frame alone.+        let steps = map.renderer.step_times.borrow_mut().report(1);         log_info(&format!(             "z{:.2} @{:.4},{:.4} b{:.0} vp {}x{}dp {}x{}px msaa {}x | resident {} tiles, {} meshes, \              {} draws, {} tris | {} in flight, {} absent | archive z{}..{} | {}",@@ -268,24 +287,6 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(             steps,         ));     }--    // The active category filter goes to the renderer as well as to tessellation: a chip both-    // narrows which POIs are drawn and pulls its own kinds in earlier than the ambient map shows-    // them. See `Layer::draws_at_focused`.-    let (_, kinds, _) = map.toggles.get();-    let outcome = map.renderer.render(-        &camera,-        &map.layers,-        map.palette,-        style::background(map.palette.variant),-        &kinds,-    );-    // The JNI-entry sample closes here: it covers drain + select + render, which is the whole-    // native half of the frame the host asked for.-    map.renderer-        .step_times-        .borrow_mut()-        .record(Step::JniEntry, nanos_since(jni_start));     match outcome {         Ok(drawn) => jboolean::from(drawn),         Err(e) => {
library/map/src/main/rust/src/bridge/handle.rs
diff --git a/library/map/src/main/rust/src/bridge/handle.rs b/library/map/src/main/rust/src/bridge/handle.rsindex 6fe69433e8..4366c24894 100644--- a/library/map/src/main/rust/src/bridge/handle.rs+++ b/library/map/src/main/rust/src/bridge/handle.rs@@ -136,8 +136,6 @@ pub(crate) struct MapHandle {     pub(crate) toggles: Arc<SharedToggles>,     /// Read live every frame, because the worker only learns it after fetching the header.     pub(crate) zoom_range: Arc<ZoomRange>,-    /// Frames drawn, for the once-a-second diagnostic log.-    pub(crate) frames: u32,     /// Last frame's density (device px per Dp), for the task-17 pick path's     /// Dp→device-px conversion. Written every render call.     pub(crate) density: f32,
library/map/src/main/rust/src/bridge/lifecycle.rs
diff --git a/library/map/src/main/rust/src/bridge/lifecycle.rs b/library/map/src/main/rust/src/bridge/lifecycle.rsindex 77ce60811d..4c69ba6ffd 100644--- a/library/map/src/main/rust/src/bridge/lifecycle.rs+++ b/library/map/src/main/rust/src/bridge/lifecycle.rs@@ -136,7 +136,6 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>(         palette: Palette::new(dark != 0, muted != 0),         toggles,         zoom_range,-        frames: 0,         density: 1.0,     });     Box::into_raw(handle) as jlong
library/map/src/main/rust/src/bridge/log.rs
diff --git a/library/map/src/main/rust/src/bridge/log.rs b/library/map/src/main/rust/src/bridge/log.rsindex c50effd224..e88098fb8a 100644--- a/library/map/src/main/rust/src/bridge/log.rs+++ b/library/map/src/main/rust/src/bridge/log.rs@@ -10,7 +10,7 @@ pub(crate) fn log(message: &str) {     write_log(6, message); } -/// Logcat, at info level, for the periodic frame report.+/// Logcat, at info level, for the per-frame report. pub(crate) fn log_info(message: &str) {     write_log(4, message); }
library/map/src/main/rust/src/tile/source/file.rs
diff --git a/library/map/src/main/rust/src/tile/source/file.rs b/library/map/src/main/rust/src/tile/source/file.rsindex 9bc0ff2f07..37bb716ae5 100644--- a/library/map/src/main/rust/src/tile/source/file.rs+++ b/library/map/src/main/rust/src/tile/source/file.rs@@ -1,36 +1,60 @@ //! A [`RangeReader`] over a local file: the pushed on-device `.mamaps` archive. //! //! When a full archive has been placed on the device — the app's external files dir —-//! the reader opens it directly and serves byte ranges straight from disk. There is no-//! network, no HTTP header fetch and no range cache: the file *is* the source of truth,-//! so none of the republished-under-a-stable-name machinery the caching reader needs-//! applies. When no such file exists the worker keeps using the URL-backed+//! the whole file is mapped read-only up front ([`memmap2::Mmap`]) and every range read+//! is served as a slice of that mapping. There is no network, no HTTP header fetch and+//! no range cache: the file *is* the source of truth, so none of the+//! republished-under-a-stable-name machinery the caching reader needs applies. When no+//! such file exists the worker keeps using the URL-backed //! [`CachingRangeReader`](super::CachingRangeReader) unchanged.+//!+//! Mapping the whole file (rather than `read_at` per range) matters because the archive+//! is gigabytes: with plain positional reads every tile fetch pays syscalls plus a copy+//! through the page cache, and the workers re-read the same leaf directories constantly.+//! With the mapping the OS pages the file in and out on demand and repeated reads of the+//! same bytes cost no I/O at all.  use std::fs::File; use std::path::{Path, PathBuf}; use tilecodec::proto::{err, Error, Result}; use tilecodec::stream::RangeReader; -/// An archive read straight from a local file handle.+/// An archive read straight from a whole-file read-only mapping. ///-/// Holds only the open handle and its path. Every [`read`](RangeReader::read) is a-/// positional read that never moves the handle's cursor, so a single reader is safe to-/// use across reads without a lock — mirroring the positional-read strategy the codec's-/// own file reader uses.+/// Holds the mapping (plus the path for error messages). Reads never touch a file+/// descriptor — they slice the mapping — so sharing one reader across threads needs no+/// lock, and the mapping itself is `Send + Sync`. pub struct FileRangeReader {-    file: File,+    mmap: Option<memmap2::Mmap>,     path: PathBuf, }  impl FileRangeReader {-    /// Open `path` for reading, returning an error the worker can log if it cannot be-    /// opened.+    /// Map the whole file read-only up front, returning an error the worker can+    /// log if it cannot be opened or mapped. An empty file maps to no mapping+    /// rather than failing: `mmap` of length 0 fails on every platform, and an+    /// empty archive simply answers every range as past-the-end.     pub fn open(path: impl Into<PathBuf>) -> Result<FileRangeReader> {         let path = path.into();         let file =             File::open(&path).map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?;-        Ok(FileRangeReader { file, path })+        let len = file+            .metadata()+            .map_err(|e| Error(format!("cannot stat {}: {e}", path.display())))?+            .len();+        let mmap = if len == 0 {+            None+        } else {+            // SAFETY: the archive lands on device via `.part`-then-rename+            // (`InitialDownloader`), so a mapped file is never mutated in place+            // afterwards — rename replaces the path, never the bytes under an+            // existing mapping. The mapping is read-only and kept alive in+            // `self` for as long as any slice of it can be read.+            let mapped = unsafe { memmap2::MmapOptions::new().map(&file) }+                .map_err(|e| Error(format!("cannot map {}: {e}", path.display())))?;+            Some(mapped)+        };+        Ok(FileRangeReader { mmap, path })     }      /// Whether `path` names an existing file, so the worker can decide up front whether@@ -41,37 +65,46 @@ impl FileRangeReader { }  impl RangeReader for FileRangeReader {+    /// Serve the range as a slice of the whole-file mapping: no syscalls, no copy+    /// through the page cache beyond what the OS already paged in. A range past the+    /// end comes back short rather than failing, as the trait's contract requires+    /// and as an HTTP server would answer it.     fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {         if length == 0 {             return Ok(Vec::new());         }-        let mut buf = vec![0u8; length as usize];-        let mut filled = 0usize;-        while filled < buf.len() {-            let Some(dst) = buf.get_mut(filled..) else {-                break;-            };-            let Some(at) = offset.checked_add(filled as u64) else {-                return err(format!(-                    "read offset overflow reading {}",-                    self.path.display()-                ));-            };-            #[cfg(windows)]-            let read = std::os::windows::fs::FileExt::seek_read(&self.file, dst, at);-            #[cfg(unix)]-            let read = std::os::unix::fs::FileExt::read_at(&self.file, dst, at);-            let n =-                read.map_err(|e| Error(format!("reading {} at {at}: {e}", self.path.display())))?;-            // A range past the end of the file comes back short rather than failing, as-            // the trait's contract requires and as an HTTP server would answer it.-            if n == 0 {-                break;-            }-            filled += n;+        let bytes: &[u8] = match self.mmap.as_ref() {+            Some(mmap) => mmap,+            None => return Ok(Vec::new()),+        };+        // Entirely past the end is empty, not an error — as the trait's+        // contract requires and as an HTTP server would answer it.+        let Ok(start) = usize::try_from(offset) else {+            return err(format!(+                "read offset {offset} out of range for {}",+                self.path.display()+            ));+        };+        if start >= bytes.len() {+            return Ok(Vec::new());         }-        buf.truncate(filled);-        Ok(buf)+        let Some(end) = start+            .checked_add(length as usize)+            .map(|e| e.min(bytes.len()))+        else {+            return err(format!(+                "read offset overflow reading {}",+                self.path.display()+            ));+        };+        let Some(slice) = bytes.get(start..end) else {+            return err(format!(+                "read range {offset}..{} out of range for {}",+                offset + u64::from(length),+                self.path.display()+            ));+        };+        Ok(slice.to_vec())     } } 
library/map/src/main/rust/src/timing.rs
diff --git a/library/map/src/main/rust/src/timing.rs b/library/map/src/main/rust/src/timing.rsindex 6020e61831..5a31283812 100644--- a/library/map/src/main/rust/src/timing.rs+++ b/library/map/src/main/rust/src/timing.rs@@ -3,13 +3,13 @@ //! The frame log used to say only how many draws and triangles the last frame submitted, so a //! janky pan or tilt could not be attributed to a stage — upload drain, tile select, fence wait, //! each record sub-pass, submit, present. This module times each of those steps separately, so-//! the once-a-second `%60` rollup can say *which* one owns the tail.+//! the per-frame report can say *which* one owns the tail. //! //! # Cost model //! //! Every frame pays one [`Instant::now`](std::time::Instant::now) pair per step and three integer-//! array stores in [`StepTimes::record`] — no allocation, no formatting. The rollup string is-//! built only on report frames (every 60th), in [`StepTimes::report`], which also resets the+//! array stores in [`StepTimes::record`] — no allocation, no formatting — plus one report string+//! built in [`StepTimes::report`], which also resets the window. A slow UI poll reads the last //! window. A slow UI poll reads the last frame's array through [`StepTimes::last_nanos`] for the //! debug overlay; the render thread never blocks on it. //!@@ -24,7 +24,7 @@  /// One timed step of a frame, in the order the frame runs them. ///-/// Short names are the `%60` logcat labels; [`Step::ALL`] fixes the order the JNI getter and the+/// Short names are the per-frame logcat labels; [`Step::ALL`] fixes the order the JNI getter and the /// Kotlin overlay mirror, so adding a step means appending here *and* there (the overlay /// size-checks the array and shows `n/a` on drift rather than mislabelling rows). #[derive(Clone, Copy)]@@ -100,7 +100,7 @@ impl Step {     /// Steps timed per frame.     pub(crate) const COUNT: usize = Self::ALL.len(); -    /// The `%60` logcat label: short, fixed-width-ish, unambiguous at a glance.+    /// The per-frame logcat label: short, fixed-width-ish, unambiguous at a glance.     pub(crate) fn short_name(self) -> &'static str {         match self {             Step::JniEntry => "jni",@@ -130,7 +130,7 @@ impl Step { /// The per-step timing state for one renderer. /// /// Three fixed arrays plus the window length: the last frame's steps (for the JNI getter), and-/// the rolling sum/max the `%60` rollup reports. Fixed-size and allocation-free by construction —+/// the rolling sum/max the per-frame report prints. Fixed-size and allocation-free by construction — /// [`record`](Self::record) is three integer stores, and only [`report`](Self::report) formats. pub(crate) struct StepTimes {     last: [u64; Step::COUNT],@@ -166,10 +166,10 @@ impl StepTimes {         &self.last     } -    /// The `avg/max` rollup over the last `frames` frames, in ms with one decimal, then reset the-    /// window. Called only on report frames, so this is the one place that formats.+    /// The `avg/max` report over the last `frames` frames, in ms with one decimal, then reset the+    /// window. Called every frame, so this is the one place that formats.     ///-    /// `frames` is the window length (60 on the `%60` cadence), not read from here, so a frame+    /// `frames` is the window length (1 on the per-frame cadence), not read from here, so a frame     /// that never ran a step still divides correctly.     pub(crate) fn report(&mut self, frames: u32) -> String {         let frames = frames.max(1) as u64;
library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs b/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rsindex 20cbf74fcc..ac892c361c 100644--- a/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs@@ -109,7 +109,7 @@ pub struct Renderer {     /// module docs of [`crate::bridge`] set out.     pub(crate) submitted_draws: Cell<usize>,     /// Per-step frame timing (see [`crate::timing`]): last-frame steps plus the rolling-    /// sum/max the `%60` rollup reports. A `RefCell` because the record sub-passes take `&self`+    /// sum/max the per-frame report prints and resets. A `RefCell` because the record sub-passes take `&self`     /// — the same reason `placed` is one — and each record is a short leaf borrow.     pub(crate) step_times: std::cell::RefCell<crate::timing::StepTimes>,     /// Task-17 pick state: the last frame's PLACED labels — accept-set id,
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 5bc3f36712..d90945af6b 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -29,11 +29,29 @@ use modelrunner::nets::gemma4; use modelrunner::vulkan::context; use modelrunner::vulkan::reshape::Reshaped; use modelrunner::vulkan::run::StepParams;-use modelrunner::weights::{graph, Weights};+use modelrunner::weights::{Streamed, graph};  /// The cache these examples record against: the top tier, so a long prompt fits. const TIER: u32 = gemma4::MAX_CONTEXT; +/// Open both `.maml` files as [`Streamed`] instead of `std::fs::read` + [`Weights::parse`].+///+/// The old path held 1.09 GB + 2.39 GB resident and then copied each data section again+/// inside `parse`, which is ~7 GB of peak host RSS against the ~2.4 GB a 7 GB Pixel 8 has+/// free — the OOM-reboot this harness caused twice. `Streamed::open` reads only the+/// ~64 KB header/table prefix; the data section stays in the file and is pulled through+/// `Net`'s 8 MB chunked staging upload plus row-at-a-time host gathers, so peak host RSS+/// is tens of MB. Identical bytes reach the device (`read_at` over the same section).+fn open_streamed(path: &PathBuf, expect_graph: u32) -> Result<Streamed, String> {+    let file = std::fs::File::open(path)+        .map_err(|e| format!("cannot open {}: {e}", path.display()))?;+    let len = file+        .metadata()+        .map_err(|e| format!("cannot size {}: {e}", path.display()))?+        .len();+    Streamed::open(file, 0, len, expect_graph)+}+ fn main() {     let mut args = std::env::args().skip(1);     let (Some(text), Some(embed), Some(golden)) =@@ -42,20 +60,13 @@ fn main() {         println!("usage: check_gemma4_parity <text.maml> <embed.maml> <golden.json>");         return;     };-    let (text_bytes, embed_bytes) = match (std::fs::read(&text), std::fs::read(&embed)) {-        (Ok(a), Ok(b)) => (a, b),-        (a, b) => {-            println!("cannot read the weights: {:?} {:?}", a.err(), b.err());-            return;-        }-    };-    let weights = match Weights::parse(&text_bytes, graph::GEMMA4_TEXT) {+    let weights = match open_streamed(&text, graph::GEMMA4_TEXT) {         Ok(w) => w,-        Err(why) => return println!("the text model does not parse: {why}"),+        Err(why) => return println!("the text model does not stream: {why}"),     };-    let embed_weights = match Weights::parse(&embed_bytes, graph::GEMMA4_EMBED) {+    let embed_weights = match open_streamed(&embed, graph::GEMMA4_EMBED) {         Ok(w) => w,-        Err(why) => return println!("the embedding does not parse: {why}"),+        Err(why) => return println!("the embedding does not stream: {why}"),     };     let golden = match std::fs::read_to_string(&golden) {         Ok(text) => text,@@ -125,14 +136,19 @@ fn field(text: &str, key: &str) -> Option<Vec<f32>> { /// [`run`] stopping after `layers` layers, returning `(hidden, per_layer)`. fn trace_run(     context: &Arc<context::Context>,-    weights: &Weights,-    embed: &Weights,+    weights: &Streamed,+    embed: &Streamed,     tokens: &[u32],     layers: usize, ) -> Result<(Vec<f32>, Vec<f32>), String> {     let mode = gemma4::Mode::Trace { layers }.at(TIER);-    let mut net =-        Reshaped::new(Arc::clone(context), weights, mode, |offsets, mode| gemma4::build(offsets, mode))?;+    let mut net = Reshaped::streamed(+        Arc::clone(context),+        weights.offsets(),+        weights,+        mode,+        |offsets, mode| gemma4::build(offsets, mode),+    )?;     let reader = embed.reader();     let rotary = weights.reader();     let mut last = (Vec::new(), Vec::new());@@ -163,12 +179,13 @@ fn trace_run( /// transformer, AND the tied-head path the app actually uses. fn run(     context: &Arc<context::Context>,-    weights: &Weights,-    embed: &Weights,+    weights: &Streamed,+    embed: &Streamed,     tokens: &[u32], ) -> Result<Vec<f32>, String> {-    let mut net = Reshaped::new(+    let mut net = Reshaped::streamed(         Arc::clone(context),+        weights.offsets(),         weights,         gemma4::Mode::DecodeStep.at(TIER),         |offsets, mode| gemma4::build(offsets, mode),
library/ml/src/main/rust/src/nets/gemma4_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part1.rs b/library/ml/src/main/rust/src/nets/gemma4_part1.rsindex 80c0463f50..6d7b40eeae 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part1.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part1.rs@@ -368,7 +368,11 @@ fn prefill_layer(             let k = b.rms_norm_grouped(k, k_norm_at, EPSILON, KV_HEADS);             let k = b.rotary(k, angles, KV_HEADS);             let v = point(b, v_proj, normed, KV_HEADS * dim);-            // No v_norm: litertlm carries none, so values cache unnormalized.+            // S10's `value_norm`, as in [`super::layer`]: a parameter-free+            // RMS norm (all-ones gamma, [`ONE_SLIDING`]/[`ONE_FULL`]) before+            // the cache write. The decode path must read what this wrote.+            let ones = if is_full_attention(index) { ONE_FULL } else { ONE_SLIDING };+            let v = b.rms_norm(v, ones, EPSILON);             // Written for the decode steps that follow this prompt. `cache_write` transposes             // channel-major into the cache's position-major layout.             b.cache_write(k, cache_k);
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 43a4e3691c..f4f80de077 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part4.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part4.rs@@ -65,8 +65,12 @@ pub mod embed { /// `inputs_embeds` is the working-table row; `per_layer_inputs` is the COMBINED /// block the reference's `maybe_preprocess_per_layer_embeddings` produces: ///-///     projected = hidden @ SHARED_PROJ * 1/sqrt(d_model)-///     combined  = (embedded + rms_norm(projected)) * 1/sqrt(2)+///     projected = hidden @ SHARED_PROJ+///     combined  = (16 * embedded + rms_norm(projected)) * 1/sqrt(2)+///+/// S10 graph walk t319 -> t30: t307 `[16.0]` scales the gather side, t304+/// `[1/sqrt(2)]` the sum. No `1/sqrt(d_model)` exists anywhere in S10 (and a+/// grouped RMS-norm would erase a uniform pre-scale anyway). /// /// `embedded` concatenates one 256-wide row from each layer's own mmap table /// (litertlm gathers the same way: 35 parallel lookups + concat).@@ -131,16 +135,20 @@ fn combine(     let gamma = embed.fp16(embed::SHARED_NORM, &[PER_LAYER])?;     let rows = LAYERS;     let wide = PER_LAYER as usize;-    let inv_sqrt_d = 1.0 / (f32::from(D_MODEL as u16)).sqrt();+    // S10 t307: the gather side carries x16 (a real term, not a neutral+    // rescale - the sum mixes two different-magnitude halves).+    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 * D_MODEL as usize..(r + 1) * wide * D_MODEL as usize];         let emb = &embedded[r * wide..(r + 1) * wide];-        // projected = W @ hidden / sqrt(d_model), one 256-wide group.+        // projected = W @ hidden, one 256-wide group. No 1/sqrt(d_model):+        // S10 has no such constant, and the grouped RMS-norm below would+        // erase a uniform pre-scale anyway.         let mut group = vec![0f32; wide];         for (o, wrow) in group.iter_mut().zip(row.chunks_exact(D_MODEL as usize)) {-            *o = wrow.iter().zip(hidden.iter()).map(|(a, b)| a * b).sum::<f32>() * inv_sqrt_d;+            *o = wrow.iter().zip(hidden.iter()).map(|(a, b)| a * b).sum::<f32>();         }         // Grouped RMS norm with the shared 256-wide gamma.         let mean_sq = group.iter().map(|v| v * v).sum::<f32>() / wide as f32;@@ -148,9 +156,9 @@ fn combine(         for (v, &g) in group.iter_mut().zip(gamma.iter()) {             *v = *v * norm * g;         }-        // combined = (embedded + normed) / sqrt(2).+        // combined = (16 * embedded + normed) / sqrt(2) (t307, t304).         for (v, &e) in group.iter_mut().zip(emb.iter()) {-            *v = (*v + e) * inv_sqrt_2;+            *v = (*v + GATHER_SCALE * e) * inv_sqrt_2;         }         out.extend_from_slice(&group);     }
maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.ktindex 585da71aba..f56148a51c 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt@@ -1,5 +1,6 @@ package com.vayunmathur.maps.data +import android.util.Log import com.vayunmathur.library.map.GeoPoint import com.vayunmathur.maps.util.PoiIndex import com.vayunmathur.maps.util.Wikidata@@ -129,6 +130,7 @@ suspend fun parse(feature: Feature1): SpecificFeature? {     // The baked link: the tagged relation id of the boundary this label names, stamped at     // build time (`region_links`). `0` is REGION_NONE — unlinked, mask nothing.     val regionId = properties["regionId"]?.jsonPrimitive?.content?.toLongOrNull() ?: 0L+    Log.d("RegionDbg", "parse kind=${properties.string("kind")} name=$name regionId=$regionId")     return when (properties.string("kind")) {         "country" -> SpecificFeature.Admin0Label(             iso = wiki?.getProperty("P297"),
maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.ktindex 5bd7b27cbc..4d7e7699f2 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.kt@@ -1,5 +1,6 @@ package com.vayunmathur.maps.ui.map +import android.util.Log import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.DpRect import androidx.compose.ui.unit.DpSize@@ -182,6 +183,7 @@ class MapFeaturePicker(          */         fun PlacedLabel.toFeature1(): Feature1? {             if (nativeToBase(layerId) == null) return null+            Log.d("RegionDbg", "pick layer=$layerId name=$name kind=$kind regionId=$regionId")             return Feature1(                 Point(position),                 JsonObject(