Modern Apps git

← Modern-Apps.git

ml: build OCR batch recognisers on first multi-line request, not at load

Commit
23c9ff3fae0a1d636539456325d0a3144d7c0650
Author
vayun-mathur <[email protected]>
When
2026-10-26 04:05 UTC (1 month ago)
Parents
4860e4d

Diff

library/ml/src/main/rust/examples/profile_vision.rs
diff --git a/library/ml/src/main/rust/examples/profile_vision.rs b/library/ml/src/main/rust/examples/profile_vision.rsindex e6b667f6c2..b73257ba7b 100644--- a/library/ml/src/main/rust/examples/profile_vision.rs+++ b/library/ml/src/main/rust/examples/profile_vision.rs@@ -273,9 +273,18 @@ fn profile_rec_batch(path: &str, passes: u32) -> Result<(), String> {     const LINES: u32 = 8;     let weights = load(path, graph::PPOCR_REC)?;     let context = context::shared()?;+    let t = Instant::now();     let mut single = Net::new(context.clone(), ppocr_rec::build(&weights, REC_WIDTH)?, &weights, PPOCR_REC)?;+    println!("load      single {:.1} ms", since(t));+    for lines in [2u32, 4] {+        let t = Instant::now();+        let _net = Net::new(context.clone(), ppocr_rec::build_batch(&weights, REC_WIDTH, lines)?, &weights, PPOCR_REC)?;+        println!("load      batch of {lines} {:.1} ms", since(t));+    }+    let t = Instant::now();     let mut batch =         Net::new(context, ppocr_rec::build_batch(&weights, REC_WIDTH, LINES)?, &weights, PPOCR_REC)?;+    println!("load      batch of {LINES} {:.1} ms", since(t));     let len = ppocr_rec::HEIGHT as usize * REC_WIDTH as usize;     let strips: Vec<Vec<i32>> = (0..LINES as usize)         .map(|i| (0..len).map(|p| (0xff00_0000u32 | ((p * 37 + i * 101) as u32 * 2_654_435_761 >> 8)) as i32).collect())
library/ml/src/main/rust/src/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsindex 7653d06c32..d5a258a11e 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -379,7 +379,7 @@ fn detect(state: &mut Handle, width: u32, height: u32) -> Result<Vec<f32>, Strin struct OcrHandle {     det: Net,     rec: Net,-    rec_batches: Vec<(u32, Net)>,+    rec_batches: RecBatches,     dictionary: Dictionary,     pixels: Vec<i32>, }@@ -438,8 +438,8 @@ fn build_ocr<'l>(     let rec_plan = ppocr_rec::build(&rec_weights, ocr::REC_WIDTH)?;     Ok(OcrHandle {         det: Net::new(shared.clone(), det_plan, &det_weights, PPOCR_DET)?,-        rec_batches: rec_batch_nets(&shared, &rec_weights)?,-        rec: Net::new(shared, rec_plan, &rec_weights, PPOCR_REC)?,+        rec: Net::new(shared.clone(), rec_plan, &rec_weights, PPOCR_REC)?,+        rec_batches: RecBatches { shared, weights: rec_weights, nets: Vec::new() },         dictionary,         pixels: Vec::new(),     })
library/ml/src/main/rust/src/bridge_part10.rs
diff --git a/library/ml/src/main/rust/src/bridge_part10.rs b/library/ml/src/main/rust/src/bridge_part10.rsindex c09060a42c..a7ea33e7f5 100644--- a/library/ml/src/main/rust/src/bridge_part10.rs+++ b/library/ml/src/main/rust/src/bridge_part10.rs@@ -274,25 +274,43 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyMa     drop(unsafe { Box::from_raw(handle as *mut MadladHandle) }); } -/// Recogniser batch sizes built at OCR load, largest first. A request's strips go through the-/// largest that fits, then smaller ones, then the single-line net, so a 10-line page is two-/// submits rather than ten (each submit costs ~4 ms on a Pixel 8 beyond its GPU time).+/// Recogniser batch sizes, largest first. A request's strips go through the largest that fits,+/// then smaller ones, then the single-line net, so a 10-line page is two submits rather than ten+/// (each submit costs ~4 ms on a Pixel 8 beyond its GPU time). const REC_BATCHES: [u32; 3] = [8, 4, 2]; -/// The batched recognisers for [`REC_BATCHES`]: independent copies of the pass in one plan.-fn rec_batch_nets(shared: &std::sync::Arc<crate::vulkan::context::Context>, weights: &Weights) -> Result<Vec<(u32, Net)>, String> {-    let mut nets = Vec::with_capacity(REC_BATCHES.len());-    for lines in REC_BATCHES {-        let plan = ppocr_rec::build_batch(weights, ocr::REC_WIDTH, lines)?;-        nets.push((lines, Net::new(shared.clone(), plan, weights, PPOCR_REC)?));+/// The batched recognisers for [`REC_BATCHES`], independent copies of the pass in one plan each.+/// Built on the first request with more than one line: the three cost 48-78 ms on a Pixel 8,+/// which a single-word request should not pay at load.+struct RecBatches {+    shared: std::sync::Arc<crate::vulkan::context::Context>,+    weights: Weights,+    nets: Vec<(u32, Net)>,+}++impl RecBatches {+    fn nets(&mut self, lines: usize) -> Result<&mut [(u32, Net)], String> {+        if self.nets.is_empty() && lines > 1 {+            for batch in REC_BATCHES {+                let plan = ppocr_rec::build_batch(&self.weights, ocr::REC_WIDTH, batch)?;+                self.nets.push((batch, Net::new(self.shared.clone(), plan, &self.weights, PPOCR_REC)?));+            }+        }+        Ok(&mut self.nets)     }-    Ok(nets) }  /// Recognise every strip, one result per strip in order. Each line's logits are identical to a /// single-line run: the batch plans are independent copies, and the strip is preprocessed by the /// same `to_planar_f16` and rounded to the same fp16 on the way in.-fn recognise_all(rec: &mut Net, batches: &mut [(u32, Net)], strips: &[Vec<i32>]) -> Vec<Result<Vec<f32>, String>> {+fn recognise_all(rec: &mut Net, batches: &mut RecBatches, strips: &[Vec<i32>]) -> Vec<Result<Vec<f32>, String>> {+    let batches = match batches.nets(strips.len()) {+        Ok(nets) => nets,+        Err(e) => {+            log(&format!("batched recognisers unavailable, one line at a time: {e}"));+            &mut []+        }+    };     let mut out = Vec::with_capacity(strips.len());     let mut rest = strips;     while let Some((first, tail)) = rest.split_first() {