Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / library / ml / src / main / rust / shaders / affine.comp

affine.comp36 lines · 1.5 KiBRaw
1#version 450
2//! `out = in * scale + shift`, both scalars. 24 uses, all in PP-OCRv5 detection.
3//!
4//! # What this is
5//!
6//! PP-HGNetV2's "learnable affine block": a per-tensor, not per-channel, affine. Two
7//! trained scalars, applied to every element of a feature map.
8//!
9//! # Why it is an op at all
10//!
11//! Almost everything constant in the PP-OCRv5 export folds into a convolution — the
12//! bias, the batch norms, the affine blocks that sit *before* an activation, even
13//! HardSigmoid's alpha and beta. `scripts/ml/ppocr_fold.py` does all of that ahead of
14//! time, which is why 117 `Add`s and 86 `Mul`s in the ONNX become 11 and 10 here.
15//!
16//! These 24 are the ones that survive, because they sit *after* an activation. Folding
17//! one into the *following* convolution is possible — `b' += shift * sum(W)` over each
18//! output row — but only when the tensor feeds nothing except convolutions, and making
19//! the conversion depend on that is how a subtle wrong answer gets shipped. One
20//! elementwise pass is the honest version, and detection runs once per OCR request
21//! rather than once per frame.
22//!
23//! The two scalars arrive as raw `f32` bits in the push block, so `nets::Push` stays
24//! entirely `u32` and needs no padding.
25
26#include "common.glsl"
27
28void main() {
29 uint index = global_index();
30 if (index >= p.count) {
31 return;
32 }
33 float scale = uintBitsToFloat(p.param0_bits);
34 float shift = uintBitsToFloat(p.param1_bits);
35 arena[p.out_at + index] = float16_t(float(arena[p.in0 + index]) * scale + shift);
36}