-
Notifications
You must be signed in to change notification settings - Fork 152
/
glm.py
383 lines (315 loc) · 13.4 KB
/
glm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
"""Implement sklearn's Generalized Linear Models (GLM)."""
from __future__ import annotations
from abc import abstractmethod
from typing import Any, Dict, Union
import numpy
import sklearn
import sklearn.linear_model
from ..common.debugging.custom_assert import assert_true
from ..common.utils import FheMode
from ..onnx.onnx_model_manipulations import clean_graph_after_node_op_type
from .base import Data, SklearnLinearRegressorMixin
# pylint: disable-next=too-many-instance-attributes
class _GeneralizedLinearRegressor(SklearnLinearRegressorMixin):
"""Regression via a penalized Generalized Linear Model (GLM) with FHE.
Parameters:
n_bits (int, Dict[str, int]): Number of bits to quantize the model. If an int is passed
for n_bits, the value will be used for quantizing inputs and weights. If a dict is
passed, then it should contain "op_inputs" and "op_weights" as keys with
corresponding number of quantization bits so that:
- op_inputs: number of bits to quantize the input values
- op_weights: number of bits to quantize the learned parameters
Default to 8.
"""
def __init__(
self,
*,
n_bits: Union[int, dict] = 8,
alpha: float = 1.0,
fit_intercept: bool = True,
solver: str = "lbfgs",
max_iter: int = 100,
tol: float = 1e-4,
warm_start: bool = False,
verbose: int = 0,
):
# Call SklearnLinearModelMixin's __init__ method
super().__init__(n_bits=n_bits)
self.alpha = alpha
self.fit_intercept = fit_intercept
self.solver = solver
self.max_iter = max_iter
self.tol = tol
self.warm_start = warm_start
self.verbose = verbose
def _clean_graph(self) -> None:
assert self.onnx_model_ is not None, self._is_not_fitted_error_message()
# Remove any operators following gemm, as they will be done in the clear in post-processing
# In particular, this includes the exponential operator
clean_graph_after_node_op_type(self.onnx_model_, node_op_type="Gemm")
super()._clean_graph()
def post_processing(self, y_preds: numpy.ndarray) -> numpy.ndarray:
return self._inverse_link(y_preds)
def predict(self, X: Data, fhe: Union[FheMode, str] = FheMode.DISABLE) -> numpy.ndarray:
# Call SklearnLinearModelMixin's predict method
y_preds = super().predict(X, fhe=fhe)
y_preds = self.post_processing(y_preds)
return y_preds
@abstractmethod
def _inverse_link(self, y_preds: numpy.ndarray) -> numpy.ndarray:
"""Apply the link function's inverse on the inputs.
Args:
y_preds (numpy.ndarray): The input data.
"""
def dump_dict(self) -> Dict:
assert self._weight_quantizer is not None, self._is_not_fitted_error_message()
metadata: Dict[str, Any] = {}
# Concrete ML
metadata["n_bits"] = self.n_bits
metadata["sklearn_model"] = self.sklearn_model
metadata["_is_fitted"] = self._is_fitted
metadata["_is_compiled"] = self._is_compiled
metadata["input_quantizers"] = self.input_quantizers
metadata["_weight_quantizer"] = self._weight_quantizer
metadata["output_quantizers"] = self.output_quantizers
metadata["onnx_model_"] = self.onnx_model_
metadata["_q_weights"] = self._q_weights
metadata["_q_bias"] = self._q_bias
metadata["post_processing_params"] = self.post_processing_params
# Scikit-Learn
metadata["alpha"] = self.alpha
metadata["fit_intercept"] = self.fit_intercept
metadata["solver"] = self.solver
metadata["max_iter"] = self.max_iter
metadata["tol"] = self.tol
metadata["warm_start"] = self.warm_start
metadata["verbose"] = self.verbose
return metadata
@classmethod
def load_dict(cls, metadata: Dict):
# Instantiate the model
obj = cls(n_bits=metadata["n_bits"])
# Concrete ML
obj.n_bits = metadata["n_bits"]
obj.sklearn_model = metadata["sklearn_model"]
obj.onnx_model_ = metadata["onnx_model_"]
obj._is_fitted = metadata["_is_fitted"]
obj._is_compiled = metadata["_is_compiled"]
obj.input_quantizers = metadata["input_quantizers"]
obj._weight_quantizer = metadata["_weight_quantizer"]
obj.output_quantizers = metadata["output_quantizers"]
obj._q_weights = metadata["_q_weights"]
obj._q_bias = metadata["_q_bias"]
obj.post_processing_params = metadata["post_processing_params"]
# Scikit-Learn
obj.alpha = metadata["alpha"]
obj.fit_intercept = metadata["fit_intercept"]
obj.solver = metadata["solver"]
obj.max_iter = metadata["max_iter"]
obj.tol = metadata["tol"]
obj.warm_start = metadata["warm_start"]
obj.verbose = metadata["verbose"]
return obj
def get_sklearn_params(self, deep: bool = True) -> dict:
# Here, the `get_params` method is the `BaseEstimator.get_params` method from scikit-learn
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/3373
params = super().get_params(deep=deep) # type: ignore[misc]
# Remove the parameters added by Concrete ML
params.pop("n_bits", None)
# Remove sklearn 1.4 parameter when using sklearn 1.1
if "1.1." in sklearn.__version__:
params.pop("solver", None) # pragma: no cover
return params
class PoissonRegressor(_GeneralizedLinearRegressor):
"""A Poisson regression model with FHE.
Parameters:
n_bits (int, Dict[str, int]): Number of bits to quantize the model. If an int is passed
for n_bits, the value will be used for quantizing inputs and weights. If a dict is
passed, then it should contain "op_inputs" and "op_weights" as keys with
corresponding number of quantization bits so that:
- op_inputs : number of bits to quantize the input values
- op_weights: number of bits to quantize the learned parameters
Default to 8.
For more details on PoissonRegressor please refer to the scikit-learn documentation:
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.PoissonRegressor.html
"""
sklearn_model_class = sklearn.linear_model.PoissonRegressor
_is_a_public_cml_model = True
def __init__( # pylint: disable=useless-parent-delegation
self,
*,
n_bits: Union[int, dict] = 8,
alpha: float = 1.0,
fit_intercept: bool = True,
solver="lbfgs",
max_iter: int = 100,
tol: float = 1e-4,
warm_start: bool = False,
verbose: int = 0,
):
super().__init__(
n_bits=n_bits,
alpha=alpha,
fit_intercept=fit_intercept,
solver=solver,
max_iter=max_iter,
tol=tol,
warm_start=warm_start,
verbose=verbose,
)
def _inverse_link(self, y_preds: numpy.ndarray) -> numpy.ndarray:
return numpy.exp(y_preds)
class GammaRegressor(_GeneralizedLinearRegressor):
"""A Gamma regression model with FHE.
Parameters:
n_bits (int, Dict[str, int]): Number of bits to quantize the model. If an int is passed
for n_bits, the value will be used for quantizing inputs and weights. If a dict is
passed, then it should contain "op_inputs" and "op_weights" as keys with
corresponding number of quantization bits so that:
- op_inputs : number of bits to quantize the input values
- op_weights: number of bits to quantize the learned parameters
Default to 8.
For more details on GammaRegressor please refer to the scikit-learn documentation:
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.GammaRegressor.html
"""
sklearn_model_class = sklearn.linear_model.GammaRegressor
_is_a_public_cml_model = True
def __init__( # pylint: disable=useless-parent-delegation
self,
*,
n_bits: Union[int, dict] = 8,
alpha: float = 1.0,
fit_intercept: bool = True,
solver="lbfgs",
max_iter: int = 100,
tol: float = 1e-4,
warm_start: bool = False,
verbose: int = 0,
):
super().__init__(
n_bits=n_bits,
alpha=alpha,
fit_intercept=fit_intercept,
solver=solver,
max_iter=max_iter,
tol=tol,
warm_start=warm_start,
verbose=verbose,
)
def _inverse_link(self, y_preds: numpy.ndarray) -> numpy.ndarray:
return numpy.exp(y_preds)
# pylint: disable-next=too-many-instance-attributes
class TweedieRegressor(_GeneralizedLinearRegressor):
"""A Tweedie regression model with FHE.
Parameters:
n_bits (int, Dict[str, int]): Number of bits to quantize the model. If an int is passed
for n_bits, the value will be used for quantizing inputs and weights. If a dict is
passed, then it should contain "op_inputs" and "op_weights" as keys with
corresponding number of quantization bits so that:
- op_inputs : number of bits to quantize the input values
- op_weights: number of bits to quantize the learned parameters
Default to 8.
For more details on TweedieRegressor please refer to the scikit-learn documentation:
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.TweedieRegressor.html
"""
sklearn_model_class = sklearn.linear_model.TweedieRegressor
_is_a_public_cml_model = True
def __init__( # pylint: disable=too-many-arguments
self,
*,
n_bits: Union[int, dict] = 8,
power: float = 0.0,
alpha: float = 1.0,
fit_intercept: bool = True,
link: str = "auto",
solver="lbfgs",
max_iter: int = 100,
tol: float = 1e-4,
warm_start: bool = False,
verbose: int = 0,
):
super().__init__(
n_bits=n_bits,
alpha=alpha,
fit_intercept=fit_intercept,
solver=solver,
max_iter=max_iter,
tol=tol,
warm_start=warm_start,
verbose=verbose,
)
assert_true(
link in ["auto", "log", "identity"],
f"link must be an element of ['auto', 'identity', 'log'], got '{link}'",
)
self.power = power
self.link = link
def _set_post_processing_params(self):
super()._set_post_processing_params()
self.post_processing_params.update(
{
"link": self.link,
"power": self.power,
}
)
def _inverse_link(self, y_preds: numpy.ndarray) -> numpy.ndarray:
self.check_model_is_fitted()
if self.post_processing_params["link"] == "auto":
# Identity link
if self.post_processing_params["power"] <= 0:
return y_preds
# Log link
return numpy.exp(y_preds)
if self.post_processing_params["link"] == "log":
return numpy.exp(y_preds)
return y_preds
def dump_dict(self) -> Dict:
assert self._weight_quantizer is not None, self._is_not_fitted_error_message()
metadata: Dict[str, Any] = {}
# Concrete ML
metadata["n_bits"] = self.n_bits
metadata["sklearn_model"] = self.sklearn_model
metadata["_is_fitted"] = self._is_fitted
metadata["_is_compiled"] = self._is_compiled
metadata["input_quantizers"] = self.input_quantizers
metadata["_weight_quantizer"] = self._weight_quantizer
metadata["output_quantizers"] = self.output_quantizers
metadata["onnx_model_"] = self.onnx_model_
metadata["_q_weights"] = self._q_weights
metadata["_q_bias"] = self._q_bias
metadata["post_processing_params"] = self.post_processing_params
metadata["power"] = self.power
metadata["link"] = self.link
# Scikit-Learn
metadata["alpha"] = self.alpha
metadata["fit_intercept"] = self.fit_intercept
metadata["max_iter"] = self.max_iter
metadata["tol"] = self.tol
metadata["warm_start"] = self.warm_start
metadata["verbose"] = self.verbose
return metadata
@classmethod
def load_dict(cls, metadata: Dict):
# Instantiate the model
obj = cls(n_bits=metadata["n_bits"])
# Concrete ML
obj.sklearn_model = metadata["sklearn_model"]
obj.onnx_model_ = metadata["onnx_model_"]
obj._is_fitted = metadata["_is_fitted"]
obj._is_compiled = metadata["_is_compiled"]
obj.input_quantizers = metadata["input_quantizers"]
obj._weight_quantizer = metadata["_weight_quantizer"]
obj.output_quantizers = metadata["output_quantizers"]
obj._q_weights = metadata["_q_weights"]
obj._q_bias = metadata["_q_bias"]
obj.power = metadata["power"]
obj.link = metadata["link"]
obj.post_processing_params = metadata["post_processing_params"]
# Scikit-Learn
obj.alpha = metadata["alpha"]
obj.fit_intercept = metadata["fit_intercept"]
obj.max_iter = metadata["max_iter"]
obj.tol = metadata["tol"]
obj.warm_start = metadata["warm_start"]
obj.verbose = metadata["verbose"]
return obj