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.
Files changed (110) hide show
  1. tributo_algorithms-0.1.0.dist-info/METADATA +328 -0
  2. tributo_algorithms-0.1.0.dist-info/RECORD +110 -0
  3. tributo_algorithms-0.1.0.dist-info/WHEEL +4 -0
  4. tributo_algorithms-0.1.0.dist-info/entry_points.txt +57 -0
  5. tributo_algorithms-0.1.0.dist-info/licenses/LICENSE +202 -0
  6. tributo_algorithms_boosting/__init__.py +42 -0
  7. tributo_algorithms_boosting/algorithm.py +825 -0
  8. tributo_algorithms_boosting/checkpointing.py +441 -0
  9. tributo_algorithms_boosting/contracts.py +232 -0
  10. tributo_algorithms_boosting/data_config.py +59 -0
  11. tributo_algorithms_boosting/descriptor.py +124 -0
  12. tributo_algorithms_boosting/lightgbm.py +511 -0
  13. tributo_algorithms_boosting/lightgbm_contracts.py +186 -0
  14. tributo_algorithms_boosting/lightgbm_descriptor.py +112 -0
  15. tributo_algorithms_boosting/native.py +557 -0
  16. tributo_algorithms_boosting/stages.py +150 -0
  17. tributo_algorithms_catboost/__init__.py +5 -0
  18. tributo_algorithms_catboost/algorithm.py +379 -0
  19. tributo_algorithms_catboost/contracts.py +145 -0
  20. tributo_algorithms_catboost/descriptor.py +121 -0
  21. tributo_algorithms_catboost/exporter.py +106 -0
  22. tributo_algorithms_catboost/flavor.py +191 -0
  23. tributo_algorithms_causal_core/__init__.py +41 -0
  24. tributo_algorithms_causal_core/algorithm.py +1193 -0
  25. tributo_algorithms_causal_core/contracts.py +136 -0
  26. tributo_algorithms_causal_core/descriptor.py +270 -0
  27. tributo_algorithms_causal_core/exporter.py +52 -0
  28. tributo_algorithms_causal_discovery/__init__.py +23 -0
  29. tributo_algorithms_causal_discovery/algorithm.py +526 -0
  30. tributo_algorithms_causal_discovery/contracts.py +97 -0
  31. tributo_algorithms_causal_discovery/descriptor.py +130 -0
  32. tributo_algorithms_causal_discovery/exporter.py +43 -0
  33. tributo_algorithms_causal_dowhy/__init__.py +38 -0
  34. tributo_algorithms_causal_dowhy/algorithm.py +325 -0
  35. tributo_algorithms_causal_dowhy/contracts.py +209 -0
  36. tributo_algorithms_causal_dowhy/descriptor.py +106 -0
  37. tributo_algorithms_causal_dowhy/exporter.py +43 -0
  38. tributo_algorithms_causal_dowhy/gcm.py +634 -0
  39. tributo_algorithms_causal_dowhy/gcm_descriptor.py +110 -0
  40. tributo_algorithms_causal_dr/__init__.py +22 -0
  41. tributo_algorithms_causal_dr/algorithm.py +446 -0
  42. tributo_algorithms_causal_dr/contracts.py +94 -0
  43. tributo_algorithms_causal_dr/descriptor.py +104 -0
  44. tributo_algorithms_causal_xlearner/__init__.py +29 -0
  45. tributo_algorithms_causal_xlearner/algorithm.py +448 -0
  46. tributo_algorithms_causal_xlearner/contracts.py +97 -0
  47. tributo_algorithms_causal_xlearner/descriptor.py +120 -0
  48. tributo_algorithms_causal_xlearner/exporter.py +432 -0
  49. tributo_algorithms_causal_xlearner/flavor.py +120 -0
  50. tributo_algorithms_causal_xlearner/model.py +116 -0
  51. tributo_algorithms_classical/__init__.py +41 -0
  52. tributo_algorithms_classical/contracts.py +139 -0
  53. tributo_algorithms_classical/descriptors.py +370 -0
  54. tributo_algorithms_classical/exporter.py +166 -0
  55. tributo_algorithms_classical/isolation_forest.py +172 -0
  56. tributo_algorithms_classical/isolation_forest_descriptor.py +122 -0
  57. tributo_algorithms_classical/kmeans.py +315 -0
  58. tributo_algorithms_classical/kmeans_descriptor.py +147 -0
  59. tributo_algorithms_classical/linear_regression.py +206 -0
  60. tributo_algorithms_classical/logistic_regression.py +238 -0
  61. tributo_algorithms_classical/models.py +28 -0
  62. tributo_algorithms_classical/multinomial_nb.py +643 -0
  63. tributo_algorithms_classical/multinomial_nb_descriptor.py +183 -0
  64. tributo_algorithms_classical/pca.py +187 -0
  65. tributo_algorithms_classical/pca_descriptor.py +111 -0
  66. tributo_algorithms_classical/random_forest.py +304 -0
  67. tributo_algorithms_classical/sgd.py +331 -0
  68. tributo_algorithms_classical/sgd_contracts.py +121 -0
  69. tributo_algorithms_classical/sgd_descriptor.py +143 -0
  70. tributo_algorithms_classical/unsupervised_contracts.py +198 -0
  71. tributo_algorithms_classical/unsupervised_exporter.py +427 -0
  72. tributo_algorithms_classical/unsupervised_models.py +90 -0
  73. tributo_algorithms_graph_pyg/__init__.py +37 -0
  74. tributo_algorithms_graph_pyg/algorithm.py +883 -0
  75. tributo_algorithms_graph_pyg/contracts.py +260 -0
  76. tributo_algorithms_graph_pyg/descriptor.py +201 -0
  77. tributo_algorithms_multistage_torch/__init__.py +40 -0
  78. tributo_algorithms_multistage_torch/algorithm.py +532 -0
  79. tributo_algorithms_multistage_torch/contracts.py +220 -0
  80. tributo_algorithms_multistage_torch/descriptor.py +146 -0
  81. tributo_algorithms_multistage_torch/pretrain.py +570 -0
  82. tributo_algorithms_multistage_torch/pretrain_descriptor.py +153 -0
  83. tributo_algorithms_recsys_torch/__init__.py +35 -0
  84. tributo_algorithms_recsys_torch/contracts.py +295 -0
  85. tributo_algorithms_recsys_torch/descriptor.py +136 -0
  86. tributo_algorithms_recsys_torch/jagged.py +707 -0
  87. tributo_algorithms_recsys_torch/jagged_descriptor.py +130 -0
  88. tributo_algorithms_recsys_torch/recipe.py +192 -0
  89. tributo_algorithms_representation/__init__.py +20 -0
  90. tributo_algorithms_representation/contracts.py +117 -0
  91. tributo_algorithms_representation/descriptor.py +137 -0
  92. tributo_algorithms_representation/recipe.py +162 -0
  93. tributo_algorithms_tabular_torch/__init__.py +46 -0
  94. tributo_algorithms_tabular_torch/contracts.py +228 -0
  95. tributo_algorithms_tabular_torch/descriptor.py +223 -0
  96. tributo_algorithms_tabular_torch/priors.py +216 -0
  97. tributo_algorithms_tabular_torch/pu_metrics.py +269 -0
  98. tributo_algorithms_tabular_torch/pu_reducer.py +129 -0
  99. tributo_algorithms_tabular_torch/recipe.py +294 -0
  100. tributo_algorithms_timeseries/__init__.py +36 -0
  101. tributo_algorithms_timeseries/contracts.py +120 -0
  102. tributo_algorithms_timeseries/descriptor.py +137 -0
  103. tributo_algorithms_timeseries/recipe.py +195 -0
  104. tributo_algorithms_timeseries/rnn_contracts.py +170 -0
  105. tributo_algorithms_timeseries/rnn_descriptor.py +167 -0
  106. tributo_algorithms_timeseries/rnn_recipe.py +223 -0
  107. tributo_algorithms_transformers_nlp/__init__.py +20 -0
  108. tributo_algorithms_transformers_nlp/contracts.py +109 -0
  109. tributo_algorithms_transformers_nlp/descriptor.py +137 -0
  110. tributo_algorithms_transformers_nlp/recipe.py +235 -0
@@ -0,0 +1,825 @@
1
+ """Public Ray Train/XGBoost distributed implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gc
6
+ import hashlib
7
+ import json
8
+ import math
9
+ import tempfile
10
+ from collections.abc import Mapping
11
+ from pathlib import Path
12
+ from traceback import clear_frames
13
+ from typing import Any, cast
14
+ from uuid import uuid4
15
+
16
+ from tributo.algorithms.api import (
17
+ AlgorithmConfigurationError,
18
+ AlgorithmExecutionError,
19
+ AlgorithmExecutionResult,
20
+ ResolvedAlgorithmPlan,
21
+ )
22
+ from tributo.algorithms.spi import FrameworkNativeAlgorithm
23
+
24
+ from tributo_algorithms_boosting.contracts import (
25
+ XGBoostInputValidator,
26
+ _validate_recovery_options,
27
+ _validate_training_metadata,
28
+ _validate_training_options,
29
+ )
30
+ from tributo_algorithms_boosting.data_config import CompleteCoverageDataConfig
31
+
32
+ _XGBOOST_BATCH_ROWS = 65_536
33
+
34
+
35
+ class _EvidenceCollector:
36
+ def __init__(self) -> None:
37
+ self.records: dict[int, dict[str, object]] = {}
38
+ self.final: dict[str, Any] | None = None
39
+
40
+ def record(self, value: dict[str, object]) -> None:
41
+ rank = value.get("rank")
42
+ if not isinstance(rank, int) or isinstance(rank, bool):
43
+ raise TypeError("XGBoost evidence rank must be an integer")
44
+ if rank in self.records:
45
+ raise ValueError(f"duplicate XGBoost evidence rank: {rank}")
46
+ self.records[rank] = dict(value)
47
+
48
+ def snapshot(self) -> list[dict[str, object]]:
49
+ return [self.records[rank] for rank in sorted(self.records)]
50
+
51
+ def replace_final(self, value: dict[str, Any]) -> None:
52
+ self.final = value
53
+
54
+ def final_snapshot(self) -> dict[str, Any] | None:
55
+ return self.final
56
+
57
+
58
+ def _train_loop(config: dict[str, Any]) -> None:
59
+ import ray
60
+ import xgboost
61
+ from ray import train
62
+ from ray.train import Checkpoint
63
+
64
+ from tributo_algorithms_boosting.checkpointing import (
65
+ REPORT_KEY,
66
+ read_checkpoint,
67
+ recovery_identity,
68
+ training_callback,
69
+ write_checkpoint,
70
+ )
71
+
72
+ feature_names = list(config["feature_names"])
73
+ label_name = str(config["label_name"])
74
+ training = {"num_rounds": config["num_boost_round"]}
75
+ for key in ("early_stopping_rounds", "maximize", "checkpoint_interval_rounds"):
76
+ if key in config:
77
+ training[key] = config[key]
78
+ try:
79
+ rounds, patience, maximize = _validate_training_options(
80
+ training, config["params"]
81
+ )
82
+ interval, _ = _validate_recovery_options(training, {}, config["params"])
83
+ except ValueError as exc:
84
+ raise AlgorithmExecutionError(str(exc)) from exc
85
+ roles = tuple(config.get("input_roles", ("train",)))
86
+ if (
87
+ not roles
88
+ or roles[0] != "train"
89
+ or len(set(roles)) != len(roles)
90
+ or set(roles) - {"train", "validation"}
91
+ or (patience is not None and "validation" not in roles)
92
+ ):
93
+ raise AlgorithmExecutionError(
94
+ "XGBoost early stopping requires validation input"
95
+ )
96
+
97
+ class ShardDataIter(xgboost.DataIter):
98
+ def __init__(self, role: str, cache_prefix: str) -> None:
99
+ super().__init__(cache_prefix=cache_prefix, release_data=True)
100
+ self.role = role
101
+ self.iterator: Any = None
102
+ self.has_rows = False
103
+
104
+ def reset(self) -> None:
105
+ self.has_rows = False
106
+ shard = train.get_dataset_shard(self.role)
107
+ if shard is None:
108
+ raise AlgorithmExecutionError(f"XGBoost {self.role} shard is missing")
109
+ self.iterator = iter(
110
+ shard.iter_batches(
111
+ batch_format="pandas",
112
+ batch_size=_XGBOOST_BATCH_ROWS,
113
+ prefetch_batches=1,
114
+ )
115
+ )
116
+
117
+ def next(self, input_data: Any) -> bool:
118
+ if self.iterator is None:
119
+ self.reset()
120
+ for frame in self.iterator:
121
+ if not frame.empty:
122
+ self.has_rows = True
123
+ input_data(
124
+ data=frame[feature_names].to_numpy(),
125
+ label=frame[label_name].to_numpy(),
126
+ )
127
+ return True
128
+ if not self.has_rows:
129
+ raise AlgorithmExecutionError(
130
+ f"XGBoost {self.role} Worker shard is empty"
131
+ )
132
+ return False
133
+
134
+ context = train.get_context()
135
+ rank = context.get_world_rank()
136
+ world_size = context.get_world_size()
137
+ evidence_actor = config["evidence_actor"]
138
+ identity = recovery_identity(config, world_size) if interval else None
139
+ restored = None
140
+ restore_model = None
141
+ if interval:
142
+ checkpoint = train.get_checkpoint()
143
+ if checkpoint is not None:
144
+ with checkpoint.as_directory() as directory:
145
+ restore_model, restored = read_checkpoint(
146
+ Path(directory),
147
+ identity=cast(Mapping[str, Any], identity),
148
+ rounds=rounds,
149
+ patience=patience,
150
+ maximize=maximize,
151
+ )
152
+
153
+ def periodic_report(model: Any, state: Any) -> None:
154
+ metrics = {
155
+ "training_rounds": state.completed,
156
+ **state.last_metrics,
157
+ REPORT_KEY: {"phase": "training", "invocation": config["invocation"]},
158
+ }
159
+ if rank == 0:
160
+ with tempfile.TemporaryDirectory(
161
+ prefix="tributo-xgboost-periodic-"
162
+ ) as directory:
163
+ root = Path(directory)
164
+ write_checkpoint(
165
+ root,
166
+ full_model=bytes(model.save_raw(raw_format="ubj")),
167
+ state=state,
168
+ identity=cast(Mapping[str, Any], identity),
169
+ )
170
+ train.report(metrics, checkpoint=Checkpoint.from_directory(root))
171
+ else:
172
+ train.report(metrics)
173
+
174
+ with tempfile.TemporaryDirectory(prefix="tributo-xgboost-pages-") as cache_root:
175
+ iterators: dict[str, Any] = {}
176
+ matrices: dict[str, Any] = {}
177
+ evals: list[Any] = []
178
+ history: dict[str, Any] = {}
179
+ state = None
180
+ try:
181
+ for role in roles:
182
+ iterators[role] = ShardDataIter(role, str(Path(cache_root) / role))
183
+ matrices[role] = xgboost.DMatrix(iterators[role])
184
+ input_rows = {
185
+ role: int(matrix.num_row()) for role, matrix in matrices.items()
186
+ }
187
+ if any(rows < 1 for rows in input_rows.values()):
188
+ raise AlgorithmExecutionError("XGBoost Worker shard is empty")
189
+ callbacks = []
190
+ if interval:
191
+ state = training_callback(
192
+ dtrain=matrices["train"],
193
+ patience=patience,
194
+ maximize=maximize,
195
+ interval=interval,
196
+ restored=restored,
197
+ report=periodic_report,
198
+ )
199
+ callbacks.append(state)
200
+ elif patience is not None:
201
+ callbacks.append(
202
+ xgboost.callback.EarlyStopping(
203
+ rounds=patience,
204
+ data_name="validation",
205
+ maximize=maximize,
206
+ save_best=True,
207
+ )
208
+ )
209
+ evals = [(matrices[role], role) for role in roles]
210
+ booster = xgboost.train(
211
+ dict(config["params"]),
212
+ matrices["train"],
213
+ num_boost_round=(
214
+ 0
215
+ if restored and restored["stopped"]
216
+ else rounds - (restored["completed_rounds"] if restored else 0)
217
+ ),
218
+ **(
219
+ {"xgb_model": bytearray(restore_model)}
220
+ if restore_model is not None
221
+ else {}
222
+ ),
223
+ evals=evals,
224
+ evals_result=history,
225
+ callbacks=callbacks,
226
+ verbose_eval=False,
227
+ )
228
+ metadata: dict[str, Any] = {
229
+ "schema_version": 1,
230
+ "training_rounds": state.completed if state is not None else rounds,
231
+ "model_rounds": int(booster.num_boosted_rounds()),
232
+ }
233
+ if patience is not None:
234
+ validation_history = (
235
+ {state.metric: state.scores}
236
+ if state is not None
237
+ else history.get("validation", {})
238
+ )
239
+ if len(validation_history) != 1:
240
+ raise AlgorithmExecutionError(
241
+ "XGBoost selection metric is ambiguous"
242
+ )
243
+ metric, scores = next(iter(validation_history.items()))
244
+ if not scores or any(not math.isfinite(score) for score in scores):
245
+ raise AlgorithmExecutionError(
246
+ "XGBoost selection scores must be finite"
247
+ )
248
+ metadata.update(
249
+ training_rounds=len(scores),
250
+ best_iteration=int(booster.best_iteration),
251
+ best_score=float(booster.best_score),
252
+ selection_metric=f"validation-{metric}",
253
+ maximize=maximize,
254
+ )
255
+ try:
256
+ metadata = _validate_training_metadata(metadata)
257
+ except ValueError as exc:
258
+ raise AlgorithmExecutionError(str(exc)) from exc
259
+ if metadata["training_rounds"] > rounds:
260
+ raise AlgorithmExecutionError(
261
+ "XGBoost exceeded the requested training rounds"
262
+ )
263
+ except BaseException as exc:
264
+ # Completed native frames retain DMatrix arguments on report failure.
265
+ # Release those locals before removing their cache pages.
266
+ clear_frames(exc.__traceback__)
267
+ raise
268
+ finally:
269
+ # DMatrix owns external-memory pages. Release it before its cache directory.
270
+ evals.clear()
271
+ matrices.clear()
272
+ iterators.clear()
273
+ if state is not None:
274
+ state.matrix = None
275
+ gc.collect()
276
+
277
+ raw = bytes(booster.save_raw(raw_format="ubj"))
278
+ digest = hashlib.sha256(raw).hexdigest()
279
+ runtime = ray.get_runtime_context()
280
+ assigned = runtime.get_assigned_resources()
281
+ evidence = {
282
+ "worker_id": str(runtime.get_worker_id()),
283
+ "node_id": str(runtime.get_node_id()),
284
+ "rank": rank,
285
+ "world_size": world_size,
286
+ "shard_id": hashlib.sha256(
287
+ f"{config['binding_digest']}:{rank}/{world_size}".encode("ascii")
288
+ ).hexdigest(),
289
+ "rows_processed": input_rows["train"],
290
+ "input_rows": input_rows,
291
+ "batch_count": state.completed - state.start
292
+ if state is not None
293
+ else metadata["training_rounds"],
294
+ "collective_steps": state.completed - state.start
295
+ if state is not None
296
+ else metadata["training_rounds"],
297
+ "model_state_digest": digest,
298
+ "resources": {
299
+ "num_cpus": float(assigned.get("CPU", 0.0)),
300
+ "num_gpus": float(assigned.get("GPU", 0.0)),
301
+ "custom": {
302
+ str(name): float(value)
303
+ for name, value in assigned.items()
304
+ if name not in {"CPU", "GPU", "memory", "object_store_memory"}
305
+ },
306
+ },
307
+ }
308
+ metrics = {
309
+ "model_state_digest": digest,
310
+ **{key: value for key, value in metadata.items() if key != "schema_version"},
311
+ }
312
+ if state is not None:
313
+ metrics.update(
314
+ state.last_metrics,
315
+ resumed_from_round=state.start,
316
+ attempt_training_rounds=state.completed - state.start,
317
+ )
318
+ metrics[REPORT_KEY] = {
319
+ "phase": "final",
320
+ "invocation": config["invocation"],
321
+ "worker": evidence,
322
+ }
323
+ for role, values in history.items():
324
+ for metric, scores in values.items():
325
+ if not scores or not math.isfinite(scores[-1]):
326
+ raise AlgorithmExecutionError(
327
+ "XGBoost evaluation scores must be finite"
328
+ )
329
+ metrics[f"{role}-{metric}"] = scores[-1]
330
+ if not interval:
331
+ ray.get(evidence_actor.record.remote(evidence))
332
+ if rank == 0:
333
+ with tempfile.TemporaryDirectory(prefix="tributo-xgboost-") as directory:
334
+ root = Path(directory)
335
+ booster.save_model(root / "model.ubj")
336
+ (root / "feature_names.json").write_text(
337
+ json.dumps(feature_names), encoding="utf-8"
338
+ )
339
+ (root / "training_metadata.json").write_text(
340
+ json.dumps(metadata, sort_keys=True, allow_nan=False), encoding="utf-8"
341
+ )
342
+ if state is not None:
343
+ write_checkpoint(
344
+ root,
345
+ full_model=state.full_model,
346
+ state=state,
347
+ identity=cast(Mapping[str, Any], identity),
348
+ selected=raw,
349
+ metadata=metadata,
350
+ )
351
+ train.report(metrics, checkpoint=Checkpoint.from_directory(root))
352
+ else:
353
+ train.report(metrics)
354
+
355
+
356
+ class DistributedXGBoost(FrameworkNativeAlgorithm):
357
+ """Train one synchronized Booster through Ray's public XGBoostTrainer."""
358
+
359
+ def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
360
+ self.plan = plan
361
+ self.collector: Any | None = None
362
+ self.invocation: str | None = None
363
+ if plan.runtime.resume_from is not None:
364
+ raise AlgorithmConfigurationError(
365
+ "official XGBoost resume requires a separate failure-recovery gate"
366
+ )
367
+
368
+ def validate_environment(self) -> None:
369
+ try:
370
+ import xgboost
371
+ from ray.train.xgboost import XGBoostTrainer
372
+ except ImportError as exc:
373
+ raise AlgorithmConfigurationError(
374
+ "official XGBoost requires xgboost and Ray Train"
375
+ ) from exc
376
+ if not xgboost.__version__ or XGBoostTrainer is None:
377
+ raise AlgorithmConfigurationError("XGBoost environment is invalid")
378
+ training = self.plan.algorithm_config.get("training", {})
379
+ if training.get("checkpoint_interval_rounds", 0):
380
+ try:
381
+ from ray.train import UserCallback
382
+ except ImportError as exc:
383
+ raise AlgorithmConfigurationError(
384
+ "XGBoost recovery requires Ray Train V2"
385
+ ) from exc
386
+ if UserCallback is None:
387
+ raise AlgorithmConfigurationError(
388
+ "XGBoost recovery requires Ray Train V2"
389
+ )
390
+
391
+ def bind_datasets(self, datasets: Mapping[str, object]) -> Mapping[str, object]:
392
+ try:
393
+ XGBoostInputValidator().validate(
394
+ self.plan.input_bindings.descriptor_payload()
395
+ )
396
+ except ValueError as exc:
397
+ raise AlgorithmConfigurationError(str(exc)) from exc
398
+ expected_roles = {binding.name for binding in self.plan.input_bindings.bindings}
399
+ if set(datasets) != expected_roles:
400
+ raise AlgorithmConfigurationError(
401
+ "XGBoost Dataset roles must match bindings"
402
+ )
403
+ data = cast(Mapping[str, Any], self.plan.algorithm_config.get("data", {}))
404
+ configured_features = tuple(data.get("feature_columns", ()))
405
+ binding = self.plan.primary_input_binding
406
+ feature_names = configured_features or binding.feature_names
407
+ if tuple(feature_names) != binding.feature_names:
408
+ raise AlgorithmConfigurationError(
409
+ "XGBoost data.feature_columns must match InputBinding"
410
+ )
411
+ if data.get("label_col") != binding.label_name:
412
+ raise AlgorithmConfigurationError(
413
+ "XGBoost data.label_col must match InputBinding label"
414
+ )
415
+ training = cast(
416
+ Mapping[str, Any], self.plan.algorithm_config.get("training", {})
417
+ )
418
+ if (
419
+ training.get("early_stopping_rounds") is not None
420
+ and "validation" not in datasets
421
+ ):
422
+ raise AlgorithmConfigurationError(
423
+ "XGBoost early stopping requires validation input"
424
+ )
425
+ import pyarrow as pa
426
+ from pandas.api.types import is_numeric_dtype
427
+
428
+ columns = [*feature_names, cast(str, binding.label_name)]
429
+ output: dict[str, object] = {}
430
+ for role in ("train", "validation"):
431
+ if role not in datasets:
432
+ continue
433
+ dataset = cast(Any, datasets[role])
434
+ schema = dataset.schema()
435
+ if schema is None:
436
+ raise AlgorithmConfigurationError(
437
+ f"XGBoost {role} schema is unavailable"
438
+ )
439
+ types = dict(zip(schema.names, schema.types, strict=True))
440
+ for column in columns:
441
+ dtype = types.get(column)
442
+ numeric = (
443
+ pa.types.is_integer(dtype)
444
+ or pa.types.is_floating(dtype)
445
+ or pa.types.is_boolean(dtype)
446
+ if isinstance(dtype, pa.DataType)
447
+ else dtype is not None and is_numeric_dtype(dtype)
448
+ )
449
+ if not numeric:
450
+ raise AlgorithmConfigurationError(
451
+ f"XGBoost {role} column {column!r} must exist and be numeric"
452
+ )
453
+ output[role] = dataset.select_columns(columns)
454
+ return output
455
+
456
+ def build_trainer(
457
+ self,
458
+ config: Mapping[str, Any],
459
+ datasets: Mapping[str, object],
460
+ ) -> object:
461
+ import ray
462
+ from ray.train import RunConfig, ScalingConfig
463
+ from ray.train.xgboost import XGBoostTrainer
464
+
465
+ data = cast(Mapping[str, Any], config.get("data", {}))
466
+ model = dict(cast(Mapping[str, Any], config.get("model", {})))
467
+ training = cast(Mapping[str, Any], config.get("training", {}))
468
+ ray_config = cast(Mapping[str, Any], config.get("ray", {}))
469
+ binding = self.plan.primary_input_binding
470
+ rounds, patience, maximize = _validate_training_options(training, model)
471
+ interval, failures = _validate_recovery_options(training, ray_config, model)
472
+ self.invocation = uuid4().hex
473
+ collector_type = ray.remote(_EvidenceCollector).options(num_cpus=0)
474
+ self.collector = collector_type.remote()
475
+ return XGBoostTrainer(
476
+ train_loop_per_worker=_train_loop,
477
+ train_loop_config={
478
+ "feature_names": list(binding.feature_names),
479
+ "label_name": str(data["label_col"]),
480
+ "params": model,
481
+ "num_boost_round": rounds,
482
+ "input_roles": list(datasets),
483
+ **(
484
+ {
485
+ "checkpoint_interval_rounds": interval,
486
+ "invocation": self.invocation,
487
+ "plan_id": self.plan.plan_id,
488
+ }
489
+ if interval
490
+ else {}
491
+ ),
492
+ **(
493
+ {"early_stopping_rounds": patience, "maximize": maximize}
494
+ if patience is not None
495
+ else {}
496
+ ),
497
+ "evidence_actor": self.collector,
498
+ "binding_digest": self.plan.primary_input_descriptor.binding_digest,
499
+ },
500
+ scaling_config=ScalingConfig(
501
+ num_workers=self.plan.runtime.worker_count,
502
+ use_gpu=self.plan.runtime.num_gpus > 0,
503
+ placement_strategy="SPREAD",
504
+ resources_per_worker={
505
+ "CPU": self.plan.runtime.num_cpus,
506
+ "GPU": self.plan.runtime.num_gpus,
507
+ **dict(self.plan.runtime.custom_resources),
508
+ },
509
+ ),
510
+ datasets=cast(dict[str, Any], dict(datasets)),
511
+ dataset_config=CompleteCoverageDataConfig(datasets_to_split=list(datasets)),
512
+ run_config=RunConfig(
513
+ name=f"tributo-official-xgboost-{self.invocation}",
514
+ storage_path=str(ray_config["storage_path"]),
515
+ **self._recovery_run_options(interval, failures),
516
+ ),
517
+ )
518
+
519
+ def _recovery_run_options(self, interval: int, failures: int) -> dict[str, Any]:
520
+ if not interval:
521
+ return {}
522
+ from ray.train import CheckpointConfig, FailureConfig
523
+
524
+ from tributo_algorithms_boosting.checkpointing import evidence_callback
525
+
526
+ # ray.train conditionally exports V1 or V2 types. The environment gate
527
+ # requires V2 for this path; these options belong to its public API.
528
+ failure_options: dict[str, Any] = {
529
+ "max_failures": failures,
530
+ "controller_failure_limit": 0,
531
+ "max_preemption_failures": 0,
532
+ }
533
+ return {
534
+ "failure_config": FailureConfig(**failure_options),
535
+ "checkpoint_config": CheckpointConfig(num_to_keep=1),
536
+ "callbacks": [
537
+ evidence_callback(
538
+ self.collector,
539
+ cast(str, self.invocation),
540
+ self.plan.runtime.worker_count,
541
+ )
542
+ ],
543
+ }
544
+
545
+ def collect_evidence(self, result: object) -> Mapping[str, Any]:
546
+ import ray
547
+
548
+ if self.collector is None:
549
+ raise AlgorithmExecutionError("XGBoost evidence collector is missing")
550
+ interval = self.plan.algorithm_config.get("training", {}).get(
551
+ "checkpoint_interval_rounds", 0
552
+ )
553
+ try:
554
+ if interval:
555
+ from tributo_algorithms_boosting.checkpointing import check_final_result
556
+
557
+ group = ray.get(self.collector.final_snapshot.remote())
558
+ if group is None:
559
+ raise AlgorithmExecutionError(
560
+ "XGBoost final Worker evidence is missing"
561
+ )
562
+ check_final_result(result, group, cast(str, self.invocation))
563
+ workers = group["workers"]
564
+ else:
565
+ workers = ray.get(self.collector.snapshot.remote())
566
+ finally:
567
+ ray.kill(self.collector, no_restart=True)
568
+ self.collector = None
569
+ if len(workers) != self.plan.runtime.worker_count:
570
+ raise AlgorithmExecutionError("XGBoost did not report every Worker")
571
+ digests = {str(item.get("model_state_digest")) for item in workers}
572
+ if len(digests) != 1:
573
+ raise AlgorithmExecutionError("XGBoost Booster state diverged")
574
+ return {
575
+ "workers": workers,
576
+ "state": {
577
+ "coordination": "framework_native",
578
+ "synchronized": True,
579
+ "bounded": True,
580
+ "global_model_digest": next(iter(digests)),
581
+ "details": {"framework": "xgboost", "collective": "rabit"},
582
+ },
583
+ "input_complete": True,
584
+ }
585
+
586
+ def checkpoint_source(self, result: object) -> object:
587
+ checkpoint = getattr(result, "checkpoint", None)
588
+ if checkpoint is None:
589
+ raise AlgorithmExecutionError("XGBoost result has no checkpoint")
590
+ return checkpoint
591
+
592
+
593
+ def create_algorithm(
594
+ *,
595
+ plan: ResolvedAlgorithmPlan,
596
+ implementation: object,
597
+ artifacts: tuple[object, ...],
598
+ ) -> DistributedXGBoost:
599
+ del artifacts
600
+ if implementation is not DistributedXGBoost:
601
+ raise AlgorithmConfigurationError("XGBoost implementation drifted")
602
+ return DistributedXGBoost(plan)
603
+
604
+
605
+ def export_result(
606
+ *,
607
+ result: object,
608
+ checkpoint: object,
609
+ plan: ResolvedAlgorithmPlan,
610
+ run_id: str,
611
+ ) -> AlgorithmExecutionResult:
612
+ import xgboost
613
+ from tributo.exporting.models import (
614
+ BundleOutputConfig,
615
+ CheckpointField,
616
+ ExportCheckpointV1,
617
+ ExportSource,
618
+ ExportTarget,
619
+ )
620
+ from tributo.exporting.service import BundleExportService
621
+
622
+ from tributo_algorithms_boosting.native import _check_training_metadata
623
+
624
+ raw_metrics = getattr(result, "metrics", {})
625
+ if not isinstance(raw_metrics, Mapping):
626
+ raise AlgorithmExecutionError("XGBoost result metrics must be a mapping")
627
+ metrics: dict[str, Any] = {}
628
+ for key, value in raw_metrics.items():
629
+ if isinstance(key, str) and key.startswith(("train-", "validation-")):
630
+ if (
631
+ not isinstance(value, (int, float))
632
+ or isinstance(value, bool)
633
+ or not math.isfinite(value)
634
+ ):
635
+ raise AlgorithmExecutionError(
636
+ "XGBoost evaluation scores must be finite"
637
+ )
638
+ metrics[key] = float(value)
639
+ elif key in {
640
+ "training_rounds",
641
+ "resumed_from_round",
642
+ "attempt_training_rounds",
643
+ }:
644
+ if (
645
+ not isinstance(value, int)
646
+ or isinstance(value, bool)
647
+ or value < (1 if key == "training_rounds" else 0)
648
+ ):
649
+ raise AlgorithmExecutionError(
650
+ "XGBoost reported training rounds are invalid"
651
+ )
652
+ metrics[key] = value
653
+ output = plan.algorithm_config.get("output")
654
+ if not isinstance(output, Mapping) or not isinstance(output.get("bundle_uri"), str):
655
+ raise AlgorithmConfigurationError("XGBoost output.bundle_uri is required")
656
+ with cast(Any, checkpoint).as_directory() as directory:
657
+ root = Path(directory)
658
+ training = cast(Mapping[str, Any], plan.algorithm_config.get("training", {}))
659
+ if training.get("checkpoint_interval_rounds", 0):
660
+ from tributo_algorithms_boosting.checkpointing import (
661
+ REPORT_KEY,
662
+ read_checkpoint,
663
+ recovery_identity,
664
+ )
665
+
666
+ internal = raw_metrics.get(REPORT_KEY, {})
667
+ if not isinstance(internal, Mapping) or internal.get("phase") != "final":
668
+ raise AlgorithmExecutionError(
669
+ "XGBoost export requires a final checkpoint"
670
+ )
671
+ identity = recovery_identity(
672
+ {
673
+ "invocation": internal.get("invocation"),
674
+ "plan_id": plan.plan_id,
675
+ "feature_names": plan.primary_input_binding.feature_names,
676
+ "label_name": plan.primary_input_binding.label_name,
677
+ "input_roles": [
678
+ binding.name for binding in plan.input_bindings.bindings
679
+ ],
680
+ },
681
+ plan.runtime.worker_count,
682
+ )
683
+ _, recovery = read_checkpoint(
684
+ root,
685
+ identity=identity,
686
+ rounds=training.get("num_rounds", 10),
687
+ patience=training.get("early_stopping_rounds"),
688
+ maximize=training.get("maximize"),
689
+ )
690
+ if (
691
+ recovery["phase"] != "final"
692
+ or recovery["selected_sha256"] != raw_metrics.get("model_state_digest")
693
+ or recovery["completed_rounds"] != metrics.get("training_rounds")
694
+ or metrics.get("resumed_from_round", -1)
695
+ + metrics.get("attempt_training_rounds", -1)
696
+ != recovery["completed_rounds"]
697
+ ):
698
+ raise AlgorithmExecutionError(
699
+ "XGBoost final checkpoint and result diverged"
700
+ )
701
+ booster = xgboost.Booster()
702
+ booster.load_model(root / "model.ubj")
703
+ metadata_path = root / "training_metadata.json"
704
+ try:
705
+ metadata = (
706
+ _validate_training_metadata(
707
+ json.loads(metadata_path.read_text(encoding="utf-8"))
708
+ )
709
+ if metadata_path.is_file()
710
+ else None
711
+ )
712
+ if metadata is not None:
713
+ _check_training_metadata(booster, metadata)
714
+ except (ValueError, OSError, AttributeError) as exc:
715
+ raise AlgorithmExecutionError(
716
+ "XGBoost checkpoint training metadata is invalid"
717
+ ) from exc
718
+ training = cast(Mapping[str, Any], plan.algorithm_config.get("training", {}))
719
+ if training.get("early_stopping_rounds") is not None and metadata is None:
720
+ raise AlgorithmExecutionError(
721
+ "XGBoost early stopping checkpoint metadata is missing"
722
+ )
723
+ if metadata is not None:
724
+ metrics.update(
725
+ {
726
+ key: value
727
+ for key, value in metadata.items()
728
+ if key != "schema_version"
729
+ }
730
+ )
731
+ feature_names = tuple(
732
+ json.loads((root / "feature_names.json").read_text(encoding="utf-8"))
733
+ )
734
+ learner = json.loads(booster.save_config())["learner"]
735
+ objective = str(learner["objective"]["name"])
736
+ classification = objective.startswith(("binary:", "multi:"))
737
+ class_count = max(2, int(learner["learner_model_param"]["num_class"]))
738
+ output_schema = (
739
+ (
740
+ CheckpointField(name="label", dtype="int64", shape=("batch",)),
741
+ CheckpointField(
742
+ name="probabilities",
743
+ dtype="float32",
744
+ shape=("batch", class_count),
745
+ ),
746
+ )
747
+ if classification
748
+ else (
749
+ CheckpointField(
750
+ name="prediction",
751
+ dtype="float32",
752
+ shape=("batch", 1),
753
+ ),
754
+ )
755
+ )
756
+ checkpoint_contract = ExportCheckpointV1(
757
+ trainer_type="xgboost",
758
+ architecture_id="xgboost",
759
+ input_schema=(
760
+ CheckpointField(
761
+ name="float_input",
762
+ dtype="float32",
763
+ shape=("batch", len(feature_names)),
764
+ ),
765
+ ),
766
+ output_schema=output_schema,
767
+ preprocessing={"type": "none"},
768
+ task_type="classification" if classification else "regression",
769
+ framework="xgboost",
770
+ framework_version=xgboost.__version__,
771
+ checkpoint_format_version=1,
772
+ )
773
+ source_fingerprint = hashlib.sha256(
774
+ bytes(booster.save_raw(raw_format="ubj"))
775
+ ).hexdigest()
776
+ metrics["model_state_digest"] = source_fingerprint
777
+ source = ExportSource(
778
+ source_kind="xgboost_result",
779
+ model_object=booster,
780
+ architecture_id="xgboost",
781
+ feature_schema={"feature_names": list(feature_names)},
782
+ metadata={
783
+ "framework": "xgboost",
784
+ "framework_versions": {"xgboost": xgboost.__version__},
785
+ "objective": objective,
786
+ "producer_distribution": "tributo-algorithms",
787
+ **({"training_metadata": metadata} if metadata is not None else {}),
788
+ },
789
+ source_fingerprint=source_fingerprint,
790
+ checkpoint_contract=checkpoint_contract,
791
+ )
792
+ bundle = BundleExportService().export_bundle(
793
+ source,
794
+ BundleOutputConfig(
795
+ bundle_uri=str(output["bundle_uri"]),
796
+ request_id=run_id,
797
+ run_id=run_id,
798
+ targets=[
799
+ ExportTarget(
800
+ name="onnx-model",
801
+ format="onnx",
802
+ exporter_id="official-xgboost-onnx-v1",
803
+ ),
804
+ ExportTarget(
805
+ name="native-model",
806
+ format="ubj",
807
+ exporter_id="official-xgboost-ubj-v1",
808
+ ),
809
+ ],
810
+ roles={"inference": "onnx-model", "native": "native-model"},
811
+ ),
812
+ )
813
+ return AlgorithmExecutionResult(
814
+ status="succeeded",
815
+ metrics=metrics,
816
+ outputs={
817
+ "bundle_id": bundle.bundle_id,
818
+ "bundle_uri": bundle.canonical_uri,
819
+ "execution_id": bundle.execution_id,
820
+ "manifest_sha256": bundle.manifest_sha256,
821
+ },
822
+ )
823
+
824
+
825
+ __all__ = ["DistributedXGBoost", "create_algorithm", "export_result"]