library:ml: PP-OCRv5 recognition, cross-checked against ncnn's params
- Commit
a03f3644a32e616b523251fd0bdd58f675a259d0- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 19:15 UTC (3 months ago)
- Parents
5c15c40
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 f6fb149eaf..c60fbc40f2 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -33,6 +33,7 @@ pub mod reference; pub mod mobilefacenet; pub mod ppocr_det;+pub mod ppocr_rec; pub mod scrfd; pub mod selfie; pub mod u2netp;
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.rsnew file mode 100644index 0000000000..0d445807a9--- /dev/null+++ b/library/ml/src/main/rust/src/nets/ppocr_rec.rs@@ -0,0 +1,503 @@+//! PP-OCRv5 mobile text recognition: a PP-LCNetV3 backbone into a small transformer.+//!+//! # The shape of it+//!+//! A line crop comes in at `3 x 48 x W`. Thirty-three convolutions reduce it to+//! `480 x 3 x W/8`, one average pool with an asymmetric window collapses the last three+//! rows and halves the width again, and what comes out is `480 x 1 x W/8` — a sequence of+//! `T = W/8` positions. Two pre-norm transformer blocks run over that, the result is+//! concatenated back onto the pooled features, and a final `1x1` emits+//! [`crate::post::ctc::LOGITS`] logits per position for a CTC decode.+//!+//! Height is **fixed** at [`HEIGHT`] rather than being a parameter, and that is not a+//! simplification. Four layers carry a vertical stride of 2 (48 → 24 → 12 → 6 → 3) and+//! the pool's kernel height is exactly 3, so the whole vertical path is a chain of+//! constants that only closes at 48. A different height would need a different pool.+//!+//! # It is folded, like detection+//!+//! Same export shape as `ppocr_det`, same `scripts/ml/ppocr_fold.py`: every convolution+//! arrives as `Conv → Mul(scalar) → Add(scalar) → HardSigmoid(1/6) → Mul(self) →+//! Mul(scalar) → Add(scalar)`, and all of the constant part folds into the weight and+//! bias ahead of time. So every layer here is a convolution with a fused activation, and+//! [`TENSORS`] is exactly twice the layer count.+//!+//! The recogniser adds three things detection did not have, and each is the reason a+//! pipeline exists:+//!+//! * **Swish**, `x * sigmoid(x)`, seven times — spelled `Mul(x, Sigmoid(x))` in the+//! export and recognised by the fold the way `HardSwish` is. Not interchangeable with+//! `HardSwish`, which this same graph also uses 31 times.+//! * **Layer norm over the channel axis**, five times, four at epsilon `1e-5` and the+//! last at `1e-6`.+//! * **Attention**, twice, at [`D_MODEL`] 120 in [`HEADS`] 8.+//!+//! # Why there is no permute anywhere+//!+//! The sequence is `[d_model, 1, T]` — the layout the backbone already produces. The ncnn+//! conversion of this same model has to `Reshape` and `Permute` into `[T, d_model]` before+//! its `LayerNorm`, and back again afterwards, four times. Here both are no-ops and are+//! simply not transcribed:+//!+//! * Every projection — the eleven in the two blocks, plus the classifier — is a `1x1`+//! convolution over channels.+//! * Splitting `d_model` into heads is free, because `[120, 1, T]` read as `[8, 15, T]`+//! is the same bytes in the same order.+//!+//! See [`super::Kind::LayerNorm`] for the full argument and [`super::Kind::AttnScores`]+//! for what the attention pipelines do with it.+//!+//! # The output is raw logits, class-major+//!+//! The export ends in a `Softmax` over the 838 classes. That is **not** transcribed: the+//! output here is `[LOGITS, 1, T]`, unnormalised, and+//! [`crate::post::ctc::decode`] takes it from there.+//!+//! Two reasons. The layout is one: a softmax over classes in this layout reduces over+//! channels, and the result would still be class-major while a CTC decode wants one row+//! per timestep — so a transpose on the host is unavoidable either way. The other is that+//! the decode does not need the distribution at all. It needs the argmax, which a softmax+//! cannot change, and the winner's probability, which is `1 / sum(exp(x - max))` from the+//! raw logits directly. So the pass is not merely moved to the host, it is deleted.++use super::{Act, Builder, Id, Plan, Shape, WeightSource};++/// Input height, in pixels. Fixed; see the module docs.+pub const HEIGHT: u32 = 48;++/// The input width must be a positive multiple of this.+///+/// Three stride-2 stages act on the width — the stem, one depthwise in the third block,+/// and the pool — so `T` is `W / 8`. A width that is not a multiple would make one of the+/// three floor, silently dropping the last column of the line.+pub const WIDTH_MULTIPLE: u32 = 8;++/// Channels the backbone ends on, which is also the sequence's width before projection.+pub const FEATURES: u32 = 480;++/// The transformer's width.+pub const D_MODEL: u32 = 120;++/// Attention heads, so `head_dim` is 15.+pub const HEADS: u32 = 8;++/// The feed-forward block's inner width.+pub const FFN: u32 = 240;++/// Logits per timestep, which is the CTC label space and not a free choice.+pub const LOGITS: u32 = crate::post::ctc::LOGITS as u32;++/// Tensors the `.vkml` must hold: 56 folded layers, each a weight and a bias.+///+/// 33 backbone convolutions (of which 4 are the two squeeze-excite blocks' squeeze and+/// expand), 2 into the sequence, 8 per transformer block, the final layer norm, and 4 in+/// the head including the classifier — `(33 + 2 + 16 + 1 + 4) * 2`.+pub const TENSORS: usize = 112;++/// 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.+struct Layers {+ next: usize,+}++impl Layers {+ fn take(&mut self) -> usize {+ let index = self.next;+ self.next += 2;+ index+ }+}++/// A 1x1 convolution, which in this net is also every linear projection.+fn point(b: &mut Builder, l: &mut Layers, x: Id, out: u32, act: Act) -> Id {+ b.conv(x, l.take(), out, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, act)+}++/// A `k x k` depthwise convolution, padded to hold the extent, at an independent stride+/// per axis.+///+/// The per-axis stride is the point: four of these stride the height alone and one+/// strides the width alone, which is how a 48-row crop becomes 3 rows while the width+/// only halves once in the backbone. A single stride would collapse the two.+fn depthwise(b: &mut Builder, l: &mut Layers, x: Id, kernel: u32, stride: (u32, u32)) -> Id {+ let channels = b.shape(x).c;+ let pad = kernel / 2;+ b.conv(+ x,+ l.take(),+ channels,+ (kernel, kernel),+ stride,+ (1, 1),+ (pad, pad, pad, pad),+ channels,+ Act::HardSwish,+ )+}++/// A `1 x 3` convolution along the sequence, padded to hold `T`.+///+/// Both uses sit in the head, after the map is one row tall, so the kernel is wide and+/// flat rather than square: it mixes three neighbouring timesteps and nothing vertical.+fn along_sequence(b: &mut Builder, l: &mut Layers, x: Id, out: u32) -> Id {+ b.conv(x, l.take(), out, (1, 3), (1, 1), (1, 1), (0, 1, 0, 1), 1, Act::Swish)+}++/// `x * gate(x)`, a squeeze-excite. Two uses, both plain rather than residual.+fn squeeze_excite(b: &mut Builder, l: &mut Layers, x: Id, reduce: u32) -> Id {+ let channels = b.shape(x).c;+ let pooled = b.global_avg_pool(x);+ let squeezed = point(b, l, pooled, reduce, Act::Relu);+ // `Clip01` rather than a HardSigmoid: the fold pushed its alpha and beta into this+ // convolution's weight and bias, leaving the bare clamp.+ let gate = point(b, l, squeezed, channels, Act::Clip01);+ b.mul_channel(x, gate)+}++/// Multi-head attention over `[d_model, 1, T]`, with no permute and no reshape.+///+/// Four projections, all `1x1`: query, key, value, and the output. In between, the score+/// map, its softmax and the weighted sum. The `1 / sqrt(head_dim)` scale is derived by+/// [`Builder::attn_scores`] from [`HEADS`] rather than passed in.+fn attention(b: &mut Builder, l: &mut Layers, x: Id) -> Id {+ let q = point(b, l, x, D_MODEL, Act::None);+ let k = point(b, l, x, D_MODEL, Act::None);+ let v = point(b, l, x, D_MODEL, Act::None);+ let scores = b.attn_scores(q, k, HEADS);+ let probs = b.softmax(scores);+ let mixed = b.attn_apply(probs, v, HEADS);+ point(b, l, mixed, D_MODEL, Act::None)+}++/// One pre-norm transformer block: `x + attn(norm(x))`, then `x + ffn(norm(x))`.+///+/// Pre-norm, not post-norm — the residual adds the *unnormalised* input, which is what+/// the export does and is visible in its graph as the `Split` before each `LayerNorm`.+fn block(b: &mut Builder, l: &mut Layers, x: Id) -> Id {+ let normed = b.layer_norm(x, l.take(), 1e-5);+ let attended = attention(b, l, normed);+ let residual = b.add(x, attended);++ let normed = b.layer_norm(residual, l.take(), 1e-5);+ let inner = point(b, l, normed, FFN, Act::Swish);+ let projected = point(b, l, inner, D_MODEL, Act::None);+ b.add(residual, projected)+}++/// Build the recognition pass for a `48 x width` crop.+///+/// `width` must be a positive multiple of [`WIDTH_MULTIPLE`]; the output is+/// `[LOGITS, 1, width / 8]`.+pub fn build(weights: &dyn WeightSource, width: u32) -> Result<Plan, String> {+ if width == 0 || !width.is_multiple_of(WIDTH_MULTIPLE) {+ return Err(format!(+ "a recognition width of {width}: three stride-2 stages act on it, so it must \+ be a positive multiple of {WIDTH_MULTIPLE}"+ ));+ }++ let l = &mut Layers { next: 0 };+ let mut builder = Builder::new(weights);+ let b = &mut builder;+ let input = b.input(Shape::new(3, HEIGHT, width));++ // 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 [+ (32, (1, 1)),+ (64, (1, 1)),+ (64, (1, 1)),+ (128, (2, 1)),+ (128, (1, 1)),+ (240, (1, 2)),+ ] {+ 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 {+ x = depthwise(b, l, x, 5, (1, 1));+ x = point(b, l, x, 240, Act::HardSwish);+ }+ // Then a fifth depthwise that halves the height and feeds the squeeze-excite+ // 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 = depthwise(b, l, x, 5, (2, 1));+ x = squeeze_excite(b, l, x, 60);++ x = point(b, l, x, FEATURES, Act::HardSwish);+ x = depthwise(b, l, x, 5, (1, 1));+ x = squeeze_excite(b, l, x, 120);++ x = point(b, l, x, FEATURES, Act::HardSwish);+ x = depthwise(b, l, x, 5, (2, 1));+ x = point(b, l, x, FEATURES, Act::HardSwish);+ x = depthwise(b, l, x, 5, (1, 1));+ x = point(b, l, x, FEATURES, Act::HardSwish);++ // Where a feature map becomes a sequence: the three surviving rows collapse to one+ // and the width halves a final time.+ let pooled = b.avg_pool(x, (3, 2), (3, 2));++ // Down to `d_model`, then the two blocks.+ let narrow = along_sequence(b, l, pooled, 60);+ let mut sequence = point(b, l, narrow, D_MODEL, Act::Swish);+ for _ in 0..2 {+ sequence = block(b, l, sequence);+ }+ // The fifth layer norm, and the only one at 1e-6.+ sequence = b.layer_norm(sequence, l.take(), 1e-6);++ // Back up to the backbone's width, and rejoined to the features it came from. The+ // pooled tensor comes first, which is the order the export's `Concat` uses.+ let widened = point(b, l, sequence, FEATURES, Act::Swish);+ let joined = b.concat(&[pooled, widened]);++ let narrow = along_sequence(b, l, joined, 60);+ let head = point(b, l, narrow, D_MODEL, Act::Swish);+ // The classifier. No softmax: see the module docs.+ let logits = point(b, l, head, LOGITS, Act::None);++ if l.next != TENSORS {+ return Err(format!("the forward pass claims {} tensors, not {TENSORS}", l.next));+ }+ builder.finish(&[logits])+}++#[cfg(test)]+mod tests {+ use super::super::tests::{assert_no_aliasing, Shapes};+ use super::super::{Kind, Op};+ use super::*;++ /// The width a line crop is padded to on device, and 320 / 8 = 40 timesteps.+ const WIDTH: u32 = 320;++ fn plan(width: u32) -> (Shapes, Plan) {+ let source = Shapes::new(TENSORS);+ let plan = build(&source, width).expect("ppocr_rec builds");+ (source, plan)+ }++ #[test]+ fn the_pass_reads_every_tensor_in_the_file_exactly_once() {+ let (source, _) = plan(WIDTH);+ let asked = source.asked.borrow();+ assert_eq!(asked.len(), TENSORS);+ // In order, with no repeats: `Builder::finish` rejects an unread tensor but not a+ // tensor read twice, which is what an off-by-one in `Layers` produces.+ let mut indices: Vec<usize> = asked.iter().map(|(i, _)| *i).collect();+ indices.sort_unstable();+ assert_eq!(indices, (0..TENSORS).collect::<Vec<usize>>());+ }++ #[test]+ fn the_output_is_one_logit_row_per_timestep() {+ let (_, plan) = plan(WIDTH);+ let out = plan.output().expect("one output");+ // Class-major `[838, 1, T]`, which is what the module docs promise the host.+ assert_eq!(out.shape, Shape::new(LOGITS, 1, WIDTH / 8));+ assert_eq!(plan.input().expect("one input").shape, Shape::new(3, HEIGHT, WIDTH));+ }++ #[test]+ fn the_timestep_count_is_the_width_over_eight() {+ // Three stride-2 stages act on the width. A net that lost one would still build+ // and would emit twice as many timesteps as the decode expects.+ for width in [8u32, 64, 320, 640] {+ let (_, plan) = plan(width);+ assert_eq!(+ plan.output().expect("one output").shape.w,+ width / 8,+ "at width {width}"+ );+ }+ }++ #[test]+ fn a_width_that_is_not_a_multiple_of_eight_is_refused() {+ let source = Shapes::new(TENSORS);+ for width in [0u32, 1, 12, 100, 321] {+ let error = build(&source, width).expect_err("a ragged width");+ assert!(error.contains("multiple of 8"), "at width {width}: {error}");+ }+ }++ #[test]+ fn the_op_inventory_matches_the_folded_graph() {+ let (_, plan) = plan(WIDTH);+ let mut counts = std::collections::BTreeMap::new();+ let mut copies = 0;+ for op in &plan.ops {+ match op {+ Op::Dispatch { kind, .. } => *counts.entry(format!("{kind:?}")).or_insert(0) += 1,+ Op::Copy { .. } => copies += 1,+ }+ }+ // 56 layers, every one a convolution: 33 backbone + 2 into the sequence + 8 per+ // block + 4 in the head. The five layer norms are the only layers that are not.+ assert_eq!(counts.get("Conv"), Some(&51), "{counts:?}");+ assert_eq!(counts.get("LayerNorm"), Some(&5), "{counts:?}");+ // Two squeeze-excites, each a pool and a channel multiply.+ assert_eq!(counts.get("GlobalAvgPool"), Some(&2), "{counts:?}");+ assert_eq!(counts.get("MulBroadcast"), Some(&2), "{counts:?}");+ // The one pool that turns the map into a sequence.+ assert_eq!(counts.get("AvgPool"), Some(&1), "{counts:?}");+ // Two attentions, each three ops.+ assert_eq!(counts.get("AttnScores"), Some(&2), "{counts:?}");+ assert_eq!(counts.get("Softmax"), Some(&2), "{counts:?}");+ assert_eq!(counts.get("AttnApply"), Some(&2), "{counts:?}");+ // Two residuals per block.+ assert_eq!(counts.get("Add"), Some(&4), "{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:?}");+ }++ #[test]+ fn the_tensor_table_matches_ncnns_independent_conversion() {+ // Every parameter the checked-in `latin_PP_OCRv5_mobile_rec.ncnn.param` declares:+ // the sum of `6=weight_data_size` over its 51 convolutions, `4 * 2=` over its two+ // `MultiHeadAttention`s, `8= * 9=` over its five `Gemm`s and `0=` over its five+ // `LayerNorm`s, plus one bias per output channel throughout.+ //+ // This is the strongest available check on the transcription, and the same one+ // `ppocr_det` leans on: ncnn converted this export independently, so a channel+ // count, kernel size or group that is wrong here disagrees with it. Every+ // individual weight size matches too — this is their sum because one number is+ // checkable by hand and 56 are not.+ let (source, _) = plan(WIDTH);+ let total: u64 = source+ .asked+ .borrow()+ .iter()+ .map(|(_, dims)| dims.iter().map(|&d| d as u64).product::<u64>())+ .sum();+ assert_eq!(total, 1_987_314);+ }++ #[test]+ fn the_backbone_reduces_the_height_to_three_before_the_pool() {+ // 48 → 24 → 12 → 6 → 3, four stride-2 stages on the height alone, then a kernel+ // of exactly 3 to collapse it. This is why the height is not a parameter: the+ // pool's window only matches at 48.+ let (_, plan) = plan(WIDTH);+ let pool = plan+ .ops+ .iter()+ .find_map(|op| match op {+ Op::Dispatch { kind: Kind::AvgPool, push, .. } => Some(*push),+ _ => None,+ })+ .expect("one average pool");+ assert_eq!((pool.in_c, pool.in_h, pool.in_w), (FEATURES, 3, WIDTH / 4));+ assert_eq!((pool.kh, pool.kw), (3, 2));+ assert_eq!((pool.out_c, pool.out_h, pool.out_w), (FEATURES, 1, WIDTH / 8));+ }++ #[test]+ fn every_attention_splits_d_model_into_eight_heads() {+ let (_, plan) = plan(WIDTH);+ let scores: Vec<super::super::Push> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ Op::Dispatch { kind: Kind::AttnScores, push, .. } => Some(*push),+ _ => None,+ })+ .collect();+ assert_eq!(scores.len(), 2);+ for push in scores {+ // Reading `[120, 1, T]` as `[8, 15, T]`, so the head count is in `group` and+ // the sequence is the width.+ assert_eq!((push.in_c, push.in_h, push.in_w), (D_MODEL, 1, WIDTH / 8));+ assert_eq!(push.group, HEADS);+ assert_eq!(push.in_c / push.group, 15);+ // The score map is `[heads, T, T]`.+ assert_eq!(+ (push.out_c, push.out_h, push.out_w),+ (HEADS, WIDTH / 8, WIDTH / 8)+ );+ // `1 / sqrt(15)`, derived from the geometry rather than read from the file.+ let scale = f32::from_bits(push.param0_bits);+ assert!((scale - 1.0 / 15f32.sqrt()).abs() < 1e-6, "{scale}");+ }+ }++ #[test]+ fn four_layer_norms_use_one_epsilon_and_the_last_uses_another() {+ // The export really does differ: 1e-5 through both blocks and 1e-6 on the final+ // one. A single hardcoded epsilon would be a small, invisible accuracy loss.+ let (_, plan) = plan(WIDTH);+ let epsilons: Vec<f32> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ Op::Dispatch { kind: Kind::LayerNorm, push, .. } => {+ Some(f32::from_bits(push.param1_bits))+ }+ _ => None,+ })+ .collect();+ assert_eq!(epsilons, vec![1e-5, 1e-5, 1e-5, 1e-5, 1e-6]);+ }++ #[test]+ fn every_layer_norm_reduces_over_d_model_and_one_position_at_a_time() {+ let (_, plan) = plan(WIDTH);+ for op in &plan.ops {+ if let Op::Dispatch { kind: Kind::LayerNorm, push, invocations } = op {+ assert_eq!(push.in_c, D_MODEL);+ // One invocation per position, not per element: `count` is the spatial+ // extent because each reduces a whole column of channels.+ assert_eq!(*invocations, WIDTH / 8);+ assert_eq!(push.count, WIDTH / 8);+ }+ }+ }++ #[test]+ fn the_head_concatenates_the_pooled_features_before_the_transformer_output() {+ // Order is load-bearing: the export's `Concat` puts the skip first, and swapping+ // the two halves changes which 480 channels the next convolution's weights see.+ let (_, plan) = plan(WIDTH);+ let copies: Vec<(u32, u32, u32)> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ Op::Copy { src, dst, elems } => Some((*src, *dst, *elems)),+ _ => None,+ })+ .collect();+ let [(_, first_dst, first_elems), (_, second_dst, second_elems)] =+ <[(u32, u32, u32); 2]>::try_from(copies.as_slice()).expect("two copies");+ assert_eq!(first_elems, FEATURES * WIDTH / 8);+ assert_eq!(second_elems, FEATURES * WIDTH / 8);+ assert_eq!(second_dst, first_dst + first_elems);+ }++ #[test]+ fn no_op_reads_a_region_of_the_arena_that_it_also_writes() {+ let (_, plan) = plan(WIDTH);+ assert_no_aliasing(&plan);+ }++ #[test]+ fn the_arena_is_bounded_at_the_width_the_device_runs() {+ let (_, plan) = plan(WIDTH);+ // fp16, so bytes are twice the elements. Printed rather than pinned to a tight+ // figure, because the allocator's fit policy is allowed to change; the assertion+ // is only that it is nothing like the sum of every intermediate.+ let mib = plan.arena_elems as f32 * 2.0 / (1024.0 * 1024.0);+ println!("ppocr_rec at 48x{WIDTH}: {} elements, {mib:.2} MiB", plan.arena_elems);+ assert!(mib < 32.0, "{mib} MiB");+ }+}
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 511444ded1..66c031e6cf 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -837,7 +837,7 @@ fn uniform(state: &mut u32) -> f32 { #[cfg(test)] mod tests {- use super::super::{mobilefacenet, ppocr_det, scrfd, selfie, u2netp, Act, Builder};+ use super::super::{mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, u2netp, Act, Builder}; use super::*; /// Build a plan whose only ops come from `record`, run it, and return the output.@@ -1699,6 +1699,53 @@ mod tests { } } + #[test]+ fn the_ppocr_rec_net_runs_end_to_end_and_decodes() {+ // The whole recognition pass, at width 16 rather than the 320 it runs at on+ // device: `T` is 2 instead of 40, which still exercises all 56 layers, both+ // attentions, all five layer norms, both squeeze-excites and the pool. Invented+ // weights, so no asset is needed.+ //+ // Width 16 rather than 8 on purpose. At `T` 1 a softmax over one key is 1.0+ // whatever the scores were, so the attention would run without its indexing being+ // observable at all. Two costs about a second more in a debug build and makes the+ // query and key axes distinguishable.+ let source = Invented::new(ppocr_rec::TENSORS);+ let plan = ppocr_rec::build(&source, 16).expect("ppocr_rec builds at width 16");+ let data = source.into_data();+ let shape = plan.input().expect("one input").shape;+ let logits = run(&plan, &data, &blob(shape)).expect("ppocr_rec runs");++ let steps = 16 / 8;+ assert_eq!(logits.len(), ppocr_rec::LOGITS as usize * steps);+ // Raw logits, so the only thing to assert about the values themselves is that fp16+ // did not saturate anywhere down 56 layers — an infinity or a NaN here is what a+ // misindexed weight or an aliased arena produces.+ for (i, &value) in logits.iter().enumerate() {+ assert!(value.is_finite(), "logit {i} is {value}");+ }+ let low = logits.iter().fold(f32::MAX, |a, &b| a.min(b));+ let high = logits.iter().fold(f32::MIN, |a, &b| a.max(b));+ println!("ppocr_rec at 48x16: logits in {low:.4}..{high:.4}");++ // And it feeds the decode. The text is meaningless — the weights are invented —+ // but the confidence must be a probability, which is the end-to-end check that the+ // class-major layout the net writes is the one `ctc::decode` reads.+ let mut keys = String::new();+ for index in 0..crate::post::ctc::DICTIONARY_ENTRIES {+ keys.push((b'a' + (index % 26) as u8) as char);+ keys.push('\n');+ }+ let dictionary = crate::post::ctc::Dictionary::parse(&keys).expect("parses");+ let decoded = crate::post::ctc::decode(&logits, &dictionary).expect("decodes");+ println!("ppocr_rec: {:?} at {:.4}", decoded.text, decoded.confidence);+ assert!(+ (0.0..=1.0).contains(&decoded.confidence),+ "confidence {}",+ decoded.confidence+ );+ }+ /// 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/src/post/ctc.rs
diff --git a/library/ml/src/main/rust/src/post/ctc.rs b/library/ml/src/main/rust/src/post/ctc.rsindex 011455dab3..ab1c9d7f2e 100644--- a/library/ml/src/main/rust/src/post/ctc.rs+++ b/library/ml/src/main/rust/src/post/ctc.rs@@ -91,39 +91,76 @@ pub struct Decoded { /// Collapse `logits` into text: argmax per timestep, drop blanks, drop repeats. ///-/// `logits` is `steps * LOGITS`, row-major — one row per timestep, already through the-/// graph's softmax. The classic CTC collapse: a label repeated across consecutive-/// timesteps is one character, and a blank between two identical labels is what separates-/// them into two.+/// # Layout: class-major, and raw+///+/// `logits` is [`LOGITS`] * `steps` values in **class-major** order — every timestep's+/// value for label 0, then every one for label 1, and so on. That is `[LOGITS, 1, T]`,+/// exactly what [`crate::nets::ppocr_rec`] writes, so nothing transposes anything.+///+/// The values are **raw logits**, not probabilities. The export ends in a `Softmax` over+/// the 838 classes and this runtime deliberately does not run it, because the decode does+/// not need it:+///+/// * The argmax is unchanged by a softmax, which is monotonic.+/// * The winner's probability is `1 / sum(exp(x - peak))` — subtracting the peak makes+/// its own term `exp(0)`, so the numerator is 1 and the denominator is at least 1. That+/// is computed here, for the timesteps that are actually kept, which is a few hundred+/// exponentials per line rather than a whole pass over the logit map.+///+/// So the softmax is not moved to the host, it is deleted.+///+/// The classic CTC collapse: a label repeated across consecutive timesteps is one+/// character, and a blank between two identical labels is what separates them into two. pub fn decode(logits: &[f32], dictionary: &Dictionary) -> Result<Decoded, String> { let labels = dictionary.labels(); if labels != LOGITS { return Err(format!("a dictionary of {labels} labels, expected {LOGITS}")); }+ if logits.is_empty() {+ return Err("no logits at all, so the recogniser produced no timesteps".into());+ } if !logits.len().is_multiple_of(labels) { return Err(format!( "{} logits is not a whole number of {labels}-wide timesteps", logits.len() )); }+ let steps = logits.len() / labels;+ let at = |label: usize, step: usize| -> Result<f32, String> {+ logits+ .get(label * steps + step)+ .copied()+ .ok_or_else(|| format!("label {label} of timestep {step} is outside the map"))+ }; let mut text = String::new(); let mut total = 0.0f64; let mut kept = 0u32; let mut previous = usize::MAX; - for step in logits.chunks_exact(labels) {- let (best, &score) = step- .iter()- .enumerate()- .max_by(|(_, a), (_, b)| a.total_cmp(b))- .ok_or("an empty timestep")?;+ for step in 0..steps {+ let mut best = 0;+ let mut peak = at(0, step)?;+ for label in 1..labels {+ let value = at(label, step)?;+ if value > peak {+ peak = value;+ best = label;+ }+ } // A repeat of the immediately preceding label is the same character held across // two frames. A blank resets that, which is how "aa" is spelled at all. if best != previous { if let Some(character) = dictionary.label(best) {+ // f64, like the mean below: summing 837 small terms into a running total+ // that already holds `exp(0) = 1` loses several f32 digits, and this+ // number is compared against a threshold by callers.+ let mut denominator = 0.0f64;+ for label in 0..labels {+ denominator += ((at(label, step)? - peak) as f64).exp();+ } text.push_str(character);- total += score as f64;+ total += 1.0 / denominator; kept += 1; } }@@ -151,15 +188,31 @@ mod tests { Dictionary::parse(&text).expect("the fixture dictionary parses") } - /// One timestep whose argmax is `label`, at probability `score`.- fn step(label: usize, score: f32) -> Vec<f32> {- let mut row = vec![0.0; LOGITS];- row[label] = score;- row+ /// One timestep's winning label and its logit. Every other label sits at zero, which+ /// makes the expected confidence [`probability`].+ ///+ /// Laid out **class-major**, the way `nets::ppocr_rec` writes it: label `l` of+ /// timestep `t` is at `l * steps + t`. A single-timestep fixture is the same bytes+ /// either way, which is why the argmax test below can stay a flat array.+ fn logits(steps: &[(usize, f32)]) -> Vec<f32> {+ let mut map = vec![0.0; LOGITS * steps.len()];+ for (step, &(label, logit)) in steps.iter().enumerate() {+ if let Some(slot) = map.get_mut(label * steps.len() + step) {+ *slot = logit;+ }+ }+ map } - fn logits(steps: &[(usize, f32)]) -> Vec<f32> {- steps.iter().flat_map(|&(l, s)| step(l, s)).collect()+ /// The softmax probability of a winner at `logit` when every other label is zero:+ /// `1 / (1 + 837 * exp(-logit))`.+ ///+ /// Computed here from the definition rather than from `decode`'s arithmetic, so the+ /// fixtures below pin the confidence rather than restate it. f64 for the same reason+ /// `decode` uses it — in f32 the two disagree in the fifth digit, which would make the+ /// tolerance hide a real error.+ fn probability(logit: f32) -> f64 {+ 1.0 / (1.0 + (LOGITS - 1) as f64 * (-logit as f64).exp()) } #[test]@@ -179,10 +232,44 @@ mod tests { #[test] fn a_run_of_one_label_collapses_to_one_character() { let d = dictionary();- let got = decode(&logits(&[(1, 0.9), (1, 0.8), (1, 0.7)]), &d).expect("decodes");+ // Different logits across the run, so "only the first is scored" is observable.+ let got = decode(&logits(&[(1, 10.0), (1, 8.0), (1, 12.0)]), &d).expect("decodes"); assert_eq!(got.text, "a");- // Only the first of the run is scored, which is what the reference does.- assert!((got.confidence - 0.9).abs() < 1e-6, "{}", got.confidence);+ let want = probability(10.0) as f32;+ assert!((got.confidence - want).abs() < 1e-6, "{} vs {want}", got.confidence);+ }++ #[test]+ fn the_confidence_is_the_winners_softmax_probability_of_the_raw_logits() {+ // The graph's final softmax is deliberately not run, so this is where the+ // probability comes from. A decoder that returned the logit itself would report+ // 10.0, and one that forgot the 836 other zero-logit classes would report 1/2.+ let d = dictionary();+ let got = decode(&logits(&[(3, 10.0)]), &d).expect("decodes");+ let want = (1.0 / (1.0 + 837.0 * (-10.0f64).exp())) as f32;+ assert!((got.confidence - want).abs() < 1e-6, "{} vs {want}", got.confidence);+ // Sanity: 837 competitors at logit zero against one at 10 is confident but not+ // certain, so this is well inside the unit interval rather than clamped to it.+ assert!((0.9..0.99).contains(&got.confidence), "{}", got.confidence);+ }++ #[test]+ fn a_flat_timestep_is_reported_at_chance() {+ // Every label equally likely is 1/838, and it is the blank that wins a tie at+ // label 0 — so nothing is emitted and the confidence falls back to zero.+ let d = dictionary();+ let got = decode(&vec![0.5; LOGITS], &d).expect("decodes");+ assert_eq!(got.text, "");+ assert_eq!(got.confidence, 0.0);+ // With a non-blank winner the same flat field gives chance plus a little.+ let mut map = vec![0.0; LOGITS];+ if let Some(slot) = map.get_mut(2) {+ *slot = f32::MIN_POSITIVE;+ }+ let got = decode(&map, &d).expect("decodes");+ assert_eq!(got.text, "b");+ let chance = 1.0 / LOGITS as f32;+ assert!((got.confidence - chance).abs() < 1e-6, "{} vs {chance}", got.confidence); } #[test]@@ -190,14 +277,14 @@ mod tests { // The whole reason CTC has a blank: without it "aa" is indistinguishable from a // held "a". let d = dictionary();- let got = decode(&logits(&[(1, 0.9), (0, 0.6), (1, 0.8)]), &d).expect("decodes");+ let got = decode(&logits(&[(1, 10.0), (0, 8.0), (1, 9.0)]), &d).expect("decodes"); assert_eq!(got.text, "aa"); } #[test] fn blanks_contribute_no_characters_and_no_confidence() { let d = dictionary();- let got = decode(&logits(&[(0, 0.99), (0, 0.99)]), &d).expect("decodes");+ let got = decode(&logits(&[(0, 12.0), (0, 12.0)]), &d).expect("decodes"); assert_eq!(got.text, ""); assert_eq!(got.confidence, 0.0); }@@ -205,31 +292,65 @@ mod tests { #[test] fn distinct_adjacent_labels_both_survive_without_a_blank() { let d = dictionary();- let got = decode(&logits(&[(1, 0.9), (2, 0.8), (3, 0.7)]), &d).expect("decodes");+ let got = decode(&logits(&[(1, 10.0), (2, 8.0), (3, 12.0)]), &d).expect("decodes"); assert_eq!(got.text, "abc");- assert!((got.confidence - 0.8).abs() < 1e-6, "{}", got.confidence);+ // The mean of all three, since none is a repeat.+ let want =+ ((probability(10.0) + probability(8.0) + probability(12.0)) / 3.0) as f32;+ assert!((got.confidence - want).abs() < 1e-6, "{} vs {want}", got.confidence); } #[test] fn the_space_label_decodes_to_a_space() { let d = dictionary();- let got = decode(&logits(&[(1, 0.9), (LOGITS - 1, 0.8), (2, 0.7)]), &d).expect("decodes");+ let got = decode(&logits(&[(1, 10.0), (LOGITS - 1, 9.0), (2, 8.0)]), &d)+ .expect("decodes"); assert_eq!(got.text, "a b"); } #[test]- fn the_argmax_is_taken_across_the_whole_row() {- // A row where the winner is not the only non-zero, so a decoder that took the- // first positive value rather than the largest would differ.+ fn a_timestep_is_a_column_not_a_row() {+ // The map is class-major, so with three timesteps the first three values are+ // label 0 across all of them, not timestep 0 across three labels. Reading it+ // row-major here would decode label 0 (the blank), then 1, then 2 — "ab" — from+ // a map that actually says "a" once. let d = dictionary();- let mut row = vec![0.0; LOGITS];- row[1] = 0.2;- row[5] = 0.7;- row[9] = 0.1;- let got = decode(&row, &d).expect("decodes");+ let (label, steps) = (1usize, 3usize);+ let mut map = vec![0.0; LOGITS * steps];+ for step in 0..steps {+ if let Some(slot) = map.get_mut(label * steps + step) {+ *slot = 10.0;+ }+ }+ let got = decode(&map, &d).expect("decodes");+ assert_eq!(got.text, "a");+ }++ #[test]+ fn the_argmax_is_taken_across_every_label_of_the_timestep() {+ // One timestep, so class-major and row-major coincide. The winner is not the only+ // non-zero, so a decoder that took the first positive value would differ.+ let d = dictionary();+ let mut column = vec![0.0; LOGITS];+ for (label, value) in [(1, 0.2), (5, 0.7), (9, 0.1)] {+ if let Some(slot) = column.get_mut(label) {+ *slot = value;+ }+ }+ let got = decode(&column, &d).expect("decodes"); assert_eq!(got.text, "e"); } + #[test]+ fn an_empty_logit_map_is_refused_rather_than_decoding_to_nothing() {+ // A zero-timestep map means the recogniser produced nothing, which is a failure+ // upstream. Returning empty text would make it indistinguishable from a crop that+ // genuinely holds no characters.+ let d = dictionary();+ let error = decode(&[], &d).expect_err("an empty map");+ assert!(error.contains("no logits"), "{error}");+ }+ #[test] fn a_dictionary_of_the_wrong_length_is_refused() { let error = Dictionary::parse("a\nb\nc\n").expect_err("too short");