Skip to main content

nuvec_core/
fast.rs

1//! Fused operations with dedicated GPU kernels, as MLX's `mx.fast`: [`rms_norm`],
2//! [`layer_norm`], [`rope`], [`cross_entropy`], [`scaled_dot_product_attention`] and
3//! [`gated_delta`] (mlx-lm's Gated DeltaNet kernels); nuvec's [`add_rms_norm`] (a residual
4//! connection and its norm), [`norm_rope`] (norm, RoPE and a cache write) and
5//! [`paged_attention`] with [`paged_write`] (a block-table KV cache); and, through
6//! [`crate::Array::softmax`] and [`crate::Array::logsumexp`] over the last axis, MLX's
7//! softmax and log-sum-exp kernels.
8//!
9//! Each operation is one GPU kernel (MLX's, or nuvec's own) with an equivalent graph of ordinary
10//! operations, its *fallback*. As in MLX, the fallback runs on the CPU stream, and it
11//! defines the forward-mode derivative and batching; reverse mode uses dedicated kernels
12//! where MLX has them.
13//!
14//! Like every operation, these return arrays: invalid arguments give a failed array that
15//! carries the error and the caller's location (see [`crate::Array::check`]).
16//!
17//! # Memory
18//!
19//! The norms, RoPE, `norm_rope`, cross entropy, softmax, log-sum-exp, the gated delta rule
20//! and the paged kernels hold no scratch beyond their inputs and outputs on the GPU (the
21//! fallback graphs on the CPU hold their intermediates). Attention's scratch depends on its
22//! plan: see [`scaled_dot_product_attention`]. Rotation frequencies are computed per call,
23//! never cached.
24//!
25//! ```
26//! use nuvec_core::{array, fast};
27//!
28//! let x = array![[1.0, 2.0], [3.0, 4.0]];
29//! let y = fast::rms_norm(&x, None, 1e-5); // x / sqrt(mean(x²) + eps), per row
30//! let v = y.to_vec::<f32>().unwrap();
31//! assert!((v[0] - 1.0 / 2.5f32.sqrt()).abs() < 1e-5);
32//! ```
33
34pub(crate) mod imp;
35pub(crate) mod plan;
36
37use std::panic::Location;
38
39use smallvec::SmallVec;
40
41use crate::Array;
42
43pub use crate::kernel::{KernelCall, KernelConfig, MetalKernel, TemplateArg};
44pub use imp::{AttentionMask, FastOp, Rotation};
45
46/// The arrays among required and optional operands, for failure reporting.
47fn operands<'a>(
48    required: &[&'a Array],
49    optional: &[Option<&'a Array>],
50) -> SmallVec<[&'a Array; 8]> {
51    let mut out: SmallVec<[&Array; 8]> = SmallVec::from_slice(required);
52    out.extend(optional.iter().flatten().copied());
53    out
54}
55
56/// Root-mean-square normalisation over the last axis, `x / sqrt(mean(x²) + eps) · weight`,
57/// as MLX's `fast.rms_norm`: statistics in float32, the result in the promoted type of `x`
58/// and `weight` (1-D, the last axis's size).
59#[track_caller]
60pub fn rms_norm<'a>(x: &Array, weight: impl Into<Option<&'a Array>>, eps: f32) -> Array {
61    let weight = weight.into();
62    let ins = operands(&[x], &[weight]);
63    Array::sticky("rms_norm", Location::caller(), &ins, || {
64        imp::rms_norm(x, weight, eps)
65    })
66}
67
68/// A residual connection followed by RMS normalisation: `h = x + residual` and
69/// [`rms_norm`]`(h, weight, eps)`, returned as `(h, normed)`, from one GPU kernel. The
70/// results equal `x + residual` then [`rms_norm`] exactly; a weight that would widen the
71/// sum's dtype runs the two operations.
72#[track_caller]
73pub fn add_rms_norm<'a>(
74    x: &Array,
75    residual: &Array,
76    weight: impl Into<Option<&'a Array>>,
77    eps: f32,
78) -> (Array, Array) {
79    let weight = weight.into();
80    let ins = operands(&[x, residual], &[weight]);
81    let [h, normed] = Array::sticky_n("add_rms_norm", Location::caller(), &ins, || {
82        let (h, n) = imp::add_rms_norm(x, residual, weight, eps)?;
83        Ok([h, n])
84    });
85    (h, normed)
86}
87
88/// Layer normalisation over the last axis, `(x - mean) / sqrt(var + eps) · weight + bias`,
89/// as MLX's `fast.layer_norm`: statistics in float32, the result in the promoted type.
90#[track_caller]
91pub fn layer_norm<'a>(
92    x: &Array,
93    weight: impl Into<Option<&'a Array>>,
94    bias: impl Into<Option<&'a Array>>,
95    eps: f32,
96) -> Array {
97    let weight = weight.into();
98    let bias = bias.into();
99    let ins = operands(&[x], &[weight, bias]);
100    Array::sticky("layer_norm", Location::caller(), &ins, || {
101        imp::layer_norm(x, weight, bias, eps)
102    })
103}
104
105/// Rotary position embeddings, as MLX's `fast.rope`, of `x` (at least 3-D: `[B, ...,
106/// T, D]`, positions along `T`): the first `dims` features (even) are rotated in pairs,
107/// the two halves (or interleaved pairs, `traditional`) by angle `(offset + t) · scale ·
108/// θᵢ`, with `θᵢ = base^(-2i/dims)` or `1 / freqs[i]`. Exactly one of `base` and `freqs`
109/// is given. `offset` is an integer scalar or one per batch entry.
110#[track_caller]
111pub fn rope<'a>(
112    x: &Array,
113    dims: i32,
114    traditional: bool,
115    base: Option<f32>,
116    scale: f32,
117    offset: &Array,
118    freqs: impl Into<Option<&'a Array>>,
119) -> Array {
120    let freqs = freqs.into();
121    let ins = operands(&[x, offset], &[freqs]);
122    Array::sticky("rope", Location::caller(), &ins, || {
123        let dims = usize::try_from(dims).map_err(|_| {
124            crate::Error::InvalidArgument(format!("rope: dims must not be negative, got {dims}"))
125        })?;
126        imp::rope(x, dims, traditional, base, scale, offset, freqs)
127    })
128}
129
130/// Cross entropy over the last axis of `logits` against integer class indices `targets`
131/// (the logits' shape without the last axis; negative indices count from the end), as
132/// MLX's `fast.cross_entropy`: `logsumexp(logits) - logits[target]` per row, in float32.
133#[track_caller]
134pub fn cross_entropy(logits: &Array, targets: &Array) -> Array {
135    Array::sticky(
136        "cross_entropy",
137        Location::caller(),
138        &[logits, targets],
139        || imp::cross_entropy(logits, targets),
140    )
141}
142
143/// An attention layer's query or key preparation in one kernel: each head's features of
144/// `x` (`[B, H, L, D]`, any strides, as the transposed projection) optionally normalised
145/// as [`rms_norm`] with `norm = (weight, eps)` (Qwen 3's `q_norm` and `k_norm`), then
146/// rotated as [`rope`] at positions `offset..offset + L`.
147///
148/// Without `cache`, the result is a new `[B, H, L, D]` array. With `cache` (`[B, H, C, D]`,
149/// `C ≥ offset + L`), the result is `cache` with positions `offset..offset + L` replaced
150/// (as [`crate::Array::at`] with `set`, and written in place when the evaluation owns the
151/// cache), so keys go into a key cache without a separate copy.
152///
153/// The results equal [`rms_norm`], [`rope`] and the update composed (on the GPU, bit for
154/// bit); differing dtypes, other ranks and head sizes over 1024 run that composition.
155#[track_caller]
156pub fn norm_rope<'a>(
157    x: &Array,
158    norm: Option<(&Array, f32)>,
159    rotation: Rotation<'_>,
160    offset: i32,
161    cache: impl Into<Option<&'a Array>>,
162) -> Array {
163    let cache = cache.into();
164    let ins = operands(&[x], &[norm.map(|n| n.0), rotation.freqs, cache]);
165    Array::sticky("norm_rope", Location::caller(), &ins, || {
166        let offset = usize::try_from(offset).map_err(|_| {
167            crate::Error::InvalidArgument(format!(
168                "norm_rope: offset must not be negative, got {offset}"
169            ))
170        })?;
171        imp::norm_rope(x, norm, rotation, offset, cache)
172    })
173}
174
175/// Attention over a paged KV cache, for a batch of sequences of different lengths.
176///
177/// Keys and values live in blocks of positions, `k_cache` and `v_cache` being
178/// `[blocks, kv_heads, block_size, D]`; sequence `b` keeps its positions in the blocks
179/// `block_tables[b]` lists (`[B, max_blocks]`, integers; entries past the sequence's blocks
180/// are ignored). `q` is `[B, Hq, L, D]` (`Hq` a multiple of `kv_heads`): the last `L`
181/// positions of each sequence, whose keys are already in the cache. Query `l` of sequence
182/// `b` attends positions `0..=lengths[b] − L + l` (causal at the end; `lengths[b] ≥ L`).
183/// Returns `[B, Hq, L, D]`.
184///
185/// Out-of-range inputs never read outside the caches: block ids are clamped to
186/// `0..blocks` and lengths to `0..=max_blocks · block_size` (the table's capacity), on
187/// every device.
188///
189/// On the GPU this is MLX's vector attention (one pass, or two for long caches) reading
190/// keys through the block table, for head sizes 64, 128 and 256 and power-of-two block
191/// sizes (others run the composition). Each sequence's result equals
192/// [`scaled_dot_product_attention`]'s vector kernel over the same keys stored contiguously
193/// when both take the same number of passes.
194#[track_caller]
195pub fn paged_attention(
196    q: &Array,
197    k_cache: &Array,
198    v_cache: &Array,
199    block_tables: &Array,
200    lengths: &Array,
201    scale: f32,
202) -> Array {
203    Array::sticky(
204        "paged_attention",
205        Location::caller(),
206        &[q, k_cache, v_cache, block_tables, lengths],
207        || imp::paged_attention(q, k_cache, v_cache, block_tables, lengths, scale),
208    )
209}
210
211/// `cache` (`[blocks, kv_heads, block_size, D]`) with the positions `new` holds
212/// (`[T, kv_heads, D]`) written into their slots: `slots[t]` (integers, `[T]`) is block
213/// `slots[t] / block_size`, position `slots[t] % block_size`. Slots must be distinct;
214/// out-of-range slots (negative, or at least `blocks · block_size`) are skipped. In place
215/// when the evaluation owns the cache.
216#[track_caller]
217pub fn paged_write(cache: &Array, new: &Array, slots: &Array) -> Array {
218    Array::sticky(
219        "paged_write",
220        Location::caller(),
221        &[cache, new, slots],
222        || imp::paged_write(cache, new, slots),
223    )
224}
225
226/// The options of [`scaled_dot_product_attention`] and [`plan_attention`]: the mask,
227/// attention sinks, a sliding window and a cap on score memory. Build them with
228/// [`AttentionOptions::causal`] or `Default` and the chained setters:
229///
230/// ```
231/// use nuvec_core::fast::AttentionOptions;
232///
233/// let opts = AttentionOptions::causal().window(4096).max_score_bytes(512 << 20);
234/// assert_eq!(opts.window, Some(4096));
235/// ```
236///
237/// This is the one options type of attention: new features (window and head-size-512
238/// kernels, backward routing) extend it, never a second entry point.
239#[non_exhaustive]
240#[derive(Clone, Copy, Debug, Default)]
241pub struct AttentionOptions<'a> {
242    /// The mask: none (the default), causal, or an array.
243    pub mask: AttentionMask<'a>,
244    /// Attention sinks (`[Hq]`): one logit per query head that takes part in the softmax
245    /// but attends to nothing.
246    pub sinks: Option<&'a Array>,
247    /// A sliding window: query `i` attends only to the `window` keys up to and including
248    /// its position (as mlx-lm's `create_causal_mask(..., window_size)`). Needs the causal
249    /// mask.
250    pub window: Option<i32>,
251    /// A cap, in bytes, on every score-sized intermediate (scores, masked scores, the
252    /// float32 sink-softmax intermediates, materialised masks); see
253    /// [`scaled_dot_product_attention`].
254    pub max_score_bytes: Option<usize>,
255}
256
257impl<'a> AttentionOptions<'a> {
258    /// Causal masking: query `i` attends to keys `0..=i + Lk - Lq` (the queries are the last
259    /// `Lq` positions).
260    pub fn causal() -> Self {
261        AttentionOptions {
262            mask: AttentionMask::Causal,
263            ..Self::default()
264        }
265    }
266
267    /// A boolean (true attends) or additive mask, broadcastable to `[B, Hq, Lq, Lk]`.
268    #[must_use]
269    pub fn mask(mut self, mask: &'a Array) -> Self {
270        self.mask = AttentionMask::Array(mask);
271        self
272    }
273
274    /// Attention sinks, `[Hq]` (`None` for none).
275    #[must_use]
276    pub fn sinks(mut self, sinks: impl Into<Option<&'a Array>>) -> Self {
277        self.sinks = sinks.into();
278        self
279    }
280
281    /// A sliding window of `keys` keys (needs [`AttentionOptions::causal`]).
282    #[must_use]
283    pub fn window(mut self, keys: i32) -> Self {
284        self.window = Some(keys);
285        self
286    }
287
288    /// Caps every score-sized intermediate at `bytes` (positive).
289    #[must_use]
290    pub fn max_score_bytes(mut self, bytes: usize) -> Self {
291        self.max_score_bytes = Some(bytes);
292        self
293    }
294}
295
296impl<'a> From<AttentionMask<'a>> for AttentionOptions<'a> {
297    /// Options with this mask and nothing else.
298    fn from(mask: AttentionMask<'a>) -> Self {
299        AttentionOptions {
300            mask,
301            ..Self::default()
302        }
303    }
304}
305
306/// The kernel family an attention call runs (see [`plan_attention`]).
307#[non_exhaustive]
308#[derive(Clone, Copy, Debug, PartialEq, Eq)]
309pub enum AttentionKernel {
310    /// At most 8 queries: MLX's vector kernels. `passes` is 1 or 2; `blocks` the key
311    /// partitions of the first of two passes (1 for one pass; the largest over
312    /// dispatches); `dispatches` is more than 1 when query rows need different one-query
313    /// configurations (the serial rule).
314    Vector {
315        /// Passes over the keys (1 or 2).
316        passes: u8,
317        /// Key partitions of the first pass.
318        blocks: i32,
319        /// Dispatches (groups of query rows with one configuration).
320        dispatches: i32,
321    },
322    /// MLX's tiled (steel) attention kernel: no scores are materialised.
323    Tiled,
324    /// The composition: `softmax(scale · q kᵀ + mask) v` from matrix products.
325    Composed,
326    /// The composition per block of `rows` queries, one block after another.
327    ComposedBlocks {
328        /// Queries per block (the last block may have fewer).
329        rows: i32,
330    },
331}
332
333/// How an attention call runs and the memory it holds (see [`plan_attention`]).
334#[non_exhaustive]
335#[derive(Clone, Copy, Debug, PartialEq, Eq)]
336pub struct AttentionPlan {
337    /// The kernel family.
338    pub kernel: AttentionKernel,
339    /// Bytes held beyond the inputs and the output while the call runs (for one block when
340    /// blocked; see the `# Memory` section of [`scaled_dot_product_attention`]).
341    pub scratch_bytes: usize,
342    /// The largest single score-sized intermediate: what `max_score_bytes` bounds.
343    pub max_intermediate_bytes: usize,
344    /// Whether the cap changed the choice.
345    pub capped: bool,
346}
347
348/// How [`scaled_dot_product_attention`] will run for these shapes (`[B, H, L, D]` each),
349/// dtype and options, on the calling thread's default device, without evaluating or
350/// allocating anything. Masks and sinks in `options` are read for their shape and dtype
351/// only. Errors are those the attention call would report.
352///
353/// The plan is a pure function of the shapes, the dtype, the options and the GPU's
354/// generation and class: the same inputs give the same plan in every call, thread and
355/// process, whatever memory is free; the attention op runs exactly this plan (one routing
356/// function).
357///
358/// ```
359/// use nuvec_core::{DType, fast::{AttentionKernel, AttentionOptions, plan_attention}};
360///
361/// # fn main() -> nuvec_core::Result<()> {
362/// let (q, k) = ([1, 16, 1024, 256], [1, 2, 33_792, 256]);
363/// let opts = AttentionOptions::causal().max_score_bytes(512 << 20);
364/// let plan = plan_attention(&q, &k, &k, DType::BF16, &opts)?;
365/// assert!(plan.max_intermediate_bytes <= 512 << 20);
366/// assert!(matches!(
367///     plan.kernel,
368///     AttentionKernel::Tiled | AttentionKernel::ComposedBlocks { .. }
369/// ));
370/// # Ok(())
371/// # }
372/// ```
373pub fn plan_attention(
374    q: &[i32],
375    k: &[i32],
376    v: &[i32],
377    dtype: crate::DType,
378    options: &AttentionOptions<'_>,
379) -> crate::Result<AttentionPlan> {
380    imp::plan_attention(q, k, v, dtype, options)
381}
382
383/// Scaled dot-product attention, as MLX's `fast.scaled_dot_product_attention`:
384/// `softmax(scale · q kᵀ + mask) v` over `[B, H, L, D]` arrays, with the mask, sinks,
385/// window and score cap in [`AttentionOptions`].
386///
387/// `k` and `v` may have fewer heads than `q` (grouped-query attention; `Hq` a multiple of
388/// `Hkv`), and `v` its own head size. Sinks (`[Hq]`) add one logit per head that takes part
389/// in the softmax but attends to nothing.
390///
391/// ```
392/// use nuvec_core::{DType, fast::{self, AttentionOptions}, ops};
393///
394/// let q = ops::ones([1, 4, 3, 64], DType::F32);
395/// let kv = ops::ones([1, 2, 5, 64], DType::F32);
396/// let out = fast::scaled_dot_product_attention(&q, &kv, &kv, 0.125, &AttentionOptions::causal());
397/// assert_eq!(out.shape(), [1, 4, 3, 64]);
398/// ```
399///
400/// # Routing
401///
402/// [`plan_attention`] decides, and reports, how the call runs. On the GPU, up to 8 queries
403/// use MLX's vector kernels, more use its tiled kernel or the composition (as MLX: the
404/// composition is faster for some head sizes and shapes); the CPU runs the composition.
405/// A window runs through the composition (keys sliced to the window).
406///
407/// **The serial rule.** With 2 to 8 queries (speculative verification), each query row
408/// takes the configuration (passes, key partitions, kernel variant) of the same row run
409/// alone as one query over its causal key prefix, and rows with equal configurations share
410/// a dispatch. So each row's result equals, bit for bit, the one-query call over its
411/// prefix (MLX picks one configuration for all rows instead). Rows that need the
412/// one-key-per-step kernel variant (float32 at head size 256) and do not fit one
413/// threadgroup together keep MLX's composition instead.
414///
415/// **The cap.** With `max_score_bytes = c`, no score-sized intermediate larger than `c`
416/// bytes is allocated (element size 4 with sinks or float32): either the tiled kernel
417/// runs (it materialises no scores) or the composition runs in blocks of query rows, one
418/// block after another (each block's queries depend on the previous block's output, so one
419/// block's scratch is live at a time), whichever measured faster. The result equals the
420/// uncapped composition within rounding. A cap below one query row's intermediate selects
421/// the tiled kernel where it supports the shape and is an `InvalidArgument` error naming
422/// the smallest admissible cap otherwise; a cap of 0 is invalid. Vector kernels (decode)
423/// never materialise scores, so the cap does not affect them.
424///
425/// # Memory
426///
427/// Scratch beyond inputs and output ([`AttentionPlan::scratch_bytes`]), with `s` the
428/// dtype's size, `r` the rows of a block (`Lq` unblocked), `L` its keys and `n = B·Hq·r·L`:
429/// vector one pass 0; vector two passes `B·Hq·rows·blocks·(Dv·s + 8)` for the largest
430/// dispatch (plus the gathered queries and outputs with several dispatches); tiled 0;
431/// composition `n·s` (the scores, masked and normalised in place) plus the larger of the
432/// scaled queries (`B·Hq·r·D·s`) and, with sinks below float32, the float32 softmax copy
433/// (`n·4`; three of them in blocks under 16 MiB), plus `r·L` bytes of causal mask; blocked,
434/// one block's composition plus the output's bytes (the blocks before concatenation).
435#[track_caller]
436pub fn scaled_dot_product_attention(
437    q: &Array,
438    k: &Array,
439    v: &Array,
440    scale: f32,
441    options: &AttentionOptions<'_>,
442) -> Array {
443    let mask_array = match options.mask {
444        AttentionMask::Array(m) => Some(m),
445        _ => None,
446    };
447    let ins = operands(&[q, k, v], &[mask_array, options.sinks]);
448    Array::sticky(
449        "scaled_dot_product_attention",
450        Location::caller(),
451        &ins,
452        || imp::scaled_dot_product_attention(q, k, v, scale, options),
453    )
454}
455
456/// The gated delta rule, Gated DeltaNet's recurrence (as mlx-lm's `gated_delta_update`
457/// once its gates are computed). For each step `t` and value head, with `S` its state
458/// (`[Dv, Dk]`):
459///
460/// `S ← g_t · S`, then `S ← S + β_t (v_t − S k_t) k_tᵀ`, and `y_t = S q_t`.
461///
462/// Shapes: `q` and `k` are `[B, T, Hk, Dk]`, `v` is `[B, T, Hv, Dv]` (value head `h` reads
463/// key head `h / (Hv / Hk)`), `g` and `beta` are `[B, T, Hv]` and `state` is
464/// `[B, Hv, Dv, Dk]`. Returns `y` (`[B, T, Hv, Dv]`, in `q`'s dtype) and the final state
465/// (in `state`'s dtype); the recurrence runs in float32. On the GPU it is one kernel
466/// (mlx-lm's, for `Dk` a multiple of 32), else the steps as ordinary operations, which also
467/// define the derivatives.
468///
469/// ```
470/// use nuvec_core::{DType, fast, ops::{ones, zeros}};
471///
472/// let q = ones([1, 2, 1, 32], DType::F32);
473/// let v = ones([1, 2, 1, 4], DType::F32);
474/// let (g, beta) = (ones([1, 2, 1], DType::F32), ones([1, 2, 1], DType::F32));
475/// let state = zeros([1, 1, 4, 32], DType::F32);
476/// let (y, s) = fast::gated_delta(&(&q * 0.25), &(&q * 0.125), &v, &g, &(&beta * 0.5), &state);
477/// // k · k = 0.5 and k · q = 1. Step 1: S = 0.5 · v kᵀ, so y = 0.5. Step 2: S k = 0.25,
478/// // so S gains (1 − 0.25) · 0.5 · v kᵀ, and y = 0.875.
479/// assert_eq!(y.to_vec::<f32>().unwrap(), [0.5, 0.5, 0.5, 0.5, 0.875, 0.875, 0.875, 0.875]);
480/// assert_eq!(s.shape(), [1, 1, 4, 32]);
481/// ```
482#[track_caller]
483pub fn gated_delta(
484    q: &Array,
485    k: &Array,
486    v: &Array,
487    g: &Array,
488    beta: &Array,
489    state: &Array,
490) -> (Array, Array) {
491    let [y, s] = Array::sticky_n(
492        "gated_delta",
493        Location::caller(),
494        &[q, k, v, g, beta, state],
495        || {
496            let (y, s) = imp::gated_delta(q, k, v, g, beta, state)?;
497            Ok([y, s])
498        },
499    );
500    (y, s)
501}
502
503/// [`gated_delta`] returning the state after every step, `[B, T, Hv, Dv, Dk]` (step `t`'s
504/// state at index `t`; the last is [`gated_delta`]'s final state), so that a caller can
505/// roll the recurrence back to any step, as speculative decoding does after a rejected
506/// draft. The outputs equal [`gated_delta`]'s bit for bit; writing every step's state
507/// costs `T` times the state's bytes.
508#[track_caller]
509pub fn gated_delta_steps(
510    q: &Array,
511    k: &Array,
512    v: &Array,
513    g: &Array,
514    beta: &Array,
515    state: &Array,
516) -> (Array, Array) {
517    let [y, s] = Array::sticky_n(
518        "gated_delta_steps",
519        Location::caller(),
520        &[q, k, v, g, beta, state],
521        || {
522            let (y, s) = imp::gated_delta_steps(q, k, v, g, beta, state)?;
523            Ok([y, s])
524        },
525    );
526    (y, s)
527}
528
529/// [`gated_delta`] for a batch of sequences whose states live in a pool: sequence `b`
530/// starts from `pool[slots[b]]` (`pool` is `[slots, Hv, Dv, Dk]`, `slots` `[B]` integers,
531/// distinct) and its final state replaces it. Returns the outputs and the updated pool,
532/// which is written in place when the evaluation owns it, so decoding many sequences
533/// moves no states. Each sequence's results equal [`gated_delta`]'s on its state alone.
534#[track_caller]
535#[allow(clippy::too_many_arguments)]
536pub fn gated_delta_slots(
537    q: &Array,
538    k: &Array,
539    v: &Array,
540    g: &Array,
541    beta: &Array,
542    pool: &Array,
543    slots: &Array,
544) -> (Array, Array) {
545    let [y, p] = Array::sticky_n(
546        "gated_delta_slots",
547        Location::caller(),
548        &[q, k, v, g, beta, pool, slots],
549        || {
550            let (y, p) = imp::gated_delta_slots(q, k, v, g, beta, pool, slots)?;
551            Ok([y, p])
552        },
553    );
554    (y, p)
555}