Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / shaders / embed.comp
embed.comp52 lines · 2.1 KiBRaw
| 1 | #version 450 |
| 2 | //! An embedding lookup: `out[c][t] = table[id(t)][c]`. |
| 3 | //! |
| 4 | //! A text encoder starts by looking up one row of a `[symbols, d_model]` table per |
| 5 | //! phoneme. That is the only op in this runtime whose *addresses* depend on the data rather |
| 6 | //! than on the plan. |
| 7 | //! |
| 8 | //! # Integer ids in an fp16 arena |
| 9 | //! |
| 10 | //! The ids arrive as a `[1, 1, T]` tensor in the arena like anything else, so the host does |
| 11 | //! not need a second input path and the plan still reads every tensor in its file. fp16 |
| 12 | //! holds every integer up to 2048 exactly, and this table has 130 rows, so a round trip |
| 13 | //! through the arena cannot move an id to its neighbour — 130 is nowhere near the 2048 where |
| 14 | //! the gaps between representable integers open up. |
| 15 | //! |
| 16 | //! Supertonic's 8,322 symbols and SMaLL-100's 128,112 are past that, so those pass ids as |
| 17 | //! **two lanes** — a `[2, 1, T]` tensor holding `id % 2048` then `id / 2048`, recombined |
| 18 | //! here. `p.in_c` is the lane count. |
| 19 | //! |
| 20 | //! `p.in_w` is the table's row count. An id outside it clamps rather than reading past the |
| 21 | //! table: a phonemiser that emitted an unknown symbol should mispronounce a word, not sample |
| 22 | //! whatever weights follow the embedding. |
| 23 | //! |
| 24 | //! # The scale is in the table |
| 25 | //! |
| 26 | //! An export that multiplies the embedding by `sqrt(d_model)` has that folded into the table |
| 27 | //! itself, which is both one op fewer and one rounding fewer — `round(table * sqrt(d))` is |
| 28 | //! closer than `round(table) * sqrt(d)`. |
| 29 | |
| 30 | #include "common.glsl" |
| 31 | |
| 32 | void main() { |
| 33 | uint index = global_index(); |
| 34 | if (index >= p.count) { |
| 35 | return; |
| 36 | } |
| 37 | uint channel, unused_row, position; |
| 38 | unpack(index, channel, unused_row, position); |
| 39 | |
| 40 | // Round rather than truncate: an id that came back as 41.9997 is 42. |
| 41 | float raw = float(arena[p.in0 + position]); |
| 42 | uint id = uint(max(raw + 0.5, 0.0)); |
| 43 | if (p.in_c == 2u) { |
| 44 | float high = float(arena[p.in0 + p.out_w + position]); |
| 45 | id += 2048u * uint(max(high + 0.5, 0.0)); |
| 46 | } |
| 47 | uint rows = p.in_w; |
| 48 | if (id >= rows) { |
| 49 | id = rows - 1u; |
| 50 | } |
| 51 | arena[p.out_at + index] = weights[p.weight + id * p.out_c + channel]; |
| 52 | } |