library:ml: fold PP-OCRv5 detection into .vkml ahead of time
- Commit
d92b64c4f8b35cbfafb7f9838b0834aff33c5a93- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 04:34 UTC (3 months ago)
- Parents
a217c96
Diff
library/ml/src/main/rust/shaders/affine.comp
diff --git a/library/ml/src/main/rust/shaders/affine.comp b/library/ml/src/main/rust/shaders/affine.compnew file mode 100644index 0000000000..53098a748d--- /dev/null+++ b/library/ml/src/main/rust/shaders/affine.comp@@ -0,0 +1,36 @@+#version 450+//! `out = in * scale + shift`, both scalars. 24 uses, all in PP-OCRv5 detection.+//!+//! # What this is+//!+//! PP-HGNetV2's "learnable affine block": a per-tensor, not per-channel, affine. Two+//! trained scalars, applied to every element of a feature map.+//!+//! # Why it is an op at all+//!+//! Almost everything constant in the PP-OCRv5 export folds into a convolution — the+//! bias, the batch norms, the affine blocks that sit *before* an activation, even+//! HardSigmoid's alpha and beta. `scripts/ml/ppocr_fold.py` does all of that ahead of+//! time, which is why 117 `Add`s and 86 `Mul`s in the ONNX become 11 and 10 here.+//!+//! These 24 are the ones that survive, because they sit *after* an activation. Folding+//! one into the *following* convolution is possible — `b' += shift * sum(W)` over each+//! output row — but only when the tensor feeds nothing except convolutions, and making+//! the conversion depend on that is how a subtle wrong answer gets shipped. One+//! elementwise pass is the honest version, and detection runs once per OCR request+//! rather than once per frame.+//!+//! The two scalars arrive as raw `f32` bits in the push block, so `nets::Push` stays+//! entirely `u32` and needs no padding.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ float scale = uintBitsToFloat(p.scale_bits);+ float shift = uintBitsToFloat(p.shift_bits);+ arena[p.out_at + index] = float16_t(float(arena[p.in0 + index]) * scale + shift);+}
library/ml/src/main/rust/shaders/common.glsl
diff --git a/library/ml/src/main/rust/shaders/common.glsl b/library/ml/src/main/rust/shaders/common.glslindex e263e26985..8b69baa010 100644--- a/library/ml/src/main/rust/shaders/common.glsl+++ b/library/ml/src/main/rust/shaders/common.glsl@@ -66,6 +66,8 @@ layout(push_constant) uniform Push { uint group; uint act; uint act_weight;+ uint scale_bits;+ uint shift_bits; uint count; } p; @@ -75,6 +77,7 @@ layout(push_constant) uniform Push { #define ACT_HARDSWISH 2u #define ACT_SIGMOID 3u #define ACT_PRELU 4u+#define ACT_CLIP01 5u // This invocation's output element, across a 2D grid of workgroups. //@@ -115,6 +118,12 @@ float activate(float x, uint kind, uint channel) { // definition does. return x < 0.0 ? x * float(weights[p.act_weight + channel]) : x; }+ if (kind == ACT_CLIP01) {+ // A normalised ONNX HardSigmoid: its alpha and beta were folded into this+ // layer's weight and bias by `scripts/ml/ppocr_fold.py`, so what is left is the+ // clamp. See `nets::Act::Clip01`.+ return clamp(x, 0.0, 1.0);+ } return x; }
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 497666d34b..ccb41972ec 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -87,6 +87,14 @@ pub enum Act { /// passes down in [`Push::act_weight`]. A plain `Relu` is the same thing at slope /// zero, and is kept separate because it needs no memory traffic at all. PRelu(usize),+ /// `clamp(x, 0, 1)`.+ ///+ /// This is a **normalised** `HardSigmoid`. ONNX's is `clamp(alpha * x + beta, 0, 1)`+ /// and PP-OCRv5 uses two different alphas, but `alpha` and `beta` fold into the+ /// convolution's weight and bias — `scripts/ml/ppocr_fold.py` does it — so the+ /// runtime needs one parameterless clamp rather than an activation carrying two+ /// floats through the push block.+ Clip01, } impl Act {@@ -97,6 +105,7 @@ impl Act { Act::HardSwish => 2, Act::Sigmoid => 3, Act::PRelu(_) => 4,+ Act::Clip01 => 5, } } }@@ -125,6 +134,14 @@ pub enum Kind { Add, /// `a * b` where `b` is `C x 1 x 1`. The excite in a squeeze-excite block. MulBroadcast,+ /// `x * scale + shift`, both scalars. PP-OCRv5's "learnable affine block".+ ///+ /// 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.+ Affine, } /// The push-constant block every shader declares.@@ -181,6 +198,13 @@ pub struct Push { /// Element offset of the per-channel slope [`Act::PRelu`] reads, in the weights /// buffer. Zero and unread for every other activation. pub act_weight: u32,+ /// [`Kind::Affine`]'s multiplier, as raw bits. Unread by everything else.+ ///+ /// `f32` bits rather than an `f32` field so [`Push`] stays all-`u32` and+ /// `push_bytes` can keep treating it as a plain byte block with no padding.+ pub scale_bits: u32,+ /// [`Kind::Affine`]'s addend, as raw bits.+ pub shift_bits: u32, /// Output elements, so an over-dispatched workgroup can bail. pub count: u32, }@@ -331,6 +355,12 @@ enum Node { parts: Vec<Id>, out: Id, },+ Affine {+ input: Id,+ out: Id,+ scale: f32,+ shift: f32,+ }, } /// Records a forward pass, then packs and resolves it.@@ -652,6 +682,14 @@ impl<'a> Builder<'a> { out } + /// `x * scale + shift`, elementwise with scalar parameters. See [`Kind::Affine`].+ pub fn affine(&mut self, input: Id, scale: f32, shift: f32) -> Id {+ let shape = self.shape_of(input);+ let out = self.tensor(shape);+ self.nodes.push(Node::Affine { input, out, scale, shift });+ out+ }+ /// Pack the arena and resolve every offset, with `outputs` as the result tensors. pub fn finish(mut self, outputs: &[Id]) -> Result<Plan, String> { self.pinned.extend_from_slice(outputs);@@ -899,6 +937,27 @@ impl<'a> Builder<'a> { written += len; } }+ Node::Affine { input, out, scale, shift } => {+ let so = shape(*out);+ ops.push(Op::Dispatch {+ kind: Kind::Affine,+ push: Push {+ in0: at(*input)?,+ out: at(*out)?,+ in_c: so.c,+ in_h: so.h,+ in_w: so.w,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ scale_bits: scale.to_bits(),+ shift_bits: shift.to_bits(),+ count: so.len(),+ ..Push::default()+ },+ invocations: so.len(),+ });+ } } Ok(()) }@@ -912,6 +971,7 @@ impl Node { | Node::Resize { out, .. } | Node::GlobalAvgPool { out, .. } | Node::Binary { out, .. }+ | Node::Affine { out, .. } | Node::Concat { out, .. } => *out, } }@@ -921,6 +981,7 @@ impl Node { Node::Conv { input, .. } | Node::MaxPool { input, .. } | Node::Resize { input, .. }+ | Node::Affine { input, .. } | Node::GlobalAvgPool { input, .. } => vec![*input], Node::Binary { a, b, .. } => vec![*a, *b], Node::Concat { parts, .. } => parts.clone(),@@ -1110,7 +1171,7 @@ pub(crate) mod tests { fn the_push_block_has_no_padding() { // The shaders read it at fixed offsets, so a gap Rust inserted would shift // every field after it.- assert_eq!(std::mem::size_of::<Push>(), 23 * 4);+ assert_eq!(std::mem::size_of::<Push>(), 25 * 4); assert_eq!(std::mem::align_of::<Push>(), 4); }
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 b8249d3369..b0ffc4c0c3 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -55,6 +55,8 @@ mod act { pub const SIGMOID: u32 = 3; /// `x < 0 ? slope[c] * x : x`. pub const PRELU: u32 = 4;+ /// `clamp(x, 0, 1)`, a normalised `HardSigmoid`.+ pub const CLIP01: u32 = 5; } /// The fused activation, mirroring `activate` in `common.glsl`.@@ -73,6 +75,7 @@ fn activate(x: f32, kind: u32, slope: f32) -> f32 { x } }+ act::CLIP01 => x.clamp(0.0, 1.0), _ => x, } }@@ -171,6 +174,7 @@ impl Reference { Kind::GlobalAvgPool => self.global_avg_pool(push), Kind::Add => self.add(push), Kind::MulBroadcast => self.mul_broadcast(push),+ Kind::Affine => self.affine(push), }, }; result.map_err(|e| format!("step {step} ({op:?}): {e}"))?;@@ -412,6 +416,17 @@ impl Reference { Ok(()) } + /// `out = in * scale + shift`, both scalars carried as raw bits in the push block.+ fn affine(&mut self, p: &Push) -> Result<(), String> {+ let scale = f32::from_bits(p.scale_bits);+ let shift = f32::from_bits(p.shift_bits);+ for i in 0..p.count {+ let value = self.load(p.in0, i)?;+ self.store(p.out, i, value * scale + shift)?;+ }+ Ok(())+ }+ /// Elementwise sum of two equal shapes. fn add(&mut self, p: &Push) -> Result<(), String> { for i in 0..p.count {@@ -967,6 +982,63 @@ mod tests { assert!(error.contains("2 outputs"), "{error}"); } + #[test]+ fn an_affine_scales_and_shifts_every_element_by_the_same_scalars() {+ let got = one(Shape::new(1, 1, 4), &[-2.0, 0.0, 1.0, 4.0], &[], |b, x| {+ b.affine(x, 0.5, 3.0)+ });+ close(&got, &[2.0, 3.0, 3.5, 5.0]);+ }++ #[test]+ fn an_affine_carries_its_scalars_through_the_push_block_as_bits() {+ // The two parameters are `f32` bits in a `u32` field so `Push` stays all-`u32`.+ // A value with a non-trivial mantissa catches a reinterpretation that happens to+ // work for small integers.+ let got = one(Shape::new(1, 1, 2), &[1.0, 2.0], &[], |b, x| {+ b.affine(x, 0.3, -0.7)+ });+ close(&got, &[0.3 - 0.7, 0.6 - 0.7]);+ }++ #[test]+ fn clip01_clamps_to_the_unit_interval() {+ // A normalised HardSigmoid: `ppocr_fold.py` folds alpha and beta into the+ // convolution, so what reaches the shader is the bare clamp.+ let got = one(+ Shape::new(1, 1, 5),+ &[-4.0, -0.5, 0.25, 1.0, 9.0],+ &[(vec![1, 1, 1, 1], vec![1.0]), (vec![1], vec![0.0])],+ |b, x| b.conv_same(x, 0, 1, 1, 1, Act::Clip01),+ );+ close(&got, &[0.0, 0.0, 0.25, 1.0, 1.0]);+ }++ #[test]+ fn a_folded_hard_sigmoid_matches_the_onnx_definition() {+ // The fold's claim: `clamp(alpha * (w*x + b) + beta, 0, 1)` equals+ // `clamp(w'*x + b', 0, 1)` with `w' = alpha*w` and `b' = alpha*b + beta`. Checked+ // here against ONNX's formula computed directly, at both alphas PP-OCRv5 uses.+ for alpha in [0.2f32, 1.0 / 6.0] {+ let (w, bias) = (2.0f32, -0.5f32);+ let inputs = [-3.0f32, -0.4, 0.0, 0.9, 5.0];+ let got = one(+ Shape::new(1, 1, 5),+ &inputs,+ &[+ (vec![1, 1, 1, 1], vec![alpha * w]),+ (vec![1], vec![alpha * bias + 0.5]),+ ],+ |b, x| b.conv_same(x, 0, 1, 1, 1, Act::Clip01),+ );+ let want: Vec<f32> = inputs+ .iter()+ .map(|&x| (alpha * (w * x + bias) + 0.5).clamp(0.0, 1.0))+ .collect();+ close(&got, &want);+ }+ }+ #[test] fn relu_clamps_at_zero_without_touching_positives() { let got = one(
library/ml/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline.rs b/library/ml/src/main/rust/src/vulkan/pipeline.rsindex e7548f73e8..93c19787c9 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -34,6 +34,7 @@ const RESIZE_NEAREST: &[u8] = const GAP: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gap.comp.spv")); const ADD: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/add.comp.spv")); const MUL_BCAST: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/mul_bcast.comp.spv"));+const AFFINE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/affine.comp.spv")); /// `local_size_x` in `shaders/common.glsl`. A dispatch covers `ceil(invocations / this)` /// workgroups, and each shader bails on the over-dispatched tail.@@ -64,6 +65,7 @@ pub struct Pipelines { gap: vk::Pipeline, add: vk::Pipeline, mul_bcast: vk::Pipeline,+ affine: vk::Pipeline, } impl Pipelines {@@ -172,7 +174,17 @@ impl Pipelines { cleanup.layout = Some(layout); let mut built = Vec::new();- for spirv in [CONV, CONV_TRANSPOSE, MAXPOOL, RESIZE, RESIZE_NEAREST, GAP, ADD, MUL_BCAST] {+ for spirv in [+ CONV,+ CONV_TRANSPOSE,+ MAXPOOL,+ RESIZE,+ RESIZE_NEAREST,+ GAP,+ ADD,+ MUL_BCAST,+ AFFINE,+ ] { match compute_pipeline(device, layout, spirv) { Ok(pipeline) => built.push(pipeline), Err(e) => {@@ -183,9 +195,9 @@ impl Pipelines { } } }- let [conv, conv_transpose, maxpool, resize, resize_nearest, gap, add, mul_bcast] =+ let [conv, conv_transpose, maxpool, resize, resize_nearest, gap, add, mul_bcast, affine] = match built.as_slice() {- [a, b, c, d, e, f, g, h] => [*a, *b, *c, *d, *e, *f, *g, *h],+ [a, b, c, d, e, f, g, h, i] => [*a, *b, *c, *d, *e, *f, *g, *h, *i], _ => return Err("wrong pipeline count".into()), }; @@ -203,6 +215,7 @@ impl Pipelines { gap, add, mul_bcast,+ affine, }) } @@ -217,6 +230,7 @@ impl Pipelines { Kind::GlobalAvgPool => self.gap, Kind::Add => self.add, Kind::MulBroadcast => self.mul_bcast,+ Kind::Affine => self.affine, } } @@ -233,6 +247,7 @@ impl Pipelines { self.gap, self.add, self.mul_bcast,+ self.affine, ] { device.destroy_pipeline(pipeline, None); }
library/ocr/src/main/assets/README.md
diff --git a/library/ocr/src/main/assets/README.md b/library/ocr/src/main/assets/README.mdnew file mode 100644index 0000000000..a5b8db8d58--- /dev/null+++ b/library/ocr/src/main/assets/README.md@@ -0,0 +1,57 @@+# `:library:ocr` bundled model assets++## `ppocr_det.vkml` — text detection++Apache-2.0, from https://huggingface.co/PaddlePaddle/PP-OCRv5_mobile_det_onnx+@ `e6f4fa85f00e168c862bc462aebca69eef9b3d3d` (`inference.onnx`, 4,826,518 B fp32,+SHA-256 `a4319856…597b6e61d`) — the official PaddleOCR export of PP-OCRv5 mobile+detection. The source ONNX SHA-256 is in the `.vkml` header, so a shipped asset traces+back to this line.++Rebuild with `./scripts/ml/fetch_and_convert.sh`.++### It is folded, not copied++Unlike every other `.vkml`, this one is **not** the ONNX's tensors verbatim. The export+is PP-HGNetV2 as `paddle2onnx` spells it, and every convolution arrives as a chain:++ Conv (no bias) → Add(bias) → Mul(scalar) → Add(scalar)+ → HardSigmoid(α=1/6) → Mul(self) → Mul(scalar) → Add(scalar)++threaded through 192 `Identity` nodes. That is 62 convolutions, 117 `Add`s, 86 `Mul`s and+34 `HardSigmoid`s, of which only about a dozen `Add`/`Mul` pairs are real ops — the+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+convolutions, 10 average pools, 10 channel multiplies, 11 adds, 6 nearest resizes, 1+concatenation and 24 scalar affines.++That op inventory matches ncnn's independent conversion of the same model layer for layer+(`Convolution` 48 + `ConvolutionDepthWise` 14 = 62, `Pooling` 10, `Interp` 6,+`Deconvolution` 2, `HardSwish` 24, `HardSigmoid` 10, `Concat` 1), which is the strongest+available check that the fold is right.++### Preprocessing and post-processing++From the export's own `inference.yml`, not guessed:++* **BGR**, not RGB (`DecodeImage: img_mode: BGR`).+* Long side resized to **960** (`DetResizeForTest: resize_long: 960`).+* ImageNet mean/std — the same constants `u2netp` uses.+* DBNet post-processing: `thresh: 0.3`, `box_thresh: 0.6`, `max_candidates: 1000`,+ `unclip_ratio: 1.5`.++## 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 (2 multi-head attentions, 5 layer norms,+batched matmul, softmax) plus the 838-entry character dictionary and CTC decoding.++`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.
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.vkmlnew file mode 100644index 0000000000..dce2c3256cBinary files /dev/null and b/library/ocr/src/main/assets/ppocr_det.vkml differ
scripts/ml/fetch_and_convert.sh
diff --git a/scripts/ml/fetch_and_convert.sh b/scripts/ml/fetch_and_convert.shindex 7436ee2134..f8fc6db139 100644--- a/scripts/ml/fetch_and_convert.sh+++ b/scripts/ml/fetch_and_convert.sh@@ -7,6 +7,7 @@ # photos/src/main/assets/u2netp.vkml U^2-Net portable (saliency) # 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) # # 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** —@@ -31,7 +32,12 @@ # set -euo pipefail -# repo-relative-dest graph sha256(onnx) url+# repo-relative-dest graph sha256(onnx) url [converter]+#+# The converter defaults to vkml_convert.py. PP-OCRv5 uses ppocr_fold.py instead: its+# export spells every convolution as a chain of constant Add/Mul/HardSigmoid nodes that+# has to be folded first, and doing that inside vkml_convert.py would make "the tensors+# verbatim" stop being true for every other model. See that script's header. # # Pinned to a commit rather than to `main`: the file SHA-256 below would catch a # silent upstream change anyway, but a pinned revision means --update tells you the@@ -41,6 +47,7 @@ MODELS=( "photos/src/main/assets/u2netp.vkml u2netp 309c8469258dda742793dce0ebea8e6dd393174f89934733ecc8b14c76f4ddd8 https://huggingface.co/BritishWerewolf/U-2-Netp/resolve/7112208dbac3a3642496c8d54e2f0f9bb3dc1dc8/onnx/model.onnx" "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" ) if [ ! -f settings.gradle.kts ]; then@@ -83,6 +90,7 @@ for entry in "${MODELS[@]}"; do graph="$2" want="$3" url="$4"+ converter="${5:-vkml_convert.py}" onnx="${work}/${graph}.onnx" echo "Downloading ${graph} from ${url}..."@@ -106,7 +114,7 @@ for entry in "${MODELS[@]}"; do [ "$layers" = 1 ] && extra="--print-layers" mkdir -p "$(dirname "$dest")" # shellcheck disable=SC2086- "$python" scripts/ml/vkml_convert.py "$onnx" --graph "$graph" -o "$dest" $extra+ "$python" "scripts/ml/${converter}" "$onnx" --graph "$graph" -o "$dest" $extra done echo
scripts/ml/ppocr_fold.py
diff --git a/scripts/ml/ppocr_fold.py b/scripts/ml/ppocr_fold.pynew file mode 100644index 0000000000..47559b6d62--- /dev/null+++ b/scripts/ml/ppocr_fold.py@@ -0,0 +1,407 @@+#!/usr/bin/env python3+"""Fold a PP-OCRv5 `paddle2onnx` export into `.vkml`, ahead of time.++PP-OCRv5's official ONNX (Apache-2.0, `PaddlePaddle/PP-OCRv5_*_onnx`) is PP-HGNetV2 as+`paddle2onnx` spells it, which is not a form `:library:ml` can lower. Every convolution+arrives as a chain:++ Conv (no bias)+ -> Add(bias, shape [1, C, 1, 1])+ -> Mul(scalar) -> Add(scalar) a "learnable affine block"+ -> HardSigmoid(alpha=1/6) -> Mul(self) a HardSwish, spelled out+ -> Mul(scalar) -> Add(scalar) another affine block++with 192 `Identity` nodes threaded through it. In the detection export that is 62+convolutions, 117 `Add`s, 86 `Mul`s and 34 `HardSigmoid`s, of which only about a dozen+`Add`/`Mul` pairs are real ops \u2014 the feature-pyramid residuals and the squeeze-excite+gates. Everything else is constant.++# Why this is a separate script++`vkml_convert.py`'s contract is that a `.vkml` is the ONNX's tensors *verbatim*, so the+Rust can index them positionally and nothing has to agree about a rewrite. Teaching it to+constant-fold a graph would make that contract "verbatim, except for these seven+rewrites", and the rewrites would then run on every model it converts.++So the fold happens here instead, once, ahead of time. The output is a `.vkml` whose+tensors are the folded weights and biases, and the input is the official export with its+SHA-256 recorded in the header exactly as before. Provenance is unchanged; only the place+the arithmetic happens moves.++# What is folded, and why it is exact++At inference every one of these is an affine map on a convolution's output, and an affine+map composed with a convolution is a convolution:++* `Add(x, bias)` becomes the bias the shaders already add.+* `Mul(x, s)` for a scalar or per-channel `s` scales the weight and the bias.+* `Add(x, t)` adds to the bias.+* `BatchNormalization` is `gamma * (x - mean) / sqrt(var + eps) + beta`, so it is the+ same shape of thing.+* `HardSigmoid(alpha=1/6, beta=0.5)` followed by `Mul` against its own input is the+ definition of `HardSwish`, which the runtime fuses into the convolution's store.++None of that is an approximation. The one thing deliberately **not** folded is an affine+block that sits *after* an activation: pushing it through the next convolution needs+`b' += t * sum(W)` over each output row, which is only valid when the tensor feeds+convolutions and nothing else. Rather than depend on that, those are emitted as an+`Affine` op the runtime runs as an elementwise pass. There are a couple of dozen, and+detection runs once per OCR request rather than per frame.++ ./scripts/ml/ppocr_fold.py det.onnx --graph ppocr_det -o out.vkml+ ./scripts/ml/ppocr_fold.py det.onnx --graph ppocr_det --print-graph+"""++import argparse+import hashlib+import os+import sys++import numpy as np+import onnx+from onnx import numpy_helper++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import vkml_convert # noqa: E402 (needs the path above)++# ONNX `HardSigmoid` defaults to alpha 0.2; Paddle's hard-swish uses 1/6. Both appear in+# these graphs, so the value is read per node and checked rather than assumed.+HARDSWISH_ALPHA = 1.0 / 6.0+TOLERANCE = 1e-4+++class Op:+ """One op in the normalised graph, as the Rust forward pass will see it."""++ def __init__(self, kind, inputs, output, **extra):+ self.kind = kind+ self.inputs = inputs+ self.output = output+ self.extra = extra++ def __str__(self):+ detail = " ".join(f"{k}={v}" for k, v in self.extra.items())+ return f"{self.kind:14s} {self.inputs} -> {self.output} {detail}"+++def resolve(name, alias):+ """Follow an `Identity` alias chain to the tensor that actually produced it."""+ seen = set()+ while name in alias and name not in seen:+ seen.add(name)+ name = alias[name]+ return name+++def normalise(model):+ """Strip `Identity`, fold the constant affine chains, and return the ops and tensors.++ Returns `(ops, layers, tensors)`: the normalised op list for transcription, the+ `Layer` records the digest is taken over, and the fp16 tensors in `.vkml` order.+ """+ graph = model.graph+ inits = {i.name: numpy_helper.to_array(i) for i in graph.initializer}++ # Rewire Identity without mutating the nodes: build an alias map and read every+ # input through it.+ alias = {}+ for node in graph.node:+ if node.op_type == "Identity":+ alias[node.output[0]] = node.input[0]+ nodes = [n for n in graph.node if n.op_type != "Identity"]+ inputs_of = {id(n): [resolve(i, alias) for i in n.input] for n in nodes}++ producer = {}+ consumers = {}+ for node in nodes:+ for name in inputs_of[id(node)]:+ consumers.setdefault(name, []).append(node)+ for name in node.output:+ producer[name] = node++ def constant(node, index):+ """The constant operand of a binary node, or `(None, None)`."""+ names = inputs_of[id(node)]+ for position, name in enumerate(names):+ if name in inits:+ other = names[1 - position] if len(names) == 2 else None+ if index is None or position == index:+ return inits[name], other+ return None, None++ consumed = set()+ ops = []+ layers = []+ tensors = []++ def emit_conv(node, weight, bias, act, act_alpha, output):+ first = len(tensors)+ tensors.append(weight.astype(np.float32))+ tensors.append(bias.astype(np.float32))+ attrs = {a.name: a for a in node.attribute}++ def ints(name, default):+ return list(attrs[name].ints) if name in attrs else list(default)++ key = (+ f"{node.op_type} w={list(weight.shape)} b={list(bias.shape)} "+ f"k={ints('kernel_shape', weight.shape[2:])} "+ f"d={ints('dilations', (1, 1))} p={ints('pads', (0, 0, 0, 0))} "+ f"s={ints('strides', (1, 1))} "+ f"g={attrs['group'].i if 'group' in attrs else 1} act={act}"+ )+ layers.append(+ vkml_convert.Layer(len(layers), node.op_type, output, key, first, 2)+ )+ ops.append(+ Op(+ node.op_type,+ [inputs_of[id(node)][0]],+ output,+ w=list(weight.shape),+ k=ints("kernel_shape", weight.shape[2:]),+ s=ints("strides", (1, 1)),+ p=ints("pads", (0, 0, 0, 0)),+ g=attrs["group"].i if "group" in attrs else 1,+ act=act,+ t=first,+ )+ )++ for node in nodes:+ if id(node) in consumed:+ continue+ if node.op_type in ("Conv", "ConvTranspose"):+ names = inputs_of[id(node)]+ weight = np.array(inits[names[1]], dtype=np.float64)+ channels = weight.shape[1] if node.op_type == "ConvTranspose" else weight.shape[0]+ bias = (+ np.array(inits[names[2]], dtype=np.float64).flatten()+ 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)+ elif node.op_type in ("Add", "Mul"):+ value, other = constant(node, None)+ if value is not None:+ # A leftover constant affine: it follows an activation, so it could not be+ # folded above. One elementwise pass rather than a weight rewrite whose+ # validity depends on what the tensor feeds.+ scalar = np.array(value, dtype=np.float64).flatten()+ if scalar.size != 1:+ raise SystemExit(+ f"{node.output[0]}: a leftover {node.op_type} against a "+ f"{list(np.array(value).shape)} constant, which is not a scalar affine"+ )+ scale = float(scalar[0]) if node.op_type == "Mul" else 1.0+ shift = float(scalar[0]) if node.op_type == "Add" else 0.0+ ops.append(Op("Affine", [other], node.output[0], scale=scale, shift=shift))+ else:+ ops.append(Op(node.op_type, inputs_of[id(node)], node.output[0]))+ else:+ ops.append(Op(node.op_type, inputs_of[id(node)], node.output[0]))++ return merge_affines(ops, consumers), layers, tensors+++def merge_affines(ops, consumers):+ """Collapse a `Mul(scalar)` immediately followed by an `Add(scalar)` into one op.++ `paddle2onnx` spells a learnable affine block as two nodes, so folding leaves them as+ two `Affine`s in a row. One op is one pass over the data instead of two.+ """+ by_input = {}+ for index, op in enumerate(ops):+ for name in op.inputs:+ by_input.setdefault(name, []).append(index)++ merged = []+ absorbed = set()+ for index, op in enumerate(ops):+ if index in absorbed:+ continue+ if op.kind == "Affine":+ followers = by_input.get(op.output, [])+ if len(followers) == 1:+ nxt = ops[followers[0]]+ # Only when the second is the other half: a scale then a shift.+ if (+ nxt.kind == "Affine"+ and len(consumers.get(op.output, [])) <= 1+ and (op.extra["shift"] == 0.0 or nxt.extra["scale"] == 1.0)+ ):+ op = Op(+ "Affine",+ op.inputs,+ nxt.output,+ # `(x * a + s) * a2 + s2`, with one of the two halves the identity.+ scale=op.extra["scale"] * nxt.extra["scale"],+ shift=op.extra["shift"] * nxt.extra["scale"] + nxt.extra["shift"],+ )+ absorbed.add(followers[0])+ merged.append(op)+ return merged+++def fold_batch_norm(node, inits, weight, bias, op_type):+ """`gamma * (x - mean) / sqrt(var + eps) + beta`, pushed into a weight and bias."""+ attrs = {a.name: a.f for a in node.attribute}+ epsilon = attrs.get("epsilon", 1e-5)+ gamma, beta, mean, var = (+ np.array(inits[n], dtype=np.float64) for n in node.input[1:5]+ )+ scale = gamma / np.sqrt(var + epsilon)+ shape = [1] * weight.ndim+ shape[1 if op_type == "ConvTranspose" else 0] = scale.size+ return weight * scale.reshape(shape), (bias - mean) * scale + beta+++def main():+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("onnx")+ parser.add_argument("--graph", required=True, choices=sorted(vkml_convert.GRAPHS))+ parser.add_argument("-o", "--out", help="where to write the .vkml")+ parser.add_argument("--print-graph", action="store_true", help="dump the folded ops")+ parser.add_argument("--print-layers", action="store_true")+ parser.add_argument("--print-digest", action="store_true")+ args = parser.parse_args()++ with open(args.onnx, "rb") as f:+ raw = f.read()+ onnx_sha256 = hashlib.sha256(raw).digest()++ model = onnx.load(args.onnx)+ ops, layers, tensors = normalise(model)++ if args.print_graph:+ for index, op in enumerate(ops):+ print(f"{index:4d} {op}")+ if args.print_layers:+ for layer in layers:+ print(f"{layer.index:4d} t{layer.first_tensor:<4d} {layer.key()} # {layer.name}")++ digest = vkml_convert.layer_table_digest(layers)+ if args.print_digest:+ print(f' "{args.graph}": "{digest}",')+ pinned = vkml_convert.EXPECTED_DIGEST.get(args.graph, "")+ if digest != pinned and not args.print_digest:+ raise SystemExit(+ f"layer table digest {digest}\n pinned {pinned}\n"+ "The folded layer table changed, so the hardcoded forward pass no longer\n"+ "matches this export. Re-read it with --print-graph, update the Rust, then\n"+ "re-pin with --print-digest."+ )++ blob, count = vkml_convert.build(+ layers, tensors, vkml_convert.GRAPHS[args.graph], onnx_sha256+ )+ if args.out:+ with open(args.out, "wb") as f:+ f.write(blob)+ kinds = {}+ for op in ops:+ kinds[op.kind] = kinds.get(op.kind, 0) + 1+ print(+ f"{args.graph}: {count} folded layers, {len(tensors)} tensors, "+ f"{len(blob)} bytes ({len(raw)} fp32 in)"+ )+ print(f" normalised ops: {kinds}")+++if __name__ == "__main__":+ main()
scripts/ml/vkml_convert.py
diff --git a/scripts/ml/vkml_convert.py b/scripts/ml/vkml_convert.pyindex 06889ea79e..7cf0a52559 100644--- a/scripts/ml/vkml_convert.py+++ b/scripts/ml/vkml_convert.py@@ -94,6 +94,9 @@ GRAPHS = { "u2netp": 2, "scrfd": 3, "mobilefacenet": 4,+ # Folded ahead of time by `scripts/ml/ppocr_fold.py`, not by this script.+ "ppocr_det": 5,+ "ppocr_rec": 6, } # SHA-256 over the ordered layer table (see `layer_table_digest`). Regenerate with@@ -103,6 +106,8 @@ EXPECTED_DIGEST = { "u2netp": "f5199e05e4d4e93a6af601d04e3e0516bb68b9f292bb81d474704ea0b4e591d0", "scrfd": "d2ce2880a432af03b0ef594029d3ab03d86de54bd0a9f10ea2c8e412309b0f46", "mobilefacenet": "40987839aec03378958581deba29ce9fd9dd1ae9aa88d0c7ad04a885a2e2122c",+ "ppocr_det": "51b0c9ed871526fa270b4bfa53b393c056db21c58193849fb83d44768f69ef9b",+ "ppocr_rec": "", } # What each graph is exported at, as `[channels, height, width]` after the batch