tract_hir/ops/array/
flatten.rs

1use crate::infer::*;
2use crate::internal::*;
3
4#[derive(Debug, Clone, new, Default, Hash)]
5pub struct Flatten {
6    pub axis: i64,
7}
8
9impl Flatten {
10    pub fn compute_shape<D: DimLike>(&self, shape: &[D]) -> TractResult<[D; 2]> {
11        if shape.iter().filter(|d| d.to_usize().is_err()).count() > 1 {
12            bail!("Can not compute a shape with square of symbols")
13        }
14        let axis = if self.axis >= 0 { self.axis } else { self.axis + shape.len() as i64 } as usize;
15        Ok([shape[..axis].iter().cloned().product::<D>(), shape[axis..].iter().cloned().product()])
16    }
17}
18
19impl Expansion for Flatten {
20    fn name(&self) -> StaticName {
21        "Flatten".into()
22    }
23
24    fn rules<'r, 'p: 'r, 's: 'r>(
25        &'s self,
26        s: &mut Solver<'r>,
27        inputs: &'p [TensorProxy],
28        outputs: &'p [TensorProxy],
29    ) -> InferenceResult {
30        s.equals(&outputs[0].datum_type, &inputs[0].datum_type)?;
31        s.given(&inputs[0].shape, move |s, shape| {
32            let [shape_0, shape_1] = self.compute_shape(&shape)?;
33            s.equals(&outputs[0].shape, ShapeFactoid::from(vec![shape_0, shape_1]))
34        })
35    }
36
37    fn wire(
38        &self,
39        prefix: &str,
40        model: &mut TypedModel,
41        inputs: &[OutletId],
42    ) -> TractResult<TVec<OutletId>> {
43        let input_shape = model.outlet_fact(inputs[0])?.shape.to_tvec();
44        let output_shape = self.compute_shape(&input_shape)?;
45        let mut wire = tvec!(inputs[0]);
46        for (ix, op) in
47            tract_core::ops::change_axes::to_axis_ops_with_tf_rules(&input_shape, &output_shape)?
48                .into_iter()
49                .enumerate()
50        {
51            wire = model.wire_node(format!("{prefix}.{ix}"), op, &wire)?;
52        }
53        Ok(wire)
54    }
55}