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,59 @@
1
+ """Ray Train data configuration that preserves every input row.
2
+
3
+ Ray's stock :class:`ray.train.DataConfig` uses ``streaming_split(...,
4
+ equal=True)``. That is convenient for synchronous data-parallel algorithms, but
5
+ it intentionally drops a remainder when the row count is not divisible by the
6
+ worker count. Tributo's execution receipt promises complete input coverage, so
7
+ official algorithms use this configuration to request the lossless split.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any
13
+
14
+ from ray.train import DataConfig
15
+
16
+
17
+ class CompleteCoverageDataConfig(DataConfig):
18
+ """Split Train datasets without dropping a remainder row."""
19
+
20
+ def configure(
21
+ self,
22
+ datasets: dict[str, Any],
23
+ world_size: int,
24
+ worker_handles: list[Any] | None,
25
+ worker_node_ids: list[str] | None,
26
+ **kwargs: Any,
27
+ ) -> list[dict[str, Any]]:
28
+ del worker_handles, kwargs
29
+ # Ray 2.59.0 compatibility: retain its execution-option resolution
30
+ # and locality setup, changing only streaming_split's ``equal``.
31
+ output: list[dict[str, Any]] = [{} for _ in range(world_size)]
32
+ for dataset_name, dataset in datasets.items():
33
+ if dataset.name is None:
34
+ dataset.set_name(dataset_name)
35
+
36
+ if self._datasets_to_split == "all":
37
+ datasets_to_split = set(datasets.keys())
38
+ else:
39
+ datasets_to_split = set(self._datasets_to_split)
40
+ locality_hints = worker_node_ids if self._enable_shard_locality else None
41
+ for name, dataset in datasets.items():
42
+ dataset = dataset.copy(dataset)
43
+ dataset.context.execution_options = self._resolve_execution_options(name)
44
+ if name in datasets_to_split:
45
+ for index, split in enumerate(
46
+ dataset.streaming_split(
47
+ world_size,
48
+ equal=False,
49
+ locality_hints=locality_hints,
50
+ )
51
+ ):
52
+ output[index][name] = split
53
+ else:
54
+ for index in range(world_size):
55
+ output[index][name] = dataset.iterator()
56
+ return output
57
+
58
+
59
+ __all__ = ["CompleteCoverageDataConfig"]
@@ -0,0 +1,124 @@
1
+ """Descriptor for official out-of-tree distributed XGBoost."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from tributo.algorithms import AlgorithmBuilder
6
+ from tributo.algorithms.api import (
7
+ ContractBinding,
8
+ ContractBindingSet,
9
+ DistributionStrategy,
10
+ EnvironmentSpec,
11
+ ExecutionMode,
12
+ ExecutionProfile,
13
+ FrameworkNativeInputRoute,
14
+ FrameworkNativePolicy,
15
+ QualifiedReference,
16
+ WorkerRange,
17
+ WorkerResources,
18
+ )
19
+ from tributo.training.algorithm_spec import (
20
+ AlgorithmSpec,
21
+ Capability,
22
+ DataLoadingMode,
23
+ ProblemType,
24
+ ResourceHints,
25
+ )
26
+
27
+ _PACKAGE = "tributo-algorithms"
28
+ _VERSION = "0.1.0"
29
+
30
+
31
+ def _binding(contract_id: str, digest: str, validator: str) -> ContractBinding:
32
+ return ContractBinding(
33
+ contract_id=contract_id,
34
+ schema_version=1,
35
+ schema_digest=digest * 64,
36
+ validator_ref=QualifiedReference.parse(
37
+ f"tributo_algorithms_boosting.contracts:{validator}"
38
+ ),
39
+ )
40
+
41
+
42
+ _SPEC = AlgorithmSpec(
43
+ name="xgboost",
44
+ trainer_cls=None,
45
+ version="1.0.0",
46
+ default_config={},
47
+ resource_hints=ResourceHints(gpu_required=False),
48
+ extras_group="training",
49
+ problem_types=(
50
+ ProblemType.BINARY_CLASSIFICATION,
51
+ ProblemType.MULTI_CLASS_CLASSIFICATION,
52
+ ProblemType.REGRESSION,
53
+ ),
54
+ data_modality=("tabular",),
55
+ capabilities=(
56
+ Capability.TUNABLE,
57
+ Capability.EXPORTABLE,
58
+ Capability.DISTRIBUTED,
59
+ ),
60
+ data_loading=DataLoadingMode.CANONICAL_DRIVER,
61
+ operations=("fit",),
62
+ learning_paradigm="supervised",
63
+ model_family="gradient_boosted_trees",
64
+ data_modalities=("tabular",),
65
+ lifecycle_kind="bounded_training",
66
+ allowed_execution_modes=(ExecutionMode.FRAMEWORK_NATIVE.value,),
67
+ config_contract_ref="tributo.algorithm-config.xgboost.v1",
68
+ input_contract_ref="tributo.algorithm-input.ray-tabular.v1",
69
+ output_contract_ref="tributo.algorithm-result.execution-only.v1",
70
+ )
71
+
72
+ XGBOOST_DESCRIPTOR = AlgorithmBuilder.from_distributed_algorithm(
73
+ spec=_SPEC,
74
+ implementation_id="tributo.official.boosting.xgboost",
75
+ implementation_version="1.0.0",
76
+ implementation="tributo_algorithms_boosting.algorithm:DistributedXGBoost",
77
+ executable_factory="tributo_algorithms_boosting.algorithm:create_algorithm",
78
+ distribution=_PACKAGE,
79
+ framework="xgboost",
80
+ environment=EnvironmentSpec(
81
+ environment_id="tributo.official.boosting.v1",
82
+ dependencies=(
83
+ "onnxmltools>=1.13",
84
+ "scikit-learn>=1.4,<2",
85
+ "xgboost>=2.1,<4",
86
+ "tributo>=1.2",
87
+ f"tributo-algorithms[boosting]=={_VERSION}",
88
+ ),
89
+ ),
90
+ allowed_config_keys=("data", "model", "output", "ray", "resource", "training"),
91
+ strategy=DistributionStrategy.FRAMEWORK_NATIVE,
92
+ supported_worker_range=WorkerRange(2, 1024),
93
+ supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
94
+ resources_per_worker=WorkerResources(num_cpus=1),
95
+ policy=FrameworkNativePolicy(
96
+ framework="xgboost-rabit",
97
+ evidence_collector_ref=(
98
+ "tributo_algorithms_boosting.algorithm:DistributedXGBoost.collect_evidence"
99
+ ),
100
+ input_routes=(
101
+ FrameworkNativeInputRoute("train", "partitioned"),
102
+ FrameworkNativeInputRoute("validation", "partitioned", required=False),
103
+ ),
104
+ ),
105
+ package_name=_PACKAGE,
106
+ package_version=_VERSION,
107
+ tributo_version_spec=">=1.2",
108
+ exporter="tributo_algorithms_boosting.algorithm:export_result",
109
+ flavor_id="onnx-runtime-v1",
110
+ contract_bindings=ContractBindingSet(
111
+ config=_binding(_SPEC.config_contract_ref or "", "1", "XGBoostConfigValidator"),
112
+ input=_binding(_SPEC.input_contract_ref or "", "2", "XGBoostInputValidator"),
113
+ output=_binding(_SPEC.output_contract_ref or "", "3", "XGBoostOutputValidator"),
114
+ coverage=_binding(
115
+ "tributo.official.xgboost.coverage.v1",
116
+ "4",
117
+ "XGBoostCoverageValidator",
118
+ ),
119
+ ),
120
+ descriptor_api_version=2,
121
+ is_default=True,
122
+ )
123
+
124
+ __all__ = ["XGBOOST_DESCRIPTOR"]
@@ -0,0 +1,511 @@
1
+ """Ray Train framework-native distributed LightGBM implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import tempfile
8
+ from collections.abc import Mapping
9
+ from pathlib import Path
10
+ from typing import Any, cast
11
+
12
+ import numpy as np
13
+ from tributo.algorithms.api import (
14
+ AlgorithmConfigurationError,
15
+ AlgorithmExecutionError,
16
+ AlgorithmExecutionResult,
17
+ ArtifactDraft,
18
+ ResolvedAlgorithmPlan,
19
+ )
20
+ from tributo.algorithms.spi import FrameworkNativeAlgorithm
21
+
22
+
23
+ class _EvidenceCollector:
24
+ def __init__(self) -> None:
25
+ self.records: dict[int, dict[str, object]] = {}
26
+
27
+ def record(self, value: dict[str, object]) -> None:
28
+ rank = value.get("rank")
29
+ if not isinstance(rank, int) or isinstance(rank, bool):
30
+ raise TypeError("LightGBM evidence rank must be an integer")
31
+ if rank in self.records:
32
+ raise ValueError(f"duplicate LightGBM evidence rank: {rank}")
33
+ self.records[rank] = dict(value)
34
+
35
+ def snapshot(self) -> list[dict[str, object]]:
36
+ return [self.records[rank] for rank in sorted(self.records)]
37
+
38
+
39
+ def _model_task(model: Mapping[str, Any]) -> tuple[str, int]:
40
+ """Resolve the bounded export task from the LightGBM model config."""
41
+ requested = str(model.get("task", "")).lower()
42
+ objective = str(model.get("objective", "")).lower()
43
+ if requested not in {"", "classification", "regression"}:
44
+ raise AlgorithmConfigurationError(
45
+ "LightGBM model.task must be classification or regression"
46
+ )
47
+ objective_is_classification = objective.startswith(
48
+ ("binary", "multiclass", "multiclassova", "multiclassova2")
49
+ )
50
+ if requested == "classification" and objective and not objective_is_classification:
51
+ raise AlgorithmConfigurationError(
52
+ "LightGBM classification task conflicts with model.objective"
53
+ )
54
+ if requested == "regression" and objective_is_classification:
55
+ raise AlgorithmConfigurationError(
56
+ "LightGBM regression task conflicts with model.objective"
57
+ )
58
+ raw_class_count = model.get("num_class")
59
+ if objective.startswith("multiclass") and raw_class_count is None:
60
+ raise AlgorithmConfigurationError(
61
+ "multiclass LightGBM requires model.num_class"
62
+ )
63
+ if (
64
+ objective == "binary"
65
+ and raw_class_count is not None
66
+ and int(raw_class_count) != 2
67
+ ):
68
+ raise AlgorithmConfigurationError("binary LightGBM requires model.num_class=2")
69
+ classification = requested == "classification" or objective.startswith(
70
+ ("binary", "multiclass", "multiclassova", "multiclassova2")
71
+ )
72
+ if not classification:
73
+ return "regression", 1
74
+ try:
75
+ class_count = int(model.get("num_class", 2))
76
+ except (TypeError, ValueError) as exc:
77
+ raise AlgorithmConfigurationError(
78
+ "LightGBM model.num_class must be an integer"
79
+ ) from exc
80
+ if class_count < 2:
81
+ raise AlgorithmConfigurationError(
82
+ "LightGBM classification requires at least two classes"
83
+ )
84
+ return "classification", class_count
85
+
86
+
87
+ def _training_params(model: Mapping[str, Any]) -> dict[str, Any]:
88
+ """Return LightGBM params without Tributo-only control keys."""
89
+ params = dict(model)
90
+ task, class_count = _model_task(model)
91
+ params.pop("task", None)
92
+ if task == "classification":
93
+ params.setdefault("objective", "multiclass" if class_count > 2 else "binary")
94
+ if class_count > 2:
95
+ params.setdefault("num_class", class_count)
96
+ else:
97
+ params.setdefault("objective", "regression")
98
+ params.setdefault("num_threads", 1)
99
+ return params
100
+
101
+
102
+ def _train_loop(config: dict[str, Any]) -> None:
103
+ import lightgbm
104
+ import numpy as np
105
+ import ray
106
+ from ray import train
107
+ from ray.train import Checkpoint
108
+ from ray.train.lightgbm import get_network_params
109
+
110
+ shard = train.get_dataset_shard("train")
111
+ # The native LightGBM API consumes pandas, so this materializes one
112
+ # complete Ray shard per worker; external-memory training is out of scope.
113
+ frame = shard.materialize().to_pandas()
114
+ feature_names = list(config["feature_names"])
115
+ label_name = str(config["label_name"])
116
+ if frame.empty:
117
+ raise AlgorithmExecutionError("LightGBM worker shard is empty")
118
+ train_set = lightgbm.Dataset(
119
+ frame[feature_names],
120
+ label=frame[label_name],
121
+ free_raw_data=False,
122
+ )
123
+ params = dict(config["params"])
124
+ params.update(
125
+ {
126
+ "tree_learner": "data_parallel",
127
+ "pre_partition": True,
128
+ **get_network_params(),
129
+ }
130
+ )
131
+ booster = lightgbm.train(
132
+ params,
133
+ train_set,
134
+ num_boost_round=int(config["num_boost_round"]),
135
+ valid_sets=[train_set],
136
+ valid_names=["train"],
137
+ )
138
+ context = train.get_context()
139
+ rank = context.get_world_rank()
140
+ world_size = context.get_world_size()
141
+ probe = np.linspace(
142
+ -1.0,
143
+ 1.0,
144
+ 8 * len(feature_names),
145
+ dtype=np.float64,
146
+ ).reshape(8, len(feature_names))
147
+ predictions = np.asarray(booster.predict(probe, raw_score=True), dtype=np.float64)
148
+ digest = hashlib.sha256(
149
+ predictions.tobytes()
150
+ + str(booster.current_iteration()).encode("ascii")
151
+ + str(booster.num_feature()).encode("ascii")
152
+ ).hexdigest()
153
+ runtime = ray.get_runtime_context()
154
+ assigned = runtime.get_assigned_resources()
155
+ evidence = {
156
+ "worker_id": str(runtime.get_worker_id()),
157
+ "node_id": str(runtime.get_node_id()),
158
+ "rank": rank,
159
+ "world_size": world_size,
160
+ "shard_id": hashlib.sha256(
161
+ f"{config['binding_digest']}:{rank}/{world_size}".encode("ascii")
162
+ ).hexdigest(),
163
+ "rows_processed": int(frame.shape[0]),
164
+ "input_rows": {"train": int(frame.shape[0])},
165
+ "batch_count": int(config["num_boost_round"]),
166
+ "collective_steps": int(config["num_boost_round"]),
167
+ "model_state_digest": digest,
168
+ "resources": {
169
+ "num_cpus": float(assigned.get("CPU", 0.0)),
170
+ "num_gpus": float(assigned.get("GPU", 0.0)),
171
+ "custom": {
172
+ str(name): float(value)
173
+ for name, value in assigned.items()
174
+ if name not in {"CPU", "GPU", "memory", "object_store_memory"}
175
+ },
176
+ },
177
+ }
178
+ ray.get(config["evidence_actor"].record.remote(evidence))
179
+ if rank == 0:
180
+ with tempfile.TemporaryDirectory(prefix="tributo-lightgbm-") as directory:
181
+ root = Path(directory)
182
+ booster.save_model(str(root / "model.txt"))
183
+ (root / "feature_names.json").write_text(
184
+ json.dumps(feature_names), encoding="utf-8"
185
+ )
186
+ (root / "model_config.json").write_text(
187
+ json.dumps(
188
+ {
189
+ "task": config["task"],
190
+ "class_count": config["class_count"],
191
+ },
192
+ sort_keys=True,
193
+ ),
194
+ encoding="utf-8",
195
+ )
196
+ train.report(
197
+ {"model_state_digest": digest},
198
+ checkpoint=Checkpoint.from_directory(root),
199
+ )
200
+ else:
201
+ train.report({"model_state_digest": digest})
202
+
203
+
204
+ class DistributedLightGBM(FrameworkNativeAlgorithm):
205
+ """Train one synchronized LightGBM Booster through Ray Train."""
206
+
207
+ def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
208
+ self.plan = plan
209
+ self.collector: Any | None = None
210
+ if plan.runtime.resume_from is not None:
211
+ raise AlgorithmConfigurationError(
212
+ "official LightGBM resume requires a separate recovery gate"
213
+ )
214
+
215
+ def validate_environment(self) -> None:
216
+ try:
217
+ import lightgbm
218
+ from ray.train.lightgbm import LightGBMTrainer
219
+ except ImportError as exc:
220
+ raise AlgorithmConfigurationError(
221
+ "official LightGBM requires LightGBM and Ray Train"
222
+ ) from exc
223
+ if not lightgbm.__version__ or LightGBMTrainer is None:
224
+ raise AlgorithmConfigurationError("LightGBM environment is invalid")
225
+
226
+ def bind_datasets(self, datasets: Mapping[str, object]) -> Mapping[str, object]:
227
+ if len(datasets) != 1:
228
+ raise AlgorithmConfigurationError("LightGBM requires one train Dataset")
229
+ dataset = next(iter(datasets.values()))
230
+ binding = self.plan.primary_input_binding
231
+ data = cast(Mapping[str, Any], self.plan.algorithm_config.get("data", {}))
232
+ configured_features = tuple(data.get("feature_columns", ()))
233
+ features = configured_features or binding.feature_names
234
+ if tuple(features) != binding.feature_names:
235
+ raise AlgorithmConfigurationError(
236
+ "LightGBM data.feature_columns must match InputBinding"
237
+ )
238
+ if data.get("label_col") != binding.label_name:
239
+ raise AlgorithmConfigurationError(
240
+ "LightGBM data.label_col must match InputBinding label"
241
+ )
242
+ return {
243
+ "train": cast(Any, dataset).select_columns(
244
+ [*features, cast(str, binding.label_name)]
245
+ )
246
+ }
247
+
248
+ def build_trainer(
249
+ self,
250
+ config: Mapping[str, Any],
251
+ datasets: Mapping[str, object],
252
+ ) -> object:
253
+ import ray
254
+ from ray.train import RunConfig, ScalingConfig
255
+ from ray.train.lightgbm import LightGBMTrainer
256
+
257
+ data = cast(Mapping[str, Any], config.get("data", {}))
258
+ model = dict(cast(Mapping[str, Any], config.get("model", {})))
259
+ task, class_count = _model_task(model)
260
+ params = _training_params(model)
261
+ training = cast(Mapping[str, Any], config.get("training", {}))
262
+ ray_config = cast(Mapping[str, Any], config.get("ray", {}))
263
+ binding = self.plan.primary_input_binding
264
+ collector_type = ray.remote(_EvidenceCollector).options(num_cpus=0)
265
+ self.collector = collector_type.remote()
266
+ return LightGBMTrainer(
267
+ train_loop_per_worker=_train_loop,
268
+ train_loop_config={
269
+ "feature_names": list(binding.feature_names),
270
+ "label_name": str(data["label_col"]),
271
+ "params": params,
272
+ "task": task,
273
+ "class_count": class_count,
274
+ "num_boost_round": int(training.get("num_rounds", 10)),
275
+ "evidence_actor": self.collector,
276
+ "binding_digest": self.plan.primary_input_descriptor.binding_digest,
277
+ },
278
+ scaling_config=ScalingConfig(
279
+ num_workers=self.plan.runtime.worker_count,
280
+ use_gpu=self.plan.runtime.num_gpus > 0,
281
+ placement_strategy="SPREAD",
282
+ resources_per_worker={
283
+ "CPU": self.plan.runtime.num_cpus,
284
+ "GPU": self.plan.runtime.num_gpus,
285
+ **dict(self.plan.runtime.custom_resources),
286
+ },
287
+ ),
288
+ datasets=cast(dict[str, Any], dict(datasets)),
289
+ run_config=RunConfig(
290
+ name="tributo-official-lightgbm",
291
+ storage_path=str(ray_config["storage_path"]),
292
+ ),
293
+ )
294
+
295
+ def collect_evidence(self, result: object) -> Mapping[str, Any]:
296
+ import ray
297
+
298
+ del result
299
+ if self.collector is None:
300
+ raise AlgorithmExecutionError("LightGBM evidence collector is missing")
301
+ workers = ray.get(self.collector.snapshot.remote())
302
+ ray.kill(self.collector, no_restart=True)
303
+ self.collector = None
304
+ if len(workers) != self.plan.runtime.worker_count:
305
+ raise AlgorithmExecutionError("LightGBM did not report every worker")
306
+ digests = {str(item.get("model_state_digest")) for item in workers}
307
+ if len(digests) != 1:
308
+ raise AlgorithmExecutionError("LightGBM Booster state diverged")
309
+ return {
310
+ "workers": workers,
311
+ "state": {
312
+ "coordination": "framework_native",
313
+ "synchronized": True,
314
+ "bounded": True,
315
+ "global_model_digest": next(iter(digests)),
316
+ "details": {"framework": "lightgbm", "collective": "tcp"},
317
+ },
318
+ "input_complete": True,
319
+ }
320
+
321
+ def checkpoint_source(self, result: object) -> object:
322
+ checkpoint = getattr(result, "checkpoint", None)
323
+ if checkpoint is None:
324
+ raise AlgorithmExecutionError("LightGBM result has no checkpoint")
325
+ return checkpoint
326
+
327
+
328
+ def create_algorithm(
329
+ *,
330
+ plan: ResolvedAlgorithmPlan,
331
+ implementation: object,
332
+ artifacts: tuple[object, ...],
333
+ ) -> DistributedLightGBM:
334
+ """Construct the descriptor-selected LightGBM implementation."""
335
+ del artifacts
336
+ if implementation is not DistributedLightGBM:
337
+ raise AlgorithmConfigurationError("LightGBM implementation drifted")
338
+ return DistributedLightGBM(plan)
339
+
340
+
341
+ def export_result(
342
+ *,
343
+ result: object,
344
+ checkpoint: object,
345
+ plan: ResolvedAlgorithmPlan,
346
+ run_id: str,
347
+ ) -> AlgorithmExecutionResult:
348
+ """Export a LightGBM checkpoint to ONNX and a validated Bundle."""
349
+ import lightgbm
350
+ from onnxmltools import convert_lightgbm
351
+ from onnxmltools.convert.common.data_types import FloatTensorType
352
+ from tributo.exporting.models import (
353
+ BundleOutputConfig,
354
+ CheckpointField,
355
+ ExportCheckpointV1,
356
+ ExportSource,
357
+ ExportTarget,
358
+ )
359
+ from tributo.exporting.service import BundleExportService
360
+
361
+ del result
362
+ output = plan.algorithm_config.get("output")
363
+ if not isinstance(output, Mapping) or not isinstance(output.get("bundle_uri"), str):
364
+ raise AlgorithmConfigurationError("LightGBM output.bundle_uri is required")
365
+ data = cast(Mapping[str, Any], plan.algorithm_config.get("data", {}))
366
+ binding = plan.primary_input_binding
367
+ with cast(Any, checkpoint).as_directory() as directory:
368
+ root = Path(directory)
369
+ booster = lightgbm.Booster(model_file=str(root / "model.txt"))
370
+ try:
371
+ raw_feature_names = json.loads(
372
+ (root / "feature_names.json").read_text(encoding="utf-8")
373
+ )
374
+ model_config = json.loads(
375
+ (root / "model_config.json").read_text(encoding="utf-8")
376
+ )
377
+ if (
378
+ not isinstance(raw_feature_names, list)
379
+ or not all(isinstance(name, str) and name for name in raw_feature_names)
380
+ or not isinstance(model_config, Mapping)
381
+ ):
382
+ raise ValueError("LightGBM checkpoint metadata is invalid")
383
+ feature_names = tuple(raw_feature_names)
384
+ task = str(model_config.get("task", "regression"))
385
+ class_count = int(model_config.get("class_count", 1))
386
+ if task not in {"classification", "regression"}:
387
+ raise ValueError("LightGBM checkpoint task is invalid")
388
+ except (OSError, TypeError, ValueError, json.JSONDecodeError) as exc:
389
+ raise AlgorithmExecutionError(
390
+ "LightGBM checkpoint metadata is invalid"
391
+ ) from exc
392
+ try:
393
+ export_model: Any = booster
394
+ output_schema: tuple[Any, ...]
395
+ if task == "classification":
396
+ if class_count < 2:
397
+ raise AlgorithmConfigurationError(
398
+ "LightGBM checkpoint has an invalid class count"
399
+ )
400
+ export_model = lightgbm.LGBMClassifier(
401
+ objective="multiclass" if class_count > 2 else "binary"
402
+ )
403
+ export_model._Booster = booster
404
+ export_model.fitted_ = True
405
+ export_model._classes = np.arange(class_count)
406
+ export_model._n_classes = class_count
407
+ export_model._objective = "multiclass" if class_count > 2 else "binary"
408
+ export_model.n_features_in_ = len(feature_names)
409
+ output_schema = (
410
+ CheckpointField(name="label", dtype="int64", shape=("batch",)),
411
+ CheckpointField(
412
+ name="probabilities",
413
+ dtype="float32",
414
+ shape=("batch", class_count),
415
+ ),
416
+ )
417
+ elif task == "regression":
418
+ output_schema = (
419
+ CheckpointField(
420
+ name="variable", dtype="float32", shape=("batch", 1)
421
+ ),
422
+ )
423
+ else:
424
+ raise AlgorithmExecutionError("LightGBM checkpoint task is invalid")
425
+ converted = convert_lightgbm(
426
+ export_model,
427
+ initial_types=[
428
+ ("float_input", FloatTensorType([None, len(feature_names)]))
429
+ ],
430
+ zipmap=False,
431
+ target_opset=15,
432
+ )
433
+ for graph_output in converted.graph.output:
434
+ dimensions = graph_output.type.tensor_type.shape.dim
435
+ if not dimensions:
436
+ raise AlgorithmExecutionError(
437
+ "LightGBM ONNX output omitted its batch dimension"
438
+ )
439
+ batch_dimension = dimensions[0]
440
+ batch_dimension.ClearField("dim_value")
441
+ batch_dimension.dim_param = "batch"
442
+ converted.graph.name = "tributo-lightgbm"
443
+ converted.doc_string = ""
444
+ for node in converted.graph.node:
445
+ node.doc_string = ""
446
+ payload = converted.SerializeToString()
447
+ except Exception as exc:
448
+ raise AlgorithmExecutionError(
449
+ f"LightGBM ONNX export failed: {type(exc).__name__}"
450
+ ) from exc
451
+ artifact = ArtifactDraft.from_payload(
452
+ name="model", kind="model", format="application/onnx", payload=payload
453
+ )
454
+ source = ExportSource(
455
+ source_kind="prebuilt_onnx",
456
+ model_object=payload,
457
+ feature_schema={"feature_names": list(feature_names)},
458
+ metadata={
459
+ "framework": "lightgbm",
460
+ "framework_versions": {"lightgbm": lightgbm.__version__},
461
+ "task_type": task,
462
+ "producer_distribution": "tributo-algorithms",
463
+ },
464
+ source_fingerprint=artifact.sha256,
465
+ checkpoint_contract=ExportCheckpointV1(
466
+ trainer_type="lightgbm",
467
+ architecture_id=plan.resolution.algorithm,
468
+ input_schema=(
469
+ CheckpointField(
470
+ name="float_input",
471
+ dtype="float32",
472
+ shape=("batch", len(feature_names)),
473
+ ),
474
+ ),
475
+ output_schema=output_schema,
476
+ task_type=task,
477
+ framework="lightgbm",
478
+ framework_version=lightgbm.__version__,
479
+ ),
480
+ )
481
+ bundle = BundleExportService().export_bundle(
482
+ source,
483
+ BundleOutputConfig(
484
+ bundle_uri=cast(str, output["bundle_uri"]),
485
+ request_id=run_id,
486
+ run_id=run_id,
487
+ targets=[
488
+ ExportTarget(
489
+ name="onnx-model",
490
+ format="onnx",
491
+ exporter_id="prebuilt-onnx-v1",
492
+ )
493
+ ],
494
+ roles={"inference": "onnx-model"},
495
+ ),
496
+ )
497
+ return AlgorithmExecutionResult(
498
+ status="succeeded",
499
+ outputs={
500
+ "bundle_id": bundle.bundle_id,
501
+ "bundle_uri": bundle.canonical_uri,
502
+ "execution_id": bundle.execution_id,
503
+ "manifest_sha256": bundle.manifest_sha256,
504
+ "feature_names": list(binding.feature_names),
505
+ "label_col": data.get("label_col"),
506
+ },
507
+ artifacts=(artifact,),
508
+ )
509
+
510
+
511
+ __all__ = ["DistributedLightGBM", "create_algorithm", "export_result"]