1 # Copyright (c) 2019 Guo Yejun
3 # This file is part of FFmpeg.
5 # FFmpeg is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License, or (at your option) any later version.
10 # FFmpeg is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with FFmpeg; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 # ==============================================================================
20 import tensorflow as tf
23 import convert_header as header
25 __all__ = ['convert_from_tensorflow']
27 class Operand(object):
30 IOTYPE_INTERMEDIATE = IOTYPE_INPUT | IOTYPE_OUTPUT
34 def __init__(self, name, dtype, dims):
40 self.index = Operand.index
41 Operand.index = Operand.index + 1
42 self.iotype2str = {Operand.IOTYPE_INPUT: 'in', Operand.IOTYPE_OUTPUT: 'out', Operand.IOTYPE_INTERMEDIATE: 'inout'}
43 self.dtype2str = {Operand.DTYPE_FLOAT: 'DT_FLOAT', Operand.DTYPE_UINT8: 'DT_UINT8'}
45 def add_iotype(self, iotype):
46 self.iotype = self.iotype | iotype
47 if iotype == Operand.IOTYPE_INPUT:
48 self.used_count = self.used_count + 1
51 return "{}: (name: {}, iotype: {}, dtype: {}, dims: ({},{},{},{}) used_count: {})".format(self.index,
52 self.name, self.iotype2str[self.iotype], self.dtype2str[self.dtype],
53 self.dims[0], self.dims[1], self.dims[2], self.dims[3], self.used_count)
55 def __lt__(self, other):
56 return self.index < other.index
59 def __init__(self, graph_def, nodes, outfile, dump4tb):
60 self.graph_def = graph_def
62 self.outfile = outfile
63 self.dump4tb = dump4tb
65 self.output_names = []
66 self.name_node_dict = {}
68 self.conv_activations = {'Relu':0, 'Tanh':1, 'Sigmoid':2, 'None':3, 'LeakyRelu':4}
69 self.conv_paddings = {'VALID':0, 'SAME':1}
70 self.converted_nodes = set()
71 self.conv2d_scope_names = set()
72 self.conv2d_scopename_inputname_dict = {}
73 self.op2code = {'Conv2D':1, 'DepthToSpace':2, 'MirrorPad':3}
74 self.mirrorpad_mode = {'CONSTANT':0, 'REFLECT':1, 'SYMMETRIC':2}
75 self.name_operand_dict = {}
78 def add_operand(self, name, type):
79 node = self.name_node_dict[name]
80 if name not in self.name_operand_dict:
81 dtype = node.attr['dtype'].type
83 dtype = node.attr['T'].type
85 if 'shape' in node.attr:
86 dims[0] = node.attr['shape'].shape.dim[0].size
87 dims[1] = node.attr['shape'].shape.dim[1].size
88 dims[2] = node.attr['shape'].shape.dim[2].size
89 dims[3] = node.attr['shape'].shape.dim[3].size
90 operand = Operand(name, dtype, dims)
91 self.name_operand_dict[name] = operand;
92 self.name_operand_dict[name].add_iotype(type)
93 return self.name_operand_dict[name].index
96 def dump_for_tensorboard(self):
97 graph = tf.get_default_graph()
98 tf.import_graph_def(self.graph_def, name="")
99 tf.summary.FileWriter('/tmp/graph', graph)
100 print('graph saved, run "tensorboard --logdir=/tmp/graph" to see it')
103 def get_conv2d_params(self, conv2d_scope_name):
104 knode = self.name_node_dict[conv2d_scope_name + '/kernel']
105 bnode = self.name_node_dict[conv2d_scope_name + '/bias']
107 if conv2d_scope_name + '/dilation_rate' in self.name_node_dict:
108 dnode = self.name_node_dict[conv2d_scope_name + '/dilation_rate']
112 # the BiasAdd name is possible be changed into the output name,
113 # if activation is None, and BiasAdd.next is the last op which is Identity
114 if conv2d_scope_name + '/BiasAdd' in self.edges:
115 anode = self.edges[conv2d_scope_name + '/BiasAdd'][0]
118 return knode, bnode, dnode, anode
121 def dump_conv2d_to_file(self, node, f):
122 assert(node.op == 'Conv2D')
123 self.layer_number = self.layer_number + 1
124 self.converted_nodes.add(node.name)
126 scope_name = TFConverter.get_scope_name(node.name)
127 #knode for kernel, bnode for bias, dnode for dilation, anode for activation
128 knode, bnode, dnode, anode = self.get_conv2d_params(scope_name)
130 if dnode is not None:
131 dilation = struct.unpack('i', dnode.attr['value'].tensor.tensor_content[0:4])[0]
135 if anode is not None:
136 activation = anode.op
140 padding = node.attr['padding'].s.decode("utf-8")
141 # conv2d with dilation > 1 generates tens of nodes, not easy to parse them, so use this tricky method.
142 if dilation > 1 and scope_name + '/stack' in self.name_node_dict:
143 if self.name_node_dict[scope_name + '/stack'].op == "Const":
145 padding = self.conv_paddings[padding]
147 ktensor = knode.attr['value'].tensor
148 filter_height = ktensor.tensor_shape.dim[0].size
149 filter_width = ktensor.tensor_shape.dim[1].size
150 in_channels = ktensor.tensor_shape.dim[2].size
151 out_channels = ktensor.tensor_shape.dim[3].size
152 kernel = np.frombuffer(ktensor.tensor_content, dtype=np.float32)
153 kernel = kernel.reshape(filter_height, filter_width, in_channels, out_channels)
154 kernel = np.transpose(kernel, [3, 0, 1, 2])
156 np.array([self.op2code[node.op], dilation, padding, self.conv_activations[activation], in_channels, out_channels, filter_height], dtype=np.uint32).tofile(f)
159 btensor = bnode.attr['value'].tensor
160 if btensor.tensor_shape.dim[0].size == 1:
161 bias = struct.pack("f", btensor.float_val[0])
163 bias = btensor.tensor_content
166 input_name = self.conv2d_scopename_inputname_dict[scope_name]
167 input_operand_index = self.add_operand(input_name, Operand.IOTYPE_INPUT)
169 if anode is not None:
170 output_operand_index = self.add_operand(anode.name, Operand.IOTYPE_OUTPUT)
172 output_operand_index = self.add_operand(self.edges[bnode.name][0].name, Operand.IOTYPE_OUTPUT)
173 np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
176 def dump_depth2space_to_file(self, node, f):
177 assert(node.op == 'DepthToSpace')
178 self.layer_number = self.layer_number + 1
179 block_size = node.attr['block_size'].i
180 np.array([self.op2code[node.op], block_size], dtype=np.uint32).tofile(f)
181 self.converted_nodes.add(node.name)
182 input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
183 output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
184 np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
187 def dump_mirrorpad_to_file(self, node, f):
188 assert(node.op == 'MirrorPad')
189 self.layer_number = self.layer_number + 1
190 mode = node.attr['mode'].s
191 mode = self.mirrorpad_mode[mode.decode("utf-8")]
192 np.array([self.op2code[node.op], mode], dtype=np.uint32).tofile(f)
193 pnode = self.name_node_dict[node.input[1]]
194 self.converted_nodes.add(pnode.name)
195 paddings = pnode.attr['value'].tensor.tensor_content
197 self.converted_nodes.add(node.name)
198 input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
199 output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
200 np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
203 def dump_layers_to_file(self, f):
204 for node in self.nodes:
205 if node.name in self.converted_nodes:
208 # conv2d with dilation generates very complex nodes, so handle it in special
209 scope_name = TFConverter.get_scope_name(node.name)
210 if scope_name in self.conv2d_scope_names:
211 if node.op == 'Conv2D':
212 self.dump_conv2d_to_file(node, f)
215 if node.op == 'DepthToSpace':
216 self.dump_depth2space_to_file(node, f)
217 elif node.op == 'MirrorPad':
218 self.dump_mirrorpad_to_file(node, f)
221 def dump_operands_to_file(self, f):
222 operands = sorted(self.name_operand_dict.values())
223 for operand in operands:
224 #print('{}'.format(operand))
225 np.array([operand.index, len(operand.name)], dtype=np.uint32).tofile(f)
226 f.write(operand.name.encode('utf-8'))
227 np.array([operand.iotype, operand.dtype], dtype=np.uint32).tofile(f)
228 np.array([operand.dims[0], operand.dims[1], operand.dims[2], operand.dims[3]], dtype=np.uint32).tofile(f)
231 def dump_to_file(self):
232 with open(self.outfile, 'wb') as f:
233 f.write(header.str.encode('utf-8'))
234 np.array([header.major, header.minor], dtype=np.uint32).tofile(f)
235 self.dump_layers_to_file(f)
236 self.dump_operands_to_file(f)
237 np.array([self.layer_number, len(self.name_operand_dict)], dtype=np.uint32).tofile(f)
240 def generate_name_node_dict(self):
241 for node in self.nodes:
242 self.name_node_dict[node.name] = node
245 def generate_output_names(self):
247 for node in self.nodes:
248 for input in node.input:
249 used_names.append(input)
251 for node in self.nodes:
252 if node.name not in used_names:
253 self.output_names.append(node.name)
256 def remove_identity(self):
259 for node in self.nodes:
260 if node.op == 'Identity':
262 input = node.input[0]
263 id_nodes.append(node)
264 # do not change the output name
265 if name in self.output_names:
266 self.name_node_dict[input].name = name
267 self.name_node_dict[name] = self.name_node_dict[input]
268 del self.name_node_dict[input]
270 id_dict[name] = input
272 for idnode in id_nodes:
273 self.nodes.remove(idnode)
275 for node in self.nodes:
276 for i in range(len(node.input)):
277 input = node.input[i]
279 node.input[i] = id_dict[input]
282 def generate_edges(self):
283 for node in self.nodes:
284 for input in node.input:
285 if input in self.edges:
286 self.edges[input].append(node)
288 self.edges[input] = [node]
292 def get_scope_name(name):
293 index = name.rfind('/')
299 def generate_conv2d_scope_info(self):
300 # conv2d is a sub block in graph, get the scope name
301 for node in self.nodes:
302 if node.op == 'Conv2D':
303 scope = TFConverter.get_scope_name(node.name)
304 self.conv2d_scope_names.add(scope)
306 # get the input name to the conv2d sub block
307 for node in self.nodes:
308 scope = TFConverter.get_scope_name(node.name)
309 if scope in self.conv2d_scope_names:
310 if node.op == 'Conv2D' or node.op == 'Shape':
311 for inp in node.input:
312 if TFConverter.get_scope_name(inp) != scope:
313 self.conv2d_scopename_inputname_dict[scope] = inp
317 self.generate_name_node_dict()
318 self.generate_output_names()
319 self.remove_identity()
320 self.generate_edges()
321 self.generate_conv2d_scope_info()
324 self.dump_for_tensorboard()
329 def convert_from_tensorflow(infile, outfile, dump4tb):
330 with open(infile, 'rb') as f:
331 # read the file in .proto format
332 graph_def = tf.GraphDef()
333 graph_def.ParseFromString(f.read())
334 nodes = graph_def.node
336 converter = TFConverter(graph_def, nodes, outfile, dump4tb)