linear.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. from typing import Optional
  2. import torch
  3. from torch.ao.nn.quantized.modules.utils import _quantize_weight, _hide_packed_params_repr
  4. __all__ = ['LinearPackedParams', 'Linear']
  5. # TODO (zaf): Inherit from `quantized.LinearPackedParams` (T83294430)
  6. class LinearPackedParams(torch.nn.Module):
  7. _version = 1
  8. def __init__(self, row_block_size=1, col_block_size=4, dtype=torch.qint8):
  9. super().__init__()
  10. if dtype != torch.qint8:
  11. raise NotImplementedError("Linear prepacking only supports QINT8")
  12. self.dtype = dtype
  13. wq = torch._empty_affine_quantized([1, 1], scale=1.0, zero_point=0, dtype=torch.qint8)
  14. self.set_weight_bias(wq, None, row_block_size, col_block_size)
  15. def _get_name(self):
  16. return "SparseQuantizedLinearPackedParams"
  17. @torch.jit.export
  18. def set_weight_bias(self, weight: torch.Tensor, bias: Optional[torch.Tensor],
  19. row_block_size: Optional[int], col_block_size: Optional[int]) -> None:
  20. assert row_block_size is not None and col_block_size is not None
  21. self._packed_params = torch.ops.sparse.qlinear_prepack(weight, bias, row_block_size, col_block_size)
  22. @torch.jit.export
  23. def _weight_bias(self):
  24. (weight, bias, block_sizes) = torch.ops.sparse.qlinear_unpack(self._packed_params)
  25. return (weight, bias, block_sizes[0], block_sizes[1])
  26. def forward(self, x):
  27. return x
  28. def _save_to_state_dict(self, destination, prefix, keep_vars):
  29. super()._save_to_state_dict(destination, prefix, keep_vars)
  30. destination[prefix + 'dtype'] = self.dtype
  31. destination[prefix + '_packed_params'] = self._weight_bias()
  32. def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
  33. missing_keys, unexpected_keys, error_msgs):
  34. version = local_metadata.get('version', None)
  35. assert version <= self._version
  36. self.dtype = state_dict.pop(prefix + 'dtype')
  37. weight, bias, row_block_size, col_block_size = state_dict.pop(prefix + '_packed_params')
  38. self.set_weight_bias(weight, bias, row_block_size, col_block_size)
  39. super()._load_from_state_dict(state_dict, prefix, local_metadata, False,
  40. missing_keys, unexpected_keys, error_msgs)
  41. @torch.jit.export
  42. def __getstate__(self):
  43. return self._packed_params, self.training, self.dtype
  44. @torch.jit.export
  45. def __setstate__(self, state):
  46. (self._packed_params, self.training, self.dtype) = state
  47. def __repr__(self):
  48. return self._weight_bias().__repr__()
  49. # TODO (zaf): Inherit from `quantized.Linear` (T83294430)
  50. class Linear(torch.nn.Module):
  51. r"""
  52. A quantized sparse linear module with quantized tensor as inputs and outputs.
  53. """
  54. _version = 1
  55. _FLOAT_MODULE = torch.nn.Linear
  56. def __init__(self, in_features, out_features, row_block_size, col_block_size, bias=True, dtype=torch.qint8):
  57. super().__init__()
  58. if dtype != torch.qint8:
  59. raise NotImplementedError("Only QINT8 is supported for Sparse Quantized Linear")
  60. self.in_features = in_features
  61. self.out_features = out_features
  62. if bias:
  63. bias = torch.zeros(self.out_features, dtype=torch.float)
  64. else:
  65. bias = None
  66. qweight = torch._empty_affine_quantized([out_features, in_features],
  67. scale=1, zero_point=0, dtype=torch.qint8)
  68. self._packed_params = LinearPackedParams(row_block_size=row_block_size,
  69. col_block_size=col_block_size,
  70. dtype=dtype)
  71. self._packed_params.set_weight_bias(qweight, bias, row_block_size, col_block_size)
  72. self.scale = 1.0
  73. self.zero_point = 0
  74. @classmethod
  75. def _get_name(cls):
  76. return 'SparseQuantizedLinear'
  77. def extra_repr(self):
  78. return 'in_features={}, out_features={}, scale={}, zero_point={}, qscheme={}'.format(
  79. self.in_features, self.out_features, self.scale, self.zero_point, self.weight().qscheme()
  80. )
  81. def __repr__(self):
  82. return _hide_packed_params_repr(self, LinearPackedParams)
  83. def forward(self, x: torch.Tensor) -> torch.Tensor:
  84. return torch.ops.sparse.qlinear(x, self._packed_params._packed_params, self.scale, self.zero_point)
  85. def _save_to_state_dict(self, destination, prefix, keep_vars):
  86. super()._save_to_state_dict(destination, prefix, keep_vars)
  87. destination[prefix + 'scale'] = torch.tensor(self.scale)
  88. destination[prefix + 'zero_point'] = torch.tensor(self.zero_point)
  89. def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
  90. missing_keys, unexpected_keys, error_msgs):
  91. self.scale = float(state_dict[prefix + 'scale'])
  92. state_dict.pop(prefix + 'scale')
  93. self.zero_point = int(state_dict[prefix + 'zero_point'])
  94. state_dict.pop(prefix + 'zero_point')
  95. op_type = int(state_dict[prefix + 'op_type'])
  96. state_dict.pop(prefix + 'op_type')
  97. version = local_metadata.get('version', None)
  98. assert version <= self._version
  99. super()._load_from_state_dict(
  100. state_dict, prefix, local_metadata, False,
  101. missing_keys, unexpected_keys, error_msgs)
  102. def _weight_bias(self):
  103. return self._packed_params._weight_bias()
  104. def weight(self):
  105. return self._weight_bias()[0]
  106. def bias(self):
  107. return self._weight_bias()[1]
  108. def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor],
  109. row_block_size: Optional[int], col_block_size: Optional[int]) -> None:
  110. assert row_block_size is not None and col_block_size is not None
  111. self._packed_params.set_weight_bias(w, b, row_block_size, col_block_size)
  112. @classmethod
  113. def from_float(cls, mod):
  114. r"""Create a quantized sparse module from a float module.
  115. We only care about the convert at this stage, no need for observers just yet.
  116. TODO(zaf): Need to add the sparse params to the qconfig
  117. """
  118. assert type(mod) == cls._FLOAT_MODULE, cls._get_name() + \
  119. '.from_float only works for ' + cls._FLOAT_MODULE.__name__
  120. assert hasattr(mod, 'sparse_params'), \
  121. ('Expecting the Linear to have `sparse_params`. Make sure you have provided arguments '
  122. 'in the `sparsifier.squash_mask(params_to_save=("sparse_block_shape",))` method.')
  123. sparse_block_shape = mod.sparse_params.get('sparse_block_shape', None) # type: ignore[operator, union-attr]
  124. assert isinstance(sparse_block_shape, (tuple, list))
  125. assert len(sparse_block_shape) == 2
  126. # TODO: Need to add options to qconfig to avoid the calibration.
  127. # TODO: Add calibration for the sparsity
  128. assert hasattr(mod, 'qconfig'), 'Input float module must have qconfig defined'
  129. activation_post_process = mod.activation_post_process
  130. weight_post_process = mod.qconfig.weight() # type: ignore[operator, union-attr]
  131. # Assumption is that the weight is already sparsified by the
  132. # `sparsifier.convert`
  133. weight = mod.weight
  134. weight_post_process(weight)
  135. dtype = weight_post_process.dtype
  136. act_scale, act_zp = activation_post_process.calculate_qparams() # type: ignore[operator, union-attr]
  137. assert dtype == torch.qint8, 'Weight observer must have dtype torch.qint8'
  138. w_sc, w_zp = weight_post_process.calculate_qparams()
  139. if isinstance(w_zp, torch.Tensor):
  140. assert not torch.any(w_zp.bool()), "All weight zero points must map to 0"
  141. else:
  142. assert w_zp == 0, 'Weight zero point must map to 0'
  143. qweight = _quantize_weight(weight.float(), weight_post_process)
  144. row_block_size = mod.sparse_params['sparse_block_shape'][0] # type: ignore[index]
  145. col_block_size = mod.sparse_params['sparse_block_shape'][1] # type: ignore[index]
  146. qlinear = cls(mod.in_features,
  147. mod.out_features,
  148. row_block_size,
  149. col_block_size,
  150. dtype=dtype)
  151. qlinear.set_weight_bias(qweight, mod.bias,
  152. row_block_size, col_block_size) # type: ignore[arg-type]
  153. qlinear.scale = float(act_scale)
  154. qlinear.zero_point = int(act_zp)
  155. return qlinear