Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / shaders / attn_apply_relative.comp
attn_apply_relative.comp50 lines · 1.8 KiBRaw
| 1 | #version 450 |
| 2 | //! Attention's weighted sum with a relative-position term, in one pass. |
| 3 | //! |
| 4 | //! `out[h][d][i] = sum_j P[h][i][j] * V[h][d][j] + sum_o P[h][i][i+o] * emb[o + window][d]` |
| 5 | //! |
| 6 | //! The value-side mirror of `attn_scores_relative`, and the same argument: the export builds |
| 7 | //! a `[heads, T, 2T-1]` relative form of the attention matrix with a pad, a reshape and a |
| 8 | //! slice, and every entry outside `|o| <= window` multiplies a zero. So the second term is |
| 9 | //! nine taps of `P` along the diagonal, weighted by the table. |
| 10 | //! |
| 11 | //! Verified against onnxruntime, not assumed: this expression reproduces the export's |
| 12 | //! attention output to 1.2e-07. |
| 13 | //! |
| 14 | //! Taps that fall outside the sequence are skipped rather than clamped. Clamping would fold |
| 15 | //! a neighbour's probability in twice at the ends of the utterance, which is where a |
| 16 | //! sentence's first and last phoneme live. |
| 17 | |
| 18 | #include "common.glsl" |
| 19 | |
| 20 | void main() { |
| 21 | uint index = global_index(); |
| 22 | if (index >= p.count) { |
| 23 | return; |
| 24 | } |
| 25 | uint channel, unused_row, query; |
| 26 | unpack(index, channel, unused_row, query); |
| 27 | |
| 28 | uint keys = p.out_w; |
| 29 | uint head_dim = p.out_c / p.group; |
| 30 | uint row = p.in0 + ((channel / head_dim) * keys + query) * keys; |
| 31 | uint values = p.in1 + channel * keys; |
| 32 | |
| 33 | float total = 0.0; |
| 34 | for (uint j = 0u; j < keys; j++) { |
| 35 | total += float(arena[row + j]) * float(arena[values + j]); |
| 36 | } |
| 37 | |
| 38 | int window = int(p.kw - 1u) / 2; |
| 39 | uint depth = channel % head_dim; |
| 40 | for (int offset = -window; offset <= window; offset++) { |
| 41 | int key = int(query) + offset; |
| 42 | if (key < 0 || key >= int(keys)) { |
| 43 | continue; |
| 44 | } |
| 45 | uint entry = uint(offset + window) * head_dim + depth; |
| 46 | total += float(arena[row + uint(key)]) * float(weights[p.weight + entry]); |
| 47 | } |
| 48 | |
| 49 | arena[p.out_at + index] = float16_t(total); |
| 50 | } |