You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

397 lines
16KB

  1. # Copyright (c) 2019 Guo Yejun
  2. #
  3. # This file is part of FFmpeg.
  4. #
  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.
  9. #
  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.
  14. #
  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. # ==============================================================================
  19. import tensorflow as tf
  20. import numpy as np
  21. import sys, struct
  22. import convert_header as header
  23. __all__ = ['convert_from_tensorflow']
  24. class Operand(object):
  25. IOTYPE_INPUT = 1
  26. IOTYPE_OUTPUT = 2
  27. IOTYPE_INTERMEDIATE = IOTYPE_INPUT | IOTYPE_OUTPUT
  28. DTYPE_FLOAT = 1
  29. DTYPE_UINT8 = 4
  30. index = 0
  31. def __init__(self, name, dtype, dims):
  32. self.name = name
  33. self.dtype = dtype
  34. self.dims = dims
  35. self.iotype = 0
  36. self.used_count = 0
  37. self.index = Operand.index
  38. Operand.index = Operand.index + 1
  39. self.iotype2str = {Operand.IOTYPE_INPUT: 'in', Operand.IOTYPE_OUTPUT: 'out', Operand.IOTYPE_INTERMEDIATE: 'inout'}
  40. self.dtype2str = {Operand.DTYPE_FLOAT: 'DT_FLOAT', Operand.DTYPE_UINT8: 'DT_UINT8'}
  41. def add_iotype(self, iotype):
  42. self.iotype = self.iotype | iotype
  43. if iotype == Operand.IOTYPE_INPUT:
  44. self.used_count = self.used_count + 1
  45. def __str__(self):
  46. return "{}: (name: {}, iotype: {}, dtype: {}, dims: ({},{},{},{}) used_count: {})".format(self.index,
  47. self.name, self.iotype2str[self.iotype], self.dtype2str[self.dtype],
  48. self.dims[0], self.dims[1], self.dims[2], self.dims[3], self.used_count)
  49. def __lt__(self, other):
  50. return self.index < other.index
  51. class TFConverter:
  52. def __init__(self, graph_def, nodes, outfile, dump4tb):
  53. self.graph_def = graph_def
  54. self.nodes = nodes
  55. self.outfile = outfile
  56. self.dump4tb = dump4tb
  57. self.layer_number = 0
  58. self.output_names = []
  59. self.name_node_dict = {}
  60. self.edges = {}
  61. self.conv_activations = {'Relu':0, 'Tanh':1, 'Sigmoid':2, 'None':3, 'LeakyRelu':4}
  62. self.conv_paddings = {'VALID':0, 'SAME':1}
  63. self.converted_nodes = set()
  64. self.conv2d_scope_names = set()
  65. self.conv2d_scopename_inputname_dict = {}
  66. self.op2code = {'Conv2D':1, 'DepthToSpace':2, 'MirrorPad':3, 'Maximum':4}
  67. self.mirrorpad_mode = {'CONSTANT':0, 'REFLECT':1, 'SYMMETRIC':2}
  68. self.name_operand_dict = {}
  69. def add_operand(self, name, type):
  70. node = self.name_node_dict[name]
  71. if name not in self.name_operand_dict:
  72. dtype = node.attr['dtype'].type
  73. if dtype == 0:
  74. dtype = node.attr['T'].type
  75. dims = [-1,-1,-1,-1]
  76. if 'shape' in node.attr:
  77. dims[0] = node.attr['shape'].shape.dim[0].size
  78. dims[1] = node.attr['shape'].shape.dim[1].size
  79. dims[2] = node.attr['shape'].shape.dim[2].size
  80. dims[3] = node.attr['shape'].shape.dim[3].size
  81. operand = Operand(name, dtype, dims)
  82. self.name_operand_dict[name] = operand;
  83. self.name_operand_dict[name].add_iotype(type)
  84. return self.name_operand_dict[name].index
  85. def dump_for_tensorboard(self):
  86. graph = tf.get_default_graph()
  87. tf.import_graph_def(self.graph_def, name="")
  88. tf.summary.FileWriter('/tmp/graph', graph)
  89. print('graph saved, run "tensorboard --logdir=/tmp/graph" to see it')
  90. def get_conv2d_params(self, conv2d_scope_name):
  91. knode = self.name_node_dict[conv2d_scope_name + '/kernel']
  92. bnode = self.name_node_dict[conv2d_scope_name + '/bias']
  93. if conv2d_scope_name + '/dilation_rate' in self.name_node_dict:
  94. dnode = self.name_node_dict[conv2d_scope_name + '/dilation_rate']
  95. else:
  96. dnode = None
  97. # the BiasAdd name is possible be changed into the output name,
  98. # if activation is None, and BiasAdd.next is the last op which is Identity
  99. if conv2d_scope_name + '/BiasAdd' in self.edges:
  100. anode = self.edges[conv2d_scope_name + '/BiasAdd'][0]
  101. else:
  102. anode = None
  103. return knode, bnode, dnode, anode
  104. def dump_complex_conv2d_to_file(self, node, f):
  105. assert(node.op == 'Conv2D')
  106. self.layer_number = self.layer_number + 1
  107. self.converted_nodes.add(node.name)
  108. scope_name = TFConverter.get_scope_name(node.name)
  109. #knode for kernel, bnode for bias, dnode for dilation, anode for activation
  110. knode, bnode, dnode, anode = self.get_conv2d_params(scope_name)
  111. if dnode is not None:
  112. dilation = struct.unpack('i', dnode.attr['value'].tensor.tensor_content[0:4])[0]
  113. else:
  114. dilation = 1
  115. if anode is not None:
  116. activation = anode.op
  117. else:
  118. activation = 'None'
  119. padding = node.attr['padding'].s.decode("utf-8")
  120. # conv2d with dilation > 1 generates tens of nodes, not easy to parse them, so use this tricky method.
  121. if dilation > 1 and scope_name + '/stack' in self.name_node_dict:
  122. if self.name_node_dict[scope_name + '/stack'].op == "Const":
  123. padding = 'SAME'
  124. padding = self.conv_paddings[padding]
  125. ktensor = knode.attr['value'].tensor
  126. filter_height = ktensor.tensor_shape.dim[0].size
  127. filter_width = ktensor.tensor_shape.dim[1].size
  128. in_channels = ktensor.tensor_shape.dim[2].size
  129. out_channels = ktensor.tensor_shape.dim[3].size
  130. kernel = np.frombuffer(ktensor.tensor_content, dtype=np.float32)
  131. kernel = kernel.reshape(filter_height, filter_width, in_channels, out_channels)
  132. kernel = np.transpose(kernel, [3, 0, 1, 2])
  133. has_bias = 1
  134. np.array([self.op2code[node.op], dilation, padding, self.conv_activations[activation], in_channels, out_channels, filter_height, has_bias], dtype=np.uint32).tofile(f)
  135. kernel.tofile(f)
  136. btensor = bnode.attr['value'].tensor
  137. if btensor.tensor_shape.dim[0].size == 1:
  138. bias = struct.pack("f", btensor.float_val[0])
  139. else:
  140. bias = btensor.tensor_content
  141. f.write(bias)
  142. input_name = self.conv2d_scopename_inputname_dict[scope_name]
  143. input_operand_index = self.add_operand(input_name, Operand.IOTYPE_INPUT)
  144. if anode is not None:
  145. output_operand_index = self.add_operand(anode.name, Operand.IOTYPE_OUTPUT)
  146. else:
  147. output_operand_index = self.add_operand(self.edges[bnode.name][0].name, Operand.IOTYPE_OUTPUT)
  148. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  149. def dump_simple_conv2d_to_file(self, node, f):
  150. assert(node.op == 'Conv2D')
  151. self.layer_number = self.layer_number + 1
  152. self.converted_nodes.add(node.name)
  153. node0 = self.name_node_dict[node.input[0]]
  154. node1 = self.name_node_dict[node.input[1]]
  155. if node0.op == 'Const':
  156. knode = node0
  157. input_name = node.input[1]
  158. else:
  159. knode = node1
  160. input_name = node.input[0]
  161. ktensor = knode.attr['value'].tensor
  162. filter_height = ktensor.tensor_shape.dim[0].size
  163. filter_width = ktensor.tensor_shape.dim[1].size
  164. in_channels = ktensor.tensor_shape.dim[2].size
  165. out_channels = ktensor.tensor_shape.dim[3].size
  166. kernel = np.frombuffer(ktensor.tensor_content, dtype=np.float32)
  167. kernel = kernel.reshape(filter_height, filter_width, in_channels, out_channels)
  168. kernel = np.transpose(kernel, [3, 0, 1, 2])
  169. has_bias = 0
  170. dilation = 1
  171. padding = node.attr['padding'].s.decode("utf-8")
  172. np.array([self.op2code[node.op], dilation, self.conv_paddings[padding], self.conv_activations['None'],
  173. in_channels, out_channels, filter_height, has_bias], dtype=np.uint32).tofile(f)
  174. kernel.tofile(f)
  175. input_operand_index = self.add_operand(input_name, Operand.IOTYPE_INPUT)
  176. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  177. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  178. def dump_depth2space_to_file(self, node, f):
  179. assert(node.op == 'DepthToSpace')
  180. self.layer_number = self.layer_number + 1
  181. block_size = node.attr['block_size'].i
  182. np.array([self.op2code[node.op], block_size], dtype=np.uint32).tofile(f)
  183. self.converted_nodes.add(node.name)
  184. input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
  185. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  186. 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
  196. f.write(paddings)
  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)
  201. def dump_maximum_to_file(self, node, f):
  202. assert(node.op == 'Maximum')
  203. self.layer_number = self.layer_number + 1
  204. ynode = self.name_node_dict[node.input[1]]
  205. y = ynode.attr['value'].tensor.float_val[0]
  206. np.array([self.op2code[node.op]], dtype=np.uint32).tofile(f)
  207. np.array([y], dtype=np.float32).tofile(f)
  208. self.converted_nodes.add(node.name)
  209. input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
  210. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  211. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  212. def dump_layers_to_file(self, f):
  213. for node in self.nodes:
  214. if node.name in self.converted_nodes:
  215. continue
  216. # conv2d with dilation generates very complex nodes, so handle it in special
  217. scope_name = TFConverter.get_scope_name(node.name)
  218. if scope_name in self.conv2d_scope_names:
  219. if node.op == 'Conv2D':
  220. self.dump_complex_conv2d_to_file(node, f)
  221. continue
  222. if node.op == 'Conv2D':
  223. self.dump_simple_conv2d_to_file(node, f)
  224. elif node.op == 'DepthToSpace':
  225. self.dump_depth2space_to_file(node, f)
  226. elif node.op == 'MirrorPad':
  227. self.dump_mirrorpad_to_file(node, f)
  228. elif node.op == 'Maximum':
  229. self.dump_maximum_to_file(node, f)
  230. def dump_operands_to_file(self, f):
  231. operands = sorted(self.name_operand_dict.values())
  232. for operand in operands:
  233. #print('{}'.format(operand))
  234. np.array([operand.index, len(operand.name)], dtype=np.uint32).tofile(f)
  235. f.write(operand.name.encode('utf-8'))
  236. np.array([operand.iotype, operand.dtype], dtype=np.uint32).tofile(f)
  237. np.array([operand.dims[0], operand.dims[1], operand.dims[2], operand.dims[3]], dtype=np.uint32).tofile(f)
  238. def dump_to_file(self):
  239. with open(self.outfile, 'wb') as f:
  240. f.write(header.str.encode('utf-8'))
  241. np.array([header.major, header.minor], dtype=np.uint32).tofile(f)
  242. self.dump_layers_to_file(f)
  243. self.dump_operands_to_file(f)
  244. np.array([self.layer_number, len(self.name_operand_dict)], dtype=np.uint32).tofile(f)
  245. def generate_name_node_dict(self):
  246. for node in self.nodes:
  247. self.name_node_dict[node.name] = node
  248. def generate_output_names(self):
  249. used_names = []
  250. for node in self.nodes:
  251. for input in node.input:
  252. used_names.append(input)
  253. for node in self.nodes:
  254. if node.name not in used_names:
  255. self.output_names.append(node.name)
  256. def remove_identity(self):
  257. id_nodes = []
  258. id_dict = {}
  259. for node in self.nodes:
  260. if node.op == 'Identity':
  261. name = node.name
  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]
  269. else:
  270. id_dict[name] = input
  271. for idnode in id_nodes:
  272. self.nodes.remove(idnode)
  273. for node in self.nodes:
  274. for i in range(len(node.input)):
  275. input = node.input[i]
  276. if input in id_dict:
  277. node.input[i] = id_dict[input]
  278. def generate_edges(self):
  279. for node in self.nodes:
  280. for input in node.input:
  281. if input in self.edges:
  282. self.edges[input].append(node)
  283. else:
  284. self.edges[input] = [node]
  285. @staticmethod
  286. def get_scope_name(name):
  287. index = name.rfind('/')
  288. if index == -1:
  289. return ""
  290. return name[0:index]
  291. def generate_conv2d_scope_info(self):
  292. # mostly, conv2d is a sub block in graph, get the scope name
  293. for node in self.nodes:
  294. if node.op == 'Conv2D':
  295. scope = TFConverter.get_scope_name(node.name)
  296. # for the case tf.nn.conv2d is called directly
  297. if scope == '':
  298. continue
  299. # for the case tf.nn.conv2d is called within a scope
  300. if scope + '/kernel' not in self.name_node_dict:
  301. continue
  302. self.conv2d_scope_names.add(scope)
  303. # get the input name to the conv2d sub block
  304. for node in self.nodes:
  305. scope = TFConverter.get_scope_name(node.name)
  306. if scope in self.conv2d_scope_names:
  307. if node.op == 'Conv2D' or node.op == 'Shape':
  308. for inp in node.input:
  309. if TFConverter.get_scope_name(inp) != scope:
  310. self.conv2d_scopename_inputname_dict[scope] = inp
  311. def run(self):
  312. self.generate_name_node_dict()
  313. self.generate_output_names()
  314. self.remove_identity()
  315. self.generate_edges()
  316. self.generate_conv2d_scope_info()
  317. if self.dump4tb:
  318. self.dump_for_tensorboard()
  319. self.dump_to_file()
  320. def convert_from_tensorflow(infile, outfile, dump4tb):
  321. with open(infile, 'rb') as f:
  322. # read the file in .proto format
  323. graph_def = tf.GraphDef()
  324. graph_def.ParseFromString(f.read())
  325. nodes = graph_def.node
  326. converter = TFConverter(graph_def, nodes, outfile, dump4tb)
  327. converter.run()