Modern Apps git

← Modern-Apps.git

library:ml: an embedding lookup, with ids in the arena as fp16

Commit
653af9910028c6f0e8611e1a7525bd7bfda762ac
Author
vayun-mathur <[email protected]>
When
2026-08-27 23:31 UTC (3 months ago)
Parents
60a7b40

Diff

library/ml/src/main/rust/shaders/embed.comp
diff --git a/library/ml/src/main/rust/shaders/embed.comp b/library/ml/src/main/rust/shaders/embed.compnew file mode 100644index 0000000000..8d3b07fb5d--- /dev/null+++ b/library/ml/src/main/rust/shaders/embed.comp@@ -0,0 +1,44 @@+#version 450+//! An embedding lookup: `out[c][t] = table[id(t)][c]`.+//!+//! VITS's text encoder starts by looking up one row of a `[symbols, d_model]` table per+//! phoneme. That is the only op in this runtime whose *addresses* depend on the data rather+//! than on the plan.+//!+//! # Integer ids in an fp16 arena+//!+//! The ids arrive as a `[1, 1, T]` tensor in the arena like anything else, so the host does+//! not need a second input path and the plan still reads every tensor in its file. fp16+//! holds every integer up to 2048 exactly, and this table has 130 rows, so a round trip+//! through the arena cannot move an id to its neighbour — 130 is nowhere near the 2048 where+//! the gaps between representable integers open up.+//!+//! `p.in_w` is the table's row count. An id outside it clamps rather than reading past the+//! table: a phonemiser that emitted an unknown symbol should mispronounce a word, not sample+//! whatever weights follow the embedding.+//!+//! # The scale is in the table+//!+//! VITS multiplies the embedding by `sqrt(d_model)`. The converter folds that into the table+//! itself, which is both one op fewer and one rounding fewer — `round(table * sqrt(d))` is+//! closer than `round(table) * sqrt(d)`.++#include "common.glsl"++void main() {+    uint index = global_index();+    if (index >= p.count) {+        return;+    }+    uint channel, unused_row, position;+    unpack(index, channel, unused_row, position);++    // Round rather than truncate: an id that came back as 41.9997 is 42.+    float raw = float(arena[p.in0 + position]);+    uint id = uint(max(raw + 0.5, 0.0));+    uint rows = p.in_w;+    if (id >= rows) {+        id = rows - 1u;+    }+    arena[p.out_at + index] = weights[p.weight + id * p.out_c + channel];+}
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex 95c105dd6f..6b74a852d0 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -234,6 +234,13 @@ pub enum Kind {     /// [`Kind::AttnApply`] plus the value-side relative term. See     /// [`Kind::AttnScoresRelative`].     AttnApplyRelative,+    /// `out[c][t] = table[id(t)][c]`, an embedding lookup.+    ///+    /// The only op here whose addresses depend on the data. Ids arrive as an ordinary fp16+    /// tensor, which is exact for the 130 phoneme symbols VITS uses — fp16 holds every+    /// integer to 2048. Table at [`Push::weight`], its row count in [`Push::in_w`], and an+    /// out-of-range id clamps rather than reading past the table.+    Embed,     /// `x < 0 ? alpha * x : x`, as a standalone pass. 16 uses in Piper's HiFi-GAN vocoder.     ///     /// The only activation here that is **not** fused into the layer before it, because in@@ -501,6 +508,12 @@ enum Node {         out: Id,         alpha: f32,     },+    Embed {+        ids: Id,+        out: Id,+        table: u32,+        rows: u32,+    },     AttnApply {         probs: Id,         v: Id,@@ -935,6 +948,26 @@ impl<'a> Builder<'a> {         out     } +    /// An embedding lookup: `out[c][t] = table[id(t)][c]`, over a `[1, 1, T]` id tensor.+    ///+    /// `table` indexes a `[rows, channels]` tensor. The `sqrt(d_model)` scale VITS applies+    /// after the lookup belongs in the table, not here; see [`Kind::Embed`].+    pub fn embed(&mut self, ids: Id, table: usize, rows: u32, channels: u32) -> Id {+        let shape = self.shape_of(ids);+        if shape.c != 1 || shape.h != 1 {+            self.fail(format!(+                "embedding {shape:?}: ids are one per position, so a [1, 1, T] tensor"+            ));+        }+        if rows == 0 || channels == 0 {+            self.fail(format!("an embedding table of {rows} x {channels}"));+        }+        let table = self.weight(table, &[rows, channels]);+        let out = self.tensor(Shape::new(channels, 1, shape.w));+        self.nodes.push(Node::Embed { ids, out, table, rows });+        out+    }+     /// `x < 0 ? alpha * x : x`, as its own pass. See [`Kind::LeakyRelu`] for why it is not     /// fused into the layer before it.     pub fn leaky_relu(&mut self, input: Id, alpha: f32) -> Id {@@ -1412,6 +1445,27 @@ impl<'a> Builder<'a> {                     invocations: so.len(),                 });             }+            Node::Embed { ids, out, table, rows } => {+                let so = shape(*out);+                ops.push(Op::Dispatch {+                    kind: Kind::Embed,+                    push: Push {+                        in0: at(*ids)?,+                        out: at(*out)?,+                        weight: *table,+                        // The table's row count, not the id tensor's extent: the shader+                        // clamps against it so an unknown symbol mispronounces a word+                        // rather than reading whatever follows the embedding.+                        in_w: *rows,+                        out_c: so.c,+                        out_h: so.h,+                        out_w: so.w,+                        count: so.len(),+                        ..Push::default()+                    },+                    invocations: so.len(),+                });+            }             Node::Softmax { input, out } => {                 let so = shape(*out);                 // One invocation per row of the last axis, each normalising `out_w`@@ -1496,6 +1550,7 @@ impl Node {             | Node::AttnApplyRelative { out, .. }             | Node::Softmax { out, .. }             | Node::LeakyRelu { out, .. }+            | Node::Embed { out, .. }             | Node::AttnApply { out, .. }             | Node::Concat { out, .. } => *out,         }@@ -1511,6 +1566,7 @@ impl Node {             | Node::LayerNorm { input, .. }             | Node::Softmax { input, .. }             | Node::LeakyRelu { input, .. }+            | Node::Embed { ids: input, .. }             | Node::GlobalAvgPool { input, .. } => vec![*input],             Node::Binary { a, b, .. } => vec![*a, *b],             Node::AttnScores { q: a, k: b, .. }
library/ml/src/main/rust/src/nets/reference.rs
diff --git a/library/ml/src/main/rust/src/nets/reference.rs b/library/ml/src/main/rust/src/nets/reference.rsindex ccd4c365d9..ad69c3e8e4 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -189,6 +189,7 @@ impl Reference {                     Kind::LeakyRelu => self.leaky_relu(push),                     Kind::AttnScoresRelative => self.attn_scores_relative(push),                     Kind::AttnApplyRelative => self.attn_apply_relative(push),+                    Kind::Embed => self.embed(push),                 },             };             result.map_err(|e| format!("step {step} ({op:?}): {e}"))?;@@ -464,6 +465,25 @@ impl Reference {         Ok(())     } +    /// `out[c][t] = table[id(t)][c]`, with the id read out of the arena as fp16.+    fn embed(&mut self, p: &Push) -> Result<(), String> {+        let rows = p.in_w;+        if rows == 0 {+            return Err("an embedding table with no rows".into());+        }+        for position in 0..p.out_w {+            let raw = self.load(p.in0, position)?;+            // Round rather than truncate, and clamp: an unknown symbol should mispronounce+            // a word rather than read past the table.+            let id = ((raw + 0.5).max(0.0) as u32).min(rows - 1);+            for channel in 0..p.out_c {+                let value = self.weight(p.weight, id * p.out_c + channel)?;+                self.store(p.out, nchw(p, channel, 0, position), value)?;+            }+        }+        Ok(())+    }+     /// `x < 0 ? alpha * x : x`, elementwise, with `alpha` carried as raw bits.     fn leaky_relu(&mut self, p: &Push) -> Result<(), String> {         let alpha = f32::from_bits(p.param0_bits);@@ -1660,6 +1680,77 @@ mod tests {         assert!(error.contains("height above"), "{error}");     } +    #[test]+    fn an_embedding_gathers_the_row_each_id_names() {+        // Four symbols of three channels, looked up in an order that is neither ascending+        // nor a permutation — 2, 0, 3, 0 — so a lookup that ignored the ids and copied the+        // table straight through would be visible.+        let table: Vec<f32> = vec![+            10.0, 11.0, 12.0, //+            20.0, 21.0, 22.0, //+            30.0, 31.0, 32.0, //+            40.0, 41.0, 42.0,+        ];+        let got = one(+            Shape::new(1, 1, 4),+            &[2.0, 0.0, 3.0, 0.0],+            &[(vec![4, 3], table)],+            |b, ids| b.embed(ids, 0, 4, 3),+        );+        // Channel-major, so all four positions of channel 0, then channel 1, then 2.+        close(+            &got,+            &[+                30.0, 10.0, 40.0, 10.0, //+                31.0, 11.0, 41.0, 11.0, //+                32.0, 12.0, 42.0, 12.0,+            ],+        );+    }++    #[test]+    fn an_embedding_id_survives_the_round_trip_through_fp16() {+        // Ids travel in the arena as fp16 like everything else. That is exact here only+        // because fp16 holds every integer to 2048 and a phoneme table has 130 rows; the+        // highest id must come back as itself and not as its neighbour.+        let rows = 130u32;+        let table: Vec<f32> = (0..rows).map(|r| r as f32).collect();+        let ids: Vec<f32> = vec![0.0, 1.0, 64.0, 127.0, 128.0, 129.0];+        let got = one(+            Shape::new(1, 1, ids.len() as u32),+            &ids,+            &[(vec![rows, 1], table)],+            |b, x| b.embed(x, 0, rows, 1),+        );+        close(&got, &ids);+    }++    #[test]+    fn an_embedding_id_past_the_table_clamps_rather_than_reading_on() {+        // A phonemiser that emitted an unknown symbol should mispronounce a word, not+        // sample whatever weights happen to follow the table.+        let table: Vec<f32> = vec![7.0, 8.0, 9.0];+        let got = one(+            Shape::new(1, 1, 3),+            &[0.0, 2.0, 99.0],+            &[(vec![3, 1], table)],+            |b, ids| b.embed(ids, 0, 3, 1),+        );+        close(&got, &[7.0, 9.0, 9.0]);+    }++    #[test]+    fn an_embedding_over_a_multi_channel_id_tensor_is_refused() {+        // Ids are one per position. A `[2, 1, T]` input would silently embed only the first+        // channel and drop the second.+        let source = Given::new(&[(vec![4, 3], vec![0.0; 12])]).expect("the fixture lays out");+        let mut b = Builder::new(&source);+        let ids = b.input(Shape::new(2, 1, 4));+        let out = b.embed(ids, 0, 4, 3);+        let error = b.finish(&[out]).expect_err("two channels of ids");+        assert!(error.contains("one per position"), "{error}");+    }+     #[test]     fn a_relative_score_map_adds_a_banded_term_from_its_table() {         // Q = K = 1 everywhere over four positions, two channels, one head. The content
library/ml/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline.rs b/library/ml/src/main/rust/src/vulkan/pipeline.rsindex d583d82568..a437ef3dc2 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -45,9 +45,10 @@ const ATTN_SCORES_RELATIVE: &[u8] =     include_bytes!(concat!(env!("OUT_DIR"), "/attn_scores_relative.comp.spv")); const ATTN_APPLY_RELATIVE: &[u8] =     include_bytes!(concat!(env!("OUT_DIR"), "/attn_apply_relative.comp.spv"));+const EMBED: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/embed.comp.spv"));  /// Every shader, in the order [`Pipelines::create`] destructures them.-const SPIRV: [&[u8]; 17] = [+const SPIRV: [&[u8]; 18] = [     CONV,     CONV_TRANSPOSE,     MAXPOOL,@@ -65,6 +66,7 @@ const SPIRV: [&[u8]; 17] = [     LEAKY_RELU,     ATTN_SCORES_RELATIVE,     ATTN_APPLY_RELATIVE,+    EMBED, ];  /// `local_size_x` in `shaders/common.glsl`. A dispatch covers `ceil(invocations / this)`@@ -105,6 +107,7 @@ pub struct Pipelines {     leaky_relu: vk::Pipeline,     attn_scores_relative: vk::Pipeline,     attn_apply_relative: vk::Pipeline,+    embed: vk::Pipeline, }  impl Pipelines {@@ -244,6 +247,7 @@ impl Pipelines {             leaky_relu,             attn_scores_relative,             attn_apply_relative,+            embed,         ] = match <[vk::Pipeline; SPIRV.len()]>::try_from(built) {             Ok(all) => all,             Err(built) => {@@ -277,6 +281,7 @@ impl Pipelines {             leaky_relu,             attn_scores_relative,             attn_apply_relative,+            embed,         })     } @@ -300,6 +305,7 @@ impl Pipelines {             Kind::LeakyRelu => self.leaky_relu,             Kind::AttnScoresRelative => self.attn_scores_relative,             Kind::AttnApplyRelative => self.attn_apply_relative,+            Kind::Embed => self.embed,         }     } @@ -325,6 +331,7 @@ impl Pipelines {             self.leaky_relu,             self.attn_scores_relative,             self.attn_apply_relative,+            self.embed,         ] {             device.destroy_pipeline(pipeline, None);         }