fusion_group_norm.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. # -------------------------------------------------------------------------
  2. # Copyright (c) Microsoft Corporation. All rights reserved.
  3. # Licensed under the MIT License.
  4. # --------------------------------------------------------------------------
  5. from logging import getLogger
  6. import numpy as np
  7. from fusion_base import Fusion
  8. from onnx import TensorProto, helper
  9. from onnx_model import OnnxModel
  10. logger = getLogger(__name__)
  11. class FusionGroupNorm(Fusion):
  12. def __init__(self, model: OnnxModel, channels_last=True):
  13. super().__init__(model, "GroupNorm", "Add")
  14. self.channels_last = channels_last
  15. def fuse(self, add_node, input_name_to_nodes: dict, output_name_to_node: dict):
  16. """
  17. Fuse Group Normalization subgraph into one node GroupNorm.
  18. The following is the pattern with swish activation:
  19. +----------------Shape-------------------------------+
  20. | |
  21. | (0, 32, -1) v (512x1x1) (512x1x1) (optional)
  22. [Root] --> Reshape -------> InstanceNormalization --> Reshape ---> Mul --> Add --> Mul--> [output]
  23. Bx512xHxW (scale=ones(32), B=zeros(32)) | ^ Bx512xHxW
  24. | |
  25. +--->Sigmoid (optional)
  26. The Mul and Sigmoid before output is for Swish activation. They are optional.
  27. """
  28. nodes = self.model.match_parent_path(
  29. add_node, ["Mul", "Reshape", "InstanceNormalization", "Reshape"], [0, 0, 0, 0], output_name_to_node
  30. )
  31. if nodes is None:
  32. return
  33. weight_mul, reshape_4d, instance_norm, reshape_3d = nodes
  34. root = reshape_3d.input[0]
  35. parents = self.model.match_parent_path(reshape_4d, ["Shape"], [1], output_name_to_node)
  36. if parents is None:
  37. return
  38. if parents[0].input[0] != root:
  39. return
  40. shape_node = parents[0]
  41. # Check whether it has swish activation.
  42. swish_mul = self.model.find_first_child_by_type(add_node, "Mul")
  43. swish_sigmoid = None
  44. if swish_mul is not None:
  45. sigmoid_path = self.model.match_parent_path(swish_mul, ["Sigmoid"], [None], output_name_to_node)
  46. if sigmoid_path is not None:
  47. swish_sigmoid = sigmoid_path[0]
  48. weight_input = weight_mul.input[1 - self.model.input_index(reshape_4d.output[0], weight_mul)]
  49. if not self.model.is_constant_with_specified_dimension(weight_input, 3, "group norm weight"):
  50. return
  51. bias_input = add_node.input[1 - self.model.input_index(weight_mul.output[0], add_node)]
  52. if not self.model.is_constant_with_specified_dimension(bias_input, 3, "layernorm bias"):
  53. return
  54. weight = self.model.get_constant_value(weight_input)
  55. if weight is None:
  56. return
  57. if not (len(weight.shape) == 3 and weight.shape[1] == 1 and weight.shape[2] == 1):
  58. return
  59. bias = self.model.get_constant_value(bias_input)
  60. if bias is None:
  61. return
  62. if not (len(bias.shape) == 3 and bias.shape[1] == 1 and bias.shape[2] == 1):
  63. return
  64. weight_elements = int(np.prod(weight.shape))
  65. bias_elements = int(np.prod(bias.shape))
  66. if weight_elements != bias_elements:
  67. return
  68. instance_norm_scale = self.model.get_constant_value(instance_norm.input[1])
  69. if instance_norm_scale is None or len(instance_norm_scale.shape) != 1:
  70. return
  71. num_groups = int(instance_norm_scale.shape[0])
  72. instance_norm_bias = self.model.get_constant_value(instance_norm.input[2])
  73. if instance_norm_bias is None or instance_norm_scale.shape != instance_norm_scale.shape:
  74. return
  75. if not np.allclose(np.ones_like(instance_norm_scale), instance_norm_scale):
  76. return
  77. if not np.allclose(np.zeros_like(instance_norm_bias), instance_norm_bias):
  78. return
  79. group_norm_name = self.model.create_node_name("GroupNorm", name_prefix="GroupNorm")
  80. self.add_initializer(
  81. name=group_norm_name + "_gamma",
  82. data_type=TensorProto.FLOAT,
  83. dims=[weight_elements],
  84. vals=weight,
  85. )
  86. self.add_initializer(
  87. name=group_norm_name + "_beta",
  88. data_type=TensorProto.FLOAT,
  89. dims=[bias_elements],
  90. vals=bias,
  91. )
  92. last_node = add_node
  93. subgraph_nodes = [add_node, weight_mul, reshape_4d, instance_norm, reshape_3d, shape_node]
  94. has_swish_activation = swish_mul and swish_sigmoid
  95. if swish_mul and swish_sigmoid:
  96. subgraph_nodes.extend([swish_mul, swish_sigmoid])
  97. last_node = swish_mul
  98. if not self.model.is_safe_to_fuse_nodes(
  99. subgraph_nodes,
  100. last_node.output,
  101. input_name_to_nodes,
  102. output_name_to_node,
  103. ):
  104. self.nodes_to_remove.extend([last_node])
  105. else:
  106. self.nodes_to_remove.extend(subgraph_nodes)
  107. # instance_norm_scale might from Constant node. Use prune graph to clear it.
  108. self.prune_graph = True
  109. input_name = root
  110. output_name = last_node.output[0]
  111. group_norm_input_name = input_name + "_NHWC" if self.channels_last else input_name
  112. group_norm_output_name = output_name + "_NHWC" if self.channels_last else output_name
  113. # NCHW to NHWC
  114. if self.channels_last:
  115. transpose_input = helper.make_node(
  116. "Transpose",
  117. [input_name],
  118. [group_norm_input_name],
  119. name=self.model.create_node_name("Transpose", name_prefix="Transpose_NCHW_to_NHWC"),
  120. perm=[0, 2, 3, 1],
  121. )
  122. self.nodes_to_add.append(transpose_input)
  123. self.node_name_to_graph_name[transpose_input.name] = self.this_graph_name
  124. new_node = helper.make_node(
  125. "GroupNorm",
  126. inputs=[group_norm_input_name, group_norm_name + "_gamma", group_norm_name + "_beta"],
  127. outputs=[group_norm_output_name],
  128. name=group_norm_name,
  129. )
  130. new_node.attribute.extend(instance_norm.attribute)
  131. new_node.attribute.extend([helper.make_attribute("groups", num_groups)])
  132. new_node.attribute.extend([helper.make_attribute("activation", 1 if has_swish_activation else 0)])
  133. if not self.channels_last:
  134. new_node.attribute.extend([helper.make_attribute("channels_last", 0)])
  135. new_node.domain = "com.microsoft"
  136. self.nodes_to_add.append(new_node)
  137. self.node_name_to_graph_name[new_node.name] = self.this_graph_name
  138. # NHWC to NCHW
  139. if self.channels_last:
  140. transpose_output = helper.make_node(
  141. "Transpose",
  142. [group_norm_output_name],
  143. [output_name],
  144. name=self.model.create_node_name("Transpose", name_prefix="Transpose_NHWC_to_NCHW"),
  145. perm=[0, 3, 1, 2],
  146. )
  147. self.nodes_to_add.append(transpose_output)
  148. self.node_name_to_graph_name[transpose_output.name] = self.this_graph_name