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.

462 lines
19KB

  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, 'MathBinary':5, 'MathUnary':6}
  67. self.mathbin2code = {'Sub':0, 'Add':1, 'Mul':2, 'RealDiv':3, 'Minimum':4}
  68. self.mathun2code = {'Abs':0, 'Sin':1, 'Cos':2, 'Tan':3, 'Asin':4,
  69. 'Acos':5, 'Atan':6, 'Sinh':7, 'Cosh':8, 'Tanh':9, 'Asinh':10,
  70. 'Acosh':11, 'Atanh':12, 'Ceil':13, 'Floor':14}
  71. self.mirrorpad_mode = {'CONSTANT':0, 'REFLECT':1, 'SYMMETRIC':2}
  72. self.name_operand_dict = {}
  73. def add_operand(self, name, type):
  74. node = self.name_node_dict[name]
  75. if name not in self.name_operand_dict:
  76. dtype = node.attr['dtype'].type
  77. if dtype == 0:
  78. dtype = node.attr['T'].type
  79. dims = [-1,-1,-1,-1]
  80. if 'shape' in node.attr:
  81. dims[0] = node.attr['shape'].shape.dim[0].size
  82. dims[1] = node.attr['shape'].shape.dim[1].size
  83. dims[2] = node.attr['shape'].shape.dim[2].size
  84. dims[3] = node.attr['shape'].shape.dim[3].size
  85. operand = Operand(name, dtype, dims)
  86. self.name_operand_dict[name] = operand;
  87. self.name_operand_dict[name].add_iotype(type)
  88. return self.name_operand_dict[name].index
  89. def dump_for_tensorboard(self):
  90. graph = tf.get_default_graph()
  91. tf.import_graph_def(self.graph_def, name="")
  92. tf.summary.FileWriter('/tmp/graph', graph)
  93. print('graph saved, run "tensorboard --logdir=/tmp/graph" to see it')
  94. def get_conv2d_params(self, conv2d_scope_name):
  95. knode = self.name_node_dict[conv2d_scope_name + '/kernel']
  96. bnode = self.name_node_dict[conv2d_scope_name + '/bias']
  97. if conv2d_scope_name + '/dilation_rate' in self.name_node_dict:
  98. dnode = self.name_node_dict[conv2d_scope_name + '/dilation_rate']
  99. else:
  100. dnode = None
  101. # the BiasAdd name is possible be changed into the output name,
  102. # if activation is None, and BiasAdd.next is the last op which is Identity
  103. if conv2d_scope_name + '/BiasAdd' in self.edges:
  104. anode = self.edges[conv2d_scope_name + '/BiasAdd'][0]
  105. if anode.op not in self.conv_activations:
  106. anode = None
  107. else:
  108. anode = None
  109. return knode, bnode, dnode, anode
  110. def dump_complex_conv2d_to_file(self, node, f):
  111. assert(node.op == 'Conv2D')
  112. self.layer_number = self.layer_number + 1
  113. self.converted_nodes.add(node.name)
  114. scope_name = TFConverter.get_scope_name(node.name)
  115. #knode for kernel, bnode for bias, dnode for dilation, anode for activation
  116. knode, bnode, dnode, anode = self.get_conv2d_params(scope_name)
  117. if dnode is not None:
  118. dilation = struct.unpack('i', dnode.attr['value'].tensor.tensor_content[0:4])[0]
  119. else:
  120. dilation = 1
  121. if anode is not None:
  122. activation = anode.op
  123. else:
  124. activation = 'None'
  125. padding = node.attr['padding'].s.decode("utf-8")
  126. # conv2d with dilation > 1 generates tens of nodes, not easy to parse them, so use this tricky method.
  127. if dilation > 1 and scope_name + '/stack' in self.name_node_dict:
  128. if self.name_node_dict[scope_name + '/stack'].op == "Const":
  129. padding = 'SAME'
  130. padding = self.conv_paddings[padding]
  131. ktensor = knode.attr['value'].tensor
  132. filter_height = ktensor.tensor_shape.dim[0].size
  133. filter_width = ktensor.tensor_shape.dim[1].size
  134. in_channels = ktensor.tensor_shape.dim[2].size
  135. out_channels = ktensor.tensor_shape.dim[3].size
  136. kernel = np.frombuffer(ktensor.tensor_content, dtype=np.float32)
  137. kernel = kernel.reshape(filter_height, filter_width, in_channels, out_channels)
  138. kernel = np.transpose(kernel, [3, 0, 1, 2])
  139. has_bias = 1
  140. 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)
  141. kernel.tofile(f)
  142. btensor = bnode.attr['value'].tensor
  143. if btensor.tensor_shape.dim[0].size == 1:
  144. bias = struct.pack("f", btensor.float_val[0])
  145. else:
  146. bias = btensor.tensor_content
  147. f.write(bias)
  148. input_name = self.conv2d_scopename_inputname_dict[scope_name]
  149. input_operand_index = self.add_operand(input_name, Operand.IOTYPE_INPUT)
  150. if anode is not None:
  151. output_operand_index = self.add_operand(anode.name, Operand.IOTYPE_OUTPUT)
  152. else:
  153. output_operand_index = self.add_operand(self.edges[bnode.name][0].name, Operand.IOTYPE_OUTPUT)
  154. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  155. def dump_simple_conv2d_to_file(self, node, f):
  156. assert(node.op == 'Conv2D')
  157. self.layer_number = self.layer_number + 1
  158. self.converted_nodes.add(node.name)
  159. node0 = self.name_node_dict[node.input[0]]
  160. node1 = self.name_node_dict[node.input[1]]
  161. if node0.op == 'Const':
  162. knode = node0
  163. input_name = node.input[1]
  164. else:
  165. knode = node1
  166. input_name = node.input[0]
  167. ktensor = knode.attr['value'].tensor
  168. filter_height = ktensor.tensor_shape.dim[0].size
  169. filter_width = ktensor.tensor_shape.dim[1].size
  170. in_channels = ktensor.tensor_shape.dim[2].size
  171. out_channels = ktensor.tensor_shape.dim[3].size
  172. if filter_height * filter_width * in_channels * out_channels == 1:
  173. kernel = np.float32(ktensor.float_val[0])
  174. else:
  175. kernel = np.frombuffer(ktensor.tensor_content, dtype=np.float32)
  176. kernel = kernel.reshape(filter_height, filter_width, in_channels, out_channels)
  177. kernel = np.transpose(kernel, [3, 0, 1, 2])
  178. has_bias = 0
  179. dilation = 1
  180. padding = node.attr['padding'].s.decode("utf-8")
  181. np.array([self.op2code[node.op], dilation, self.conv_paddings[padding], self.conv_activations['None'],
  182. in_channels, out_channels, filter_height, has_bias], dtype=np.uint32).tofile(f)
  183. kernel.tofile(f)
  184. input_operand_index = self.add_operand(input_name, 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_depth2space_to_file(self, node, f):
  188. assert(node.op == 'DepthToSpace')
  189. self.layer_number = self.layer_number + 1
  190. block_size = node.attr['block_size'].i
  191. np.array([self.op2code[node.op], block_size], dtype=np.uint32).tofile(f)
  192. self.converted_nodes.add(node.name)
  193. input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
  194. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  195. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  196. def dump_mirrorpad_to_file(self, node, f):
  197. assert(node.op == 'MirrorPad')
  198. self.layer_number = self.layer_number + 1
  199. mode = node.attr['mode'].s
  200. mode = self.mirrorpad_mode[mode.decode("utf-8")]
  201. np.array([self.op2code[node.op], mode], dtype=np.uint32).tofile(f)
  202. pnode = self.name_node_dict[node.input[1]]
  203. self.converted_nodes.add(pnode.name)
  204. paddings = pnode.attr['value'].tensor.tensor_content
  205. f.write(paddings)
  206. self.converted_nodes.add(node.name)
  207. input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
  208. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  209. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  210. def dump_maximum_to_file(self, node, f):
  211. assert(node.op == 'Maximum')
  212. self.layer_number = self.layer_number + 1
  213. ynode = self.name_node_dict[node.input[1]]
  214. y = ynode.attr['value'].tensor.float_val[0]
  215. np.array([self.op2code[node.op]], dtype=np.uint32).tofile(f)
  216. np.array([y], dtype=np.float32).tofile(f)
  217. self.converted_nodes.add(node.name)
  218. input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
  219. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  220. np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
  221. def dump_mathbinary_to_file(self, node, f):
  222. self.layer_number = self.layer_number + 1
  223. self.converted_nodes.add(node.name)
  224. i0_node = self.name_node_dict[node.input[0]]
  225. i1_node = self.name_node_dict[node.input[1]]
  226. np.array([self.op2code['MathBinary'], self.mathbin2code[node.op]], dtype=np.uint32).tofile(f)
  227. if i0_node.op == 'Const':
  228. scalar = i0_node.attr['value'].tensor.float_val[0]
  229. np.array([1], dtype=np.uint32).tofile(f) # broadcast: 1
  230. np.array([scalar], dtype=np.float32).tofile(f)
  231. np.array([0], dtype=np.uint32).tofile(f) # broadcast: 0
  232. input_operand_index = self.add_operand(i1_node.name, Operand.IOTYPE_INPUT)
  233. np.array([input_operand_index], dtype=np.uint32).tofile(f)
  234. elif i1_node.op == 'Const':
  235. scalar = i1_node.attr['value'].tensor.float_val[0]
  236. np.array([0], dtype=np.uint32).tofile(f)
  237. input_operand_index = self.add_operand(i0_node.name, Operand.IOTYPE_INPUT)
  238. np.array([input_operand_index], dtype=np.uint32).tofile(f)
  239. np.array([1], dtype=np.uint32).tofile(f)
  240. np.array([scalar], dtype=np.float32).tofile(f)
  241. else:
  242. np.array([0], dtype=np.uint32).tofile(f)
  243. input_operand_index = self.add_operand(i0_node.name, Operand.IOTYPE_INPUT)
  244. np.array([input_operand_index], dtype=np.uint32).tofile(f)
  245. np.array([0], dtype=np.uint32).tofile(f)
  246. input_operand_index = self.add_operand(i1_node.name, Operand.IOTYPE_INPUT)
  247. np.array([input_operand_index], dtype=np.uint32).tofile(f)
  248. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  249. np.array([output_operand_index], dtype=np.uint32).tofile(f)
  250. def dump_mathunary_to_file(self, node, f):
  251. self.layer_number = self.layer_number + 1
  252. self.converted_nodes.add(node.name)
  253. i0_node = self.name_node_dict[node.input[0]]
  254. np.array([self.op2code['MathUnary'], self.mathun2code[node.op]], dtype=np.uint32).tofile(f)
  255. input_operand_index = self.add_operand(i0_node.name, Operand.IOTYPE_INPUT)
  256. np.array([input_operand_index], dtype=np.uint32).tofile(f)
  257. output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
  258. np.array([output_operand_index],dtype=np.uint32).tofile(f)
  259. def dump_layers_to_file(self, f):
  260. for node in self.nodes:
  261. if node.name in self.converted_nodes:
  262. continue
  263. # conv2d with dilation generates very complex nodes, so handle it in special
  264. if self.in_conv2d_scope(node.name):
  265. if node.op == 'Conv2D':
  266. self.dump_complex_conv2d_to_file(node, f)
  267. continue
  268. if node.op == 'Conv2D':
  269. self.dump_simple_conv2d_to_file(node, f)
  270. elif node.op == 'DepthToSpace':
  271. self.dump_depth2space_to_file(node, f)
  272. elif node.op == 'MirrorPad':
  273. self.dump_mirrorpad_to_file(node, f)
  274. elif node.op == 'Maximum':
  275. self.dump_maximum_to_file(node, f)
  276. elif node.op in self.mathbin2code:
  277. self.dump_mathbinary_to_file(node, f)
  278. elif node.op in self.mathun2code:
  279. self.dump_mathunary_to_file(node, f)
  280. def dump_operands_to_file(self, f):
  281. operands = sorted(self.name_operand_dict.values())
  282. for operand in operands:
  283. #print('{}'.format(operand))
  284. np.array([operand.index, len(operand.name)], dtype=np.uint32).tofile(f)
  285. f.write(operand.name.encode('utf-8'))
  286. np.array([operand.iotype, operand.dtype], dtype=np.uint32).tofile(f)
  287. np.array([operand.dims[0], operand.dims[1], operand.dims[2], operand.dims[3]], dtype=np.uint32).tofile(f)
  288. def dump_to_file(self):
  289. with open(self.outfile, 'wb') as f:
  290. f.write(header.str.encode('utf-8'))
  291. np.array([header.major, header.minor], dtype=np.uint32).tofile(f)
  292. self.dump_layers_to_file(f)
  293. self.dump_operands_to_file(f)
  294. np.array([self.layer_number, len(self.name_operand_dict)], dtype=np.uint32).tofile(f)
  295. def generate_name_node_dict(self):
  296. for node in self.nodes:
  297. self.name_node_dict[node.name] = node
  298. def generate_output_names(self):
  299. used_names = []
  300. for node in self.nodes:
  301. for input in node.input:
  302. used_names.append(input)
  303. for node in self.nodes:
  304. if node.name not in used_names:
  305. self.output_names.append(node.name)
  306. def remove_identity(self):
  307. id_nodes = []
  308. id_dict = {}
  309. for node in self.nodes:
  310. if node.op == 'Identity':
  311. name = node.name
  312. input = node.input[0]
  313. id_nodes.append(node)
  314. # do not change the output name
  315. if name in self.output_names:
  316. self.name_node_dict[input].name = name
  317. self.name_node_dict[name] = self.name_node_dict[input]
  318. del self.name_node_dict[input]
  319. else:
  320. id_dict[name] = input
  321. for idnode in id_nodes:
  322. self.nodes.remove(idnode)
  323. for node in self.nodes:
  324. for i in range(len(node.input)):
  325. input = node.input[i]
  326. if input in id_dict:
  327. node.input[i] = id_dict[input]
  328. def generate_edges(self):
  329. for node in self.nodes:
  330. for input in node.input:
  331. if input in self.edges:
  332. self.edges[input].append(node)
  333. else:
  334. self.edges[input] = [node]
  335. @staticmethod
  336. def get_scope_name(name):
  337. index = name.rfind('/')
  338. if index == -1:
  339. return ""
  340. return name[0:index]
  341. def in_conv2d_scope(self, name):
  342. inner_scope = TFConverter.get_scope_name(name)
  343. if inner_scope == "":
  344. return False;
  345. for scope in self.conv2d_scope_names:
  346. index = inner_scope.find(scope)
  347. if index == 0:
  348. return True
  349. return False
  350. def generate_conv2d_scope_info(self):
  351. # mostly, conv2d is a sub block in graph, get the scope name
  352. for node in self.nodes:
  353. if node.op == 'Conv2D':
  354. scope = TFConverter.get_scope_name(node.name)
  355. # for the case tf.nn.conv2d is called directly
  356. if scope == '':
  357. continue
  358. # for the case tf.nn.conv2d is called within a scope
  359. if scope + '/kernel' not in self.name_node_dict:
  360. continue
  361. self.conv2d_scope_names.add(scope)
  362. # get the input name to the conv2d sub block
  363. for node in self.nodes:
  364. scope = TFConverter.get_scope_name(node.name)
  365. if scope in self.conv2d_scope_names:
  366. if node.op == 'Conv2D' or node.op == 'Shape':
  367. for inp in node.input:
  368. if TFConverter.get_scope_name(inp) != scope:
  369. self.conv2d_scopename_inputname_dict[scope] = inp
  370. def run(self):
  371. self.generate_name_node_dict()
  372. self.generate_output_names()
  373. self.remove_identity()
  374. self.generate_edges()
  375. self.generate_conv2d_scope_info()
  376. if self.dump4tb:
  377. self.dump_for_tensorboard()
  378. self.dump_to_file()
  379. def convert_from_tensorflow(infile, outfile, dump4tb):
  380. with open(infile, 'rb') as f:
  381. # read the file in .proto format
  382. graph_def = tf.GraphDef()
  383. graph_def.ParseFromString(f.read())
  384. nodes = graph_def.node
  385. converter = TFConverter(graph_def, nodes, outfile, dump4tb)
  386. converter.run()