Modern Apps git

← Modern-Apps.git

ml: gemma4 prefill runs layers 15-34 on the last token only, TTFT 1.09 -> 0.57 s

Commit
fc52fe317bbc301e45af8dbc00ad303c859b7e78
Author
vayun-mathur <[email protected]>
When
2026-10-26 20:54 UTC (1 month ago)
Parents
3fe2ef7

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 4fd60be475..3157741132 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -587,6 +587,8 @@ struct PrefillTimes {     plan_wait: f64,     record: f64,     gpu: f64,+    /// The last token's `Mode::Tail` submit.+    tail: f64,     /// The last token's final-normed state, which the head reads.     state: Vec<f32>, }@@ -653,8 +655,20 @@ fn prefill_app(         at.set_params(StepParams { prefix: start, window_start: start.saturating_sub(gemma4::WINDOW - 1) })?;         let out = at.infer_raw_many(&[&hidden, &per_layer, &local, &global])?;         times.gpu += tick.elapsed().as_secs_f64() * 1000.0;-        let states = out.first().ok_or("a prefill returned nothing")?;-        times.state = g::column(states, chunk.len() - 1, width as usize);+        if (index + 1) * CHUNK < prompt.len() {+            continue;+        }+        // As `Gemma4Handle::tail`: the last real column through the layers that own no cache.+        let tick = Instant::now();+        let last = chunk.len() - 1;+        let residual = out.first().ok_or("a prefill returned nothing")?;+        let inputs = gemma4::tail_inputs(residual, [&hidden, &per_layer, &local, &global], last, width as usize, fused());+        let at = net.at(gemma4::Mode::Tail.at(TIER))?;+        let position = start + last as u32;+        at.set_params(StepParams { prefix: position, window_start: position.saturating_sub(gemma4::WINDOW - 1) })?;+        let refs: Vec<&[f32]> = inputs.iter().map(Vec::as_slice).collect();+        times.state = at.infer_raw_many(&refs)?.into_iter().next().ok_or("the tail returned nothing")?;+        times.tail += tick.elapsed().as_secs_f64() * 1000.0;     }     Ok(times) }@@ -688,6 +702,7 @@ fn time_prefill(     let warmed = (|| -> Result<(), String> {         net.at(gemma4::Mode::Prefill { tokens: 256 }.at(TIER))?;         net.at(gemma4::Mode::PrefillFresh { tokens: 256 }.at(TIER))?;+        net.at(gemma4::Mode::Tail.at(TIER))?;         net.at(gemma4::Mode::DecodeStep.at(TIER))?;         for width in [256, 1].into_iter().filter(|_| !fused()) {             gather.at(width)?;@@ -736,10 +751,10 @@ fn time_prefill(             };             let head_ms = tick.elapsed().as_secs_f64() * 1000.0;             println!(-                "{} prefill {width}+1 tokens: rows {:.0} + plan wait {:.0} + combine {:.0} + rotary {:.0} + record {:.0} + gpu {:.0} = {prefill_ms:.0} ms; \+                "{} prefill {width}+1 tokens: rows {:.0} + plan wait {:.0} + combine {:.0} + rotary {:.0} + record {:.0} + gpu {:.0} + tail {:.0} = {prefill_ms:.0} ms; \                  head {head_ms:.0} ms (id {id:?}); TTFT {:.0} ms",                 if run == 0 { "cold" } else { "warm" },-                p.rows, p.plan_wait, p.combine, p.rotary, p.record, p.gpu,+                p.rows, p.plan_wait, p.combine, p.rotary, p.record, p.gpu, p.tail,                 prefill_ms + head_ms,             );         }@@ -888,8 +903,10 @@ fn split_check(             tail_ms = tail_tick.elapsed().as_secs_f64() * 1000.0;         }         let logits = last_logits(&mut net, &mut head_net, &reader, &rotary, last, (n - 1) as u32)?;+        let caches = net.at(gemma4::Mode::DecodeStep.at(TIER))?.export_pinned(gemma4::CACHE_TENSORS, n as u32)?;+        let hash = caches.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &b| (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3));         println!(-            "  {label:<32} {:>7.0} ms (tail {tail_ms:.0} ms = {:.1} ms/token)  top10 {:?}",+            "  {label:<32} {:>7.0} ms (tail {tail_ms:.0} ms = {:.1} ms/token)  caches {hash:016x}  top10 {:?}",             tick.elapsed().as_secs_f64() * 1000.0,             tail_ms / tail.len().max(1) as f64,             top10(&logits)
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 0f9db4390d..41ee2d1d1f 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -64,6 +64,7 @@ fn warm_gemma4(net: &mut Reshaped<gemma4::Pass>, context: u32) -> Result<(), Str     let width = CHUNK.min(context);     net.at(gemma4::Mode::Prefill { tokens: width }.at(context))?;     net.at(gemma4::Mode::PrefillFresh { tokens: width }.at(context))?;+    net.at(gemma4::Mode::Tail.at(context))?;     net.at(gemma4::Mode::DecodeStep.at(context))?;     Ok(()) }
library/ml/src/main/rust/src/bridge_part9.rs
diff --git a/library/ml/src/main/rust/src/bridge_part9.rs b/library/ml/src/main/rust/src/bridge_part9.rsindex 9d97da2017..70d38141f1 100644--- a/library/ml/src/main/rust/src/bridge_part9.rs+++ b/library/ml/src/main/rust/src/bridge_part9.rs@@ -305,7 +305,7 @@ impl Gemma4Handle {     fn flush(&mut self) -> Result<(), String> {         let tokens = std::mem::take(&mut self.pending);         if !tokens.is_empty() {-            self.prefill(&tokens)?;+            self.prefill(&tokens, false)?;         }         Ok(())     }@@ -318,17 +318,18 @@ impl Gemma4Handle {         }         let mut tokens = std::mem::take(&mut self.pending);         tokens.push(token);-        self.prefill(&tokens).map(Some)+        self.prefill(&tokens, true).map(Some)     } -    /// Feed many tokens in **one** submit per chunk, filling the caches. Returns the last token's-    /// final-normed state, which the head reads when that token is a step's.+    /// Feed many tokens in **one** submit per chunk, filling the caches. With `tail`, returns the+    /// last token's final-normed state (from [`gemma4::Mode::Tail`]), which the head reads when+    /// that token is a step's; otherwise an empty state.     ///     /// At one position a pass reads 1.30 GB of weights for a single 1536-wide vector; at T     /// positions it reads them once and every projection becomes a GEMM over T columns. Chunked     /// because each chunk's score maps are eight heads of `T x context`. Every chunk attends the     /// whole cache (`attn_cached_multi`), so any split and any starting position is correct.-    fn prefill(&mut self, tokens: &[u32]) -> Result<Vec<f32>, String> {+    fn prefill(&mut self, tokens: &[u32], tail: bool) -> Result<Vec<f32>, String> {         if self.position as usize + tokens.len() > self.context as usize {             return Err(format!(                 "a prompt of {} positions past this device's {} cache",@@ -337,13 +338,14 @@ impl Gemma4Handle {             ));         }         let mut state = Vec::new();-        for chunk in tokens.chunks(CHUNK as usize) {+        let chunks = tokens.len().div_ceil(CHUNK as usize);+        for (index, chunk) in tokens.chunks(CHUNK as usize).enumerate() {             let real = chunk.len() as u32;             let width = crate::nets::gemma4_gather::padded(real, self.context - self.position);             // Pad columns feed the pad token; nothing real reads them (see `padded`).             let mut fed = chunk.to_vec();             fed.resize(width as usize, 0);-            state = self.prefill_chunk(real, width, |reader| {+            state = self.prefill_chunk(real, width, tail && index + 1 == chunks, |reader| {                 let hidden = crate::nets::gemma4_gather::token_rows(reader, &fed)?;                 Ok((hidden, crate::nets::gemma4_gather::layer_rows(reader, &fed)?))             })?;@@ -369,7 +371,7 @@ impl Gemma4Handle {         for chunk in values.chunks(d * CHUNK as usize) {             let real = (chunk.len() / d) as u32;             let width = crate::nets::gemma4_gather::padded(real, self.context - self.position);-            self.prefill_chunk(real, width, |reader| {+            self.prefill_chunk(real, width, false, |reader| {                 let mut hidden = vec![0f32; d * width as usize];                 for (at, row) in chunk.chunks_exact(d).enumerate() {                     crate::nets::gemma4_gather::place(&mut hidden, row, at, width as usize);@@ -382,11 +384,13 @@ impl Gemma4Handle {      /// One chunk of `real` positions run at `width`: `rows` gathers the `[C, 1, width]` hidden     /// and table blocks while the chunk's plan builds on another thread if it was evicted, then-    /// one combine submit and one Prefill submit. Returns the last real column's normed state.+    /// one combine submit and one Prefill submit. With `tail`, runs the last real column on+    /// through [`gemma4::Mode::Tail`] and returns its normed state; otherwise an empty one.     fn prefill_chunk(         &mut self,         real: u32,         width: u32,+        tail: bool,         rows: impl FnOnce(&crate::weights::Reader<'_>) -> Result<(Vec<f32>, Vec<f32>), String>,     ) -> Result<Vec<f32>, String> {         let started = std::time::Instant::now();@@ -442,8 +446,28 @@ impl Gemma4Handle {             recorded.as_secs_f64() * 1000.0,             ran.elapsed().as_secs_f64() * 1000.0,         ));+        let last = self.position + real - 1;         self.position += real;-        let states = out.first().ok_or("a prefill returned nothing")?;-        Ok(crate::nets::gemma4_gather::column(states, real.saturating_sub(1) as usize, wide))+        if !tail {+            return Ok(Vec::new());+        }+        let residual = out.first().ok_or("a prefill returned nothing")?;+        let inputs = gemma4::tail_inputs(residual, [&hidden, &per_layer, &local, &global], (real - 1) as usize, wide, self.fused());+        self.tail(&inputs, last)+    }++    /// [`gemma4::Mode::Tail`] for the prefill column at `position`: its final-normed state.+    fn tail(&mut self, inputs: &[Vec<f32>], position: u32) -> Result<Vec<f32>, String> {+        let ran = std::time::Instant::now();+        let at = self.net.at(gemma4::Mode::Tail.at(self.context))?;+        at.set_params(StepParams { prefix: position, window_start: position.saturating_sub(gemma4::WINDOW - 1) })?;+        let refs: Vec<&[f32]> = inputs.iter().map(Vec::as_slice).collect();+        let out = at.infer_raw_many(&refs)?;+        log(&format!("gemma4 tail at {position}: {:.0} ms", ran.elapsed().as_secs_f64() * 1000.0));+        let state = out.into_iter().next().unwrap_or_default();+        if state.len() != gemma4::D_MODEL as usize {+            return Err(format!("a tail state of {} values, not {}", state.len(), gemma4::D_MODEL));+        }+        Ok(state)     } }
library/ml/src/main/rust/src/nets/gemma4.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4.rs b/library/ml/src/main/rust/src/nets/gemma4.rsindex cbedd37d02..e2a3c115af 100644--- a/library/ml/src/main/rust/src/nets/gemma4.rs+++ b/library/ml/src/main/rust/src/nets/gemma4.rs@@ -436,4 +436,5 @@ include!("gemma4_part5.rs"); include!("gemma4_part6.rs"); include!("gemma4_part7.rs"); include!("gemma4_part8.rs");-include!("gemma4_part9.rs");\ No newline at end of file+include!("gemma4_part9.rs");+include!("gemma4_part10.rs");\ No newline at end of file
library/ml/src/main/rust/src/nets/gemma4_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part1.rs b/library/ml/src/main/rust/src/nets/gemma4_part1.rsindex c6a2a382ff..0de91bcfc2 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part1.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part1.rs@@ -53,7 +53,10 @@ pub enum Mode {     /// divergence point. Computed by the same op sequence as [`layer`](super::layer),     /// so the KV cache it fills matches a decode step exactly.     TraceTail,-    /// Run every layer to fill the KV cache, with **no logits head**. `tokens` positions at once.+    /// Run the cache-owning layers to fill the KV cache, with **no logits head**. `tokens`+    /// positions at once. Returns the residual after layer `OWNS_CACHE_LAYERS - 1` for every+    /// column: the later layers write no cache, so only the column whose logits are wanted goes+    /// on through them, in [`Mode::Tail`].     ///     /// # Why the head is skipped rather than ignored     ///@@ -83,6 +86,11 @@ pub enum Mode {     /// attention runs over the chunk's own keys with the tiled `T x T` kernels, which is faster     /// than the cache-wide multi-query path. Wrong at any other position.     PrefillFresh { tokens: u32 },+    /// Layers `OWNS_CACHE_LAYERS..LAYERS` and the final norm for one prefill column, through the+    /// decode-step ops, submitted with `StepParams` at that column's position. Inputs: the+    /// prefill's residual at that column, then the column of the prefill's inputs 1..3, then of+    /// input 0 when the plan combines in-plan. See [`tail_inputs`].+    Tail, }  /// Plan inputs, in declaration order.@@ -121,20 +129,23 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> {     if !CONTEXT_TIERS.contains(&context) {         return Err(format!("a cache of {context} positions, which is not one of the tiers"));     }-    let stop_after = match mode {-        Mode::DecodeStep => LAYERS,-        // Prefill runs every layer; what it skips is the head, not the depth.+    let run = match mode {+        Mode::DecodeStep => 0..LAYERS,+        Mode::Tail => OWNS_CACHE_LAYERS..LAYERS,         Mode::Prefill { tokens: 0 } | Mode::PrefillFresh { tokens: 0 } => {             return Err("a prefill of no positions".into())         }-        Mode::Prefill { tokens } | Mode::PrefillFresh { tokens } if tokens <= context => LAYERS,+        // Past the owning layers a prefill column reaches no cache, so they stop here.+        Mode::Prefill { tokens } | Mode::PrefillFresh { tokens } if tokens <= context => {+            0..OWNS_CACHE_LAYERS+        }         Mode::Prefill { tokens } | Mode::PrefillFresh { tokens } => {             return Err(format!("a prefill of {tokens} positions, past a {context} cache"))         }-        Mode::Trace { layers } if layers <= LAYERS => layers,+        Mode::Trace { layers } if layers <= LAYERS => 0..layers,         Mode::Trace { layers } => return Err(format!("a trace of {layers} of {LAYERS} layers")),         // Layer 0 only; the branches come from that one layer.-        Mode::TraceTail => 1,+        Mode::TraceTail => 0..1,     };     let mut builder = Builder::new(weights);     let b = &mut builder;@@ -178,7 +189,9 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> {     let angles_local = b.input(Shape::new(HEAD_DIM, 1, width));     let angles_global = b.input(Shape::new(GLOBAL_HEAD_DIM, 1, width));     let fused = combines_in_plan(weights);-    let per_layer_inputs = if fused { combine_in_plan(b, x, per_layer_in) } else { per_layer_in };+    // The tail's input 0 is a residual, so the token row the combine reads comes after the rest.+    let row = if fused && mode == Mode::Tail { b.input(Shape::new(D_MODEL, 1, 1)) } else { x };+    let per_layer_inputs = if fused { combine_in_plan(b, row, per_layer_in) } else { per_layer_in };     // The rotary tables. Read on the host, a row at a time, and handed back as the two angle     // inputs above - the same arrangement as the embedding.     b.host_tensor(ROTARY_LOCAL, &[MAX_CONTEXT, HEAD_DIM]);@@ -194,7 +207,7 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> {     // to the shared layers as tensors (the `cache_source` mapping, resolved to tensors).     let fresh = matches!(mode, Mode::PrefillFresh { .. });     let (mut sliding_kv, mut full_kv): (Option<(Id, Id)>, Option<(Id, Id)>) = (None, None);-    for index in 0..stop_after {+    for index in run.clone() {         let angles = if is_full_attention(index) { angles_global } else { angles_local };         let (cache_k, cache_v) = *caches             .get(cache_source(index))@@ -222,108 +235,34 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> {         }     } -    if let Mode::TraceTail = mode {-        // Layers 1..35 are named rather than evaluated, exactly as `Trace` does.-        for index in stop_after..LAYERS {-            declare_layer(weights, index)?;-            name_layer(b, index);-        }-        name_head(b);-        let Some([attn_branch, mlp_branch, ple_branch, out]) = tail else {-            return Err("a tail trace with no layer 0".into());-        };-        return builder.finish(&[attn_branch, mlp_branch, ple_branch, out]);+    // Every tensor a skipped layer would have read still has to be read, or `finish` refuses the+    // plan - so those layers are named rather than evaluated.+    for index in (0..LAYERS).filter(|index| !run.contains(index)) {+        declare_layer(weights, index)?;+        name_layer(b, index);     }--    if let Mode::Trace { .. } = mode {-        // Every tensor the untraced pass would have read still has to be read, or `finish`-        // refuses the plan - so the layers this stops short of, and the head, are named rather-        // than evaluated.-        for index in stop_after..LAYERS {-            declare_layer(weights, index)?;-            name_layer(b, index);+    match mode {+        Mode::TraceTail => {+            name_head(b);+            let Some([attn_branch, mlp_branch, ple_branch, out]) = tail else {+                return Err("a tail trace with no layer 0".into());+            };+            builder.finish(&[attn_branch, mlp_branch, ple_branch, out])+        }+        Mode::Trace { .. } => {+            name_head(b);+            builder.finish(&[x, per_layer_inputs])+        }+        Mode::Prefill { .. } | Mode::PrefillFresh { .. } => {+            name_head(b);+            builder.finish(&[x])+        }+        // The normed hidden state; the head lives in its own file.+        Mode::DecodeStep | Mode::Tail => {+            let state = b.rms_norm(x, FINAL_NORM, EPSILON);+            builder.finish(&[state])         }-        name_head(b);-        return builder.finish(&[x, per_layer_inputs]);-    }--    if let Mode::Prefill { .. } | Mode::PrefillFresh { .. } = mode {-        // Prefill runs every layer - the point is the caches those layers fill - and then the-        // final norm, so the host can run the head on the last column: a prompt's final token-        // rides its prefill instead of costing a decode step of its own. The other columns'-        // states are read back and ignored.-        let state = b.rms_norm(x, FINAL_NORM, EPSILON);-        return builder.finish(&[state]);-    }--    let state = b.rms_norm(x, FINAL_NORM, EPSILON);-    // Tied head: litertlm stores no logits head, so logits are hidden @ E^T with-    // E the working embedding table - computed ON THE HOST in bridge_part6-    // (host tied-head SGEMV over the embed file's int4 table, then softcap).-    // The device returns the normed hidden state; this keeps 201 MB of head-    // weights out of the text file and out of VRAM. A Vulkan tied-head GEMM-    // (chunked over vocab) is the follow-up; host SGEMV is the correct v1.-    builder.finish(&[state])-}--/// Name the final norm as host-read, for the modes that stop before the head.-///-/// [`Mode::Trace`] and [`Mode::Prefill`] both end after a layer rather than after the-/// norm, and `Builder::finish` refuses a plan that leaves a tensor unread.-fn name_head(b: &mut Builder) {-    b.host_tensor(FINAL_NORM, &[D_MODEL]);-}--/// Name every tensor of layer `index` as host-read, for [`Mode::Trace`].-///-/// A trace stops early, so the layers after it are never evaluated - but `Builder::finish`-/// refuses a plan that leaves a tensor unread, and rightly so. This says "the host owns these",-/// which keeps that invariant meaningful for the layers the trace *does* run.-///-/// Mirrors [`super::declare_layer`] tensor for tensor: split gate/ff1/linear, no-/// `v_norm`, plus the trailing `skip` scalar. A shape here that drifted from the-/// declaration would name a tensor the file does not hold at that index.-fn name_layer(b: &mut Builder, index: usize) {-    let dim = head_dim(index);-    let inner = ffn(index);-    let blocks = |inp: u32| inp.div_ceil(crate::weights::I4_BLOCK);-    let mut next = layer_at(index);-    let mut plain = |b: &mut Builder, n: &mut usize, dims: &[u32]| {-        b.host_tensor(*n, dims);-        *n += 1;-    };-    let mut proj4 = |b: &mut Builder, n: &mut usize, out: u32, inp: u32| {-        b.host_tensor(*n, &[out, inp, 1, 1]);-        b.host_tensor(*n + 1, &[out, blocks(inp)]);-        b.host_tensor(*n + 2, &[out]);-        *n += PROJECTION_TENSORS;-    };-    let mut proj8 = |b: &mut Builder, n: &mut usize, out: u32, inp: u32| {-        b.host_tensor(*n, &[out, inp, 1, 1]);-        b.host_tensor(*n + 1, &[out]);-        b.host_tensor(*n + 2, &[out]);-        *n += PROJECTION_TENSORS;-    };-    plain(b, &mut next, &[D_MODEL]);-    plain(b, &mut next, &[dim]);-    proj4(b, &mut next, HEADS * dim, D_MODEL);-    if owns_cache(index) {-        plain(b, &mut next, &[dim]);-        proj4(b, &mut next, KV_HEADS * dim, D_MODEL);-        proj4(b, &mut next, KV_HEADS * dim, D_MODEL);     }-    proj4(b, &mut next, D_MODEL, HEADS * dim);-    plain(b, &mut next, &[D_MODEL]);-    plain(b, &mut next, &[D_MODEL]);-    proj4(b, &mut next, inner, D_MODEL);-    proj4(b, &mut next, inner, D_MODEL);-    proj4(b, &mut next, D_MODEL, inner);-    plain(b, &mut next, &[D_MODEL]);-    proj8(b, &mut next, PER_LAYER, D_MODEL);-    proj8(b, &mut next, D_MODEL, PER_LAYER);-    plain(b, &mut next, &[D_MODEL]);-    plain(b, &mut next, &[1]);-    debug_assert_eq!(next, layer_at(index + 1), "layer {index} names past its span"); }  /// One decoder layer over `width` positions at once.
library/ml/src/main/rust/src/nets/gemma4_part10.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part10.rs b/library/ml/src/main/rust/src/nets/gemma4_part10.rsnew file mode 100644index 0000000000..99c09f41d4--- /dev/null+++ b/library/ml/src/main/rust/src/nets/gemma4_part10.rs@@ -0,0 +1,152 @@+/// Name the final norm as host-read, for the modes that stop before the head.+///+/// [`Mode::Trace`] and [`Mode::Prefill`] both end after a layer rather than after the+/// norm, and `Builder::finish` refuses a plan that leaves a tensor unread.+fn name_head(b: &mut Builder) {+    b.host_tensor(FINAL_NORM, &[D_MODEL]);+}++/// Name every tensor of layer `index` as host-read, for the modes that skip it.+///+/// `Builder::finish` refuses a plan that leaves a tensor unread, and rightly so. This says "the+/// host owns these", which keeps that invariant meaningful for the layers the plan *does* run.+///+/// Mirrors [`super::declare_layer`] tensor for tensor: split gate/ff1/linear, no+/// `v_norm`, plus the trailing `skip` scalar. A shape here that drifted from the+/// declaration would name a tensor the file does not hold at that index.+fn name_layer(b: &mut Builder, index: usize) {+    let dim = head_dim(index);+    let inner = ffn(index);+    let blocks = |inp: u32| inp.div_ceil(crate::weights::I4_BLOCK);+    let mut next = layer_at(index);+    let plain = |b: &mut Builder, n: &mut usize, dims: &[u32]| {+        b.host_tensor(*n, dims);+        *n += 1;+    };+    let proj4 = |b: &mut Builder, n: &mut usize, out: u32, inp: u32| {+        b.host_tensor(*n, &[out, inp, 1, 1]);+        b.host_tensor(*n + 1, &[out, blocks(inp)]);+        b.host_tensor(*n + 2, &[out]);+        *n += PROJECTION_TENSORS;+    };+    let proj8 = |b: &mut Builder, n: &mut usize, out: u32, inp: u32| {+        b.host_tensor(*n, &[out, inp, 1, 1]);+        b.host_tensor(*n + 1, &[out]);+        b.host_tensor(*n + 2, &[out]);+        *n += PROJECTION_TENSORS;+    };+    plain(b, &mut next, &[D_MODEL]);+    plain(b, &mut next, &[dim]);+    proj4(b, &mut next, HEADS * dim, D_MODEL);+    if owns_cache(index) {+        plain(b, &mut next, &[dim]);+        proj4(b, &mut next, KV_HEADS * dim, D_MODEL);+        proj4(b, &mut next, KV_HEADS * dim, D_MODEL);+    }+    proj4(b, &mut next, D_MODEL, HEADS * dim);+    plain(b, &mut next, &[D_MODEL]);+    plain(b, &mut next, &[D_MODEL]);+    proj4(b, &mut next, inner, D_MODEL);+    proj4(b, &mut next, inner, D_MODEL);+    proj4(b, &mut next, D_MODEL, inner);+    plain(b, &mut next, &[D_MODEL]);+    proj8(b, &mut next, PER_LAYER, D_MODEL);+    proj8(b, &mut next, D_MODEL, PER_LAYER);+    plain(b, &mut next, &[D_MODEL]);+    plain(b, &mut next, &[1]);+    debug_assert_eq!(next, layer_at(index + 1), "layer {index} names past its span");+}++/// [`Mode::Tail`]'s inputs for column `at` of a `width`-wide prefill: that column of the+/// residual the prefill returned and of the prefill's inputs 1..3, then of input 0 when the plan+/// combines in-plan ([`combines_in_plan`]).+pub fn tail_inputs(residual: &[f32], inputs: [&[f32]; 4], at: usize, width: usize, fused: bool) -> Vec<Vec<f32>> {+    use super::gemma4_gather::column;+    let mut out = vec![column(residual, at, width)];+    out.extend(inputs[1..].iter().map(|block| column(block, at, width)));+    if fused {+        out.push(column(inputs[0], at, width));+    }+    out+}++#[cfg(test)]+mod tail_tests {+    use super::*;+    use crate::nets::tests::Shapes;+    use crate::nets::{Kind, Op};++    const TEST_CONTEXT: u32 = CONTEXT_TIERS[0];++    fn count(plan: &Plan, wanted: Kind) -> usize {+        plan.ops.iter().filter(|op| matches!(op, Op::Dispatch { kind, .. } if *kind == wanted)).count()+    }++    #[test]+    fn a_prefill_and_its_tail_split_the_layers_at_the_last_cache_owner() {+        for tensors in [TENSORS, TENSORS_WITH_COMBINE] {+            let source = Shapes::new(tensors);+            let decode = build(&source, Mode::DecodeStep.at(TEST_CONTEXT)).expect("decode builds");+            let prefill = build(&source, Mode::Prefill { tokens: 8 }.at(TEST_CONTEXT)).expect("prefill builds");+            let tail = build(&source, Mode::Tail.at(TEST_CONTEXT)).expect("tail builds");+            assert_eq!(count(&prefill, Kind::AttnScoresCached), OWNS_CACHE_LAYERS);+            assert_eq!(count(&tail, Kind::AttnScoresCached), LAYERS - OWNS_CACHE_LAYERS);+            assert_eq!(count(&prefill, Kind::CacheWrite), count(&decode, Kind::CacheWrite), "every cache");+            assert_eq!(count(&tail, Kind::CacheWrite), 0, "the tail's layers own no cache");+            assert_eq!(prefill.outputs[0].shape, Shape::new(D_MODEL, 1, 8), "the residual, every column");+            assert_eq!(tail.outputs[0].shape, decode.outputs[0].shape, "the normed state");+            let fused = tensors == TENSORS_WITH_COMBINE;+            assert_eq!(tail.inputs.len(), INPUTS + usize::from(fused));+            assert!(tail.inputs.iter().all(|input| input.shape.w == 1));+            // At most the one extra input: warm-up records it, so it never grows a filled arena.+            let slack = if fused { D_MODEL } else { 0 };+            assert!(+                tail.arena_elems <= decode.arena_elems + slack,+                "tail {} against decode {}",+                tail.arena_elems,+                decode.arena_elems+            );+        }+    }++    #[test]+    fn the_tail_reads_the_caches_where_the_prefill_wrote_them() {+        let source = Shapes::new(TENSORS);+        let reads = |plan: &Plan| -> Vec<u32> {+            plan.ops+                .iter()+                .filter_map(|op| match op {+                    Op::Dispatch { kind: Kind::AttnScoresCached | Kind::AttnApplyCached, push, .. } => Some(push.in1),+                    _ => None,+                })+                .collect()+        };+        let writes = |plan: &Plan| -> Vec<u32> {+            plan.ops+                .iter()+                .filter_map(|op| match op {+                    Op::Dispatch { kind: Kind::CacheWrite, push, .. } => Some(push.out),+                    _ => None,+                })+                .collect()+        };+        let prefill = build(&source, Mode::Prefill { tokens: 8 }.at(TEST_CONTEXT)).expect("prefill builds");+        let tail = build(&source, Mode::Tail.at(TEST_CONTEXT)).expect("tail builds");+        let written = writes(&prefill);+        let read = reads(&tail);+        assert_eq!(read.len(), 2 * (LAYERS - OWNS_CACHE_LAYERS));+        assert!(read.iter().all(|at| written.contains(at)), "tail reads {read:?}, prefill wrote {written:?}");+    }++    #[test]+    fn tail_inputs_take_one_column_of_each_block() {+        let width = 3;+        let block = |c: usize| (0..c * width).map(|i| i as f32).collect::<Vec<f32>>();+        let (residual, hidden, rows, local, global) = (block(2), block(2), block(3), block(1), block(1));+        let plain = tail_inputs(&residual, [&hidden, &rows, &local, &global], 2, width, false);+        assert_eq!(plain, vec![vec![2.0, 5.0], vec![2.0, 5.0, 8.0], vec![2.0], vec![2.0]]);+        let fused = tail_inputs(&residual, [&hidden, &rows, &local, &global], 1, width, true);+        assert_eq!(fused.len(), 5);+        assert_eq!(fused[4], vec![1.0, 4.0]);+    }+}
library/ml/src/main/rust/src/nets/gemma4_part3.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part3.rs b/library/ml/src/main/rust/src/nets/gemma4_part3.rsindex 4a41b5e52c..967ac1f0d2 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part3.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part3.rs@@ -186,15 +186,16 @@ mod tests {     }      #[test]-    fn a_prefill_plan_ends_at_the_final_norm_like_decode() {-        // A prefill skips nothing a decode step runs: the head lives in its own file, and the-        // final norm stays so the host can run the head on a prefill's last column.+    fn a_prefill_plan_and_its_tail_run_what_decode_runs() {+        // A prefill runs the cache-owning layers and the tail the rest plus the final norm: the+        // two together are exactly a decode step, so the host can run the head on the tail.         let decode = build(&Shapes::new(TENSORS), Mode::DecodeStep.at(TEST_CONTEXT)).expect("decode builds");         let prefill =             build(&Shapes::new(TENSORS), Mode::Prefill { tokens: 1 }.at(TEST_CONTEXT)).expect("prefill builds");-        assert_eq!(decode.ops.len(), prefill.ops.len(), "prefill {} ops against decode {}", prefill.ops.len(), decode.ops.len());+        let tail = build(&Shapes::new(TENSORS), Mode::Tail.at(TEST_CONTEXT)).expect("tail builds");+        assert_eq!(decode.ops.len(), prefill.ops.len() + tail.ops.len(), "prefill {} + tail {} ops against decode {}", prefill.ops.len(), tail.ops.len(), decode.ops.len());         assert_eq!(prefill.outputs.len(), 1);-        assert_eq!(prefill.outputs[0].shape, decode.outputs[0].shape, "the normed state, one per column");+        assert_eq!(prefill.outputs[0].shape, decode.outputs[0].shape, "the residual, one per column");         // The caches are the point of a prefill, so it must still write all of them.         let writes = |plan: &Plan| {             plan.ops@@ -260,8 +261,9 @@ mod tests {                     _ => {}                 }             }-            assert_eq!((scores, softmaxes), (LAYERS, LAYERS), "one cached attention per layer");-            assert_eq!(windowed, 28, "and the sliding ones carry a window");+            let owners = OWNS_CACHE_LAYERS;+            assert_eq!((scores, softmaxes), (owners, owners), "one cached attention per owning layer");+            assert_eq!(windowed, 12, "and the sliding ones carry a window");              // At position 0 the chunk is all there is, so it attends itself with the T x T kernels.             let fresh = build(&Shapes::new(TENSORS), Mode::PrefillFresh { tokens }.at(TEST_CONTEXT))@@ -271,7 +273,7 @@ mod tests {             assert!(kinds().all(|(k, _)| !matches!(k, Kind::AttnScoresCached | Kind::AttnApplyCached)));             let causal: Vec<_> = kinds().filter(|(k, _)| *k == Kind::SoftmaxCausal).collect();             assert!(causal.iter().all(|(_, p)| (p.out_h, p.out_w) == (tokens, tokens)), "T x T scores");-            assert_eq!((causal.len(), causal.iter().filter(|(_, p)| p.kh == WINDOW).count()), (LAYERS, 28));+            assert_eq!((causal.len(), causal.iter().filter(|(_, p)| p.kh == WINDOW).count()), (OWNS_CACHE_LAYERS, 12));         }         assert!(build(&Shapes::new(TENSORS), Mode::Prefill { tokens: 0 }.at(TEST_CONTEXT)).is_err());         let past = MAX_CONTEXT + 1;