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,130 @@
1
+ """Descriptor for the jagged-history RayTorchAdapter."""
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_recsys_torch.contracts import (
28
+ JaggedConfigValidator,
29
+ JaggedOutputValidator,
30
+ JaggedTorchCoverageValidator,
31
+ JaggedTorchInputValidator,
32
+ )
33
+
34
+ _PACKAGE = "tributo-algorithms"
35
+ _VERSION = "0.1.0"
36
+ _ROOT = Path(__file__).resolve().parent
37
+
38
+
39
+ def _code_digest() -> str:
40
+ return hashlib.sha256((_ROOT / "jagged.py").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_recsys_torch.contracts:{validator.__name__}"
52
+ ),
53
+ )
54
+
55
+
56
+ _SPEC = AlgorithmSpec(
57
+ name="jagged_embedding_recommender",
58
+ trainer_cls=None,
59
+ version="1.0.0",
60
+ default_config={},
61
+ supported_tasks=("fit",),
62
+ operations=("fit",),
63
+ problem_types=(ProblemType.RANKING,),
64
+ capabilities=(Capability.DISTRIBUTED, Capability.EXPORTABLE, Capability.TUNABLE),
65
+ learning_paradigm="supervised_implicit_feedback",
66
+ model_family="jagged_embedding_ddp_alltoall_routing",
67
+ data_modalities=("interaction", "jagged_sequence"),
68
+ lifecycle_kind="batch_fit",
69
+ allowed_execution_modes=(ExecutionMode.RAY_TRAIN_TORCH.value,),
70
+ config_contract_ref="tributo.official.jagged-recsys.config.v2",
71
+ input_contract_ref="tributo.official.jagged-recsys.interactions.v2",
72
+ output_contract_ref="tributo.official.jagged-recsys.bundle.v1",
73
+ )
74
+
75
+ _POLICY = TorchPolicy(
76
+ torch_runtime_api_version=1,
77
+ loop_owner="adapter",
78
+ parallelism_id="torch.ddp.replicated",
79
+ dataset_routing=(TorchDatasetRoute("train", "split_exact", True, 1, 1, "reject"),),
80
+ execution_plan=SingleStageTorchPlan(
81
+ stage=TorchStageSpec(
82
+ "train",
83
+ ("train",),
84
+ )
85
+ ),
86
+ state_layout="replicated",
87
+ metric_reducers={"train_loss": MetricReduction.SUM_COUNT},
88
+ backend="auto",
89
+ )
90
+
91
+ _CONTRACTS = ContractBindingSet(
92
+ config=_binding(_SPEC.config_contract_ref or "", JaggedConfigValidator, 1),
93
+ input=_binding(_SPEC.input_contract_ref or "", JaggedTorchInputValidator),
94
+ output=_binding(_SPEC.output_contract_ref or "", JaggedOutputValidator, 1),
95
+ coverage=_binding(
96
+ "tributo.official.jagged-recsys.torch-coverage.v2", JaggedTorchCoverageValidator
97
+ ),
98
+ )
99
+
100
+ JAGGED_DESCRIPTOR = AlgorithmBuilder.from_torch_adapter(
101
+ spec=_SPEC,
102
+ implementation_id="tributo.official.recsys_torch.jagged_embedding",
103
+ implementation_version="2.0.0",
104
+ adapter="tributo_algorithms_recsys_torch.jagged:DistributedJaggedEmbedding",
105
+ environment=EnvironmentSpec(
106
+ environment_id="tributo.official.recsys-torch-jagged.v2",
107
+ dependencies=(
108
+ "onnx>=1.16",
109
+ "onnxruntime>=1.20",
110
+ "safetensors>=0.4.3",
111
+ "torch>=2.5",
112
+ "tributo>=1.1",
113
+ f"tributo-algorithms[recsys-torch]=={_VERSION}",
114
+ ),
115
+ ),
116
+ metric_reducers={"train_loss": MetricReduction.SUM_COUNT},
117
+ supported_worker_range=WorkerRange(2, 64),
118
+ supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
119
+ resources_per_worker=WorkerResources(num_cpus=1),
120
+ package_name=_PACKAGE,
121
+ package_version=_VERSION,
122
+ tributo_version_spec=">=1.1",
123
+ policy=_POLICY,
124
+ code_digest=_code_digest(),
125
+ contract_bindings=_CONTRACTS,
126
+ descriptor_api_version=2,
127
+ is_default=True,
128
+ )
129
+
130
+ __all__ = ["JAGGED_DESCRIPTOR"]
@@ -0,0 +1,192 @@
1
+ """Typed TorchRecipe implementation for the Two-Tower recommender."""
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 _integer_tensor(value: object, field_name: str) -> Any:
29
+ import torch
30
+
31
+ tensor = torch.as_tensor(value)
32
+ if tensor.dtype == torch.bool or tensor.is_floating_point() or tensor.is_complex():
33
+ raise ValueError(f"{field_name} must contain integer values")
34
+ return tensor.to(dtype=torch.int64)
35
+
36
+
37
+ def _model(config: Mapping[str, Any]) -> object:
38
+ import torch
39
+
40
+ user_count = int(config.get("user_count", 1))
41
+ item_count = int(config.get("item_count", 1))
42
+ embedding_dim = int(config.get("embedding_dim", 16))
43
+ if min(user_count, item_count, embedding_dim) < 1:
44
+ raise ValueError("Two-Tower dimensions must be positive")
45
+
46
+ class TwoTower(torch.nn.Module):
47
+ def __init__(self) -> None:
48
+ super().__init__()
49
+ self.user_embedding = torch.nn.Embedding(user_count, embedding_dim)
50
+ self.item_embedding = torch.nn.Embedding(item_count, embedding_dim)
51
+ self.user_bias = torch.nn.Embedding(user_count, 1)
52
+ self.item_bias = torch.nn.Embedding(item_count, 1)
53
+
54
+ def forward(self, user_id: object, item_id: object) -> object:
55
+ users = cast(torch.Tensor, _integer_tensor(user_id, "Two-Tower user IDs"))
56
+ items = cast(torch.Tensor, _integer_tensor(item_id, "Two-Tower item IDs"))
57
+ if users.ndim != 1 or items.ndim != 1 or users.shape != items.shape:
58
+ raise ValueError("Two-Tower IDs must have shape [batch]")
59
+ if bool((users < 0).any()) or bool((users >= user_count).any()):
60
+ raise ValueError("Two-Tower user ID is out of range")
61
+ if bool((items < 0).any()) or bool((items >= item_count).any()):
62
+ raise ValueError("Two-Tower item ID is out of range")
63
+ score = (self.user_embedding(users) * self.item_embedding(items)).sum(
64
+ dim=1, keepdim=True
65
+ )
66
+ return score + self.user_bias(users) + self.item_bias(items)
67
+
68
+ return TwoTower()
69
+
70
+
71
+ def _batch(batch: object, context: TorchBatchContext) -> TorchBatch:
72
+ import torch
73
+
74
+ if not isinstance(batch, Mapping):
75
+ raise ValueError("Two-Tower batch must be columnar")
76
+ names = context.feature_names or ("user_id", "item_id")
77
+ label_name = context.label_name or ("label" if "label" in batch else None)
78
+ if len(names) != 2 or label_name is None:
79
+ raise ValueError("Two-Tower requires user_id, item_id, and label")
80
+ if context.weight_name is not None:
81
+ raise ValueError("Two-Tower does not support sample-weight binding")
82
+ user_id = _integer_tensor(batch[names[0]], "Two-Tower user IDs")
83
+ item_id = _integer_tensor(batch[names[1]], "Two-Tower item IDs")
84
+ labels = torch.as_tensor(batch[label_name], dtype=torch.float32).reshape(-1, 1)
85
+ if not torch.isfinite(labels).all() or not bool(
86
+ ((labels == 0) | (labels == 1)).all()
87
+ ):
88
+ raise ValueError("Two-Tower labels must be finite 0 or 1")
89
+ if user_id.ndim != 1 or item_id.ndim != 1 or user_id.shape != item_id.shape:
90
+ raise ValueError("Two-Tower IDs must have shape [batch]")
91
+ rows = int(user_id.shape[0])
92
+ return TorchBatch(
93
+ keyword={"user_id": user_id, "item_id": item_id},
94
+ targets=labels,
95
+ local_rows=rows,
96
+ coverage_counts={
97
+ "coverage.positive_pairs": int((labels == 1).sum().item()),
98
+ "coverage.negative_pairs": int((labels == 0).sum().item()),
99
+ },
100
+ )
101
+
102
+
103
+ class TwoTowerRecipe(TorchRecipe):
104
+ """Train user/item embeddings from named interaction ID tensors."""
105
+
106
+ def build_modules(self, context: TorchBuildContext) -> TorchModuleSet:
107
+ import torch
108
+
109
+ config = context.runtime.algorithm_config.get("model", {})
110
+ if not isinstance(config, Mapping):
111
+ raise ValueError("Two-Tower model config must be a mapping")
112
+ return TorchModuleSet({"model": _model(config), "loss": torch.nn.Identity()})
113
+
114
+ def adapt_batch(self, batch: object, context: TorchBatchContext) -> TorchBatch:
115
+ return _batch(batch, context)
116
+
117
+ def training_step(
118
+ self, modules: TorchModuleSet, batch: TorchBatch, context: TorchStepContext
119
+ ) -> TorchStepResult:
120
+ del context
121
+ import torch
122
+
123
+ model = cast(torch.nn.Module, modules["model"])
124
+ predictions = model(batch.keyword["user_id"], batch.keyword["item_id"])
125
+ labels = cast(torch.Tensor, batch.targets)
126
+ numerator = torch.nn.functional.binary_cross_entropy_with_logits(
127
+ predictions, labels, reduction="sum"
128
+ )
129
+ correct = (torch.sigmoid(predictions) >= 0.5).eq(labels >= 0.5)
130
+ return TorchStepResult(
131
+ outputs={"output": predictions},
132
+ loss=TorchLossContribution(numerator, batch.local_rows),
133
+ coverage_counts=dict(batch.coverage_counts),
134
+ metrics={
135
+ "pair_accuracy": TorchMetricContribution(
136
+ float(correct.sum().item()), batch.local_rows
137
+ )
138
+ },
139
+ )
140
+
141
+ def validation_step(
142
+ self, modules: TorchModuleSet, batch: TorchBatch, context: TorchStepContext
143
+ ) -> TorchStepResult:
144
+ return self.training_step(modules, batch, context)
145
+
146
+ def configure_optimizers(
147
+ self, modules: TorchModuleSet, context: TorchBuildContext
148
+ ) -> TorchOptimizationPlan:
149
+ import torch
150
+
151
+ config = context.runtime.algorithm_config.get("optimizer", {})
152
+ if not isinstance(config, Mapping):
153
+ raise ValueError("Two-Tower optimizer config must be a mapping")
154
+ return TorchOptimizationPlan(
155
+ optimizer=torch.optim.Adam(
156
+ cast(torch.nn.Module, modules["model"]).parameters(),
157
+ lr=float(config.get("learning_rate", 0.01)),
158
+ weight_decay=float(config.get("weight_decay", 0.0)),
159
+ ),
160
+ gradient_accumulation_steps=config.get("accumulation_steps", 1),
161
+ max_gradient_norm=config.get("max_gradient_norm", 1.0),
162
+ )
163
+
164
+ def metric_plan(self, context: TorchRuntimeContext) -> TorchMetricPlan:
165
+ del context
166
+ return TorchMetricPlan(
167
+ {"pair_accuracy": "sum_count", "train_loss": "sum_count"}
168
+ )
169
+
170
+ def artifact_plan(self, context: TorchArtifactContext) -> TorchArtifactPlan:
171
+ return TorchArtifactPlan(
172
+ source_kind="torch_module",
173
+ input_signature=(
174
+ {"name": "user_id", "dtype": "int64", "shape": ("batch",)},
175
+ {"name": "item_id", "dtype": "int64", "shape": ("batch",)},
176
+ ),
177
+ output_signature=(
178
+ {"name": "output", "dtype": "float32", "shape": ("batch", 1)},
179
+ ),
180
+ targets=(
181
+ {
182
+ "name": "onnx-model",
183
+ "format": "onnx",
184
+ "exporter_id": "torch-onnx-v1",
185
+ "options": {"dynamo": False},
186
+ },
187
+ ),
188
+ roles={"inference": "onnx-model"},
189
+ )
190
+
191
+
192
+ __all__ = ["TwoTowerRecipe"]
@@ -0,0 +1,20 @@
1
+ """Official self-supervised representation algorithms with lazy exports."""
2
+
3
+ from typing import Any
4
+
5
+ from tributo_algorithms_representation.descriptor import TABULAR_AUTOENCODER_DESCRIPTOR
6
+
7
+
8
+ def __getattr__(name: str) -> Any:
9
+ if name != "TabularAutoencoderRecipe":
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_representation.recipe"), name
15
+ )
16
+ globals()[name] = value
17
+ return value
18
+
19
+
20
+ __all__ = ["TABULAR_AUTOENCODER_DESCRIPTOR", "TabularAutoencoderRecipe"]
@@ -0,0 +1,117 @@
1
+ """Versioned contracts for the tabular autoencoder."""
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.representation.{name}.v2".encode()).hexdigest()
12
+
13
+
14
+ class RepresentationConfigValidator:
15
+ api_version = 1
16
+ schema_digest = "9" * 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 representation 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("representation output.bundle_uri is required")
30
+ optimizer = value.get("optimizer", {})
31
+ if isinstance(optimizer, Mapping):
32
+ accumulation = optimizer.get("accumulation_steps", 1)
33
+ if (
34
+ not isinstance(accumulation, int)
35
+ or isinstance(accumulation, bool)
36
+ or accumulation < 1
37
+ ):
38
+ raise ValueError("Autoencoder accumulation_steps must be positive")
39
+ return dict(value)
40
+
41
+
42
+ class AutoencoderTensorInputValidator:
43
+ api_version = 1
44
+ schema_digest = _digest("tensor-input-role-routed")
45
+
46
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
47
+ bindings = value.get("bindings")
48
+ if not isinstance(bindings, list) or not 1 <= len(bindings) <= 3:
49
+ raise ValueError(
50
+ "Autoencoder requires train and optional val/test bindings"
51
+ )
52
+ if any(not isinstance(binding, Mapping) for binding in bindings):
53
+ raise ValueError("Autoencoder bindings must be mappings")
54
+ names = [binding.get("name") for binding in bindings]
55
+ if any(not isinstance(name, str) for name in names):
56
+ raise ValueError("Autoencoder input roles must be named")
57
+ by_role = {str(binding["name"]): binding for binding in bindings}
58
+ if (
59
+ len(by_role) != len(bindings)
60
+ or "train" not in by_role
61
+ or not set(by_role).issubset({"train", "val", "test"})
62
+ or value.get("primary_role") != "train"
63
+ ):
64
+ raise ValueError("Autoencoder input roles are invalid")
65
+ expected_features = by_role["train"].get("feature_names")
66
+ for binding in by_role.values():
67
+ features = binding.get("feature_names")
68
+ if (
69
+ not isinstance(features, list)
70
+ or not features
71
+ or features != expected_features
72
+ ):
73
+ raise ValueError(
74
+ "Autoencoder requires consistent named dense feature columns"
75
+ )
76
+ if (
77
+ binding.get("label_name") is not None
78
+ or binding.get("sample_weight_name") is not None
79
+ ):
80
+ raise ValueError(
81
+ "Autoencoder does not accept label or sample-weight bindings"
82
+ )
83
+ return value
84
+
85
+
86
+ class RepresentationOutputValidator:
87
+ api_version = 1
88
+ schema_digest = "b" * 64
89
+
90
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
91
+ outputs = value.get("outputs")
92
+ if value.get("status") != "succeeded" or not isinstance(outputs, Mapping):
93
+ raise ValueError("representation execution failed")
94
+ if not isinstance(outputs.get("bundle_uri"), str) or not outputs["bundle_uri"]:
95
+ raise ValueError("representation output requires Bundle")
96
+ return value
97
+
98
+
99
+ class AutoencoderTorchCoverageValidator:
100
+ api_version = 1
101
+ schema_digest = _digest("coverage")
102
+
103
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
104
+ if (
105
+ value.get("input_complete") is not True
106
+ or value.get("distributed") is not True
107
+ ):
108
+ raise ValueError("Autoencoder input coverage is incomplete")
109
+ return value
110
+
111
+
112
+ __all__ = [
113
+ "AutoencoderTensorInputValidator",
114
+ "AutoencoderTorchCoverageValidator",
115
+ "RepresentationConfigValidator",
116
+ "RepresentationOutputValidator",
117
+ ]
@@ -0,0 +1,137 @@
1
+ """Descriptor for the official tabular autoencoder 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_representation.contracts import (
28
+ AutoencoderTensorInputValidator,
29
+ AutoencoderTorchCoverageValidator,
30
+ RepresentationConfigValidator,
31
+ RepresentationOutputValidator,
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_representation.contracts:{validator.__name__}"
52
+ ),
53
+ )
54
+
55
+
56
+ _SPEC = AlgorithmSpec(
57
+ name="tabular_autoencoder",
58
+ trainer_cls=None,
59
+ version="1.0.0",
60
+ default_config={},
61
+ supported_tasks=("fit",),
62
+ operations=("fit",),
63
+ problem_types=(ProblemType.ANOMALY_DETECTION,),
64
+ capabilities=(Capability.DISTRIBUTED, Capability.EXPORTABLE, Capability.TUNABLE),
65
+ learning_paradigm="self_supervised",
66
+ model_family="tabular_autoencoder",
67
+ data_modalities=("tabular",),
68
+ lifecycle_kind="batch_fit",
69
+ allowed_execution_modes=(ExecutionMode.RAY_TRAIN_TORCH.value,),
70
+ config_contract_ref="tributo.official.autoencoder.config.v1",
71
+ input_contract_ref="tributo.official.autoencoder.tensor-input.v2",
72
+ output_contract_ref="tributo.official.autoencoder.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
+ "reconstruction_mse": 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 "", RepresentationConfigValidator, 1),
100
+ input=_binding(_SPEC.input_contract_ref or "", AutoencoderTensorInputValidator),
101
+ output=_binding(_SPEC.output_contract_ref or "", RepresentationOutputValidator, 1),
102
+ coverage=_binding(
103
+ "tributo.official.autoencoder.torch-coverage.v2",
104
+ AutoencoderTorchCoverageValidator,
105
+ ),
106
+ )
107
+
108
+ TABULAR_AUTOENCODER_DESCRIPTOR = AlgorithmBuilder.from_torch(
109
+ spec=_SPEC,
110
+ implementation_id="tributo.official.representation.tabular_autoencoder",
111
+ implementation_version="2.0.0",
112
+ recipe="tributo_algorithms_representation.recipe:TabularAutoencoderRecipe",
113
+ environment=EnvironmentSpec(
114
+ environment_id="tributo.official.representation.v2",
115
+ dependencies=(
116
+ "onnx>=1.16",
117
+ "onnxruntime>=1.20",
118
+ "torch>=2.5",
119
+ "tributo>=1.1",
120
+ f"tributo-algorithms[representation]=={_VERSION}",
121
+ ),
122
+ ),
123
+ metric_reducers={"reconstruction_mse": 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__ = ["TABULAR_AUTOENCODER_DESCRIPTOR"]