use std::ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive};
use ruxla_ir::{GatherScatterMode, ScatterDims, Shape};
use ruxla_kernels::{BinaryOp, Element};
use crate::backend::Backend;
use crate::lax;
use crate::value::{Array, ArrayLike, Int, Num, Scalar};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Slice {
pub start: Option<i64>,
pub stop: Option<i64>,
pub step: i64,
}
impl Slice {
pub fn new(start: Option<i64>, stop: Option<i64>) -> Self {
Self {
start,
stop,
step: 1,
}
}
#[track_caller]
pub fn step(self, step: i64) -> Self {
assert_ne!(step, 0, "the step of a slice must not be zero");
Self { step, ..self }
}
fn indices(&self, size: usize) -> (i64, i64, i64) {
let size = size as i64;
let (lo, hi) = if self.step > 0 {
(0, size)
} else {
(-1, size - 1)
};
let resolve = |v: Option<i64>, default: i64| match v {
None => default,
Some(v) if v < 0 => (v + size).clamp(lo, hi),
Some(v) => v.clamp(lo, hi),
};
if self.step > 0 {
(resolve(self.start, 0), resolve(self.stop, size), self.step)
} else {
(
resolve(self.start, size - 1),
resolve(self.stop, -1),
self.step,
)
}
}
fn start_and_size(&self, size: usize) -> (i64, usize) {
let (start, stop, step) = self.indices(size);
if step < 0 {
let new_start = stop + 1 + (start - stop - 1).abs() % step.abs();
(new_start, (start + 1 - new_start).max(0) as usize)
} else {
(start, (stop - start).max(0) as usize)
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NewAxis;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Ellipsis;
#[derive(Clone, Copy, Debug)]
pub enum Index<B: Backend> {
Int(i64),
Slice(Slice),
Dynamic(Scalar<B, i32>),
NewAxis,
Ellipsis,
}
macro_rules! int_index {
($($t:ty)*) => {$(
impl<B: Backend> From<$t> for Index<B> {
#[inline]
fn from(i: $t) -> Self {
Index::Int(i64::try_from(i).expect("index out of range"))
}
}
)*};
}
int_index!(i32 i64 isize u32 usize);
macro_rules! range_index {
($($t:ty)*) => {$(
impl<B: Backend> From<Range<$t>> for Index<B> {
#[inline]
fn from(r: Range<$t>) -> Self {
Index::Slice(Slice::new(Some(r.start as i64), Some(r.end as i64)))
}
}
impl<B: Backend> From<RangeFrom<$t>> for Index<B> {
#[inline]
fn from(r: RangeFrom<$t>) -> Self {
Index::Slice(Slice::new(Some(r.start as i64), None))
}
}
impl<B: Backend> From<RangeTo<$t>> for Index<B> {
#[inline]
fn from(r: RangeTo<$t>) -> Self {
Index::Slice(Slice::new(None, Some(r.end as i64)))
}
}
impl<B: Backend> From<RangeInclusive<$t>> for Index<B> {
#[inline]
fn from(r: RangeInclusive<$t>) -> Self {
let end = *r.end() as i64;
Index::Slice(Slice::new(Some(*r.start() as i64), if end == -1 { None } else { Some(end + 1) }))
}
}
impl<B: Backend> From<RangeToInclusive<$t>> for Index<B> {
#[inline]
fn from(r: RangeToInclusive<$t>) -> Self {
let end = r.end as i64;
Index::Slice(Slice::new(None, if end == -1 { None } else { Some(end + 1) }))
}
}
)*};
}
range_index!(i32 i64 usize);
impl<B: Backend> From<RangeFull> for Index<B> {
#[inline]
fn from(_: RangeFull) -> Self {
Index::Slice(Slice::new(None, None))
}
}
impl<B: Backend> From<Slice> for Index<B> {
#[inline]
fn from(s: Slice) -> Self {
Index::Slice(s)
}
}
impl<B: Backend> From<NewAxis> for Index<B> {
#[inline]
fn from(_: NewAxis) -> Self {
Index::NewAxis
}
}
impl<B: Backend> From<Ellipsis> for Index<B> {
#[inline]
fn from(_: Ellipsis) -> Self {
Index::Ellipsis
}
}
impl<B: Backend, I: Int> From<Scalar<B, I>> for Index<B> {
#[inline]
fn from(s: Scalar<B, I>) -> Self {
Index::Dynamic(s.cast::<i32>())
}
}
const INLINE_INDICES: usize = 4;
#[derive(Clone, Debug)]
pub struct Indices<B: Backend>(IndexList<B>);
#[derive(Clone)]
enum IndexList<B: Backend> {
Inline {
len: usize,
items: [std::mem::MaybeUninit<Index<B>>; INLINE_INDICES],
},
Heap(Vec<Index<B>>),
}
impl<B: Backend> std::fmt::Debug for IndexList<B> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list().entries(Indices::slice(self)).finish()
}
}
impl<B: Backend> Indices<B> {
#[inline]
pub fn new() -> Self {
Indices(IndexList::Inline {
len: 0,
items: [std::mem::MaybeUninit::uninit(); INLINE_INDICES],
})
}
#[inline(always)]
pub fn push(&mut self, index: Index<B>) {
match &mut self.0 {
IndexList::Inline { len, items } if *len < INLINE_INDICES => {
items[*len].write(index);
*len += 1;
}
IndexList::Inline { .. } => {
let mut v = Self::slice(&self.0).to_vec();
v.push(index);
self.0 = IndexList::Heap(v);
}
IndexList::Heap(v) => v.push(index),
}
}
}
impl<B: Backend> Indices<B> {
#[inline]
fn slice(list: &IndexList<B>) -> &[Index<B>] {
match list {
IndexList::Inline { len, items } => {
unsafe { std::slice::from_raw_parts(items.as_ptr().cast::<Index<B>>(), *len) }
}
IndexList::Heap(v) => v,
}
}
}
impl<B: Backend> Default for Indices<B> {
fn default() -> Self {
Self::new()
}
}
impl<B: Backend> std::ops::Deref for Indices<B> {
type Target = [Index<B>];
#[inline]
fn deref(&self) -> &[Index<B>] {
Self::slice(&self.0)
}
}
impl<B: Backend> FromIterator<Index<B>> for Indices<B> {
fn from_iter<I: IntoIterator<Item = Index<B>>>(iter: I) -> Self {
let mut out = Self::new();
for i in iter {
out.push(i);
}
out
}
}
impl<B: Backend> IntoIndices<B> for Indices<B> {
#[inline]
fn into_indices(self) -> Indices<B> {
self
}
}
pub trait IntoIndices<B: Backend> {
fn into_indices(self) -> Indices<B>;
}
impl<B: Backend, T: Into<Index<B>>> IntoIndices<B> for T {
#[inline]
fn into_indices(self) -> Indices<B> {
let mut out = Indices::new();
out.push(self.into());
out
}
}
macro_rules! tuple_indices {
($($t:ident),+) => {
impl<B: Backend, $($t: Into<Index<B>>),+> IntoIndices<B> for ($($t,)+) {
#[allow(non_snake_case)]
#[inline]
fn into_indices(self) -> Indices<B> {
let ($($t,)+) = self;
let mut out = Indices::new();
$(out.push($t.into());)+
out
}
}
};
}
tuple_indices!(A);
tuple_indices!(A, C);
tuple_indices!(A, C, D);
tuple_indices!(A, C, D, E);
tuple_indices!(A, C, D, E, F);
tuple_indices!(A, C, D, E, F, G);
#[track_caller]
fn expand<B: Backend>(indices: Indices<B>, ndim: usize) -> Indices<B> {
let consumed = indices
.iter()
.filter(|i| matches!(i, Index::Int(_) | Index::Slice(_) | Index::Dynamic(_)))
.count();
assert!(
consumed <= ndim,
"too many indices: {consumed} for an array of rank {ndim}"
);
let ellipses = indices
.iter()
.filter(|i| matches!(i, Index::Ellipsis))
.count();
assert!(ellipses <= 1, "an index can have only one ellipsis");
let whole = || Index::Slice(Slice::new(None, None));
let mut out = Indices::new();
let mut seen = false;
for &i in indices.iter() {
if matches!(i, Index::Ellipsis) {
(0..ndim - consumed).for_each(|_| out.push(whole()));
seen = true;
} else {
out.push(i);
}
}
if !seen {
(0..ndim - consumed).for_each(|_| out.push(whole()));
}
out
}
fn finish<B: Backend, T: Element>(
x: Array<B, T>,
squeeze: &[usize],
new_axes: &[usize],
) -> Array<B, T> {
let mut x = x;
if !squeeze.is_empty() {
let dims: Shape = x
.shape()
.iter()
.enumerate()
.filter(|(i, _)| !squeeze.contains(i))
.map(|(_, &d)| d)
.collect();
x = x.reshape(dims);
}
if !new_axes.is_empty() {
let shape = x.shape();
let rank = shape.rank() + new_axes.len();
let mut kept = 0..;
let mut out = Vec::with_capacity(rank);
let mut dims = Vec::new();
for i in 0..rank {
if new_axes.contains(&i) {
out.push(1);
} else {
out.push(shape[kept.next().expect("counted")]);
dims.push(i);
}
}
x = lax::broadcast_in_dim(&x, out, &dims);
}
x
}
impl<B: Backend, T: Element> Array<B, T> {
#[track_caller]
#[inline]
pub fn i(&self, index: impl IntoIndices<B>) -> Array<B, T> {
let indices = index.into_indices();
if B::FAST_PATHS
&& let Some(shape) = B::dims(&self.0)
{
if let Some(x) = self.static_element(&indices, shape) {
return x.to_array();
}
if let Some(x) = self.leading_rows(&indices, shape) {
return x;
}
if let Some(x) = self.box_index(&indices, shape) {
return x;
}
}
self.index_general(indices, self.shape())
}
fn box_index(&self, indices: &[Index<B>], shape: &[usize]) -> Option<Array<B, T>> {
const MAX: usize = 8;
let rank = shape.len();
if rank > MAX || indices.len() > rank {
return None;
}
let (mut starts, mut sizes) = ([0usize; MAX], [0usize; MAX]);
let mut out = Shape::scalar();
for d in 0..rank {
match indices.get(d) {
None => {
sizes[d] = shape[d];
out.push(shape[d]);
}
Some(&Index::Int(i)) => {
let n = shape[d] as i64;
let j = if i < 0 { i + n } else { i };
if j < 0 || j >= n {
return None;
}
(starts[d], sizes[d]) = (j as usize, 1);
}
Some(Index::Slice(s)) => {
let (start, size) = s.start_and_size(shape[d]);
if s.step != 1 || start < 0 {
return None;
}
(starts[d], sizes[d]) = (start as usize, size);
out.push(size);
}
_ => return None,
}
}
B::slice_box::<T>(&self.0, &starts[..rank], &sizes[..rank], out).map(Array)
}
#[inline]
fn leading_rows(&self, indices: &[Index<B>], shape: &[usize]) -> Option<Array<B, T>> {
const MAX: usize = 8;
if indices.is_empty() || indices.len() >= shape.len() || indices.len() > MAX {
return None;
}
let mut at = [0usize; MAX];
for ((p, index), &size) in at.iter_mut().zip(indices).zip(shape) {
*p = match *index {
Index::Int(i) => {
let j = if i < 0 { i + size as i64 } else { i };
if j < 0 || j >= size as i64 {
return None;
}
j as usize
}
Index::Dynamic(s) if size > 0 => {
let i = B::int_value(s.0)?;
let j = if i < 0 { i + size as i64 } else { i };
j.clamp(0, size as i64 - 1) as usize
}
_ => return None,
};
}
B::index_leading::<T>(&self.0, &at[..indices.len()]).map(Array)
}
#[track_caller]
fn index_general(&self, indices: Indices<B>, shape: Shape) -> Array<B, T> {
if indices.len() <= shape.rank() && indices.iter().all(|i| matches!(i, Index::Int(_))) {
return self.int_index(&indices, &shape);
}
let indices = expand(indices, shape.rank());
if indices.iter().any(|i| matches!(i, Index::Dynamic(_))) {
self.dynamic_index(&indices, &shape)
} else {
self.static_index(&indices, &shape)
}
}
#[track_caller]
#[inline]
pub fn get(&self, index: impl IntoIndices<B>) -> Scalar<B, T> {
let indices = index.into_indices();
if B::FAST_PATHS
&& let Some(shape) = B::dims(&self.0)
&& let Some(x) = self.static_element(&indices, shape)
{
return x;
}
self.get_general(indices)
}
#[cold]
#[inline(never)]
#[track_caller]
fn get_general(&self, indices: Indices<B>) -> Scalar<B, T> {
self.i(indices).to_scalar()
}
#[inline(always)]
fn static_element(&self, indices: &[Index<B>], shape: &[usize]) -> Option<Scalar<B, T>> {
if indices.len() != shape.len() {
return None;
}
let mut flat = 0usize;
for (index, &size) in indices.iter().zip(shape) {
let j = match *index {
Index::Int(i) => {
let j = if i < 0 { i + size as i64 } else { i };
if j < 0 || j >= size as i64 {
return None;
}
j
}
Index::Dynamic(s) if size > 0 => {
let i = B::int_value(s.0)?;
let j = if i < 0 { i + size as i64 } else { i };
j.clamp(0, size as i64 - 1)
}
_ => return None,
};
flat = flat * size + j as usize;
}
B::element::<T>(&self.0, flat).map(Scalar)
}
#[track_caller]
fn int_index(&self, indices: &[Index<B>], shape: &[usize]) -> Array<B, T> {
let mut starts: Shape = shape.iter().map(|_| 0).collect();
let mut limits = Shape::from(shape);
for (axis, index) in indices.iter().enumerate() {
let Index::Int(i) = *index else {
unreachable!("checked by the caller")
};
let size = shape[axis] as i64;
let j = if i < 0 { i + size } else { i };
assert!(
(0..size).contains(&j),
"index {i} is out of bounds for axis {axis} with size {size}"
);
starts.set(axis, j as usize);
limits.set(axis, j as usize + 1);
}
if B::FAST_PATHS
&& let Some(r) = B::index_leading::<T>(&self.0, &starts[..indices.len()])
{
return Array(r);
}
let trivial = starts.iter().all(|&s| s == 0) && limits[..] == shape[..];
let x = if trivial {
self.clone()
} else {
lax::slice(self, &starts, &limits, None)
};
x.reshape(&shape[indices.len()..])
}
#[track_caller]
fn static_index(&self, indices: &[Index<B>], shape: &[usize]) -> Array<B, T> {
let (mut starts, mut limits, mut strides) =
(Shape::scalar(), Shape::scalar(), Shape::scalar());
let (mut rev, mut squeeze, mut new_axes) =
(Shape::scalar(), Shape::scalar(), Shape::scalar());
let mut axis = 0;
for index in indices {
match index {
Index::NewAxis => new_axes.push(starts.len() - squeeze.len() + new_axes.len()),
Index::Int(i) => {
let size = shape[axis] as i64;
let j = if *i < 0 { i + size } else { *i };
assert!(
(0..size).contains(&j),
"index {i} is out of bounds for axis {axis} with size {size}"
);
starts.push(j as usize);
limits.push(j as usize + 1);
strides.push(1);
squeeze.push(axis);
axis += 1;
}
Index::Slice(s) => {
let size = shape[axis];
let (start, stop, step) = s.indices(size);
if step < 0 {
let new_start =
(stop + 1 + (start - stop - 1).abs() % step.abs()).min(size as i64);
starts.push(new_start as usize);
limits.push(new_start.max(start + 1) as usize);
strides.push(step.unsigned_abs() as usize);
rev.push(axis);
} else {
starts.push(start as usize);
limits.push(start.max(stop) as usize);
strides.push(step as usize);
}
axis += 1;
}
Index::Dynamic(_) | Index::Ellipsis => unreachable!("handled before"),
}
}
let trivial = starts.iter().all(|&s| s == 0)
&& limits.iter().zip(shape).all(|(&l, &n)| l == n)
&& strides.iter().all(|&s| s == 1);
let mut x = if trivial {
self.clone()
} else {
let st = (!strides.iter().all(|&s| s == 1)).then_some(strides);
lax::slice(self, &starts, &limits, st.as_deref())
};
if !rev.is_empty() {
x = lax::rev(&x, &rev);
}
finish(x, &squeeze, &new_axes)
}
#[track_caller]
fn dynamic_index(&self, indices: &[Index<B>], shape: &[usize]) -> Array<B, T> {
let mut starts: Vec<Scalar<B, i32>> = Vec::new();
let mut sizes = Vec::new();
let (mut rev, mut squeeze, mut new_axes) = (Vec::new(), Vec::new(), Vec::new());
let mut axis = 0;
for index in indices {
match index {
Index::NewAxis => new_axes.push(starts.len() - squeeze.len() + new_axes.len()),
Index::Int(_) | Index::Dynamic(_) => {
assert!(
shape[axis] > 0,
"index is out of bounds for axis {axis} with size 0"
);
starts.push(match index {
Index::Int(i) => Scalar::new(*i as i32),
Index::Dynamic(s) => *s,
_ => unreachable!("matched above"),
});
sizes.push(1);
squeeze.push(axis);
axis += 1;
}
Index::Slice(s) => {
assert!(
s.step.abs() == 1,
"slices with steps other than 1 and -1 cannot be combined with run-time indices"
);
let (start, n) = s.start_and_size(shape[axis]);
if s.step < 0 {
rev.push(axis);
}
starts.push(Scalar::new(start as i32));
sizes.push(n);
axis += 1;
}
Index::Ellipsis => unreachable!("handled before"),
}
}
let mut x = lax::dynamic_slice(self, &starts, &sizes);
if !rev.is_empty() {
x = lax::rev(&x, &rev);
}
finish(x, &squeeze, &new_axes)
}
#[track_caller]
pub fn at(&self, index: impl IntoIndices<B>) -> At<'_, B, T> {
At {
array: Base::Borrowed(self),
indices: index.into_indices(),
}
}
#[track_caller]
pub fn into_at(self, index: impl IntoIndices<B>) -> At<'static, B, T> {
At {
array: Base::Owned(self),
indices: index.into_indices(),
}
}
#[track_caller]
pub fn at_mut(&mut self, index: impl IntoIndices<B>) -> AtMut<'_, B, T> {
AtMut {
array: self,
indices: index.into_indices(),
}
}
}
fn box_update<B: Backend, T: Element>(
x: &mut Array<B, T>,
indices: &[Index<B>],
values: &Array<B, T>,
combine: Option<BinaryOp>,
) -> bool {
const MAX: usize = 8;
let Some(shape) = B::dims(&x.0) else {
return false;
};
let rank = shape.len();
if rank > MAX || indices.len() > rank {
return false;
}
let (mut starts, mut sizes) = ([0usize; MAX], [0usize; MAX]);
let (mut selected, mut n_selected) = ([0usize; MAX], 0);
for d in 0..rank {
match indices.get(d) {
None => {
sizes[d] = shape[d];
selected[n_selected] = shape[d];
n_selected += 1;
}
Some(&Index::Int(i)) => {
let n = shape[d] as i64;
let j = if i < 0 { i + n } else { i };
if j < 0 || j >= n {
return false;
}
(starts[d], sizes[d]) = (j as usize, 1);
}
Some(Index::Slice(s)) => {
let (start, size) = s.start_and_size(shape[d]);
if s.step != 1 || start < 0 {
return false;
}
(starts[d], sizes[d]) = (start as usize, size);
selected[n_selected] = size;
n_selected += 1;
}
_ => return false,
}
}
let selected = &selected[..n_selected];
let broadcast;
let values = if values.size() == 1 || B::dims(&values.0) == Some(selected) {
values
} else {
broadcast = crate::jnp::broadcast_to(values, Shape::from(selected));
&broadcast
};
B::update_box::<T>(
&mut x.0,
&starts[..rank],
&sizes[..rank],
&values.0,
combine,
)
}
#[derive(Debug)]
pub struct AtMut<'a, B: Backend, T: Element> {
array: &'a mut Array<B, T>,
indices: Indices<B>,
}
impl<B: Backend, T: Element> AtMut<'_, B, T> {
#[track_caller]
pub fn set(self, values: impl ArrayLike<B, T>) {
self.update(values, None);
}
#[allow(clippy::should_implement_trait)]
#[track_caller]
pub fn add(self, values: impl ArrayLike<B, T>) {
self.update(values, Some(BinaryOp::Add));
}
#[allow(clippy::should_implement_trait)]
#[track_caller]
pub fn mul(self, values: impl ArrayLike<B, T>) {
self.update(values, Some(BinaryOp::Mul));
}
#[track_caller]
pub fn max(self, values: impl ArrayLike<B, T>) {
self.update(values, Some(BinaryOp::Max));
}
#[track_caller]
pub fn min(self, values: impl ArrayLike<B, T>) {
self.update(values, Some(BinaryOp::Min));
}
#[track_caller]
#[inline(always)]
fn update(self, values: impl ArrayLike<B, T>, combine: Option<BinaryOp>) {
if B::FAST_PATHS
&& let Some(v) = values.as_scalar()
&& B::point_update_in_place::<T>(&mut self.array.0, &self.indices, v.0, combine)
{
return;
}
self.update_general(values.into_array(), combine);
}
#[track_caller]
#[cold]
#[inline(never)]
fn update_general(self, values: Array<B, T>, combine: Option<BinaryOp>) {
if B::FAST_PATHS && box_update(self.array, &self.indices, &values, combine) {
return;
}
let at = At {
array: Base::Borrowed(&*self.array),
indices: self.indices,
};
let updated = at.scatter(values, combine);
*self.array = updated;
}
}
#[derive(Debug)]
enum Base<'a, B: Backend, T: Element> {
Borrowed(&'a Array<B, T>),
Owned(Array<B, T>),
}
impl<B: Backend, T: Element> std::ops::Deref for Base<'_, B, T> {
type Target = Array<B, T>;
#[inline]
fn deref(&self) -> &Array<B, T> {
match self {
Base::Borrowed(x) => x,
Base::Owned(x) => x,
}
}
}
#[derive(Debug)]
pub struct At<'a, B: Backend, T: Element> {
array: Base<'a, B, T>,
indices: Indices<B>,
}
impl<B: Backend, T: Element> At<'_, B, T> {
#[track_caller]
pub fn get(self) -> Array<B, T> {
let shape = self.array.shape();
let indices = expand(self.indices, shape.rank());
if indices.iter().any(|i| matches!(i, Index::Dynamic(_))) {
self.array.dynamic_index(&indices, &shape)
} else {
self.array.static_index(&indices, &shape)
}
}
#[track_caller]
pub fn set(self, values: impl ArrayLike<B, T>) -> Array<B, T> {
self.scatter(values, None)
}
#[track_caller]
pub fn max(self, values: impl ArrayLike<B, T>) -> Array<B, T> {
self.scatter(values, Some(BinaryOp::Max))
}
#[track_caller]
pub fn min(self, values: impl ArrayLike<B, T>) -> Array<B, T> {
self.scatter(values, Some(BinaryOp::Min))
}
#[inline]
fn points(x: &Array<B, T>, indices: &[Index<B>]) -> Option<[B::Scalar<i32>; 8]> {
let shape = x.shape();
if indices.len() != shape.rank() || indices.len() > 8 {
return None;
}
let mut points = [Scalar::<B, i32>::new(0).0; 8];
for ((p, index), &size) in points.iter_mut().zip(indices).zip(shape.iter()) {
*p = match *index {
Index::Int(i) => {
Scalar::<B, i32>::new((if i < 0 { i + size as i64 } else { i }) as i32).0
}
Index::Dynamic(s) => lax::wrap_negative(s, size).0,
_ => return None,
};
}
Some(points)
}
#[track_caller]
fn scatter(mut self, values: impl ArrayLike<B, T>, combine: Option<BinaryOp>) -> Array<B, T> {
if B::FAST_PATHS
&& let Some(v) = values.as_scalar()
{
let n = self.indices.len();
if let Base::Owned(x) = &mut self.array {
if B::point_update_in_place::<T>(&mut x.0, &self.indices, v.0, combine) {
let Base::Owned(x) = self.array else {
unreachable!("matched above")
};
return x;
}
} else if let Some(points) = Self::points(&self.array, &self.indices) {
let x = &*self.array;
if let Some(r) = B::point_update::<T>(&x.0, &points[..n], &v.to_array().0, combine)
{
return Array(r);
}
}
}
let values = values.into_array();
if B::FAST_PATHS {
let mut x = match self.array {
Base::Owned(x) => x,
Base::Borrowed(x) => x.clone(),
};
if box_update(&mut x, &self.indices, &values, combine) {
return x;
}
return Self {
array: Base::Owned(x),
indices: self.indices,
}
.scatter_general(values, combine);
}
self.scatter_general(values, combine)
}
#[track_caller]
fn scatter_general(self, values: Array<B, T>, combine: Option<BinaryOp>) -> Array<B, T> {
let x = &*self.array;
let shape = x.shape();
let point = self.indices.len() == shape.rank()
&& self
.indices
.iter()
.all(|i| matches!(i, Index::Int(_) | Index::Dynamic(_)));
let indices = if point {
self.indices
} else {
expand(self.indices, shape.rank())
};
if B::FAST_PATHS && point && values.size() == 1 {
let mut buf = [Scalar::<B, i32>::new(0).0; 8];
let mut heap = Vec::new();
for (k, (index, &size)) in indices.iter().zip(shape.iter()).enumerate() {
let p = match *index {
Index::Int(i) => {
Scalar::<B, i32>::new((if i < 0 { i + size as i64 } else { i }) as i32).0
}
Index::Dynamic(s) => lax::wrap_negative(s, size).0,
_ => unreachable!("checked above"),
};
if k < buf.len() {
buf[k] = p;
}
heap.extend((indices.len() > buf.len()).then_some(p));
}
let points = if indices.len() <= buf.len() {
&buf[..indices.len()]
} else {
&heap[..]
};
if let Some(r) = B::point_update::<T>(&x.0, points, &values.0, combine) {
return Array(r);
}
}
let mut offset_dims = Vec::new();
let mut collapsed = Vec::new();
let mut start_index_map = Vec::new();
let mut gather_indices: Vec<(Array<B, i32>, usize)> = Vec::new();
let mut gather_shape: Vec<usize> = Vec::new();
let mut slice_shape = Vec::new();
let mut new_axes = Vec::new();
let mut reversed = Vec::new();
let (mut x_axis, mut y_axis, mut collapsed_y) = (0, 0, 0);
for index in indices.iter() {
match index {
Index::Int(_) | Index::Dynamic(_) => {
let size = shape[x_axis];
assert!(
size > 0,
"index is out of bounds for axis {x_axis} with size 0"
);
let i: Scalar<B, i32> = match index {
Index::Int(i) => {
Scalar::new((if *i < 0 { i + size as i64 } else { *i }) as i32)
}
Index::Dynamic(s) => lax::wrap_negative(*s, size),
_ => unreachable!("matched above"),
};
gather_indices.push((i.to_array(), gather_shape.len()));
collapsed.push(x_axis);
start_index_map.push(x_axis);
x_axis += 1;
}
Index::NewAxis => {
slice_shape.push(1);
new_axes.push(y_axis);
y_axis += 1;
}
Index::Slice(s) => {
let size = shape[x_axis];
let (start, stop, step) = s.indices(size);
let n = if step > 0 {
((stop - start).max(0) as usize).div_ceil(step as usize)
} else {
((start - stop).max(0) as usize).div_ceil(step.unsigned_abs() as usize)
};
slice_shape.push(n);
if step == 1 {
if n != size {
gather_indices.push((
Scalar::<B, i32>::new(start as i32).to_array(),
gather_shape.len(),
));
start_index_map.push(x_axis);
}
offset_dims.push(collapsed_y);
} else {
let base = Scalar::<B, i32>::new(start as i32);
let mut idx = lax::iota::<B, i32>([n], 0) * Scalar::new(step as i32) + base;
if step < 0 {
reversed.push(collapsed_y);
idx = lax::rev(&idx, &[0]);
}
gather_indices.push((idx, gather_shape.len()));
start_index_map.push(x_axis);
gather_shape.push(n);
collapsed.push(x_axis);
}
collapsed_y += 1;
y_axis += 1;
x_axis += 1;
}
Index::Ellipsis => unreachable!("handled before"),
}
}
if slice_shape.contains(&0) {
return x.clone();
}
let index_array: Array<B, i32> = match gather_indices.len() {
0 => crate::jnp::zeros([0]),
1 => {
let (g, _) = &gather_indices[0];
let mut s = g.shape().dims().to_vec();
s.push(1);
let dims: Vec<usize> = (0..g.ndim()).collect();
lax::broadcast_in_dim(g, s, &dims)
}
_ => {
let mut full = gather_shape.clone();
full.push(1);
let parts: Vec<Array<B, i32>> = gather_indices
.iter()
.map(|(g, i)| {
let dims: Vec<usize> = (*i..i + g.ndim()).collect();
lax::broadcast_in_dim(g, full.clone(), &dims)
})
.collect();
lax::concatenate(&parts, gather_shape.len())
}
};
collapsed.sort_unstable();
let y = values.broadcast_to(slice_shape);
let mut y = finish(y, &new_axes, &[]);
if !reversed.is_empty() {
y = lax::rev(&y, &reversed);
}
let dims = ScatterDims {
update_window_dims: offset_dims,
inserted_window_dims: collapsed,
scatter_dims_to_operand_dims: start_index_map,
operand_batching_dims: vec![],
scatter_indices_batching_dims: vec![],
};
Array(B::scatter::<T, i32>(
combine,
&x.0,
&index_array.0,
&y.0,
&dims,
GatherScatterMode::FillOrDrop,
true,
))
}
}
impl<B: Backend, T: Num> At<'_, B, T> {
#[allow(clippy::should_implement_trait)]
#[track_caller]
pub fn add(self, values: impl ArrayLike<B, T>) -> Array<B, T> {
self.scatter(values, Some(BinaryOp::Add))
}
#[allow(clippy::should_implement_trait)]
#[track_caller]
pub fn mul(self, values: impl ArrayLike<B, T>) -> Array<B, T> {
self.scatter(values, Some(BinaryOp::Mul))
}
}