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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use crate::internal::*;
use tract_core::ops::nn::Reduce as TReduce;
use tract_core::ops::nn::Reducer as TReducer;
#[derive(Clone, Copy, Debug, Hash, PartialEq)]
pub enum Reducer {
ArgMax(bool),
ArgMin(bool),
L1,
L2,
LogSum,
LogSumExp,
Max,
Mean,
Min,
Prod,
Sum,
SumSquare,
}
impl Reducer {
pub fn wire(
&self,
axes: TVec<usize>,
name: &str,
target: &mut TypedModel,
mut wire: OutletId,
) -> TractResult<OutletId> {
use tract_core::ops::math;
use Reducer::*;
match self {
ArgMax(last) => {
wire =
target.wire_node(name, TReduce::new(axes, TReducer::ArgMax(*last)), &[wire])?[0]
}
ArgMin(last) => {
wire =
target.wire_node(name, TReduce::new(axes, TReducer::ArgMin(*last)), &[wire])?[0]
}
Max => wire = target.wire_node(name, TReduce::new(axes, TReducer::Max), &[wire])?[0],
Min => wire = target.wire_node(name, TReduce::new(axes, TReducer::Min), &[wire])?[0],
Sum => wire = target.wire_node(name, TReduce::new(axes, TReducer::Sum), &[wire])?[0],
Prod => wire = target.wire_node(name, TReduce::new(axes, TReducer::Prod), &[wire])?[0],
L1 => {
wire = target.wire_node(format!("{}.abs", name), math::abs(), &[wire])?[0];
wire = target.wire_node(
format!("{}.sum", name),
TReduce::new(axes, TReducer::Sum),
&[wire],
)?[0];
}
L2 => {
wire = target.wire_node(format!("{}.sq", name), math::square(), &[wire])?[0];
wire = target.wire_node(
format!("{}.sum", name),
TReduce::new(axes, TReducer::Sum),
&[wire],
)?[0];
wire = target.wire_node(format!("{}.sqrt", name), math::sqrt(), &[wire])?[0];
}
LogSum => {
wire = target.wire_node(
format!("{}.sum", name),
TReduce::new(axes, TReducer::Sum),
&[wire],
)?[0];
wire = target.wire_node(format!("{}.ln", name), math::ln(), &[wire])?[0];
}
LogSumExp => {
wire = target.wire_node(format!("{}.exp", name), math::exp(), &[wire])?[0];
wire = target.wire_node(
format!("{}.sum", name),
TReduce::new(axes, TReducer::Sum),
&[wire],
)?[0];
wire = target.wire_node(format!("{}.ln", name), math::ln(), &[wire])?[0];
}
SumSquare => {
wire = target.wire_node(format!("{}.sq", name), math::square(), &[wire])?[0];
wire = target.wire_node(
name.to_string() + ".sum",
TReduce::new(axes, TReducer::Sum),
&[wire],
)?[0]
}
Mean => {
let fact = target.outlet_fact(wire)?.clone();
wire = target.wire_node(
name.to_string() + ".sum",
TReduce::new(axes.clone(), TReducer::Sum),
&[wire],
)?[0];
let size: TDim = axes.iter().map(|ax| &fact.shape[*ax]).product();
let size = size.to_i64()?;
let size = tensor0(size)
.cast_to_dt(fact.datum_type)?
.into_owned()
.into_shape(&*tvec!(1; fact.rank()))?;
let size = target.add_const(name.to_string() + ".divisor", size)?;
wire = target.wire_node(
name.to_string() + ".norm",
math::div::bin_typed(),
&[wire, size],
)?[0];
}
};
Ok(wire)
}
}
#[derive(Clone, Debug, new, Hash)]
pub struct Reduce {
axes: Option<Vec<i64>>,
keep_dims: bool,
reducer: Reducer,
}
impl_dyn_hash!(Reduce);
impl Reduce {
pub fn must_reduce(&self, ax: usize, rank: usize) -> bool {
let resolved_axes: Option<Vec<usize>> = match &self.axes {
None => None,
Some(original_axes) => {
let mut ans: Vec<usize> = vec![];
for or_ax in original_axes.iter() {
ans.push(Self::resolve_axis(*or_ax, rank).unwrap());
}
Some(ans)
}
};
resolved_axes.as_ref().map(|axes| axes.contains(&ax)).unwrap_or(true)
}
pub fn output_shape(&self, shape: &[TDim]) -> TVec<TDim> {
shape
.iter()
.enumerate()
.filter_map(|(ix, d)| {
if self.must_reduce(ix, shape.len()) {
if self.keep_dims {
Some(1.to_dim())
} else {
None
}
} else {
Some(d.clone())
}
})
.collect()
}
fn resolve_axis(axis: i64, rank: usize) -> TractResult<usize> {
if 0 <= axis && axis as usize <= rank - 1 {
Ok(axis as usize)
} else if -(rank as i64) <= axis && axis < 0 {
Ok((axis + rank as i64) as usize)
} else {
bail!("Illegal combination of values for rank and axis: {} and {}", rank, axis)
}
}
fn resolve_axes(&self, input_rank: usize) -> TractResult<TVec<usize>> {
let mut axes: TVec<usize> = match self.axes.as_ref() {
None => Ok((0..input_rank).collect()),
Some(axis) => axis.iter().map(|&a| Self::resolve_axis(a, input_rank)).collect(),
}?;
axes.sort();
Ok(axes)
}
}
impl Expansion for Reduce {
fn name(&self) -> Cow<str> {
format!("Reduce<{:?}>", self.reducer).into()
}
fn info(&self) -> TractResult<Vec<String>> {
Ok(vec![format!("axes: {:?} keep_dims: {}", self.axes, self.keep_dims)])
}
op_hir!();
fn rules<'r, 'p: 'r, 's: 'r>(
&'s self,
s: &mut Solver<'r>,
inputs: &'p [TensorProxy],
outputs: &'p [TensorProxy],
) -> InferenceResult {
check_input_arity(&inputs, 1)?;
check_output_arity(&outputs, 1)?;
if let Reducer::ArgMax(_) | Reducer::ArgMin(_) = self.reducer {
s.equals(&outputs[0].datum_type, DatumType::I64)?;
} else {
s.equals(&inputs[0].datum_type, &outputs[0].datum_type)?;
}
if self.keep_dims {
s.equals(&inputs[0].rank, &outputs[0].rank)?;
} else if let Some(axes) = self.axes.as_ref() {
s.equals(inputs[0].rank.bex() - axes.len() as i64, &outputs[0].rank)?;
} else {
s.equals(&outputs[0].rank, 0)?;
}
s.given(&inputs[0].shape, move |s, shape| {
let out_shape = self.output_shape(&*shape);
s.equals(&outputs[0].shape, out_shape)
})
}
fn wire(
&self,
name: &str,
target: &mut TypedModel,
inputs: &[OutletId],
) -> TractResult<TVec<OutletId>> {
let input = inputs[0];
let fact = target.outlet_fact(input)?;
let mut axes = self.resolve_axes(fact.rank())?;
axes.sort();
let mut wire = self.reducer.wire(axes.clone(), name, target, input)?;
if !self.keep_dims {
for axis in axes.into_iter().rev() {
wire = target.wire_node(
format!("{}-dispose-dims-{}", name, axis),
AxisOp::Rm(axis),
&[wire],
)?[0];
}
}
Ok(tvec!(wire))
}
}