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

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

resize_nearest.comp43 lines · 1.7 KiBRaw
1#version 450
2//! Nearest-neighbour resize, `asymmetric` coordinates and `floor` rounding. Two uses,
3//! both SCRFD feature-pyramid upsamples.
4//!
5//! # Why this is not a flag on `resize.comp`
6//!
7//! The two conventions share no arithmetic. Bilinear `half_pixel` samples at
8//! `(dst + 0.5) * in / out - 0.5` and blends four taps; this picks one tap at
9//! `floor(dst * in / out)`. SCRFD's neck adds each upsampled level to a lateral
10//! convolution of the level below, so running it through the bilinear kernel would
11//! smear every one of those additions — an error that leaves the detector working and
12//! quietly worse at small faces.
13//!
14//! # Exact in integers
15//!
16//! `asymmetric` with `floor` is `floor(dst * in / out)`, which for unsigned integers is
17//! just `dst * in / out`. So there is no float here at all, and a 2x upsample lands
18//! exactly on `dst / 2` rather than within a rounding error of it. `in_w` and `out_w`
19//! are both at most a few thousand, so the product cannot overflow `uint`.
20
21#include "common.glsl"
22
23// The source index for `dst`, clamped. ONNX would never generate an out-of-range index
24// for an upsample, but a downsample with a rounding quirk could, and a clamp is cheaper
25// than reasoning about it.
26uint nearest(uint dst, uint in_extent, uint out_extent) {
27 return min(dst * in_extent / out_extent, in_extent - 1u);
28}
29
30void main() {
31 uint index = global_index();
32 if (index >= p.count) {
33 return;
34 }
35 uint oc, oy, ox;
36 unpack(index, oc, oy, ox);
37
38 uint iy = nearest(oy, p.in_h, p.out_h);
39 uint ix = nearest(ox, p.in_w, p.out_w);
40
41 uint plane = p.in0 + oc * p.in_h * p.in_w;
42 arena[p.out_at + index] = arena[plane + iy * p.in_w + ix];
43}