various fixes
- Commit
0542c4a17213c2ab6f5f2d8633816615faaf7d45- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-02 15:24 UTC (2 months ago)
- Parents
88985d4
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 9d9e7c7420..7a3d06df6a 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -303,9 +303,14 @@ fn time_decode( let stamps = modelrunner::knobs::is_set("timestamps"); let mut op_report: Option<Vec<(String, f64, f64)>> = None; let mut steady: Vec<f64> = Vec::new();- // Host-side split: gather+rotary file reads vs device infer per step.- // Accumulated over steady-state passes only, reported once.- let mut host_ms = 0.0;+ // Host-side split, accumulated over steady-state passes only, reported once:+ // the gather's row reads / bulk projection reads / matmul (from `gather_timed`)+ // plus this loop's own rotary reads, vs device infer per step. Phase 3a′+ // step 1: this decides how steps 2–3 divide the ~240 ms host slice.+ let mut rows_ms = 0.0;+ let mut bulk_ms = 0.0;+ let mut matmul_ms = 0.0;+ let mut rotary_ms = 0.0; let mut infer_ms = 0.0; let mut host_steps = 0usize; for pass in 0..repeats {@@ -316,10 +321,10 @@ fn time_decode( Ok(p) => p, Err(_) => return println!("a step past u32"), };- let host_tick = Instant::now();- let Ok((hidden_in, per_layer)) = gemma4::gather(&reader, token) else {+ let Ok((hidden_in, per_layer, gtimes)) = gemma4::gather_timed(&reader, token) else { return println!("gather failed at step {step}"); };+ let rotary_tick = Instant::now(); let Ok(angles_local) = rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position) else {@@ -330,7 +335,7 @@ fn time_decode( else { return println!("rotary global failed at step {step}"); };- let host_done = host_tick.elapsed().as_secs_f64() * 1000.0;+ let rotary_done = rotary_tick.elapsed().as_secs_f64() * 1000.0; let at = match net.at(gemma4::Mode::DecodeStep.at(TIER)) { Ok(at) => at, Err(why) => return println!("the net does not bind at step {step}: {why}"),@@ -350,7 +355,10 @@ fn time_decode( Err(why) => return println!("step {step} failed: {why}"), } if pass > 0 {- host_ms += host_done;+ rows_ms += gtimes.rows_ms;+ bulk_ms += gtimes.bulk_ms;+ matmul_ms += gtimes.matmul_ms;+ rotary_ms += rotary_done; infer_ms += infer_tick.elapsed().as_secs_f64() * 1000.0; host_steps += 1; }@@ -378,10 +386,14 @@ fn time_decode( println!("steady-state: {mean:.1} ms/token = {:.2} tok/s", 1000.0 / mean.max(1e-9)); } if host_steps > 0 {+ let steps = host_steps as f64; println!(- "host split per step: gather+rotary {:.1} ms, infer {:.1} ms ({} steps)",- host_ms / host_steps as f64,- infer_ms / host_steps as f64,+ "host split per step: rows {:.1} ms, int8_all {:.1} ms, matmul {:.1} ms, rotary {:.1} ms, infer {:.1} ms ({} steps)",+ rows_ms / steps,+ bulk_ms / steps,+ matmul_ms / steps,+ rotary_ms / steps,+ infer_ms / steps, host_steps ); }
library/ml/src/main/rust/examples/probe_rmsnorm.rs
diff --git a/library/ml/src/main/rust/examples/probe_rmsnorm.rs b/library/ml/src/main/rust/examples/probe_rmsnorm.rsnew file mode 100644index 0000000000..1bdc63595f--- /dev/null+++ b/library/ml/src/main/rust/examples/probe_rmsnorm.rs@@ -0,0 +1,176 @@+//! Single-norm microbenchmark: why is device RmsNorm 80x the sibling small ops?+//!+//! ```text+//! cargo run --offline --release -p modelrunner --example probe_rmsnorm+//! ```+//!+//! Phase 3b′ probe (read-only): one RmsNorm at decode shapes, sweeping channels,+//! groups, and count, best-of-5 wall plus per-op device times when+//! `MODELRUNNER_TIMESTAMPS=1` is set. Synthetic `Builder` plan + `Net::infer_raw`+//! over a kilobytes-large dummy blob — no model file, no whole-file upload, zero+//! OOM risk by construction.+//!+//! # The question this answers+//!+//! The per-op timestamp table puts 241 RmsNorm dispatches at ~830 µs mean each+//! (~200 ms a step) against Mul at 8.5 µs, Rotary at 11.5 µs, SoftmaxPrefix at+//! 14 µs. A norm over ≤1536 elements moves ~6 KB; at 830 µs that is ~7 MB/s+//! effective — so it is not fetch-bound. Candidate mechanisms and their+//! predictions:+//!+//! * single-workgroup launch/drain cost → flat vs channels, per-op cost drops+//! (or holds) when tiled, rises linearly with count;+//! * serial-reduction ALU → linear in channels;+//! * driver pathologies → cliffs at specific shapes.+//!+//! The sweep below is shaped to discriminate exactly these three. No fix is+//! designed until the numbers speak — the one-paragraph mechanism statement+//! this prints is the gate for all Phase 3b′ fix work.+//!+//! # Geometries (every RmsNorm the transformer actually runs)+//!+//! * plain 1536 (input / pre_ff / final norms, groups = 1);+//! * plain 256 (K norm: KV_HEADS = 1, so grouped-over-1; v norms);+//! * grouped 2048 = 8 heads × 256 (local Q norm, groups = 8);+//! * grouped 4096 = 8 heads × 512 (global Q norm, groups = 8);+//! * grouped 256 with groups = 8 (cross-cut: same channels as the K norm,+//! grouped like Q — isolates the grouping effect from the width effect).++use modelrunner::nets::{Builder, Shape, WeightSource};+use modelrunner::vulkan::{context, run::Net};+use modelrunner::weights::{Blob, Tensor};++/// Channels × groups × chained-count to sweep: decode widths, the natural+/// grouping for each width, the 256-wide cross-cut, and 1 vs 35-chained (one+/// layer's worth of sequential norms in a single plan).+const SWEEP: [(u32, u32, usize); 10] = [+ (256, 1, 1),+ (512, 1, 1),+ (1536, 1, 1),+ (2048, 8, 1),+ (4096, 8, 1),+ // Grouping cross-cut at fixed width.+ (256, 8, 1),+ (2048, 1, 1),+ // Tiled: one layer's sequential norms in one plan.+ (1536, 1, 35),+ (2048, 8, 35),+ (256, 1, 35),+];++/// A weight source for the norm probe: every tensor at offset zero.+///+/// Mirrors the `ProbeSource` in `bridge_part7.rs` (which examples cannot use:+/// it is private to the Android-gated bridge). They alias, which would be+/// nonsense for inference and is right here — the probe asks how fast a norm+/// runs, not what it computes.+struct NormSource;++impl WeightSource for NormSource {+ fn shaped(&self, _index: usize, _dims: &[u32]) -> Result<u32, String> {+ Ok(0)+ }+ fn shaped_words(&self, _index: usize, _dims: &[u32]) -> Result<u32, String> {+ Ok(0)+ }+ fn count(&self) -> usize {+ 1+ }+}++/// A kilobytes-large blob of identical bytes with a one-tensor table beside it.+///+/// The gamma the norms read is whatever these bytes decode to as fp16 — the+/// values do not matter for timing (no NaN: the input feed is nonzero and the+/// norm divides by the input's own magnitude, never by gamma).+struct NormFile {+ bytes: Vec<u8>,+ table: Vec<Tensor>,+}++impl Blob for NormFile {+ fn data_len(&self) -> u64 {+ self.bytes.len() as u64+ }+ fn tensors(&self) -> &[Tensor] {+ &self.table+ }+ fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String> {+ let from = offset as usize;+ let span = self.bytes.get(from..from + into.len()).ok_or_else(|| {+ format!("a read of {} at {offset} past {}", into.len(), self.bytes.len())+ })?;+ into.copy_from_slice(span);+ Ok(())+ }+}++fn main() {+ let context = match context::shared() {+ Ok(context) => context,+ Err(why) => return println!("no Vulkan device: {why}"),+ };+ let stamps = modelrunner::knobs::is_set("timestamps");+ println!("channels groups count best-us per-op-us (best of 5)");+ for (channels, groups, count) in SWEEP {+ match probe(&context, channels, groups, count, stamps) {+ Ok((best, per_op)) => match per_op {+ Some(op) => println!("{channels:>8} {groups:>6} {count:>5} {best:>7.1} {op:>9.1}"),+ None => println!("{channels:>8} {groups:>6} {count:>5} {best:>7.1} (set MODELRUNNER_TIMESTAMPS=1 for per-op)"),+ },+ Err(why) => println!("{channels:>8} {groups:>6} {count:>5} failed: {why}"),+ }+ }+}++/// Time `count` chained RmsNorms over `channels` inputs in `groups` groups.+///+/// Returns best-of-5 wall µs plus, when `stamps` is set, the timestamped+/// per-op mean for the last iteration. Chained (each op reads the previous+/// output) so the dispatches serialize exactly as decode's interleaved norms do.+fn probe(+ context: &std::sync::Arc<context::Context>,+ channels: u32,+ groups: u32,+ count: usize,+ stamps: bool,+) -> Result<(f64, Option<f64>), String> {+ let source = NormSource;+ let mut builder = Builder::new(&source);+ let input = builder.input(Shape::new(channels, 1, 1));+ let mut out = input;+ for _ in 0..count {+ out = builder.rms_norm_grouped(out, 0, modelrunner::nets::gemma4::EPSILON, groups);+ }+ let plan = builder.finish(&[out])?;+ if plan.ops.len() != count {+ return Err(format!("{} chained norms built {} ops", count, plan.ops.len()));+ }+ // Gamma needs per_group fp16 entries; 8 KB covers the widest point.+ let bytes = vec![0x11u8; 8192];+ let table = vec![Tensor {+ rank: 1,+ dims: [4096, 0, 0, 0],+ offset: 0,+ len: 4096,+ dtype: modelrunner::weights::Dtype::F16,+ }];+ let file = NormFile { bytes, table };+ let mut net = Net::new(std::sync::Arc::clone(context), plan, &file, modelrunner::preprocess::RESCALE_ONLY)?;+ let feed = vec![0.5f32; channels as usize];+ net.infer_raw(&feed)?;+ let mut best = f64::MAX;+ for _ in 0..5 {+ let started = std::time::Instant::now();+ net.infer_raw(&feed)?;+ best = best.min(started.elapsed().as_secs_f64());+ }+ let per_op = if stamps {+ let report = net.op_times()?;+ let total: f64 = report.iter().map(|(_, us, _)| us).sum();+ Some(total / report.len().max(1) as f64)+ } else {+ None+ };+ Ok((best * 1e6, per_op))+}
library/ml/src/main/rust/examples/run_gemma4.rs
diff --git a/library/ml/src/main/rust/examples/run_gemma4.rs b/library/ml/src/main/rust/examples/run_gemma4.rsindex 5bae92834c..3e4f762f92 100644--- a/library/ml/src/main/rust/examples/run_gemma4.rs+++ b/library/ml/src/main/rust/examples/run_gemma4.rs@@ -257,45 +257,16 @@ fn gather_rows( /// Host combine over already-gathered rows (see `gather_rows`). ///-/// Mirrors `gemma4_part4::combine` exactly (private there): int8-/// `SHARED_PROJ` projection, grouped RMS norm with `SHARED_NORM` gamma,-/// `(16 * embedded + normed) / sqrt(2)`. Needs the EMBED reader for the-/// projection table + gamma — passed by the gate caller.+/// A thin wrapper over the shared cached implementation+/// (`gemma4::combine_cached`): int8 `SHARED_PROJ` projection, grouped RMS norm+/// with `SHARED_NORM` gamma, `(16 * embedded + normed) / sqrt(2)`. fn gather_combine_host( reader: &modelrunner::weights::Reader<'_>, hidden: &[f32], embedded: &[f32], ) -> Result<Vec<f32>, String> { use modelrunner::nets::gemma4;- let proj = reader.int8_all(- gemma4::embed::SHARED_PROJ,- gemma4::embed::SHARED_PROJ + 1,- &[gemma4::LAYERS as u32 * gemma4::PER_LAYER, gemma4::D_MODEL, 1, 1],- )?;- let gamma = reader.fp16(gemma4::embed::SHARED_NORM, &[gemma4::PER_LAYER])?;- let rows = gemma4::LAYERS;- let wide = gemma4::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 + gemma4::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)+ gemma4::combine_cached(reader, hidden, embedded) } /// Logits for `hidden`: the GPU head when the EMBED file carries chunks.
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 699cacc44e..f0eaeeed62 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -7,10 +7,11 @@ // irrelevant — e.g. `CHUNK` here is read by `prefill` in part6. /// 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+/// caller already gathered.+///+/// A thin wrapper over `gemma4::combine_cached` — the single shared+/// implementation, served from the process-constant combine cache (see+/// `nets::gemma4_part4`). 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(@@ -18,37 +19,7 @@ fn gather_combine_host( 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)+ crate::nets::gemma4::combine_cached(&embed.reader(), hidden, embedded) } fn gemma4_head_greedy_plan(offsets: &Offsets, _: ()) -> Result<Plan, String> {
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 c739530b1f..a8182ab75b 100644--- a/library/ml/src/main/rust/src/bridge_part6.rs+++ b/library/ml/src/main/rust/src/bridge_part6.rs@@ -41,10 +41,9 @@ impl Gemma4Handle { // Wrong shape: fall through to the host combine rather than failing. } // Host combine: the same projection + grouped-norm + scaled add that- // `gemma4_gather::build_plan` runs on-device. Inlined (not shared)- // because `gemma4_part4::combine` is private to that module AND reads- // through a `Reader`; this takes the already-gathered rows. The two- // must agree exactly, which the `--gather-parity` gate enforces.+ // `gemma4_gather::build_plan` runs on-device, via the shared cached+ // implementation (`gemma4::combine_cached`) over the already-gathered+ // rows. The `--gather-parity` gate enforces exact agreement. Ok((hidden.clone(), gather_combine_host(&self.embed, &hidden, &embedded)?)) }
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 079903aba4..04594e2349 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part4.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part4.rs@@ -102,13 +102,47 @@ pub mod embed { /// (litertlm gathers the same way: 35 parallel lookups + concat). /// The combination lives here rather than in [`build`] because the projection /// lives in the EMBED file and a pass reads one weights file, not two.+///+/// The process-constant projection comes from the combine cache (see+/// [`combine_cached`]); use [`gather_timed`] when the per-phase attribution+/// matters. pub fn gather( embed: &crate::weights::Reader<'_>, token: u32, ) -> Result<(Vec<f32>, Vec<f32>), String> {+ gather_timed(embed, token).map(|(hidden, per_layer, _)| (hidden, per_layer))+}++/// Host-side milliseconds inside one [`gather`], by phase.+///+/// `rows` covers the 36 int4 row reads (working table + 35 per-layer tables);+/// `bulk` the process-constant `int8_all` + gamma reads (`~0` on a combine-cache+/// hit — the row going quiet is the cache's gate signal); `matmul` the 13.7M-MAC+/// projection + grouped norm + scaled add. Rotary stays harness-side: the+/// `--time` loop times its own `rotary_row` calls.+pub struct GatherTimes {+ /// ms in the 36 int4 row reads.+ pub rows_ms: f64,+ /// ms in the `int8_all` + gamma bulk reads (`~0` on a cache hit).+ pub bulk_ms: f64,+ /// ms in the projection + grouped norm + scaled add.+ pub matmul_ms: f64,+}++/// [`gather`] with its host split attached (Phase 3a′ step 1).+///+/// Harness-only attribution: the bytes computed are identical to [`gather`]'s,+/// only timed. The `--time` loop accumulates these alongside its own rotary+/// timing to decide how steps 2–3 divide the ~240 ms host slice.+pub fn gather_timed(+ embed: &crate::weights::Reader<'_>,+ token: u32,+) -> Result<(Vec<f32>, Vec<f32>, GatherTimes), String> {+ use std::time::Instant; if token >= VOCAB { return Err(format!("token {token} is past the {}-entry vocabulary", VOCAB)); }+ let rows_tick = Instant::now(); let hidden = embed.int4_row(embed::TOKENS, embed::TOKENS + 1, &[VOCAB, D_MODEL], token)?; // The placeholders have no per-layer row of their own; the export masks them to 0. let per_layer_row = if embed::PLACEHOLDERS.contains(&token) { 0 } else { token };@@ -117,7 +151,10 @@ pub fn gather( let at = embed::table(i); embedded.extend(embed.int4_row(at, at + 1, &[VOCAB, PER_LAYER], per_layer_row)?); }- Ok((hidden.clone(), combine(embed, &hidden, &embedded)?))+ let rows_ms = rows_tick.elapsed().as_secs_f64() * 1000.0;+ let (per_layer, bulk_ms, matmul_ms) =+ combine_timed(embed, &hidden, &embedded, combine_cache_enabled())?;+ Ok((hidden.clone(), per_layer, GatherTimes { rows_ms, bulk_ms, matmul_ms })) } /// The per-layer combination for an EXPLICIT hidden state (see [`gather`]).@@ -144,21 +181,135 @@ pub fn gather_soft( let at = embed::table(i); embedded.extend(embed.int4_row(at, at + 1, &[VOCAB, PER_LAYER], token)?); }- combine(embed, hidden, &embedded)+ combine_cached(embed, hidden, &embedded) } -/// `combine` proper: project, grouped-norm, add, halve the variance.-fn combine(+/// The per-layer combination over already-gathered rows, cached (Phase 3a′ step 2).+///+/// The projection (`SHARED_PROJ` int8 `[8960, 1536]`, 13.7 MB) and the gamma+/// (`SHARED_NORM`) are process-constant: only the rows vary per token. The+/// first call reads and dequantises them once (~55 MB fp32 resident) and every+/// later step is served from memory; the bytes are identical by construction —+/// same file, same decode, once not per step.+///+/// On by default; `MODELRUNNER_COMBINE_CACHE=0` (or `off`/`false`, or+/// `debug.modelrunner.combine_cache` on Android) re-reads per step — today's+/// path, the per-phase fallback. The flag shares the on-by-default opt-out+/// convention of the quantize fold (see `quant_fold_on`).+///+/// This is the single shared implementation: the bridge's `gather_combine_host`+/// and the `--gather-parity` gate's both delegate here, so the cache covers the+/// shipped step path as well as the harnesses.+pub fn combine_cached( embed: &crate::weights::Reader<'_>, hidden: &[f32], embedded: &[f32], ) -> Result<Vec<f32>, String> {- let proj = embed.int8_all(- embed::SHARED_PROJ,- embed::SHARED_PROJ + 1,- &[LAYERS as u32 * PER_LAYER, D_MODEL, 1, 1],- )?;+ combine_timed(embed, hidden, embedded, combine_cache_enabled()).map(|(out, _, _)| out)+}++/// Whether the combine cache serves, read once.+///+/// Cached because this is consulted per token, where a property lookup per call+/// would be a (small but pointless) share of what Phase 3a′ is trying to remove.+/// Same rationale as the timestamp knob in `vulkan::run`.+fn combine_cache_enabled() -> bool {+ use std::sync::OnceLock;+ static ON: OnceLock<bool> = OnceLock::new();+ *ON.get_or_init(|| crate::nets::quant_fold_on(crate::knobs::get("combine_cache")))+}++/// The cached process-constant half of the combine: dequantised projection + gamma.+///+/// `key` pins the file identity AND the three tensors' descriptors, so a cache+/// hit means the same bytes by construction. Fills under the lock: decode is+/// single-threaded and the fill happens once per file, so no step ever waits on+/// another's I/O.+struct CombineBulk {+ /// File identity plus projection/scale/gamma descriptors (see `Reader::file_id`).+ key: (usize, u64, crate::weights::Tensor, crate::weights::Tensor, crate::weights::Tensor),+ /// Dequantised `SHARED_PROJ`, `[LAYERS * PER_LAYER, D_MODEL]` fp32 (~55 MB).+ proj: std::sync::Arc<Vec<f32>>,+ /// Dequantised `SHARED_NORM`, `[PER_LAYER]` fp32.+ gamma: std::sync::Arc<Vec<f32>>,+}++/// The combine cache itself: one slot, replaced when the file changes.+///+/// One slot is enough because every flow opens its EMBED file once and holds it:+/// the bridge handle for the conversation, each harness for its run. A second+/// file evicts the first rather than growing without bound (the OOM guard: the+/// streaming harness exists because this device reboots).+fn combine_cache() -> &'static std::sync::Mutex<Option<CombineBulk>> {+ use std::sync::OnceLock;+ static CACHE: OnceLock<std::sync::Mutex<Option<CombineBulk>>> = OnceLock::new();+ CACHE.get_or_init(|| std::sync::Mutex::new(None))+}++/// `combine` proper with its bulk/matmul split attached: projection, grouped-norm, add.+///+/// `use_cache = true` serves the process-constant half from the combine cache;+/// `false` re-reads per step (today's path, and the identity test's oracle).+/// The arithmetic below is byte-for-byte the old `combine` — only where the+/// projection comes from changed.+fn combine_timed(+ embed: &crate::weights::Reader<'_>,+ hidden: &[f32],+ embedded: &[f32],+ use_cache: bool,+) -> Result<(Vec<f32>, f64, f64), String> {+ use std::time::Instant;+ let bulk_tick = Instant::now();+ let (proj, gamma) = combine_projection(embed, use_cache)?;+ let bulk_ms = bulk_tick.elapsed().as_secs_f64() * 1000.0;+ let matmul_tick = Instant::now();+ let out = apply_combine(&proj, &gamma, hidden, embedded);+ let matmul_ms = matmul_tick.elapsed().as_secs_f64() * 1000.0;+ Ok((out, bulk_ms, matmul_ms))+}++/// The process-constant half of the combine, cached or freshly read.+fn combine_projection(+ embed: &crate::weights::Reader<'_>,+ use_cache: bool,+) -> Result<(std::sync::Arc<Vec<f32>>, std::sync::Arc<Vec<f32>>), String> {+ let proj_dims = [LAYERS as u32 * PER_LAYER, D_MODEL, 1, 1];+ if !use_cache {+ let proj = embed.int8_all(embed::SHARED_PROJ, embed::SHARED_PROJ + 1, &proj_dims)?;+ let gamma = embed.fp16(embed::SHARED_NORM, &[PER_LAYER])?;+ return Ok((std::sync::Arc::new(proj), std::sync::Arc::new(gamma)));+ }+ let (table, data_len) = embed.file_id();+ let proj_tensor = embed.describe(embed::SHARED_PROJ, &proj_dims)?;+ let scale_tensor = embed.describe(embed::SHARED_PROJ + 1, &[LAYERS as u32 * PER_LAYER])?;+ let gamma_tensor = embed.describe(embed::SHARED_NORM, &[PER_LAYER])?;+ let key = (table, data_len, proj_tensor, scale_tensor, gamma_tensor);+ let mut guard =+ combine_cache().lock().unwrap_or_else(|poisoned| poisoned.into_inner());+ if let Some(cached) = guard.as_ref() {+ if cached.key == key {+ return Ok((std::sync::Arc::clone(&cached.proj), std::sync::Arc::clone(&cached.gamma)));+ }+ }+ let proj = embed.int8_all(embed::SHARED_PROJ, embed::SHARED_PROJ + 1, &proj_dims)?; let gamma = embed.fp16(embed::SHARED_NORM, &[PER_LAYER])?;+ let bulk = CombineBulk {+ key,+ proj: std::sync::Arc::new(proj),+ gamma: std::sync::Arc::new(gamma),+ };+ let out = (std::sync::Arc::clone(&bulk.proj), std::sync::Arc::clone(&bulk.gamma));+ *guard = Some(bulk);+ Ok(out)+}++/// The per-token half of the combine over an already-held projection.+fn apply_combine(+ proj: &[f32],+ gamma: &[f32],+ hidden: &[f32],+ embedded: &[f32],+) -> Vec<f32> { let rows = LAYERS; let wide = PER_LAYER as usize; // S10 t307: the gather side carries x16 (a real term, not a neutral@@ -188,5 +339,64 @@ fn combine( } out.extend_from_slice(&group); }- Ok(out)+ out+}++#[cfg(test)]+mod combine_cache_tests {+ use super::*;++ /// Cached vs re-read combine is bit-identical (Phase 3a′ step 2 gate).+ ///+ /// The gate the plan requires before the cache lands: the bytes are+ /// identical by construction (same file, same decode, once not per step),+ /// and this pins it on synthetic rows. Forced through `combine_timed`+ /// directly rather than the flag so no environment is touched — the flag's+ /// `OnceLock` is process-global and other tests share the process.+ #[test]+ fn cached_combine_is_bit_identical_to_reread() {+ // The fixture carries only what the combine reads: dummies at 0-2,+ // the int8 projection triple at 3-5, the gamma at 6. The row tables+ // the gather reads are irrelevant — this tests the combine, not the rows.+ const PROJ: usize = LAYERS * PER_LAYER as usize * D_MODEL as usize;+ let blob = crate::weights::write_mixed(+ crate::weights::graph::GEMMA4_EMBED,+ &[+ crate::weights::Fixture::F16(vec![1], vec![0.0]),+ crate::weights::Fixture::F16(vec![1], vec![0.0]),+ crate::weights::Fixture::F16(vec![1], vec![0.0]),+ crate::weights::Fixture::I8(+ vec![LAYERS as u32 * PER_LAYER, D_MODEL, 1, 1],+ (0..PROJ).map(|i| (i % 15) as i8 - 7).collect(),+ ),+ crate::weights::Fixture::F16(+ vec![LAYERS as u32 * PER_LAYER],+ vec![1.0; LAYERS * PER_LAYER as usize],+ ),+ crate::weights::Fixture::F16(vec![1], vec![0.0]),+ crate::weights::Fixture::F16(vec![PER_LAYER], vec![1.0; PER_LAYER as usize]),+ ],+ );+ let weights = crate::weights::Weights::parse(&blob, crate::weights::graph::GEMMA4_EMBED)+ .expect("the combine fixture parses");+ let reader = weights.reader();+ let hidden: Vec<f32> =+ (0..D_MODEL as usize).map(|i| (i % 7) as f32 * 0.125).collect();+ let embedded: Vec<f32> =+ (0..LAYERS * PER_LAYER as usize).map(|i| (i % 11) as f32 * 0.0625).collect();+ // Re-read first (today's path, no cache interaction), then cached twice:+ // the second cached call is the hit the gate cares about.+ let reread = combine_timed(&reader, &hidden, &embedded, false)+ .expect("the uncached combine runs")+ .0;+ let miss = combine_timed(&reader, &hidden, &embedded, true)+ .expect("the cache fill runs")+ .0;+ let hit = combine_timed(&reader, &hidden, &embedded, true)+ .expect("the cache hit runs")+ .0;+ assert_eq!(reread.len(), LAYERS * PER_LAYER as usize);+ assert_eq!(miss, reread);+ assert_eq!(hit, reread);+ } }
library/ml/src/main/rust/src/weights_part2.rs
diff --git a/library/ml/src/main/rust/src/weights_part2.rs b/library/ml/src/main/rust/src/weights_part2.rsindex 3fe80a5455..b1cc374e32 100644--- a/library/ml/src/main/rust/src/weights_part2.rs+++ b/library/ml/src/main/rust/src/weights_part2.rs@@ -4,6 +4,26 @@ impl<'a> Reader<'a> { Reader { table, data } } + /// File identity for host-side process-constant caches.+ ///+ /// The table's address plus the data section's length: every flow that+ /// gathers opens its EMBED file once and holds it for the process, so a+ /// cache keyed on this serves the same file's bytes every step. The+ /// combine cache pairs it with the tensors' descriptors (see+ /// [`Reader::describe`]), so a second file at a reused address with a+ /// different layout still misses.+ pub fn file_id(&self) -> (usize, u64) {+ (self.table as *const _ as usize, self.data.data_len())+ }++ /// Tensor `index`'s descriptor, checked against `dims`, without reading bytes.+ ///+ /// The table is in memory, so this is a lookup, not I/O: cache keys are+ /// built from it on every step while the bulk bytes are read only on a miss.+ pub fn describe(&self, index: usize, dims: &[u32]) -> Result<Tensor, String> {+ self.table.shaped(index, dims)+ }+ /// Tensor `index` as `f32`, in the file's order, checked against `dims`. /// /// fp16 only: every tensor the host reads is fp16, and an int8 one would need its companion
library/src/main/java/com/vayunmathur/library/util/Navigation.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/Navigation.kt b/library/src/main/java/com/vayunmathur/library/util/Navigation.ktindex 1152474717..30cff0edd0 100644--- a/library/src/main/java/com/vayunmathur/library/util/Navigation.kt+++ b/library/src/main/java/com/vayunmathur/library/util/Navigation.kt@@ -24,17 +24,17 @@ import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally import androidx.compose.animation.slideOutVertically import androidx.compose.animation.togetherWith+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.captionBar import androidx.compose.foundation.layout.captionBarPadding import androidx.compose.foundation.layout.consumeWindowInsets-import androidx.compose.foundation.layout.imePadding-import androidx.compose.foundation.layout.navigationBarsPadding-import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.contentColorFor-import androidx.compose.material3.Scaffold-import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarResult import androidx.compose.material3.adaptive.ExperimentalMaterial3AdaptiveApi@@ -110,6 +110,18 @@ class NavBackStack<T: NavKey>(initial: Array<out T>) { val LocalSnackbarHostState = compositionLocalOf<SnackbarHostState?> { null } +/**+ * Whether the screen is hosted inside [MainNavigation], so inner scaffolds apply+ * window insets exactly once.+ *+ * False (the default) means the screen is NOT hosted: previews, screenshot tests,+ * and pages hosted directly by an Activity. Those keep current M3 behavior.+ * True means hosted: the host owns the outer chrome, and the shared `Scaffold`+ * wrapper in `:library:ui` unions IME into the insets M3 itself consumes — never+ * padding outside a Scaffold.+ */+val LocalHostScaffoldInfo = staticCompositionLocalOf { false }+ class EntryProviderScope<T: NavKey>(val obj: T) { var result: NavEntry<T>? = null @@ -430,26 +442,29 @@ fun <T: NavKey> MainNavigation( } } - Scaffold(- contentWindowInsets = WindowInsets(),- containerColor = resolvedContainerColor,- contentColor = resolvedContentColor,- // The scaffold disables automatic insets (contentWindowInsets = WindowInsets()), so the- // snackbar host must apply its own navigation-bar and IME padding — otherwise messages- // render behind the system navigation bar and are hidden (issue #630).- snackbarHost = {- SnackbarHost(- snackbarHostState,- modifier = Modifier- .navigationBarsPadding()- .imePadding(),- )- },- bottomBar = bottomBar- ) { paddingValues ->+ // No outer Scaffold by design: it used to own the IME inset here while every+ // screen's inner Scaffold consumed insets again, double-lifting bottom bars by+ // a keyboard height (live probe: bottomBar laid out at H-2K). Instead the host+ // is a plain Box that marks screens hosted via LocalHostScaffoldInfo, and the+ // shared Scaffold wrapper in :library:ui unions IME into the insets M3 itself+ // consumes — exactly once, never padded outside a Scaffold.+ // The snackbar renderer lives there too (default host when the screen supplies+ // none); this function keeps only the producer (state + AppMessages drain).+ Box(+ Modifier+ .fillMaxSize()+ .background(resolvedContainerColor)+ // captionBarPadding: on desktop windowing (freeform, ChromeOS) the+ // system caption bar overlays the top of the window, and nothing else+ // in the inset chain accounts for it. Zero on phones.+ .captionBarPadding()+ .consumeWindowInsets(WindowInsets.captionBar),+ ) { CompositionLocalProvider( LocalNavResultRegistry provides resultRegistry,- LocalSnackbarHostState provides snackbarHostState+ LocalSnackbarHostState provides snackbarHostState,+ LocalHostScaffoldInfo provides true,+ LocalContentColor provides resolvedContentColor, ) { // Lets a component morph into its counterpart on the next screen instead of the two // screens merely swapping underneath it. See sharedContainer.@@ -459,37 +474,25 @@ fun <T: NavKey> MainNavigation( LocalNavMultiPane provides multiPane, LocalNavMotion provides topMotion, ) {- NavDisplay(- // consumeWindowInsets before imePadding: when a bottom bar is- // present it has already shifted itself up, and that shows up- // in paddingValues. Without consuming it the content would be- // pushed up by the keyboard twice.- //- // captionBarPadding first: on desktop windowing (freeform,- // ChromeOS) the system caption bar overlays the top of the- // window, and nothing else in the inset chain accounts for- // it — without this, top bars render underneath it. Zero on- // phones, so phone layout is unchanged.- modifier = Modifier- .captionBarPadding()- .padding(paddingValues)- .consumeWindowInsets(paddingValues)- .consumeWindowInsets(WindowInsets.captionBar)- .imePadding(),- sceneStrategies = listOf(DialogSceneStrategy(), sceneStrategy),- // The destination decides: the motion is read off the entry the user is- // arriving at when pushing, and off the one they are leaving when popping,- // so a route animates the same way in both directions.- transitionSpec = { transitions.push(targetState.navMotion()) },- popTransitionSpec = { transitions.pop(initialState.navMotion()) },- predictivePopTransitionSpec = { swipeEdge ->- transitions.predictivePop(initialState.navMotion(), swipeEdge)- },- backStack = backStack.backStack, entryProvider = {- EntryProviderScope(it).apply {- entryProvider()- }.result!!- })+ Column(Modifier.fillMaxSize()) {+ NavDisplay(+ modifier = Modifier.weight(1f),+ sceneStrategies = listOf(DialogSceneStrategy(), sceneStrategy),+ // The destination decides: the motion is read off the entry the user is+ // arriving at when pushing, and off the one they are leaving when popping,+ // so a route animates the same way in both directions.+ transitionSpec = { transitions.push(targetState.navMotion()) },+ popTransitionSpec = { transitions.pop(initialState.navMotion()) },+ predictivePopTransitionSpec = { swipeEdge ->+ transitions.predictivePop(initialState.navMotion(), swipeEdge)+ },+ backStack = backStack.backStack, entryProvider = {+ EntryProviderScope(it).apply {+ entryProvider()+ }.result!!+ })+ bottomBar()+ } } } }
library/ui/src/main/java/com/vayunmathur/library/ui/AppScaffold.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/AppScaffold.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/AppScaffold.ktindex b22ba61767..05b11d6550 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/AppScaffold.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/AppScaffold.kt@@ -65,7 +65,7 @@ fun AppScaffold( scrollBehavior: TopAppBarScrollBehavior, floatingActionButton: @Composable () -> Unit = {}, bottomBar: @Composable () -> Unit = {},- snackbarHost: @Composable () -> Unit = {},+ snackbarHost: (@Composable () -> Unit)? = null, content: @Composable (PaddingValues) -> Unit, ) = AppScaffold( title = { Text(title) },@@ -104,7 +104,7 @@ fun AppScaffold( scrollBehavior: TopAppBarScrollBehavior, floatingActionButton: @Composable () -> Unit = {}, bottomBar: @Composable () -> Unit = {},- snackbarHost: @Composable () -> Unit = {},+ snackbarHost: (@Composable () -> Unit)? = null, content: @Composable (PaddingValues) -> Unit, ) { val resolvedNavigationIcon = resolveNavigationIcon(navigationIcon, onClose, onNavigateBack)@@ -143,7 +143,7 @@ fun <T : NavKey> AppScaffold( scrollBehavior: TopAppBarScrollBehavior, floatingActionButton: @Composable () -> Unit = {}, bottomBar: @Composable () -> Unit = {},- snackbarHost: @Composable () -> Unit = {},+ snackbarHost: (@Composable () -> Unit)? = null, content: @Composable (PaddingValues) -> Unit, ) = AppScaffold( title = title,
library/ui/src/main/java/com/vayunmathur/library/ui/LazyListScaffold.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/LazyListScaffold.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/LazyListScaffold.ktindex 6daa989c40..adfa8bb4b3 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/LazyListScaffold.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/LazyListScaffold.kt@@ -55,7 +55,7 @@ fun LazyListScaffold( actions: (@Composable RowScope.() -> Unit)? = null, scrollBehavior: TopAppBarScrollBehavior, bottomBar: @Composable () -> Unit = {},- snackbarHost: @Composable () -> Unit = {},+ snackbarHost: (@Composable () -> Unit)? = null, floatingActionButton: @Composable () -> Unit = {}, floatingActionButtonPosition: FabPosition = FabPosition.End, state: LazyListState = rememberLazyListState(),
library/ui/src/main/java/com/vayunmathur/library/ui/ListPage.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/ListPage.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/ListPage.ktindex 82bcb88180..e445645ed8 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/ListPage.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/ListPage.kt@@ -15,7 +15,6 @@ import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem import androidx.compose.material3.ListItemColors import androidx.compose.material3.ListItemDefaults-import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable
library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.ktindex 0f3e4a3a07..7e2d0b1f3f 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.kt@@ -7,10 +7,17 @@ package com.vayunmathur.library.ui import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.RowScope+import androidx.compose.foundation.layout.WindowInsets+import androidx.compose.foundation.layout.asPaddingValues+import androidx.compose.foundation.layout.ime+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.union import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.AssistChipDefaults@@ -29,7 +36,10 @@ import androidx.compose.material3.NavigationBarItem as Material3NavigationBarIte import androidx.compose.material3.ProgressIndicatorDefaults import androidx.compose.material3.SegmentedButton as Material3SegmentedButton import androidx.compose.material3.SegmentedButtonDefaults+import androidx.compose.material3.ScaffoldDefaults import androidx.compose.material3.SliderDefaults+import androidx.compose.material3.SnackbarHost+import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.TextFieldDefaults import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.contentColorFor@@ -58,6 +68,8 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp+import com.vayunmathur.library.util.LocalHostScaffoldInfo+import com.vayunmathur.library.util.LocalSnackbarHostState /** * Thin same-named `@Composable` wrappers around Material 3 components.@@ -272,22 +284,61 @@ fun Surface( ) // --- Scaffold ---+//+// Hosted-mode IME ownership: screens under MainNavigation must apply the keyboard+// inset exactly once. MainNavigation no longer lifts content itself; instead it+// publishes LocalHostScaffoldInfo, and this funnel — the single path every+// AppScaffold screen goes through — unions IME into the insets M3 itself consumes,+// so bars, FAB, snackbar and content padding are all positioned consistently by+// M3, exactly once. Nothing is ever padded outside a Scaffold. When the local is+// absent (previews, screenshot tests, directly-hosted pages) behavior is+// byte-identical to before. @Composable fun Scaffold( modifier: Modifier = Modifier, topBar: @Composable () -> Unit = {}, bottomBar: @Composable () -> Unit = {},- snackbarHost: @Composable () -> Unit = {},+ snackbarHost: (@Composable () -> Unit)? = null, floatingActionButton: @Composable () -> Unit = {}, floatingActionButtonPosition: FabPosition = FabPosition.End, containerColor: Color = MaterialTheme.colorScheme.background, contentColor: Color = contentColorFor(containerColor),+ contentWindowInsets: WindowInsets = ScaffoldDefaults.contentWindowInsets, content: @Composable (PaddingValues) -> Unit,-) = androidx.compose.material3.Scaffold(- modifier = modifier, topBar = topBar, bottomBar = bottomBar, snackbarHost = snackbarHost,- floatingActionButton = floatingActionButton, floatingActionButtonPosition = floatingActionButtonPosition,- containerColor = containerColor, contentColor = contentColor, content = content,-)+) {+ val hosted = LocalHostScaffoldInfo.current+ if (!hosted) {+ androidx.compose.material3.Scaffold(+ modifier = modifier, topBar = topBar, bottomBar = bottomBar,+ snackbarHost = snackbarHost ?: {},+ floatingActionButton = floatingActionButton, floatingActionButtonPosition = floatingActionButtonPosition,+ containerColor = containerColor, contentColor = contentColor, contentWindowInsets = contentWindowInsets,+ content = content,+ )+ return+ }+ // Hosted: render the global snackbar when the screen supplied no explicit host.+ val globalSnackbarState: SnackbarHostState? = LocalSnackbarHostState.current+ val resolvedSnackbarHost: @Composable () -> Unit = snackbarHost+ ?: globalSnackbarState?.let { state ->+ {+ SnackbarHost(+ state,+ modifier = Modifier+ .navigationBarsPadding()+ .padding(WindowInsets.ime.asPaddingValues()),+ )+ }+ } ?: {}+ androidx.compose.material3.Scaffold(+ modifier = modifier, topBar = topBar, bottomBar = bottomBar,+ snackbarHost = resolvedSnackbarHost,+ floatingActionButton = floatingActionButton, floatingActionButtonPosition = floatingActionButtonPosition,+ containerColor = containerColor, contentColor = contentColor,+ contentWindowInsets = contentWindowInsets.union(WindowInsets.ime),+ content = content,+ )+} // --- Top app bars --- @Composable
metadata_data/photos/web/4.png
diff --git a/metadata_data/photos/web/4.png b/metadata_data/photos/web/4.pngnew file mode 100644index 0000000000..f0feadca1fBinary files /dev/null and b/metadata_data/photos/web/4.png differ
rules/device-runs.md
diff --git a/rules/device-runs.md b/rules/device-runs.mdnew file mode 100644index 0000000000..6340f59a9b--- /dev/null+++ b/rules/device-runs.md@@ -0,0 +1,19 @@+# Device runs (Pixel 8) — OOM avoidance++The Pixel 8 OOM-reboots when memory is overcommitted, and a reboot wipes the+measurement session. The only rule is: never overcommit. Everything below+serves that.++- Memory gate before every heavy run: `adb shell "uptime; free -m"`. No heavy+ run under ~2 GB free. After any reboot (uptime reset): stop, report, do not+ retry blindly.+- Known costs: TEXT upload ~1.1 GB, whole-EMBED ~3.6 GB, standalone head file+ ~402 MB. The crash-safe flow is `check_gemma4_parity --time N` (no logits, no+ head upload, ~1.5 GB peak with the head file).+- The known-killer shape is whole-EMBED upload + logits/head in one process+ (~4.7 GB peak vs ~2.4 GB free). It has rebooted the device three times. Only+ with explicit user approval AND a fresh memory gate.+- One heavy run at a time across all agents — concurrent runs stack toward the+ same OOM.+- Pushes/downloads over 100 MB need approval: multi-GB transfers churn the page+ cache and spike pressure toward the same cliff.
scripts/maps/tile_build/src/bin/mamaps_probe.rs
diff --git a/scripts/maps/tile_build/src/bin/mamaps_probe.rs b/scripts/maps/tile_build/src/bin/mamaps_probe.rsnew file mode 100644index 0000000000..cf9d2485cd--- /dev/null+++ b/scripts/maps/tile_build/src/bin/mamaps_probe.rs@@ -0,0 +1,708 @@+//! `mamaps_probe` — read a handful of tiles out of a `.mamaps` archive by range.+//!+//! `mamaps_dump` reads the whole file into RAM, which dies on a 60 GB archive.+//! This opens the archive over a file-backed [`RangeReader`] and prints one line+//! per requested tile: which `landtype` kinds it carries and how much ground+//! each covers. Built for the Santa Cruz water/land question — the ocean below+//! Santa Cruz rendered as land past ~z7 with only rivers showing as water.+//!+//! Usage:+//! mamaps_probe IN.mamaps Z/X/Y [Z/X/Y ...]+//! mamaps_probe IN.mamaps --breakdown [SAMPLES_PER_ZOOM]+//!+//! `--breakdown` walks the whole leaf index (cheap: index only, no bodies) and+//! prints per-zoom: addressed tiles, stored bodies, stored (DEFLATE) bytes, plus+//! — from up to SAMPLES_PER_ZOOM sampled bodies per zoom (default 200) — the+//! share of bodies carrying a heightmap, the mean raw body size, and the mean+//! raw heightmap section size. That answers "how much space does height take".++use std::fs::File;+use std::io::{Read, Seek, SeekFrom};+use std::process::ExitCode;++use tile_build::mamaps::body::{Body, GEOM_POLYGON};+use tile_build::mamaps::dict::Dictionary;+use tile_build::mamaps::read::MamapsArchive;+use tile_build::proto::{err, Result};+use tilecodec::stream::RangeReader;++struct FileRanges {+ file: std::sync::Mutex<File>,+}++impl RangeReader for FileRanges {+ fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {+ let mut file = self.file.lock().map_err(|_| tile_build::proto::Error("lock".into()))?;+ file.seek(SeekFrom::Start(offset))+ .map_err(|e| tile_build::proto::Error(format!("seek {offset}: {e}")))?;+ let mut buf = vec![0u8; length as usize];+ let mut got = 0usize;+ while got < buf.len() {+ match file.read(&mut buf[got..]) {+ Ok(0) => break,+ Ok(n) => got += n,+ Err(e) => return err(format!("read at {offset}: {e}")),+ }+ }+ buf.truncate(got);+ Ok(buf)+ }+}++fn kind_name(dict: &Dictionary, kind: u16) -> &str {+ if kind == 0 {+ return "(land-base)";+ }+ dict.kind_name(kind).unwrap_or("?")+}++fn main() -> ExitCode {+ let args: Vec<String> = std::env::args().collect();+ if args.len() < 3 {+ eprintln!("usage: mamaps_probe IN.mamaps Z/X/Y [Z/X/Y ...]");+ eprintln!(" or: mamaps_probe IN.mamaps --breakdown [SAMPLES_PER_ZOOM]");+ return ExitCode::from(2);+ }+ let file = match File::open(&args[1]) {+ Ok(f) => f,+ Err(e) => {+ eprintln!("mamaps_probe: cannot open {}: {e}", args[1]);+ return ExitCode::from(1);+ }+ };+ if args[2] == "--breakdown" {+ let samples: usize = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(200);+ return breakdown(&args[1], samples);+ }+ if args[2] == "--layers" {+ let samples: usize = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(200);+ return layer_breakdown(&args[1], samples);+ }+ if args[2] == "--sidecars" {+ return sidecars(&args[1]);+ }+ let mut archive = match MamapsArchive::open(FileRanges { file: std::sync::Mutex::new(file) }) {+ Ok(a) => a,+ Err(e) => {+ eprintln!("mamaps_probe: open: {e}");+ return ExitCode::from(1);+ }+ };+ println!(+ "archive z{}-{} build_id {:#018x} validated={}",+ archive.header.min_zoom,+ archive.header.max_zoom,+ archive.header.build_id,+ archive.header.rings_validated(),+ );+ let mut code = ExitCode::SUCCESS;+ for spec in &args[2..] {+ let mut parts = spec.split('/');+ let tile = match (parts.next(), parts.next(), parts.next(), parts.next()) {+ (Some(z), Some(x), Some(y), None) => {+ match (z.parse::<u8>(), x.parse::<u32>(), y.parse::<u32>()) {+ (Ok(z), Ok(x), Ok(y)) => (z, x, y),+ _ => {+ eprintln!("mamaps_probe: bad tile '{spec}', want Z/X/Y");+ code = ExitCode::from(2);+ continue;+ }+ }+ }+ _ => {+ eprintln!("mamaps_probe: bad tile '{spec}', want Z/X/Y");+ code = ExitCode::from(2);+ continue;+ }+ };+ let (z, x, y) = tile;+ match archive.tile(z, x, y) {+ Err(e) => {+ println!("{z}/{x}/{y}\tERROR {e}");+ code = ExitCode::from(1);+ }+ Ok(None) => println!("{z}/{x}/{y}\tABSENT"),+ Ok(Some(body)) => print_tile(&archive.dictionary, z, x, y, &body),+ }+ }+ code+}++fn print_tile(dict: &Dictionary, z: u8, x: u32, y: u32, body: &Body) {+ let extent = body.extent.max(1) as f64;+ let full = extent * extent;+ let Some(layer) = body.layer(tile_build::mamaps::dict::LAYER_LANDTYPE) else {+ println!("{z}/{x}/{y}\tno landtype layer");+ return;+ };+ // Per-kind ground: sum of absolute ring areas, so holes add rather than cancel.+ let mut kinds: std::collections::BTreeMap<u16, (usize, f64)> =+ std::collections::BTreeMap::new();+ let mut feats = 0usize;+ for feature in &layer.features {+ if feature.geom_type != GEOM_POLYGON {+ continue;+ }+ feats += 1;+ let mut area = 0.0f64;+ for part in layer.parts_of(feature) {+ area += ring_area(layer.points(part)).abs();+ }+ let e = kinds.entry(feature.kind).or_insert((0, 0.0));+ e.0 += 1;+ e.1 += area;+ }+ if kinds.is_empty() {+ println!("{z}/{x}/{y}\tlandtype: no polygons ({feats} polygon features)");+ return;+ }+ let mut bits: Vec<String> = Vec::new();+ for (kind, (count, area)) in &kinds {+ bits.push(format!(+ "{}x{}={:.1}%",+ kind_name(dict, *kind),+ count,+ 100.0 * area / full+ ));+ }+ let dem = if body.heightmap.is_some() { " dem" } else { "" };+ println!("{z}/{x}/{y}\tlandtype: {}{}", bits.join(" "), dem);+}++fn ring_area(pts: &[(i16, i16)]) -> f64 {+ let n = pts.len();+ if n < 3 {+ return 0.0;+ }+ let mut twice: i64 = 0;+ for i in 0..n {+ let (x1, y1) = pts[i];+ let (x2, y2) = pts[(i + 1) % n];+ twice += x1 as i64 * y2 as i64 - x2 as i64 * y1 as i64;+ }+ twice as f64 / 2.0+}++/// Walk the whole archive and report per-zoom storage: addressed tiles (with+/// run-length expansion), stored bodies, stored (DEFLATE) bytes, plus sampled+/// body stats — the heightmap share and the raw (pre-DEFLATE) body/heightmap+/// sizes that say how much of each zoom is elevation.+///+/// The index walk reads only the root (already in the open prefix) plus one+/// read per leaf — kilobytes against a 60 GB file. Bodies are fetched only for+/// the sample: evenly spaced entries per zoom, so one sample per ~N bodies,+/// each a single range read plus inflate.+fn breakdown(path: &str, samples_per_zoom: usize) -> ExitCode {+ use tile_build::mamaps::{header, index};+ use tilecodec::pmtiles::tile_zxy;++ let file = match File::open(path) {+ Ok(f) => f,+ Err(e) => {+ eprintln!("mamaps_probe: cannot open {path}: {e}");+ return ExitCode::from(1);+ }+ };+ let ranges = FileRanges { file: std::sync::Mutex::new(file) };+ // Header + dictionary + root straight out of the open prefix.+ let prefix = match ranges.read(0, tilecodec::stream::OPEN_PREFIX_BYTES) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("mamaps_probe: open: {e}");+ return ExitCode::from(1);+ }+ };+ let hdr = match header::Header::parse(&prefix) {+ Ok(h) => h,+ Err(e) => {+ eprintln!("mamaps_probe: header: {e}");+ return ExitCode::from(1);+ }+ };+ let root = match index::parse_root(+ &prefix[hdr.root_offset as usize..(hdr.root_offset + hdr.root_len as u64) as usize],+ ) {+ Ok(r) => r,+ Err(e) => {+ eprintln!("mamaps_probe: root: {e}");+ return ExitCode::from(1);+ }+ };+ let file_len = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);+ println!(+ "archive z{}-{} build_id {:#018x} validated={} compression={} file={:.2}GB data={:.2}GB bodies_written={} tiles_addressed={}",+ hdr.min_zoom,+ hdr.max_zoom,+ hdr.build_id,+ hdr.rings_validated(),+ hdr.compression,+ file_len as f64 / 1e9,+ hdr.data_len as f64 / 1e9,+ hdr.bodies_written,+ hdr.tiles_addressed,+ );+ // Per-zoom aggregates from the index alone.+ struct Zoom {+ addressed: u64,+ bodies: u64,+ stored: u64,+ entries: Vec<(u64, u32)>,+ }+ let mut zooms: std::collections::BTreeMap<u8, Zoom> = std::collections::BTreeMap::new();+ for root_entry in &root {+ let len = root_entry.leaf_entry_count as u64 * index::LEAF_ENTRY_LEN as u64;+ let raw = match ranges.read(+ (hdr.leaf_offset + root_entry.leaf_offset) as u64,+ len as u32,+ ) {+ Ok(r) => r,+ Err(e) => {+ eprintln!("mamaps_probe: leaf: {e}");+ return ExitCode::from(1);+ }+ };+ let leaf = match index::parse_leaf(&raw) {+ Ok(l) => l,+ Err(e) => {+ eprintln!("mamaps_probe: leaf parse: {e}");+ return ExitCode::from(1);+ }+ };+ for e in &leaf {+ let (z, _, _) = tile_zxy(root_entry.base_tile_id + e.tile_id_lo as u64);+ let at = hdr.data_offset + root_entry.base_data_offset + e.offset_delta as u64;+ let zoom = zooms.entry(z).or_insert(Zoom {+ addressed: 0,+ bodies: 0,+ stored: 0,+ entries: Vec::new(),+ });+ zoom.addressed += e.run_length as u64;+ zoom.bodies += 1;+ zoom.stored += e.length as u64;+ zoom.entries.push((at, e.length));+ }+ }+ println!("zoom addressed bodies stored_GB avg_stored");+ let mut total_stored = 0u64;+ for (z, zoom) in &zooms {+ total_stored += zoom.stored;+ println!(+ "z{z:<3} {:>9} {:>8} {:>10.3} {:>8}",+ zoom.addressed,+ zoom.bodies,+ zoom.stored as f64 / 1e9,+ fmt_bytes(zoom.stored / zoom.bodies.max(1)),+ );+ }+ println!("total stored bodies: {:.3} GB", total_stored as f64 / 1e9);+ // Sampled bodies per zoom: heightmap share + raw sizes.+ let mut archive = match MamapsArchive::open(FileRanges {+ file: std::sync::Mutex::new(File::open(path).expect("open")),+ }) {+ Ok(a) => a,+ Err(e) => {+ eprintln!("mamaps_probe: reopen: {e}");+ return ExitCode::from(1);+ }+ };+ println!("zoom sampled with_dem dem_share avg_raw_body avg_raw_dem dem_of_raw stored_dem dem_of_stored");+ for (z, zoom) in &zooms {+ if zoom.entries.is_empty() {+ continue;+ }+ let step = (zoom.entries.len() / samples_per_zoom.max(1)).max(1);+ let mut sampled = 0u64;+ let mut with_dem = 0u64;+ let mut raw_body = 0u64;+ let mut raw_dem = 0u64;+ let mut stored_dem = 0u64;+ let mut stored_nodem = 0u64;+ let mut idx = 0usize;+ while idx < zoom.entries.len() {+ let (at, len) = zoom.entries[idx];+ let stored = match archive.reader().read(at, len) {+ Ok(s) => s,+ Err(_) => {+ idx += step;+ continue;+ }+ };+ let raw = match tile_build::mamaps::read::decompress(hdr.compression, &stored) {+ Ok(r) => r,+ Err(_) => {+ idx += step;+ continue;+ }+ };+ let body = match Body::parse(&raw) {+ Ok(b) => b,+ Err(_) => {+ idx += step;+ continue;+ }+ };+ sampled += 1;+ raw_body += raw.len() as u64;+ if let Some(hm) = &body.heightmap {+ with_dem += 1;+ raw_dem += (2 + hm.samples.len() * 2) as u64;+ stored_dem += len as u64;+ } else {+ stored_nodem += len as u64;+ }+ idx += step;+ }+ if sampled == 0 {+ continue;+ }+ // Stored-bytes split: mean stored size of dem vs no-dem bodies, scaled to+ // the zoom's body count. DEFLATE-compressibility differs between the two+ // populations, so this is measured, not modelled.+ let dem_bodies = zoom.bodies as f64 * with_dem as f64 / sampled as f64;+ let nodem_bodies = zoom.bodies as f64 - dem_bodies;+ let avg_stored_dem = if with_dem > 0 { stored_dem / with_dem } else { 0 };+ let avg_stored_nodem =+ if sampled > with_dem { stored_nodem / (sampled - with_dem) } else { 0 };+ let stored_dem_total = dem_bodies * avg_stored_dem as f64;+ println!(+ "z{z:<3} {:>7} {:>8} {:>8.1}% {:>11} {:>10} {:>8.1}% {:>10} {:>6.1}%",+ sampled,+ with_dem,+ 100.0 * with_dem as f64 / sampled as f64,+ fmt_bytes(raw_body / sampled),+ if with_dem > 0 {+ fmt_bytes(raw_dem / with_dem).to_string()+ } else {+ "-".to_string()+ },+ 100.0 * raw_dem as f64 / raw_body.max(1) as f64,+ fmt_bytes(stored_dem_total as u64),+ 100.0 * stored_dem_total / zoom.stored.max(1) as f64,+ );+ }+ ExitCode::SUCCESS+}++fn fmt_bytes(n: u64) -> String {+ if n >= 1_000_000 {+ format!("{:.1}M", n as f64 / 1e6)+ } else if n >= 1_000 {+ format!("{:.1}K", n as f64 / 1e3)+ } else {+ format!("{n}B")+ }+}++/// List the packed sidecar sections: kind, byte offset, length. Reads only the+/// 32-byte `MAMA8` footer off the file's tail plus the section directory it+/// points at — kilobytes against a 60 GB file.+///+/// Sidecars are appended **uncompressed** after the tile data (see+/// `mamaps_pack`), so these lengths are the bytes on disk, not estimates.+fn sidecars(path: &str) -> ExitCode {+ use tile_build::mamaps::archive::{ARCHIVE_DIR_HEADER_LEN, ARCHIVE_ENTRY_LEN, ARCHIVE_FOOTER_LEN};++ fn kind_name(kind: u8) -> &'static str {+ match kind {+ 1 => "graph_meta (metadata.bin: MARG header, node/edge/escape/name counts)",+ 2 => "graph_nodes (nodes.bin: per-node records + sentinel)",+ 3 => "graph_edges (edges.bin: edge records + escape index/rows + name bitmap/offs)",+ 4 => "graph_intermediate (intermediate.bin: geometry blob + trailer)",+ 5 => "graph_names (road_names.bin: NUL-terminated string pool)",+ 6 => "graph_lanes (lanes.bin: sparse lane index + blob)",+ 7 => "graph_elevation (elevation.bin: per-node i16 elevations)",+ 8 => "poi_index (poi_index.bin: 14 B records, one per POI)",+ 9 => "poi_names (poi_names.bin: NUL-terminated name pool)",+ 10 => "poi_attrs (poi_attrs.bin: MAPA attribute sidecar)",+ 11 => "poi_spatial (poi_spatial.bin: PSP1 spatial grid)",+ 12 => "poi_words (poi_name_index.bin: PNI1 full-text word index)",+ 13 => "transit (world.transit: TRIX pack of routes/shapes)",+ _ => "unknown",+ }+ }++ let file = match File::open(path) {+ Ok(f) => f,+ Err(e) => {+ eprintln!("mamaps_probe: cannot open {path}: {e}");+ return ExitCode::from(1);+ }+ };+ let ranges = FileRanges { file: std::sync::Mutex::new(file) };+ let file_len = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);+ if file_len < ARCHIVE_FOOTER_LEN as u64 {+ eprintln!("mamaps_probe: file shorter than a footer");+ return ExitCode::from(1);+ }+ let foot = match ranges.read(file_len - ARCHIVE_FOOTER_LEN as u64, ARCHIVE_FOOTER_LEN as u32)+ {+ Ok(f) => f,+ Err(e) => {+ eprintln!("mamaps_probe: footer read: {e}");+ return ExitCode::from(1);+ }+ };+ if &foot[0..8] != b"MAMA8\0\0\0" {+ println!("no MAMA8 footer: tiles-only archive, no sidecars packed");+ return ExitCode::SUCCESS;+ }+ let u64_at = |o: usize| {+ u64::from_le_bytes([+ foot[o], foot[o + 1], foot[o + 2], foot[o + 3], foot[o + 4], foot[o + 5], foot[o + 6],+ foot[o + 7],+ ])+ };+ let (dir_offset, dir_len, build_id) = (u64_at(8), u64_at(16), u64_at(24));+ let dir = match ranges.read(dir_offset, dir_len as u32) {+ Ok(d) => d,+ Err(e) => {+ eprintln!("mamaps_probe: directory read: {e}");+ return ExitCode::from(1);+ }+ };+ let count = u32::from_le_bytes([dir[0], dir[1], dir[2], dir[3]]) as usize;+ println!("MAMA8 footer: build_id {build_id:#018x} dir at {dir_offset} ({dir_len} B) file {file_len} B");+ println!("kind section (+ what the payload holds)");+ println!(" offset length");+ let mut total = 0u64;+ for i in 0..count {+ let at = ARCHIVE_DIR_HEADER_LEN + i * ARCHIVE_ENTRY_LEN;+ let e = &dir[at..at + ARCHIVE_ENTRY_LEN];+ let u32_at = |o: usize| u32::from_le_bytes([e[o], e[o + 1], e[o + 2], e[o + 3]]);+ let u64_at = |o: usize| {+ u64::from_le_bytes([+ e[o], e[o + 1], e[o + 2], e[o + 3], e[o + 4], e[o + 5], e[o + 6], e[o + 7],+ ])+ };+ // Entry layout: kind u8 @0, flags u32 @4, offset u64 @8, len u64 @16, extra u64 @24.+ let (kind, offset, len) = (e[0], u64_at(8), u64_at(16));+ let _ = u32_at(0);+ total += len;+ println!("{kind:<5} {}", kind_name(kind));+ println!(" {offset:<17} {}", fmt_bytes(len));+ }+ println!("sidecar total: {} ({:.1}% of file)", fmt_bytes(total), 100.0 * total as f64 / file_len as f64);+ ExitCode::SUCCESS+}++/// Per-layer, per-zoom raw payload sizes from sampled bodies: for each zoom,+/// the mean raw (pre-DEFLATE) bytes each layer's features+parts+coords occupy,+/// scaled to the zoom's body count. Plus the side tables (names, ids, lanes,+/// buildings, heightmap, carriageways, region links) the same way.+///+/// Raw, not stored: the body DEFLATEs as one blob, so per-section stored bytes+/// are unmeasurable — but raw sizes are exact per body, and the ratio between+/// sections is what says where the bytes go. The heightmap column is the DEM+/// answer: `2 + dim*dim*2` bytes wherever the section is present.+fn layer_breakdown(path: &str, samples_per_zoom: usize) -> ExitCode {+ use tile_build::mamaps::{header, index};+ use tilecodec::pmtiles::tile_zxy;++ let file = match File::open(path) {+ Ok(f) => f,+ Err(e) => {+ eprintln!("mamaps_probe: cannot open {path}: {e}");+ return ExitCode::from(1);+ }+ };+ let ranges = FileRanges { file: std::sync::Mutex::new(file) };+ let prefix = match ranges.read(0, tilecodec::stream::OPEN_PREFIX_BYTES) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("mamaps_probe: open: {e}");+ return ExitCode::from(1);+ }+ };+ let hdr = match header::Header::parse(&prefix) {+ Ok(h) => h,+ Err(e) => {+ eprintln!("mamaps_probe: header: {e}");+ return ExitCode::from(1);+ }+ };+ let dictionary = match tile_build::mamaps::dict::Dictionary::parse(+ &prefix[hdr.dict_offset as usize..(hdr.dict_offset + hdr.dict_len as u64) as usize],+ ) {+ Ok(d) => d,+ Err(e) => {+ eprintln!("mamaps_probe: dict: {e}");+ return ExitCode::from(1);+ }+ };+ let root = match index::parse_root(+ &prefix[hdr.root_offset as usize..(hdr.root_offset + hdr.root_len as u64) as usize],+ ) {+ Ok(r) => r,+ Err(e) => {+ eprintln!("mamaps_probe: root: {e}");+ return ExitCode::from(1);+ }+ };+ // Leaf entries per zoom (positions only — bodies fetched in the sample pass).+ let mut zoom_entries: std::collections::BTreeMap<u8, Vec<(u64, u32)>> =+ std::collections::BTreeMap::new();+ let mut zoom_bodies: std::collections::BTreeMap<u8, u64> =+ std::collections::BTreeMap::new();+ for root_entry in &root {+ let len = root_entry.leaf_entry_count as u64 * index::LEAF_ENTRY_LEN as u64;+ let raw = match ranges.read((hdr.leaf_offset + root_entry.leaf_offset) as u64, len as u32)+ {+ Ok(r) => r,+ Err(e) => {+ eprintln!("mamaps_probe: leaf: {e}");+ return ExitCode::from(1);+ }+ };+ let leaf = match index::parse_leaf(&raw) {+ Ok(l) => l,+ Err(e) => {+ eprintln!("mamaps_probe: leaf parse: {e}");+ return ExitCode::from(1);+ }+ };+ for e in &leaf {+ let (z, _, _) = tile_zxy(root_entry.base_tile_id + e.tile_id_lo as u64);+ let at = hdr.data_offset + root_entry.base_data_offset + e.offset_delta as u64;+ zoom_entries.entry(z).or_default().push((at, e.length));+ *zoom_bodies.entry(z).or_default() += 1;+ }+ }+ let layer_name = |id: u8| -> String {+ dictionary.layer_name(id).unwrap_or("?").to_string()+ };+ let mut archive = match MamapsArchive::open(FileRanges {+ file: std::sync::Mutex::new(File::open(path).expect("open")),+ }) {+ Ok(a) => a,+ Err(e) => {+ eprintln!("mamaps_probe: reopen: {e}");+ return ExitCode::from(1);+ }+ };+ // Fixed layer order for the table: the schema's own layer list, then the+ // side tables in wire order.+ let mut layer_order: Vec<u8> = (0..dictionary.layers.len() as u8).collect();+ layer_order.sort_by_key(|id| layer_name(*id));+ println!("per-zoom mean RAW body bytes by section (sampled bodies, scaled to zoom body count):");+ for (z, entries) in &zoom_entries {+ let bodies = zoom_bodies[z] as f64;+ let step = (entries.len() / samples_per_zoom.max(1)).max(1);+ let mut sampled = 0u64;+ let mut layer_raw: std::collections::BTreeMap<u8, u64> =+ std::collections::BTreeMap::new();+ let mut names = 0u64;+ let mut ids = 0u64;+ let mut lanes = 0u64;+ let mut buildings = 0u64;+ let mut dem = 0u64;+ let mut dem_tiles = 0u64;+ let mut carriage = 0u64;+ let mut regions = 0u64;+ let mut idx = 0usize;+ while idx < entries.len() {+ let (at, len) = entries[idx];+ let stored = match archive.reader().read(at, len) {+ Ok(s) => s,+ Err(_) => {+ idx += step;+ continue;+ }+ };+ let raw = match tile_build::mamaps::read::decompress(hdr.compression, &stored) {+ Ok(r) => r,+ Err(_) => {+ idx += step;+ continue;+ }+ };+ let body = match Body::parse(&raw) {+ Ok(b) => b,+ Err(_) => {+ idx += step;+ continue;+ }+ };+ sampled += 1;+ for layer in &body.layers {+ // Raw payload: 24 B per feature record, 12 B per part entry+ // (10 + align4), ~2-3 B per coordinate (zigzag varint mean).+ let payload = layer.features.len() as u64 * 24+ + layer.parts.len() as u64 * 12+ + layer.coords.len() as u64 * 3;+ *layer_raw.entry(layer.layer_id).or_default() += payload;+ }+ for s in &body.names {+ names += s.len() as u64 + 1;+ }+ for (_, v) in &body.ids {+ ids += v.len() as u64 * 8;+ }+ for (_, v) in &body.turn_lanes {+ for t in v {+ lanes += 2 + t.forward.len() as u64 * 2 + t.backward.len() as u64 * 2;+ }+ }+ for (_, v) in &body.buildings {+ buildings += v.len() as u64 * 20;+ }+ if let Some(hm) = &body.heightmap {+ dem_tiles += 1;+ dem += (2 + hm.samples.len() * 2) as u64;+ }+ for (_, v) in &body.carriageways {+ carriage += v.len() as u64 * 6;+ }+ for (_, v) in &body.region_links {+ regions += v.len() as u64 * 8;+ }+ idx += step;+ }+ if sampled == 0 {+ continue;+ }+ // Scale the per-body mean to the zoom's full body count. (An earlier+ // version multiplied by bodies/sampled — dividing by the sample twice+ // and understating every absolute ~400x. Ratios were unaffected.)+ let scale = bodies;+ let mut cells: Vec<String> = Vec::new();+ let mut total = 0u64;+ for id in &layer_order {+ let mean = layer_raw.get(id).copied().unwrap_or(0) as f64 / sampled as f64;+ let zoom_total = (mean * scale) as u64;+ total += zoom_total;+ if zoom_total > 0 {+ cells.push(format!("{}={}", layer_name(*id), fmt_bytes(zoom_total)));+ }+ }+ let mut side = |n: u64, label: &str| -> Option<String> {+ let t = (n as f64 / sampled as f64 * scale) as u64;+ total += t;+ (t > 0).then(|| format!("{label}={}", fmt_bytes(t)))+ };+ for s in [+ side(names, "names"),+ side(ids, "ids"),+ side(lanes, "lanes"),+ side(buildings, "bldg"),+ side(dem, "DEM"),+ side(carriage, "carr"),+ side(regions, "rgn"),+ ]+ .into_iter()+ .flatten()+ {+ cells.push(s);+ }+ let dem_share = dem as f64 / sampled as f64 * scale / total.max(1) as f64 * 100.0;+ println!(+ "z{z:<3} bodies={:<9} raw_total={:<8} dem_tiles={:.0}% dem_share={:.0}% {}",+ zoom_bodies[z],+ fmt_bytes(total),+ 100.0 * dem_tiles as f64 / sampled as f64,+ dem_share,+ cells.join(" "),+ );+ }+ ExitCode::SUCCESS+}
stamps_run1.txt
diff --git a/stamps_run1.txt b/stamps_run1.txtnew file mode 100644index 0000000000..450b1c1dc2--- /dev/null+++ b/stamps_run1.txt@@ -0,0 +1,877 @@+tokens [2, 818, 5279, 529, 7001, 563]+pass 0: 6 steps, mean 559.6 ms/step+ step 0: 453.7 ms+ step 1: 595.7 ms+ step 2: 579.3 ms+ step 3: 576.7 ms+ step 4: 574.0 ms+ step 5: 578.3 ms+pass 1: 6 steps, mean 554.9 ms/step+ step 0: 530.5 ms+ step 1: 571.3 ms+ step 2: 565.9 ms+ step 3: 523.4 ms+ step 4: 573.1 ms+ step 5: 565.2 ms+steady-state: 554.9 ms/token = 1.80 tok/s+host split per step: gather+rotary 240.6 ms, infer 312.9 ms (6 steps)++ step us gap-us kind+0: RmsNorm 1124.9 1.0+1: ConvVecInt4 208.3 0.9+2: RmsNorm 179.5 0.9+3: Rotary 17.4 0.9+4: ConvVecInt4 46.5 0.9+5: RmsNorm 176.1 0.9+6: Rotary 12.9 0.9+7: ConvVecInt4 47.0 0.9+8: RmsNorm 175.9 10.3+11: CacheWrite 13.1 0.9+12: CacheWrite 7.9 0.9+13: AttnScoresCached 46.7 0.9+14: SoftmaxPrefix 16.2 0.9+15: AttnApplyCached 23.9 0.9+16: ConvVecInt4 185.1 0.9+17: RmsNorm 1340.9 0.9+18: RmsNorm 1023.9 0.9+19: ConvVecInt4 549.4 0.9+20: ConvVecInt4 544.6 0.9+21: Mul 13.8 0.9+22: ConvVecInt4 507.4 0.9+23: RmsNorm 1006.6 0.9+24: Add 9.8 3.5+26: ConvVecInt8 44.8 0.9+27: Mul 7.8 0.9+28: ConvVecInt8 49.9 0.9+29: RmsNorm 1318.1 0.9+30: MulScalar 14.2 0.9+31: RmsNorm 1126.6 0.9+32: ConvVecInt4 214.5 0.9+33: RmsNorm 181.8 0.9+34: Rotary 18.0 0.9+35: ConvVecInt4 47.9 0.9+36: RmsNorm 174.3 0.9+37: Rotary 11.4 0.9+38: ConvVecInt4 44.9 0.9+39: RmsNorm 179.9 10.9+42: CacheWrite 14.8 0.9+43: CacheWrite 8.2 0.9+44: AttnScoresCached 44.5 0.9+45: SoftmaxPrefix 15.7 0.9+46: AttnApplyCached 20.2 1.0+47: ConvVecInt4 187.6 0.9+48: RmsNorm 1365.8 0.9+49: RmsNorm 1021.9 0.9+50: ConvVecInt4 563.2 0.9+51: ConvVecInt4 560.5 0.9+52: Mul 14.2 0.9+53: ConvVecInt4 520.8 0.9+54: RmsNorm 1024.9 0.9+55: Add 8.6 4.0+57: ConvVecInt8 41.3 0.9+58: Mul 9.5 0.9+59: ConvVecInt8 47.6 0.9+60: RmsNorm 1304.5 0.9+61: MulScalar 8.6 0.9+62: RmsNorm 1069.9 0.9+63: ConvVecInt4 241.1 0.9+64: RmsNorm 194.0 0.9+65: Rotary 13.0 0.9+66: ConvVecInt4 49.5 0.9+67: RmsNorm 185.1 0.8+68: Rotary 10.2 0.9+69: ConvVecInt4 51.4 0.9+70: RmsNorm 191.0 9.7+73: CacheWrite 12.2 0.9+74: CacheWrite 9.2 0.9+75: AttnScoresCached 47.5 0.9+76: SoftmaxPrefix 17.7 0.9+77: AttnApplyCached 19.4 0.9+78: ConvVecInt4 209.5 0.9+79: RmsNorm 1444.3 0.9+80: RmsNorm 1128.3 0.9+81: ConvVecInt4 620.5 0.9+82: ConvVecInt4 624.5 0.9+83: Mul 10.2 0.9+84: ConvVecInt4 576.6 0.9+85: RmsNorm 1115.1 0.9+86: Add 9.8 5.3+88: ConvVecInt8 45.4 0.9+89: Mul 7.5 0.9+90: ConvVecInt8 51.1 0.9+91: RmsNorm 1471.3 0.9+92: MulScalar 11.6 0.9+93: RmsNorm 1310.6 0.9+94: ConvVecInt4 242.2 0.9+95: RmsNorm 193.0 0.9+96: Rotary 17.6 0.9+97: ConvVecInt4 48.3 0.9+98: RmsNorm 192.6 0.9+99: Rotary 14.6 0.9+100: ConvVecInt4 50.2 0.9+101: RmsNorm 198.8 12.7+104: CacheWrite 13.1 0.9+105: CacheWrite 8.1 0.9+106: AttnScoresCached 47.4 0.9+107: SoftmaxPrefix 17.0 0.9+108: AttnApplyCached 22.7 0.9+109: ConvVecInt4 208.6 0.9+110: RmsNorm 1481.6 0.9+111: RmsNorm 1136.9 0.9+112: ConvVecInt4 622.6 0.9+113: ConvVecInt4 623.4 0.9+114: Mul 9.1 0.9+115: ConvVecInt4 578.6 0.9+116: RmsNorm 1141.4 0.8+117: Add 11.8 5.0+119: ConvVecInt8 44.8 0.9+120: Mul 10.3 0.9+121: ConvVecInt8 50.6 0.9+122: RmsNorm 1453.4 0.9+123: MulScalar 10.4 0.9+124: RmsNorm 1254.0 0.9+125: ConvVecInt4 415.4 0.9+126: RmsNorm 394.3 0.9+127: Rotary 12.6 0.9+128: ConvVecInt4 64.7 0.9+129: RmsNorm 301.4 0.9+130: Rotary 9.4 0.9+131: ConvVecInt4 59.3 0.9+132: RmsNorm 304.8 8.2+135: CacheWrite 10.9 0.9+136: CacheWrite 9.6 0.9+137: AttnScoresCached 54.4 0.9+138: SoftmaxPrefix 14.4 0.9+139: AttnApplyCached 21.1 0.9+140: ConvVecInt4 314.0 0.9+141: RmsNorm 1182.7 0.9+142: RmsNorm 882.0 0.9+143: ConvVecInt4 490.6 0.9+144: ConvVecInt4 488.4 0.9+145: Mul 9.4 0.9+146: ConvVecInt4 454.3 0.9+147: RmsNorm 937.1 0.9+148: Add 10.3 2.7+150: ConvVecInt8 37.9 0.9+151: Mul 7.5 0.9+152: ConvVecInt8 43.5 0.9+153: RmsNorm 1190.6 0.9+154: MulScalar 9.6 0.9+155: RmsNorm 1019.9 0.9+156: ConvVecInt4 192.9 0.9+157: RmsNorm 163.3 0.9+158: Rotary 9.9 0.9+159: ConvVecInt4 39.6 0.9+160: RmsNorm 156.3 0.9+161: Rotary 9.2 0.9+162: ConvVecInt4 41.6 0.9+163: RmsNorm 160.4 8.1+166: CacheWrite 9.2 0.9+167: CacheWrite 9.4 0.9+168: AttnScoresCached 39.4 0.9+169: SoftmaxPrefix 13.3 0.9+170: AttnApplyCached 15.4 0.9+171: ConvVecInt4 167.6 0.9+172: RmsNorm 1178.5 0.9+173: RmsNorm 883.7 0.9+174: ConvVecInt4 505.2 0.9+175: ConvVecInt4 508.2 0.9+176: Mul 9.9 0.9+177: ConvVecInt4 466.6 0.9+178: RmsNorm 909.2 0.9+179: Add 8.9 2.8+181: ConvVecInt8 36.6 0.9+182: Mul 6.3 0.9+183: ConvVecInt8 45.4 0.9+184: RmsNorm 1193.8 0.9+185: MulScalar 7.3 0.8+186: RmsNorm 1017.3 0.9+187: ConvVecInt4 192.5 0.9+188: RmsNorm 168.1 0.9+189: Rotary 11.6 0.8+190: ConvVecInt4 39.7 0.8+191: RmsNorm 156.3 0.9+192: Rotary 11.0 0.9+193: ConvVecInt4 41.9 0.9+194: RmsNorm 159.4 6.4+197: CacheWrite 12.1 0.9+198: CacheWrite 7.1 0.9+199: AttnScoresCached 37.6 0.9+200: SoftmaxPrefix 13.2 0.9+201: AttnApplyCached 16.3 0.9+202: ConvVecInt4 169.3 0.9+203: RmsNorm 1162.0 0.9+204: RmsNorm 908.6 0.9+205: ConvVecInt4 506.1 0.9+206: ConvVecInt4 507.5 0.9+207: Mul 7.6 0.9+208: ConvVecInt4 466.7 0.9+209: RmsNorm 924.0 0.9+210: Add 8.9 2.8+212: ConvVecInt8 36.9 0.9+213: Mul 7.1 0.9+214: ConvVecInt8 45.2 0.9+215: RmsNorm 1192.8 0.9+216: MulScalar 6.8 0.9+217: RmsNorm 1014.7 0.9+218: ConvVecInt4 191.0 0.9+219: RmsNorm 169.2 0.9+220: Rotary 11.2 0.9+221: ConvVecInt4 41.6 0.9+222: RmsNorm 156.3 0.9+223: Rotary 12.9 0.9+224: ConvVecInt4 41.5 0.9+225: RmsNorm 157.8 9.5+228: CacheWrite 9.8 0.8+229: CacheWrite 8.7 0.9+230: AttnScoresCached 36.6 0.9+231: SoftmaxPrefix 14.2 0.9+232: AttnApplyCached 19.2 0.9+233: ConvVecInt4 169.1 0.9+234: RmsNorm 1189.2 0.9+235: RmsNorm 912.2 2.2+236: ConvVecInt4 504.4 0.9+237: ConvVecInt4 506.2 0.9+238: Mul 9.6 0.9+239: ConvVecInt4 469.6 0.9+240: RmsNorm 928.0 0.9+241: Add 7.1 2.7+243: ConvVecInt8 37.4 0.9+244: Mul 8.7 0.9+245: ConvVecInt8 45.9 0.9+246: RmsNorm 1188.6 0.9+247: MulScalar 9.0 0.9+248: RmsNorm 1010.9 0.9+249: ConvVecInt4 185.7 0.9+250: RmsNorm 159.5 0.9+251: Rotary 8.5 0.9+252: ConvVecInt4 40.2 0.9+253: RmsNorm 154.9 0.9+254: Rotary 8.1 0.9+255: ConvVecInt4 39.6 0.9+256: RmsNorm 155.6 7.2+259: CacheWrite 9.4 0.9+260: CacheWrite 7.8 0.9+261: AttnScoresCached 37.6 0.9+262: SoftmaxPrefix 12.9 0.9+263: AttnApplyCached 19.2 0.9+264: ConvVecInt4 164.7 0.9+265: RmsNorm 1185.1 0.9+266: RmsNorm 887.2 0.9+267: ConvVecInt4 493.3 0.9+268: ConvVecInt4 491.6 0.9+269: Mul 6.8 0.9+270: ConvVecInt4 454.4 0.9+271: RmsNorm 900.7 0.9+272: Add 6.6 4.0+274: ConvVecInt8 35.6 0.9+275: Mul 9.0 0.9+276: ConvVecInt8 40.7 0.9+277: RmsNorm 1173.9 0.9+278: MulScalar 10.5 0.9+279: RmsNorm 997.3 0.9+280: ConvVecInt4 348.5 0.9+281: RmsNorm 321.0 0.9+282: Rotary 10.9 0.9+283: ConvVecInt4 59.1 0.9+284: RmsNorm 304.5 0.9+285: Rotary 8.3 0.9+286: ConvVecInt4 58.2 0.9+287: RmsNorm 306.2 7.2+290: CacheWrite 11.6 0.9+291: CacheWrite 8.4 0.9+292: AttnScoresCached 51.4 0.9+293: SoftmaxPrefix 12.6 0.9+294: AttnApplyCached 16.4 0.9+295: ConvVecInt4 320.4 0.9+296: RmsNorm 1192.8 0.9+297: RmsNorm 915.4 0.9+298: ConvVecInt4 507.4 0.9+299: ConvVecInt4 506.7 0.9+300: Mul 8.3 0.9+301: ConvVecInt4 468.7 0.9+302: RmsNorm 905.4 0.9+303: Add 6.9 4.1+305: ConvVecInt8 38.0 0.9+306: Mul 7.0 0.9+307: ConvVecInt8 42.3 0.9+308: RmsNorm 1180.6 0.9+309: MulScalar 8.5 0.9+310: RmsNorm 1015.1 0.9+311: ConvVecInt4 193.0 0.9+312: RmsNorm 164.8 0.9+313: Rotary 13.0 0.9+314: ConvVecInt4 43.1 0.9+315: RmsNorm 158.6 0.9+316: Rotary 11.1 0.9+317: ConvVecInt4 42.8 0.9+318: RmsNorm 159.4 7.9+321: CacheWrite 10.8 0.9+322: CacheWrite 8.2 0.9+323: AttnScoresCached 36.4 0.9+324: SoftmaxPrefix 14.4 0.9+325: AttnApplyCached 19.8 0.9+326: ConvVecInt4 167.6 0.9+327: RmsNorm 1162.7 0.9+328: RmsNorm 907.8 0.9+329: ConvVecInt4 506.5 0.9+330: ConvVecInt4 506.0 0.9+331: Mul 7.7 0.9+332: ConvVecInt4 466.4 0.9+333: RmsNorm 896.9 0.9+334: Add 9.1 3.3+336: ConvVecInt8 38.2 0.9+337: Mul 7.1 0.9+338: ConvVecInt8 42.0 0.9+339: RmsNorm 1194.3 0.9+340: MulScalar 8.3 0.9+341: RmsNorm 1012.0 0.9+342: ConvVecInt4 193.7 0.9+343: RmsNorm 162.7 0.9+344: Rotary 13.8 0.9+345: ConvVecInt4 41.5 0.9+346: RmsNorm 155.3 0.9+347: Rotary 10.6 0.9+348: ConvVecInt4 42.1 0.9+349: RmsNorm 161.1 8.6+352: CacheWrite 9.1 0.9+353: CacheWrite 9.0 0.9+354: AttnScoresCached 39.1 0.9+355: SoftmaxPrefix 11.3 0.9+356: AttnApplyCached 17.4 0.9+357: ConvVecInt4 169.0 0.9+358: RmsNorm 1156.6 0.9+359: RmsNorm 909.1 0.9+360: ConvVecInt4 504.2 0.9+361: ConvVecInt4 507.0 0.9+362: Mul 10.4 0.9+363: ConvVecInt4 469.4 0.9+364: RmsNorm 924.4 0.9+365: Add 8.2 3.2+367: ConvVecInt8 35.5 0.9+368: Mul 5.9 0.9+369: ConvVecInt8 42.5 0.9+370: RmsNorm 1182.0 3.1+371: MulScalar 8.6 0.9+372: RmsNorm 999.6 0.9+373: ConvVecInt4 184.1 0.9+374: RmsNorm 160.1 0.9+375: Rotary 9.7 0.9+376: ConvVecInt4 39.6 0.9+377: RmsNorm 152.8 0.9+378: Rotary 7.7 0.9+379: ConvVecInt4 40.4 0.9+380: RmsNorm 155.3 7.1+383: CacheWrite 8.5 0.9+384: CacheWrite 7.4 0.9+385: AttnScoresCached 39.2 0.9+386: SoftmaxPrefix 14.5 0.9+387: AttnApplyCached 14.9 0.9+388: ConvVecInt4 164.4 0.9+389: RmsNorm 1145.7 0.9+390: RmsNorm 888.4 0.9+391: ConvVecInt4 490.8 0.9+392: ConvVecInt4 490.6 0.9+393: Mul 8.5 0.9+394: ConvVecInt4 454.6 0.9+395: RmsNorm 894.9 0.9+396: Add 9.3 2.7+398: ConvVecInt8 35.3 0.9+399: Mul 7.0 0.9+400: ConvVecInt8 42.0 0.9+401: RmsNorm 1193.2 0.9+402: MulScalar 9.6 0.9+403: RmsNorm 1014.9 0.9+404: ConvVecInt4 194.3 0.9+405: RmsNorm 167.4 0.9+406: Rotary 13.1 0.9+407: ConvVecInt4 41.2 0.9+408: RmsNorm 155.9 0.9+409: Rotary 11.3 0.9+410: ConvVecInt4 42.4 0.9+411: RmsNorm 158.8 8.0+414: CacheWrite 9.3 0.9+415: CacheWrite 6.8 0.9+416: AttnScoresCached 39.5 0.9+417: SoftmaxPrefix 17.5 0.9+418: AttnApplyCached 17.5 0.9+419: ConvVecInt4 170.9 0.9+420: RmsNorm 1174.5 0.9+421: RmsNorm 915.3 0.9+422: ConvVecInt4 507.2 0.9+423: ConvVecInt4 505.2 0.9+424: Mul 7.6 0.9+425: ConvVecInt4 471.4 0.9+426: RmsNorm 924.5 0.9+427: Add 6.6 3.0+429: ConvVecInt8 36.7 0.9+430: Mul 8.0 0.9+431: ConvVecInt8 42.5 0.9+432: RmsNorm 1191.7 0.9+433: MulScalar 7.1 0.9+434: RmsNorm 995.7 0.9+435: ConvVecInt4 347.8 0.9+436: RmsNorm 317.9 0.9+437: Rotary 11.8 0.9+438: ConvVecInt4 58.7 0.9+439: RmsNorm 303.4 0.9+440: Rotary 9.5 0.9+441: ConvVecInt4 57.4 0.9+442: RmsNorm 305.3 7.1+445: CacheWrite 11.1 0.9+446: CacheWrite 8.3 0.9+447: AttnScoresCached 52.9 0.9+448: SoftmaxPrefix 12.6 0.9+449: AttnApplyCached 16.2 0.9+450: ConvVecInt4 319.5 0.9+451: RmsNorm 1182.2 0.9+452: RmsNorm 910.5 0.9+453: ConvVecInt4 504.3 0.9+454: ConvVecInt4 503.9 0.9+455: Mul 8.3 0.9+456: ConvVecInt4 468.6 0.9+457: RmsNorm 899.7 0.9+458: Add 9.0 3.3+460: ConvVecInt8 35.8 0.9+461: Mul 6.2 0.9+462: ConvVecInt8 44.4 0.9+463: RmsNorm 1192.3 0.9+464: MulScalar 10.4 0.9+465: RmsNorm 1011.4 0.9+466: ConvVecInt4 197.2 0.9+467: RmsNorm 159.1 0.9+468: Rotary 12.3 0.9+469: AttnScoresCached 38.9 0.9+470: SoftmaxPrefix 15.4 0.9+471: AttnApplyCached 17.9 0.9+472: ConvVecInt4 171.1 0.9+473: RmsNorm 1181.6 0.9+474: RmsNorm 909.3 0.9+475: ConvVecInt4 976.8 0.9+476: ConvVecInt4 977.9 0.9+477: Mul 9.7 0.9+478: ConvVecInt4 920.7 0.9+479: RmsNorm 925.7 0.9+480: Add 7.0 3.8+482: ConvVecInt8 35.6 0.9+483: Mul 7.8 0.9+484: ConvVecInt8 41.3 0.9+485: RmsNorm 1193.7 0.8+486: MulScalar 10.8 0.9+487: RmsNorm 1014.9 0.9+488: ConvVecInt4 190.2 0.9+489: RmsNorm 166.5 0.9+490: Rotary 9.5 0.9+491: AttnScoresCached 38.9 0.9+492: SoftmaxPrefix 12.5 0.9+493: AttnApplyCached 20.1 0.9+494: ConvVecInt4 164.6 0.9+495: RmsNorm 1215.3 0.9+496: RmsNorm 894.0 0.9+497: ConvVecInt4 950.0 0.9+498: ConvVecInt4 961.7 0.9+499: Mul 10.7 0.9+500: ConvVecInt4 891.7 0.9+501: RmsNorm 932.3 0.9+502: Add 7.4 4.4+504: ConvVecInt8 36.4 0.9+505: Mul 7.1 0.9+506: ConvVecInt8 40.2 0.9+507: RmsNorm 1188.6 0.9+508: MulScalar 9.0 0.9+509: RmsNorm 1014.2 0.9+510: ConvVecInt4 191.9 0.9+511: RmsNorm 164.0 0.9+512: Rotary 13.5 0.9+513: AttnScoresCached 36.8 0.9+514: SoftmaxPrefix 13.6 0.9+515: AttnApplyCached 17.9 0.9+516: ConvVecInt4 171.0 0.9+517: RmsNorm 1183.7 0.9+518: RmsNorm 912.0 0.9+519: ConvVecInt4 990.0 0.9+520: ConvVecInt4 978.7 0.9+521: Mul 8.5 0.9+522: ConvVecInt4 919.4 0.9+523: RmsNorm 937.2 0.9+524: Add 9.0 4.4+526: ConvVecInt8 35.5 0.9+527: Mul 6.8 0.9+528: ConvVecInt8 41.6 0.9+529: RmsNorm 1200.5 0.9+530: MulScalar 12.3 0.9+531: RmsNorm 1014.6 0.9+532: ConvVecInt4 192.2 0.9+533: RmsNorm 162.0 0.9+534: Rotary 13.0 0.9+535: AttnScoresCached 38.3 0.9+536: SoftmaxPrefix 13.0 0.9+537: AttnApplyCached 19.2 0.9+538: ConvVecInt4 169.8 0.9+539: RmsNorm 1173.6 0.9+540: RmsNorm 910.6 0.9+541: ConvVecInt4 977.5 0.9+542: ConvVecInt4 978.2 0.9+543: Mul 8.5 0.9+544: ConvVecInt4 918.0 0.9+545: RmsNorm 940.9 0.9+546: Add 6.9 2.9+548: ConvVecInt8 37.0 0.9+549: Mul 6.5 0.9+550: ConvVecInt8 41.3 0.9+551: RmsNorm 1194.9 0.9+552: MulScalar 7.4 0.9+553: RmsNorm 1020.7 0.9+554: ConvVecInt4 349.7 0.9+555: RmsNorm 321.2 0.9+556: Rotary 9.8 0.9+557: AttnScoresCached 50.9 0.9+558: SoftmaxPrefix 15.2 0.9+559: AttnApplyCached 17.3 0.9+560: ConvVecInt4 319.9 0.9+561: RmsNorm 1196.1 0.9+562: RmsNorm 908.2 0.9+563: ConvVecInt4 980.3 0.8+564: ConvVecInt4 990.8 0.9+565: Mul 9.0 0.9+566: ConvVecInt4 918.2 0.9+567: RmsNorm 930.2 0.8+568: Add 8.1 3.1+570: ConvVecInt8 38.2 0.9+571: Mul 7.7 0.9+572: ConvVecInt8 43.4 0.9+573: RmsNorm 1188.8 0.9+574: MulScalar 10.4 0.9+575: RmsNorm 1012.7 0.9+576: ConvVecInt4 186.8 0.9+577: RmsNorm 168.5 0.9+578: Rotary 11.6 0.9+579: AttnScoresCached 40.6 0.9+580: SoftmaxPrefix 11.7 0.9+581: AttnApplyCached 16.8 0.9+582: ConvVecInt4 163.9 0.9+583: RmsNorm 1173.2 0.9+584: RmsNorm 914.3 0.9+585: ConvVecInt4 949.5 0.9+586: ConvVecInt4 950.2 0.9+587: Mul 10.2 0.9+588: ConvVecInt4 891.5 0.9+589: RmsNorm 936.6 0.9+590: Add 8.1 3.1+592: ConvVecInt8 36.7 0.9+593: Mul 6.8 0.9+594: ConvVecInt8 45.5 0.9+595: RmsNorm 1148.4 0.9+596: MulScalar 10.3 0.9+597: RmsNorm 1015.6 0.9+598: ConvVecInt4 194.1 0.9+599: RmsNorm 166.9 0.9+600: Rotary 10.9 0.9+601: AttnScoresCached 37.8 0.9+602: SoftmaxPrefix 13.9 0.9+603: AttnApplyCached 16.6 0.9+604: ConvVecInt4 168.9 2.0+605: RmsNorm 1176.0 0.9+606: RmsNorm 902.8 0.9+607: ConvVecInt4 978.6 0.9+608: ConvVecInt4 977.6 0.8+609: Mul 10.7 0.9+610: ConvVecInt4 920.2 0.9+611: RmsNorm 931.9 0.9+612: Add 7.9 3.1+614: ConvVecInt8 39.6 0.9+615: Mul 8.5 0.9+616: ConvVecInt8 43.6 0.9+617: RmsNorm 1193.4 0.9+618: MulScalar 8.7 0.9+619: RmsNorm 995.5 0.9+620: ConvVecInt4 190.0 0.9+621: RmsNorm 163.5 0.9+622: Rotary 10.5 0.9+623: AttnScoresCached 37.8 0.9+624: SoftmaxPrefix 13.6 0.9+625: AttnApplyCached 17.3 0.9+626: ConvVecInt4 169.6 0.9+627: RmsNorm 1168.6 0.9+628: RmsNorm 911.5 0.9+629: ConvVecInt4 977.6 0.9+630: ConvVecInt4 976.3 0.9+631: Mul 10.7 0.8+632: ConvVecInt4 916.9 0.9+633: RmsNorm 937.5 0.9+634: Add 8.1 3.2+636: ConvVecInt8 35.1 0.9+637: Mul 6.3 0.9+638: ConvVecInt8 40.4 0.9+639: RmsNorm 1187.5 0.9+640: MulScalar 10.5 0.9+641: RmsNorm 1009.9 0.9+642: ConvVecInt4 194.9 0.9+643: RmsNorm 159.4 0.9+644: Rotary 11.9 0.9+645: AttnScoresCached 40.6 0.9+646: SoftmaxPrefix 13.6 0.9+647: AttnApplyCached 18.2 0.9+648: ConvVecInt4 170.3 0.9+649: RmsNorm 1163.8 0.9+650: RmsNorm 909.0 0.9+651: ConvVecInt4 980.6 2.2+652: ConvVecInt4 981.4 0.9+653: Mul 7.4 0.9+654: ConvVecInt4 918.5 0.9+655: RmsNorm 938.0 0.9+656: Add 8.2 3.7+658: ConvVecInt8 35.4 0.9+659: Mul 8.5 0.9+660: ConvVecInt8 46.0 0.9+661: RmsNorm 1192.7 0.9+662: MulScalar 9.4 0.9+663: RmsNorm 1012.7 0.9+664: ConvVecInt4 338.7 0.9+665: RmsNorm 327.1 0.9+666: Rotary 9.8 0.9+667: AttnScoresCached 55.9 0.9+668: SoftmaxPrefix 13.6 0.9+669: AttnApplyCached 18.3 0.9+670: ConvVecInt4 307.8 0.9+671: RmsNorm 1178.2 0.9+672: RmsNorm 918.2 0.9+673: ConvVecInt4 951.6 0.9+674: ConvVecInt4 952.6 0.9+675: Mul 9.7 0.9+676: ConvVecInt4 893.4 0.9+677: RmsNorm 932.3 0.9+678: Add 7.3 3.9+680: ConvVecInt8 36.2 0.9+681: Mul 6.6 0.9+682: ConvVecInt8 41.6 0.9+683: RmsNorm 1194.4 0.9+684: MulScalar 10.7 0.9+685: RmsNorm 1009.0 0.9+686: ConvVecInt4 193.8 0.9+687: RmsNorm 163.1 0.9+688: Rotary 12.1 0.9+689: AttnScoresCached 37.9 0.9+690: SoftmaxPrefix 13.5 0.9+691: AttnApplyCached 17.5 0.9+692: ConvVecInt4 171.0 0.9+693: RmsNorm 1137.1 0.9+694: RmsNorm 883.3 0.9+695: ConvVecInt4 977.9 0.9+696: ConvVecInt4 978.2 0.9+697: Mul 10.4 0.9+698: ConvVecInt4 921.6 0.9+699: RmsNorm 938.2 0.9+700: Add 7.5 3.5+702: ConvVecInt8 35.8 0.9+703: Mul 6.6 0.9+704: ConvVecInt8 40.3 0.9+705: RmsNorm 1192.1 0.9+706: MulScalar 8.7 0.9+707: RmsNorm 1017.3 0.9+708: ConvVecInt4 191.9 0.9+709: RmsNorm 163.8 0.9+710: Rotary 10.2 0.9+711: AttnScoresCached 41.6 0.9+712: SoftmaxPrefix 10.9 0.9+713: AttnApplyCached 14.9 0.9+714: ConvVecInt4 169.2 0.9+715: RmsNorm 1155.4 0.9+716: RmsNorm 911.6 0.9+717: ConvVecInt4 977.6 0.9+718: ConvVecInt4 977.6 0.9+719: Mul 9.8 0.9+720: ConvVecInt4 918.0 0.8+721: RmsNorm 931.1 0.9+722: Add 8.9 3.2+724: ConvVecInt8 35.4 0.9+725: Mul 6.6 0.9+726: ConvVecInt8 42.9 0.9+727: RmsNorm 1182.0 0.9+728: MulScalar 6.6 0.9+729: RmsNorm 1016.3 0.9+730: ConvVecInt4 192.6 0.9+731: RmsNorm 162.9 0.9+732: Rotary 12.6 0.9+733: AttnScoresCached 40.5 0.9+734: SoftmaxPrefix 14.5 0.9+735: AttnApplyCached 17.6 0.9+736: ConvVecInt4 171.8 0.9+737: RmsNorm 1176.0 0.9+738: RmsNorm 909.8 0.9+739: ConvVecInt4 978.6 0.9+740: ConvVecInt4 977.3 0.9+741: Mul 9.9 0.9+742: ConvVecInt4 917.8 0.9+743: RmsNorm 949.6 0.9+744: Add 7.4 3.1+746: ConvVecInt8 35.7 0.9+747: Mul 7.7 0.9+748: ConvVecInt8 45.0 0.9+749: RmsNorm 1188.9 0.9+750: MulScalar 7.3 0.9+751: RmsNorm 1008.1 0.9+752: ConvVecInt4 184.2 0.9+753: RmsNorm 164.0 0.9+754: Rotary 11.8 0.9+755: AttnScoresCached 39.8 0.9+756: SoftmaxPrefix 13.5 0.9+757: AttnApplyCached 14.1 0.9+758: ConvVecInt4 164.9 0.9+759: RmsNorm 1187.8 0.9+760: RmsNorm 915.3 0.9+761: ConvVecInt4 962.8 0.9+762: ConvVecInt4 960.1 0.9+763: Mul 8.1 0.9+764: ConvVecInt4 890.6 0.9+765: RmsNorm 943.2 0.9+766: Add 9.4 3.3+768: ConvVecInt8 36.5 2.0+769: Mul 7.4 0.9+770: ConvVecInt8 42.4 0.9+771: RmsNorm 1196.4 0.9+772: MulScalar 10.5 0.9+773: RmsNorm 970.8 0.9+774: ConvVecInt4 347.1 0.9+775: RmsNorm 328.6 0.9+776: Rotary 10.5 0.9+777: AttnScoresCached 51.6 0.8+778: SoftmaxPrefix 12.8 0.9+779: AttnApplyCached 19.9 0.9+780: ConvVecInt4 319.9 0.9+781: RmsNorm 1195.1 0.9+782: RmsNorm 907.7 0.9+783: ConvVecInt4 977.5 2.0+784: ConvVecInt4 978.0 0.9+785: Mul 8.6 0.9+786: ConvVecInt4 920.4 0.9+787: RmsNorm 929.5 0.9+788: Add 8.0 3.1+790: ConvVecInt8 36.5 0.9+791: Mul 5.7 0.9+792: ConvVecInt8 40.2 0.9+793: RmsNorm 1154.8 0.9+794: MulScalar 8.1 0.9+795: RmsNorm 1014.4 0.9+796: ConvVecInt4 192.3 0.9+797: RmsNorm 161.2 0.9+798: Rotary 10.9 0.9+799: AttnScoresCached 40.1 0.9+800: SoftmaxPrefix 15.1 0.9+801: AttnApplyCached 13.5 0.9+802: ConvVecInt4 168.9 0.9+803: RmsNorm 1192.4 0.9+804: RmsNorm 912.1 0.9+805: ConvVecInt4 976.9 0.9+806: ConvVecInt4 976.7 0.9+807: Mul 10.8 0.9+808: ConvVecInt4 916.8 0.9+809: RmsNorm 942.3 0.9+810: Add 8.1 2.8+812: ConvVecInt8 35.2 0.9+813: Mul 7.3 0.9+814: ConvVecInt8 43.1 0.9+815: RmsNorm 1186.5 0.9+816: MulScalar 7.8 0.9+817: RmsNorm 1013.5 0.9+818: ConvVecInt4 191.7 0.9+819: RmsNorm 168.4 0.9+820: Rotary 10.7 0.9+821: AttnScoresCached 41.3 0.9+822: SoftmaxPrefix 12.0 0.9+823: AttnApplyCached 15.5 0.9+824: ConvVecInt4 170.1 0.9+825: RmsNorm 1176.7 0.9+826: RmsNorm 914.1 0.9+827: ConvVecInt4 974.1 0.9+828: ConvVecInt4 978.2 0.9+829: Mul 10.3 0.9+830: ConvVecInt4 916.1 0.9+831: RmsNorm 942.8 0.9+832: Add 8.0 2.9+834: ConvVecInt8 35.7 0.9+835: Mul 6.4 0.9+836: ConvVecInt8 42.2 0.9+837: RmsNorm 1192.4 0.9+838: MulScalar 8.1 0.9+839: RmsNorm 1001.3 0.9+840: ConvVecInt4 187.1 0.9+841: RmsNorm 161.6 0.9+842: Rotary 9.8 0.9+843: AttnScoresCached 38.6 0.9+844: SoftmaxPrefix 12.6 0.9+845: AttnApplyCached 17.8 0.9+846: ConvVecInt4 165.4 0.9+847: RmsNorm 1097.0 0.9+848: RmsNorm 914.9 0.9+849: ConvVecInt4 952.5 0.9+850: ConvVecInt4 948.2 0.9+851: Mul 8.9 0.9+852: ConvVecInt4 892.5 0.9+853: RmsNorm 930.6 0.9+854: Add 7.6 3.3+856: ConvVecInt8 36.1 0.9+857: Mul 7.3 0.9+858: ConvVecInt8 42.6 0.9+859: RmsNorm 1196.0 0.9+860: MulScalar 7.8 0.9+861: RmsNorm 1017.2 0.9+862: ConvVecInt4 193.0 0.9+863: RmsNorm 166.3 0.9+864: Rotary 11.0 0.9+865: AttnScoresCached 38.4 0.9+866: SoftmaxPrefix 15.7 0.9+867: AttnApplyCached 14.9 0.9+868: ConvVecInt4 171.4 0.9+869: RmsNorm 1172.0 0.9+870: RmsNorm 909.7 0.9+871: ConvVecInt4 977.5 0.9+872: ConvVecInt4 994.8 0.9+873: Mul 9.8 0.9+874: ConvVecInt4 918.0 0.9+875: RmsNorm 932.3 0.9+876: Add 7.6 3.9+878: ConvVecInt8 36.6 0.9+879: Mul 9.5 0.9+880: ConvVecInt8 42.3 0.9+881: RmsNorm 1161.7 0.9+882: MulScalar 7.6 0.9+883: RmsNorm 971.5 0.9+884: ConvVecInt4 350.9 0.9+885: RmsNorm 325.5 0.9+886: Rotary 9.8 0.9+887: AttnScoresCached 53.5 0.9+888: SoftmaxPrefix 15.3 0.9+889: AttnApplyCached 19.9 0.9+890: ConvVecInt4 319.5 0.9+891: RmsNorm 1179.9 0.9+892: RmsNorm 886.4 0.9+893: ConvVecInt4 976.8 0.9+894: ConvVecInt4 977.4 0.9+895: Mul 10.7 0.9+896: ConvVecInt4 918.1 0.9+897: RmsNorm 917.8 1.1+898: Add 6.9 3.3+900: ConvVecInt8 36.3 0.9+901: Mul 7.0 0.9+902: ConvVecInt8 41.3 0.9+903: RmsNorm 1191.7 0.9+904: MulScalar 8.4 0.9+905: RmsNorm 913.0 0.0++ count total-ms mean-us gap-ms kind+ 241 199.7 828.5 0.3 RmsNorm+ 205 96.7 471.5 0.2 ConvVecInt4+ 70 2.8 40.4 0.1 ConvVecInt8+ 35 1.5 42.6 0.0 AttnScoresCached+ 35 0.6 17.9 0.0 AttnApplyCached+ 70 0.6 8.5 0.1 Mul+ 50 0.6 11.5 0.0 Rotary+ 35 0.5 14.0 0.0 SoftmaxPrefix+ 35 0.3 9.2 0.0 MulScalar+ 30 0.3 9.6 0.0 CacheWrite+ 35 0.3 8.2 0.1 Add++timestamped device total: 303.8 ms against the step mean above+barrier/bind gaps total: 0.9 ms+(copies and host work are not timestamped)
web/src/main/java/com/vayunmathur/web/ui/BrowserChrome.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/BrowserChrome.kt b/web/src/main/java/com/vayunmathur/web/ui/BrowserChrome.ktindex fe16047e64..1c5a150fd4 100644--- a/web/src/main/java/com/vayunmathur/web/ui/BrowserChrome.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/BrowserChrome.kt@@ -5,7 +5,6 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues-import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.consumeWindowInsets@@ -13,28 +12,18 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable-import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.DropdownMenu-import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.IconArrowForward-import com.vayunmathur.library.ui.IconBack-import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.IconMoreVert-import com.vayunmathur.library.ui.IconSearch-import com.vayunmathur.library.ui.IconShield import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.LinearProgressIndicator-import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Scaffold@@ -44,36 +33,27 @@ import com.vayunmathur.library.ui.TopAppBar import com.vayunmathur.library.ui.TopAppBarDefaults import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.web.R-import androidx.compose.ui.text.style.TextOverflow-import com.vayunmathur.web.platform.BrowserUtils @OptIn(ExperimentalMaterial3Api::class) @Composable internal fun BrowserChrome( omniboxText: String, tabCount: Int,- canGoBack: Boolean = false,- canGoForward: Boolean = false, progress: Float = 0f, atBottom: Boolean = false,- onBack: () -> Unit = {},- onForward: () -> Unit = {}, onOmniboxClick: () -> Unit = {}, onTabSwitcherClick: () -> Unit = {},- shieldHost: String? = null,- blockedCount: Int = 0,- onShieldClick: () -> Unit = {}, onMenuClick: () -> Unit = {}, menu: @Composable () -> Unit = {}, content: @Composable (PaddingValues) -> Unit, ) { // RAW SCAFFOLD EXCEPTION: bespoke browser toolbar chrome. The bar is a- // Column of a custom TopAppBar (back/forward nav row, a tappable read-only- // address pill as the title, and shield + tab-count + overflow-menu actions- // on a surface-colored bar) with a page LinearProgressIndicator drawn- // alongside it, and it can sit in either the top or the bottom slot. That- // composite bar has no equivalent in the shared scaffolds, and the content- // is the full-bleed WebView.+ // Column of a custom TopAppBar (a tappable read-only address pill as the+ // title, with tab-count + overflow-menu actions on a surface-colored bar)+ // with a page LinearProgressIndicator drawn alongside it, and it can sit+ // in either the top or the bottom slot. That composite bar has no+ // equivalent in the shared scaffolds, and the content is the full-bleed+ // WebView. Back/forward/shields live in the overflow menu instead. val bar: @Composable () -> Unit = { // At the bottom, TopAppBar's hardcoded top inset would be a status bar's // height of dead space, and nothing else applies the navigation bar inset.@@ -95,12 +75,6 @@ internal fun BrowserChrome( // far side of the toolbar when the toolbar moves to the bottom. if (atBottom) PageProgress(progress) TopAppBar(- navigationIcon = {- Row(verticalAlignment = Alignment.CenterVertically) {- IconButton(onClick = onBack, enabled = canGoBack) { IconBack() }- IconButton(onClick = onForward, enabled = canGoForward) { IconArrowForward() }- }- }, title = { DisplayOnlyAddressPill( fullUrl = omniboxText,@@ -109,10 +83,6 @@ internal fun BrowserChrome( ) }, actions = {- if (shieldHost != null) {- ShieldChip(blockedCount = blockedCount, onClick = onShieldClick)- Spacer(Modifier.width(4.dp))- } Surface( shape = RoundedCornerShape(20.dp), color = MaterialTheme.colorScheme.secondaryContainer,@@ -150,37 +120,13 @@ private fun PageProgress(progress: Float) { } } -/**- * Toolbar shield. Shows the number of requests blocked on the current page, which is the- * only feedback the user gets that shields are doing anything.- */-@Composable-private fun ShieldChip(blockedCount: Int, onClick: () -> Unit) {- Surface(- shape = RoundedCornerShape(20.dp),- color = MaterialTheme.colorScheme.secondaryContainer,- modifier = Modifier.clip(RoundedCornerShape(20.dp)).clickable(onClick = onClick),- ) {- Row(- Modifier.padding(horizontal = 10.dp, vertical = 8.dp),- verticalAlignment = Alignment.CenterVertically,- ) {- IconShield(Modifier.size(18.dp))- if (blockedCount > 0) {- Spacer(Modifier.width(4.dp))- Text(blockedCount.toString(), style = MaterialTheme.typography.labelLarge)- }- }- }-}- @Composable private fun DisplayOnlyAddressPill( fullUrl: String, onClick: () -> Unit, modifier: Modifier = Modifier, ) {- // Now matches CommonSearchBar visually: OutlinedTextField 28dp rounded, search icon, same padding.+ // Now matches CommonSearchBar visually: OutlinedTextField 28dp rounded, same padding. // bodySmall keeps the bar slim so more of the URL fits horizontally. Box(modifier = modifier) { OutlinedTextField(@@ -189,7 +135,6 @@ private fun DisplayOnlyAddressPill( readOnly = true, textStyle = MaterialTheme.typography.bodySmall, placeholder = { Text(stringResource(R.string.search_or_enter_address), style = MaterialTheme.typography.bodySmall) },- leadingIcon = { IconSearch() }, singleLine = true, shape = RoundedCornerShape(28.dp), modifier = Modifier.fillMaxWidth()
web/src/main/java/com/vayunmathur/web/ui/BrowserMenu.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/BrowserMenu.kt b/web/src/main/java/com/vayunmathur/web/ui/BrowserMenu.ktindex f47b2a3636..5c4789b02b 100644--- a/web/src/main/java/com/vayunmathur/web/ui/BrowserMenu.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/BrowserMenu.kt@@ -20,6 +20,9 @@ import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.DropdownMenu import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.ExternalIntents+import com.vayunmathur.library.ui.IconArrowForward+import com.vayunmathur.library.ui.IconBack+import com.vayunmathur.library.ui.IconShield import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Surface@@ -35,8 +38,8 @@ import com.vayunmathur.web.platform.PwaInfo import com.vayunmathur.web.platform.WebViewModel /**- * Overflow menu for the browser chrome: reload, install/pin, bookmark, share,- * new tabs, and the library/settings destinations.+ * Overflow menu for the browser chrome: nav, shields, reload, install/pin,+ * bookmark, share, new tabs, and the library/settings destinations. */ @Composable internal fun BrowserMenu(@@ -46,6 +49,13 @@ internal fun BrowserMenu( backStack: NavBackStack<Route>, isNewTabActive: Boolean, isCurrentBookmarked: Boolean,+ canGoBack: Boolean,+ canGoForward: Boolean,+ onGoBack: () -> Unit,+ onGoForward: () -> Unit,+ shieldHost: String?,+ blockedCount: Int,+ onShieldClick: () -> Unit, onShowInstallDialog: () -> Unit, onReload: () -> Unit, ) {@@ -53,6 +63,37 @@ internal fun BrowserMenu( val bookmarks by viewModel.bookmarks.collectAsStateWithLifecycle() val activeTab = viewModel.activeTab DropdownMenu(expanded = expanded, onDismissRequest = onDismiss) {+ DropdownMenuItem(+ text = { Text(stringResource(R.string.go_back)) },+ leadingIcon = { IconBack() },+ onClick = {+ onDismiss()+ onGoBack()+ },+ enabled = canGoBack,+ )+ DropdownMenuItem(+ text = { Text(stringResource(R.string.go_forward)) },+ leadingIcon = { IconArrowForward() },+ onClick = {+ onDismiss()+ onGoForward()+ },+ enabled = canGoForward,+ )+ if (shieldHost != null) {+ DropdownMenuItem(+ text = { Text(stringResource(R.string.shields)) },+ leadingIcon = { IconShield() },+ trailingIcon = {+ if (blockedCount > 0) Text(blockedCount.toString())+ },+ onClick = {+ onDismiss()+ onShieldClick()+ },+ )+ } if (!isNewTabActive) { DropdownMenuItem( text = { Text(stringResource(R.string.reload)) },
web/src/main/java/com/vayunmathur/web/ui/BrowserOmniboxEditor.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/BrowserOmniboxEditor.kt b/web/src/main/java/com/vayunmathur/web/ui/BrowserOmniboxEditor.ktindex 9dcb1f974f..9059c38b34 100644--- a/web/src/main/java/com/vayunmathur/web/ui/BrowserOmniboxEditor.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/BrowserOmniboxEditor.kt@@ -2,6 +2,7 @@ package com.vayunmathur.web.ui import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBarsPadding@@ -19,6 +20,9 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.positionInWindow+import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.ImeAction@@ -27,7 +31,6 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.DesktopMaxWidthContainer import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.IconBack import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.IconSearch@@ -109,7 +112,7 @@ internal fun OmniboxEditor( ) } val dismissOmnibox: @Composable () -> Unit = {- IconButton(onClick = onDismiss) { IconBack() }+ IconButton(onClick = onDismiss) { IconClose() } } val suggestions: @Composable (androidx.compose.foundation.layout.PaddingValues) -> Unit = { paddingValues -> OmniboxSuggestions(@@ -133,7 +136,11 @@ internal fun OmniboxEditor( Row( modifier = Modifier .navigationBarsPadding()- .padding(start = 4.dp, end = 12.dp, top = 4.dp, bottom = 4.dp),+ .padding(start = 4.dp, end = 12.dp, top = 4.dp, bottom = 4.dp)+ .onGloballyPositioned { coords ->+ ImeDebugState.barBottomY =+ (coords.positionInWindow().y + coords.size.height).toInt()+ }, verticalAlignment = Alignment.CenterVertically, ) { dismissOmnibox()@@ -141,7 +148,14 @@ internal fun OmniboxEditor( } } },- ) { paddingValues -> suggestions(paddingValues) }+ ) { paddingValues ->+ ImeDebugState.contentPadBottomPx = with(LocalDensity.current) {+ paddingValues.calculateBottomPadding().toPx().toInt()+ }+ // TEMP DEBUG readout at top of content: always visible. Remove before commit.+ ImeDebugOverlay()+ suggestions(paddingValues)+ } } else { AppScaffold( title = { omniboxField(Modifier.fillMaxWidth()) },
web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt b/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.ktindex ed5dd75d95..88a0cf0e90 100644--- a/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt@@ -131,12 +131,8 @@ fun BrowserPage( BrowserChrome( omniboxText = viewModel.omniboxText, tabCount = viewModel.tabs.size,- canGoBack = canGoBack,- canGoForward = canGoForward, progress = if (activeTab != null && !isNewTabActive) progress else 0f, atBottom = viewModel.searchBarAtBottom,- onBack = { if (canGoBack) activeTab?.let { webViewPool[it.id]?.goBack() } },- onForward = { if (canGoForward) activeTab?.let { webViewPool[it.id]?.goForward() } }, onOmniboxClick = { val full = activeTab?.url?.let { if (it.isBlank() || it == "about:blank") "" else it } ?: "" viewModel.searchDraft = full@@ -148,9 +144,6 @@ fun BrowserPage( activeTab?.let { tab -> webViewPool[tab.id]?.let { viewModel.captureThumbnail(tab.id, it) } } viewModel.showTabSwitcher = true },- shieldHost = shieldHost,- blockedCount = activeTab?.let { viewModel.blockedCount(it.id) } ?: 0,- onShieldClick = { viewModel.showShieldsPanel = true }, onMenuClick = { showMenu = true }, menu = { BrowserMenu(@@ -160,6 +153,13 @@ fun BrowserPage( backStack = backStack, isNewTabActive = isNewTabActive, isCurrentBookmarked = isCurrentBookmarked,+ canGoBack = canGoBack,+ canGoForward = canGoForward,+ onGoBack = { if (canGoBack) activeTab?.let { webViewPool[it.id]?.goBack() } },+ onGoForward = { if (canGoForward) activeTab?.let { webViewPool[it.id]?.goForward() } },+ shieldHost = shieldHost,+ blockedCount = activeTab?.let { viewModel.blockedCount(it.id) } ?: 0,+ onShieldClick = { viewModel.showShieldsPanel = true }, onShowInstallDialog = { showInstallDialog = true }, onReload = { activeTab?.let {
web/src/main/java/com/vayunmathur/web/ui/ImeDebugOverlay.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/ImeDebugOverlay.kt b/web/src/main/java/com/vayunmathur/web/ui/ImeDebugOverlay.ktnew file mode 100644index 0000000000..f2d6046934--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/ui/ImeDebugOverlay.kt@@ -0,0 +1,46 @@+package com.vayunmathur.web.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.WindowInsets+import androidx.compose.foundation.layout.ime+import androidx.compose.foundation.layout.navigationBars+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++/** TEMP DEBUG. DO NOT COMMIT. */+internal object ImeDebugState {+ var barBottomY by mutableIntStateOf(-1)+ var contentPadBottomPx by mutableIntStateOf(-1)+}++/**+ * TEMP DEBUG readout. Renders inside CONTENT (always above keyboard) so it is+ * visible in every state. DO NOT COMMIT.+ */+@Composable+internal fun ImeDebugOverlay() {+ val density = LocalDensity.current+ val imeBottom = WindowInsets.ime.getBottom(density)+ val navBottom = WindowInsets.navigationBars.getBottom(density)+ Box(+ Modifier+ .background(Color.Red.copy(alpha = 0.85f))+ .padding(horizontal = 8.dp, vertical = 2.dp),+ ) {+ Text(+ text = "ime=$imeBottom nav=$navBottom bar=${ImeDebugState.barBottomY} pad=${ImeDebugState.contentPadBottomPx}",+ style = MaterialTheme.typography.labelSmall,+ color = Color.White,+ )+ }+}
web/src/main/res/values/strings.xml
diff --git a/web/src/main/res/values/strings.xml b/web/src/main/res/values/strings.xmlindex 8232812ac6..9d53adfb5e 100644--- a/web/src/main/res/values/strings.xml+++ b/web/src/main/res/values/strings.xml@@ -119,6 +119,8 @@ <string name="shields_engine_loading">Loading filter lists…</string> <string name="copy_link">Copy link</string> <string name="open_link">Open link</string>+ <string name="go_back">Back</string>+ <string name="go_forward">Forward</string> <string name="open_in_new_tab">Open in new tab</string> <string name="link_copied">Link copied</string> <string name="cleartext_blocked_title">Insecure connection blocked</string>