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,183 @@
|
|
|
1
|
+
"""Lightweight descriptor for the official distributed MultinomialNB."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from tributo.algorithms.api import (
|
|
6
|
+
AlgorithmOperation,
|
|
7
|
+
AlgorithmRegistration,
|
|
8
|
+
BackendInputCompatibility,
|
|
9
|
+
ContractBinding,
|
|
10
|
+
ContractBindingSet,
|
|
11
|
+
DistributedAlgorithmDescriptor,
|
|
12
|
+
DistributionSpec,
|
|
13
|
+
DistributionStrategy,
|
|
14
|
+
EnvironmentSpec,
|
|
15
|
+
ExecutionMode,
|
|
16
|
+
ExecutionProfile,
|
|
17
|
+
ImplementationDescriptor,
|
|
18
|
+
InputDistribution,
|
|
19
|
+
MapReducePolicy,
|
|
20
|
+
QualifiedReference,
|
|
21
|
+
RuntimeTopology,
|
|
22
|
+
StateCoordination,
|
|
23
|
+
StateField,
|
|
24
|
+
WorkerRange,
|
|
25
|
+
WorkerResources,
|
|
26
|
+
)
|
|
27
|
+
from tributo.algorithms.api.models import FORMAL_DISTRIBUTED_STRATEGY_CONTRACTS
|
|
28
|
+
from tributo.training.algorithm_spec import AlgorithmSpec, Capability, ProblemType
|
|
29
|
+
|
|
30
|
+
_STATE_SCHEMA = (
|
|
31
|
+
StateField("classes", "int64", (None,)),
|
|
32
|
+
StateField("class_count", "float64", (None,)),
|
|
33
|
+
StateField("feature_count", "float64", (None, None)),
|
|
34
|
+
StateField("row_count", "int64", ()),
|
|
35
|
+
)
|
|
36
|
+
_MAP_REDUCE_CONTRACT = FORMAL_DISTRIBUTED_STRATEGY_CONTRACTS[
|
|
37
|
+
DistributionStrategy.RAY_MAP_REDUCE
|
|
38
|
+
]
|
|
39
|
+
_INPUT_ADAPTER = QualifiedReference.parse(_MAP_REDUCE_CONTRACT.worker_input_adapter_ref)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _binding(contract_id: str, digest: str, validator: str) -> ContractBinding:
|
|
43
|
+
return ContractBinding(
|
|
44
|
+
contract_id=contract_id,
|
|
45
|
+
schema_version=1,
|
|
46
|
+
schema_digest=digest * 64,
|
|
47
|
+
validator_ref=QualifiedReference.parse(
|
|
48
|
+
f"tributo_algorithms_classical.contracts:{validator}"
|
|
49
|
+
),
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
_CONTRACTS = ContractBindingSet(
|
|
54
|
+
config=_binding(
|
|
55
|
+
"tributo.multinomial_nb.config.v1",
|
|
56
|
+
"5",
|
|
57
|
+
"ClassicalConfigValidator",
|
|
58
|
+
),
|
|
59
|
+
input=_binding(
|
|
60
|
+
"tributo.tabular.nonnegative.v1",
|
|
61
|
+
"2",
|
|
62
|
+
"TabularInputValidator",
|
|
63
|
+
),
|
|
64
|
+
output=_binding(
|
|
65
|
+
"tributo.classification.onnx.v1",
|
|
66
|
+
"3",
|
|
67
|
+
"SklearnOutputValidator",
|
|
68
|
+
),
|
|
69
|
+
coverage=_binding(
|
|
70
|
+
"tributo.official.distributed.coverage.v1",
|
|
71
|
+
"4",
|
|
72
|
+
"DistributedCoverageValidator",
|
|
73
|
+
),
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
MULTINOMIAL_NB_REGISTRATION = AlgorithmRegistration(
|
|
77
|
+
spec=AlgorithmSpec(
|
|
78
|
+
name="multinomial_nb",
|
|
79
|
+
trainer_cls=None,
|
|
80
|
+
version="1.0.0",
|
|
81
|
+
default_config={"alpha": 1.0, "force_alpha": True, "fit_prior": True},
|
|
82
|
+
supported_tasks=("fit",),
|
|
83
|
+
operations=("fit",),
|
|
84
|
+
problem_types=(
|
|
85
|
+
ProblemType.BINARY_CLASSIFICATION,
|
|
86
|
+
ProblemType.MULTI_CLASS_CLASSIFICATION,
|
|
87
|
+
),
|
|
88
|
+
capabilities=(Capability.EXPORTABLE, Capability.DISTRIBUTED),
|
|
89
|
+
extras_group="training",
|
|
90
|
+
learning_paradigm="supervised",
|
|
91
|
+
model_family="naive_bayes",
|
|
92
|
+
data_modalities=("tabular",),
|
|
93
|
+
lifecycle_kind="batch_fit",
|
|
94
|
+
allowed_execution_modes=(ExecutionMode.MAP_REDUCE.value,),
|
|
95
|
+
config_contract_ref="tributo.multinomial_nb.config.v1",
|
|
96
|
+
input_contract_ref="tributo.tabular.nonnegative.v1",
|
|
97
|
+
output_contract_ref="tributo.classification.onnx.v1",
|
|
98
|
+
),
|
|
99
|
+
implementation=ImplementationDescriptor(
|
|
100
|
+
implementation_id="tributo.official.multinomial_nb.map_reduce",
|
|
101
|
+
version="1.0.0",
|
|
102
|
+
execution_mode=ExecutionMode.MAP_REDUCE,
|
|
103
|
+
implementation_ref=QualifiedReference.parse(
|
|
104
|
+
"tributo_algorithms_classical.multinomial_nb:DistributedMultinomialNB"
|
|
105
|
+
),
|
|
106
|
+
executable_factory_ref=QualifiedReference.parse(
|
|
107
|
+
"tributo_algorithms_classical.multinomial_nb:create_algorithm"
|
|
108
|
+
),
|
|
109
|
+
operations=(AlgorithmOperation.FIT,),
|
|
110
|
+
input_compatibility=BackendInputCompatibility(
|
|
111
|
+
accepted_input_views=("ray_data",),
|
|
112
|
+
accepted_ingestion_engines=("tributo.ray_data",),
|
|
113
|
+
required_input_capabilities=("shardable",),
|
|
114
|
+
supported_explicit_adapters=(_INPUT_ADAPTER,),
|
|
115
|
+
distribution_policy=(RuntimeTopology.RAY_MAP_REDUCE,),
|
|
116
|
+
),
|
|
117
|
+
distribution="tributo-algorithms",
|
|
118
|
+
framework="sklearn",
|
|
119
|
+
artifact_format="none",
|
|
120
|
+
allowed_config_keys=(
|
|
121
|
+
"alpha",
|
|
122
|
+
"class_prior",
|
|
123
|
+
"fit_prior",
|
|
124
|
+
"force_alpha",
|
|
125
|
+
"output",
|
|
126
|
+
),
|
|
127
|
+
runtime_id=_MAP_REDUCE_CONTRACT.runtime_id,
|
|
128
|
+
worker_input_adapter_ref=_INPUT_ADAPTER,
|
|
129
|
+
exporter_ref=QualifiedReference.parse(
|
|
130
|
+
"tributo_algorithms_classical.multinomial_nb:export_model"
|
|
131
|
+
),
|
|
132
|
+
flavor_id="onnx-runtime-v1",
|
|
133
|
+
),
|
|
134
|
+
environment=EnvironmentSpec(
|
|
135
|
+
environment_id="tributo.multinomial_nb.v1",
|
|
136
|
+
dependencies=(
|
|
137
|
+
"tributo-algorithms[classical]==0.1.0",
|
|
138
|
+
"tributo>=1.1",
|
|
139
|
+
"onnx>=1.16.0",
|
|
140
|
+
"onnxruntime>=1.20.0",
|
|
141
|
+
"scikit-learn>=1.4,<2",
|
|
142
|
+
"skl2onnx>=1.17",
|
|
143
|
+
),
|
|
144
|
+
),
|
|
145
|
+
distribution_spec=DistributionSpec(
|
|
146
|
+
strategy=DistributionStrategy.RAY_MAP_REDUCE,
|
|
147
|
+
supported_worker_range=WorkerRange(1, 1024),
|
|
148
|
+
supported_execution_profiles=(
|
|
149
|
+
ExecutionProfile.LOCAL,
|
|
150
|
+
ExecutionProfile.CLUSTER,
|
|
151
|
+
),
|
|
152
|
+
resources_per_worker=WorkerResources(num_cpus=1, num_gpus=0),
|
|
153
|
+
input_distribution=InputDistribution.SHARDED,
|
|
154
|
+
state_coordination=StateCoordination.ASSOCIATIVE_REDUCE,
|
|
155
|
+
policy=MapReducePolicy(
|
|
156
|
+
state_schema=_STATE_SCHEMA,
|
|
157
|
+
max_partial_state_bytes=64 * 1024 * 1024,
|
|
158
|
+
reducer_ref=(
|
|
159
|
+
"tributo_algorithms_classical.multinomial_nb:"
|
|
160
|
+
"DistributedMultinomialNB.merge_states"
|
|
161
|
+
),
|
|
162
|
+
finalizer_ref=(
|
|
163
|
+
"tributo_algorithms_classical.multinomial_nb:"
|
|
164
|
+
"DistributedMultinomialNB.finalize_model"
|
|
165
|
+
),
|
|
166
|
+
commutative=True,
|
|
167
|
+
max_retries=0,
|
|
168
|
+
),
|
|
169
|
+
),
|
|
170
|
+
contract_bindings=_CONTRACTS,
|
|
171
|
+
is_default=True,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
MULTINOMIAL_NB_DESCRIPTOR = DistributedAlgorithmDescriptor(
|
|
175
|
+
registration=MULTINOMIAL_NB_REGISTRATION,
|
|
176
|
+
package_name="tributo-algorithms",
|
|
177
|
+
package_version="0.1.0",
|
|
178
|
+
tributo_version_spec=">=1.1",
|
|
179
|
+
api_version=2,
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
__all__ = ["MULTINOMIAL_NB_DESCRIPTOR", "MULTINOMIAL_NB_REGISTRATION"]
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Distributed PCA using Chan/Welford mergeable sufficient statistics."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable, Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from tributo.algorithms.api import (
|
|
10
|
+
AlgorithmConfigurationError,
|
|
11
|
+
AlgorithmExecutionError,
|
|
12
|
+
AlgorithmInputError,
|
|
13
|
+
ResolvedAlgorithmPlan,
|
|
14
|
+
)
|
|
15
|
+
from tributo.algorithms.spi import AlgorithmExecutionContext, MapReduceAlgorithm
|
|
16
|
+
|
|
17
|
+
from tributo_algorithms_classical.unsupervised_models import PCAModel
|
|
18
|
+
|
|
19
|
+
_MAX_PARTIAL_STATE_BYTES = 64 * 1024 * 1024
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _matrix(batch: Mapping[str, object], feature_names: tuple[str, ...]) -> np.ndarray:
|
|
23
|
+
try:
|
|
24
|
+
values = np.column_stack(
|
|
25
|
+
[np.asarray(batch[name], dtype=np.float64) for name in feature_names]
|
|
26
|
+
)
|
|
27
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
28
|
+
raise AlgorithmInputError(
|
|
29
|
+
"PCA input batch is not a dense feature matrix"
|
|
30
|
+
) from exc
|
|
31
|
+
if values.ndim != 2 or not values.shape[0]:
|
|
32
|
+
raise AlgorithmInputError("PCA input batches must contain rows")
|
|
33
|
+
if not np.isfinite(values).all():
|
|
34
|
+
raise AlgorithmInputError("PCA input must contain finite values")
|
|
35
|
+
return values
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _batch_state(values: np.ndarray) -> dict[str, object]:
|
|
39
|
+
mean = values.mean(axis=0, dtype=np.float64)
|
|
40
|
+
centered = values - mean
|
|
41
|
+
return {
|
|
42
|
+
"count": np.asarray(values.shape[0], dtype=np.int64),
|
|
43
|
+
"mean": mean,
|
|
44
|
+
"M2": centered.T @ centered,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class DistributedPCA(
|
|
49
|
+
MapReduceAlgorithm[Mapping[str, object], Mapping[str, object], PCAModel]
|
|
50
|
+
):
|
|
51
|
+
"""Fit PCA from associative per-shard count, mean, and M2 states."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
|
|
54
|
+
self._plan = plan
|
|
55
|
+
self._feature_names = plan.primary_input_binding.feature_names
|
|
56
|
+
feature_count = len(self._feature_names)
|
|
57
|
+
configured_count = plan.algorithm_config.get("feature_count")
|
|
58
|
+
if configured_count is not None and int(configured_count) != feature_count:
|
|
59
|
+
raise AlgorithmConfigurationError("PCA feature_count disagrees with input")
|
|
60
|
+
estimated_state_bytes = 8 * (feature_count * feature_count + feature_count + 1)
|
|
61
|
+
if estimated_state_bytes > _MAX_PARTIAL_STATE_BYTES:
|
|
62
|
+
raise AlgorithmConfigurationError(
|
|
63
|
+
"PCA feature dimension exceeds the bounded partial-state limit"
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
def map_partition(
|
|
67
|
+
self,
|
|
68
|
+
batches: Iterable[Mapping[str, object]],
|
|
69
|
+
context: AlgorithmExecutionContext,
|
|
70
|
+
) -> Mapping[str, object]:
|
|
71
|
+
del context
|
|
72
|
+
state = self.empty_partition()
|
|
73
|
+
for batch in batches:
|
|
74
|
+
state = self.merge_states(
|
|
75
|
+
state, _batch_state(_matrix(batch, self._feature_names))
|
|
76
|
+
)
|
|
77
|
+
return state
|
|
78
|
+
|
|
79
|
+
def merge_states(
|
|
80
|
+
self,
|
|
81
|
+
left: Mapping[str, object],
|
|
82
|
+
right: Mapping[str, object],
|
|
83
|
+
) -> Mapping[str, object]:
|
|
84
|
+
left_count = int(np.asarray(left["count"], dtype=np.int64))
|
|
85
|
+
right_count = int(np.asarray(right["count"], dtype=np.int64))
|
|
86
|
+
left_mean = np.asarray(left["mean"], dtype=np.float64)
|
|
87
|
+
right_mean = np.asarray(right["mean"], dtype=np.float64)
|
|
88
|
+
left_m2 = np.asarray(left["M2"], dtype=np.float64)
|
|
89
|
+
right_m2 = np.asarray(right["M2"], dtype=np.float64)
|
|
90
|
+
dimension = len(self._feature_names)
|
|
91
|
+
if (
|
|
92
|
+
left_mean.shape != (dimension,)
|
|
93
|
+
or right_mean.shape != (dimension,)
|
|
94
|
+
or left_m2.shape != (dimension, dimension)
|
|
95
|
+
or right_m2.shape != (dimension, dimension)
|
|
96
|
+
):
|
|
97
|
+
raise AlgorithmExecutionError(
|
|
98
|
+
"PCA partial state dimensions are inconsistent"
|
|
99
|
+
)
|
|
100
|
+
if left_count == 0:
|
|
101
|
+
return {
|
|
102
|
+
"count": np.asarray(right_count),
|
|
103
|
+
"mean": right_mean,
|
|
104
|
+
"M2": right_m2,
|
|
105
|
+
}
|
|
106
|
+
if right_count == 0:
|
|
107
|
+
return {"count": np.asarray(left_count), "mean": left_mean, "M2": left_m2}
|
|
108
|
+
total = left_count + right_count
|
|
109
|
+
delta = right_mean - left_mean
|
|
110
|
+
mean = left_mean + delta * (right_count / total)
|
|
111
|
+
m2 = (
|
|
112
|
+
left_m2
|
|
113
|
+
+ right_m2
|
|
114
|
+
+ np.outer(delta, delta) * (left_count * right_count / total)
|
|
115
|
+
)
|
|
116
|
+
return {"count": np.asarray(total, dtype=np.int64), "mean": mean, "M2": m2}
|
|
117
|
+
|
|
118
|
+
def finalize_model(self, state: Mapping[str, object]) -> PCAModel:
|
|
119
|
+
count = int(np.asarray(state["count"], dtype=np.int64))
|
|
120
|
+
if count < 2:
|
|
121
|
+
raise AlgorithmInputError("PCA requires at least two rows")
|
|
122
|
+
mean = np.asarray(state["mean"], dtype=np.float64)
|
|
123
|
+
covariance = np.asarray(state["M2"], dtype=np.float64) / (count - 1)
|
|
124
|
+
eigenvalues, eigenvectors = np.linalg.eigh(covariance)
|
|
125
|
+
order = np.argsort(eigenvalues)[::-1]
|
|
126
|
+
components_count = int(
|
|
127
|
+
self._plan.algorithm_config.get(
|
|
128
|
+
"n_components", min(len(self._feature_names), count)
|
|
129
|
+
)
|
|
130
|
+
)
|
|
131
|
+
if not 1 <= components_count <= min(len(self._feature_names), count):
|
|
132
|
+
raise AlgorithmConfigurationError(
|
|
133
|
+
"PCA n_components must be between 1 and min(feature_count, row_count)"
|
|
134
|
+
)
|
|
135
|
+
selected = order[:components_count]
|
|
136
|
+
explained = np.maximum(eigenvalues[selected], 0.0)
|
|
137
|
+
total_variance = float(np.maximum(eigenvalues, 0.0).sum())
|
|
138
|
+
ratio = (
|
|
139
|
+
explained / total_variance
|
|
140
|
+
if total_variance > 0
|
|
141
|
+
else np.zeros_like(explained)
|
|
142
|
+
)
|
|
143
|
+
return PCAModel(
|
|
144
|
+
components=eigenvectors[:, selected].T,
|
|
145
|
+
mean=mean,
|
|
146
|
+
explained_variance=explained,
|
|
147
|
+
explained_variance_ratio=ratio,
|
|
148
|
+
feature_names=self._feature_names,
|
|
149
|
+
n_samples=count,
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
def state_schema(self) -> tuple[Any, ...]:
|
|
153
|
+
from tributo.algorithms.api import StateField
|
|
154
|
+
|
|
155
|
+
return (
|
|
156
|
+
StateField("count", "int64", ()),
|
|
157
|
+
StateField("mean", "float64", (None,)),
|
|
158
|
+
StateField("M2", "float64", (None, None)),
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
def empty_partition(self) -> Mapping[str, object]:
|
|
162
|
+
dimension = len(self._feature_names)
|
|
163
|
+
return {
|
|
164
|
+
"count": np.asarray(0, dtype=np.int64),
|
|
165
|
+
"mean": np.zeros(dimension, dtype=np.float64),
|
|
166
|
+
"M2": np.zeros((dimension, dimension), dtype=np.float64),
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
@property
|
|
170
|
+
def retry_safe(self) -> bool:
|
|
171
|
+
return True
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def create_algorithm(
|
|
175
|
+
*,
|
|
176
|
+
plan: ResolvedAlgorithmPlan,
|
|
177
|
+
implementation: object,
|
|
178
|
+
artifacts: tuple[object, ...],
|
|
179
|
+
) -> DistributedPCA:
|
|
180
|
+
"""Construct the descriptor-selected PCA implementation."""
|
|
181
|
+
del artifacts
|
|
182
|
+
if implementation is not DistributedPCA:
|
|
183
|
+
raise AlgorithmConfigurationError("PCA implementation reference drifted")
|
|
184
|
+
return DistributedPCA(plan)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
__all__ = ["DistributedPCA", "create_algorithm"]
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Descriptor for the official distributed PCA algorithm."""
|
|
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
|
+
MapReducePolicy,
|
|
14
|
+
QualifiedReference,
|
|
15
|
+
StateField,
|
|
16
|
+
WorkerRange,
|
|
17
|
+
WorkerResources,
|
|
18
|
+
)
|
|
19
|
+
from tributo.training.algorithm_spec import AlgorithmSpec, Capability, DataLoadingMode
|
|
20
|
+
|
|
21
|
+
_PACKAGE = "tributo-algorithms"
|
|
22
|
+
_VERSION = "0.1.0"
|
|
23
|
+
_INPUT = "tributo.official.tabular.unlabeled_dense.v1"
|
|
24
|
+
_OUTPUT = "tributo.official.unsupervised.pca.transform.v1"
|
|
25
|
+
_COVERAGE = "tributo.official.distributed.coverage.v1"
|
|
26
|
+
_STATE_SCHEMA = (
|
|
27
|
+
StateField("count", "int64", ()),
|
|
28
|
+
StateField("mean", "float64", (None,)),
|
|
29
|
+
StateField("M2", "float64", (None, None)),
|
|
30
|
+
)
|
|
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
|
+
_SPEC = AlgorithmSpec(
|
|
45
|
+
name="pca",
|
|
46
|
+
trainer_cls=None,
|
|
47
|
+
version="1.0.0",
|
|
48
|
+
default_config={},
|
|
49
|
+
supported_tasks=("fit",),
|
|
50
|
+
operations=("fit",),
|
|
51
|
+
data_loading=DataLoadingMode.CANONICAL_DRIVER,
|
|
52
|
+
capabilities=(Capability.DISTRIBUTED, Capability.EXPORTABLE),
|
|
53
|
+
learning_paradigm="unsupervised",
|
|
54
|
+
model_family="principal_component_analysis",
|
|
55
|
+
data_modalities=("tabular",),
|
|
56
|
+
lifecycle_kind="batch_fit",
|
|
57
|
+
allowed_execution_modes=(ExecutionMode.MAP_REDUCE.value,),
|
|
58
|
+
config_contract_ref="tributo.official.unsupervised.pca.config.v1",
|
|
59
|
+
input_contract_ref=_INPUT,
|
|
60
|
+
output_contract_ref=_OUTPUT,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
PCA_DESCRIPTOR = AlgorithmBuilder.from_distributed_algorithm(
|
|
64
|
+
spec=_SPEC,
|
|
65
|
+
implementation_id="tributo.official.classical.pca.map_reduce",
|
|
66
|
+
implementation_version="1.0.0",
|
|
67
|
+
implementation="tributo_algorithms_classical.pca:DistributedPCA",
|
|
68
|
+
executable_factory="tributo_algorithms_classical.pca:create_algorithm",
|
|
69
|
+
distribution=_PACKAGE,
|
|
70
|
+
framework="numpy",
|
|
71
|
+
environment=EnvironmentSpec(
|
|
72
|
+
environment_id="tributo.official.classical.unsupervised.v1",
|
|
73
|
+
dependencies=(
|
|
74
|
+
"numpy>=2,<3",
|
|
75
|
+
"onnx>=1.16",
|
|
76
|
+
"onnxruntime>=1.20",
|
|
77
|
+
"tributo>=1.1",
|
|
78
|
+
f"tributo-algorithms[classical]=={_VERSION}",
|
|
79
|
+
),
|
|
80
|
+
),
|
|
81
|
+
allowed_config_keys=("feature_count", "n_components", "output", "runtime", "seed"),
|
|
82
|
+
strategy=DistributionStrategy.RAY_MAP_REDUCE,
|
|
83
|
+
supported_worker_range=WorkerRange(1, 1024),
|
|
84
|
+
supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
|
|
85
|
+
resources_per_worker=WorkerResources(num_cpus=1),
|
|
86
|
+
policy=MapReducePolicy(
|
|
87
|
+
state_schema=_STATE_SCHEMA,
|
|
88
|
+
max_partial_state_bytes=64 * 1024 * 1024,
|
|
89
|
+
reducer_ref="tributo_algorithms_classical.pca:DistributedPCA.merge_states",
|
|
90
|
+
finalizer_ref="tributo_algorithms_classical.pca:DistributedPCA.finalize_model",
|
|
91
|
+
commutative=True,
|
|
92
|
+
max_retries=0,
|
|
93
|
+
),
|
|
94
|
+
package_name=_PACKAGE,
|
|
95
|
+
package_version=_VERSION,
|
|
96
|
+
tributo_version_spec=">=1.1",
|
|
97
|
+
exporter="tributo_algorithms_classical.unsupervised_exporter:export_pca_model",
|
|
98
|
+
flavor_id="onnx-runtime-v1",
|
|
99
|
+
contract_bindings=ContractBindingSet(
|
|
100
|
+
config=_binding(
|
|
101
|
+
_SPEC.config_contract_ref or "", "6", "UnsupervisedConfigValidator"
|
|
102
|
+
),
|
|
103
|
+
input=_binding(_INPUT, "7", "UnlabeledDenseInputValidator"),
|
|
104
|
+
output=_binding(_OUTPUT, "8", "PCAOutputValidator"),
|
|
105
|
+
coverage=_binding(_COVERAGE, "a", "UnsupervisedCoverageValidator"),
|
|
106
|
+
),
|
|
107
|
+
descriptor_api_version=2,
|
|
108
|
+
is_default=True,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
__all__ = ["PCA_DESCRIPTOR"]
|