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,294 @@
1
+ """Typed TorchRecipe implementations for dense DNN and PU learning."""
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
+ TorchCompositeLossContribution,
10
+ TorchLossContribution,
11
+ TorchMetricContribution,
12
+ )
13
+ from tributo.algorithms.spi import (
14
+ TorchArtifactContext,
15
+ TorchArtifactPlan,
16
+ TorchBatch,
17
+ TorchBatchContext,
18
+ TorchBuildContext,
19
+ TorchMetricPlan,
20
+ TorchModuleSet,
21
+ TorchOptimizationPlan,
22
+ TorchRecipe,
23
+ TorchRuntimeContext,
24
+ TorchStepContext,
25
+ TorchStepResult,
26
+ )
27
+
28
+
29
+ def _config(context: TorchRuntimeContext | TorchBuildContext) -> Mapping[str, Any]:
30
+ runtime = context if isinstance(context, TorchRuntimeContext) else context.runtime
31
+ return cast(Mapping[str, Any], runtime.algorithm_config)
32
+
33
+
34
+ def _feature_and_label_names(
35
+ batch: Mapping[str, object], context: TorchBatchContext
36
+ ) -> tuple[tuple[str, ...], str]:
37
+ label_name = context.label_name or ("label" if "label" in batch else None)
38
+ if label_name is None:
39
+ raise ValueError("tabular-torch training requires a label")
40
+ feature_names = context.feature_names or tuple(
41
+ name for name in batch if name not in {label_name, context.weight_name}
42
+ )
43
+ if not feature_names:
44
+ raise ValueError("tabular-torch requires at least one feature")
45
+ return tuple(feature_names), label_name
46
+
47
+
48
+ def _dense_batch(batch: object, context: TorchBatchContext) -> TorchBatch:
49
+ import torch
50
+
51
+ if not isinstance(batch, Mapping):
52
+ raise ValueError("tabular-torch batch must be columnar")
53
+ feature_names, label_name = _feature_and_label_names(batch, context)
54
+ if context.weight_name is not None:
55
+ raise ValueError("tabular-torch does not support sample-weight binding")
56
+ try:
57
+ features = torch.stack(
58
+ [
59
+ torch.as_tensor(batch[name], dtype=torch.float32)
60
+ for name in feature_names
61
+ ],
62
+ dim=1,
63
+ )
64
+ labels = torch.as_tensor(batch[label_name], dtype=torch.float32).reshape(-1, 1)
65
+ except (KeyError, TypeError, ValueError) as exc:
66
+ raise ValueError("tabular-torch batch columns are malformed") from exc
67
+ if not torch.isfinite(features).all() or not torch.isfinite(labels).all():
68
+ raise ValueError("tabular-torch features and labels must be finite")
69
+ if not bool(((labels == 0) | (labels == 1)).all()):
70
+ raise ValueError("tabular-torch labels must be 0 or 1")
71
+ rows = int(features.shape[0])
72
+ return TorchBatch(
73
+ keyword={"features": features},
74
+ targets=labels,
75
+ local_rows=rows,
76
+ )
77
+
78
+
79
+ def _binary_metric(predictions: object, targets: object) -> TorchMetricContribution:
80
+ import torch
81
+
82
+ logits = cast(torch.Tensor, predictions).reshape(-1)
83
+ labels = cast(torch.Tensor, targets).reshape(-1)
84
+ correct = (torch.sigmoid(logits) >= 0.5).eq(labels >= 0.5)
85
+ return TorchMetricContribution(float(correct.sum().item()), int(labels.numel()))
86
+
87
+
88
+ def _model(config: Mapping[str, Any]) -> object:
89
+ import torch
90
+
91
+ input_features = int(config.get("input_features", 4))
92
+ hidden_units = tuple(int(value) for value in config.get("hidden_units", (16, 8)))
93
+ if (
94
+ input_features < 1
95
+ or not hidden_units
96
+ or any(value < 1 for value in hidden_units)
97
+ ):
98
+ raise ValueError("DNN dimensions must be positive")
99
+ layers: list[torch.nn.Module] = []
100
+ current = input_features
101
+ for width in hidden_units:
102
+ layers.extend((torch.nn.Linear(current, width), torch.nn.ReLU()))
103
+ current = width
104
+ layers.append(torch.nn.Linear(current, 1))
105
+ return torch.nn.Sequential(*layers)
106
+
107
+
108
+ class _BaseDenseRecipe(TorchRecipe):
109
+ """Shared typed hooks for dense binary classifiers."""
110
+
111
+ def adapt_batch(self, batch: object, context: TorchBatchContext) -> TorchBatch:
112
+ return _dense_batch(batch, context)
113
+
114
+ def configure_optimizers(
115
+ self, modules: TorchModuleSet, context: TorchBuildContext
116
+ ) -> TorchOptimizationPlan:
117
+ import torch
118
+
119
+ config = _config(context)
120
+ optimizer_config = config.get("optimizer", {})
121
+ if not isinstance(optimizer_config, Mapping):
122
+ raise ValueError("optimizer config must be a mapping")
123
+ model = cast(torch.nn.Module, modules["model"])
124
+ return TorchOptimizationPlan(
125
+ optimizer=torch.optim.Adam(
126
+ model.parameters(),
127
+ lr=float(optimizer_config.get("learning_rate", 0.001)),
128
+ weight_decay=float(optimizer_config.get("weight_decay", 0.0)),
129
+ ),
130
+ gradient_accumulation_steps=optimizer_config.get("accumulation_steps", 1),
131
+ max_gradient_norm=optimizer_config.get("max_gradient_norm", 1.0),
132
+ )
133
+
134
+ def artifact_plan(self, context: TorchArtifactContext) -> TorchArtifactPlan:
135
+ config = _config(context.stage.runtime)
136
+ model_config = config.get("model", {})
137
+ input_features = (
138
+ int(model_config.get("input_features", 4))
139
+ if isinstance(model_config, Mapping)
140
+ else 4
141
+ )
142
+ return TorchArtifactPlan(
143
+ source_kind="torch_module",
144
+ input_signature=(
145
+ {
146
+ "name": "features",
147
+ "dtype": "float32",
148
+ "shape": ("batch", input_features),
149
+ },
150
+ ),
151
+ output_signature=(
152
+ {"name": "output", "dtype": "float32", "shape": ("batch", 1)},
153
+ ),
154
+ targets=(
155
+ {
156
+ "name": "onnx-model",
157
+ "format": "onnx",
158
+ "exporter_id": "torch-onnx-v1",
159
+ "options": {"dynamo": False},
160
+ },
161
+ ),
162
+ roles={"inference": "onnx-model"},
163
+ )
164
+
165
+
166
+ class DNNRecipe(_BaseDenseRecipe):
167
+ """Binary dense DNN classification."""
168
+
169
+ def build_modules(self, context: TorchBuildContext) -> TorchModuleSet:
170
+ import torch
171
+
172
+ config = _config(context)
173
+ model_config = config.get("model", {})
174
+ if not isinstance(model_config, Mapping):
175
+ raise ValueError("model config must be a mapping")
176
+ return TorchModuleSet(
177
+ {"model": _model(model_config), "loss": torch.nn.Identity()}
178
+ )
179
+
180
+ def training_step(
181
+ self, modules: TorchModuleSet, batch: TorchBatch, context: TorchStepContext
182
+ ) -> TorchStepResult:
183
+ del context
184
+ import torch
185
+
186
+ model = cast(torch.nn.Module, modules["model"])
187
+ predictions = model(batch.keyword["features"])
188
+ targets = cast(torch.Tensor, batch.targets)
189
+ numerator = torch.nn.functional.binary_cross_entropy_with_logits(
190
+ predictions, targets, reduction="sum"
191
+ )
192
+ return TorchStepResult(
193
+ outputs={"output": predictions},
194
+ loss=TorchLossContribution(numerator, batch.local_rows),
195
+ metrics={"accuracy": _binary_metric(predictions, targets)},
196
+ )
197
+
198
+ def validation_step(
199
+ self, modules: TorchModuleSet, batch: TorchBatch, context: TorchStepContext
200
+ ) -> TorchStepResult:
201
+ return self.training_step(modules, batch, context)
202
+
203
+ def metric_plan(self, context: TorchRuntimeContext) -> TorchMetricPlan:
204
+ del context
205
+ return TorchMetricPlan({"accuracy": "sum_count", "train_loss": "sum_count"})
206
+
207
+
208
+ class PURecipe(_BaseDenseRecipe):
209
+ """Positive-unlabeled classifier using the Wheel-owned global reducer."""
210
+
211
+ component_schema_id = "tributo.official.tabular_torch.pu-risk-components.v1"
212
+
213
+ def build_modules(self, context: TorchBuildContext) -> TorchModuleSet:
214
+ import torch
215
+
216
+ config = _config(context)
217
+ model_config = config.get("model", {})
218
+ if not isinstance(model_config, Mapping):
219
+ raise ValueError("model config must be a mapping")
220
+ return TorchModuleSet(
221
+ {"model": _model(model_config), "loss": torch.nn.Identity()}
222
+ )
223
+
224
+ def configure_optimizers(
225
+ self, modules: TorchModuleSet, context: TorchBuildContext
226
+ ) -> TorchOptimizationPlan:
227
+ plan = super().configure_optimizers(modules, context)
228
+ if plan.gradient_accumulation_steps != 1:
229
+ raise ValueError("PU requires gradient_accumulation_steps=1")
230
+ return plan
231
+
232
+ def training_step(
233
+ self, modules: TorchModuleSet, batch: TorchBatch, context: TorchStepContext
234
+ ) -> TorchStepResult:
235
+ del context
236
+ import torch
237
+
238
+ model = cast(torch.nn.Module, modules["model"])
239
+ predictions = model(batch.keyword["features"]).reshape(-1)
240
+ labels = cast(torch.Tensor, batch.targets).reshape(-1)
241
+ positive = labels == 1
242
+ unlabeled = labels == 0
243
+ positive_loss = torch.nn.functional.softplus(-predictions[positive]).sum()
244
+ positive_as_negative = torch.nn.functional.softplus(predictions[positive]).sum()
245
+ unlabeled_negative = torch.nn.functional.softplus(predictions[unlabeled]).sum()
246
+ positive_count = int(positive.sum().item())
247
+ unlabeled_count = int(unlabeled.sum().item())
248
+ metrics = {
249
+ "observed_positive_recall": TorchMetricContribution(
250
+ float((torch.sigmoid(predictions[positive]) >= 0.5).sum().item()),
251
+ positive_count,
252
+ )
253
+ }
254
+ return TorchStepResult(
255
+ outputs={"output": predictions.reshape(-1, 1)},
256
+ loss=TorchCompositeLossContribution(
257
+ self.component_schema_id,
258
+ {
259
+ "positive_loss_sum": positive_loss,
260
+ "positive_as_negative_sum": positive_as_negative,
261
+ "unlabeled_negative_sum": unlabeled_negative,
262
+ },
263
+ {
264
+ "positive_count": positive_count,
265
+ "unlabeled_count": unlabeled_count,
266
+ },
267
+ evidence={
268
+ "positive_count": positive_count,
269
+ "unlabeled_count": unlabeled_count,
270
+ },
271
+ ),
272
+ coverage_counts={
273
+ "coverage.positive": positive_count,
274
+ "coverage.unlabeled": unlabeled_count,
275
+ },
276
+ metrics=metrics,
277
+ )
278
+
279
+ def validation_step(
280
+ self, modules: TorchModuleSet, batch: TorchBatch, context: TorchStepContext
281
+ ) -> TorchStepResult:
282
+ return self.training_step(modules, batch, context)
283
+
284
+ def metric_plan(self, context: TorchRuntimeContext) -> TorchMetricPlan:
285
+ del context
286
+ return TorchMetricPlan(
287
+ {
288
+ "observed_positive_recall": "sum_count",
289
+ "train_loss": "sum_count",
290
+ }
291
+ )
292
+
293
+
294
+ __all__ = ["DNNRecipe", "PURecipe"]
@@ -0,0 +1,36 @@
1
+ """Official distributed time-series algorithms with lazy runtime exports."""
2
+
3
+ from typing import Any
4
+
5
+ from tributo_algorithms_timeseries.descriptor import TEMPORAL_CONV_DESCRIPTOR
6
+ from tributo_algorithms_timeseries.rnn_descriptor import GRU_DESCRIPTOR, LSTM_DESCRIPTOR
7
+
8
+ _LAZY_EXPORTS = {
9
+ "TemporalConvRecipe": (
10
+ "tributo_algorithms_timeseries.recipe",
11
+ "TemporalConvRecipe",
12
+ ),
13
+ "LSTMRecipe": ("tributo_algorithms_timeseries.rnn_recipe", "LSTMRecipe"),
14
+ "GRURecipe": ("tributo_algorithms_timeseries.rnn_recipe", "GRURecipe"),
15
+ }
16
+
17
+
18
+ def __getattr__(name: str) -> Any:
19
+ target = _LAZY_EXPORTS.get(name)
20
+ if target is None:
21
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
22
+ import importlib
23
+
24
+ value = getattr(importlib.import_module(target[0]), target[1])
25
+ globals()[name] = value
26
+ return value
27
+
28
+
29
+ __all__ = [
30
+ "GRU_DESCRIPTOR",
31
+ "GRURecipe",
32
+ "LSTM_DESCRIPTOR",
33
+ "LSTMRecipe",
34
+ "TEMPORAL_CONV_DESCRIPTOR",
35
+ "TemporalConvRecipe",
36
+ ]
@@ -0,0 +1,120 @@
1
+ """Versioned contracts for the temporal convolution TorchRecipe."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from collections.abc import Mapping
7
+ from typing import Any
8
+
9
+
10
+ def _digest(name: str) -> str:
11
+ return hashlib.sha256(f"tributo.timeseries.{name}.v2".encode()).hexdigest()
12
+
13
+
14
+ class TimeSeriesConfigValidator:
15
+ api_version = 1
16
+ schema_digest = "5" * 64
17
+
18
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
19
+ allowed = {"metrics", "model", "optimizer", "output", "ray", "training"}
20
+ if unknown := sorted(set(value) - allowed):
21
+ raise ValueError(f"unknown time-series config keys: {unknown}")
22
+ for name in allowed:
23
+ item = value.get(name)
24
+ if item is not None and not isinstance(item, Mapping):
25
+ raise ValueError(f"{name} must be a mapping")
26
+ output = value.get("output")
27
+ if not isinstance(output, Mapping) or not isinstance(
28
+ output.get("bundle_uri"), str
29
+ ):
30
+ raise ValueError("output.bundle_uri is required")
31
+ return dict(value)
32
+
33
+
34
+ class WindowInputValidator:
35
+ api_version = 1
36
+ schema_digest = "6" * 64
37
+
38
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
39
+ bindings = value.get("bindings")
40
+ if not isinstance(bindings, list) or not 1 <= len(bindings) <= 3:
41
+ raise ValueError("time-series input requires train and optional val/test")
42
+ if any(not isinstance(binding, Mapping) for binding in bindings):
43
+ raise ValueError("time-series bindings must be mappings")
44
+ names = [binding.get("name") for binding in bindings]
45
+ if any(not isinstance(name, str) for name in names):
46
+ raise ValueError("time-series input roles must be named")
47
+ by_role = {str(binding["name"]): binding for binding in bindings}
48
+ if (
49
+ len(by_role) != len(bindings)
50
+ or "train" not in by_role
51
+ or not set(by_role).issubset({"train", "val", "test"})
52
+ or value.get("primary_role") != "train"
53
+ ):
54
+ raise ValueError("time-series input roles are invalid")
55
+ train = by_role["train"]
56
+ expected_features = train.get("feature_names")
57
+ expected_label = train.get("label_name")
58
+ for binding in by_role.values():
59
+ features = binding.get("feature_names")
60
+ if (
61
+ not isinstance(features, list)
62
+ or len(features) < 2
63
+ or features != expected_features
64
+ ):
65
+ raise ValueError("time-series input requires consistent ordered lags")
66
+ if binding.get("label_name") != expected_label or not isinstance(
67
+ expected_label, str
68
+ ):
69
+ raise ValueError("time-series input requires a consistent label")
70
+ if binding.get("sample_weight_name") is not None:
71
+ raise ValueError(
72
+ "time-series algorithms do not support sample-weight binding"
73
+ )
74
+ return value
75
+
76
+
77
+ class TimeSeriesOutputValidator:
78
+ api_version = 1
79
+ schema_digest = "7" * 64
80
+
81
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
82
+ outputs = value.get("outputs")
83
+ if value.get("status") != "succeeded" or not isinstance(outputs, Mapping):
84
+ raise ValueError("time-series execution failed")
85
+ if not isinstance(outputs.get("bundle_uri"), str) or not outputs["bundle_uri"]:
86
+ raise ValueError("time-series output requires a Bundle")
87
+ return value
88
+
89
+
90
+ class WindowCoverageValidator:
91
+ api_version = 1
92
+ schema_digest = "8" * 64
93
+
94
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
95
+ if (
96
+ value.get("input_complete") is not True
97
+ or value.get("distributed") is not True
98
+ ):
99
+ raise ValueError("time-series window coverage is incomplete")
100
+ return value
101
+
102
+
103
+ class TemporalConvTensorInputValidator(WindowInputValidator):
104
+ api_version = 1
105
+ schema_digest = _digest("tcn-window-input-role-routed")
106
+
107
+
108
+ class TemporalConvTorchCoverageValidator(WindowCoverageValidator):
109
+ api_version = 1
110
+ schema_digest = _digest("tcn-coverage")
111
+
112
+
113
+ __all__ = [
114
+ "TimeSeriesConfigValidator",
115
+ "TemporalConvTensorInputValidator",
116
+ "TemporalConvTorchCoverageValidator",
117
+ "TimeSeriesOutputValidator",
118
+ "WindowCoverageValidator",
119
+ "WindowInputValidator",
120
+ ]
@@ -0,0 +1,137 @@
1
+ """Descriptor for the official temporal convolution TorchRecipe."""
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.contracts import (
28
+ TemporalConvTensorInputValidator,
29
+ TemporalConvTorchCoverageValidator,
30
+ TimeSeriesConfigValidator,
31
+ TimeSeriesOutputValidator,
32
+ )
33
+
34
+ _PACKAGE = "tributo-algorithms"
35
+ _VERSION = "0.1.0"
36
+ _ROOT = Path(__file__).resolve().parent
37
+
38
+
39
+ def _code_digest(filename: str) -> str:
40
+ return hashlib.sha256((_ROOT / filename).read_bytes()).hexdigest()
41
+
42
+
43
+ def _binding(
44
+ contract_id: str, validator: type[Any], version: int = 2
45
+ ) -> ContractBinding:
46
+ return ContractBinding(
47
+ contract_id=contract_id,
48
+ schema_version=version,
49
+ schema_digest=str(validator.schema_digest),
50
+ validator_ref=QualifiedReference.parse(
51
+ f"tributo_algorithms_timeseries.contracts:{validator.__name__}"
52
+ ),
53
+ )
54
+
55
+
56
+ _SPEC = AlgorithmSpec(
57
+ name="temporal_conv_classifier",
58
+ trainer_cls=None,
59
+ version="1.0.0",
60
+ default_config={},
61
+ supported_tasks=("fit",),
62
+ operations=("fit",),
63
+ problem_types=(ProblemType.BINARY_CLASSIFICATION,),
64
+ capabilities=(Capability.DISTRIBUTED, Capability.EXPORTABLE, Capability.TUNABLE),
65
+ learning_paradigm="supervised",
66
+ model_family="temporal_convolution",
67
+ data_modalities=("time_series",),
68
+ lifecycle_kind="batch_fit",
69
+ allowed_execution_modes=(ExecutionMode.RAY_TRAIN_TORCH.value,),
70
+ config_contract_ref="tributo.official.timeseries.tcn.config.v1",
71
+ input_contract_ref="tributo.official.timeseries.tcn.window-tensor.v2",
72
+ output_contract_ref="tributo.official.timeseries.tcn.onnx.v1",
73
+ )
74
+
75
+ _POLICY = TorchPolicy(
76
+ torch_runtime_api_version=1,
77
+ loop_owner="core_recipe",
78
+ parallelism_id="torch.ddp.replicated",
79
+ dataset_routing=(
80
+ TorchDatasetRoute("train", "split_exact", True, 1, 1, "reject"),
81
+ TorchDatasetRoute("val", "split_exact", False, 1, 0, "zero_contribution"),
82
+ TorchDatasetRoute("test", "split_exact", False, 1, 0, "zero_contribution"),
83
+ ),
84
+ execution_plan=SingleStageTorchPlan(
85
+ stage=TorchStageSpec(
86
+ "train",
87
+ ("train", "val", "test"),
88
+ )
89
+ ),
90
+ state_layout="replicated",
91
+ metric_reducers={
92
+ "accuracy": MetricReduction.SUM_COUNT,
93
+ "train_loss": MetricReduction.SUM_COUNT,
94
+ },
95
+ backend="auto",
96
+ )
97
+
98
+ _CONTRACTS = ContractBindingSet(
99
+ config=_binding(_SPEC.config_contract_ref or "", TimeSeriesConfigValidator, 1),
100
+ input=_binding(_SPEC.input_contract_ref or "", TemporalConvTensorInputValidator),
101
+ output=_binding(_SPEC.output_contract_ref or "", TimeSeriesOutputValidator, 1),
102
+ coverage=_binding(
103
+ "tributo.official.timeseries.tcn.torch-coverage.v2",
104
+ TemporalConvTorchCoverageValidator,
105
+ ),
106
+ )
107
+
108
+ TEMPORAL_CONV_DESCRIPTOR = AlgorithmBuilder.from_torch(
109
+ spec=_SPEC,
110
+ implementation_id="tributo.official.timeseries.temporal_conv",
111
+ implementation_version="2.0.0",
112
+ recipe="tributo_algorithms_timeseries.recipe:TemporalConvRecipe",
113
+ environment=EnvironmentSpec(
114
+ environment_id="tributo.official.timeseries.v2",
115
+ dependencies=(
116
+ "onnx>=1.16",
117
+ "onnxruntime>=1.20",
118
+ "torch>=2.5",
119
+ "tributo>=1.1",
120
+ f"tributo-algorithms[timeseries]=={_VERSION}",
121
+ ),
122
+ ),
123
+ metric_reducers={"accuracy": MetricReduction.SUM_COUNT},
124
+ supported_worker_range=WorkerRange(1, 64),
125
+ supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
126
+ resources_per_worker=WorkerResources(num_cpus=1),
127
+ package_name=_PACKAGE,
128
+ package_version=_VERSION,
129
+ tributo_version_spec=">=1.1",
130
+ policy=_POLICY,
131
+ code_digest=_code_digest("recipe.py"),
132
+ contract_bindings=_CONTRACTS,
133
+ descriptor_api_version=2,
134
+ is_default=True,
135
+ )
136
+
137
+ __all__ = ["TEMPORAL_CONV_DESCRIPTOR"]