library:ml: VITS relative attention as nine taps, not a skew
- Commit
60a7b40ecb63fa926786a22f6e88739b2df755f6- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 23:09 UTC (3 months ago)
- Parents
f3573fb
Diff
library/ml/src/main/rust/shaders/attn_apply_relative.comp
diff --git a/library/ml/src/main/rust/shaders/attn_apply_relative.comp b/library/ml/src/main/rust/shaders/attn_apply_relative.compnew file mode 100644index 0000000000..b44e3f9769--- /dev/null+++ b/library/ml/src/main/rust/shaders/attn_apply_relative.comp@@ -0,0 +1,50 @@+#version 450+//! Attention's weighted sum with VITS's relative-position term, in one pass.+//!+//! `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]`+//!+//! The value-side mirror of `attn_scores_relative`, and the same argument: the export builds+//! a `[heads, T, 2T-1]` relative form of the attention matrix with a pad, a reshape and a+//! slice, and every entry outside `|o| <= window` multiplies a zero. So the second term is+//! nine taps of `P` along the diagonal, weighted by the table.+//!+//! Verified against onnxruntime, not assumed: this expression reproduces the export's+//! attention output to 1.2e-07.+//!+//! Taps that fall outside the sequence are skipped rather than clamped. Clamping would fold+//! a neighbour's probability in twice at the ends of the utterance, which is where a+//! sentence's first and last phoneme live.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ uint channel, unused_row, query;+ unpack(index, channel, unused_row, query);++ uint keys = p.out_w;+ uint head_dim = p.out_c / p.group;+ uint row = p.in0 + ((channel / head_dim) * keys + query) * keys;+ uint values = p.in1 + channel * keys;++ float total = 0.0;+ for (uint j = 0u; j < keys; j++) {+ total += float(arena[row + j]) * float(arena[values + j]);+ }++ int window = int(p.kw - 1u) / 2;+ uint depth = channel % head_dim;+ for (int offset = -window; offset <= window; offset++) {+ int key = int(query) + offset;+ if (key < 0 || key >= int(keys)) {+ continue;+ }+ uint entry = uint(offset + window) * head_dim + depth;+ total += float(arena[row + uint(key)]) * float(weights[p.weight + entry]);+ }++ arena[p.out_at + index] = float16_t(total);+}
library/ml/src/main/rust/shaders/attn_scores_relative.comp
diff --git a/library/ml/src/main/rust/shaders/attn_scores_relative.comp b/library/ml/src/main/rust/shaders/attn_scores_relative.compnew file mode 100644index 0000000000..f66ba43615--- /dev/null+++ b/library/ml/src/main/rust/shaders/attn_scores_relative.comp@@ -0,0 +1,62 @@+#version 450+//! Attention scores with VITS's relative-position term, in one pass.+//!+//! `scores[h][i][j] = scale * (Q[h,.,i] . K[h,.,j] + Q[h,.,i] . emb[j - i + window])`+//!+//! # Why the relative term is nine taps and not a skew+//!+//! VITS learns a table of `2 * window + 1` offsets per attention layer and adds+//! `Q . emb[j - i]` to every score. Its ONNX export computes that as a full+//! `[heads, T, 2T-1]` product and then *skews* it into `[heads, T, T]` with a pad, a reshape+//! and a slice — 48 `Pad`s, 96 `Reshape`s and 42 `Slice`s across the encoder, none of which+//! this runtime can express.+//!+//! None of it is necessary. The table has nine entries, so the skewed result is zero+//! wherever `|j - i| > window`, and the surviving band is just `emb[j - i + window]` read+//! directly. Checked against onnxruntime rather than assumed: the difference between the+//! final scores and the content-only scores is *exactly* zero outside the band, and inside+//! it matches this expression to fp32 accumulation noise.+//!+//! # Layout+//!+//! `p.weight` points at the table as `[2 * window + 1, head_dim]`, shared across heads —+//! which is VITS's `heads_share` default, and was verified by reconstructing both heads from+//! the one table. `p.kw` is the number of offsets, so the window is `(p.kw - 1) / 2`; a+//! nine-wide kernel over the sequence is exactly what this is.+//!+//! `p.param0_bits` scales **both** terms, because the export divides the query by+//! `sqrt(head_dim)` before either product.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ uint head, query, key;+ unpack(index, head, query, key);++ uint head_dim = p.in_c / p.group;+ uint stride = p.in_h * p.in_w;+ uint base = head * head_dim * stride;++ float total = 0.0;+ for (uint d = 0u; d < head_dim; d++) {+ uint channel = base + d * stride;+ total += float(arena[p.in0 + channel + query]) * float(arena[p.in1 + channel + key]);+ }++ // The relative band. Signed, because `key` may be either side of `query`.+ int window = int(p.kw - 1u) / 2;+ int offset = int(key) - int(query);+ if (offset >= -window && offset <= window) {+ uint row = uint(offset + window) * head_dim;+ for (uint d = 0u; d < head_dim; d++) {+ total += float(arena[p.in0 + base + d * stride + query])+ * float(weights[p.weight + row + d]);+ }+ }++ arena[p.out_at + index] = float16_t(total * uintBitsToFloat(p.param0_bits));+}
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 1d1707c0ab..95c105dd6f 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -227,6 +227,13 @@ pub enum Kind { /// attention is not an op: output channel `c` belongs to head `c / head_dim` and /// lands where the concatenated result wants it. Head count in [`Push::group`]. AttnApply,+ /// [`Kind::AttnScores`] plus VITS's relative-position term, which is nine taps rather+ /// than the `[heads, T, 2T-1]` product and skew its export spells out. Table at+ /// [`Push::weight`] as `[2 * window + 1, head_dim]`, offset count in [`Push::kw`].+ AttnScoresRelative,+ /// [`Kind::AttnApply`] plus the value-side relative term. See+ /// [`Kind::AttnScoresRelative`].+ AttnApplyRelative, /// `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@@ -500,6 +507,23 @@ enum Node { out: Id, heads: u32, },+ AttnScoresRelative {+ q: Id,+ k: Id,+ out: Id,+ heads: u32,+ scale: f32,+ table: u32,+ offsets: u32,+ },+ AttnApplyRelative {+ probs: Id,+ v: Id,+ out: Id,+ heads: u32,+ table: u32,+ offsets: u32,+ }, } /// Records a forward pass, then packs and resolves it.@@ -875,6 +899,13 @@ impl<'a> Builder<'a> { /// it is a property of the head geometry, not a trained value, so there is no call /// site that could legitimately pass a different one. pub fn attn_scores(&mut self, q: Id, k: Id, heads: u32) -> Id {+ let (out, scale) = self.score_map(q, k, heads);+ self.nodes.push(Node::AttnScores { q, k, out, heads, scale });+ out+ }++ /// The validation, output tensor and scale every score map shares, relative or not.+ fn score_map(&mut self, q: Id, k: Id, heads: u32) -> (Id, f32) { let (sq, sk) = (self.shape_of(q), self.shape_of(k)); if sq != sk { self.fail(format!("attention over q {sq:?} and k {sk:?}"));@@ -890,9 +921,7 @@ impl<'a> Builder<'a> { } let head_dim = sq.c.checked_div(heads).unwrap_or(0); let scale = 1.0 / (head_dim.max(1) as f32).sqrt();- let out = self.tensor(Shape::new(heads, sq.w, sq.w));- self.nodes.push(Node::AttnScores { q, k, out, heads, scale });- out+ (self.tensor(Shape::new(heads, sq.w, sq.w)), scale) } /// Softmax over the last axis, which for a score map is one query's distribution.@@ -915,8 +944,70 @@ impl<'a> Builder<'a> { out } + /// [`Builder::attn_scores`] plus VITS's relative-position term.+ ///+ /// `table` is a `[offsets, head_dim]` tensor of learned offsets, shared across heads.+ /// `offsets` must be odd: it is `2 * window + 1`, centred on zero displacement.+ pub fn attn_scores_relative(+ &mut self,+ q: Id,+ k: Id,+ heads: u32,+ table: usize,+ offsets: u32,+ ) -> Id {+ let (out, scale) = self.score_map(q, k, heads);+ let shape = self.shape_of(q);+ let head_dim = shape.c.checked_div(heads.max(1)).unwrap_or(0);+ self.check_offsets(offsets, shape.w);+ let table = self.weight(table, &[offsets, head_dim]);+ self.nodes.push(Node::AttnScoresRelative { q, k, out, heads, scale, table, offsets });+ out+ }++ /// [`Builder::attn_apply`] plus the value-side relative term.+ pub fn attn_apply_relative(+ &mut self,+ probs: Id,+ v: Id,+ heads: u32,+ table: usize,+ offsets: u32,+ ) -> Id {+ let out = self.mixed(probs, v, heads);+ let shape = self.shape_of(v);+ let head_dim = shape.c.checked_div(heads.max(1)).unwrap_or(0);+ self.check_offsets(offsets, shape.w);+ let table = self.weight(table, &[offsets, head_dim]);+ self.nodes.push(Node::AttnApplyRelative { probs, v, out, heads, table, offsets });+ out+ }++ /// A relative table is `2 * window + 1` entries centred on zero displacement.+ fn check_offsets(&mut self, offsets: u32, sequence: u32) {+ if offsets == 0 || offsets.is_multiple_of(2) {+ self.fail(format!(+ "{offsets} relative offsets: the table is 2 * window + 1 entries centred on \+ zero displacement, so an even count has no centre"+ ));+ }+ if offsets > sequence * 2 {+ self.fail(format!(+ "{offsets} relative offsets over a sequence of {sequence}: the band is wider \+ than any pair of positions can be apart"+ ));+ }+ }+ /// Apply `probs`, a `[heads, T, T]` score map, to `v`, a `[d_model, 1, T]` sequence. pub fn attn_apply(&mut self, probs: Id, v: Id, heads: u32) -> Id {+ let out = self.mixed(probs, v, heads);+ self.nodes.push(Node::AttnApply { probs, v, out, heads });+ out+ }++ /// The validation and output tensor every weighted sum shares, relative or not.+ fn mixed(&mut self, probs: Id, v: Id, heads: u32) -> Id { let (sp, sv) = (self.shape_of(probs), self.shape_of(v)); if sp != Shape::new(heads, sv.w, sv.w) { self.fail(format!(@@ -931,9 +1022,7 @@ impl<'a> Builder<'a> { if heads == 0 || !sv.c.is_multiple_of(heads) { self.fail(format!("{} channels do not split into {heads} heads", sv.c)); }- let out = self.tensor(sv);- self.nodes.push(Node::AttnApply { probs, v, out, heads });- out+ self.tensor(sv) } /// Pack the arena and resolve every offset, with `outputs` as the result tensors.@@ -1274,6 +1363,55 @@ impl<'a> Builder<'a> { invocations: so.len(), }); }+ Node::AttnScoresRelative { q, k, out, heads, scale, table, offsets } => {+ let (si, so) = (shape(*q), shape(*out));+ ops.push(Op::Dispatch {+ kind: Kind::AttnScoresRelative,+ push: Push {+ in0: at(*q)?,+ in1: at(*k)?,+ out: at(*out)?,+ weight: *table,+ in_c: si.c,+ in_h: si.h,+ in_w: si.w,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ // The offset count reads as a kernel width, because that is what a+ // band of `2 * window + 1` taps along the sequence is.+ kw: *offsets,+ group: *heads,+ param0_bits: scale.to_bits(),+ count: so.len(),+ ..Push::default()+ },+ invocations: so.len(),+ });+ }+ Node::AttnApplyRelative { probs, v, out, heads, table, offsets } => {+ let so = shape(*out);+ ops.push(Op::Dispatch {+ kind: Kind::AttnApplyRelative,+ push: Push {+ in0: at(*probs)?,+ in1: at(*v)?,+ out: at(*out)?,+ weight: *table,+ in_c: so.c,+ in_h: so.h,+ in_w: so.w,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ kw: *offsets,+ group: *heads,+ 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`@@ -1354,6 +1492,8 @@ impl Node { | Node::Affine { out, .. } | Node::LayerNorm { out, .. } | Node::AttnScores { out, .. }+ | Node::AttnScoresRelative { out, .. }+ | Node::AttnApplyRelative { out, .. } | Node::Softmax { out, .. } | Node::LeakyRelu { out, .. } | Node::AttnApply { out, .. }@@ -1373,7 +1513,10 @@ impl Node { | Node::LeakyRelu { input, .. } | Node::GlobalAvgPool { input, .. } => vec![*input], Node::Binary { a, b, .. } => vec![*a, *b],- Node::AttnScores { q: a, k: b, .. } | Node::AttnApply { probs: a, v: b, .. } => {+ Node::AttnScores { q: a, k: b, .. }+ | Node::AttnApply { probs: a, v: b, .. }+ | Node::AttnScoresRelative { q: a, k: b, .. }+ | Node::AttnApplyRelative { probs: a, v: b, .. } => { vec![*a, *b] } Node::Concat { parts, .. } => parts.clone(),
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 af6be8b7d2..ccd4c365d9 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -187,6 +187,8 @@ impl Reference { Kind::Softmax => self.softmax(push), Kind::AttnApply => self.attn_apply(push), Kind::LeakyRelu => self.leaky_relu(push),+ Kind::AttnScoresRelative => self.attn_scores_relative(push),+ Kind::AttnApplyRelative => self.attn_apply_relative(push), }, }; result.map_err(|e| format!("step {step} ({op:?}): {e}"))?;@@ -605,6 +607,71 @@ impl Reference { Ok(()) } + /// [`Self::attn_scores`] plus VITS's relative-position term: nine taps of a learned+ /// table indexed by `key - query`, in place of the export's product-and-skew.+ ///+ /// The scale multiplies both terms, because the export divides the query by+ /// `sqrt(head_dim)` before either product.+ fn attn_scores_relative(&mut self, p: &Push) -> Result<(), String> {+ let head_dim = heads(p, p.in_c)?;+ let stride = p.in_h * p.in_w;+ let scale = f32::from_bits(p.param0_bits);+ let window = (p.kw.max(1) - 1) as i64 / 2;+ for head in 0..p.group {+ let base = head * head_dim * stride;+ for query in 0..p.out_h {+ for key in 0..p.out_w {+ let mut total = 0.0;+ for d in 0..head_dim {+ let channel = base + d * stride;+ total += self.load(p.in0, channel + query)?+ * self.load(p.in1, channel + key)?;+ }+ let offset = key as i64 - query as i64;+ if offset.abs() <= window {+ let row = (offset + window) as u32 * head_dim;+ for d in 0..head_dim {+ total += self.load(p.in0, base + d * stride + query)?+ * self.weight(p.weight, row + d)?;+ }+ }+ self.store(p.out, nchw(p, head, query, key), total * scale)?;+ }+ }+ }+ Ok(())+ }++ /// [`Self::attn_apply`] plus the value-side relative term. Taps outside the sequence+ /// are skipped rather than clamped, which would double-count a neighbour at the ends.+ fn attn_apply_relative(&mut self, p: &Push) -> Result<(), String> {+ let head_dim = heads(p, p.out_c)?;+ let keys = p.out_w;+ let window = (p.kw.max(1) - 1) as i64 / 2;+ for channel in 0..p.out_c {+ let row = (channel / head_dim) * keys * keys;+ let depth = channel % head_dim;+ for query in 0..keys {+ let mut total = 0.0;+ for key in 0..keys {+ total += self.load(p.in0, row + query * keys + key)?+ * self.load(p.in1, channel * keys + key)?;+ }+ for offset in -window..=window {+ let key = query as i64 + offset;+ if key < 0 || key >= keys as i64 {+ continue;+ }+ let entry = (offset + window) as u32 * head_dim + depth;+ total += self.load(p.in0, row + query * keys + key as u32)?+ * self.weight(p.weight, entry)?;+ }+ self.store(p.out, nchw(p, channel, 0, query), total)?;+ }+ }+ Ok(())+ }+ /// `out[c][y][x] = a[c][y][x] * b[c]`, the excite half of a squeeze-excite block. fn mul_broadcast(&mut self, p: &Push) -> Result<(), String> { for oc in 0..p.out_c {@@ -900,6 +967,28 @@ mod tests { } } + /// [`two`], with weight tensors and independent shapes, for the relative attention.+ fn two_weighted(+ shapes: (Shape, Shape),+ inputs: (&[f32], &[f32]),+ tensors: &[(Vec<u32>, Vec<f32>)],+ record: impl FnOnce(&mut Builder, Id, Id) -> Id,+ ) -> Vec<f32> {+ let given = Given::new(tensors).expect("the fixture tensors lay out");+ let mut builder = Builder::new(&given);+ let first = builder.input(shapes.0);+ let second = builder.input(shapes.1);+ let last = record(&mut builder, first, second);+ let plan = builder.finish(&[last]).expect("the fixture plan builds");+ super::super::tests::assert_no_aliasing(&plan);+ let outputs =+ run_multi(&plan, given.data(), &[inputs.0, inputs.1]).expect("the fixture plan runs");+ match <[Vec<f32>; 1]>::try_from(outputs) {+ Ok([only]) => only,+ Err(other) => panic!("{} outputs", other.len()),+ }+ }+ fn close(got: &[f32], want: &[f32]) { assert_eq!(got.len(), want.len(), "{got:?} vs {want:?}"); for (i, (&g, &w)) in got.iter().zip(want).enumerate() {@@ -1571,6 +1660,103 @@ mod tests { assert!(error.contains("height above"), "{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+ // term is then `scale * head_dim` for every pair, and the relative term adds+ // `scale * sum_d table[j - i + window][d]` inside the band and nothing outside it.+ //+ // A table of three offsets whose rows sum to -10, 0 and +10, so the sign of the+ // displacement is visible in the answer: a transposed `j - i` would mirror it.+ let table: Vec<f32> = vec![-5.0, -5.0, 0.0, 0.0, 5.0, 5.0];+ let got = two_weighted(+ (Shape::new(2, 1, 4), Shape::new(2, 1, 4)),+ (&[1.0; 8], &[1.0; 8]),+ &[(vec![3, 2], table)],+ |b, q, k| b.attn_scores_relative(q, k, 1, 0, 3),+ );+ // scale = 1/sqrt(2); content is 2 * scale for every pair.+ let scale = 1.0 / 2.0f32.sqrt();+ let content = 2.0 * scale;+ let mut want = vec![0.0f32; 16];+ for query in 0..4i64 {+ for key in 0..4i64 {+ let offset = key - query;+ let relative = match offset {+ -1 => -10.0,+ 0 => 0.0,+ 1 => 10.0,+ _ => 0.0,+ };+ want[(query * 4 + key) as usize] = content + relative * scale;+ }+ }+ close(&got, &want);+ }++ #[test]+ fn a_relative_score_map_leaves_the_band_alone_outside_the_window() {+ // The whole reason this is nine taps and not a `[heads, T, 2T-1]` product and skew:+ // beyond the window the export's skewed tensor is exactly zero. Verified against+ // onnxruntime on Piper's encoder, and pinned here.+ let table: Vec<f32> = vec![7.0, 7.0, 0.0, 0.0, 7.0, 7.0];+ let got = two_weighted(+ (Shape::new(2, 1, 5), Shape::new(2, 1, 5)),+ (&[1.0; 10], &[1.0; 10]),+ &[(vec![3, 2], table)],+ |b, q, k| b.attn_scores_relative(q, k, 1, 0, 3),+ );+ let scale = 1.0 / 2.0f32.sqrt();+ let content = 2.0 * scale;+ for query in 0..5usize {+ for key in 0..5usize {+ let value = got[query * 5 + key];+ let far = (key as i64 - query as i64).abs() > 1;+ if far {+ assert!(+ (value - content).abs() < 1e-3,+ "({query},{key}) is outside the band but moved: {value} vs {content}"+ );+ }+ }+ }+ }++ #[test]+ fn a_relative_weighted_sum_reads_the_diagonal_of_its_probabilities() {+ // One head, two channels, three positions. Probabilities are the identity, so the+ // content term picks V[.,i] and the relative term adds `table[window][d]` — the+ // centre row — because the only non-zero probability is at `key == query`.+ let probs: Vec<f32> = vec![+ 1.0, 0.0, 0.0, //+ 0.0, 1.0, 0.0, //+ 0.0, 0.0, 1.0,+ ];+ let values: Vec<f32> = vec![1.0, 2.0, 3.0, 10.0, 20.0, 30.0];+ let table: Vec<f32> = vec![100.0, 200.0, 1.0, 2.0, 300.0, 400.0];+ let got = two_weighted(+ (Shape::new(1, 3, 3), Shape::new(2, 1, 3)),+ (&probs, &values),+ &[(vec![3, 2], table)],+ |b, p, v| b.attn_apply_relative(p, v, 1, 0, 3),+ );+ // Channel 0 gets table[1][0] = 1, channel 1 gets table[1][1] = 2.+ close(&got, &[2.0, 3.0, 4.0, 12.0, 22.0, 32.0]);+ }++ #[test]+ fn a_relative_table_with_an_even_number_of_offsets_is_refused() {+ // `2 * window + 1` is always odd, so an even count has no centre and the+ // displacement it indexed would be ambiguous.+ let source = Given::new(&[(vec![4, 2], vec![0.0; 8])]).expect("the fixture lays out");+ let mut b = Builder::new(&source);+ let q = b.input(Shape::new(2, 1, 4));+ let k = b.input(Shape::new(2, 1, 4));+ let out = b.attn_scores_relative(q, k, 1, 0, 4);+ let error = b.finish(&[out]).expect_err("an even offset count");+ assert!(error.contains("no centre"), "{error}");+ }+ #[test] fn a_leaky_relu_scales_only_the_negative_side() { // HiFi-GAN's slope. A standalone pass rather than a fused activation, because in a
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 7e3365c55f..d583d82568 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -41,9 +41,13 @@ const ATTN_SCORES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/attn_scores const SOFTMAX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/softmax.comp.spv")); const ATTN_APPLY: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/attn_apply.comp.spv")); const LEAKY_RELU: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/leaky_relu.comp.spv"));+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")); /// Every shader, in the order [`Pipelines::create`] destructures them.-const SPIRV: [&[u8]; 15] = [+const SPIRV: [&[u8]; 17] = [ CONV, CONV_TRANSPOSE, MAXPOOL,@@ -59,6 +63,8 @@ const SPIRV: [&[u8]; 15] = [ SOFTMAX, ATTN_APPLY, LEAKY_RELU,+ ATTN_SCORES_RELATIVE,+ ATTN_APPLY_RELATIVE, ]; /// `local_size_x` in `shaders/common.glsl`. A dispatch covers `ceil(invocations / this)`@@ -97,6 +103,8 @@ pub struct Pipelines { softmax: vk::Pipeline, attn_apply: vk::Pipeline, leaky_relu: vk::Pipeline,+ attn_scores_relative: vk::Pipeline,+ attn_apply_relative: vk::Pipeline, } impl Pipelines {@@ -234,6 +242,8 @@ impl Pipelines { softmax, attn_apply, leaky_relu,+ attn_scores_relative,+ attn_apply_relative, ] = match <[vk::Pipeline; SPIRV.len()]>::try_from(built) { Ok(all) => all, Err(built) => {@@ -265,6 +275,8 @@ impl Pipelines { softmax, attn_apply, leaky_relu,+ attn_scores_relative,+ attn_apply_relative, }) } @@ -286,6 +298,8 @@ impl Pipelines { Kind::Softmax => self.softmax, Kind::AttnApply => self.attn_apply, Kind::LeakyRelu => self.leaky_relu,+ Kind::AttnScoresRelative => self.attn_scores_relative,+ Kind::AttnApplyRelative => self.attn_apply_relative, } } @@ -309,6 +323,8 @@ impl Pipelines { self.softmax, self.attn_apply, self.leaky_relu,+ self.attn_scores_relative,+ self.attn_apply_relative, ] { device.destroy_pipeline(pipeline, None); }