Apply fake quantization to bias, with the special scale from input tensor and weight tensor, the quantized type set to qint32 also. Args: bias: the bias tensor which need to be faked. inp: the input tensor which contain the quantization parameters. w_qat: the weight
(bias: Tensor, inp: Tensor, w_qat: Tensor)
| 187 | |
| 188 | |
| 189 | def fake_quant_bias(bias: Tensor, inp: Tensor, w_qat: Tensor) -> Tensor: |
| 190 | """Apply fake quantization to bias, with the special scale from input tensor |
| 191 | and weight tensor, the quantized type set to qint32 also. |
| 192 | |
| 193 | Args: |
| 194 | bias: the bias tensor which need to be faked. |
| 195 | inp: the input tensor which contain the quantization parameters. |
| 196 | w_qat: the weight tensor which contain the quantization parameters. |
| 197 | |
| 198 | Warning: |
| 199 | Only work for symmetric quantization method now. |
| 200 | """ |
| 201 | b_qat = bias |
| 202 | if ( |
| 203 | getattr(inp, "qparams", None) is not None |
| 204 | and getattr(w_qat, "qparams", None) is not None |
| 205 | and bias is not None |
| 206 | ): |
| 207 | inp_params = inp.qparams |
| 208 | w_params = w_qat.qparams |
| 209 | |
| 210 | if inp_params.scale is None or w_params.scale is None: |
| 211 | return b_qat |
| 212 | |
| 213 | if inp_params.mode != QuantMode.SYMMERTIC: |
| 214 | return b_qat |
| 215 | |
| 216 | # TODO: support different mode |
| 217 | if inp_params.mode != w_params.mode: |
| 218 | return b_qat |
| 219 | |
| 220 | # TODO: support quint8 dtype. |
| 221 | if inp_params.dtype_meta.np_dtype_str != "int8": |
| 222 | return b_qat |
| 223 | if w_params.dtype_meta.np_dtype_str != "int8": |
| 224 | return b_qat |
| 225 | |
| 226 | # use the same mode with weight. |
| 227 | # TODO: avoid hardcode |
| 228 | b_dtype = _builtin_quant_dtypes["qint32"] |
| 229 | b_param = create_qparams( |
| 230 | w_params.mode, b_dtype, scale=inp_params.scale * w_params.scale |
| 231 | ) |
| 232 | b_qat = fake_quant_tensor(bias, b_param) |
| 233 | b_qat.qparams.update(b_param) |
| 234 | return b_qat |