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,195 @@
|
|
|
1
|
+
"""Typed TorchRecipe implementation for the temporal convolution classifier."""
|
|
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 _config(context: TorchRuntimeContext | TorchBuildContext) -> Mapping[str, Any]:
|
|
29
|
+
runtime = context if isinstance(context, TorchRuntimeContext) else context.runtime
|
|
30
|
+
return cast(Mapping[str, Any], runtime.algorithm_config)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _window_batch(batch: object, context: TorchBatchContext) -> TorchBatch:
|
|
34
|
+
import torch
|
|
35
|
+
|
|
36
|
+
if not isinstance(batch, Mapping):
|
|
37
|
+
raise ValueError("time-series batch must be columnar")
|
|
38
|
+
feature_names = context.feature_names or tuple(
|
|
39
|
+
name for name in batch if name not in {context.label_name, context.weight_name}
|
|
40
|
+
)
|
|
41
|
+
label_name = context.label_name or ("label" if "label" in batch else None)
|
|
42
|
+
if not feature_names or label_name is None:
|
|
43
|
+
raise ValueError("time-series classifier requires ordered features and label")
|
|
44
|
+
if context.weight_name is not None:
|
|
45
|
+
raise ValueError("time-series algorithms do not support sample-weight binding")
|
|
46
|
+
windows = torch.stack(
|
|
47
|
+
[torch.as_tensor(batch[name], dtype=torch.float32) for name in feature_names],
|
|
48
|
+
dim=1,
|
|
49
|
+
)
|
|
50
|
+
targets = torch.as_tensor(batch[label_name], dtype=torch.float32).reshape(-1, 1)
|
|
51
|
+
if not torch.isfinite(windows).all() or not torch.isfinite(targets).all():
|
|
52
|
+
raise ValueError("time-series features and labels must be finite")
|
|
53
|
+
if not bool(((targets == 0) | (targets == 1)).all()):
|
|
54
|
+
raise ValueError("time-series labels must be 0 or 1")
|
|
55
|
+
rows = int(windows.shape[0])
|
|
56
|
+
return TorchBatch(
|
|
57
|
+
keyword={"window": windows},
|
|
58
|
+
targets=targets,
|
|
59
|
+
local_rows=rows,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _accuracy(predictions: object, targets: object) -> TorchMetricContribution:
|
|
64
|
+
import torch
|
|
65
|
+
|
|
66
|
+
logits = cast(torch.Tensor, predictions).reshape(-1)
|
|
67
|
+
labels = cast(torch.Tensor, targets).reshape(-1)
|
|
68
|
+
predicted = torch.sigmoid(logits) >= 0.5
|
|
69
|
+
return TorchMetricContribution(
|
|
70
|
+
float(predicted.eq(labels >= 0.5).sum().item()), int(labels.numel())
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _model(input_features: int, channels: int) -> object:
|
|
75
|
+
import torch
|
|
76
|
+
|
|
77
|
+
if input_features < 1 or channels < 1:
|
|
78
|
+
raise ValueError("TCN dimensions must be positive")
|
|
79
|
+
|
|
80
|
+
class TemporalConvClassifier(torch.nn.Module):
|
|
81
|
+
def __init__(self) -> None:
|
|
82
|
+
super().__init__()
|
|
83
|
+
self.input_features = input_features
|
|
84
|
+
self.network = torch.nn.Sequential(
|
|
85
|
+
torch.nn.Conv1d(1, channels, kernel_size=3, padding=1),
|
|
86
|
+
torch.nn.ReLU(),
|
|
87
|
+
torch.nn.AdaptiveAvgPool1d(1),
|
|
88
|
+
)
|
|
89
|
+
self.output = torch.nn.Linear(channels, 1)
|
|
90
|
+
|
|
91
|
+
def forward(self, values: object) -> object:
|
|
92
|
+
tensor = cast(torch.Tensor, values)
|
|
93
|
+
if tensor.ndim != 2 or tensor.shape[1] != input_features:
|
|
94
|
+
raise ValueError("TCN input must have shape [batch, window]")
|
|
95
|
+
encoded = self.network(tensor.unsqueeze(1)).squeeze(-1)
|
|
96
|
+
return self.output(encoded)
|
|
97
|
+
|
|
98
|
+
return TemporalConvClassifier()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class TemporalConvRecipe(TorchRecipe):
|
|
102
|
+
"""Train a finite-window temporal convolution classifier."""
|
|
103
|
+
|
|
104
|
+
def build_modules(self, context: TorchBuildContext) -> TorchModuleSet:
|
|
105
|
+
import torch
|
|
106
|
+
|
|
107
|
+
model_config = _config(context).get("model", {})
|
|
108
|
+
if not isinstance(model_config, Mapping):
|
|
109
|
+
raise ValueError("TCN model config must be a mapping")
|
|
110
|
+
return TorchModuleSet(
|
|
111
|
+
{
|
|
112
|
+
"model": _model(
|
|
113
|
+
int(model_config.get("input_features", 4)),
|
|
114
|
+
int(model_config.get("channels", 8)),
|
|
115
|
+
),
|
|
116
|
+
"loss": torch.nn.Identity(),
|
|
117
|
+
}
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
def adapt_batch(self, batch: object, context: TorchBatchContext) -> TorchBatch:
|
|
121
|
+
return _window_batch(batch, context)
|
|
122
|
+
|
|
123
|
+
def training_step(
|
|
124
|
+
self, modules: TorchModuleSet, batch: TorchBatch, context: TorchStepContext
|
|
125
|
+
) -> TorchStepResult:
|
|
126
|
+
del context
|
|
127
|
+
import torch
|
|
128
|
+
|
|
129
|
+
predictions = cast(torch.nn.Module, modules["model"])(batch.keyword["window"])
|
|
130
|
+
targets = cast(torch.Tensor, batch.targets)
|
|
131
|
+
numerator = torch.nn.functional.binary_cross_entropy_with_logits(
|
|
132
|
+
predictions, targets, reduction="sum"
|
|
133
|
+
)
|
|
134
|
+
return TorchStepResult(
|
|
135
|
+
outputs={"output": predictions},
|
|
136
|
+
loss=TorchLossContribution(numerator, batch.local_rows),
|
|
137
|
+
metrics={"accuracy": _accuracy(predictions, targets)},
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
def validation_step(
|
|
141
|
+
self, modules: TorchModuleSet, batch: TorchBatch, context: TorchStepContext
|
|
142
|
+
) -> TorchStepResult:
|
|
143
|
+
return self.training_step(modules, batch, context)
|
|
144
|
+
|
|
145
|
+
def configure_optimizers(
|
|
146
|
+
self, modules: TorchModuleSet, context: TorchBuildContext
|
|
147
|
+
) -> TorchOptimizationPlan:
|
|
148
|
+
import torch
|
|
149
|
+
|
|
150
|
+
optimizer_config = _config(context).get("optimizer", {})
|
|
151
|
+
if not isinstance(optimizer_config, Mapping):
|
|
152
|
+
raise ValueError("TCN optimizer config must be a mapping")
|
|
153
|
+
return TorchOptimizationPlan(
|
|
154
|
+
optimizer=torch.optim.Adam(
|
|
155
|
+
cast(torch.nn.Module, modules["model"]).parameters(),
|
|
156
|
+
lr=float(optimizer_config.get("learning_rate", 0.01)),
|
|
157
|
+
weight_decay=float(optimizer_config.get("weight_decay", 0.0)),
|
|
158
|
+
),
|
|
159
|
+
gradient_accumulation_steps=optimizer_config.get("accumulation_steps", 1),
|
|
160
|
+
max_gradient_norm=optimizer_config.get("max_gradient_norm", 1.0),
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
def metric_plan(self, context: TorchRuntimeContext) -> TorchMetricPlan:
|
|
164
|
+
del context
|
|
165
|
+
return TorchMetricPlan({"accuracy": "sum_count", "train_loss": "sum_count"})
|
|
166
|
+
|
|
167
|
+
def artifact_plan(self, context: TorchArtifactContext) -> TorchArtifactPlan:
|
|
168
|
+
config = context.stage.runtime.algorithm_config
|
|
169
|
+
model_config = config.get("model", {})
|
|
170
|
+
features = (
|
|
171
|
+
int(model_config.get("input_features", 4))
|
|
172
|
+
if isinstance(model_config, Mapping)
|
|
173
|
+
else 4
|
|
174
|
+
)
|
|
175
|
+
return TorchArtifactPlan(
|
|
176
|
+
source_kind="torch_module",
|
|
177
|
+
input_signature=(
|
|
178
|
+
{"name": "window", "dtype": "float32", "shape": ("batch", features)},
|
|
179
|
+
),
|
|
180
|
+
output_signature=(
|
|
181
|
+
{"name": "output", "dtype": "float32", "shape": ("batch", 1)},
|
|
182
|
+
),
|
|
183
|
+
targets=(
|
|
184
|
+
{
|
|
185
|
+
"name": "onnx-model",
|
|
186
|
+
"format": "onnx",
|
|
187
|
+
"exporter_id": "torch-onnx-v1",
|
|
188
|
+
"options": {"dynamo": False},
|
|
189
|
+
},
|
|
190
|
+
),
|
|
191
|
+
roles={"inference": "onnx-model"},
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
__all__ = ["TemporalConvRecipe"]
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Versioned contracts for fixed-window recurrent TorchRecipe 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.timeseries.rnn.{name}.v2".encode()).hexdigest()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class RNNConfigValidator:
|
|
16
|
+
api_version = 1
|
|
17
|
+
schema_digest = "9" * 64
|
|
18
|
+
|
|
19
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
20
|
+
allowed = {"metrics", "model", "optimizer", "output", "ray", "training"}
|
|
21
|
+
if unknown := sorted(set(value) - allowed):
|
|
22
|
+
raise ValueError(f"unknown RNN config keys: {unknown}")
|
|
23
|
+
for name in allowed:
|
|
24
|
+
item = value.get(name)
|
|
25
|
+
if item is not None and not isinstance(item, Mapping):
|
|
26
|
+
raise ValueError(f"{name} must be a mapping")
|
|
27
|
+
optimizer = value.get("optimizer", {})
|
|
28
|
+
if isinstance(optimizer, Mapping):
|
|
29
|
+
learning_rate = optimizer.get("learning_rate", 0.001)
|
|
30
|
+
weight_decay = optimizer.get("weight_decay", 0.0)
|
|
31
|
+
accumulation = optimizer.get("accumulation_steps", 1)
|
|
32
|
+
max_gradient_norm = optimizer.get("max_gradient_norm", 1.0)
|
|
33
|
+
if (
|
|
34
|
+
not isinstance(learning_rate, (int, float))
|
|
35
|
+
or isinstance(learning_rate, bool)
|
|
36
|
+
or not math.isfinite(float(learning_rate))
|
|
37
|
+
or float(learning_rate) <= 0
|
|
38
|
+
):
|
|
39
|
+
raise ValueError("optimizer.learning_rate must be positive and finite")
|
|
40
|
+
if (
|
|
41
|
+
not isinstance(accumulation, int)
|
|
42
|
+
or isinstance(accumulation, bool)
|
|
43
|
+
or accumulation < 1
|
|
44
|
+
):
|
|
45
|
+
raise ValueError("optimizer.accumulation_steps must be positive")
|
|
46
|
+
if (
|
|
47
|
+
not isinstance(weight_decay, (int, float))
|
|
48
|
+
or isinstance(weight_decay, bool)
|
|
49
|
+
or weight_decay < 0
|
|
50
|
+
):
|
|
51
|
+
raise ValueError("optimizer.weight_decay must be non-negative")
|
|
52
|
+
if (
|
|
53
|
+
not isinstance(max_gradient_norm, (int, float))
|
|
54
|
+
or isinstance(max_gradient_norm, bool)
|
|
55
|
+
or max_gradient_norm <= 0
|
|
56
|
+
):
|
|
57
|
+
raise ValueError("optimizer.max_gradient_norm must be positive")
|
|
58
|
+
model = value.get("model", {})
|
|
59
|
+
if isinstance(model, Mapping):
|
|
60
|
+
for name in ("input_features", "hidden_size", "num_layers"):
|
|
61
|
+
item = model.get(name)
|
|
62
|
+
if item is not None and (
|
|
63
|
+
not isinstance(item, int) or isinstance(item, bool) or item < 1
|
|
64
|
+
):
|
|
65
|
+
raise ValueError(f"model.{name} must be a positive integer")
|
|
66
|
+
output = value.get("output")
|
|
67
|
+
if not isinstance(output, Mapping) or not isinstance(
|
|
68
|
+
output.get("bundle_uri"), str
|
|
69
|
+
):
|
|
70
|
+
raise ValueError("output.bundle_uri is required")
|
|
71
|
+
return dict(value)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class FixedWindowInputValidator:
|
|
75
|
+
api_version = 1
|
|
76
|
+
schema_digest = "a" * 64
|
|
77
|
+
|
|
78
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
79
|
+
bindings = value.get("bindings")
|
|
80
|
+
if not isinstance(bindings, list) or not 1 <= len(bindings) <= 3:
|
|
81
|
+
raise ValueError("RNN input requires train and optional val/test bindings")
|
|
82
|
+
if any(not isinstance(binding, Mapping) for binding in bindings):
|
|
83
|
+
raise ValueError("RNN bindings must be mappings")
|
|
84
|
+
names = [binding.get("name") for binding in bindings]
|
|
85
|
+
if any(not isinstance(name, str) for name in names):
|
|
86
|
+
raise ValueError("RNN input roles must be named")
|
|
87
|
+
by_role = {str(binding["name"]): binding for binding in bindings}
|
|
88
|
+
if (
|
|
89
|
+
len(by_role) != len(bindings)
|
|
90
|
+
or "train" not in by_role
|
|
91
|
+
or not set(by_role).issubset({"train", "val", "test"})
|
|
92
|
+
or value.get("primary_role") != "train"
|
|
93
|
+
):
|
|
94
|
+
raise ValueError("RNN input roles are invalid")
|
|
95
|
+
train = by_role["train"]
|
|
96
|
+
expected_features = train.get("feature_names")
|
|
97
|
+
expected_label = train.get("label_name")
|
|
98
|
+
for binding in by_role.values():
|
|
99
|
+
features = binding.get("feature_names")
|
|
100
|
+
if (
|
|
101
|
+
not isinstance(features, list)
|
|
102
|
+
or len(features) < 2
|
|
103
|
+
or features != expected_features
|
|
104
|
+
):
|
|
105
|
+
raise ValueError("RNN input requires consistent ordered lags")
|
|
106
|
+
if binding.get("label_name") != expected_label or not isinstance(
|
|
107
|
+
expected_label, str
|
|
108
|
+
):
|
|
109
|
+
raise ValueError("RNN input requires a consistent label")
|
|
110
|
+
if binding.get("sample_weight_name") is not None:
|
|
111
|
+
raise ValueError("RNN algorithms do not support sample-weight binding")
|
|
112
|
+
return value
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class RNNOutputValidator:
|
|
116
|
+
api_version = 1
|
|
117
|
+
schema_digest = "b" * 64
|
|
118
|
+
|
|
119
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
120
|
+
outputs = value.get("outputs")
|
|
121
|
+
if value.get("status") != "succeeded" or not isinstance(outputs, Mapping):
|
|
122
|
+
raise ValueError("RNN execution failed")
|
|
123
|
+
if not isinstance(outputs.get("bundle_uri"), str) or not outputs["bundle_uri"]:
|
|
124
|
+
raise ValueError("RNN output requires a Bundle")
|
|
125
|
+
return value
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class RNNCoverageValidator:
|
|
129
|
+
api_version = 1
|
|
130
|
+
schema_digest = "c" * 64
|
|
131
|
+
|
|
132
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
133
|
+
if (
|
|
134
|
+
value.get("input_complete") is not True
|
|
135
|
+
or value.get("distributed") is not True
|
|
136
|
+
):
|
|
137
|
+
raise ValueError("RNN window coverage is incomplete")
|
|
138
|
+
return value
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class LSTMTensorInputValidator(FixedWindowInputValidator):
|
|
142
|
+
api_version = 1
|
|
143
|
+
schema_digest = _digest("lstm-window-input-role-routed")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class GRUTensorInputValidator(FixedWindowInputValidator):
|
|
147
|
+
api_version = 1
|
|
148
|
+
schema_digest = _digest("gru-window-input-role-routed")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class LSTMTorchCoverageValidator(RNNCoverageValidator):
|
|
152
|
+
api_version = 1
|
|
153
|
+
schema_digest = _digest("lstm-coverage")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class GRUTorchCoverageValidator(RNNCoverageValidator):
|
|
157
|
+
api_version = 1
|
|
158
|
+
schema_digest = _digest("gru-coverage")
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
__all__ = [
|
|
162
|
+
"FixedWindowInputValidator",
|
|
163
|
+
"GRUTensorInputValidator",
|
|
164
|
+
"GRUTorchCoverageValidator",
|
|
165
|
+
"LSTMTensorInputValidator",
|
|
166
|
+
"LSTMTorchCoverageValidator",
|
|
167
|
+
"RNNCoverageValidator",
|
|
168
|
+
"RNNConfigValidator",
|
|
169
|
+
"RNNOutputValidator",
|
|
170
|
+
]
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Descriptors for fixed-window LSTM and GRU TorchRecipe algorithms."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
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 AlgorithmSpec, Capability, ProblemType
|
|
26
|
+
|
|
27
|
+
from tributo_algorithms_timeseries.rnn_contracts import (
|
|
28
|
+
GRUTensorInputValidator,
|
|
29
|
+
GRUTorchCoverageValidator,
|
|
30
|
+
LSTMTensorInputValidator,
|
|
31
|
+
LSTMTorchCoverageValidator,
|
|
32
|
+
RNNConfigValidator,
|
|
33
|
+
RNNOutputValidator,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
_PACKAGE = "tributo-algorithms"
|
|
37
|
+
_VERSION = "0.1.0"
|
|
38
|
+
_ROOT = Path(__file__).resolve().parent
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _code_digest(filename: str) -> str:
|
|
42
|
+
return hashlib.sha256((_ROOT / filename).read_bytes()).hexdigest()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _binding(
|
|
46
|
+
contract_id: str, validator: type[Any], version: int = 2
|
|
47
|
+
) -> ContractBinding:
|
|
48
|
+
return ContractBinding(
|
|
49
|
+
contract_id=contract_id,
|
|
50
|
+
schema_version=version,
|
|
51
|
+
schema_digest=str(validator.schema_digest),
|
|
52
|
+
validator_ref=QualifiedReference.parse(
|
|
53
|
+
f"tributo_algorithms_timeseries.rnn_contracts:{validator.__name__}"
|
|
54
|
+
),
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _descriptor(
|
|
59
|
+
*,
|
|
60
|
+
name: str,
|
|
61
|
+
implementation_id: str,
|
|
62
|
+
recipe: str,
|
|
63
|
+
output_contract: str,
|
|
64
|
+
input_validator: type[object],
|
|
65
|
+
coverage_validator: type[object],
|
|
66
|
+
) -> object:
|
|
67
|
+
spec = AlgorithmSpec(
|
|
68
|
+
name=name,
|
|
69
|
+
trainer_cls=None,
|
|
70
|
+
version="1.0.0",
|
|
71
|
+
default_config={},
|
|
72
|
+
supported_tasks=("fit",),
|
|
73
|
+
operations=("fit",),
|
|
74
|
+
problem_types=(ProblemType.BINARY_CLASSIFICATION,),
|
|
75
|
+
capabilities=(
|
|
76
|
+
Capability.DISTRIBUTED,
|
|
77
|
+
Capability.EXPORTABLE,
|
|
78
|
+
Capability.TUNABLE,
|
|
79
|
+
),
|
|
80
|
+
learning_paradigm="supervised",
|
|
81
|
+
model_family="recurrent_neural_network",
|
|
82
|
+
data_modalities=("time_series",),
|
|
83
|
+
lifecycle_kind="batch_fit",
|
|
84
|
+
allowed_execution_modes=(ExecutionMode.RAY_TRAIN_TORCH.value,),
|
|
85
|
+
config_contract_ref=f"tributo.official.timeseries.{name}.config.v1",
|
|
86
|
+
input_contract_ref=f"tributo.official.timeseries.{name.removesuffix('_classifier')}.window-tensor.v2",
|
|
87
|
+
output_contract_ref=output_contract,
|
|
88
|
+
)
|
|
89
|
+
policy = TorchPolicy(
|
|
90
|
+
torch_runtime_api_version=1,
|
|
91
|
+
loop_owner="core_recipe",
|
|
92
|
+
parallelism_id="torch.ddp.replicated",
|
|
93
|
+
dataset_routing=(
|
|
94
|
+
TorchDatasetRoute("train", "split_exact", True, 1, 1, "reject"),
|
|
95
|
+
TorchDatasetRoute("val", "split_exact", False, 1, 0, "zero_contribution"),
|
|
96
|
+
TorchDatasetRoute("test", "split_exact", False, 1, 0, "zero_contribution"),
|
|
97
|
+
),
|
|
98
|
+
execution_plan=SingleStageTorchPlan(
|
|
99
|
+
stage=TorchStageSpec(
|
|
100
|
+
"train",
|
|
101
|
+
("train", "val", "test"),
|
|
102
|
+
)
|
|
103
|
+
),
|
|
104
|
+
state_layout="replicated",
|
|
105
|
+
metric_reducers={
|
|
106
|
+
"accuracy": MetricReduction.SUM_COUNT,
|
|
107
|
+
"train_loss": MetricReduction.SUM_COUNT,
|
|
108
|
+
},
|
|
109
|
+
backend="auto",
|
|
110
|
+
)
|
|
111
|
+
contracts = ContractBindingSet(
|
|
112
|
+
config=_binding(spec.config_contract_ref or "", RNNConfigValidator, 1),
|
|
113
|
+
input=_binding(spec.input_contract_ref or "", input_validator),
|
|
114
|
+
output=_binding(output_contract, RNNOutputValidator, 1),
|
|
115
|
+
coverage=_binding(
|
|
116
|
+
f"tributo.official.timeseries.{name}.torch-coverage.v2",
|
|
117
|
+
coverage_validator,
|
|
118
|
+
),
|
|
119
|
+
)
|
|
120
|
+
return AlgorithmBuilder.from_torch(
|
|
121
|
+
spec=spec,
|
|
122
|
+
implementation_id=implementation_id,
|
|
123
|
+
implementation_version="2.0.0",
|
|
124
|
+
recipe=recipe,
|
|
125
|
+
environment=EnvironmentSpec(
|
|
126
|
+
environment_id="tributo.official.timeseries.rnn.v2",
|
|
127
|
+
dependencies=(
|
|
128
|
+
"onnx>=1.16",
|
|
129
|
+
"onnxruntime>=1.20",
|
|
130
|
+
"torch>=2.5",
|
|
131
|
+
"tributo>=1.1",
|
|
132
|
+
f"tributo-algorithms[timeseries]=={_VERSION}",
|
|
133
|
+
),
|
|
134
|
+
),
|
|
135
|
+
metric_reducers={"accuracy": MetricReduction.SUM_COUNT},
|
|
136
|
+
supported_worker_range=WorkerRange(1, 64),
|
|
137
|
+
supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
|
|
138
|
+
resources_per_worker=WorkerResources(num_cpus=1),
|
|
139
|
+
package_name=_PACKAGE,
|
|
140
|
+
package_version=_VERSION,
|
|
141
|
+
tributo_version_spec=">=1.1",
|
|
142
|
+
policy=policy,
|
|
143
|
+
code_digest=_code_digest("rnn_recipe.py"),
|
|
144
|
+
contract_bindings=contracts,
|
|
145
|
+
descriptor_api_version=2,
|
|
146
|
+
is_default=True,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
LSTM_DESCRIPTOR = _descriptor(
|
|
151
|
+
name="lstm_classifier",
|
|
152
|
+
implementation_id="tributo.official.timeseries.lstm",
|
|
153
|
+
recipe="tributo_algorithms_timeseries.rnn_recipe:LSTMRecipe",
|
|
154
|
+
output_contract="tributo.official.timeseries.lstm.onnx.v1",
|
|
155
|
+
input_validator=LSTMTensorInputValidator,
|
|
156
|
+
coverage_validator=LSTMTorchCoverageValidator,
|
|
157
|
+
)
|
|
158
|
+
GRU_DESCRIPTOR = _descriptor(
|
|
159
|
+
name="gru_classifier",
|
|
160
|
+
implementation_id="tributo.official.timeseries.gru",
|
|
161
|
+
recipe="tributo_algorithms_timeseries.rnn_recipe:GRURecipe",
|
|
162
|
+
output_contract="tributo.official.timeseries.gru.onnx.v1",
|
|
163
|
+
input_validator=GRUTensorInputValidator,
|
|
164
|
+
coverage_validator=GRUTorchCoverageValidator,
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
__all__ = ["GRU_DESCRIPTOR", "LSTM_DESCRIPTOR"]
|