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
use crate::tfpb::graph::GraphDef;
use crate::tfpb::node_def::NodeDef;
use tract_core::internal::*;
#[derive(Default)]
pub struct ParsingContext {
pub node_output_arities: HashMap<String, usize>,
}
#[derive(Clone, Default)]
pub struct TfOpRegister(
pub HashMap<String, fn(&ParsingContext, node: &NodeDef) -> TractResult<Box<dyn InferenceOp>>>,
);
impl TfOpRegister {
pub fn insert(
&mut self,
s: &'static str,
builder: fn(&ParsingContext, node: &NodeDef) -> TractResult<Box<dyn InferenceOp>>,
) {
self.0.insert(s.into(), builder);
}
}
pub struct Tensorflow {
pub op_register: TfOpRegister,
}
impl Tensorflow {
fn parse_input(i: &str) -> TractResult<(&str, usize)> {
let pair = if i.starts_with("^") {
(&i[1..], 0)
} else {
let splits: Vec<_> = i.splitn(2, ':').collect();
(splits[0], if splits.len() > 1 { splits[1].parse::<usize>()? } else { 0 })
};
Ok(pair)
}
pub fn determinize(model: &mut GraphDef) -> TractResult<()> {
for pbnode in model.mut_node().iter_mut() {
if pbnode.get_op() == "RandomUniform" {
if pbnode.get_attr_int::<i64>("seed")? == 0
&& pbnode.get_attr_int::<i64>("seed2")? == 0
{
pbnode.mut_attr().insert("seed".to_string(), 1.into());
pbnode.mut_attr().insert("seed2".to_string(), 1.into());
}
}
}
Ok(())
}
}
impl Framework<GraphDef> for Tensorflow {
fn proto_model_for_read(&self, r: &mut dyn std::io::Read) -> TractResult<GraphDef> {
Ok(::protobuf::parse_from_reader::<GraphDef>(r).map_err(|e| format!("{:?}", e))?)
}
fn model_for_proto_model(&self, graph: &GraphDef) -> TractResult<InferenceModel> {
use crate::ops::control_flow as cf;
let mut model = InferenceModel::default();
let mut inputs = tvec!();
let mut context = ParsingContext::default();
for pbnode in graph.get_node().iter() {
for i in pbnode.get_input().iter() {
let (node, slot) = Self::parse_input(i)?;
let arity = context.node_output_arities.entry(node.to_string()).or_insert(1);
*arity = (*arity).max(slot + 1);
}
}
for pbnode in graph.get_node().iter() {
let name = pbnode.get_name().to_string();
let output_arity = context.node_output_arities.get(&*name).cloned().unwrap_or(1);
let facts = tvec!(InferenceFact::default(); output_arity);
if pbnode.get_op() == "NextIteration" {
let source_op = cf::NextIteration::new(name.clone(), cf::NextIterationRole::Source);
let sink_op = cf::NextIteration::new(name.clone(), cf::NextIterationRole::Sink);
let _source =
model.add_node(name.clone(), source_op, tvec!(InferenceFact::default()))?;
let _sink = model.add_node(format!("{}-Sink", name), sink_op, tvec!())?;
continue;
}
let op = match self.op_register.0.get(pbnode.get_op()) {
Some(builder) => (builder)(&context, pbnode)?,
None => tract_core::ops::unimpl::UnimplementedOp::new(
pbnode.get_op(),
format!("{:?}", pbnode),
)
.into(),
};
let node_id = model.add_node(name.clone(), op, facts)?;
if pbnode.get_op() == "Placeholder" {
let dt = pbnode.get_attr_datum_type("dtype")?;
let mut fact = InferenceFact::dt(dt);
if let Some(shape) = pbnode.get_attr_opt_shape("shape")? {
let shape_fact = ShapeFact::closed(
shape
.iter()
.map(|d| {
if *d == -1 {
GenericFact::Any
} else {
GenericFact::Only(d.to_dim())
}
})
.collect(),
);
fact = fact.with_shape(shape_fact);
}
inputs.push(OutletId::new(node_id, 0));
model.set_outlet_fact(OutletId::new(node_id, 0), fact)?;
}
}
for pbnode in graph.get_node().iter() {
let node_id = if pbnode.get_op() == "NextIteration" {
model.node_by_name(&*format!("{}-Sink", pbnode.get_name()))?.id
} else {
model.node_by_name(pbnode.get_name())?.id
};
for (ix, i) in pbnode.get_input().iter().enumerate() {
let input = Self::parse_input(i)?;
let prec = model.node_by_name(input.0)?.id;
if i.starts_with("^") {
model.node_mut(node_id).control_inputs.push(prec);
} else {
let outlet = OutletId::new(prec, input.1);
let inlet = InletId::new(node_id, ix);
model.add_edge(outlet, inlet)?;
model.set_outlet_label(outlet, i.to_string());
}
}
}
for id in 0..model.nodes().len() {
use crate::ops::vars::*;
if model.node(id).op_is::<Assign>() {
let prec = model.node(id).inputs[0];
let var_id = model.node(prec.node).op_as::<VariableV2>().map(|v| v.id.clone());
if let (Some(var_id), Some(assign)) =
(var_id, model.node_mut(id).op_as_mut::<Assign>())
{
assign.var_id = Some(var_id);
} else {
bail!("Model contains unlinked Assign/Variable2");
}
}
}
model.set_input_outlets(&*inputs)?;
model.auto_outputs()?;
Ok(model)
}
}