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.

353 lines
14KB

  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_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_maximum_to_file(self, node, f):
  172. assert(node.op == 'Maximum')
  173. self.layer_number = self.layer_number + 1
  174. ynode = self.name_node_dict[node.input[1]]
  175. y = ynode.attr['value'].tensor.float_val[0]
  176. np.array([self.op2code[node.op]], dtype=np.uint32).tofile(f)
  177. np.array([y], dtype=np.float32).tofile(f)
  178. self.converted_nodes.add(node.name)
  179. input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
  180. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  181. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  182. def dump_layers_to_file(self, f):
  183. for node in self.nodes:
  184. if node.name in self.converted_nodes:
  185. continue
  186. # conv2d with dilation generates very complex nodes, so handle it in special
  187. scope_name = TFConverter.get_scope_name(node.name)
  188. if scope_name in self.conv2d_scope_names:
  189. if node.op == 'Conv2D':
  190. self.dump_conv2d_to_file(node, f)
  191. continue
  192. if node.op == 'DepthToSpace':
  193. self.dump_depth2space_to_file(node, f)
  194. elif node.op == 'MirrorPad':
  195. self.dump_mirrorpad_to_file(node, f)
  196. elif node.op == 'Maximum':
  197. self.dump_maximum_to_file(node, f)
  198. def dump_operands_to_file(self, f):
  199. operands = sorted(self.name_operand_dict.values())
  200. for operand in operands:
  201. #print('{}'.format(operand))
  202. np.array([operand.index, len(operand.name)], dtype=np.uint32).tofile(f)
  203. f.write(operand.name.encode('utf-8'))
  204. np.array([operand.iotype, operand.dtype], dtype=np.uint32).tofile(f)
  205. np.array([operand.dims[0], operand.dims[1], operand.dims[2], operand.dims[3]], dtype=np.uint32).tofile(f)
  206. def dump_to_file(self):
  207. with open(self.outfile, 'wb') as f:
  208. f.write(header.str.encode('utf-8'))
  209. np.array([header.major, header.minor], dtype=np.uint32).tofile(f)
  210. self.dump_layers_to_file(f)
  211. self.dump_operands_to_file(f)
  212. np.array([self.layer_number, len(self.name_operand_dict)], dtype=np.uint32).tofile(f)
  213. def generate_name_node_dict(self):
  214. for node in self.nodes:
  215. self.name_node_dict[node.name] = node
  216. def generate_output_names(self):
  217. used_names = []
  218. for node in self.nodes:
  219. for input in node.input:
  220. used_names.append(input)
  221. for node in self.nodes:
  222. if node.name not in used_names:
  223. self.output_names.append(node.name)
  224. def remove_identity(self):
  225. id_nodes = []
  226. id_dict = {}
  227. for node in self.nodes:
  228. if node.op == 'Identity':
  229. name = node.name
  230. input = node.input[0]
  231. id_nodes.append(node)
  232. # do not change the output name
  233. if name in self.output_names:
  234. self.name_node_dict[input].name = name
  235. self.name_node_dict[name] = self.name_node_dict[input]
  236. del self.name_node_dict[input]
  237. else:
  238. id_dict[name] = input
  239. for idnode in id_nodes:
  240. self.nodes.remove(idnode)
  241. for node in self.nodes:
  242. for i in range(len(node.input)):
  243. input = node.input[i]
  244. if input in id_dict:
  245. node.input[i] = id_dict[input]
  246. def generate_edges(self):
  247. for node in self.nodes:
  248. for input in node.input:
  249. if input in self.edges:
  250. self.edges[input].append(node)
  251. else:
  252. self.edges[input] = [node]
  253. @staticmethod
  254. def get_scope_name(name):
  255. index = name.rfind('/')
  256. if index == -1:
  257. return ""
  258. return name[0:index]
  259. def generate_conv2d_scope_info(self):
  260. # conv2d is a sub block in graph, get the scope name
  261. for node in self.nodes:
  262. if node.op == 'Conv2D':
  263. scope = TFConverter.get_scope_name(node.name)
  264. self.conv2d_scope_names.add(scope)
  265. # get the input name to the conv2d sub block
  266. for node in self.nodes:
  267. scope = TFConverter.get_scope_name(node.name)
  268. if scope in self.conv2d_scope_names:
  269. if node.op == 'Conv2D' or node.op == 'Shape':
  270. for inp in node.input:
  271. if TFConverter.get_scope_name(inp) != scope:
  272. self.conv2d_scopename_inputname_dict[scope] = inp
  273. def run(self):
  274. self.generate_name_node_dict()
  275. self.generate_output_names()
  276. self.remove_identity()
  277. self.generate_edges()
  278. self.generate_conv2d_scope_info()
  279. if self.dump4tb:
  280. self.dump_for_tensorboard()
  281. self.dump_to_file()
  282. def convert_from_tensorflow(infile, outfile, dump4tb):
  283. with open(infile, 'rb') as f:
  284. # read the file in .proto format
  285. graph_def = tf.GraphDef()
  286. graph_def.ParseFromString(f.read())
  287. nodes = graph_def.node
  288. converter = TFConverter(graph_def, nodes, outfile, dump4tb)
  289. converter.run()