tract_core/ops/array/
gather_elements.rs1use 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_dense = data.try_as_dense()?;
24 let data_view = unsafe { data_dense.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 unsafe { 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_dense_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}