Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / shaders / avgpool.comp
avgpool.comp56 lines · 2.1 KiBRaw
| 1 | #version 450 |
| 2 | //! Average pooling over an explicit window. One use, in PP-OCRv5 recognition. |
| 3 | //! |
| 4 | //! # What it is for |
| 5 | //! |
| 6 | //! The recogniser's backbone ends at `[480, 3, 80]` and its transformer wants a |
| 7 | //! sequence. One pool with kernel `(3, 2)` and stride `(3, 2)` does both jobs at once: |
| 8 | //! it collapses the remaining three rows to one and halves the width, giving |
| 9 | //! `[480, 1, 40]` — which is `[d_model, 1, T]`, the layout everything downstream reads. |
| 10 | //! |
| 11 | //! So this is not a general-purpose pooling layer that happens to be used once. It is |
| 12 | //! the point at which a feature map becomes a sequence, and the asymmetric kernel is why |
| 13 | //! the shader takes `kh` and `kw` separately rather than one size. |
| 14 | //! |
| 15 | //! # No padding, and an exact divisor |
| 16 | //! |
| 17 | //! `nets::Builder::avg_pool` refuses a window that does not tile its input exactly, so |
| 18 | //! every window is fully inside the map and the divisor is always `kh * kw`. That is |
| 19 | //! what `count_include_pad = 0` means when there is no padding to count, and it is why |
| 20 | //! the bounds tests below can never fire — they are here so that a plan which somehow |
| 21 | //! got past the builder reads in range rather than off the end of the arena. |
| 22 | //! |
| 23 | //! Distinct from `gap.comp`, which reduces *all* of H and W to one value per channel and |
| 24 | //! is the squeeze in a squeeze-excite. That one needs no window at all; this one is |
| 25 | //! nothing but window. |
| 26 | |
| 27 | #include "common.glsl" |
| 28 | |
| 29 | void main() { |
| 30 | uint index = global_index(); |
| 31 | if (index >= p.count) { |
| 32 | return; |
| 33 | } |
| 34 | uint oc, oy, ox; |
| 35 | unpack(index, oc, oy, ox); |
| 36 | uint plane = p.in0 + oc * p.in_h * p.in_w; |
| 37 | uint top = oy * p.stride_h; |
| 38 | uint left = ox * p.stride_w; |
| 39 | |
| 40 | float total = 0.0; |
| 41 | for (uint ky = 0u; ky < p.kh; ky++) { |
| 42 | uint iy = top + ky; |
| 43 | if (iy >= p.in_h) { |
| 44 | continue; |
| 45 | } |
| 46 | uint row = plane + iy * p.in_w; |
| 47 | for (uint kx = 0u; kx < p.kw; kx++) { |
| 48 | uint ix = left + kx; |
| 49 | if (ix >= p.in_w) { |
| 50 | continue; |
| 51 | } |
| 52 | total += float(arena[row + ix]); |
| 53 | } |
| 54 | } |
| 55 | arena[p.out_at + index] = float16_t(total / float(p.kh * p.kw)); |
| 56 | } |