ml: batch OCR recognition lines into one submit, 8 lines 217 -> 136 ms
- Commit
4860e4ddbc039df020f83f1763ea328700d8177d- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 03:56 UTC (1 month ago)
- Parents
1adb9b4
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 a28858bd32..e6b667f6c2 100644--- a/library/ml/src/main/rust/examples/profile_vision.rs+++ b/library/ml/src/main/rust/examples/profile_vision.rs@@ -21,7 +21,7 @@ use modelrunner::nets::{ maia, mobilefacenet, modnet, ppocr_det, ppocr_rec, scrfd, selfie, tinyclip, u2netp, Plan, }; use modelrunner::post::ocr::REC_WIDTH;-use modelrunner::preprocess::{RESCALE_ONLY, PPOCR_REC};+use modelrunner::preprocess::{f16_to_f32, to_planar_f16, PPOCR_REC, RESCALE_ONLY}; use modelrunner::vulkan::context; use modelrunner::vulkan::reshape::Reshaped; use modelrunner::vulkan::run::Net;@@ -44,6 +44,7 @@ fn main() { ("mbf", "w600k_mbf.maml", 5), ("det", "ppocr_det.maml", 2), ("rec", "ppocr_rec.maml", 5),+ ("rec_batch", "ppocr_rec.maml", 5), ("clip_image", "clip/tinyclip.maml", 3), ("clip_text", "clip/tinyclip.maml", 5), ("maia", "maia3-5m.maml", 3),@@ -63,6 +64,7 @@ fn main() { "mbf" => profile_mbf(&path, *passes), "det" => profile_det(&path, *passes), "rec" => profile_rec(&path, *passes),+ "rec_batch" => profile_rec_batch(&path, *passes), "clip_image" => profile_clip_image(&path, *passes), "clip_text" => profile_clip_text(&path, *passes), "maia" => profile_maia(&path, *passes),@@ -266,6 +268,48 @@ fn profile_rec(path: &str, passes: u32) -> Result<(), String> { report("rec", &mut net, &input, &input_b, passes) } +/// Eight lines one submit each against one batched submit; the logits must match bit for bit.+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 mut single = Net::new(context.clone(), ppocr_rec::build(&weights, REC_WIDTH)?, &weights, PPOCR_REC)?;+ let mut batch =+ Net::new(context, ppocr_rec::build_batch(&weights, REC_WIDTH, LINES)?, &weights, PPOCR_REC)?;+ 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())+ .collect();+ let shape = modelrunner::nets::Shape::new(3, ppocr_rec::HEIGHT, REC_WIDTH);+ let mut half = vec![0u16; shape.len() as usize];+ let mut inputs = Vec::new();+ for strip in &strips {+ to_planar_f16(strip, REC_WIDTH, ppocr_rec::HEIGHT, shape, &PPOCR_REC, &mut half)?;+ inputs.push(half.iter().map(|&h| f16_to_f32(h)).collect::<Vec<f32>>());+ }+ let refs: Vec<&[f32]> = inputs.iter().map(Vec::as_slice).collect();+ let (mut one, mut many) = (Vec::new(), Vec::new());+ let mut expected = Vec::new();+ for _ in 0..=passes {+ let t = Instant::now();+ expected = strips+ .iter()+ .map(|s| single.infer(s, REC_WIDTH, ppocr_rec::HEIGHT))+ .collect::<Result<Vec<_>, _>>()?;+ one.push(since(t));+ let t = Instant::now();+ let got = batch.infer_raw_many(&refs)?;+ many.push(since(t));+ if expected != got {+ return Err("a batched line's logits differ from its single run".into());+ }+ }+ println!("single {} for {LINES} lines", stats(&one[1..]));+ println!("batched {} for {LINES} lines (identical logits)", stats(&many[1..]));+ print_checksums(&expected);+ Ok(())+}+ fn tinyclip_plan(offsets: &Offsets, mode: tinyclip::Mode) -> Result<Plan, String> { tinyclip::build(offsets, mode) }
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 1258c33709..7653d06c32 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -379,6 +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)>, dictionary: Dictionary, pixels: Vec<i32>, }@@ -437,6 +438,7 @@ 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)?, dictionary, pixels: Vec::new(),
library/ml/src/main/rust/src/bridge_part1.rs
diff --git a/library/ml/src/main/rust/src/bridge_part1.rs b/library/ml/src/main/rust/src/bridge_part1.rsindex 5b690c621f..b153868d8c 100644--- a/library/ml/src/main/rust/src/bridge_part1.rs+++ b/library/ml/src/main/rust/src/bridge_part1.rs@@ -68,12 +68,12 @@ fn read_text(state: &mut OcrHandle, width: u32, height: u32) -> Result<Vec<Line> let (map_w, map_h) = state.det.output_size()?; // Disjoint field borrows: the recogniser is taken mutably while the pixels and the // dictionary are read, which is why this is not `state.rec.infer(...)` inline.- let OcrHandle { rec, dictionary, pixels, .. } = state;- ocr::lines(+ let OcrHandle { rec, rec_batches, dictionary, pixels, .. } = state;+ ocr::lines_batched( &ocr::Detection { probability, width: map_w, height: map_h, fit: &fit }, &ocr::Source { pixels, width, height }, dictionary,- |crop, crop_w, crop_h| rec.infer(crop, crop_w, crop_h),+ |strips| recognise_all(rec, rec_batches, strips), ) }
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 c4c984baa3..c09060a42c 100644--- a/library/ml/src/main/rust/src/bridge_part10.rs+++ b/library/ml/src/main/rust/src/bridge_part10.rs@@ -273,3 +273,53 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyMa // destroyed. `Net`'s Drop waits for the device to go idle before freeing. 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).+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)?));+ }+ 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>> {+ let mut out = Vec::with_capacity(strips.len());+ let mut rest = strips;+ while let Some((first, tail)) = rest.split_first() {+ let fit = batches.iter_mut().find(|(lines, _)| *lines as usize <= rest.len());+ if let Some((lines, net)) = fit {+ let (now, later) = rest.split_at(*lines as usize);+ match infer_batch(net, now) {+ Ok(logits) => out.extend(logits.into_iter().map(Ok)),+ Err(e) => out.extend(now.iter().map(|_| Err(e.clone()))),+ }+ rest = later;+ } else {+ out.push(rec.infer(first, ocr::REC_WIDTH, ppocr_rec::HEIGHT));+ rest = tail;+ }+ }+ out+}++fn infer_batch(net: &mut Net, strips: &[Vec<i32>]) -> Result<Vec<Vec<f32>>, String> {+ let shape = crate::nets::Shape::new(3, ppocr_rec::HEIGHT, ocr::REC_WIDTH);+ let mut half = vec![0u16; shape.len() as usize];+ let mut inputs = Vec::with_capacity(strips.len());+ for strip in strips {+ crate::preprocess::to_planar_f16(strip, ocr::REC_WIDTH, ppocr_rec::HEIGHT, shape, &PPOCR_REC, &mut half)?;+ inputs.push(half.iter().map(|&h| crate::preprocess::f16_to_f32(h)).collect::<Vec<f32>>());+ }+ let refs: Vec<&[f32]> = inputs.iter().map(Vec::as_slice).collect();+ net.infer_raw_many(&refs)+}\ No newline at end of file
library/ml/src/main/rust/src/nets/ppocr_rec.rs
diff --git a/library/ml/src/main/rust/src/nets/ppocr_rec.rs b/library/ml/src/main/rust/src/nets/ppocr_rec.rsindex cadc227508..80d1d2cf18 100644--- a/library/ml/src/main/rust/src/nets/ppocr_rec.rs+++ b/library/ml/src/main/rust/src/nets/ppocr_rec.rs@@ -221,7 +221,7 @@ pub(crate) fn block(b: &mut Builder, l: &mut Layers, x: Id) -> Id { /// Build the recognition pass. Implemented in [`super::ppocr_rec_extra`] to keep this /// file under the size limit; re-exported so `ppocr_rec::build` keeps working.-pub use super::ppocr_rec_extra::build;+pub use super::ppocr_rec_extra::{build, build_batch}; #[cfg(test)] mod tests {
library/ml/src/main/rust/src/nets/ppocr_rec_extra.rs
diff --git a/library/ml/src/main/rust/src/nets/ppocr_rec_extra.rs b/library/ml/src/main/rust/src/nets/ppocr_rec_extra.rsindex 0fd1dc620c..61002bffca 100644--- a/library/ml/src/main/rust/src/nets/ppocr_rec_extra.rs+++ b/library/ml/src/main/rust/src/nets/ppocr_rec_extra.rs@@ -9,7 +9,6 @@ use super::ppocr_rec::{along_sequence, block, depthwise, point, squeeze_excite}; /// `width` must be a positive multiple of [`WIDTH_MULTIPLE`]; the output is /// `[LOGITS, 1, width / 8]`. pub fn build(weights: &dyn WeightSource, width: u32) -> Result<Plan, String> {- use super::ppocr_rec::Layers; if width == 0 || !width.is_multiple_of(WIDTH_MULTIPLE) { return Err(format!( "a recognition width of {width}: three stride-2 stages act on it, so it must \@@ -17,10 +16,31 @@ pub fn build(weights: &dyn WeightSource, width: u32) -> Result<Plan, String> { )); } - let l = &mut Layers { next: 0 }; let mut builder = Builder::new(weights);- let b = &mut builder;- let input = b.input(Shape::new(3, HEIGHT, width));+ let input = builder.input(Shape::new(3, HEIGHT, width));+ let logits = chain(&mut builder, input)?;+ builder.finish(&[logits])+}++/// [`build`] for `lines` crops at once: independent copies of the pass in one plan, so a+/// whole OCR request's lines are one submit. Input and output `i` are line `i`'s.+pub fn build_batch(weights: &dyn WeightSource, width: u32, lines: u32) -> Result<Plan, String> {+ if width == 0 || !width.is_multiple_of(WIDTH_MULTIPLE) || lines == 0 {+ return Err(format!("a batch of {lines} recognitions at width {width}"));+ }+ let mut builder = Builder::new(weights);+ let inputs: Vec<Id> = (0..lines).map(|_| builder.input(Shape::new(3, HEIGHT, width))).collect();+ let mut outputs = Vec::with_capacity(inputs.len());+ for input in inputs {+ outputs.push(chain(&mut builder, input)?);+ }+ builder.finish(&outputs)+}++/// One crop's pass from its input to its logits, reading every tensor once.+fn chain(b: &mut Builder, input: Id) -> Result<Id, String> {+ use super::ppocr_rec::Layers;+ let l = &mut Layers { next: 0 }; let affine = |b: &mut Builder, x: Id, which: usize| -> Id { let (scale, shift) = AFFINES[which]; b.affine(x, scale, shift)@@ -108,5 +128,5 @@ pub fn build(weights: &dyn WeightSource, width: u32) -> Result<Plan, String> { if l.next != TENSORS { return Err(format!("the forward pass claims {} tensors, not {TENSORS}", l.next)); }- builder.finish(&[logits])+ Ok(logits) }
library/ml/src/main/rust/src/post/ocr.rs
diff --git a/library/ml/src/main/rust/src/post/ocr.rs b/library/ml/src/main/rust/src/post/ocr.rsindex 2b12d385e4..b8079d5af3 100644--- a/library/ml/src/main/rust/src/post/ocr.rs+++ b/library/ml/src/main/rust/src/post/ocr.rs@@ -89,6 +89,20 @@ pub fn lines( source: &Source, dictionary: &Dictionary, mut recognise: impl FnMut(&[i32], u32, u32) -> Result<Vec<f32>, String>,+) -> Result<Vec<Line>, String> {+ lines_batched(detection, source, dictionary, |strips| {+ strips.iter().map(|strip| recognise(strip, REC_WIDTH, ppocr_rec::HEIGHT)).collect()+ })+}++/// [`lines`] with every strip handed over at once, `REC_WIDTH x HEIGHT` each, so the device can+/// recognise a request's lines in a few submits instead of one per line. `recognise` returns one+/// result per strip, in order; a failed strip is skipped like a failed crop.+pub fn lines_batched(+ detection: &Detection,+ source: &Source,+ dictionary: &Dictionary,+ recognise: impl FnOnce(&[Vec<i32>]) -> Vec<Result<Vec<f32>, String>>, ) -> Result<Vec<Line>, String> { let regions = dbnet::regions( detection.probability,@@ -97,19 +111,20 @@ pub fn lines( detection.fit, (source.width, source.height), )?;- let mut lines = Vec::with_capacity(regions.len());+ let mut pending = Vec::with_capacity(regions.len());+ let mut strips = Vec::with_capacity(regions.len()); for region in ®ions { let corners = crop::corners(®ion.rect); let content = crop::crop_width(region, ppocr_rec::HEIGHT, ppocr_rec::WIDTH_MULTIPLE, REC_WIDTH);- let strip = match strip(source, &corners, content) {- Ok(s) => s,- Err(_) => continue,- };- let logits = match recognise(&strip, REC_WIDTH, ppocr_rec::HEIGHT) {- Ok(l) => l,- Err(_) => continue,- };+ if let Ok(s) = strip(source, &corners, content) {+ strips.push(s);+ pending.push((corners, content, region.vertical));+ }+ }+ let mut lines = Vec::with_capacity(pending.len());+ for ((corners, content, vertical), logits) in pending.into_iter().zip(recognise(&strips)) {+ let Ok(logits) = logits else { continue }; // Only the timesteps the crop actually filled; the rest is padding. let used = (content / ppocr_rec::WIDTH_MULTIPLE) as usize; let Decoded { text, confidence } = match ctc::decode(&logits, used, dictionary) {@@ -120,7 +135,7 @@ pub fn lines( if text.is_empty() { continue; }- lines.push(Line { text, confidence, corners, vertical: region.vertical });+ lines.push(Line { text, confidence, corners, vertical }); } order(&mut lines); Ok(lines)