tributo-algorithms 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tributo_algorithms-0.1.0.dist-info/METADATA +328 -0
- tributo_algorithms-0.1.0.dist-info/RECORD +110 -0
- tributo_algorithms-0.1.0.dist-info/WHEEL +4 -0
- tributo_algorithms-0.1.0.dist-info/entry_points.txt +57 -0
- tributo_algorithms-0.1.0.dist-info/licenses/LICENSE +202 -0
- tributo_algorithms_boosting/__init__.py +42 -0
- tributo_algorithms_boosting/algorithm.py +825 -0
- tributo_algorithms_boosting/checkpointing.py +441 -0
- tributo_algorithms_boosting/contracts.py +232 -0
- tributo_algorithms_boosting/data_config.py +59 -0
- tributo_algorithms_boosting/descriptor.py +124 -0
- tributo_algorithms_boosting/lightgbm.py +511 -0
- tributo_algorithms_boosting/lightgbm_contracts.py +186 -0
- tributo_algorithms_boosting/lightgbm_descriptor.py +112 -0
- tributo_algorithms_boosting/native.py +557 -0
- tributo_algorithms_boosting/stages.py +150 -0
- tributo_algorithms_catboost/__init__.py +5 -0
- tributo_algorithms_catboost/algorithm.py +379 -0
- tributo_algorithms_catboost/contracts.py +145 -0
- tributo_algorithms_catboost/descriptor.py +121 -0
- tributo_algorithms_catboost/exporter.py +106 -0
- tributo_algorithms_catboost/flavor.py +191 -0
- tributo_algorithms_causal_core/__init__.py +41 -0
- tributo_algorithms_causal_core/algorithm.py +1193 -0
- tributo_algorithms_causal_core/contracts.py +136 -0
- tributo_algorithms_causal_core/descriptor.py +270 -0
- tributo_algorithms_causal_core/exporter.py +52 -0
- tributo_algorithms_causal_discovery/__init__.py +23 -0
- tributo_algorithms_causal_discovery/algorithm.py +526 -0
- tributo_algorithms_causal_discovery/contracts.py +97 -0
- tributo_algorithms_causal_discovery/descriptor.py +130 -0
- tributo_algorithms_causal_discovery/exporter.py +43 -0
- tributo_algorithms_causal_dowhy/__init__.py +38 -0
- tributo_algorithms_causal_dowhy/algorithm.py +325 -0
- tributo_algorithms_causal_dowhy/contracts.py +209 -0
- tributo_algorithms_causal_dowhy/descriptor.py +106 -0
- tributo_algorithms_causal_dowhy/exporter.py +43 -0
- tributo_algorithms_causal_dowhy/gcm.py +634 -0
- tributo_algorithms_causal_dowhy/gcm_descriptor.py +110 -0
- tributo_algorithms_causal_dr/__init__.py +22 -0
- tributo_algorithms_causal_dr/algorithm.py +446 -0
- tributo_algorithms_causal_dr/contracts.py +94 -0
- tributo_algorithms_causal_dr/descriptor.py +104 -0
- tributo_algorithms_causal_xlearner/__init__.py +29 -0
- tributo_algorithms_causal_xlearner/algorithm.py +448 -0
- tributo_algorithms_causal_xlearner/contracts.py +97 -0
- tributo_algorithms_causal_xlearner/descriptor.py +120 -0
- tributo_algorithms_causal_xlearner/exporter.py +432 -0
- tributo_algorithms_causal_xlearner/flavor.py +120 -0
- tributo_algorithms_causal_xlearner/model.py +116 -0
- tributo_algorithms_classical/__init__.py +41 -0
- tributo_algorithms_classical/contracts.py +139 -0
- tributo_algorithms_classical/descriptors.py +370 -0
- tributo_algorithms_classical/exporter.py +166 -0
- tributo_algorithms_classical/isolation_forest.py +172 -0
- tributo_algorithms_classical/isolation_forest_descriptor.py +122 -0
- tributo_algorithms_classical/kmeans.py +315 -0
- tributo_algorithms_classical/kmeans_descriptor.py +147 -0
- tributo_algorithms_classical/linear_regression.py +206 -0
- tributo_algorithms_classical/logistic_regression.py +238 -0
- tributo_algorithms_classical/models.py +28 -0
- tributo_algorithms_classical/multinomial_nb.py +643 -0
- tributo_algorithms_classical/multinomial_nb_descriptor.py +183 -0
- tributo_algorithms_classical/pca.py +187 -0
- tributo_algorithms_classical/pca_descriptor.py +111 -0
- tributo_algorithms_classical/random_forest.py +304 -0
- tributo_algorithms_classical/sgd.py +331 -0
- tributo_algorithms_classical/sgd_contracts.py +121 -0
- tributo_algorithms_classical/sgd_descriptor.py +143 -0
- tributo_algorithms_classical/unsupervised_contracts.py +198 -0
- tributo_algorithms_classical/unsupervised_exporter.py +427 -0
- tributo_algorithms_classical/unsupervised_models.py +90 -0
- tributo_algorithms_graph_pyg/__init__.py +37 -0
- tributo_algorithms_graph_pyg/algorithm.py +883 -0
- tributo_algorithms_graph_pyg/contracts.py +260 -0
- tributo_algorithms_graph_pyg/descriptor.py +201 -0
- tributo_algorithms_multistage_torch/__init__.py +40 -0
- tributo_algorithms_multistage_torch/algorithm.py +532 -0
- tributo_algorithms_multistage_torch/contracts.py +220 -0
- tributo_algorithms_multistage_torch/descriptor.py +146 -0
- tributo_algorithms_multistage_torch/pretrain.py +570 -0
- tributo_algorithms_multistage_torch/pretrain_descriptor.py +153 -0
- tributo_algorithms_recsys_torch/__init__.py +35 -0
- tributo_algorithms_recsys_torch/contracts.py +295 -0
- tributo_algorithms_recsys_torch/descriptor.py +136 -0
- tributo_algorithms_recsys_torch/jagged.py +707 -0
- tributo_algorithms_recsys_torch/jagged_descriptor.py +130 -0
- tributo_algorithms_recsys_torch/recipe.py +192 -0
- tributo_algorithms_representation/__init__.py +20 -0
- tributo_algorithms_representation/contracts.py +117 -0
- tributo_algorithms_representation/descriptor.py +137 -0
- tributo_algorithms_representation/recipe.py +162 -0
- tributo_algorithms_tabular_torch/__init__.py +46 -0
- tributo_algorithms_tabular_torch/contracts.py +228 -0
- tributo_algorithms_tabular_torch/descriptor.py +223 -0
- tributo_algorithms_tabular_torch/priors.py +216 -0
- tributo_algorithms_tabular_torch/pu_metrics.py +269 -0
- tributo_algorithms_tabular_torch/pu_reducer.py +129 -0
- tributo_algorithms_tabular_torch/recipe.py +294 -0
- tributo_algorithms_timeseries/__init__.py +36 -0
- tributo_algorithms_timeseries/contracts.py +120 -0
- tributo_algorithms_timeseries/descriptor.py +137 -0
- tributo_algorithms_timeseries/recipe.py +195 -0
- tributo_algorithms_timeseries/rnn_contracts.py +170 -0
- tributo_algorithms_timeseries/rnn_descriptor.py +167 -0
- tributo_algorithms_timeseries/rnn_recipe.py +223 -0
- tributo_algorithms_transformers_nlp/__init__.py +20 -0
- tributo_algorithms_transformers_nlp/contracts.py +109 -0
- tributo_algorithms_transformers_nlp/descriptor.py +137 -0
- tributo_algorithms_transformers_nlp/recipe.py +235 -0
|
@@ -0,0 +1,557 @@
|
|
|
1
|
+
"""Official XGBoost exporters, validator, and safe native Bundle flavor."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import time
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any, ClassVar, Mapping, cast
|
|
10
|
+
|
|
11
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
12
|
+
from tributo.exceptions import ModelLoadError, UnsupportedArtifactFormat
|
|
13
|
+
from tributo.exporting.errors import sanitize_error_message
|
|
14
|
+
from tributo.exporting.models import (
|
|
15
|
+
ArtifactDraft,
|
|
16
|
+
DraftFile,
|
|
17
|
+
ExportContext,
|
|
18
|
+
ExportSource,
|
|
19
|
+
FailureInfo,
|
|
20
|
+
PlannedTarget,
|
|
21
|
+
ProducerInfo,
|
|
22
|
+
ResolvedArtifact,
|
|
23
|
+
SupportRequest,
|
|
24
|
+
SupportResult,
|
|
25
|
+
ValidationResult,
|
|
26
|
+
ValidatorBinding,
|
|
27
|
+
)
|
|
28
|
+
from tributo.exporting.runtime import SECURITY_MODE_SAFE, BundleModel
|
|
29
|
+
|
|
30
|
+
from tributo_algorithms_boosting.contracts import _validate_training_metadata
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _check_training_metadata(booster: Any, value: object) -> dict[str, Any]:
|
|
34
|
+
metadata = _validate_training_metadata(value)
|
|
35
|
+
if booster.num_boosted_rounds() != metadata["model_rounds"]:
|
|
36
|
+
raise ValueError("XGBoost training metadata model rounds drifted")
|
|
37
|
+
if "best_iteration" in metadata and (
|
|
38
|
+
booster.best_iteration != metadata["best_iteration"]
|
|
39
|
+
or not math.isclose(booster.best_score, metadata["best_score"], rel_tol=1e-12)
|
|
40
|
+
):
|
|
41
|
+
raise ValueError("XGBoost training metadata best model drifted")
|
|
42
|
+
return metadata
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _training_metadata_files(
|
|
46
|
+
context: ExportContext, source: ExportSource
|
|
47
|
+
) -> tuple[DraftFile, ...]:
|
|
48
|
+
value = source.metadata.get("training_metadata")
|
|
49
|
+
if value is None:
|
|
50
|
+
return ()
|
|
51
|
+
metadata = _check_training_metadata(source.model_object, value)
|
|
52
|
+
(context.artifact_dir / "training_metadata.json").write_text(
|
|
53
|
+
json.dumps(metadata, sort_keys=True, allow_nan=False), encoding="utf-8"
|
|
54
|
+
)
|
|
55
|
+
return (DraftFile(relative_path="training_metadata.json", role="config"),)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class XGBoostONNXOptions(BaseModel):
|
|
59
|
+
model_config = ConfigDict(extra="forbid")
|
|
60
|
+
opset: int = Field(default=15, ge=12, le=21)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class XGBoostNativeOptions(BaseModel):
|
|
64
|
+
model_config = ConfigDict(extra="forbid")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class XGBoostValidationOptions(BaseModel):
|
|
68
|
+
model_config = ConfigDict(extra="forbid")
|
|
69
|
+
num_samples: int = Field(default=2, ge=1, le=128)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class _NativeExplanation:
|
|
74
|
+
values: Any
|
|
75
|
+
data: Any
|
|
76
|
+
base_values: Any
|
|
77
|
+
model_outputs: Any
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class _NativeTreeExplainer:
|
|
81
|
+
def __init__(self, model: _XGBoostModel, feature_names: tuple[str, ...]) -> None:
|
|
82
|
+
self.model = model
|
|
83
|
+
self.feature_names = feature_names
|
|
84
|
+
|
|
85
|
+
def __call__(
|
|
86
|
+
self,
|
|
87
|
+
values: object,
|
|
88
|
+
*,
|
|
89
|
+
check_additivity: bool = False,
|
|
90
|
+
) -> _NativeExplanation:
|
|
91
|
+
del check_additivity
|
|
92
|
+
import numpy as np
|
|
93
|
+
|
|
94
|
+
data = np.asarray(values, dtype=np.float32)
|
|
95
|
+
if data.ndim != 2 or (
|
|
96
|
+
self.feature_names and len(self.feature_names) != data.shape[1]
|
|
97
|
+
):
|
|
98
|
+
raise ValueError("XGBoost attribution input shape is invalid")
|
|
99
|
+
feature_types = tuple(self.model.booster.feature_types or ())
|
|
100
|
+
matrix = self.model.xgboost.DMatrix(
|
|
101
|
+
data,
|
|
102
|
+
feature_names=list(self.feature_names) or None,
|
|
103
|
+
feature_types=list(feature_types) or None,
|
|
104
|
+
)
|
|
105
|
+
contributions = np.asarray(
|
|
106
|
+
self.model.booster.predict(
|
|
107
|
+
matrix,
|
|
108
|
+
pred_contribs=True,
|
|
109
|
+
approx_contribs=False,
|
|
110
|
+
strict_shape=True,
|
|
111
|
+
)
|
|
112
|
+
)
|
|
113
|
+
outputs = np.asarray(
|
|
114
|
+
self.model.booster.predict(
|
|
115
|
+
matrix,
|
|
116
|
+
output_margin=True,
|
|
117
|
+
strict_shape=True,
|
|
118
|
+
)
|
|
119
|
+
)
|
|
120
|
+
expected = (data.shape[0], outputs.shape[1], data.shape[1] + 1)
|
|
121
|
+
if outputs.ndim != 2 or contributions.shape != expected:
|
|
122
|
+
raise ValueError("XGBoost attribution output shape is invalid")
|
|
123
|
+
return _NativeExplanation(
|
|
124
|
+
values=np.transpose(contributions[:, :, :-1], (0, 2, 1)),
|
|
125
|
+
data=data,
|
|
126
|
+
base_values=contributions[:, :, -1],
|
|
127
|
+
model_outputs=outputs,
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class OfficialXGBoostONNXExporter:
|
|
132
|
+
api_version: ClassVar[int] = 2
|
|
133
|
+
exporter_id: ClassVar[str] = "official-xgboost-onnx-v1"
|
|
134
|
+
priority: ClassVar[int] = 100
|
|
135
|
+
output_format: ClassVar[str] = "onnx"
|
|
136
|
+
output_flavor_id: ClassVar[str] = "onnx-runtime-v1"
|
|
137
|
+
source_kinds: ClassVar[tuple[str, ...]] = ("xgboost_result",)
|
|
138
|
+
options_model: ClassVar[type[BaseModel]] = XGBoostONNXOptions
|
|
139
|
+
validator_bindings: ClassVar[tuple[ValidatorBinding, ...]] = (
|
|
140
|
+
ValidatorBinding(validator_id="structure-v1", required=True),
|
|
141
|
+
ValidatorBinding(validator_id="onnx-runtime-v1", required=True),
|
|
142
|
+
)
|
|
143
|
+
mutates_source: ClassVar[bool] = False
|
|
144
|
+
upstream_requirements: ClassVar[tuple[Any, ...]] = ()
|
|
145
|
+
|
|
146
|
+
@classmethod
|
|
147
|
+
def supports(cls, request: SupportRequest) -> SupportResult:
|
|
148
|
+
objective = str(request.source_metadata.get("objective", ""))
|
|
149
|
+
supported = request.source_kind == "xgboost_result" and (
|
|
150
|
+
objective.startswith(("binary:", "multi:"))
|
|
151
|
+
or objective == "reg:squarederror"
|
|
152
|
+
)
|
|
153
|
+
return SupportResult(
|
|
154
|
+
supported=supported,
|
|
155
|
+
code="OK" if supported else "UNSUPPORTED_XGBOOST_SOURCE",
|
|
156
|
+
reason=(
|
|
157
|
+
"numeric XGBoost source is supported"
|
|
158
|
+
if supported
|
|
159
|
+
else "official XGBoost ONNX requires a supported numeric objective"
|
|
160
|
+
),
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
def export(
|
|
164
|
+
self,
|
|
165
|
+
context: ExportContext,
|
|
166
|
+
source: ExportSource,
|
|
167
|
+
upstream: Mapping[str, ResolvedArtifact],
|
|
168
|
+
target: PlannedTarget,
|
|
169
|
+
) -> ArtifactDraft:
|
|
170
|
+
del upstream
|
|
171
|
+
import onnxmltools
|
|
172
|
+
import xgboost
|
|
173
|
+
from onnxmltools.convert.common.data_types import FloatTensorType
|
|
174
|
+
|
|
175
|
+
booster = cast(xgboost.Booster, source.model_object)
|
|
176
|
+
feature_names = tuple(
|
|
177
|
+
str(name) for name in source.feature_schema.get("feature_names", ())
|
|
178
|
+
)
|
|
179
|
+
if not feature_names:
|
|
180
|
+
feature_names = tuple(
|
|
181
|
+
f"f{index}" for index in range(int(booster.num_features()))
|
|
182
|
+
)
|
|
183
|
+
# A raw Booster is classified heuristically from its cover values by
|
|
184
|
+
# ONNXMLTools. A short best prefix can have integral covers even for
|
|
185
|
+
# classification, so preserve the declared objective explicitly.
|
|
186
|
+
objective = json.loads(booster.save_config())["learner"]["objective"]["name"]
|
|
187
|
+
model: Any = (
|
|
188
|
+
xgboost.XGBClassifier()
|
|
189
|
+
if objective.startswith(("binary:", "multi:"))
|
|
190
|
+
else xgboost.XGBRegressor()
|
|
191
|
+
)
|
|
192
|
+
model.load_model(bytearray(booster.save_raw(raw_format="ubj")))
|
|
193
|
+
converted = onnxmltools.convert_xgboost(
|
|
194
|
+
model,
|
|
195
|
+
initial_types=[
|
|
196
|
+
("float_input", FloatTensorType([None, len(feature_names)]))
|
|
197
|
+
],
|
|
198
|
+
target_opset=int(target.typed_options.get("opset", 15)),
|
|
199
|
+
)
|
|
200
|
+
converted.graph.name = "tributo-official-xgboost"
|
|
201
|
+
path = context.artifact_dir / "model.onnx"
|
|
202
|
+
path.write_bytes(converted.SerializeToString())
|
|
203
|
+
return ArtifactDraft(
|
|
204
|
+
name=target.target.name,
|
|
205
|
+
format="onnx",
|
|
206
|
+
flavor_id="onnx-runtime-v1",
|
|
207
|
+
files=(
|
|
208
|
+
DraftFile(relative_path="model.onnx", role="model"),
|
|
209
|
+
*_training_metadata_files(context, source),
|
|
210
|
+
),
|
|
211
|
+
entrypoint="model.onnx",
|
|
212
|
+
producer=ProducerInfo(
|
|
213
|
+
exporter_id=self.exporter_id,
|
|
214
|
+
framework_versions={
|
|
215
|
+
"xgboost": xgboost.__version__,
|
|
216
|
+
"onnxmltools": getattr(onnxmltools, "__version__", "unknown"),
|
|
217
|
+
},
|
|
218
|
+
effective_options=dict(target.typed_options),
|
|
219
|
+
),
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class OfficialXGBoostUBJExporter:
|
|
224
|
+
api_version: ClassVar[int] = 2
|
|
225
|
+
exporter_id: ClassVar[str] = "official-xgboost-ubj-v1"
|
|
226
|
+
priority: ClassVar[int] = 100
|
|
227
|
+
output_format: ClassVar[str] = "ubj"
|
|
228
|
+
output_flavor_id: ClassVar[str] = "official-xgboost-native-v1"
|
|
229
|
+
source_kinds: ClassVar[tuple[str, ...]] = ("xgboost_result",)
|
|
230
|
+
options_model: ClassVar[type[BaseModel]] = XGBoostNativeOptions
|
|
231
|
+
validator_bindings: ClassVar[tuple[ValidatorBinding, ...]] = (
|
|
232
|
+
ValidatorBinding(validator_id="structure-v1", required=True),
|
|
233
|
+
ValidatorBinding(
|
|
234
|
+
validator_id="official-xgboost-native-runtime-v1", required=True
|
|
235
|
+
),
|
|
236
|
+
)
|
|
237
|
+
mutates_source: ClassVar[bool] = False
|
|
238
|
+
upstream_requirements: ClassVar[tuple[Any, ...]] = ()
|
|
239
|
+
|
|
240
|
+
@classmethod
|
|
241
|
+
def supports(cls, request: SupportRequest) -> SupportResult:
|
|
242
|
+
supported = request.source_kind == "xgboost_result"
|
|
243
|
+
return SupportResult(
|
|
244
|
+
supported=supported,
|
|
245
|
+
code="OK" if supported else "UNSUPPORTED_SOURCE_KIND",
|
|
246
|
+
reason=(
|
|
247
|
+
"XGBoost Booster source is supported"
|
|
248
|
+
if supported
|
|
249
|
+
else "official UBJ exporter requires xgboost_result"
|
|
250
|
+
),
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
def export(
|
|
254
|
+
self,
|
|
255
|
+
context: ExportContext,
|
|
256
|
+
source: ExportSource,
|
|
257
|
+
upstream: Mapping[str, ResolvedArtifact],
|
|
258
|
+
target: PlannedTarget,
|
|
259
|
+
) -> ArtifactDraft:
|
|
260
|
+
del upstream
|
|
261
|
+
import xgboost
|
|
262
|
+
|
|
263
|
+
booster = cast(xgboost.Booster, source.model_object)
|
|
264
|
+
(context.artifact_dir / "model.ubj").write_bytes(
|
|
265
|
+
bytes(booster.save_raw(raw_format="ubj"))
|
|
266
|
+
)
|
|
267
|
+
files = [DraftFile(relative_path="model.ubj", role="model")]
|
|
268
|
+
files.extend(_training_metadata_files(context, source))
|
|
269
|
+
feature_names = tuple(
|
|
270
|
+
booster.feature_names or source.feature_schema.get("feature_names", ())
|
|
271
|
+
)
|
|
272
|
+
if feature_names:
|
|
273
|
+
(context.artifact_dir / "feature_names.json").write_text(
|
|
274
|
+
json.dumps(feature_names), encoding="utf-8"
|
|
275
|
+
)
|
|
276
|
+
files.append(DraftFile(relative_path="feature_names.json", role="config"))
|
|
277
|
+
return ArtifactDraft(
|
|
278
|
+
name=target.target.name,
|
|
279
|
+
format="ubj",
|
|
280
|
+
flavor_id="official-xgboost-native-v1",
|
|
281
|
+
files=tuple(files),
|
|
282
|
+
entrypoint="model.ubj",
|
|
283
|
+
producer=ProducerInfo(
|
|
284
|
+
exporter_id=self.exporter_id,
|
|
285
|
+
framework_versions={"xgboost": xgboost.__version__},
|
|
286
|
+
effective_options=dict(target.typed_options),
|
|
287
|
+
),
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
class OfficialXGBoostNativeValidator:
|
|
292
|
+
api_version: ClassVar[int] = 1
|
|
293
|
+
validator_id: ClassVar[str] = "official-xgboost-native-runtime-v1"
|
|
294
|
+
options_model: ClassVar[type[BaseModel]] = XGBoostValidationOptions
|
|
295
|
+
|
|
296
|
+
def validate(
|
|
297
|
+
self,
|
|
298
|
+
source: ExportSource,
|
|
299
|
+
artifact: ResolvedArtifact,
|
|
300
|
+
upstream: Mapping[str, ResolvedArtifact],
|
|
301
|
+
options: BaseModel,
|
|
302
|
+
) -> ValidationResult:
|
|
303
|
+
del upstream
|
|
304
|
+
try:
|
|
305
|
+
import numpy as np
|
|
306
|
+
import xgboost
|
|
307
|
+
|
|
308
|
+
source_booster = source.model_object
|
|
309
|
+
if not isinstance(source_booster, xgboost.Booster):
|
|
310
|
+
raise TypeError("official XGBoost validation requires a Booster")
|
|
311
|
+
started = time.perf_counter()
|
|
312
|
+
loaded = xgboost.Booster()
|
|
313
|
+
loaded.load_model(str(artifact.entrypoint_path))
|
|
314
|
+
metadata_path = artifact.path_for("training_metadata.json")
|
|
315
|
+
expected_metadata = source.metadata.get("training_metadata")
|
|
316
|
+
if expected_metadata is not None and not metadata_path.is_file():
|
|
317
|
+
raise ValueError("XGBoost training metadata sidecar is missing")
|
|
318
|
+
if metadata_path.is_file():
|
|
319
|
+
metadata = _check_training_metadata(
|
|
320
|
+
loaded, json.loads(metadata_path.read_text(encoding="utf-8"))
|
|
321
|
+
)
|
|
322
|
+
if (
|
|
323
|
+
expected_metadata is not None
|
|
324
|
+
and metadata
|
|
325
|
+
!= _check_training_metadata(source_booster, expected_metadata)
|
|
326
|
+
):
|
|
327
|
+
raise ValueError("XGBoost training metadata sidecar drifted")
|
|
328
|
+
features = int(loaded.num_features())
|
|
329
|
+
if features != int(source_booster.num_features()) or features < 1:
|
|
330
|
+
raise ValueError("reloaded Booster feature count drifted")
|
|
331
|
+
values = np.zeros(
|
|
332
|
+
(int(getattr(options, "num_samples", 2)), features),
|
|
333
|
+
dtype=np.float32,
|
|
334
|
+
)
|
|
335
|
+
source_margin = source_booster.predict(
|
|
336
|
+
xgboost.DMatrix(values, feature_names=source_booster.feature_names),
|
|
337
|
+
output_margin=True,
|
|
338
|
+
strict_shape=True,
|
|
339
|
+
)
|
|
340
|
+
loaded_margin = loaded.predict(
|
|
341
|
+
xgboost.DMatrix(values, feature_names=loaded.feature_names),
|
|
342
|
+
output_margin=True,
|
|
343
|
+
strict_shape=True,
|
|
344
|
+
)
|
|
345
|
+
if not np.allclose(source_margin, loaded_margin, rtol=1e-6, atol=1e-7):
|
|
346
|
+
raise ValueError("reloaded Booster predictions drifted")
|
|
347
|
+
return ValidationResult(
|
|
348
|
+
validator_id=self.validator_id,
|
|
349
|
+
status="passed",
|
|
350
|
+
metrics={
|
|
351
|
+
"feature_count": float(features),
|
|
352
|
+
"load_seconds": round(time.perf_counter() - started, 6),
|
|
353
|
+
},
|
|
354
|
+
)
|
|
355
|
+
except Exception as exc:
|
|
356
|
+
return ValidationResult(
|
|
357
|
+
validator_id=self.validator_id,
|
|
358
|
+
status="failed",
|
|
359
|
+
failure=FailureInfo(
|
|
360
|
+
code=type(exc).__name__,
|
|
361
|
+
category="validation",
|
|
362
|
+
message=sanitize_error_message(str(exc))[:4096],
|
|
363
|
+
),
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
class OfficialXGBoostNativeFlavor:
|
|
368
|
+
api_version: ClassVar[int] = 1
|
|
369
|
+
flavor_id: ClassVar[str] = "official-xgboost-native-v1"
|
|
370
|
+
supported_formats: ClassVar[tuple[str, ...]] = ("ubj",)
|
|
371
|
+
batch_supported: ClassVar[bool] = True
|
|
372
|
+
serveable: ClassVar[bool] = True
|
|
373
|
+
security_mode: ClassVar[str] = SECURITY_MODE_SAFE
|
|
374
|
+
signature_required: ClassVar[bool] = True
|
|
375
|
+
required_dependencies: ClassVar[tuple[str, ...]] = ("xgboost",)
|
|
376
|
+
operations: ClassVar[tuple[str, ...]] = (
|
|
377
|
+
"prediction.batch",
|
|
378
|
+
"prediction.online",
|
|
379
|
+
)
|
|
380
|
+
conditional_operations: ClassVar[tuple[str, ...]] = ()
|
|
381
|
+
|
|
382
|
+
def load(
|
|
383
|
+
self,
|
|
384
|
+
artifact: ResolvedArtifact,
|
|
385
|
+
*,
|
|
386
|
+
role: str,
|
|
387
|
+
unsafe: bool = False,
|
|
388
|
+
architecture_id: str | None = None,
|
|
389
|
+
) -> BundleModel:
|
|
390
|
+
del role, unsafe
|
|
391
|
+
if architecture_id not in (None, "xgboost"):
|
|
392
|
+
raise UnsupportedArtifactFormat(
|
|
393
|
+
f"official XGBoost flavor cannot load {architecture_id!r}"
|
|
394
|
+
)
|
|
395
|
+
try:
|
|
396
|
+
import xgboost
|
|
397
|
+
except ImportError as exc:
|
|
398
|
+
raise ModelLoadError("official XGBoost flavor requires xgboost") from exc
|
|
399
|
+
booster = xgboost.Booster()
|
|
400
|
+
try:
|
|
401
|
+
booster.load_model(str(artifact.entrypoint_path))
|
|
402
|
+
except Exception as exc:
|
|
403
|
+
raise ModelLoadError(
|
|
404
|
+
f"failed to load official XGBoost model ({type(exc).__name__})"
|
|
405
|
+
) from None
|
|
406
|
+
sidecar = artifact.path_for("feature_names.json")
|
|
407
|
+
if sidecar.is_file():
|
|
408
|
+
raw_names = json.loads(sidecar.read_text(encoding="utf-8"))
|
|
409
|
+
if not isinstance(raw_names, list) or not all(
|
|
410
|
+
isinstance(name, str) for name in raw_names
|
|
411
|
+
):
|
|
412
|
+
raise ModelLoadError("XGBoost feature-name sidecar is invalid")
|
|
413
|
+
if booster.feature_names and tuple(booster.feature_names) != tuple(
|
|
414
|
+
raw_names
|
|
415
|
+
):
|
|
416
|
+
raise ModelLoadError("XGBoost feature-name sidecar drifted")
|
|
417
|
+
booster.feature_names = list(raw_names)
|
|
418
|
+
return cast(BundleModel, _XGBoostModel(booster, xgboost))
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
class _XGBoostModel:
|
|
422
|
+
def __init__(self, booster: Any, xgboost: Any) -> None:
|
|
423
|
+
self.booster = booster
|
|
424
|
+
self.xgboost = xgboost
|
|
425
|
+
config = json.loads(booster.save_config())["learner"]
|
|
426
|
+
self.objective = str(config["objective"]["name"])
|
|
427
|
+
self.features = int(booster.num_features())
|
|
428
|
+
self.classification = self.objective.startswith(("binary:", "multi:"))
|
|
429
|
+
self.classes = max(2, int(config["learner_model_param"]["num_class"]))
|
|
430
|
+
|
|
431
|
+
@property
|
|
432
|
+
def input_names(self) -> tuple[str, ...]:
|
|
433
|
+
return ("float_input",)
|
|
434
|
+
|
|
435
|
+
@property
|
|
436
|
+
def output_names(self) -> tuple[str, ...]:
|
|
437
|
+
return ("label", "probabilities") if self.classification else ("prediction",)
|
|
438
|
+
|
|
439
|
+
@property
|
|
440
|
+
def input_dtypes(self) -> tuple[str, ...]:
|
|
441
|
+
return ("float32",)
|
|
442
|
+
|
|
443
|
+
@property
|
|
444
|
+
def output_dtypes(self) -> tuple[str, ...]:
|
|
445
|
+
return ("int64", "float32") if self.classification else ("float32",)
|
|
446
|
+
|
|
447
|
+
@property
|
|
448
|
+
def input_shapes(self) -> tuple[tuple[int | None, ...], ...]:
|
|
449
|
+
return ((None, self.features),)
|
|
450
|
+
|
|
451
|
+
@property
|
|
452
|
+
def output_shapes(self) -> tuple[tuple[int | None, ...], ...]:
|
|
453
|
+
return ((None,), (None, self.classes)) if self.classification else ((None, 1),)
|
|
454
|
+
|
|
455
|
+
def predict(self, inputs: dict[str, Any]) -> dict[str, Any]:
|
|
456
|
+
import numpy as np
|
|
457
|
+
|
|
458
|
+
matrix = self.xgboost.DMatrix(
|
|
459
|
+
np.asarray(inputs["float_input"], dtype=np.float32),
|
|
460
|
+
feature_names=self.booster.feature_names,
|
|
461
|
+
)
|
|
462
|
+
values = np.asarray(self.booster.predict(matrix), dtype=np.float32)
|
|
463
|
+
if not self.classification:
|
|
464
|
+
return {"prediction": values.reshape(-1, 1)}
|
|
465
|
+
if self.objective.startswith("multi:"):
|
|
466
|
+
probabilities = values.reshape(-1, self.classes)
|
|
467
|
+
else:
|
|
468
|
+
positive = values.reshape(-1)
|
|
469
|
+
probabilities = np.column_stack((1.0 - positive, positive)).astype(
|
|
470
|
+
np.float32, copy=False
|
|
471
|
+
)
|
|
472
|
+
return {
|
|
473
|
+
"label": probabilities.argmax(axis=1).astype(np.int64),
|
|
474
|
+
"probabilities": probabilities,
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
@property
|
|
478
|
+
def native_attribution_id(self) -> str | None:
|
|
479
|
+
config = json.loads(self.booster.save_config())["learner"]
|
|
480
|
+
booster_kind = str(config["gradient_booster"]["name"])
|
|
481
|
+
supported_objective = self.objective.startswith(("binary:", "multi:")) or (
|
|
482
|
+
self.objective in {"reg:squarederror", "reg:logistic"}
|
|
483
|
+
)
|
|
484
|
+
return (
|
|
485
|
+
"xgboost-tree-shap-v1"
|
|
486
|
+
if booster_kind in {"gbtree", "dart"} and supported_objective
|
|
487
|
+
else None
|
|
488
|
+
)
|
|
489
|
+
|
|
490
|
+
@property
|
|
491
|
+
def native_model_object(self) -> Any:
|
|
492
|
+
return self.booster
|
|
493
|
+
|
|
494
|
+
@property
|
|
495
|
+
def native_feature_names(self) -> tuple[str, ...]:
|
|
496
|
+
return tuple(self.booster.feature_names or ())
|
|
497
|
+
|
|
498
|
+
@property
|
|
499
|
+
def native_objective(self) -> str | None:
|
|
500
|
+
return self.objective
|
|
501
|
+
|
|
502
|
+
def native_attribution_support(self, request: Any) -> Any:
|
|
503
|
+
from tributo.explainability.protocols import SupportDecision
|
|
504
|
+
|
|
505
|
+
if self.native_attribution_id is None:
|
|
506
|
+
return SupportDecision(
|
|
507
|
+
supported=False,
|
|
508
|
+
reason="XGBoost Booster does not support exact TreeSHAP",
|
|
509
|
+
backend="tree",
|
|
510
|
+
exactness="exact",
|
|
511
|
+
)
|
|
512
|
+
if request.output_target not in {"model_output", "raw", "raw_margin"}:
|
|
513
|
+
return SupportDecision(
|
|
514
|
+
supported=False,
|
|
515
|
+
reason="official native XGBoost attribution supports raw outputs",
|
|
516
|
+
backend="tree",
|
|
517
|
+
exactness="exact",
|
|
518
|
+
)
|
|
519
|
+
if request.output_selection == "predicted" and not self.classification:
|
|
520
|
+
return SupportDecision(
|
|
521
|
+
supported=False,
|
|
522
|
+
reason="predicted output selection requires classification",
|
|
523
|
+
backend="tree",
|
|
524
|
+
exactness="exact",
|
|
525
|
+
)
|
|
526
|
+
return SupportDecision(supported=True, backend="tree", exactness="exact")
|
|
527
|
+
|
|
528
|
+
def prepare_native_attribution(
|
|
529
|
+
self,
|
|
530
|
+
request: Any,
|
|
531
|
+
*,
|
|
532
|
+
feature_names: tuple[str, ...],
|
|
533
|
+
reference_data: Any,
|
|
534
|
+
) -> Any:
|
|
535
|
+
from tributo.explainability.protocols import PreparedExplainer
|
|
536
|
+
|
|
537
|
+
del reference_data
|
|
538
|
+
decision = self.native_attribution_support(request)
|
|
539
|
+
if not decision.supported:
|
|
540
|
+
raise ValueError(decision.reason)
|
|
541
|
+
names = feature_names or self.native_feature_names
|
|
542
|
+
if names and len(names) != self.features:
|
|
543
|
+
raise ValueError("XGBoost feature names do not match model width")
|
|
544
|
+
return PreparedExplainer(
|
|
545
|
+
backend="tree",
|
|
546
|
+
exactness="exact",
|
|
547
|
+
explain=_NativeTreeExplainer(self, names),
|
|
548
|
+
feature_names=names,
|
|
549
|
+
)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
__all__ = [
|
|
553
|
+
"OfficialXGBoostNativeFlavor",
|
|
554
|
+
"OfficialXGBoostNativeValidator",
|
|
555
|
+
"OfficialXGBoostONNXExporter",
|
|
556
|
+
"OfficialXGBoostUBJExporter",
|
|
557
|
+
]
|