Skip to main content

tract_core/ops/array/
scatter_nd.rs

1use crate::internal::*;
2use ndarray::*;
3
4#[derive(Debug, Clone, new, Hash)]
5pub struct ScatterNd;
6
7impl Op for ScatterNd {
8    fn name(&self) -> StaticName {
9        "ScatterNd".into()
10    }
11
12    op_as_typed_op!();
13}
14
15impl ScatterNd {
16    unsafe fn eval_t<T: Datum>(
17        &self,
18        data: TValue,
19        indices: &ArrayViewD<i64>,
20        updates: TValue,
21    ) -> TractResult<TValue> {
22        let mut data = unsafe { data.into_tensor().into_array_unchecked::<T>() };
23        let updates_dense = updates.try_as_dense()?;
24        let updates_view = unsafe { updates_dense.to_array_view_unchecked::<T>() };
25        for coords in tract_ndarray::indices(&indices.shape()[..indices.ndim() - 1]) {
26            let mut indices_into_data = indices.view();
27            let mut updates = updates_view.view();
28            for x in coords.slice() {
29                indices_into_data.index_axis_inplace(Axis(0), *x);
30                updates.index_axis_inplace(Axis(0), *x);
31            }
32            let mut data = data.view_mut();
33            for x in indices_into_data {
34                data.index_axis_inplace(Axis(0), *x as usize);
35            }
36
37            data.assign(&updates)
38        }
39        let mut tensor = data.into_tensor();
40        unsafe { tensor.set_datum_type(updates.datum_type()) };
41        Ok(tensor.into_tvalue())
42    }
43}
44
45impl TypedOp for ScatterNd {
46    as_op!();
47
48    fn output_facts(&self, inputs: &[&TypedFact]) -> TractResult<TVec<TypedFact>> {
49        Ok(tvec!(inputs[0].datum_type.fact(inputs[0].shape.to_tvec())))
50    }
51}
52
53impl EvalOp for ScatterNd {
54    fn is_stateless(&self) -> bool {
55        true
56    }
57
58    fn eval(&self, inputs: TVec<TValue>) -> TractResult<TVec<TValue>> {
59        let (data, indices, updates) = args_3!(inputs);
60        let indices = indices.cast_to::<i64>()?;
61        let indices = indices.to_dense_array_view::<i64>()?;
62        if data.datum_type() != updates.datum_type() {
63            bail!(
64                "Data and update must be of the same type, got {:?} and {:?}",
65                data.datum_type(),
66                updates.datum_type()
67            );
68        }
69        unsafe {
70            Ok(tvec!(dispatch_datum_by_size!(Self::eval_t(data.datum_type())(
71                self, data, &indices, updates
72            ))?))
73        }
74    }
75}