1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
use crate::internal::*;
use ndarray::*;

use super::MultiBroadcastTo;

#[derive(Debug, Clone, new, Default, Hash)]
pub struct Tile {
    pub multipliers: TVec<TDim>,
}

impl Tile {
    fn eval_t<T: Datum>(data: &TValue, multipliers: &[usize]) -> TractResult<TValue> {
        let view = unsafe { data.to_array_view_unchecked::<T>() };
        let output_shape: TVec<usize> =
            view.shape().iter().zip(multipliers.iter()).map(|(&d, &m)| d * m).collect();
        let output = ndarray::ArrayD::from_shape_fn(&*output_shape, |coords| {
            let coords: TVec<usize> =
                coords.slice().iter().zip(data.shape().iter()).map(|(&x, &d)| x % d).collect();
            view[&*coords].clone()
        });
        let mut output = output.into_tensor();
        unsafe {
            output.set_datum_type(data.datum_type());
        }

        Ok(output.into_tvalue())
    }
}

impl Op for Tile {
    fn name(&self) -> Cow<str> {
        "Tile".into()
    }

    fn info(&self) -> TractResult<Vec<String>> {
        Ok(vec![format!("multipliers: {:?}", self.multipliers)])
    }

    op_as_typed_op!();
}

impl EvalOp for Tile {
    fn is_stateless(&self) -> bool {
        self.multipliers.iter().all(|m| m.to_usize().is_ok())
    }

    fn eval(&self, inputs: TVec<TValue>) -> TractResult<TVec<TValue>> {
        let multipliers: TVec<usize> =
            self.multipliers.iter().map(|m| m.to_usize()).collect::<TractResult<_>>()?;
        let result = dispatch_datum_by_size!(Self::eval_t(inputs[0].datum_type())(
            &inputs[0],
            &multipliers
        ))?;
        Ok(tvec!(result))
    }

    fn state(
        &self,
        _session: &mut SessionState,
        _node_id: usize,
    ) -> TractResult<Option<Box<dyn OpState>>> {
        Ok(Some(Box::new(self.clone())))
    }
}

trivial_op_state_freeeze!(Tile);
impl OpState for Tile {
    fn eval(
        &mut self,
        session: &mut SessionState,
        _op: &dyn Op,
        inputs: TVec<TValue>,
    ) -> TractResult<TVec<TValue>> {
        let multipliers: TVec<usize> = self
            .multipliers
            .iter()
            .map(|m| m.eval(&session.resolved_symbols).to_usize())
            .collect::<TractResult<_>>()?;
        let result = dispatch_datum_by_size!(Self::eval_t(inputs[0].datum_type())(
            &inputs[0],
            &multipliers
        ))?;
        Ok(tvec!(result))
    }
}

impl TypedOp for Tile {
    as_op!();

    fn concretize_dims(
        &self,
        _source: &TypedModel,
        node: &TypedNode,
        target: &mut TypedModel,
        mapping: &HashMap<OutletId, OutletId>,
        values: &SymbolValues,
    ) -> TractResult<TVec<OutletId>> {
        let multipliers = self.multipliers.iter().map(|m| m.eval(values)).collect();
        target.wire_node(&node.name, Self { multipliers }, &[mapping[&node.inputs[0]]])
    }

    fn declutter(
        &self,
        model: &TypedModel,
        node: &TypedNode,
    ) -> TractResult<Option<TypedModelPatch>> {
        let input_fact = model.outlet_fact(node.inputs[0])?;
        if input_fact
            .shape
            .iter()
            .zip(self.multipliers.iter())
            .all(|(i, m)| i.is_one() || m.is_one())
        {
            let output_fact = self.output_facts(&[input_fact])?.remove(0);
            TypedModelPatch::replace_single_op(
                model,
                node,
                &node.inputs,
                MultiBroadcastTo { shape: output_fact.shape },
            )
            .map(Some)
        } else {
            Ok(None)
        }
    }

    fn output_facts(&self, inputs: &[&TypedFact]) -> TractResult<TVec<TypedFact>> {
        let shape = inputs[0]
            .shape
            .iter()
            .zip(self.multipliers.iter())
            .map(|(a, b)| a * b.clone())
            .collect::<TVec<_>>();
        Ok(tvec!(inputs[0].datum_type.fact(shape)))
    }
}