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,643 @@
1
+ """True distributed MultinomialNB using bounded sufficient statistics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Iterable, Mapping
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+ from tributo.algorithms.api import (
11
+ AlgorithmConfigurationError,
12
+ AlgorithmExecutionError,
13
+ AlgorithmExecutionResult,
14
+ AlgorithmInputError,
15
+ AlgorithmOperation,
16
+ AlgorithmRegistration,
17
+ ArtifactDraft,
18
+ BackendInputCompatibility,
19
+ ContractBinding,
20
+ ContractBindingSet,
21
+ DistributedAlgorithmDescriptor,
22
+ DistributionSpec,
23
+ DistributionStrategy,
24
+ EnvironmentSpec,
25
+ ExecutionMode,
26
+ ExecutionProfile,
27
+ ImplementationDescriptor,
28
+ InputDistribution,
29
+ MapReducePolicy,
30
+ QualifiedReference,
31
+ ResolvedAlgorithmPlan,
32
+ RuntimeTopology,
33
+ StateCoordination,
34
+ StateField,
35
+ WorkerRange,
36
+ WorkerResources,
37
+ )
38
+ from tributo.algorithms.api.models import FORMAL_DISTRIBUTED_STRATEGY_CONTRACTS
39
+ from tributo.algorithms.spi import AlgorithmExecutionContext, MapReduceAlgorithm
40
+ from tributo.training.algorithm_spec import AlgorithmSpec, Capability, ProblemType
41
+ from tributo.util.annotations import DeveloperAPI, PublicAPI
42
+
43
+ _STATE_SCHEMA = (
44
+ StateField("classes", "int64", (None,)),
45
+ StateField("class_count", "float64", (None,)),
46
+ StateField("feature_count", "float64", (None, None)),
47
+ StateField("row_count", "int64", ()),
48
+ )
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class MultinomialNBModel:
53
+ """Bounded finalizer output passed to the declared exporter."""
54
+
55
+ estimator: Any
56
+ feature_names: tuple[str, ...]
57
+ row_count: int
58
+ sample_weight_sum: float
59
+
60
+
61
+ @PublicAPI(stability="alpha")
62
+ class DistributedMultinomialNB(
63
+ MapReduceAlgorithm[
64
+ Mapping[str, object],
65
+ Mapping[str, object],
66
+ MultinomialNBModel,
67
+ ]
68
+ ):
69
+ """Map and merge exact class/feature counts before public-API finalization."""
70
+
71
+ def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
72
+ self._plan = plan
73
+ binding = plan.primary_input_binding
74
+ self._feature_names = binding.feature_names
75
+ label_name = binding.label_name
76
+ self._label_name: str = label_name or ""
77
+ self._weight_name = binding.sample_weight_name
78
+ if label_name is None:
79
+ raise AlgorithmConfigurationError(
80
+ "MultinomialNB fit requires InputBinding.label_name"
81
+ )
82
+
83
+ def map_partition(
84
+ self,
85
+ batches: Iterable[Mapping[str, object]],
86
+ context: AlgorithmExecutionContext,
87
+ ) -> Mapping[str, object]:
88
+ """Aggregate one shard into class and feature sufficient statistics."""
89
+ del context
90
+ import numpy as np
91
+
92
+ state = self.empty_partition()
93
+ for batch in batches:
94
+ features, labels, weights = self._batch_arrays(batch)
95
+ if labels.size == 0:
96
+ continue
97
+ classes = np.unique(labels)
98
+ class_count = np.zeros(classes.shape[0], dtype=np.float64)
99
+ feature_count = np.zeros(
100
+ (classes.shape[0], len(self._feature_names)),
101
+ dtype=np.float64,
102
+ )
103
+ for index, label in enumerate(classes):
104
+ mask = labels == label
105
+ selected_weights = weights[mask]
106
+ class_count[index] = selected_weights.sum(dtype=np.float64)
107
+ feature_count[index] = self._weighted_feature_sum(
108
+ features[mask],
109
+ selected_weights,
110
+ np,
111
+ )
112
+ state = self.merge_states(
113
+ state,
114
+ {
115
+ "classes": classes.astype(np.int64, copy=False),
116
+ "class_count": class_count,
117
+ "feature_count": feature_count,
118
+ "row_count": np.asarray(labels.shape[0], dtype=np.int64),
119
+ },
120
+ )
121
+ return state
122
+
123
+ def _batch_arrays(self, batch: Mapping[str, object]) -> tuple[Any, Any, Any]:
124
+ import numpy as np
125
+ from scipy import sparse
126
+
127
+ missing = [
128
+ name
129
+ for name in (*self._feature_names, self._label_name)
130
+ if name not in batch
131
+ ]
132
+ if self._weight_name is not None and self._weight_name not in batch:
133
+ missing.append(self._weight_name)
134
+ if missing:
135
+ raise AlgorithmInputError(
136
+ f"MultinomialNB batch is missing required column(s): {missing}"
137
+ )
138
+ try:
139
+ feature_columns = [
140
+ self._feature_column(batch[name], np, sparse)
141
+ for name in self._feature_names
142
+ ]
143
+ if any(sparse.issparse(column) for column in feature_columns):
144
+ sparse_columns = [
145
+ column
146
+ if sparse.issparse(column)
147
+ else sparse.csr_matrix(column[:, None])
148
+ for column in feature_columns
149
+ ]
150
+ features = sparse.hstack(sparse_columns, format="csr")
151
+ else:
152
+ features = np.column_stack(feature_columns)
153
+ raw_labels = np.asarray(batch[self._label_name])
154
+ labels = raw_labels.astype(np.int64)
155
+ if raw_labels.ndim != 1 or not np.array_equal(raw_labels, labels):
156
+ raise ValueError("labels must contain exact integer values")
157
+ weights = (
158
+ np.asarray(batch[self._weight_name], dtype=np.float64)
159
+ if self._weight_name is not None
160
+ else np.ones(labels.shape[0], dtype=np.float64)
161
+ )
162
+ except (TypeError, ValueError) as exc:
163
+ raise AlgorithmInputError(
164
+ f"MultinomialNB could not convert a tabular batch: {exc}"
165
+ ) from exc
166
+ if features.shape[0] != labels.shape[0] or weights.shape != labels.shape:
167
+ raise AlgorithmInputError(
168
+ "MultinomialNB feature, label, and sample-weight rows disagree"
169
+ )
170
+ feature_values = features.data if sparse.issparse(features) else features
171
+ if not np.isfinite(feature_values).all() or (feature_values < 0).any():
172
+ raise AlgorithmInputError(
173
+ "MultinomialNB features must be finite and non-negative"
174
+ )
175
+ if not np.isfinite(weights).all() or (weights < 0).any():
176
+ raise AlgorithmInputError(
177
+ "MultinomialNB sample weights must be finite and non-negative"
178
+ )
179
+ return features, labels, weights
180
+
181
+ @staticmethod
182
+ def _feature_column(value: object, np: Any, sparse: Any) -> Any:
183
+ """Normalize a dense or sparse batch column without batch densification."""
184
+ if sparse.issparse(value):
185
+ column = sparse.csr_matrix(value, dtype=np.float64)
186
+ if column.ndim != 2 or column.shape[1] != 1:
187
+ raise ValueError("sparse feature columns must have shape (rows, 1)")
188
+ return column
189
+ array = np.asarray(value, dtype=np.float64)
190
+ if array.ndim == 2 and array.shape[1] == 1:
191
+ array = array[:, 0]
192
+ if array.ndim != 1:
193
+ raise ValueError("feature columns must be one-dimensional")
194
+ return array
195
+
196
+ @staticmethod
197
+ def _weighted_feature_sum(features: Any, weights: Any, np: Any) -> Any:
198
+ """Return one bounded dense statistic while preserving sparse batches."""
199
+ from scipy import sparse
200
+
201
+ if sparse.issparse(features):
202
+ return np.asarray(
203
+ features.multiply(weights[:, None]).sum(axis=0),
204
+ dtype=np.float64,
205
+ ).reshape(-1)
206
+ return (features * weights[:, None]).sum(axis=0, dtype=np.float64)
207
+
208
+ def merge_states(
209
+ self,
210
+ left: Mapping[str, object],
211
+ right: Mapping[str, object],
212
+ ) -> Mapping[str, object]:
213
+ """Associatively align class identities and sum exact counts."""
214
+ import numpy as np
215
+
216
+ left_classes = np.asarray(left["classes"], dtype=np.int64)
217
+ right_classes = np.asarray(right["classes"], dtype=np.int64)
218
+ classes = np.union1d(left_classes, right_classes).astype(np.int64)
219
+ class_count = np.zeros(classes.shape[0], dtype=np.float64)
220
+ feature_count = np.zeros(
221
+ (classes.shape[0], len(self._feature_names)),
222
+ dtype=np.float64,
223
+ )
224
+ row_count = 0
225
+ for state, state_classes in (
226
+ (left, left_classes),
227
+ (right, right_classes),
228
+ ):
229
+ counts = np.asarray(state["class_count"], dtype=np.float64)
230
+ features = np.asarray(state["feature_count"], dtype=np.float64)
231
+ if counts.shape != (state_classes.shape[0],) or features.shape != (
232
+ state_classes.shape[0],
233
+ len(self._feature_names),
234
+ ):
235
+ raise AlgorithmExecutionError(
236
+ "MultinomialNB state dimensions are internally inconsistent"
237
+ )
238
+ if state_classes.size:
239
+ indices = np.searchsorted(classes, state_classes)
240
+ class_count[indices] += counts
241
+ feature_count[indices] += features
242
+ raw_row_count = np.asarray(state["row_count"], dtype=np.int64)
243
+ if raw_row_count.shape != ():
244
+ raise AlgorithmExecutionError(
245
+ "MultinomialNB row_count state must be scalar"
246
+ )
247
+ row_count += int(raw_row_count)
248
+ return {
249
+ "classes": classes,
250
+ "class_count": class_count,
251
+ "feature_count": feature_count,
252
+ "row_count": np.asarray(row_count, dtype=np.int64),
253
+ }
254
+
255
+ def finalize_model(self, state: Mapping[str, object]) -> MultinomialNBModel:
256
+ """Reconstruct sklearn state through public ``partial_fit`` only."""
257
+ import numpy as np
258
+ from sklearn.naive_bayes import MultinomialNB
259
+
260
+ classes = np.asarray(state["classes"], dtype=np.int64)
261
+ class_count = np.asarray(state["class_count"], dtype=np.float64)
262
+ feature_count = np.asarray(state["feature_count"], dtype=np.float64)
263
+ row_count = int(np.asarray(state["row_count"], dtype=np.int64))
264
+ if classes.size == 0 or class_count.sum() <= 0:
265
+ raise AlgorithmInputError(
266
+ "MultinomialNB requires at least one positive-weight training row"
267
+ )
268
+ config = dict(self._plan.algorithm_config)
269
+ class_prior_value = config.get("class_prior")
270
+ class_prior = (
271
+ list(class_prior_value)
272
+ if isinstance(class_prior_value, (list, tuple))
273
+ else class_prior_value
274
+ )
275
+ estimator = MultinomialNB(
276
+ alpha=float(config.get("alpha", 1.0)),
277
+ force_alpha=bool(config.get("force_alpha", True)),
278
+ fit_prior=bool(config.get("fit_prior", True)),
279
+ class_prior=class_prior,
280
+ )
281
+ synthetic = np.divide(
282
+ feature_count,
283
+ class_count[:, None],
284
+ out=np.zeros_like(feature_count),
285
+ where=class_count[:, None] != 0,
286
+ )
287
+ estimator.partial_fit(
288
+ synthetic,
289
+ classes,
290
+ classes=classes,
291
+ sample_weight=class_count,
292
+ )
293
+ return MultinomialNBModel(
294
+ estimator=estimator,
295
+ feature_names=self._feature_names,
296
+ row_count=row_count,
297
+ sample_weight_sum=float(class_count.sum()),
298
+ )
299
+
300
+ def state_schema(self) -> tuple[StateField, ...]:
301
+ """Return the exact descriptor-owned state schema."""
302
+ return _STATE_SCHEMA
303
+
304
+ def empty_partition(self) -> Mapping[str, object]:
305
+ """Return the identity state for an empty shard."""
306
+ import numpy as np
307
+
308
+ return {
309
+ "classes": np.empty((0,), dtype=np.int64),
310
+ "class_count": np.empty((0,), dtype=np.float64),
311
+ "feature_count": np.empty((0, len(self._feature_names)), dtype=np.float64),
312
+ "row_count": np.asarray(0, dtype=np.int64),
313
+ }
314
+
315
+ @property
316
+ def retry_safe(self) -> bool:
317
+ """Map and merge stages are deterministic and side-effect free."""
318
+ return True
319
+
320
+
321
+ @DeveloperAPI
322
+ def create_algorithm(
323
+ *,
324
+ plan: ResolvedAlgorithmPlan,
325
+ implementation: object,
326
+ artifacts: tuple[object, ...],
327
+ ) -> DistributedMultinomialNB:
328
+ """Construct the descriptor-selected MapReduce implementation."""
329
+ del artifacts
330
+ if not isinstance(implementation, type) or not issubclass(
331
+ implementation, DistributedMultinomialNB
332
+ ):
333
+ raise AlgorithmConfigurationError(
334
+ "MultinomialNB implementation reference must resolve to its SPI class"
335
+ )
336
+ return implementation(plan)
337
+
338
+
339
+ @DeveloperAPI
340
+ def export_model(
341
+ *,
342
+ model: MultinomialNBModel,
343
+ plan: ResolvedAlgorithmPlan,
344
+ run_id: str | None = None,
345
+ ) -> AlgorithmExecutionResult:
346
+ """Convert the finalized estimator to a bounded ONNX artifact."""
347
+ import numpy as np
348
+ from skl2onnx import convert_sklearn
349
+ from skl2onnx.common.data_types import FloatTensorType
350
+ from sklearn import __version__ as sklearn_version
351
+
352
+ if not isinstance(model, MultinomialNBModel):
353
+ raise AlgorithmExecutionError(
354
+ "MultinomialNB exporter received an incompatible model"
355
+ )
356
+ try:
357
+ onnx_model = convert_sklearn(
358
+ model.estimator,
359
+ initial_types=[
360
+ (
361
+ "float_input",
362
+ FloatTensorType([None, len(model.feature_names)]),
363
+ )
364
+ ],
365
+ options={id(model.estimator): {"zipmap": False}},
366
+ target_opset=18,
367
+ )
368
+ onnx_model.graph.name = "tributo-multinomial-nb"
369
+ onnx_model.doc_string = ""
370
+ for node in onnx_model.graph.node:
371
+ node.doc_string = ""
372
+ metadata = {
373
+ "feature_names": json.dumps(model.feature_names),
374
+ "distribution_spec_digest": plan.runtime.distribution_digest or "",
375
+ }
376
+ for name, value in sorted(metadata.items()):
377
+ item = onnx_model.metadata_props.add()
378
+ item.key = name
379
+ item.value = value
380
+ payload = onnx_model.SerializeToString()
381
+ except Exception as exc:
382
+ raise AlgorithmExecutionError(
383
+ f"MultinomialNB ONNX export failed: {type(exc).__name__}"
384
+ ) from exc
385
+ estimator = model.estimator
386
+ artifact = ArtifactDraft.from_payload(
387
+ name="model",
388
+ kind="model",
389
+ format="application/onnx",
390
+ payload=payload,
391
+ )
392
+ output_config = plan.algorithm_config.get("output", {})
393
+ bundle_outputs: dict[str, object] = {}
394
+ if isinstance(output_config, Mapping) and output_config.get("bundle_uri"):
395
+ from tributo.exporting.models import (
396
+ BundleOutputConfig,
397
+ CheckpointField,
398
+ ExportCheckpointV1,
399
+ ExportSource,
400
+ ExportTarget,
401
+ )
402
+ from tributo.exporting.service import BundleExportService
403
+
404
+ bundle_uri = output_config["bundle_uri"]
405
+ if not isinstance(bundle_uri, str) or not bundle_uri:
406
+ raise AlgorithmConfigurationError(
407
+ "output.bundle_uri must be a non-empty string"
408
+ )
409
+ source = ExportSource(
410
+ source_kind="prebuilt_onnx",
411
+ model_object=payload,
412
+ feature_schema={"feature_names": list(model.feature_names)},
413
+ metadata={
414
+ "framework": "sklearn",
415
+ "framework_versions": {"scikit-learn": sklearn_version},
416
+ "task_type": "classification",
417
+ },
418
+ source_fingerprint=artifact.sha256,
419
+ checkpoint_contract=ExportCheckpointV1(
420
+ trainer_type="sklearn",
421
+ architecture_id=plan.resolution.algorithm,
422
+ input_schema=(
423
+ CheckpointField(
424
+ name="float_input",
425
+ dtype="float32",
426
+ shape=("batch", len(model.feature_names)),
427
+ ),
428
+ ),
429
+ output_schema=(
430
+ CheckpointField(
431
+ name="label",
432
+ dtype="int64",
433
+ shape=("batch",),
434
+ ),
435
+ CheckpointField(
436
+ name="probabilities",
437
+ dtype="float32",
438
+ shape=("batch", len(model.estimator.classes_)),
439
+ ),
440
+ ),
441
+ task_type="classification",
442
+ framework="sklearn",
443
+ framework_version=sklearn_version,
444
+ ),
445
+ )
446
+ bundle = BundleExportService().export_bundle(
447
+ source,
448
+ BundleOutputConfig(
449
+ bundle_uri=bundle_uri,
450
+ request_id=run_id,
451
+ run_id=run_id,
452
+ targets=[
453
+ ExportTarget(
454
+ name="onnx-model",
455
+ format="onnx",
456
+ exporter_id="prebuilt-onnx-v1",
457
+ )
458
+ ],
459
+ roles={"inference": "onnx-model"},
460
+ ),
461
+ )
462
+ bundle_outputs = {
463
+ "bundle_id": bundle.bundle_id,
464
+ "bundle_uri": bundle.canonical_uri,
465
+ "execution_id": bundle.execution_id,
466
+ "manifest_sha256": bundle.manifest_sha256,
467
+ }
468
+ return AlgorithmExecutionResult(
469
+ status="succeeded",
470
+ metrics={
471
+ "row_count": model.row_count,
472
+ "sample_weight_sum": model.sample_weight_sum,
473
+ },
474
+ outputs={
475
+ "classes": np.asarray(estimator.classes_).tolist(),
476
+ "class_count": np.asarray(estimator.class_count_).tolist(),
477
+ "feature_count": np.asarray(estimator.feature_count_).tolist(),
478
+ **bundle_outputs,
479
+ },
480
+ artifacts=(artifact,),
481
+ )
482
+
483
+
484
+ _MAP_REDUCE_CONTRACT = FORMAL_DISTRIBUTED_STRATEGY_CONTRACTS[
485
+ DistributionStrategy.RAY_MAP_REDUCE
486
+ ]
487
+ _INPUT_ADAPTER = QualifiedReference.parse(_MAP_REDUCE_CONTRACT.worker_input_adapter_ref)
488
+
489
+
490
+ def _contract_binding(
491
+ contract_id: str,
492
+ digest: str,
493
+ validator: str,
494
+ ) -> ContractBinding:
495
+ return ContractBinding(
496
+ contract_id=contract_id,
497
+ schema_version=1,
498
+ schema_digest=digest * 64,
499
+ validator_ref=QualifiedReference.parse(
500
+ f"tributo_algorithms_classical.contracts:{validator}"
501
+ ),
502
+ )
503
+
504
+
505
+ _CONTRACTS = ContractBindingSet(
506
+ config=_contract_binding(
507
+ "tributo.multinomial_nb.config.v1",
508
+ "5",
509
+ "ClassicalConfigValidator",
510
+ ),
511
+ input=_contract_binding(
512
+ "tributo.tabular.nonnegative.v1",
513
+ "2",
514
+ "TabularInputValidator",
515
+ ),
516
+ output=_contract_binding(
517
+ "tributo.classification.onnx.v1",
518
+ "3",
519
+ "SklearnOutputValidator",
520
+ ),
521
+ coverage=_contract_binding(
522
+ "tributo.official.distributed.coverage.v1",
523
+ "4",
524
+ "DistributedCoverageValidator",
525
+ ),
526
+ )
527
+
528
+ MULTINOMIAL_NB_REGISTRATION = AlgorithmRegistration(
529
+ spec=AlgorithmSpec(
530
+ name="multinomial_nb",
531
+ trainer_cls=None,
532
+ version="1.0.0",
533
+ default_config={"alpha": 1.0, "force_alpha": True, "fit_prior": True},
534
+ supported_tasks=("fit",),
535
+ operations=("fit",),
536
+ problem_types=(
537
+ ProblemType.BINARY_CLASSIFICATION,
538
+ ProblemType.MULTI_CLASS_CLASSIFICATION,
539
+ ),
540
+ capabilities=(Capability.EXPORTABLE, Capability.DISTRIBUTED),
541
+ extras_group="training",
542
+ learning_paradigm="supervised",
543
+ model_family="naive_bayes",
544
+ data_modalities=("tabular",),
545
+ lifecycle_kind="batch_fit",
546
+ allowed_execution_modes=(ExecutionMode.MAP_REDUCE.value,),
547
+ config_contract_ref="tributo.multinomial_nb.config.v1",
548
+ input_contract_ref="tributo.tabular.nonnegative.v1",
549
+ output_contract_ref="tributo.classification.onnx.v1",
550
+ ),
551
+ implementation=ImplementationDescriptor(
552
+ implementation_id="tributo.official.multinomial_nb.map_reduce",
553
+ version="1.0.0",
554
+ execution_mode=ExecutionMode.MAP_REDUCE,
555
+ implementation_ref=QualifiedReference.parse(
556
+ "tributo_algorithms_classical.multinomial_nb:DistributedMultinomialNB"
557
+ ),
558
+ executable_factory_ref=QualifiedReference.parse(
559
+ "tributo_algorithms_classical.multinomial_nb:create_algorithm"
560
+ ),
561
+ operations=(AlgorithmOperation.FIT,),
562
+ input_compatibility=BackendInputCompatibility(
563
+ accepted_input_views=("ray_data",),
564
+ accepted_ingestion_engines=("tributo.ray_data",),
565
+ required_input_capabilities=("shardable",),
566
+ supported_explicit_adapters=(_INPUT_ADAPTER,),
567
+ distribution_policy=(RuntimeTopology.RAY_MAP_REDUCE,),
568
+ ),
569
+ distribution="tributo-algorithms",
570
+ framework="sklearn",
571
+ artifact_format="none",
572
+ allowed_config_keys=(
573
+ "alpha",
574
+ "class_prior",
575
+ "fit_prior",
576
+ "force_alpha",
577
+ "output",
578
+ ),
579
+ runtime_id=_MAP_REDUCE_CONTRACT.runtime_id,
580
+ worker_input_adapter_ref=_INPUT_ADAPTER,
581
+ exporter_ref=QualifiedReference.parse(
582
+ "tributo_algorithms_classical.multinomial_nb:export_model"
583
+ ),
584
+ flavor_id="onnx-runtime-v1",
585
+ ),
586
+ environment=EnvironmentSpec(
587
+ environment_id="tributo.multinomial_nb.v1",
588
+ dependencies=(
589
+ "tributo-algorithms[classical]==0.1.0",
590
+ "tributo>=1.1",
591
+ "onnx>=1.16.0",
592
+ "onnxruntime>=1.20.0",
593
+ "scikit-learn>=1.4,<2",
594
+ "skl2onnx>=1.17",
595
+ ),
596
+ ),
597
+ distribution_spec=DistributionSpec(
598
+ strategy=DistributionStrategy.RAY_MAP_REDUCE,
599
+ supported_worker_range=WorkerRange(1, 1024),
600
+ supported_execution_profiles=(
601
+ ExecutionProfile.LOCAL,
602
+ ExecutionProfile.CLUSTER,
603
+ ),
604
+ resources_per_worker=WorkerResources(num_cpus=1, num_gpus=0),
605
+ input_distribution=InputDistribution.SHARDED,
606
+ state_coordination=StateCoordination.ASSOCIATIVE_REDUCE,
607
+ policy=MapReducePolicy(
608
+ state_schema=_STATE_SCHEMA,
609
+ max_partial_state_bytes=64 * 1024 * 1024,
610
+ reducer_ref=(
611
+ "tributo_algorithms_classical.multinomial_nb:"
612
+ "DistributedMultinomialNB.merge_states"
613
+ ),
614
+ finalizer_ref=(
615
+ "tributo_algorithms_classical.multinomial_nb:"
616
+ "DistributedMultinomialNB.finalize_model"
617
+ ),
618
+ commutative=True,
619
+ max_retries=0,
620
+ ),
621
+ ),
622
+ contract_bindings=_CONTRACTS,
623
+ is_default=True,
624
+ )
625
+
626
+ MULTINOMIAL_NB_DESCRIPTOR = DistributedAlgorithmDescriptor(
627
+ registration=MULTINOMIAL_NB_REGISTRATION,
628
+ package_name="tributo-algorithms",
629
+ package_version="0.1.0",
630
+ tributo_version_spec=">=1.1",
631
+ stability="alpha",
632
+ tested=False,
633
+ supported=False,
634
+ validated_execution_profiles=(),
635
+ api_version=2,
636
+ )
637
+
638
+
639
+ __all__ = [
640
+ "DistributedMultinomialNB",
641
+ "create_algorithm",
642
+ "export_model",
643
+ ]