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,304 @@
1
+ """Random Forest Hook implementations for Joblib and native unit runtimes."""
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 (
11
+ EnsembleUnitSpec,
12
+ JoblibEstimatorRecipe,
13
+ ParallelEnsembleAlgorithm,
14
+ )
15
+ from tributo.algorithms.spi import (
16
+ AlgorithmExecutionContext,
17
+ MaterializedTabularInputView,
18
+ )
19
+
20
+ from tributo_algorithms_classical.models import SklearnModel, TreeUnitModel
21
+
22
+
23
+ class PickleCodec:
24
+ """Serialize bounded sklearn state for runtime digests and checkpoints."""
25
+
26
+ def dumps(self, value: object) -> bytes:
27
+ return pickle.dumps(value, protocol=5)
28
+
29
+ def loads(self, payload: bytes) -> object:
30
+ return pickle.loads(payload)
31
+
32
+
33
+ def _arrays(
34
+ inputs: Mapping[str, object],
35
+ ) -> tuple[MaterializedTabularInputView, np.ndarray, np.ndarray]:
36
+ view = cast(MaterializedTabularInputView, inputs["train"])
37
+ columns = view.columns()
38
+ features = np.column_stack(
39
+ [np.asarray(columns[name], dtype=np.float64) for name in view.feature_names]
40
+ )
41
+ if view.label_name is None:
42
+ raise ValueError("Random Forest requires a label")
43
+ labels = np.asarray(columns[view.label_name])
44
+ return view, features, labels
45
+
46
+
47
+ class RandomForestJoblibRecipe(JoblibEstimatorRecipe):
48
+ """Use sklearn's public Random Forest estimator with Ray Joblib."""
49
+
50
+ def build_estimator(self, config: Mapping[str, Any]) -> object:
51
+ common = {
52
+ "n_estimators": int(config.get("n_estimators", 32)),
53
+ "max_depth": config.get("max_depth"),
54
+ "max_features": config.get("max_features", "sqrt"),
55
+ "random_state": int(config.get("seed", 42)),
56
+ }
57
+ if config.get("task", "classification") == "regression":
58
+ from sklearn.ensemble import RandomForestRegressor
59
+
60
+ return RandomForestRegressor(**common)
61
+ from sklearn.ensemble import RandomForestClassifier
62
+
63
+ return RandomForestClassifier(
64
+ **common,
65
+ class_weight=config.get("class_weight"),
66
+ )
67
+
68
+ def fit_arguments(
69
+ self,
70
+ inputs: Mapping[str, object],
71
+ config: Mapping[str, Any],
72
+ ) -> tuple[tuple[object, ...], Mapping[str, object]]:
73
+ del config
74
+ view, features, labels = _arrays(inputs)
75
+ self._feature_names = tuple(view.feature_names)
76
+ return (features, labels), {}
77
+
78
+ def parallelism_contract(self) -> Mapping[str, object]:
79
+ return {"fit_operations": ("fit",), "exactness": "exact"}
80
+
81
+ def extract_model(self, fitted_estimator: object) -> object:
82
+ estimator = cast(Any, fitted_estimator)
83
+ feature_names = tuple(
84
+ str(name) for name in getattr(estimator, "feature_names_in_", ())
85
+ )
86
+ if not feature_names:
87
+ feature_names = tuple(getattr(self, "_feature_names", ()))
88
+ if not feature_names:
89
+ feature_count = int(estimator.n_features_in_)
90
+ feature_names = tuple(f"feature_{index}" for index in range(feature_count))
91
+ task = "classification" if hasattr(estimator, "classes_") else "regression"
92
+ return SklearnModel(estimator, feature_names, task)
93
+
94
+ def model_codec(self) -> object:
95
+ return PickleCodec()
96
+
97
+
98
+ class ExtraTreesJoblibRecipe(RandomForestJoblibRecipe):
99
+ """Use sklearn's randomized Extra Trees estimator with Ray Joblib."""
100
+
101
+ def build_estimator(self, config: Mapping[str, Any]) -> object:
102
+ common = {
103
+ "n_estimators": int(config.get("n_estimators", 32)),
104
+ "max_depth": config.get("max_depth"),
105
+ "max_features": config.get("max_features", "sqrt"),
106
+ "random_state": int(config.get("seed", 42)),
107
+ }
108
+ if config.get("task", "classification") == "regression":
109
+ from sklearn.ensemble import ExtraTreesRegressor
110
+
111
+ return ExtraTreesRegressor(**common)
112
+ from sklearn.ensemble import ExtraTreesClassifier
113
+
114
+ return ExtraTreesClassifier(
115
+ **common,
116
+ class_weight=config.get("class_weight"),
117
+ )
118
+
119
+
120
+ class RandomForestEnsemble(ParallelEnsembleAlgorithm[TreeUnitModel, SklearnModel]):
121
+ """Expose one deterministic bootstrap tree as each independent unit."""
122
+
123
+ def plan_units(
124
+ self,
125
+ config: Mapping[str, Any],
126
+ input_descriptor: object,
127
+ seed: int,
128
+ ) -> tuple[EnsembleUnitSpec, ...]:
129
+ del input_descriptor
130
+ count = int(config.get("unit_count", config.get("n_estimators", 32)))
131
+ seeds = np.random.RandomState(seed).randint(
132
+ np.iinfo(np.int32).max,
133
+ size=count,
134
+ )
135
+ payload = {
136
+ "task": str(config.get("task", "classification")),
137
+ "max_depth": config.get("max_depth"),
138
+ "max_features": config.get("max_features", "sqrt"),
139
+ "class_weight": config.get("class_weight"),
140
+ }
141
+ return tuple(
142
+ EnsembleUnitSpec(
143
+ unit_id=f"tree-{index}",
144
+ seed=int(tree_seed),
145
+ payload=payload,
146
+ )
147
+ for index, tree_seed in enumerate(seeds)
148
+ )
149
+
150
+ def fit_unit(
151
+ self,
152
+ unit: EnsembleUnitSpec,
153
+ inputs: Mapping[str, object],
154
+ context: AlgorithmExecutionContext,
155
+ ) -> TreeUnitModel:
156
+ del context
157
+ view, features, labels = _arrays(inputs)
158
+ sample_indices = np.random.RandomState(unit.seed).randint(
159
+ 0,
160
+ len(labels),
161
+ len(labels),
162
+ )
163
+ task = str(unit.payload.get("task", "classification"))
164
+ if task == "regression":
165
+ from sklearn.tree import DecisionTreeRegressor
166
+
167
+ estimator = DecisionTreeRegressor(
168
+ max_depth=unit.payload.get("max_depth"),
169
+ max_features=unit.payload.get("max_features", "sqrt"),
170
+ random_state=unit.seed,
171
+ )
172
+ classes: tuple[object, ...] = ()
173
+ else:
174
+ from sklearn.tree import DecisionTreeClassifier
175
+
176
+ estimator = DecisionTreeClassifier(
177
+ max_depth=unit.payload.get("max_depth"),
178
+ max_features=unit.payload.get("max_features", "sqrt"),
179
+ random_state=unit.seed,
180
+ class_weight=unit.payload.get("class_weight"),
181
+ )
182
+ classes = tuple(np.unique(labels).tolist())
183
+ estimator.fit(features[sample_indices], labels[sample_indices])
184
+ return TreeUnitModel(
185
+ estimator=estimator,
186
+ feature_names=view.feature_names,
187
+ task=task,
188
+ classes=classes,
189
+ n_outputs=1,
190
+ )
191
+
192
+ def merge_units(self, ordered_units: tuple[TreeUnitModel, ...]) -> object:
193
+ return ordered_units
194
+
195
+ def finalize_ensemble(self, merged: object) -> SklearnModel:
196
+ units = cast(tuple[TreeUnitModel, ...], merged)
197
+ if not units:
198
+ raise ValueError("Random Forest requires at least one tree")
199
+ first = units[0]
200
+ if any(
201
+ unit.feature_names != first.feature_names or unit.task != first.task
202
+ for unit in units
203
+ ):
204
+ raise ValueError("Random Forest unit metadata is inconsistent")
205
+ if first.task == "regression":
206
+ from sklearn.ensemble import RandomForestRegressor
207
+
208
+ forest: Any = RandomForestRegressor(n_estimators=len(units))
209
+ else:
210
+ from sklearn.ensemble import RandomForestClassifier
211
+
212
+ forest = RandomForestClassifier(n_estimators=len(units))
213
+ forest.classes_ = np.asarray(first.classes)
214
+ forest.n_classes_ = len(first.classes)
215
+ forest.estimators_ = [unit.estimator for unit in units]
216
+ forest.n_features_in_ = len(first.feature_names)
217
+ forest.n_outputs_ = first.n_outputs
218
+ return SklearnModel(forest, first.feature_names, first.task)
219
+
220
+ def unit_schema(self) -> Mapping[str, object]:
221
+ return {
222
+ "estimator": "sklearn.tree",
223
+ "feature_names": "tuple[str]",
224
+ "task": "classification|regression",
225
+ }
226
+
227
+ @property
228
+ def retry_safe(self) -> bool:
229
+ return True
230
+
231
+
232
+ class ExtraTreesEnsemble(RandomForestEnsemble):
233
+ """Fit independent randomized Extra Trees without bootstrap sampling."""
234
+
235
+ def fit_unit(
236
+ self,
237
+ unit: EnsembleUnitSpec,
238
+ inputs: Mapping[str, object],
239
+ context: AlgorithmExecutionContext,
240
+ ) -> TreeUnitModel:
241
+ del context
242
+ view, features, labels = _arrays(inputs)
243
+ task = str(unit.payload.get("task", "classification"))
244
+ if task == "regression":
245
+ from sklearn.tree import ExtraTreeRegressor
246
+
247
+ estimator = ExtraTreeRegressor(
248
+ max_depth=unit.payload.get("max_depth"),
249
+ max_features=unit.payload.get("max_features", "sqrt"),
250
+ random_state=unit.seed,
251
+ )
252
+ classes: tuple[object, ...] = ()
253
+ else:
254
+ from sklearn.tree import ExtraTreeClassifier
255
+
256
+ estimator = ExtraTreeClassifier(
257
+ max_depth=unit.payload.get("max_depth"),
258
+ max_features=unit.payload.get("max_features", "sqrt"),
259
+ random_state=unit.seed,
260
+ class_weight=unit.payload.get("class_weight"),
261
+ )
262
+ classes = tuple(np.unique(labels).tolist())
263
+ estimator.fit(features, labels)
264
+ return TreeUnitModel(
265
+ estimator=estimator,
266
+ feature_names=view.feature_names,
267
+ task=task,
268
+ classes=classes,
269
+ n_outputs=1,
270
+ )
271
+
272
+ def finalize_ensemble(self, merged: object) -> SklearnModel:
273
+ units = cast(tuple[TreeUnitModel, ...], merged)
274
+ if not units:
275
+ raise ValueError("Extra Trees requires at least one tree")
276
+ first = units[0]
277
+ if any(
278
+ unit.feature_names != first.feature_names or unit.task != first.task
279
+ for unit in units
280
+ ):
281
+ raise ValueError("Extra Trees unit metadata is inconsistent")
282
+ if first.task == "regression":
283
+ from sklearn.ensemble import ExtraTreesRegressor
284
+
285
+ ensemble: Any = ExtraTreesRegressor(n_estimators=len(units))
286
+ else:
287
+ from sklearn.ensemble import ExtraTreesClassifier
288
+
289
+ ensemble = ExtraTreesClassifier(n_estimators=len(units))
290
+ ensemble.classes_ = np.asarray(first.classes)
291
+ ensemble.n_classes_ = len(first.classes)
292
+ ensemble.estimators_ = [unit.estimator for unit in units]
293
+ ensemble.n_features_in_ = len(first.feature_names)
294
+ ensemble.n_outputs_ = first.n_outputs
295
+ return SklearnModel(ensemble, first.feature_names, first.task)
296
+
297
+
298
+ __all__ = [
299
+ "ExtraTreesEnsemble",
300
+ "ExtraTreesJoblibRecipe",
301
+ "PickleCodec",
302
+ "RandomForestEnsemble",
303
+ "RandomForestJoblibRecipe",
304
+ ]
@@ -0,0 +1,331 @@
1
+ """Synchronous full-batch linear gradient algorithms."""
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.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.models import SklearnModel
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 _batch_arrays(
33
+ batch: Mapping[str, object],
34
+ feature_names: tuple[str, ...],
35
+ label_name: str,
36
+ ) -> tuple[np.ndarray, np.ndarray]:
37
+ try:
38
+ features = np.column_stack(
39
+ [np.asarray(batch[name], dtype=np.float64) for name in feature_names]
40
+ )
41
+ labels = np.asarray(batch[label_name], dtype=np.float64)
42
+ except (KeyError, TypeError, ValueError) as exc:
43
+ raise AlgorithmInputError(
44
+ "SGD input batch is not a dense labeled matrix"
45
+ ) from exc
46
+ if not features.shape[0] or labels.shape != (features.shape[0],):
47
+ raise AlgorithmInputError("SGD input batch dimensions are invalid")
48
+ if not np.isfinite(features).all() or not np.isfinite(labels).all():
49
+ raise AlgorithmInputError("SGD input must contain finite values")
50
+ return features, labels
51
+
52
+
53
+ class DistributedSGD(
54
+ IterativeOptimizationAlgorithm[
55
+ Mapping[str, object],
56
+ Mapping[str, object],
57
+ Mapping[str, object],
58
+ SklearnModel,
59
+ ]
60
+ ):
61
+ """Synchronously update one global linear model per full-data round."""
62
+
63
+ def __init__(self, plan: ResolvedAlgorithmPlan, *, task: str) -> None:
64
+ if task not in {"classification", "regression"}:
65
+ raise AlgorithmConfigurationError("SGD task is invalid")
66
+ self._plan = plan
67
+ self._task = task
68
+ self._feature_names = plan.primary_input_binding.feature_names
69
+ label_name = plan.primary_input_binding.label_name
70
+ if label_name is None:
71
+ raise AlgorithmConfigurationError("SGD requires a label")
72
+ self._label_name = label_name
73
+
74
+ def initialize_state(
75
+ self,
76
+ config: Mapping[str, Any],
77
+ input_descriptor: object,
78
+ ) -> Mapping[str, object]:
79
+ del input_descriptor
80
+ feature_count = len(self._feature_names)
81
+ alpha = float(config.get("alpha", 0.0001))
82
+ learning_rate = float(config.get("learning_rate", 0.01))
83
+ decay = float(config.get("learning_rate_decay", 0.0))
84
+ if alpha <= 0 or learning_rate <= 0 or decay < 0:
85
+ raise AlgorithmConfigurationError("SGD optimization parameters are invalid")
86
+ max_iter = int(config.get("max_iter", 20))
87
+ if max_iter < 1:
88
+ raise AlgorithmConfigurationError("SGD max_iter must be positive")
89
+ tolerance = float(config.get("tolerance", 1e-5))
90
+ if tolerance <= 0:
91
+ raise AlgorithmConfigurationError("SGD tolerance must be positive")
92
+ loss = str(
93
+ config.get(
94
+ "loss",
95
+ "log_loss" if self._task == "classification" else "squared_error",
96
+ )
97
+ )
98
+ expected_loss = (
99
+ "log_loss" if self._task == "classification" else "squared_error"
100
+ )
101
+ if loss != expected_loss:
102
+ raise AlgorithmConfigurationError(
103
+ f"SGD {self._task} requires loss={expected_loss!r}"
104
+ )
105
+ return {
106
+ "coef": np.zeros(feature_count, dtype=np.float64),
107
+ "intercept": np.asarray(0.0, dtype=np.float64),
108
+ "round": np.asarray(0, dtype=np.int64),
109
+ "step": np.asarray(0, dtype=np.int64),
110
+ "last_gradient_norm": np.asarray(np.inf, dtype=np.float64),
111
+ "alpha": np.asarray(alpha, dtype=np.float64),
112
+ "learning_rate": np.asarray(learning_rate, dtype=np.float64),
113
+ "learning_rate_decay": np.asarray(decay, dtype=np.float64),
114
+ "max_iter": np.asarray(max_iter, dtype=np.int64),
115
+ "tolerance": np.asarray(tolerance, dtype=np.float64),
116
+ "feature_names": self._feature_names,
117
+ }
118
+
119
+ def compute_partition_update(
120
+ self,
121
+ batches: Iterable[Mapping[str, object]],
122
+ state: Mapping[str, object],
123
+ round_index: int,
124
+ context: AlgorithmExecutionContext,
125
+ ) -> Mapping[str, object]:
126
+ del round_index, context
127
+ coef = np.asarray(state["coef"], dtype=np.float64)
128
+ intercept = float(np.asarray(state["intercept"], dtype=np.float64))
129
+ gradient = np.zeros_like(coef)
130
+ intercept_gradient = 0.0
131
+ loss_sum = 0.0
132
+ row_count = 0
133
+ for batch in batches:
134
+ features, labels = _batch_arrays(
135
+ batch, self._feature_names, self._label_name
136
+ )
137
+ logits = features @ coef + intercept
138
+ if self._task == "classification":
139
+ if not np.isin(labels, (0.0, 1.0)).all():
140
+ raise AlgorithmInputError("SGD classifier labels must be 0 or 1")
141
+ probabilities = 1.0 / (1.0 + np.exp(-np.clip(logits, -30.0, 30.0)))
142
+ errors = probabilities - labels
143
+ loss = np.logaddexp(0.0, logits) - labels * logits
144
+ else:
145
+ errors = logits - labels
146
+ loss = 0.5 * np.square(errors)
147
+ gradient += features.T @ errors
148
+ intercept_gradient += float(errors.sum())
149
+ loss_sum += float(loss.sum())
150
+ row_count += len(labels)
151
+ return {
152
+ "gradient": gradient,
153
+ "intercept_gradient": np.asarray(intercept_gradient, dtype=np.float64),
154
+ "loss": np.asarray(loss_sum, dtype=np.float64),
155
+ "row_count": np.asarray(row_count, dtype=np.int64),
156
+ }
157
+
158
+ def merge_updates(
159
+ self,
160
+ left: Mapping[str, object],
161
+ right: Mapping[str, object],
162
+ ) -> Mapping[str, object]:
163
+ dimension = len(self._feature_names)
164
+ left_gradient = np.asarray(left["gradient"], dtype=np.float64)
165
+ right_gradient = np.asarray(right["gradient"], dtype=np.float64)
166
+ if left_gradient.shape != (dimension,) or right_gradient.shape != (dimension,):
167
+ raise AlgorithmExecutionError("SGD gradient dimensions are inconsistent")
168
+ return {
169
+ "gradient": left_gradient + right_gradient,
170
+ "intercept_gradient": np.asarray(left["intercept_gradient"])
171
+ + np.asarray(right["intercept_gradient"]),
172
+ "loss": np.asarray(left["loss"]) + np.asarray(right["loss"]),
173
+ "row_count": np.asarray(left["row_count"]) + np.asarray(right["row_count"]),
174
+ }
175
+
176
+ def apply_update(
177
+ self,
178
+ state: Mapping[str, object],
179
+ update: Mapping[str, object],
180
+ round_index: int,
181
+ ) -> Mapping[str, object]:
182
+ if int(np.asarray(update["row_count"], dtype=np.int64)) < 1:
183
+ raise AlgorithmInputError("SGD cannot update from zero rows")
184
+ coef = np.asarray(state["coef"], dtype=np.float64).copy()
185
+ intercept = float(np.asarray(state["intercept"], dtype=np.float64))
186
+ step = int(np.asarray(state["step"], dtype=np.int64))
187
+ alpha = float(np.asarray(state["alpha"], dtype=np.float64))
188
+ base_rate = float(np.asarray(state["learning_rate"], dtype=np.float64))
189
+ decay = float(np.asarray(state["learning_rate_decay"], dtype=np.float64))
190
+ rows = int(np.asarray(update["row_count"], dtype=np.int64))
191
+ gradient = np.asarray(update["gradient"], dtype=np.float64) / rows
192
+ intercept_gradient = (
193
+ float(np.asarray(update["intercept_gradient"], dtype=np.float64)) / rows
194
+ )
195
+ gradient += alpha * coef
196
+ rate = base_rate / (1.0 + decay * step)
197
+ coef -= rate * gradient
198
+ intercept -= rate * intercept_gradient
199
+ step += 1
200
+ last_norm = float(np.linalg.norm(gradient))
201
+ return {
202
+ **state,
203
+ "coef": coef,
204
+ "intercept": np.asarray(intercept, dtype=np.float64),
205
+ "round": np.asarray(round_index + 1, dtype=np.int64),
206
+ "step": np.asarray(step, dtype=np.int64),
207
+ "last_gradient_norm": np.asarray(last_norm, dtype=np.float64),
208
+ }
209
+
210
+ def evaluate_round(
211
+ self,
212
+ state: Mapping[str, object],
213
+ update: Mapping[str, object],
214
+ round_index: int,
215
+ ) -> Mapping[str, int | float]:
216
+ del state, round_index
217
+ rows = int(np.asarray(update["row_count"], dtype=np.int64))
218
+ loss = float(np.asarray(update["loss"], dtype=np.float64))
219
+ return {"loss": loss / rows, "row_count": rows}
220
+
221
+ def should_stop(
222
+ self,
223
+ state: Mapping[str, object],
224
+ metrics: Mapping[str, int | float],
225
+ round_index: int,
226
+ ) -> bool:
227
+ del metrics
228
+ completed = int(np.asarray(state["round"], dtype=np.int64))
229
+ max_iter = int(np.asarray(state["max_iter"], dtype=np.int64))
230
+ tolerance = float(np.asarray(state["tolerance"], dtype=np.float64))
231
+ return (
232
+ completed >= max_iter
233
+ or float(np.asarray(state["last_gradient_norm"], dtype=np.float64))
234
+ < tolerance
235
+ )
236
+
237
+ def finalize_model(self, state: Mapping[str, object]) -> SklearnModel:
238
+ coef = np.asarray(state["coef"], dtype=np.float64)
239
+ intercept = float(np.asarray(state["intercept"], dtype=np.float64))
240
+ rounds = int(np.asarray(state["round"], dtype=np.int64))
241
+ steps = int(np.asarray(state["step"], dtype=np.int64))
242
+ if rounds < 1:
243
+ raise AlgorithmExecutionError("SGD did not complete a training round")
244
+ if self._task == "classification":
245
+ from sklearn.linear_model import SGDClassifier
246
+
247
+ estimator: Any = SGDClassifier(loss="log_loss", penalty="l2", max_iter=1)
248
+ estimator.classes_ = np.asarray([0, 1], dtype=np.int64)
249
+ estimator.coef_ = coef[None, :]
250
+ estimator.intercept_ = np.asarray([intercept], dtype=np.float64)
251
+ estimator.n_features_in_ = len(self._feature_names)
252
+ estimator.n_iter_ = np.asarray([rounds], dtype=np.int32)
253
+ estimator.t_ = float(steps + 1)
254
+ else:
255
+ from sklearn.linear_model import SGDRegressor
256
+
257
+ estimator = SGDRegressor(loss="squared_error", penalty="l2", max_iter=1)
258
+ estimator.coef_ = coef
259
+ estimator.intercept_ = np.asarray([intercept], dtype=np.float64)
260
+ estimator.n_features_in_ = len(self._feature_names)
261
+ estimator.n_iter_ = rounds
262
+ estimator.t_ = float(steps + 1)
263
+ return SklearnModel(estimator, self._feature_names, self._task)
264
+
265
+ def state_schema(self) -> Mapping[str, object]:
266
+ return {
267
+ "coef": "float64[features]",
268
+ "intercept": "float64[1]",
269
+ "round": "int64[1]",
270
+ "step": "int64[1]",
271
+ "last_gradient_norm": "float64[1]",
272
+ "alpha": "float64[1]",
273
+ "learning_rate": "float64[1]",
274
+ "learning_rate_decay": "float64[1]",
275
+ "max_iter": "int64[1]",
276
+ "tolerance": "float64[1]",
277
+ "feature_names": "tuple[str]",
278
+ }
279
+
280
+ def update_schema(self) -> Mapping[str, object]:
281
+ return {
282
+ "gradient": "float64[features]",
283
+ "intercept_gradient": "float64[1]",
284
+ "loss": "float64[1]",
285
+ "row_count": "int64[1]",
286
+ }
287
+
288
+ def checkpoint_codec(self) -> object:
289
+ return _CheckpointCodec()
290
+
291
+ @property
292
+ def retry_safe(self) -> bool:
293
+ return True
294
+
295
+
296
+ class DistributedSGDClassifier(DistributedSGD):
297
+ """Binary synchronous SGD classifier."""
298
+
299
+ def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
300
+ super().__init__(plan, task="classification")
301
+
302
+
303
+ class DistributedSGDRegressor(DistributedSGD):
304
+ """Squared-error synchronous SGD regressor."""
305
+
306
+ def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
307
+ super().__init__(plan, task="regression")
308
+
309
+
310
+ def create_algorithm(
311
+ *,
312
+ plan: ResolvedAlgorithmPlan,
313
+ implementation: object,
314
+ artifacts: tuple[object, ...],
315
+ ) -> DistributedSGD:
316
+ """Construct the descriptor-selected SGD implementation."""
317
+ del artifacts
318
+ if not isinstance(implementation, type) or not issubclass(
319
+ implementation, DistributedSGD
320
+ ):
321
+ raise AlgorithmConfigurationError("SGD implementation reference drifted")
322
+ constructor = cast(Any, implementation)
323
+ return cast(DistributedSGD, constructor(plan))
324
+
325
+
326
+ __all__ = [
327
+ "DistributedSGD",
328
+ "DistributedSGDClassifier",
329
+ "DistributedSGDRegressor",
330
+ "create_algorithm",
331
+ ]