Skip to main content

ruxla_kernels/
array.rs

1//! Array operations on row-major buffers.
2//!
3//! Each function takes the elements of its operands as slices with their
4//! shapes, and returns the elements of the result. Shapes are assumed to
5//! have been checked (by shape inference); the functions panic on
6//! inconsistent inputs.
7
8use std::cmp::Ordering;
9
10use crate::buffer::Buffer;
11use crate::dtype::{DType, Element, Value, cast};
12use crate::ops::{BinaryOp, UnaryOp};
13
14/// Returns the row-major strides of `shape`.
15pub fn strides(shape: &[usize]) -> Vec<usize> {
16    let mut s = vec![1; shape.len()];
17    for i in (0..shape.len().saturating_sub(1)).rev() {
18        s[i] = s[i + 1] * shape[i + 1];
19    }
20    s
21}
22
23/// [`strides`] on the stack, for at most 8 dimensions.
24fn small_strides(shape: &[usize]) -> [usize; 8] {
25    let mut s = [1usize; 8];
26    for i in (0..shape.len().saturating_sub(1)).rev() {
27        s[i] = s[i + 1] * shape[i + 1];
28    }
29    s
30}
31
32/// Returns the number of elements of `shape`.
33pub fn size(shape: &[usize]) -> usize {
34    shape.iter().product()
35}
36
37/// Converts a flat index into a multi-index.
38pub fn unravel(mut flat: usize, shape: &[usize]) -> Vec<usize> {
39    let mut index = vec![0; shape.len()];
40    for (i, &d) in shape.iter().enumerate().rev() {
41        if d > 0 {
42            index[i] = flat % d;
43            flat /= d;
44        }
45    }
46    index
47}
48
49/// Converts a multi-index into a flat index, given strides.
50pub fn ravel(index: &[usize], strides: &[usize]) -> usize {
51    index.iter().zip(strides).map(|(i, s)| i * s).sum()
52}
53
54/// Applies `f` to the multi-index of each element of `shape`, in row-major
55/// order, and collects the results.
56fn map_indices<T>(shape: &[usize], mut f: impl FnMut(&[usize]) -> T) -> Vec<T> {
57    let n = size(shape);
58    let mut out = Vec::with_capacity(n);
59    let mut index = vec![0; shape.len()];
60    for _ in 0..n {
61        out.push(f(&index));
62        for d in (0..shape.len()).rev() {
63            index[d] += 1;
64            if index[d] < shape[d] {
65                break;
66            }
67            index[d] = 0;
68        }
69    }
70    out
71}
72
73/// `broadcast_in_dim`: dimension `i` of `x` becomes dimension `dims[i]` of
74/// the result, which has shape `out_shape`.
75pub fn broadcast_in_dim<T: Copy>(
76    x: &[T],
77    shape: &[usize],
78    out_shape: &[usize],
79    dims: &[usize],
80) -> Vec<T> {
81    let n = size(out_shape);
82    if n == 0 {
83        return Vec::new();
84    }
85    let st = strides(shape);
86    let mut src = vec![0usize; out_shape.len()];
87    for (i, &d) in dims.iter().enumerate() {
88        if shape[i] != 1 {
89            src[d] = st[i];
90        }
91    }
92    strided_gather(x, out_shape, &src)
93}
94
95/// [`broadcast_in_dim`] written to `out` (of `size(out_shape)` elements).
96pub fn broadcast_in_dim_into<T: Copy>(
97    x: &[T],
98    shape: &[usize],
99    out_shape: &[usize],
100    dims: &[usize],
101    out: &mut [T],
102) {
103    if out_shape.len() > 8 {
104        out.copy_from_slice(&broadcast_in_dim(x, shape, out_shape, dims));
105        return;
106    }
107    let st = small_strides(shape);
108    let mut src = [0usize; 8];
109    for (i, &d) in dims.iter().enumerate() {
110        if shape[i] != 1 {
111            src[d] = st[i];
112        }
113    }
114    strided_gather_into(x, out_shape, &src[..out_shape.len()], out);
115}
116
117/// The elements of `x` at `sum(index[d] * src_strides[d])` for every index
118/// of `out_shape`, in row-major order: the positions advance by adding
119/// strides, and the innermost dimension is filled, copied, or gathered.
120pub fn strided_gather<T: Copy>(x: &[T], out_shape: &[usize], src_strides: &[usize]) -> Vec<T> {
121    let n = size(out_shape);
122    if n == 0 {
123        return Vec::new();
124    }
125    let mut out = vec![x[0]; n];
126    strided_gather_into(x, out_shape, src_strides, &mut out);
127    out
128}
129
130/// [`strided_gather`] written to `out` (of `size(out_shape)` elements),
131/// without allocating for up to 8 dimensions.
132pub fn strided_gather_into<T: Copy>(
133    x: &[T],
134    out_shape: &[usize],
135    src_strides: &[usize],
136    out: &mut [T],
137) {
138    if out.is_empty() {
139        return;
140    }
141    // Dimensions of size 1 dropped, and each merged into the one before it
142    // where contiguous.
143    // (At most one per dimension: on the stack for up to 8.)
144    let mut stack = [(0usize, 0usize); 8];
145    let mut heap = Vec::new();
146    let mut nd = 0;
147    for (&d, &st) in out_shape.iter().zip(src_strides) {
148        if d == 1 {
149            continue;
150        }
151        let dims: &mut [(usize, usize)] = if out_shape.len() <= 8 {
152            &mut stack
153        } else {
154            if heap.is_empty() {
155                heap = vec![(0usize, 0usize); out_shape.len()];
156            }
157            &mut heap
158        };
159        if nd > 0 && dims[nd - 1].1 == d * st {
160            dims[nd - 1] = (dims[nd - 1].0 * d, st);
161        } else {
162            dims[nd] = (d, st);
163            nd += 1;
164        }
165    }
166    let dims: &[(usize, usize)] = if out_shape.len() <= 8 {
167        &stack[..nd]
168    } else {
169        &heap[..nd]
170    };
171    if dims.is_empty() {
172        out.fill(x[0]);
173        return;
174    }
175    // The two innermost dimensions in tight loops, the others by an
176    // odometer that adds strides.
177    let (inner, inner_st) = dims[dims.len() - 1];
178    let (mid, mid_st) = if dims.len() >= 2 {
179        dims[dims.len() - 2]
180    } else {
181        (1, 0)
182    };
183    let rest = &dims[..dims.len().saturating_sub(2)];
184    let block = inner * mid;
185    let mut index = [0usize; 8];
186    let mut index_heap = if rest.len() > 8 {
187        vec![0usize; rest.len()]
188    } else {
189        Vec::new()
190    };
191    let index: &mut [usize] = if rest.len() <= 8 {
192        &mut index[..rest.len()]
193    } else {
194        &mut index_heap
195    };
196    let mut base = 0usize;
197    for chunk in out.chunks_exact_mut(block) {
198        for (m, row) in chunk.chunks_exact_mut(inner).enumerate() {
199            let b = base + m * mid_st;
200            match inner_st {
201                0 => row.fill(x[b]),
202                1 => row.copy_from_slice(&x[b..b + inner]),
203                s => {
204                    for (j, o) in row.iter_mut().enumerate() {
205                        *o = x[b + j * s];
206                    }
207                }
208            }
209        }
210        for d in (0..rest.len()).rev() {
211            index[d] += 1;
212            base += rest[d].1;
213            if index[d] < rest[d].0 {
214                break;
215            }
216            base -= rest[d].1 * rest[d].0;
217            index[d] = 0;
218        }
219    }
220}
221
222/// `transpose`: dimension `i` of the result is dimension `perm[i]` of `x`.
223pub fn transpose<T: Copy>(x: &[T], shape: &[usize], perm: &[usize]) -> Vec<T> {
224    let st = strides(shape);
225    let out_shape: Vec<usize> = perm.iter().map(|&p| shape[p]).collect();
226    let src: Vec<usize> = perm.iter().map(|&p| st[p]).collect();
227    strided_gather(x, &out_shape, &src)
228}
229
230/// [`transpose`] written to `out` (of `size(shape)` elements), without
231/// allocating for up to 8 dimensions.
232pub fn transpose_into<T: Copy>(x: &[T], shape: &[usize], perm: &[usize], out: &mut [T]) {
233    if perm.len() > 8 {
234        out.copy_from_slice(&transpose(x, shape, perm));
235        return;
236    }
237    let st = small_strides(shape);
238    let (mut out_shape, mut src) = ([0usize; 8], [0usize; 8]);
239    for (i, &p) in perm.iter().enumerate() {
240        out_shape[i] = shape[p];
241        src[i] = st[p];
242    }
243    let r = perm.len();
244    strided_gather_into(x, &out_shape[..r], &src[..r], out);
245}
246
247/// `slice` with static bounds and strides.
248pub fn slice<T: Copy>(
249    x: &[T],
250    shape: &[usize],
251    start: &[usize],
252    limit: &[usize],
253    step: &[usize],
254) -> Vec<T> {
255    let st = strides(shape);
256    let out_shape: Vec<usize> = (0..shape.len())
257        .map(|i| (limit[i].saturating_sub(start[i])).div_ceil(step[i]))
258        .collect();
259    map_indices(&out_shape, |out| {
260        let flat: usize = (0..shape.len())
261            .map(|i| (start[i] + out[i] * step[i]) * st[i])
262            .sum();
263        x[flat]
264    })
265}
266
267/// Clamps start indices so that a window of `sizes` stays inside `shape`,
268/// as XLA does for `dynamic_slice` and `dynamic_update_slice`.
269pub fn clamp_starts(starts: &[i64], shape: &[usize], sizes: &[usize]) -> Vec<usize> {
270    starts
271        .iter()
272        .zip(shape.iter().zip(sizes))
273        .map(|(&s, (&n, &k))| s.clamp(0, (n - k) as i64) as usize)
274        .collect()
275}
276
277/// `dynamic_slice`: a window of `sizes` at (clamped) `starts`.
278pub fn dynamic_slice<T: Copy>(x: &[T], shape: &[usize], starts: &[i64], sizes: &[usize]) -> Vec<T> {
279    let start = clamp_starts(starts, shape, sizes);
280    let ones = vec![1; shape.len()];
281    let limit: Vec<usize> = start.iter().zip(sizes).map(|(s, k)| s + k).collect();
282    slice(x, shape, &start, &limit, &ones)
283}
284
285/// `dynamic_update_slice`: `x` with `update` written at (clamped) `starts`.
286pub fn dynamic_update_slice<T: Copy>(
287    x: &[T],
288    shape: &[usize],
289    update: &[T],
290    update_shape: &[usize],
291    starts: &[i64],
292) -> Vec<T> {
293    let start = clamp_starts(starts, shape, update_shape);
294    let st = strides(shape);
295    let mut out = x.to_vec();
296    let mut i = 0;
297    map_indices(update_shape, |u| {
298        let flat: usize = (0..shape.len()).map(|d| (start[d] + u[d]) * st[d]).sum();
299        out[flat] = update[i];
300        i += 1;
301    });
302    out
303}
304
305/// `concatenate` along `dim`.
306pub fn concatenate<T: Copy>(parts: &[(&[T], &[usize])], dim: usize) -> Vec<T> {
307    let shape0 = parts[0].1;
308    let outer: usize = shape0[..dim].iter().product();
309    let mut out = Vec::new();
310    for o in 0..outer {
311        for (x, shape) in parts {
312            let inner: usize = shape[dim..].iter().product();
313            out.extend_from_slice(&x[o * inner..(o + 1) * inner]);
314        }
315    }
316    out
317}
318
319/// `pad`: for each dimension, `(low, high, interior)` padding with `value`.
320/// Negative `low` or `high` removes elements.
321pub fn pad<T: Copy>(x: &[T], shape: &[usize], value: T, config: &[(i64, i64, usize)]) -> Vec<T> {
322    let out_shape: Vec<usize> = shape
323        .iter()
324        .zip(config)
325        .map(|(&n, &(lo, hi, int))| {
326            let inner = if n == 0 { 0 } else { n + (n - 1) * int } as i64;
327            (lo + hi + inner).max(0) as usize
328        })
329        .collect();
330    let st = strides(shape);
331    map_indices(&out_shape, |out| {
332        let mut flat = 0;
333        for d in 0..shape.len() {
334            let (lo, _, int) = config[d];
335            let pos = out[d] as i64 - lo;
336            let step = int as i64 + 1;
337            if pos < 0 || pos % step != 0 || pos / step >= shape[d] as i64 {
338                return value;
339            }
340            flat += (pos / step) as usize * st[d];
341        }
342        x[flat]
343    })
344}
345
346/// `rev`: reverses the elements along `dims`.
347pub fn rev<T: Copy>(x: &[T], shape: &[usize], dims: &[usize]) -> Vec<T> {
348    let n = size(shape);
349    if n == 0 {
350        return Vec::new();
351    }
352    // The trailing dimensions that are not reversed form contiguous blocks,
353    // copied whole; the dimensions before them are walked by an odometer
354    // (the last of them, reversed, in a loop).
355    let mut k = shape.len();
356    let mut block = 1;
357    while k > 0 && !dims.contains(&(k - 1)) {
358        k -= 1;
359        block *= shape[k];
360    }
361    if k == 0 {
362        return x.to_vec();
363    }
364    let outer = &shape[..k - 1];
365    let last = shape[k - 1];
366    // Strides in blocks.
367    let mut st = vec![0usize; k];
368    let mut s = 1;
369    for d in (0..k).rev() {
370        st[d] = s;
371        s *= shape[d];
372    }
373    let mut out = Vec::with_capacity(n);
374    let mut index = vec![0usize; outer.len()];
375    loop {
376        let base: usize = index
377            .iter()
378            .enumerate()
379            .map(|(d, &i)| {
380                let i = if dims.contains(&d) {
381                    shape[d] - 1 - i
382                } else {
383                    i
384                };
385                i * st[d]
386            })
387            .sum();
388        for j in (0..last).rev() {
389            let src = (base + j) * block;
390            out.extend_from_slice(&x[src..src + block]);
391        }
392        // The next index of the outer dimensions.
393        let mut d = outer.len();
394        loop {
395            if d == 0 {
396                return out;
397            }
398            d -= 1;
399            index[d] += 1;
400            if index[d] < outer[d] {
401                break;
402            }
403            index[d] = 0;
404        }
405    }
406}
407
408/// The order of `lax.sort` keys: integers and booleans in their natural
409/// order, and floats in the total order `-inf < ... < 0 < ... < inf < NaN`
410/// in which `-0.0` equals `0.0` and all NaNs are equal, as JAX's comparator
411/// makes it by canonicalizing zeros and NaNs before a total-order
412/// comparison.
413///
414/// Complex numbers order lexicographically by their real and imaginary
415/// parts, each in the order of floats, as JAX's comparator splits them into
416/// two keys.
417pub fn sort_order<T: Element>(a: T, b: T) -> Ordering {
418    if let (Value::Complex(ar, ai), Value::Complex(br, bi)) = (a.to_value(), b.to_value()) {
419        return sort_order(ar, br).then_with(|| sort_order(ai, bi));
420    }
421    // `x != x` holds only for NaN.
422    #[allow(clippy::eq_op)]
423    let (a_nan, b_nan) = (a != a, b != b);
424    match (a_nan, b_nan) {
425        (true, true) => Ordering::Equal,
426        (true, false) => Ordering::Greater,
427        (false, true) => Ordering::Less,
428        (false, false) => a.partial_cmp(&b).unwrap_or(Ordering::Equal),
429    }
430}
431
432/// The permutation that sorts along `dim` stably by `cmp`, which compares
433/// the flat indices of two elements: for each element of the result, the
434/// flat index of the element it comes from.
435pub fn sort_permutation(
436    shape: &[usize],
437    dim: usize,
438    cmp: impl Fn(usize, usize) -> Ordering,
439) -> Vec<usize> {
440    let n = shape[dim];
441    let inner: usize = shape[dim + 1..].iter().product();
442    let outer: usize = shape[..dim].iter().product();
443    let mut perm = vec![0; size(shape)];
444    let mut line: Vec<usize> = Vec::with_capacity(n);
445    for o in 0..outer {
446        for i in 0..inner {
447            let base = o * n * inner + i;
448            line.clear();
449            line.extend((0..n).map(|k| base + k * inner));
450            // `sort_by` is stable.
451            line.sort_by(|&a, &b| cmp(a, b));
452            for (k, &src) in line.iter().enumerate() {
453                perm[base + k * inner] = src;
454            }
455        }
456    }
457    perm
458}
459
460/// `sort`: sorts the operands (of the same shape) along `dim`, stably and
461/// lexicographically by the first `num_keys` of them in [`sort_order`].
462pub fn sort(operands: &[&Buffer], shape: &[usize], dim: usize, num_keys: usize) -> Vec<Buffer> {
463    type Cmp<'a> = Box<dyn Fn(usize, usize) -> Ordering + 'a>;
464    let keys: Vec<Cmp<'_>> = operands[..num_keys]
465        .iter()
466        .map(|b| crate::with_buffer!(b, |v| Box::new(|i, j| sort_order(v[i], v[j])) as Cmp<'_>))
467        .collect();
468    let perm = sort_permutation(shape, dim, |i, j| {
469        keys.iter()
470            .map(|cmp| cmp(i, j))
471            .find(|&o| o != Ordering::Equal)
472            .unwrap_or(Ordering::Equal)
473    });
474    operands
475        .iter()
476        .map(|b| {
477            crate::with_buffer!(b, |v| Buffer::from_vec(
478                perm.iter().map(|&p| v[p]).collect()
479            ))
480        })
481        .collect()
482}
483
484/// `iota`: the index along `dim` of each element of `shape`.
485pub fn iota<T: Element>(shape: &[usize], dim: usize) -> Vec<T> {
486    let mut out = vec![T::default(); size(shape)];
487    iota_into(shape, dim, &mut out);
488    out
489}
490
491/// [`iota`] written to `out` (of `size(shape)` elements), without
492/// allocating.
493pub fn iota_into<T: Element>(shape: &[usize], dim: usize, out: &mut [T]) {
494    // Runs of `inner` equal values, `n` values per block.
495    let n = shape[dim];
496    let inner: usize = shape[dim + 1..].iter().product();
497    if n == 0 || inner == 0 {
498        return;
499    }
500    for block in out.chunks_exact_mut(n * inner) {
501        for (k, run) in block.chunks_exact_mut(inner).enumerate() {
502            run.fill(cast::<u64, T>(k as u64));
503        }
504    }
505}
506
507/// A reduction.
508#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
509pub enum ReduceOp {
510    /// Sum (integers wrap around).
511    Sum,
512    /// Maximum, propagating NaN (logical or for booleans).
513    Max,
514    /// Minimum, propagating NaN (logical and for booleans).
515    Min,
516}
517
518impl ReduceOp {
519    /// The binary operation that combines elements.
520    pub fn binary(self) -> BinaryOp {
521        match self {
522            ReduceOp::Sum => BinaryOp::Add,
523            ReduceOp::Max => BinaryOp::Max,
524            ReduceOp::Min => BinaryOp::Min,
525        }
526    }
527
528    /// The identity.
529    pub fn identity<T: Element>(self) -> T {
530        match self {
531            ReduceOp::Sum => T::default(),
532            ReduceOp::Max => T::lowest(),
533            ReduceOp::Min => T::highest(),
534        }
535    }
536}
537
538/// Returns `shape` without `axes`.
539pub fn reduced_shape(shape: &[usize], axes: &[usize]) -> Vec<usize> {
540    shape
541        .iter()
542        .enumerate()
543        .filter(|(i, _)| !axes.contains(i))
544        .map(|(_, &d)| d)
545        .collect()
546}
547
548/// Reduces `x` over `axes`, combining elements in row-major order.
549pub fn reduce<T: Element>(x: &[T], shape: &[usize], axes: &[usize], op: ReduceOp) -> Vec<T> {
550    // Reduced axes that are contiguous (after sorting) make the operand
551    // `[pre, n, post]`, reduced over `n` in order.
552    let mut sorted = axes.to_vec();
553    sorted.sort_unstable();
554    if sorted.windows(2).all(|w| w[1] == w[0] + 1)
555        && sorted.last().is_some_and(|&a| a < shape.len())
556    {
557        let (a, b) = (sorted[0], sorted[sorted.len() - 1] + 1);
558        let pre = size(&shape[..a]);
559        let n = size(&shape[a..b]);
560        let post = size(&shape[b..]);
561        let mut out = vec![op.identity::<T>(); pre * post];
562        match op {
563            ReduceOp::Sum => reduce_middle(x, &mut out, [pre, n, post], |a, b| {
564                T::binary(BinaryOp::Add, a, b)
565            }),
566            ReduceOp::Max => reduce_middle(x, &mut out, [pre, n, post], |a, b| {
567                T::binary(BinaryOp::Max, a, b)
568            }),
569            ReduceOp::Min => reduce_middle(x, &mut out, [pre, n, post], |a, b| {
570                T::binary(BinaryOp::Min, a, b)
571            }),
572        }
573        return out;
574    }
575    let out_shape = reduced_shape(shape, axes);
576    let out_st = strides(&out_shape);
577    let mut out = vec![op.identity::<T>(); size(&out_shape)];
578    // The stride in the result of each operand dimension (0 if reduced).
579    let mut kept = out_st.iter();
580    let st: Vec<usize> = (0..shape.len())
581        .map(|d| {
582            if axes.contains(&d) {
583                0
584            } else {
585                *kept.next().expect("one stride per kept dimension")
586            }
587        })
588        .collect();
589    match op {
590        ReduceOp::Sum => reduce_strided(x, &mut out, shape, &st, |a, b| {
591            T::binary(BinaryOp::Add, a, b)
592        }),
593        ReduceOp::Max => reduce_strided(x, &mut out, shape, &st, |a, b| {
594            T::binary(BinaryOp::Max, a, b)
595        }),
596        ReduceOp::Min => reduce_strided(x, &mut out, shape, &st, |a, b| {
597            T::binary(BinaryOp::Min, a, b)
598        }),
599    }
600    out
601}
602
603/// `out[o] = f(out[o], x[i])` for every element `i` of `x` (of `shape`) in
604/// order, with `o` the dot product of its index and `st` (the strides in
605/// `out`, 0 for reduced dimensions): rows of the last dimension at a time,
606/// with the offset of each row updated as an odometer.
607#[inline(always)]
608fn reduce_strided<T: Element>(
609    x: &[T],
610    out: &mut [T],
611    shape: &[usize],
612    st: &[usize],
613    f: impl Fn(T, T) -> T,
614) {
615    let Some((&inner, outer_shape)) = shape.split_last() else {
616        if let (Some(o), Some(&v)) = (out.first_mut(), x.first()) {
617            *o = f(*o, v);
618        }
619        return;
620    };
621    if inner == 0 {
622        return;
623    }
624    let s_in = st[shape.len() - 1];
625    let mut index = vec![0usize; outer_shape.len()];
626    let mut base = 0usize;
627    for row in x.chunks_exact(inner) {
628        if s_in == 0 {
629            let mut acc = out[base];
630            for &v in row {
631                acc = f(acc, v);
632            }
633            out[base] = acc;
634        } else {
635            for (j, &v) in row.iter().enumerate() {
636                let o = base + j * s_in;
637                out[o] = f(out[o], v);
638            }
639        }
640        for d in (0..outer_shape.len()).rev() {
641            index[d] += 1;
642            base += st[d];
643            if index[d] < outer_shape[d] {
644                break;
645            }
646            base -= st[d] * outer_shape[d];
647            index[d] = 0;
648        }
649    }
650}
651
652/// `out[p, q] = f(...f(out[p, q], x[p, 0, q])..., x[p, n - 1, q])` for `x` of
653/// shape `[pre, n, post]`.
654#[inline(always)]
655fn reduce_middle<T: Element>(
656    x: &[T],
657    out: &mut [T],
658    [pre, n, post]: [usize; 3],
659    f: impl Fn(T, T) -> T,
660) {
661    if post == 1 {
662        // Rows of `n` contiguous elements.
663        for (o, row) in out.iter_mut().zip(x.chunks_exact(n.max(1))) {
664            for &v in row {
665                *o = f(*o, v);
666            }
667        }
668        return;
669    }
670    for p in 0..pre {
671        let o = &mut out[p * post..(p + 1) * post];
672        for k in 0..n {
673            let row = &x[(p * n + k) * post..(p * n + k + 1) * post];
674            for (o, &v) in o.iter_mut().zip(row) {
675                *o = f(*o, v);
676            }
677        }
678    }
679}
680
681/// `x` folded by `op` from `op`'s identity, element by element in order.
682/// Integers and booleans, whose operations are associative, are folded in
683/// eight lanes, which gives the same result.
684pub fn reduce_all<T: Element>(x: &[T], op: ReduceOp) -> T {
685    let id = op.identity::<T>();
686    let associative = !matches!(
687        T::DTYPE.kind(),
688        crate::DTypeKind::Float | crate::DTypeKind::Complex
689    );
690    match op {
691        ReduceOp::Sum => fold(x, id, associative, |a, b| T::binary(BinaryOp::Add, a, b)),
692        ReduceOp::Max => fold(x, id, associative, |a, b| T::binary(BinaryOp::Max, a, b)),
693        ReduceOp::Min => fold(x, id, associative, |a, b| T::binary(BinaryOp::Min, a, b)),
694    }
695}
696
697#[inline(always)]
698fn fold<T: Element>(x: &[T], id: T, associative: bool, f: impl Fn(T, T) -> T) -> T {
699    if associative && x.len() >= 16 {
700        let mut lanes = [id; 8];
701        let (chunks, rest) = x.as_chunks::<8>();
702        for c in chunks {
703            for (l, &v) in lanes.iter_mut().zip(c) {
704                *l = f(*l, v);
705            }
706        }
707        let acc = lanes.into_iter().fold(id, &f);
708        return rest.iter().fold(acc, |a, &v| f(a, v));
709    }
710    x.iter().fold(id, |a, &v| f(a, v))
711}
712
713/// The index of the largest (`max`) or smallest element along `axis`. NaN
714/// counts as the extreme, and ties take the first index, as in JAX.
715pub fn arg_min_max<T: Element>(x: &[T], shape: &[usize], axis: usize, max: bool) -> Vec<u64> {
716    let n = shape[axis];
717    let post: usize = shape[axis + 1..].iter().product();
718    let pre: usize = shape[..axis].iter().product();
719    let mut out = Vec::with_capacity(pre * post);
720    for p in 0..pre {
721        for q in 0..post {
722            let mut best = 0usize;
723            let mut best_v: Option<T> = None;
724            for k in 0..n {
725                let v = x[(p * n + k) * post + q];
726                let better = match best_v {
727                    None => true,
728                    Some(b) => {
729                        // `x != x` tests for NaN without a `Float` bound.
730                        #[allow(clippy::eq_op)]
731                        let (v_nan, b_nan) = (v != v, b != b);
732                        if b_nan {
733                            false
734                        } else if v_nan {
735                            true
736                        } else if max {
737                            v > b
738                        } else {
739                            v < b
740                        }
741                    }
742                };
743                if better {
744                    best = k;
745                    best_v = Some(v);
746                }
747            }
748            out.push(best as u64);
749        }
750    }
751    out
752}
753
754/// The operation of a cumulative reduction (`cumsum` and the like).
755#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
756pub enum CumulativeOp {
757    /// Sum (integers wrap around).
758    Sum,
759    /// Product (integers wrap around).
760    Prod,
761    /// Maximum, propagating NaN.
762    Max,
763    /// Minimum, propagating NaN.
764    Min,
765    /// `log(exp(a) + exp(b))`, computed as JAX's `logaddexp` (floats only).
766    LogSumExp,
767}
768
769impl CumulativeOp {
770    /// The identity: the initial value of XLA's `reduce_window`.
771    pub fn identity<T: Element>(self) -> T {
772        match self {
773            CumulativeOp::Sum => T::default(),
774            CumulativeOp::Prod => cast::<u64, T>(1),
775            CumulativeOp::Max | CumulativeOp::LogSumExp => T::lowest(),
776            CumulativeOp::Min => T::highest(),
777        }
778    }
779
780    /// Combines an accumulated value with the next element.
781    #[inline]
782    pub fn combine<T: Element>(self, a: T, b: T) -> T {
783        match self {
784            CumulativeOp::Sum => T::binary(BinaryOp::Add, a, b),
785            CumulativeOp::Prod => T::binary(BinaryOp::Mul, a, b),
786            CumulativeOp::Max => T::binary(BinaryOp::Max, a, b),
787            CumulativeOp::Min => T::binary(BinaryOp::Min, a, b),
788            CumulativeOp::LogSumExp => {
789                // JAX's `logaddexp`: `max(a, b) + log1p(exp(-|a - b|))`, or
790                // `a + b` where `a - b` is NaN (NaNs, or infinities of the
791                // same sign).
792                let delta = T::binary(BinaryOp::Sub, a, b);
793                #[allow(clippy::eq_op)] // `x != x` holds only for NaN
794                if delta != delta {
795                    T::binary(BinaryOp::Add, a, b)
796                } else {
797                    let amax = T::binary(BinaryOp::Max, a, b);
798                    let e = T::unary(UnaryOp::Neg, T::unary(UnaryOp::Abs, delta));
799                    let l = T::unary(UnaryOp::Log1p, T::unary(UnaryOp::Exp, e));
800                    T::binary(BinaryOp::Add, amax, l)
801                }
802            }
803        }
804    }
805}
806
807/// The length of the blocks of XLA's `ReduceWindowRewriter`, which rewrites
808/// a long cumulative `reduce_window` on CPU into scans of blocks.
809const SCAN_BLOCK: usize = 16;
810
811/// The window of XLA's `reduce_window` (on CPU) at each position, written to
812/// `out`: `init` combined with the elements of the window in order. The
813/// window of a forward scan ends at the position, and that of a reverse
814/// scan starts there; with `exclusive`, the position itself is left out.
815fn scan_windows_into<T: Element>(
816    x: &[T],
817    out: &mut [T],
818    reverse: bool,
819    exclusive: bool,
820    op: CumulativeOp,
821) {
822    let init = op.identity::<T>();
823    if !reverse {
824        // Each window extends the previous one, so a running value folds
825        // the elements in the same order.
826        let mut acc = init;
827        for (o, &v) in out.iter_mut().zip(x) {
828            let before = acc;
829            acc = op.combine(acc, v);
830            *o = if exclusive { before } else { acc };
831        }
832    } else {
833        for (i, o) in out.iter_mut().enumerate() {
834            let start = if exclusive { i + 1 } else { i };
835            *o = x[start..].iter().fold(init, |acc, &v| op.combine(acc, v));
836        }
837    }
838}
839
840/// An inclusive scan of one line, written to `out`, as XLA computes
841/// `reduce_window` with a window as long as the line on CPU (as JAX lowers
842/// cumulative reductions): lines up to [`SCAN_BLOCK`] long directly, and
843/// longer lines as XLA's `ReduceWindowRewriter` rewrites them. The line is
844/// padded with the identity to whole blocks, each block is scanned, the
845/// totals of the blocks are scanned exclusively (recursively), and each
846/// element is combined with the total before its block.
847fn scan_line_into<T: Element>(x: &[T], out: &mut [T], reverse: bool, op: CumulativeOp) {
848    let n = x.len();
849    if n <= SCAN_BLOCK {
850        scan_windows_into(x, out, reverse, false, op);
851        return;
852    }
853    let init = op.identity::<T>();
854    let blocks = n.div_ceil(SCAN_BLOCK);
855    let mut totals = vec![init; blocks];
856    let (mut block, mut scanned) = ([init; SCAN_BLOCK], [init; SCAN_BLOCK]);
857    for (b, total) in totals.iter_mut().enumerate() {
858        let (lo, hi) = (b * SCAN_BLOCK, ((b + 1) * SCAN_BLOCK).min(n));
859        block[..hi - lo].copy_from_slice(&x[lo..hi]);
860        block[hi - lo..].fill(init);
861        scan_windows_into(&block, &mut scanned, reverse, false, op);
862        out[lo..hi].copy_from_slice(&scanned[..hi - lo]);
863        *total = if reverse {
864            scanned[0]
865        } else {
866            scanned[SCAN_BLOCK - 1]
867        };
868    }
869    let mut outer = vec![init; blocks];
870    if blocks <= SCAN_BLOCK {
871        scan_windows_into(&totals, &mut outer, reverse, true, op);
872    } else {
873        // An exclusive scan is rewritten as an inclusive one, shifted.
874        let mut inclusive = vec![init; blocks];
875        scan_line_into(&totals, &mut inclusive, reverse, op);
876        if reverse {
877            outer[..blocks - 1].copy_from_slice(&inclusive[1..]);
878        } else {
879            outer[1..].copy_from_slice(&inclusive[..blocks - 1]);
880        }
881    }
882    for (i, o) in out.iter_mut().enumerate() {
883        *o = op.combine(*o, outer[i / SCAN_BLOCK]);
884    }
885}
886
887/// A cumulative reduction along `axis` (inclusive; from the end with
888/// `reverse`), combining elements in the order XLA does on CPU.
889pub fn cumulative<T: Element>(
890    x: &[T],
891    shape: &[usize],
892    axis: usize,
893    reverse: bool,
894    op: CumulativeOp,
895) -> Vec<T> {
896    let mut out = vec![T::default(); x.len()];
897    cumulative_into(x, shape, axis, reverse, op, &mut out);
898    out
899}
900
901/// [`cumulative`] written to `out` (of the size of `x`).
902pub fn cumulative_into<T: Element>(
903    x: &[T],
904    shape: &[usize],
905    axis: usize,
906    reverse: bool,
907    op: CumulativeOp,
908    out: &mut [T],
909) {
910    let n = shape[axis];
911    let inner: usize = shape[axis + 1..].iter().product();
912    let outer: usize = shape[..axis].iter().product();
913    if inner == 1 {
914        for o in 0..outer {
915            let base = o * n;
916            scan_line_into(&x[base..base + n], &mut out[base..base + n], reverse, op);
917        }
918        return;
919    }
920    let (mut line, mut scanned) = (vec![T::default(); n], vec![T::default(); n]);
921    for o in 0..outer {
922        for i in 0..inner {
923            let base = o * n * inner + i;
924            for (k, l) in line.iter_mut().enumerate() {
925                *l = x[base + k * inner];
926            }
927            scan_line_into(&line, &mut scanned, reverse, op);
928            for (k, &v) in scanned.iter().enumerate() {
929                out[base + k * inner] = v;
930            }
931        }
932    }
933}
934
935/// The key by which `top_k` orders elements, as XLA's comparator does: the
936/// total order of floats by their bits (`-NaN < -inf < ... < -0.0 < 0.0 <
937/// ... < inf < NaN`), and the natural order of integers and booleans.
938fn top_k_key<T: Element>(v: T) -> i128 {
939    let dtype = T::DTYPE;
940    if dtype.is_float() {
941        let bits = 8 * dtype.size_in_bytes() as u32;
942        // Sign-extend the bit pattern, then flip the magnitude of negative
943        // values so that they order in reverse.
944        let shift = 64 - bits;
945        let s = ((v.to_bits() << shift) as i64) >> shift;
946        let s = if s < 0 {
947            s ^ (u64::MAX >> (65 - bits)) as i64
948        } else {
949            s
950        };
951        i128::from(s)
952    } else {
953        match v.to_value() {
954            Value::Int(i) => i128::from(i),
955            Value::UInt(u) => i128::from(u),
956            _ => i128::from(v.to_bits()),
957        }
958    }
959}
960
961/// `top_k` along `axis`: the `k` largest elements of each line in
962/// descending order (ties in their original order), and their indices.
963pub fn top_k<T: Element>(x: &[T], shape: &[usize], k: usize, axis: usize) -> (Vec<T>, Vec<i32>) {
964    let rank = shape.len();
965    if axis + 1 == rank {
966        return top_k_last(x, shape, k);
967    }
968    // Move the axis last and back (the permutation is its own inverse).
969    let mut perm: Vec<usize> = (0..rank).collect();
970    perm.swap(axis, rank - 1);
971    let moved: Vec<usize> = perm.iter().map(|&d| shape[d]).collect();
972    let (values, indices) = top_k_last(&transpose(x, shape, &perm), &moved, k);
973    let mut out = moved;
974    out[rank - 1] = k;
975    (
976        transpose(&values, &out, &perm),
977        transpose(&indices, &out, &perm),
978    )
979}
980
981/// [`top_k`] along the last dimension.
982fn top_k_last<T: Element>(x: &[T], shape: &[usize], k: usize) -> (Vec<T>, Vec<i32>) {
983    let n = *shape.last().expect("top_k needs at least one dimension");
984    let lines = size(&shape[..shape.len() - 1]);
985    let mut values = Vec::with_capacity(lines * k);
986    let mut indices = Vec::with_capacity(lines * k);
987    let mut order: Vec<usize> = Vec::with_capacity(n);
988    for l in 0..lines {
989        let line = &x[l * n..(l + 1) * n];
990        order.clear();
991        order.extend(0..n);
992        // `sort_by` is stable.
993        order.sort_by(|&a, &b| top_k_key(line[b]).cmp(&top_k_key(line[a])));
994        for &i in &order[..k] {
995            values.push(line[i]);
996            indices.push(i as i32);
997        }
998    }
999    (values, indices)
1000}
1001
1002/// The dimensions that `dot_general` contracts and batches over. The result
1003/// has the batch dimensions, then the free dimensions of the left operand,
1004/// then those of the right operand.
1005#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
1006pub struct DotDims {
1007    /// Contracting dimensions of the left operand.
1008    pub lhs_contracting: Vec<usize>,
1009    /// Contracting dimensions of the right operand.
1010    pub rhs_contracting: Vec<usize>,
1011    /// Batch dimensions of the left operand.
1012    pub lhs_batch: Vec<usize>,
1013    /// Batch dimensions of the right operand.
1014    pub rhs_batch: Vec<usize>,
1015}
1016
1017/// The dimensions of an operand that are neither contracted nor batched.
1018pub fn free_dims(rank: usize, contracting: &[usize], batch: &[usize]) -> Vec<usize> {
1019    (0..rank)
1020        .filter(|d| !contracting.contains(d) && !batch.contains(d))
1021        .collect()
1022}
1023
1024/// The shape of the result of `dot_general`.
1025pub fn dot_shape(lhs: &[usize], rhs: &[usize], d: &DotDims) -> Vec<usize> {
1026    let mut out: Vec<usize> = d.lhs_batch.iter().map(|&i| lhs[i]).collect();
1027    out.extend(
1028        free_dims(lhs.len(), &d.lhs_contracting, &d.lhs_batch)
1029            .iter()
1030            .map(|&i| lhs[i]),
1031    );
1032    out.extend(
1033        free_dims(rhs.len(), &d.rhs_contracting, &d.rhs_batch)
1034            .iter()
1035            .map(|&i| rhs[i]),
1036    );
1037    out
1038}
1039
1040/// `dot_general`: sums of products over the contracting dimensions, in the
1041/// operands' type.
1042pub fn dot_general<T: Element>(
1043    lhs: &[T],
1044    lshape: &[usize],
1045    rhs: &[T],
1046    rshape: &[usize],
1047    d: &DotDims,
1048) -> Vec<T> {
1049    // Like XLA on CPU, 16-bit floats are multiplied and accumulated in `f32`
1050    // and rounded once.
1051    if matches!(T::DTYPE, DType::F16 | DType::BF16) {
1052        let wide = |x: &[T]| {
1053            x.iter()
1054                .map(|&v| crate::cast::<T, f32>(v))
1055                .collect::<Vec<f32>>()
1056        };
1057        return dot_general(&wide(lhs), lshape, &wide(rhs), rshape, d)
1058            .into_iter()
1059            .map(crate::cast::<f32, T>)
1060            .collect();
1061    }
1062    // Every product is computed as a batch of matrix products `[M, K] x
1063    // [K, N]`: the operands are permuted (copied only if needed) to `[batch,
1064    // free, contracting]` and `[batch, contracting, free]`, the contracting
1065    // dimensions in the order of `d` (row-major), which is the order of the
1066    // sums, so every element is summed in the same order whatever the
1067    // layout.
1068    let lfree = free_dims(lshape.len(), &d.lhs_contracting, &d.lhs_batch);
1069    let rfree = free_dims(rshape.len(), &d.rhs_contracting, &d.rhs_batch);
1070    let lperm: Vec<usize> = d
1071        .lhs_batch
1072        .iter()
1073        .chain(&lfree)
1074        .chain(&d.lhs_contracting)
1075        .copied()
1076        .collect();
1077    let rperm: Vec<usize> = d
1078        .rhs_batch
1079        .iter()
1080        .chain(&d.rhs_contracting)
1081        .chain(&rfree)
1082        .copied()
1083        .collect();
1084    let lt = permuted(lhs, lshape, &lperm);
1085    let rt = permuted(rhs, rshape, &rperm);
1086    let batch: usize = d.lhs_batch.iter().map(|&i| lshape[i]).product();
1087    let m: usize = lfree.iter().map(|&i| lshape[i]).product();
1088    let kk: usize = d.lhs_contracting.iter().map(|&i| lshape[i]).product();
1089    let n: usize = rfree.iter().map(|&i| rshape[i]).product();
1090    let mut out = vec![T::default(); batch * m * n];
1091    if m * n == 0 || kk == 0 {
1092        return out;
1093    }
1094    for ((o, l), r) in out
1095        .chunks_exact_mut(m * n)
1096        .zip(lt.chunks_exact(m * kk))
1097        .zip(rt.chunks_exact(kk * n))
1098    {
1099        matmul_rows(o, l, r, kk, n);
1100    }
1101    out
1102}
1103
1104/// `x` transposed by `perm`, borrowed if `perm` is the identity.
1105fn permuted<'a, T: Copy>(x: &'a [T], shape: &[usize], perm: &[usize]) -> std::borrow::Cow<'a, [T]> {
1106    if perm.iter().enumerate().all(|(i, &p)| i == p) {
1107        std::borrow::Cow::Borrowed(x)
1108    } else {
1109        std::borrow::Cow::Owned(transpose(x, shape, perm))
1110    }
1111}
1112
1113/// `out += l r` for row-major `l` (`m x kk`) and `r` (`kk x n`), where `out`
1114/// starts at zero: each row of the result is accumulated over `k` in order,
1115/// a whole row at a time, so that the loop over the columns vectorizes.
1116fn matmul_rows<T: Element>(out: &mut [T], l: &[T], r: &[T], kk: usize, n: usize) {
1117    let fma = |o: T, a: T, b: T| T::binary(BinaryOp::Add, o, T::binary(BinaryOp::Mul, a, b));
1118    let m = out.len() / n;
1119    let full_cols = n - n % TILE_COLS;
1120    let mut i = 0;
1121    // Tiles of 4 x `TILE_COLS` elements of the result stay in registers for
1122    // the whole loop over `k`; each element is summed over `k` in order.
1123    while i + 4 <= m {
1124        let mut j = 0;
1125        while j < full_cols {
1126            let mut acc = [[T::default(); TILE_COLS]; 4];
1127            for k in 0..kk {
1128                let rrow: &[T; TILE_COLS] = r[k * n + j..k * n + j + TILE_COLS]
1129                    .try_into()
1130                    .expect("tile");
1131                for (t, accrow) in acc.iter_mut().enumerate() {
1132                    let a = l[(i + t) * kk + k];
1133                    for (x, &b) in accrow.iter_mut().zip(rrow) {
1134                        *x = fma(*x, a, b);
1135                    }
1136                }
1137            }
1138            for (t, accrow) in acc.iter().enumerate() {
1139                out[(i + t) * n + j..(i + t) * n + j + TILE_COLS].copy_from_slice(accrow);
1140            }
1141            j += TILE_COLS;
1142        }
1143        i += 4;
1144    }
1145    // The remaining rows and columns, a row at a time.
1146    for row in 0..m {
1147        let cols = if row < i { full_cols..n } else { 0..n };
1148        if cols.is_empty() {
1149            continue;
1150        }
1151        let lrow = &l[row * kk..(row + 1) * kk];
1152        let orow = &mut out[row * n + cols.start..row * n + cols.end];
1153        for (k, &a) in lrow.iter().enumerate() {
1154            let rrow = &r[k * n + cols.start..k * n + cols.end];
1155            for (o, &b) in orow.iter_mut().zip(rrow) {
1156                *o = fma(*o, a, b);
1157            }
1158        }
1159    }
1160}
1161
1162/// The columns of a tile of [`matmul_rows`].
1163const TILE_COLS: usize = 16;
1164
1165/// `select_n`: element `i` comes from `cases[which[i]]` (`which` is a scalar
1166/// or has the shape of the cases). Out-of-range indices are clamped.
1167pub fn select_n<T: Copy>(which: &[usize], cases: &[&[T]]) -> Vec<T> {
1168    let n = cases[0].len();
1169    (0..n)
1170        .map(|i| {
1171            let w = if which.len() == 1 { which[0] } else { which[i] };
1172            cases[w.min(cases.len() - 1)][i]
1173        })
1174        .collect()
1175}
1176
1177/// `clamp(lo, x, hi)`, propagating NaN; `lo` and `hi` are scalars or have
1178/// the shape of `x`.
1179pub fn clamp<T: Element>(lo: &[T], x: &[T], hi: &[T]) -> Vec<T> {
1180    let at = |a: &[T], i: usize| if a.len() == 1 { a[0] } else { a[i] };
1181    (0..x.len())
1182        .map(|i| {
1183            let v = T::binary(BinaryOp::Max, x[i], at(lo, i));
1184            T::binary(BinaryOp::Min, v, at(hi, i))
1185        })
1186        .collect()
1187}
1188
1189/// How `gather` and `scatter` treat out-of-bounds indices.
1190#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
1191pub enum GatherScatterMode {
1192    /// Indices are clamped so that the slice or window is in bounds.
1193    #[default]
1194    Clip,
1195    /// Out-of-bounds updates are dropped (scatter only).
1196    FillOrDrop,
1197    /// The caller promises that indices are in bounds; XLA's native behavior
1198    /// (clamping for gather, dropping for scatter) applies otherwise.
1199    PromiseInBounds,
1200}
1201
1202/// StableHLO's gather dimension numbers; the index vector is the last
1203/// dimension of the indices, as in JAX.
1204#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
1205pub struct GatherDims {
1206    /// The dimensions of the result that index into a slice.
1207    pub offset_dims: Vec<usize>,
1208    /// Operand dimensions whose slices have size 1 and are dropped.
1209    pub collapsed_slice_dims: Vec<usize>,
1210    /// The operand dimension that each index vector component starts.
1211    pub start_index_map: Vec<usize>,
1212    /// Operand batching dimensions, matched with `start_indices_batching_dims`.
1213    pub operand_batching_dims: Vec<usize>,
1214    /// Batching dimensions of the indices.
1215    pub start_indices_batching_dims: Vec<usize>,
1216}
1217
1218/// StableHLO's scatter dimension numbers; the index vector is the last
1219/// dimension of the indices, as in JAX.
1220#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
1221pub struct ScatterDims {
1222    /// The dimensions of the updates that index into a window.
1223    pub update_window_dims: Vec<usize>,
1224    /// Operand dimensions whose windows have size 1 and are not in the updates.
1225    pub inserted_window_dims: Vec<usize>,
1226    /// The operand dimension that each index vector component starts.
1227    pub scatter_dims_to_operand_dims: Vec<usize>,
1228    /// Operand batching dimensions, matched with `scatter_indices_batching_dims`.
1229    pub operand_batching_dims: Vec<usize>,
1230    /// Batching dimensions of the indices.
1231    pub scatter_indices_batching_dims: Vec<usize>,
1232}
1233
1234/// The shape of the result of a gather.
1235pub fn gather_shape(indices: &[usize], d: &GatherDims, slice_sizes: &[usize]) -> Vec<usize> {
1236    let q = indices.len();
1237    let out_rank = d.offset_dims.len() + q - 1;
1238    let mut offsets = (0..slice_sizes.len())
1239        .filter(|i| !d.collapsed_slice_dims.contains(i) && !d.operand_batching_dims.contains(i))
1240        .map(|i| slice_sizes[i]);
1241    let mut batch = indices[..q - 1].iter().copied();
1242    (0..out_rank)
1243        .map(|i| {
1244            if d.offset_dims.contains(&i) {
1245                offsets.next().expect("offset dimension")
1246            } else {
1247                batch.next().expect("batch dimension")
1248            }
1249        })
1250        .collect()
1251}
1252
1253/// `gather`, with start indices clamped so that slices are in bounds (the
1254/// semantics of every mode that gather supports).
1255pub fn gather<T: Copy>(
1256    x: &[T],
1257    shape: &[usize],
1258    indices: &[i64],
1259    indices_shape: &[usize],
1260    d: &GatherDims,
1261    slice_sizes: &[usize],
1262) -> Vec<T> {
1263    let out_shape = gather_shape(indices_shape, d, slice_sizes);
1264    let st = strides(shape);
1265    let out_st = strides(&out_shape);
1266    let q = indices_shape.len();
1267    let vec_len = indices_shape[q - 1];
1268    let batch_dims: Vec<usize> = (0..out_shape.len())
1269        .filter(|i| !d.offset_dims.contains(i))
1270        .collect();
1271    let offset_operand: Vec<usize> = (0..shape.len())
1272        .filter(|i| !d.collapsed_slice_dims.contains(i) && !d.operand_batching_dims.contains(i))
1273        .collect();
1274    // The positions of the slice elements in the operand and in the result,
1275    // relative to the start of the slice and of its place in the result.
1276    let slice_shape: Vec<usize> = offset_operand.iter().map(|&od| slice_sizes[od]).collect();
1277    let mut slice_x = Vec::with_capacity(slice_shape.iter().product());
1278    let mut slice_out = Vec::with_capacity(slice_x.capacity());
1279    for_each_index(&slice_shape, |o| {
1280        let mut ox = 0;
1281        let mut oo = 0;
1282        for (k, &v) in o.iter().enumerate() {
1283            ox += v * st[offset_operand[k]];
1284            oo += v * out_st[d.offset_dims[k]];
1285        }
1286        slice_x.push(ox);
1287        slice_out.push(oo);
1288    });
1289    let batch_shape = &indices_shape[..q - 1];
1290    let size: usize = out_shape.iter().product();
1291    if size == 0 {
1292        return Vec::new();
1293    }
1294    // Every position of the result is written below.
1295    let mut out = vec![x[0]; size];
1296    let mut b = 0;
1297    for_each_index(batch_shape, |batch| {
1298        let start = &indices[b * vec_len..(b + 1) * vec_len];
1299        let mut base = 0;
1300        for (&i, &od) in start.iter().zip(&d.start_index_map) {
1301            let hi = (shape[od] - slice_sizes[od]) as i64;
1302            base += i.clamp(0, hi) as usize * st[od];
1303        }
1304        for (&ob, &ib) in d
1305            .operand_batching_dims
1306            .iter()
1307            .zip(&d.start_indices_batching_dims)
1308        {
1309            base += batch[ib] * st[ob];
1310        }
1311        let out_base: usize = batch
1312            .iter()
1313            .zip(&batch_dims)
1314            .map(|(&v, &od)| v * out_st[od])
1315            .sum();
1316        for (&sx, &so) in slice_x.iter().zip(&slice_out) {
1317            out[out_base + so] = x[base + sx];
1318        }
1319        b += 1;
1320    });
1321    out
1322}
1323
1324/// Calls `f` with every index of `shape` in row-major order (once with an
1325/// empty index for a scalar shape).
1326fn for_each_index(shape: &[usize], mut f: impl FnMut(&[usize])) {
1327    if shape.contains(&0) {
1328        return;
1329    }
1330    let mut index = vec![0usize; shape.len()];
1331    loop {
1332        f(&index);
1333        let mut k = shape.len();
1334        loop {
1335            if k == 0 {
1336                return;
1337            }
1338            k -= 1;
1339            index[k] += 1;
1340            if index[k] < shape[k] {
1341                break;
1342            }
1343            index[k] = 0;
1344        }
1345    }
1346}
1347
1348/// The size of the window of a scatter in each operand dimension.
1349pub fn scatter_window(rank: usize, updates_shape: &[usize], d: &ScatterDims) -> Vec<usize> {
1350    let mut window = d.update_window_dims.iter();
1351    (0..rank)
1352        .map(|i| {
1353            if d.inserted_window_dims.contains(&i) || d.operand_batching_dims.contains(&i) {
1354                1
1355            } else {
1356                updates_shape[*window.next().expect("window dimension")]
1357            }
1358        })
1359        .collect()
1360}
1361
1362/// `scatter`: combines `updates` into `x` with `combine(old, update)` (or
1363/// replaces when `combine` is `None`), in row-major order of the updates.
1364/// With `Clip`, start indices are clamped; otherwise windows that are not
1365/// entirely in bounds are skipped, as XLA does.
1366#[allow(clippy::too_many_arguments)]
1367pub fn scatter<T: Copy>(
1368    x: &[T],
1369    shape: &[usize],
1370    indices: &[i64],
1371    indices_shape: &[usize],
1372    updates: &[T],
1373    updates_shape: &[usize],
1374    d: &ScatterDims,
1375    mode: GatherScatterMode,
1376    combine: Option<&dyn Fn(T, T) -> T>,
1377) -> Vec<T> {
1378    let window = scatter_window(shape.len(), updates_shape, d);
1379    let st = strides(shape);
1380    let ist = strides(indices_shape);
1381    let ust = strides(updates_shape);
1382    let q = indices_shape.len();
1383    let scatter_dims: Vec<usize> = (0..updates_shape.len())
1384        .filter(|i| !d.update_window_dims.contains(i))
1385        .collect();
1386    let window_operand: Vec<usize> = (0..shape.len())
1387        .filter(|i| !d.inserted_window_dims.contains(i) && !d.operand_batching_dims.contains(i))
1388        .collect();
1389    let mut out = x.to_vec();
1390    let ru = updates_shape.len();
1391    let nw = d.update_window_dims.len();
1392    if d.operand_batching_dims.is_empty()
1393        && d.update_window_dims.iter().copied().eq(ru - nw..ru)
1394        && q >= 1
1395    {
1396        // The window dimensions trail the updates: each index vector's
1397        // window is a block of the updates. The operand position of each
1398        // window element is computed once, then each block is combined at
1399        // its start, in the order of the updates (as below).
1400        let window_size: usize = updates_shape[ru - nw..].iter().product();
1401        let mut offsets = vec![0usize; window_size];
1402        for (w, o) in offsets.iter_mut().enumerate() {
1403            let mut rem = w;
1404            for (k, &od) in window_operand.iter().enumerate().rev() {
1405                let n = updates_shape[ru - nw + k];
1406                *o += (rem % n) * st[od];
1407                rem /= n;
1408            }
1409        }
1410        let vector = indices_shape[q - 1];
1411        let blocks = updates.len().checked_div(window_size).unwrap_or(0);
1412        'blocks: for b in 0..blocks {
1413            let mut base = 0;
1414            for (k, &od) in d.scatter_dims_to_operand_dims.iter().enumerate() {
1415                let hi = (shape[od] - window[od]) as i64;
1416                let start = indices[b * vector + k];
1417                let start = if mode == GatherScatterMode::Clip {
1418                    start.clamp(0, hi)
1419                } else if (0..=hi).contains(&start) {
1420                    start
1421                } else {
1422                    continue 'blocks;
1423                };
1424                base += start as usize * st[od];
1425            }
1426            let ub = &updates[b * window_size..(b + 1) * window_size];
1427            match combine {
1428                Some(f) => {
1429                    for (&o, &u) in offsets.iter().zip(ub) {
1430                        out[base + o] = f(out[base + o], u);
1431                    }
1432                }
1433                None => {
1434                    for (&o, &u) in offsets.iter().zip(ub) {
1435                        out[base + o] = u;
1436                    }
1437                }
1438            }
1439        }
1440        return out;
1441    }
1442    // Scratch buffers, reused for every update element.
1443    let mut up = vec![0usize; updates_shape.len()];
1444    let mut full = vec![0i64; shape.len()];
1445    for (flat, &u) in updates.iter().enumerate() {
1446        for (k, (&s, &n)) in ust.iter().zip(updates_shape).enumerate() {
1447            up[k] = (flat / s) % n;
1448        }
1449        // The flat position of the index vector of this update (the index
1450        // vector dimension is the last of the indices).
1451        let at0: usize = scatter_dims
1452            .iter()
1453            .zip(&ist[..q - 1])
1454            .map(|(&sd, &s)| up[sd] * s)
1455            .sum();
1456        full.iter_mut().for_each(|f| *f = 0);
1457        let mut dropped = false;
1458        for (k, &od) in d.scatter_dims_to_operand_dims.iter().enumerate() {
1459            let hi = (shape[od] - window[od]) as i64;
1460            let start = indices[at0 + k * ist[q - 1]];
1461            if mode == GatherScatterMode::Clip {
1462                full[od] = start.clamp(0, hi);
1463            } else if (0..=hi).contains(&start) {
1464                full[od] = start;
1465            } else {
1466                dropped = true;
1467                break;
1468            }
1469        }
1470        if dropped {
1471            continue;
1472        }
1473        for (&ob, &ib) in d
1474            .operand_batching_dims
1475            .iter()
1476            .zip(&d.scatter_indices_batching_dims)
1477        {
1478            full[ob] += up[scatter_dims[ib]] as i64;
1479        }
1480        for (&od, &ud) in window_operand.iter().zip(&d.update_window_dims) {
1481            full[od] += up[ud] as i64;
1482        }
1483        let o: usize = full.iter().zip(&st).map(|(&v, &s)| v as usize * s).sum();
1484        out[o] = match combine {
1485            Some(f) => f(out[o], u),
1486            None => u,
1487        };
1488    }
1489    out
1490}
1491
1492#[cfg(test)]
1493mod tests {
1494    use super::*;
1495
1496    /// Reductions over axes that are not adjacent agree with a sum over the
1497    /// indices, element by element in order.
1498    #[test]
1499    fn reduce_over_axes_apart() {
1500        let shape = [2, 3, 2, 3, 2];
1501        let x: Vec<f32> = (0..72).map(|i| (i as f32 * 0.37).sin()).collect();
1502        for axes in [vec![1, 3], vec![0, 2, 4], vec![0, 4], vec![1, 3, 4]] {
1503            let out_shape = reduced_shape(&shape, &axes);
1504            let mut expected = vec![0.0f32; size(&out_shape)];
1505            let mut index = [0usize; 5];
1506            for &v in &x {
1507                let mut o = 0;
1508                for d in 0..5 {
1509                    if !axes.contains(&d) {
1510                        o = o * shape[d] + index[d];
1511                    }
1512                }
1513                expected[o] += v;
1514                for d in (0..5).rev() {
1515                    index[d] += 1;
1516                    if index[d] < shape[d] {
1517                        break;
1518                    }
1519                    index[d] = 0;
1520                }
1521            }
1522            let got = reduce(&x, &shape, &axes, ReduceOp::Sum);
1523            let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::<Vec<_>>();
1524            assert_eq!(bits(&got), bits(&expected), "axes {axes:?}");
1525            let max = reduce(&x, &shape, &axes, ReduceOp::Max);
1526            assert_eq!(max.len(), expected.len());
1527        }
1528    }
1529
1530    #[test]
1531    fn shape_operations() {
1532        let x: Vec<i32> = (0..6).collect();
1533        assert_eq!(transpose(&x, &[2, 3], &[1, 0]), [0, 3, 1, 4, 2, 5]);
1534        assert_eq!(broadcast_in_dim(&[1, 2], &[2], &[2, 2], &[0]), [1, 1, 2, 2]);
1535        assert_eq!(slice(&x, &[2, 3], &[0, 1], &[2, 3], &[1, 2]), [1, 4]);
1536        assert_eq!(dynamic_slice(&x, &[2, 3], &[5, -1], &[1, 2]), [3, 4]);
1537        assert_eq!(
1538            dynamic_update_slice(&x, &[2, 3], &[9], &[1, 1], &[1, 9]),
1539            [0, 1, 2, 3, 4, 9]
1540        );
1541        assert_eq!(concatenate(&[(&[1, 2], &[2]), (&[3], &[1])], 0), [1, 2, 3]);
1542        assert_eq!(pad(&[1, 2], &[2], 0, &[(1, -1, 1)]), [0, 1, 0]);
1543        assert_eq!(rev(&x, &[2, 3], &[1]), [2, 1, 0, 5, 4, 3]);
1544        assert_eq!(iota::<f32>(&[2, 2], 1), [0.0, 1.0, 0.0, 1.0]);
1545    }
1546
1547    #[test]
1548    fn cumulative_reductions() {
1549        let x = [1, 2, 3, 4, 5, 6];
1550        let c = |axis, reverse, op| cumulative(&x, &[2, 3], axis, reverse, op);
1551        assert_eq!(c(1, false, CumulativeOp::Sum), [1, 3, 6, 4, 9, 15]);
1552        assert_eq!(c(1, true, CumulativeOp::Sum), [6, 5, 3, 15, 11, 6]);
1553        assert_eq!(c(0, false, CumulativeOp::Prod), [1, 2, 3, 4, 10, 18]);
1554        assert_eq!(c(0, true, CumulativeOp::Min), [1, 2, 3, 4, 5, 6]);
1555        // Lines longer than a block (and than 16 blocks) give the running
1556        // values, which are exact for integers.
1557        for n in [17, 40, 300] {
1558            let x: Vec<i32> = (0..n).map(|i| (i * 7) % 11 - 5).collect();
1559            let fwd = cumulative(&x, &[n as usize], 0, false, CumulativeOp::Sum);
1560            let rev = cumulative(&x, &[n as usize], 0, true, CumulativeOp::Sum);
1561            let mut acc = 0;
1562            for i in 0..x.len() {
1563                acc += x[i];
1564                assert_eq!(fwd[i], acc);
1565                assert_eq!(rev[i], x[i..].iter().sum::<i32>());
1566            }
1567        }
1568        let x = [1.0f32, f32::NAN, 0.5];
1569        let m = cumulative(&x, &[3], 0, false, CumulativeOp::Max);
1570        assert!(m[0] == 1.0 && m[1].is_nan() && m[2].is_nan());
1571        let l = cumulative(&[0.0f64, 0.0], &[2], 0, false, CumulativeOp::LogSumExp);
1572        assert_eq!(l, [0.0, 2f64.ln()]);
1573    }
1574
1575    #[test]
1576    fn top_k_orders_by_bits() {
1577        let nan = f32::NAN;
1578        let x = [1.0, -nan, -0.0, 0.0, nan, f32::NEG_INFINITY, 1.0];
1579        let (v, i) = top_k(&x, &[7], 7, 0);
1580        assert_eq!(i, [4, 0, 6, 3, 2, 5, 1]);
1581        assert!(v[0].is_nan() && v[6].is_nan());
1582        assert_eq!(v[3].to_bits(), 0.0f32.to_bits());
1583        assert_eq!(v[4].to_bits(), (-0.0f32).to_bits());
1584        // Along the first axis of [3, 2].
1585        let (v, i) = top_k(&[1, 5, 3, 2, 3, 9], &[3, 2], 2, 0);
1586        assert_eq!(v, [3, 9, 3, 5]);
1587        assert_eq!(i, [1, 2, 2, 0]);
1588    }
1589
1590    #[test]
1591    fn sorting() {
1592        let nan = f32::NAN;
1593        let x = [1.0f32, -nan, 0.0, -0.0, f32::NEG_INFINITY, nan, -1.0];
1594        let v: Vec<i32> = (0..7).collect();
1595        let out = sort(
1596            &[&Buffer::from_vec(x.to_vec()), &Buffer::from_vec(v)],
1597            &[7],
1598            0,
1599            1,
1600        );
1601        // Zeros keep their order (they are equal), as do NaNs.
1602        assert_eq!(out[1].as_slice::<i32>().unwrap(), [4, 6, 2, 3, 0, 1, 5]);
1603        // Lexicographic over two keys, along the last dimension.
1604        let k1 = Buffer::from_vec(vec![1u8, 0, 1, 0, 2, 2]);
1605        let k2 = Buffer::from_vec(vec![true, true, false, false, true, false]);
1606        let out = sort(&[&k1, &k2], &[2, 3], 1, 2);
1607        assert_eq!(out[0].as_slice::<u8>().unwrap(), [0, 1, 1, 0, 2, 2]);
1608        assert_eq!(
1609            out[1].as_slice::<bool>().unwrap(),
1610            [true, false, true, false, false, true]
1611        );
1612        // Along the first dimension.
1613        let out = sort(&[&k1], &[2, 3], 0, 1);
1614        assert_eq!(out[0].as_slice::<u8>().unwrap(), [0, 0, 1, 1, 2, 2]);
1615    }
1616
1617    #[test]
1618    fn reductions() {
1619        let x = [1.0f32, 5.0, 3.0, 7.0, 2.0, 7.0];
1620        assert_eq!(reduce(&x, &[2, 3], &[1], ReduceOp::Sum), [9.0, 16.0]);
1621        assert_eq!(reduce(&x, &[2, 3], &[0, 1], ReduceOp::Max), [7.0]);
1622        assert_eq!(arg_min_max(&x, &[2, 3], 1, true), [1, 0]);
1623        assert_eq!(arg_min_max(&[1.0f32, f32::NAN, 3.0], &[3], 0, true), [1]);
1624        assert_eq!(reduce::<bool>(&[], &[0], &[0], ReduceOp::Max), [false]);
1625    }
1626
1627    #[test]
1628    fn dot() {
1629        let a = [1, 2, 3, 4];
1630        let b = [5, 6, 7, 8];
1631        let d = DotDims {
1632            lhs_contracting: vec![1],
1633            rhs_contracting: vec![0],
1634            ..DotDims::default()
1635        };
1636        assert_eq!(dot_general(&a, &[2, 2], &b, &[2, 2], &d), [19, 22, 43, 50]);
1637    }
1638
1639    #[test]
1640    fn gather_and_scatter() {
1641        let x: Vec<i32> = (0..15).collect();
1642        let rows = GatherDims {
1643            offset_dims: vec![1],
1644            collapsed_slice_dims: vec![0],
1645            start_index_map: vec![0],
1646            ..GatherDims::default()
1647        };
1648        assert_eq!(
1649            gather(&x, &[5, 3], &[3, 9], &[2, 1], &rows, &[1, 3]),
1650            [9, 10, 11, 12, 13, 14]
1651        );
1652        let d = ScatterDims {
1653            update_window_dims: vec![1],
1654            inserted_window_dims: vec![0],
1655            scatter_dims_to_operand_dims: vec![0],
1656            ..ScatterDims::default()
1657        };
1658        let set = scatter(
1659            &x,
1660            &[5, 3],
1661            &[1, 7],
1662            &[2, 1],
1663            &[-1, -1, -1, -2, -2, -2],
1664            &[2, 3],
1665            &d,
1666            GatherScatterMode::FillOrDrop,
1667            None,
1668        );
1669        assert_eq!(&set[..6], [0, 1, 2, -1, -1, -1]);
1670        assert_eq!(&set[12..], [12, 13, 14]);
1671        let add = |a: i32, b: i32| a + b;
1672        let summed = scatter(
1673            &x,
1674            &[5, 3],
1675            &[2, 2],
1676            &[2, 1],
1677            &[1; 6],
1678            &[2, 3],
1679            &d,
1680            GatherScatterMode::Clip,
1681            Some(&add),
1682        );
1683        assert_eq!(&summed[6..9], [8, 9, 10]);
1684    }
1685}
1686
1687#[cfg(test)]
1688mod dot_tests {
1689    use super::*;
1690
1691    /// The matrix-product path gives the same bits as the general one.
1692    #[test]
1693    fn matrix_products_match_the_general_path() {
1694        let l: Vec<f32> = (0..3 * 5).map(|i| (i as f32 * 0.37).sin()).collect();
1695        let r: Vec<f32> = (0..5 * 4).map(|i| (i as f32 * 0.71).cos()).collect();
1696        let fast = dot_general(
1697            &l,
1698            &[3, 5],
1699            &r,
1700            &[5, 4],
1701            &DotDims {
1702                lhs_contracting: vec![1],
1703                rhs_contracting: vec![0],
1704                ..DotDims::default()
1705            },
1706        );
1707        // The same product with the operands transposed takes the general path.
1708        let lt: Vec<f32> = (0..15).map(|i| l[(i % 3) * 5 + i / 3]).collect();
1709        let general = dot_general(
1710            &lt,
1711            &[5, 3],
1712            &r,
1713            &[5, 4],
1714            &DotDims {
1715                lhs_contracting: vec![0],
1716                rhs_contracting: vec![0],
1717                ..DotDims::default()
1718            },
1719        );
1720        assert_eq!(fast, general);
1721        let v = dot_general(
1722            &l,
1723            &[3, 5],
1724            &r[..5],
1725            &[5],
1726            &DotDims {
1727                lhs_contracting: vec![1],
1728                rhs_contracting: vec![0],
1729                ..DotDims::default()
1730            },
1731        );
1732        let expected: Vec<f32> = (0..3)
1733            .map(|m| (0..5).fold(0.0f32, |acc, k| acc + l[m * 5 + k] * r[k]))
1734            .collect();
1735        assert_eq!(v, expected);
1736    }
1737}