-
Notifications
You must be signed in to change notification settings - Fork 16
/
quant_layer.py
290 lines (253 loc) · 11.2 KB
/
quant_layer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Union
class StraightThrough(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input):
return input
def round_ste(x: torch.Tensor):
"""
Implement Straight-Through Estimator for rounding operation.
"""
return (x.round() - x).detach() + x
def lp_loss(pred, tgt, p=2.0, reduction='none'):
"""
loss function measured in L_p Norm
"""
if reduction == 'none':
return (pred - tgt).abs().pow(p).sum(1).mean()
else:
return (pred - tgt).abs().pow(p).mean()
class UniformAffineQuantizer(nn.Module):
"""
PyTorch Function that can be used for asymmetric quantization (also called uniform affine
quantization). Quantizes its argument in the forward pass, passes the gradient 'straight
through' on the backward pass, ignoring the quantization that occurred.
Based on https://arxiv.org/abs/1806.08342.
:param n_bits: number of bit for quantization
:param symmetric: if True, the zero_point should always be 0
:param channel_wise: if True, compute scale and zero_point in each channel
:param scale_method: determines the quantization scale and zero point
:param prob: for qdrop;
"""
def __init__(self, n_bits: int = 8, symmetric: bool = False, channel_wise: bool = False,
scale_method: str = 'minmax',
leaf_param: bool = False, prob: float = 1.0):
super(UniformAffineQuantizer, self).__init__()
self.sym = symmetric
if self.sym:
raise NotImplementedError
assert 2 <= n_bits <= 8, 'bitwidth not supported'
self.n_bits = n_bits
self.n_levels = 2 ** self.n_bits
self.delta = 1.0
self.zero_point = 0.0
self.inited = True
'''if leaf_param, use EMA to set scale'''
self.leaf_param = leaf_param
self.channel_wise = channel_wise
self.eps = torch.tensor(1e-8, dtype=torch.float32)
'''mse params'''
self.scale_method = 'mse'
self.one_side_dist = None
self.num = 100
'''for activation quantization'''
self.running_min = None
self.running_max = None
'''do like dropout'''
self.prob = prob
self.is_training = False
def set_inited(self, inited: bool = True): # inited manually
self.inited = inited
def update_quantize_range(self, x_min, x_max):
if self.running_min is None:
self.running_min = x_min
self.running_max = x_max
self.running_min = 0.1 * x_min + 0.9 * self.running_min
self.running_max = 0.1 * x_max + 0.9 * self.running_max
return self.running_min, self.running_max
def forward(self, x: torch.Tensor):
if self.inited is False:
if self.leaf_param:
self.delta, self.zero_point = self.init_quantization_scale(x.clone().detach(), self.channel_wise)
else:
self.delta, self.zero_point = self.init_quantization_scale(x.clone().detach(), self.channel_wise)
# start quantization
x_int = round_ste(x / self.delta) + self.zero_point
x_quant = torch.clamp(x_int, 0, self.n_levels - 1)
x_dequant = (x_quant - self.zero_point) * self.delta
if self.is_training and self.prob < 1.0:
x_ans = torch.where(torch.rand_like(x) < self.prob, x_dequant, x)
else:
x_ans = x_dequant
return x_ans
def lp_loss(self, pred, tgt, p=2.0):
x = (pred - tgt).abs().pow(p)
if not self.channel_wise:
return x.mean()
else:
y = torch.flatten(x, 1)
return y.mean(1)
def calculate_qparams(self, min_val, max_val):
# one_dim or one element
quant_min, quant_max = 0, self.n_levels - 1
min_val_neg = torch.min(min_val, torch.zeros_like(min_val))
max_val_pos = torch.max(max_val, torch.zeros_like(max_val))
scale = (max_val_pos - min_val_neg) / float(quant_max - quant_min)
scale = torch.max(scale, self.eps)
zero_point = quant_min - torch.round(min_val_neg / scale)
zero_point = torch.clamp(zero_point, quant_min, quant_max)
return scale, zero_point
def quantize(self, x: torch.Tensor, x_max, x_min):
delta, zero_point = self.calculate_qparams(x_min, x_max)
if self.channel_wise:
new_shape = [1] * len(x.shape)
new_shape[0] = x.shape[0]
delta = delta.reshape(new_shape)
zero_point = zero_point.reshape(new_shape)
x_int = torch.round(x / delta)
x_quant = torch.clamp(x_int + zero_point, 0, self.n_levels - 1)
x_float_q = (x_quant - zero_point) * delta
return x_float_q
def perform_2D_search(self, x):
if self.channel_wise:
y = torch.flatten(x, 1)
x_min, x_max = torch._aminmax(y, 1)
# may also have the one side distribution in some channels
x_max = torch.max(x_max, torch.zeros_like(x_max))
x_min = torch.min(x_min, torch.zeros_like(x_min))
else:
x_min, x_max = torch._aminmax(x)
xrange = x_max - x_min
best_score = torch.zeros_like(x_min) + (1e+10)
best_min = x_min.clone()
best_max = x_max.clone()
# enumerate xrange
for i in range(1, self.num + 1):
tmp_min = torch.zeros_like(x_min)
tmp_max = xrange / self.num * i
tmp_delta = (tmp_max - tmp_min) / (2 ** self.n_bits - 1)
# enumerate zp
for zp in range(0, self.n_levels):
new_min = tmp_min - zp * tmp_delta
new_max = tmp_max - zp * tmp_delta
x_q = self.quantize(x, new_max, new_min)
score = self.lp_loss(x, x_q, 2.4)
best_min = torch.where(score < best_score, new_min, best_min)
best_max = torch.where(score < best_score, new_max, best_max)
best_score = torch.min(best_score, score)
return best_min, best_max
def perform_1D_search(self, x):
if self.channel_wise:
y = torch.flatten(x, 1)
x_min, x_max = torch._aminmax(y, 1)
else:
x_min, x_max = torch._aminmax(x)
xrange = torch.max(x_min.abs(), x_max)
best_score = torch.zeros_like(x_min) + (1e+10)
best_min = x_min.clone()
best_max = x_max.clone()
# enumerate xrange
for i in range(1, self.num + 1):
thres = xrange / self.num * i
new_min = torch.zeros_like(x_min) if self.one_side_dist == 'pos' else -thres
new_max = torch.zeros_like(x_max) if self.one_side_dist == 'neg' else thres
x_q = self.quantize(x, new_max, new_min)
score = self.lp_loss(x, x_q, 2.4)
best_min = torch.where(score < best_score, new_min, best_min)
best_max = torch.where(score < best_score, new_max, best_max)
best_score = torch.min(score, best_score)
return best_min, best_max
def get_x_min_x_max(self, x):
if self.scale_method != 'mse':
raise NotImplementedError
if self.one_side_dist is None:
self.one_side_dist = 'pos' if x.min() >= 0.0 else 'neg' if x.max() <= 0.0 else 'no'
if self.one_side_dist != 'no' or self.sym: # one-side distribution or symmetric value for 1-d search
best_min, best_max = self.perform_1D_search(x)
else: # 2-d search
best_min, best_max = self.perform_2D_search(x)
if self.leaf_param:
return self.update_quantize_range(best_min, best_max)
return best_min, best_max
def init_quantization_scale_channel(self, x: torch.Tensor):
x_min, x_max = self.get_x_min_x_max(x)
return self.calculate_qparams(x_min, x_max)
def init_quantization_scale(self, x_clone: torch.Tensor, channel_wise: bool = False):
if channel_wise:
# determine the scale and zero point channel-by-channel
delta, zero_point = self.init_quantization_scale_channel(x_clone)
new_shape = [1] * len(x_clone.shape)
new_shape[0] = x_clone.shape[0]
delta = delta.reshape(new_shape)
zero_point = zero_point.reshape(new_shape)
else:
delta, zero_point = self.init_quantization_scale_channel(x_clone)
return delta, zero_point
def bitwidth_refactor(self, refactored_bit: int):
assert 2 <= refactored_bit <= 8, 'bitwidth not supported'
self.n_bits = refactored_bit
self.n_levels = 2 ** self.n_bits
@torch.jit.export
def extra_repr(self):
return 'bit={}, is_training={}, inited={}'.format(
self.n_bits, self.is_training, self.inited
)
class QuantModule(nn.Module):
"""
Quantized Module that can perform quantized convolution or normal convolution.
To activate quantization, please use set_quant_state function.
"""
def __init__(self, org_module: Union[nn.Conv2d, nn.Linear], weight_quant_params: dict = {},
act_quant_params: dict = {}, disable_act_quant=False):
super(QuantModule, self).__init__()
if isinstance(org_module, nn.Conv2d):
self.fwd_kwargs = dict(stride=org_module.stride, padding=org_module.padding,
dilation=org_module.dilation, groups=org_module.groups)
self.fwd_func = F.conv2d
else:
self.fwd_kwargs = dict()
self.fwd_func = F.linear
self.weight = org_module.weight
self.org_weight = org_module.weight.data.clone()
if org_module.bias is not None:
self.bias = org_module.bias
self.org_bias = org_module.bias.data.clone()
else:
self.bias = None
self.org_bias = None
# de-activate the quantized forward default
self.use_weight_quant = False
self.use_act_quant = False
# initialize quantizer
self.weight_quantizer = UniformAffineQuantizer(**weight_quant_params)
self.act_quantizer = UniformAffineQuantizer(**act_quant_params)
self.activation_function = StraightThrough()
self.ignore_reconstruction = False
self.disable_act_quant = disable_act_quant
def forward(self, input: torch.Tensor):
if self.use_weight_quant:
weight = self.weight_quantizer(self.weight)
bias = self.bias
else:
weight = self.org_weight
bias = self.org_bias
out = self.fwd_func(input, weight, bias, **self.fwd_kwargs)
# disable act quantization is designed for convolution before elemental-wise operation,
# in that case, we apply activation function and quantization after ele-wise op.
out = self.activation_function(out)
if self.disable_act_quant:
return out
if self.use_act_quant:
out = self.act_quantizer(out)
return out
def set_quant_state(self, weight_quant: bool = False, act_quant: bool = False):
self.use_weight_quant = weight_quant
self.use_act_quant = act_quant
@torch.jit.export
def extra_repr(self):
return 'wbit={}, abit={}, disable_act_quant={}'.format(
self.weight_quantizer.n_bits, self.act_quantizer.n_bits, self.disable_act_quant
)