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,223 @@
|
|
|
1
|
+
"""Typed TorchRecipe implementations for fixed-window LSTM and GRU."""
|
|
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 _batch(batch: object, context: TorchBatchContext) -> TorchBatch:
|
|
34
|
+
import torch
|
|
35
|
+
|
|
36
|
+
if not isinstance(batch, Mapping):
|
|
37
|
+
raise ValueError("RNN batch must be columnar")
|
|
38
|
+
features = 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 len(features) < 2 or label_name is None:
|
|
43
|
+
raise ValueError("RNN requires a fixed window and label")
|
|
44
|
+
if context.weight_name is not None:
|
|
45
|
+
raise ValueError("RNN algorithms do not support sample-weight binding")
|
|
46
|
+
sequence = torch.stack(
|
|
47
|
+
[torch.as_tensor(batch[name], dtype=torch.float32) for name in features], dim=1
|
|
48
|
+
).unsqueeze(-1)
|
|
49
|
+
targets = torch.as_tensor(batch[label_name], dtype=torch.float32).reshape(-1, 1)
|
|
50
|
+
if not torch.isfinite(sequence).all() or not torch.isfinite(targets).all():
|
|
51
|
+
raise ValueError("RNN inputs must be finite")
|
|
52
|
+
if not bool(((targets == 0) | (targets == 1)).all()):
|
|
53
|
+
raise ValueError("RNN labels must be 0 or 1")
|
|
54
|
+
rows = int(sequence.shape[0])
|
|
55
|
+
return TorchBatch(
|
|
56
|
+
keyword={"window": sequence},
|
|
57
|
+
targets=targets,
|
|
58
|
+
local_rows=rows,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _accuracy(predictions: object, targets: object) -> TorchMetricContribution:
|
|
63
|
+
import torch
|
|
64
|
+
|
|
65
|
+
logits = cast(torch.Tensor, predictions).reshape(-1)
|
|
66
|
+
labels = cast(torch.Tensor, targets).reshape(-1)
|
|
67
|
+
return TorchMetricContribution(
|
|
68
|
+
float((torch.sigmoid(logits) >= 0.5).eq(labels >= 0.5).sum().item()),
|
|
69
|
+
int(labels.numel()),
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _model(config: Mapping[str, Any], *, recurrent_kind: str) -> object:
|
|
74
|
+
import torch
|
|
75
|
+
|
|
76
|
+
input_features = int(config.get("input_features", 4))
|
|
77
|
+
hidden_size = int(config.get("hidden_size", 16))
|
|
78
|
+
num_layers = int(config.get("num_layers", 1))
|
|
79
|
+
if input_features < 1 or hidden_size < 1 or num_layers < 1:
|
|
80
|
+
raise ValueError("RNN dimensions must be positive")
|
|
81
|
+
|
|
82
|
+
class RecurrentClassifier(torch.nn.Module):
|
|
83
|
+
def __init__(self) -> None:
|
|
84
|
+
super().__init__()
|
|
85
|
+
recurrent = torch.nn.LSTM if recurrent_kind == "lstm" else torch.nn.GRU
|
|
86
|
+
self.recurrent = recurrent(
|
|
87
|
+
input_size=1,
|
|
88
|
+
hidden_size=hidden_size,
|
|
89
|
+
num_layers=num_layers,
|
|
90
|
+
batch_first=True,
|
|
91
|
+
)
|
|
92
|
+
self.output = torch.nn.Linear(hidden_size, 1)
|
|
93
|
+
|
|
94
|
+
def forward(self, values: object) -> object:
|
|
95
|
+
sequence = cast(torch.Tensor, values)
|
|
96
|
+
if sequence.ndim == 2 and sequence.shape[1] == input_features:
|
|
97
|
+
sequence = sequence.unsqueeze(-1)
|
|
98
|
+
if (
|
|
99
|
+
sequence.ndim != 3
|
|
100
|
+
or sequence.shape[-1] != 1
|
|
101
|
+
or sequence.shape[1] != input_features
|
|
102
|
+
):
|
|
103
|
+
raise ValueError("RNN input must have shape [batch, window, 1]")
|
|
104
|
+
encoded, _ = self.recurrent(sequence)
|
|
105
|
+
return self.output(encoded[:, -1, :])
|
|
106
|
+
|
|
107
|
+
return RecurrentClassifier()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class _BaseRNNRecipe(TorchRecipe):
|
|
111
|
+
recurrent_kind = "lstm"
|
|
112
|
+
|
|
113
|
+
def adapt_batch(self, batch: object, context: TorchBatchContext) -> TorchBatch:
|
|
114
|
+
return _batch(batch, context)
|
|
115
|
+
|
|
116
|
+
def training_step(
|
|
117
|
+
self, modules: TorchModuleSet, batch: TorchBatch, context: TorchStepContext
|
|
118
|
+
) -> TorchStepResult:
|
|
119
|
+
del context
|
|
120
|
+
import torch
|
|
121
|
+
|
|
122
|
+
predictions = cast(torch.nn.Module, modules["model"])(batch.keyword["window"])
|
|
123
|
+
targets = cast(torch.Tensor, batch.targets)
|
|
124
|
+
numerator = torch.nn.functional.binary_cross_entropy_with_logits(
|
|
125
|
+
predictions, targets, reduction="sum"
|
|
126
|
+
)
|
|
127
|
+
return TorchStepResult(
|
|
128
|
+
outputs={"output": predictions},
|
|
129
|
+
loss=TorchLossContribution(numerator, batch.local_rows),
|
|
130
|
+
metrics={"accuracy": _accuracy(predictions, targets)},
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
def validation_step(
|
|
134
|
+
self, modules: TorchModuleSet, batch: TorchBatch, context: TorchStepContext
|
|
135
|
+
) -> TorchStepResult:
|
|
136
|
+
return self.training_step(modules, batch, context)
|
|
137
|
+
|
|
138
|
+
def configure_optimizers(
|
|
139
|
+
self, modules: TorchModuleSet, context: TorchBuildContext
|
|
140
|
+
) -> TorchOptimizationPlan:
|
|
141
|
+
import torch
|
|
142
|
+
|
|
143
|
+
optimizer_config = _config(context).get("optimizer", {})
|
|
144
|
+
if not isinstance(optimizer_config, Mapping):
|
|
145
|
+
raise ValueError("RNN optimizer config must be a mapping")
|
|
146
|
+
return TorchOptimizationPlan(
|
|
147
|
+
optimizer=torch.optim.Adam(
|
|
148
|
+
cast(torch.nn.Module, modules["model"]).parameters(),
|
|
149
|
+
lr=float(optimizer_config.get("learning_rate", 0.001)),
|
|
150
|
+
weight_decay=float(optimizer_config.get("weight_decay", 0.0)),
|
|
151
|
+
),
|
|
152
|
+
gradient_accumulation_steps=optimizer_config.get("accumulation_steps", 1),
|
|
153
|
+
max_gradient_norm=optimizer_config.get("max_gradient_norm", 1.0),
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
def metric_plan(self, context: TorchRuntimeContext) -> TorchMetricPlan:
|
|
157
|
+
del context
|
|
158
|
+
return TorchMetricPlan({"accuracy": "sum_count", "train_loss": "sum_count"})
|
|
159
|
+
|
|
160
|
+
def artifact_plan(self, context: TorchArtifactContext) -> TorchArtifactPlan:
|
|
161
|
+
config = context.stage.runtime.algorithm_config
|
|
162
|
+
model_config = config.get("model", {})
|
|
163
|
+
features = (
|
|
164
|
+
int(model_config.get("input_features", 4))
|
|
165
|
+
if isinstance(model_config, Mapping)
|
|
166
|
+
else 4
|
|
167
|
+
)
|
|
168
|
+
return TorchArtifactPlan(
|
|
169
|
+
source_kind="torch_module",
|
|
170
|
+
input_signature=(
|
|
171
|
+
{"name": "window", "dtype": "float32", "shape": ("batch", features)},
|
|
172
|
+
),
|
|
173
|
+
output_signature=(
|
|
174
|
+
{"name": "output", "dtype": "float32", "shape": ("batch", 1)},
|
|
175
|
+
),
|
|
176
|
+
targets=(
|
|
177
|
+
{
|
|
178
|
+
"name": "onnx-model",
|
|
179
|
+
"format": "onnx",
|
|
180
|
+
"exporter_id": "torch-onnx-v1",
|
|
181
|
+
"options": {"dynamo": False},
|
|
182
|
+
},
|
|
183
|
+
),
|
|
184
|
+
roles={"inference": "onnx-model"},
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class LSTMRecipe(_BaseRNNRecipe):
|
|
189
|
+
"""Train a fixed-window LSTM binary classifier."""
|
|
190
|
+
|
|
191
|
+
recurrent_kind = "lstm"
|
|
192
|
+
|
|
193
|
+
def build_modules(self, context: TorchBuildContext) -> TorchModuleSet:
|
|
194
|
+
import torch
|
|
195
|
+
|
|
196
|
+
config = _config(context).get("model", {})
|
|
197
|
+
if not isinstance(config, Mapping):
|
|
198
|
+
raise ValueError("LSTM model config must be a mapping")
|
|
199
|
+
return TorchModuleSet(
|
|
200
|
+
{
|
|
201
|
+
"model": _model(config, recurrent_kind="lstm"),
|
|
202
|
+
"loss": torch.nn.Identity(),
|
|
203
|
+
}
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class GRURecipe(_BaseRNNRecipe):
|
|
208
|
+
"""Train a fixed-window GRU binary classifier."""
|
|
209
|
+
|
|
210
|
+
recurrent_kind = "gru"
|
|
211
|
+
|
|
212
|
+
def build_modules(self, context: TorchBuildContext) -> TorchModuleSet:
|
|
213
|
+
import torch
|
|
214
|
+
|
|
215
|
+
config = _config(context).get("model", {})
|
|
216
|
+
if not isinstance(config, Mapping):
|
|
217
|
+
raise ValueError("GRU model config must be a mapping")
|
|
218
|
+
return TorchModuleSet(
|
|
219
|
+
{"model": _model(config, recurrent_kind="gru"), "loss": torch.nn.Identity()}
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
__all__ = ["GRURecipe", "LSTMRecipe"]
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Official distributed Transformer NLP algorithms with lazy exports."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from tributo_algorithms_transformers_nlp.descriptor import TOKEN_TRANSFORMER_DESCRIPTOR
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def __getattr__(name: str) -> Any:
|
|
9
|
+
if name != "TokenTransformerRecipe":
|
|
10
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
11
|
+
import importlib
|
|
12
|
+
|
|
13
|
+
value = getattr(
|
|
14
|
+
importlib.import_module("tributo_algorithms_transformers_nlp.recipe"), name
|
|
15
|
+
)
|
|
16
|
+
globals()[name] = value
|
|
17
|
+
return value
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
__all__ = ["TOKEN_TRANSFORMER_DESCRIPTOR", "TokenTransformerRecipe"]
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Versioned contracts for the pre-tokenized Transformer classifier."""
|
|
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.transformer.{name}.v2".encode()).hexdigest()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class TransformerConfigValidator:
|
|
15
|
+
api_version = 1
|
|
16
|
+
schema_digest = "d" * 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 Transformer 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
|
+
if not isinstance(value.get("output"), Mapping) or not isinstance(
|
|
27
|
+
value["output"].get("bundle_uri"), str
|
|
28
|
+
):
|
|
29
|
+
raise ValueError("Transformer output.bundle_uri is required")
|
|
30
|
+
return dict(value)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TokenTensorInputValidator:
|
|
34
|
+
api_version = 1
|
|
35
|
+
schema_digest = _digest("tokens-role-routed")
|
|
36
|
+
|
|
37
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
38
|
+
bindings = value.get("bindings")
|
|
39
|
+
if not isinstance(bindings, list) or not 1 <= len(bindings) <= 3:
|
|
40
|
+
raise ValueError(
|
|
41
|
+
"Transformer requires train and optional val/test bindings"
|
|
42
|
+
)
|
|
43
|
+
if any(not isinstance(binding, Mapping) for binding in bindings):
|
|
44
|
+
raise ValueError("Transformer bindings must be mappings")
|
|
45
|
+
names = [binding.get("name") for binding in bindings]
|
|
46
|
+
if any(not isinstance(name, str) for name in names):
|
|
47
|
+
raise ValueError("Transformer input roles must be named")
|
|
48
|
+
by_role = {str(binding["name"]): binding for binding in bindings}
|
|
49
|
+
if (
|
|
50
|
+
len(by_role) != len(bindings)
|
|
51
|
+
or "train" not in by_role
|
|
52
|
+
or not set(by_role).issubset({"train", "val", "test"})
|
|
53
|
+
or value.get("primary_role") != "train"
|
|
54
|
+
):
|
|
55
|
+
raise ValueError("Transformer input roles are invalid")
|
|
56
|
+
train = by_role["train"]
|
|
57
|
+
expected_features = train.get("feature_names")
|
|
58
|
+
expected_label = train.get("label_name")
|
|
59
|
+
for binding in by_role.values():
|
|
60
|
+
features = binding.get("feature_names")
|
|
61
|
+
if (
|
|
62
|
+
not isinstance(features, list)
|
|
63
|
+
or not features
|
|
64
|
+
or features != expected_features
|
|
65
|
+
):
|
|
66
|
+
raise ValueError(
|
|
67
|
+
"Transformer requires consistent ordered token columns"
|
|
68
|
+
)
|
|
69
|
+
if binding.get("label_name") != expected_label or not isinstance(
|
|
70
|
+
expected_label, str
|
|
71
|
+
):
|
|
72
|
+
raise ValueError("Transformer classification requires a label")
|
|
73
|
+
if binding.get("sample_weight_name") is not None:
|
|
74
|
+
raise ValueError("Transformer does not support sample-weight binding")
|
|
75
|
+
return value
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class TransformerOutputValidator:
|
|
79
|
+
api_version = 1
|
|
80
|
+
schema_digest = "f" * 64
|
|
81
|
+
|
|
82
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
83
|
+
outputs = value.get("outputs")
|
|
84
|
+
if value.get("status") != "succeeded" or not isinstance(outputs, Mapping):
|
|
85
|
+
raise ValueError("Transformer execution failed")
|
|
86
|
+
if not isinstance(outputs.get("bundle_uri"), str) or not outputs["bundle_uri"]:
|
|
87
|
+
raise ValueError("Transformer output requires Bundle")
|
|
88
|
+
return value
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class TransformerTorchCoverageValidator:
|
|
92
|
+
api_version = 1
|
|
93
|
+
schema_digest = _digest("coverage")
|
|
94
|
+
|
|
95
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
96
|
+
if (
|
|
97
|
+
value.get("input_complete") is not True
|
|
98
|
+
or value.get("distributed") is not True
|
|
99
|
+
):
|
|
100
|
+
raise ValueError("Transformer token coverage is incomplete")
|
|
101
|
+
return value
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
__all__ = [
|
|
105
|
+
"TokenTensorInputValidator",
|
|
106
|
+
"TransformerConfigValidator",
|
|
107
|
+
"TransformerOutputValidator",
|
|
108
|
+
"TransformerTorchCoverageValidator",
|
|
109
|
+
]
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Descriptor for the official pre-tokenized Transformer 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_transformers_nlp.contracts import (
|
|
28
|
+
TokenTensorInputValidator,
|
|
29
|
+
TransformerConfigValidator,
|
|
30
|
+
TransformerOutputValidator,
|
|
31
|
+
TransformerTorchCoverageValidator,
|
|
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_transformers_nlp.contracts:{validator.__name__}"
|
|
52
|
+
),
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
_SPEC = AlgorithmSpec(
|
|
57
|
+
name="token_transformer_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="transformer_encoder",
|
|
67
|
+
data_modalities=("text",),
|
|
68
|
+
lifecycle_kind="batch_fit",
|
|
69
|
+
allowed_execution_modes=(ExecutionMode.RAY_TRAIN_TORCH.value,),
|
|
70
|
+
config_contract_ref="tributo.official.transformer.config.v1",
|
|
71
|
+
input_contract_ref="tributo.official.transformer.tokens.v2",
|
|
72
|
+
output_contract_ref="tributo.official.transformer.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 "", TransformerConfigValidator, 1),
|
|
100
|
+
input=_binding(_SPEC.input_contract_ref or "", TokenTensorInputValidator),
|
|
101
|
+
output=_binding(_SPEC.output_contract_ref or "", TransformerOutputValidator, 1),
|
|
102
|
+
coverage=_binding(
|
|
103
|
+
"tributo.official.transformer.torch-coverage.v2",
|
|
104
|
+
TransformerTorchCoverageValidator,
|
|
105
|
+
),
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
TOKEN_TRANSFORMER_DESCRIPTOR = AlgorithmBuilder.from_torch(
|
|
109
|
+
spec=_SPEC,
|
|
110
|
+
implementation_id="tributo.official.transformer.token_classifier",
|
|
111
|
+
implementation_version="2.0.0",
|
|
112
|
+
recipe="tributo_algorithms_transformers_nlp.recipe:TokenTransformerRecipe",
|
|
113
|
+
environment=EnvironmentSpec(
|
|
114
|
+
environment_id="tributo.official.transformer.v2",
|
|
115
|
+
dependencies=(
|
|
116
|
+
"onnx>=1.16",
|
|
117
|
+
"onnxruntime>=1.20",
|
|
118
|
+
"torch>=2.5",
|
|
119
|
+
"tributo>=1.1",
|
|
120
|
+
f"tributo-algorithms[transformers-nlp]=={_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__ = ["TOKEN_TRANSFORMER_DESCRIPTOR"]
|