convert_from_tensorflow.py 19 KB

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