Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / shaders / resize.comp
resize.comp52 lines · 2.0 KiBRaw
| 1 | #version 450 |
| 2 | //! Bilinear resize with `half_pixel` coordinates. 41 uses across both networks. |
| 3 | //! |
| 4 | //! # One convention, everywhere |
| 5 | //! |
| 6 | //! `src = (dst + 0.5) * in / out - 0.5`. The selfie net's three `Resize` nodes are |
| 7 | //! `coordinate_transformation_mode=half_pixel`; U^2-Netp's 38 are `pytorch_half_pixel`, |
| 8 | //! which differs from `half_pixel` only when the resized extent is 1 — and none of these |
| 9 | //! are, since every one is an exact 2x upsample. So both lower to this, and |
| 10 | //! `preprocess::to_planar_f16` uses the same formula for the input resize. |
| 11 | //! |
| 12 | //! That agreement is load-bearing rather than tidy: U^2-Netp's decoder upsamples and then |
| 13 | //! *adds* to an encoder skip five times over, so a half-pixel shift between the two paths |
| 14 | //! would misregister every residual in the net. |
| 15 | //! |
| 16 | //! Coordinates outside the source clamp to the edge, which is what ONNX `Resize` does |
| 17 | //! with its default `nearest_mode`/exclude-outside behaviour for linear sampling. |
| 18 | |
| 19 | #include "common.glsl" |
| 20 | |
| 21 | // The two bracketing source indices and the weight of the second, at `half_pixel`. |
| 22 | void bracket(uint dst, uint in_extent, uint out_extent, out uint low, out uint high, out float t) { |
| 23 | float source = (float(dst) + 0.5) * float(in_extent) / float(out_extent) - 0.5; |
| 24 | source = max(source, 0.0); |
| 25 | float base = floor(source); |
| 26 | t = source - base; |
| 27 | low = min(uint(base), in_extent - 1u); |
| 28 | high = min(low + 1u, in_extent - 1u); |
| 29 | } |
| 30 | |
| 31 | void main() { |
| 32 | uint index = global_index(); |
| 33 | if (index >= p.count) { |
| 34 | return; |
| 35 | } |
| 36 | uint oc, oy, ox; |
| 37 | unpack(index, oc, oy, ox); |
| 38 | |
| 39 | uint y0, y1, x0, x1; |
| 40 | float ty, tx; |
| 41 | bracket(oy, p.in_h, p.out_h, y0, y1, ty); |
| 42 | bracket(ox, p.in_w, p.out_w, x0, x1, tx); |
| 43 | |
| 44 | uint plane = p.in0 + oc * p.in_h * p.in_w; |
| 45 | uint row0 = plane + y0 * p.in_w; |
| 46 | uint row1 = plane + y1 * p.in_w; |
| 47 | |
| 48 | float top = mix(float(arena[row0 + x0]), float(arena[row0 + x1]), tx); |
| 49 | float bottom = mix(float(arena[row1 + x0]), float(arena[row1 + x1]), tx); |
| 50 | |
| 51 | arena[p.out_at + index] = float16_t(mix(top, bottom, ty)); |
| 52 | } |