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.

216 lines
7.6KB

  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. __all__ = ['convert_from_tensorflow']
  23. class TFConverter:
  24. def __init__(self, graph_def, nodes, outfile, dump4tb):
  25. self.graph_def = graph_def
  26. self.nodes = nodes
  27. self.outfile = outfile
  28. self.dump4tb = dump4tb
  29. self.layer_number = 0
  30. self.output_names = []
  31. self.name_node_dict = {}
  32. self.edges = {}
  33. self.conv_activations = {'Relu':0, 'Tanh':1, 'Sigmoid':2, 'LeakyRelu':4}
  34. self.conv_paddings = {'VALID':0, 'SAME':1}
  35. self.converted_nodes = set()
  36. self.op2code = {'Conv2D':1, 'DepthToSpace':2, 'MirrorPad':3}
  37. self.mirrorpad_mode = {'CONSTANT':0, 'REFLECT':1, 'SYMMETRIC':2}
  38. def dump_for_tensorboard(self):
  39. graph = tf.get_default_graph()
  40. tf.import_graph_def(self.graph_def, name="")
  41. tf.summary.FileWriter('/tmp/graph', graph)
  42. print('graph saved, run "tensorboard --logdir=/tmp/graph" to see it')
  43. def get_conv2d_params(self, node):
  44. knode = self.name_node_dict[node.input[1]]
  45. bnode = None
  46. activation = 'None'
  47. next = self.edges[node.name][0]
  48. if next.op == 'BiasAdd':
  49. self.converted_nodes.add(next.name)
  50. bnode = self.name_node_dict[next.input[1]]
  51. next = self.edges[next.name][0]
  52. if next.op in self.conv_activations:
  53. self.converted_nodes.add(next.name)
  54. activation = next.op
  55. return knode, bnode, activation
  56. def dump_conv2d_to_file(self, node, f):
  57. assert(node.op == 'Conv2D')
  58. self.layer_number = self.layer_number + 1
  59. self.converted_nodes.add(node.name)
  60. knode, bnode, activation = self.get_conv2d_params(node)
  61. dilation = node.attr['dilations'].list.i[0]
  62. padding = node.attr['padding'].s
  63. padding = self.conv_paddings[padding.decode("utf-8")]
  64. ktensor = knode.attr['value'].tensor
  65. filter_height = ktensor.tensor_shape.dim[0].size
  66. filter_width = ktensor.tensor_shape.dim[1].size
  67. in_channels = ktensor.tensor_shape.dim[2].size
  68. out_channels = ktensor.tensor_shape.dim[3].size
  69. kernel = np.frombuffer(ktensor.tensor_content, dtype=np.float32)
  70. kernel = kernel.reshape(filter_height, filter_width, in_channels, out_channels)
  71. kernel = np.transpose(kernel, [3, 0, 1, 2])
  72. np.array([self.op2code[node.op], dilation, padding, self.conv_activations[activation], in_channels, out_channels, filter_height], dtype=np.uint32).tofile(f)
  73. kernel.tofile(f)
  74. btensor = bnode.attr['value'].tensor
  75. if btensor.tensor_shape.dim[0].size == 1:
  76. bias = struct.pack("f", btensor.float_val[0])
  77. else:
  78. bias = btensor.tensor_content
  79. f.write(bias)
  80. def dump_depth2space_to_file(self, node, f):
  81. assert(node.op == 'DepthToSpace')
  82. self.layer_number = self.layer_number + 1
  83. block_size = node.attr['block_size'].i
  84. np.array([self.op2code[node.op], block_size], dtype=np.uint32).tofile(f)
  85. self.converted_nodes.add(node.name)
  86. def dump_mirrorpad_to_file(self, node, f):
  87. assert(node.op == 'MirrorPad')
  88. self.layer_number = self.layer_number + 1
  89. mode = node.attr['mode'].s
  90. mode = self.mirrorpad_mode[mode.decode("utf-8")]
  91. np.array([self.op2code[node.op], mode], dtype=np.uint32).tofile(f)
  92. pnode = self.name_node_dict[node.input[1]]
  93. self.converted_nodes.add(pnode.name)
  94. paddings = pnode.attr['value'].tensor.tensor_content
  95. f.write(paddings)
  96. self.converted_nodes.add(node.name)
  97. def generate_layer_number(self):
  98. # in current hard code implementation, the layer number is the first data written to the native model file
  99. # it is not easy to know it at the beginning time in the general converter, so first do a dry run for compatibility
  100. # will be refined later.
  101. with open('/tmp/tmp.model', 'wb') as f:
  102. self.dump_layers_to_file(f)
  103. self.converted_nodes.clear()
  104. def dump_layers_to_file(self, f):
  105. for node in self.nodes:
  106. if node.name in self.converted_nodes:
  107. continue
  108. if node.op == 'Conv2D':
  109. self.dump_conv2d_to_file(node, f)
  110. elif node.op == 'DepthToSpace':
  111. self.dump_depth2space_to_file(node, f)
  112. elif node.op == 'MirrorPad':
  113. self.dump_mirrorpad_to_file(node, f)
  114. def dump_to_file(self):
  115. self.generate_layer_number()
  116. with open(self.outfile, 'wb') as f:
  117. np.array([self.layer_number], dtype=np.uint32).tofile(f)
  118. self.dump_layers_to_file(f)
  119. def generate_name_node_dict(self):
  120. for node in self.nodes:
  121. self.name_node_dict[node.name] = node
  122. def generate_output_names(self):
  123. used_names = []
  124. for node in self.nodes:
  125. for input in node.input:
  126. used_names.append(input)
  127. for node in self.nodes:
  128. if node.name not in used_names:
  129. self.output_names.append(node.name)
  130. def remove_identity(self):
  131. id_nodes = []
  132. id_dict = {}
  133. for node in self.nodes:
  134. if node.op == 'Identity':
  135. name = node.name
  136. input = node.input[0]
  137. id_nodes.append(node)
  138. # do not change the output name
  139. if name in self.output_names:
  140. self.name_node_dict[input].name = name
  141. self.name_node_dict[name] = self.name_node_dict[input]
  142. del self.name_node_dict[input]
  143. else:
  144. id_dict[name] = input
  145. for idnode in id_nodes:
  146. self.nodes.remove(idnode)
  147. for node in self.nodes:
  148. for i in range(len(node.input)):
  149. input = node.input[i]
  150. if input in id_dict:
  151. node.input[i] = id_dict[input]
  152. def generate_edges(self):
  153. for node in self.nodes:
  154. for input in node.input:
  155. if input in self.edges:
  156. self.edges[input].append(node)
  157. else:
  158. self.edges[input] = [node]
  159. def run(self):
  160. self.generate_name_node_dict()
  161. self.generate_output_names()
  162. self.remove_identity()
  163. self.generate_edges()
  164. if self.dump4tb:
  165. self.dump_for_tensorboard()
  166. self.dump_to_file()
  167. def convert_from_tensorflow(infile, outfile, dump4tb):
  168. with open(infile, 'rb') as f:
  169. # read the file in .proto format
  170. graph_def = tf.GraphDef()
  171. graph_def.ParseFromString(f.read())
  172. nodes = graph_def.node
  173. converter = TFConverter(graph_def, nodes, outfile, dump4tb)
  174. converter.run()