convert_from_tensorflow.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. # as the first step to be compatible with vf_sr, it is not general.
  24. # it will be refined step by step.
  25. class TFConverter:
  26. def __init__(self, graph_def, nodes, outfile):
  27. self.graph_def = graph_def
  28. self.nodes = nodes
  29. self.outfile = outfile
  30. self.layer_number = 0
  31. self.output_names = []
  32. self.name_node_dict = {}
  33. self.edges = {}
  34. self.conv_activations = {'Relu':0, 'Tanh':1, 'Sigmoid':2, 'LeakyRelu':4}
  35. self.conv_paddings = {'VALID':2, 'SAME':1}
  36. self.converted_nodes = set()
  37. self.op2code = {'Conv2D':1, 'DepthToSpace':2}
  38. def dump_for_tensorboard(self):
  39. graph = tf.get_default_graph()
  40. tf.import_graph_def(self.graph_def, name="")
  41. # tensorboard --logdir=/tmp/graph
  42. tf.summary.FileWriter('/tmp/graph', graph)
  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 generate_layer_number(self):
  87. # in current hard code implementation, the layer number is the first data written to the native model file
  88. # it is not easy to know it at the beginning time in the general converter, so first do a dry run for compatibility
  89. # will be refined later.
  90. with open('/tmp/tmp.model', 'wb') as f:
  91. self.dump_layers_to_file(f)
  92. self.converted_nodes.clear()
  93. def dump_layers_to_file(self, f):
  94. for node in self.nodes:
  95. if node.name in self.converted_nodes:
  96. continue
  97. if node.op == 'Conv2D':
  98. self.dump_conv2d_to_file(node, f)
  99. elif node.op == 'DepthToSpace':
  100. self.dump_depth2space_to_file(node, f)
  101. def dump_to_file(self):
  102. self.generate_layer_number()
  103. with open(self.outfile, 'wb') as f:
  104. np.array([self.layer_number], dtype=np.uint32).tofile(f)
  105. self.dump_layers_to_file(f)
  106. def generate_name_node_dict(self):
  107. for node in self.nodes:
  108. self.name_node_dict[node.name] = node
  109. def generate_output_names(self):
  110. used_names = []
  111. for node in self.nodes:
  112. for input in node.input:
  113. used_names.append(input)
  114. for node in self.nodes:
  115. if node.name not in used_names:
  116. self.output_names.append(node.name)
  117. def remove_identity(self):
  118. id_nodes = []
  119. id_dict = {}
  120. for node in self.nodes:
  121. if node.op == 'Identity':
  122. name = node.name
  123. input = node.input[0]
  124. id_nodes.append(node)
  125. # do not change the output name
  126. if name in self.output_names:
  127. self.name_node_dict[input].name = name
  128. self.name_node_dict[name] = self.name_node_dict[input]
  129. del self.name_node_dict[input]
  130. else:
  131. id_dict[name] = input
  132. for idnode in id_nodes:
  133. self.nodes.remove(idnode)
  134. for node in self.nodes:
  135. for i in range(len(node.input)):
  136. input = node.input[i]
  137. if input in id_dict:
  138. node.input[i] = id_dict[input]
  139. def generate_edges(self):
  140. for node in self.nodes:
  141. for input in node.input:
  142. if input in self.edges:
  143. self.edges[input].append(node)
  144. else:
  145. self.edges[input] = [node]
  146. def run(self):
  147. self.generate_name_node_dict()
  148. self.generate_output_names()
  149. self.remove_identity()
  150. self.generate_edges()
  151. #check the graph with tensorboard with human eyes
  152. #self.dump_for_tensorboard()
  153. self.dump_to_file()
  154. def convert_from_tensorflow(infile, outfile):
  155. with open(infile, 'rb') as f:
  156. # read the file in .proto format
  157. graph_def = tf.GraphDef()
  158. graph_def.ParseFromString(f.read())
  159. nodes = graph_def.node
  160. converter = TFConverter(graph_def, nodes, outfile)
  161. converter.run()