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
use crate::{internal::*, ops::sync_inputs};
use tract_core::model::translator::Translate;
pub type PulsedModel = Graph<PulsedFact, Box<dyn PulsedOp>>;
pub type PulsedNode = Node<PulsedFact, Box<dyn PulsedOp>>;
#[allow(clippy::new_ret_no_self)]
pub trait PulsedModelExt {
fn new(source: &TypedModel, pulse: usize) -> TractResult<PulsedModel>;
fn new_with_mapping(
source: &TypedModel,
pulse: usize,
) -> TractResult<(PulsedModel, HashMap<OutletId, OutletId>)>;
fn into_typed(self) -> TractResult<TypedModel>;
}
impl PulsedModelExt for PulsedModel {
fn new(source: &TypedModel, pulse: usize) -> TractResult<PulsedModel> {
Ok(PulsedModel::new_with_mapping(source, pulse)?.0)
}
fn new_with_mapping(
source: &TypedModel,
pulse: usize,
) -> TractResult<(PulsedModel, HashMap<OutletId, OutletId>)> {
let pulsifiers = crate::ops::OpPulsifier::inventory();
Pulsifier(pulse, pulsifiers).translate_model_with_mappings(source)
}
fn into_typed(self) -> TractResult<TypedModel> {
let mut typed = tract_core::model::translator::IntoTranslator.translate_model(&self)?;
let delays = tensor1(
&self
.output_outlets()?
.iter()
.map(|oo| Ok(self.outlet_fact(*oo)?.delay as _))
.collect::<TractResult<TVec<i64>>>()?,
);
typed.properties.insert("pulse.delay".to_string(), delays.into_arc_tensor());
let input_axes = tensor1(
&self
.input_outlets()?
.iter()
.map(|oo| Ok(self.outlet_fact(*oo)?.axis as _))
.collect::<TractResult<TVec<i64>>>()?,
);
typed.properties.insert("pulse.input_axes".to_string(), input_axes.into_arc_tensor());
let output_axes = tensor1(
&self
.output_outlets()?
.iter()
.map(|oo| Ok(self.outlet_fact(*oo)?.axis as _))
.collect::<TractResult<TVec<i64>>>()?,
);
typed.properties.insert("pulse.output_axes".to_string(), output_axes.into_arc_tensor());
Ok(typed)
}
}
impl SpecialOps<PulsedFact, Box<dyn PulsedOp>> for PulsedModel {
fn is_source(op: &Box<dyn PulsedOp>) -> bool {
op.as_op().downcast_ref::<crate::ops::source::PulsedSource>().is_some()
}
fn create_source(&self, fact: PulsedFact) -> Box<dyn PulsedOp> {
Box::new(crate::ops::source::PulsedSource(fact))
}
fn create_dummy(&self) -> Box<dyn PulsedOp> {
Box::new(tract_core::ops::dummy::Dummy::new())
}
fn wire_node(
&mut self,
name: impl Into<String>,
op: impl Into<Box<dyn PulsedOp>>,
inputs: &[OutletId],
) -> TractResult<TVec<OutletId>> {
let op = op.into();
let output_facts = {
let input_facts =
inputs.iter().map(|o| self.outlet_fact(*o)).collect::<TractResult<TVec<_>>>()?;
op.pulsed_output_facts(&*input_facts)?
};
let id = self.add_node(name, op, output_facts)?;
inputs
.iter()
.enumerate()
.try_for_each(|(ix, i)| self.add_edge(*i, InletId::new(id, ix)))?;
Ok(self.node(id).outputs.iter().enumerate().map(|(ix, _)| OutletId::new(id, ix)).collect())
}
}
struct Pulsifier(usize, HashMap<TypeId, crate::ops::OpPulsifier>);
impl std::fmt::Debug for Pulsifier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Pulsifier({})", self.0)
}
}
impl
tract_core::model::translator::Translate<
TypedFact,
Box<dyn TypedOp>,
PulsedFact,
Box<dyn PulsedOp>,
> for Pulsifier
{
fn translate_node(
&self,
source: &TypedModel,
node: &TypedNode,
target: &mut PulsedModel,
mapping: &HashMap<OutletId, OutletId>,
) -> TractResult<TVec<OutletId>> {
if let Some(pulsifier) = self.1.get(&node.op.type_id()) {
if let Some(pulsified) = (pulsifier.func)(source, node, target, mapping, self.0)? {
return Ok(pulsified);
}
}
let (input_facts, output_facts) = source.node_facts(node.id)?;
if input_facts.len() > 0 {
let invariants = node.op.invariants(&input_facts, &output_facts)?;
let pulse_input_fact = target.outlet_fact(mapping[&node.inputs[0]])?;
let axis_info = invariants.track_input_axis(0, pulse_input_fact.axis);
if axis_info.is_some() {
let pulse_op = PulseWrappingOp(node.op.clone());
let inputs = sync_inputs(node, target, mapping)?;
return target.wire_node(&node.name, pulse_op, &inputs);
}
}
bail!("No pulsifier nor pulsable axis invariant for {}", node);
}
}
#[derive(Debug, Clone, Hash)]
pub(crate) struct PulseWrappingOp(pub Box<dyn TypedOp>);
impl_dyn_hash!(PulseWrappingOp);
impl Op for PulseWrappingOp {
fn name(&self) -> Cow<str> {
format!("PulseWrapping({}", self.0.name()).into()
}
fn as_typed(&self) -> Option<&dyn TypedOp> {
Some(self.0.as_ref())
}
op_pulse!();
}
impl EvalOp for PulseWrappingOp {
fn is_stateless(&self) -> bool {
self.0.is_stateless()
}
fn eval(&self, inputs: TVec<Arc<Tensor>>) -> TractResult<TVec<Arc<Tensor>>> {
self.0.eval(inputs)
}
fn state(
&self,
session: &mut SessionState,
node_id: usize,
) -> TractResult<Option<Box<dyn OpState>>> {
self.0.state(session, node_id)
}
}
impl PulsedOp for PulseWrappingOp {
fn pulsed_output_facts(&self, inputs: &[&PulsedFact]) -> TractResult<TVec<PulsedFact>> {
let input_stream_axis = inputs[0].axis;
let input_facts =
inputs.iter().map(|pf| pf.to_typed_fact()).collect::<TractResult<TVec<_>>>()?;
let input_facts_ref = input_facts.iter().map(|f| f.as_ref()).collect::<TVec<_>>();
let output_facts = self.0.output_facts(&*input_facts_ref)?;
let output_facts_ref = output_facts.iter().collect::<TVec<_>>();
let invariant = self.0.invariants(&input_facts_ref, &output_facts_ref)?;
let axis_info = invariant
.track_input_axis(0, input_stream_axis)
.context("Unable to track pulse axis on PulseWrappingOp")?;
std::mem::forget(output_facts_ref);
output_facts
.into_iter()
.enumerate()
.map(|(ix, tf)| {
Ok(PulsedFact {
shape: tf.shape,
datum_type: tf.datum_type,
delay: inputs[0].delay,
axis: axis_info.outputs[ix].context("Disappearing streaming axis")?,
dim: inputs[0].dim.clone(),
})
})
.collect()
}
as_op!();
fn to_typed(&self) -> Box<dyn TypedOp> {
self.0.clone()
}
}