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,441 @@
|
|
|
1
|
+
"""Invocation-local XGBoost state and public framework callback integration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import importlib.metadata
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
import platform
|
|
10
|
+
from collections.abc import Callable, Mapping
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, cast
|
|
13
|
+
|
|
14
|
+
from tributo.algorithms.api import AlgorithmExecutionError
|
|
15
|
+
|
|
16
|
+
REPORT_KEY = "_tributo_xgboost_recovery"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def recovery_identity(config: Mapping[str, Any], world_size: int) -> dict[str, Any]:
|
|
20
|
+
return {
|
|
21
|
+
"invocation": config["invocation"],
|
|
22
|
+
"plan_id": config["plan_id"],
|
|
23
|
+
"world_size": world_size,
|
|
24
|
+
"feature_names": list(config["feature_names"]),
|
|
25
|
+
"label_name": config["label_name"],
|
|
26
|
+
"input_roles": sorted(config["input_roles"]),
|
|
27
|
+
"versions": {
|
|
28
|
+
**{
|
|
29
|
+
name: importlib.metadata.version(name)
|
|
30
|
+
for name in ("tributo", "tributo-algorithms", "ray", "xgboost")
|
|
31
|
+
},
|
|
32
|
+
"python": platform.python_version(),
|
|
33
|
+
},
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def write_checkpoint(
|
|
38
|
+
root: Path,
|
|
39
|
+
*,
|
|
40
|
+
full_model: bytes,
|
|
41
|
+
state: Any,
|
|
42
|
+
identity: Mapping[str, Any],
|
|
43
|
+
selected: bytes | None = None,
|
|
44
|
+
metadata: Mapping[str, Any] | None = None,
|
|
45
|
+
) -> None:
|
|
46
|
+
(root / "training.ubj").write_bytes(full_model)
|
|
47
|
+
(root / "feature_names.json").write_text(
|
|
48
|
+
json.dumps(identity["feature_names"]), encoding="utf-8"
|
|
49
|
+
)
|
|
50
|
+
if selected is not None:
|
|
51
|
+
(root / "model.ubj").write_bytes(selected)
|
|
52
|
+
(root / "training_metadata.json").write_text(
|
|
53
|
+
json.dumps(metadata, sort_keys=True, allow_nan=False), encoding="utf-8"
|
|
54
|
+
)
|
|
55
|
+
payload = {
|
|
56
|
+
"schema_version": 1,
|
|
57
|
+
"identity": dict(identity),
|
|
58
|
+
"phase": "final" if selected is not None else "training",
|
|
59
|
+
"completed_rounds": state.completed,
|
|
60
|
+
"metric": state.metric,
|
|
61
|
+
"scores": state.scores,
|
|
62
|
+
"stopped": state.stopped,
|
|
63
|
+
"patience": state.patience,
|
|
64
|
+
"maximize": state.maximize,
|
|
65
|
+
"best_iteration": state.best_iteration,
|
|
66
|
+
"best_score": state.best_score,
|
|
67
|
+
"last_metrics": state.last_metrics,
|
|
68
|
+
"training_sha256": hashlib.sha256(full_model).hexdigest(),
|
|
69
|
+
"selected_sha256": hashlib.sha256(selected).hexdigest()
|
|
70
|
+
if selected is not None
|
|
71
|
+
else None,
|
|
72
|
+
}
|
|
73
|
+
(root / "recovery_state.json").write_text(
|
|
74
|
+
json.dumps(payload, sort_keys=True, allow_nan=False), encoding="utf-8"
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def read_checkpoint(
|
|
79
|
+
root: Path,
|
|
80
|
+
*,
|
|
81
|
+
identity: Mapping[str, Any],
|
|
82
|
+
rounds: int,
|
|
83
|
+
patience: int | None,
|
|
84
|
+
maximize: bool | None = None,
|
|
85
|
+
) -> tuple[bytes, dict[str, Any]]:
|
|
86
|
+
"""Fail closed on a corrupt, foreign, or internally inconsistent checkpoint."""
|
|
87
|
+
import xgboost
|
|
88
|
+
|
|
89
|
+
try:
|
|
90
|
+
state = json.loads((root / "recovery_state.json").read_text(encoding="utf-8"))
|
|
91
|
+
fields = {
|
|
92
|
+
"schema_version",
|
|
93
|
+
"identity",
|
|
94
|
+
"phase",
|
|
95
|
+
"completed_rounds",
|
|
96
|
+
"metric",
|
|
97
|
+
"scores",
|
|
98
|
+
"stopped",
|
|
99
|
+
"last_metrics",
|
|
100
|
+
"training_sha256",
|
|
101
|
+
"selected_sha256",
|
|
102
|
+
"patience",
|
|
103
|
+
"maximize",
|
|
104
|
+
"best_iteration",
|
|
105
|
+
"best_score",
|
|
106
|
+
}
|
|
107
|
+
if (
|
|
108
|
+
not isinstance(state, dict)
|
|
109
|
+
or set(state) != fields
|
|
110
|
+
or type(state["schema_version"]) is not int
|
|
111
|
+
or state["schema_version"] != 1
|
|
112
|
+
or state["identity"] != dict(identity)
|
|
113
|
+
or state["phase"] not in {"training", "final"}
|
|
114
|
+
or type(state["completed_rounds"]) is not int
|
|
115
|
+
or not 1 <= state["completed_rounds"] <= rounds
|
|
116
|
+
or type(state["stopped"]) is not bool
|
|
117
|
+
):
|
|
118
|
+
raise ValueError("identity, version, phase or rounds mismatch")
|
|
119
|
+
scores = state["scores"]
|
|
120
|
+
if not isinstance(scores, list) or any(
|
|
121
|
+
not isinstance(score, (float, int))
|
|
122
|
+
or isinstance(score, bool)
|
|
123
|
+
or not math.isfinite(score)
|
|
124
|
+
for score in scores
|
|
125
|
+
):
|
|
126
|
+
raise ValueError("selection scores are invalid")
|
|
127
|
+
if patience is not None:
|
|
128
|
+
if (
|
|
129
|
+
len(scores) != state["completed_rounds"]
|
|
130
|
+
or not isinstance(state["metric"], str)
|
|
131
|
+
or not state["metric"]
|
|
132
|
+
):
|
|
133
|
+
raise ValueError("selection history is incomplete")
|
|
134
|
+
best, score = state["best_iteration"], state["best_score"]
|
|
135
|
+
if (
|
|
136
|
+
type(state["patience"]) is not int
|
|
137
|
+
or state["patience"] != patience
|
|
138
|
+
or type(state["maximize"]) is not bool
|
|
139
|
+
or state["maximize"] != maximize
|
|
140
|
+
or type(best) is not int
|
|
141
|
+
or not 0 <= best < state["completed_rounds"]
|
|
142
|
+
or not isinstance(score, (float, int))
|
|
143
|
+
or isinstance(score, bool)
|
|
144
|
+
or not math.isfinite(score)
|
|
145
|
+
):
|
|
146
|
+
raise ValueError("selection configuration or best state mismatch")
|
|
147
|
+
elif scores or state["metric"] is not None or state["stopped"]:
|
|
148
|
+
raise ValueError("unexpected early-stopping state")
|
|
149
|
+
elif any(
|
|
150
|
+
state[key] is not None
|
|
151
|
+
for key in ("patience", "maximize", "best_iteration", "best_score")
|
|
152
|
+
):
|
|
153
|
+
raise ValueError("unexpected selection configuration")
|
|
154
|
+
last = state["last_metrics"]
|
|
155
|
+
if not isinstance(last, dict) or any(
|
|
156
|
+
not isinstance(key, str)
|
|
157
|
+
or not key.startswith(("train-", "validation-"))
|
|
158
|
+
or not isinstance(value, (float, int))
|
|
159
|
+
or isinstance(value, bool)
|
|
160
|
+
or not math.isfinite(value)
|
|
161
|
+
for key, value in last.items()
|
|
162
|
+
):
|
|
163
|
+
raise ValueError("last metrics are invalid")
|
|
164
|
+
if (
|
|
165
|
+
patience is not None
|
|
166
|
+
and last.get(f"validation-{state['metric']}") != scores[-1]
|
|
167
|
+
):
|
|
168
|
+
raise ValueError("last selection score mismatch")
|
|
169
|
+
features = json.loads((root / "feature_names.json").read_text(encoding="utf-8"))
|
|
170
|
+
raw = (root / "training.ubj").read_bytes()
|
|
171
|
+
model = xgboost.Booster(model_file=bytearray(raw))
|
|
172
|
+
if (
|
|
173
|
+
features != identity["feature_names"]
|
|
174
|
+
or model.num_features() != len(features)
|
|
175
|
+
or model.num_boosted_rounds() != state["completed_rounds"]
|
|
176
|
+
or hashlib.sha256(raw).hexdigest() != state["training_sha256"]
|
|
177
|
+
):
|
|
178
|
+
raise ValueError("training model or features mismatch")
|
|
179
|
+
if patience is not None and (
|
|
180
|
+
model.best_iteration != state["best_iteration"]
|
|
181
|
+
or model.best_score != state["best_score"]
|
|
182
|
+
):
|
|
183
|
+
raise ValueError("training model best attrs mismatch")
|
|
184
|
+
if state["phase"] == "final":
|
|
185
|
+
from tributo_algorithms_boosting.contracts import (
|
|
186
|
+
_validate_training_metadata,
|
|
187
|
+
)
|
|
188
|
+
from tributo_algorithms_boosting.native import _check_training_metadata
|
|
189
|
+
|
|
190
|
+
selected_raw = (root / "model.ubj").read_bytes()
|
|
191
|
+
selected = xgboost.Booster(model_file=bytearray(selected_raw))
|
|
192
|
+
metadata = _validate_training_metadata(
|
|
193
|
+
json.loads(
|
|
194
|
+
(root / "training_metadata.json").read_text(encoding="utf-8")
|
|
195
|
+
)
|
|
196
|
+
)
|
|
197
|
+
_check_training_metadata(selected, metadata)
|
|
198
|
+
if (
|
|
199
|
+
hashlib.sha256(selected_raw).hexdigest() != state["selected_sha256"]
|
|
200
|
+
or metadata["training_rounds"] != state["completed_rounds"]
|
|
201
|
+
or (not state["stopped"] and state["completed_rounds"] != rounds)
|
|
202
|
+
or (
|
|
203
|
+
patience is not None
|
|
204
|
+
and any(
|
|
205
|
+
metadata.get(key) != state[key]
|
|
206
|
+
for key in ("best_iteration", "best_score", "maximize")
|
|
207
|
+
)
|
|
208
|
+
)
|
|
209
|
+
):
|
|
210
|
+
raise ValueError("final model mismatch")
|
|
211
|
+
elif state["selected_sha256"] is not None:
|
|
212
|
+
raise ValueError("periodic checkpoint contains a selected model digest")
|
|
213
|
+
return raw, state
|
|
214
|
+
except (
|
|
215
|
+
OSError,
|
|
216
|
+
ValueError,
|
|
217
|
+
TypeError,
|
|
218
|
+
KeyError,
|
|
219
|
+
AttributeError,
|
|
220
|
+
xgboost.core.XGBoostError,
|
|
221
|
+
) as exc:
|
|
222
|
+
raise AlgorithmExecutionError("XGBoost recovery checkpoint is invalid") from exc
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def training_callback(
|
|
226
|
+
*,
|
|
227
|
+
dtrain: Any,
|
|
228
|
+
patience: int | None,
|
|
229
|
+
maximize: bool | None,
|
|
230
|
+
interval: int,
|
|
231
|
+
restored: Mapping[str, Any] | None = None,
|
|
232
|
+
report: Callable[[Any, Any], None] | None = None,
|
|
233
|
+
) -> Any:
|
|
234
|
+
"""Compose native early stopping with checkpointing in a defined order.
|
|
235
|
+
|
|
236
|
+
Rebuild native patience by replaying scalar history through public hooks.
|
|
237
|
+
The auxiliary zero-round Booster keeps historical epochs absolute; calling
|
|
238
|
+
before_training on the real Booster then sets the continuation offset.
|
|
239
|
+
"""
|
|
240
|
+
import xgboost
|
|
241
|
+
|
|
242
|
+
class TrainingState(xgboost.callback.TrainingCallback):
|
|
243
|
+
def __init__(self) -> None:
|
|
244
|
+
self.matrix: Any = None
|
|
245
|
+
self.patience, self.maximize = patience, maximize
|
|
246
|
+
self.best_iteration: int | None = None
|
|
247
|
+
self.best_score: float | None = None
|
|
248
|
+
self.completed = int(restored["completed_rounds"]) if restored else 0
|
|
249
|
+
self.start = self.completed
|
|
250
|
+
self.scores = list(restored["scores"]) if restored else []
|
|
251
|
+
self.metric = restored["metric"] if restored else None
|
|
252
|
+
self.last_metrics = dict(restored["last_metrics"]) if restored else {}
|
|
253
|
+
self.stopped = False
|
|
254
|
+
self.full_model = b""
|
|
255
|
+
self.early = (
|
|
256
|
+
xgboost.callback.EarlyStopping(
|
|
257
|
+
rounds=patience,
|
|
258
|
+
data_name="validation",
|
|
259
|
+
maximize=maximize,
|
|
260
|
+
save_best=True,
|
|
261
|
+
)
|
|
262
|
+
if patience is not None
|
|
263
|
+
else None
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
def before_training(self, model: Any) -> Any:
|
|
267
|
+
if model.num_boosted_rounds() != self.start:
|
|
268
|
+
raise AlgorithmExecutionError("XGBoost checkpoint round mismatch")
|
|
269
|
+
if self.early is not None:
|
|
270
|
+
if self.scores:
|
|
271
|
+
if not isinstance(self.metric, str) or not self.metric:
|
|
272
|
+
raise AlgorithmExecutionError(
|
|
273
|
+
"XGBoost selection metric is missing"
|
|
274
|
+
)
|
|
275
|
+
auxiliary = xgboost.Booster(cache=[self.matrix])
|
|
276
|
+
self.early.before_training(auxiliary)
|
|
277
|
+
for epoch, score in enumerate(self.scores):
|
|
278
|
+
if self.stopped:
|
|
279
|
+
raise AlgorithmExecutionError(
|
|
280
|
+
"XGBoost history continues after early stopping"
|
|
281
|
+
)
|
|
282
|
+
self.stopped = self.early.after_iteration(
|
|
283
|
+
auxiliary,
|
|
284
|
+
epoch,
|
|
285
|
+
{"validation": {cast(str, self.metric): [score]}},
|
|
286
|
+
)
|
|
287
|
+
if (
|
|
288
|
+
auxiliary.attr("best_iteration") != model.attr("best_iteration")
|
|
289
|
+
or auxiliary.attr("best_score") != model.attr("best_score")
|
|
290
|
+
or restored is None
|
|
291
|
+
or self.stopped != restored["stopped"]
|
|
292
|
+
):
|
|
293
|
+
raise AlgorithmExecutionError(
|
|
294
|
+
"XGBoost checkpoint early-stopping state mismatch"
|
|
295
|
+
)
|
|
296
|
+
self.early.before_training(model)
|
|
297
|
+
if self.scores:
|
|
298
|
+
self.best_iteration, self.best_score = (
|
|
299
|
+
int(model.best_iteration),
|
|
300
|
+
float(model.best_score),
|
|
301
|
+
)
|
|
302
|
+
return model
|
|
303
|
+
|
|
304
|
+
def after_iteration(self, model: Any, epoch: int, evals_log: Any) -> bool:
|
|
305
|
+
self.completed = self.start + epoch + 1
|
|
306
|
+
for role, values in evals_log.items():
|
|
307
|
+
for metric, scores in values.items():
|
|
308
|
+
score = float(scores[-1])
|
|
309
|
+
if not math.isfinite(score):
|
|
310
|
+
raise AlgorithmExecutionError(
|
|
311
|
+
"XGBoost evaluation scores must be finite"
|
|
312
|
+
)
|
|
313
|
+
self.last_metrics[f"{role}-{metric}"] = score
|
|
314
|
+
if self.early is not None:
|
|
315
|
+
validation = evals_log.get("validation", {})
|
|
316
|
+
if len(validation) != 1:
|
|
317
|
+
raise AlgorithmExecutionError(
|
|
318
|
+
"XGBoost selection metric is ambiguous"
|
|
319
|
+
)
|
|
320
|
+
metric, scores = next(iter(validation.items()))
|
|
321
|
+
if self.metric is not None and self.metric != metric:
|
|
322
|
+
raise AlgorithmExecutionError("XGBoost selection metric changed")
|
|
323
|
+
self.metric = metric
|
|
324
|
+
self.stopped = self.early.after_iteration(model, epoch, evals_log)
|
|
325
|
+
self.scores.append(float(scores[-1]))
|
|
326
|
+
self.best_iteration, self.best_score = (
|
|
327
|
+
int(model.best_iteration),
|
|
328
|
+
float(model.best_score),
|
|
329
|
+
)
|
|
330
|
+
if interval and self.completed % interval == 0 and report is not None:
|
|
331
|
+
report(model, self)
|
|
332
|
+
return self.stopped
|
|
333
|
+
|
|
334
|
+
def after_training(self, model: Any) -> Any:
|
|
335
|
+
self.full_model = bytes(model.save_raw(raw_format="ubj"))
|
|
336
|
+
self.matrix = None
|
|
337
|
+
return self.early.after_training(model) if self.early is not None else model
|
|
338
|
+
|
|
339
|
+
callback = TrainingState()
|
|
340
|
+
callback.matrix = dtrain
|
|
341
|
+
return callback
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def final_report_group(
|
|
345
|
+
metrics: list[dict[str, Any]],
|
|
346
|
+
checkpoint: Any,
|
|
347
|
+
*,
|
|
348
|
+
invocation: str,
|
|
349
|
+
world_size: int,
|
|
350
|
+
) -> dict[str, Any] | None:
|
|
351
|
+
"""Accept one complete final report, never a mixture of rank records."""
|
|
352
|
+
if len(metrics) != world_size:
|
|
353
|
+
raise AlgorithmExecutionError("XGBoost report is missing Workers")
|
|
354
|
+
raw_reports = [item.get(REPORT_KEY) for item in metrics]
|
|
355
|
+
if any(
|
|
356
|
+
not isinstance(item, Mapping) or item.get("invocation") != invocation
|
|
357
|
+
for item in raw_reports
|
|
358
|
+
):
|
|
359
|
+
raise AlgorithmExecutionError("XGBoost report invocation mismatch")
|
|
360
|
+
reports = [cast(Mapping[str, Any], item) for item in raw_reports]
|
|
361
|
+
phases = {item.get("phase") for item in reports}
|
|
362
|
+
if phases == {"training"}:
|
|
363
|
+
return None
|
|
364
|
+
if phases != {"final"} or checkpoint is None:
|
|
365
|
+
raise AlgorithmExecutionError("XGBoost final report requires a Checkpoint")
|
|
366
|
+
public = [
|
|
367
|
+
{key: value for key, value in item.items() if key != REPORT_KEY}
|
|
368
|
+
for item in metrics
|
|
369
|
+
]
|
|
370
|
+
if any(item != public[0] for item in public[1:]):
|
|
371
|
+
raise AlgorithmExecutionError("XGBoost final Worker metrics diverged")
|
|
372
|
+
completed, start, attempt = (
|
|
373
|
+
public[0].get(key)
|
|
374
|
+
for key in ("training_rounds", "resumed_from_round", "attempt_training_rounds")
|
|
375
|
+
)
|
|
376
|
+
if (
|
|
377
|
+
type(completed) is not int
|
|
378
|
+
or completed < 1
|
|
379
|
+
or type(start) is not int
|
|
380
|
+
or start < 0
|
|
381
|
+
or type(attempt) is not int
|
|
382
|
+
or attempt < 0
|
|
383
|
+
or start + attempt != completed
|
|
384
|
+
):
|
|
385
|
+
raise AlgorithmExecutionError("XGBoost final report round counts are invalid")
|
|
386
|
+
workers = [item.get("worker") for item in reports]
|
|
387
|
+
if any(
|
|
388
|
+
not isinstance(worker, dict)
|
|
389
|
+
or type(worker.get("rank")) is not int
|
|
390
|
+
or worker["rank"] != rank
|
|
391
|
+
or worker.get("world_size") != world_size
|
|
392
|
+
or worker.get("model_state_digest") != public[0].get("model_state_digest")
|
|
393
|
+
or worker.get("collective_steps") != public[0].get("attempt_training_rounds")
|
|
394
|
+
or worker.get("batch_count") != public[0].get("attempt_training_rounds")
|
|
395
|
+
for rank, worker in enumerate(workers)
|
|
396
|
+
):
|
|
397
|
+
raise AlgorithmExecutionError("XGBoost final Worker evidence is inconsistent")
|
|
398
|
+
return {
|
|
399
|
+
"checkpoint_path": checkpoint.path,
|
|
400
|
+
"metrics": public[0],
|
|
401
|
+
"workers": workers,
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def check_final_result(result: Any, group: Mapping[str, Any], invocation: str) -> None:
|
|
406
|
+
metrics = getattr(result, "metrics", {})
|
|
407
|
+
checkpoint = getattr(result, "checkpoint", None)
|
|
408
|
+
if not isinstance(metrics, Mapping):
|
|
409
|
+
raise AlgorithmExecutionError("XGBoost result metrics must be a mapping")
|
|
410
|
+
internal = metrics.get(REPORT_KEY, {})
|
|
411
|
+
if (
|
|
412
|
+
checkpoint is None
|
|
413
|
+
or checkpoint.path != group.get("checkpoint_path")
|
|
414
|
+
or not isinstance(internal, Mapping)
|
|
415
|
+
or internal.get("invocation") != invocation
|
|
416
|
+
or internal.get("phase") != "final"
|
|
417
|
+
or any(
|
|
418
|
+
metrics.get(key) != value for key, value in group.get("metrics", {}).items()
|
|
419
|
+
)
|
|
420
|
+
):
|
|
421
|
+
raise AlgorithmExecutionError(
|
|
422
|
+
"XGBoost result does not match final Worker evidence"
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def evidence_callback(collector: Any, invocation: str, world_size: int) -> Any:
|
|
427
|
+
"""Commit final evidence only after Ray persists the complete group report."""
|
|
428
|
+
import ray
|
|
429
|
+
from ray.train import UserCallback
|
|
430
|
+
|
|
431
|
+
class FinalEvidence(UserCallback):
|
|
432
|
+
def after_report(
|
|
433
|
+
self, run_context: Any, metrics: list[dict[str, Any]], checkpoint: Any
|
|
434
|
+
) -> None:
|
|
435
|
+
group = final_report_group(
|
|
436
|
+
metrics, checkpoint, invocation=invocation, world_size=world_size
|
|
437
|
+
)
|
|
438
|
+
if group is not None:
|
|
439
|
+
ray.get(collector.replace_final.remote(group))
|
|
440
|
+
|
|
441
|
+
return FinalEvidence()
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""Executable contracts for official distributed XGBoost."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _validate_training_options(
|
|
11
|
+
training: Mapping[str, Any], model: Mapping[str, Any]
|
|
12
|
+
) -> tuple[int, int | None, bool | None]:
|
|
13
|
+
if unknown := sorted(
|
|
14
|
+
set(training)
|
|
15
|
+
- {
|
|
16
|
+
"num_rounds",
|
|
17
|
+
"early_stopping_rounds",
|
|
18
|
+
"maximize",
|
|
19
|
+
"checkpoint_interval_rounds",
|
|
20
|
+
}
|
|
21
|
+
):
|
|
22
|
+
raise ValueError(f"unknown XGBoost training keys: {unknown}")
|
|
23
|
+
rounds = training.get("num_rounds", 10)
|
|
24
|
+
if not isinstance(rounds, int) or isinstance(rounds, bool) or rounds < 1:
|
|
25
|
+
raise ValueError("XGBoost num_rounds/num_boost_round must be positive")
|
|
26
|
+
patience = training.get("early_stopping_rounds")
|
|
27
|
+
if patience is None:
|
|
28
|
+
if "maximize" in training:
|
|
29
|
+
raise ValueError("training.maximize requires early stopping")
|
|
30
|
+
return rounds, None, None
|
|
31
|
+
if not isinstance(patience, int) or isinstance(patience, bool) or patience < 1:
|
|
32
|
+
raise ValueError("training.early_stopping_rounds must be a positive integer")
|
|
33
|
+
maximize = training.get("maximize")
|
|
34
|
+
if not isinstance(maximize, bool):
|
|
35
|
+
raise ValueError("early stopping requires an explicit training.maximize bool")
|
|
36
|
+
metric = model.get("eval_metric")
|
|
37
|
+
if not isinstance(metric, str) or not metric.strip():
|
|
38
|
+
raise ValueError("early stopping requires a single model.eval_metric string")
|
|
39
|
+
if model.get("booster", "gbtree") == "gblinear":
|
|
40
|
+
raise ValueError("early stopping best-model export requires a tree Booster")
|
|
41
|
+
return rounds, patience, maximize
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _validate_recovery_options(
|
|
45
|
+
training: Mapping[str, Any], ray_config: Mapping[str, Any], model: Mapping[str, Any]
|
|
46
|
+
) -> tuple[int, int]:
|
|
47
|
+
interval = training.get("checkpoint_interval_rounds", 0)
|
|
48
|
+
failures = ray_config.get("max_failures", 0)
|
|
49
|
+
for name, value in (
|
|
50
|
+
("checkpoint_interval_rounds", interval),
|
|
51
|
+
("max_failures", failures),
|
|
52
|
+
):
|
|
53
|
+
if type(value) is not int or value < 0:
|
|
54
|
+
raise ValueError(f"XGBoost {name} must be a non-negative integer")
|
|
55
|
+
if failures and not interval:
|
|
56
|
+
raise ValueError("XGBoost max_failures requires checkpoint_interval_rounds")
|
|
57
|
+
if interval and model.get("booster", "gbtree") != "gbtree":
|
|
58
|
+
raise ValueError("XGBoost checkpoint recovery requires gbtree")
|
|
59
|
+
return interval, failures
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _validate_training_metadata(value: object) -> dict[str, Any]:
|
|
63
|
+
required = {"schema_version", "training_rounds", "model_rounds"}
|
|
64
|
+
selection = {"best_iteration", "best_score", "selection_metric", "maximize"}
|
|
65
|
+
if not isinstance(value, Mapping) or set(value) not in (
|
|
66
|
+
required,
|
|
67
|
+
required | selection,
|
|
68
|
+
):
|
|
69
|
+
raise ValueError("XGBoost training metadata fields are invalid")
|
|
70
|
+
for field in required:
|
|
71
|
+
item = value[field]
|
|
72
|
+
if not isinstance(item, int) or isinstance(item, bool) or item < 1:
|
|
73
|
+
raise ValueError(f"XGBoost training metadata {field} must be positive")
|
|
74
|
+
if value["schema_version"] != 1:
|
|
75
|
+
raise ValueError("unsupported XGBoost training metadata version")
|
|
76
|
+
if value["model_rounds"] > value["training_rounds"]:
|
|
77
|
+
raise ValueError("XGBoost model rounds exceed executed training rounds")
|
|
78
|
+
if selection <= set(value):
|
|
79
|
+
best = value["best_iteration"]
|
|
80
|
+
score = value["best_score"]
|
|
81
|
+
metric = value["selection_metric"]
|
|
82
|
+
if (
|
|
83
|
+
not isinstance(best, int)
|
|
84
|
+
or isinstance(best, bool)
|
|
85
|
+
or best < 0
|
|
86
|
+
or best + 1 != value["model_rounds"]
|
|
87
|
+
or not isinstance(score, (int, float))
|
|
88
|
+
or isinstance(score, bool)
|
|
89
|
+
or not math.isfinite(score)
|
|
90
|
+
or not isinstance(metric, str)
|
|
91
|
+
or not metric.startswith("validation-")
|
|
92
|
+
or len(metric) == len("validation-")
|
|
93
|
+
or not isinstance(value["maximize"], bool)
|
|
94
|
+
):
|
|
95
|
+
raise ValueError("XGBoost best-model metadata is inconsistent")
|
|
96
|
+
return dict(value)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class XGBoostConfigValidator:
|
|
100
|
+
api_version = 1
|
|
101
|
+
schema_digest = "1" * 64
|
|
102
|
+
|
|
103
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
104
|
+
allowed = {"data", "model", "output", "ray", "resource", "training"}
|
|
105
|
+
if unknown := sorted(set(value) - allowed):
|
|
106
|
+
raise ValueError(f"unknown XGBoost config keys: {unknown}")
|
|
107
|
+
for name in allowed:
|
|
108
|
+
if name in value and not isinstance(value[name], Mapping):
|
|
109
|
+
raise ValueError(f"{name} must be a mapping")
|
|
110
|
+
data = value.get("data")
|
|
111
|
+
if not isinstance(data, Mapping) or not data.get("label_col"):
|
|
112
|
+
raise ValueError("data.label_col is required")
|
|
113
|
+
output = value.get("output")
|
|
114
|
+
if not isinstance(output, Mapping) or not output.get("bundle_uri"):
|
|
115
|
+
raise ValueError("output.bundle_uri is required")
|
|
116
|
+
ray = value.get("ray")
|
|
117
|
+
if not isinstance(ray, Mapping) or not ray.get("storage_path"):
|
|
118
|
+
raise ValueError("ray.storage_path is required")
|
|
119
|
+
_validate_training_options(value.get("training", {}), value.get("model", {}))
|
|
120
|
+
_validate_recovery_options(
|
|
121
|
+
value.get("training", {}), ray, value.get("model", {})
|
|
122
|
+
)
|
|
123
|
+
return dict(value)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class XGBoostInputValidator:
|
|
127
|
+
api_version = 1
|
|
128
|
+
schema_digest = "2" * 64
|
|
129
|
+
|
|
130
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
131
|
+
bindings = value.get("bindings")
|
|
132
|
+
if not isinstance(bindings, list) or len(bindings) not in {1, 2}:
|
|
133
|
+
raise ValueError("XGBoost requires train and optional validation bindings")
|
|
134
|
+
by_role: dict[str, Mapping[str, Any]] = {}
|
|
135
|
+
for binding in bindings:
|
|
136
|
+
if not isinstance(binding, Mapping):
|
|
137
|
+
raise ValueError("XGBoost input binding must be a mapping")
|
|
138
|
+
role = binding.get("name")
|
|
139
|
+
if (
|
|
140
|
+
not isinstance(role, str)
|
|
141
|
+
or role not in {"train", "validation"}
|
|
142
|
+
or role in by_role
|
|
143
|
+
):
|
|
144
|
+
raise ValueError("XGBoost input roles must be unique train/validation")
|
|
145
|
+
features = binding.get("feature_names")
|
|
146
|
+
label = binding.get("label_name")
|
|
147
|
+
if (
|
|
148
|
+
not isinstance(features, (list, tuple))
|
|
149
|
+
or not features
|
|
150
|
+
or any(not isinstance(name, str) or not name for name in features)
|
|
151
|
+
or len(set(features)) != len(features)
|
|
152
|
+
or not isinstance(label, str)
|
|
153
|
+
or not label
|
|
154
|
+
):
|
|
155
|
+
raise ValueError("XGBoost requires features and label")
|
|
156
|
+
by_role[role] = binding
|
|
157
|
+
if "train" not in by_role or value.get("primary_role", "train") != "train":
|
|
158
|
+
raise ValueError("XGBoost requires train as the primary input role")
|
|
159
|
+
train = by_role["train"]
|
|
160
|
+
if "validation" in by_role:
|
|
161
|
+
validation = by_role["validation"]
|
|
162
|
+
if (
|
|
163
|
+
tuple(validation["feature_names"]) != tuple(train["feature_names"])
|
|
164
|
+
or validation["label_name"] != train["label_name"]
|
|
165
|
+
):
|
|
166
|
+
raise ValueError(
|
|
167
|
+
"XGBoost validation feature order and label must match train"
|
|
168
|
+
)
|
|
169
|
+
return value
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class XGBoostOutputValidator:
|
|
173
|
+
api_version = 1
|
|
174
|
+
schema_digest = "3" * 64
|
|
175
|
+
|
|
176
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
177
|
+
outputs = value.get("outputs")
|
|
178
|
+
if value.get("status") != "succeeded" or not isinstance(outputs, Mapping):
|
|
179
|
+
raise ValueError("XGBoost execution failed")
|
|
180
|
+
if not outputs.get("bundle_uri"):
|
|
181
|
+
raise ValueError("XGBoost output requires Bundle")
|
|
182
|
+
metrics = value.get("metrics", {})
|
|
183
|
+
if not isinstance(metrics, Mapping):
|
|
184
|
+
raise ValueError("XGBoost result metrics must be a mapping")
|
|
185
|
+
fields = {
|
|
186
|
+
"training_rounds",
|
|
187
|
+
"model_rounds",
|
|
188
|
+
"best_iteration",
|
|
189
|
+
"best_score",
|
|
190
|
+
"selection_metric",
|
|
191
|
+
"maximize",
|
|
192
|
+
}
|
|
193
|
+
if set(metrics) & (fields - {"training_rounds"}):
|
|
194
|
+
_validate_training_metadata(
|
|
195
|
+
{
|
|
196
|
+
"schema_version": 1,
|
|
197
|
+
**{key: metrics[key] for key in fields if key in metrics},
|
|
198
|
+
}
|
|
199
|
+
)
|
|
200
|
+
if {"resumed_from_round", "attempt_training_rounds"} & set(metrics):
|
|
201
|
+
resumed = metrics.get("resumed_from_round")
|
|
202
|
+
attempt = metrics.get("attempt_training_rounds")
|
|
203
|
+
if (
|
|
204
|
+
type(resumed) is not int
|
|
205
|
+
or resumed < 0
|
|
206
|
+
or type(attempt) is not int
|
|
207
|
+
or attempt < 0
|
|
208
|
+
or resumed + attempt != metrics.get("training_rounds")
|
|
209
|
+
):
|
|
210
|
+
raise ValueError("XGBoost recovery round counts are inconsistent")
|
|
211
|
+
return value
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class XGBoostCoverageValidator:
|
|
215
|
+
api_version = 1
|
|
216
|
+
schema_digest = "4" * 64
|
|
217
|
+
|
|
218
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
219
|
+
if (
|
|
220
|
+
value.get("input_complete") is not True
|
|
221
|
+
or value.get("distributed") is not True
|
|
222
|
+
):
|
|
223
|
+
raise ValueError("XGBoost distributed coverage is incomplete")
|
|
224
|
+
return value
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
__all__ = [
|
|
228
|
+
"XGBoostConfigValidator",
|
|
229
|
+
"XGBoostCoverageValidator",
|
|
230
|
+
"XGBoostInputValidator",
|
|
231
|
+
"XGBoostOutputValidator",
|
|
232
|
+
]
|