x: the activation that we need to quantize num_bits: the number of bits we need to quantize the activation to *args: some extra arguments that are useless but needed for align with the interface of other quantization functions
(self, x, num_bits, *args)
| 38 | self.register_buffer('x_min_max', torch.zeros(2)) |
| 39 | |
| 40 | def forward(self, x, num_bits, *args): |
| 41 | """ |
| 42 | x: the activation that we need to quantize |
| 43 | num_bits: the number of bits we need to quantize the activation to |
| 44 | *args: some extra arguments that are useless but needed for align with the interface of other quantization functions |
| 45 | """ |
| 46 | |
| 47 | if self.training: |
| 48 | x_min = x.data.min() |
| 49 | x_max = x.data.max() |
| 50 | |
| 51 | # Initialization |
| 52 | if self.x_min_max[0] == self.x_min_max[1]: |
| 53 | self.x_min_max[0] = x_min |
| 54 | self.x_min_max[1] = x_max |
| 55 | |
| 56 | # if do not need momentum, please set self.act_range_momentum = 0 |
| 57 | self.x_min_max[0] = self.x_min_max[0] * self.act_range_momentum + x_min * (1 - self.act_range_momentum) |
| 58 | self.x_min_max[1] = self.x_min_max[1] * self.act_range_momentum + x_max * (1 - self.act_range_momentum) |
| 59 | |
| 60 | x_q = self.act_function(x, num_bits, self.x_min_max[0], self.x_min_max[1]) |
| 61 | |
| 62 | return x_q |
| 63 | |
| 64 | |
| 65 | class Embedding_Compress(nn.Embedding): |