tract_core/ops/array/
scatter_nd.rs1use 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_view = unsafe { updates.to_array_view_unchecked::<T>() };
24 for coords in tract_ndarray::indices(&indices.shape()[..indices.ndim() - 1]) {
25 let mut indices_into_data = indices.view();
26 let mut updates = updates_view.view();
27 for x in coords.slice() {
28 indices_into_data.index_axis_inplace(Axis(0), *x);
29 updates.index_axis_inplace(Axis(0), *x);
30 }
31 let mut data = data.view_mut();
32 for x in indices_into_data {
33 data.index_axis_inplace(Axis(0), *x as usize);
34 }
35
36 data.assign(&updates)
37 }
38 let mut tensor = data.into_tensor();
39 unsafe { tensor.set_datum_type(updates.datum_type()) };
40 Ok(tensor.into_tvalue())
41 }
42}
43
44impl TypedOp for ScatterNd {
45 as_op!();
46
47 fn output_facts(&self, inputs: &[&TypedFact]) -> TractResult<TVec<TypedFact>> {
48 Ok(tvec!(inputs[0].datum_type.fact(inputs[0].shape.to_tvec())))
49 }
50}
51
52impl EvalOp for ScatterNd {
53 fn is_stateless(&self) -> bool {
54 true
55 }
56
57 fn eval(&self, inputs: TVec<TValue>) -> TractResult<TVec<TValue>> {
58 let (data, indices, updates) = args_3!(inputs);
59 let indices = indices.cast_to::<i64>()?;
60 let indices = indices.to_array_view::<i64>()?;
61 if data.datum_type() != updates.datum_type() {
62 bail!(
63 "Data and update must be of the same type, got {:?} and {:?}",
64 data.datum_type(),
65 updates.datum_type()
66 );
67 }
68 unsafe {
69 Ok(tvec!(dispatch_datum_by_size!(Self::eval_t(data.datum_type())(
70 self, data, &indices, updates
71 ))?))
72 }
73 }
74}