Modern Apps git

← Modern-Apps.git

ml: plan fold passes index readers once per fold, gemma4 plan build 30 -> 12 ms

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

Diff

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 e3e1477120..09b13f67a6 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -493,4 +493,5 @@ include!("mod_part10.rs"); include!("mod_part11.rs"); include!("mod_part12.rs"); include!("mod_part13.rs");-include!("mod_part14.rs");\ No newline at end of file+include!("mod_part14.rs");+include!("mod_part15.rs");\ No newline at end of file
library/ml/src/main/rust/src/nets/mod_part13.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part13.rs b/library/ml/src/main/rust/src/nets/mod_part13.rsindex d5c21e7e8c..c024b93676 100644--- a/library/ml/src/main/rust/src/nets/mod_part13.rs+++ b/library/ml/src/main/rust/src/nets/mod_part13.rs@@ -49,6 +49,7 @@ impl<'a> Builder<'a> {      /// One fold, or `false` when no quantize qualifies.     fn fuse_one_quantize(&mut self, outputs: &[Id]) -> bool {+        let readers = Readers::of(&self.nodes, self.shapes.len());         let folded = (0..self.nodes.len()).find_map(|i| {             // The quantize's input, its scale, and its own output, which the             // rounded value moves onto. All `Copy`, so the borrow ends here.@@ -69,13 +70,13 @@ impl<'a> Builder<'a> {             }             // The producer's index. `None` for anything that is not a             // quant-fusable store, or one that already carries a scale.-            let index = quant_producer_of(&self.nodes, produced)?;+            let index = readers+                .writer(produced)+                .filter(|&w| quant_producer_of(&self.nodes[w..=w], produced).is_some())?;             // The producer's output must reach exactly this quantize: a second             // reader, or the plan holding it as an output, keeps the quantize             // unfolded. Same rule as the elementwise fold.-            let single = self.nodes.iter().enumerate()-                .filter(|(j, _)| *j != index && *j != i)-                .all(|(_, node)| !node.inputs().contains(&produced))+            let single = readers.only_readers(&self.nodes, produced, [index, i])                 && !outputs.contains(&produced);             single.then_some((i, index, scale, out))         });
library/ml/src/main/rust/src/nets/mod_part15.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part15.rs b/library/ml/src/main/rust/src/nets/mod_part15.rsnew file mode 100644index 0000000000..f08615319b--- /dev/null+++ b/library/ml/src/main/rust/src/nets/mod_part15.rs@@ -0,0 +1,56 @@+// Reader and writer indexes for `Builder`'s fold passes.+//+// `fuse_elementwise` and `fuse_quantize` ask, per candidate, which node writes a tensor and how many+// nodes read it. Answered by scanning the node list, that made each fold step quadratic: 30 of the+// 32 ms a Gemma 4 prefill plan took to build on a PC. These answer the same questions from one pass+// per fold step, with the same first-match semantics as the scans they replace.++/// For one snapshot of `nodes`: how many nodes read each tensor, and the first node writing it.+struct Readers {+    /// Per tensor id, the number of nodes whose inputs include it (a node counts once).+    count: Vec<u32>,+    /// Per tensor id, the index of the first node whose output it is.+    writer: Vec<Option<usize>>,+}++impl Readers {+    fn of(nodes: &[Node], tensors: usize) -> Readers {+        let mut count = vec![0u32; tensors];+        let mut writer = vec![None; tensors];+        for (index, node) in nodes.iter().enumerate() {+            let mut inputs = node.inputs();+            inputs.sort_unstable_by_key(|id| id.0);+            inputs.dedup();+            for id in inputs {+                if let Some(slot) = count.get_mut(id.0) {+                    *slot += 1;+                }+            }+            if let Some(slot) = writer.get_mut(node.out().0) {+                slot.get_or_insert(index);+            }+        }+        Readers { count, writer }+    }++    /// The first node writing `id`, as `nodes.iter().position(|n| n.out() == id)`.+    fn writer(&self, id: Id) -> Option<usize> {+        self.writer.get(id.0).copied().flatten()+    }++    /// Whether no node other than `skip` (two indices) reads `id`.+    fn only_readers(&self, nodes: &[Node], id: Id, skip: [usize; 2]) -> bool {+        let mut others = self.count.get(id.0).copied().unwrap_or(0);+        let mut seen = [usize::MAX; 2];+        for (slot, index) in skip.into_iter().enumerate() {+            if seen.contains(&index) {+                continue;+            }+            seen[slot] = index;+            if nodes.get(index).is_some_and(|node| node.inputs().contains(&id)) {+                others = others.saturating_sub(1);+            }+        }+        others == 0+    }+}
library/ml/src/main/rust/src/nets/mod_part7.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part7.rs b/library/ml/src/main/rust/src/nets/mod_part7.rsindex 5062b647e3..e69fa4a018 100644--- a/library/ml/src/main/rust/src/nets/mod_part7.rs+++ b/library/ml/src/main/rust/src/nets/mod_part7.rs@@ -358,6 +358,12 @@ impl<'a> Builder<'a> {      /// One fold, or `false` when no binary qualifies.     fn fuse_one_elementwise(&mut self, outputs: &[Id]) -> bool {+        let readers = Readers::of(&self.nodes, self.shapes.len());+        let producer_of = |nodes: &[Node], id: Id| {+            readers.writer(id).filter(|&w| {+                matches!(nodes[w], Node::Conv { .. } | Node::ConvInt8 { .. } | Node::RmsNorm { .. })+            })+        };         let folded = (0..self.nodes.len()).find_map(|i| {             // The producer's index, the tensor it produced, the addend that folds, and             // the binary's own output, which the sum moves onto. All `Copy`, so the@@ -401,9 +407,7 @@ impl<'a> Builder<'a> {                 while let Some(next) = stack.pop() {                     // No producing node: an input or a host tensor, written before the                     // pass runs, so always ready.-                    let Some(node_index) =-                        self.nodes.iter().position(|node| node.out() == next)-                    else {+                    let Some(node_index) = readers.writer(next) else {                         continue;                     };                     if node_index >= index {@@ -422,9 +426,7 @@ impl<'a> Builder<'a> {             }             // The producer's output must reach exactly this binary: a second reader, or             // the plan holding it as an output, keeps the add unfolded.-            let single = self.nodes.iter().enumerate()-                .filter(|(j, _)| *j != index && *j != i)-                .all(|(_, node)| !node.inputs().contains(&produced))+            let single = readers.only_readers(&self.nodes, produced, [index, i])                 && !outputs.contains(&produced);             single.then_some((i, index, residual, shift, out))         });