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,162 @@
|
|
|
1
|
+
"""Typed TorchRecipe implementation for the tabular autoencoder."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any, cast
|
|
7
|
+
|
|
8
|
+
from tributo.algorithms.api.torch_runtime import (
|
|
9
|
+
TorchLossContribution,
|
|
10
|
+
TorchMetricContribution,
|
|
11
|
+
)
|
|
12
|
+
from tributo.algorithms.spi import (
|
|
13
|
+
TorchArtifactContext,
|
|
14
|
+
TorchArtifactPlan,
|
|
15
|
+
TorchBatch,
|
|
16
|
+
TorchBatchContext,
|
|
17
|
+
TorchBuildContext,
|
|
18
|
+
TorchMetricPlan,
|
|
19
|
+
TorchModuleSet,
|
|
20
|
+
TorchOptimizationPlan,
|
|
21
|
+
TorchRecipe,
|
|
22
|
+
TorchRuntimeContext,
|
|
23
|
+
TorchStepContext,
|
|
24
|
+
TorchStepResult,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _batch(batch: object, context: TorchBatchContext) -> TorchBatch:
|
|
29
|
+
import torch
|
|
30
|
+
|
|
31
|
+
if not isinstance(batch, Mapping):
|
|
32
|
+
raise ValueError("Autoencoder batch must be columnar")
|
|
33
|
+
feature_names = context.feature_names or tuple(batch)
|
|
34
|
+
if not feature_names:
|
|
35
|
+
raise ValueError("Autoencoder requires dense feature columns")
|
|
36
|
+
if context.label_name is not None or context.weight_name is not None:
|
|
37
|
+
raise ValueError("Autoencoder does not accept label or sample-weight bindings")
|
|
38
|
+
features = torch.stack(
|
|
39
|
+
[torch.as_tensor(batch[name], dtype=torch.float32) for name in feature_names],
|
|
40
|
+
dim=1,
|
|
41
|
+
)
|
|
42
|
+
if not torch.isfinite(features).all():
|
|
43
|
+
raise ValueError("Autoencoder features must be finite")
|
|
44
|
+
rows = int(features.shape[0])
|
|
45
|
+
return TorchBatch(
|
|
46
|
+
keyword={"features": features},
|
|
47
|
+
targets=features,
|
|
48
|
+
local_rows=rows,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _model(config: Mapping[str, Any]) -> object:
|
|
53
|
+
import torch
|
|
54
|
+
|
|
55
|
+
input_features = int(config.get("input_features", 4))
|
|
56
|
+
latent_features = int(config.get("latent_features", 2))
|
|
57
|
+
if input_features < 1 or latent_features < 1:
|
|
58
|
+
raise ValueError("Autoencoder dimensions must be positive")
|
|
59
|
+
return torch.nn.Sequential(
|
|
60
|
+
torch.nn.Linear(input_features, latent_features),
|
|
61
|
+
torch.nn.ReLU(),
|
|
62
|
+
torch.nn.Linear(latent_features, input_features),
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class TabularAutoencoderRecipe(TorchRecipe):
|
|
67
|
+
"""Reconstruct dense inputs with element-normalized squared error."""
|
|
68
|
+
|
|
69
|
+
def build_modules(self, context: TorchBuildContext) -> TorchModuleSet:
|
|
70
|
+
import torch
|
|
71
|
+
|
|
72
|
+
model_config = context.runtime.algorithm_config.get("model", {})
|
|
73
|
+
if not isinstance(model_config, Mapping):
|
|
74
|
+
raise ValueError("Autoencoder model config must be a mapping")
|
|
75
|
+
return TorchModuleSet(
|
|
76
|
+
{"model": _model(model_config), "loss": torch.nn.Identity()}
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
def adapt_batch(self, batch: object, context: TorchBatchContext) -> TorchBatch:
|
|
80
|
+
return _batch(batch, context)
|
|
81
|
+
|
|
82
|
+
def training_step(
|
|
83
|
+
self, modules: TorchModuleSet, batch: TorchBatch, context: TorchStepContext
|
|
84
|
+
) -> TorchStepResult:
|
|
85
|
+
del context
|
|
86
|
+
import torch
|
|
87
|
+
|
|
88
|
+
model = cast(torch.nn.Module, modules["model"])
|
|
89
|
+
features = cast(torch.Tensor, batch.keyword["features"])
|
|
90
|
+
reconstruction = model(features)
|
|
91
|
+
squared_error = (reconstruction - cast(torch.Tensor, batch.targets)) ** 2
|
|
92
|
+
numerator = squared_error.sum()
|
|
93
|
+
element_count = int(squared_error.numel())
|
|
94
|
+
return TorchStepResult(
|
|
95
|
+
outputs={"output": reconstruction},
|
|
96
|
+
loss=TorchLossContribution(numerator, element_count),
|
|
97
|
+
metrics={
|
|
98
|
+
"reconstruction_mse": TorchMetricContribution(
|
|
99
|
+
float(numerator.detach().item()), element_count
|
|
100
|
+
)
|
|
101
|
+
},
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
def validation_step(
|
|
105
|
+
self, modules: TorchModuleSet, batch: TorchBatch, context: TorchStepContext
|
|
106
|
+
) -> TorchStepResult:
|
|
107
|
+
return self.training_step(modules, batch, context)
|
|
108
|
+
|
|
109
|
+
def configure_optimizers(
|
|
110
|
+
self, modules: TorchModuleSet, context: TorchBuildContext
|
|
111
|
+
) -> TorchOptimizationPlan:
|
|
112
|
+
import torch
|
|
113
|
+
|
|
114
|
+
optimizer_config = context.runtime.algorithm_config.get("optimizer", {})
|
|
115
|
+
if not isinstance(optimizer_config, Mapping):
|
|
116
|
+
raise ValueError("Autoencoder optimizer config must be a mapping")
|
|
117
|
+
return TorchOptimizationPlan(
|
|
118
|
+
optimizer=torch.optim.Adam(
|
|
119
|
+
cast(torch.nn.Module, modules["model"]).parameters(),
|
|
120
|
+
lr=float(optimizer_config.get("learning_rate", 0.01)),
|
|
121
|
+
weight_decay=float(optimizer_config.get("weight_decay", 0.0)),
|
|
122
|
+
),
|
|
123
|
+
gradient_accumulation_steps=optimizer_config.get("accumulation_steps", 1),
|
|
124
|
+
max_gradient_norm=optimizer_config.get("max_gradient_norm", 1.0),
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
def metric_plan(self, context: TorchRuntimeContext) -> TorchMetricPlan:
|
|
128
|
+
del context
|
|
129
|
+
return TorchMetricPlan(
|
|
130
|
+
{"reconstruction_mse": "sum_count", "train_loss": "sum_count"}
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
def artifact_plan(self, context: TorchArtifactContext) -> TorchArtifactPlan:
|
|
134
|
+
config = context.stage.runtime.algorithm_config.get("model", {})
|
|
135
|
+
features = (
|
|
136
|
+
int(config.get("input_features", 4)) if isinstance(config, Mapping) else 4
|
|
137
|
+
)
|
|
138
|
+
return TorchArtifactPlan(
|
|
139
|
+
source_kind="torch_module",
|
|
140
|
+
input_signature=(
|
|
141
|
+
{"name": "features", "dtype": "float32", "shape": ("batch", features)},
|
|
142
|
+
),
|
|
143
|
+
output_signature=(
|
|
144
|
+
{
|
|
145
|
+
"name": "output",
|
|
146
|
+
"dtype": "float32",
|
|
147
|
+
"shape": ("batch", features),
|
|
148
|
+
},
|
|
149
|
+
),
|
|
150
|
+
targets=(
|
|
151
|
+
{
|
|
152
|
+
"name": "onnx-model",
|
|
153
|
+
"format": "onnx",
|
|
154
|
+
"exporter_id": "torch-onnx-v1",
|
|
155
|
+
"options": {"dynamo": False},
|
|
156
|
+
},
|
|
157
|
+
),
|
|
158
|
+
roles={"inference": "onnx-model"},
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
__all__ = ["TabularAutoencoderRecipe"]
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Official distributed tabular PyTorch algorithms with lazy runtime exports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from tributo_algorithms_tabular_torch.descriptor import DNN_DESCRIPTOR, PU_DESCRIPTOR
|
|
8
|
+
|
|
9
|
+
_LAZY_EXPORTS = {
|
|
10
|
+
"DNNRecipe": ("tributo_algorithms_tabular_torch.recipe", "DNNRecipe"),
|
|
11
|
+
"PURecipe": ("tributo_algorithms_tabular_torch.recipe", "PURecipe"),
|
|
12
|
+
"PUGlobalLossReducer": (
|
|
13
|
+
"tributo_algorithms_tabular_torch.pu_reducer",
|
|
14
|
+
"PUGlobalLossReducer",
|
|
15
|
+
),
|
|
16
|
+
"PURiskReducerPlan": (
|
|
17
|
+
"tributo_algorithms_tabular_torch.pu_reducer",
|
|
18
|
+
"PURiskReducerPlan",
|
|
19
|
+
),
|
|
20
|
+
"estimate_class_prior": (
|
|
21
|
+
"tributo_algorithms_tabular_torch.priors",
|
|
22
|
+
"estimate_class_prior",
|
|
23
|
+
),
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def __getattr__(name: str) -> Any:
|
|
28
|
+
target = _LAZY_EXPORTS.get(name)
|
|
29
|
+
if target is None:
|
|
30
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
31
|
+
import importlib
|
|
32
|
+
|
|
33
|
+
value = getattr(importlib.import_module(target[0]), target[1])
|
|
34
|
+
globals()[name] = value
|
|
35
|
+
return value
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"DNN_DESCRIPTOR",
|
|
40
|
+
"DNNRecipe",
|
|
41
|
+
"PU_DESCRIPTOR",
|
|
42
|
+
"PURecipe",
|
|
43
|
+
"PUGlobalLossReducer",
|
|
44
|
+
"PURiskReducerPlan",
|
|
45
|
+
"estimate_class_prior",
|
|
46
|
+
]
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""Versioned contracts for official tabular Torch algorithms."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import math
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _digest(name: str) -> str:
|
|
12
|
+
return hashlib.sha256(f"tributo.tabular-torch.{name}.v2".encode()).hexdigest()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class TabularTorchConfigValidator:
|
|
16
|
+
api_version = 1
|
|
17
|
+
schema_digest = "5" * 64
|
|
18
|
+
|
|
19
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
20
|
+
allowed = {"loss", "metrics", "model", "optimizer", "output", "ray", "training"}
|
|
21
|
+
if unknown := sorted(set(value) - allowed):
|
|
22
|
+
raise ValueError(f"unknown tabular-torch config keys: {unknown}")
|
|
23
|
+
normalized = dict(value)
|
|
24
|
+
for name in allowed:
|
|
25
|
+
item = normalized.get(name)
|
|
26
|
+
if item is not None and not isinstance(item, Mapping):
|
|
27
|
+
raise ValueError(f"{name} must be a mapping")
|
|
28
|
+
output = normalized.get("output")
|
|
29
|
+
if (
|
|
30
|
+
not isinstance(output, Mapping)
|
|
31
|
+
or not isinstance(output.get("bundle_uri"), str)
|
|
32
|
+
or not output["bundle_uri"]
|
|
33
|
+
):
|
|
34
|
+
raise ValueError("output.bundle_uri is required")
|
|
35
|
+
optimizer = normalized.get("optimizer", {})
|
|
36
|
+
if isinstance(optimizer, Mapping):
|
|
37
|
+
learning_rate = optimizer.get("learning_rate", 0.001)
|
|
38
|
+
accumulation = optimizer.get("accumulation_steps", 1)
|
|
39
|
+
if (
|
|
40
|
+
not isinstance(learning_rate, (int, float))
|
|
41
|
+
or isinstance(learning_rate, bool)
|
|
42
|
+
or not math.isfinite(float(learning_rate))
|
|
43
|
+
or float(learning_rate) <= 0
|
|
44
|
+
):
|
|
45
|
+
raise ValueError("optimizer.learning_rate must be positive and finite")
|
|
46
|
+
if (
|
|
47
|
+
not isinstance(accumulation, int)
|
|
48
|
+
or isinstance(accumulation, bool)
|
|
49
|
+
or accumulation < 1
|
|
50
|
+
):
|
|
51
|
+
raise ValueError("optimizer.accumulation_steps must be positive")
|
|
52
|
+
return normalized
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class PUConfigValidator(TabularTorchConfigValidator):
|
|
56
|
+
api_version = 1
|
|
57
|
+
schema_digest = "6" * 64
|
|
58
|
+
|
|
59
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
60
|
+
normalized = dict(super().validate(value))
|
|
61
|
+
loss = normalized.get("loss")
|
|
62
|
+
if not isinstance(loss, Mapping) or "class_prior" not in loss:
|
|
63
|
+
raise ValueError("PU loss.class_prior is required")
|
|
64
|
+
prior = loss["class_prior"]
|
|
65
|
+
if (
|
|
66
|
+
not isinstance(prior, (int, float))
|
|
67
|
+
or isinstance(prior, bool)
|
|
68
|
+
or not math.isfinite(float(prior))
|
|
69
|
+
or not 0 < float(prior) < 1
|
|
70
|
+
):
|
|
71
|
+
raise ValueError("PU loss.class_prior must be in (0, 1)")
|
|
72
|
+
if loss.get("type", "nnpu") not in {"nnpu", "upu"}:
|
|
73
|
+
raise ValueError("PU loss.type must be nnpu or upu")
|
|
74
|
+
beta = loss.get("beta", 0.0)
|
|
75
|
+
gamma = loss.get("gamma", 1.0)
|
|
76
|
+
if (
|
|
77
|
+
not isinstance(beta, (int, float))
|
|
78
|
+
or isinstance(beta, bool)
|
|
79
|
+
or not math.isfinite(float(beta))
|
|
80
|
+
or float(beta) < 0
|
|
81
|
+
):
|
|
82
|
+
raise ValueError("PU loss.beta must be finite and non-negative")
|
|
83
|
+
if (
|
|
84
|
+
not isinstance(gamma, (int, float))
|
|
85
|
+
or isinstance(gamma, bool)
|
|
86
|
+
or not math.isfinite(float(gamma))
|
|
87
|
+
or not 0 <= float(gamma) <= 1
|
|
88
|
+
):
|
|
89
|
+
raise ValueError("PU loss.gamma must be in [0, 1]")
|
|
90
|
+
training = normalized.get("training", {})
|
|
91
|
+
if isinstance(training, Mapping) and training.get("accumulation_steps", 1) != 1:
|
|
92
|
+
raise ValueError("PU requires gradient_accumulation_steps=1")
|
|
93
|
+
optimizer = normalized.get("optimizer", {})
|
|
94
|
+
if (
|
|
95
|
+
isinstance(optimizer, Mapping)
|
|
96
|
+
and optimizer.get("accumulation_steps", 1) != 1
|
|
97
|
+
):
|
|
98
|
+
raise ValueError("PU requires gradient_accumulation_steps=1")
|
|
99
|
+
return normalized
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class DNNTensorInputValidator:
|
|
103
|
+
api_version = 1
|
|
104
|
+
schema_digest = _digest("dnn-named-input-role-routed")
|
|
105
|
+
|
|
106
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
107
|
+
bindings = value.get("bindings")
|
|
108
|
+
if not isinstance(bindings, list) or not 1 <= len(bindings) <= 3:
|
|
109
|
+
raise ValueError(
|
|
110
|
+
"tabular-torch requires train and optional val/test bindings"
|
|
111
|
+
)
|
|
112
|
+
if any(not isinstance(binding, Mapping) for binding in bindings):
|
|
113
|
+
raise ValueError("tabular-torch bindings must be mappings")
|
|
114
|
+
names = [binding.get("name") for binding in bindings]
|
|
115
|
+
if any(not isinstance(name, str) for name in names):
|
|
116
|
+
raise ValueError("tabular-torch input roles must be named")
|
|
117
|
+
by_role = {str(binding["name"]): binding for binding in bindings}
|
|
118
|
+
if (
|
|
119
|
+
len(by_role) != len(bindings)
|
|
120
|
+
or "train" not in by_role
|
|
121
|
+
or not set(by_role).issubset({"train", "val", "test"})
|
|
122
|
+
or value.get("primary_role") != "train"
|
|
123
|
+
):
|
|
124
|
+
raise ValueError("tabular-torch input roles are invalid")
|
|
125
|
+
train = by_role["train"]
|
|
126
|
+
expected_features = train.get("feature_names")
|
|
127
|
+
expected_label = train.get("label_name")
|
|
128
|
+
for binding in by_role.values():
|
|
129
|
+
features = binding.get("feature_names")
|
|
130
|
+
if (
|
|
131
|
+
not isinstance(features, list)
|
|
132
|
+
or not features
|
|
133
|
+
or any(not isinstance(name, str) or not name for name in features)
|
|
134
|
+
or features != expected_features
|
|
135
|
+
):
|
|
136
|
+
raise ValueError(
|
|
137
|
+
"tabular-torch requires consistent named dense features"
|
|
138
|
+
)
|
|
139
|
+
if binding.get("label_name") != expected_label or not isinstance(
|
|
140
|
+
expected_label, str
|
|
141
|
+
):
|
|
142
|
+
raise ValueError("tabular-torch requires one consistent label")
|
|
143
|
+
if binding.get("sample_weight_name") is not None:
|
|
144
|
+
raise ValueError("tabular-torch does not support sample-weight binding")
|
|
145
|
+
return value
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class PUTensorInputValidator(DNNTensorInputValidator):
|
|
149
|
+
api_version = 1
|
|
150
|
+
schema_digest = _digest("pu-named-input-role-routed")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class DNNTorchBundleOutputValidator:
|
|
154
|
+
api_version = 1
|
|
155
|
+
schema_digest = _digest("dnn-onnx-output")
|
|
156
|
+
|
|
157
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
158
|
+
outputs = value.get("outputs")
|
|
159
|
+
if value.get("status") != "succeeded" or not isinstance(outputs, Mapping):
|
|
160
|
+
raise ValueError("tabular-torch execution failed")
|
|
161
|
+
if not isinstance(outputs.get("bundle_uri"), str) or not outputs["bundle_uri"]:
|
|
162
|
+
raise ValueError("tabular-torch output requires Bundle")
|
|
163
|
+
return value
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class DNNTorchCoverageValidator:
|
|
167
|
+
api_version = 1
|
|
168
|
+
schema_digest = _digest("dnn-coverage")
|
|
169
|
+
|
|
170
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
171
|
+
if (
|
|
172
|
+
value.get("input_complete") is not True
|
|
173
|
+
or value.get("distributed") is not True
|
|
174
|
+
):
|
|
175
|
+
raise ValueError("tabular-torch distributed coverage is incomplete")
|
|
176
|
+
return value
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class PUTorchBundleOutputValidator(DNNTorchBundleOutputValidator):
|
|
180
|
+
api_version = 1
|
|
181
|
+
schema_digest = _digest("pu-onnx-output")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class PUCoverageValidator(DNNTorchCoverageValidator):
|
|
185
|
+
api_version = 1
|
|
186
|
+
schema_digest = _digest("pu-coverage")
|
|
187
|
+
|
|
188
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
189
|
+
validated = super().validate(value)
|
|
190
|
+
workers = validated.get("workers")
|
|
191
|
+
if not isinstance(workers, list) or not workers:
|
|
192
|
+
raise ValueError("PU coverage requires worker evidence")
|
|
193
|
+
totals = {"positive": 0, "unlabeled": 0}
|
|
194
|
+
for worker in workers:
|
|
195
|
+
if not isinstance(worker, Mapping) or not isinstance(
|
|
196
|
+
worker.get("input_rows"), Mapping
|
|
197
|
+
):
|
|
198
|
+
raise ValueError("PU worker group coverage is missing")
|
|
199
|
+
rows = worker["input_rows"]
|
|
200
|
+
train_rows = rows.get("train")
|
|
201
|
+
group_total = 0
|
|
202
|
+
for group in totals:
|
|
203
|
+
count = rows.get(f"coverage.{group}")
|
|
204
|
+
if not isinstance(count, int) or isinstance(count, bool) or count < 0:
|
|
205
|
+
raise ValueError(f"PU {group} coverage is malformed")
|
|
206
|
+
totals[group] += count
|
|
207
|
+
group_total += count
|
|
208
|
+
if (
|
|
209
|
+
not isinstance(train_rows, int)
|
|
210
|
+
or isinstance(train_rows, bool)
|
|
211
|
+
or group_total != train_rows
|
|
212
|
+
):
|
|
213
|
+
raise ValueError("PU group coverage does not partition train rows")
|
|
214
|
+
if any(count <= 0 for count in totals.values()):
|
|
215
|
+
raise ValueError("PU execution did not cover both label groups")
|
|
216
|
+
return validated
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
__all__ = [
|
|
220
|
+
"DNNTensorInputValidator",
|
|
221
|
+
"DNNTorchBundleOutputValidator",
|
|
222
|
+
"DNNTorchCoverageValidator",
|
|
223
|
+
"PUTensorInputValidator",
|
|
224
|
+
"PUTorchBundleOutputValidator",
|
|
225
|
+
"PUConfigValidator",
|
|
226
|
+
"PUCoverageValidator",
|
|
227
|
+
"TabularTorchConfigValidator",
|
|
228
|
+
]
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""Descriptors for official dense DNN and PU TorchRecipe algorithms."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, cast
|
|
8
|
+
|
|
9
|
+
from tributo.algorithms import AlgorithmBuilder
|
|
10
|
+
from tributo.algorithms.api import (
|
|
11
|
+
ContractBinding,
|
|
12
|
+
ContractBindingSet,
|
|
13
|
+
EnvironmentSpec,
|
|
14
|
+
ExecutionMode,
|
|
15
|
+
ExecutionProfile,
|
|
16
|
+
MetricReduction,
|
|
17
|
+
QualifiedReference,
|
|
18
|
+
SingleStageTorchPlan,
|
|
19
|
+
TorchDatasetRoute,
|
|
20
|
+
TorchPolicy,
|
|
21
|
+
TorchStageSpec,
|
|
22
|
+
WorkerRange,
|
|
23
|
+
WorkerResources,
|
|
24
|
+
)
|
|
25
|
+
from tributo.training.algorithm_spec import (
|
|
26
|
+
AlgorithmSpec,
|
|
27
|
+
Capability,
|
|
28
|
+
DataLoadingMode,
|
|
29
|
+
ProblemType,
|
|
30
|
+
ResourceHints,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
from tributo_algorithms_tabular_torch.contracts import (
|
|
34
|
+
DNNTensorInputValidator,
|
|
35
|
+
DNNTorchBundleOutputValidator,
|
|
36
|
+
DNNTorchCoverageValidator,
|
|
37
|
+
PUConfigValidator,
|
|
38
|
+
PUCoverageValidator,
|
|
39
|
+
PUTensorInputValidator,
|
|
40
|
+
PUTorchBundleOutputValidator,
|
|
41
|
+
TabularTorchConfigValidator,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
_PACKAGE = "tributo-algorithms"
|
|
45
|
+
_VERSION = "0.1.0"
|
|
46
|
+
_ROOT = Path(__file__).resolve().parent
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _code_digest(filename: str) -> str:
|
|
50
|
+
return hashlib.sha256((_ROOT / filename).read_bytes()).hexdigest()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _binding(
|
|
54
|
+
contract_id: str, validator: type[Any], *, version: int | None = None
|
|
55
|
+
) -> ContractBinding:
|
|
56
|
+
return ContractBinding(
|
|
57
|
+
contract_id=contract_id,
|
|
58
|
+
schema_version=version or 2,
|
|
59
|
+
schema_digest=str(validator.schema_digest),
|
|
60
|
+
validator_ref=QualifiedReference.parse(
|
|
61
|
+
f"tributo_algorithms_tabular_torch.contracts:{validator.__name__}"
|
|
62
|
+
),
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _spec(name: str, *, pu: bool) -> AlgorithmSpec:
|
|
67
|
+
return AlgorithmSpec(
|
|
68
|
+
name=name,
|
|
69
|
+
trainer_cls=None,
|
|
70
|
+
version="1.0.0",
|
|
71
|
+
default_config={},
|
|
72
|
+
supported_tasks=("fit",),
|
|
73
|
+
operations=("fit",),
|
|
74
|
+
resource_hints=ResourceHints(gpu_required=False),
|
|
75
|
+
extras_group="identity",
|
|
76
|
+
problem_types=(
|
|
77
|
+
(ProblemType.PU_LEARNING,) if pu else (ProblemType.BINARY_CLASSIFICATION,)
|
|
78
|
+
),
|
|
79
|
+
data_loading=DataLoadingMode.CANONICAL_TRAINER,
|
|
80
|
+
learning_paradigm="positive_unlabeled" if pu else "supervised",
|
|
81
|
+
model_family="deep_neural_network",
|
|
82
|
+
data_modalities=("tabular",),
|
|
83
|
+
lifecycle_kind="bounded_training",
|
|
84
|
+
capabilities=(
|
|
85
|
+
Capability.TUNABLE,
|
|
86
|
+
Capability.EXPORTABLE,
|
|
87
|
+
Capability.DISTRIBUTED,
|
|
88
|
+
),
|
|
89
|
+
allowed_execution_modes=(ExecutionMode.RAY_TRAIN_TORCH.value,),
|
|
90
|
+
config_contract_ref=f"tributo.algorithm-config.{name}.v1",
|
|
91
|
+
input_contract_ref=(
|
|
92
|
+
"tributo.official.pu.named-tensor.v2"
|
|
93
|
+
if pu
|
|
94
|
+
else "tributo.official.dnn.named-tensor.v2"
|
|
95
|
+
),
|
|
96
|
+
output_contract_ref=(f"tributo.official.{name}.onnx-bundle.v2"),
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _policy(*, pu: bool) -> TorchPolicy:
|
|
101
|
+
routes = (
|
|
102
|
+
TorchDatasetRoute("train", "split_exact", True, 1, 1, "reject"),
|
|
103
|
+
TorchDatasetRoute("val", "split_exact", False, 1, 0, "zero_contribution"),
|
|
104
|
+
TorchDatasetRoute("test", "split_exact", False, 1, 0, "zero_contribution"),
|
|
105
|
+
)
|
|
106
|
+
metrics = (
|
|
107
|
+
{"observed_positive_recall": MetricReduction.SUM_COUNT}
|
|
108
|
+
if pu
|
|
109
|
+
else {"accuracy": MetricReduction.SUM_COUNT}
|
|
110
|
+
)
|
|
111
|
+
metrics["train_loss"] = MetricReduction.SUM_COUNT
|
|
112
|
+
policy_kwargs: dict[str, object] = {
|
|
113
|
+
"torch_runtime_api_version": 1,
|
|
114
|
+
"loop_owner": "core_recipe",
|
|
115
|
+
"parallelism_id": "torch.ddp.replicated",
|
|
116
|
+
"dataset_routing": routes,
|
|
117
|
+
"execution_plan": SingleStageTorchPlan(
|
|
118
|
+
stage=TorchStageSpec(
|
|
119
|
+
"train",
|
|
120
|
+
("train", "val", "test"),
|
|
121
|
+
)
|
|
122
|
+
),
|
|
123
|
+
"state_layout": "replicated",
|
|
124
|
+
"metric_reducers": metrics,
|
|
125
|
+
"backend": "auto",
|
|
126
|
+
}
|
|
127
|
+
if pu:
|
|
128
|
+
policy_kwargs.update(
|
|
129
|
+
{
|
|
130
|
+
"global_loss_reducer_ref": "tributo_algorithms_tabular_torch.pu_reducer:PUGlobalLossReducer",
|
|
131
|
+
"global_loss_reducer_api_version": 1,
|
|
132
|
+
"global_loss_reducer_code_digest": _code_digest("pu_reducer.py"),
|
|
133
|
+
"composite_loss_schema_id": "tributo.official.tabular_torch.pu-risk-components.v1",
|
|
134
|
+
}
|
|
135
|
+
)
|
|
136
|
+
return cast(TorchPolicy, cast(Any, TorchPolicy)(**policy_kwargs))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _contracts(*, pu: bool) -> ContractBindingSet:
|
|
140
|
+
if pu:
|
|
141
|
+
return ContractBindingSet(
|
|
142
|
+
config=_binding(
|
|
143
|
+
"tributo.algorithm-config.pu.v1", PUConfigValidator, version=1
|
|
144
|
+
),
|
|
145
|
+
input=_binding(
|
|
146
|
+
"tributo.official.pu.named-tensor.v2", PUTensorInputValidator
|
|
147
|
+
),
|
|
148
|
+
output=_binding(
|
|
149
|
+
"tributo.official.pu.onnx-bundle.v2", PUTorchBundleOutputValidator
|
|
150
|
+
),
|
|
151
|
+
coverage=_binding(
|
|
152
|
+
"tributo.official.pu.torch-coverage.v2", PUCoverageValidator
|
|
153
|
+
),
|
|
154
|
+
)
|
|
155
|
+
return ContractBindingSet(
|
|
156
|
+
config=_binding(
|
|
157
|
+
"tributo.algorithm-config.dnn.v1", TabularTorchConfigValidator, version=1
|
|
158
|
+
),
|
|
159
|
+
input=_binding("tributo.official.dnn.named-tensor.v2", DNNTensorInputValidator),
|
|
160
|
+
output=_binding(
|
|
161
|
+
"tributo.official.dnn.onnx-bundle.v2", DNNTorchBundleOutputValidator
|
|
162
|
+
),
|
|
163
|
+
coverage=_binding(
|
|
164
|
+
"tributo.official.dnn.torch-coverage.v2", DNNTorchCoverageValidator
|
|
165
|
+
),
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
_ENVIRONMENT = EnvironmentSpec(
|
|
170
|
+
environment_id="tributo.official.tabular-torch.v2",
|
|
171
|
+
dependencies=(
|
|
172
|
+
"onnx>=1.16",
|
|
173
|
+
"onnxruntime>=1.20",
|
|
174
|
+
"torch>=2.5",
|
|
175
|
+
"tributo>=1.1",
|
|
176
|
+
f"tributo-algorithms[tabular-torch]=={_VERSION}",
|
|
177
|
+
),
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
_DNN_SPEC = _spec("dnn", pu=False)
|
|
181
|
+
_PU_SPEC = _spec("pu", pu=True)
|
|
182
|
+
|
|
183
|
+
DNN_DESCRIPTOR = AlgorithmBuilder.from_torch(
|
|
184
|
+
spec=_DNN_SPEC,
|
|
185
|
+
implementation_id="tributo.official.tabular_torch.dnn",
|
|
186
|
+
implementation_version="2.0.0",
|
|
187
|
+
recipe="tributo_algorithms_tabular_torch.recipe:DNNRecipe",
|
|
188
|
+
environment=_ENVIRONMENT,
|
|
189
|
+
metric_reducers={"accuracy": MetricReduction.SUM_COUNT},
|
|
190
|
+
supported_worker_range=WorkerRange(1, 64),
|
|
191
|
+
supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
|
|
192
|
+
resources_per_worker=WorkerResources(num_cpus=1),
|
|
193
|
+
package_name=_PACKAGE,
|
|
194
|
+
package_version=_VERSION,
|
|
195
|
+
tributo_version_spec=">=1.1",
|
|
196
|
+
policy=_policy(pu=False),
|
|
197
|
+
code_digest=_code_digest("recipe.py"),
|
|
198
|
+
contract_bindings=_contracts(pu=False),
|
|
199
|
+
descriptor_api_version=2,
|
|
200
|
+
is_default=True,
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
PU_DESCRIPTOR = AlgorithmBuilder.from_torch(
|
|
204
|
+
spec=_PU_SPEC,
|
|
205
|
+
implementation_id="tributo.official.tabular_torch.pu",
|
|
206
|
+
implementation_version="2.0.0",
|
|
207
|
+
recipe="tributo_algorithms_tabular_torch.recipe:PURecipe",
|
|
208
|
+
environment=_ENVIRONMENT,
|
|
209
|
+
metric_reducers={"observed_positive_recall": MetricReduction.SUM_COUNT},
|
|
210
|
+
supported_worker_range=WorkerRange(1, 64),
|
|
211
|
+
supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
|
|
212
|
+
resources_per_worker=WorkerResources(num_cpus=1),
|
|
213
|
+
package_name=_PACKAGE,
|
|
214
|
+
package_version=_VERSION,
|
|
215
|
+
tributo_version_spec=">=1.1",
|
|
216
|
+
policy=_policy(pu=True),
|
|
217
|
+
code_digest=_code_digest("recipe.py"),
|
|
218
|
+
contract_bindings=_contracts(pu=True),
|
|
219
|
+
descriptor_api_version=2,
|
|
220
|
+
is_default=True,
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
__all__ = ["DNN_DESCRIPTOR", "PU_DESCRIPTOR"]
|