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,153 @@
1
+ """Descriptor for the Core-orchestrated pretrain/finetune Component plan."""
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
+ ComponentStageTorchPlan,
12
+ ContractBinding,
13
+ ContractBindingSet,
14
+ EnvironmentSpec,
15
+ ExecutionMode,
16
+ ExecutionProfile,
17
+ MetricReduction,
18
+ QualifiedReference,
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_multistage_torch.contracts import (
28
+ PretrainFinetuneConfigValidator,
29
+ PretrainFinetuneOutputValidator,
30
+ PretrainFinetuneTorchCoverageValidator,
31
+ PretrainFinetuneTorchInputValidator,
32
+ )
33
+
34
+ STAGES = ("pretrain", "finetune")
35
+ _PACKAGE = "tributo-algorithms"
36
+ _VERSION = "0.1.0"
37
+ _ROOT = Path(__file__).resolve().parent
38
+
39
+
40
+ def _code_digest() -> str:
41
+ return hashlib.sha256((_ROOT / "pretrain.py").read_bytes()).hexdigest()
42
+
43
+
44
+ def _binding(contract_id: str, validator: type[Any], version: int) -> ContractBinding:
45
+ return ContractBinding(
46
+ contract_id=contract_id,
47
+ schema_version=version,
48
+ schema_digest=str(validator.schema_digest),
49
+ validator_ref=QualifiedReference.parse(
50
+ f"tributo_algorithms_multistage_torch.contracts:{validator.__name__}"
51
+ ),
52
+ )
53
+
54
+
55
+ _SPEC = AlgorithmSpec(
56
+ name="pretrain_finetune_classifier",
57
+ trainer_cls=None,
58
+ version="1.0.0",
59
+ default_config={},
60
+ supported_tasks=("fit",),
61
+ operations=("fit",),
62
+ problem_types=(ProblemType.BINARY_CLASSIFICATION,),
63
+ capabilities=(Capability.DISTRIBUTED, Capability.EXPORTABLE, Capability.TUNABLE),
64
+ learning_paradigm="self_supervised_pretrain_then_supervised_finetune",
65
+ model_family="encoder_classifier",
66
+ data_modalities=("tabular",),
67
+ lifecycle_kind="finite_multistage_fit",
68
+ allowed_execution_modes=(ExecutionMode.RAY_TRAIN_TORCH.value,),
69
+ config_contract_ref="tributo.official.pretrain-finetune.config.v1",
70
+ input_contract_ref="tributo.official.pretrain-finetune.dense-labeled.v2",
71
+ output_contract_ref="tributo.official.pretrain-finetune.bundle.v1",
72
+ )
73
+
74
+ _POLICY = TorchPolicy(
75
+ torch_runtime_api_version=1,
76
+ loop_owner="adapter",
77
+ parallelism_id="torch.ddp.replicated",
78
+ dataset_routing=(TorchDatasetRoute("train", "split_exact", True, 1, 1, "reject"),),
79
+ execution_plan=ComponentStageTorchPlan(
80
+ stages=(
81
+ TorchStageSpec(
82
+ "pretrain",
83
+ ("train",),
84
+ ),
85
+ TorchStageSpec(
86
+ "finetune",
87
+ ("train",),
88
+ checkpoint_from_stage="pretrain",
89
+ ),
90
+ ),
91
+ final_stage_id="finetune",
92
+ ),
93
+ state_layout="component",
94
+ metric_reducers={
95
+ "pretrain_loss": MetricReduction.SUM_COUNT,
96
+ "finetune_loss": MetricReduction.SUM_COUNT,
97
+ "train_loss": MetricReduction.SUM_COUNT,
98
+ },
99
+ backend="auto",
100
+ )
101
+
102
+ _CONTRACTS = ContractBindingSet(
103
+ config=_binding(
104
+ _SPEC.config_contract_ref or "", PretrainFinetuneConfigValidator, 1
105
+ ),
106
+ input=_binding(
107
+ _SPEC.input_contract_ref or "", PretrainFinetuneTorchInputValidator, 2
108
+ ),
109
+ output=_binding(
110
+ _SPEC.output_contract_ref or "", PretrainFinetuneOutputValidator, 1
111
+ ),
112
+ coverage=_binding(
113
+ "tributo.official.pretrain-finetune.torch-component-coverage.v2",
114
+ PretrainFinetuneTorchCoverageValidator,
115
+ 2,
116
+ ),
117
+ )
118
+
119
+ PRETRAIN_FINETUNE_DESCRIPTOR = AlgorithmBuilder.from_torch_adapter(
120
+ spec=_SPEC,
121
+ implementation_id="tributo.official.multistage_torch.pretrain_finetune",
122
+ implementation_version="2.0.0",
123
+ adapter="tributo_algorithms_multistage_torch.pretrain:DistributedPretrainFinetune",
124
+ environment=EnvironmentSpec(
125
+ environment_id="tributo.official.pretrain-finetune.v2",
126
+ dependencies=(
127
+ "onnx>=1.16",
128
+ "onnxruntime>=1.20",
129
+ "safetensors>=0.4.3",
130
+ "torch>=2.5",
131
+ "tributo>=1.1",
132
+ f"tributo-algorithms[multistage-torch]=={_VERSION}",
133
+ ),
134
+ ),
135
+ metric_reducers={
136
+ "pretrain_loss": MetricReduction.SUM_COUNT,
137
+ "finetune_loss": MetricReduction.SUM_COUNT,
138
+ "train_loss": MetricReduction.SUM_COUNT,
139
+ },
140
+ supported_worker_range=WorkerRange(2, 64),
141
+ supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
142
+ resources_per_worker=WorkerResources(num_cpus=1),
143
+ package_name=_PACKAGE,
144
+ package_version=_VERSION,
145
+ tributo_version_spec=">=1.1",
146
+ policy=_POLICY,
147
+ code_digest=_code_digest(),
148
+ contract_bindings=_CONTRACTS,
149
+ descriptor_api_version=2,
150
+ is_default=True,
151
+ )
152
+
153
+ __all__ = ["PRETRAIN_FINETUNE_DESCRIPTOR", "STAGES"]
@@ -0,0 +1,35 @@
1
+ """Official distributed recommendation algorithms with lazy runtime exports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from tributo_algorithms_recsys_torch.descriptor import TWO_TOWER_DESCRIPTOR
8
+ from tributo_algorithms_recsys_torch.jagged_descriptor import JAGGED_DESCRIPTOR
9
+
10
+ _LAZY_EXPORTS = {
11
+ "DistributedJaggedEmbedding": (
12
+ "tributo_algorithms_recsys_torch.jagged",
13
+ "DistributedJaggedEmbedding",
14
+ ),
15
+ "TwoTowerRecipe": ("tributo_algorithms_recsys_torch.recipe", "TwoTowerRecipe"),
16
+ }
17
+
18
+
19
+ def __getattr__(name: str) -> Any:
20
+ target = _LAZY_EXPORTS.get(name)
21
+ if target is None:
22
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
23
+ import importlib
24
+
25
+ value = getattr(importlib.import_module(target[0]), target[1])
26
+ globals()[name] = value
27
+ return value
28
+
29
+
30
+ __all__ = [
31
+ "JAGGED_DESCRIPTOR",
32
+ "TWO_TOWER_DESCRIPTOR",
33
+ "DistributedJaggedEmbedding",
34
+ "TwoTowerRecipe",
35
+ ]
@@ -0,0 +1,295 @@
1
+ """Executable contracts for the official Two-Tower Wheel."""
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.recsys-torch.{name}.v2".encode()).hexdigest()
12
+
13
+
14
+ class TwoTowerConfigValidator:
15
+ api_version = 1
16
+ schema_digest = "b" * 64
17
+
18
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
19
+ allowed = {"loss", "metrics", "model", "optimizer", "output", "ray", "training"}
20
+ if unknown := sorted(set(value) - allowed):
21
+ raise ValueError(f"unknown Two-Tower config keys: {unknown}")
22
+ normalized = dict(value)
23
+ model = normalized.get("model")
24
+ if not isinstance(model, Mapping):
25
+ raise ValueError("Two-Tower model config is required")
26
+ for name in ("user_count", "item_count"):
27
+ count = model.get(name)
28
+ if not isinstance(count, int) or isinstance(count, bool) or count < 1:
29
+ raise ValueError(f"model.{name} must be a positive integer")
30
+ output = normalized.get("output")
31
+ if (
32
+ not isinstance(output, Mapping)
33
+ or not isinstance(output.get("bundle_uri"), str)
34
+ or not output["bundle_uri"]
35
+ ):
36
+ raise ValueError("output.bundle_uri is required")
37
+ return normalized
38
+
39
+
40
+ class PairInputValidator:
41
+ api_version = 1
42
+ schema_digest = "c" * 64
43
+
44
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
45
+ bindings = value.get("bindings")
46
+ if not isinstance(bindings, list) or not 1 <= len(bindings) <= 3:
47
+ raise ValueError("Two-Tower requires train and optional val/test bindings")
48
+ if any(not isinstance(binding, Mapping) for binding in bindings):
49
+ raise ValueError("Two-Tower bindings must be mappings")
50
+ names = [binding.get("name") for binding in bindings]
51
+ if any(not isinstance(name, str) for name in names):
52
+ raise ValueError("Two-Tower input roles must be named")
53
+ by_role = {str(binding["name"]): binding for binding in bindings}
54
+ if (
55
+ len(by_role) != len(bindings)
56
+ or "train" not in by_role
57
+ or not set(by_role).issubset({"train", "val", "test"})
58
+ or value.get("primary_role") != "train"
59
+ ):
60
+ raise ValueError("Two-Tower input roles are invalid")
61
+ train = by_role["train"]
62
+ expected_features = train.get("feature_names")
63
+ expected_label = train.get("label_name")
64
+ for binding in by_role.values():
65
+ if (
66
+ binding.get("feature_names") != expected_features
67
+ or not isinstance(expected_features, list)
68
+ or len(expected_features) != 2
69
+ or binding.get("label_name") != expected_label
70
+ or not isinstance(expected_label, str)
71
+ or binding.get("sample_weight_name") is not None
72
+ ):
73
+ raise ValueError(
74
+ "Two-Tower requires consistent user ID, item ID, and label columns"
75
+ )
76
+ return value
77
+
78
+
79
+ class TwoTowerOutputValidator:
80
+ api_version = 1
81
+ schema_digest = "d" * 64
82
+
83
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
84
+ outputs = value.get("outputs")
85
+ if value.get("status") != "succeeded" or not isinstance(outputs, Mapping):
86
+ raise ValueError("Two-Tower execution failed")
87
+ if not isinstance(outputs.get("bundle_uri"), str) or not outputs["bundle_uri"]:
88
+ raise ValueError("Two-Tower output requires Bundle")
89
+ return value
90
+
91
+
92
+ class PairCoverageValidator:
93
+ api_version = 1
94
+ schema_digest = "e" * 64
95
+
96
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
97
+ if (
98
+ value.get("input_complete") is not True
99
+ or value.get("distributed") is not True
100
+ ):
101
+ raise ValueError("Two-Tower distributed coverage is incomplete")
102
+ workers = value.get("workers")
103
+ if not isinstance(workers, list):
104
+ raise ValueError("Two-Tower coverage requires Worker evidence")
105
+ totals = {"positive_pairs": 0, "negative_pairs": 0}
106
+ for worker in workers:
107
+ rows = worker.get("input_rows") if isinstance(worker, Mapping) else None
108
+ if not isinstance(rows, Mapping):
109
+ raise ValueError("Two-Tower pair coverage is missing")
110
+ train_rows = rows.get("train")
111
+ local_total = 0
112
+ for name in totals:
113
+ count = rows.get(f"coverage.{name}")
114
+ if not isinstance(count, int) or isinstance(count, bool) or count < 0:
115
+ raise ValueError(f"Two-Tower {name} coverage is malformed")
116
+ totals[name] += count
117
+ local_total += count
118
+ if local_total != train_rows:
119
+ raise ValueError("Two-Tower pair groups do not partition train rows")
120
+ if any(count <= 0 for count in totals.values()):
121
+ raise ValueError("Two-Tower requires positive and negative interactions")
122
+ return value
123
+
124
+
125
+ class JaggedConfigValidator:
126
+ api_version = 1
127
+ schema_digest = "9" * 64
128
+
129
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
130
+ allowed = {"data", "model", "output", "ray", "training"}
131
+ if unknown := sorted(set(value) - allowed):
132
+ raise ValueError(f"unknown jagged recommendation config keys: {unknown}")
133
+ for name in allowed:
134
+ if not isinstance(value.get(name), Mapping):
135
+ raise ValueError(f"{name} config is required")
136
+ model = value["model"]
137
+ for name in ("user_count", "item_count", "embedding_dim"):
138
+ item = model.get(name)
139
+ if not isinstance(item, int) or isinstance(item, bool) or item < 1:
140
+ raise ValueError(f"model.{name} must be positive")
141
+ data = value["data"]
142
+ columns = [
143
+ data.get(name)
144
+ for name in ("user_col", "history_col", "candidate_col", "label_col")
145
+ ]
146
+ if any(not isinstance(name, str) or not name for name in columns):
147
+ raise ValueError("jagged data column names are required")
148
+ if len(set(columns)) != len(columns):
149
+ raise ValueError("jagged data columns must be distinct")
150
+ history_width = data.get("inference_history_width")
151
+ if (
152
+ not isinstance(history_width, int)
153
+ or isinstance(history_width, bool)
154
+ or history_width < 1
155
+ ):
156
+ raise ValueError("data.inference_history_width must be positive")
157
+ if not value["ray"].get("storage_path"):
158
+ raise ValueError("ray.storage_path is required")
159
+ if (
160
+ not isinstance(value["output"].get("bundle_uri"), str)
161
+ or not value["output"]["bundle_uri"]
162
+ ):
163
+ raise ValueError("output.bundle_uri is required")
164
+ return dict(value)
165
+
166
+
167
+ class JaggedInputValidator:
168
+ api_version = 1
169
+ schema_digest = "6" * 64
170
+
171
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
172
+ bindings = value.get("bindings")
173
+ if not isinstance(bindings, list) or len(bindings) != 1:
174
+ raise ValueError("jagged recommendation requires one train binding")
175
+ binding = bindings[0]
176
+ if (
177
+ not isinstance(binding, Mapping)
178
+ or len(binding.get("feature_names", ())) != 3
179
+ or not binding.get("label_name")
180
+ ):
181
+ raise ValueError(
182
+ "jagged recommendation requires user, history, candidate, and label"
183
+ )
184
+ return value
185
+
186
+
187
+ class JaggedOutputValidator:
188
+ api_version = 1
189
+ schema_digest = "7" * 64
190
+
191
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
192
+ outputs = value.get("outputs")
193
+ if value.get("status") != "succeeded" or not isinstance(outputs, Mapping):
194
+ raise ValueError("jagged recommendation failed")
195
+ if not isinstance(outputs.get("bundle_uri"), str) or not outputs["bundle_uri"]:
196
+ raise ValueError("jagged recommendation requires model Bundle")
197
+ return value
198
+
199
+
200
+ class JaggedCoverageValidator:
201
+ api_version = 1
202
+ schema_digest = "8" * 64
203
+
204
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
205
+ if (
206
+ value.get("input_complete") is not True
207
+ or value.get("distributed") is not True
208
+ ):
209
+ raise ValueError("jagged recommendation coverage is incomplete")
210
+ workers = value.get("workers")
211
+ if not isinstance(workers, list):
212
+ raise ValueError("jagged recommendation requires Worker evidence")
213
+ history_tokens = 0
214
+ routed_tokens = 0
215
+ pair_groups = {"positive_pairs": 0, "negative_pairs": 0}
216
+ for worker in workers:
217
+ rows = worker.get("input_rows") if isinstance(worker, Mapping) else None
218
+ if not isinstance(rows, Mapping):
219
+ raise ValueError("jagged Worker coverage is missing")
220
+ history_tokens += int(rows.get("coverage.history_tokens", 0))
221
+ routed_tokens += int(rows.get("coverage.routed_owned_tokens", 0))
222
+ local_pairs = 0
223
+ for name in pair_groups:
224
+ count = int(rows.get(f"coverage.{name}", 0))
225
+ pair_groups[name] += count
226
+ local_pairs += count
227
+ if local_pairs != rows.get("train"):
228
+ raise ValueError("jagged pair groups do not partition train rows")
229
+ if history_tokens < 1 or history_tokens != routed_tokens:
230
+ raise ValueError("jagged All-to-All routing does not conserve sparse keys")
231
+ if any(count < 1 for count in pair_groups.values()):
232
+ raise ValueError("jagged training requires positive and negative pairs")
233
+ state = value.get("state")
234
+ details = state.get("details") if isinstance(state, Mapping) else None
235
+ if (
236
+ not isinstance(details, Mapping)
237
+ or details.get("jagged") is not True
238
+ or details.get("routing") != "all_to_all_single_owner_mod"
239
+ ):
240
+ raise ValueError("jagged All-to-All routing evidence is missing")
241
+ return value
242
+
243
+
244
+ class JaggedTorchInputValidator(JaggedInputValidator):
245
+ api_version = 1
246
+ schema_digest = _digest("jagged-input-role-named")
247
+
248
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
249
+ validated = super().validate(value)
250
+ bindings = validated.get("bindings")
251
+ binding = bindings[0] if isinstance(bindings, list) else None
252
+ if (
253
+ not isinstance(binding, Mapping)
254
+ or binding.get("name") != "train"
255
+ or binding.get("sample_weight_name") is not None
256
+ or not all(
257
+ isinstance(name, str) and name
258
+ for name in binding.get("feature_names", ())
259
+ )
260
+ ):
261
+ raise ValueError(
262
+ "jagged recommendation requires named, unweighted train input"
263
+ )
264
+ return validated
265
+
266
+
267
+ class JaggedTorchCoverageValidator(JaggedCoverageValidator):
268
+ api_version = 1
269
+ schema_digest = _digest("jagged-coverage")
270
+
271
+
272
+ class TwoTowerTensorInputValidator(PairInputValidator):
273
+ api_version = 1
274
+ schema_digest = _digest("two-tower-input-role-routed")
275
+
276
+
277
+ class TwoTowerTorchCoverageValidator(PairCoverageValidator):
278
+ api_version = 1
279
+ schema_digest = _digest("two-tower-coverage")
280
+
281
+
282
+ __all__ = [
283
+ "PairCoverageValidator",
284
+ "PairInputValidator",
285
+ "TwoTowerTensorInputValidator",
286
+ "TwoTowerTorchCoverageValidator",
287
+ "TwoTowerConfigValidator",
288
+ "TwoTowerOutputValidator",
289
+ "JaggedConfigValidator",
290
+ "JaggedCoverageValidator",
291
+ "JaggedInputValidator",
292
+ "JaggedOutputValidator",
293
+ "JaggedTorchCoverageValidator",
294
+ "JaggedTorchInputValidator",
295
+ ]
@@ -0,0 +1,136 @@
1
+ """Descriptor for the official Two-Tower TorchRecipe recommender."""
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
+ TwoTowerConfigValidator,
29
+ TwoTowerOutputValidator,
30
+ TwoTowerTensorInputValidator,
31
+ TwoTowerTorchCoverageValidator,
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_recsys_torch.contracts:{validator.__name__}"
52
+ ),
53
+ )
54
+
55
+
56
+ _SPEC = AlgorithmSpec(
57
+ name="two_tower_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_pairwise",
66
+ model_family="two_tower_embedding",
67
+ data_modalities=("interaction",),
68
+ lifecycle_kind="batch_fit",
69
+ allowed_execution_modes=(ExecutionMode.RAY_TRAIN_TORCH.value,),
70
+ config_contract_ref="tributo.official.two-tower.config.v1",
71
+ input_contract_ref="tributo.official.two-tower.pairs.v2",
72
+ output_contract_ref="tributo.official.two-tower.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
+ "pair_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 "", TwoTowerConfigValidator, 1),
100
+ input=_binding(_SPEC.input_contract_ref or "", TwoTowerTensorInputValidator),
101
+ output=_binding(_SPEC.output_contract_ref or "", TwoTowerOutputValidator, 1),
102
+ coverage=_binding(
103
+ "tributo.official.two-tower.torch-coverage.v2", TwoTowerTorchCoverageValidator
104
+ ),
105
+ )
106
+
107
+ TWO_TOWER_DESCRIPTOR = AlgorithmBuilder.from_torch(
108
+ spec=_SPEC,
109
+ implementation_id="tributo.official.recsys_torch.two_tower",
110
+ implementation_version="2.0.0",
111
+ recipe="tributo_algorithms_recsys_torch.recipe:TwoTowerRecipe",
112
+ environment=EnvironmentSpec(
113
+ environment_id="tributo.official.recsys-torch.v2",
114
+ dependencies=(
115
+ "onnx>=1.16",
116
+ "onnxruntime>=1.20",
117
+ "torch>=2.5",
118
+ "tributo>=1.1",
119
+ f"tributo-algorithms[recsys-torch]=={_VERSION}",
120
+ ),
121
+ ),
122
+ metric_reducers={"pair_accuracy": MetricReduction.SUM_COUNT},
123
+ supported_worker_range=WorkerRange(1, 64),
124
+ supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
125
+ resources_per_worker=WorkerResources(num_cpus=1),
126
+ package_name=_PACKAGE,
127
+ package_version=_VERSION,
128
+ tributo_version_spec=">=1.1",
129
+ policy=_POLICY,
130
+ code_digest=_code_digest("recipe.py"),
131
+ contract_bindings=_CONTRACTS,
132
+ descriptor_api_version=2,
133
+ is_default=True,
134
+ )
135
+
136
+ __all__ = ["TWO_TOWER_DESCRIPTOR"]