forked from zama-ai/concrete-ml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xgb.py
446 lines (404 loc) · 18.7 KB
/
xgb.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
"""Implements XGBoost models."""
import platform
import warnings
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy
import xgboost.sklearn
from ..common.debugging.custom_assert import assert_true
from ..sklearn.tree_to_numpy import tree_to_numpy
from .base import BaseTreeClassifierMixin, BaseTreeRegressorMixin
# Disabling invalid-name to use uppercase X
# pylint: disable=invalid-name,too-many-instance-attributes
class XGBClassifier(BaseTreeClassifierMixin):
"""Implements the XGBoost classifier.
See https://xgboost.readthedocs.io/en/stable/python/python_api.html#module-xgboost.sklearn
for more information about the parameters used.
"""
sklearn_model_class = xgboost.sklearn.XGBClassifier
framework = "xgboost"
_is_a_public_cml_model = True
# pylint: disable=too-many-arguments,too-many-locals
def __init__(
self,
n_bits: int = 6,
max_depth: Optional[int] = 3,
learning_rate: Optional[float] = None,
n_estimators: Optional[int] = 20,
objective: Optional[str] = "binary:logistic",
booster: Optional[str] = None,
tree_method: Optional[str] = None,
n_jobs: Optional[int] = None,
gamma: Optional[float] = None,
min_child_weight: Optional[float] = None,
max_delta_step: Optional[float] = None,
subsample: Optional[float] = None,
colsample_bytree: Optional[float] = None,
colsample_bylevel: Optional[float] = None,
colsample_bynode: Optional[float] = None,
reg_alpha: Optional[float] = None,
reg_lambda: Optional[float] = None,
scale_pos_weight: Optional[float] = None,
base_score: Optional[float] = None,
missing: float = numpy.nan,
num_parallel_tree: Optional[int] = None,
monotone_constraints: Optional[Union[Dict[str, int], str]] = None,
interaction_constraints: Optional[Union[str, List[Tuple[str]]]] = None,
importance_type: Optional[str] = None,
gpu_id: Optional[int] = None,
validate_parameters: Optional[bool] = None,
predictor: Optional[str] = None,
enable_categorical: bool = False,
use_label_encoder: bool = False,
random_state: Optional[int] = None,
verbosity: Optional[int] = None,
):
# base_score != 0.5 or None does not seem to not pass our tests
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/474
assert_true(
base_score in [0.5, None],
f"Currently, only 0.5 or None are supported for base_score. Got {base_score}",
)
# See https://github.com/zama-ai/concrete-ml-internal/issues/503, there is currently
# an issue with n_jobs != 1 on macOS
#
# When it gets fixed, we'll remove this workaround
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/2747
if platform.system() == "Darwin":
if n_jobs != 1: # pragma: no cover
warnings.warn(
"forcing n_jobs = 1 on mac for segfault issue", stacklevel=3
) # pragma: no cover
n_jobs = 1 # pragma: no cover
# Call BaseClassifier's __init__ method
super().__init__(n_bits=n_bits)
self.max_depth = max_depth
self.learning_rate = learning_rate
self.n_estimators = n_estimators
self.objective = objective
self.booster = booster
self.tree_method = tree_method
self.n_jobs = n_jobs
self.gamma = gamma
self.min_child_weight = min_child_weight
self.max_delta_step = max_delta_step
self.subsample = subsample
self.colsample_bytree = colsample_bytree
self.colsample_bylevel = colsample_bylevel
self.colsample_bynode = colsample_bynode
self.reg_alpha = reg_alpha
self.reg_lambda = reg_lambda
self.scale_pos_weight = scale_pos_weight
self.base_score = base_score
self.missing = missing
self.num_parallel_tree = num_parallel_tree
self.monotone_constraints = monotone_constraints
self.interaction_constraints = interaction_constraints
self.importance_type = importance_type
self.gpu_id = gpu_id
self.validate_parameters = validate_parameters
self.predictor = predictor
self.enable_categorical = enable_categorical
self.use_label_encoder = use_label_encoder
self.random_state = random_state
self.verbosity = verbosity
def dump_dict(self) -> Dict[str, Any]:
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["output_quantizers"] = self.output_quantizers
metadata["onnx_model_"] = self.onnx_model_
metadata["framework"] = self.framework
metadata["post_processing_params"] = self.post_processing_params
# XGBoost
metadata["max_depth"] = self.max_depth
metadata["learning_rate"] = self.learning_rate
metadata["n_estimators"] = self.n_estimators
metadata["objective"] = self.objective
metadata["booster"] = self.booster
metadata["tree_method"] = self.tree_method
metadata["n_jobs"] = self.n_jobs
metadata["gamma"] = self.gamma
metadata["min_child_weight"] = self.min_child_weight
metadata["max_delta_step"] = self.max_delta_step
metadata["subsample"] = self.subsample
metadata["colsample_bytree"] = self.colsample_bytree
metadata["colsample_bylevel"] = self.colsample_bylevel
metadata["colsample_bynode"] = self.colsample_bynode
metadata["reg_alpha"] = self.reg_alpha
metadata["reg_lambda"] = self.reg_lambda
metadata["scale_pos_weight"] = self.scale_pos_weight
metadata["base_score"] = self.base_score
metadata["missing"] = self.missing
metadata["num_parallel_tree"] = self.num_parallel_tree
metadata["monotone_constraints"] = self.monotone_constraints
metadata["interaction_constraints"] = self.interaction_constraints
metadata["importance_type"] = self.importance_type
metadata["gpu_id"] = self.gpu_id
metadata["validate_parameters"] = self.validate_parameters
metadata["predictor"] = self.predictor
metadata["enable_categorical"] = self.enable_categorical
metadata["use_label_encoder"] = self.use_label_encoder
metadata["random_state"] = self.random_state
metadata["verbosity"] = self.verbosity
return metadata
@classmethod
def load_dict(cls, metadata: Dict):
# Instantiate the model
obj = XGBClassifier(n_bits=metadata["n_bits"])
# Concrete-ML
obj.sklearn_model = metadata["sklearn_model"]
obj._is_fitted = metadata["_is_fitted"]
obj._is_compiled = metadata["_is_compiled"]
obj.input_quantizers = metadata["input_quantizers"]
obj.framework = metadata["framework"]
obj.onnx_model_ = metadata["onnx_model_"]
obj.output_quantizers = metadata["output_quantizers"]
obj._tree_inference = tree_to_numpy(
obj.sklearn_model,
numpy.zeros((len(obj.input_quantizers),))[None, ...],
framework=obj.framework,
output_n_bits=obj.n_bits,
)[0]
obj.post_processing_params = metadata["post_processing_params"]
# XGBoost
obj.max_depth = metadata["max_depth"]
obj.learning_rate = metadata["learning_rate"]
obj.n_estimators = metadata["n_estimators"]
obj.objective = metadata["objective"]
obj.booster = metadata["booster"]
obj.tree_method = metadata["tree_method"]
obj.n_jobs = metadata["n_jobs"]
obj.gamma = metadata["gamma"]
obj.min_child_weight = metadata["min_child_weight"]
obj.max_delta_step = metadata["max_delta_step"]
obj.subsample = metadata["subsample"]
obj.colsample_bytree = metadata["colsample_bytree"]
obj.colsample_bylevel = metadata["colsample_bylevel"]
obj.colsample_bynode = metadata["colsample_bynode"]
obj.reg_alpha = metadata["reg_alpha"]
obj.reg_lambda = metadata["reg_lambda"]
obj.scale_pos_weight = metadata["scale_pos_weight"]
obj.base_score = metadata["base_score"]
obj.missing = metadata["missing"]
obj.num_parallel_tree = metadata["num_parallel_tree"]
obj.monotone_constraints = metadata["monotone_constraints"]
obj.interaction_constraints = metadata["interaction_constraints"]
obj.importance_type = metadata["importance_type"]
obj.gpu_id = metadata["gpu_id"]
obj.validate_parameters = metadata["validate_parameters"]
obj.predictor = metadata["predictor"]
obj.enable_categorical = metadata["enable_categorical"]
obj.use_label_encoder = metadata["use_label_encoder"]
obj.random_state = metadata["random_state"]
obj.verbosity = metadata["verbosity"]
return obj
# Disabling invalid-name to use uppercase X
# pylint: disable=invalid-name,too-many-instance-attributes
class XGBRegressor(BaseTreeRegressorMixin):
"""Implements the XGBoost regressor.
See https://xgboost.readthedocs.io/en/stable/python/python_api.html#module-xgboost.sklearn
for more information about the parameters used.
"""
sklearn_model_class = xgboost.sklearn.XGBRegressor
framework = "xgboost"
_is_a_public_cml_model = True
# pylint: disable=too-many-arguments,too-many-locals
def __init__(
self,
n_bits: int = 6,
max_depth: Optional[int] = 3,
learning_rate: Optional[float] = None,
n_estimators: Optional[int] = 20,
objective: Optional[str] = "reg:squarederror",
booster: Optional[str] = None,
tree_method: Optional[str] = None,
n_jobs: Optional[int] = None,
gamma: Optional[float] = None,
min_child_weight: Optional[float] = None,
max_delta_step: Optional[float] = None,
subsample: Optional[float] = None,
colsample_bytree: Optional[float] = None,
colsample_bylevel: Optional[float] = None,
colsample_bynode: Optional[float] = None,
reg_alpha: Optional[float] = None,
reg_lambda: Optional[float] = None,
scale_pos_weight: Optional[float] = None,
base_score: Optional[float] = None,
missing: float = numpy.nan,
num_parallel_tree: Optional[int] = None,
monotone_constraints: Optional[Union[Dict[str, int], str]] = None,
interaction_constraints: Optional[Union[str, List[Tuple[str]]]] = None,
importance_type: Optional[str] = None,
gpu_id: Optional[int] = None,
validate_parameters: Optional[bool] = None,
predictor: Optional[str] = None,
enable_categorical: bool = False,
use_label_encoder: bool = False,
random_state: Optional[int] = None,
verbosity: Optional[int] = None,
):
# base_score != 0.5 or None does not seem to not pass our tests
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/474
assert_true(
base_score in [0.5, None],
f"Currently, only 0.5 or None are supported for base_score. Got {base_score}",
)
# See https://github.com/zama-ai/concrete-ml-internal/issues/503, there is currently
# an issue with n_jobs != 1 on macOS
#
# When it gets fixed, we'll remove this workaround
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/2747
if platform.system() == "Darwin":
if n_jobs != 1: # pragma: no cover
warnings.warn(
"forcing n_jobs = 1 on mac for segfault issue", stacklevel=3
) # pragma: no cover
n_jobs = 1 # pragma: no cover
# Call BaseTreeEstimatorMixin's __init__ method
super().__init__(n_bits=n_bits)
self.max_depth = max_depth
self.learning_rate = learning_rate
self.n_estimators = n_estimators
self.objective = objective
self.booster = booster
self.tree_method = tree_method
self.n_jobs = n_jobs
self.gamma = gamma
self.min_child_weight = min_child_weight
self.max_delta_step = max_delta_step
self.subsample = subsample
self.colsample_bytree = colsample_bytree
self.colsample_bylevel = colsample_bylevel
self.colsample_bynode = colsample_bynode
self.reg_alpha = reg_alpha
self.reg_lambda = reg_lambda
self.scale_pos_weight = scale_pos_weight
self.base_score = base_score
self.missing = missing
self.num_parallel_tree = num_parallel_tree
self.monotone_constraints = monotone_constraints
self.interaction_constraints = interaction_constraints
self.importance_type = importance_type
self.gpu_id = gpu_id
self.validate_parameters = validate_parameters
self.predictor = predictor
self.enable_categorical = enable_categorical
self.use_label_encoder = use_label_encoder
self.random_state = random_state
self.verbosity = verbosity
def fit(self, X, y, *args, **kwargs) -> Any:
# Hummingbird and XGBoost don't properly manage multi-outputs cases
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/1856
assert_true(
(isinstance(y, list) and (not isinstance(y[0], list) or (len(y[0]) == 1)))
or (not isinstance(y, list) and (len(y.shape) == 1 or y.shape[1] == 1)),
"XGBRegressor doesn't support multi-output cases.",
)
# Call BaseTreeEstimatorMixin's fit method
super().fit(X, y, *args, **kwargs)
return self
def post_processing(self, y_preds: numpy.ndarray) -> numpy.ndarray:
y_preds = super().post_processing(y_preds)
# Hummingbird Gemm for XGBoostRegressor adds a + 0.5 at the end of the graph.
# We need to add it back here since the graph is cut before this add node.
y_preds += 0.5
return y_preds
def dump_dict(self) -> Dict[str, Any]:
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["output_quantizers"] = self.output_quantizers
metadata["onnx_model_"] = self.onnx_model_
metadata["framework"] = self.framework
metadata["post_processing_params"] = self.post_processing_params
# XGBoost
metadata["max_depth"] = self.max_depth
metadata["learning_rate"] = self.learning_rate
metadata["n_estimators"] = self.n_estimators
metadata["objective"] = self.objective
metadata["booster"] = self.booster
metadata["tree_method"] = self.tree_method
metadata["n_jobs"] = self.n_jobs
metadata["gamma"] = self.gamma
metadata["min_child_weight"] = self.min_child_weight
metadata["max_delta_step"] = self.max_delta_step
metadata["subsample"] = self.subsample
metadata["colsample_bytree"] = self.colsample_bytree
metadata["colsample_bylevel"] = self.colsample_bylevel
metadata["colsample_bynode"] = self.colsample_bynode
metadata["reg_alpha"] = self.reg_alpha
metadata["reg_lambda"] = self.reg_lambda
metadata["scale_pos_weight"] = self.scale_pos_weight
metadata["base_score"] = self.base_score
metadata["missing"] = self.missing
metadata["num_parallel_tree"] = self.num_parallel_tree
metadata["monotone_constraints"] = self.monotone_constraints
metadata["interaction_constraints"] = self.interaction_constraints
metadata["importance_type"] = self.importance_type
metadata["gpu_id"] = self.gpu_id
metadata["validate_parameters"] = self.validate_parameters
metadata["predictor"] = self.predictor
metadata["enable_categorical"] = self.enable_categorical
metadata["use_label_encoder"] = self.use_label_encoder
metadata["random_state"] = self.random_state
metadata["verbosity"] = self.verbosity
return metadata
@classmethod
def load_dict(cls, metadata: Dict):
# Instantiate the model
obj = XGBRegressor(n_bits=metadata["n_bits"])
# Concrete-ML
obj.sklearn_model = metadata["sklearn_model"]
obj._is_fitted = metadata["_is_fitted"]
obj._is_compiled = metadata["_is_compiled"]
obj.input_quantizers = metadata["input_quantizers"]
obj.framework = metadata["framework"]
obj.onnx_model_ = metadata["onnx_model_"]
obj.output_quantizers = metadata["output_quantizers"]
obj._tree_inference = tree_to_numpy(
obj.sklearn_model,
numpy.zeros((len(obj.input_quantizers),))[None, ...],
framework=obj.framework,
output_n_bits=obj.n_bits,
)[0]
obj.post_processing_params = metadata["post_processing_params"]
# XGBoost
obj.max_depth = metadata["max_depth"]
obj.learning_rate = metadata["learning_rate"]
obj.n_estimators = metadata["n_estimators"]
obj.objective = metadata["objective"]
obj.booster = metadata["booster"]
obj.tree_method = metadata["tree_method"]
obj.n_jobs = metadata["n_jobs"]
obj.gamma = metadata["gamma"]
obj.min_child_weight = metadata["min_child_weight"]
obj.max_delta_step = metadata["max_delta_step"]
obj.subsample = metadata["subsample"]
obj.colsample_bytree = metadata["colsample_bytree"]
obj.colsample_bylevel = metadata["colsample_bylevel"]
obj.colsample_bynode = metadata["colsample_bynode"]
obj.reg_alpha = metadata["reg_alpha"]
obj.reg_lambda = metadata["reg_lambda"]
obj.scale_pos_weight = metadata["scale_pos_weight"]
obj.base_score = metadata["base_score"]
obj.missing = metadata["missing"]
obj.num_parallel_tree = metadata["num_parallel_tree"]
obj.monotone_constraints = metadata["monotone_constraints"]
obj.interaction_constraints = metadata["interaction_constraints"]
obj.importance_type = metadata["importance_type"]
obj.gpu_id = metadata["gpu_id"]
obj.validate_parameters = metadata["validate_parameters"]
obj.predictor = metadata["predictor"]
obj.enable_categorical = metadata["enable_categorical"]
obj.use_label_encoder = metadata["use_label_encoder"]
obj.random_state = metadata["random_state"]
obj.verbosity = metadata["verbosity"]
return obj