tributo-algorithms 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tributo_algorithms-0.1.0.dist-info/METADATA +328 -0
- tributo_algorithms-0.1.0.dist-info/RECORD +110 -0
- tributo_algorithms-0.1.0.dist-info/WHEEL +4 -0
- tributo_algorithms-0.1.0.dist-info/entry_points.txt +57 -0
- tributo_algorithms-0.1.0.dist-info/licenses/LICENSE +202 -0
- tributo_algorithms_boosting/__init__.py +42 -0
- tributo_algorithms_boosting/algorithm.py +825 -0
- tributo_algorithms_boosting/checkpointing.py +441 -0
- tributo_algorithms_boosting/contracts.py +232 -0
- tributo_algorithms_boosting/data_config.py +59 -0
- tributo_algorithms_boosting/descriptor.py +124 -0
- tributo_algorithms_boosting/lightgbm.py +511 -0
- tributo_algorithms_boosting/lightgbm_contracts.py +186 -0
- tributo_algorithms_boosting/lightgbm_descriptor.py +112 -0
- tributo_algorithms_boosting/native.py +557 -0
- tributo_algorithms_boosting/stages.py +150 -0
- tributo_algorithms_catboost/__init__.py +5 -0
- tributo_algorithms_catboost/algorithm.py +379 -0
- tributo_algorithms_catboost/contracts.py +145 -0
- tributo_algorithms_catboost/descriptor.py +121 -0
- tributo_algorithms_catboost/exporter.py +106 -0
- tributo_algorithms_catboost/flavor.py +191 -0
- tributo_algorithms_causal_core/__init__.py +41 -0
- tributo_algorithms_causal_core/algorithm.py +1193 -0
- tributo_algorithms_causal_core/contracts.py +136 -0
- tributo_algorithms_causal_core/descriptor.py +270 -0
- tributo_algorithms_causal_core/exporter.py +52 -0
- tributo_algorithms_causal_discovery/__init__.py +23 -0
- tributo_algorithms_causal_discovery/algorithm.py +526 -0
- tributo_algorithms_causal_discovery/contracts.py +97 -0
- tributo_algorithms_causal_discovery/descriptor.py +130 -0
- tributo_algorithms_causal_discovery/exporter.py +43 -0
- tributo_algorithms_causal_dowhy/__init__.py +38 -0
- tributo_algorithms_causal_dowhy/algorithm.py +325 -0
- tributo_algorithms_causal_dowhy/contracts.py +209 -0
- tributo_algorithms_causal_dowhy/descriptor.py +106 -0
- tributo_algorithms_causal_dowhy/exporter.py +43 -0
- tributo_algorithms_causal_dowhy/gcm.py +634 -0
- tributo_algorithms_causal_dowhy/gcm_descriptor.py +110 -0
- tributo_algorithms_causal_dr/__init__.py +22 -0
- tributo_algorithms_causal_dr/algorithm.py +446 -0
- tributo_algorithms_causal_dr/contracts.py +94 -0
- tributo_algorithms_causal_dr/descriptor.py +104 -0
- tributo_algorithms_causal_xlearner/__init__.py +29 -0
- tributo_algorithms_causal_xlearner/algorithm.py +448 -0
- tributo_algorithms_causal_xlearner/contracts.py +97 -0
- tributo_algorithms_causal_xlearner/descriptor.py +120 -0
- tributo_algorithms_causal_xlearner/exporter.py +432 -0
- tributo_algorithms_causal_xlearner/flavor.py +120 -0
- tributo_algorithms_causal_xlearner/model.py +116 -0
- tributo_algorithms_classical/__init__.py +41 -0
- tributo_algorithms_classical/contracts.py +139 -0
- tributo_algorithms_classical/descriptors.py +370 -0
- tributo_algorithms_classical/exporter.py +166 -0
- tributo_algorithms_classical/isolation_forest.py +172 -0
- tributo_algorithms_classical/isolation_forest_descriptor.py +122 -0
- tributo_algorithms_classical/kmeans.py +315 -0
- tributo_algorithms_classical/kmeans_descriptor.py +147 -0
- tributo_algorithms_classical/linear_regression.py +206 -0
- tributo_algorithms_classical/logistic_regression.py +238 -0
- tributo_algorithms_classical/models.py +28 -0
- tributo_algorithms_classical/multinomial_nb.py +643 -0
- tributo_algorithms_classical/multinomial_nb_descriptor.py +183 -0
- tributo_algorithms_classical/pca.py +187 -0
- tributo_algorithms_classical/pca_descriptor.py +111 -0
- tributo_algorithms_classical/random_forest.py +304 -0
- tributo_algorithms_classical/sgd.py +331 -0
- tributo_algorithms_classical/sgd_contracts.py +121 -0
- tributo_algorithms_classical/sgd_descriptor.py +143 -0
- tributo_algorithms_classical/unsupervised_contracts.py +198 -0
- tributo_algorithms_classical/unsupervised_exporter.py +427 -0
- tributo_algorithms_classical/unsupervised_models.py +90 -0
- tributo_algorithms_graph_pyg/__init__.py +37 -0
- tributo_algorithms_graph_pyg/algorithm.py +883 -0
- tributo_algorithms_graph_pyg/contracts.py +260 -0
- tributo_algorithms_graph_pyg/descriptor.py +201 -0
- tributo_algorithms_multistage_torch/__init__.py +40 -0
- tributo_algorithms_multistage_torch/algorithm.py +532 -0
- tributo_algorithms_multistage_torch/contracts.py +220 -0
- tributo_algorithms_multistage_torch/descriptor.py +146 -0
- tributo_algorithms_multistage_torch/pretrain.py +570 -0
- tributo_algorithms_multistage_torch/pretrain_descriptor.py +153 -0
- tributo_algorithms_recsys_torch/__init__.py +35 -0
- tributo_algorithms_recsys_torch/contracts.py +295 -0
- tributo_algorithms_recsys_torch/descriptor.py +136 -0
- tributo_algorithms_recsys_torch/jagged.py +707 -0
- tributo_algorithms_recsys_torch/jagged_descriptor.py +130 -0
- tributo_algorithms_recsys_torch/recipe.py +192 -0
- tributo_algorithms_representation/__init__.py +20 -0
- tributo_algorithms_representation/contracts.py +117 -0
- tributo_algorithms_representation/descriptor.py +137 -0
- tributo_algorithms_representation/recipe.py +162 -0
- tributo_algorithms_tabular_torch/__init__.py +46 -0
- tributo_algorithms_tabular_torch/contracts.py +228 -0
- tributo_algorithms_tabular_torch/descriptor.py +223 -0
- tributo_algorithms_tabular_torch/priors.py +216 -0
- tributo_algorithms_tabular_torch/pu_metrics.py +269 -0
- tributo_algorithms_tabular_torch/pu_reducer.py +129 -0
- tributo_algorithms_tabular_torch/recipe.py +294 -0
- tributo_algorithms_timeseries/__init__.py +36 -0
- tributo_algorithms_timeseries/contracts.py +120 -0
- tributo_algorithms_timeseries/descriptor.py +137 -0
- tributo_algorithms_timeseries/recipe.py +195 -0
- tributo_algorithms_timeseries/rnn_contracts.py +170 -0
- tributo_algorithms_timeseries/rnn_descriptor.py +167 -0
- tributo_algorithms_timeseries/rnn_recipe.py +223 -0
- tributo_algorithms_transformers_nlp/__init__.py +20 -0
- tributo_algorithms_transformers_nlp/contracts.py +109 -0
- tributo_algorithms_transformers_nlp/descriptor.py +137 -0
- tributo_algorithms_transformers_nlp/recipe.py +235 -0
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
"""Distributed KMeans and MiniBatchKMeans with synchronous centroid updates."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import pickle
|
|
6
|
+
from collections.abc import Iterable, Mapping
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from tributo.algorithms.api import (
|
|
11
|
+
AlgorithmConfigurationError,
|
|
12
|
+
AlgorithmExecutionError,
|
|
13
|
+
AlgorithmInputError,
|
|
14
|
+
ResolvedAlgorithmPlan,
|
|
15
|
+
)
|
|
16
|
+
from tributo.algorithms.spi import (
|
|
17
|
+
AlgorithmExecutionContext,
|
|
18
|
+
IterativeOptimizationAlgorithm,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
from tributo_algorithms_classical.unsupervised_models import KMeansModel
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _CheckpointCodec:
|
|
25
|
+
def dumps(self, value: object) -> bytes:
|
|
26
|
+
return pickle.dumps(value, protocol=5)
|
|
27
|
+
|
|
28
|
+
def loads(self, payload: bytes) -> object:
|
|
29
|
+
return pickle.loads(payload)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _matrix(batch: Mapping[str, object], feature_names: tuple[str, ...]) -> np.ndarray:
|
|
33
|
+
try:
|
|
34
|
+
values = np.column_stack(
|
|
35
|
+
[np.asarray(batch[name], dtype=np.float64) for name in feature_names]
|
|
36
|
+
)
|
|
37
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
38
|
+
raise AlgorithmInputError(
|
|
39
|
+
"KMeans input batch is not a dense feature matrix"
|
|
40
|
+
) from exc
|
|
41
|
+
if values.ndim != 2 or not values.shape[0] or not np.isfinite(values).all():
|
|
42
|
+
raise AlgorithmInputError("KMeans input batches must contain finite rows")
|
|
43
|
+
return values
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class DistributedKMeans(
|
|
47
|
+
IterativeOptimizationAlgorithm[
|
|
48
|
+
Mapping[str, object],
|
|
49
|
+
Mapping[str, object],
|
|
50
|
+
Mapping[str, object],
|
|
51
|
+
KMeansModel,
|
|
52
|
+
]
|
|
53
|
+
):
|
|
54
|
+
"""Fit centroids through synchronous full-data or mini-batch rounds."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, plan: ResolvedAlgorithmPlan, *, variant: str) -> None:
|
|
57
|
+
if variant not in {"kmeans", "minibatch"}:
|
|
58
|
+
raise AlgorithmConfigurationError("unsupported KMeans variant")
|
|
59
|
+
self._plan = plan
|
|
60
|
+
self._feature_names = plan.primary_input_binding.feature_names
|
|
61
|
+
self._variant = variant
|
|
62
|
+
|
|
63
|
+
def initialize_state(
|
|
64
|
+
self,
|
|
65
|
+
config: Mapping[str, Any],
|
|
66
|
+
input_descriptor: object,
|
|
67
|
+
) -> Mapping[str, object]:
|
|
68
|
+
del input_descriptor
|
|
69
|
+
n_clusters = int(config.get("n_clusters", 8))
|
|
70
|
+
feature_count = len(self._feature_names)
|
|
71
|
+
declared = config.get("feature_count")
|
|
72
|
+
if declared is not None and int(declared) != feature_count:
|
|
73
|
+
raise AlgorithmConfigurationError(
|
|
74
|
+
"KMeans feature_count disagrees with input"
|
|
75
|
+
)
|
|
76
|
+
if n_clusters < 1:
|
|
77
|
+
raise AlgorithmConfigurationError("n_clusters must be positive")
|
|
78
|
+
max_iter = int(config.get("max_iter", 100))
|
|
79
|
+
if max_iter < 1:
|
|
80
|
+
raise AlgorithmConfigurationError("KMeans max_iter must be positive")
|
|
81
|
+
seed = int(config.get("seed", 0))
|
|
82
|
+
centers = np.random.default_rng(seed).normal(
|
|
83
|
+
loc=0.0,
|
|
84
|
+
scale=1.0,
|
|
85
|
+
size=(n_clusters, feature_count),
|
|
86
|
+
)
|
|
87
|
+
return {
|
|
88
|
+
"centers": centers,
|
|
89
|
+
"round": np.asarray(0, dtype=np.int64),
|
|
90
|
+
"max_iter": np.asarray(max_iter, dtype=np.int64),
|
|
91
|
+
"last_shift": np.asarray(np.inf, dtype=np.float64),
|
|
92
|
+
"rows_seen": np.asarray(0, dtype=np.int64),
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
def compute_partition_update(
|
|
96
|
+
self,
|
|
97
|
+
batches: Iterable[Mapping[str, object]],
|
|
98
|
+
state: Mapping[str, object],
|
|
99
|
+
round_index: int,
|
|
100
|
+
context: AlgorithmExecutionContext,
|
|
101
|
+
) -> Mapping[str, object]:
|
|
102
|
+
del context
|
|
103
|
+
centers = np.asarray(state["centers"], dtype=np.float64)
|
|
104
|
+
sums = np.zeros_like(centers)
|
|
105
|
+
counts = np.zeros(centers.shape[0], dtype=np.int64)
|
|
106
|
+
loss = 0.0
|
|
107
|
+
sampled_rows = 0
|
|
108
|
+
dataset_rows = 0
|
|
109
|
+
reservoir: list[np.ndarray] = []
|
|
110
|
+
seen = 0
|
|
111
|
+
batch_size = int(self._plan.algorithm_config.get("batch_size", 128))
|
|
112
|
+
if self._variant == "minibatch" and batch_size < 1:
|
|
113
|
+
raise AlgorithmConfigurationError(
|
|
114
|
+
"MiniBatchKMeans batch_size must be positive"
|
|
115
|
+
)
|
|
116
|
+
rng = np.random.default_rng(
|
|
117
|
+
int(self._plan.algorithm_config.get("seed", 0)) + round_index
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
def accumulate(values: np.ndarray) -> None:
|
|
121
|
+
nonlocal loss, sampled_rows
|
|
122
|
+
distances = np.sum(
|
|
123
|
+
(values[:, None, :] - centers[None, :, :]) ** 2,
|
|
124
|
+
axis=2,
|
|
125
|
+
)
|
|
126
|
+
assignments = np.argmin(distances, axis=1)
|
|
127
|
+
nearest = distances[np.arange(values.shape[0]), assignments]
|
|
128
|
+
loss += float(nearest.sum())
|
|
129
|
+
sampled_rows += values.shape[0]
|
|
130
|
+
for index in range(centers.shape[0]):
|
|
131
|
+
selected = values[assignments == index]
|
|
132
|
+
if selected.size:
|
|
133
|
+
counts[index] += selected.shape[0]
|
|
134
|
+
sums[index] += selected.sum(axis=0, dtype=np.float64)
|
|
135
|
+
|
|
136
|
+
for batch in batches:
|
|
137
|
+
batch_values = _matrix(batch, self._feature_names)
|
|
138
|
+
dataset_rows += batch_values.shape[0]
|
|
139
|
+
if self._variant != "minibatch":
|
|
140
|
+
accumulate(batch_values)
|
|
141
|
+
continue
|
|
142
|
+
for row in batch_values:
|
|
143
|
+
seen += 1
|
|
144
|
+
if len(reservoir) < batch_size:
|
|
145
|
+
reservoir.append(row.copy())
|
|
146
|
+
continue
|
|
147
|
+
replacement = int(rng.integers(seen))
|
|
148
|
+
if replacement < batch_size:
|
|
149
|
+
reservoir[replacement] = row.copy()
|
|
150
|
+
if self._variant == "minibatch" and reservoir:
|
|
151
|
+
accumulate(np.asarray(reservoir, dtype=np.float64))
|
|
152
|
+
if dataset_rows == 0:
|
|
153
|
+
return {
|
|
154
|
+
"sums": sums,
|
|
155
|
+
"counts": counts,
|
|
156
|
+
"loss": np.asarray(0.0, dtype=np.float64),
|
|
157
|
+
"row_count": np.asarray(0, dtype=np.int64),
|
|
158
|
+
"dataset_row_count": np.asarray(0, dtype=np.int64),
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
"sums": sums,
|
|
162
|
+
"counts": counts,
|
|
163
|
+
"loss": np.asarray(loss, dtype=np.float64),
|
|
164
|
+
"row_count": np.asarray(sampled_rows, dtype=np.int64),
|
|
165
|
+
"dataset_row_count": np.asarray(dataset_rows, dtype=np.int64),
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
def merge_updates(
|
|
169
|
+
self,
|
|
170
|
+
left: Mapping[str, object],
|
|
171
|
+
right: Mapping[str, object],
|
|
172
|
+
) -> Mapping[str, object]:
|
|
173
|
+
return {
|
|
174
|
+
"sums": np.asarray(left["sums"]) + np.asarray(right["sums"]),
|
|
175
|
+
"counts": np.asarray(left["counts"]) + np.asarray(right["counts"]),
|
|
176
|
+
"loss": np.asarray(left["loss"]) + np.asarray(right["loss"]),
|
|
177
|
+
"row_count": np.asarray(left["row_count"]) + np.asarray(right["row_count"]),
|
|
178
|
+
"dataset_row_count": np.asarray(left["dataset_row_count"])
|
|
179
|
+
+ np.asarray(right["dataset_row_count"]),
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
def apply_update(
|
|
183
|
+
self,
|
|
184
|
+
state: Mapping[str, object],
|
|
185
|
+
update: Mapping[str, object],
|
|
186
|
+
round_index: int,
|
|
187
|
+
) -> Mapping[str, object]:
|
|
188
|
+
old = np.asarray(state["centers"], dtype=np.float64)
|
|
189
|
+
sums = np.asarray(update["sums"], dtype=np.float64)
|
|
190
|
+
counts = np.asarray(update["counts"], dtype=np.int64)
|
|
191
|
+
dataset_rows = int(np.asarray(update["dataset_row_count"], dtype=np.int64))
|
|
192
|
+
if int(np.asarray(update["row_count"], dtype=np.int64)) < 1:
|
|
193
|
+
raise AlgorithmInputError("KMeans cannot update from zero rows")
|
|
194
|
+
# The runtime tree-reduces all shard updates before this method runs;
|
|
195
|
+
# dataset_row_count is therefore the merged count for this round.
|
|
196
|
+
if round_index == 0 and counts.shape[0] > dataset_rows:
|
|
197
|
+
raise AlgorithmInputError("KMeans n_clusters cannot exceed row_count")
|
|
198
|
+
means = old.copy()
|
|
199
|
+
populated = counts > 0
|
|
200
|
+
means[populated] = sums[populated] / counts[populated, None]
|
|
201
|
+
if self._variant == "minibatch":
|
|
202
|
+
rate = float(
|
|
203
|
+
self._plan.algorithm_config.get(
|
|
204
|
+
"learning_rate", 1.0 / (round_index + 1)
|
|
205
|
+
)
|
|
206
|
+
)
|
|
207
|
+
if not 0 < rate <= 1:
|
|
208
|
+
raise AlgorithmConfigurationError(
|
|
209
|
+
"MiniBatchKMeans learning_rate must be in (0, 1]"
|
|
210
|
+
)
|
|
211
|
+
new_centers = old + rate * (means - old)
|
|
212
|
+
else:
|
|
213
|
+
new_centers = means
|
|
214
|
+
return {
|
|
215
|
+
"centers": new_centers,
|
|
216
|
+
"round": np.asarray(round_index + 1, dtype=np.int64),
|
|
217
|
+
"max_iter": state["max_iter"],
|
|
218
|
+
"last_shift": np.asarray(
|
|
219
|
+
np.linalg.norm(new_centers - old), dtype=np.float64
|
|
220
|
+
),
|
|
221
|
+
"rows_seen": np.asarray(
|
|
222
|
+
int(np.asarray(state.get("rows_seen", 0), dtype=np.int64))
|
|
223
|
+
+ dataset_rows,
|
|
224
|
+
dtype=np.int64,
|
|
225
|
+
),
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
def evaluate_round(
|
|
229
|
+
self,
|
|
230
|
+
state: Mapping[str, object],
|
|
231
|
+
update: Mapping[str, object],
|
|
232
|
+
round_index: int,
|
|
233
|
+
) -> Mapping[str, int | float]:
|
|
234
|
+
del round_index
|
|
235
|
+
rows = int(np.asarray(update["row_count"], dtype=np.int64))
|
|
236
|
+
return {
|
|
237
|
+
"inertia": float(np.asarray(update["loss"], dtype=np.float64) / rows),
|
|
238
|
+
"center_shift": float(np.asarray(state["last_shift"], dtype=np.float64)),
|
|
239
|
+
"row_count": rows,
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
def should_stop(
|
|
243
|
+
self,
|
|
244
|
+
state: Mapping[str, object],
|
|
245
|
+
metrics: Mapping[str, int | float],
|
|
246
|
+
round_index: int,
|
|
247
|
+
) -> bool:
|
|
248
|
+
del round_index
|
|
249
|
+
completed = int(np.asarray(state["round"], dtype=np.int64))
|
|
250
|
+
max_iter = int(np.asarray(state["max_iter"], dtype=np.int64))
|
|
251
|
+
return (
|
|
252
|
+
float(metrics["center_shift"])
|
|
253
|
+
<= float(self._plan.algorithm_config.get("tolerance", 1e-4))
|
|
254
|
+
or completed >= max_iter
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
def finalize_model(self, state: Mapping[str, object]) -> KMeansModel:
|
|
258
|
+
centers = np.asarray(state["centers"], dtype=np.float64)
|
|
259
|
+
n_iter = int(np.asarray(state["round"], dtype=np.int64))
|
|
260
|
+
if n_iter < 1:
|
|
261
|
+
raise AlgorithmExecutionError("KMeans did not complete a training round")
|
|
262
|
+
rows_seen = int(np.asarray(state.get("rows_seen", 0), dtype=np.int64))
|
|
263
|
+
if centers.shape[0] > rows_seen:
|
|
264
|
+
raise AlgorithmInputError("KMeans n_clusters cannot exceed row_count")
|
|
265
|
+
return KMeansModel(centers, self._feature_names, n_iter, self._variant)
|
|
266
|
+
|
|
267
|
+
def state_schema(self) -> Mapping[str, object]:
|
|
268
|
+
return {
|
|
269
|
+
"centers": "float64[clusters,features]",
|
|
270
|
+
"round": "int64[1]",
|
|
271
|
+
"max_iter": "int64[1]",
|
|
272
|
+
"last_shift": "float64[1]",
|
|
273
|
+
"rows_seen": "int64[1]",
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
def update_schema(self) -> Mapping[str, object]:
|
|
277
|
+
return {
|
|
278
|
+
"sums": "float64[clusters,features]",
|
|
279
|
+
"counts": "int64[clusters]",
|
|
280
|
+
"loss": "float64[1]",
|
|
281
|
+
"row_count": "int64[1]",
|
|
282
|
+
"dataset_row_count": "int64[1]",
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
def checkpoint_codec(self) -> object:
|
|
286
|
+
return _CheckpointCodec()
|
|
287
|
+
|
|
288
|
+
@property
|
|
289
|
+
def retry_safe(self) -> bool:
|
|
290
|
+
return True
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def create_algorithm(
|
|
294
|
+
*,
|
|
295
|
+
plan: ResolvedAlgorithmPlan,
|
|
296
|
+
implementation: object,
|
|
297
|
+
artifacts: tuple[object, ...],
|
|
298
|
+
) -> DistributedKMeans:
|
|
299
|
+
"""Construct the descriptor-selected KMeans implementation."""
|
|
300
|
+
del artifacts
|
|
301
|
+
if implementation is DistributedKMeans:
|
|
302
|
+
return DistributedKMeans(plan, variant="kmeans")
|
|
303
|
+
if implementation is MiniBatchKMeans:
|
|
304
|
+
return DistributedKMeans(plan, variant="minibatch")
|
|
305
|
+
raise AlgorithmConfigurationError("KMeans implementation reference drifted")
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
class MiniBatchKMeans(DistributedKMeans):
|
|
309
|
+
"""Marker class selecting the MiniBatchKMeans update rule."""
|
|
310
|
+
|
|
311
|
+
def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
|
|
312
|
+
super().__init__(plan, variant="minibatch")
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
__all__ = ["DistributedKMeans", "MiniBatchKMeans", "create_algorithm"]
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Descriptors for the official KMeans algorithms."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from tributo.algorithms import AlgorithmBuilder
|
|
6
|
+
from tributo.algorithms.api import (
|
|
7
|
+
ContractBinding,
|
|
8
|
+
ContractBindingSet,
|
|
9
|
+
DistributedExactness,
|
|
10
|
+
DistributionStrategy,
|
|
11
|
+
EnvironmentSpec,
|
|
12
|
+
ExecutionMode,
|
|
13
|
+
ExecutionProfile,
|
|
14
|
+
IterativeOptimizationPolicy,
|
|
15
|
+
QualifiedReference,
|
|
16
|
+
WorkerRange,
|
|
17
|
+
WorkerResources,
|
|
18
|
+
)
|
|
19
|
+
from tributo.training.algorithm_spec import (
|
|
20
|
+
AlgorithmSpec,
|
|
21
|
+
Capability,
|
|
22
|
+
DataLoadingMode,
|
|
23
|
+
ProblemType,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
_PACKAGE = "tributo-algorithms"
|
|
27
|
+
_VERSION = "0.1.0"
|
|
28
|
+
_INPUT = "tributo.official.tabular.unlabeled_dense.v1"
|
|
29
|
+
_OUTPUT = "tributo.official.unsupervised.kmeans.clustering.v1"
|
|
30
|
+
_COVERAGE = "tributo.official.distributed.coverage.v1"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _binding(contract_id: str, digest: str, validator: str) -> ContractBinding:
|
|
34
|
+
return ContractBinding(
|
|
35
|
+
contract_id=contract_id,
|
|
36
|
+
schema_version=1,
|
|
37
|
+
schema_digest=digest * 64,
|
|
38
|
+
validator_ref=QualifiedReference.parse(
|
|
39
|
+
f"tributo_algorithms_classical.unsupervised_contracts:{validator}"
|
|
40
|
+
),
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _spec(name: str) -> AlgorithmSpec:
|
|
45
|
+
return AlgorithmSpec(
|
|
46
|
+
name=name,
|
|
47
|
+
trainer_cls=None,
|
|
48
|
+
version="1.0.0",
|
|
49
|
+
default_config={"n_clusters": 8},
|
|
50
|
+
supported_tasks=("fit",),
|
|
51
|
+
operations=("fit",),
|
|
52
|
+
data_loading=DataLoadingMode.CANONICAL_DRIVER,
|
|
53
|
+
capabilities=(
|
|
54
|
+
Capability.DISTRIBUTED,
|
|
55
|
+
Capability.EXPORTABLE,
|
|
56
|
+
Capability.TUNABLE,
|
|
57
|
+
),
|
|
58
|
+
problem_types=(ProblemType.CLUSTERING,),
|
|
59
|
+
learning_paradigm="unsupervised",
|
|
60
|
+
model_family="centroid_clustering",
|
|
61
|
+
data_modalities=("tabular",),
|
|
62
|
+
lifecycle_kind="batch_fit",
|
|
63
|
+
allowed_execution_modes=(ExecutionMode.ITERATIVE_OPTIMIZATION.value,),
|
|
64
|
+
config_contract_ref=f"tributo.official.unsupervised.{name}.config.v1",
|
|
65
|
+
input_contract_ref=_INPUT,
|
|
66
|
+
output_contract_ref=_OUTPUT,
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _descriptor(
|
|
71
|
+
spec: AlgorithmSpec,
|
|
72
|
+
implementation_id: str,
|
|
73
|
+
implementation: str,
|
|
74
|
+
exactness: DistributedExactness,
|
|
75
|
+
) -> object:
|
|
76
|
+
return AlgorithmBuilder.from_distributed_algorithm(
|
|
77
|
+
spec=spec,
|
|
78
|
+
implementation_id=implementation_id,
|
|
79
|
+
implementation_version="1.0.0",
|
|
80
|
+
implementation=implementation,
|
|
81
|
+
executable_factory="tributo_algorithms_classical.kmeans:create_algorithm",
|
|
82
|
+
distribution=_PACKAGE,
|
|
83
|
+
framework="numpy",
|
|
84
|
+
environment=EnvironmentSpec(
|
|
85
|
+
environment_id="tributo.official.classical.unsupervised.v1",
|
|
86
|
+
dependencies=(
|
|
87
|
+
"numpy>=2,<3",
|
|
88
|
+
"onnx>=1.16",
|
|
89
|
+
"onnxruntime>=1.20",
|
|
90
|
+
"tributo>=1.1",
|
|
91
|
+
f"tributo-algorithms[classical]=={_VERSION}",
|
|
92
|
+
),
|
|
93
|
+
),
|
|
94
|
+
allowed_config_keys=(
|
|
95
|
+
"batch_size",
|
|
96
|
+
"feature_count",
|
|
97
|
+
"learning_rate",
|
|
98
|
+
"max_iter",
|
|
99
|
+
"n_clusters",
|
|
100
|
+
"output",
|
|
101
|
+
"runtime",
|
|
102
|
+
"seed",
|
|
103
|
+
"tolerance",
|
|
104
|
+
),
|
|
105
|
+
strategy=DistributionStrategy.RAY_ITERATIVE_OPTIMIZATION,
|
|
106
|
+
supported_worker_range=WorkerRange(1, 1024),
|
|
107
|
+
supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
|
|
108
|
+
resources_per_worker=WorkerResources(num_cpus=1),
|
|
109
|
+
policy=IterativeOptimizationPolicy(
|
|
110
|
+
max_rounds=100,
|
|
111
|
+
checkpoint_interval=10,
|
|
112
|
+
max_retries=1,
|
|
113
|
+
exactness=exactness,
|
|
114
|
+
),
|
|
115
|
+
package_name=_PACKAGE,
|
|
116
|
+
package_version=_VERSION,
|
|
117
|
+
tributo_version_spec=">=1.1",
|
|
118
|
+
exporter="tributo_algorithms_classical.unsupervised_exporter:export_kmeans_model",
|
|
119
|
+
flavor_id="onnx-runtime-v1",
|
|
120
|
+
contract_bindings=ContractBindingSet(
|
|
121
|
+
config=_binding(
|
|
122
|
+
spec.config_contract_ref or "", "6", "UnsupervisedConfigValidator"
|
|
123
|
+
),
|
|
124
|
+
input=_binding(_INPUT, "7", "UnlabeledDenseInputValidator"),
|
|
125
|
+
output=_binding(_OUTPUT, "9", "KMeansOutputValidator"),
|
|
126
|
+
coverage=_binding(_COVERAGE, "a", "UnsupervisedCoverageValidator"),
|
|
127
|
+
),
|
|
128
|
+
descriptor_api_version=2,
|
|
129
|
+
is_default=True,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
KMEANS_DESCRIPTOR = _descriptor(
|
|
134
|
+
_spec("kmeans"),
|
|
135
|
+
"tributo.official.classical.kmeans.iterative",
|
|
136
|
+
"tributo_algorithms_classical.kmeans:DistributedKMeans",
|
|
137
|
+
DistributedExactness.EXACT,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
MINIBATCH_KMEANS_DESCRIPTOR = _descriptor(
|
|
141
|
+
_spec("kmeans_minibatch"),
|
|
142
|
+
"tributo.official.classical.kmeans_minibatch.iterative",
|
|
143
|
+
"tributo_algorithms_classical.kmeans:MiniBatchKMeans",
|
|
144
|
+
DistributedExactness.APPROXIMATE,
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
__all__ = ["KMEANS_DESCRIPTOR", "MINIBATCH_KMEANS_DESCRIPTOR"]
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""Distributed full-gradient linear regression mathematical Hook."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import pickle
|
|
6
|
+
from collections.abc import Iterable, Mapping
|
|
7
|
+
from typing import Any, cast
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from tributo.algorithms import IterativeOptimizationAlgorithm
|
|
11
|
+
from tributo.algorithms.spi import (
|
|
12
|
+
AlgorithmExecutionContext,
|
|
13
|
+
MaterializedTabularInputView,
|
|
14
|
+
TabularBatchInputView,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
from tributo_algorithms_classical.models import SklearnModel
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class LinearRegressionCheckpointCodec:
|
|
21
|
+
def dumps(self, value: object) -> bytes:
|
|
22
|
+
return pickle.dumps(value, protocol=5)
|
|
23
|
+
|
|
24
|
+
def loads(self, payload: bytes) -> object:
|
|
25
|
+
return pickle.loads(payload)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class DistributedLinearRegression(
|
|
29
|
+
IterativeOptimizationAlgorithm[
|
|
30
|
+
Mapping[str, object],
|
|
31
|
+
Mapping[str, object],
|
|
32
|
+
Mapping[str, object],
|
|
33
|
+
SklearnModel,
|
|
34
|
+
]
|
|
35
|
+
):
|
|
36
|
+
"""Synchronous squared-error linear regression with L2 stabilization."""
|
|
37
|
+
|
|
38
|
+
def initialize_state(
|
|
39
|
+
self,
|
|
40
|
+
config: Mapping[str, Any],
|
|
41
|
+
input_descriptor: object,
|
|
42
|
+
) -> Mapping[str, object]:
|
|
43
|
+
del input_descriptor
|
|
44
|
+
feature_count = int(config.get("feature_count", 2))
|
|
45
|
+
feature_names = tuple(
|
|
46
|
+
str(name)
|
|
47
|
+
for name in config.get(
|
|
48
|
+
"_tributo_feature_names",
|
|
49
|
+
tuple(f"feature_{index}" for index in range(feature_count)),
|
|
50
|
+
)
|
|
51
|
+
)
|
|
52
|
+
if len(feature_names) != feature_count:
|
|
53
|
+
raise ValueError("feature_count does not match input feature names")
|
|
54
|
+
return {
|
|
55
|
+
"coef": np.zeros(feature_count, dtype=np.float64),
|
|
56
|
+
"intercept": np.zeros(1, dtype=np.float64),
|
|
57
|
+
"round": np.zeros(1, dtype=np.int64),
|
|
58
|
+
"feature_count": np.asarray([feature_count], dtype=np.int64),
|
|
59
|
+
"learning_rate": np.asarray(
|
|
60
|
+
[float(config.get("learning_rate", 0.05))], dtype=np.float64
|
|
61
|
+
),
|
|
62
|
+
"tolerance": np.asarray(
|
|
63
|
+
[float(config.get("tolerance", 1e-6))], dtype=np.float64
|
|
64
|
+
),
|
|
65
|
+
"feature_names": feature_names,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
def compute_partition_update(
|
|
69
|
+
self,
|
|
70
|
+
batches: Iterable[Mapping[str, object]],
|
|
71
|
+
state: Mapping[str, object],
|
|
72
|
+
round_index: int,
|
|
73
|
+
context: AlgorithmExecutionContext,
|
|
74
|
+
) -> Mapping[str, object]:
|
|
75
|
+
del round_index
|
|
76
|
+
view = context.inputs["train"]
|
|
77
|
+
if not isinstance(view, (TabularBatchInputView, MaterializedTabularInputView)):
|
|
78
|
+
raise ValueError("Linear Regression requires tabular batch input")
|
|
79
|
+
if view.label_name is None:
|
|
80
|
+
raise ValueError("Linear Regression requires a label")
|
|
81
|
+
coef = np.asarray(state["coef"], dtype=np.float64)
|
|
82
|
+
intercept = float(np.asarray(state["intercept"])[0])
|
|
83
|
+
gradient = np.zeros_like(coef)
|
|
84
|
+
intercept_gradient = 0.0
|
|
85
|
+
loss_sum = 0.0
|
|
86
|
+
rows = 0
|
|
87
|
+
for batch in batches:
|
|
88
|
+
features = np.column_stack(
|
|
89
|
+
[
|
|
90
|
+
np.asarray(batch[name], dtype=np.float64)
|
|
91
|
+
for name in view.feature_names
|
|
92
|
+
]
|
|
93
|
+
)
|
|
94
|
+
labels = np.asarray(batch[view.label_name], dtype=np.float64)
|
|
95
|
+
if not np.isfinite(features).all() or not np.isfinite(labels).all():
|
|
96
|
+
raise ValueError("Linear Regression requires finite input")
|
|
97
|
+
errors = features @ coef + intercept - labels
|
|
98
|
+
gradient += features.T @ errors
|
|
99
|
+
intercept_gradient += float(errors.sum())
|
|
100
|
+
loss_sum += float(np.square(errors).sum())
|
|
101
|
+
rows += len(labels)
|
|
102
|
+
return {
|
|
103
|
+
"gradient_sum": gradient,
|
|
104
|
+
"intercept_gradient_sum": np.asarray([intercept_gradient]),
|
|
105
|
+
"loss_sum": np.asarray([loss_sum]),
|
|
106
|
+
"row_count": np.asarray([rows], dtype=np.int64),
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
def merge_updates(
|
|
110
|
+
self,
|
|
111
|
+
left: Mapping[str, object],
|
|
112
|
+
right: Mapping[str, object],
|
|
113
|
+
) -> Mapping[str, object]:
|
|
114
|
+
return {name: np.asarray(left[name]) + np.asarray(right[name]) for name in left}
|
|
115
|
+
|
|
116
|
+
def apply_update(
|
|
117
|
+
self,
|
|
118
|
+
state: Mapping[str, object],
|
|
119
|
+
update: Mapping[str, object],
|
|
120
|
+
round_index: int,
|
|
121
|
+
) -> Mapping[str, object]:
|
|
122
|
+
rows = int(np.asarray(update["row_count"])[0])
|
|
123
|
+
if rows < 1:
|
|
124
|
+
raise ValueError("Linear Regression cannot update from zero rows")
|
|
125
|
+
rate = float(np.asarray(state["learning_rate"])[0])
|
|
126
|
+
coef = np.asarray(state["coef"], dtype=np.float64)
|
|
127
|
+
return {
|
|
128
|
+
**state,
|
|
129
|
+
"coef": coef
|
|
130
|
+
- rate
|
|
131
|
+
* (
|
|
132
|
+
np.asarray(update["gradient_sum"], dtype=np.float64) / rows
|
|
133
|
+
+ coef / rows
|
|
134
|
+
),
|
|
135
|
+
"intercept": np.asarray(state["intercept"], dtype=np.float64)
|
|
136
|
+
- rate
|
|
137
|
+
* np.asarray(update["intercept_gradient_sum"], dtype=np.float64)
|
|
138
|
+
/ rows,
|
|
139
|
+
"round": np.asarray([round_index + 1], dtype=np.int64),
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
def evaluate_round(
|
|
143
|
+
self,
|
|
144
|
+
state: Mapping[str, object],
|
|
145
|
+
update: Mapping[str, object],
|
|
146
|
+
round_index: int,
|
|
147
|
+
) -> Mapping[str, int | float]:
|
|
148
|
+
del state, round_index
|
|
149
|
+
rows = int(np.asarray(update["row_count"])[0])
|
|
150
|
+
gradient = np.asarray(update["gradient_sum"], dtype=np.float64) / rows
|
|
151
|
+
return {
|
|
152
|
+
"loss": float(np.asarray(update["loss_sum"])[0] / rows),
|
|
153
|
+
"gradient_norm": float(np.linalg.norm(gradient)),
|
|
154
|
+
"row_count": rows,
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
def should_stop(
|
|
158
|
+
self,
|
|
159
|
+
state: Mapping[str, object],
|
|
160
|
+
metrics: Mapping[str, int | float],
|
|
161
|
+
round_index: int,
|
|
162
|
+
) -> bool:
|
|
163
|
+
del round_index
|
|
164
|
+
return float(metrics["gradient_norm"]) < float(
|
|
165
|
+
np.asarray(state["tolerance"])[0]
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def finalize_model(self, state: Mapping[str, object]) -> SklearnModel:
|
|
169
|
+
from sklearn.linear_model import LinearRegression
|
|
170
|
+
|
|
171
|
+
estimator = LinearRegression()
|
|
172
|
+
estimator.coef_ = np.asarray(state["coef"], dtype=np.float64)
|
|
173
|
+
estimator.intercept_ = float(np.asarray(state["intercept"])[0])
|
|
174
|
+
estimator.n_features_in_ = int(np.asarray(state["feature_count"])[0])
|
|
175
|
+
feature_names = tuple(
|
|
176
|
+
str(name) for name in cast(Iterable[object], state["feature_names"])
|
|
177
|
+
)
|
|
178
|
+
return SklearnModel(estimator, feature_names, "regression")
|
|
179
|
+
|
|
180
|
+
def state_schema(self) -> Mapping[str, object]:
|
|
181
|
+
return {
|
|
182
|
+
"coef": "float64[*]",
|
|
183
|
+
"intercept": "float64[1]",
|
|
184
|
+
"round": "int64[1]",
|
|
185
|
+
"feature_count": "int64[1]",
|
|
186
|
+
"learning_rate": "float64[1]",
|
|
187
|
+
"tolerance": "float64[1]",
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
def update_schema(self) -> Mapping[str, object]:
|
|
191
|
+
return {
|
|
192
|
+
"gradient_sum": "float64[*]",
|
|
193
|
+
"intercept_gradient_sum": "float64[1]",
|
|
194
|
+
"loss_sum": "float64[1]",
|
|
195
|
+
"row_count": "int64[1]",
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
def checkpoint_codec(self) -> object:
|
|
199
|
+
return LinearRegressionCheckpointCodec()
|
|
200
|
+
|
|
201
|
+
@property
|
|
202
|
+
def retry_safe(self) -> bool:
|
|
203
|
+
return True
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
__all__ = ["DistributedLinearRegression", "LinearRegressionCheckpointCodec"]
|