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