tract_hir/ops/array/
constant_of_shape.rs1use crate::infer::*;
2use crate::internal::*;
3
4#[derive(Debug, Clone, new, Hash)]
5pub struct ConstantOfShape {
6 scalar: Arc<Tensor>,
7}
8
9
10
11impl Expansion for ConstantOfShape {
12 fn name(&self) -> StaticName {
13 "ConstantOfShape".into()
14 }
15
16
17 fn rules<'r, 'p: 'r, 's: 'r>(
18 &'s self,
19 s: &mut Solver<'r>,
20 inputs: &'p [TensorProxy],
21 outputs: &'p [TensorProxy],
22 ) -> InferenceResult {
23 check_input_arity(inputs, 1)?;
24 check_output_arity(outputs, 1)?;
25 s.equals(&outputs[0].datum_type, self.scalar.datum_type())?;
26 s.equals(&inputs[0].rank, 1)?;
27 s.equals(&inputs[0].shape[0], outputs[0].rank.bex().to_dim())?;
28 s.given(&inputs[0].value, move |s, shape| {
29 let shape = shape.cast_to::<TDim>()?;
30 let shape = shape.as_slice::<TDim>()?;
31 for (axis, dim) in shape.iter().enumerate() {
32 s.equals(&outputs[0].shape[axis], dim)?;
33 }
34 Ok(())
35 })?;
36 Ok(())
45 }
46
47 fn wire(
48 &self,
49 prefix: &str,
50 target: &mut TypedModel,
51 inputs: &[OutletId],
52 ) -> TractResult<TVec<OutletId>> {
53 if let Some(shape) = target.outlet_fact(inputs[0])?.konst.clone() {
54 let shape = shape.cast_to::<TDim>()?;
55 let shape = shape.as_slice::<TDim>()?;
56 let scalar = target.add_const(format!("{prefix}.scalar"), self.scalar.clone())?;
57 let op = tract_core::ops::array::MultiBroadcastTo::new(shape.into());
58 return target.wire_node(prefix, op, &[scalar]);
59 }
60 bail!("shape input is variable")
61 }
62}