-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathmodel_serializer.py
1187 lines (1005 loc) · 42.4 KB
/
model_serializer.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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8; -*-
# Copyright (c) 2023 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
import cloudpickle
import numpy as np
import pandas as pd
from ads.model.serde.common import Serializer, Deserializer
from ads.common.decorator.runtime_dependency import (
runtime_dependency,
OptionalDependency,
)
from ads.common import logger
from pandas.api.types import is_numeric_dtype, is_string_dtype
from typing import Any, Dict, List, Optional, Tuple, Union
from joblib import dump
MODEL_SERIALIZATION_TYPE_ONNX = "onnx"
MODEL_SERIALIZATION_TYPE_CLOUDPICKLE = "cloudpickle"
MODEL_SERIALIZATION_TYPE_TORHCSCRIPT = "torchscript"
MODEL_SERIALIZATION_TYPE_TORCH = "torch"
MODEL_SERIALIZATION_TYPE_TORCH_ONNX = "torch_onnx"
MODEL_SERIALIZATION_TYPE_TF = "tf"
MODEL_SERIALIZATION_TYPE_TF_ONNX = "tf_onnx"
MODEL_SERIALIZATION_TYPE_JOBLIB = "joblib"
MODEL_SERIALIZATION_TYPE_SKLEARN_ONNX = "sklearn_onnx"
MODEL_SERIALIZATION_TYPE_LIGHTGBM = "lightgbm"
MODEL_SERIALIZATION_TYPE_LIGHTGBM_ONNX = "lightgbm_onnx"
MODEL_SERIALIZATION_TYPE_XGBOOST = "xgboost"
MODEL_SERIALIZATION_TYPE_XGBOOST_UBJ = "xgboost_ubj"
MODEL_SERIALIZATION_TYPE_XGBOOST_TXT = "xgboost_txt"
MODEL_SERIALIZATION_TYPE_XGBOOST_ONNX = "xgboost_onnx"
MODEL_SERIALIZATION_TYPE_SPARK = "spark"
MODEL_SERIALIZATION_TYPE_HUGGINGFACE = "huggingface"
SUPPORTED_MODEL_SERIALIZERS = [
MODEL_SERIALIZATION_TYPE_ONNX,
MODEL_SERIALIZATION_TYPE_CLOUDPICKLE,
MODEL_SERIALIZATION_TYPE_TORHCSCRIPT,
MODEL_SERIALIZATION_TYPE_TORCH,
MODEL_SERIALIZATION_TYPE_TORCH_ONNX,
MODEL_SERIALIZATION_TYPE_TF,
MODEL_SERIALIZATION_TYPE_TF_ONNX,
MODEL_SERIALIZATION_TYPE_JOBLIB,
MODEL_SERIALIZATION_TYPE_SKLEARN_ONNX,
MODEL_SERIALIZATION_TYPE_LIGHTGBM,
MODEL_SERIALIZATION_TYPE_LIGHTGBM_ONNX,
MODEL_SERIALIZATION_TYPE_XGBOOST,
MODEL_SERIALIZATION_TYPE_XGBOOST_ONNX,
MODEL_SERIALIZATION_TYPE_SPARK,
MODEL_SERIALIZATION_TYPE_HUGGINGFACE,
]
class ModelSerializerType:
CLOUDPICKLE = MODEL_SERIALIZATION_TYPE_CLOUDPICKLE
ONNX = MODEL_SERIALIZATION_TYPE_ONNX
class PyTorchModelSerializerType:
TORCH = MODEL_SERIALIZATION_TYPE_TORCH
TORCHSCRIPT = MODEL_SERIALIZATION_TYPE_TORHCSCRIPT
ONNX = MODEL_SERIALIZATION_TYPE_TORCH_ONNX
class TensorflowModelSerializerType:
TENSORFLOW = MODEL_SERIALIZATION_TYPE_TF
ONNX = MODEL_SERIALIZATION_TYPE_TF_ONNX
class LightGBMModelSerializerType:
LIGHTGBM = MODEL_SERIALIZATION_TYPE_LIGHTGBM
ONNX = MODEL_SERIALIZATION_TYPE_LIGHTGBM_ONNX
class SklearnModelSerializerType:
JOBLIB = MODEL_SERIALIZATION_TYPE_JOBLIB
CLOUDPICKLE = MODEL_SERIALIZATION_TYPE_CLOUDPICKLE
ONNX = MODEL_SERIALIZATION_TYPE_SKLEARN_ONNX
class XgboostModelSerializerType:
XGBOOST = MODEL_SERIALIZATION_TYPE_XGBOOST
ONNX = MODEL_SERIALIZATION_TYPE_XGBOOST_ONNX
class SparkModelSerializerType:
SPARK = MODEL_SERIALIZATION_TYPE_SPARK
class HuggingFaceSerializerType:
HUGGINGFACE = MODEL_SERIALIZATION_TYPE_HUGGINGFACE
class ModelSerializer(Serializer):
"""Base class for creation of new model serializers."""
def __init__(self, model_file_suffix):
super().__init__()
self.model_file_suffix = model_file_suffix
class ModelDeserializer(Deserializer):
"""Base class for creation of new model deserializers."""
def deserialize(self, **kwargs):
raise NotImplementedError
class CloudPickleModelSerializer(ModelSerializer):
"""Uses `Cloudpickle` to save model."""
def __init__(self, model_file_suffix="pkl"):
super().__init__(model_file_suffix=model_file_suffix)
def serialize(self, estimator, model_path, **kwargs):
"""Uses `cloudpickle.dump` to save model. See https://docs.python.org/3/library/pickle.html#pickle.dump for more details.
Args:
estimator: The model to be saved.
model_path: The file object or path of the model in which it is to be stored.
kwargs:
model_save: (dict, optional).
The dictionary where contains the availiable options to be passed to `cloudpickle.dump`.
"""
cloudpickle_kwargs = kwargs.pop("model_save", {})
with open(model_path, "wb") as f:
cloudpickle.dump(estimator, f, **cloudpickle_kwargs)
class JobLibModelSerializer(ModelSerializer):
"""Uses `Joblib` to save model."""
def __init__(self, model_file_suffix="joblib"):
super().__init__(model_file_suffix=model_file_suffix)
def serialize(self, estimator, model_path, **kwargs):
"""Uses `joblib.dump` to save model. See https://joblib.readthedocs.io/en/latest/generated/joblib.dump.html for more details.
Args:
estimator: The model to be saved.
model_path: The file object or path of the model in which it is to be stored.
kwargs:
model_save: (dict, optional).
The dictionary where contains the availiable options to be passed to `joblib.dump`.
"""
joblib_kwargs = kwargs.pop("model_save", {})
dump(estimator, model_path, **joblib_kwargs)
class SparkModelSerializer(ModelSerializer):
"""Save Spark Model."""
def __init__(self, model_file_suffix=""):
super().__init__(model_file_suffix=model_file_suffix)
def serialize(self, estimator, model_path, **kwargs):
estimator.write().overwrite().save(model_path)
class PyTorchModelSerializer(ModelSerializer):
"""Save PyTorch Model using torch.save(). See https://pytorch.org/docs/stable/generated/torch.save.html for more details."""
def __init__(self, model_file_suffix="pt"):
super().__init__(model_file_suffix=model_file_suffix)
@runtime_dependency(module="torch", install_from=OptionalDependency.PYTORCH)
def serialize(self, estimator, model_path, **kwarg):
torch.save(estimator.state_dict(), model_path)
class TorchScriptModelSerializer(ModelSerializer):
"""Save PyTorch Model using torchscript. See https://pytorch.org/tutorials/beginner/saving_loading_models.html#export-load-model-in-torchscript-format for more details."""
def __init__(self, model_file_suffix="pt"):
super().__init__(model_file_suffix=model_file_suffix)
@runtime_dependency(module="torch", install_from=OptionalDependency.PYTORCH)
def serialize(self, estimator, model_path, **kwargs):
compiled_model = torch.jit.script(estimator)
torch.jit.save(compiled_model, model_path)
class LightGBMModelSerializer(ModelSerializer):
"""Save LightGBM Model through save_model into txt."""
def __init__(self, model_file_suffix="txt"):
super().__init__(model_file_suffix=model_file_suffix)
def serialize(self, estimator, model_path, **kwargs):
estimator.save_model(model_path)
class XgboostJsonModelSerializer(ModelSerializer):
"""Save Xgboost Model through xgboost.save_model into JSON."""
def __init__(self, model_file_suffix="json"):
super().__init__(model_file_suffix=model_file_suffix)
def serialize(self, estimator, model_path, **kwargs):
"""Save Xgboost Model through xgboost.save_model .See
https://xgboost.readthedocs.io/en/stable/python/python_api.html#xgboost.Booster.save_model
for more details.
Args:
estimator: The model to be saved.
model_path: The file object or path of the model in which it is to be stored.
"""
estimator.save_model(model_path)
class XgboostTxtModelSerializer(ModelSerializer):
"""Save Xgboost Model through xgboost.save_model into txt."""
def __init__(self, model_file_suffix="txt"):
super().__init__(model_file_suffix=model_file_suffix)
def serialize(self, estimator, model_path, **kwargs):
"""Save Xgboost Model through xgboost.save_model .See
https://xgboost.readthedocs.io/en/stable/python/python_api.html#xgboost.Booster.save_model
for more details.
Args:
estimator: The model to be saved.
model_path: The file object or path of the model in which it is to be stored.
"""
estimator.save_model(model_path)
class XgboostUbjModelSerializer(ModelSerializer):
"""Save Xgboost Model through xgboost.save_model into binary JSON."""
def __init__(self, model_file_suffix="ubj"):
super().__init__(model_file_suffix=model_file_suffix)
def serialize(self, estimator, model_path, **kwargs):
"""Save Xgboost Model through xgboost.save_model .See
https://xgboost.readthedocs.io/en/stable/python/python_api.html#xgboost.Booster.save_model
for more details.
Args:
estimator: The model to be saved.
model_path: The file object or path of the model in which it is to be stored.
"""
estimator.save_model(model_path)
class TensorFlowModelSerializer(ModelSerializer):
"""Save Tensorflow Model."""
def __init__(self, model_file_suffix="h5"):
super().__init__(model_file_suffix=model_file_suffix)
def serialize(self, estimator, model_path, **kwargs):
estimator.save(model_path)
class HuggingFaceModelSerializer(ModelSerializer):
"""Save HuggingFace Pipeline."""
def __init__(self, model_file_suffix=""):
super().__init__(model_file_suffix=model_file_suffix)
def serialize(self, estimator, model_path, **kwargs):
estimator.save_pretrained(save_directory=model_path)
estimator.model.config.use_pretrained_backbone = False
estimator.model.config.save_pretrained(save_directory=model_path)
class OnnxModelSerializer(ModelSerializer):
"""Base class for creation of onnx converter for each model framework."""
def __init__(self, model_file_suffix="onnx"):
super().__init__(model_file_suffix=model_file_suffix)
def serialize(
self,
estimator,
model_path,
initial_types: List[Tuple] = None,
X_sample: Optional[
Union[
Dict,
str,
List,
Tuple,
np.ndarray,
pd.core.series.Series,
pd.core.frame.DataFrame,
]
] = None,
**kwargs,
):
"""Save model into onnx format.
Args:
estimator: The model to be saved.
model_path: The file object or path of the model in which it is to be stored.
initial_types: (List[Tuple], optional)
a python list. Each element is a tuple of a variable name and a data type.
X_sample: (any, optional). Defaults to None.
Contains model inputs such that model(X_sample) is a valid
invocation of the model, used to valid model input type.
"""
self.estimator = estimator
onx = self._to_onnx(
initial_types=initial_types,
X_sample=X_sample,
**kwargs,
)
with open(model_path, "wb") as f:
f.write(onx.SerializeToString())
def _to_onnx(
self,
initial_types: List[Tuple] = None,
X_sample: Optional[
Union[
Dict,
str,
List,
Tuple,
np.ndarray,
pd.core.series.Series,
pd.core.frame.DataFrame,
]
] = None,
**kwargs,
):
raise NotImplementedError
class SklearnOnnxModelSerializer(OnnxModelSerializer):
"""Converts Skearn Model into Onnx."""
def __init__(self):
super().__init__()
@runtime_dependency(module="onnx", install_from=OptionalDependency.ONNX)
@runtime_dependency(module="xgboost", install_from=OptionalDependency.BOOSTED)
@runtime_dependency(module="lightgbm", install_from=OptionalDependency.BOOSTED)
@runtime_dependency(module="skl2onnx", install_from=OptionalDependency.ONNX)
@runtime_dependency(module="onnxmltools", install_from=OptionalDependency.ONNX)
@runtime_dependency(
module="onnxmltools.convert.xgboost.operator_converters.XGBoost",
object="convert_xgboost",
install_from=OptionalDependency.ONNX,
)
@runtime_dependency(
module="onnxmltools.convert.lightgbm.operator_converters.LightGbm",
object="convert_lightgbm",
install_from=OptionalDependency.ONNX,
)
def _to_onnx(
self,
initial_types: List[Tuple] = None,
X_sample: Optional[
Union[
Dict,
str,
List,
Tuple,
np.ndarray,
pd.core.series.Series,
pd.core.frame.DataFrame,
]
] = None,
**kwargs,
):
"""
Produces an equivalent ONNX model of the given scikit-learn model.
Parameters
----------
initial_types: (List[Tuple], optional). Defaults to None.
Each element is a tuple of a variable name and a type.
X_sample: Union[Dict, str, List, np.ndarray, pd.core.series.Series, pd.core.frame.DataFrame,]. Defaults to None.
Contains model inputs such that model(X_sample) is a valid invocation of the model.
Used to generate initial_types.
Returns
-------
onnx.onnx_ml_pb2.ModelProto
An ONNX model (type: ModelProto) which is equivalent to the input scikit-learn model.
"""
auto_generated_initial_types = None
if not initial_types:
if X_sample is None:
raise ValueError(
" At least one of `X_sample` or `initial_types` must be provided."
)
auto_generated_initial_types = self._generate_initial_types(X_sample)
if str(type(self.estimator)).startswith("<class 'sklearn.pipeline"):
model_types = []
model_types = [type(val[1]) for val in self.estimator.steps]
if xgboost.sklearn.XGBClassifier in model_types:
skl2onnx.update_registered_converter(
xgboost.XGBClassifier,
"XGBoostXGBClassifier",
skl2onnx.common.shape_calculator.calculate_linear_classifier_output_shapes,
convert_xgboost,
options=kwargs.pop(
"options", {"nocl": [True, False], "zipmap": [True, False]}
),
)
if xgboost.sklearn.XGBRegressor in model_types:
skl2onnx.update_registered_converter(
xgboost.XGBRegressor,
"XGBoostXGBRegressor",
skl2onnx.common.shape_calculator.calculate_linear_regressor_output_shapes,
convert_xgboost,
)
if lightgbm.sklearn.LGBMClassifier in model_types:
skl2onnx.update_registered_converter(
lightgbm.LGBMClassifier,
"LightGbmLGBMClassifier",
skl2onnx.common.shape_calculator.calculate_linear_classifier_output_shapes,
convert_lightgbm,
options=kwargs.pop(
"options",
{"nocl": [True, False], "zipmap": [True, False, "columns"]},
),
)
if lightgbm.sklearn.LGBMRegressor in model_types:
def skl2onnx_convert_lightgbm(scope, operator, container):
options = scope.get_options(operator.raw_operator)
if "split" in options:
if StrictVersion(onnxmltools.__version__) < StrictVersion(
"1.9.2"
):
logger.warnings(
"Option split was released in version 1.9.2 but %s is "
"installed. It will be ignored."
% onnxmltools.__version__
)
operator.split = options["split"]
else:
operator.split = None
convert_lightgbm(scope, operator, container)
skl2onnx.update_registered_converter(
lightgbm.LGBMRegressor,
"LightGbmLGBMRegressor",
skl2onnx.common.shape_calculator.calculate_linear_regressor_output_shapes,
skl2onnx_convert_lightgbm,
options=kwargs.pop("options", {"split": None}),
)
if initial_types:
return skl2onnx.convert_sklearn(
self.estimator, initial_types=initial_types, **kwargs
)
else:
try:
return skl2onnx.convert_sklearn(
self.estimator,
initial_types=auto_generated_initial_types,
target_opset=None,
**kwargs,
)
except Exception as e:
logger.exception("Exception details:")
raise ValueError(
"`initial_types` can not be autodetected. Please directly pass `initial_types`."
)
else:
if initial_types:
return onnxmltools.convert_sklearn(
self.estimator,
initial_types=initial_types,
targeted_onnx=onnx.__version__,
**kwargs,
)
else:
try:
return onnxmltools.convert_sklearn(
self.estimator,
initial_types=auto_generated_initial_types,
targeted_onnx=onnx.__version__,
**kwargs,
)
except Exception as e:
raise ValueError(
"`initial_types` can not be detected. Please directly pass initial_types."
)
@runtime_dependency(module="skl2onnx", install_from=OptionalDependency.ONNX)
def _generate_initial_types(self, X_sample: Any) -> List:
"""Auto generate intial types.
Parameters
----------
X_sample: (Any)
Train data.
Returns
-------
List
Initial types.
"""
if self._is_all_numerical_array_dataframe(X_sample):
# if it's a dataframe and all the columns are numerical. Or
# it's not a dataframe, also try this.
if hasattr(X_sample, "shape") and len(X_sample.shape) >= 2:
auto_generated_initial_types = [
(
"input",
skl2onnx.common.data_types.FloatTensorType(
[None, X_sample.shape[1]]
),
)
]
elif hasattr(self.estimator, "n_features_in_"):
n_cols = self.estimator.n_features_in_
auto_generated_initial_types = [
(
"input",
skl2onnx.common.data_types.FloatTensorType([None, n_cols]),
)
]
else:
raise ValueError(
"`initial_types` can not be detected. Please directly pass initial_types."
)
elif self.is_either_numerical_or_string_dataframe(X_sample):
# for dataframe and not all the columns are numerical, then generate
# the input types of all the columns one by one.
auto_generated_initial_types = []
for i, col in X_sample.items():
if is_numeric_dtype(col.dtypes):
auto_generated_initial_types.append(
(
col.name,
skl2onnx.common.data_types.FloatTensorType([None, 1]),
)
)
else:
auto_generated_initial_types.append(
(
col.name,
skl2onnx.common.data_types.StringTensorType([None, 1]),
)
)
else:
try:
auto_generated_initial_types = (
skl2onnx.common.data_types.guess_data_type(
np.array(X_sample) if isinstance(X_sample, list) else X_sample
)
)
except:
auto_generated_initial_types = None
return auto_generated_initial_types
@staticmethod
def _is_all_numerical_array_dataframe(
data: Union[pd.DataFrame, np.ndarray]
) -> bool:
"""Check whether all the columns are numerical for numpy array and dataframe.
For data with any other data types, it will return False.
Parameters
----------
data: Union[pd.DataFrame, np.ndarray]
Returns
-------
bool
Whether all the columns in a pandas dataframe or numpy array are all numerical.
"""
return (
isinstance(data, pd.DataFrame)
and all([is_numeric_dtype(dtype) for dtype in data.dtypes])
or (isinstance(data, np.ndarray) and is_numeric_dtype(data.dtype))
)
@staticmethod
def is_either_numerical_or_string_dataframe(data: pd.DataFrame) -> bool:
"""Check whether all the columns are either numerical or string for dataframe."""
return isinstance(data, pd.DataFrame) and all(
[
is_numeric_dtype(col.dtypes) or is_string_dtype(col.dtypes)
for _, col in data.items()
]
)
class LightGBMOnnxModelSerializer(OnnxModelSerializer):
"""Converts LightGBM model into onnx format."""
def __init__(self):
super().__init__()
@runtime_dependency(
module="skl2onnx.common.data_types",
object="FloatTensorType",
install_from=OptionalDependency.ONNX,
)
@runtime_dependency(
module="onnxmltools.convert",
object="convert_lightgbm",
install_from=OptionalDependency.ONNX,
)
def _to_onnx(
self,
initial_types: List[Tuple] = None,
X_sample: Optional[
Union[
Dict,
str,
List,
Tuple,
np.ndarray,
pd.core.series.Series,
pd.core.frame.DataFrame,
]
] = None,
**kwargs,
):
"""
Produces an equivalent ONNX model of the given LightGBM model.
Parameters
----------
initial_types: (List[Tuple], optional). Defaults to None.
Each element is a tuple of a variable name and a type.
X_sample: Union[Dict, str, List, np.ndarray, pd.core.series.Series, pd.core.frame.DataFrame,]. Defaults to None.
Contains model inputs such that model(X_sample) is a valid invocation of the model.
Used to generate initial_types.
Returns
------
An ONNX model (type: ModelProto) which is equivalent to the input LightGBM model.
"""
auto_generated_initial_types = None
if not initial_types:
auto_generated_initial_types = self._generate_initial_types(X_sample)
try:
return convert_lightgbm(
self.estimator,
initial_types=auto_generated_initial_types,
target_opset=kwargs.pop("target_opset", None),
**kwargs,
)
except:
raise ValueError(
"`initial_types` can not be detected. Please directly pass initial_types."
)
else:
return convert_lightgbm(
self.estimator,
initial_types=initial_types,
target_opset=kwargs.pop("target_opset", None),
**kwargs,
)
@runtime_dependency(
module="skl2onnx.common.data_types",
object="FloatTensorType",
install_from=OptionalDependency.ONNX,
)
def _generate_initial_types(self, X_sample: Any) -> List:
"""Auto generate intial types.
Parameters
----------
X_sample: (Any)
Train data.
Returns
-------
List
Initial types.
"""
if X_sample is not None and hasattr(X_sample, "shape"):
auto_generated_initial_types = [
("input", FloatTensorType([None, X_sample.shape[1]]))
]
elif hasattr(self.estimator, "num_feature"):
n_cols = self.estimator.num_feature()
auto_generated_initial_types = [("input", FloatTensorType([None, n_cols]))]
elif hasattr(self.estimator, "n_features_in_"):
n_cols = self.estimator.n_features_in_
auto_generated_initial_types = [("input", FloatTensorType([None, n_cols]))]
else:
raise ValueError(
"`initial_types` can not be detected. Please directly pass initial_types."
)
return auto_generated_initial_types
class XgboostOnnxModelSerializer(OnnxModelSerializer):
"""Converts Xgboost model into onnx format."""
def __init__(self):
super().__init__()
@runtime_dependency(module="onnx", install_from=OptionalDependency.ONNX)
@runtime_dependency(module="xgboost", install_from=OptionalDependency.BOOSTED)
@runtime_dependency(
module="skl2onnx",
object="convert_sklearn",
install_from=OptionalDependency.ONNX,
)
@runtime_dependency(
module="skl2onnx",
object="update_registered_converter",
install_from=OptionalDependency.ONNX,
)
@runtime_dependency(
module="skl2onnx.common.data_types",
object="FloatTensorType",
install_from=OptionalDependency.ONNX,
)
@runtime_dependency(
module="skl2onnx.common.shape_calculator",
object="calculate_linear_classifier_output_shapes",
install_from=OptionalDependency.ONNX,
)
@runtime_dependency(
module="skl2onnx.common.shape_calculator",
object="calculate_linear_regressor_output_shapes",
install_from=OptionalDependency.ONNX,
)
@runtime_dependency(module="onnxmltools", install_from=OptionalDependency.ONNX)
@runtime_dependency(
module="onnxmltools.convert.xgboost.operator_converters.XGBoost",
object="convert_xgboost",
install_from=OptionalDependency.ONNX,
)
def _to_onnx(
self,
initial_types: List[Tuple] = None,
X_sample: Union[list, tuple, pd.DataFrame, pd.Series, np.ndarray] = None,
**kwargs,
):
"""
Produces an equivalent ONNX model of the given Xgboost model.
Parameters
----------
initial_types: (List[Tuple], optional). Defaults to None.
Each element is a tuple of a variable name and a type.
X_sample: Union[Dict, str, List, np.ndarray, pd.core.series.Series, pd.core.frame.DataFrame,]. Defaults to None.
Contains model inputs such that model(X_sample) is a valid invocation of the model.
Used to generate initial_types.
Returns
-------
onnx.onnx_ml_pb2.ModelProto
An ONNX model (type: ModelProto) which is equivalent to the input xgboost model.
"""
auto_generated_initial_types = None
if not initial_types:
auto_generated_initial_types = self._generate_initial_types(X_sample)
model_types = []
if str(type(self.estimator)).startswith("<class 'xgboost.sklearn."):
model_types.append(type(self.estimator))
if model_types:
if xgboost.sklearn.XGBClassifier in model_types:
update_registered_converter(
xgboost.XGBClassifier,
"XGBoostXGBClassifier",
calculate_linear_classifier_output_shapes,
convert_xgboost,
options={"nocl": [True, False], "zipmap": [True, False]},
)
elif xgboost.sklearn.XGBRegressor in model_types:
update_registered_converter(
xgboost.XGBRegressor,
"XGBoostXGBRegressor",
calculate_linear_regressor_output_shapes,
convert_xgboost,
)
if initial_types:
return convert_sklearn(
self.estimator, initial_types=initial_types, **kwargs
)
else:
try:
return convert_sklearn(
self.estimator,
initial_types=auto_generated_initial_types,
**kwargs,
)
except:
logger.exception("Exception details:")
raise ValueError(
"`initial_types` can not be autodetected. Please directly pass `initial_types`."
)
else:
# xgboost api
if initial_types:
return onnxmltools.convert_xgboost(
self.estimator,
initial_types=initial_types,
target_opset=kwargs.pop("target_opset", None),
targeted_onnx=onnx.__version__,
**kwargs,
)
else:
try:
return onnxmltools.convert_xgboost(
self.estimator,
initial_types=auto_generated_initial_types,
target_opset=kwargs.pop("target_opset", None),
targeted_onnx=onnx.__version__,
**kwargs,
)
except:
logger.exception("Exception details:")
raise ValueError(
"`initial_types` can not be autodetected. Please directly pass `initial_types`."
)
@runtime_dependency(
module="skl2onnx.common.data_types",
object="FloatTensorType",
install_from=OptionalDependency.ONNX,
)
def _generate_initial_types(self, X_sample: Any) -> List:
"""Auto generate intial types.
Parameters
----------
X_sample: (Any)
Train data.
Returns
-------
List
Initial types.
"""
if hasattr(self.estimator, "n_features_in_"):
# sklearn api
n_cols = self.estimator.n_features_in_
return [("input", FloatTensorType([None, n_cols]))]
elif hasattr(self.estimator, "feature_names") and self.estimator.feature_names:
# xgboost learning api
n_cols = len(self.estimator.feature_names)
return [("input", FloatTensorType([None, n_cols]))]
if X_sample is None:
raise ValueError(
" At least one of `X_sample` or `initial_types` must be provided."
)
if (
X_sample is not None
and hasattr(X_sample, "shape")
and len(X_sample.shape) >= 2
):
auto_generated_initial_types = [
("input", FloatTensorType([None, X_sample.shape[1]]))
]
else:
raise ValueError(
"`initial_types` can not be detected. Please directly pass initial_types."
)
return auto_generated_initial_types
class PytorchOnnxModelSerializer(OnnxModelSerializer):
"""Converts Pytorch model into onnx format."""
def __init__(self):
super().__init__()
@runtime_dependency(module="torch", install_from=OptionalDependency.PYTORCH)
def serialize(
self,
estimator,
model_path: str,
X_sample: Optional[
Union[
Dict,
str,
List,
Tuple,
np.ndarray,
pd.core.series.Series,
pd.core.frame.DataFrame,
]
] = None,
**kwargs,
):
"""
Exports the given Pytorch model into ONNX format.
Parameters
----------
path: str, default to None
Path to save the serialized model.
onnx_args: (tuple or torch.Tensor), default to None
Contains model inputs such that model(onnx_args) is a valid
invocation of the model. Can be structured either as: 1) ONLY A
TUPLE OF ARGUMENTS; 2) A TENSOR; 3) A TUPLE OF ARGUMENTS ENDING
WITH A DICTIONARY OF NAMED ARGUMENTS
X_sample: Union[list, tuple, pd.Series, np.ndarray, pd.DataFrame]. Defaults to None.
A sample of input data that will be used to generate input schema and detect onnx_args.
kwargs:
input_names: (List[str], optional). Defaults to ["input"].
Names to assign to the input nodes of the graph, in order.
output_names: (List[str], optional). Defaults to ["output"].
Names to assign to the output nodes of the graph, in order.
dynamic_axes: (dict, optional). Defaults to None.
Specify axes of tensors as dynamic (i.e. known only at run-time).
Returns
-------
None
Nothing
Raises
------
AssertionError
if onnx module is not support by the current version of torch
ValueError
if X_sample is not provided
if path is not provided
"""
onnx_args = kwargs.get("onnx_args", None)
input_names = kwargs.get("input_names", ["input"])
output_names = kwargs.get("output_names", ["output"])
dynamic_axes = kwargs.get("dynamic_axes", None)
assert hasattr(torch, "onnx"), (
f"This version of pytorch {torch.__version__} does not appear to support onnx "
"conversion."
)
if onnx_args is None:
if X_sample is not None:
logger.warning(
"Since `onnx_args` is not provided, `onnx_args` is "
"detected from `X_sample` to export pytorch model as onnx."
)
onnx_args = X_sample
else:
raise ValueError(
"`onnx_args` can not be detected. The parameter `onnx_args` must be provided to export pytorch model as onnx."
)
if not model_path:
raise ValueError(
"The parameter `model_path` must be provided to save the model file."
)
torch.onnx.export(
estimator,
args=onnx_args,
f=model_path,
input_names=input_names,
output_names=output_names,
dynamic_axes=dynamic_axes,
)
class TensorFlowOnnxModelSerializer(OnnxModelSerializer):
"""Converts Tensorflow model into onnx format."""
def __init__(self):
super().__init__()
@runtime_dependency(module="tf2onnx", install_from=OptionalDependency.ONNX)
@runtime_dependency(
module="tensorflow",
short_name="tf",
install_from=OptionalDependency.TENSORFLOW,
)
def serialize(
self,
estimator,
model_path: str = None,
X_sample: Optional[
Union[
Dict,
str,
List,
Tuple,
np.ndarray,
pd.core.series.Series,
pd.core.frame.DataFrame,
]
] = None,
**kwargs,
):
"""
Exports the given Tensorflow model into ONNX format.
Parameters
----------
model_path: str, default to None