|
20 | 20 | MinMaxObserver, |
21 | 21 | MovingAverageMinMaxObserver, |
22 | 22 | PerChannelMinMaxObserver, |
| 23 | + UniformQuantizationObserverBase, |
23 | 24 | ) |
24 | 25 |
|
25 | 26 | from torch.ao.quantization.quantizer import ( |
|
35 | 36 | from torch.fx import Node |
36 | 37 |
|
37 | 38 |
|
| 39 | +class ParamObserver(UniformQuantizationObserverBase): |
| 40 | + def __init__( |
| 41 | + self, |
| 42 | + ch_axis=0, |
| 43 | + use_mse=True, |
| 44 | + steps=100, |
| 45 | + dtype=torch.int8, |
| 46 | + qscheme=torch.per_channel_symmetric, |
| 47 | + reduce_range=False, |
| 48 | + quant_min=None, |
| 49 | + quant_max=None, |
| 50 | + factory_kwargs=None, |
| 51 | + eps=torch.finfo(torch.float32).eps, # noqa: B008 |
| 52 | + is_dynamic=False, |
| 53 | + **kwargs, |
| 54 | + ) -> None: |
| 55 | + super().__init__( |
| 56 | + dtype=dtype, |
| 57 | + qscheme=qscheme, |
| 58 | + reduce_range=reduce_range, |
| 59 | + quant_min=quant_min, |
| 60 | + quant_max=quant_max, |
| 61 | + factory_kwargs=factory_kwargs, |
| 62 | + eps=eps, |
| 63 | + is_dynamic=is_dynamic, |
| 64 | + **kwargs, |
| 65 | + ) |
| 66 | + |
| 67 | + factory_kwargs = torch.nn.factory_kwargs(factory_kwargs) |
| 68 | + self.register_buffer("min_val", torch.tensor(float("inf"), **factory_kwargs)) |
| 69 | + self.register_buffer("max_val", torch.tensor(float("-inf"), **factory_kwargs)) |
| 70 | + self.ch_axis = ch_axis |
| 71 | + self.use_mse = use_mse |
| 72 | + self.steps = steps |
| 73 | + self.calibrated = False |
| 74 | + |
| 75 | + def to_ch_axis(self, x): |
| 76 | + axis_order = list(range(len(x.size()))) |
| 77 | + axis_order[self.ch_axis], axis_order[0] = 0, self.ch_axis |
| 78 | + return torch.flatten(x.permute(axis_order), start_dim=1) |
| 79 | + |
| 80 | + def mse(self, pred, expect): |
| 81 | + loss = (pred - expect).abs().pow(2) |
| 82 | + return self.to_ch_axis(loss).mean(1) |
| 83 | + |
| 84 | + def cosine(self, pred, expect): |
| 85 | + target = torch.ones(pred.shape[self.ch_axis]) |
| 86 | + pred_n = self.to_ch_axis(pred).reshape(pred.shape[0], -1) |
| 87 | + expect_n = self.to_ch_axis(expect).reshape(expect.shape[0], -1) |
| 88 | + return torch.nn.CosineEmbeddingLoss()(pred_n, expect_n, target) |
| 89 | + |
| 90 | + def loss_fn(self, x, new_min, new_max): |
| 91 | + scale, offset = self._calculate_qparams(new_min, new_max) |
| 92 | + x_q = torch.fake_quantize_per_channel_affine( |
| 93 | + x, |
| 94 | + scale.data, |
| 95 | + offset.data.int(), |
| 96 | + self.ch_axis, |
| 97 | + self.quant_min, |
| 98 | + self.quant_max, |
| 99 | + ) |
| 100 | + return self.mse(x_q, x) if self.use_mse else self.cosine(x_q, x) |
| 101 | + |
| 102 | + def line_search(self, x): |
| 103 | + x_min, x_max = torch.aminmax(self.to_ch_axis(x), dim=1) |
| 104 | + x_range = torch.max(x_min.abs(), x_max) |
| 105 | + optimal_loss = torch.zeros_like(x_min) + 1e9 |
| 106 | + |
| 107 | + # check which clip range could produce smallest loss |
| 108 | + for i in range(1, self.steps + 1): |
| 109 | + thres = x_range / self.steps * i |
| 110 | + current_loss = self.loss_fn(x, -thres, thres) |
| 111 | + x_min = torch.where(current_loss < optimal_loss, -thres, x_min) |
| 112 | + x_max = torch.where(current_loss < optimal_loss, thres, x_max) |
| 113 | + optimal_loss = torch.min(current_loss, optimal_loss) |
| 114 | + |
| 115 | + return x_min, x_max |
| 116 | + |
| 117 | + def forward(self, x_orig): |
| 118 | + # since params are static, one calibration is enough |
| 119 | + if not self.calibrated: |
| 120 | + x = x_orig.detach().to(self.min_val.dtype) |
| 121 | + self.min_val, self.max_val = self.line_search(x) |
| 122 | + self.calibrated = True |
| 123 | + |
| 124 | + # return fake-quant result for saturating outliers |
| 125 | + scale, zero_point = self._calculate_qparams(self.min_val, self.max_val) |
| 126 | + return torch.fake_quantize_per_channel_affine( |
| 127 | + x_orig, |
| 128 | + scale.data, |
| 129 | + zero_point.data.int(), |
| 130 | + self.ch_axis, |
| 131 | + self.quant_min, |
| 132 | + self.quant_max, |
| 133 | + ) |
| 134 | + |
| 135 | + @torch.jit.export |
| 136 | + def calculate_qparams(self): |
| 137 | + return self._calculate_qparams(self.min_val, self.max_val) |
| 138 | + |
| 139 | + |
38 | 140 | @dataclass(eq=True, frozen=True) |
39 | 141 | class QuantizationConfig: |
40 | 142 | input_activation: Optional[QuantizationSpec] |
@@ -235,7 +337,7 @@ def get_default_16bit_qnn_ptq_config( |
235 | 337 | return quantization_config |
236 | 338 |
|
237 | 339 |
|
238 | | -def get_ptq_per_channel_weight_config( |
| 340 | +def get_ptq_per_channel_quant_config( |
239 | 341 | act_dtype=torch.uint8, weight_dtype=torch.int8 |
240 | 342 | ) -> QuantizationConfig: |
241 | 343 | extra_args: Dict[str, Any] = {"eps": 2**-12} |
@@ -585,7 +687,7 @@ def annotate_prelu(node: Node, quantization_config: QuantizationConfig) -> None: |
585 | 687 | annotate_single_in_single_out(node, quantization_config) |
586 | 688 |
|
587 | 689 |
|
588 | | -@register_annotator([torch.ops.aten.view.default]) |
| 690 | +@register_annotator([torch.ops.aten.view.default, torch.ops.aten._unsafe_view.default]) |
589 | 691 | def annotate_view(node: Node, quantization_config: QuantizationConfig) -> None: |
590 | 692 | annotate_in_out_obs_sharing_op(node, quantization_config) |
591 | 693 | if not _is_annotated([node]): |
|
0 commit comments