tract_core/ops/array/
gather_elements.rs

1use crate::internal::*;
2use ndarray::*;
3
4#[derive(Debug, Clone, new, Hash)]
5pub struct GatherElements {
6    pub axis: usize,
7}
8
9impl Op for GatherElements {
10    fn name(&self) -> StaticName {
11        "GatherElements".into()
12    }
13
14    op_as_typed_op!();
15}
16
17impl GatherElements {
18    unsafe fn eval_t<T: Datum>(
19        &self,
20        data: TValue,
21        indices: &ArrayViewD<i64>,
22    ) -> TractResult<TValue> {
23        let data_view = unsafe { data.to_array_view_unchecked::<T>() };
24        let output = ArrayD::<T>::from_shape_fn(indices.shape(), |mut coords| {
25            let index = indices[&coords];
26            coords[self.axis] =
27                if index < 0 { index + data_view.shape()[self.axis] as i64 } else { index }
28                    as usize;
29            data_view[coords].clone()
30        });
31        let mut tensor = output.into_tensor();
32        unsafe { tensor.set_datum_type(data.datum_type()) };
33        Ok(tensor.into_tvalue())
34    }
35}
36
37impl TypedOp for GatherElements {
38    as_op!();
39
40    fn output_facts(&self, inputs: &[&TypedFact]) -> TractResult<TVec<TypedFact>> {
41        Ok(tvec!(inputs[0].datum_type.fact(&*inputs[1].shape)))
42    }
43}
44
45impl EvalOp for GatherElements {
46    fn is_stateless(&self) -> bool {
47        true
48    }
49
50    fn eval(&self, inputs: TVec<TValue>) -> TractResult<TVec<TValue>> {
51        let (data, indices) = args_2!(inputs);
52        let indices = indices.cast_to::<i64>()?;
53        let indices = indices.to_array_view::<i64>()?;
54        unsafe {
55            Ok(tvec!(dispatch_datum_by_size!(Self::eval_t(data.datum_type())(
56                self, data, &indices
57            ))?))
58        }
59    }
60}