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.

400 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. if filter_height * filter_width * in_channels * out_channels == 1:
  167. kernel = np.float32(ktensor.float_val[0])
  168. else:
  169. kernel = np.frombuffer(ktensor.tensor_content, dtype=np.float32)
  170. kernel = kernel.reshape(filter_height, filter_width, in_channels, out_channels)
  171. kernel = np.transpose(kernel, [3, 0, 1, 2])
  172. has_bias = 0
  173. dilation = 1
  174. padding = node.attr['padding'].s.decode("utf-8")
  175. np.array([self.op2code[node.op], dilation, self.conv_paddings[padding], self.conv_activations['None'],
  176. in_channels, out_channels, filter_height, has_bias], dtype=np.uint32).tofile(f)
  177. kernel.tofile(f)
  178. input_operand_index = self.add_operand(input_name, Operand.IOTYPE_INPUT)
  179. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  180. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  181. def dump_depth2space_to_file(self, node, f):
  182. assert(node.op == 'DepthToSpace')
  183. self.layer_number = self.layer_number + 1
  184. block_size = node.attr['block_size'].i
  185. np.array([self.op2code[node.op], block_size], dtype=np.uint32).tofile(f)
  186. self.converted_nodes.add(node.name)
  187. input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
  188. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  189. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  190. def dump_mirrorpad_to_file(self, node, f):
  191. assert(node.op == 'MirrorPad')
  192. self.layer_number = self.layer_number + 1
  193. mode = node.attr['mode'].s
  194. mode = self.mirrorpad_mode[mode.decode("utf-8")]
  195. np.array([self.op2code[node.op], mode], dtype=np.uint32).tofile(f)
  196. pnode = self.name_node_dict[node.input[1]]
  197. self.converted_nodes.add(pnode.name)
  198. paddings = pnode.attr['value'].tensor.tensor_content
  199. f.write(paddings)
  200. self.converted_nodes.add(node.name)
  201. input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
  202. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  203. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  204. def dump_maximum_to_file(self, node, f):
  205. assert(node.op == 'Maximum')
  206. self.layer_number = self.layer_number + 1
  207. ynode = self.name_node_dict[node.input[1]]
  208. y = ynode.attr['value'].tensor.float_val[0]
  209. np.array([self.op2code[node.op]], dtype=np.uint32).tofile(f)
  210. np.array([y], dtype=np.float32).tofile(f)
  211. self.converted_nodes.add(node.name)
  212. input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
  213. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  214. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  215. def dump_layers_to_file(self, f):
  216. for node in self.nodes:
  217. if node.name in self.converted_nodes:
  218. continue
  219. # conv2d with dilation generates very complex nodes, so handle it in special
  220. scope_name = TFConverter.get_scope_name(node.name)
  221. if scope_name in self.conv2d_scope_names:
  222. if node.op == 'Conv2D':
  223. self.dump_complex_conv2d_to_file(node, f)
  224. continue
  225. if node.op == 'Conv2D':
  226. self.dump_simple_conv2d_to_file(node, f)
  227. elif node.op == 'DepthToSpace':
  228. self.dump_depth2space_to_file(node, f)
  229. elif node.op == 'MirrorPad':
  230. self.dump_mirrorpad_to_file(node, f)
  231. elif node.op == 'Maximum':
  232. self.dump_maximum_to_file(node, f)
  233. def dump_operands_to_file(self, f):
  234. operands = sorted(self.name_operand_dict.values())
  235. for operand in operands:
  236. #print('{}'.format(operand))
  237. np.array([operand.index, len(operand.name)], dtype=np.uint32).tofile(f)
  238. f.write(operand.name.encode('utf-8'))
  239. np.array([operand.iotype, operand.dtype], dtype=np.uint32).tofile(f)
  240. np.array([operand.dims[0], operand.dims[1], operand.dims[2], operand.dims[3]], dtype=np.uint32).tofile(f)
  241. def dump_to_file(self):
  242. with open(self.outfile, 'wb') as f:
  243. f.write(header.str.encode('utf-8'))
  244. np.array([header.major, header.minor], dtype=np.uint32).tofile(f)
  245. self.dump_layers_to_file(f)
  246. self.dump_operands_to_file(f)
  247. np.array([self.layer_number, len(self.name_operand_dict)], dtype=np.uint32).tofile(f)
  248. def generate_name_node_dict(self):
  249. for node in self.nodes:
  250. self.name_node_dict[node.name] = node
  251. def generate_output_names(self):
  252. used_names = []
  253. for node in self.nodes:
  254. for input in node.input:
  255. used_names.append(input)
  256. for node in self.nodes:
  257. if node.name not in used_names:
  258. self.output_names.append(node.name)
  259. def remove_identity(self):
  260. id_nodes = []
  261. id_dict = {}
  262. for node in self.nodes:
  263. if node.op == 'Identity':
  264. name = node.name
  265. input = node.input[0]
  266. id_nodes.append(node)
  267. # do not change the output name
  268. if name in self.output_names:
  269. self.name_node_dict[input].name = name
  270. self.name_node_dict[name] = self.name_node_dict[input]
  271. del self.name_node_dict[input]
  272. else:
  273. id_dict[name] = input
  274. for idnode in id_nodes:
  275. self.nodes.remove(idnode)
  276. for node in self.nodes:
  277. for i in range(len(node.input)):
  278. input = node.input[i]
  279. if input in id_dict:
  280. node.input[i] = id_dict[input]
  281. def generate_edges(self):
  282. for node in self.nodes:
  283. for input in node.input:
  284. if input in self.edges:
  285. self.edges[input].append(node)
  286. else:
  287. self.edges[input] = [node]
  288. @staticmethod
  289. def get_scope_name(name):
  290. index = name.rfind('/')
  291. if index == -1:
  292. return ""
  293. return name[0:index]
  294. def generate_conv2d_scope_info(self):
  295. # mostly, conv2d is a sub block in graph, get the scope name
  296. for node in self.nodes:
  297. if node.op == 'Conv2D':
  298. scope = TFConverter.get_scope_name(node.name)
  299. # for the case tf.nn.conv2d is called directly
  300. if scope == '':
  301. continue
  302. # for the case tf.nn.conv2d is called within a scope
  303. if scope + '/kernel' not in self.name_node_dict:
  304. continue
  305. 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
  314. def run(self):
  315. self.generate_name_node_dict()
  316. self.generate_output_names()
  317. self.remove_identity()
  318. self.generate_edges()
  319. self.generate_conv2d_scope_info()
  320. if self.dump4tb:
  321. self.dump_for_tensorboard()
  322. self.dump_to_file()
  323. def convert_from_tensorflow(infile, outfile, dump4tb):
  324. with open(infile, 'rb') as f:
  325. # read the file in .proto format
  326. graph_def = tf.GraphDef()
  327. graph_def.ParseFromString(f.read())
  328. nodes = graph_def.node
  329. converter = TFConverter(graph_def, nodes, outfile, dump4tb)
  330. converter.run()