conv.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import numpy as np
  2. import onnx
  3. from onnx import onnx_pb as onnx_proto
  4. from ..quant_utils import (
  5. TENSOR_NAME_QUANT_SUFFIX,
  6. QuantizedValue,
  7. QuantizedValueType,
  8. attribute_to_kwarg,
  9. find_by_name,
  10. get_mul_node,
  11. )
  12. from .base_operator import QuantOperatorBase
  13. from .qdq_base_operator import QDQOperatorBase
  14. class ConvInteger(QuantOperatorBase):
  15. def __init__(self, onnx_quantizer, onnx_node):
  16. super().__init__(onnx_quantizer, onnx_node)
  17. def add_bias(self, nodes, scaled_output):
  18. """
  19. Given a node, this function handles bias add by adding a "reshape" node on bias and an "add" node
  20. parameter nodes: new nodes would be appended into nodes
  21. parameter node: current node (Conv)
  22. parameter scaled_output: output of quant conv without bias
  23. parameter output: output of Conv
  24. parameter bias_name: bias of Conv
  25. return: the name of output
  26. """
  27. node = self.node
  28. model = self.quantizer.model
  29. # Add tensors for the shape to be reshaped to
  30. weight = find_by_name(node.input[1], model.initializer())
  31. if weight is None:
  32. raise ValueError(f"Expected {node.input[1]} to be an initializer")
  33. # Add reshape for correct broadcase
  34. output = node.output[0]
  35. reshape_input_data = node.input[2] # bias of Conv
  36. reshape_input_shape = output + "_bias_reshape_shape"
  37. reshape_output = output + "_bias_reshape_output"
  38. shape = np.ones((len(weight.dims)), dtype=np.int64)
  39. shape[1] = -1
  40. init_shape = onnx.helper.make_tensor(
  41. reshape_input_shape, onnx_proto.TensorProto.INT64, [len(weight.dims)], shape
  42. )
  43. model.add_initializer(init_shape)
  44. reshape_node = onnx.helper.make_node("Reshape", [reshape_input_data, reshape_input_shape], [reshape_output])
  45. nodes.append(reshape_node)
  46. # Add an Add operation for bias
  47. add_node = onnx.helper.make_node("Add", [scaled_output, reshape_output], [output], output + "_bias_add")
  48. nodes.append(add_node)
  49. def quantize(self):
  50. node = self.node
  51. assert node.op_type == "Conv"
  52. # Get Quantized from both activation(input[0]) and weight(input[1])
  53. (
  54. quantized_input_names,
  55. zero_point_names,
  56. scale_names,
  57. nodes,
  58. ) = self.quantizer.quantize_activation(node, [0])
  59. (
  60. quantized_input_names_weight,
  61. zero_point_names_weight,
  62. scale_names_weight,
  63. nodes_weight,
  64. ) = self.quantizer.quantize_weight(node, [1], reduce_range=self.quantizer.reduce_range)
  65. quantized_input_names.extend(quantized_input_names_weight)
  66. zero_point_names.extend(zero_point_names_weight)
  67. scale_names.extend(scale_names_weight)
  68. nodes.extend(nodes_weight)
  69. conv_integer_output = node.output[0] + "_output_quantized"
  70. conv_integer_name = node.name + "_quant" if node.name else ""
  71. kwargs = {}
  72. for attribute in node.attribute:
  73. kwargs.update(attribute_to_kwarg(attribute))
  74. conv_integer_node = onnx.helper.make_node(
  75. "ConvInteger", quantized_input_names + zero_point_names, [conv_integer_output], conv_integer_name, **kwargs
  76. )
  77. nodes.append(conv_integer_node)
  78. # Add cast operation to cast convInteger output to float.
  79. onnx_type = self.quantizer.get_tensor_type(node.output[0], mandatory=True)
  80. cast_op_output = conv_integer_output + "_cast_output"
  81. cast_node = onnx.helper.make_node(
  82. "Cast",
  83. [conv_integer_output],
  84. [cast_op_output],
  85. conv_integer_output + "_cast",
  86. to=onnx_type, # TODO: FLOAT ot FLOAT16
  87. )
  88. nodes.append(cast_node)
  89. # Add mul operation to multiply scales of two inputs.
  90. assert len(scale_names) == 2
  91. if conv_integer_name:
  92. scales_mul_op = conv_integer_name + "_scales_mul"
  93. else:
  94. scales_mul_op = scale_names[0] + "_" + scale_names[1] + "_mul"
  95. scales_mul_node = find_by_name(scales_mul_op, self.quantizer.new_nodes)
  96. if scales_mul_node is None:
  97. scales_mul_node = get_mul_node(scale_names, scales_mul_op + ":0", scales_mul_op)
  98. nodes.append(scales_mul_node)
  99. scales_mul_op_output = scales_mul_node.output[0]
  100. has_bias = len(node.input) == 3
  101. scaled_output_name = node.output[0] if not has_bias else node.output[0] + "quant_scaled_output"
  102. # Add mul operation to multiply mul_scales_op result with output of ConvInteger
  103. # and make the output of this node the same as output of original conv node.
  104. output_scale_mul_op = conv_integer_name + "_output_scale_mul" if conv_integer_name else ""
  105. nodes.append(
  106. get_mul_node(
  107. [cast_op_output, scales_mul_op_output],
  108. scaled_output_name,
  109. output_scale_mul_op,
  110. )
  111. )
  112. if has_bias:
  113. self.add_bias(nodes, scaled_output_name)
  114. self.quantizer.new_nodes += nodes
  115. class QLinearConv(QuantOperatorBase):
  116. def __init__(self, onnx_quantizer, onnx_node):
  117. super().__init__(onnx_quantizer, onnx_node)
  118. def quantize(self):
  119. node = self.node
  120. assert node.op_type == "Conv"
  121. (
  122. data_found,
  123. output_scale_name,
  124. output_zp_name,
  125. _,
  126. _,
  127. ) = self.quantizer._get_quantization_params(node.output[0])
  128. if self.quantizer.is_input_a_initializer(node.input[1]) and self.quantizer.is_per_channel():
  129. (
  130. quantized_input_names,
  131. zero_point_names,
  132. scale_names,
  133. nodes,
  134. ) = self.quantizer.quantize_activation(node, [0])
  135. quant_weight_tuple = self.quantizer.quantize_weight_per_channel(
  136. node.input[1],
  137. onnx_proto.TensorProto.INT8,
  138. 0, # self.quantizer.weight_qType?
  139. )
  140. quantized_input_names.append(quant_weight_tuple[0])
  141. zero_point_names.append(quant_weight_tuple[1])
  142. scale_names.append(quant_weight_tuple[2])
  143. else:
  144. (
  145. quantized_input_names,
  146. zero_point_names,
  147. scale_names,
  148. nodes,
  149. ) = self.quantizer.quantize_activation(node, [0])
  150. (
  151. quantized_input_names_weight,
  152. zero_point_names_weight,
  153. scale_names_weight,
  154. nodes_weight,
  155. ) = self.quantizer.quantize_weight(node, [1], reduce_range=self.quantizer.reduce_range)
  156. quantized_input_names.extend(quantized_input_names_weight)
  157. zero_point_names.extend(zero_point_names_weight)
  158. scale_names.extend(scale_names_weight)
  159. nodes.extend(nodes_weight)
  160. if not data_found or quantized_input_names is None:
  161. return super().quantize()
  162. quantized_bias_name = ""
  163. bias_present = False
  164. if len(node.input) == 3:
  165. if self.quantizer.weight_qType == onnx_proto.TensorProto.FLOAT8E4M3FN:
  166. raise RuntimeError("Quantization to FLOAT8E4M3FN for operator Conv is not supported.")
  167. quantized_bias_name = self.quantizer.quantize_bias_static(node.input[2], node.input[0], node.input[1])
  168. bias_present = True
  169. qlinear_conv_output = node.output[0] + TENSOR_NAME_QUANT_SUFFIX
  170. qlinear_conv_name = node.name + "_quant" if node.name else ""
  171. kwargs = {}
  172. for attribute in node.attribute:
  173. kwargs.update(attribute_to_kwarg(attribute))
  174. qlinear_conv_inputs = []
  175. # Input 0
  176. qlinear_conv_inputs.append(quantized_input_names[0])
  177. qlinear_conv_inputs.append(scale_names[0])
  178. qlinear_conv_inputs.append(zero_point_names[0])
  179. # Input 1
  180. qlinear_conv_inputs.append(quantized_input_names[1])
  181. qlinear_conv_inputs.append(scale_names[1])
  182. qlinear_conv_inputs.append(zero_point_names[1])
  183. # Output
  184. qlinear_conv_inputs.append(output_scale_name)
  185. qlinear_conv_inputs.append(output_zp_name)
  186. if bias_present:
  187. qlinear_conv_inputs.append(quantized_bias_name)
  188. qlinear_conv_node = onnx.helper.make_node(
  189. "QLinearConv", qlinear_conv_inputs, [qlinear_conv_output], qlinear_conv_name, **kwargs
  190. )
  191. nodes.append(qlinear_conv_node)
  192. # Create an entry for this quantized value
  193. q_output = QuantizedValue(
  194. node.output[0],
  195. qlinear_conv_output,
  196. output_scale_name,
  197. output_zp_name,
  198. QuantizedValueType.Input,
  199. )
  200. self.quantizer.quantized_value_map[node.output[0]] = q_output
  201. self.quantizer.new_nodes += nodes
  202. class QDQConv(QDQOperatorBase):
  203. def __init__(self, onnx_quantizer, onnx_node):
  204. super().__init__(onnx_quantizer, onnx_node)
  205. def quantize(self):
  206. node = self.node
  207. assert node.op_type == "Conv" or node.op_type == "ConvTranspose"
  208. self.quantizer.quantize_activation_tensor(node.input[0])
  209. if not self.disable_qdq_for_node_output:
  210. self.quantizer.quantize_activation_tensor(node.output[0])
  211. is_weight_per_channel, weight_axis = self.quantizer.is_tensor_per_channel(
  212. node.input[1], default_axis=0 if node.op_type == "Conv" else 1
  213. )
  214. if is_weight_per_channel:
  215. self.quantizer.quantize_weight_tensor_per_channel(node.input[1], weight_axis)
  216. else:
  217. self.quantizer.quantize_weight_tensor(node.input[1])
  218. if len(node.input) == 3:
  219. self.quantizer.quantize_bias_tensor(node.name, node.input[2], node.input[0], node.input[1])