library:ml: PP-OCRv5 recognition, and fix an affine fold over padding
- Commit
f06b4a3179f2ca7f4411135bf58deb616535b99b- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 20:07 UTC (3 months ago)
- Parents
a03f364
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 c60fbc40f2..08c75eabaf 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -154,10 +154,24 @@ pub enum Kind { /// /// One pass over the data for two multiplies. It exists because these sit *after* an /// activation, so unlike everything else constant in that export they cannot be- /// folded into the preceding convolution's weight — and pushing them into the- /// *following* one needs `b' += shift * sum(W)` per output row, which is only valid- /// when the tensor feeds nothing but convolutions. 24 uses in detection, of which 23- /// do fold, leaving one.+ /// folded into the preceding convolution's weight.+ ///+ /// # Why they cannot all fold forward either+ ///+ /// Pushing one into the *following* convolution looks free: `conv(a * x + t)[m]` is+ /// `a * conv(x)[m] + t * sum(W[m])`. That identity holds at an interior pixel and+ /// **fails at a border one**, because a padded convolution reads zero outside the+ /// input rather than `t`, so the constant's real contribution there is `t` times the+ /// sum of only the in-bounds taps. The correction varies per output position, so it is+ /// not a bias and there is no fold.+ ///+ /// `scripts/ml/ppocr_fold.py` therefore folds an affine only into an *unpadded*+ /// convolution, which leaves 14 in detection and 16 in recognition — all of them+ /// feeding either a padded depthwise or a squeeze-excite's two branches.+ ///+ /// Getting this wrong is invisible to every structural check: the layer table, the+ /// tensor count and the digest are all unchanged, and only the weight *values* differ.+ /// `scripts/ml/onnx_parity.py` is what caught it. Affine, /// Layer normalisation **over the channel axis**, with a per-channel affine. ///
library/ml/src/main/rust/src/nets/ppocr_det.rs
diff --git a/library/ml/src/main/rust/src/nets/ppocr_det.rs b/library/ml/src/main/rust/src/nets/ppocr_det.rsindex 40fa2563fc..234c9024f4 100644--- a/library/ml/src/main/rust/src/nets/ppocr_det.rs+++ b/library/ml/src/main/rust/src/nets/ppocr_det.rs@@ -60,14 +60,37 @@ const NECK: u32 = 96; /// Channels each head branch produces, four of which concatenate back to [`NECK`]. const HEAD: u32 = 24; -/// The one surviving learnable affine block's scale, from the folded graph.+/// The learnable affine blocks that survive the fold, in graph order. ///-/// It is a *weight*, not a hyperparameter — it is here rather than in the `.vkml` because-/// `.vkml` holds tensors and this is a scalar, and putting a one-element tensor in the-/// table for it would mean the whole ordered table shifted by one.-const AFFINE_SCALE: f32 = 1.2535226345062256;-/// Its shift.-const AFFINE_SHIFT: f32 = -1.0351486206054688;+/// `scripts/ml/ppocr_fold.py` pushes an affine into the convolution it feeds wherever that+/// is exact, which is wherever the convolution is **unpadded**. These fourteen are the ones+/// that are not: twelve feed a padded depthwise, and two feed a squeeze-excite's pool and+/// multiply at once.+///+/// The padding is the reason. `conv(a * x + t)` is `a * conv(x) + t * sum(W)` at an+/// interior pixel, but a padded convolution reads zero rather than `t` outside the input,+/// so the constant's real contribution at the border is `t` times the sum of only the+/// in-bounds taps — position-dependent, and therefore not a bias. Folding anyway biases+/// the border of every feature map and compounds down the backbone.+///+/// They are scalars, so they live here rather than in the `.vkml`, which holds tensors:+/// putting a one-element tensor in the table for each would shift the whole ordered table.+const AFFINES: [(f32, f32); 14] = [+ (0.6775133, -0.22914815),+ (0.36771294, -0.87113833),+ (1.4989212, -0.5550208),+ (0.5583892, -0.9510202),+ (1.5417316, -0.05748394),+ (0.6538819, -0.815451),+ (0.790457, -0.1132517),+ (0.72976404, 0.04859176),+ (0.8216482, 0.1775174),+ (1.3613669, 0.18224998),+ (0.9679641, 0.13799295),+ (1.2535226, -1.0351486),+ (0.919406, 0.25822622),+ (0.93593925, 0.16590087),+]; /// Hands out `.vkml` tensor indices in the order the layers appear. Every folded layer is /// a convolution with a weight and a bias, so this steps by two throughout.@@ -138,6 +161,15 @@ fn residual_excite(b: &mut Builder, l: &mut Layers, x: Id, reduce: u32) -> Id { /// Compile the forward pass for an input of `height` x `width`. pub fn build(weights: &dyn WeightSource, height: u32, width: u32) -> Result<Plan, String> {+ compile(weights, height, width, false)+}++fn compile(+ weights: &dyn WeightSource,+ height: u32,+ width: u32,+ backbone: bool,+) -> Result<Plan, String> { if height == 0 || width == 0 { return Err(format!("a {width}x{height} input")); }@@ -154,46 +186,56 @@ pub fn build(weights: &dyn WeightSource, height: u32, width: u32) -> Result<Plan let input = b.input(Shape::new(3, height, width)); // Backbone. Stem to 1/2, then depthwise/pointwise stages; the branch is always the- // last pointwise before a stride-2 depthwise.+ // last pointwise before a stride-2 depthwise, taken *after* that stage's affine+ // because the export's lateral reads the affined tensor rather than the convolution's+ // own output. let x = spatial_strided(&mut b, l, input, 16, 2, Act::None); let x = depthwise(&mut b, l, x, 3, 1, Act::HardSwish); let x = point(&mut b, l, x, 32, Act::HardSwish);+ let x = affine(&mut b, x, 0); let x = depthwise(&mut b, l, x, 3, 2, Act::None); let x = point(&mut b, l, x, 48, Act::HardSwish);+ let x = affine(&mut b, x, 1); let x = depthwise(&mut b, l, x, 3, 1, Act::HardSwish); // 1/4, 48 channels.- let c2 = point(&mut b, l, x, 48, Act::HardSwish);+ let x = point(&mut b, l, x, 48, Act::HardSwish);+ let c2 = affine(&mut b, x, 2); let x = depthwise(&mut b, l, c2, 3, 2, Act::None); let x = point(&mut b, l, x, 96, Act::HardSwish);+ let x = affine(&mut b, x, 3); let x = depthwise(&mut b, l, x, 3, 1, Act::HardSwish); // 1/8, 96 channels.- let c3 = point(&mut b, l, x, 96, Act::HardSwish);+ let x = point(&mut b, l, x, 96, Act::HardSwish);+ let c3 = affine(&mut b, x, 4); let mut x = depthwise(&mut b, l, c3, 3, 2, Act::None); // Four 5x5 depthwise/pointwise pairs at 192 channels.- for _ in 0..4 {+ for index in 0..4 { x = point(&mut b, l, x, 192, Act::HardSwish);+ x = affine(&mut b, x, 5 + index); x = depthwise(&mut b, l, x, 5, 1, Act::HardSwish); } // 1/16, 192 channels. The loop above ends on a depthwise, so the branch is the // pointwise that closes the stage.- let c4 = point(&mut b, l, x, 192, Act::HardSwish);+ let x = point(&mut b, l, x, 192, Act::HardSwish);+ let c4 = affine(&mut b, x, 9); let x = depthwise(&mut b, l, c4, 5, 2, Act::None); let x = squeeze_excite(&mut b, l, x, 48); let x = point(&mut b, l, x, 384, Act::HardSwish);+ let x = affine(&mut b, x, 10); let x = depthwise(&mut b, l, x, 5, 1, Act::HardSwish);- // The one learnable affine block the fold could not absorb: its output feeds both the- // squeeze-excite's pool and its multiply, so it is not a single-convolution consumer.- let x = b.affine(x, AFFINE_SCALE, AFFINE_SHIFT);+ let x = affine(&mut b, x, 11); let mut x = squeeze_excite(&mut b, l, x, 96);- for _ in 0..2 {+ for index in 0..2 { x = point(&mut b, l, x, 384, Act::HardSwish);+ x = affine(&mut b, x, 12 + index); x = depthwise(&mut b, l, x, 5, 1, Act::HardSwish); }- // 1/32, 384 channels.+ // 1/32, 384 channels. The only stage whose branch has no affine after it — the+ // export's coarsest lateral reads this convolution's output directly. let c5 = point(&mut b, l, x, 384, Act::HardSwish); // Neck laterals, in the export's order: fine to coarse, and each to its own width.@@ -235,9 +277,26 @@ pub fn build(weights: &dyn WeightSource, height: u32, width: u32) -> Result<Plan let x = b.conv_transpose(x, l.take(), HEAD, (2, 2), (2, 2), (0, 0, 0, 0), Act::Relu); let probability = b.conv_transpose(x, l.take(), 1, (2, 2), (2, 2), (0, 0, 0, 0), Act::Sigmoid);+ if backbone {+ return b.finish(&[probability, c5]);+ } b.finish(&[probability]) } +/// [`build`], plus the backbone's output as a second binding.+///+/// Only for `scripts/ml/onnx_parity.py`: detection's own output is a text probability that+/// saturates to zero on a synthetic input, so comparing it against the export compares+/// zeros. `c5` is where all fourteen of the surviving [`AFFINES`] are, which is the part a+/// numerical check needs to see.+pub fn build_with_backbone(+ weights: &dyn WeightSource,+ height: u32,+ width: u32,+) -> Result<Plan, String> {+ compile(weights, height, width, true)+}+ /// A 3x3 convolution at `stride`, for the stem. fn spatial_strided( b: &mut Builder,@@ -250,6 +309,12 @@ fn spatial_strided( b.conv(x, l.take(), out, (3, 3), (stride, stride), (1, 1), (1, 1, 1, 1), 1, act) } +/// One of the [`AFFINES`], by position in the folded graph.+fn affine(b: &mut Builder, x: Id, which: usize) -> Id {+ let (scale, shift) = AFFINES[which];+ b.affine(x, scale, shift)+}+ /// A neck level: 1x1 to [`NECK`] channels, then a residual squeeze-excite at 24. fn project_excite(b: &mut Builder, l: &mut Layers, x: Id) -> Id { let projected = point(b, l, x, NECK, Act::None);@@ -291,7 +356,7 @@ mod tests { assert_eq!(dispatches(&plan, Kind::MulBroadcast), 10); assert_eq!(dispatches(&plan, Kind::Add), 11); assert_eq!(dispatches(&plan, Kind::ResizeNearest), 6);- assert_eq!(dispatches(&plan, Kind::Affine), 1);+ assert_eq!(dispatches(&plan, Kind::Affine), 14); // The export's six `Resize` nodes are all nearest, so the bilinear pipeline must // not appear anywhere. assert_eq!(dispatches(&plan, Kind::Resize), 0);
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 0d445807a9..22fea1171a 100644--- a/library/ml/src/main/rust/src/nets/ppocr_rec.rs+++ b/library/ml/src/main/rust/src/nets/ppocr_rec.rs@@ -94,6 +94,40 @@ pub const LOGITS: u32 = crate::post::ctc::LOGITS as u32; /// the head including the classifier — `(33 + 2 + 16 + 1 + 4) * 2`. pub const TENSORS: usize = 112; +/// The learnable affine blocks that survive the fold, in graph order.+///+/// `scripts/ml/ppocr_fold.py` pushes an affine into the convolution it feeds wherever that+/// is exact, which is wherever the convolution is **unpadded**. These sixteen are the ones+/// that are not: thirteen feed a padded depthwise, two feed a squeeze-excite's pool and+/// multiply, and the last feeds the sequence pool.+///+/// The padding is the whole reason. `conv(a * x + t)` is `a * conv(x) + t * sum(W)` at an+/// interior pixel, but a padded convolution reads zero rather than `t` outside the input,+/// so the constant's real contribution at the border is `t` times the sum of only the+/// in-bounds taps. Folding anyway biases the border of every feature map — 27% of a 12x16+/// map at a 3x3 kernel — and it compounds. ncnn's conversion of this model runs all 100 of+/// these as explicit elementwise ops; sixteen is what is left after the exact ones fold.+///+/// They are scalars, so they live here rather than in the `.vkml`, which holds tensors.+const AFFINES: [(f32, f32); 16] = [+ (0.15316115, -0.25247484),+ (0.1658402, -0.41049767),+ (0.2158067, -0.13324346),+ (0.25548476, -0.3735239),+ (0.36402965, -0.035169836),+ (0.44559416, -0.27406755),+ (0.4579334, -0.15619978),+ (0.56647635, 0.074552566),+ (0.6249867, 0.1702801),+ (0.53231597, 0.17400852),+ (1.0831748, -1.0197166),+ (0.65120953, 0.05214425),+ (1.5772517, -1.7144594),+ (0.5974116, 0.17121108),+ (0.36693764, 0.11679397),+ (3.71384, -0.29614934),+];+ /// Hands out `.vkml` tensor indices in the order the layers appear. Every folded layer is /// a weight followed by a bias, including the layer norms, whose gamma and beta land in /// the same pair.@@ -201,25 +235,40 @@ pub fn build(weights: &dyn WeightSource, width: u32) -> Result<Plan, String> { let mut builder = Builder::new(weights); let b = &mut builder; let input = b.input(Shape::new(3, HEIGHT, width));-- // Stem: the only convolution that strides both axes.- let mut x = b.conv(input, l.take(), 16, (3, 3), (2, 2), (1, 1), (1, 1, 1, 1), 1, Act::HardSwish);-- // Six depthwise/pointwise pairs at 3x3, striding one axis at a time.- for (out, stride) in [+ let affine = |b: &mut Builder, x: Id, which: usize| -> Id {+ let (scale, shift) = AFFINES[which];+ b.affine(x, scale, shift)+ };++ // Stem. The only convolution that strides both axes, and the only one in the backbone+ // with **no** activation: the export puts its batch norm here and the affine and+ // HardSwish after the depthwise that follows.+ let mut x = b.conv(input, l.take(), 16, (3, 3), (2, 2), (1, 1), (1, 1, 1, 1), 1, Act::None);++ // Six depthwise/pointwise pairs at 3x3, striding one axis at a time. Each pair after+ // the first is preceded by an affine, because the depthwise it feeds is padded; the+ // first is not, because the stem it follows has no affine to leave behind.+ for (index, (out, stride)) in [ (32, (1, 1)), (64, (1, 1)), (64, (1, 1)), (128, (2, 1)), (128, (1, 1)), (240, (1, 2)),- ] {+ ]+ .into_iter()+ .enumerate()+ {+ if index > 0 {+ x = affine(b, x, index - 1);+ } x = depthwise(b, l, x, 3, stride); x = point(b, l, x, out, Act::HardSwish); } // Four depthwise/pointwise pairs at 5x5, all at 240 channels.- for _ in 0..4 {+ for index in 0..4 {+ x = affine(b, x, 5 + index); x = depthwise(b, l, x, 5, (1, 1)); x = point(b, l, x, 240, Act::HardSwish); }@@ -227,18 +276,25 @@ pub fn build(weights: &dyn WeightSource, width: u32) -> Result<Plan, String> { // directly. There is no pointwise between the two — this is the one place the // backbone's depthwise/pointwise alternation breaks, and pairing it up regardless // reads every subsequent tensor one layer out of step.+ x = affine(b, x, 9); x = depthwise(b, l, x, 5, (2, 1));+ x = affine(b, x, 10); x = squeeze_excite(b, l, x, 60); x = point(b, l, x, FEATURES, Act::HardSwish);+ x = affine(b, x, 11); x = depthwise(b, l, x, 5, (1, 1));+ x = affine(b, x, 12); x = squeeze_excite(b, l, x, 120); x = point(b, l, x, FEATURES, Act::HardSwish);+ x = affine(b, x, 13); x = depthwise(b, l, x, 5, (2, 1)); x = point(b, l, x, FEATURES, Act::HardSwish);+ x = affine(b, x, 14); x = depthwise(b, l, x, 5, (1, 1)); x = point(b, l, x, FEATURES, Act::HardSwish);+ x = affine(b, x, 15); // Where a feature map becomes a sequence: the three surviving rows collapse to one // and the width halves a final time.@@ -354,12 +410,15 @@ mod tests { assert_eq!(counts.get("AttnApply"), Some(&2), "{counts:?}"); // Two residuals per block. assert_eq!(counts.get("Add"), Some(&4), "{counts:?}");+ // The sixteen learnable affine blocks that could not fold; see `AFFINES`.+ assert_eq!(counts.get("Affine"), Some(&16), "{counts:?}"); // The one concatenation, lowered to two copies and no shader. assert_eq!(copies, 2, "{counts:?}");- // Nothing else. In particular no `Affine`: unlike detection, every scalar affine- // in this export folds away, because each one feeds a convolution and nothing- // else.- assert_eq!(counts.len(), 9, "{counts:?}");+ // Nothing else. The op inventory below matches `ppocr_fold.py`'s, which is the+ // check that the transcription and the converter agree about the graph:+ // Conv 38 + Linear 13 = 51, LayerNorm 5, Affine 16, GlobalAveragePool 2,+ // Mul 2, AveragePool 1, MatMul 4, Softmax 2, Add 4, Concat 1.+ assert_eq!(counts.len(), 10, "{counts:?}"); } #[test]
library/ml/src/main/rust/src/nets/reference.rs
diff --git a/library/ml/src/main/rust/src/nets/reference.rs b/library/ml/src/main/rust/src/nets/reference.rsindex 66c031e6cf..043bbb7fd4 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -1746,6 +1746,57 @@ mod tests { ); } + /// Run a shipped net on an input from disk and write its output back, for+ /// `scripts/ml/onnx_parity.py` to compare against onnxruntime.+ ///+ /// Ignored, and a no-op without `PARITY_DIR`: it exists to be driven by that script,+ /// which needs the export's ONNX and an `onnxruntime` install that CI does not have.+ /// See the script's header for what the comparison is worth and what it has caught.+ #[test]+ #[ignore = "driven by scripts/ml/onnx_parity.py"]+ fn dump_reference_output() {+ let Ok(dir) = std::env::var("PARITY_DIR") else {+ return;+ };+ let dir = std::path::PathBuf::from(dir);+ let graph = std::env::var("PARITY_GRAPH").expect("PARITY_GRAPH");+ let width: u32 = std::env::var("PARITY_WIDTH")+ .expect("PARITY_WIDTH")+ .parse()+ .expect("a width");+ let raw = std::fs::read(dir.join("input.f32")).expect("the input");+ let input: Vec<f32> = raw+ .chunks_exact(4)+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))+ .collect();++ let (path, id) = match graph.as_str() {+ "ppocr_rec" => ("library/ocr/src/main/assets/ppocr_rec.vkml", crate::weights::graph::PPOCR_REC),+ "ppocr_det" => ("library/ocr/src/main/assets/ppocr_det.vkml", crate::weights::graph::PPOCR_DET),+ other => panic!("no parity probe for {other}"),+ };+ let bytes = asset(path).unwrap_or_else(|| panic!("{path} is not checked out"));+ let weights = crate::weights::Weights::parse(&bytes, id).expect("the asset parses");+ // Detection's own output is a saturated probability map, so the probe is its+ // backbone output — where all fourteen of its surviving affines are.+ let plan = match graph.as_str() {+ "ppocr_rec" => ppocr_rec::build(&weights, width).expect("ppocr_rec builds"),+ _ => ppocr_det::build_with_backbone(&weights, width, width).expect("det builds"),+ };+ let outputs = run_multi(&plan, weights.data(), &[&input]).expect("the net runs");+ let probe = match graph.as_str() {+ "ppocr_rec" => outputs.first(),+ _ => outputs.get(1),+ }+ .expect("a probe output");+ let mut out = Vec::with_capacity(probe.len() * 4);+ for value in probe {+ out.extend_from_slice(&value.to_le_bytes());+ }+ std::fs::write(dir.join("reference.f32"), out).expect("writes");+ println!("{graph} at {width}: wrote {} values", probe.len());+ }+ /// The shipped `.vkml` for `name`, or `None` if it is not checked out. fn asset(name: &str) -> Option<Vec<u8>> { let mut dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
library/ml/src/main/rust/tests/assets.rs
diff --git a/library/ml/src/main/rust/tests/assets.rs b/library/ml/src/main/rust/tests/assets.rsindex ff03acb2d0..d03b206942 100644--- a/library/ml/src/main/rust/tests/assets.rs+++ b/library/ml/src/main/rust/tests/assets.rs@@ -13,7 +13,7 @@ use std::path::{Path, PathBuf}; -use modelrunner::nets::{mobilefacenet, ppocr_det, scrfd, selfie, u2netp};+use modelrunner::nets::{mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, u2netp}; use modelrunner::post::ctc; use modelrunner::weights::{graph, Weights}; @@ -103,6 +103,34 @@ fn the_shipped_ppocr_det_asset_builds_the_ppocr_det_forward_pass() { ); } +#[test]+fn the_shipped_ppocr_rec_asset_builds_the_ppocr_rec_forward_pass() {+ let weights = load("library/ocr/src/main/assets/ppocr_rec.vkml", graph::PPOCR_REC);+ assert_eq!(weights.len(), ppocr_rec::TENSORS);+ // Building against the real file checks every one of the 112 tensors' shapes, because+ // `Builder::weight` asks for each by index *and* dimensions — so a converter that+ // transposed a linear, split the fused QKV projection the wrong way, or emitted a+ // layer norm's gamma and beta in the wrong order fails here rather than on device.+ let plan = ppocr_rec::build(&weights, 320)+ .expect("the shipped asset matches nets::ppocr_rec");+ assert_eq!(+ plan.output().expect("one output").shape,+ modelrunner::nets::Shape::new(ppocr_rec::LOGITS, 1, 40)+ );+}++#[test]+fn the_shipped_ppocr_rec_asset_builds_at_every_padded_line_width() {+ // A line crop is resized to 48 tall and padded to a multiple of 8, so the plan has to+ // lower at whatever width the batcher lands on.+ let weights = load("library/ocr/src/main/assets/ppocr_rec.vkml", graph::PPOCR_REC);+ for width in [8u32, 64, 160, 320, 640, 1024] {+ let plan = ppocr_rec::build(&weights, width)+ .unwrap_or_else(|e| panic!("at width {width}: {e}"));+ assert_eq!(plan.output().expect("one output").shape.w, width / 8);+ }+}+ #[test] fn the_shipped_character_dictionary_matches_the_recogniser_label_space() { // The model's final layer emits 838 logits positionally, so the dictionary's *length*
library/ocr/src/main/assets/README.md
diff --git a/library/ocr/src/main/assets/README.md b/library/ocr/src/main/assets/README.mdindex 36da9246e4..0a9d7a279f 100644--- a/library/ocr/src/main/assets/README.md+++ b/library/ocr/src/main/assets/README.md@@ -25,10 +25,15 @@ feature-pyramid residuals and the squeeze-excite gates. `scripts/ml/ppocr_fold.py` folds the constant part ahead of time: the bias, the batch norms, the affine blocks that precede an activation, and `HardSigmoid`'s α and β all go into each convolution's weight and bias, and `HardSigmoid(1/6) → Mul(self)` is recognised-as the `HardSwish` the runtime already fuses. All of it is exact — an affine map composed-with a convolution is a convolution — and the result is 62 convolutions, 2 transposed+as the `HardSwish` the runtime already fuses. All of it is exact - an affine map composed+with a convolution is a convolution - and the result is 62 convolutions, 2 transposed convolutions, 10 average pools, 10 channel multiplies, 11 adds, 6 nearest resizes, 1-concatenation and 24 scalar affines.+concatenation and 14 scalar affines.+The 14 are the affine blocks that could **not** be folded forward into the convolution they+feed. `conv(a * x + t)` is `a * conv(x) + t * sum(W)` only at an interior pixel: a padded+convolution reads zero outside the input rather than `t`, so at the border the constant's+contribution is `t` times the in-bounds taps alone. Twelve of the 14 feed a padded+depthwise and two feed a squeeze-excite's two branches. See `nets::Kind::Affine`. That op inventory matches ncnn's independent conversion of the same model layer for layer (`Convolution` 48 + `ConvolutionDepthWise` 14 = 62, `Pooling` 10, `Interp` 6,@@ -67,14 +72,32 @@ The space is deliberately **not** in the file — no entry in it is whitespace text editor or a line-ending conversion cannot silently eat it. `post::ctc::Dictionary` appends it. -## Recognition--`latin_PP_OCRv5_mobile_rec.ncnn.{param,bin}` still runs on ncnn, and is what keeps-`libncnn_android.so` in `:photos`, `:pdf` and `:translate`. Its replacement needs a-transformer stack the runtime does not have yet: the export decomposes each of its 5 layer-norms into `ReduceMean`/`Sub`/`Pow`/`Sqrt`/`Div`, and its attention into 13 `MatMul`s, 3-`Softmax`es and 9 `Transpose`s. The dictionary and the CTC decode for it are already here.--`PP_OCRv5_mobile_det.ncnn.{param,bin}` is superseded by `ppocr_det.vkml` but still-present, because `OcrEngine.kt` loads both models through the one ncnn wrapper and cannot-drop half of it.+## `ppocr_rec.vkml` - text recognition+Apache-2.0, from https://huggingface.co/PaddlePaddle/latin_PP-OCRv5_mobile_rec_onnx+@ `89d3a50e2c27e2e7cceeab0e944c25c807d5db4f` (`inference.onnx`, 8,042,023 B fp32,+SHA-256 `78881130.dd121498`) - the official export of the **latin** PP-OCRv5 mobile+recogniser, which is the variant whose 836-character dictionary is `ppocr_keys.txt`.+Folded by `scripts/ml/ppocr_fold.py` like detection, into 56 layers and 112 tensors.+From the export's own `inference.yml`: **BGR**, `image_shape [3, 48, 320]`,+`CTCLabelDecode`. Height is fixed at 48 and width must be a multiple of 8, so `T = W / 8`+and the standard 320-wide crop gives 40 timesteps.+### A CNN into a transformer, with no permutes+The backbone takes `3 x 48 x W` to `480 x 3 x W/4`; one average pool with kernel and+stride `(3, 2)` collapses that to `480 x 1 x W/8`, which *is* a sequence. Two pre-norm+transformer blocks at `d_model` 120 in 8 heads follow, then a concat back onto the pooled+features and an 838-way classifier.+`nets::ppocr_rec` keeps the sequence as `[d_model, 1, T]` - the layout the backbone already+produces - so all nine `Transpose`s and 52 `Reshape`s in the export are no-ops and are not+transcribed. Every projection is a 1x1 convolution and splitting `d_model` into heads is a+reinterpretation rather than a copy. The export's fused `[120, 360]` QKV projection is+split into three by the fold, and its `Mul(q, 1/sqrt(15))` is dropped because+`Kind::AttnScores` derives the same scale from the head geometry.+The classifier's final `Softmax` is **not** transcribed either. `post::ctc::decode` reads+the raw class-major logits: the argmax is unchanged by a softmax, and the winner's+probability is `1 / sum(exp(x - peak))` from the logits directly.+### Both folds are checked against onnxruntime+The layer table digest pins structure, not weight values, so a fold that computes the+wrong number passes it. `scripts/ml/onnx_parity.py` checks the numbers, and found two+bugs that everything else missed - an affine folded into a padded convolution, and a+silently zeroed QKV bias. At 64 wide the recogniser's logits agree with onnxruntime to+0.073 against a 0.075 bar from fp16 weight quantisation alone.
library/ocr/src/main/assets/ppocr_det.vkml
diff --git a/library/ocr/src/main/assets/ppocr_det.vkml b/library/ocr/src/main/assets/ppocr_det.vkmlindex 6385fc4210..e9cd46b9fa 100644Binary files a/library/ocr/src/main/assets/ppocr_det.vkml and b/library/ocr/src/main/assets/ppocr_det.vkml differ
library/ocr/src/main/assets/ppocr_rec.vkml
diff --git a/library/ocr/src/main/assets/ppocr_rec.vkml b/library/ocr/src/main/assets/ppocr_rec.vkmlnew file mode 100644index 0000000000..7f91915941Binary files /dev/null and b/library/ocr/src/main/assets/ppocr_rec.vkml differ
scripts/ml/fetch_and_convert.sh
diff --git a/scripts/ml/fetch_and_convert.sh b/scripts/ml/fetch_and_convert.shindex f8fc6db139..8b269fa789 100644--- a/scripts/ml/fetch_and_convert.sh+++ b/scripts/ml/fetch_and_convert.sh@@ -8,6 +8,7 @@ # photos/src/main/assets/scrfd_500m.vkml SCRFD 500M (face detection) # photos/src/main/assets/w600k_mbf.vkml MobileFaceNet (face embedding) # library/ocr/src/main/assets/ppocr_det.vkml PP-OCRv5 mobile (text detection)+# library/ocr/src/main/assets/ppocr_rec.vkml PP-OCRv5 mobile latin (text recognition) # # The first two are Apache-2.0. The two face models are InsightFace's buffalo_s pack # under InsightFace's own licence, which permits **non-commercial research use only** —@@ -22,10 +23,15 @@ # # The conversion is deliberately not a graph import. `:library:ml` hardcodes each # forward pass in Rust, so `.vkml` carries ordered tensors and nothing else, and-# vkml_convert.py pins a digest over the whole ordered layer table — an upstream+# vkml_convert.py pins a digest over the whole ordered layer table - an upstream # re-export that reorders or re-pads one layer fails here rather than shipping a # net that infers nonsense. See scripts/ml/vkml_convert.py. #+# The digest pins *structure*, not weight values. For the two folded models it is worth+# also running scripts/ml/onnx_parity.py, which checks the numbers against onnxruntime;+# it is how two silently-wrong folds were found. See that script's header.+# net that infers nonsense. See scripts/ml/vkml_convert.py.+# # ./scripts/ml/fetch_and_convert.sh # verify pinned hashes, rebuild assets # ./scripts/ml/fetch_and_convert.sh --update # re-download and rewrite hashes # ./scripts/ml/fetch_and_convert.sh --layers # also dump the per-layer tables@@ -48,6 +54,7 @@ MODELS=( "photos/src/main/assets/scrfd_500m.vkml scrfd 5e4447f50245bbd7966bd6c0fa52938c61474a04ec7def48753668a9d8b4ea3a https://huggingface.co/immich-app/buffalo_s/resolve/0ff1751885575e62e084dff70549ce24a11fa5dc/detection/model.onnx" "photos/src/main/assets/w600k_mbf.vkml mobilefacenet 9cc6e4a75f0e2bf0b1aed94578f144d15175f357bdc05e815e5c4a02b319eb4f https://huggingface.co/immich-app/buffalo_s/resolve/0ff1751885575e62e084dff70549ce24a11fa5dc/recognition/model.onnx" "library/ocr/src/main/assets/ppocr_det.vkml ppocr_det a431985659dc921974177a95adcfbb90fd9e51989a5e04d70d0b75f597b6e61d https://huggingface.co/PaddlePaddle/PP-OCRv5_mobile_det_onnx/resolve/e6f4fa85f00e168c862bc462aebca69eef9b3d3d/inference.onnx ppocr_fold.py"+ "library/ocr/src/main/assets/ppocr_rec.vkml ppocr_rec 7888113072263cb471b93f66dd5e2ad70548dc526fa1ace760d0d973dd121498 https://huggingface.co/PaddlePaddle/latin_PP-OCRv5_mobile_rec_onnx/resolve/89d3a50e2c27e2e7cceeab0e944c25c807d5db4f/inference.onnx ppocr_fold.py" ) if [ ! -f settings.gradle.kts ]; then
scripts/ml/onnx_parity.py
diff --git a/scripts/ml/onnx_parity.py b/scripts/ml/onnx_parity.pynew file mode 100644index 0000000000..b56c5719a4--- /dev/null+++ b/scripts/ml/onnx_parity.py@@ -0,0 +1,170 @@+#!/usr/bin/env python3+"""Check a `.vkml` forward pass against onnxruntime, numerically.++Nothing else in this repo compares the *numbers* `:library:ml` produces against the export+they came from. The per-op fixtures in `nets::reference` check each op against hand+arithmetic, and the layer table digest checks that the shapes still line up, but neither+notices a weight that is subtly wrong. Both bugs this script found were exactly that shape:++* `ppocr_fold.py` folded a scalar affine into a **padded** convolution, which is only exact+ at interior pixels. That biased the border of every feature map in both PP-OCRv5 models+ and changed 5% of the shipped detection weights.+* A fused QKV projection's bias `Add` became unreachable once its slices were rewritten, so+ dead-code elimination removed it and all three projections got a zero bias. Every shape+ check, the tensor count and the digest passed.++So this exists, and is worth running whenever `ppocr_fold.py` or a net module changes.++# How to run it++ ./scripts/ml/fetch_and_convert.sh # produce the .vkml first+ python scripts/ml/onnx_parity.py <graph> <inference.onnx> [--width N]++It writes a scratch directory, runs onnxruntime, then asks the Rust reference interpreter+for the same tensor and reports the difference. `onnxruntime` is an extra dependency:++ python -m pip install onnxruntime++# What "agreeing" means++`.vkml` is fp16, so the two cannot agree exactly. The bar is that the difference is no+larger than fp16 weight quantisation alone accounts for, which this script measures by+running onnxruntime a second time with every weight rounded through fp16. A difference+materially above that line is a bug, not precision.+"""++import argparse+import os+import subprocess+import sys+import tempfile++import numpy as np+import onnx+import onnxruntime+from onnx import numpy_helper++# The tensor to compare per graph, and why it rather than the network's output.+#+# Detection ends in a sigmoid over a text-probability map, which on a synthetic input is+# saturated to zero everywhere — comparing it would compare zeros. Its backbone output is+# where all fourteen of its surviving affines live, so that is the informative tensor.+PROBE = {+ "ppocr_rec": None,+ "ppocr_det": "p2o.pd_op.hardswish.23.0",+}+++def rounded_to_fp16(model):+ """`model` with every weight put through fp16, to measure quantisation on its own."""+ clone = onnx.ModelProto()+ clone.CopyFrom(model)+ for node in clone.graph.node:+ if node.op_type != "Constant":+ continue+ for attribute in node.attribute:+ if attribute.name != "value":+ continue+ value = numpy_helper.to_array(attribute.t)+ if value.dtype == np.float32 and value.size >= 8:+ attribute.t.CopyFrom(+ numpy_helper.from_array(+ value.astype(np.float16).astype(np.float32), attribute.t.name+ )+ )+ for initializer in clone.graph.initializer:+ value = numpy_helper.to_array(initializer)+ if value.dtype == np.float32 and value.size >= 8:+ initializer.CopyFrom(+ numpy_helper.from_array(+ value.astype(np.float16).astype(np.float32), initializer.name+ )+ )+ return clone+++def final_logits(model):+ """The name of the tensor before a trailing `Softmax`, or the graph's own output.++ `nets::ppocr_rec` deliberately does not run the classifier's softmax, so the comparable+ tensor is its input.+ """+ outputs = {o.name for o in model.graph.output}+ for node in model.graph.node:+ if node.op_type == "Softmax" and node.output[0] in outputs:+ return node.input[0]+ return next(iter(outputs))+++def run(model, probe, x):+ session = onnxruntime.InferenceSession(+ model.SerializeToString(), providers=["CPUExecutionProvider"]+ )+ names = [o.name for o in session.get_outputs()]+ outputs = session.run(None, {session.get_inputs()[0].name: x})+ return np.squeeze(np.asarray(outputs[names.index(probe)]))+++def main():+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("graph", choices=sorted(PROBE))+ parser.add_argument("onnx")+ parser.add_argument("--width", type=int, default=64)+ args = parser.parse_args()++ onnxruntime.set_default_logger_severity(3)+ model = onnx.load(args.onnx)+ probe = PROBE[args.graph] or final_logits(model)+ if probe not in {o.name for o in model.graph.output}:+ model.graph.output.append(+ onnx.helper.make_tensor_value_info(probe, onnx.TensorProto.FLOAT, None)+ )++ height = 48 if args.graph == "ppocr_rec" else args.width+ work = tempfile.mkdtemp(prefix="vkml_parity_")+ # Deterministic and free of transcendentals, so both sides read identical bytes.+ count = 3 * height * args.width+ ramp = ((np.arange(count, dtype=np.int64) * 37) % 255).astype(np.float32) / 255.0 - 0.5+ x = ramp.reshape(1, 3, height, args.width)+ x.tofile(os.path.join(work, "input.f32"))++ reference = run(model, probe, x)+ quantised = run(rounded_to_fp16(model), probe, x)++ environment = dict(os.environ, PARITY_DIR=work, PARITY_GRAPH=args.graph)+ environment["PARITY_WIDTH"] = str(args.width)+ subprocess.run(+ [+ "cargo", "test", "--release", "-p", "modelrunner", "--lib",+ "dump_reference_output", "--", "--ignored", "--nocapture",+ ],+ check=True,+ env=environment,+ )+ got = np.fromfile(os.path.join(work, "reference.f32"), dtype=np.float32)++ # The runtime writes `[c, h, w]`; reshape the ONNX tensor to match by element count.+ want = np.ascontiguousarray(reference).flatten()+ if want.size != got.size:+ raise SystemExit(f"{probe}: onnx has {want.size} values, the runtime {got.size}")+ if args.graph == "ppocr_rec":+ # `[1, T, 838]` against the runtime's class-major `[838, T]`.+ want = np.ascontiguousarray(reference.T).flatten()++ def report(label, a, b):+ d = np.abs(a - b)+ print(+ f" {label:28s} max {d.max():.6f} mean {d.mean():.7f} "+ f"corr {np.corrcoef(a, b)[0, 1]:.8f}"+ )++ bound = np.ascontiguousarray(+ quantised.T if args.graph == "ppocr_rec" else quantised+ ).flatten()+ print(f"{args.graph} at {args.width} wide, tensor {probe}:")+ report("fp16 weights alone (the bar)", want, bound)+ report("the runtime", want, got)+++if __name__ == "__main__":+ main()
scripts/ml/ppocr_fold.py
diff --git a/scripts/ml/ppocr_fold.py b/scripts/ml/ppocr_fold.pyindex 134e41a9dc..70d36c0d08 100644--- a/scripts/ml/ppocr_fold.py+++ b/scripts/ml/ppocr_fold.py@@ -69,6 +69,26 @@ import vkml_convert # noqa: E402 (needs the path above) HARDSWISH_ALPHA = 1.0 / 6.0 TOLERANCE = 1e-4 +# Ops that only rearrange or relabel, and are therefore aliases in `.vkml`'s layout.+#+# This runtime's tensors are `[c, h, w]` with batch always 1, and `nets::ppocr_rec` keeps a+# transformer's sequence as `[d_model, 1, T]` precisely so that the export's reshapes and+# permutes are no-ops. Nine `Transpose`s, 52 `Reshape`s and nine `Squeeze`s in the+# recognition graph are exactly that: `[1, 120, 1, T]` to `[1, T, 120]` and back, and the+# five-dimensional shuffle that splits a fused QKV projection into heads.+#+# Aliasing them is a **claim**, not an observation: nothing here checks that a given+# `Transpose` is a no-op in the target layout. What checks it is that the forward pass in+# `nets::ppocr_rec` was written from a reading of this same graph, and that the layer table+# digest below pins every weight's shape. A permute that mattered would show up as a net+# that infers nonsense, so `--print-graph` is worth reading when this list changes.+SHAPE_ONLY = ("Reshape", "Transpose", "Squeeze", "Unsqueeze", "Flatten")++# The shape-computation subgraph that feeds those reshapes: `Shape` into `Slice` into+# `Concat`. Once the reshapes are aliased away nothing reads it, so it is dropped as dead+# code rather than recognised.+SHAPE_MACHINERY = ("Shape", "ConstantOfShape")+ class Op: """One op in the normalised graph, as the Rust forward pass will see it."""@@ -112,14 +132,46 @@ def normalise(model): # Rewire Identity without mutating the nodes: build an alias map and read every # input through it. `Cast` is aliased too — paddle2onnx inserts one in front of every- # transposed convolution's weight, and it is a no-op between two float types.+ # transposed convolution's weight, and it is a no-op between two float types. So are+ # the pure shape ops; see `SHAPE_ONLY`. alias = {} for node in graph.node: if node.op_type == "Identity" or ( node.op_type == "Cast" and node.input and node.input[0] in inits ): alias[node.output[0]] = node.input[0]- nodes = [n for n in graph.node if n.op_type not in ("Identity", "Constant")]+ elif node.op_type in SHAPE_ONLY and node.input:+ alias[node.output[0]] = node.input[0]+ elif node.op_type in ("Add", "Mul") and len(node.input) == 2:+ # `Add(x, 0)` and `Mul(x, 1)`. paddle2onnx emits three of these around the+ # sequence pool, where Paddle's `assign` became an unsqueeze, an add of zero+ # and a squeeze. Folding them as affines would work and would leave an+ # elementwise pass over 115,200 elements that does nothing.+ for position, name in enumerate(node.input):+ value = inits.get(name)+ if value is None:+ continue+ flat = np.array(value, dtype=np.float64).flatten()+ identity = 0.0 if node.op_type == "Add" else 1.0+ if flat.size == 1 and abs(flat[0] - identity) < 1e-12:+ alias[node.output[0]] = node.input[1 - position]+ break++ # The fused QKV projection, and the three slices that split it. Resolved here rather+ # than during the walk because the alias map has to be complete before any input is+ # read through it; this adds the slice outputs to it.+ fused, keep = split_fused_qkv(graph, inits, alias)++ nodes = [+ n+ for n in graph.node+ if n.op_type not in ("Identity", "Constant")+ and n.op_type not in SHAPE_MACHINERY+ and not (n.output and n.output[0] in alias)+ ]+ # Whatever is left of the shape machinery reads a `Shape` that is now gone, so it is+ # dead. Reverse reachability from the graph's output is what removes it.+ nodes = live_nodes(nodes, graph, alias, fused, keep) inputs_of = {id(n): [resolve(i, alias) for i in n.input] for n in nodes} producer = {}@@ -179,6 +231,141 @@ def normalise(model): ) ) + def emit_linear(node, weight, bias, act, source, output, already_transposed=False):+ """A `MatMul` against a constant, as the 1x1 convolution the runtime lowers it to.++ ONNX spells `x[..., in] @ W[in, out]`, so the weight arrives transposed relative to+ a convolution's `[out, in, kh, kw]`. Transposing here rather than in the shader is+ what lets every projection in the transformer be an ordinary `Kind::Conv`.+ """+ kernel = weight if already_transposed else transposed(weight)+ first = len(tensors)+ tensors.append(kernel.astype(np.float32))+ tensors.append(bias.astype(np.float32))+ key = (+ f"Linear w={list(kernel.shape)} b={list(bias.shape)} "+ f"k=[1, 1] d=[1, 1] p=[0, 0, 0, 0] s=[1, 1] g=1 act={act}"+ )+ layers.append(vkml_convert.Layer(len(layers), "MatMul", output, key, first, 2))+ ops.append(+ Op("Linear", [source], output, w=list(kernel.shape), act=act, t=first)+ )++ def emit_layer_norm(gamma, beta, epsilon, source, output):+ """One `LayerNorm` layer from the nine nodes the export decomposes it into."""+ first = len(tensors)+ tensors.append(np.array(gamma, dtype=np.float32).flatten())+ tensors.append(np.array(beta, dtype=np.float32).flatten())+ key = f"LayerNorm c={gamma.size} eps={epsilon:.9g}"+ layers.append(vkml_convert.Layer(len(layers), "LayerNorm", output, key, first, 2))+ ops.append(Op("LayerNorm", [source], output, c=int(gamma.size), eps=epsilon, t=first))++ def absorb(cursor, weight, bias, channels, is_transpose):+ """Pull every constant that follows `cursor` into `weight` and `bias`.++ Stops at the activation, because an affine applied *after* one cannot move before+ it. Returns the updated weight and bias, the activation found, and the name of the+ last tensor absorbed — which becomes the layer's output.++ Shared by the convolutions and the `MatMul` linears: the recognition export spells+ a feed-forward layer as `MatMul -> Add(bias) -> Sigmoid -> Mul(self)`, which is the+ same chain a convolution gets, so recognising it twice would be two chances to+ recognise it differently.+ """+ act = "None"+ while True:+ following = consumers.get(cursor, [])+ if act != "None":+ break+ # `x * HardSigmoid(x)` is not a single-consumer chain: the tensor feeds+ # both the HardSigmoid and the Mul that combines them. Matching it before+ # the branch test below is the difference between fusing 24 HardSwishes+ # and emitting 48 extra ops for them.+ gate = next((n for n in following if n.op_type in ("HardSigmoid", "Sigmoid")), None)+ if len(following) == 2 and gate is not None:+ other = following[0] if following[1] is gate else following[1]+ after = consumers.get(gate.output[0], [])+ if (+ other.op_type == "Mul"+ and len(after) == 1+ and after[0] is other+ and gate.output[0] in inputs_of[id(other)]+ and cursor in inputs_of[id(other)]+ ):+ if gate.op_type == "Sigmoid":+ act = "Swish"+ else:+ attrs = {a.name: a.f for a in gate.attribute}+ alpha = attrs.get("alpha", 0.2)+ beta = attrs.get("beta", 0.5)+ if (+ abs(alpha - HARDSWISH_ALPHA) > TOLERANCE+ or abs(beta - 0.5) > TOLERANCE+ ):+ raise SystemExit(+ f"{gate.output[0]}: x * HardSigmoid(x) with "+ f"alpha={alpha} beta={beta}; the runtime's HardSwish "+ "is alpha=1/6 beta=0.5"+ )+ act = "HardSwish"+ consumed.add(id(gate))+ consumed.add(id(other))+ cursor = other.output[0]+ continue+ if len(following) != 1:+ break+ step = following[0]+ if step.op_type == "Add":+ value, _ = constant(step, None)+ if value is None:+ break+ bias = bias + np.array(value, dtype=np.float64).flatten()+ elif step.op_type == "Mul":+ value, _ = constant(step, None)+ if value is None:+ break+ scale = np.array(value, dtype=np.float64).flatten()+ if scale.size == 1:+ weight = weight * scale[0]+ bias = bias * scale[0]+ elif scale.size == channels:+ shape = [1] * weight.ndim+ axis = 1 if is_transpose else 0+ shape[axis] = channels+ weight = weight * scale.reshape(shape)+ bias = bias * scale+ else:+ break+ elif step.op_type == "BatchNormalization":+ weight, bias = fold_batch_norm(+ step, inits, weight, bias, "ConvTranspose" if is_transpose else "Conv"+ )+ elif step.op_type == "Relu":+ act = "Relu"+ elif step.op_type == "Sigmoid":+ act = "Sigmoid"+ elif step.op_type == "HardSigmoid":+ # A HardSigmoid with a single consumer is a standalone gate — the+ # excite half of a squeeze-excite block, whose Mul takes a different+ # tensor. The self-multiplying kind was matched above.+ #+ # Its alpha and beta fold into the convolution:+ # `clamp(alpha * (Wx + b) + beta, 0, 1)` is `clamp(W'x + b', 0, 1)`.+ # Both 0.2 and 1/6 appear in this graph, so an activation carrying the+ # two parameters would have to put them in the push block; this way the+ # runtime needs one parameterless clamp.+ attrs = {a.name: a.f for a in step.attribute}+ alpha = attrs.get("alpha", 0.2)+ beta = attrs.get("beta", 0.5)+ weight = weight * alpha+ bias = bias * alpha + beta+ act = "Clip01"+ else:+ break+ consumed.add(id(step))+ cursor = step.output[0]+ return weight, bias, act, cursor+ for node in nodes: if id(node) in consumed: continue@@ -191,102 +378,68 @@ def normalise(model): if len(names) > 2 else np.zeros(channels, dtype=np.float64) )- act, act_alpha = "None", None- cursor = node.output[0]-- # Absorb everything constant that follows, stopping at the activation: an- # affine applied *after* one cannot move before it.- while True:- following = consumers.get(cursor, [])- if act != "None":- break- # `x * HardSigmoid(x)` is not a single-consumer chain: the tensor feeds- # both the HardSigmoid and the Mul that combines them. Matching it before- # the branch test below is the difference between fusing 24 HardSwishes- # and emitting 48 extra ops for them.- gate = next((n for n in following if n.op_type in ("HardSigmoid", "Sigmoid")), None)- if len(following) == 2 and gate is not None:- other = following[0] if following[1] is gate else following[1]- after = consumers.get(gate.output[0], [])- if (- other.op_type == "Mul"- and len(after) == 1- and after[0] is other- and gate.output[0] in inputs_of[id(other)]- and cursor in inputs_of[id(other)]- ):- if gate.op_type == "Sigmoid":- act = "Swish"- else:- attrs = {a.name: a.f for a in gate.attribute}- alpha = attrs.get("alpha", 0.2)- beta = attrs.get("beta", 0.5)- if (- abs(alpha - HARDSWISH_ALPHA) > TOLERANCE- or abs(beta - 0.5) > TOLERANCE- ):- raise SystemExit(- f"{gate.output[0]}: x * HardSigmoid(x) with "- f"alpha={alpha} beta={beta}; the runtime's HardSwish "- "is alpha=1/6 beta=0.5"- )- act = "HardSwish"- consumed.add(id(gate))- consumed.add(id(other))- cursor = other.output[0]- continue- if len(following) != 1:- break- step = following[0]- if step.op_type == "Add":- value, _ = constant(step, None)- if value is None:- break- bias = bias + np.array(value, dtype=np.float64).flatten()- elif step.op_type == "Mul":- value, _ = constant(step, None)- if value is None:- break- scale = np.array(value, dtype=np.float64).flatten()- if scale.size == 1:- weight = weight * scale[0]- bias = bias * scale[0]- elif scale.size == channels:- shape = [1] * weight.ndim- axis = 1 if node.op_type == "ConvTranspose" else 0- shape[axis] = channels- weight = weight * scale.reshape(shape)- bias = bias * scale- else:- break- elif step.op_type == "BatchNormalization":- weight, bias = fold_batch_norm(step, inits, weight, bias, node.op_type)- elif step.op_type == "Relu":- act = "Relu"- elif step.op_type == "Sigmoid":- act = "Sigmoid"- elif step.op_type == "HardSigmoid":- # A HardSigmoid with a single consumer is a standalone gate — the- # excite half of a squeeze-excite block, whose Mul takes a different- # tensor. The self-multiplying kind was matched above.- #- # Its alpha and beta fold into the convolution:- # `clamp(alpha * (Wx + b) + beta, 0, 1)` is `clamp(W'x + b', 0, 1)`.- # Both 0.2 and 1/6 appear in this graph, so an activation carrying the- # two parameters would have to put them in the push block; this way the- # runtime needs one parameterless clamp.- attrs = {a.name: a.f for a in step.attribute}- alpha = attrs.get("alpha", 0.2)- beta = attrs.get("beta", 0.5)- weight = weight * alpha- bias = bias * alpha + beta- act = "Clip01"- else:- break- consumed.add(id(step))- cursor = step.output[0]-- emit_conv(node, weight, bias, act, act_alpha, cursor)+ weight, bias, act, cursor = absorb(+ node.output[0], weight, bias, channels, node.op_type == "ConvTranspose"+ )+ emit_conv(node, weight, bias, act, None, cursor)+ elif node.op_type == "MatMul":+ names = inputs_of[id(node)]+ constants = [n for n in names if n in inits]+ if not constants:+ # Both operands are activations, so this is one of attention's two+ # products — the scores or the weighted sum. `nets::ppocr_rec` lowers+ # those to `AttnScores` and `AttnApply`, which read no weights.+ ops.append(Op("MatMul", names, node.output[0]))+ continue+ weight = np.array(inits[constants[0]], dtype=np.float64)+ if weight.ndim != 2:+ raise SystemExit(+ f"{node.output[0]}: a MatMul against a {list(weight.shape)} constant"+ )+ source = next(n for n in names if n not in inits)+ outputs = weight.shape[1]+ bias, bias_node = following_bias(node, consumers, inputs_of, inits, outputs)+ if bias_node is not None:+ consumed.add(id(bias_node))+ cursor = bias_node.output[0] if bias_node is not None else node.output[0]+ parts = fused.get(node.output[0])+ if parts is not None:+ # A fused QKV projection: one `[d, 3d]` weight that the export slices into+ # query, key and value after a five-dimensional shuffle. Split here into+ # three ordinary linears, because `nets::ppocr_rec` projects them+ # separately and a channel slice of a constant is exact.+ width = outputs // 3+ for index, name in enumerate(parts):+ emit_linear(+ node,+ weight[:, index * width : (index + 1) * width],+ bias[index * width : (index + 1) * width],+ "None",+ source,+ name,+ )+ continue+ weight, bias, act, cursor = absorb(cursor, transposed(weight), bias, outputs, False)+ emit_linear(node, weight, bias, act, source, cursor, already_transposed=True)+ elif node.op_type == "ReduceMean":+ matched = match_layer_norm(node, consumers, inputs_of, inits)+ if matched is None:+ ops.append(Op(node.op_type, inputs_of[id(node)], node.output[0]))+ continue+ chain, gamma, beta, epsilon, source, output = matched+ for member in chain:+ consumed.add(id(member))+ emit_layer_norm(gamma, beta, epsilon, source, output)+ elif node.op_type == "Softmax":+ axis = next((a.i for a in node.attribute if a.name == "axis"), -1)+ if node.output[0] in {o.name for o in graph.output}:+ # The classifier's softmax over the 838 classes. Deliberately dropped:+ # `post::ctc::decode` takes the argmax, which a softmax cannot change, and+ # recovers the winner's probability from the raw logits directly. See the+ # module docs in `nets::ppocr_rec`.+ ops.append(Op("DroppedSoftmax", inputs_of[id(node)], node.output[0], axis=axis))+ continue+ ops.append(Op(node.op_type, inputs_of[id(node)], node.output[0], axis=axis)) elif node.op_type in ("Add", "Mul"): value, other = constant(node, None) if value is not None:@@ -312,29 +465,298 @@ def normalise(model): return ops, layers, tensors +def transposed(weight):+ """`[in, out]` as a convolution kernel `[out, in, 1, 1]`."""+ return np.ascontiguousarray(weight.T).reshape(weight.shape[1], weight.shape[0], 1, 1)+++def following_bias(node, consumers, inputs_of, inits, outputs):+ """The `Add(matmul, bias)` that follows a linear, as `(bias, node)`.++ Raises rather than defaulting to zeros. Every `MatMul` in this export carries its bias+ as a following `Add`, so failing to find one means the graph is not the shape this+ script thinks — and a silently zeroed bias is invisible: it survives every shape check,+ the layer table digest and the tensor count, and shows up only as lost accuracy.+ """+ following = consumers.get(node.output[0], [])+ if len(following) == 1 and following[0].op_type == "Add":+ for name in inputs_of[id(following[0])]:+ if name in inits:+ value = np.array(inits[name], dtype=np.float64).flatten()+ if value.size == outputs:+ return value, following[0]+ raise SystemExit(+ f"{node.output[0]}: a MatMul with {outputs} outputs and no following Add against a "+ f"[{outputs}] constant, so its bias cannot be read"+ )+++def split_fused_qkv(graph, inits, alias):+ """Find each fused QKV projection and alias its three slices to per-part names.++ PaddleOCR's attention projects query, key and value in one `[d, 3d]` `MatMul`, then+ reshapes to `[batch, T, 3, heads, head_dim]`, permutes and slices the leading axis.+ `nets::ppocr_rec` projects the three separately, so this records which slice is which+ and lets the walk emit three linears from the one weight.++ It also drops the `Mul(q, 1/sqrt(head_dim))` the export applies to the query, after+ checking the constant really is that: `Kind::AttnScores` derives the same scale from+ the head geometry, so leaving it here would apply it twice.++ Mutates `alias`, and returns `({matmul_output: [q_name, k_name, v_name]}, keep)`, where+ `keep` is the set of output names that must survive dead-code elimination.+ """+ def resolved(name):+ return resolve(name, alias)++ constants = dict(inits)+ consumers = {}+ for node in graph.node:+ for name in node.input:+ consumers.setdefault(resolved(name), []).append(node)++ fused = {}+ keep = set()+ for node in graph.node:+ if node.op_type != "MatMul":+ continue+ weights = [resolved(n) for n in node.input if resolved(n) in constants]+ if not weights:+ continue+ weight = np.array(constants[weights[0]])+ if weight.ndim != 2 or weight.shape[1] != weight.shape[0] * 3:+ continue++ width = weight.shape[0]+ names = [f"{node.output[0]}#{part}" for part in ("q", "k", "v")]+ # The slices read the bias `Add`'s output through the aliased reshape and permute.+ bias_node = next(+ (n for n in consumers.get(node.output[0], []) if n.op_type == "Add"), None+ )+ if bias_node is None:+ raise SystemExit(f"{node.output[0]}: a fused QKV projection with no bias")+ # Aliasing the three slices below orphans this `Add` — nothing in the graph reads+ # its output any more — so without pinning it here the dead-code pass removes it+ # and the walk reads a zero bias for all three projections.+ #+ # Pinned by output *name*, not by `id()`: protobuf's upb backend hands out a fresh+ # Python wrapper on each access to a repeated field, so an id taken here does not+ # match the one `normalise` sees. Names are unique — ONNX graphs are SSA.+ keep.add(bias_node.output[0])+ split_source = resolved(bias_node.output[0])+ found = {}+ for candidate in graph.node:+ if candidate.op_type != "Slice":+ continue+ if not candidate.input or resolved(candidate.input[0]) != split_source:+ continue+ starts = next((list(a.ints) for a in candidate.attribute if a.name == "starts"), [])+ if len(starts) != 1 or not 0 <= starts[0] < 3:+ continue+ found[starts[0]] = candidate+ if len(found) != 3:+ raise SystemExit(+ f"{node.output[0]}: a [{width}, {width * 3}] projection with "+ f"{len(found)} slices, expected three (query, key, value)"+ )+ for part, candidate in found.items():+ alias[candidate.output[0]] = names[part]+ fused[node.output[0]] = names++ # The query's scale. `heads` is not known here, so the check is that the constant+ # is `1/sqrt(width / heads)` for the integer head count that makes it so.+ scale_node = next(+ (+ n+ for n in graph.node+ if n.op_type == "Mul" and any(resolved(i) == names[0] for i in n.input)+ ),+ None,+ )+ if scale_node is None:+ raise SystemExit(f"{node.output[0]}: the query is not scaled at all")+ value = next(+ (np.array(constants[resolved(i)]).flatten() for i in scale_node.input+ if resolved(i) in constants),+ None,+ )+ if value is None or value.size != 1:+ raise SystemExit(f"{scale_node.output[0]}: the query's scale is not a scalar")+ head_dim = 1.0 / float(value[0]) ** 2+ if abs(head_dim - round(head_dim)) > 1e-3 or not width % max(round(head_dim), 1) == 0:+ raise SystemExit(+ f"{scale_node.output[0]}: a query scale of {value[0]} is not "+ f"1/sqrt(head_dim) for any head count dividing {width}"+ )+ alias[scale_node.output[0]] = names[0]+ return fused, keep+++def live_nodes(nodes, graph, alias, fused, keep):+ """`nodes`, restricted to those that transitively feed a graph output, plus `keep`.++ Aliasing the reshapes away orphans the `Shape`/`Slice`/`Concat` subgraphs that computed+ their target shapes — 52 reshapes' worth. Reverse reachability removes them without+ this script having to recognise what each one was for.++ `fused` has to be threaded through: a fused QKV projection's three parts are named for+ slices that no longer exist, so without registering the `MatMul` as their producer the+ walk backwards stops dead there and takes both attentions and the two layer norms in+ front of them with it. `keep` carries the output names of nodes that are unreachable+ *by construction* but still hold data the walk needs — those projections' bias `Add`s.+ """+ producer = {}+ for node in nodes:+ for name in node.output:+ producer[name] = node+ for part in fused.get(node.output[0] if node.output else "", []):+ producer[part] = node+ live = set()+ queue = [resolve(o.name, alias) for o in graph.output]+ queue.extend(keep)+ while queue:+ name = queue.pop()+ node = producer.get(name)+ if node is None or id(node) in live:+ continue+ live.add(id(node))+ queue.extend(resolve(i, alias) for i in node.input)+ return [n for n in nodes if id(n) in live]+++def match_layer_norm(first_mean, consumers, inputs_of, inits):+ """Match `ReduceMean/Sub/Pow/ReduceMean/Add/Sqrt/Div/Mul/Add` as one layer norm.++ The export decomposes each of the recogniser's five layer norms into nine nodes. Left+ alone that is 45 ops, most of them reductions over a dynamic axis. Returns+ `(chain, gamma, beta, epsilon, source, output)`, or `None` if this `ReduceMean` is+ something else.++ Matched forwards from the *first* `ReduceMean` rather than from the `Div`, because the+ walk reaches it first and would otherwise have emitted it as a standalone op.+ """+ def only(name, kind):+ following = consumers.get(name, [])+ if len(following) == 1 and following[0].op_type == kind:+ return following[0]+ return None++ def other_input(node, known):+ return next((n for n in inputs_of[id(node)] if n != known), None)++ source = next(iter(inputs_of[id(first_mean)]), None)+ if source is None:+ return None+ # `Sub(x, mean)` reads both the layer norm's input and this mean.+ centre = next(+ (+ n+ for n in consumers.get(first_mean.output[0], [])+ if n.op_type == "Sub" and source in inputs_of[id(n)]+ ),+ None,+ )+ if centre is None:+ return None+ power = next(+ (n for n in consumers.get(centre.output[0], []) if n.op_type == "Pow"), None+ )+ if power is None:+ return None+ exponent = next(+ (np.array(inits[n]).flatten() for n in inputs_of[id(power)] if n in inits), None+ )+ if exponent is None or exponent.size != 1 or abs(exponent[0] - 2.0) > 1e-9:+ return None+ variance = only(power.output[0], "ReduceMean")+ if variance is None:+ return None+ stabilised = only(variance.output[0], "Add")+ if stabilised is None:+ return None+ epsilon = next(+ (np.array(inits[n]).flatten() for n in inputs_of[id(stabilised)] if n in inits), None+ )+ if epsilon is None or epsilon.size != 1:+ return None+ root = only(stabilised.output[0], "Sqrt")+ if root is None:+ return None+ divide = next(+ (+ n+ for n in consumers.get(root.output[0], [])+ if n.op_type == "Div" and centre.output[0] in inputs_of[id(n)]+ ),+ None,+ )+ if divide is None:+ return None+ scale = only(divide.output[0], "Mul")+ if scale is None:+ return None+ gamma_name = other_input(scale, divide.output[0])+ if gamma_name not in inits:+ return None+ shift = only(scale.output[0], "Add")+ if shift is None:+ return None+ beta_name = other_input(shift, scale.output[0])+ if beta_name not in inits:+ return None++ gamma = np.array(inits[gamma_name]).flatten()+ beta = np.array(inits[beta_name]).flatten()+ if gamma.size != beta.size:+ return None+ chain = [first_mean, centre, power, variance, stabilised, root, divide, scale, shift]+ return chain, gamma, beta, float(epsilon[0]), source, shift.output[0]++ def fold_affine_into_convs(ops, tensors):- """Push each scalar `Affine` into the convolutions it feeds, where they are all convs.+ """Push each scalar `Affine` into the convolutions it feeds, where that is exact. `conv(a * x + t)[m]` is `a * conv(x)[m] + t * sum(W[m])`, so an affine on a convolution's *input* folds into its weight and bias just as one on its output does. The sum is over every weight axis but the output-channel one, which for a grouped or depthwise convolution is exactly the channels that output reads. - This is only valid when the affine's result is not needed anywhere else, so it is- applied only when every consumer is a convolution. In the detection graph that is 23- of the 24: the one exception feeds a squeeze-excite branch, and stays an op.+ # Only when the convolution is unpadded++ That identity holds at an interior pixel and **fails at a border one**. A padded+ convolution reads zero outside the input, not `t`, so the constant's true contribution+ there is `t * sum(W over the in-bounds taps)` — position-dependent, and smaller than+ `t * sum(W)` by whatever hangs over the edge. Folding anyway biases the whole border+ of every feature map, which is 27% of the pixels of a 12x16 map at a 3x3 kernel, and+ compounds through the backbone.++ There is no fix that keeps the fold: the correction varies per output position, so it+ is not a bias. Padding the input with `t` instead of zero would make the identity exact+ and is not what the graph says. So an affine feeding a padded convolution stays an op,+ which is what ncnn's conversion of these models does with all of them.++ Also only when the affine's result is not needed anywhere else, so every consumer has+ to be a convolution as well. """ consumers = {} for op in ops: for name in op.inputs: consumers.setdefault(name, []).append(op) + def foldable(op):+ if op.kind not in ("Conv", "ConvTranspose"):+ return False+ # `Linear` is a 1x1 with no padding by construction, but it is spelled as its own+ # kind and is deliberately not folded into: it would mean this function had to know+ # that a `MatMul`'s weight is stored transposed.+ return not any(op.extra.get("p", (0, 0, 0, 0)))+ dropped = set() for op in ops: if op.kind != "Affine": continue following = consumers.get(op.output, [])- if not following or any(f.kind not in ("Conv", "ConvTranspose") for f in following):+ if not following or not all(foldable(f) for f in following): continue scale = op.extra["scale"] shift = op.extra["shift"]
scripts/ml/vkml_convert.py
diff --git a/scripts/ml/vkml_convert.py b/scripts/ml/vkml_convert.pyindex 7cf0a52559..02a2ffb173 100644--- a/scripts/ml/vkml_convert.py+++ b/scripts/ml/vkml_convert.py@@ -107,7 +107,7 @@ EXPECTED_DIGEST = { "scrfd": "d2ce2880a432af03b0ef594029d3ab03d86de54bd0a9f10ea2c8e412309b0f46", "mobilefacenet": "40987839aec03378958581deba29ce9fd9dd1ae9aa88d0c7ad04a885a2e2122c", "ppocr_det": "51b0c9ed871526fa270b4bfa53b393c056db21c58193849fb83d44768f69ef9b",- "ppocr_rec": "",+ "ppocr_rec": "8c16a8702aa7a1e7b4d94787d089616ca4bc3d8aaeebb0b0159eabc56af3ba08", } # What each graph is exported at, as `[channels, height, width]` after the batch