lstm.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. import numpy
  2. import onnx
  3. from onnx import onnx_pb as onnx_proto
  4. from ..quant_utils import QuantType, attribute_to_kwarg, ms_domain # noqa: F401
  5. from .base_operator import QuantOperatorBase
  6. """
  7. Quantize LSTM
  8. """
  9. class LSTMQuant(QuantOperatorBase):
  10. def __init__(self, onnx_quantizer, onnx_node):
  11. super().__init__(onnx_quantizer, onnx_node)
  12. def quantize(self):
  13. """
  14. parameter node: LSTM node.
  15. parameter new_nodes_list: List of new nodes created before processing this node.
  16. return: a list of nodes in topological order that represents quantized Attention node.
  17. """
  18. node = self.node
  19. assert node.op_type == "LSTM"
  20. if not self.quantizer.is_valid_quantize_weight(node.input[1]) or not self.quantizer.is_valid_quantize_weight(
  21. node.input[2]
  22. ):
  23. super().quantize()
  24. return
  25. model = self.quantizer.model
  26. W = model.get_initializer(node.input[1]) # noqa: N806
  27. R = model.get_initializer(node.input[2]) # noqa: N806
  28. if len(W.dims) != 3 or len(R.dims) != 3:
  29. super().quantize()
  30. return
  31. [W_num_dir, W_4_hidden_size, W_input_size] = W.dims # noqa: N806
  32. [R_num_dir, R_4_hidden_size, R_hidden_size] = R.dims # noqa: N806
  33. if self.quantizer.is_per_channel():
  34. del W.dims[0]
  35. del R.dims[0]
  36. W.dims[0] = W_num_dir * W_4_hidden_size
  37. R.dims[0] = R_num_dir * R_4_hidden_size
  38. quant_input_weight_tuple = self.quantizer.quantize_weight_per_channel(
  39. node.input[1],
  40. onnx_proto.TensorProto.INT8,
  41. 0, # self.quantizer.weight_qType?
  42. )
  43. quant_recurrent_weight_tuple = self.quantizer.quantize_weight_per_channel(
  44. node.input[2],
  45. onnx_proto.TensorProto.INT8,
  46. 0, # self.quantizer.weight_qType?
  47. )
  48. W_quant_weight = model.get_initializer(quant_input_weight_tuple[0]) # noqa: N806
  49. R_quant_weight = model.get_initializer(quant_recurrent_weight_tuple[0]) # noqa: N806
  50. W_quant_array = onnx.numpy_helper.to_array(W_quant_weight) # noqa: N806
  51. R_quant_array = onnx.numpy_helper.to_array(R_quant_weight) # noqa: N806
  52. W_quant_array = numpy.reshape(W_quant_array, (W_num_dir, W_4_hidden_size, W_input_size)) # noqa: N806
  53. R_quant_array = numpy.reshape(R_quant_array, (R_num_dir, R_4_hidden_size, R_hidden_size)) # noqa: N806
  54. W_quant_array = numpy.transpose(W_quant_array, (0, 2, 1)) # noqa: N806
  55. R_quant_array = numpy.transpose(R_quant_array, (0, 2, 1)) # noqa: N806
  56. W_quant_tranposed = onnx.numpy_helper.from_array(W_quant_array, quant_input_weight_tuple[0]) # noqa: N806
  57. R_quant_tranposed = onnx.numpy_helper.from_array(R_quant_array, quant_recurrent_weight_tuple[0]) # noqa: N806
  58. model.remove_initializers([W_quant_weight, R_quant_weight])
  59. model.add_initializer(W_quant_tranposed)
  60. model.add_initializer(R_quant_tranposed)
  61. W_quant_zp = model.get_initializer(quant_input_weight_tuple[1]) # noqa: N806
  62. R_quant_zp = model.get_initializer(quant_recurrent_weight_tuple[1]) # noqa: N806
  63. W_quant_scale = model.get_initializer(quant_input_weight_tuple[2]) # noqa: N806
  64. R_quant_scale = model.get_initializer(quant_recurrent_weight_tuple[2]) # noqa: N806
  65. if self.quantizer.is_per_channel():
  66. W_quant_zp.dims[:] = [W_num_dir, W_4_hidden_size]
  67. R_quant_zp.dims[:] = [R_num_dir, R_4_hidden_size]
  68. W_quant_scale.dims[:] = [W_num_dir, W_4_hidden_size]
  69. R_quant_scale.dims[:] = [R_num_dir, R_4_hidden_size]
  70. inputs = []
  71. input_len = len(node.input)
  72. inputs.extend([node.input[0]])
  73. inputs.extend([quant_input_weight_tuple[0], quant_recurrent_weight_tuple[0]])
  74. inputs.extend([node.input[3] if input_len > 3 else ""])
  75. inputs.extend([node.input[4] if input_len > 4 else ""])
  76. inputs.extend([node.input[5] if input_len > 5 else ""])
  77. inputs.extend([node.input[6] if input_len > 6 else ""])
  78. inputs.extend([node.input[7] if input_len > 7 else ""])
  79. inputs.extend(
  80. [
  81. quant_input_weight_tuple[2],
  82. quant_input_weight_tuple[1],
  83. quant_recurrent_weight_tuple[2],
  84. quant_recurrent_weight_tuple[1],
  85. ]
  86. )
  87. kwargs = {}
  88. for attribute in node.attribute:
  89. if attribute.name == "layout":
  90. continue
  91. kwargs.update(attribute_to_kwarg(attribute))
  92. kwargs["domain"] = ms_domain
  93. quant_lstm_name = "" if not node.name else node.name + "_quant"
  94. quant_lstm_node = onnx.helper.make_node("DynamicQuantizeLSTM", inputs, node.output, quant_lstm_name, **kwargs)
  95. self.quantizer.new_nodes.append(quant_lstm_node)
  96. dequantize_node = self.quantizer._dequantize_value(node.input[0])
  97. if dequantize_node is not None:
  98. self.quantizer.new_nodes.append(dequantize_node)