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,526 @@
1
+ """Distributed stability-selection PC causal discovery."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ from collections.abc import Iterable, Mapping
8
+ from dataclasses import dataclass
9
+ from typing import cast
10
+
11
+ from tributo.algorithms import AlgorithmBuilder
12
+ from tributo.algorithms.api import (
13
+ AlgorithmConfigurationError,
14
+ AlgorithmExecutionError,
15
+ AlgorithmExecutionResult,
16
+ AlgorithmInputError,
17
+ ArtifactDraft,
18
+ ContractBinding,
19
+ ContractBindingSet,
20
+ DistributionStrategy,
21
+ EnvironmentSpec,
22
+ ExecutionMode,
23
+ ExecutionProfile,
24
+ MapReducePolicy,
25
+ QualifiedReference,
26
+ ResolvedAlgorithmPlan,
27
+ StateField,
28
+ WorkerRange,
29
+ WorkerResources,
30
+ )
31
+ from tributo.algorithms.spi import AlgorithmExecutionContext, MapReduceAlgorithm
32
+ from tributo.exporting.models import BundleOutputConfig, ExportSource, ExportTarget
33
+ from tributo.exporting.service import BundleExportService
34
+ from tributo.training.algorithm_spec import AlgorithmSpec, Capability, ProblemType
35
+
36
+ _PACKAGE = "tributo-algorithms"
37
+ _VERSION = "0.1.0"
38
+ _STATE_SCHEMA = (
39
+ StateField("adjacency_votes", "int64", (None, None)),
40
+ StateField("arrow_votes", "int64", (None, None)),
41
+ StateField("tail_votes", "int64", (None, None)),
42
+ StateField("run_count", "int64", ()),
43
+ StateField("row_count", "int64", ()),
44
+ )
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class CausalGraphModel:
49
+ variables: tuple[str, ...]
50
+ endpoint_matrix: tuple[tuple[int, ...], ...]
51
+ adjacency_vote_fraction: tuple[tuple[float, ...], ...]
52
+ run_count: int
53
+ row_count: int
54
+ alpha: float
55
+ vote_threshold: float
56
+
57
+ def report(self) -> dict[str, object]:
58
+ edges = []
59
+ for left in range(len(self.variables)):
60
+ for right in range(left + 1, len(self.variables)):
61
+ left_endpoint = self.endpoint_matrix[left][right]
62
+ right_endpoint = self.endpoint_matrix[right][left]
63
+ if left_endpoint == 0 or right_endpoint == 0:
64
+ continue
65
+ edges.append(
66
+ {
67
+ "left": self.variables[left],
68
+ "right": self.variables[right],
69
+ "left_endpoint": left_endpoint,
70
+ "right_endpoint": right_endpoint,
71
+ "vote_fraction": self.adjacency_vote_fraction[left][right],
72
+ }
73
+ )
74
+ return {
75
+ "api_version": 1,
76
+ "kind": "causal_discovery",
77
+ "method": "distributed_shard_stability_pc",
78
+ "variables": list(self.variables),
79
+ "edges": edges,
80
+ "endpoint_encoding": {"tail": -1, "arrow": 1, "absent": 0},
81
+ "alpha": self.alpha,
82
+ "vote_threshold": self.vote_threshold,
83
+ "shard_runs": self.run_count,
84
+ "row_count": self.row_count,
85
+ "limitations": [
86
+ "stability-selected shard PC is not bitwise equivalent to centralized PC"
87
+ ],
88
+ }
89
+
90
+
91
+ def _query_onnx(model: CausalGraphModel) -> bytes:
92
+ """Build a bounded ONNX graph for exact causal-edge report queries."""
93
+ import numpy as np
94
+ import onnx
95
+ from onnx import TensorProto, helper, numpy_helper
96
+
97
+ endpoints = np.asarray(model.endpoint_matrix, dtype=np.int64)
98
+ votes = np.asarray(model.adjacency_vote_fraction, dtype=np.float32)
99
+ node_count = len(model.variables)
100
+ graph = helper.make_graph(
101
+ [
102
+ helper.make_node("GreaterOrEqual", ["edge_index", "min_index"], ["ge"]),
103
+ helper.make_node("Less", ["edge_index", "max_exclusive"], ["lt"]),
104
+ helper.make_node("And", ["ge", "lt"], ["element_valid"]),
105
+ helper.make_node(
106
+ "Cast",
107
+ ["element_valid"],
108
+ ["element_valid_int"],
109
+ to=TensorProto.INT64,
110
+ ),
111
+ helper.make_node(
112
+ "ReduceMin",
113
+ ["element_valid_int", "row_axis"],
114
+ ["valid_int"],
115
+ keepdims=0,
116
+ ),
117
+ helper.make_node("Cast", ["valid_int"], ["valid"], to=TensorProto.BOOL),
118
+ helper.make_node(
119
+ "Clip",
120
+ ["edge_index", "min_index", "max_index"],
121
+ ["safe_edge_index"],
122
+ ),
123
+ helper.make_node(
124
+ "GatherND",
125
+ ["endpoint_matrix", "safe_edge_index"],
126
+ ["raw_left_endpoint"],
127
+ ),
128
+ helper.make_node(
129
+ "Gather",
130
+ ["safe_edge_index", "reverse_order"],
131
+ ["reverse_edge_index"],
132
+ axis=1,
133
+ ),
134
+ helper.make_node(
135
+ "GatherND",
136
+ ["endpoint_matrix", "reverse_edge_index"],
137
+ ["raw_right_endpoint"],
138
+ ),
139
+ helper.make_node(
140
+ "GatherND",
141
+ ["vote_matrix", "safe_edge_index"],
142
+ ["raw_vote_fraction"],
143
+ ),
144
+ helper.make_node(
145
+ "Where",
146
+ ["valid", "raw_left_endpoint", "invalid_endpoint"],
147
+ ["left_endpoint"],
148
+ ),
149
+ helper.make_node(
150
+ "Where",
151
+ ["valid", "raw_right_endpoint", "invalid_endpoint"],
152
+ ["right_endpoint"],
153
+ ),
154
+ helper.make_node(
155
+ "Where",
156
+ ["valid", "raw_vote_fraction", "invalid_vote"],
157
+ ["vote_fraction"],
158
+ ),
159
+ ],
160
+ "tributo_pc_edge_query",
161
+ [helper.make_tensor_value_info("edge_index", TensorProto.INT64, [None, 2])],
162
+ [
163
+ helper.make_tensor_value_info("left_endpoint", TensorProto.INT64, [None]),
164
+ helper.make_tensor_value_info("right_endpoint", TensorProto.INT64, [None]),
165
+ helper.make_tensor_value_info("vote_fraction", TensorProto.FLOAT, [None]),
166
+ helper.make_tensor_value_info("valid", TensorProto.BOOL, [None]),
167
+ ],
168
+ initializer=[
169
+ numpy_helper.from_array(endpoints, name="endpoint_matrix"),
170
+ numpy_helper.from_array(votes, name="vote_matrix"),
171
+ numpy_helper.from_array(np.asarray(0, dtype=np.int64), name="min_index"),
172
+ numpy_helper.from_array(
173
+ np.asarray(node_count, dtype=np.int64), name="max_exclusive"
174
+ ),
175
+ numpy_helper.from_array(
176
+ np.asarray(node_count - 1, dtype=np.int64), name="max_index"
177
+ ),
178
+ numpy_helper.from_array(
179
+ np.asarray([1, 0], dtype=np.int64), name="reverse_order"
180
+ ),
181
+ numpy_helper.from_array(np.asarray([1], dtype=np.int64), name="row_axis"),
182
+ numpy_helper.from_array(
183
+ np.asarray(0, dtype=np.int64), name="invalid_endpoint"
184
+ ),
185
+ numpy_helper.from_array(
186
+ np.asarray(0.0, dtype=np.float32), name="invalid_vote"
187
+ ),
188
+ ],
189
+ )
190
+ built = helper.make_model_gen_version(
191
+ graph,
192
+ opset_imports=[helper.make_opsetid("", 18)],
193
+ producer_name="tributo-algorithms",
194
+ )
195
+ onnx.checker.check_model(built)
196
+ return cast(bytes, built.SerializeToString())
197
+
198
+
199
+ class DistributedPCStability(
200
+ MapReduceAlgorithm[Mapping[str, object], Mapping[str, object], CausalGraphModel]
201
+ ):
202
+ """Run causal-learn PC per shard and aggregate stable endpoint votes."""
203
+
204
+ def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
205
+ self.plan = plan
206
+ self.variables = plan.primary_input_binding.feature_names
207
+ self.alpha = float(plan.algorithm_config.get("alpha", 0.05))
208
+ self.vote_threshold = float(plan.algorithm_config.get("vote_threshold", 0.5))
209
+ raw_max_k = plan.algorithm_config.get("max_condition_set")
210
+ self.max_k = int(raw_max_k) if raw_max_k is not None else None
211
+
212
+ def map_partition(
213
+ self,
214
+ batches: Iterable[Mapping[str, object]],
215
+ context: AlgorithmExecutionContext,
216
+ ) -> Mapping[str, object]:
217
+ del context
218
+ import numpy as np
219
+ from causallearn.search.ConstraintBased.PC import pc
220
+
221
+ pieces = []
222
+ for batch in batches:
223
+ missing = [name for name in self.variables if name not in batch]
224
+ if missing:
225
+ raise AlgorithmInputError(f"PC batch is missing variables: {missing}")
226
+ values = np.column_stack(
227
+ [np.asarray(batch[name], dtype=np.float64) for name in self.variables]
228
+ )
229
+ if not np.isfinite(values).all():
230
+ raise AlgorithmInputError("PC discovery requires finite values")
231
+ pieces.append(values)
232
+ if not pieces:
233
+ return self.empty_partition()
234
+ data = np.vstack(pieces)
235
+ if data.shape[0] < max(8, data.shape[1] + 2):
236
+ raise AlgorithmInputError("PC shard has insufficient rows")
237
+ try:
238
+ discovered = pc(
239
+ data,
240
+ alpha=self.alpha,
241
+ stable=True,
242
+ show_progress=False,
243
+ node_names=list(self.variables),
244
+ max_k=self.max_k,
245
+ )
246
+ graph = np.asarray(discovered.G.graph, dtype=np.int64)
247
+ except Exception as exc:
248
+ raise AlgorithmExecutionError(
249
+ f"causal-learn PC failed: {type(exc).__name__}"
250
+ ) from exc
251
+ if graph.shape != (len(self.variables), len(self.variables)):
252
+ raise AlgorithmExecutionError("PC returned an invalid graph matrix")
253
+ return {
254
+ "adjacency_votes": np.asarray(graph != 0, dtype=np.int64),
255
+ "arrow_votes": np.asarray(graph == 1, dtype=np.int64),
256
+ "tail_votes": np.asarray(graph == -1, dtype=np.int64),
257
+ "run_count": np.asarray(1, dtype=np.int64),
258
+ "row_count": np.asarray(data.shape[0], dtype=np.int64),
259
+ }
260
+
261
+ def merge_states(
262
+ self,
263
+ left: Mapping[str, object],
264
+ right: Mapping[str, object],
265
+ ) -> Mapping[str, object]:
266
+ import numpy as np
267
+
268
+ return {
269
+ item.name: np.asarray(
270
+ np.asarray(left[item.name], dtype=item.dtype)
271
+ + np.asarray(right[item.name], dtype=item.dtype),
272
+ dtype=item.dtype,
273
+ )
274
+ for item in _STATE_SCHEMA
275
+ }
276
+
277
+ def finalize_model(self, state: Mapping[str, object]) -> CausalGraphModel:
278
+ import numpy as np
279
+
280
+ runs = int(np.asarray(state["run_count"]))
281
+ if runs < 1:
282
+ raise AlgorithmInputError("PC discovery produced no shard graph")
283
+ adjacency = np.asarray(state["adjacency_votes"], dtype=np.int64)
284
+ arrows = np.asarray(state["arrow_votes"], dtype=np.int64)
285
+ tails = np.asarray(state["tail_votes"], dtype=np.int64)
286
+ required_votes = math.ceil(runs * self.vote_threshold)
287
+ stable = adjacency >= required_votes
288
+ endpoints = np.where(arrows > tails, 1, -1).astype(np.int64)
289
+ endpoints[~stable] = 0
290
+ np.fill_diagonal(endpoints, 0)
291
+ fractions = adjacency.astype(np.float64) / runs
292
+ return CausalGraphModel(
293
+ variables=self.variables,
294
+ endpoint_matrix=tuple(
295
+ tuple(int(value) for value in row) for row in endpoints
296
+ ),
297
+ adjacency_vote_fraction=tuple(
298
+ tuple(float(value) for value in row) for row in fractions
299
+ ),
300
+ run_count=runs,
301
+ row_count=int(np.asarray(state["row_count"])),
302
+ alpha=self.alpha,
303
+ vote_threshold=self.vote_threshold,
304
+ )
305
+
306
+ def state_schema(self) -> tuple[StateField, ...]:
307
+ return _STATE_SCHEMA
308
+
309
+ def empty_partition(self) -> Mapping[str, object]:
310
+ import numpy as np
311
+
312
+ width = len(self.variables)
313
+ return {
314
+ "adjacency_votes": np.zeros((width, width), dtype=np.int64),
315
+ "arrow_votes": np.zeros((width, width), dtype=np.int64),
316
+ "tail_votes": np.zeros((width, width), dtype=np.int64),
317
+ "run_count": np.asarray(0, dtype=np.int64),
318
+ "row_count": np.asarray(0, dtype=np.int64),
319
+ }
320
+
321
+ def coverage_counts(self, state: Mapping[str, object]) -> Mapping[str, int]:
322
+ import numpy as np
323
+
324
+ return {"discovery_rows": int(np.asarray(state["row_count"]))}
325
+
326
+ @property
327
+ def retry_safe(self) -> bool:
328
+ return True
329
+
330
+
331
+ def create_algorithm(
332
+ *,
333
+ plan: ResolvedAlgorithmPlan,
334
+ implementation: object,
335
+ artifacts: tuple[object, ...],
336
+ ) -> DistributedPCStability:
337
+ del artifacts
338
+ if implementation is not DistributedPCStability:
339
+ raise AlgorithmConfigurationError("PC implementation identity drifted")
340
+ return DistributedPCStability(plan)
341
+
342
+
343
+ def export_graph(
344
+ *,
345
+ model: CausalGraphModel,
346
+ plan: ResolvedAlgorithmPlan,
347
+ run_id: str | None = None,
348
+ ) -> AlgorithmExecutionResult:
349
+ report = model.report()
350
+ payload = json.dumps(report, sort_keys=True).encode("utf-8")
351
+ artifact = ArtifactDraft.from_payload(
352
+ name="causal-discovery-report",
353
+ kind="report",
354
+ format="application/json",
355
+ payload=payload,
356
+ )
357
+ output = plan.algorithm_config.get("output")
358
+ if not isinstance(output, Mapping) or not isinstance(output.get("bundle_uri"), str):
359
+ raise AlgorithmConfigurationError("PC output.bundle_uri is required")
360
+ from tributo.exporting.models import CheckpointField, ExportCheckpointV1
361
+
362
+ source = ExportSource(
363
+ source_kind="prebuilt_onnx",
364
+ model_object=_query_onnx(model),
365
+ architecture_id=plan.resolution.implementation_id,
366
+ metadata={
367
+ "causal_study": report,
368
+ "framework": "causal-learn",
369
+ "framework_versions": {"onnx_opset": "18"},
370
+ "producer_distribution": _PACKAGE,
371
+ },
372
+ source_fingerprint=artifact.sha256,
373
+ checkpoint_contract=ExportCheckpointV1(
374
+ trainer_type="pc_stability_discovery",
375
+ architecture_id=plan.resolution.implementation_id,
376
+ input_schema=(
377
+ CheckpointField(name="edge_index", dtype="int64", shape=("batch", 2)),
378
+ ),
379
+ output_schema=(
380
+ CheckpointField(name="left_endpoint", dtype="int64", shape=("batch",)),
381
+ CheckpointField(name="right_endpoint", dtype="int64", shape=("batch",)),
382
+ CheckpointField(
383
+ name="vote_fraction", dtype="float32", shape=("batch",)
384
+ ),
385
+ CheckpointField(name="valid", dtype="bool", shape=("batch",)),
386
+ ),
387
+ preprocessing={
388
+ "type": "variable_index_pair",
389
+ "variables": list(model.variables),
390
+ "invalid_index_policy": "zero_output_with_valid_false",
391
+ },
392
+ task_type="causal_graph_query",
393
+ framework="onnx",
394
+ framework_version="18",
395
+ ),
396
+ )
397
+ bundle = BundleExportService().export_bundle(
398
+ source,
399
+ BundleOutputConfig(
400
+ bundle_uri=str(output["bundle_uri"]),
401
+ request_id=run_id,
402
+ run_id=run_id,
403
+ targets=[
404
+ ExportTarget(
405
+ name="causal-graph-query",
406
+ format="onnx",
407
+ exporter_id="prebuilt-onnx-v1",
408
+ ),
409
+ ExportTarget(
410
+ name="causal-graph-report",
411
+ format="json",
412
+ exporter_id="official-causal-discovery-report-v1",
413
+ ),
414
+ ],
415
+ roles={
416
+ "inference": "causal-graph-query",
417
+ "report": "causal-graph-report",
418
+ },
419
+ ),
420
+ )
421
+ return AlgorithmExecutionResult(
422
+ status="succeeded",
423
+ metrics={"shard_runs": model.run_count, "row_count": model.row_count},
424
+ outputs={
425
+ "bundle_id": bundle.bundle_id,
426
+ "bundle_uri": bundle.canonical_uri,
427
+ "execution_id": bundle.execution_id,
428
+ "manifest_sha256": bundle.manifest_sha256,
429
+ "report_artifact_sha256": artifact.sha256,
430
+ },
431
+ artifacts=(artifact,),
432
+ )
433
+
434
+
435
+ def _contract(contract_id: str, digest: str, validator: str) -> ContractBinding:
436
+ return ContractBinding(
437
+ contract_id=contract_id,
438
+ schema_version=1,
439
+ schema_digest=digest * 64,
440
+ validator_ref=QualifiedReference.parse(
441
+ f"tributo_algorithms_causal_discovery.contracts:{validator}"
442
+ ),
443
+ )
444
+
445
+
446
+ _SPEC = AlgorithmSpec(
447
+ name="pc_stability_discovery",
448
+ trainer_cls=None,
449
+ version="1.0.0",
450
+ default_config={},
451
+ supported_tasks=("fit",),
452
+ operations=("fit",),
453
+ problem_types=(ProblemType.CAUSAL_EFFECT_ESTIMATION,),
454
+ capabilities=(Capability.DISTRIBUTED, Capability.EXPORTABLE, Capability.TUNABLE),
455
+ learning_paradigm="causal_discovery",
456
+ model_family="pc_stability",
457
+ data_modalities=("tabular",),
458
+ lifecycle_kind="discover_validate_report",
459
+ allowed_execution_modes=(ExecutionMode.MAP_REDUCE.value,),
460
+ config_contract_ref="tributo.official.causal.pc.config.v1",
461
+ input_contract_ref="tributo.official.causal.discovery-table.v1",
462
+ output_contract_ref="tributo.official.causal.discovery-report.v1",
463
+ )
464
+
465
+ PC_DISCOVERY_DESCRIPTOR = AlgorithmBuilder.from_distributed_algorithm(
466
+ spec=_SPEC,
467
+ implementation_id="tributo.official.causal_discovery.pc_stability",
468
+ implementation_version="1.0.0",
469
+ implementation=(
470
+ "tributo_algorithms_causal_discovery.algorithm:DistributedPCStability"
471
+ ),
472
+ executable_factory="tributo_algorithms_causal_discovery.algorithm:create_algorithm",
473
+ distribution=_PACKAGE,
474
+ framework="causal-learn",
475
+ environment=EnvironmentSpec(
476
+ environment_id="tributo.official.causal-discovery.v1",
477
+ dependencies=(
478
+ "causal-learn>=0.1.4,<0.2",
479
+ "numpy>=2,<3",
480
+ "onnx>=1.16",
481
+ "onnxruntime>=1.20",
482
+ "tributo>=1.1",
483
+ f"tributo-algorithms[causal-discovery]=={_VERSION}",
484
+ ),
485
+ ),
486
+ allowed_config_keys=("alpha", "max_condition_set", "output", "vote_threshold"),
487
+ strategy=DistributionStrategy.RAY_MAP_REDUCE,
488
+ supported_worker_range=WorkerRange(2, 64),
489
+ supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
490
+ resources_per_worker=WorkerResources(num_cpus=1),
491
+ policy=MapReducePolicy(
492
+ state_schema=_STATE_SCHEMA,
493
+ max_partial_state_bytes=64 * 1024 * 1024,
494
+ reducer_ref=(
495
+ "tributo_algorithms_causal_discovery.algorithm:"
496
+ "DistributedPCStability.merge_states"
497
+ ),
498
+ finalizer_ref=(
499
+ "tributo_algorithms_causal_discovery.algorithm:"
500
+ "DistributedPCStability.finalize_model"
501
+ ),
502
+ commutative=True,
503
+ max_retries=0,
504
+ ),
505
+ package_name=_PACKAGE,
506
+ package_version=_VERSION,
507
+ tributo_version_spec=">=1.1",
508
+ exporter="tributo_algorithms_causal_discovery.algorithm:export_graph",
509
+ flavor_id="onnx-runtime-v1",
510
+ contract_bindings=ContractBindingSet(
511
+ config=_contract(_SPEC.config_contract_ref or "", "6", "PCConfigValidator"),
512
+ input=_contract(_SPEC.input_contract_ref or "", "7", "DiscoveryInputValidator"),
513
+ output=_contract(
514
+ _SPEC.output_contract_ref or "", "8", "DiscoveryOutputValidator"
515
+ ),
516
+ coverage=_contract(
517
+ "tributo.official.causal.discovery-coverage.v1",
518
+ "9",
519
+ "DiscoveryCoverageValidator",
520
+ ),
521
+ ),
522
+ descriptor_api_version=2,
523
+ is_default=True,
524
+ )
525
+
526
+ __all__ = ["PC_DISCOVERY_DESCRIPTOR", "CausalGraphModel", "DistributedPCStability"]
@@ -0,0 +1,97 @@
1
+ """Executable contracts for causal discovery."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any
7
+
8
+
9
+ class PCConfigValidator:
10
+ api_version = 1
11
+ schema_digest = "6" * 64
12
+
13
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
14
+ allowed = {"alpha", "max_condition_set", "output", "vote_threshold"}
15
+ if unknown := sorted(set(value) - allowed):
16
+ raise ValueError(f"unknown PC discovery config keys: {unknown}")
17
+ alpha = value.get("alpha", 0.05)
18
+ threshold = value.get("vote_threshold", 0.5)
19
+ if (
20
+ not isinstance(alpha, (int, float))
21
+ or isinstance(alpha, bool)
22
+ or not 0 < float(alpha) < 1
23
+ ):
24
+ raise ValueError("alpha must be in (0, 1)")
25
+ if (
26
+ not isinstance(threshold, (int, float))
27
+ or isinstance(threshold, bool)
28
+ or not 0.5 <= float(threshold) <= 1
29
+ ):
30
+ raise ValueError("vote_threshold must be in [0.5, 1]")
31
+ output = value.get("output")
32
+ if not isinstance(output, Mapping) or not output.get("bundle_uri"):
33
+ raise ValueError("output.bundle_uri is required")
34
+ return dict(value)
35
+
36
+
37
+ class DiscoveryInputValidator:
38
+ api_version = 1
39
+ schema_digest = "7" * 64
40
+
41
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
42
+ bindings = value.get("bindings")
43
+ if not isinstance(bindings, list) or len(bindings) != 1:
44
+ raise ValueError("causal discovery requires one train binding")
45
+ binding = bindings[0]
46
+ if (
47
+ not isinstance(binding, Mapping)
48
+ or len(binding.get("feature_names", ())) < 2
49
+ or binding.get("label_name") is not None
50
+ ):
51
+ raise ValueError(
52
+ "causal discovery requires at least two unlabeled variables"
53
+ )
54
+ return value
55
+
56
+
57
+ class DiscoveryOutputValidator:
58
+ api_version = 1
59
+ schema_digest = "8" * 64
60
+
61
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
62
+ outputs = value.get("outputs")
63
+ if value.get("status") != "succeeded" or not isinstance(outputs, Mapping):
64
+ raise ValueError("causal discovery failed")
65
+ if not outputs.get("bundle_uri") or not outputs.get("report_artifact_sha256"):
66
+ raise ValueError("causal discovery requires report Bundle output")
67
+ return value
68
+
69
+
70
+ class DiscoveryCoverageValidator:
71
+ api_version = 1
72
+ schema_digest = "9" * 64
73
+
74
+ def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
75
+ if (
76
+ value.get("input_complete") is not True
77
+ or value.get("distributed") is not True
78
+ ):
79
+ raise ValueError("causal discovery coverage is incomplete")
80
+ workers = value.get("workers")
81
+ if not isinstance(workers, list):
82
+ raise ValueError("causal discovery requires Worker evidence")
83
+ for worker in workers:
84
+ rows = worker.get("input_rows") if isinstance(worker, Mapping) else None
85
+ if not isinstance(rows, Mapping):
86
+ raise ValueError("causal discovery row evidence is missing")
87
+ if rows.get("coverage.discovery_rows") != rows.get("train"):
88
+ raise ValueError("causal discovery shard coverage drifted")
89
+ return value
90
+
91
+
92
+ __all__ = [
93
+ "DiscoveryCoverageValidator",
94
+ "DiscoveryInputValidator",
95
+ "DiscoveryOutputValidator",
96
+ "PCConfigValidator",
97
+ ]