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.

338 lines
13KB

  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}
  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_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. np.array([self.op2code[node.op], dilation, padding, self.conv_activations[activation], in_channels, out_channels, filter_height], dtype=np.uint32).tofile(f)
  134. kernel.tofile(f)
  135. btensor = bnode.attr['value'].tensor
  136. if btensor.tensor_shape.dim[0].size == 1:
  137. bias = struct.pack("f", btensor.float_val[0])
  138. else:
  139. bias = btensor.tensor_content
  140. f.write(bias)
  141. input_name = self.conv2d_scopename_inputname_dict[scope_name]
  142. input_operand_index = self.add_operand(input_name, Operand.IOTYPE_INPUT)
  143. if anode is not None:
  144. output_operand_index = self.add_operand(anode.name, Operand.IOTYPE_OUTPUT)
  145. else:
  146. output_operand_index = self.add_operand(self.edges[bnode.name][0].name, Operand.IOTYPE_OUTPUT)
  147. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  148. def dump_depth2space_to_file(self, node, f):
  149. assert(node.op == 'DepthToSpace')
  150. self.layer_number = self.layer_number + 1
  151. block_size = node.attr['block_size'].i
  152. np.array([self.op2code[node.op], block_size], dtype=np.uint32).tofile(f)
  153. self.converted_nodes.add(node.name)
  154. input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
  155. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  156. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  157. def dump_mirrorpad_to_file(self, node, f):
  158. assert(node.op == 'MirrorPad')
  159. self.layer_number = self.layer_number + 1
  160. mode = node.attr['mode'].s
  161. mode = self.mirrorpad_mode[mode.decode("utf-8")]
  162. np.array([self.op2code[node.op], mode], dtype=np.uint32).tofile(f)
  163. pnode = self.name_node_dict[node.input[1]]
  164. self.converted_nodes.add(pnode.name)
  165. paddings = pnode.attr['value'].tensor.tensor_content
  166. f.write(paddings)
  167. self.converted_nodes.add(node.name)
  168. input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
  169. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  170. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  171. def dump_layers_to_file(self, f):
  172. for node in self.nodes:
  173. if node.name in self.converted_nodes:
  174. continue
  175. # conv2d with dilation generates very complex nodes, so handle it in special
  176. scope_name = TFConverter.get_scope_name(node.name)
  177. if scope_name in self.conv2d_scope_names:
  178. if node.op == 'Conv2D':
  179. self.dump_conv2d_to_file(node, f)
  180. continue
  181. if node.op == 'DepthToSpace':
  182. self.dump_depth2space_to_file(node, f)
  183. elif node.op == 'MirrorPad':
  184. self.dump_mirrorpad_to_file(node, f)
  185. def dump_operands_to_file(self, f):
  186. operands = sorted(self.name_operand_dict.values())
  187. for operand in operands:
  188. #print('{}'.format(operand))
  189. np.array([operand.index, len(operand.name)], dtype=np.uint32).tofile(f)
  190. f.write(operand.name.encode('utf-8'))
  191. np.array([operand.iotype, operand.dtype], dtype=np.uint32).tofile(f)
  192. np.array([operand.dims[0], operand.dims[1], operand.dims[2], operand.dims[3]], dtype=np.uint32).tofile(f)
  193. def dump_to_file(self):
  194. with open(self.outfile, 'wb') as f:
  195. f.write(header.str.encode('utf-8'))
  196. np.array([header.major, header.minor], dtype=np.uint32).tofile(f)
  197. self.dump_layers_to_file(f)
  198. self.dump_operands_to_file(f)
  199. np.array([self.layer_number, len(self.name_operand_dict)], dtype=np.uint32).tofile(f)
  200. def generate_name_node_dict(self):
  201. for node in self.nodes:
  202. self.name_node_dict[node.name] = node
  203. def generate_output_names(self):
  204. used_names = []
  205. for node in self.nodes:
  206. for input in node.input:
  207. used_names.append(input)
  208. for node in self.nodes:
  209. if node.name not in used_names:
  210. self.output_names.append(node.name)
  211. def remove_identity(self):
  212. id_nodes = []
  213. id_dict = {}
  214. for node in self.nodes:
  215. if node.op == 'Identity':
  216. name = node.name
  217. input = node.input[0]
  218. id_nodes.append(node)
  219. # do not change the output name
  220. if name in self.output_names:
  221. self.name_node_dict[input].name = name
  222. self.name_node_dict[name] = self.name_node_dict[input]
  223. del self.name_node_dict[input]
  224. else:
  225. id_dict[name] = input
  226. for idnode in id_nodes:
  227. self.nodes.remove(idnode)
  228. for node in self.nodes:
  229. for i in range(len(node.input)):
  230. input = node.input[i]
  231. if input in id_dict:
  232. node.input[i] = id_dict[input]
  233. def generate_edges(self):
  234. for node in self.nodes:
  235. for input in node.input:
  236. if input in self.edges:
  237. self.edges[input].append(node)
  238. else:
  239. self.edges[input] = [node]
  240. @staticmethod
  241. def get_scope_name(name):
  242. index = name.rfind('/')
  243. if index == -1:
  244. return ""
  245. return name[0:index]
  246. def generate_conv2d_scope_info(self):
  247. # conv2d is a sub block in graph, get the scope name
  248. for node in self.nodes:
  249. if node.op == 'Conv2D':
  250. scope = TFConverter.get_scope_name(node.name)
  251. self.conv2d_scope_names.add(scope)
  252. # get the input name to the conv2d sub block
  253. for node in self.nodes:
  254. scope = TFConverter.get_scope_name(node.name)
  255. if scope in self.conv2d_scope_names:
  256. if node.op == 'Conv2D' or node.op == 'Shape':
  257. for inp in node.input:
  258. if TFConverter.get_scope_name(inp) != scope:
  259. self.conv2d_scopename_inputname_dict[scope] = inp
  260. def run(self):
  261. self.generate_name_node_dict()
  262. self.generate_output_names()
  263. self.remove_identity()
  264. self.generate_edges()
  265. self.generate_conv2d_scope_info()
  266. if self.dump4tb:
  267. self.dump_for_tensorboard()
  268. self.dump_to_file()
  269. def convert_from_tensorflow(infile, outfile, dump4tb):
  270. with open(infile, 'rb') as f:
  271. # read the file in .proto format
  272. graph_def = tf.GraphDef()
  273. graph_def.ParseFromString(f.read())
  274. nodes = graph_def.node
  275. converter = TFConverter(graph_def, nodes, outfile, dump4tb)
  276. converter.run()