ml: dedupe Gemma projection helpers into nets
- Commit
79ef9851c963a8fde38518777a6e1224f8ba1a06- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 21:41 UTC (4 days ago)
- Parents
84686c0
The Gemma 4 decoder, vision tower and audio tower each carried a private copy of projection (three copies), the vision and audio towers each carried dense (two copies), and the decoder and vision tower each carried as_exported (two copies). All bodies were verified byte-identical before deletion; the per-module PROJECTION_TENSORS constants are all 3 and DENSE_TENSORS are both 2, so the shared helpers in nets use those literals. Move all three helpers into nets (pub(crate) projection/dense, pub as_exported) and import them in each tower. The decoder and vision tower re-export as_exported with pub use, preserving their public paths. The audio tower keeps its own as_exported, which has an extra depthwise-convolution arm and is not a duplicate. No call site changes, so declaration behaviour is unchanged. Net -39 lines. Skipped in this crate: layer_dims in nllb/whisper and build/ name_host_tensors/cross_kv in madlad/nllb look identical as text but resolve to per-net constants and functions, so they are not shareable as-is; Layers::take/point families are per-struct by design; conv_out/conv_out_shape is deliberately duplicated per its own comment in weights_part8.rs. Verified: bodies compared verbatim before deleting - identical. cargo test -p modelrunner --locked: 871 passed, 19 assets, 5 pure logic (same as baseline). cargo fmt -p modelrunner -- --check clean. structure_check lines: OK, 1,655,772 (delta -39).
Diff
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 35c5a1eb3a..3e23b415a6 100644--- a/library/ml/src/main/rust/src/nets/gemma4.rs+++ b/library/ml/src/main/rust/src/nets/gemma4.rs@@ -51,7 +51,9 @@ //! error and not a crash, just quietly flatter attention. The converter divides it out; see //! [`Q_NORM_CARRIES_SCALE`]. -use super::{Act, Builder, Id, Plan, Shape, WeightSource};+use super::{projection, Act, Builder, Id, Plan, Shape, WeightSource};++pub use super::as_exported; /// Hidden width. pub const D_MODEL: u32 = 1536;@@ -380,23 +382,6 @@ pub fn declare_layer(weights: &dyn WeightSource, index: usize) -> Result<(), Str Ok(()) } -/// One quantised `1x1` projection: kernel, per-block scale, bias.-///-/// Four bits, which is what every large projection uses.-fn projection(- weights: &dyn WeightSource,- next: &mut usize,- out: u32,- inp: u32,-) -> Result<(), String> {- weights.shaped_words(*next, &[out, inp, 1, 1])?;- let blocks = inp.div_ceil(crate::weights::I4_BLOCK);- weights.shaped(*next + 1, &[out, blocks])?;- weights.shaped(*next + 2, &[out])?;- *next += PROJECTION_TENSORS;- Ok(())-}- /// [`projection`] at **eight** bits, whose scale is rank 1. /// /// For the two per-layer-input projections. They are the smallest weights in a layer -@@ -417,18 +402,6 @@ fn projection8( Ok(()) } -/// The `[in, out]` shape the export holds for a kernel this module declares as `dims`.-///-/// The inverse of the transpose described on [`declare_layer`], so a converter check can compare-/// against the ONNX file without either side restating the other's convention. Scales and biases-/// have no counterpart in the export and come back unchanged.-pub fn as_exported(dims: &[u32]) -> Vec<u32> {- match dims {- [out, inp, 1, 1] => vec![*inp, *out],- other => other.to_vec(),- }-}- include!("gemma4_part1.rs"); include!("gemma4_part2.rs"); include!("gemma4_part3.rs");
library/ml/src/main/rust/src/nets/gemma4_audio.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_audio.rs b/library/ml/src/main/rust/src/nets/gemma4_audio.rsindex 5b9cc8251c..f2301c74bb 100644--- a/library/ml/src/main/rust/src/nets/gemma4_audio.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_audio.rs@@ -105,7 +105,7 @@ //! it. The export's initializers are anonymised (`val_2567`, `permute_9`, `_to_copy_16`), so the //! converter matches on **node numbering** in topological order and asserts the counts, which //! makes agreeing on this order more load-bearing here rather than less.-use super::{Act, Builder, Id, Plan, Shape, WeightSource};+use super::{dense, projection, Act, Builder, Id, Plan, Shape, WeightSource}; /// Channels through the tower. `audio_config.hidden_size`. pub const D_MODEL: u32 = 1024;
library/ml/src/main/rust/src/nets/gemma4_audio_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_audio_part1.rs b/library/ml/src/main/rust/src/nets/gemma4_audio_part1.rsindex a6023bdf37..e53d5084b3 100644--- a/library/ml/src/main/rust/src/nets/gemma4_audio_part1.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_audio_part1.rs@@ -86,29 +86,6 @@ pub fn declare_layer(weights: &dyn WeightSource, index: usize) -> Result<(), Str Ok(()) } -/// One quantised `1 x 1` projection: kernel, per-block scale, bias.-fn projection(- weights: &dyn WeightSource,- next: &mut usize,- out: u32,- inp: u32,-) -> Result<(), String> {- weights.shaped_words(*next, &[out, inp, 1, 1])?;- let blocks = inp.div_ceil(crate::weights::I4_BLOCK);- weights.shaped(*next + 1, &[out, blocks])?;- weights.shaped(*next + 2, &[out])?;- *next += PROJECTION_TENSORS;- Ok(())-}--/// One **unquantised** `1 x 1` projection: kernel and bias, the pair `Builder::conv` reads.-fn dense(weights: &dyn WeightSource, next: &mut usize, out: u32, inp: u32) -> Result<(), String> {- weights.shaped(*next, &[out, inp, 1, 1])?;- weights.shaped(*next + 1, &[out])?;- *next += DENSE_TENSORS;- Ok(())-}- /// Declare the tensors that sit outside any layer, in file order. pub fn declare_shared(weights: &dyn WeightSource) -> Result<(), String> { let mut next = SSCP_CONV0;
library/ml/src/main/rust/src/nets/gemma4_vision.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_vision.rs b/library/ml/src/main/rust/src/nets/gemma4_vision.rsindex 9d2b60122a..648dc6f56a 100644--- a/library/ml/src/main/rust/src/nets/gemma4_vision.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_vision.rs@@ -44,7 +44,9 @@ //! it. The export's initializers are anonymised (`_to_copy_104`), so unlike the decoder the //! converter cannot match by name and walks the graph in topological order instead - which makes //! agreeing on this order more load-bearing here, not less.-use super::{Act, Builder, Id, Plan, Shape, WeightSource};+use super::{dense, projection, Act, Builder, Id, Plan, Shape, WeightSource};++pub use super::as_exported; /// Channels through the tower. `hidden_size` in `vision_config`. pub const D_MODEL: u32 = 768;@@ -252,33 +254,6 @@ pub fn declare_layer(weights: &dyn WeightSource, index: usize) -> Result<(), Str Ok(()) } -/// One quantised `1x1` projection: kernel, per-block scale, bias.-///-/// int4 like the decoder's, and for the same reason - the tower is 337 MB at fp16 and 99 MB at-/// four bits, on top of a download that is already large. The two projections at the ends are the-/// exception; see [`PATCH_PROJECTION`].-fn projection(- weights: &dyn WeightSource,- next: &mut usize,- out: u32,- inp: u32,-) -> Result<(), String> {- weights.shaped_words(*next, &[out, inp, 1, 1])?;- let blocks = inp.div_ceil(crate::weights::I4_BLOCK);- weights.shaped(*next + 1, &[out, blocks])?;- weights.shaped(*next + 2, &[out])?;- *next += PROJECTION_TENSORS;- Ok(())-}--/// One **unquantised** `1x1` projection: kernel and bias, the pair [`Builder::conv`] reads.-fn dense(weights: &dyn WeightSource, next: &mut usize, out: u32, inp: u32) -> Result<(), String> {- weights.shaped(*next, &[out, inp, 1, 1])?;- weights.shaped(*next + 1, &[out])?;- *next += DENSE_TENSORS;- Ok(())-}- /// Declare the tensors that sit outside any layer, in file order. pub fn declare_shared(weights: &dyn WeightSource) -> Result<(), String> { let mut next = PATCH_PROJECTION;@@ -298,14 +273,6 @@ pub fn declare_shared(weights: &dyn WeightSource) -> Result<(), String> { Ok(()) } -/// The `[in, out]` shape the export holds for a kernel declared here as `dims`.-pub fn as_exported(dims: &[u32]) -> Vec<u32> {- match dims {- [out, inp, 1, 1] => vec![*inp, *out],- other => other.to_vec(),- }-}- /// The patch grid one image is resized to, in patches. /// /// Both extents are multiples of [`POOL`], which is what the reference preprocessor guarantees by
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex b9c8eb28aa..0a35213d11 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -150,6 +150,50 @@ pub enum Act { Gelu, } +/// One quantised `1x1` Gemma projection: kernel, per-block scale, bias.+///+/// Shared by the Gemma 4 decoder, vision tower and audio tower, whose+/// `PROJECTION_TENSORS` constants are all 3.+pub(crate) fn projection(+ weights: &dyn WeightSource,+ next: &mut usize,+ out: u32,+ inp: u32,+) -> Result<(), String> {+ weights.shaped_words(*next, &[out, inp, 1, 1])?;+ let blocks = inp.div_ceil(crate::weights::I4_BLOCK);+ weights.shaped(*next + 1, &[out, blocks])?;+ weights.shaped(*next + 2, &[out])?;+ *next += 3;+ Ok(())+}++/// One unquantised `1x1` Gemma projection: kernel and bias.+///+/// Shared by the Gemma 4 vision and audio towers, whose+/// `DENSE_TENSORS` constants are both 2.+pub(crate) fn dense(+ weights: &dyn WeightSource,+ next: &mut usize,+ out: u32,+ inp: u32,+) -> Result<(), String> {+ weights.shaped(*next, &[out, inp, 1, 1])?;+ weights.shaped(*next + 1, &[out])?;+ *next += 2;+ Ok(())+}++/// The `[in, out]` shape the export holds for a Gemma kernel declared as `dims`.+///+/// Scales and biases have no counterpart in the export and come back unchanged.+pub fn as_exported(dims: &[u32]) -> Vec<u32> {+ match dims {+ [out, inp, 1, 1] => vec![*inp, *out],+ other => other.to_vec(),+ }+}+ /// Which compute pipeline an [`Op::Dispatch`] wants. include!("mod_kind.rs"); #[cfg(test)]