-
Notifications
You must be signed in to change notification settings - Fork 1
/
_binary_base_plus.py
247 lines (198 loc) · 8.12 KB
/
_binary_base_plus.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
"""
Quantized modules: the base class
"""
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
import math
from enum import Enum
__all__ = ['Qmodes', '_Conv2dB', '_LinearB', '_ActB', '_ActB_qk',
'truncation', 'get_sparsity_mask', 'FunStopGradient', 'round_pass', 'grad_scale']
class Qmodes(Enum):
layer_wise = 1
kernel_wise = 2
def grad_scale(x, scale):
y = x
y_grad = x * scale
return y.detach() - y_grad.detach() + y_grad
def get_sparsity_mask(param, sparsity):
bottomk, _ = torch.topk(param.abs().view(-1), int(sparsity * param.numel()), largest=False, sorted=True)
threshold = bottomk.data[-1] # This is the largest element from the group of elements that we prune away
return torch.gt(torch.abs(param), threshold).type(param.type())
def round_pass(x):
y = x.round()
y_grad = x
return y.detach() - y_grad.detach() + y_grad
class FunStopGradient(torch.autograd.Function):
@staticmethod
def forward(ctx, weight, stopGradientMask):
ctx.save_for_backward(stopGradientMask)
return weight
@staticmethod
def backward(ctx, grad_outputs):
stopGradientMask, = ctx.saved_tensors
grad_inputs = grad_outputs * stopGradientMask
return grad_inputs, None
def log_shift(value_fp):
value_shift = 2 ** (torch.log2(value_fp).ceil())
return value_shift
def clamp(input, min, max, inplace=False):
if inplace:
input.clamp_(min, max)
return input
return torch.clamp(input, min, max)
def get_quantized_range(num_bits, signed=True):
if signed:
n = 2 ** (num_bits - 1)
return -n, n - 1
return 0, 2 ** num_bits - 1
def linear_quantize(input, scale_factor, inplace=False):
if inplace:
input.mul_(scale_factor).round_()
return input
return torch.round(scale_factor * input)
def linear_quantize_clamp(input, scale_factor, clamp_min, clamp_max, inplace=False):
output = linear_quantize(input, scale_factor, inplace)
return clamp(output, clamp_min, clamp_max, inplace)
def linear_dequantize(input, scale_factor, inplace=False):
if inplace:
input.div_(scale_factor)
return input
return input / scale_factor
def truncation(fp_data, nbits=8):
il = torch.log2(torch.max(fp_data.max(), fp_data.min().abs())) + 1
il = math.ceil(il - 1e-5)
qcode = nbits - il
scale_factor = 2 ** qcode
clamp_min, clamp_max = get_quantized_range(nbits, signed=True)
q_data = linear_quantize_clamp(fp_data, scale_factor, clamp_min, clamp_max)
q_data = linear_dequantize(q_data, scale_factor)
return q_data, qcode
def get_default_kwargs_q(kwargs_q, layer_type):
default = {
'nbits': 1
}
if isinstance(layer_type, _Conv2dB):
default.update({
'mode': Qmodes.layer_wise})
elif isinstance(layer_type, _LinearB):
pass
elif isinstance(layer_type, _ActB):
pass
# default.update({
# 'signed': 'Auto'})
else:
assert NotImplementedError
return
for k, v in default.items():
if k not in kwargs_q:
kwargs_q[k] = v
return kwargs_q
class _Conv2dB(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=True, **kwargs_q):
super(_Conv2dB, self).__init__(in_channels, out_channels, kernel_size, stride=stride,
padding=padding, dilation=dilation, groups=groups, bias=bias)
self.kwargs_q = get_default_kwargs_q(kwargs_q, layer_type=self)
self.nbits = kwargs_q['nbits']
if self.nbits < 0:
self.register_parameter('alpha', None)
return
self.q_mode = kwargs_q['mode']
if self.q_mode == Qmodes.kernel_wise:
self.alpha = Parameter(torch.Tensor(out_channels))
else: # layer-wise quantization
self.alpha = Parameter(torch.Tensor(1))
self.register_buffer('init_state', torch.zeros(1))
def add_param(self, param_k, param_v):
self.kwargs_q[param_k] = param_v
def set_bit(self, nbits):
self.kwargs_q['nbits'] = nbits
def extra_repr(self):
s_prefix = super(_Conv2dB, self).extra_repr()
if self.alpha is None:
return '{}, fake'.format(s_prefix)
return '{}, {}'.format(s_prefix, self.kwargs_q)
class _LinearB(nn.Linear):
def __init__(self, in_features, out_features, bias=True, **kwargs_q):
super(_LinearB, self).__init__(in_features=in_features, out_features=out_features, bias=bias)
self.kwargs_q = get_default_kwargs_q(kwargs_q, layer_type=self)
self.nbits = kwargs_q['nbits']
if self.nbits < 0:
self.register_parameter('alpha', None)
return
self.q_mode = kwargs_q['mode']
self.alpha = Parameter(torch.Tensor(1))
if self.q_mode == Qmodes.kernel_wise:
self.alpha = Parameter(torch.Tensor(out_features))
self.register_buffer('init_state', torch.zeros(1))
def add_param(self, param_k, param_v):
self.kwargs_q[param_k] = param_v
def extra_repr(self):
s_prefix = super(_LinearB, self).extra_repr()
if self.alpha is None:
return '{}, fake'.format(s_prefix)
return '{}, {}'.format(s_prefix, self.kwargs_q)
class _ActB(nn.Module):
def __init__(self, in_features, **kwargs_q):
super(_ActB, self).__init__()
self.kwargs_q = get_default_kwargs_q(kwargs_q, layer_type=self)
self.nbits = kwargs_q['nbits']
if self.nbits < 0:
self.register_parameter('alpha', None)
self.register_parameter('zero_point', None)
return
# self.signed = kwargs_q['signed']
self.q_mode = kwargs_q['mode']
self.alpha = Parameter(torch.Tensor(1))
self.zero_point = Parameter(torch.Tensor([0]))
if self.q_mode == Qmodes.kernel_wise:
self.alpha = Parameter(torch.Tensor(in_features))
self.zero_point = Parameter(torch.Tensor(in_features))
torch.nn.init.zeros_(self.zero_point)
# self.zero_point = Parameter(torch.Tensor([0]))
self.register_buffer('init_state', torch.zeros(1))
self.register_buffer('signed', torch.zeros(1))
def add_param(self, param_k, param_v):
self.kwargs_q[param_k] = param_v
def set_bit(self, nbits):
self.kwargs_q['nbits'] = nbits
def extra_repr(self):
# s_prefix = super(_ActQ, self).extra_repr()
if self.alpha is None:
return 'fake'
return '{}'.format(self.kwargs_q)
class _ActB_qk(nn.Module):
def __init__(self, in_features, **kwargs_q):
super(_ActB_qk, self).__init__()
self.kwargs_q = get_default_kwargs_q(kwargs_q, layer_type=self)
self.nbits = kwargs_q['nbits']
if self.nbits < 0:
self.register_parameter('alpha', None)
self.register_parameter('zero_point', None)
return
# self.signed = kwargs_q['signed']
self.q_mode = kwargs_q['mode']
self.alpha_q = Parameter(torch.Tensor(1))
self.alpha_k = Parameter(torch.Tensor(1))
self.zero_point_q = Parameter(torch.Tensor([0]))
self.zero_point_k = Parameter(torch.Tensor([0]))
if self.q_mode == Qmodes.kernel_wise:
self.alpha_q = Parameter(torch.Tensor(in_features))
self.alpha_k = Parameter(torch.Tensor(in_features))
self.zero_point_q = Parameter(torch.Tensor(in_features))
self.zero_point_k = Parameter(torch.Tensor(in_features))
torch.nn.init.zeros_(self.zero_point_q)
torch.nn.init.zeros_(self.zero_point_k)
# self.zero_point = Parameter(torch.Tensor([0]))
self.register_buffer('init_state', torch.zeros(1))
self.register_buffer('signed', torch.zeros(1))
def add_param(self, param_k, param_v):
self.kwargs_q[param_k] = param_v
def set_bit(self, nbits):
self.kwargs_q['nbits'] = nbits
def extra_repr(self):
# s_prefix = super(_ActQ, self).extra_repr()
if self.alpha_q is None:
return 'fake'
return '{}'.format(self.kwargs_q)