Args: inputs (`torch.FloatTensor`) The input which needs to be quantized num_bits (int, >=4) Number of bits to use for quantization min_value/max_value (torch.FloatTensor) Used for static activation quantiza
(ctx, input, num_bits, min_value=None, max_value=None, num_groups=1)
| 66 | |
| 67 | @staticmethod |
| 68 | def forward(ctx, input, num_bits, min_value=None, max_value=None, num_groups=1): |
| 69 | """ |
| 70 | Args: |
| 71 | inputs (`torch.FloatTensor`) |
| 72 | The input which needs to be quantized |
| 73 | num_bits (int, >=4) |
| 74 | Number of bits to use for quantization |
| 75 | min_value/max_value (torch.FloatTensor) |
| 76 | Used for static activation quantization |
| 77 | num_groups (int) |
| 78 | How many groups to partition the quantization into |
| 79 | Returns: |
| 80 | quantized_input (`torch.FloatTensor`) |
| 81 | Quantized input |
| 82 | """ |
| 83 | assert (min_value is None and max_value is None) or (min_value is not None and max_value is not None |
| 84 | and num_groups == 1) |
| 85 | q_range = 2**num_bits |
| 86 | input_shape = input.shape |
| 87 | if min_value is None: |
| 88 | input = input.reshape(num_groups, -1) |
| 89 | max_input = torch.amax(torch.abs(input), dim=-1).view(num_groups, -1) |
| 90 | else: |
| 91 | max_input = torch.max(min_value.abs(), max_value).view(-1) |
| 92 | |
| 93 | scale = 2 * max_input / q_range |
| 94 | output = (input / scale).round().clamp(-q_range // 2, q_range // 2 - 1) * scale |
| 95 | output = output.reshape(input_shape).contiguous() |
| 96 | return output |
| 97 | |
| 98 | @staticmethod |
| 99 | def backward(ctx, grad_output): |