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,150 @@
1
+ """Reusable public XGBoost stage runner for official multi-stage algorithms."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from dataclasses import dataclass
7
+ from typing import Any, Mapping, cast
8
+
9
+ import ray
10
+ from tributo.algorithms.api import AlgorithmExecutionError, WorkerResources
11
+
12
+ from tributo_algorithms_boosting.algorithm import _EvidenceCollector, _train_loop
13
+ from tributo_algorithms_boosting.data_config import CompleteCoverageDataConfig
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class XGBoostStageResult:
18
+ """One completed distributed Booster stage and its bounded evidence."""
19
+
20
+ name: str
21
+ checkpoint: object
22
+ booster_raw: bytes
23
+ evidence: Mapping[str, object]
24
+ row_count: int
25
+
26
+
27
+ class XGBoostStageRunner:
28
+ """Run named Ray Train/XGBoost stages through one audited implementation."""
29
+
30
+ def __init__(
31
+ self,
32
+ *,
33
+ worker_count: int,
34
+ resources_per_worker: WorkerResources,
35
+ storage_path: str,
36
+ input_binding_digest: str,
37
+ ) -> None:
38
+ self.worker_count = worker_count
39
+ self.resources = resources_per_worker
40
+ self.storage_path = storage_path
41
+ self.input_binding_digest = input_binding_digest
42
+
43
+ def fit(
44
+ self,
45
+ name: str,
46
+ dataset: object,
47
+ *,
48
+ feature_names: tuple[str, ...],
49
+ label_name: str,
50
+ params: Mapping[str, object],
51
+ num_boost_round: int,
52
+ ) -> XGBoostStageResult:
53
+ import xgboost
54
+ from ray.train import RunConfig, ScalingConfig
55
+ from ray.train.xgboost import XGBoostTrainer
56
+
57
+ dataset_value = cast(Any, dataset)
58
+ rows = int(dataset_value.count())
59
+ if rows < self.worker_count:
60
+ raise AlgorithmExecutionError(
61
+ f"XGBoost stage {name!r} has insufficient rows for every Worker"
62
+ )
63
+ try:
64
+ block_count = dataset_value.num_blocks()
65
+ except NotImplementedError:
66
+ dataset_value = dataset_value.materialize()
67
+ block_count = dataset_value.num_blocks()
68
+ if block_count < self.worker_count:
69
+ dataset_value = dataset_value.repartition(
70
+ self.worker_count,
71
+ strict=True,
72
+ shuffle=False,
73
+ )
74
+ collector_type = ray.remote(_EvidenceCollector).options(num_cpus=0)
75
+ collector: Any = collector_type.remote()
76
+ stage_digest = hashlib.sha256(
77
+ f"{self.input_binding_digest}:{name}".encode("utf-8")
78
+ ).hexdigest()
79
+ try:
80
+ trainer = XGBoostTrainer(
81
+ train_loop_per_worker=_train_loop,
82
+ train_loop_config={
83
+ "feature_names": list(feature_names),
84
+ "label_name": label_name,
85
+ "params": dict(params),
86
+ "num_boost_round": num_boost_round,
87
+ "evidence_actor": collector,
88
+ "binding_digest": stage_digest,
89
+ },
90
+ scaling_config=ScalingConfig(
91
+ num_workers=self.worker_count,
92
+ use_gpu=self.resources.num_gpus > 0,
93
+ placement_strategy="SPREAD",
94
+ resources_per_worker={
95
+ "CPU": self.resources.num_cpus,
96
+ "GPU": self.resources.num_gpus,
97
+ **dict(self.resources.custom),
98
+ },
99
+ ),
100
+ datasets={"train": dataset_value},
101
+ dataset_config=CompleteCoverageDataConfig(datasets_to_split=["train"]),
102
+ run_config=RunConfig(
103
+ name=f"tributo-xgboost-stage-{name}",
104
+ storage_path=self.storage_path,
105
+ ),
106
+ )
107
+ result = trainer.fit()
108
+ checkpoint = result.checkpoint
109
+ if checkpoint is None:
110
+ raise AlgorithmExecutionError(
111
+ f"XGBoost stage {name!r} did not publish a Checkpoint"
112
+ )
113
+ workers = ray.get(collector.snapshot.remote())
114
+ digests = {str(item.get("model_state_digest")) for item in workers}
115
+ if len(workers) != self.worker_count or len(digests) != 1:
116
+ raise AlgorithmExecutionError(
117
+ f"XGBoost stage {name!r} evidence is incomplete"
118
+ )
119
+ with checkpoint.as_directory() as directory:
120
+ booster = xgboost.Booster()
121
+ booster.load_model(f"{directory}/model.ubj")
122
+ booster_raw = bytes(booster.save_raw(raw_format="ubj"))
123
+ evidence: Mapping[str, object] = {
124
+ "workers": workers,
125
+ "state": {
126
+ "coordination": "framework_native",
127
+ "synchronized": True,
128
+ "bounded": True,
129
+ "global_model_digest": next(iter(digests)),
130
+ "details": {
131
+ "framework": "xgboost",
132
+ "collective": "rabit",
133
+ "stage": name,
134
+ },
135
+ },
136
+ "input_complete": True,
137
+ "expected_training_rows": rows,
138
+ }
139
+ return XGBoostStageResult(
140
+ name=name,
141
+ checkpoint=checkpoint,
142
+ booster_raw=booster_raw,
143
+ evidence=evidence,
144
+ row_count=rows,
145
+ )
146
+ finally:
147
+ ray.kill(collector, no_restart=True)
148
+
149
+
150
+ __all__ = ["XGBoostStageResult", "XGBoostStageRunner"]
@@ -0,0 +1,5 @@
1
+ """Official CatBoost algorithms for Tributo."""
2
+
3
+ from tributo_algorithms_catboost.descriptor import CATBOOST_DESCRIPTOR
4
+
5
+ __all__ = ["CATBOOST_DESCRIPTOR"]
@@ -0,0 +1,379 @@
1
+ """Conditional CatBoost ensemble implementation over Ray shards."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pickle
6
+ from collections.abc import Mapping
7
+ from typing import Any, cast
8
+
9
+ import numpy as np
10
+ from tributo.algorithms import EnsembleUnitSpec, ParallelEnsembleAlgorithm
11
+ from tributo.algorithms.api import (
12
+ AlgorithmConfigurationError,
13
+ AlgorithmExecutionError,
14
+ AlgorithmExecutionResult,
15
+ AlgorithmInputError,
16
+ ResolvedAlgorithmPlan,
17
+ )
18
+ from tributo.algorithms.spi import (
19
+ AlgorithmExecutionContext,
20
+ MaterializedTabularInputView,
21
+ )
22
+
23
+
24
+ class CatBoostModel:
25
+ """Final CatBoost model plus ordered feature metadata."""
26
+
27
+ def __init__(
28
+ self,
29
+ model: object,
30
+ feature_names: tuple[str, ...],
31
+ task: str,
32
+ cat_features: tuple[int, ...] = (),
33
+ classes: tuple[object, ...] = (),
34
+ ) -> None:
35
+ self.model = model
36
+ self.feature_names = feature_names
37
+ self.task = task
38
+ self.cat_features = cat_features
39
+ self.classes = classes
40
+
41
+
42
+ class _CheckpointCodec:
43
+ def dumps(self, value: object) -> bytes:
44
+ return pickle.dumps(value, protocol=5)
45
+
46
+ def loads(self, payload: bytes) -> object:
47
+ return pickle.loads(payload)
48
+
49
+
50
+ def _arrays(
51
+ inputs: Mapping[str, object],
52
+ *,
53
+ cat_indices: tuple[int, ...],
54
+ ) -> tuple[np.ndarray, np.ndarray, tuple[str, ...]]:
55
+ view = cast(MaterializedTabularInputView, inputs["train"])
56
+ if view.label_name is None:
57
+ raise AlgorithmConfigurationError("CatBoost requires a label")
58
+ columns = view.columns()
59
+ raw_features = [np.asarray(columns[name]) for name in view.feature_names]
60
+ if not raw_features or any(
61
+ values.ndim != 1
62
+ or not values.shape[0]
63
+ or values.shape[0] != raw_features[0].shape[0]
64
+ for values in raw_features
65
+ ):
66
+ raise AlgorithmExecutionError(
67
+ "CatBoost input features must be non-empty columns"
68
+ )
69
+ if cat_indices:
70
+ features = np.empty((raw_features[0].shape[0], len(raw_features)), dtype=object)
71
+ for index, values in enumerate(raw_features):
72
+ if index in cat_indices:
73
+ features[:, index] = np.asarray(values).astype(str)
74
+ else:
75
+ features[:, index] = np.asarray(values, dtype=np.float64)
76
+ numeric_features = [
77
+ np.asarray(values, dtype=np.float64)
78
+ for index, values in enumerate(raw_features)
79
+ if index not in cat_indices
80
+ ]
81
+ if (
82
+ numeric_features
83
+ and not np.isfinite(np.column_stack(numeric_features)).all()
84
+ ):
85
+ raise AlgorithmExecutionError(
86
+ "CatBoost numeric input contains non-finite values"
87
+ )
88
+ else:
89
+ try:
90
+ features = np.column_stack(
91
+ [np.asarray(values, dtype=np.float64) for values in raw_features]
92
+ )
93
+ except (TypeError, ValueError) as exc:
94
+ raise AlgorithmExecutionError(
95
+ "CatBoost categorical columns require explicit cat_features"
96
+ ) from exc
97
+ if not np.isfinite(features).all():
98
+ raise AlgorithmExecutionError(
99
+ "CatBoost input contains non-finite numeric values"
100
+ )
101
+ labels = np.asarray(columns[view.label_name])
102
+ if not len(labels) or labels.shape != (features.shape[0],):
103
+ raise AlgorithmExecutionError(
104
+ "CatBoost input contains no rows or mismatched labels"
105
+ )
106
+ return features, labels, tuple(view.feature_names)
107
+
108
+
109
+ class CatBoostEnsemble(ParallelEnsembleAlgorithm[CatBoostModel, CatBoostModel]):
110
+ """Train one CatBoost model per shard and combine additive models conditionally."""
111
+
112
+ def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
113
+ self._plan = plan
114
+ self._feature_names = plan.primary_input_binding.feature_names
115
+
116
+ def plan_units(
117
+ self,
118
+ config: Mapping[str, Any],
119
+ input_descriptor: object,
120
+ seed: int,
121
+ ) -> tuple[EnsembleUnitSpec, ...]:
122
+ del input_descriptor
123
+ count = int(config.get("unit_count", config.get("n_estimators", 4)))
124
+ if count < 1:
125
+ raise AlgorithmConfigurationError("CatBoost unit_count must be positive")
126
+ return tuple(
127
+ EnsembleUnitSpec(unit_id=f"catboost-{index}", seed=seed + index, payload={})
128
+ for index in range(count)
129
+ )
130
+
131
+ def fit_unit(
132
+ self,
133
+ unit: EnsembleUnitSpec,
134
+ inputs: Mapping[str, object],
135
+ context: AlgorithmExecutionContext,
136
+ ) -> CatBoostModel:
137
+ del context
138
+ from catboost import CatBoostClassifier, CatBoostRegressor
139
+
140
+ config = self._plan.algorithm_config
141
+ model_config = config.get("model", {})
142
+ if not isinstance(model_config, Mapping):
143
+ raise AlgorithmConfigurationError("CatBoost model config must be a mapping")
144
+ task = str(config.get("task", "classification"))
145
+ cat_features = model_config.get("cat_features", ())
146
+ if not isinstance(cat_features, (list, tuple)):
147
+ raise AlgorithmConfigurationError(
148
+ "CatBoost cat_features must be a sequence"
149
+ )
150
+ feature_names = self._feature_names
151
+ cat_indices: list[int] = []
152
+ for item in cat_features:
153
+ if isinstance(item, str):
154
+ if item not in feature_names:
155
+ raise AlgorithmConfigurationError(
156
+ f"CatBoost cat feature is not bound: {item!r}"
157
+ )
158
+ cat_indices.append(feature_names.index(item))
159
+ elif isinstance(item, int) and not isinstance(item, bool):
160
+ if not 0 <= item < len(feature_names):
161
+ raise AlgorithmConfigurationError(
162
+ f"CatBoost cat feature index is out of range: {item}"
163
+ )
164
+ cat_indices.append(item)
165
+ else:
166
+ raise AlgorithmConfigurationError(
167
+ "CatBoost cat_features entries must be names or indices"
168
+ )
169
+ if len(set(cat_indices)) != len(cat_indices):
170
+ raise AlgorithmConfigurationError("CatBoost cat_features must be unique")
171
+ features, labels, feature_names = _arrays(
172
+ inputs, cat_indices=tuple(cat_indices)
173
+ )
174
+ if task == "regression":
175
+ try:
176
+ labels = np.asarray(labels, dtype=np.float64)
177
+ except (TypeError, ValueError) as exc:
178
+ raise AlgorithmInputError(
179
+ "CatBoost regression labels must be numeric"
180
+ ) from exc
181
+ if not np.isfinite(labels).all():
182
+ raise AlgorithmInputError("CatBoost regression labels must be finite")
183
+ elif task == "classification":
184
+ try:
185
+ numeric_labels = np.asarray(labels, dtype=np.float64)
186
+ if (
187
+ not np.isfinite(numeric_labels).all()
188
+ or not np.equal(numeric_labels, np.floor(numeric_labels)).all()
189
+ ):
190
+ raise ValueError
191
+ labels = numeric_labels.astype(np.int64)
192
+ except (TypeError, ValueError):
193
+ if any(item is None for item in labels):
194
+ raise AlgorithmInputError(
195
+ "CatBoost classification labels must not contain nulls"
196
+ ) from None
197
+ labels = np.asarray(labels, dtype=str)
198
+ else:
199
+ raise AlgorithmConfigurationError(
200
+ "CatBoost task must be classification or regression"
201
+ )
202
+ params: dict[str, Any] = {
203
+ "iterations": int(model_config.get("iterations", 100)),
204
+ "depth": int(model_config.get("depth", 6)),
205
+ "learning_rate": float(model_config.get("learning_rate", 0.05)),
206
+ "random_seed": int(unit.seed),
207
+ "verbose": False,
208
+ "thread_count": 1,
209
+ "allow_writing_files": False,
210
+ }
211
+ if cat_features:
212
+ params["cat_features"] = cat_indices
213
+ estimator: Any
214
+ if task == "regression":
215
+ estimator = CatBoostRegressor(**params)
216
+ elif task == "classification":
217
+ estimator = CatBoostClassifier(**params)
218
+ estimator.fit(features, labels)
219
+ raw_classes = getattr(estimator, "classes_", ())
220
+ classes = tuple(
221
+ raw_classes.tolist() if hasattr(raw_classes, "tolist") else raw_classes
222
+ )
223
+ return CatBoostModel(
224
+ estimator, feature_names, task, tuple(cat_indices), classes
225
+ )
226
+
227
+ def merge_units(self, ordered_units: tuple[CatBoostModel, ...]) -> object:
228
+ return ordered_units
229
+
230
+ def finalize_ensemble(self, merged: object) -> CatBoostModel:
231
+ from catboost import sum_models
232
+
233
+ units = cast(tuple[CatBoostModel, ...], merged)
234
+ if not units:
235
+ raise AlgorithmExecutionError("CatBoost requires at least one fitted unit")
236
+ first = units[0]
237
+ if any(
238
+ unit.task != first.task
239
+ or unit.feature_names != first.feature_names
240
+ or unit.cat_features != first.cat_features
241
+ or unit.classes != first.classes
242
+ for unit in units
243
+ ):
244
+ raise AlgorithmExecutionError("CatBoost unit metadata is inconsistent")
245
+ models = [unit.model for unit in units]
246
+ combined = sum_models(models, weights=[1.0 / len(models)] * len(models))
247
+ return CatBoostModel(
248
+ combined,
249
+ first.feature_names,
250
+ first.task,
251
+ first.cat_features,
252
+ first.classes,
253
+ )
254
+
255
+ def unit_schema(self) -> Mapping[str, object]:
256
+ return {
257
+ "model": "catboost",
258
+ "feature_names": "tuple[str]",
259
+ "cat_features": "tuple[int]",
260
+ "classes": "tuple[scalar]",
261
+ "task": "classification|regression",
262
+ }
263
+
264
+ @property
265
+ def retry_safe(self) -> bool:
266
+ return True
267
+
268
+
269
+ def create_algorithm(
270
+ *,
271
+ plan: ResolvedAlgorithmPlan,
272
+ implementation: object,
273
+ artifacts: tuple[object, ...],
274
+ ) -> CatBoostEnsemble:
275
+ """Construct the descriptor-selected CatBoost ensemble."""
276
+ del artifacts
277
+ if implementation is not CatBoostEnsemble:
278
+ raise AlgorithmConfigurationError("CatBoost implementation reference drifted")
279
+ return CatBoostEnsemble(plan)
280
+
281
+
282
+ def export_result(
283
+ *,
284
+ model: CatBoostModel,
285
+ plan: ResolvedAlgorithmPlan,
286
+ run_id: str | None = None,
287
+ ) -> AlgorithmExecutionResult:
288
+ """Export the conditional CatBoost ensemble through native Bundle format."""
289
+ if not isinstance(model, CatBoostModel):
290
+ raise AlgorithmExecutionError("CatBoost exporter received an invalid model")
291
+ output = plan.algorithm_config.get("output")
292
+ if not isinstance(output, Mapping) or not isinstance(output.get("bundle_uri"), str):
293
+ raise AlgorithmConfigurationError("CatBoost output.bundle_uri is required")
294
+ import catboost
295
+ from tributo.exporting.models import (
296
+ BundleOutputConfig,
297
+ CheckpointField,
298
+ ExportCheckpointV1,
299
+ ExportSource,
300
+ ExportTarget,
301
+ )
302
+ from tributo.exporting.service import BundleExportService
303
+
304
+ classification = model.task == "classification"
305
+ raw_classes = getattr(model.model, "classes_", ())
306
+ classes = model.classes or tuple(
307
+ raw_classes.tolist() if hasattr(raw_classes, "tolist") else raw_classes
308
+ )
309
+ class_count = len(classes) or 2
310
+ output_schema = (
311
+ (
312
+ CheckpointField(name="label", dtype="int64", shape=("batch",)),
313
+ CheckpointField(
314
+ name="probabilities", dtype="float32", shape=("batch", class_count)
315
+ ),
316
+ )
317
+ if classification
318
+ else (CheckpointField(name="variable", dtype="float32", shape=("batch", 1)),)
319
+ )
320
+ source = ExportSource(
321
+ source_kind="catboost_result",
322
+ model_object=model,
323
+ feature_schema={
324
+ "feature_names": list(model.feature_names),
325
+ "cat_features": list(model.cat_features),
326
+ "classes": list(classes),
327
+ },
328
+ metadata={
329
+ "framework": "catboost",
330
+ "framework_versions": {"catboost": catboost.__version__},
331
+ "task_type": model.task,
332
+ "producer_distribution": "tributo-algorithms",
333
+ },
334
+ checkpoint_contract=ExportCheckpointV1(
335
+ trainer_type="catboost",
336
+ architecture_id=plan.resolution.algorithm,
337
+ input_schema=(
338
+ CheckpointField(
339
+ name="float_input",
340
+ dtype="object" if model.cat_features else "float32",
341
+ shape=("batch", len(model.feature_names)),
342
+ ),
343
+ ),
344
+ output_schema=output_schema,
345
+ task_type=model.task,
346
+ framework="catboost",
347
+ framework_version="1",
348
+ ),
349
+ )
350
+ bundle = BundleExportService().export_bundle(
351
+ source,
352
+ BundleOutputConfig(
353
+ bundle_uri=cast(str, output["bundle_uri"]),
354
+ request_id=run_id,
355
+ run_id=run_id,
356
+ targets=[
357
+ ExportTarget(
358
+ name="native-model",
359
+ format="catboost",
360
+ exporter_id="catboost-native-v1",
361
+ )
362
+ ],
363
+ roles={"inference": "native-model"},
364
+ ),
365
+ )
366
+ return AlgorithmExecutionResult(
367
+ status="succeeded",
368
+ outputs={
369
+ "bundle_id": bundle.bundle_id,
370
+ "bundle_uri": bundle.canonical_uri,
371
+ "execution_id": bundle.execution_id,
372
+ "manifest_sha256": bundle.manifest_sha256,
373
+ "feature_names": list(model.feature_names),
374
+ "task": model.task,
375
+ },
376
+ )
377
+
378
+
379
+ __all__ = ["CatBoostEnsemble", "CatBoostModel", "create_algorithm", "export_result"]
@@ -0,0 +1,145 @@
1
+ """Executable contracts for the CatBoost algorithm package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any
7
+
8
+
9
+ class CatBoostConfigValidator:
10
+ """Validate the intentionally narrow CatBoost configuration surface."""
11
+
12
+ api_version = 1
13
+ schema_digest = "5" * 64
14
+ _MODEL_ALLOWED = {"cat_features", "depth", "iterations", "learning_rate"}
15
+
16
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
17
+ allowed = {
18
+ "model",
19
+ "n_estimators",
20
+ "output",
21
+ "runtime",
22
+ "seed",
23
+ "task",
24
+ "training",
25
+ "unit_count",
26
+ }
27
+ unknown = sorted(set(value) - allowed)
28
+ if unknown:
29
+ raise ValueError(f"unknown CatBoost config keys: {unknown}")
30
+ for name in {"model", "output", "runtime", "training"}:
31
+ item = value.get(name)
32
+ if item is not None and not isinstance(item, Mapping):
33
+ raise ValueError(f"{name} must be a mapping")
34
+ model = value.get("model", {})
35
+ if not isinstance(model, Mapping):
36
+ raise ValueError("CatBoost model must be a mapping")
37
+ unknown_model = sorted(set(model) - self._MODEL_ALLOWED)
38
+ if unknown_model:
39
+ raise ValueError(f"unknown CatBoost model keys: {unknown_model}")
40
+ for name in ("depth", "iterations"):
41
+ item = model.get(name)
42
+ if item is not None and (
43
+ not isinstance(item, int) or isinstance(item, bool) or item < 1
44
+ ):
45
+ raise ValueError(f"model.{name} must be a positive integer")
46
+ learning_rate = model.get("learning_rate")
47
+ if learning_rate is not None and (
48
+ not isinstance(learning_rate, (int, float))
49
+ or isinstance(learning_rate, bool)
50
+ or not 0 < float(learning_rate)
51
+ ):
52
+ raise ValueError("model.learning_rate must be positive")
53
+ cat_features = model.get("cat_features", ())
54
+ if not isinstance(cat_features, (list, tuple)) or any(
55
+ not isinstance(item, (str, int)) or isinstance(item, bool)
56
+ for item in cat_features
57
+ ):
58
+ raise ValueError("model.cat_features must contain names or indices")
59
+ if len(set(cat_features)) != len(cat_features):
60
+ raise ValueError("model.cat_features must be unique")
61
+ task = value.get("task")
62
+ if task is not None and task not in {"classification", "regression"}:
63
+ raise ValueError("CatBoost task must be classification or regression")
64
+ for name in ("n_estimators", "unit_count"):
65
+ item = value.get(name)
66
+ if item is not None and (
67
+ not isinstance(item, int) or isinstance(item, bool) or item < 1
68
+ ):
69
+ raise ValueError(f"{name} must be a positive integer")
70
+ seed = value.get("seed")
71
+ if seed is not None and (
72
+ not isinstance(seed, int) or isinstance(seed, bool) or seed < 0
73
+ ):
74
+ raise ValueError("CatBoost seed must be a non-negative integer")
75
+ output = value.get("output")
76
+ if (
77
+ not isinstance(output, Mapping)
78
+ or not isinstance(output.get("bundle_uri"), str)
79
+ or not output["bundle_uri"]
80
+ ):
81
+ raise ValueError("CatBoost output.bundle_uri is required")
82
+ return dict(value)
83
+
84
+
85
+ class CatBoostInputValidator:
86
+ """Require one labeled feature-only-compatible tabular role."""
87
+
88
+ api_version = 1
89
+ schema_digest = "6" * 64
90
+
91
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
92
+ bindings = value.get("bindings")
93
+ descriptors = value.get("descriptors")
94
+ if not isinstance(bindings, list) or not isinstance(descriptors, Mapping):
95
+ raise ValueError("CatBoost input requires bindings and descriptors")
96
+ binding = next(
97
+ (
98
+ item
99
+ for item in bindings
100
+ if isinstance(item, Mapping) and item.get("name") == "train"
101
+ ),
102
+ None,
103
+ )
104
+ if not isinstance(binding, Mapping) or not binding.get("feature_names"):
105
+ raise ValueError("CatBoost input requires train feature columns")
106
+ if not isinstance(binding.get("label_name"), str) or not binding["label_name"]:
107
+ raise ValueError("CatBoost input requires a label")
108
+ return value
109
+
110
+
111
+ class CatBoostOutputValidator:
112
+ """Require successful CatBoost Bundle output."""
113
+
114
+ api_version = 1
115
+ schema_digest = "7" * 64
116
+
117
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
118
+ outputs = value.get("outputs")
119
+ if value.get("status") != "succeeded" or not isinstance(outputs, Mapping):
120
+ raise ValueError("CatBoost output requires successful execution")
121
+ if not outputs.get("bundle_uri"):
122
+ raise ValueError("CatBoost output requires bundle_uri")
123
+ return value
124
+
125
+
126
+ class CatBoostCoverageValidator:
127
+ """Require complete distributed CatBoost ensemble coverage."""
128
+
129
+ api_version = 1
130
+ schema_digest = "8" * 64
131
+
132
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
133
+ if value.get("input_complete") is not True:
134
+ raise ValueError("CatBoost input coverage is incomplete")
135
+ if value.get("distributed") is not True:
136
+ raise ValueError("CatBoost execution did not prove distribution")
137
+ return value
138
+
139
+
140
+ __all__ = [
141
+ "CatBoostConfigValidator",
142
+ "CatBoostCoverageValidator",
143
+ "CatBoostInputValidator",
144
+ "CatBoostOutputValidator",
145
+ ]