tract-hir 0.23.0-dev.4

Tiny, no-nonsense, self contained, TensorFlow and ONNX inference
Documentation
use tract_core::ops::cast::wire_cast;

use crate::infer::*;
use crate::internal::*;

pub use tract_core::ops::array::ScatterReduction;

#[derive(Debug, Clone, new, Default, Hash, PartialEq, Eq)]
pub struct ScatterNd {
    pub reduction: ScatterReduction,
}

impl Expansion for ScatterNd {
    fn name(&self) -> StaticName {
        "ScatterNd".into()
    }

    fn rules<'r, 'p: 'r, 's: 'r>(
        &'s self,
        s: &mut Solver<'r>,
        inputs: &'p [TensorProxy],
        outputs: &'p [TensorProxy],
    ) -> InferenceResult {
        check_input_arity(inputs, 3)?;
        check_output_arity(outputs, 1)?;

        s.given_2(&inputs[0].datum_type, &inputs[2].datum_type, move |s, input, updates| {
            let super_type: DatumType = DatumType::super_type_for([input, updates])
                .with_context(|| format!("No supertype found for {input:?} and {updates:?}"))?;
            s.equals(&outputs[0].datum_type, super_type)
        })?;
        s.equals(&outputs[0].shape, &inputs[0].shape)?;

        s.given_2(&inputs[0].rank, &inputs[1].rank, move |s, p, q| {
            s.given(&inputs[1].shape[q as usize - 1], move |s, r| {
                if let Ok(r) = r.to_i64() {
                    s.equals(&inputs[2].rank, p + q - r - 1)?;
                }
                Ok(())
            })
        })?;
        Ok(())
    }

    fn wire(
        &self,
        prefix: &str,
        model: &mut TypedModel,
        inputs: &[OutletId],
    ) -> TractResult<TVec<OutletId>> {
        let super_type = if let Some(super_type) = DatumType::super_type_for([
            model.outlet_fact(inputs[0])?.datum_type,
            model.outlet_fact(inputs[2])?.datum_type,
        ]) {
            super_type
        } else {
            bail!("Can not type op");
        };
        let casted = wire_cast(prefix, model, &[inputs[0], inputs[2]], super_type)?;
        model.wire_node(
            prefix,
            tract_core::ops::array::ScatterNd::new(self.reduction),
            &[casted[0], inputs[1], casted[1]],
        )
    }
}