Upload learned functions
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- fn_gen/rnd_search_fb/1/distortion.png +0 -0
- fn_gen/rnd_search_fb/1/expressions.txt +2 -0
- fn_gen/rnd_search_fb/1/fn.py +584 -0
- fn_gen/rnd_search_fb/1/loss.png +0 -0
- fn_gen/rnd_search_fb/1/quantization.png +0 -0
- fn_gen/rnd_search_fb/10/distortion.png +0 -0
- fn_gen/rnd_search_fb/10/expressions.txt +2 -0
- fn_gen/rnd_search_fb/10/fn.py +584 -0
- fn_gen/rnd_search_fb/10/loss.png +0 -0
- fn_gen/rnd_search_fb/10/quantization.png +0 -0
- fn_gen/rnd_search_fb/11/distortion.png +0 -0
- fn_gen/rnd_search_fb/11/expressions.txt +2 -0
- fn_gen/rnd_search_fb/11/fn.py +584 -0
- fn_gen/rnd_search_fb/11/loss.png +0 -0
- fn_gen/rnd_search_fb/11/quantization.png +0 -0
- fn_gen/rnd_search_fb/12/distortion.png +0 -0
- fn_gen/rnd_search_fb/12/expressions.txt +2 -0
- fn_gen/rnd_search_fb/12/fn.py +498 -0
- fn_gen/rnd_search_fb/12/loss.png +0 -0
- fn_gen/rnd_search_fb/12/quantization.png +0 -0
- fn_gen/rnd_search_fb/13/distortion.png +0 -0
- fn_gen/rnd_search_fb/13/expressions.txt +2 -0
- fn_gen/rnd_search_fb/13/fn.py +584 -0
- fn_gen/rnd_search_fb/13/loss.png +0 -0
- fn_gen/rnd_search_fb/13/quantization.png +0 -0
- fn_gen/rnd_search_fb/15/distortion.png +0 -0
- fn_gen/rnd_search_fb/15/expressions.txt +2 -0
- fn_gen/rnd_search_fb/15/fn.py +498 -0
- fn_gen/rnd_search_fb/15/loss.png +0 -0
- fn_gen/rnd_search_fb/15/quantization.png +0 -0
- fn_gen/rnd_search_fb/16/distortion.png +0 -0
- fn_gen/rnd_search_fb/16/expressions.txt +2 -0
- fn_gen/rnd_search_fb/16/fn.py +584 -0
- fn_gen/rnd_search_fb/16/loss.png +0 -0
- fn_gen/rnd_search_fb/16/quantization.png +0 -0
- fn_gen/rnd_search_fb/17/distortion.png +0 -0
- fn_gen/rnd_search_fb/17/expressions.txt +2 -0
- fn_gen/rnd_search_fb/17/fn.py +584 -0
- fn_gen/rnd_search_fb/17/loss.png +0 -0
- fn_gen/rnd_search_fb/17/quantization.png +0 -0
- fn_gen/rnd_search_fb/18/distortion.png +0 -0
- fn_gen/rnd_search_fb/18/expressions.txt +2 -0
- fn_gen/rnd_search_fb/18/fn.py +584 -0
- fn_gen/rnd_search_fb/18/loss.png +0 -0
- fn_gen/rnd_search_fb/18/quantization.png +0 -0
- fn_gen/rnd_search_fb/2/distortion.png +0 -0
- fn_gen/rnd_search_fb/2/expressions.txt +2 -0
- fn_gen/rnd_search_fb/2/fn.py +498 -0
- fn_gen/rnd_search_fb/2/loss.png +0 -0
- fn_gen/rnd_search_fb/2/quantization.png +0 -0
fn_gen/rnd_search_fb/1/distortion.png
ADDED
fn_gen/rnd_search_fb/1/expressions.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
asin(_0*x)/_s
|
2 |
+
sin(_s*x)/_0
|
fn_gen/rnd_search_fb/1/fn.py
ADDED
@@ -0,0 +1,584 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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np
|
8 |
+
|
9 |
+
from scipy.optimize import curve_fit
|
10 |
+
from typing import Dict, Any, Tuple, List, Callable
|
11 |
+
|
12 |
+
|
13 |
+
def quantization(x, **params):
|
14 |
+
return (torch.div(1, replace_num(params['_s'], num=0, to=10000)) * torch.asin(domain_guard((params['_0'] * x), min=-0.99999, max=0.99999, nan=0)))
|
15 |
+
|
16 |
+
|
17 |
+
def dequantization(x, **params):
|
18 |
+
return (torch.div(1, replace_num(params['_0'], num=0, to=10000)) * torch.sin((params['_s'] * x)))
|
19 |
+
|
20 |
+
|
21 |
+
def init_space_search(
|
22 |
+
x: torch.Tensor,
|
23 |
+
**kwargs: Dict[str, Any],
|
24 |
+
) -> torch.Tensor:
|
25 |
+
|
26 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
27 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
28 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
29 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
30 |
+
|
31 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
32 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
33 |
+
torch_tensors = torch.stack(tensors)
|
34 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
35 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
36 |
+
mean = torch.mean(torch_tensors, dim=0)
|
37 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
38 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
39 |
+
|
40 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
41 |
+
x_ = x.transpose(0, 1)
|
42 |
+
x_ = qtz_func(x=x_, **params)
|
43 |
+
x_ = deqtz_func(x=x_, **params)
|
44 |
+
x_ = x_.transpose(0, 1)
|
45 |
+
return x_
|
46 |
+
|
47 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
48 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
49 |
+
assert "params_list" in kwargs, "params list must be provided."
|
50 |
+
assert "param" in kwargs, "param must be provided."
|
51 |
+
|
52 |
+
qtz_func = kwargs.get('qtz_func')
|
53 |
+
deqtz_func = kwargs.get('deqtz_func')
|
54 |
+
params_list = kwargs.get('params_list')
|
55 |
+
param = kwargs.get('param')
|
56 |
+
|
57 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
58 |
+
n_random_params = 50 # Number of random parameters to generate
|
59 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
60 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
61 |
+
|
62 |
+
# Initializes the parameters
|
63 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
64 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
65 |
+
|
66 |
+
# Performs the search
|
67 |
+
for _ in range(n_runs):
|
68 |
+
|
69 |
+
best_params = []
|
70 |
+
for param_ in params:
|
71 |
+
try:
|
72 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
73 |
+
loss_ones = nn.MSELoss()(x, x_)
|
74 |
+
|
75 |
+
if len(best_params) < n_best_to_pick:
|
76 |
+
best_params.append((param_, loss_ones.item()))
|
77 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
78 |
+
elif loss_ones < best_params[-1][1]:
|
79 |
+
best_params[-1] = (param_, loss_ones.item())
|
80 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
81 |
+
|
82 |
+
except Exception: # The parameters might not be valid for the function's domain
|
83 |
+
continue
|
84 |
+
|
85 |
+
# Generates new parameters around the mean
|
86 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
87 |
+
|
88 |
+
# Checks if the best parameter is better than the init_ones
|
89 |
+
p_ones = init_ones(x, **kwargs)
|
90 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
91 |
+
loss_ones = nn.MSELoss()(x, x_)
|
92 |
+
|
93 |
+
# Checks if the best parameter is better than the init_rand
|
94 |
+
p_rand = init_rand(x, **kwargs)
|
95 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
96 |
+
loss_rand = nn.MSELoss()(x, x_)
|
97 |
+
|
98 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
99 |
+
return p_rand
|
100 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
101 |
+
return p_ones
|
102 |
+
else:
|
103 |
+
return best_params[0][0]
|
104 |
+
|
105 |
+
|
106 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
107 |
+
x: torch.Tensor,
|
108 |
+
**kwargs: Dict[str, Any],
|
109 |
+
) -> torch.Tensor:
|
110 |
+
assert "bits" in kwargs, "bits must be provided."
|
111 |
+
assert "params" in kwargs, "params must be provided."
|
112 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
113 |
+
|
114 |
+
bits = kwargs.get('bits')
|
115 |
+
params = kwargs.get('params')
|
116 |
+
qtz_func = kwargs.get('qtz_func')
|
117 |
+
|
118 |
+
x_ = x.transpose(0, 1)
|
119 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
120 |
+
x_ = x_.transpose(0, 1)
|
121 |
+
|
122 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
123 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
124 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
125 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
126 |
+
|
127 |
+
eps = torch.finfo(torch.float32).eps
|
128 |
+
|
129 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
130 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
131 |
+
|
132 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
133 |
+
|
134 |
+
# Introduces some noise in scale
|
135 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
136 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
137 |
+
return scale
|
138 |
+
|
139 |
+
|
140 |
+
def init_params(x: torch.Tensor, **kwargs: Dict[str, Any]) -> Dict[str, nn.Parameter]:
|
141 |
+
params = {
|
142 |
+
'_0': init_space_search(x, qtz_func=quantization, deqtz_func=dequantization, param='_0', params_list=['_0', '_s'], **kwargs),
|
143 |
+
}
|
144 |
+
params['_s'] = init_linear_scale(x, params=params, qtz_func=quantization, **kwargs)
|
145 |
+
params = {k: nn.Parameter(v, requires_grad=False) for k, v in params.items()}
|
146 |
+
|
147 |
+
if 'post_init_hook' in kwargs:
|
148 |
+
kwargs['post_init_hook'](parameters=params)
|
149 |
+
|
150 |
+
|
151 |
+
if 'post_train_hook' in kwargs:
|
152 |
+
kwargs['post_train_hook'](parameters=params)
|
153 |
+
|
154 |
+
return params
|
155 |
+
|
156 |
+
|
157 |
+
############### Numpy Qtz ###############
|
158 |
+
|
159 |
+
|
160 |
+
def np_quantization(x, _0, _s):
|
161 |
+
return (np.divide(1, np_replace_num(_s, num=0, to=10000)) * np.arcsin(np_domain_guard((_0 * x), min=-0.99999, max=0.99999, nan=0)))
|
162 |
+
|
163 |
+
|
164 |
+
def np_dequantization(x, _0, _s):
|
165 |
+
return (np.divide(1, np_replace_num(_0, num=0, to=10000)) * np.sin((_s * x)))
|
166 |
+
|
167 |
+
|
168 |
+
def fit_func(x, _0, _s):
|
169 |
+
x_ = np_quantization(x, _0, _s)
|
170 |
+
x_ = np_dequantization(x_, _0, _s)
|
171 |
+
return x_
|
172 |
+
|
173 |
+
|
174 |
+
|
175 |
+
############### HELPERS ###############
|
176 |
+
|
177 |
+
def domain_guard(
|
178 |
+
x: torch.Tensor,
|
179 |
+
min: float = None,
|
180 |
+
max: float = None,
|
181 |
+
posinf: float = None,
|
182 |
+
neginf: float = None,
|
183 |
+
nan: float = None
|
184 |
+
) -> torch.Tensor:
|
185 |
+
"""Guard a tensor to a valid domain."""
|
186 |
+
x = torch.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
187 |
+
if min is not None or max is not None:
|
188 |
+
x = torch.clamp(x, min=min, max=max)
|
189 |
+
return x
|
190 |
+
|
191 |
+
|
192 |
+
def replace_num(x: torch.Tensor, num: float, to: float) -> torch.Tensor:
|
193 |
+
"""Replace a number in a tensor with another number.
|
194 |
+
|
195 |
+
Args:
|
196 |
+
x (torch.Tensor): The input tensor.
|
197 |
+
num (float): The number to replace.
|
198 |
+
to (float): The number to replace with.
|
199 |
+
|
200 |
+
Returns:
|
201 |
+
torch.Tensor: The tensor with the number replaced.
|
202 |
+
"""
|
203 |
+
return torch.where(x == num, to, x)
|
204 |
+
|
205 |
+
|
206 |
+
def guarded_torch_power(x: torch.Tensor, exp: float) -> torch.Tensor:
|
207 |
+
"""Guard the power operation to a valid domain."""
|
208 |
+
return torch.pow(x, exp) if exp >= 1 else torch.pow(torch.relu(x), exp)
|
209 |
+
|
210 |
+
|
211 |
+
def init_ones(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
212 |
+
val = torch.amin(x, dim=1)
|
213 |
+
return torch.ones_like(val, dtype=torch.float32, device=x.device)
|
214 |
+
|
215 |
+
|
216 |
+
def init_rand(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
217 |
+
val = torch.amin(x, dim=1)
|
218 |
+
return torch.randn_like(val, dtype=torch.float32, device=x.device)
|
219 |
+
|
220 |
+
|
221 |
+
def init_space_search(
|
222 |
+
x: torch.Tensor,
|
223 |
+
**kwargs: Dict[str, Any],
|
224 |
+
) -> torch.Tensor:
|
225 |
+
|
226 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
227 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
228 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
229 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
230 |
+
|
231 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
232 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
233 |
+
torch_tensors = torch.stack(tensors)
|
234 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
235 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
236 |
+
mean = torch.mean(torch_tensors, dim=0)
|
237 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
238 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
239 |
+
|
240 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
241 |
+
x_ = x.transpose(0, 1)
|
242 |
+
x_ = qtz_func(x=x_, **params)
|
243 |
+
x_ = deqtz_func(x=x_, **params)
|
244 |
+
x_ = x_.transpose(0, 1)
|
245 |
+
return x_
|
246 |
+
|
247 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
248 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
249 |
+
assert "params_list" in kwargs, "params list must be provided."
|
250 |
+
assert "param" in kwargs, "param must be provided."
|
251 |
+
|
252 |
+
qtz_func = kwargs.get('qtz_func')
|
253 |
+
deqtz_func = kwargs.get('deqtz_func')
|
254 |
+
params_list = kwargs.get('params_list')
|
255 |
+
param = kwargs.get('param')
|
256 |
+
|
257 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
258 |
+
n_random_params = 50 # Number of random parameters to generate
|
259 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
260 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
261 |
+
|
262 |
+
# Initializes the parameters
|
263 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
264 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
265 |
+
|
266 |
+
# Performs the search
|
267 |
+
for _ in range(n_runs):
|
268 |
+
|
269 |
+
best_params = []
|
270 |
+
for param_ in params:
|
271 |
+
try:
|
272 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
273 |
+
loss_ones = nn.MSELoss()(x, x_)
|
274 |
+
|
275 |
+
if len(best_params) < n_best_to_pick:
|
276 |
+
best_params.append((param_, loss_ones.item()))
|
277 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
278 |
+
elif loss_ones < best_params[-1][1]:
|
279 |
+
best_params[-1] = (param_, loss_ones.item())
|
280 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
281 |
+
|
282 |
+
except Exception: # The parameters might not be valid for the function's domain
|
283 |
+
continue
|
284 |
+
|
285 |
+
# Generates new parameters around the mean
|
286 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
287 |
+
|
288 |
+
# Checks if the best parameter is better than the init_ones
|
289 |
+
p_ones = init_ones(x, **kwargs)
|
290 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
291 |
+
loss_ones = nn.MSELoss()(x, x_)
|
292 |
+
|
293 |
+
# Checks if the best parameter is better than the init_rand
|
294 |
+
p_rand = init_rand(x, **kwargs)
|
295 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
296 |
+
loss_rand = nn.MSELoss()(x, x_)
|
297 |
+
|
298 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
299 |
+
return p_rand
|
300 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
301 |
+
return p_ones
|
302 |
+
else:
|
303 |
+
return best_params[0][0]
|
304 |
+
|
305 |
+
|
306 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
307 |
+
x: torch.Tensor,
|
308 |
+
**kwargs: Dict[str, Any],
|
309 |
+
) -> torch.Tensor:
|
310 |
+
assert "bits" in kwargs, "bits must be provided."
|
311 |
+
assert "params" in kwargs, "params must be provided."
|
312 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
313 |
+
|
314 |
+
bits = kwargs.get('bits')
|
315 |
+
params = kwargs.get('params')
|
316 |
+
qtz_func = kwargs.get('qtz_func')
|
317 |
+
|
318 |
+
x_ = x.transpose(0, 1)
|
319 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
320 |
+
x_ = x_.transpose(0, 1)
|
321 |
+
|
322 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
323 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
324 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
325 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
326 |
+
|
327 |
+
eps = torch.finfo(torch.float32).eps
|
328 |
+
|
329 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
330 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
331 |
+
|
332 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
333 |
+
|
334 |
+
# Introduces some noise in scale
|
335 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
336 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
337 |
+
return scale
|
338 |
+
|
339 |
+
|
340 |
+
def init_non_linear_regression_fit(
|
341 |
+
x: torch.Tensor,
|
342 |
+
**kwargs: Dict[str, Any],
|
343 |
+
) -> torch.Tensor:
|
344 |
+
|
345 |
+
assert "params_list" in kwargs, "params list must be provided."
|
346 |
+
assert "np_fit_func" in kwargs, "np_fit_func must be provided."
|
347 |
+
assert "p0" in kwargs, "p0 must be provided."
|
348 |
+
np_fit_func = kwargs.get('np_fit_func')
|
349 |
+
params_list = kwargs.get('params_list')
|
350 |
+
p0 = kwargs.get('p0')
|
351 |
+
|
352 |
+
def _fit(xdata: np.ndarray, ydata: np.ndarray, func: Callable, p0: List[float]):
|
353 |
+
popt, _ = curve_fit(
|
354 |
+
func,
|
355 |
+
xdata,
|
356 |
+
ydata,
|
357 |
+
maxfev=1000,
|
358 |
+
p0=p0,
|
359 |
+
method='lm'
|
360 |
+
)
|
361 |
+
return popt
|
362 |
+
|
363 |
+
# 1. Needs to convert the torch tensor to numpy tensor
|
364 |
+
xdata = x.cpu().numpy()
|
365 |
+
|
366 |
+
# 2. Sorts the data so that it makes it easier to fit to it
|
367 |
+
sorted_xdata = np.sort(xdata, axis=-1)
|
368 |
+
|
369 |
+
p0 = {k: v.cpu().numpy() for k, v in p0.items()}
|
370 |
+
params_list = sorted(params_list) # We need to make sure that it matches the numpy fit func arg order
|
371 |
+
|
372 |
+
# 3. Finds the best parameters for each channel
|
373 |
+
try:
|
374 |
+
params = []
|
375 |
+
for i in range(sorted_xdata.shape[0]):
|
376 |
+
xdata_ = sorted_xdata[i]
|
377 |
+
p0_ = [p0[p][i] for p in params_list]
|
378 |
+
ch_params = _fit(xdata_, xdata_, np_fit_func, p0_)
|
379 |
+
params.append(ch_params)
|
380 |
+
|
381 |
+
# 4. Builds the parameters
|
382 |
+
result = {}
|
383 |
+
for i, p in enumerate(params_list):
|
384 |
+
result[p] = torch.tensor([p_[i] for p_ in params], dtype=torch.float32).to(x.device)
|
385 |
+
|
386 |
+
return result
|
387 |
+
|
388 |
+
except ValueError as e:
|
389 |
+
print(f"Could not fit the function with error: {e}")
|
390 |
+
print(f"Using fallback result...")
|
391 |
+
return {
|
392 |
+
k: torch.tensor(v, dtype=torch.float32).to(x.device) for k, v in p0.items()
|
393 |
+
}
|
394 |
+
|
395 |
+
|
396 |
+
def init_zeros(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
397 |
+
val = torch.amin(x, dim=1)
|
398 |
+
return torch.zeros_like(val, dtype=torch.float32, device=x.device)
|
399 |
+
|
400 |
+
|
401 |
+
def init_inner_scale(tensor: torch.Tensor, _min: float = torch.inf, _max: float = torch.inf) -> torch.Tensor:
|
402 |
+
# Calculate the original minimum and maximum values
|
403 |
+
min_vals, max_vals = torch.aminmax(tensor, dim=-1)
|
404 |
+
x_min = torch.min(min_vals, torch.zeros_like(min_vals))
|
405 |
+
x_max = torch.max(max_vals, torch.zeros_like(max_vals))
|
406 |
+
|
407 |
+
if _max is torch.inf: # We do not need to scale the tensor. Just need to move it
|
408 |
+
return torch.ones_like(x_min)
|
409 |
+
|
410 |
+
# Calculate the scale factor
|
411 |
+
scale = (_max - _min) / (x_max - x_min)
|
412 |
+
return scale
|
413 |
+
|
414 |
+
|
415 |
+
|
416 |
+
############## Quant ###############
|
417 |
+
|
418 |
+
@torch.enable_grad()
|
419 |
+
def learn_parameters(
|
420 |
+
x: torch.Tensor,
|
421 |
+
params: Dict[str, nn.Parameter],
|
422 |
+
qtz_func: nn.Module,
|
423 |
+
deqtz_func: nn.Module,
|
424 |
+
bits: int,
|
425 |
+
target_dtype: torch.dtype,
|
426 |
+
epochs: int = 1000,
|
427 |
+
early_stop: bool = True,
|
428 |
+
do_report: bool = False
|
429 |
+
) -> Tuple[Dict[str, nn.Parameter], torch.Tensor]:
|
430 |
+
loss_fn = nn.MSELoss()
|
431 |
+
|
432 |
+
# Determines the initial learning rate by computing the initial loss and multiplying it by
|
433 |
+
# the order of magnitude of the loss divided by 2
|
434 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
435 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
436 |
+
loss = loss_fn(x, dequant)
|
437 |
+
|
438 |
+
base_lr = 0.1
|
439 |
+
exponent = int(np.floor(np.log10(loss.item())))
|
440 |
+
lr = base_lr * (10 ** (exponent // 2))
|
441 |
+
|
442 |
+
# Requires gradients in the parameters
|
443 |
+
for p in params.values():
|
444 |
+
p.requires_grad = True
|
445 |
+
p.grad = None
|
446 |
+
|
447 |
+
param_keys = list(params.keys())
|
448 |
+
param_values = list(params.values())
|
449 |
+
|
450 |
+
# Defines optimizer and loss function
|
451 |
+
optimizer = torch.optim.Adam(param_values, lr=lr)
|
452 |
+
scheduler = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=1.0, end_factor=0.01, total_iters=epochs // 10)
|
453 |
+
|
454 |
+
# Contains the best loss and the best parameters
|
455 |
+
best_loss = float("inf")
|
456 |
+
best_params = None
|
457 |
+
|
458 |
+
# Used to stop the search early
|
459 |
+
min_delta = 1e-7
|
460 |
+
acc_loss = []
|
461 |
+
percent_epochs_before_stop = 0.1
|
462 |
+
|
463 |
+
for i in range(epochs):
|
464 |
+
optimizer.zero_grad()
|
465 |
+
|
466 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
467 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
468 |
+
loss = loss_fn(x, dequant)
|
469 |
+
|
470 |
+
if loss.isnan() or loss.isinf():
|
471 |
+
raise Exception("Loss is NaN or Inf. Stopping the search.")
|
472 |
+
|
473 |
+
loss.backward()
|
474 |
+
optimizer.step()
|
475 |
+
scheduler.step()
|
476 |
+
|
477 |
+
acc_loss.append(loss.item())
|
478 |
+
|
479 |
+
# Reports loss every 10 steps
|
480 |
+
if i % 10 == 0 and do_report:
|
481 |
+
print(f"Epoch {i}: Loss {loss.item()}")
|
482 |
+
|
483 |
+
# Optimizes the parameter search by storing the best loss and the parameters
|
484 |
+
if loss.item() < best_loss:
|
485 |
+
best_loss = loss.item()
|
486 |
+
best_params = copy.deepcopy({
|
487 |
+
k: v for k, v in params.items() if k in param_keys
|
488 |
+
})
|
489 |
+
|
490 |
+
# We also stop the search if the loss has not considerably during the last 10% epochs
|
491 |
+
if early_stop:
|
492 |
+
epochs_before_stop = int(epochs * percent_epochs_before_stop)
|
493 |
+
if i > epochs_before_stop and abs(acc_loss[i - epochs_before_stop] - acc_loss[i]) < min_delta:
|
494 |
+
break
|
495 |
+
|
496 |
+
# No longer requires gradients in the parameters
|
497 |
+
for p in best_params.values():
|
498 |
+
p.requires_grad = False
|
499 |
+
p.grad = None
|
500 |
+
|
501 |
+
if do_report:
|
502 |
+
return best_params, acc_loss
|
503 |
+
else:
|
504 |
+
return best_params
|
505 |
+
|
506 |
+
|
507 |
+
def quantize(
|
508 |
+
x: torch.Tensor,
|
509 |
+
params: Dict[str, nn.Parameter],
|
510 |
+
func: nn.Module,
|
511 |
+
bits: int,
|
512 |
+
target_dtype: torch.dtype = torch.int8
|
513 |
+
) -> torch.Tensor:
|
514 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
515 |
+
x = x.transpose(0, 1) # Aligns shapes
|
516 |
+
x = func(x=x, **params)
|
517 |
+
x = x.transpose(0, 1)
|
518 |
+
x = torch.clamp(round_func_BPDA(x), quant_min, quant_max).to(target_dtype)
|
519 |
+
return x
|
520 |
+
|
521 |
+
|
522 |
+
def dequantize(
|
523 |
+
x: torch.Tensor,
|
524 |
+
params: Dict[str, nn.Parameter],
|
525 |
+
func: nn.Module,
|
526 |
+
bits: int,
|
527 |
+
out_dtype: torch.dtype
|
528 |
+
) -> torch.Tensor:
|
529 |
+
x = x.to(dtype=out_dtype)
|
530 |
+
x = x.transpose(0, 1)
|
531 |
+
x = func(x=x, **params)
|
532 |
+
x = x.transpose(0, 1)
|
533 |
+
return x
|
534 |
+
|
535 |
+
|
536 |
+
def round_func_BPDA(input):
|
537 |
+
# This is equivalent to replacing round function (non-differentiable) with
|
538 |
+
# an identity function (differentiable) only when backward.
|
539 |
+
forward_value = torch.round(input)
|
540 |
+
out = input.clone()
|
541 |
+
out.data = forward_value.data
|
542 |
+
return out
|
543 |
+
|
544 |
+
|
545 |
+
def get_min_max_from_bits_signed(bit_width: int) -> Tuple[int, int]:
|
546 |
+
return -2 ** (bit_width - 1), 2 ** (bit_width - 1) - 1
|
547 |
+
|
548 |
+
|
549 |
+
|
550 |
+
############## Numpy ###############
|
551 |
+
|
552 |
+
def np_domain_guard(
|
553 |
+
x: np.ndarray,
|
554 |
+
min: float = None,
|
555 |
+
max: float = None,
|
556 |
+
posinf: float = None,
|
557 |
+
neginf: float = None,
|
558 |
+
nan: float = None
|
559 |
+
) -> np.ndarray:
|
560 |
+
"""Guard a tensor to a valid domain."""
|
561 |
+
x = np.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
562 |
+
if min is not None or max is not None:
|
563 |
+
x = np.clip(x, min, max)
|
564 |
+
return x
|
565 |
+
|
566 |
+
|
567 |
+
def np_replace_num(x: np.ndarray, num: float, to: float) -> np.ndarray:
|
568 |
+
"""Replace a number in a tensor with another number.
|
569 |
+
|
570 |
+
Args:
|
571 |
+
x (np.ndarray): The input tensor.
|
572 |
+
num (float): The number to replace.
|
573 |
+
to (float): The number to replace with.
|
574 |
+
|
575 |
+
Returns:
|
576 |
+
np.ndarray: The tensor with the number replaced.
|
577 |
+
"""
|
578 |
+
return np.where(x == num, to, x)
|
579 |
+
|
580 |
+
|
581 |
+
def np_guarded_power(x: np.ndarray, exp: float) -> np.ndarray:
|
582 |
+
"""Guard the power operation to a valid domain."""
|
583 |
+
return np.power(x, exp) if exp >= 1 else np.power(np.maximum(x, 0), exp)
|
584 |
+
|
fn_gen/rnd_search_fb/1/loss.png
ADDED
fn_gen/rnd_search_fb/1/quantization.png
ADDED
fn_gen/rnd_search_fb/10/distortion.png
ADDED
fn_gen/rnd_search_fb/10/expressions.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
asinh(_0*x)/_s
|
2 |
+
sinh(_s*x)/_0
|
fn_gen/rnd_search_fb/10/fn.py
ADDED
@@ -0,0 +1,584 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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# Necessary for arcsin
|
5 |
+
import copy
|
6 |
+
import torch.nn as nn
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
from scipy.optimize import curve_fit
|
10 |
+
from typing import Dict, Any, Tuple, List, Callable
|
11 |
+
|
12 |
+
|
13 |
+
def quantization(x, **params):
|
14 |
+
return (torch.div(1, replace_num(params['_s'], num=0, to=10000)) * torch.asinh((params['_0'] * x)))
|
15 |
+
|
16 |
+
|
17 |
+
def dequantization(x, **params):
|
18 |
+
return (torch.div(1, replace_num(params['_0'], num=0, to=10000)) * torch.sinh((params['_s'] * x)))
|
19 |
+
|
20 |
+
|
21 |
+
def init_space_search(
|
22 |
+
x: torch.Tensor,
|
23 |
+
**kwargs: Dict[str, Any],
|
24 |
+
) -> torch.Tensor:
|
25 |
+
|
26 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
27 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
28 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
29 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
30 |
+
|
31 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
32 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
33 |
+
torch_tensors = torch.stack(tensors)
|
34 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
35 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
36 |
+
mean = torch.mean(torch_tensors, dim=0)
|
37 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
38 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
39 |
+
|
40 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
41 |
+
x_ = x.transpose(0, 1)
|
42 |
+
x_ = qtz_func(x=x_, **params)
|
43 |
+
x_ = deqtz_func(x=x_, **params)
|
44 |
+
x_ = x_.transpose(0, 1)
|
45 |
+
return x_
|
46 |
+
|
47 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
48 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
49 |
+
assert "params_list" in kwargs, "params list must be provided."
|
50 |
+
assert "param" in kwargs, "param must be provided."
|
51 |
+
|
52 |
+
qtz_func = kwargs.get('qtz_func')
|
53 |
+
deqtz_func = kwargs.get('deqtz_func')
|
54 |
+
params_list = kwargs.get('params_list')
|
55 |
+
param = kwargs.get('param')
|
56 |
+
|
57 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
58 |
+
n_random_params = 50 # Number of random parameters to generate
|
59 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
60 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
61 |
+
|
62 |
+
# Initializes the parameters
|
63 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
64 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
65 |
+
|
66 |
+
# Performs the search
|
67 |
+
for _ in range(n_runs):
|
68 |
+
|
69 |
+
best_params = []
|
70 |
+
for param_ in params:
|
71 |
+
try:
|
72 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
73 |
+
loss_ones = nn.MSELoss()(x, x_)
|
74 |
+
|
75 |
+
if len(best_params) < n_best_to_pick:
|
76 |
+
best_params.append((param_, loss_ones.item()))
|
77 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
78 |
+
elif loss_ones < best_params[-1][1]:
|
79 |
+
best_params[-1] = (param_, loss_ones.item())
|
80 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
81 |
+
|
82 |
+
except Exception: # The parameters might not be valid for the function's domain
|
83 |
+
continue
|
84 |
+
|
85 |
+
# Generates new parameters around the mean
|
86 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
87 |
+
|
88 |
+
# Checks if the best parameter is better than the init_ones
|
89 |
+
p_ones = init_ones(x, **kwargs)
|
90 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
91 |
+
loss_ones = nn.MSELoss()(x, x_)
|
92 |
+
|
93 |
+
# Checks if the best parameter is better than the init_rand
|
94 |
+
p_rand = init_rand(x, **kwargs)
|
95 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
96 |
+
loss_rand = nn.MSELoss()(x, x_)
|
97 |
+
|
98 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
99 |
+
return p_rand
|
100 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
101 |
+
return p_ones
|
102 |
+
else:
|
103 |
+
return best_params[0][0]
|
104 |
+
|
105 |
+
|
106 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
107 |
+
x: torch.Tensor,
|
108 |
+
**kwargs: Dict[str, Any],
|
109 |
+
) -> torch.Tensor:
|
110 |
+
assert "bits" in kwargs, "bits must be provided."
|
111 |
+
assert "params" in kwargs, "params must be provided."
|
112 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
113 |
+
|
114 |
+
bits = kwargs.get('bits')
|
115 |
+
params = kwargs.get('params')
|
116 |
+
qtz_func = kwargs.get('qtz_func')
|
117 |
+
|
118 |
+
x_ = x.transpose(0, 1)
|
119 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
120 |
+
x_ = x_.transpose(0, 1)
|
121 |
+
|
122 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
123 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
124 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
125 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
126 |
+
|
127 |
+
eps = torch.finfo(torch.float32).eps
|
128 |
+
|
129 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
130 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
131 |
+
|
132 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
133 |
+
|
134 |
+
# Introduces some noise in scale
|
135 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
136 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
137 |
+
return scale
|
138 |
+
|
139 |
+
|
140 |
+
def init_params(x: torch.Tensor, **kwargs: Dict[str, Any]) -> Dict[str, nn.Parameter]:
|
141 |
+
params = {
|
142 |
+
'_0': init_space_search(x, qtz_func=quantization, deqtz_func=dequantization, param='_0', params_list=['_0', '_s'], **kwargs),
|
143 |
+
}
|
144 |
+
params['_s'] = init_linear_scale(x, params=params, qtz_func=quantization, **kwargs)
|
145 |
+
params = {k: nn.Parameter(v, requires_grad=False) for k, v in params.items()}
|
146 |
+
|
147 |
+
if 'post_init_hook' in kwargs:
|
148 |
+
kwargs['post_init_hook'](parameters=params)
|
149 |
+
|
150 |
+
|
151 |
+
if 'post_train_hook' in kwargs:
|
152 |
+
kwargs['post_train_hook'](parameters=params)
|
153 |
+
|
154 |
+
return params
|
155 |
+
|
156 |
+
|
157 |
+
############### Numpy Qtz ###############
|
158 |
+
|
159 |
+
|
160 |
+
def np_quantization(x, _0, _s):
|
161 |
+
return (np.divide(1, np_replace_num(_s, num=0, to=10000)) * np.arcsinh((_0 * x)))
|
162 |
+
|
163 |
+
|
164 |
+
def np_dequantization(x, _0, _s):
|
165 |
+
return (np.divide(1, np_replace_num(_0, num=0, to=10000)) * np.sinh((_s * x)))
|
166 |
+
|
167 |
+
|
168 |
+
def fit_func(x, _0, _s):
|
169 |
+
x_ = np_quantization(x, _0, _s)
|
170 |
+
x_ = np_dequantization(x_, _0, _s)
|
171 |
+
return x_
|
172 |
+
|
173 |
+
|
174 |
+
|
175 |
+
############### HELPERS ###############
|
176 |
+
|
177 |
+
def domain_guard(
|
178 |
+
x: torch.Tensor,
|
179 |
+
min: float = None,
|
180 |
+
max: float = None,
|
181 |
+
posinf: float = None,
|
182 |
+
neginf: float = None,
|
183 |
+
nan: float = None
|
184 |
+
) -> torch.Tensor:
|
185 |
+
"""Guard a tensor to a valid domain."""
|
186 |
+
x = torch.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
187 |
+
if min is not None or max is not None:
|
188 |
+
x = torch.clamp(x, min=min, max=max)
|
189 |
+
return x
|
190 |
+
|
191 |
+
|
192 |
+
def replace_num(x: torch.Tensor, num: float, to: float) -> torch.Tensor:
|
193 |
+
"""Replace a number in a tensor with another number.
|
194 |
+
|
195 |
+
Args:
|
196 |
+
x (torch.Tensor): The input tensor.
|
197 |
+
num (float): The number to replace.
|
198 |
+
to (float): The number to replace with.
|
199 |
+
|
200 |
+
Returns:
|
201 |
+
torch.Tensor: The tensor with the number replaced.
|
202 |
+
"""
|
203 |
+
return torch.where(x == num, to, x)
|
204 |
+
|
205 |
+
|
206 |
+
def guarded_torch_power(x: torch.Tensor, exp: float) -> torch.Tensor:
|
207 |
+
"""Guard the power operation to a valid domain."""
|
208 |
+
return torch.pow(x, exp) if exp >= 1 else torch.pow(torch.relu(x), exp)
|
209 |
+
|
210 |
+
|
211 |
+
def init_ones(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
212 |
+
val = torch.amin(x, dim=1)
|
213 |
+
return torch.ones_like(val, dtype=torch.float32, device=x.device)
|
214 |
+
|
215 |
+
|
216 |
+
def init_rand(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
217 |
+
val = torch.amin(x, dim=1)
|
218 |
+
return torch.randn_like(val, dtype=torch.float32, device=x.device)
|
219 |
+
|
220 |
+
|
221 |
+
def init_space_search(
|
222 |
+
x: torch.Tensor,
|
223 |
+
**kwargs: Dict[str, Any],
|
224 |
+
) -> torch.Tensor:
|
225 |
+
|
226 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
227 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
228 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
229 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
230 |
+
|
231 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
232 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
233 |
+
torch_tensors = torch.stack(tensors)
|
234 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
235 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
236 |
+
mean = torch.mean(torch_tensors, dim=0)
|
237 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
238 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
239 |
+
|
240 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
241 |
+
x_ = x.transpose(0, 1)
|
242 |
+
x_ = qtz_func(x=x_, **params)
|
243 |
+
x_ = deqtz_func(x=x_, **params)
|
244 |
+
x_ = x_.transpose(0, 1)
|
245 |
+
return x_
|
246 |
+
|
247 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
248 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
249 |
+
assert "params_list" in kwargs, "params list must be provided."
|
250 |
+
assert "param" in kwargs, "param must be provided."
|
251 |
+
|
252 |
+
qtz_func = kwargs.get('qtz_func')
|
253 |
+
deqtz_func = kwargs.get('deqtz_func')
|
254 |
+
params_list = kwargs.get('params_list')
|
255 |
+
param = kwargs.get('param')
|
256 |
+
|
257 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
258 |
+
n_random_params = 50 # Number of random parameters to generate
|
259 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
260 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
261 |
+
|
262 |
+
# Initializes the parameters
|
263 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
264 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
265 |
+
|
266 |
+
# Performs the search
|
267 |
+
for _ in range(n_runs):
|
268 |
+
|
269 |
+
best_params = []
|
270 |
+
for param_ in params:
|
271 |
+
try:
|
272 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
273 |
+
loss_ones = nn.MSELoss()(x, x_)
|
274 |
+
|
275 |
+
if len(best_params) < n_best_to_pick:
|
276 |
+
best_params.append((param_, loss_ones.item()))
|
277 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
278 |
+
elif loss_ones < best_params[-1][1]:
|
279 |
+
best_params[-1] = (param_, loss_ones.item())
|
280 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
281 |
+
|
282 |
+
except Exception: # The parameters might not be valid for the function's domain
|
283 |
+
continue
|
284 |
+
|
285 |
+
# Generates new parameters around the mean
|
286 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
287 |
+
|
288 |
+
# Checks if the best parameter is better than the init_ones
|
289 |
+
p_ones = init_ones(x, **kwargs)
|
290 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
291 |
+
loss_ones = nn.MSELoss()(x, x_)
|
292 |
+
|
293 |
+
# Checks if the best parameter is better than the init_rand
|
294 |
+
p_rand = init_rand(x, **kwargs)
|
295 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
296 |
+
loss_rand = nn.MSELoss()(x, x_)
|
297 |
+
|
298 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
299 |
+
return p_rand
|
300 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
301 |
+
return p_ones
|
302 |
+
else:
|
303 |
+
return best_params[0][0]
|
304 |
+
|
305 |
+
|
306 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
307 |
+
x: torch.Tensor,
|
308 |
+
**kwargs: Dict[str, Any],
|
309 |
+
) -> torch.Tensor:
|
310 |
+
assert "bits" in kwargs, "bits must be provided."
|
311 |
+
assert "params" in kwargs, "params must be provided."
|
312 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
313 |
+
|
314 |
+
bits = kwargs.get('bits')
|
315 |
+
params = kwargs.get('params')
|
316 |
+
qtz_func = kwargs.get('qtz_func')
|
317 |
+
|
318 |
+
x_ = x.transpose(0, 1)
|
319 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
320 |
+
x_ = x_.transpose(0, 1)
|
321 |
+
|
322 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
323 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
324 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
325 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
326 |
+
|
327 |
+
eps = torch.finfo(torch.float32).eps
|
328 |
+
|
329 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
330 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
331 |
+
|
332 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
333 |
+
|
334 |
+
# Introduces some noise in scale
|
335 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
336 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
337 |
+
return scale
|
338 |
+
|
339 |
+
|
340 |
+
def init_non_linear_regression_fit(
|
341 |
+
x: torch.Tensor,
|
342 |
+
**kwargs: Dict[str, Any],
|
343 |
+
) -> torch.Tensor:
|
344 |
+
|
345 |
+
assert "params_list" in kwargs, "params list must be provided."
|
346 |
+
assert "np_fit_func" in kwargs, "np_fit_func must be provided."
|
347 |
+
assert "p0" in kwargs, "p0 must be provided."
|
348 |
+
np_fit_func = kwargs.get('np_fit_func')
|
349 |
+
params_list = kwargs.get('params_list')
|
350 |
+
p0 = kwargs.get('p0')
|
351 |
+
|
352 |
+
def _fit(xdata: np.ndarray, ydata: np.ndarray, func: Callable, p0: List[float]):
|
353 |
+
popt, _ = curve_fit(
|
354 |
+
func,
|
355 |
+
xdata,
|
356 |
+
ydata,
|
357 |
+
maxfev=1000,
|
358 |
+
p0=p0,
|
359 |
+
method='lm'
|
360 |
+
)
|
361 |
+
return popt
|
362 |
+
|
363 |
+
# 1. Needs to convert the torch tensor to numpy tensor
|
364 |
+
xdata = x.cpu().numpy()
|
365 |
+
|
366 |
+
# 2. Sorts the data so that it makes it easier to fit to it
|
367 |
+
sorted_xdata = np.sort(xdata, axis=-1)
|
368 |
+
|
369 |
+
p0 = {k: v.cpu().numpy() for k, v in p0.items()}
|
370 |
+
params_list = sorted(params_list) # We need to make sure that it matches the numpy fit func arg order
|
371 |
+
|
372 |
+
# 3. Finds the best parameters for each channel
|
373 |
+
try:
|
374 |
+
params = []
|
375 |
+
for i in range(sorted_xdata.shape[0]):
|
376 |
+
xdata_ = sorted_xdata[i]
|
377 |
+
p0_ = [p0[p][i] for p in params_list]
|
378 |
+
ch_params = _fit(xdata_, xdata_, np_fit_func, p0_)
|
379 |
+
params.append(ch_params)
|
380 |
+
|
381 |
+
# 4. Builds the parameters
|
382 |
+
result = {}
|
383 |
+
for i, p in enumerate(params_list):
|
384 |
+
result[p] = torch.tensor([p_[i] for p_ in params], dtype=torch.float32).to(x.device)
|
385 |
+
|
386 |
+
return result
|
387 |
+
|
388 |
+
except ValueError as e:
|
389 |
+
print(f"Could not fit the function with error: {e}")
|
390 |
+
print(f"Using fallback result...")
|
391 |
+
return {
|
392 |
+
k: torch.tensor(v, dtype=torch.float32).to(x.device) for k, v in p0.items()
|
393 |
+
}
|
394 |
+
|
395 |
+
|
396 |
+
def init_zeros(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
397 |
+
val = torch.amin(x, dim=1)
|
398 |
+
return torch.zeros_like(val, dtype=torch.float32, device=x.device)
|
399 |
+
|
400 |
+
|
401 |
+
def init_inner_scale(tensor: torch.Tensor, _min: float = torch.inf, _max: float = torch.inf) -> torch.Tensor:
|
402 |
+
# Calculate the original minimum and maximum values
|
403 |
+
min_vals, max_vals = torch.aminmax(tensor, dim=-1)
|
404 |
+
x_min = torch.min(min_vals, torch.zeros_like(min_vals))
|
405 |
+
x_max = torch.max(max_vals, torch.zeros_like(max_vals))
|
406 |
+
|
407 |
+
if _max is torch.inf: # We do not need to scale the tensor. Just need to move it
|
408 |
+
return torch.ones_like(x_min)
|
409 |
+
|
410 |
+
# Calculate the scale factor
|
411 |
+
scale = (_max - _min) / (x_max - x_min)
|
412 |
+
return scale
|
413 |
+
|
414 |
+
|
415 |
+
|
416 |
+
############## Quant ###############
|
417 |
+
|
418 |
+
@torch.enable_grad()
|
419 |
+
def learn_parameters(
|
420 |
+
x: torch.Tensor,
|
421 |
+
params: Dict[str, nn.Parameter],
|
422 |
+
qtz_func: nn.Module,
|
423 |
+
deqtz_func: nn.Module,
|
424 |
+
bits: int,
|
425 |
+
target_dtype: torch.dtype,
|
426 |
+
epochs: int = 1000,
|
427 |
+
early_stop: bool = True,
|
428 |
+
do_report: bool = False
|
429 |
+
) -> Tuple[Dict[str, nn.Parameter], torch.Tensor]:
|
430 |
+
loss_fn = nn.MSELoss()
|
431 |
+
|
432 |
+
# Determines the initial learning rate by computing the initial loss and multiplying it by
|
433 |
+
# the order of magnitude of the loss divided by 2
|
434 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
435 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
436 |
+
loss = loss_fn(x, dequant)
|
437 |
+
|
438 |
+
base_lr = 0.1
|
439 |
+
exponent = int(np.floor(np.log10(loss.item())))
|
440 |
+
lr = base_lr * (10 ** (exponent // 2))
|
441 |
+
|
442 |
+
# Requires gradients in the parameters
|
443 |
+
for p in params.values():
|
444 |
+
p.requires_grad = True
|
445 |
+
p.grad = None
|
446 |
+
|
447 |
+
param_keys = list(params.keys())
|
448 |
+
param_values = list(params.values())
|
449 |
+
|
450 |
+
# Defines optimizer and loss function
|
451 |
+
optimizer = torch.optim.Adam(param_values, lr=lr)
|
452 |
+
scheduler = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=1.0, end_factor=0.01, total_iters=epochs // 10)
|
453 |
+
|
454 |
+
# Contains the best loss and the best parameters
|
455 |
+
best_loss = float("inf")
|
456 |
+
best_params = None
|
457 |
+
|
458 |
+
# Used to stop the search early
|
459 |
+
min_delta = 1e-7
|
460 |
+
acc_loss = []
|
461 |
+
percent_epochs_before_stop = 0.1
|
462 |
+
|
463 |
+
for i in range(epochs):
|
464 |
+
optimizer.zero_grad()
|
465 |
+
|
466 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
467 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
468 |
+
loss = loss_fn(x, dequant)
|
469 |
+
|
470 |
+
if loss.isnan() or loss.isinf():
|
471 |
+
raise Exception("Loss is NaN or Inf. Stopping the search.")
|
472 |
+
|
473 |
+
loss.backward()
|
474 |
+
optimizer.step()
|
475 |
+
scheduler.step()
|
476 |
+
|
477 |
+
acc_loss.append(loss.item())
|
478 |
+
|
479 |
+
# Reports loss every 10 steps
|
480 |
+
if i % 10 == 0 and do_report:
|
481 |
+
print(f"Epoch {i}: Loss {loss.item()}")
|
482 |
+
|
483 |
+
# Optimizes the parameter search by storing the best loss and the parameters
|
484 |
+
if loss.item() < best_loss:
|
485 |
+
best_loss = loss.item()
|
486 |
+
best_params = copy.deepcopy({
|
487 |
+
k: v for k, v in params.items() if k in param_keys
|
488 |
+
})
|
489 |
+
|
490 |
+
# We also stop the search if the loss has not considerably during the last 10% epochs
|
491 |
+
if early_stop:
|
492 |
+
epochs_before_stop = int(epochs * percent_epochs_before_stop)
|
493 |
+
if i > epochs_before_stop and abs(acc_loss[i - epochs_before_stop] - acc_loss[i]) < min_delta:
|
494 |
+
break
|
495 |
+
|
496 |
+
# No longer requires gradients in the parameters
|
497 |
+
for p in best_params.values():
|
498 |
+
p.requires_grad = False
|
499 |
+
p.grad = None
|
500 |
+
|
501 |
+
if do_report:
|
502 |
+
return best_params, acc_loss
|
503 |
+
else:
|
504 |
+
return best_params
|
505 |
+
|
506 |
+
|
507 |
+
def quantize(
|
508 |
+
x: torch.Tensor,
|
509 |
+
params: Dict[str, nn.Parameter],
|
510 |
+
func: nn.Module,
|
511 |
+
bits: int,
|
512 |
+
target_dtype: torch.dtype = torch.int8
|
513 |
+
) -> torch.Tensor:
|
514 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
515 |
+
x = x.transpose(0, 1) # Aligns shapes
|
516 |
+
x = func(x=x, **params)
|
517 |
+
x = x.transpose(0, 1)
|
518 |
+
x = torch.clamp(round_func_BPDA(x), quant_min, quant_max).to(target_dtype)
|
519 |
+
return x
|
520 |
+
|
521 |
+
|
522 |
+
def dequantize(
|
523 |
+
x: torch.Tensor,
|
524 |
+
params: Dict[str, nn.Parameter],
|
525 |
+
func: nn.Module,
|
526 |
+
bits: int,
|
527 |
+
out_dtype: torch.dtype
|
528 |
+
) -> torch.Tensor:
|
529 |
+
x = x.to(dtype=out_dtype)
|
530 |
+
x = x.transpose(0, 1)
|
531 |
+
x = func(x=x, **params)
|
532 |
+
x = x.transpose(0, 1)
|
533 |
+
return x
|
534 |
+
|
535 |
+
|
536 |
+
def round_func_BPDA(input):
|
537 |
+
# This is equivalent to replacing round function (non-differentiable) with
|
538 |
+
# an identity function (differentiable) only when backward.
|
539 |
+
forward_value = torch.round(input)
|
540 |
+
out = input.clone()
|
541 |
+
out.data = forward_value.data
|
542 |
+
return out
|
543 |
+
|
544 |
+
|
545 |
+
def get_min_max_from_bits_signed(bit_width: int) -> Tuple[int, int]:
|
546 |
+
return -2 ** (bit_width - 1), 2 ** (bit_width - 1) - 1
|
547 |
+
|
548 |
+
|
549 |
+
|
550 |
+
############## Numpy ###############
|
551 |
+
|
552 |
+
def np_domain_guard(
|
553 |
+
x: np.ndarray,
|
554 |
+
min: float = None,
|
555 |
+
max: float = None,
|
556 |
+
posinf: float = None,
|
557 |
+
neginf: float = None,
|
558 |
+
nan: float = None
|
559 |
+
) -> np.ndarray:
|
560 |
+
"""Guard a tensor to a valid domain."""
|
561 |
+
x = np.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
562 |
+
if min is not None or max is not None:
|
563 |
+
x = np.clip(x, min, max)
|
564 |
+
return x
|
565 |
+
|
566 |
+
|
567 |
+
def np_replace_num(x: np.ndarray, num: float, to: float) -> np.ndarray:
|
568 |
+
"""Replace a number in a tensor with another number.
|
569 |
+
|
570 |
+
Args:
|
571 |
+
x (np.ndarray): The input tensor.
|
572 |
+
num (float): The number to replace.
|
573 |
+
to (float): The number to replace with.
|
574 |
+
|
575 |
+
Returns:
|
576 |
+
np.ndarray: The tensor with the number replaced.
|
577 |
+
"""
|
578 |
+
return np.where(x == num, to, x)
|
579 |
+
|
580 |
+
|
581 |
+
def np_guarded_power(x: np.ndarray, exp: float) -> np.ndarray:
|
582 |
+
"""Guard the power operation to a valid domain."""
|
583 |
+
return np.power(x, exp) if exp >= 1 else np.power(np.maximum(x, 0), exp)
|
584 |
+
|
fn_gen/rnd_search_fb/10/loss.png
ADDED
fn_gen/rnd_search_fb/10/quantization.png
ADDED
fn_gen/rnd_search_fb/11/distortion.png
ADDED
fn_gen/rnd_search_fb/11/expressions.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
atanh(_0*x)/_s
|
2 |
+
tanh(_s*x)/_0
|
fn_gen/rnd_search_fb/11/fn.py
ADDED
@@ -0,0 +1,584 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ch import amin # Necessary for arcsin
|
5 |
+
import copy
|
6 |
+
import torch.nn as nn
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
from scipy.optimize import curve_fit
|
10 |
+
from typing import Dict, Any, Tuple, List, Callable
|
11 |
+
|
12 |
+
|
13 |
+
def quantization(x, **params):
|
14 |
+
return (torch.div(1, replace_num(params['_s'], num=0, to=10000)) * torch.atanh(domain_guard((params['_0'] * x), min=-0.9999, max=0.9999, nan=0)))
|
15 |
+
|
16 |
+
|
17 |
+
def dequantization(x, **params):
|
18 |
+
return (torch.div(1, replace_num(params['_0'], num=0, to=10000)) * torch.tanh((params['_s'] * x)))
|
19 |
+
|
20 |
+
|
21 |
+
def init_space_search(
|
22 |
+
x: torch.Tensor,
|
23 |
+
**kwargs: Dict[str, Any],
|
24 |
+
) -> torch.Tensor:
|
25 |
+
|
26 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
27 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
28 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
29 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
30 |
+
|
31 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
32 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
33 |
+
torch_tensors = torch.stack(tensors)
|
34 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
35 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
36 |
+
mean = torch.mean(torch_tensors, dim=0)
|
37 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
38 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
39 |
+
|
40 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
41 |
+
x_ = x.transpose(0, 1)
|
42 |
+
x_ = qtz_func(x=x_, **params)
|
43 |
+
x_ = deqtz_func(x=x_, **params)
|
44 |
+
x_ = x_.transpose(0, 1)
|
45 |
+
return x_
|
46 |
+
|
47 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
48 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
49 |
+
assert "params_list" in kwargs, "params list must be provided."
|
50 |
+
assert "param" in kwargs, "param must be provided."
|
51 |
+
|
52 |
+
qtz_func = kwargs.get('qtz_func')
|
53 |
+
deqtz_func = kwargs.get('deqtz_func')
|
54 |
+
params_list = kwargs.get('params_list')
|
55 |
+
param = kwargs.get('param')
|
56 |
+
|
57 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
58 |
+
n_random_params = 50 # Number of random parameters to generate
|
59 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
60 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
61 |
+
|
62 |
+
# Initializes the parameters
|
63 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
64 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
65 |
+
|
66 |
+
# Performs the search
|
67 |
+
for _ in range(n_runs):
|
68 |
+
|
69 |
+
best_params = []
|
70 |
+
for param_ in params:
|
71 |
+
try:
|
72 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
73 |
+
loss_ones = nn.MSELoss()(x, x_)
|
74 |
+
|
75 |
+
if len(best_params) < n_best_to_pick:
|
76 |
+
best_params.append((param_, loss_ones.item()))
|
77 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
78 |
+
elif loss_ones < best_params[-1][1]:
|
79 |
+
best_params[-1] = (param_, loss_ones.item())
|
80 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
81 |
+
|
82 |
+
except Exception: # The parameters might not be valid for the function's domain
|
83 |
+
continue
|
84 |
+
|
85 |
+
# Generates new parameters around the mean
|
86 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
87 |
+
|
88 |
+
# Checks if the best parameter is better than the init_ones
|
89 |
+
p_ones = init_ones(x, **kwargs)
|
90 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
91 |
+
loss_ones = nn.MSELoss()(x, x_)
|
92 |
+
|
93 |
+
# Checks if the best parameter is better than the init_rand
|
94 |
+
p_rand = init_rand(x, **kwargs)
|
95 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
96 |
+
loss_rand = nn.MSELoss()(x, x_)
|
97 |
+
|
98 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
99 |
+
return p_rand
|
100 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
101 |
+
return p_ones
|
102 |
+
else:
|
103 |
+
return best_params[0][0]
|
104 |
+
|
105 |
+
|
106 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
107 |
+
x: torch.Tensor,
|
108 |
+
**kwargs: Dict[str, Any],
|
109 |
+
) -> torch.Tensor:
|
110 |
+
assert "bits" in kwargs, "bits must be provided."
|
111 |
+
assert "params" in kwargs, "params must be provided."
|
112 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
113 |
+
|
114 |
+
bits = kwargs.get('bits')
|
115 |
+
params = kwargs.get('params')
|
116 |
+
qtz_func = kwargs.get('qtz_func')
|
117 |
+
|
118 |
+
x_ = x.transpose(0, 1)
|
119 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
120 |
+
x_ = x_.transpose(0, 1)
|
121 |
+
|
122 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
123 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
124 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
125 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
126 |
+
|
127 |
+
eps = torch.finfo(torch.float32).eps
|
128 |
+
|
129 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
130 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
131 |
+
|
132 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
133 |
+
|
134 |
+
# Introduces some noise in scale
|
135 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
136 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
137 |
+
return scale
|
138 |
+
|
139 |
+
|
140 |
+
def init_params(x: torch.Tensor, **kwargs: Dict[str, Any]) -> Dict[str, nn.Parameter]:
|
141 |
+
params = {
|
142 |
+
'_0': init_space_search(x, qtz_func=quantization, deqtz_func=dequantization, param='_0', params_list=['_0', '_s'], **kwargs),
|
143 |
+
}
|
144 |
+
params['_s'] = init_linear_scale(x, params=params, qtz_func=quantization, **kwargs)
|
145 |
+
params = {k: nn.Parameter(v, requires_grad=False) for k, v in params.items()}
|
146 |
+
|
147 |
+
if 'post_init_hook' in kwargs:
|
148 |
+
kwargs['post_init_hook'](parameters=params)
|
149 |
+
|
150 |
+
|
151 |
+
if 'post_train_hook' in kwargs:
|
152 |
+
kwargs['post_train_hook'](parameters=params)
|
153 |
+
|
154 |
+
return params
|
155 |
+
|
156 |
+
|
157 |
+
############### Numpy Qtz ###############
|
158 |
+
|
159 |
+
|
160 |
+
def np_quantization(x, _0, _s):
|
161 |
+
return (np.divide(1, np_replace_num(_s, num=0, to=10000)) * np.arctanh(np_domain_guard((_0 * x), min=-0.9999, max=0.9999, nan=0)))
|
162 |
+
|
163 |
+
|
164 |
+
def np_dequantization(x, _0, _s):
|
165 |
+
return (np.divide(1, np_replace_num(_0, num=0, to=10000)) * np.tanh((_s * x)))
|
166 |
+
|
167 |
+
|
168 |
+
def fit_func(x, _0, _s):
|
169 |
+
x_ = np_quantization(x, _0, _s)
|
170 |
+
x_ = np_dequantization(x_, _0, _s)
|
171 |
+
return x_
|
172 |
+
|
173 |
+
|
174 |
+
|
175 |
+
############### HELPERS ###############
|
176 |
+
|
177 |
+
def domain_guard(
|
178 |
+
x: torch.Tensor,
|
179 |
+
min: float = None,
|
180 |
+
max: float = None,
|
181 |
+
posinf: float = None,
|
182 |
+
neginf: float = None,
|
183 |
+
nan: float = None
|
184 |
+
) -> torch.Tensor:
|
185 |
+
"""Guard a tensor to a valid domain."""
|
186 |
+
x = torch.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
187 |
+
if min is not None or max is not None:
|
188 |
+
x = torch.clamp(x, min=min, max=max)
|
189 |
+
return x
|
190 |
+
|
191 |
+
|
192 |
+
def replace_num(x: torch.Tensor, num: float, to: float) -> torch.Tensor:
|
193 |
+
"""Replace a number in a tensor with another number.
|
194 |
+
|
195 |
+
Args:
|
196 |
+
x (torch.Tensor): The input tensor.
|
197 |
+
num (float): The number to replace.
|
198 |
+
to (float): The number to replace with.
|
199 |
+
|
200 |
+
Returns:
|
201 |
+
torch.Tensor: The tensor with the number replaced.
|
202 |
+
"""
|
203 |
+
return torch.where(x == num, to, x)
|
204 |
+
|
205 |
+
|
206 |
+
def guarded_torch_power(x: torch.Tensor, exp: float) -> torch.Tensor:
|
207 |
+
"""Guard the power operation to a valid domain."""
|
208 |
+
return torch.pow(x, exp) if exp >= 1 else torch.pow(torch.relu(x), exp)
|
209 |
+
|
210 |
+
|
211 |
+
def init_ones(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
212 |
+
val = torch.amin(x, dim=1)
|
213 |
+
return torch.ones_like(val, dtype=torch.float32, device=x.device)
|
214 |
+
|
215 |
+
|
216 |
+
def init_rand(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
217 |
+
val = torch.amin(x, dim=1)
|
218 |
+
return torch.randn_like(val, dtype=torch.float32, device=x.device)
|
219 |
+
|
220 |
+
|
221 |
+
def init_space_search(
|
222 |
+
x: torch.Tensor,
|
223 |
+
**kwargs: Dict[str, Any],
|
224 |
+
) -> torch.Tensor:
|
225 |
+
|
226 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
227 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
228 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
229 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
230 |
+
|
231 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
232 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
233 |
+
torch_tensors = torch.stack(tensors)
|
234 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
235 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
236 |
+
mean = torch.mean(torch_tensors, dim=0)
|
237 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
238 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
239 |
+
|
240 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
241 |
+
x_ = x.transpose(0, 1)
|
242 |
+
x_ = qtz_func(x=x_, **params)
|
243 |
+
x_ = deqtz_func(x=x_, **params)
|
244 |
+
x_ = x_.transpose(0, 1)
|
245 |
+
return x_
|
246 |
+
|
247 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
248 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
249 |
+
assert "params_list" in kwargs, "params list must be provided."
|
250 |
+
assert "param" in kwargs, "param must be provided."
|
251 |
+
|
252 |
+
qtz_func = kwargs.get('qtz_func')
|
253 |
+
deqtz_func = kwargs.get('deqtz_func')
|
254 |
+
params_list = kwargs.get('params_list')
|
255 |
+
param = kwargs.get('param')
|
256 |
+
|
257 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
258 |
+
n_random_params = 50 # Number of random parameters to generate
|
259 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
260 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
261 |
+
|
262 |
+
# Initializes the parameters
|
263 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
264 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
265 |
+
|
266 |
+
# Performs the search
|
267 |
+
for _ in range(n_runs):
|
268 |
+
|
269 |
+
best_params = []
|
270 |
+
for param_ in params:
|
271 |
+
try:
|
272 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
273 |
+
loss_ones = nn.MSELoss()(x, x_)
|
274 |
+
|
275 |
+
if len(best_params) < n_best_to_pick:
|
276 |
+
best_params.append((param_, loss_ones.item()))
|
277 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
278 |
+
elif loss_ones < best_params[-1][1]:
|
279 |
+
best_params[-1] = (param_, loss_ones.item())
|
280 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
281 |
+
|
282 |
+
except Exception: # The parameters might not be valid for the function's domain
|
283 |
+
continue
|
284 |
+
|
285 |
+
# Generates new parameters around the mean
|
286 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
287 |
+
|
288 |
+
# Checks if the best parameter is better than the init_ones
|
289 |
+
p_ones = init_ones(x, **kwargs)
|
290 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
291 |
+
loss_ones = nn.MSELoss()(x, x_)
|
292 |
+
|
293 |
+
# Checks if the best parameter is better than the init_rand
|
294 |
+
p_rand = init_rand(x, **kwargs)
|
295 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
296 |
+
loss_rand = nn.MSELoss()(x, x_)
|
297 |
+
|
298 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
299 |
+
return p_rand
|
300 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
301 |
+
return p_ones
|
302 |
+
else:
|
303 |
+
return best_params[0][0]
|
304 |
+
|
305 |
+
|
306 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
307 |
+
x: torch.Tensor,
|
308 |
+
**kwargs: Dict[str, Any],
|
309 |
+
) -> torch.Tensor:
|
310 |
+
assert "bits" in kwargs, "bits must be provided."
|
311 |
+
assert "params" in kwargs, "params must be provided."
|
312 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
313 |
+
|
314 |
+
bits = kwargs.get('bits')
|
315 |
+
params = kwargs.get('params')
|
316 |
+
qtz_func = kwargs.get('qtz_func')
|
317 |
+
|
318 |
+
x_ = x.transpose(0, 1)
|
319 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
320 |
+
x_ = x_.transpose(0, 1)
|
321 |
+
|
322 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
323 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
324 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
325 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
326 |
+
|
327 |
+
eps = torch.finfo(torch.float32).eps
|
328 |
+
|
329 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
330 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
331 |
+
|
332 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
333 |
+
|
334 |
+
# Introduces some noise in scale
|
335 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
336 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
337 |
+
return scale
|
338 |
+
|
339 |
+
|
340 |
+
def init_non_linear_regression_fit(
|
341 |
+
x: torch.Tensor,
|
342 |
+
**kwargs: Dict[str, Any],
|
343 |
+
) -> torch.Tensor:
|
344 |
+
|
345 |
+
assert "params_list" in kwargs, "params list must be provided."
|
346 |
+
assert "np_fit_func" in kwargs, "np_fit_func must be provided."
|
347 |
+
assert "p0" in kwargs, "p0 must be provided."
|
348 |
+
np_fit_func = kwargs.get('np_fit_func')
|
349 |
+
params_list = kwargs.get('params_list')
|
350 |
+
p0 = kwargs.get('p0')
|
351 |
+
|
352 |
+
def _fit(xdata: np.ndarray, ydata: np.ndarray, func: Callable, p0: List[float]):
|
353 |
+
popt, _ = curve_fit(
|
354 |
+
func,
|
355 |
+
xdata,
|
356 |
+
ydata,
|
357 |
+
maxfev=1000,
|
358 |
+
p0=p0,
|
359 |
+
method='lm'
|
360 |
+
)
|
361 |
+
return popt
|
362 |
+
|
363 |
+
# 1. Needs to convert the torch tensor to numpy tensor
|
364 |
+
xdata = x.cpu().numpy()
|
365 |
+
|
366 |
+
# 2. Sorts the data so that it makes it easier to fit to it
|
367 |
+
sorted_xdata = np.sort(xdata, axis=-1)
|
368 |
+
|
369 |
+
p0 = {k: v.cpu().numpy() for k, v in p0.items()}
|
370 |
+
params_list = sorted(params_list) # We need to make sure that it matches the numpy fit func arg order
|
371 |
+
|
372 |
+
# 3. Finds the best parameters for each channel
|
373 |
+
try:
|
374 |
+
params = []
|
375 |
+
for i in range(sorted_xdata.shape[0]):
|
376 |
+
xdata_ = sorted_xdata[i]
|
377 |
+
p0_ = [p0[p][i] for p in params_list]
|
378 |
+
ch_params = _fit(xdata_, xdata_, np_fit_func, p0_)
|
379 |
+
params.append(ch_params)
|
380 |
+
|
381 |
+
# 4. Builds the parameters
|
382 |
+
result = {}
|
383 |
+
for i, p in enumerate(params_list):
|
384 |
+
result[p] = torch.tensor([p_[i] for p_ in params], dtype=torch.float32).to(x.device)
|
385 |
+
|
386 |
+
return result
|
387 |
+
|
388 |
+
except ValueError as e:
|
389 |
+
print(f"Could not fit the function with error: {e}")
|
390 |
+
print(f"Using fallback result...")
|
391 |
+
return {
|
392 |
+
k: torch.tensor(v, dtype=torch.float32).to(x.device) for k, v in p0.items()
|
393 |
+
}
|
394 |
+
|
395 |
+
|
396 |
+
def init_zeros(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
397 |
+
val = torch.amin(x, dim=1)
|
398 |
+
return torch.zeros_like(val, dtype=torch.float32, device=x.device)
|
399 |
+
|
400 |
+
|
401 |
+
def init_inner_scale(tensor: torch.Tensor, _min: float = torch.inf, _max: float = torch.inf) -> torch.Tensor:
|
402 |
+
# Calculate the original minimum and maximum values
|
403 |
+
min_vals, max_vals = torch.aminmax(tensor, dim=-1)
|
404 |
+
x_min = torch.min(min_vals, torch.zeros_like(min_vals))
|
405 |
+
x_max = torch.max(max_vals, torch.zeros_like(max_vals))
|
406 |
+
|
407 |
+
if _max is torch.inf: # We do not need to scale the tensor. Just need to move it
|
408 |
+
return torch.ones_like(x_min)
|
409 |
+
|
410 |
+
# Calculate the scale factor
|
411 |
+
scale = (_max - _min) / (x_max - x_min)
|
412 |
+
return scale
|
413 |
+
|
414 |
+
|
415 |
+
|
416 |
+
############## Quant ###############
|
417 |
+
|
418 |
+
@torch.enable_grad()
|
419 |
+
def learn_parameters(
|
420 |
+
x: torch.Tensor,
|
421 |
+
params: Dict[str, nn.Parameter],
|
422 |
+
qtz_func: nn.Module,
|
423 |
+
deqtz_func: nn.Module,
|
424 |
+
bits: int,
|
425 |
+
target_dtype: torch.dtype,
|
426 |
+
epochs: int = 1000,
|
427 |
+
early_stop: bool = True,
|
428 |
+
do_report: bool = False
|
429 |
+
) -> Tuple[Dict[str, nn.Parameter], torch.Tensor]:
|
430 |
+
loss_fn = nn.MSELoss()
|
431 |
+
|
432 |
+
# Determines the initial learning rate by computing the initial loss and multiplying it by
|
433 |
+
# the order of magnitude of the loss divided by 2
|
434 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
435 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
436 |
+
loss = loss_fn(x, dequant)
|
437 |
+
|
438 |
+
base_lr = 0.1
|
439 |
+
exponent = int(np.floor(np.log10(loss.item())))
|
440 |
+
lr = base_lr * (10 ** (exponent // 2))
|
441 |
+
|
442 |
+
# Requires gradients in the parameters
|
443 |
+
for p in params.values():
|
444 |
+
p.requires_grad = True
|
445 |
+
p.grad = None
|
446 |
+
|
447 |
+
param_keys = list(params.keys())
|
448 |
+
param_values = list(params.values())
|
449 |
+
|
450 |
+
# Defines optimizer and loss function
|
451 |
+
optimizer = torch.optim.Adam(param_values, lr=lr)
|
452 |
+
scheduler = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=1.0, end_factor=0.01, total_iters=epochs // 10)
|
453 |
+
|
454 |
+
# Contains the best loss and the best parameters
|
455 |
+
best_loss = float("inf")
|
456 |
+
best_params = None
|
457 |
+
|
458 |
+
# Used to stop the search early
|
459 |
+
min_delta = 1e-7
|
460 |
+
acc_loss = []
|
461 |
+
percent_epochs_before_stop = 0.1
|
462 |
+
|
463 |
+
for i in range(epochs):
|
464 |
+
optimizer.zero_grad()
|
465 |
+
|
466 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
467 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
468 |
+
loss = loss_fn(x, dequant)
|
469 |
+
|
470 |
+
if loss.isnan() or loss.isinf():
|
471 |
+
raise Exception("Loss is NaN or Inf. Stopping the search.")
|
472 |
+
|
473 |
+
loss.backward()
|
474 |
+
optimizer.step()
|
475 |
+
scheduler.step()
|
476 |
+
|
477 |
+
acc_loss.append(loss.item())
|
478 |
+
|
479 |
+
# Reports loss every 10 steps
|
480 |
+
if i % 10 == 0 and do_report:
|
481 |
+
print(f"Epoch {i}: Loss {loss.item()}")
|
482 |
+
|
483 |
+
# Optimizes the parameter search by storing the best loss and the parameters
|
484 |
+
if loss.item() < best_loss:
|
485 |
+
best_loss = loss.item()
|
486 |
+
best_params = copy.deepcopy({
|
487 |
+
k: v for k, v in params.items() if k in param_keys
|
488 |
+
})
|
489 |
+
|
490 |
+
# We also stop the search if the loss has not considerably during the last 10% epochs
|
491 |
+
if early_stop:
|
492 |
+
epochs_before_stop = int(epochs * percent_epochs_before_stop)
|
493 |
+
if i > epochs_before_stop and abs(acc_loss[i - epochs_before_stop] - acc_loss[i]) < min_delta:
|
494 |
+
break
|
495 |
+
|
496 |
+
# No longer requires gradients in the parameters
|
497 |
+
for p in best_params.values():
|
498 |
+
p.requires_grad = False
|
499 |
+
p.grad = None
|
500 |
+
|
501 |
+
if do_report:
|
502 |
+
return best_params, acc_loss
|
503 |
+
else:
|
504 |
+
return best_params
|
505 |
+
|
506 |
+
|
507 |
+
def quantize(
|
508 |
+
x: torch.Tensor,
|
509 |
+
params: Dict[str, nn.Parameter],
|
510 |
+
func: nn.Module,
|
511 |
+
bits: int,
|
512 |
+
target_dtype: torch.dtype = torch.int8
|
513 |
+
) -> torch.Tensor:
|
514 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
515 |
+
x = x.transpose(0, 1) # Aligns shapes
|
516 |
+
x = func(x=x, **params)
|
517 |
+
x = x.transpose(0, 1)
|
518 |
+
x = torch.clamp(round_func_BPDA(x), quant_min, quant_max).to(target_dtype)
|
519 |
+
return x
|
520 |
+
|
521 |
+
|
522 |
+
def dequantize(
|
523 |
+
x: torch.Tensor,
|
524 |
+
params: Dict[str, nn.Parameter],
|
525 |
+
func: nn.Module,
|
526 |
+
bits: int,
|
527 |
+
out_dtype: torch.dtype
|
528 |
+
) -> torch.Tensor:
|
529 |
+
x = x.to(dtype=out_dtype)
|
530 |
+
x = x.transpose(0, 1)
|
531 |
+
x = func(x=x, **params)
|
532 |
+
x = x.transpose(0, 1)
|
533 |
+
return x
|
534 |
+
|
535 |
+
|
536 |
+
def round_func_BPDA(input):
|
537 |
+
# This is equivalent to replacing round function (non-differentiable) with
|
538 |
+
# an identity function (differentiable) only when backward.
|
539 |
+
forward_value = torch.round(input)
|
540 |
+
out = input.clone()
|
541 |
+
out.data = forward_value.data
|
542 |
+
return out
|
543 |
+
|
544 |
+
|
545 |
+
def get_min_max_from_bits_signed(bit_width: int) -> Tuple[int, int]:
|
546 |
+
return -2 ** (bit_width - 1), 2 ** (bit_width - 1) - 1
|
547 |
+
|
548 |
+
|
549 |
+
|
550 |
+
############## Numpy ###############
|
551 |
+
|
552 |
+
def np_domain_guard(
|
553 |
+
x: np.ndarray,
|
554 |
+
min: float = None,
|
555 |
+
max: float = None,
|
556 |
+
posinf: float = None,
|
557 |
+
neginf: float = None,
|
558 |
+
nan: float = None
|
559 |
+
) -> np.ndarray:
|
560 |
+
"""Guard a tensor to a valid domain."""
|
561 |
+
x = np.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
562 |
+
if min is not None or max is not None:
|
563 |
+
x = np.clip(x, min, max)
|
564 |
+
return x
|
565 |
+
|
566 |
+
|
567 |
+
def np_replace_num(x: np.ndarray, num: float, to: float) -> np.ndarray:
|
568 |
+
"""Replace a number in a tensor with another number.
|
569 |
+
|
570 |
+
Args:
|
571 |
+
x (np.ndarray): The input tensor.
|
572 |
+
num (float): The number to replace.
|
573 |
+
to (float): The number to replace with.
|
574 |
+
|
575 |
+
Returns:
|
576 |
+
np.ndarray: The tensor with the number replaced.
|
577 |
+
"""
|
578 |
+
return np.where(x == num, to, x)
|
579 |
+
|
580 |
+
|
581 |
+
def np_guarded_power(x: np.ndarray, exp: float) -> np.ndarray:
|
582 |
+
"""Guard the power operation to a valid domain."""
|
583 |
+
return np.power(x, exp) if exp >= 1 else np.power(np.maximum(x, 0), exp)
|
584 |
+
|
fn_gen/rnd_search_fb/11/loss.png
ADDED
fn_gen/rnd_search_fb/11/quantization.png
ADDED
fn_gen/rnd_search_fb/12/distortion.png
ADDED
fn_gen/rnd_search_fb/12/expressions.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
x/_s
|
2 |
+
_s*x
|
fn_gen/rnd_search_fb/12/fn.py
ADDED
@@ -0,0 +1,498 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch import amin # Necessary for arcsin
|
5 |
+
import copy
|
6 |
+
import torch.nn as nn
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
from scipy.optimize import curve_fit
|
10 |
+
from typing import Dict, Any, Tuple, List, Callable
|
11 |
+
|
12 |
+
|
13 |
+
def quantization(x, **params):
|
14 |
+
return (x * torch.div(1, replace_num(params['_s'], num=0, to=10000)))
|
15 |
+
|
16 |
+
|
17 |
+
def dequantization(x, **params):
|
18 |
+
return (params['_s'] * x)
|
19 |
+
|
20 |
+
|
21 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
22 |
+
x: torch.Tensor,
|
23 |
+
**kwargs: Dict[str, Any],
|
24 |
+
) -> torch.Tensor:
|
25 |
+
assert "bits" in kwargs, "bits must be provided."
|
26 |
+
assert "params" in kwargs, "params must be provided."
|
27 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
28 |
+
|
29 |
+
bits = kwargs.get('bits')
|
30 |
+
params = kwargs.get('params')
|
31 |
+
qtz_func = kwargs.get('qtz_func')
|
32 |
+
|
33 |
+
x_ = x.transpose(0, 1)
|
34 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
35 |
+
x_ = x_.transpose(0, 1)
|
36 |
+
|
37 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
38 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
39 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
40 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
41 |
+
|
42 |
+
eps = torch.finfo(torch.float32).eps
|
43 |
+
|
44 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
45 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
46 |
+
|
47 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
48 |
+
|
49 |
+
# Introduces some noise in scale
|
50 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
51 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
52 |
+
return scale
|
53 |
+
|
54 |
+
|
55 |
+
def init_params(x: torch.Tensor, **kwargs: Dict[str, Any]) -> Dict[str, nn.Parameter]:
|
56 |
+
params = {
|
57 |
+
}
|
58 |
+
params['_s'] = init_linear_scale(x, params=params, qtz_func=quantization, **kwargs)
|
59 |
+
params = {k: nn.Parameter(v, requires_grad=False) for k, v in params.items()}
|
60 |
+
|
61 |
+
if 'post_init_hook' in kwargs:
|
62 |
+
kwargs['post_init_hook'](parameters=params)
|
63 |
+
|
64 |
+
|
65 |
+
if 'post_train_hook' in kwargs:
|
66 |
+
kwargs['post_train_hook'](parameters=params)
|
67 |
+
|
68 |
+
return params
|
69 |
+
|
70 |
+
|
71 |
+
############### Numpy Qtz ###############
|
72 |
+
|
73 |
+
|
74 |
+
def np_quantization(x, _s):
|
75 |
+
return (x * np.divide(1, np_replace_num(_s, num=0, to=10000)))
|
76 |
+
|
77 |
+
|
78 |
+
def np_dequantization(x, _s):
|
79 |
+
return (_s * x)
|
80 |
+
|
81 |
+
|
82 |
+
def fit_func(x, _s):
|
83 |
+
x_ = np_quantization(x, _s)
|
84 |
+
x_ = np_dequantization(x_, _s)
|
85 |
+
return x_
|
86 |
+
|
87 |
+
|
88 |
+
|
89 |
+
############### HELPERS ###############
|
90 |
+
|
91 |
+
def domain_guard(
|
92 |
+
x: torch.Tensor,
|
93 |
+
min: float = None,
|
94 |
+
max: float = None,
|
95 |
+
posinf: float = None,
|
96 |
+
neginf: float = None,
|
97 |
+
nan: float = None
|
98 |
+
) -> torch.Tensor:
|
99 |
+
"""Guard a tensor to a valid domain."""
|
100 |
+
x = torch.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
101 |
+
if min is not None or max is not None:
|
102 |
+
x = torch.clamp(x, min=min, max=max)
|
103 |
+
return x
|
104 |
+
|
105 |
+
|
106 |
+
def replace_num(x: torch.Tensor, num: float, to: float) -> torch.Tensor:
|
107 |
+
"""Replace a number in a tensor with another number.
|
108 |
+
|
109 |
+
Args:
|
110 |
+
x (torch.Tensor): The input tensor.
|
111 |
+
num (float): The number to replace.
|
112 |
+
to (float): The number to replace with.
|
113 |
+
|
114 |
+
Returns:
|
115 |
+
torch.Tensor: The tensor with the number replaced.
|
116 |
+
"""
|
117 |
+
return torch.where(x == num, to, x)
|
118 |
+
|
119 |
+
|
120 |
+
def guarded_torch_power(x: torch.Tensor, exp: float) -> torch.Tensor:
|
121 |
+
"""Guard the power operation to a valid domain."""
|
122 |
+
return torch.pow(x, exp) if exp >= 1 else torch.pow(torch.relu(x), exp)
|
123 |
+
|
124 |
+
|
125 |
+
def init_ones(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
126 |
+
val = torch.amin(x, dim=1)
|
127 |
+
return torch.ones_like(val, dtype=torch.float32, device=x.device)
|
128 |
+
|
129 |
+
|
130 |
+
def init_rand(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
131 |
+
val = torch.amin(x, dim=1)
|
132 |
+
return torch.randn_like(val, dtype=torch.float32, device=x.device)
|
133 |
+
|
134 |
+
|
135 |
+
def init_space_search(
|
136 |
+
x: torch.Tensor,
|
137 |
+
**kwargs: Dict[str, Any],
|
138 |
+
) -> torch.Tensor:
|
139 |
+
|
140 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
141 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
142 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
143 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
144 |
+
|
145 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
146 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
147 |
+
torch_tensors = torch.stack(tensors)
|
148 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
149 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
150 |
+
mean = torch.mean(torch_tensors, dim=0)
|
151 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
152 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
153 |
+
|
154 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
155 |
+
x_ = x.transpose(0, 1)
|
156 |
+
x_ = qtz_func(x=x_, **params)
|
157 |
+
x_ = deqtz_func(x=x_, **params)
|
158 |
+
x_ = x_.transpose(0, 1)
|
159 |
+
return x_
|
160 |
+
|
161 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
162 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
163 |
+
assert "params_list" in kwargs, "params list must be provided."
|
164 |
+
assert "param" in kwargs, "param must be provided."
|
165 |
+
|
166 |
+
qtz_func = kwargs.get('qtz_func')
|
167 |
+
deqtz_func = kwargs.get('deqtz_func')
|
168 |
+
params_list = kwargs.get('params_list')
|
169 |
+
param = kwargs.get('param')
|
170 |
+
|
171 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
172 |
+
n_random_params = 50 # Number of random parameters to generate
|
173 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
174 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
175 |
+
|
176 |
+
# Initializes the parameters
|
177 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
178 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
179 |
+
|
180 |
+
# Performs the search
|
181 |
+
for _ in range(n_runs):
|
182 |
+
|
183 |
+
best_params = []
|
184 |
+
for param_ in params:
|
185 |
+
try:
|
186 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
187 |
+
loss_ones = nn.MSELoss()(x, x_)
|
188 |
+
|
189 |
+
if len(best_params) < n_best_to_pick:
|
190 |
+
best_params.append((param_, loss_ones.item()))
|
191 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
192 |
+
elif loss_ones < best_params[-1][1]:
|
193 |
+
best_params[-1] = (param_, loss_ones.item())
|
194 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
195 |
+
|
196 |
+
except Exception: # The parameters might not be valid for the function's domain
|
197 |
+
continue
|
198 |
+
|
199 |
+
# Generates new parameters around the mean
|
200 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
201 |
+
|
202 |
+
# Checks if the best parameter is better than the init_ones
|
203 |
+
p_ones = init_ones(x, **kwargs)
|
204 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
205 |
+
loss_ones = nn.MSELoss()(x, x_)
|
206 |
+
|
207 |
+
# Checks if the best parameter is better than the init_rand
|
208 |
+
p_rand = init_rand(x, **kwargs)
|
209 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
210 |
+
loss_rand = nn.MSELoss()(x, x_)
|
211 |
+
|
212 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
213 |
+
return p_rand
|
214 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
215 |
+
return p_ones
|
216 |
+
else:
|
217 |
+
return best_params[0][0]
|
218 |
+
|
219 |
+
|
220 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
221 |
+
x: torch.Tensor,
|
222 |
+
**kwargs: Dict[str, Any],
|
223 |
+
) -> torch.Tensor:
|
224 |
+
assert "bits" in kwargs, "bits must be provided."
|
225 |
+
assert "params" in kwargs, "params must be provided."
|
226 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
227 |
+
|
228 |
+
bits = kwargs.get('bits')
|
229 |
+
params = kwargs.get('params')
|
230 |
+
qtz_func = kwargs.get('qtz_func')
|
231 |
+
|
232 |
+
x_ = x.transpose(0, 1)
|
233 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
234 |
+
x_ = x_.transpose(0, 1)
|
235 |
+
|
236 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
237 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
238 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
239 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
240 |
+
|
241 |
+
eps = torch.finfo(torch.float32).eps
|
242 |
+
|
243 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
244 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
245 |
+
|
246 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
247 |
+
|
248 |
+
# Introduces some noise in scale
|
249 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
250 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
251 |
+
return scale
|
252 |
+
|
253 |
+
|
254 |
+
def init_non_linear_regression_fit(
|
255 |
+
x: torch.Tensor,
|
256 |
+
**kwargs: Dict[str, Any],
|
257 |
+
) -> torch.Tensor:
|
258 |
+
|
259 |
+
assert "params_list" in kwargs, "params list must be provided."
|
260 |
+
assert "np_fit_func" in kwargs, "np_fit_func must be provided."
|
261 |
+
assert "p0" in kwargs, "p0 must be provided."
|
262 |
+
np_fit_func = kwargs.get('np_fit_func')
|
263 |
+
params_list = kwargs.get('params_list')
|
264 |
+
p0 = kwargs.get('p0')
|
265 |
+
|
266 |
+
def _fit(xdata: np.ndarray, ydata: np.ndarray, func: Callable, p0: List[float]):
|
267 |
+
popt, _ = curve_fit(
|
268 |
+
func,
|
269 |
+
xdata,
|
270 |
+
ydata,
|
271 |
+
maxfev=1000,
|
272 |
+
p0=p0,
|
273 |
+
method='lm'
|
274 |
+
)
|
275 |
+
return popt
|
276 |
+
|
277 |
+
# 1. Needs to convert the torch tensor to numpy tensor
|
278 |
+
xdata = x.cpu().numpy()
|
279 |
+
|
280 |
+
# 2. Sorts the data so that it makes it easier to fit to it
|
281 |
+
sorted_xdata = np.sort(xdata, axis=-1)
|
282 |
+
|
283 |
+
p0 = {k: v.cpu().numpy() for k, v in p0.items()}
|
284 |
+
params_list = sorted(params_list) # We need to make sure that it matches the numpy fit func arg order
|
285 |
+
|
286 |
+
# 3. Finds the best parameters for each channel
|
287 |
+
try:
|
288 |
+
params = []
|
289 |
+
for i in range(sorted_xdata.shape[0]):
|
290 |
+
xdata_ = sorted_xdata[i]
|
291 |
+
p0_ = [p0[p][i] for p in params_list]
|
292 |
+
ch_params = _fit(xdata_, xdata_, np_fit_func, p0_)
|
293 |
+
params.append(ch_params)
|
294 |
+
|
295 |
+
# 4. Builds the parameters
|
296 |
+
result = {}
|
297 |
+
for i, p in enumerate(params_list):
|
298 |
+
result[p] = torch.tensor([p_[i] for p_ in params], dtype=torch.float32).to(x.device)
|
299 |
+
|
300 |
+
return result
|
301 |
+
|
302 |
+
except ValueError as e:
|
303 |
+
print(f"Could not fit the function with error: {e}")
|
304 |
+
print(f"Using fallback result...")
|
305 |
+
return {
|
306 |
+
k: torch.tensor(v, dtype=torch.float32).to(x.device) for k, v in p0.items()
|
307 |
+
}
|
308 |
+
|
309 |
+
|
310 |
+
def init_zeros(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
311 |
+
val = torch.amin(x, dim=1)
|
312 |
+
return torch.zeros_like(val, dtype=torch.float32, device=x.device)
|
313 |
+
|
314 |
+
|
315 |
+
def init_inner_scale(tensor: torch.Tensor, _min: float = torch.inf, _max: float = torch.inf) -> torch.Tensor:
|
316 |
+
# Calculate the original minimum and maximum values
|
317 |
+
min_vals, max_vals = torch.aminmax(tensor, dim=-1)
|
318 |
+
x_min = torch.min(min_vals, torch.zeros_like(min_vals))
|
319 |
+
x_max = torch.max(max_vals, torch.zeros_like(max_vals))
|
320 |
+
|
321 |
+
if _max is torch.inf: # We do not need to scale the tensor. Just need to move it
|
322 |
+
return torch.ones_like(x_min)
|
323 |
+
|
324 |
+
# Calculate the scale factor
|
325 |
+
scale = (_max - _min) / (x_max - x_min)
|
326 |
+
return scale
|
327 |
+
|
328 |
+
|
329 |
+
|
330 |
+
############## Quant ###############
|
331 |
+
|
332 |
+
@torch.enable_grad()
|
333 |
+
def learn_parameters(
|
334 |
+
x: torch.Tensor,
|
335 |
+
params: Dict[str, nn.Parameter],
|
336 |
+
qtz_func: nn.Module,
|
337 |
+
deqtz_func: nn.Module,
|
338 |
+
bits: int,
|
339 |
+
target_dtype: torch.dtype,
|
340 |
+
epochs: int = 1000,
|
341 |
+
early_stop: bool = True,
|
342 |
+
do_report: bool = False
|
343 |
+
) -> Tuple[Dict[str, nn.Parameter], torch.Tensor]:
|
344 |
+
loss_fn = nn.MSELoss()
|
345 |
+
|
346 |
+
# Determines the initial learning rate by computing the initial loss and multiplying it by
|
347 |
+
# the order of magnitude of the loss divided by 2
|
348 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
349 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
350 |
+
loss = loss_fn(x, dequant)
|
351 |
+
|
352 |
+
base_lr = 0.1
|
353 |
+
exponent = int(np.floor(np.log10(loss.item())))
|
354 |
+
lr = base_lr * (10 ** (exponent // 2))
|
355 |
+
|
356 |
+
# Requires gradients in the parameters
|
357 |
+
for p in params.values():
|
358 |
+
p.requires_grad = True
|
359 |
+
p.grad = None
|
360 |
+
|
361 |
+
param_keys = list(params.keys())
|
362 |
+
param_values = list(params.values())
|
363 |
+
|
364 |
+
# Defines optimizer and loss function
|
365 |
+
optimizer = torch.optim.Adam(param_values, lr=lr)
|
366 |
+
scheduler = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=1.0, end_factor=0.01, total_iters=epochs // 10)
|
367 |
+
|
368 |
+
# Contains the best loss and the best parameters
|
369 |
+
best_loss = float("inf")
|
370 |
+
best_params = None
|
371 |
+
|
372 |
+
# Used to stop the search early
|
373 |
+
min_delta = 1e-7
|
374 |
+
acc_loss = []
|
375 |
+
percent_epochs_before_stop = 0.1
|
376 |
+
|
377 |
+
for i in range(epochs):
|
378 |
+
optimizer.zero_grad()
|
379 |
+
|
380 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
381 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
382 |
+
loss = loss_fn(x, dequant)
|
383 |
+
|
384 |
+
if loss.isnan() or loss.isinf():
|
385 |
+
raise Exception("Loss is NaN or Inf. Stopping the search.")
|
386 |
+
|
387 |
+
loss.backward()
|
388 |
+
optimizer.step()
|
389 |
+
scheduler.step()
|
390 |
+
|
391 |
+
acc_loss.append(loss.item())
|
392 |
+
|
393 |
+
# Reports loss every 10 steps
|
394 |
+
if i % 10 == 0 and do_report:
|
395 |
+
print(f"Epoch {i}: Loss {loss.item()}")
|
396 |
+
|
397 |
+
# Optimizes the parameter search by storing the best loss and the parameters
|
398 |
+
if loss.item() < best_loss:
|
399 |
+
best_loss = loss.item()
|
400 |
+
best_params = copy.deepcopy({
|
401 |
+
k: v for k, v in params.items() if k in param_keys
|
402 |
+
})
|
403 |
+
|
404 |
+
# We also stop the search if the loss has not considerably during the last 10% epochs
|
405 |
+
if early_stop:
|
406 |
+
epochs_before_stop = int(epochs * percent_epochs_before_stop)
|
407 |
+
if i > epochs_before_stop and abs(acc_loss[i - epochs_before_stop] - acc_loss[i]) < min_delta:
|
408 |
+
break
|
409 |
+
|
410 |
+
# No longer requires gradients in the parameters
|
411 |
+
for p in best_params.values():
|
412 |
+
p.requires_grad = False
|
413 |
+
p.grad = None
|
414 |
+
|
415 |
+
if do_report:
|
416 |
+
return best_params, acc_loss
|
417 |
+
else:
|
418 |
+
return best_params
|
419 |
+
|
420 |
+
|
421 |
+
def quantize(
|
422 |
+
x: torch.Tensor,
|
423 |
+
params: Dict[str, nn.Parameter],
|
424 |
+
func: nn.Module,
|
425 |
+
bits: int,
|
426 |
+
target_dtype: torch.dtype = torch.int8
|
427 |
+
) -> torch.Tensor:
|
428 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
429 |
+
x = x.transpose(0, 1) # Aligns shapes
|
430 |
+
x = func(x=x, **params)
|
431 |
+
x = x.transpose(0, 1)
|
432 |
+
x = torch.clamp(round_func_BPDA(x), quant_min, quant_max).to(target_dtype)
|
433 |
+
return x
|
434 |
+
|
435 |
+
|
436 |
+
def dequantize(
|
437 |
+
x: torch.Tensor,
|
438 |
+
params: Dict[str, nn.Parameter],
|
439 |
+
func: nn.Module,
|
440 |
+
bits: int,
|
441 |
+
out_dtype: torch.dtype
|
442 |
+
) -> torch.Tensor:
|
443 |
+
x = x.to(dtype=out_dtype)
|
444 |
+
x = x.transpose(0, 1)
|
445 |
+
x = func(x=x, **params)
|
446 |
+
x = x.transpose(0, 1)
|
447 |
+
return x
|
448 |
+
|
449 |
+
|
450 |
+
def round_func_BPDA(input):
|
451 |
+
# This is equivalent to replacing round function (non-differentiable) with
|
452 |
+
# an identity function (differentiable) only when backward.
|
453 |
+
forward_value = torch.round(input)
|
454 |
+
out = input.clone()
|
455 |
+
out.data = forward_value.data
|
456 |
+
return out
|
457 |
+
|
458 |
+
|
459 |
+
def get_min_max_from_bits_signed(bit_width: int) -> Tuple[int, int]:
|
460 |
+
return -2 ** (bit_width - 1), 2 ** (bit_width - 1) - 1
|
461 |
+
|
462 |
+
|
463 |
+
|
464 |
+
############## Numpy ###############
|
465 |
+
|
466 |
+
def np_domain_guard(
|
467 |
+
x: np.ndarray,
|
468 |
+
min: float = None,
|
469 |
+
max: float = None,
|
470 |
+
posinf: float = None,
|
471 |
+
neginf: float = None,
|
472 |
+
nan: float = None
|
473 |
+
) -> np.ndarray:
|
474 |
+
"""Guard a tensor to a valid domain."""
|
475 |
+
x = np.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
476 |
+
if min is not None or max is not None:
|
477 |
+
x = np.clip(x, min, max)
|
478 |
+
return x
|
479 |
+
|
480 |
+
|
481 |
+
def np_replace_num(x: np.ndarray, num: float, to: float) -> np.ndarray:
|
482 |
+
"""Replace a number in a tensor with another number.
|
483 |
+
|
484 |
+
Args:
|
485 |
+
x (np.ndarray): The input tensor.
|
486 |
+
num (float): The number to replace.
|
487 |
+
to (float): The number to replace with.
|
488 |
+
|
489 |
+
Returns:
|
490 |
+
np.ndarray: The tensor with the number replaced.
|
491 |
+
"""
|
492 |
+
return np.where(x == num, to, x)
|
493 |
+
|
494 |
+
|
495 |
+
def np_guarded_power(x: np.ndarray, exp: float) -> np.ndarray:
|
496 |
+
"""Guard the power operation to a valid domain."""
|
497 |
+
return np.power(x, exp) if exp >= 1 else np.power(np.maximum(x, 0), exp)
|
498 |
+
|
fn_gen/rnd_search_fb/12/loss.png
ADDED
fn_gen/rnd_search_fb/12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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch import amin # Necessary for arcsin
|
5 |
+
import copy
|
6 |
+
import torch.nn as nn
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
from scipy.optimize import curve_fit
|
10 |
+
from typing import Dict, Any, Tuple, List, Callable
|
11 |
+
|
12 |
+
|
13 |
+
def quantization(x, **params):
|
14 |
+
return (torch.div(1, replace_num(params['_s'], num=0, to=10000)) * torch.tanh((params['_0'] * x)))
|
15 |
+
|
16 |
+
|
17 |
+
def dequantization(x, **params):
|
18 |
+
return (torch.div(1, replace_num(params['_0'], num=0, to=10000)) * torch.log(domain_guard((torch.div(1, replace_num((torch.tensor(-1) + (params['_s'] * x)), num=0, to=10000)) * (torch.tensor(-1) + (torch.tensor(-1) * params['_s'] * x))), min=1e-5, nan=1e-5)))
|
19 |
+
|
20 |
+
|
21 |
+
def init_space_search(
|
22 |
+
x: torch.Tensor,
|
23 |
+
**kwargs: Dict[str, Any],
|
24 |
+
) -> torch.Tensor:
|
25 |
+
|
26 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
27 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
28 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
29 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
30 |
+
|
31 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
32 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
33 |
+
torch_tensors = torch.stack(tensors)
|
34 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
35 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
36 |
+
mean = torch.mean(torch_tensors, dim=0)
|
37 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
38 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
39 |
+
|
40 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
41 |
+
x_ = x.transpose(0, 1)
|
42 |
+
x_ = qtz_func(x=x_, **params)
|
43 |
+
x_ = deqtz_func(x=x_, **params)
|
44 |
+
x_ = x_.transpose(0, 1)
|
45 |
+
return x_
|
46 |
+
|
47 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
48 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
49 |
+
assert "params_list" in kwargs, "params list must be provided."
|
50 |
+
assert "param" in kwargs, "param must be provided."
|
51 |
+
|
52 |
+
qtz_func = kwargs.get('qtz_func')
|
53 |
+
deqtz_func = kwargs.get('deqtz_func')
|
54 |
+
params_list = kwargs.get('params_list')
|
55 |
+
param = kwargs.get('param')
|
56 |
+
|
57 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
58 |
+
n_random_params = 50 # Number of random parameters to generate
|
59 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
60 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
61 |
+
|
62 |
+
# Initializes the parameters
|
63 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
64 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
65 |
+
|
66 |
+
# Performs the search
|
67 |
+
for _ in range(n_runs):
|
68 |
+
|
69 |
+
best_params = []
|
70 |
+
for param_ in params:
|
71 |
+
try:
|
72 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
73 |
+
loss_ones = nn.MSELoss()(x, x_)
|
74 |
+
|
75 |
+
if len(best_params) < n_best_to_pick:
|
76 |
+
best_params.append((param_, loss_ones.item()))
|
77 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
78 |
+
elif loss_ones < best_params[-1][1]:
|
79 |
+
best_params[-1] = (param_, loss_ones.item())
|
80 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
81 |
+
|
82 |
+
except Exception: # The parameters might not be valid for the function's domain
|
83 |
+
continue
|
84 |
+
|
85 |
+
# Generates new parameters around the mean
|
86 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
87 |
+
|
88 |
+
# Checks if the best parameter is better than the init_ones
|
89 |
+
p_ones = init_ones(x, **kwargs)
|
90 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
91 |
+
loss_ones = nn.MSELoss()(x, x_)
|
92 |
+
|
93 |
+
# Checks if the best parameter is better than the init_rand
|
94 |
+
p_rand = init_rand(x, **kwargs)
|
95 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
96 |
+
loss_rand = nn.MSELoss()(x, x_)
|
97 |
+
|
98 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
99 |
+
return p_rand
|
100 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
101 |
+
return p_ones
|
102 |
+
else:
|
103 |
+
return best_params[0][0]
|
104 |
+
|
105 |
+
|
106 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
107 |
+
x: torch.Tensor,
|
108 |
+
**kwargs: Dict[str, Any],
|
109 |
+
) -> torch.Tensor:
|
110 |
+
assert "bits" in kwargs, "bits must be provided."
|
111 |
+
assert "params" in kwargs, "params must be provided."
|
112 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
113 |
+
|
114 |
+
bits = kwargs.get('bits')
|
115 |
+
params = kwargs.get('params')
|
116 |
+
qtz_func = kwargs.get('qtz_func')
|
117 |
+
|
118 |
+
x_ = x.transpose(0, 1)
|
119 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
120 |
+
x_ = x_.transpose(0, 1)
|
121 |
+
|
122 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
123 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
124 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
125 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
126 |
+
|
127 |
+
eps = torch.finfo(torch.float32).eps
|
128 |
+
|
129 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
130 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
131 |
+
|
132 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
133 |
+
|
134 |
+
# Introduces some noise in scale
|
135 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
136 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
137 |
+
return scale
|
138 |
+
|
139 |
+
|
140 |
+
def init_params(x: torch.Tensor, **kwargs: Dict[str, Any]) -> Dict[str, nn.Parameter]:
|
141 |
+
params = {
|
142 |
+
'_0': init_space_search(x, qtz_func=quantization, deqtz_func=dequantization, param='_0', params_list=['_0', '_s'], **kwargs),
|
143 |
+
}
|
144 |
+
params['_s'] = init_linear_scale(x, params=params, qtz_func=quantization, **kwargs)
|
145 |
+
params = {k: nn.Parameter(v, requires_grad=False) for k, v in params.items()}
|
146 |
+
|
147 |
+
if 'post_init_hook' in kwargs:
|
148 |
+
kwargs['post_init_hook'](parameters=params)
|
149 |
+
|
150 |
+
|
151 |
+
if 'post_train_hook' in kwargs:
|
152 |
+
kwargs['post_train_hook'](parameters=params)
|
153 |
+
|
154 |
+
return params
|
155 |
+
|
156 |
+
|
157 |
+
############### Numpy Qtz ###############
|
158 |
+
|
159 |
+
|
160 |
+
def np_quantization(x, _0, _s):
|
161 |
+
return (np.divide(1, np_replace_num(_s, num=0, to=10000)) * np.tanh((_0 * x)))
|
162 |
+
|
163 |
+
|
164 |
+
def np_dequantization(x, _0, _s):
|
165 |
+
return (np.divide(1, np_replace_num(_0, num=0, to=10000)) * np.log(np_domain_guard((np.divide(1, np_replace_num((np.array(-1) + (_s * x)), num=0, to=10000)) * (np.array(-1) + (np.array(-1) * _s * x))), min=1e-5, nan=1e-5)))
|
166 |
+
|
167 |
+
|
168 |
+
def fit_func(x, _0, _s):
|
169 |
+
x_ = np_quantization(x, _0, _s)
|
170 |
+
x_ = np_dequantization(x_, _0, _s)
|
171 |
+
return x_
|
172 |
+
|
173 |
+
|
174 |
+
|
175 |
+
############### HELPERS ###############
|
176 |
+
|
177 |
+
def domain_guard(
|
178 |
+
x: torch.Tensor,
|
179 |
+
min: float = None,
|
180 |
+
max: float = None,
|
181 |
+
posinf: float = None,
|
182 |
+
neginf: float = None,
|
183 |
+
nan: float = None
|
184 |
+
) -> torch.Tensor:
|
185 |
+
"""Guard a tensor to a valid domain."""
|
186 |
+
x = torch.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
187 |
+
if min is not None or max is not None:
|
188 |
+
x = torch.clamp(x, min=min, max=max)
|
189 |
+
return x
|
190 |
+
|
191 |
+
|
192 |
+
def replace_num(x: torch.Tensor, num: float, to: float) -> torch.Tensor:
|
193 |
+
"""Replace a number in a tensor with another number.
|
194 |
+
|
195 |
+
Args:
|
196 |
+
x (torch.Tensor): The input tensor.
|
197 |
+
num (float): The number to replace.
|
198 |
+
to (float): The number to replace with.
|
199 |
+
|
200 |
+
Returns:
|
201 |
+
torch.Tensor: The tensor with the number replaced.
|
202 |
+
"""
|
203 |
+
return torch.where(x == num, to, x)
|
204 |
+
|
205 |
+
|
206 |
+
def guarded_torch_power(x: torch.Tensor, exp: float) -> torch.Tensor:
|
207 |
+
"""Guard the power operation to a valid domain."""
|
208 |
+
return torch.pow(x, exp) if exp >= 1 else torch.pow(torch.relu(x), exp)
|
209 |
+
|
210 |
+
|
211 |
+
def init_ones(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
212 |
+
val = torch.amin(x, dim=1)
|
213 |
+
return torch.ones_like(val, dtype=torch.float32, device=x.device)
|
214 |
+
|
215 |
+
|
216 |
+
def init_rand(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
217 |
+
val = torch.amin(x, dim=1)
|
218 |
+
return torch.randn_like(val, dtype=torch.float32, device=x.device)
|
219 |
+
|
220 |
+
|
221 |
+
def init_space_search(
|
222 |
+
x: torch.Tensor,
|
223 |
+
**kwargs: Dict[str, Any],
|
224 |
+
) -> torch.Tensor:
|
225 |
+
|
226 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
227 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
228 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
229 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
230 |
+
|
231 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
232 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
233 |
+
torch_tensors = torch.stack(tensors)
|
234 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
235 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
236 |
+
mean = torch.mean(torch_tensors, dim=0)
|
237 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
238 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
239 |
+
|
240 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
241 |
+
x_ = x.transpose(0, 1)
|
242 |
+
x_ = qtz_func(x=x_, **params)
|
243 |
+
x_ = deqtz_func(x=x_, **params)
|
244 |
+
x_ = x_.transpose(0, 1)
|
245 |
+
return x_
|
246 |
+
|
247 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
248 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
249 |
+
assert "params_list" in kwargs, "params list must be provided."
|
250 |
+
assert "param" in kwargs, "param must be provided."
|
251 |
+
|
252 |
+
qtz_func = kwargs.get('qtz_func')
|
253 |
+
deqtz_func = kwargs.get('deqtz_func')
|
254 |
+
params_list = kwargs.get('params_list')
|
255 |
+
param = kwargs.get('param')
|
256 |
+
|
257 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
258 |
+
n_random_params = 50 # Number of random parameters to generate
|
259 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
260 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
261 |
+
|
262 |
+
# Initializes the parameters
|
263 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
264 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
265 |
+
|
266 |
+
# Performs the search
|
267 |
+
for _ in range(n_runs):
|
268 |
+
|
269 |
+
best_params = []
|
270 |
+
for param_ in params:
|
271 |
+
try:
|
272 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
273 |
+
loss_ones = nn.MSELoss()(x, x_)
|
274 |
+
|
275 |
+
if len(best_params) < n_best_to_pick:
|
276 |
+
best_params.append((param_, loss_ones.item()))
|
277 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
278 |
+
elif loss_ones < best_params[-1][1]:
|
279 |
+
best_params[-1] = (param_, loss_ones.item())
|
280 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
281 |
+
|
282 |
+
except Exception: # The parameters might not be valid for the function's domain
|
283 |
+
continue
|
284 |
+
|
285 |
+
# Generates new parameters around the mean
|
286 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
287 |
+
|
288 |
+
# Checks if the best parameter is better than the init_ones
|
289 |
+
p_ones = init_ones(x, **kwargs)
|
290 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
291 |
+
loss_ones = nn.MSELoss()(x, x_)
|
292 |
+
|
293 |
+
# Checks if the best parameter is better than the init_rand
|
294 |
+
p_rand = init_rand(x, **kwargs)
|
295 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
296 |
+
loss_rand = nn.MSELoss()(x, x_)
|
297 |
+
|
298 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
299 |
+
return p_rand
|
300 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
301 |
+
return p_ones
|
302 |
+
else:
|
303 |
+
return best_params[0][0]
|
304 |
+
|
305 |
+
|
306 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
307 |
+
x: torch.Tensor,
|
308 |
+
**kwargs: Dict[str, Any],
|
309 |
+
) -> torch.Tensor:
|
310 |
+
assert "bits" in kwargs, "bits must be provided."
|
311 |
+
assert "params" in kwargs, "params must be provided."
|
312 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
313 |
+
|
314 |
+
bits = kwargs.get('bits')
|
315 |
+
params = kwargs.get('params')
|
316 |
+
qtz_func = kwargs.get('qtz_func')
|
317 |
+
|
318 |
+
x_ = x.transpose(0, 1)
|
319 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
320 |
+
x_ = x_.transpose(0, 1)
|
321 |
+
|
322 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
323 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
324 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
325 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
326 |
+
|
327 |
+
eps = torch.finfo(torch.float32).eps
|
328 |
+
|
329 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
330 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
331 |
+
|
332 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
333 |
+
|
334 |
+
# Introduces some noise in scale
|
335 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
336 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
337 |
+
return scale
|
338 |
+
|
339 |
+
|
340 |
+
def init_non_linear_regression_fit(
|
341 |
+
x: torch.Tensor,
|
342 |
+
**kwargs: Dict[str, Any],
|
343 |
+
) -> torch.Tensor:
|
344 |
+
|
345 |
+
assert "params_list" in kwargs, "params list must be provided."
|
346 |
+
assert "np_fit_func" in kwargs, "np_fit_func must be provided."
|
347 |
+
assert "p0" in kwargs, "p0 must be provided."
|
348 |
+
np_fit_func = kwargs.get('np_fit_func')
|
349 |
+
params_list = kwargs.get('params_list')
|
350 |
+
p0 = kwargs.get('p0')
|
351 |
+
|
352 |
+
def _fit(xdata: np.ndarray, ydata: np.ndarray, func: Callable, p0: List[float]):
|
353 |
+
popt, _ = curve_fit(
|
354 |
+
func,
|
355 |
+
xdata,
|
356 |
+
ydata,
|
357 |
+
maxfev=1000,
|
358 |
+
p0=p0,
|
359 |
+
method='lm'
|
360 |
+
)
|
361 |
+
return popt
|
362 |
+
|
363 |
+
# 1. Needs to convert the torch tensor to numpy tensor
|
364 |
+
xdata = x.cpu().numpy()
|
365 |
+
|
366 |
+
# 2. Sorts the data so that it makes it easier to fit to it
|
367 |
+
sorted_xdata = np.sort(xdata, axis=-1)
|
368 |
+
|
369 |
+
p0 = {k: v.cpu().numpy() for k, v in p0.items()}
|
370 |
+
params_list = sorted(params_list) # We need to make sure that it matches the numpy fit func arg order
|
371 |
+
|
372 |
+
# 3. Finds the best parameters for each channel
|
373 |
+
try:
|
374 |
+
params = []
|
375 |
+
for i in range(sorted_xdata.shape[0]):
|
376 |
+
xdata_ = sorted_xdata[i]
|
377 |
+
p0_ = [p0[p][i] for p in params_list]
|
378 |
+
ch_params = _fit(xdata_, xdata_, np_fit_func, p0_)
|
379 |
+
params.append(ch_params)
|
380 |
+
|
381 |
+
# 4. Builds the parameters
|
382 |
+
result = {}
|
383 |
+
for i, p in enumerate(params_list):
|
384 |
+
result[p] = torch.tensor([p_[i] for p_ in params], dtype=torch.float32).to(x.device)
|
385 |
+
|
386 |
+
return result
|
387 |
+
|
388 |
+
except ValueError as e:
|
389 |
+
print(f"Could not fit the function with error: {e}")
|
390 |
+
print(f"Using fallback result...")
|
391 |
+
return {
|
392 |
+
k: torch.tensor(v, dtype=torch.float32).to(x.device) for k, v in p0.items()
|
393 |
+
}
|
394 |
+
|
395 |
+
|
396 |
+
def init_zeros(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
397 |
+
val = torch.amin(x, dim=1)
|
398 |
+
return torch.zeros_like(val, dtype=torch.float32, device=x.device)
|
399 |
+
|
400 |
+
|
401 |
+
def init_inner_scale(tensor: torch.Tensor, _min: float = torch.inf, _max: float = torch.inf) -> torch.Tensor:
|
402 |
+
# Calculate the original minimum and maximum values
|
403 |
+
min_vals, max_vals = torch.aminmax(tensor, dim=-1)
|
404 |
+
x_min = torch.min(min_vals, torch.zeros_like(min_vals))
|
405 |
+
x_max = torch.max(max_vals, torch.zeros_like(max_vals))
|
406 |
+
|
407 |
+
if _max is torch.inf: # We do not need to scale the tensor. Just need to move it
|
408 |
+
return torch.ones_like(x_min)
|
409 |
+
|
410 |
+
# Calculate the scale factor
|
411 |
+
scale = (_max - _min) / (x_max - x_min)
|
412 |
+
return scale
|
413 |
+
|
414 |
+
|
415 |
+
|
416 |
+
############## Quant ###############
|
417 |
+
|
418 |
+
@torch.enable_grad()
|
419 |
+
def learn_parameters(
|
420 |
+
x: torch.Tensor,
|
421 |
+
params: Dict[str, nn.Parameter],
|
422 |
+
qtz_func: nn.Module,
|
423 |
+
deqtz_func: nn.Module,
|
424 |
+
bits: int,
|
425 |
+
target_dtype: torch.dtype,
|
426 |
+
epochs: int = 1000,
|
427 |
+
early_stop: bool = True,
|
428 |
+
do_report: bool = False
|
429 |
+
) -> Tuple[Dict[str, nn.Parameter], torch.Tensor]:
|
430 |
+
loss_fn = nn.MSELoss()
|
431 |
+
|
432 |
+
# Determines the initial learning rate by computing the initial loss and multiplying it by
|
433 |
+
# the order of magnitude of the loss divided by 2
|
434 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
435 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
436 |
+
loss = loss_fn(x, dequant)
|
437 |
+
|
438 |
+
base_lr = 0.1
|
439 |
+
exponent = int(np.floor(np.log10(loss.item())))
|
440 |
+
lr = base_lr * (10 ** (exponent // 2))
|
441 |
+
|
442 |
+
# Requires gradients in the parameters
|
443 |
+
for p in params.values():
|
444 |
+
p.requires_grad = True
|
445 |
+
p.grad = None
|
446 |
+
|
447 |
+
param_keys = list(params.keys())
|
448 |
+
param_values = list(params.values())
|
449 |
+
|
450 |
+
# Defines optimizer and loss function
|
451 |
+
optimizer = torch.optim.Adam(param_values, lr=lr)
|
452 |
+
scheduler = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=1.0, end_factor=0.01, total_iters=epochs // 10)
|
453 |
+
|
454 |
+
# Contains the best loss and the best parameters
|
455 |
+
best_loss = float("inf")
|
456 |
+
best_params = None
|
457 |
+
|
458 |
+
# Used to stop the search early
|
459 |
+
min_delta = 1e-7
|
460 |
+
acc_loss = []
|
461 |
+
percent_epochs_before_stop = 0.1
|
462 |
+
|
463 |
+
for i in range(epochs):
|
464 |
+
optimizer.zero_grad()
|
465 |
+
|
466 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
467 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
468 |
+
loss = loss_fn(x, dequant)
|
469 |
+
|
470 |
+
if loss.isnan() or loss.isinf():
|
471 |
+
raise Exception("Loss is NaN or Inf. Stopping the search.")
|
472 |
+
|
473 |
+
loss.backward()
|
474 |
+
optimizer.step()
|
475 |
+
scheduler.step()
|
476 |
+
|
477 |
+
acc_loss.append(loss.item())
|
478 |
+
|
479 |
+
# Reports loss every 10 steps
|
480 |
+
if i % 10 == 0 and do_report:
|
481 |
+
print(f"Epoch {i}: Loss {loss.item()}")
|
482 |
+
|
483 |
+
# Optimizes the parameter search by storing the best loss and the parameters
|
484 |
+
if loss.item() < best_loss:
|
485 |
+
best_loss = loss.item()
|
486 |
+
best_params = copy.deepcopy({
|
487 |
+
k: v for k, v in params.items() if k in param_keys
|
488 |
+
})
|
489 |
+
|
490 |
+
# We also stop the search if the loss has not considerably during the last 10% epochs
|
491 |
+
if early_stop:
|
492 |
+
epochs_before_stop = int(epochs * percent_epochs_before_stop)
|
493 |
+
if i > epochs_before_stop and abs(acc_loss[i - epochs_before_stop] - acc_loss[i]) < min_delta:
|
494 |
+
break
|
495 |
+
|
496 |
+
# No longer requires gradients in the parameters
|
497 |
+
for p in best_params.values():
|
498 |
+
p.requires_grad = False
|
499 |
+
p.grad = None
|
500 |
+
|
501 |
+
if do_report:
|
502 |
+
return best_params, acc_loss
|
503 |
+
else:
|
504 |
+
return best_params
|
505 |
+
|
506 |
+
|
507 |
+
def quantize(
|
508 |
+
x: torch.Tensor,
|
509 |
+
params: Dict[str, nn.Parameter],
|
510 |
+
func: nn.Module,
|
511 |
+
bits: int,
|
512 |
+
target_dtype: torch.dtype = torch.int8
|
513 |
+
) -> torch.Tensor:
|
514 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
515 |
+
x = x.transpose(0, 1) # Aligns shapes
|
516 |
+
x = func(x=x, **params)
|
517 |
+
x = x.transpose(0, 1)
|
518 |
+
x = torch.clamp(round_func_BPDA(x), quant_min, quant_max).to(target_dtype)
|
519 |
+
return x
|
520 |
+
|
521 |
+
|
522 |
+
def dequantize(
|
523 |
+
x: torch.Tensor,
|
524 |
+
params: Dict[str, nn.Parameter],
|
525 |
+
func: nn.Module,
|
526 |
+
bits: int,
|
527 |
+
out_dtype: torch.dtype
|
528 |
+
) -> torch.Tensor:
|
529 |
+
x = x.to(dtype=out_dtype)
|
530 |
+
x = x.transpose(0, 1)
|
531 |
+
x = func(x=x, **params)
|
532 |
+
x = x.transpose(0, 1)
|
533 |
+
return x
|
534 |
+
|
535 |
+
|
536 |
+
def round_func_BPDA(input):
|
537 |
+
# This is equivalent to replacing round function (non-differentiable) with
|
538 |
+
# an identity function (differentiable) only when backward.
|
539 |
+
forward_value = torch.round(input)
|
540 |
+
out = input.clone()
|
541 |
+
out.data = forward_value.data
|
542 |
+
return out
|
543 |
+
|
544 |
+
|
545 |
+
def get_min_max_from_bits_signed(bit_width: int) -> Tuple[int, int]:
|
546 |
+
return -2 ** (bit_width - 1), 2 ** (bit_width - 1) - 1
|
547 |
+
|
548 |
+
|
549 |
+
|
550 |
+
############## Numpy ###############
|
551 |
+
|
552 |
+
def np_domain_guard(
|
553 |
+
x: np.ndarray,
|
554 |
+
min: float = None,
|
555 |
+
max: float = None,
|
556 |
+
posinf: float = None,
|
557 |
+
neginf: float = None,
|
558 |
+
nan: float = None
|
559 |
+
) -> np.ndarray:
|
560 |
+
"""Guard a tensor to a valid domain."""
|
561 |
+
x = np.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
562 |
+
if min is not None or max is not None:
|
563 |
+
x = np.clip(x, min, max)
|
564 |
+
return x
|
565 |
+
|
566 |
+
|
567 |
+
def np_replace_num(x: np.ndarray, num: float, to: float) -> np.ndarray:
|
568 |
+
"""Replace a number in a tensor with another number.
|
569 |
+
|
570 |
+
Args:
|
571 |
+
x (np.ndarray): The input tensor.
|
572 |
+
num (float): The number to replace.
|
573 |
+
to (float): The number to replace with.
|
574 |
+
|
575 |
+
Returns:
|
576 |
+
np.ndarray: The tensor with the number replaced.
|
577 |
+
"""
|
578 |
+
return np.where(x == num, to, x)
|
579 |
+
|
580 |
+
|
581 |
+
def np_guarded_power(x: np.ndarray, exp: float) -> np.ndarray:
|
582 |
+
"""Guard the power operation to a valid domain."""
|
583 |
+
return np.power(x, exp) if exp >= 1 else np.power(np.maximum(x, 0), exp)
|
584 |
+
|
fn_gen/rnd_search_fb/13/loss.png
ADDED
fn_gen/rnd_search_fb/13/quantization.png
ADDED
fn_gen/rnd_search_fb/15/distortion.png
ADDED
fn_gen/rnd_search_fb/15/expressions.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
x**2/_s
|
2 |
+
sqrt(_s*x)
|
fn_gen/rnd_search_fb/15/fn.py
ADDED
@@ -0,0 +1,498 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch import amin # Necessary for arcsin
|
5 |
+
import copy
|
6 |
+
import torch.nn as nn
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
from scipy.optimize import curve_fit
|
10 |
+
from typing import Dict, Any, Tuple, List, Callable
|
11 |
+
|
12 |
+
|
13 |
+
def quantization(x, **params):
|
14 |
+
return (torch.div(1, replace_num(params['_s'], num=0, to=10000)) * guarded_torch_power(x, torch.tensor(2)))
|
15 |
+
|
16 |
+
|
17 |
+
def dequantization(x, **params):
|
18 |
+
return torch.sqrt(domain_guard((params['_s'] * x), min=0.1, nan=0.1))
|
19 |
+
|
20 |
+
|
21 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
22 |
+
x: torch.Tensor,
|
23 |
+
**kwargs: Dict[str, Any],
|
24 |
+
) -> torch.Tensor:
|
25 |
+
assert "bits" in kwargs, "bits must be provided."
|
26 |
+
assert "params" in kwargs, "params must be provided."
|
27 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
28 |
+
|
29 |
+
bits = kwargs.get('bits')
|
30 |
+
params = kwargs.get('params')
|
31 |
+
qtz_func = kwargs.get('qtz_func')
|
32 |
+
|
33 |
+
x_ = x.transpose(0, 1)
|
34 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
35 |
+
x_ = x_.transpose(0, 1)
|
36 |
+
|
37 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
38 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
39 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
40 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
41 |
+
|
42 |
+
eps = torch.finfo(torch.float32).eps
|
43 |
+
|
44 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
45 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
46 |
+
|
47 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
48 |
+
|
49 |
+
# Introduces some noise in scale
|
50 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
51 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
52 |
+
return scale
|
53 |
+
|
54 |
+
|
55 |
+
def init_params(x: torch.Tensor, **kwargs: Dict[str, Any]) -> Dict[str, nn.Parameter]:
|
56 |
+
params = {
|
57 |
+
}
|
58 |
+
params['_s'] = init_linear_scale(x, params=params, qtz_func=quantization, **kwargs)
|
59 |
+
params = {k: nn.Parameter(v, requires_grad=False) for k, v in params.items()}
|
60 |
+
|
61 |
+
if 'post_init_hook' in kwargs:
|
62 |
+
kwargs['post_init_hook'](parameters=params)
|
63 |
+
|
64 |
+
|
65 |
+
if 'post_train_hook' in kwargs:
|
66 |
+
kwargs['post_train_hook'](parameters=params)
|
67 |
+
|
68 |
+
return params
|
69 |
+
|
70 |
+
|
71 |
+
############### Numpy Qtz ###############
|
72 |
+
|
73 |
+
|
74 |
+
def np_quantization(x, _s):
|
75 |
+
return (np.divide(1, np_replace_num(_s, num=0, to=10000)) * np_guarded_power(x, np.array(2)))
|
76 |
+
|
77 |
+
|
78 |
+
def np_dequantization(x, _s):
|
79 |
+
return np.sqrt(np_domain_guard((_s * x), min=0.1, nan=0.1))
|
80 |
+
|
81 |
+
|
82 |
+
def fit_func(x, _s):
|
83 |
+
x_ = np_quantization(x, _s)
|
84 |
+
x_ = np_dequantization(x_, _s)
|
85 |
+
return x_
|
86 |
+
|
87 |
+
|
88 |
+
|
89 |
+
############### HELPERS ###############
|
90 |
+
|
91 |
+
def domain_guard(
|
92 |
+
x: torch.Tensor,
|
93 |
+
min: float = None,
|
94 |
+
max: float = None,
|
95 |
+
posinf: float = None,
|
96 |
+
neginf: float = None,
|
97 |
+
nan: float = None
|
98 |
+
) -> torch.Tensor:
|
99 |
+
"""Guard a tensor to a valid domain."""
|
100 |
+
x = torch.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
101 |
+
if min is not None or max is not None:
|
102 |
+
x = torch.clamp(x, min=min, max=max)
|
103 |
+
return x
|
104 |
+
|
105 |
+
|
106 |
+
def replace_num(x: torch.Tensor, num: float, to: float) -> torch.Tensor:
|
107 |
+
"""Replace a number in a tensor with another number.
|
108 |
+
|
109 |
+
Args:
|
110 |
+
x (torch.Tensor): The input tensor.
|
111 |
+
num (float): The number to replace.
|
112 |
+
to (float): The number to replace with.
|
113 |
+
|
114 |
+
Returns:
|
115 |
+
torch.Tensor: The tensor with the number replaced.
|
116 |
+
"""
|
117 |
+
return torch.where(x == num, to, x)
|
118 |
+
|
119 |
+
|
120 |
+
def guarded_torch_power(x: torch.Tensor, exp: float) -> torch.Tensor:
|
121 |
+
"""Guard the power operation to a valid domain."""
|
122 |
+
return torch.pow(x, exp) if exp >= 1 else torch.pow(torch.relu(x), exp)
|
123 |
+
|
124 |
+
|
125 |
+
def init_ones(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
126 |
+
val = torch.amin(x, dim=1)
|
127 |
+
return torch.ones_like(val, dtype=torch.float32, device=x.device)
|
128 |
+
|
129 |
+
|
130 |
+
def init_rand(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
131 |
+
val = torch.amin(x, dim=1)
|
132 |
+
return torch.randn_like(val, dtype=torch.float32, device=x.device)
|
133 |
+
|
134 |
+
|
135 |
+
def init_space_search(
|
136 |
+
x: torch.Tensor,
|
137 |
+
**kwargs: Dict[str, Any],
|
138 |
+
) -> torch.Tensor:
|
139 |
+
|
140 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
141 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
142 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
143 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
144 |
+
|
145 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
146 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
147 |
+
torch_tensors = torch.stack(tensors)
|
148 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
149 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
150 |
+
mean = torch.mean(torch_tensors, dim=0)
|
151 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
152 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
153 |
+
|
154 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
155 |
+
x_ = x.transpose(0, 1)
|
156 |
+
x_ = qtz_func(x=x_, **params)
|
157 |
+
x_ = deqtz_func(x=x_, **params)
|
158 |
+
x_ = x_.transpose(0, 1)
|
159 |
+
return x_
|
160 |
+
|
161 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
162 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
163 |
+
assert "params_list" in kwargs, "params list must be provided."
|
164 |
+
assert "param" in kwargs, "param must be provided."
|
165 |
+
|
166 |
+
qtz_func = kwargs.get('qtz_func')
|
167 |
+
deqtz_func = kwargs.get('deqtz_func')
|
168 |
+
params_list = kwargs.get('params_list')
|
169 |
+
param = kwargs.get('param')
|
170 |
+
|
171 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
172 |
+
n_random_params = 50 # Number of random parameters to generate
|
173 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
174 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
175 |
+
|
176 |
+
# Initializes the parameters
|
177 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
178 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
179 |
+
|
180 |
+
# Performs the search
|
181 |
+
for _ in range(n_runs):
|
182 |
+
|
183 |
+
best_params = []
|
184 |
+
for param_ in params:
|
185 |
+
try:
|
186 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
187 |
+
loss_ones = nn.MSELoss()(x, x_)
|
188 |
+
|
189 |
+
if len(best_params) < n_best_to_pick:
|
190 |
+
best_params.append((param_, loss_ones.item()))
|
191 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
192 |
+
elif loss_ones < best_params[-1][1]:
|
193 |
+
best_params[-1] = (param_, loss_ones.item())
|
194 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
195 |
+
|
196 |
+
except Exception: # The parameters might not be valid for the function's domain
|
197 |
+
continue
|
198 |
+
|
199 |
+
# Generates new parameters around the mean
|
200 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
201 |
+
|
202 |
+
# Checks if the best parameter is better than the init_ones
|
203 |
+
p_ones = init_ones(x, **kwargs)
|
204 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
205 |
+
loss_ones = nn.MSELoss()(x, x_)
|
206 |
+
|
207 |
+
# Checks if the best parameter is better than the init_rand
|
208 |
+
p_rand = init_rand(x, **kwargs)
|
209 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
210 |
+
loss_rand = nn.MSELoss()(x, x_)
|
211 |
+
|
212 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
213 |
+
return p_rand
|
214 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
215 |
+
return p_ones
|
216 |
+
else:
|
217 |
+
return best_params[0][0]
|
218 |
+
|
219 |
+
|
220 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
221 |
+
x: torch.Tensor,
|
222 |
+
**kwargs: Dict[str, Any],
|
223 |
+
) -> torch.Tensor:
|
224 |
+
assert "bits" in kwargs, "bits must be provided."
|
225 |
+
assert "params" in kwargs, "params must be provided."
|
226 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
227 |
+
|
228 |
+
bits = kwargs.get('bits')
|
229 |
+
params = kwargs.get('params')
|
230 |
+
qtz_func = kwargs.get('qtz_func')
|
231 |
+
|
232 |
+
x_ = x.transpose(0, 1)
|
233 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
234 |
+
x_ = x_.transpose(0, 1)
|
235 |
+
|
236 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
237 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
238 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
239 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
240 |
+
|
241 |
+
eps = torch.finfo(torch.float32).eps
|
242 |
+
|
243 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
244 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
245 |
+
|
246 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
247 |
+
|
248 |
+
# Introduces some noise in scale
|
249 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
250 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
251 |
+
return scale
|
252 |
+
|
253 |
+
|
254 |
+
def init_non_linear_regression_fit(
|
255 |
+
x: torch.Tensor,
|
256 |
+
**kwargs: Dict[str, Any],
|
257 |
+
) -> torch.Tensor:
|
258 |
+
|
259 |
+
assert "params_list" in kwargs, "params list must be provided."
|
260 |
+
assert "np_fit_func" in kwargs, "np_fit_func must be provided."
|
261 |
+
assert "p0" in kwargs, "p0 must be provided."
|
262 |
+
np_fit_func = kwargs.get('np_fit_func')
|
263 |
+
params_list = kwargs.get('params_list')
|
264 |
+
p0 = kwargs.get('p0')
|
265 |
+
|
266 |
+
def _fit(xdata: np.ndarray, ydata: np.ndarray, func: Callable, p0: List[float]):
|
267 |
+
popt, _ = curve_fit(
|
268 |
+
func,
|
269 |
+
xdata,
|
270 |
+
ydata,
|
271 |
+
maxfev=1000,
|
272 |
+
p0=p0,
|
273 |
+
method='lm'
|
274 |
+
)
|
275 |
+
return popt
|
276 |
+
|
277 |
+
# 1. Needs to convert the torch tensor to numpy tensor
|
278 |
+
xdata = x.cpu().numpy()
|
279 |
+
|
280 |
+
# 2. Sorts the data so that it makes it easier to fit to it
|
281 |
+
sorted_xdata = np.sort(xdata, axis=-1)
|
282 |
+
|
283 |
+
p0 = {k: v.cpu().numpy() for k, v in p0.items()}
|
284 |
+
params_list = sorted(params_list) # We need to make sure that it matches the numpy fit func arg order
|
285 |
+
|
286 |
+
# 3. Finds the best parameters for each channel
|
287 |
+
try:
|
288 |
+
params = []
|
289 |
+
for i in range(sorted_xdata.shape[0]):
|
290 |
+
xdata_ = sorted_xdata[i]
|
291 |
+
p0_ = [p0[p][i] for p in params_list]
|
292 |
+
ch_params = _fit(xdata_, xdata_, np_fit_func, p0_)
|
293 |
+
params.append(ch_params)
|
294 |
+
|
295 |
+
# 4. Builds the parameters
|
296 |
+
result = {}
|
297 |
+
for i, p in enumerate(params_list):
|
298 |
+
result[p] = torch.tensor([p_[i] for p_ in params], dtype=torch.float32).to(x.device)
|
299 |
+
|
300 |
+
return result
|
301 |
+
|
302 |
+
except ValueError as e:
|
303 |
+
print(f"Could not fit the function with error: {e}")
|
304 |
+
print(f"Using fallback result...")
|
305 |
+
return {
|
306 |
+
k: torch.tensor(v, dtype=torch.float32).to(x.device) for k, v in p0.items()
|
307 |
+
}
|
308 |
+
|
309 |
+
|
310 |
+
def init_zeros(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
311 |
+
val = torch.amin(x, dim=1)
|
312 |
+
return torch.zeros_like(val, dtype=torch.float32, device=x.device)
|
313 |
+
|
314 |
+
|
315 |
+
def init_inner_scale(tensor: torch.Tensor, _min: float = torch.inf, _max: float = torch.inf) -> torch.Tensor:
|
316 |
+
# Calculate the original minimum and maximum values
|
317 |
+
min_vals, max_vals = torch.aminmax(tensor, dim=-1)
|
318 |
+
x_min = torch.min(min_vals, torch.zeros_like(min_vals))
|
319 |
+
x_max = torch.max(max_vals, torch.zeros_like(max_vals))
|
320 |
+
|
321 |
+
if _max is torch.inf: # We do not need to scale the tensor. Just need to move it
|
322 |
+
return torch.ones_like(x_min)
|
323 |
+
|
324 |
+
# Calculate the scale factor
|
325 |
+
scale = (_max - _min) / (x_max - x_min)
|
326 |
+
return scale
|
327 |
+
|
328 |
+
|
329 |
+
|
330 |
+
############## Quant ###############
|
331 |
+
|
332 |
+
@torch.enable_grad()
|
333 |
+
def learn_parameters(
|
334 |
+
x: torch.Tensor,
|
335 |
+
params: Dict[str, nn.Parameter],
|
336 |
+
qtz_func: nn.Module,
|
337 |
+
deqtz_func: nn.Module,
|
338 |
+
bits: int,
|
339 |
+
target_dtype: torch.dtype,
|
340 |
+
epochs: int = 1000,
|
341 |
+
early_stop: bool = True,
|
342 |
+
do_report: bool = False
|
343 |
+
) -> Tuple[Dict[str, nn.Parameter], torch.Tensor]:
|
344 |
+
loss_fn = nn.MSELoss()
|
345 |
+
|
346 |
+
# Determines the initial learning rate by computing the initial loss and multiplying it by
|
347 |
+
# the order of magnitude of the loss divided by 2
|
348 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
349 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
350 |
+
loss = loss_fn(x, dequant)
|
351 |
+
|
352 |
+
base_lr = 0.1
|
353 |
+
exponent = int(np.floor(np.log10(loss.item())))
|
354 |
+
lr = base_lr * (10 ** (exponent // 2))
|
355 |
+
|
356 |
+
# Requires gradients in the parameters
|
357 |
+
for p in params.values():
|
358 |
+
p.requires_grad = True
|
359 |
+
p.grad = None
|
360 |
+
|
361 |
+
param_keys = list(params.keys())
|
362 |
+
param_values = list(params.values())
|
363 |
+
|
364 |
+
# Defines optimizer and loss function
|
365 |
+
optimizer = torch.optim.Adam(param_values, lr=lr)
|
366 |
+
scheduler = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=1.0, end_factor=0.01, total_iters=epochs // 10)
|
367 |
+
|
368 |
+
# Contains the best loss and the best parameters
|
369 |
+
best_loss = float("inf")
|
370 |
+
best_params = None
|
371 |
+
|
372 |
+
# Used to stop the search early
|
373 |
+
min_delta = 1e-7
|
374 |
+
acc_loss = []
|
375 |
+
percent_epochs_before_stop = 0.1
|
376 |
+
|
377 |
+
for i in range(epochs):
|
378 |
+
optimizer.zero_grad()
|
379 |
+
|
380 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
381 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
382 |
+
loss = loss_fn(x, dequant)
|
383 |
+
|
384 |
+
if loss.isnan() or loss.isinf():
|
385 |
+
raise Exception("Loss is NaN or Inf. Stopping the search.")
|
386 |
+
|
387 |
+
loss.backward()
|
388 |
+
optimizer.step()
|
389 |
+
scheduler.step()
|
390 |
+
|
391 |
+
acc_loss.append(loss.item())
|
392 |
+
|
393 |
+
# Reports loss every 10 steps
|
394 |
+
if i % 10 == 0 and do_report:
|
395 |
+
print(f"Epoch {i}: Loss {loss.item()}")
|
396 |
+
|
397 |
+
# Optimizes the parameter search by storing the best loss and the parameters
|
398 |
+
if loss.item() < best_loss:
|
399 |
+
best_loss = loss.item()
|
400 |
+
best_params = copy.deepcopy({
|
401 |
+
k: v for k, v in params.items() if k in param_keys
|
402 |
+
})
|
403 |
+
|
404 |
+
# We also stop the search if the loss has not considerably during the last 10% epochs
|
405 |
+
if early_stop:
|
406 |
+
epochs_before_stop = int(epochs * percent_epochs_before_stop)
|
407 |
+
if i > epochs_before_stop and abs(acc_loss[i - epochs_before_stop] - acc_loss[i]) < min_delta:
|
408 |
+
break
|
409 |
+
|
410 |
+
# No longer requires gradients in the parameters
|
411 |
+
for p in best_params.values():
|
412 |
+
p.requires_grad = False
|
413 |
+
p.grad = None
|
414 |
+
|
415 |
+
if do_report:
|
416 |
+
return best_params, acc_loss
|
417 |
+
else:
|
418 |
+
return best_params
|
419 |
+
|
420 |
+
|
421 |
+
def quantize(
|
422 |
+
x: torch.Tensor,
|
423 |
+
params: Dict[str, nn.Parameter],
|
424 |
+
func: nn.Module,
|
425 |
+
bits: int,
|
426 |
+
target_dtype: torch.dtype = torch.int8
|
427 |
+
) -> torch.Tensor:
|
428 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
429 |
+
x = x.transpose(0, 1) # Aligns shapes
|
430 |
+
x = func(x=x, **params)
|
431 |
+
x = x.transpose(0, 1)
|
432 |
+
x = torch.clamp(round_func_BPDA(x), quant_min, quant_max).to(target_dtype)
|
433 |
+
return x
|
434 |
+
|
435 |
+
|
436 |
+
def dequantize(
|
437 |
+
x: torch.Tensor,
|
438 |
+
params: Dict[str, nn.Parameter],
|
439 |
+
func: nn.Module,
|
440 |
+
bits: int,
|
441 |
+
out_dtype: torch.dtype
|
442 |
+
) -> torch.Tensor:
|
443 |
+
x = x.to(dtype=out_dtype)
|
444 |
+
x = x.transpose(0, 1)
|
445 |
+
x = func(x=x, **params)
|
446 |
+
x = x.transpose(0, 1)
|
447 |
+
return x
|
448 |
+
|
449 |
+
|
450 |
+
def round_func_BPDA(input):
|
451 |
+
# This is equivalent to replacing round function (non-differentiable) with
|
452 |
+
# an identity function (differentiable) only when backward.
|
453 |
+
forward_value = torch.round(input)
|
454 |
+
out = input.clone()
|
455 |
+
out.data = forward_value.data
|
456 |
+
return out
|
457 |
+
|
458 |
+
|
459 |
+
def get_min_max_from_bits_signed(bit_width: int) -> Tuple[int, int]:
|
460 |
+
return -2 ** (bit_width - 1), 2 ** (bit_width - 1) - 1
|
461 |
+
|
462 |
+
|
463 |
+
|
464 |
+
############## Numpy ###############
|
465 |
+
|
466 |
+
def np_domain_guard(
|
467 |
+
x: np.ndarray,
|
468 |
+
min: float = None,
|
469 |
+
max: float = None,
|
470 |
+
posinf: float = None,
|
471 |
+
neginf: float = None,
|
472 |
+
nan: float = None
|
473 |
+
) -> np.ndarray:
|
474 |
+
"""Guard a tensor to a valid domain."""
|
475 |
+
x = np.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
476 |
+
if min is not None or max is not None:
|
477 |
+
x = np.clip(x, min, max)
|
478 |
+
return x
|
479 |
+
|
480 |
+
|
481 |
+
def np_replace_num(x: np.ndarray, num: float, to: float) -> np.ndarray:
|
482 |
+
"""Replace a number in a tensor with another number.
|
483 |
+
|
484 |
+
Args:
|
485 |
+
x (np.ndarray): The input tensor.
|
486 |
+
num (float): The number to replace.
|
487 |
+
to (float): The number to replace with.
|
488 |
+
|
489 |
+
Returns:
|
490 |
+
np.ndarray: The tensor with the number replaced.
|
491 |
+
"""
|
492 |
+
return np.where(x == num, to, x)
|
493 |
+
|
494 |
+
|
495 |
+
def np_guarded_power(x: np.ndarray, exp: float) -> np.ndarray:
|
496 |
+
"""Guard the power operation to a valid domain."""
|
497 |
+
return np.power(x, exp) if exp >= 1 else np.power(np.maximum(x, 0), exp)
|
498 |
+
|
fn_gen/rnd_search_fb/15/loss.png
ADDED
fn_gen/rnd_search_fb/15/quantization.png
ADDED
fn_gen/rnd_search_fb/16/distortion.png
ADDED
fn_gen/rnd_search_fb/16/expressions.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
tan(_0*x)/_s
|
2 |
+
atan(_s*x)/_0
|
fn_gen/rnd_search_fb/16/fn.py
ADDED
@@ -0,0 +1,584 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch import amin # Necessary for arcsin
|
5 |
+
import copy
|
6 |
+
import torch.nn as nn
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
from scipy.optimize import curve_fit
|
10 |
+
from typing import Dict, Any, Tuple, List, Callable
|
11 |
+
|
12 |
+
|
13 |
+
def quantization(x, **params):
|
14 |
+
return (torch.div(1, replace_num(params['_s'], num=0, to=10000)) * torch.tan(domain_guard((params['_0'] * x), posinf=1, neginf=-1, nan=0)))
|
15 |
+
|
16 |
+
|
17 |
+
def dequantization(x, **params):
|
18 |
+
return (torch.div(1, replace_num(params['_0'], num=0, to=10000)) * torch.atan((params['_s'] * x)))
|
19 |
+
|
20 |
+
|
21 |
+
def init_space_search(
|
22 |
+
x: torch.Tensor,
|
23 |
+
**kwargs: Dict[str, Any],
|
24 |
+
) -> torch.Tensor:
|
25 |
+
|
26 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
27 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
28 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
29 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
30 |
+
|
31 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
32 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
33 |
+
torch_tensors = torch.stack(tensors)
|
34 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
35 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
36 |
+
mean = torch.mean(torch_tensors, dim=0)
|
37 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
38 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
39 |
+
|
40 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
41 |
+
x_ = x.transpose(0, 1)
|
42 |
+
x_ = qtz_func(x=x_, **params)
|
43 |
+
x_ = deqtz_func(x=x_, **params)
|
44 |
+
x_ = x_.transpose(0, 1)
|
45 |
+
return x_
|
46 |
+
|
47 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
48 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
49 |
+
assert "params_list" in kwargs, "params list must be provided."
|
50 |
+
assert "param" in kwargs, "param must be provided."
|
51 |
+
|
52 |
+
qtz_func = kwargs.get('qtz_func')
|
53 |
+
deqtz_func = kwargs.get('deqtz_func')
|
54 |
+
params_list = kwargs.get('params_list')
|
55 |
+
param = kwargs.get('param')
|
56 |
+
|
57 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
58 |
+
n_random_params = 50 # Number of random parameters to generate
|
59 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
60 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
61 |
+
|
62 |
+
# Initializes the parameters
|
63 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
64 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
65 |
+
|
66 |
+
# Performs the search
|
67 |
+
for _ in range(n_runs):
|
68 |
+
|
69 |
+
best_params = []
|
70 |
+
for param_ in params:
|
71 |
+
try:
|
72 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
73 |
+
loss_ones = nn.MSELoss()(x, x_)
|
74 |
+
|
75 |
+
if len(best_params) < n_best_to_pick:
|
76 |
+
best_params.append((param_, loss_ones.item()))
|
77 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
78 |
+
elif loss_ones < best_params[-1][1]:
|
79 |
+
best_params[-1] = (param_, loss_ones.item())
|
80 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
81 |
+
|
82 |
+
except Exception: # The parameters might not be valid for the function's domain
|
83 |
+
continue
|
84 |
+
|
85 |
+
# Generates new parameters around the mean
|
86 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
87 |
+
|
88 |
+
# Checks if the best parameter is better than the init_ones
|
89 |
+
p_ones = init_ones(x, **kwargs)
|
90 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
91 |
+
loss_ones = nn.MSELoss()(x, x_)
|
92 |
+
|
93 |
+
# Checks if the best parameter is better than the init_rand
|
94 |
+
p_rand = init_rand(x, **kwargs)
|
95 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
96 |
+
loss_rand = nn.MSELoss()(x, x_)
|
97 |
+
|
98 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
99 |
+
return p_rand
|
100 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
101 |
+
return p_ones
|
102 |
+
else:
|
103 |
+
return best_params[0][0]
|
104 |
+
|
105 |
+
|
106 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
107 |
+
x: torch.Tensor,
|
108 |
+
**kwargs: Dict[str, Any],
|
109 |
+
) -> torch.Tensor:
|
110 |
+
assert "bits" in kwargs, "bits must be provided."
|
111 |
+
assert "params" in kwargs, "params must be provided."
|
112 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
113 |
+
|
114 |
+
bits = kwargs.get('bits')
|
115 |
+
params = kwargs.get('params')
|
116 |
+
qtz_func = kwargs.get('qtz_func')
|
117 |
+
|
118 |
+
x_ = x.transpose(0, 1)
|
119 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
120 |
+
x_ = x_.transpose(0, 1)
|
121 |
+
|
122 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
123 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
124 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
125 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
126 |
+
|
127 |
+
eps = torch.finfo(torch.float32).eps
|
128 |
+
|
129 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
130 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
131 |
+
|
132 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
133 |
+
|
134 |
+
# Introduces some noise in scale
|
135 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
136 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
137 |
+
return scale
|
138 |
+
|
139 |
+
|
140 |
+
def init_params(x: torch.Tensor, **kwargs: Dict[str, Any]) -> Dict[str, nn.Parameter]:
|
141 |
+
params = {
|
142 |
+
'_0': init_space_search(x, qtz_func=quantization, deqtz_func=dequantization, param='_0', params_list=['_0', '_s'], **kwargs),
|
143 |
+
}
|
144 |
+
params['_s'] = init_linear_scale(x, params=params, qtz_func=quantization, **kwargs)
|
145 |
+
params = {k: nn.Parameter(v, requires_grad=False) for k, v in params.items()}
|
146 |
+
|
147 |
+
if 'post_init_hook' in kwargs:
|
148 |
+
kwargs['post_init_hook'](parameters=params)
|
149 |
+
|
150 |
+
|
151 |
+
if 'post_train_hook' in kwargs:
|
152 |
+
kwargs['post_train_hook'](parameters=params)
|
153 |
+
|
154 |
+
return params
|
155 |
+
|
156 |
+
|
157 |
+
############### Numpy Qtz ###############
|
158 |
+
|
159 |
+
|
160 |
+
def np_quantization(x, _0, _s):
|
161 |
+
return (np.divide(1, np_replace_num(_s, num=0, to=10000)) * np.tan(np_domain_guard((_0 * x), posinf=1, neginf=-1, nan=0)))
|
162 |
+
|
163 |
+
|
164 |
+
def np_dequantization(x, _0, _s):
|
165 |
+
return (np.divide(1, np_replace_num(_0, num=0, to=10000)) * np.arctan((_s * x)))
|
166 |
+
|
167 |
+
|
168 |
+
def fit_func(x, _0, _s):
|
169 |
+
x_ = np_quantization(x, _0, _s)
|
170 |
+
x_ = np_dequantization(x_, _0, _s)
|
171 |
+
return x_
|
172 |
+
|
173 |
+
|
174 |
+
|
175 |
+
############### HELPERS ###############
|
176 |
+
|
177 |
+
def domain_guard(
|
178 |
+
x: torch.Tensor,
|
179 |
+
min: float = None,
|
180 |
+
max: float = None,
|
181 |
+
posinf: float = None,
|
182 |
+
neginf: float = None,
|
183 |
+
nan: float = None
|
184 |
+
) -> torch.Tensor:
|
185 |
+
"""Guard a tensor to a valid domain."""
|
186 |
+
x = torch.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
187 |
+
if min is not None or max is not None:
|
188 |
+
x = torch.clamp(x, min=min, max=max)
|
189 |
+
return x
|
190 |
+
|
191 |
+
|
192 |
+
def replace_num(x: torch.Tensor, num: float, to: float) -> torch.Tensor:
|
193 |
+
"""Replace a number in a tensor with another number.
|
194 |
+
|
195 |
+
Args:
|
196 |
+
x (torch.Tensor): The input tensor.
|
197 |
+
num (float): The number to replace.
|
198 |
+
to (float): The number to replace with.
|
199 |
+
|
200 |
+
Returns:
|
201 |
+
torch.Tensor: The tensor with the number replaced.
|
202 |
+
"""
|
203 |
+
return torch.where(x == num, to, x)
|
204 |
+
|
205 |
+
|
206 |
+
def guarded_torch_power(x: torch.Tensor, exp: float) -> torch.Tensor:
|
207 |
+
"""Guard the power operation to a valid domain."""
|
208 |
+
return torch.pow(x, exp) if exp >= 1 else torch.pow(torch.relu(x), exp)
|
209 |
+
|
210 |
+
|
211 |
+
def init_ones(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
212 |
+
val = torch.amin(x, dim=1)
|
213 |
+
return torch.ones_like(val, dtype=torch.float32, device=x.device)
|
214 |
+
|
215 |
+
|
216 |
+
def init_rand(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
217 |
+
val = torch.amin(x, dim=1)
|
218 |
+
return torch.randn_like(val, dtype=torch.float32, device=x.device)
|
219 |
+
|
220 |
+
|
221 |
+
def init_space_search(
|
222 |
+
x: torch.Tensor,
|
223 |
+
**kwargs: Dict[str, Any],
|
224 |
+
) -> torch.Tensor:
|
225 |
+
|
226 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
227 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
228 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
229 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
230 |
+
|
231 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
232 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
233 |
+
torch_tensors = torch.stack(tensors)
|
234 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
235 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
236 |
+
mean = torch.mean(torch_tensors, dim=0)
|
237 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
238 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
239 |
+
|
240 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
241 |
+
x_ = x.transpose(0, 1)
|
242 |
+
x_ = qtz_func(x=x_, **params)
|
243 |
+
x_ = deqtz_func(x=x_, **params)
|
244 |
+
x_ = x_.transpose(0, 1)
|
245 |
+
return x_
|
246 |
+
|
247 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
248 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
249 |
+
assert "params_list" in kwargs, "params list must be provided."
|
250 |
+
assert "param" in kwargs, "param must be provided."
|
251 |
+
|
252 |
+
qtz_func = kwargs.get('qtz_func')
|
253 |
+
deqtz_func = kwargs.get('deqtz_func')
|
254 |
+
params_list = kwargs.get('params_list')
|
255 |
+
param = kwargs.get('param')
|
256 |
+
|
257 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
258 |
+
n_random_params = 50 # Number of random parameters to generate
|
259 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
260 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
261 |
+
|
262 |
+
# Initializes the parameters
|
263 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
264 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
265 |
+
|
266 |
+
# Performs the search
|
267 |
+
for _ in range(n_runs):
|
268 |
+
|
269 |
+
best_params = []
|
270 |
+
for param_ in params:
|
271 |
+
try:
|
272 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
273 |
+
loss_ones = nn.MSELoss()(x, x_)
|
274 |
+
|
275 |
+
if len(best_params) < n_best_to_pick:
|
276 |
+
best_params.append((param_, loss_ones.item()))
|
277 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
278 |
+
elif loss_ones < best_params[-1][1]:
|
279 |
+
best_params[-1] = (param_, loss_ones.item())
|
280 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
281 |
+
|
282 |
+
except Exception: # The parameters might not be valid for the function's domain
|
283 |
+
continue
|
284 |
+
|
285 |
+
# Generates new parameters around the mean
|
286 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
287 |
+
|
288 |
+
# Checks if the best parameter is better than the init_ones
|
289 |
+
p_ones = init_ones(x, **kwargs)
|
290 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
291 |
+
loss_ones = nn.MSELoss()(x, x_)
|
292 |
+
|
293 |
+
# Checks if the best parameter is better than the init_rand
|
294 |
+
p_rand = init_rand(x, **kwargs)
|
295 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
296 |
+
loss_rand = nn.MSELoss()(x, x_)
|
297 |
+
|
298 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
299 |
+
return p_rand
|
300 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
301 |
+
return p_ones
|
302 |
+
else:
|
303 |
+
return best_params[0][0]
|
304 |
+
|
305 |
+
|
306 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
307 |
+
x: torch.Tensor,
|
308 |
+
**kwargs: Dict[str, Any],
|
309 |
+
) -> torch.Tensor:
|
310 |
+
assert "bits" in kwargs, "bits must be provided."
|
311 |
+
assert "params" in kwargs, "params must be provided."
|
312 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
313 |
+
|
314 |
+
bits = kwargs.get('bits')
|
315 |
+
params = kwargs.get('params')
|
316 |
+
qtz_func = kwargs.get('qtz_func')
|
317 |
+
|
318 |
+
x_ = x.transpose(0, 1)
|
319 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
320 |
+
x_ = x_.transpose(0, 1)
|
321 |
+
|
322 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
323 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
324 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
325 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
326 |
+
|
327 |
+
eps = torch.finfo(torch.float32).eps
|
328 |
+
|
329 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
330 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
331 |
+
|
332 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
333 |
+
|
334 |
+
# Introduces some noise in scale
|
335 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
336 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
337 |
+
return scale
|
338 |
+
|
339 |
+
|
340 |
+
def init_non_linear_regression_fit(
|
341 |
+
x: torch.Tensor,
|
342 |
+
**kwargs: Dict[str, Any],
|
343 |
+
) -> torch.Tensor:
|
344 |
+
|
345 |
+
assert "params_list" in kwargs, "params list must be provided."
|
346 |
+
assert "np_fit_func" in kwargs, "np_fit_func must be provided."
|
347 |
+
assert "p0" in kwargs, "p0 must be provided."
|
348 |
+
np_fit_func = kwargs.get('np_fit_func')
|
349 |
+
params_list = kwargs.get('params_list')
|
350 |
+
p0 = kwargs.get('p0')
|
351 |
+
|
352 |
+
def _fit(xdata: np.ndarray, ydata: np.ndarray, func: Callable, p0: List[float]):
|
353 |
+
popt, _ = curve_fit(
|
354 |
+
func,
|
355 |
+
xdata,
|
356 |
+
ydata,
|
357 |
+
maxfev=1000,
|
358 |
+
p0=p0,
|
359 |
+
method='lm'
|
360 |
+
)
|
361 |
+
return popt
|
362 |
+
|
363 |
+
# 1. Needs to convert the torch tensor to numpy tensor
|
364 |
+
xdata = x.cpu().numpy()
|
365 |
+
|
366 |
+
# 2. Sorts the data so that it makes it easier to fit to it
|
367 |
+
sorted_xdata = np.sort(xdata, axis=-1)
|
368 |
+
|
369 |
+
p0 = {k: v.cpu().numpy() for k, v in p0.items()}
|
370 |
+
params_list = sorted(params_list) # We need to make sure that it matches the numpy fit func arg order
|
371 |
+
|
372 |
+
# 3. Finds the best parameters for each channel
|
373 |
+
try:
|
374 |
+
params = []
|
375 |
+
for i in range(sorted_xdata.shape[0]):
|
376 |
+
xdata_ = sorted_xdata[i]
|
377 |
+
p0_ = [p0[p][i] for p in params_list]
|
378 |
+
ch_params = _fit(xdata_, xdata_, np_fit_func, p0_)
|
379 |
+
params.append(ch_params)
|
380 |
+
|
381 |
+
# 4. Builds the parameters
|
382 |
+
result = {}
|
383 |
+
for i, p in enumerate(params_list):
|
384 |
+
result[p] = torch.tensor([p_[i] for p_ in params], dtype=torch.float32).to(x.device)
|
385 |
+
|
386 |
+
return result
|
387 |
+
|
388 |
+
except ValueError as e:
|
389 |
+
print(f"Could not fit the function with error: {e}")
|
390 |
+
print(f"Using fallback result...")
|
391 |
+
return {
|
392 |
+
k: torch.tensor(v, dtype=torch.float32).to(x.device) for k, v in p0.items()
|
393 |
+
}
|
394 |
+
|
395 |
+
|
396 |
+
def init_zeros(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
397 |
+
val = torch.amin(x, dim=1)
|
398 |
+
return torch.zeros_like(val, dtype=torch.float32, device=x.device)
|
399 |
+
|
400 |
+
|
401 |
+
def init_inner_scale(tensor: torch.Tensor, _min: float = torch.inf, _max: float = torch.inf) -> torch.Tensor:
|
402 |
+
# Calculate the original minimum and maximum values
|
403 |
+
min_vals, max_vals = torch.aminmax(tensor, dim=-1)
|
404 |
+
x_min = torch.min(min_vals, torch.zeros_like(min_vals))
|
405 |
+
x_max = torch.max(max_vals, torch.zeros_like(max_vals))
|
406 |
+
|
407 |
+
if _max is torch.inf: # We do not need to scale the tensor. Just need to move it
|
408 |
+
return torch.ones_like(x_min)
|
409 |
+
|
410 |
+
# Calculate the scale factor
|
411 |
+
scale = (_max - _min) / (x_max - x_min)
|
412 |
+
return scale
|
413 |
+
|
414 |
+
|
415 |
+
|
416 |
+
############## Quant ###############
|
417 |
+
|
418 |
+
@torch.enable_grad()
|
419 |
+
def learn_parameters(
|
420 |
+
x: torch.Tensor,
|
421 |
+
params: Dict[str, nn.Parameter],
|
422 |
+
qtz_func: nn.Module,
|
423 |
+
deqtz_func: nn.Module,
|
424 |
+
bits: int,
|
425 |
+
target_dtype: torch.dtype,
|
426 |
+
epochs: int = 1000,
|
427 |
+
early_stop: bool = True,
|
428 |
+
do_report: bool = False
|
429 |
+
) -> Tuple[Dict[str, nn.Parameter], torch.Tensor]:
|
430 |
+
loss_fn = nn.MSELoss()
|
431 |
+
|
432 |
+
# Determines the initial learning rate by computing the initial loss and multiplying it by
|
433 |
+
# the order of magnitude of the loss divided by 2
|
434 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
435 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
436 |
+
loss = loss_fn(x, dequant)
|
437 |
+
|
438 |
+
base_lr = 0.1
|
439 |
+
exponent = int(np.floor(np.log10(loss.item())))
|
440 |
+
lr = base_lr * (10 ** (exponent // 2))
|
441 |
+
|
442 |
+
# Requires gradients in the parameters
|
443 |
+
for p in params.values():
|
444 |
+
p.requires_grad = True
|
445 |
+
p.grad = None
|
446 |
+
|
447 |
+
param_keys = list(params.keys())
|
448 |
+
param_values = list(params.values())
|
449 |
+
|
450 |
+
# Defines optimizer and loss function
|
451 |
+
optimizer = torch.optim.Adam(param_values, lr=lr)
|
452 |
+
scheduler = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=1.0, end_factor=0.01, total_iters=epochs // 10)
|
453 |
+
|
454 |
+
# Contains the best loss and the best parameters
|
455 |
+
best_loss = float("inf")
|
456 |
+
best_params = None
|
457 |
+
|
458 |
+
# Used to stop the search early
|
459 |
+
min_delta = 1e-7
|
460 |
+
acc_loss = []
|
461 |
+
percent_epochs_before_stop = 0.1
|
462 |
+
|
463 |
+
for i in range(epochs):
|
464 |
+
optimizer.zero_grad()
|
465 |
+
|
466 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
467 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
468 |
+
loss = loss_fn(x, dequant)
|
469 |
+
|
470 |
+
if loss.isnan() or loss.isinf():
|
471 |
+
raise Exception("Loss is NaN or Inf. Stopping the search.")
|
472 |
+
|
473 |
+
loss.backward()
|
474 |
+
optimizer.step()
|
475 |
+
scheduler.step()
|
476 |
+
|
477 |
+
acc_loss.append(loss.item())
|
478 |
+
|
479 |
+
# Reports loss every 10 steps
|
480 |
+
if i % 10 == 0 and do_report:
|
481 |
+
print(f"Epoch {i}: Loss {loss.item()}")
|
482 |
+
|
483 |
+
# Optimizes the parameter search by storing the best loss and the parameters
|
484 |
+
if loss.item() < best_loss:
|
485 |
+
best_loss = loss.item()
|
486 |
+
best_params = copy.deepcopy({
|
487 |
+
k: v for k, v in params.items() if k in param_keys
|
488 |
+
})
|
489 |
+
|
490 |
+
# We also stop the search if the loss has not considerably during the last 10% epochs
|
491 |
+
if early_stop:
|
492 |
+
epochs_before_stop = int(epochs * percent_epochs_before_stop)
|
493 |
+
if i > epochs_before_stop and abs(acc_loss[i - epochs_before_stop] - acc_loss[i]) < min_delta:
|
494 |
+
break
|
495 |
+
|
496 |
+
# No longer requires gradients in the parameters
|
497 |
+
for p in best_params.values():
|
498 |
+
p.requires_grad = False
|
499 |
+
p.grad = None
|
500 |
+
|
501 |
+
if do_report:
|
502 |
+
return best_params, acc_loss
|
503 |
+
else:
|
504 |
+
return best_params
|
505 |
+
|
506 |
+
|
507 |
+
def quantize(
|
508 |
+
x: torch.Tensor,
|
509 |
+
params: Dict[str, nn.Parameter],
|
510 |
+
func: nn.Module,
|
511 |
+
bits: int,
|
512 |
+
target_dtype: torch.dtype = torch.int8
|
513 |
+
) -> torch.Tensor:
|
514 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
515 |
+
x = x.transpose(0, 1) # Aligns shapes
|
516 |
+
x = func(x=x, **params)
|
517 |
+
x = x.transpose(0, 1)
|
518 |
+
x = torch.clamp(round_func_BPDA(x), quant_min, quant_max).to(target_dtype)
|
519 |
+
return x
|
520 |
+
|
521 |
+
|
522 |
+
def dequantize(
|
523 |
+
x: torch.Tensor,
|
524 |
+
params: Dict[str, nn.Parameter],
|
525 |
+
func: nn.Module,
|
526 |
+
bits: int,
|
527 |
+
out_dtype: torch.dtype
|
528 |
+
) -> torch.Tensor:
|
529 |
+
x = x.to(dtype=out_dtype)
|
530 |
+
x = x.transpose(0, 1)
|
531 |
+
x = func(x=x, **params)
|
532 |
+
x = x.transpose(0, 1)
|
533 |
+
return x
|
534 |
+
|
535 |
+
|
536 |
+
def round_func_BPDA(input):
|
537 |
+
# This is equivalent to replacing round function (non-differentiable) with
|
538 |
+
# an identity function (differentiable) only when backward.
|
539 |
+
forward_value = torch.round(input)
|
540 |
+
out = input.clone()
|
541 |
+
out.data = forward_value.data
|
542 |
+
return out
|
543 |
+
|
544 |
+
|
545 |
+
def get_min_max_from_bits_signed(bit_width: int) -> Tuple[int, int]:
|
546 |
+
return -2 ** (bit_width - 1), 2 ** (bit_width - 1) - 1
|
547 |
+
|
548 |
+
|
549 |
+
|
550 |
+
############## Numpy ###############
|
551 |
+
|
552 |
+
def np_domain_guard(
|
553 |
+
x: np.ndarray,
|
554 |
+
min: float = None,
|
555 |
+
max: float = None,
|
556 |
+
posinf: float = None,
|
557 |
+
neginf: float = None,
|
558 |
+
nan: float = None
|
559 |
+
) -> np.ndarray:
|
560 |
+
"""Guard a tensor to a valid domain."""
|
561 |
+
x = np.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
562 |
+
if min is not None or max is not None:
|
563 |
+
x = np.clip(x, min, max)
|
564 |
+
return x
|
565 |
+
|
566 |
+
|
567 |
+
def np_replace_num(x: np.ndarray, num: float, to: float) -> np.ndarray:
|
568 |
+
"""Replace a number in a tensor with another number.
|
569 |
+
|
570 |
+
Args:
|
571 |
+
x (np.ndarray): The input tensor.
|
572 |
+
num (float): The number to replace.
|
573 |
+
to (float): The number to replace with.
|
574 |
+
|
575 |
+
Returns:
|
576 |
+
np.ndarray: The tensor with the number replaced.
|
577 |
+
"""
|
578 |
+
return np.where(x == num, to, x)
|
579 |
+
|
580 |
+
|
581 |
+
def np_guarded_power(x: np.ndarray, exp: float) -> np.ndarray:
|
582 |
+
"""Guard the power operation to a valid domain."""
|
583 |
+
return np.power(x, exp) if exp >= 1 else np.power(np.maximum(x, 0), exp)
|
584 |
+
|
fn_gen/rnd_search_fb/16/loss.png
ADDED
fn_gen/rnd_search_fb/16/quantization.png
ADDED
fn_gen/rnd_search_fb/17/distortion.png
ADDED
fn_gen/rnd_search_fb/17/expressions.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
atan(_0*x)/_s
|
2 |
+
tan(_s*x)/_0
|
fn_gen/rnd_search_fb/17/fn.py
ADDED
@@ -0,0 +1,584 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch import amin # Necessary for arcsin
|
5 |
+
import copy
|
6 |
+
import torch.nn as nn
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
from scipy.optimize import curve_fit
|
10 |
+
from typing import Dict, Any, Tuple, List, Callable
|
11 |
+
|
12 |
+
|
13 |
+
def quantization(x, **params):
|
14 |
+
return (torch.div(1, replace_num(params['_s'], num=0, to=10000)) * torch.atan((params['_0'] * x)))
|
15 |
+
|
16 |
+
|
17 |
+
def dequantization(x, **params):
|
18 |
+
return (torch.div(1, replace_num(params['_0'], num=0, to=10000)) * torch.tan(domain_guard((params['_s'] * x), posinf=1, neginf=-1, nan=0)))
|
19 |
+
|
20 |
+
|
21 |
+
def init_space_search(
|
22 |
+
x: torch.Tensor,
|
23 |
+
**kwargs: Dict[str, Any],
|
24 |
+
) -> torch.Tensor:
|
25 |
+
|
26 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
27 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
28 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
29 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
30 |
+
|
31 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
32 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
33 |
+
torch_tensors = torch.stack(tensors)
|
34 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
35 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
36 |
+
mean = torch.mean(torch_tensors, dim=0)
|
37 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
38 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
39 |
+
|
40 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
41 |
+
x_ = x.transpose(0, 1)
|
42 |
+
x_ = qtz_func(x=x_, **params)
|
43 |
+
x_ = deqtz_func(x=x_, **params)
|
44 |
+
x_ = x_.transpose(0, 1)
|
45 |
+
return x_
|
46 |
+
|
47 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
48 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
49 |
+
assert "params_list" in kwargs, "params list must be provided."
|
50 |
+
assert "param" in kwargs, "param must be provided."
|
51 |
+
|
52 |
+
qtz_func = kwargs.get('qtz_func')
|
53 |
+
deqtz_func = kwargs.get('deqtz_func')
|
54 |
+
params_list = kwargs.get('params_list')
|
55 |
+
param = kwargs.get('param')
|
56 |
+
|
57 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
58 |
+
n_random_params = 50 # Number of random parameters to generate
|
59 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
60 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
61 |
+
|
62 |
+
# Initializes the parameters
|
63 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
64 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
65 |
+
|
66 |
+
# Performs the search
|
67 |
+
for _ in range(n_runs):
|
68 |
+
|
69 |
+
best_params = []
|
70 |
+
for param_ in params:
|
71 |
+
try:
|
72 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
73 |
+
loss_ones = nn.MSELoss()(x, x_)
|
74 |
+
|
75 |
+
if len(best_params) < n_best_to_pick:
|
76 |
+
best_params.append((param_, loss_ones.item()))
|
77 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
78 |
+
elif loss_ones < best_params[-1][1]:
|
79 |
+
best_params[-1] = (param_, loss_ones.item())
|
80 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
81 |
+
|
82 |
+
except Exception: # The parameters might not be valid for the function's domain
|
83 |
+
continue
|
84 |
+
|
85 |
+
# Generates new parameters around the mean
|
86 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
87 |
+
|
88 |
+
# Checks if the best parameter is better than the init_ones
|
89 |
+
p_ones = init_ones(x, **kwargs)
|
90 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
91 |
+
loss_ones = nn.MSELoss()(x, x_)
|
92 |
+
|
93 |
+
# Checks if the best parameter is better than the init_rand
|
94 |
+
p_rand = init_rand(x, **kwargs)
|
95 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
96 |
+
loss_rand = nn.MSELoss()(x, x_)
|
97 |
+
|
98 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
99 |
+
return p_rand
|
100 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
101 |
+
return p_ones
|
102 |
+
else:
|
103 |
+
return best_params[0][0]
|
104 |
+
|
105 |
+
|
106 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
107 |
+
x: torch.Tensor,
|
108 |
+
**kwargs: Dict[str, Any],
|
109 |
+
) -> torch.Tensor:
|
110 |
+
assert "bits" in kwargs, "bits must be provided."
|
111 |
+
assert "params" in kwargs, "params must be provided."
|
112 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
113 |
+
|
114 |
+
bits = kwargs.get('bits')
|
115 |
+
params = kwargs.get('params')
|
116 |
+
qtz_func = kwargs.get('qtz_func')
|
117 |
+
|
118 |
+
x_ = x.transpose(0, 1)
|
119 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
120 |
+
x_ = x_.transpose(0, 1)
|
121 |
+
|
122 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
123 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
124 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
125 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
126 |
+
|
127 |
+
eps = torch.finfo(torch.float32).eps
|
128 |
+
|
129 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
130 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
131 |
+
|
132 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
133 |
+
|
134 |
+
# Introduces some noise in scale
|
135 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
136 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
137 |
+
return scale
|
138 |
+
|
139 |
+
|
140 |
+
def init_params(x: torch.Tensor, **kwargs: Dict[str, Any]) -> Dict[str, nn.Parameter]:
|
141 |
+
params = {
|
142 |
+
'_0': init_space_search(x, qtz_func=quantization, deqtz_func=dequantization, param='_0', params_list=['_0', '_s'], **kwargs),
|
143 |
+
}
|
144 |
+
params['_s'] = init_linear_scale(x, params=params, qtz_func=quantization, **kwargs)
|
145 |
+
params = {k: nn.Parameter(v, requires_grad=False) for k, v in params.items()}
|
146 |
+
|
147 |
+
if 'post_init_hook' in kwargs:
|
148 |
+
kwargs['post_init_hook'](parameters=params)
|
149 |
+
|
150 |
+
|
151 |
+
if 'post_train_hook' in kwargs:
|
152 |
+
kwargs['post_train_hook'](parameters=params)
|
153 |
+
|
154 |
+
return params
|
155 |
+
|
156 |
+
|
157 |
+
############### Numpy Qtz ###############
|
158 |
+
|
159 |
+
|
160 |
+
def np_quantization(x, _0, _s):
|
161 |
+
return (np.divide(1, np_replace_num(_s, num=0, to=10000)) * np.arctan((_0 * x)))
|
162 |
+
|
163 |
+
|
164 |
+
def np_dequantization(x, _0, _s):
|
165 |
+
return (np.divide(1, np_replace_num(_0, num=0, to=10000)) * np.tan(np_domain_guard((_s * x), posinf=1, neginf=-1, nan=0)))
|
166 |
+
|
167 |
+
|
168 |
+
def fit_func(x, _0, _s):
|
169 |
+
x_ = np_quantization(x, _0, _s)
|
170 |
+
x_ = np_dequantization(x_, _0, _s)
|
171 |
+
return x_
|
172 |
+
|
173 |
+
|
174 |
+
|
175 |
+
############### HELPERS ###############
|
176 |
+
|
177 |
+
def domain_guard(
|
178 |
+
x: torch.Tensor,
|
179 |
+
min: float = None,
|
180 |
+
max: float = None,
|
181 |
+
posinf: float = None,
|
182 |
+
neginf: float = None,
|
183 |
+
nan: float = None
|
184 |
+
) -> torch.Tensor:
|
185 |
+
"""Guard a tensor to a valid domain."""
|
186 |
+
x = torch.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
187 |
+
if min is not None or max is not None:
|
188 |
+
x = torch.clamp(x, min=min, max=max)
|
189 |
+
return x
|
190 |
+
|
191 |
+
|
192 |
+
def replace_num(x: torch.Tensor, num: float, to: float) -> torch.Tensor:
|
193 |
+
"""Replace a number in a tensor with another number.
|
194 |
+
|
195 |
+
Args:
|
196 |
+
x (torch.Tensor): The input tensor.
|
197 |
+
num (float): The number to replace.
|
198 |
+
to (float): The number to replace with.
|
199 |
+
|
200 |
+
Returns:
|
201 |
+
torch.Tensor: The tensor with the number replaced.
|
202 |
+
"""
|
203 |
+
return torch.where(x == num, to, x)
|
204 |
+
|
205 |
+
|
206 |
+
def guarded_torch_power(x: torch.Tensor, exp: float) -> torch.Tensor:
|
207 |
+
"""Guard the power operation to a valid domain."""
|
208 |
+
return torch.pow(x, exp) if exp >= 1 else torch.pow(torch.relu(x), exp)
|
209 |
+
|
210 |
+
|
211 |
+
def init_ones(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
212 |
+
val = torch.amin(x, dim=1)
|
213 |
+
return torch.ones_like(val, dtype=torch.float32, device=x.device)
|
214 |
+
|
215 |
+
|
216 |
+
def init_rand(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
217 |
+
val = torch.amin(x, dim=1)
|
218 |
+
return torch.randn_like(val, dtype=torch.float32, device=x.device)
|
219 |
+
|
220 |
+
|
221 |
+
def init_space_search(
|
222 |
+
x: torch.Tensor,
|
223 |
+
**kwargs: Dict[str, Any],
|
224 |
+
) -> torch.Tensor:
|
225 |
+
|
226 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
227 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
228 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
229 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
230 |
+
|
231 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
232 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
233 |
+
torch_tensors = torch.stack(tensors)
|
234 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
235 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
236 |
+
mean = torch.mean(torch_tensors, dim=0)
|
237 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
238 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
239 |
+
|
240 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
241 |
+
x_ = x.transpose(0, 1)
|
242 |
+
x_ = qtz_func(x=x_, **params)
|
243 |
+
x_ = deqtz_func(x=x_, **params)
|
244 |
+
x_ = x_.transpose(0, 1)
|
245 |
+
return x_
|
246 |
+
|
247 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
248 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
249 |
+
assert "params_list" in kwargs, "params list must be provided."
|
250 |
+
assert "param" in kwargs, "param must be provided."
|
251 |
+
|
252 |
+
qtz_func = kwargs.get('qtz_func')
|
253 |
+
deqtz_func = kwargs.get('deqtz_func')
|
254 |
+
params_list = kwargs.get('params_list')
|
255 |
+
param = kwargs.get('param')
|
256 |
+
|
257 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
258 |
+
n_random_params = 50 # Number of random parameters to generate
|
259 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
260 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
261 |
+
|
262 |
+
# Initializes the parameters
|
263 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
264 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
265 |
+
|
266 |
+
# Performs the search
|
267 |
+
for _ in range(n_runs):
|
268 |
+
|
269 |
+
best_params = []
|
270 |
+
for param_ in params:
|
271 |
+
try:
|
272 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
273 |
+
loss_ones = nn.MSELoss()(x, x_)
|
274 |
+
|
275 |
+
if len(best_params) < n_best_to_pick:
|
276 |
+
best_params.append((param_, loss_ones.item()))
|
277 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
278 |
+
elif loss_ones < best_params[-1][1]:
|
279 |
+
best_params[-1] = (param_, loss_ones.item())
|
280 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
281 |
+
|
282 |
+
except Exception: # The parameters might not be valid for the function's domain
|
283 |
+
continue
|
284 |
+
|
285 |
+
# Generates new parameters around the mean
|
286 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
287 |
+
|
288 |
+
# Checks if the best parameter is better than the init_ones
|
289 |
+
p_ones = init_ones(x, **kwargs)
|
290 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
291 |
+
loss_ones = nn.MSELoss()(x, x_)
|
292 |
+
|
293 |
+
# Checks if the best parameter is better than the init_rand
|
294 |
+
p_rand = init_rand(x, **kwargs)
|
295 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
296 |
+
loss_rand = nn.MSELoss()(x, x_)
|
297 |
+
|
298 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
299 |
+
return p_rand
|
300 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
301 |
+
return p_ones
|
302 |
+
else:
|
303 |
+
return best_params[0][0]
|
304 |
+
|
305 |
+
|
306 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
307 |
+
x: torch.Tensor,
|
308 |
+
**kwargs: Dict[str, Any],
|
309 |
+
) -> torch.Tensor:
|
310 |
+
assert "bits" in kwargs, "bits must be provided."
|
311 |
+
assert "params" in kwargs, "params must be provided."
|
312 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
313 |
+
|
314 |
+
bits = kwargs.get('bits')
|
315 |
+
params = kwargs.get('params')
|
316 |
+
qtz_func = kwargs.get('qtz_func')
|
317 |
+
|
318 |
+
x_ = x.transpose(0, 1)
|
319 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
320 |
+
x_ = x_.transpose(0, 1)
|
321 |
+
|
322 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
323 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
324 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
325 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
326 |
+
|
327 |
+
eps = torch.finfo(torch.float32).eps
|
328 |
+
|
329 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
330 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
331 |
+
|
332 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
333 |
+
|
334 |
+
# Introduces some noise in scale
|
335 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
336 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
337 |
+
return scale
|
338 |
+
|
339 |
+
|
340 |
+
def init_non_linear_regression_fit(
|
341 |
+
x: torch.Tensor,
|
342 |
+
**kwargs: Dict[str, Any],
|
343 |
+
) -> torch.Tensor:
|
344 |
+
|
345 |
+
assert "params_list" in kwargs, "params list must be provided."
|
346 |
+
assert "np_fit_func" in kwargs, "np_fit_func must be provided."
|
347 |
+
assert "p0" in kwargs, "p0 must be provided."
|
348 |
+
np_fit_func = kwargs.get('np_fit_func')
|
349 |
+
params_list = kwargs.get('params_list')
|
350 |
+
p0 = kwargs.get('p0')
|
351 |
+
|
352 |
+
def _fit(xdata: np.ndarray, ydata: np.ndarray, func: Callable, p0: List[float]):
|
353 |
+
popt, _ = curve_fit(
|
354 |
+
func,
|
355 |
+
xdata,
|
356 |
+
ydata,
|
357 |
+
maxfev=1000,
|
358 |
+
p0=p0,
|
359 |
+
method='lm'
|
360 |
+
)
|
361 |
+
return popt
|
362 |
+
|
363 |
+
# 1. Needs to convert the torch tensor to numpy tensor
|
364 |
+
xdata = x.cpu().numpy()
|
365 |
+
|
366 |
+
# 2. Sorts the data so that it makes it easier to fit to it
|
367 |
+
sorted_xdata = np.sort(xdata, axis=-1)
|
368 |
+
|
369 |
+
p0 = {k: v.cpu().numpy() for k, v in p0.items()}
|
370 |
+
params_list = sorted(params_list) # We need to make sure that it matches the numpy fit func arg order
|
371 |
+
|
372 |
+
# 3. Finds the best parameters for each channel
|
373 |
+
try:
|
374 |
+
params = []
|
375 |
+
for i in range(sorted_xdata.shape[0]):
|
376 |
+
xdata_ = sorted_xdata[i]
|
377 |
+
p0_ = [p0[p][i] for p in params_list]
|
378 |
+
ch_params = _fit(xdata_, xdata_, np_fit_func, p0_)
|
379 |
+
params.append(ch_params)
|
380 |
+
|
381 |
+
# 4. Builds the parameters
|
382 |
+
result = {}
|
383 |
+
for i, p in enumerate(params_list):
|
384 |
+
result[p] = torch.tensor([p_[i] for p_ in params], dtype=torch.float32).to(x.device)
|
385 |
+
|
386 |
+
return result
|
387 |
+
|
388 |
+
except ValueError as e:
|
389 |
+
print(f"Could not fit the function with error: {e}")
|
390 |
+
print(f"Using fallback result...")
|
391 |
+
return {
|
392 |
+
k: torch.tensor(v, dtype=torch.float32).to(x.device) for k, v in p0.items()
|
393 |
+
}
|
394 |
+
|
395 |
+
|
396 |
+
def init_zeros(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
397 |
+
val = torch.amin(x, dim=1)
|
398 |
+
return torch.zeros_like(val, dtype=torch.float32, device=x.device)
|
399 |
+
|
400 |
+
|
401 |
+
def init_inner_scale(tensor: torch.Tensor, _min: float = torch.inf, _max: float = torch.inf) -> torch.Tensor:
|
402 |
+
# Calculate the original minimum and maximum values
|
403 |
+
min_vals, max_vals = torch.aminmax(tensor, dim=-1)
|
404 |
+
x_min = torch.min(min_vals, torch.zeros_like(min_vals))
|
405 |
+
x_max = torch.max(max_vals, torch.zeros_like(max_vals))
|
406 |
+
|
407 |
+
if _max is torch.inf: # We do not need to scale the tensor. Just need to move it
|
408 |
+
return torch.ones_like(x_min)
|
409 |
+
|
410 |
+
# Calculate the scale factor
|
411 |
+
scale = (_max - _min) / (x_max - x_min)
|
412 |
+
return scale
|
413 |
+
|
414 |
+
|
415 |
+
|
416 |
+
############## Quant ###############
|
417 |
+
|
418 |
+
@torch.enable_grad()
|
419 |
+
def learn_parameters(
|
420 |
+
x: torch.Tensor,
|
421 |
+
params: Dict[str, nn.Parameter],
|
422 |
+
qtz_func: nn.Module,
|
423 |
+
deqtz_func: nn.Module,
|
424 |
+
bits: int,
|
425 |
+
target_dtype: torch.dtype,
|
426 |
+
epochs: int = 1000,
|
427 |
+
early_stop: bool = True,
|
428 |
+
do_report: bool = False
|
429 |
+
) -> Tuple[Dict[str, nn.Parameter], torch.Tensor]:
|
430 |
+
loss_fn = nn.MSELoss()
|
431 |
+
|
432 |
+
# Determines the initial learning rate by computing the initial loss and multiplying it by
|
433 |
+
# the order of magnitude of the loss divided by 2
|
434 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
435 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
436 |
+
loss = loss_fn(x, dequant)
|
437 |
+
|
438 |
+
base_lr = 0.1
|
439 |
+
exponent = int(np.floor(np.log10(loss.item())))
|
440 |
+
lr = base_lr * (10 ** (exponent // 2))
|
441 |
+
|
442 |
+
# Requires gradients in the parameters
|
443 |
+
for p in params.values():
|
444 |
+
p.requires_grad = True
|
445 |
+
p.grad = None
|
446 |
+
|
447 |
+
param_keys = list(params.keys())
|
448 |
+
param_values = list(params.values())
|
449 |
+
|
450 |
+
# Defines optimizer and loss function
|
451 |
+
optimizer = torch.optim.Adam(param_values, lr=lr)
|
452 |
+
scheduler = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=1.0, end_factor=0.01, total_iters=epochs // 10)
|
453 |
+
|
454 |
+
# Contains the best loss and the best parameters
|
455 |
+
best_loss = float("inf")
|
456 |
+
best_params = None
|
457 |
+
|
458 |
+
# Used to stop the search early
|
459 |
+
min_delta = 1e-7
|
460 |
+
acc_loss = []
|
461 |
+
percent_epochs_before_stop = 0.1
|
462 |
+
|
463 |
+
for i in range(epochs):
|
464 |
+
optimizer.zero_grad()
|
465 |
+
|
466 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
467 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
468 |
+
loss = loss_fn(x, dequant)
|
469 |
+
|
470 |
+
if loss.isnan() or loss.isinf():
|
471 |
+
raise Exception("Loss is NaN or Inf. Stopping the search.")
|
472 |
+
|
473 |
+
loss.backward()
|
474 |
+
optimizer.step()
|
475 |
+
scheduler.step()
|
476 |
+
|
477 |
+
acc_loss.append(loss.item())
|
478 |
+
|
479 |
+
# Reports loss every 10 steps
|
480 |
+
if i % 10 == 0 and do_report:
|
481 |
+
print(f"Epoch {i}: Loss {loss.item()}")
|
482 |
+
|
483 |
+
# Optimizes the parameter search by storing the best loss and the parameters
|
484 |
+
if loss.item() < best_loss:
|
485 |
+
best_loss = loss.item()
|
486 |
+
best_params = copy.deepcopy({
|
487 |
+
k: v for k, v in params.items() if k in param_keys
|
488 |
+
})
|
489 |
+
|
490 |
+
# We also stop the search if the loss has not considerably during the last 10% epochs
|
491 |
+
if early_stop:
|
492 |
+
epochs_before_stop = int(epochs * percent_epochs_before_stop)
|
493 |
+
if i > epochs_before_stop and abs(acc_loss[i - epochs_before_stop] - acc_loss[i]) < min_delta:
|
494 |
+
break
|
495 |
+
|
496 |
+
# No longer requires gradients in the parameters
|
497 |
+
for p in best_params.values():
|
498 |
+
p.requires_grad = False
|
499 |
+
p.grad = None
|
500 |
+
|
501 |
+
if do_report:
|
502 |
+
return best_params, acc_loss
|
503 |
+
else:
|
504 |
+
return best_params
|
505 |
+
|
506 |
+
|
507 |
+
def quantize(
|
508 |
+
x: torch.Tensor,
|
509 |
+
params: Dict[str, nn.Parameter],
|
510 |
+
func: nn.Module,
|
511 |
+
bits: int,
|
512 |
+
target_dtype: torch.dtype = torch.int8
|
513 |
+
) -> torch.Tensor:
|
514 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
515 |
+
x = x.transpose(0, 1) # Aligns shapes
|
516 |
+
x = func(x=x, **params)
|
517 |
+
x = x.transpose(0, 1)
|
518 |
+
x = torch.clamp(round_func_BPDA(x), quant_min, quant_max).to(target_dtype)
|
519 |
+
return x
|
520 |
+
|
521 |
+
|
522 |
+
def dequantize(
|
523 |
+
x: torch.Tensor,
|
524 |
+
params: Dict[str, nn.Parameter],
|
525 |
+
func: nn.Module,
|
526 |
+
bits: int,
|
527 |
+
out_dtype: torch.dtype
|
528 |
+
) -> torch.Tensor:
|
529 |
+
x = x.to(dtype=out_dtype)
|
530 |
+
x = x.transpose(0, 1)
|
531 |
+
x = func(x=x, **params)
|
532 |
+
x = x.transpose(0, 1)
|
533 |
+
return x
|
534 |
+
|
535 |
+
|
536 |
+
def round_func_BPDA(input):
|
537 |
+
# This is equivalent to replacing round function (non-differentiable) with
|
538 |
+
# an identity function (differentiable) only when backward.
|
539 |
+
forward_value = torch.round(input)
|
540 |
+
out = input.clone()
|
541 |
+
out.data = forward_value.data
|
542 |
+
return out
|
543 |
+
|
544 |
+
|
545 |
+
def get_min_max_from_bits_signed(bit_width: int) -> Tuple[int, int]:
|
546 |
+
return -2 ** (bit_width - 1), 2 ** (bit_width - 1) - 1
|
547 |
+
|
548 |
+
|
549 |
+
|
550 |
+
############## Numpy ###############
|
551 |
+
|
552 |
+
def np_domain_guard(
|
553 |
+
x: np.ndarray,
|
554 |
+
min: float = None,
|
555 |
+
max: float = None,
|
556 |
+
posinf: float = None,
|
557 |
+
neginf: float = None,
|
558 |
+
nan: float = None
|
559 |
+
) -> np.ndarray:
|
560 |
+
"""Guard a tensor to a valid domain."""
|
561 |
+
x = np.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
562 |
+
if min is not None or max is not None:
|
563 |
+
x = np.clip(x, min, max)
|
564 |
+
return x
|
565 |
+
|
566 |
+
|
567 |
+
def np_replace_num(x: np.ndarray, num: float, to: float) -> np.ndarray:
|
568 |
+
"""Replace a number in a tensor with another number.
|
569 |
+
|
570 |
+
Args:
|
571 |
+
x (np.ndarray): The input tensor.
|
572 |
+
num (float): The number to replace.
|
573 |
+
to (float): The number to replace with.
|
574 |
+
|
575 |
+
Returns:
|
576 |
+
np.ndarray: The tensor with the number replaced.
|
577 |
+
"""
|
578 |
+
return np.where(x == num, to, x)
|
579 |
+
|
580 |
+
|
581 |
+
def np_guarded_power(x: np.ndarray, exp: float) -> np.ndarray:
|
582 |
+
"""Guard the power operation to a valid domain."""
|
583 |
+
return np.power(x, exp) if exp >= 1 else np.power(np.maximum(x, 0), exp)
|
584 |
+
|
fn_gen/rnd_search_fb/17/loss.png
ADDED
fn_gen/rnd_search_fb/17/quantization.png
ADDED
fn_gen/rnd_search_fb/18/distortion.png
ADDED
fn_gen/rnd_search_fb/18/expressions.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
acosh(_0*x)/_s
|
2 |
+
cosh(_s*x)/_0
|
fn_gen/rnd_search_fb/18/fn.py
ADDED
@@ -0,0 +1,584 @@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch import amin # Necessary for arcsin
|
5 |
+
import copy
|
6 |
+
import torch.nn as nn
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
from scipy.optimize import curve_fit
|
10 |
+
from typing import Dict, Any, Tuple, List, Callable
|
11 |
+
|
12 |
+
|
13 |
+
def quantization(x, **params):
|
14 |
+
return (torch.div(1, replace_num(params['_s'], num=0, to=10000)) * torch.acosh(domain_guard((params['_0'] * x), min=1, nan=1)))
|
15 |
+
|
16 |
+
|
17 |
+
def dequantization(x, **params):
|
18 |
+
return (torch.div(1, replace_num(params['_0'], num=0, to=10000)) * torch.cosh((params['_s'] * x)))
|
19 |
+
|
20 |
+
|
21 |
+
def init_space_search(
|
22 |
+
x: torch.Tensor,
|
23 |
+
**kwargs: Dict[str, Any],
|
24 |
+
) -> torch.Tensor:
|
25 |
+
|
26 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
27 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
28 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
29 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
30 |
+
|
31 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
32 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
33 |
+
torch_tensors = torch.stack(tensors)
|
34 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
35 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
36 |
+
mean = torch.mean(torch_tensors, dim=0)
|
37 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
38 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
39 |
+
|
40 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
41 |
+
x_ = x.transpose(0, 1)
|
42 |
+
x_ = qtz_func(x=x_, **params)
|
43 |
+
x_ = deqtz_func(x=x_, **params)
|
44 |
+
x_ = x_.transpose(0, 1)
|
45 |
+
return x_
|
46 |
+
|
47 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
48 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
49 |
+
assert "params_list" in kwargs, "params list must be provided."
|
50 |
+
assert "param" in kwargs, "param must be provided."
|
51 |
+
|
52 |
+
qtz_func = kwargs.get('qtz_func')
|
53 |
+
deqtz_func = kwargs.get('deqtz_func')
|
54 |
+
params_list = kwargs.get('params_list')
|
55 |
+
param = kwargs.get('param')
|
56 |
+
|
57 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
58 |
+
n_random_params = 50 # Number of random parameters to generate
|
59 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
60 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
61 |
+
|
62 |
+
# Initializes the parameters
|
63 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
64 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
65 |
+
|
66 |
+
# Performs the search
|
67 |
+
for _ in range(n_runs):
|
68 |
+
|
69 |
+
best_params = []
|
70 |
+
for param_ in params:
|
71 |
+
try:
|
72 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
73 |
+
loss_ones = nn.MSELoss()(x, x_)
|
74 |
+
|
75 |
+
if len(best_params) < n_best_to_pick:
|
76 |
+
best_params.append((param_, loss_ones.item()))
|
77 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
78 |
+
elif loss_ones < best_params[-1][1]:
|
79 |
+
best_params[-1] = (param_, loss_ones.item())
|
80 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
81 |
+
|
82 |
+
except Exception: # The parameters might not be valid for the function's domain
|
83 |
+
continue
|
84 |
+
|
85 |
+
# Generates new parameters around the mean
|
86 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
87 |
+
|
88 |
+
# Checks if the best parameter is better than the init_ones
|
89 |
+
p_ones = init_ones(x, **kwargs)
|
90 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
91 |
+
loss_ones = nn.MSELoss()(x, x_)
|
92 |
+
|
93 |
+
# Checks if the best parameter is better than the init_rand
|
94 |
+
p_rand = init_rand(x, **kwargs)
|
95 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
96 |
+
loss_rand = nn.MSELoss()(x, x_)
|
97 |
+
|
98 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
99 |
+
return p_rand
|
100 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
101 |
+
return p_ones
|
102 |
+
else:
|
103 |
+
return best_params[0][0]
|
104 |
+
|
105 |
+
|
106 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
107 |
+
x: torch.Tensor,
|
108 |
+
**kwargs: Dict[str, Any],
|
109 |
+
) -> torch.Tensor:
|
110 |
+
assert "bits" in kwargs, "bits must be provided."
|
111 |
+
assert "params" in kwargs, "params must be provided."
|
112 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
113 |
+
|
114 |
+
bits = kwargs.get('bits')
|
115 |
+
params = kwargs.get('params')
|
116 |
+
qtz_func = kwargs.get('qtz_func')
|
117 |
+
|
118 |
+
x_ = x.transpose(0, 1)
|
119 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
120 |
+
x_ = x_.transpose(0, 1)
|
121 |
+
|
122 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
123 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
124 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
125 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
126 |
+
|
127 |
+
eps = torch.finfo(torch.float32).eps
|
128 |
+
|
129 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
130 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
131 |
+
|
132 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
133 |
+
|
134 |
+
# Introduces some noise in scale
|
135 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
136 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
137 |
+
return scale
|
138 |
+
|
139 |
+
|
140 |
+
def init_params(x: torch.Tensor, **kwargs: Dict[str, Any]) -> Dict[str, nn.Parameter]:
|
141 |
+
params = {
|
142 |
+
'_0': init_space_search(x, qtz_func=quantization, deqtz_func=dequantization, param='_0', params_list=['_0', '_s'], **kwargs),
|
143 |
+
}
|
144 |
+
params['_s'] = init_linear_scale(x, params=params, qtz_func=quantization, **kwargs)
|
145 |
+
params = {k: nn.Parameter(v, requires_grad=False) for k, v in params.items()}
|
146 |
+
|
147 |
+
if 'post_init_hook' in kwargs:
|
148 |
+
kwargs['post_init_hook'](parameters=params)
|
149 |
+
|
150 |
+
|
151 |
+
if 'post_train_hook' in kwargs:
|
152 |
+
kwargs['post_train_hook'](parameters=params)
|
153 |
+
|
154 |
+
return params
|
155 |
+
|
156 |
+
|
157 |
+
############### Numpy Qtz ###############
|
158 |
+
|
159 |
+
|
160 |
+
def np_quantization(x, _0, _s):
|
161 |
+
return (np.divide(1, np_replace_num(_s, num=0, to=10000)) * np.arccosh(np_domain_guard((_0 * x), min=1, nan=1)))
|
162 |
+
|
163 |
+
|
164 |
+
def np_dequantization(x, _0, _s):
|
165 |
+
return (np.divide(1, np_replace_num(_0, num=0, to=10000)) * np.cosh((_s * x)))
|
166 |
+
|
167 |
+
|
168 |
+
def fit_func(x, _0, _s):
|
169 |
+
x_ = np_quantization(x, _0, _s)
|
170 |
+
x_ = np_dequantization(x_, _0, _s)
|
171 |
+
return x_
|
172 |
+
|
173 |
+
|
174 |
+
|
175 |
+
############### HELPERS ###############
|
176 |
+
|
177 |
+
def domain_guard(
|
178 |
+
x: torch.Tensor,
|
179 |
+
min: float = None,
|
180 |
+
max: float = None,
|
181 |
+
posinf: float = None,
|
182 |
+
neginf: float = None,
|
183 |
+
nan: float = None
|
184 |
+
) -> torch.Tensor:
|
185 |
+
"""Guard a tensor to a valid domain."""
|
186 |
+
x = torch.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
187 |
+
if min is not None or max is not None:
|
188 |
+
x = torch.clamp(x, min=min, max=max)
|
189 |
+
return x
|
190 |
+
|
191 |
+
|
192 |
+
def replace_num(x: torch.Tensor, num: float, to: float) -> torch.Tensor:
|
193 |
+
"""Replace a number in a tensor with another number.
|
194 |
+
|
195 |
+
Args:
|
196 |
+
x (torch.Tensor): The input tensor.
|
197 |
+
num (float): The number to replace.
|
198 |
+
to (float): The number to replace with.
|
199 |
+
|
200 |
+
Returns:
|
201 |
+
torch.Tensor: The tensor with the number replaced.
|
202 |
+
"""
|
203 |
+
return torch.where(x == num, to, x)
|
204 |
+
|
205 |
+
|
206 |
+
def guarded_torch_power(x: torch.Tensor, exp: float) -> torch.Tensor:
|
207 |
+
"""Guard the power operation to a valid domain."""
|
208 |
+
return torch.pow(x, exp) if exp >= 1 else torch.pow(torch.relu(x), exp)
|
209 |
+
|
210 |
+
|
211 |
+
def init_ones(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
212 |
+
val = torch.amin(x, dim=1)
|
213 |
+
return torch.ones_like(val, dtype=torch.float32, device=x.device)
|
214 |
+
|
215 |
+
|
216 |
+
def init_rand(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
217 |
+
val = torch.amin(x, dim=1)
|
218 |
+
return torch.randn_like(val, dtype=torch.float32, device=x.device)
|
219 |
+
|
220 |
+
|
221 |
+
def init_space_search(
|
222 |
+
x: torch.Tensor,
|
223 |
+
**kwargs: Dict[str, Any],
|
224 |
+
) -> torch.Tensor:
|
225 |
+
|
226 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
227 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
228 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
229 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
230 |
+
|
231 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
232 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
233 |
+
torch_tensors = torch.stack(tensors)
|
234 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
235 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
236 |
+
mean = torch.mean(torch_tensors, dim=0)
|
237 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
238 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
239 |
+
|
240 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
241 |
+
x_ = x.transpose(0, 1)
|
242 |
+
x_ = qtz_func(x=x_, **params)
|
243 |
+
x_ = deqtz_func(x=x_, **params)
|
244 |
+
x_ = x_.transpose(0, 1)
|
245 |
+
return x_
|
246 |
+
|
247 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
248 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
249 |
+
assert "params_list" in kwargs, "params list must be provided."
|
250 |
+
assert "param" in kwargs, "param must be provided."
|
251 |
+
|
252 |
+
qtz_func = kwargs.get('qtz_func')
|
253 |
+
deqtz_func = kwargs.get('deqtz_func')
|
254 |
+
params_list = kwargs.get('params_list')
|
255 |
+
param = kwargs.get('param')
|
256 |
+
|
257 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
258 |
+
n_random_params = 50 # Number of random parameters to generate
|
259 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
260 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
261 |
+
|
262 |
+
# Initializes the parameters
|
263 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
264 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
265 |
+
|
266 |
+
# Performs the search
|
267 |
+
for _ in range(n_runs):
|
268 |
+
|
269 |
+
best_params = []
|
270 |
+
for param_ in params:
|
271 |
+
try:
|
272 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
273 |
+
loss_ones = nn.MSELoss()(x, x_)
|
274 |
+
|
275 |
+
if len(best_params) < n_best_to_pick:
|
276 |
+
best_params.append((param_, loss_ones.item()))
|
277 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
278 |
+
elif loss_ones < best_params[-1][1]:
|
279 |
+
best_params[-1] = (param_, loss_ones.item())
|
280 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
281 |
+
|
282 |
+
except Exception: # The parameters might not be valid for the function's domain
|
283 |
+
continue
|
284 |
+
|
285 |
+
# Generates new parameters around the mean
|
286 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
287 |
+
|
288 |
+
# Checks if the best parameter is better than the init_ones
|
289 |
+
p_ones = init_ones(x, **kwargs)
|
290 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
291 |
+
loss_ones = nn.MSELoss()(x, x_)
|
292 |
+
|
293 |
+
# Checks if the best parameter is better than the init_rand
|
294 |
+
p_rand = init_rand(x, **kwargs)
|
295 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
296 |
+
loss_rand = nn.MSELoss()(x, x_)
|
297 |
+
|
298 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
299 |
+
return p_rand
|
300 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
301 |
+
return p_ones
|
302 |
+
else:
|
303 |
+
return best_params[0][0]
|
304 |
+
|
305 |
+
|
306 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
307 |
+
x: torch.Tensor,
|
308 |
+
**kwargs: Dict[str, Any],
|
309 |
+
) -> torch.Tensor:
|
310 |
+
assert "bits" in kwargs, "bits must be provided."
|
311 |
+
assert "params" in kwargs, "params must be provided."
|
312 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
313 |
+
|
314 |
+
bits = kwargs.get('bits')
|
315 |
+
params = kwargs.get('params')
|
316 |
+
qtz_func = kwargs.get('qtz_func')
|
317 |
+
|
318 |
+
x_ = x.transpose(0, 1)
|
319 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
320 |
+
x_ = x_.transpose(0, 1)
|
321 |
+
|
322 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
323 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
324 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
325 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
326 |
+
|
327 |
+
eps = torch.finfo(torch.float32).eps
|
328 |
+
|
329 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
330 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
331 |
+
|
332 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
333 |
+
|
334 |
+
# Introduces some noise in scale
|
335 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
336 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
337 |
+
return scale
|
338 |
+
|
339 |
+
|
340 |
+
def init_non_linear_regression_fit(
|
341 |
+
x: torch.Tensor,
|
342 |
+
**kwargs: Dict[str, Any],
|
343 |
+
) -> torch.Tensor:
|
344 |
+
|
345 |
+
assert "params_list" in kwargs, "params list must be provided."
|
346 |
+
assert "np_fit_func" in kwargs, "np_fit_func must be provided."
|
347 |
+
assert "p0" in kwargs, "p0 must be provided."
|
348 |
+
np_fit_func = kwargs.get('np_fit_func')
|
349 |
+
params_list = kwargs.get('params_list')
|
350 |
+
p0 = kwargs.get('p0')
|
351 |
+
|
352 |
+
def _fit(xdata: np.ndarray, ydata: np.ndarray, func: Callable, p0: List[float]):
|
353 |
+
popt, _ = curve_fit(
|
354 |
+
func,
|
355 |
+
xdata,
|
356 |
+
ydata,
|
357 |
+
maxfev=1000,
|
358 |
+
p0=p0,
|
359 |
+
method='lm'
|
360 |
+
)
|
361 |
+
return popt
|
362 |
+
|
363 |
+
# 1. Needs to convert the torch tensor to numpy tensor
|
364 |
+
xdata = x.cpu().numpy()
|
365 |
+
|
366 |
+
# 2. Sorts the data so that it makes it easier to fit to it
|
367 |
+
sorted_xdata = np.sort(xdata, axis=-1)
|
368 |
+
|
369 |
+
p0 = {k: v.cpu().numpy() for k, v in p0.items()}
|
370 |
+
params_list = sorted(params_list) # We need to make sure that it matches the numpy fit func arg order
|
371 |
+
|
372 |
+
# 3. Finds the best parameters for each channel
|
373 |
+
try:
|
374 |
+
params = []
|
375 |
+
for i in range(sorted_xdata.shape[0]):
|
376 |
+
xdata_ = sorted_xdata[i]
|
377 |
+
p0_ = [p0[p][i] for p in params_list]
|
378 |
+
ch_params = _fit(xdata_, xdata_, np_fit_func, p0_)
|
379 |
+
params.append(ch_params)
|
380 |
+
|
381 |
+
# 4. Builds the parameters
|
382 |
+
result = {}
|
383 |
+
for i, p in enumerate(params_list):
|
384 |
+
result[p] = torch.tensor([p_[i] for p_ in params], dtype=torch.float32).to(x.device)
|
385 |
+
|
386 |
+
return result
|
387 |
+
|
388 |
+
except ValueError as e:
|
389 |
+
print(f"Could not fit the function with error: {e}")
|
390 |
+
print(f"Using fallback result...")
|
391 |
+
return {
|
392 |
+
k: torch.tensor(v, dtype=torch.float32).to(x.device) for k, v in p0.items()
|
393 |
+
}
|
394 |
+
|
395 |
+
|
396 |
+
def init_zeros(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
397 |
+
val = torch.amin(x, dim=1)
|
398 |
+
return torch.zeros_like(val, dtype=torch.float32, device=x.device)
|
399 |
+
|
400 |
+
|
401 |
+
def init_inner_scale(tensor: torch.Tensor, _min: float = torch.inf, _max: float = torch.inf) -> torch.Tensor:
|
402 |
+
# Calculate the original minimum and maximum values
|
403 |
+
min_vals, max_vals = torch.aminmax(tensor, dim=-1)
|
404 |
+
x_min = torch.min(min_vals, torch.zeros_like(min_vals))
|
405 |
+
x_max = torch.max(max_vals, torch.zeros_like(max_vals))
|
406 |
+
|
407 |
+
if _max is torch.inf: # We do not need to scale the tensor. Just need to move it
|
408 |
+
return torch.ones_like(x_min)
|
409 |
+
|
410 |
+
# Calculate the scale factor
|
411 |
+
scale = (_max - _min) / (x_max - x_min)
|
412 |
+
return scale
|
413 |
+
|
414 |
+
|
415 |
+
|
416 |
+
############## Quant ###############
|
417 |
+
|
418 |
+
@torch.enable_grad()
|
419 |
+
def learn_parameters(
|
420 |
+
x: torch.Tensor,
|
421 |
+
params: Dict[str, nn.Parameter],
|
422 |
+
qtz_func: nn.Module,
|
423 |
+
deqtz_func: nn.Module,
|
424 |
+
bits: int,
|
425 |
+
target_dtype: torch.dtype,
|
426 |
+
epochs: int = 1000,
|
427 |
+
early_stop: bool = True,
|
428 |
+
do_report: bool = False
|
429 |
+
) -> Tuple[Dict[str, nn.Parameter], torch.Tensor]:
|
430 |
+
loss_fn = nn.MSELoss()
|
431 |
+
|
432 |
+
# Determines the initial learning rate by computing the initial loss and multiplying it by
|
433 |
+
# the order of magnitude of the loss divided by 2
|
434 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
435 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
436 |
+
loss = loss_fn(x, dequant)
|
437 |
+
|
438 |
+
base_lr = 0.1
|
439 |
+
exponent = int(np.floor(np.log10(loss.item())))
|
440 |
+
lr = base_lr * (10 ** (exponent // 2))
|
441 |
+
|
442 |
+
# Requires gradients in the parameters
|
443 |
+
for p in params.values():
|
444 |
+
p.requires_grad = True
|
445 |
+
p.grad = None
|
446 |
+
|
447 |
+
param_keys = list(params.keys())
|
448 |
+
param_values = list(params.values())
|
449 |
+
|
450 |
+
# Defines optimizer and loss function
|
451 |
+
optimizer = torch.optim.Adam(param_values, lr=lr)
|
452 |
+
scheduler = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=1.0, end_factor=0.01, total_iters=epochs // 10)
|
453 |
+
|
454 |
+
# Contains the best loss and the best parameters
|
455 |
+
best_loss = float("inf")
|
456 |
+
best_params = None
|
457 |
+
|
458 |
+
# Used to stop the search early
|
459 |
+
min_delta = 1e-7
|
460 |
+
acc_loss = []
|
461 |
+
percent_epochs_before_stop = 0.1
|
462 |
+
|
463 |
+
for i in range(epochs):
|
464 |
+
optimizer.zero_grad()
|
465 |
+
|
466 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
467 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
468 |
+
loss = loss_fn(x, dequant)
|
469 |
+
|
470 |
+
if loss.isnan() or loss.isinf():
|
471 |
+
raise Exception("Loss is NaN or Inf. Stopping the search.")
|
472 |
+
|
473 |
+
loss.backward()
|
474 |
+
optimizer.step()
|
475 |
+
scheduler.step()
|
476 |
+
|
477 |
+
acc_loss.append(loss.item())
|
478 |
+
|
479 |
+
# Reports loss every 10 steps
|
480 |
+
if i % 10 == 0 and do_report:
|
481 |
+
print(f"Epoch {i}: Loss {loss.item()}")
|
482 |
+
|
483 |
+
# Optimizes the parameter search by storing the best loss and the parameters
|
484 |
+
if loss.item() < best_loss:
|
485 |
+
best_loss = loss.item()
|
486 |
+
best_params = copy.deepcopy({
|
487 |
+
k: v for k, v in params.items() if k in param_keys
|
488 |
+
})
|
489 |
+
|
490 |
+
# We also stop the search if the loss has not considerably during the last 10% epochs
|
491 |
+
if early_stop:
|
492 |
+
epochs_before_stop = int(epochs * percent_epochs_before_stop)
|
493 |
+
if i > epochs_before_stop and abs(acc_loss[i - epochs_before_stop] - acc_loss[i]) < min_delta:
|
494 |
+
break
|
495 |
+
|
496 |
+
# No longer requires gradients in the parameters
|
497 |
+
for p in best_params.values():
|
498 |
+
p.requires_grad = False
|
499 |
+
p.grad = None
|
500 |
+
|
501 |
+
if do_report:
|
502 |
+
return best_params, acc_loss
|
503 |
+
else:
|
504 |
+
return best_params
|
505 |
+
|
506 |
+
|
507 |
+
def quantize(
|
508 |
+
x: torch.Tensor,
|
509 |
+
params: Dict[str, nn.Parameter],
|
510 |
+
func: nn.Module,
|
511 |
+
bits: int,
|
512 |
+
target_dtype: torch.dtype = torch.int8
|
513 |
+
) -> torch.Tensor:
|
514 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
515 |
+
x = x.transpose(0, 1) # Aligns shapes
|
516 |
+
x = func(x=x, **params)
|
517 |
+
x = x.transpose(0, 1)
|
518 |
+
x = torch.clamp(round_func_BPDA(x), quant_min, quant_max).to(target_dtype)
|
519 |
+
return x
|
520 |
+
|
521 |
+
|
522 |
+
def dequantize(
|
523 |
+
x: torch.Tensor,
|
524 |
+
params: Dict[str, nn.Parameter],
|
525 |
+
func: nn.Module,
|
526 |
+
bits: int,
|
527 |
+
out_dtype: torch.dtype
|
528 |
+
) -> torch.Tensor:
|
529 |
+
x = x.to(dtype=out_dtype)
|
530 |
+
x = x.transpose(0, 1)
|
531 |
+
x = func(x=x, **params)
|
532 |
+
x = x.transpose(0, 1)
|
533 |
+
return x
|
534 |
+
|
535 |
+
|
536 |
+
def round_func_BPDA(input):
|
537 |
+
# This is equivalent to replacing round function (non-differentiable) with
|
538 |
+
# an identity function (differentiable) only when backward.
|
539 |
+
forward_value = torch.round(input)
|
540 |
+
out = input.clone()
|
541 |
+
out.data = forward_value.data
|
542 |
+
return out
|
543 |
+
|
544 |
+
|
545 |
+
def get_min_max_from_bits_signed(bit_width: int) -> Tuple[int, int]:
|
546 |
+
return -2 ** (bit_width - 1), 2 ** (bit_width - 1) - 1
|
547 |
+
|
548 |
+
|
549 |
+
|
550 |
+
############## Numpy ###############
|
551 |
+
|
552 |
+
def np_domain_guard(
|
553 |
+
x: np.ndarray,
|
554 |
+
min: float = None,
|
555 |
+
max: float = None,
|
556 |
+
posinf: float = None,
|
557 |
+
neginf: float = None,
|
558 |
+
nan: float = None
|
559 |
+
) -> np.ndarray:
|
560 |
+
"""Guard a tensor to a valid domain."""
|
561 |
+
x = np.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
562 |
+
if min is not None or max is not None:
|
563 |
+
x = np.clip(x, min, max)
|
564 |
+
return x
|
565 |
+
|
566 |
+
|
567 |
+
def np_replace_num(x: np.ndarray, num: float, to: float) -> np.ndarray:
|
568 |
+
"""Replace a number in a tensor with another number.
|
569 |
+
|
570 |
+
Args:
|
571 |
+
x (np.ndarray): The input tensor.
|
572 |
+
num (float): The number to replace.
|
573 |
+
to (float): The number to replace with.
|
574 |
+
|
575 |
+
Returns:
|
576 |
+
np.ndarray: The tensor with the number replaced.
|
577 |
+
"""
|
578 |
+
return np.where(x == num, to, x)
|
579 |
+
|
580 |
+
|
581 |
+
def np_guarded_power(x: np.ndarray, exp: float) -> np.ndarray:
|
582 |
+
"""Guard the power operation to a valid domain."""
|
583 |
+
return np.power(x, exp) if exp >= 1 else np.power(np.maximum(x, 0), exp)
|
584 |
+
|
fn_gen/rnd_search_fb/18/loss.png
ADDED
fn_gen/rnd_search_fb/18/quantization.png
ADDED
fn_gen/rnd_search_fb/2/distortion.png
ADDED
fn_gen/rnd_search_fb/2/expressions.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
x**3/_s
|
2 |
+
(_s*x)**(1/3)
|
fn_gen/rnd_search_f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|
+
|
3 |
+
import torch
|
4 |
+
from torch import amin # Necessary for arcsin
|
5 |
+
import copy
|
6 |
+
import torch.nn as nn
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
from scipy.optimize import curve_fit
|
10 |
+
from typing import Dict, Any, Tuple, List, Callable
|
11 |
+
|
12 |
+
|
13 |
+
def quantization(x, **params):
|
14 |
+
return (torch.div(1, replace_num(params['_s'], num=0, to=10000)) * guarded_torch_power(x, torch.tensor(3)))
|
15 |
+
|
16 |
+
|
17 |
+
def dequantization(x, **params):
|
18 |
+
return guarded_torch_power((params['_s'] * x), 1 / 3)
|
19 |
+
|
20 |
+
|
21 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
22 |
+
x: torch.Tensor,
|
23 |
+
**kwargs: Dict[str, Any],
|
24 |
+
) -> torch.Tensor:
|
25 |
+
assert "bits" in kwargs, "bits must be provided."
|
26 |
+
assert "params" in kwargs, "params must be provided."
|
27 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
28 |
+
|
29 |
+
bits = kwargs.get('bits')
|
30 |
+
params = kwargs.get('params')
|
31 |
+
qtz_func = kwargs.get('qtz_func')
|
32 |
+
|
33 |
+
x_ = x.transpose(0, 1)
|
34 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
35 |
+
x_ = x_.transpose(0, 1)
|
36 |
+
|
37 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
38 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
39 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
40 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
41 |
+
|
42 |
+
eps = torch.finfo(torch.float32).eps
|
43 |
+
|
44 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
45 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
46 |
+
|
47 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
48 |
+
|
49 |
+
# Introduces some noise in scale
|
50 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
51 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
52 |
+
return scale
|
53 |
+
|
54 |
+
|
55 |
+
def init_params(x: torch.Tensor, **kwargs: Dict[str, Any]) -> Dict[str, nn.Parameter]:
|
56 |
+
params = {
|
57 |
+
}
|
58 |
+
params['_s'] = init_linear_scale(x, params=params, qtz_func=quantization, **kwargs)
|
59 |
+
params = {k: nn.Parameter(v, requires_grad=False) for k, v in params.items()}
|
60 |
+
|
61 |
+
if 'post_init_hook' in kwargs:
|
62 |
+
kwargs['post_init_hook'](parameters=params)
|
63 |
+
|
64 |
+
|
65 |
+
if 'post_train_hook' in kwargs:
|
66 |
+
kwargs['post_train_hook'](parameters=params)
|
67 |
+
|
68 |
+
return params
|
69 |
+
|
70 |
+
|
71 |
+
############### Numpy Qtz ###############
|
72 |
+
|
73 |
+
|
74 |
+
def np_quantization(x, _s):
|
75 |
+
return (np.divide(1, np_replace_num(_s, num=0, to=10000)) * np_guarded_power(x, np.array(3)))
|
76 |
+
|
77 |
+
|
78 |
+
def np_dequantization(x, _s):
|
79 |
+
return np_guarded_power((_s * x), 1 / 3)
|
80 |
+
|
81 |
+
|
82 |
+
def fit_func(x, _s):
|
83 |
+
x_ = np_quantization(x, _s)
|
84 |
+
x_ = np_dequantization(x_, _s)
|
85 |
+
return x_
|
86 |
+
|
87 |
+
|
88 |
+
|
89 |
+
############### HELPERS ###############
|
90 |
+
|
91 |
+
def domain_guard(
|
92 |
+
x: torch.Tensor,
|
93 |
+
min: float = None,
|
94 |
+
max: float = None,
|
95 |
+
posinf: float = None,
|
96 |
+
neginf: float = None,
|
97 |
+
nan: float = None
|
98 |
+
) -> torch.Tensor:
|
99 |
+
"""Guard a tensor to a valid domain."""
|
100 |
+
x = torch.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
101 |
+
if min is not None or max is not None:
|
102 |
+
x = torch.clamp(x, min=min, max=max)
|
103 |
+
return x
|
104 |
+
|
105 |
+
|
106 |
+
def replace_num(x: torch.Tensor, num: float, to: float) -> torch.Tensor:
|
107 |
+
"""Replace a number in a tensor with another number.
|
108 |
+
|
109 |
+
Args:
|
110 |
+
x (torch.Tensor): The input tensor.
|
111 |
+
num (float): The number to replace.
|
112 |
+
to (float): The number to replace with.
|
113 |
+
|
114 |
+
Returns:
|
115 |
+
torch.Tensor: The tensor with the number replaced.
|
116 |
+
"""
|
117 |
+
return torch.where(x == num, to, x)
|
118 |
+
|
119 |
+
|
120 |
+
def guarded_torch_power(x: torch.Tensor, exp: float) -> torch.Tensor:
|
121 |
+
"""Guard the power operation to a valid domain."""
|
122 |
+
return torch.pow(x, exp) if exp >= 1 else torch.pow(torch.relu(x), exp)
|
123 |
+
|
124 |
+
|
125 |
+
def init_ones(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
126 |
+
val = torch.amin(x, dim=1)
|
127 |
+
return torch.ones_like(val, dtype=torch.float32, device=x.device)
|
128 |
+
|
129 |
+
|
130 |
+
def init_rand(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
131 |
+
val = torch.amin(x, dim=1)
|
132 |
+
return torch.randn_like(val, dtype=torch.float32, device=x.device)
|
133 |
+
|
134 |
+
|
135 |
+
def init_space_search(
|
136 |
+
x: torch.Tensor,
|
137 |
+
**kwargs: Dict[str, Any],
|
138 |
+
) -> torch.Tensor:
|
139 |
+
|
140 |
+
def _build_initial_param(tensor: torch.Tensor, max_initial: int, n_params: int):
|
141 |
+
"""Generates the initial set of parameters. The first iteration generates 10 times more parameters."""
|
142 |
+
for _ in range(n_params * 10): # The first iteration generates 10 times more parameters
|
143 |
+
yield init_rand(tensor) * max_initial # Generates n_params in range [-max_initial, max_initial]
|
144 |
+
|
145 |
+
def _search_param(tensors: List[torch.tensor], n_params):
|
146 |
+
"""Takes the best parameters and generates new parameters around the mean of the best parameters."""
|
147 |
+
torch_tensors = torch.stack(tensors)
|
148 |
+
min_vals, max_vals = torch.aminmax(torch_tensors, dim=0)
|
149 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
150 |
+
mean = torch.mean(torch_tensors, dim=0)
|
151 |
+
for _ in range(n_params): # Generates n_params around the mean of the tensors
|
152 |
+
yield torch.randn_like(min_vals) * abs_max_val_per_ch + mean
|
153 |
+
|
154 |
+
def _calc(x, qtz_func, deqtz_func, **params):
|
155 |
+
x_ = x.transpose(0, 1)
|
156 |
+
x_ = qtz_func(x=x_, **params)
|
157 |
+
x_ = deqtz_func(x=x_, **params)
|
158 |
+
x_ = x_.transpose(0, 1)
|
159 |
+
return x_
|
160 |
+
|
161 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
162 |
+
assert "deqtz_func" in kwargs, "deqtz_func must be provided."
|
163 |
+
assert "params_list" in kwargs, "params list must be provided."
|
164 |
+
assert "param" in kwargs, "param must be provided."
|
165 |
+
|
166 |
+
qtz_func = kwargs.get('qtz_func')
|
167 |
+
deqtz_func = kwargs.get('deqtz_func')
|
168 |
+
params_list = kwargs.get('params_list')
|
169 |
+
param = kwargs.get('param')
|
170 |
+
|
171 |
+
n_runs = 50 # Number of runs to try to find the best parameters
|
172 |
+
n_random_params = 50 # Number of random parameters to generate
|
173 |
+
n_best_to_pick = 5 # Number of best parameters to pick after each run
|
174 |
+
max_initial = 10000 # Maximum value to initialize the parameters
|
175 |
+
|
176 |
+
# Initializes the parameters
|
177 |
+
base_params = { p: init_ones(x, **kwargs) for p in params_list if p != param }
|
178 |
+
params = _build_initial_param(x, max_initial, n_random_params)
|
179 |
+
|
180 |
+
# Performs the search
|
181 |
+
for _ in range(n_runs):
|
182 |
+
|
183 |
+
best_params = []
|
184 |
+
for param_ in params:
|
185 |
+
try:
|
186 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: param_})
|
187 |
+
loss_ones = nn.MSELoss()(x, x_)
|
188 |
+
|
189 |
+
if len(best_params) < n_best_to_pick:
|
190 |
+
best_params.append((param_, loss_ones.item()))
|
191 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
192 |
+
elif loss_ones < best_params[-1][1]:
|
193 |
+
best_params[-1] = (param_, loss_ones.item())
|
194 |
+
best_params = sorted(best_params, key=lambda x: x[1])
|
195 |
+
|
196 |
+
except Exception: # The parameters might not be valid for the function's domain
|
197 |
+
continue
|
198 |
+
|
199 |
+
# Generates new parameters around the mean
|
200 |
+
params = _search_param([p for p, _ in best_params], n_random_params)
|
201 |
+
|
202 |
+
# Checks if the best parameter is better than the init_ones
|
203 |
+
p_ones = init_ones(x, **kwargs)
|
204 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_ones})
|
205 |
+
loss_ones = nn.MSELoss()(x, x_)
|
206 |
+
|
207 |
+
# Checks if the best parameter is better than the init_rand
|
208 |
+
p_rand = init_rand(x, **kwargs)
|
209 |
+
x_ = _calc(x, qtz_func, deqtz_func, **base_params, **{param: p_rand})
|
210 |
+
loss_rand = nn.MSELoss()(x, x_)
|
211 |
+
|
212 |
+
if loss_rand < best_params[0][1] and loss_rand < loss_ones:
|
213 |
+
return p_rand
|
214 |
+
elif loss_ones < best_params[0][1] and loss_ones < loss_rand:
|
215 |
+
return p_ones
|
216 |
+
else:
|
217 |
+
return best_params[0][0]
|
218 |
+
|
219 |
+
|
220 |
+
def init_linear_scale( # Symmetric scale. From the study folder
|
221 |
+
x: torch.Tensor,
|
222 |
+
**kwargs: Dict[str, Any],
|
223 |
+
) -> torch.Tensor:
|
224 |
+
assert "bits" in kwargs, "bits must be provided."
|
225 |
+
assert "params" in kwargs, "params must be provided."
|
226 |
+
assert "qtz_func" in kwargs, "qtz_func must be provided."
|
227 |
+
|
228 |
+
bits = kwargs.get('bits')
|
229 |
+
params = kwargs.get('params')
|
230 |
+
qtz_func = kwargs.get('qtz_func')
|
231 |
+
|
232 |
+
x_ = x.transpose(0, 1)
|
233 |
+
x_ = qtz_func(x=x_, **params, _s=init_ones(x, **kwargs))
|
234 |
+
x_ = x_.transpose(0, 1)
|
235 |
+
|
236 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
237 |
+
min_vals, max_vals = torch.aminmax(x_, dim=1)
|
238 |
+
min_vals = torch.min(min_vals, torch.zeros_like(min_vals))
|
239 |
+
max_vals = torch.max(max_vals, torch.zeros_like(max_vals))
|
240 |
+
|
241 |
+
eps = torch.finfo(torch.float32).eps
|
242 |
+
|
243 |
+
abs_max_val_per_ch = torch.max(-min_vals, max_vals)
|
244 |
+
scale = abs_max_val_per_ch / (float(quant_max - quant_min) / 2)
|
245 |
+
|
246 |
+
scale = torch.clamp(scale, min=eps).to(dtype=torch.float32, device=min_vals.device)
|
247 |
+
|
248 |
+
# Introduces some noise in scale
|
249 |
+
# If I don't introduce noise, the accuracy is going to be 0.0 and not learn anything
|
250 |
+
# scale = scale + 0.01 * torch.randn_like(scale)
|
251 |
+
return scale
|
252 |
+
|
253 |
+
|
254 |
+
def init_non_linear_regression_fit(
|
255 |
+
x: torch.Tensor,
|
256 |
+
**kwargs: Dict[str, Any],
|
257 |
+
) -> torch.Tensor:
|
258 |
+
|
259 |
+
assert "params_list" in kwargs, "params list must be provided."
|
260 |
+
assert "np_fit_func" in kwargs, "np_fit_func must be provided."
|
261 |
+
assert "p0" in kwargs, "p0 must be provided."
|
262 |
+
np_fit_func = kwargs.get('np_fit_func')
|
263 |
+
params_list = kwargs.get('params_list')
|
264 |
+
p0 = kwargs.get('p0')
|
265 |
+
|
266 |
+
def _fit(xdata: np.ndarray, ydata: np.ndarray, func: Callable, p0: List[float]):
|
267 |
+
popt, _ = curve_fit(
|
268 |
+
func,
|
269 |
+
xdata,
|
270 |
+
ydata,
|
271 |
+
maxfev=1000,
|
272 |
+
p0=p0,
|
273 |
+
method='lm'
|
274 |
+
)
|
275 |
+
return popt
|
276 |
+
|
277 |
+
# 1. Needs to convert the torch tensor to numpy tensor
|
278 |
+
xdata = x.cpu().numpy()
|
279 |
+
|
280 |
+
# 2. Sorts the data so that it makes it easier to fit to it
|
281 |
+
sorted_xdata = np.sort(xdata, axis=-1)
|
282 |
+
|
283 |
+
p0 = {k: v.cpu().numpy() for k, v in p0.items()}
|
284 |
+
params_list = sorted(params_list) # We need to make sure that it matches the numpy fit func arg order
|
285 |
+
|
286 |
+
# 3. Finds the best parameters for each channel
|
287 |
+
try:
|
288 |
+
params = []
|
289 |
+
for i in range(sorted_xdata.shape[0]):
|
290 |
+
xdata_ = sorted_xdata[i]
|
291 |
+
p0_ = [p0[p][i] for p in params_list]
|
292 |
+
ch_params = _fit(xdata_, xdata_, np_fit_func, p0_)
|
293 |
+
params.append(ch_params)
|
294 |
+
|
295 |
+
# 4. Builds the parameters
|
296 |
+
result = {}
|
297 |
+
for i, p in enumerate(params_list):
|
298 |
+
result[p] = torch.tensor([p_[i] for p_ in params], dtype=torch.float32).to(x.device)
|
299 |
+
|
300 |
+
return result
|
301 |
+
|
302 |
+
except ValueError as e:
|
303 |
+
print(f"Could not fit the function with error: {e}")
|
304 |
+
print(f"Using fallback result...")
|
305 |
+
return {
|
306 |
+
k: torch.tensor(v, dtype=torch.float32).to(x.device) for k, v in p0.items()
|
307 |
+
}
|
308 |
+
|
309 |
+
|
310 |
+
def init_zeros(x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:
|
311 |
+
val = torch.amin(x, dim=1)
|
312 |
+
return torch.zeros_like(val, dtype=torch.float32, device=x.device)
|
313 |
+
|
314 |
+
|
315 |
+
def init_inner_scale(tensor: torch.Tensor, _min: float = torch.inf, _max: float = torch.inf) -> torch.Tensor:
|
316 |
+
# Calculate the original minimum and maximum values
|
317 |
+
min_vals, max_vals = torch.aminmax(tensor, dim=-1)
|
318 |
+
x_min = torch.min(min_vals, torch.zeros_like(min_vals))
|
319 |
+
x_max = torch.max(max_vals, torch.zeros_like(max_vals))
|
320 |
+
|
321 |
+
if _max is torch.inf: # We do not need to scale the tensor. Just need to move it
|
322 |
+
return torch.ones_like(x_min)
|
323 |
+
|
324 |
+
# Calculate the scale factor
|
325 |
+
scale = (_max - _min) / (x_max - x_min)
|
326 |
+
return scale
|
327 |
+
|
328 |
+
|
329 |
+
|
330 |
+
############## Quant ###############
|
331 |
+
|
332 |
+
@torch.enable_grad()
|
333 |
+
def learn_parameters(
|
334 |
+
x: torch.Tensor,
|
335 |
+
params: Dict[str, nn.Parameter],
|
336 |
+
qtz_func: nn.Module,
|
337 |
+
deqtz_func: nn.Module,
|
338 |
+
bits: int,
|
339 |
+
target_dtype: torch.dtype,
|
340 |
+
epochs: int = 1000,
|
341 |
+
early_stop: bool = True,
|
342 |
+
do_report: bool = False
|
343 |
+
) -> Tuple[Dict[str, nn.Parameter], torch.Tensor]:
|
344 |
+
loss_fn = nn.MSELoss()
|
345 |
+
|
346 |
+
# Determines the initial learning rate by computing the initial loss and multiplying it by
|
347 |
+
# the order of magnitude of the loss divided by 2
|
348 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
349 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
350 |
+
loss = loss_fn(x, dequant)
|
351 |
+
|
352 |
+
base_lr = 0.1
|
353 |
+
exponent = int(np.floor(np.log10(loss.item())))
|
354 |
+
lr = base_lr * (10 ** (exponent // 2))
|
355 |
+
|
356 |
+
# Requires gradients in the parameters
|
357 |
+
for p in params.values():
|
358 |
+
p.requires_grad = True
|
359 |
+
p.grad = None
|
360 |
+
|
361 |
+
param_keys = list(params.keys())
|
362 |
+
param_values = list(params.values())
|
363 |
+
|
364 |
+
# Defines optimizer and loss function
|
365 |
+
optimizer = torch.optim.Adam(param_values, lr=lr)
|
366 |
+
scheduler = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=1.0, end_factor=0.01, total_iters=epochs // 10)
|
367 |
+
|
368 |
+
# Contains the best loss and the best parameters
|
369 |
+
best_loss = float("inf")
|
370 |
+
best_params = None
|
371 |
+
|
372 |
+
# Used to stop the search early
|
373 |
+
min_delta = 1e-7
|
374 |
+
acc_loss = []
|
375 |
+
percent_epochs_before_stop = 0.1
|
376 |
+
|
377 |
+
for i in range(epochs):
|
378 |
+
optimizer.zero_grad()
|
379 |
+
|
380 |
+
quant = quantize(x, params, qtz_func, bits, target_dtype)
|
381 |
+
dequant = dequantize(quant, params, deqtz_func, bits, x.dtype)
|
382 |
+
loss = loss_fn(x, dequant)
|
383 |
+
|
384 |
+
if loss.isnan() or loss.isinf():
|
385 |
+
raise Exception("Loss is NaN or Inf. Stopping the search.")
|
386 |
+
|
387 |
+
loss.backward()
|
388 |
+
optimizer.step()
|
389 |
+
scheduler.step()
|
390 |
+
|
391 |
+
acc_loss.append(loss.item())
|
392 |
+
|
393 |
+
# Reports loss every 10 steps
|
394 |
+
if i % 10 == 0 and do_report:
|
395 |
+
print(f"Epoch {i}: Loss {loss.item()}")
|
396 |
+
|
397 |
+
# Optimizes the parameter search by storing the best loss and the parameters
|
398 |
+
if loss.item() < best_loss:
|
399 |
+
best_loss = loss.item()
|
400 |
+
best_params = copy.deepcopy({
|
401 |
+
k: v for k, v in params.items() if k in param_keys
|
402 |
+
})
|
403 |
+
|
404 |
+
# We also stop the search if the loss has not considerably during the last 10% epochs
|
405 |
+
if early_stop:
|
406 |
+
epochs_before_stop = int(epochs * percent_epochs_before_stop)
|
407 |
+
if i > epochs_before_stop and abs(acc_loss[i - epochs_before_stop] - acc_loss[i]) < min_delta:
|
408 |
+
break
|
409 |
+
|
410 |
+
# No longer requires gradients in the parameters
|
411 |
+
for p in best_params.values():
|
412 |
+
p.requires_grad = False
|
413 |
+
p.grad = None
|
414 |
+
|
415 |
+
if do_report:
|
416 |
+
return best_params, acc_loss
|
417 |
+
else:
|
418 |
+
return best_params
|
419 |
+
|
420 |
+
|
421 |
+
def quantize(
|
422 |
+
x: torch.Tensor,
|
423 |
+
params: Dict[str, nn.Parameter],
|
424 |
+
func: nn.Module,
|
425 |
+
bits: int,
|
426 |
+
target_dtype: torch.dtype = torch.int8
|
427 |
+
) -> torch.Tensor:
|
428 |
+
quant_min, quant_max = get_min_max_from_bits_signed(bits)
|
429 |
+
x = x.transpose(0, 1) # Aligns shapes
|
430 |
+
x = func(x=x, **params)
|
431 |
+
x = x.transpose(0, 1)
|
432 |
+
x = torch.clamp(round_func_BPDA(x), quant_min, quant_max).to(target_dtype)
|
433 |
+
return x
|
434 |
+
|
435 |
+
|
436 |
+
def dequantize(
|
437 |
+
x: torch.Tensor,
|
438 |
+
params: Dict[str, nn.Parameter],
|
439 |
+
func: nn.Module,
|
440 |
+
bits: int,
|
441 |
+
out_dtype: torch.dtype
|
442 |
+
) -> torch.Tensor:
|
443 |
+
x = x.to(dtype=out_dtype)
|
444 |
+
x = x.transpose(0, 1)
|
445 |
+
x = func(x=x, **params)
|
446 |
+
x = x.transpose(0, 1)
|
447 |
+
return x
|
448 |
+
|
449 |
+
|
450 |
+
def round_func_BPDA(input):
|
451 |
+
# This is equivalent to replacing round function (non-differentiable) with
|
452 |
+
# an identity function (differentiable) only when backward.
|
453 |
+
forward_value = torch.round(input)
|
454 |
+
out = input.clone()
|
455 |
+
out.data = forward_value.data
|
456 |
+
return out
|
457 |
+
|
458 |
+
|
459 |
+
def get_min_max_from_bits_signed(bit_width: int) -> Tuple[int, int]:
|
460 |
+
return -2 ** (bit_width - 1), 2 ** (bit_width - 1) - 1
|
461 |
+
|
462 |
+
|
463 |
+
|
464 |
+
############## Numpy ###############
|
465 |
+
|
466 |
+
def np_domain_guard(
|
467 |
+
x: np.ndarray,
|
468 |
+
min: float = None,
|
469 |
+
max: float = None,
|
470 |
+
posinf: float = None,
|
471 |
+
neginf: float = None,
|
472 |
+
nan: float = None
|
473 |
+
) -> np.ndarray:
|
474 |
+
"""Guard a tensor to a valid domain."""
|
475 |
+
x = np.nan_to_num(x, posinf=posinf, neginf=neginf, nan=nan)
|
476 |
+
if min is not None or max is not None:
|
477 |
+
x = np.clip(x, min, max)
|
478 |
+
return x
|
479 |
+
|
480 |
+
|
481 |
+
def np_replace_num(x: np.ndarray, num: float, to: float) -> np.ndarray:
|
482 |
+
"""Replace a number in a tensor with another number.
|
483 |
+
|
484 |
+
Args:
|
485 |
+
x (np.ndarray): The input tensor.
|
486 |
+
num (float): The number to replace.
|
487 |
+
to (float): The number to replace with.
|
488 |
+
|
489 |
+
Returns:
|
490 |
+
np.ndarray: The tensor with the number replaced.
|
491 |
+
"""
|
492 |
+
return np.where(x == num, to, x)
|
493 |
+
|
494 |
+
|
495 |
+
def np_guarded_power(x: np.ndarray, exp: float) -> np.ndarray:
|
496 |
+
"""Guard the power operation to a valid domain."""
|
497 |
+
return np.power(x, exp) if exp >= 1 else np.power(np.maximum(x, 0), exp)
|
498 |
+
|
fn_gen/rnd_search_fb/2/loss.png
ADDED
fn_gen/rnd_search_fb/2/quantization.png
ADDED