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,1193 @@
1
+ """Exact distributed difference-in-means causal estimator."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ from collections.abc import Iterable, Mapping
9
+ from dataclasses import dataclass, field
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.training.algorithm_spec import AlgorithmSpec, Capability, ProblemType
33
+
34
+ _PACKAGE = "tributo-algorithms"
35
+ _VERSION = "0.1.0"
36
+ _STATE_SCHEMA = (
37
+ StateField("treated_count", "int64", ()),
38
+ StateField("control_count", "int64", ()),
39
+ StateField("treated_sum", "float64", ()),
40
+ StateField("control_sum", "float64", ()),
41
+ StateField("treated_sum_squares", "float64", ()),
42
+ StateField("control_sum_squares", "float64", ()),
43
+ StateField("row_count", "int64", ()),
44
+ )
45
+ _DML_STATE_SCHEMA = (
46
+ StateField("xtx", "float64", (None, None)),
47
+ StateField("xty", "float64", (None,)),
48
+ StateField("xtt", "float64", (None,)),
49
+ StateField("yty", "float64", ()),
50
+ StateField("ytt", "float64", ()),
51
+ StateField("ttt", "float64", ()),
52
+ StateField("treated_count", "int64", ()),
53
+ StateField("control_count", "int64", ()),
54
+ StateField("treated_sum", "float64", ()),
55
+ StateField("control_sum", "float64", ()),
56
+ StateField("row_count", "int64", ()),
57
+ StateField("fold_xtx", "float64", (None, None, None)),
58
+ StateField("fold_xty", "float64", (None, None)),
59
+ StateField("fold_xtt", "float64", (None, None)),
60
+ StateField("fold_yty", "float64", (None,)),
61
+ StateField("fold_ytt", "float64", (None,)),
62
+ StateField("fold_ttt", "float64", (None,)),
63
+ )
64
+ _IV_STATE_SCHEMA = (
65
+ StateField("xtx", "float64", (None, None)),
66
+ StateField("xty", "float64", (None,)),
67
+ StateField("xtt", "float64", (None,)),
68
+ StateField("xtz", "float64", (None,)),
69
+ StateField("yty", "float64", ()),
70
+ StateField("ytt", "float64", ()),
71
+ StateField("ttt", "float64", ()),
72
+ StateField("ytz", "float64", ()),
73
+ StateField("ttz", "float64", ()),
74
+ StateField("ztz", "float64", ()),
75
+ StateField("treated_count", "int64", ()),
76
+ StateField("control_count", "int64", ()),
77
+ StateField("treated_sum", "float64", ()),
78
+ StateField("control_sum", "float64", ()),
79
+ StateField("row_count", "int64", ()),
80
+ )
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class CausalATEModel:
85
+ method: str
86
+ treatment: str
87
+ outcome: str
88
+ feature_names: tuple[str, ...]
89
+ treated_count: int
90
+ control_count: int
91
+ treated_mean: float
92
+ control_mean: float
93
+ effect: float
94
+ standard_error: float
95
+ confidence_interval: tuple[float, float]
96
+ policy_cost: float
97
+ treat_all_policy: bool
98
+ diagnostics: Mapping[str, float] = field(default_factory=dict)
99
+
100
+ def report(self) -> dict[str, object]:
101
+ if self.standard_error > 0:
102
+ null_z_score = self.effect / self.standard_error
103
+ null_p_value = math.erfc(abs(null_z_score) / math.sqrt(2.0))
104
+ signal_to_noise = abs(null_z_score)
105
+ else:
106
+ null_z_score = None
107
+ null_p_value = 0.0 if self.effect else 1.0
108
+ signal_to_noise = None
109
+ return {
110
+ "api_version": 1,
111
+ "problem": {
112
+ "treatment": self.treatment,
113
+ "outcome": self.outcome,
114
+ "estimand": "ATE",
115
+ "assumptions": [
116
+ "consistency",
117
+ "exchangeability_or_random_assignment",
118
+ "positivity",
119
+ ],
120
+ },
121
+ "estimate": {
122
+ "method": self.method,
123
+ "effect": self.effect,
124
+ "standard_error": self.standard_error,
125
+ "confidence_interval": list(self.confidence_interval),
126
+ "treated_mean": self.treated_mean,
127
+ "control_mean": self.control_mean,
128
+ },
129
+ "coverage": {
130
+ "treated": self.treated_count,
131
+ "control": self.control_count,
132
+ },
133
+ "policy": {
134
+ "cost": self.policy_cost,
135
+ "treat_all": self.treat_all_policy,
136
+ },
137
+ "refutation": {
138
+ "method": "analytic_null_effect",
139
+ "null_effect": 0.0,
140
+ "z_score": null_z_score,
141
+ "two_sided_normal_p_value": null_p_value,
142
+ "rejects_null_at_0_05": null_p_value < 0.05,
143
+ },
144
+ "sensitivity": {
145
+ "method": "estimate_to_standard_error_ratio",
146
+ "signal_to_noise": signal_to_noise,
147
+ },
148
+ "diagnostics": dict(sorted(self.diagnostics.items())),
149
+ }
150
+
151
+
152
+ class DifferenceInMeansATE(
153
+ MapReduceAlgorithm[Mapping[str, object], Mapping[str, object], CausalATEModel]
154
+ ):
155
+ """Merge exact treated/control sufficient statistics across Ray Workers."""
156
+
157
+ def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
158
+ self.plan = plan
159
+ binding = plan.primary_input_binding
160
+ self.treatment = str(plan.algorithm_config["treatment_col"])
161
+ self.outcome = binding.label_name or ""
162
+ self.feature_names = binding.feature_names
163
+ if not self.outcome or self.treatment not in self.feature_names:
164
+ raise AlgorithmConfigurationError(
165
+ "ATE InputBinding must contain treatment and outcome columns"
166
+ )
167
+
168
+ def map_partition(
169
+ self,
170
+ batches: Iterable[Mapping[str, object]],
171
+ context: AlgorithmExecutionContext,
172
+ ) -> Mapping[str, object]:
173
+ del context
174
+ import numpy as np
175
+
176
+ state = self.empty_partition()
177
+ for batch in batches:
178
+ if self.treatment not in batch or self.outcome not in batch:
179
+ raise AlgorithmInputError(
180
+ "causal batch is missing treatment or outcome"
181
+ )
182
+ treatment = np.asarray(batch[self.treatment])
183
+ outcome = np.asarray(batch[self.outcome], dtype=np.float64)
184
+ if (
185
+ treatment.ndim != 1
186
+ or outcome.ndim != 1
187
+ or treatment.shape != outcome.shape
188
+ ):
189
+ raise AlgorithmInputError("causal treatment and outcome rows disagree")
190
+ if not np.isfinite(outcome).all() or not np.isin(treatment, (0, 1)).all():
191
+ raise AlgorithmInputError(
192
+ "causal outcome must be finite and treatment must be binary"
193
+ )
194
+ treated = outcome[treatment == 1]
195
+ control = outcome[treatment == 0]
196
+ state = self.merge_states(
197
+ state,
198
+ {
199
+ "treated_count": np.asarray(treated.size, dtype=np.int64),
200
+ "control_count": np.asarray(control.size, dtype=np.int64),
201
+ "treated_sum": np.asarray(treated.sum(), dtype=np.float64),
202
+ "control_sum": np.asarray(control.sum(), dtype=np.float64),
203
+ "treated_sum_squares": np.asarray(
204
+ (treated**2).sum(), dtype=np.float64
205
+ ),
206
+ "control_sum_squares": np.asarray(
207
+ (control**2).sum(), dtype=np.float64
208
+ ),
209
+ "row_count": np.asarray(outcome.size, dtype=np.int64),
210
+ },
211
+ )
212
+ return state
213
+
214
+ def merge_states(
215
+ self,
216
+ left: Mapping[str, object],
217
+ right: Mapping[str, object],
218
+ ) -> Mapping[str, object]:
219
+ import numpy as np
220
+
221
+ return {
222
+ field.name: np.asarray(
223
+ np.asarray(left[field.name], dtype=field.dtype)
224
+ + np.asarray(right[field.name], dtype=field.dtype),
225
+ dtype=field.dtype,
226
+ )
227
+ for field in _STATE_SCHEMA
228
+ }
229
+
230
+ def finalize_model(self, state: Mapping[str, object]) -> CausalATEModel:
231
+ import numpy as np
232
+
233
+ treated_count = int(np.asarray(state["treated_count"]))
234
+ control_count = int(np.asarray(state["control_count"]))
235
+ if treated_count < 2 or control_count < 2:
236
+ raise AlgorithmInputError(
237
+ "ATE requires at least two treated and two control observations"
238
+ )
239
+ treated_sum = float(np.asarray(state["treated_sum"]))
240
+ control_sum = float(np.asarray(state["control_sum"]))
241
+ treated_mean = treated_sum / treated_count
242
+ control_mean = control_sum / control_count
243
+ treated_variance = max(
244
+ 0.0,
245
+ (
246
+ float(np.asarray(state["treated_sum_squares"]))
247
+ - treated_count * treated_mean**2
248
+ )
249
+ / (treated_count - 1),
250
+ )
251
+ control_variance = max(
252
+ 0.0,
253
+ (
254
+ float(np.asarray(state["control_sum_squares"]))
255
+ - control_count * control_mean**2
256
+ )
257
+ / (control_count - 1),
258
+ )
259
+ effect = treated_mean - control_mean
260
+ standard_error = math.sqrt(
261
+ treated_variance / treated_count + control_variance / control_count
262
+ )
263
+ z = float(self.plan.algorithm_config.get("confidence_z", 1.959963984540054))
264
+ policy_cost = float(self.plan.algorithm_config.get("policy_cost", 0.0))
265
+ return CausalATEModel(
266
+ method="distributed_difference_in_means",
267
+ treatment=self.treatment,
268
+ outcome=self.outcome,
269
+ feature_names=self.feature_names,
270
+ treated_count=treated_count,
271
+ control_count=control_count,
272
+ treated_mean=treated_mean,
273
+ control_mean=control_mean,
274
+ effect=effect,
275
+ standard_error=standard_error,
276
+ confidence_interval=(
277
+ effect - z * standard_error,
278
+ effect + z * standard_error,
279
+ ),
280
+ policy_cost=policy_cost,
281
+ treat_all_policy=effect > policy_cost,
282
+ )
283
+
284
+ def state_schema(self) -> tuple[StateField, ...]:
285
+ return _STATE_SCHEMA
286
+
287
+ def empty_partition(self) -> Mapping[str, object]:
288
+ import numpy as np
289
+
290
+ return {field.name: np.asarray(0, dtype=field.dtype) for field in _STATE_SCHEMA}
291
+
292
+ def coverage_counts(self, state: Mapping[str, object]) -> Mapping[str, int]:
293
+ import numpy as np
294
+
295
+ return {
296
+ "treated": int(np.asarray(state["treated_count"])),
297
+ "control": int(np.asarray(state["control_count"])),
298
+ }
299
+
300
+ @property
301
+ def retry_safe(self) -> bool:
302
+ return True
303
+
304
+
305
+ class LinearDMLATE(
306
+ MapReduceAlgorithm[Mapping[str, object], Mapping[str, object], CausalATEModel]
307
+ ):
308
+ """Estimate a partially linear ATE from distributed normal equations."""
309
+
310
+ def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
311
+ self.plan = plan
312
+ binding = plan.primary_input_binding
313
+ self.treatment = str(plan.algorithm_config["treatment_col"])
314
+ self.outcome = binding.label_name or ""
315
+ self.feature_names = binding.feature_names
316
+ self.fold_count = int(self.plan.algorithm_config.get("cross_fit_folds", 5))
317
+ if self.fold_count < 1 or self.fold_count > 20:
318
+ raise AlgorithmConfigurationError(
319
+ "cross_fit_folds must be between 1 and 20"
320
+ )
321
+ self.fold_column = self.plan.algorithm_config.get("fold_column")
322
+ if self.fold_column is not None and not isinstance(self.fold_column, str):
323
+ raise AlgorithmConfigurationError("fold_column must be a string")
324
+ self.confounders = tuple(
325
+ name
326
+ for name in self.feature_names
327
+ if name != self.treatment and name != self.fold_column
328
+ )
329
+ if not self.outcome or self.treatment not in self.feature_names:
330
+ raise AlgorithmConfigurationError(
331
+ "Linear DML requires treatment features and outcome label"
332
+ )
333
+
334
+ def map_partition(
335
+ self,
336
+ batches: Iterable[Mapping[str, object]],
337
+ context: AlgorithmExecutionContext,
338
+ ) -> Mapping[str, object]:
339
+ del context
340
+ import numpy as np
341
+
342
+ state = self.empty_partition()
343
+ for batch in batches:
344
+ required = (*self.confounders, self.treatment, self.outcome)
345
+ if self.fold_column is not None:
346
+ required = (*required, self.fold_column)
347
+ missing = [name for name in required if name not in batch]
348
+ if missing:
349
+ raise AlgorithmInputError(f"Linear DML batch is missing: {missing}")
350
+ treatment = np.asarray(batch[self.treatment], dtype=np.float64)
351
+ outcome = np.asarray(batch[self.outcome], dtype=np.float64)
352
+ confounders = (
353
+ np.column_stack(
354
+ [
355
+ np.asarray(batch[name], dtype=np.float64)
356
+ for name in self.confounders
357
+ ]
358
+ )
359
+ if self.confounders
360
+ else np.empty((outcome.size, 0), dtype=np.float64)
361
+ )
362
+ design = np.column_stack(
363
+ [np.ones(outcome.size, dtype=np.float64), confounders]
364
+ )
365
+ if (
366
+ treatment.ndim != 1
367
+ or outcome.ndim != 1
368
+ or design.shape[0] != outcome.size
369
+ or treatment.shape != outcome.shape
370
+ or not np.isfinite(design).all()
371
+ or not np.isfinite(outcome).all()
372
+ or not np.isin(treatment, (0.0, 1.0)).all()
373
+ ):
374
+ raise AlgorithmInputError("Linear DML input is invalid")
375
+ treated = treatment == 1
376
+ control = ~treated
377
+ partial = {
378
+ "xtx": design.T @ design,
379
+ "xty": design.T @ outcome,
380
+ "xtt": design.T @ treatment,
381
+ "yty": np.asarray(outcome @ outcome, dtype=np.float64),
382
+ "ytt": np.asarray(outcome @ treatment, dtype=np.float64),
383
+ "ttt": np.asarray(treatment @ treatment, dtype=np.float64),
384
+ "treated_count": np.asarray(treated.sum(), dtype=np.int64),
385
+ "control_count": np.asarray(control.sum(), dtype=np.int64),
386
+ "treated_sum": np.asarray(outcome[treated].sum(), dtype=np.float64),
387
+ "control_sum": np.asarray(outcome[control].sum(), dtype=np.float64),
388
+ "row_count": np.asarray(outcome.size, dtype=np.int64),
389
+ }
390
+ if self.fold_count > 1:
391
+ fold_values = (
392
+ np.asarray(batch[self.fold_column])
393
+ if self.fold_column is not None and self.fold_column in batch
394
+ else np.floor(
395
+ np.abs(
396
+ np.sum(
397
+ np.column_stack(
398
+ [
399
+ treatment,
400
+ *[
401
+ np.asarray(batch[name], dtype=np.float64)
402
+ for name in self.confounders
403
+ ],
404
+ ]
405
+ )
406
+ * np.arange(1, len(self.confounders) + 2),
407
+ axis=1,
408
+ )
409
+ * 1_000_003
410
+ )
411
+ ).astype(np.int64)
412
+ )
413
+ if self.fold_column is not None:
414
+ try:
415
+ fold_values = np.asarray(fold_values, dtype=np.int64)
416
+ except (TypeError, ValueError):
417
+ fold_values = np.asarray(
418
+ [
419
+ int(
420
+ hashlib.sha256(
421
+ str(value).encode("utf-8")
422
+ ).hexdigest(),
423
+ 16,
424
+ )
425
+ for value in fold_values
426
+ ],
427
+ dtype=np.int64,
428
+ )
429
+ fold_values %= self.fold_count
430
+ width = design.shape[1]
431
+ fold_xtx = np.zeros((self.fold_count, width, width), dtype=np.float64)
432
+ fold_xty = np.zeros((self.fold_count, width), dtype=np.float64)
433
+ fold_xtt = np.zeros((self.fold_count, width), dtype=np.float64)
434
+ fold_yty = np.zeros(self.fold_count, dtype=np.float64)
435
+ fold_ytt = np.zeros(self.fold_count, dtype=np.float64)
436
+ fold_ttt = np.zeros(self.fold_count, dtype=np.float64)
437
+ for fold in range(self.fold_count):
438
+ selected = fold_values == fold
439
+ fold_design = design[selected]
440
+ fold_outcome = outcome[selected]
441
+ fold_treatment = treatment[selected]
442
+ fold_xtx[fold] = fold_design.T @ fold_design
443
+ fold_xty[fold] = fold_design.T @ fold_outcome
444
+ fold_xtt[fold] = fold_design.T @ fold_treatment
445
+ fold_yty[fold] = fold_outcome @ fold_outcome
446
+ fold_ytt[fold] = fold_outcome @ fold_treatment
447
+ fold_ttt[fold] = fold_treatment @ fold_treatment
448
+ partial.update(
449
+ {
450
+ "fold_xtx": fold_xtx,
451
+ "fold_xty": fold_xty,
452
+ "fold_xtt": fold_xtt,
453
+ "fold_yty": fold_yty,
454
+ "fold_ytt": fold_ytt,
455
+ "fold_ttt": fold_ttt,
456
+ }
457
+ )
458
+ else:
459
+ width = design.shape[1]
460
+ partial.update(
461
+ {
462
+ "fold_xtx": np.zeros((1, width, width), dtype=np.float64),
463
+ "fold_xty": np.zeros((1, width), dtype=np.float64),
464
+ "fold_xtt": np.zeros((1, width), dtype=np.float64),
465
+ "fold_yty": np.zeros(1, dtype=np.float64),
466
+ "fold_ytt": np.zeros(1, dtype=np.float64),
467
+ "fold_ttt": np.zeros(1, dtype=np.float64),
468
+ }
469
+ )
470
+ state = self.merge_states(state, partial)
471
+ return state
472
+
473
+ def merge_states(
474
+ self,
475
+ left: Mapping[str, object],
476
+ right: Mapping[str, object],
477
+ ) -> Mapping[str, object]:
478
+ import numpy as np
479
+
480
+ return {
481
+ field.name: np.asarray(
482
+ np.asarray(left[field.name], dtype=field.dtype)
483
+ + np.asarray(right[field.name], dtype=field.dtype),
484
+ dtype=field.dtype,
485
+ )
486
+ for field in _DML_STATE_SCHEMA
487
+ }
488
+
489
+ def finalize_model(self, state: Mapping[str, object]) -> CausalATEModel:
490
+ import numpy as np
491
+
492
+ xtx = np.asarray(state["xtx"], dtype=np.float64)
493
+ xty = np.asarray(state["xty"], dtype=np.float64)
494
+ xtt = np.asarray(state["xtt"], dtype=np.float64)
495
+ inverse = np.linalg.pinv(xtx)
496
+ if self.fold_count > 1 and "fold_xtx" in state:
497
+ fold_xtx = np.asarray(state["fold_xtx"], dtype=np.float64)
498
+ fold_xty = np.asarray(state["fold_xty"], dtype=np.float64)
499
+ fold_xtt = np.asarray(state["fold_xtt"], dtype=np.float64)
500
+ fold_yty = np.asarray(state["fold_yty"], dtype=np.float64)
501
+ fold_ytt = np.asarray(state["fold_ytt"], dtype=np.float64)
502
+ fold_ttt = np.asarray(state["fold_ttt"], dtype=np.float64)
503
+ residual_yt = 0.0
504
+ residual_tt = 0.0
505
+ residual_yy = 0.0
506
+ for fold in range(self.fold_count):
507
+ if not np.any(fold_xtx[fold]):
508
+ raise AlgorithmInputError(
509
+ "Linear DML cross-fitting produced an empty fold"
510
+ )
511
+ train_xtx = xtx - fold_xtx[fold]
512
+ train_xty = xty - fold_xty[fold]
513
+ train_xtt = xtt - fold_xtt[fold]
514
+ nuisance_inverse = np.linalg.pinv(train_xtx)
515
+ beta_y = nuisance_inverse @ train_xty
516
+ beta_t = nuisance_inverse @ train_xtt
517
+ residual_yt += float(
518
+ fold_ytt[fold]
519
+ - beta_t @ fold_xty[fold]
520
+ - beta_y @ fold_xtt[fold]
521
+ + beta_t @ fold_xtx[fold] @ beta_y
522
+ )
523
+ residual_tt += float(
524
+ fold_ttt[fold]
525
+ - 2 * beta_t @ fold_xtt[fold]
526
+ + beta_t @ fold_xtx[fold] @ beta_t
527
+ )
528
+ residual_yy += float(
529
+ fold_yty[fold]
530
+ - 2 * beta_y @ fold_xty[fold]
531
+ + beta_y @ fold_xtx[fold] @ beta_y
532
+ )
533
+ else:
534
+ residual_yt = float(np.asarray(state["ytt"])) - float(xtt @ inverse @ xty)
535
+ residual_tt = float(np.asarray(state["ttt"])) - float(xtt @ inverse @ xtt)
536
+ residual_yy = float(np.asarray(state["yty"])) - float(xty @ inverse @ xty)
537
+ if residual_tt <= 1e-12:
538
+ raise AlgorithmInputError("Linear DML treatment residual has no overlap")
539
+ effect = residual_yt / residual_tt
540
+ row_count = int(np.asarray(state["row_count"]))
541
+ degrees = max(1, row_count - xtx.shape[0] - 1)
542
+ residual_variance = max(
543
+ 0.0,
544
+ (residual_yy - 2 * effect * residual_yt + effect**2 * residual_tt)
545
+ / degrees,
546
+ )
547
+ standard_error = math.sqrt(residual_variance / residual_tt)
548
+ treated_count = int(np.asarray(state["treated_count"]))
549
+ control_count = int(np.asarray(state["control_count"]))
550
+ if treated_count < 2 or control_count < 2:
551
+ raise AlgorithmInputError("Linear DML requires treatment overlap")
552
+ treated_mean = float(np.asarray(state["treated_sum"])) / treated_count
553
+ control_mean = float(np.asarray(state["control_sum"])) / control_count
554
+ z = float(self.plan.algorithm_config.get("confidence_z", 1.959963984540054))
555
+ policy_cost = float(self.plan.algorithm_config.get("policy_cost", 0.0))
556
+ return CausalATEModel(
557
+ method="distributed_linear_dml",
558
+ treatment=self.treatment,
559
+ outcome=self.outcome,
560
+ feature_names=self.feature_names,
561
+ treated_count=treated_count,
562
+ control_count=control_count,
563
+ treated_mean=treated_mean,
564
+ control_mean=control_mean,
565
+ effect=effect,
566
+ standard_error=standard_error,
567
+ confidence_interval=(
568
+ effect - z * standard_error,
569
+ effect + z * standard_error,
570
+ ),
571
+ policy_cost=policy_cost,
572
+ treat_all_policy=effect > policy_cost,
573
+ diagnostics={"cross_fit_folds": float(self.fold_count)},
574
+ )
575
+
576
+ def state_schema(self) -> tuple[StateField, ...]:
577
+ return _DML_STATE_SCHEMA
578
+
579
+ def empty_partition(self) -> Mapping[str, object]:
580
+ import numpy as np
581
+
582
+ width = len(self.confounders) + 1
583
+ return {
584
+ "xtx": np.zeros((width, width), dtype=np.float64),
585
+ "xty": np.zeros(width, dtype=np.float64),
586
+ "xtt": np.zeros(width, dtype=np.float64),
587
+ **{
588
+ field.name: np.asarray(0, dtype=field.dtype)
589
+ for field in _DML_STATE_SCHEMA
590
+ if field.name not in {"xtx", "xty", "xtt"}
591
+ },
592
+ "fold_xtx": np.zeros((self.fold_count, width, width), dtype=np.float64),
593
+ "fold_xty": np.zeros((self.fold_count, width), dtype=np.float64),
594
+ "fold_xtt": np.zeros((self.fold_count, width), dtype=np.float64),
595
+ "fold_yty": np.zeros(self.fold_count, dtype=np.float64),
596
+ "fold_ytt": np.zeros(self.fold_count, dtype=np.float64),
597
+ "fold_ttt": np.zeros(self.fold_count, dtype=np.float64),
598
+ }
599
+
600
+ def coverage_counts(self, state: Mapping[str, object]) -> Mapping[str, int]:
601
+ import numpy as np
602
+
603
+ return {
604
+ "treated": int(np.asarray(state["treated_count"])),
605
+ "control": int(np.asarray(state["control_count"])),
606
+ }
607
+
608
+ @property
609
+ def retry_safe(self) -> bool:
610
+ return True
611
+
612
+
613
+ class LinearIVATE(
614
+ MapReduceAlgorithm[Mapping[str, object], Mapping[str, object], CausalATEModel]
615
+ ):
616
+ """Estimate a just-identified linear IV effect from distributed moments."""
617
+
618
+ def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
619
+ self.plan = plan
620
+ binding = plan.primary_input_binding
621
+ self.treatment = str(plan.algorithm_config["treatment_col"])
622
+ self.instrument = str(plan.algorithm_config["instrument_col"])
623
+ self.outcome = binding.label_name or ""
624
+ self.feature_names = binding.feature_names
625
+ self.confounders = tuple(
626
+ name
627
+ for name in self.feature_names
628
+ if name not in {self.treatment, self.instrument}
629
+ )
630
+ if (
631
+ not self.outcome
632
+ or self.treatment not in self.feature_names
633
+ or self.instrument not in self.feature_names
634
+ ):
635
+ raise AlgorithmConfigurationError(
636
+ "Linear IV requires treatment, instrument, and outcome"
637
+ )
638
+
639
+ def map_partition(
640
+ self,
641
+ batches: Iterable[Mapping[str, object]],
642
+ context: AlgorithmExecutionContext,
643
+ ) -> Mapping[str, object]:
644
+ del context
645
+ import numpy as np
646
+
647
+ state = self.empty_partition()
648
+ for batch in batches:
649
+ required = (
650
+ *self.confounders,
651
+ self.treatment,
652
+ self.instrument,
653
+ self.outcome,
654
+ )
655
+ missing = [name for name in required if name not in batch]
656
+ if missing:
657
+ raise AlgorithmInputError(f"Linear IV batch is missing: {missing}")
658
+ treatment = np.asarray(batch[self.treatment], dtype=np.float64)
659
+ instrument = np.asarray(batch[self.instrument], dtype=np.float64)
660
+ outcome = np.asarray(batch[self.outcome], dtype=np.float64)
661
+ confounders = (
662
+ np.column_stack(
663
+ [
664
+ np.asarray(batch[name], dtype=np.float64)
665
+ for name in self.confounders
666
+ ]
667
+ )
668
+ if self.confounders
669
+ else np.empty((outcome.size, 0), dtype=np.float64)
670
+ )
671
+ design = np.column_stack(
672
+ [np.ones(outcome.size, dtype=np.float64), confounders]
673
+ )
674
+ if (
675
+ treatment.ndim != 1
676
+ or instrument.ndim != 1
677
+ or outcome.ndim != 1
678
+ or treatment.shape != outcome.shape
679
+ or instrument.shape != outcome.shape
680
+ or not np.isfinite(design).all()
681
+ or not np.isfinite(outcome).all()
682
+ or not np.isfinite(instrument).all()
683
+ or not np.isin(treatment, (0.0, 1.0)).all()
684
+ ):
685
+ raise AlgorithmInputError("Linear IV input is invalid")
686
+ treated = treatment == 1
687
+ control = ~treated
688
+ partial = {
689
+ "xtx": design.T @ design,
690
+ "xty": design.T @ outcome,
691
+ "xtt": design.T @ treatment,
692
+ "xtz": design.T @ instrument,
693
+ "yty": np.asarray(outcome @ outcome, dtype=np.float64),
694
+ "ytt": np.asarray(outcome @ treatment, dtype=np.float64),
695
+ "ttt": np.asarray(treatment @ treatment, dtype=np.float64),
696
+ "ytz": np.asarray(outcome @ instrument, dtype=np.float64),
697
+ "ttz": np.asarray(treatment @ instrument, dtype=np.float64),
698
+ "ztz": np.asarray(instrument @ instrument, dtype=np.float64),
699
+ "treated_count": np.asarray(treated.sum(), dtype=np.int64),
700
+ "control_count": np.asarray(control.sum(), dtype=np.int64),
701
+ "treated_sum": np.asarray(outcome[treated].sum(), dtype=np.float64),
702
+ "control_sum": np.asarray(outcome[control].sum(), dtype=np.float64),
703
+ "row_count": np.asarray(outcome.size, dtype=np.int64),
704
+ }
705
+ state = self.merge_states(state, partial)
706
+ return state
707
+
708
+ def merge_states(
709
+ self,
710
+ left: Mapping[str, object],
711
+ right: Mapping[str, object],
712
+ ) -> Mapping[str, object]:
713
+ import numpy as np
714
+
715
+ return {
716
+ item.name: np.asarray(
717
+ np.asarray(left[item.name], dtype=item.dtype)
718
+ + np.asarray(right[item.name], dtype=item.dtype),
719
+ dtype=item.dtype,
720
+ )
721
+ for item in _IV_STATE_SCHEMA
722
+ }
723
+
724
+ def finalize_model(self, state: Mapping[str, object]) -> CausalATEModel:
725
+ import numpy as np
726
+
727
+ xtx = np.asarray(state["xtx"], dtype=np.float64)
728
+ xty = np.asarray(state["xty"], dtype=np.float64)
729
+ xtt = np.asarray(state["xtt"], dtype=np.float64)
730
+ xtz = np.asarray(state["xtz"], dtype=np.float64)
731
+ inverse = np.linalg.pinv(xtx)
732
+ yz = float(np.asarray(state["ytz"])) - float(xtz @ inverse @ xty)
733
+ tz = float(np.asarray(state["ttz"])) - float(xtz @ inverse @ xtt)
734
+ zz = float(np.asarray(state["ztz"])) - float(xtz @ inverse @ xtz)
735
+ tt = float(np.asarray(state["ttt"])) - float(xtt @ inverse @ xtt)
736
+ if abs(tz) <= 1e-12 or zz <= 1e-12 or tt <= 1e-12:
737
+ raise AlgorithmInputError("Linear IV has a weak or degenerate instrument")
738
+ effect = yz / tz
739
+ yy = float(np.asarray(state["yty"])) - float(xty @ inverse @ xty)
740
+ yt = float(np.asarray(state["ytt"])) - float(xtt @ inverse @ xty)
741
+ row_count = int(np.asarray(state["row_count"]))
742
+ degrees = max(1, row_count - xtx.shape[0] - 1)
743
+ residual_variance = max(
744
+ 0.0,
745
+ (yy - 2 * effect * yt + effect**2 * tt) / degrees,
746
+ )
747
+ standard_error = math.sqrt(residual_variance * zz / (tz**2))
748
+ first_stage_correlation = tz / math.sqrt(zz * tt)
749
+ treated_count = int(np.asarray(state["treated_count"]))
750
+ control_count = int(np.asarray(state["control_count"]))
751
+ if treated_count < 2 or control_count < 2:
752
+ raise AlgorithmInputError("Linear IV requires treatment overlap")
753
+ treated_mean = float(np.asarray(state["treated_sum"])) / treated_count
754
+ control_mean = float(np.asarray(state["control_sum"])) / control_count
755
+ z_value = float(
756
+ self.plan.algorithm_config.get("confidence_z", 1.959963984540054)
757
+ )
758
+ policy_cost = float(self.plan.algorithm_config.get("policy_cost", 0.0))
759
+ return CausalATEModel(
760
+ method="distributed_linear_2sls",
761
+ treatment=self.treatment,
762
+ outcome=self.outcome,
763
+ feature_names=self.feature_names,
764
+ treated_count=treated_count,
765
+ control_count=control_count,
766
+ treated_mean=treated_mean,
767
+ control_mean=control_mean,
768
+ effect=effect,
769
+ standard_error=standard_error,
770
+ confidence_interval=(
771
+ effect - z_value * standard_error,
772
+ effect + z_value * standard_error,
773
+ ),
774
+ policy_cost=policy_cost,
775
+ treat_all_policy=effect > policy_cost,
776
+ diagnostics={
777
+ "first_stage_correlation": first_stage_correlation,
778
+ "residualized_instrument_variance": zz,
779
+ },
780
+ )
781
+
782
+ def state_schema(self) -> tuple[StateField, ...]:
783
+ return _IV_STATE_SCHEMA
784
+
785
+ def empty_partition(self) -> Mapping[str, object]:
786
+ import numpy as np
787
+
788
+ width = len(self.confounders) + 1
789
+ return {
790
+ "xtx": np.zeros((width, width), dtype=np.float64),
791
+ "xty": np.zeros(width, dtype=np.float64),
792
+ "xtt": np.zeros(width, dtype=np.float64),
793
+ "xtz": np.zeros(width, dtype=np.float64),
794
+ **{
795
+ item.name: np.asarray(0, dtype=item.dtype)
796
+ for item in _IV_STATE_SCHEMA
797
+ if item.name not in {"xtx", "xty", "xtt", "xtz"}
798
+ },
799
+ }
800
+
801
+ def coverage_counts(self, state: Mapping[str, object]) -> Mapping[str, int]:
802
+ import numpy as np
803
+
804
+ return {
805
+ "treated": int(np.asarray(state["treated_count"])),
806
+ "control": int(np.asarray(state["control_count"])),
807
+ }
808
+
809
+ @property
810
+ def retry_safe(self) -> bool:
811
+ return True
812
+
813
+
814
+ def create_algorithm(
815
+ *,
816
+ plan: ResolvedAlgorithmPlan,
817
+ implementation: object,
818
+ artifacts: tuple[object, ...],
819
+ ) -> DifferenceInMeansATE | LinearDMLATE | LinearIVATE:
820
+ del artifacts
821
+ if implementation is DifferenceInMeansATE:
822
+ return DifferenceInMeansATE(plan)
823
+ if implementation is LinearDMLATE:
824
+ return LinearDMLATE(plan)
825
+ if implementation is LinearIVATE:
826
+ return LinearIVATE(plan)
827
+ raise AlgorithmConfigurationError("causal implementation identity drifted")
828
+
829
+
830
+ def export_model(
831
+ *,
832
+ model: CausalATEModel,
833
+ plan: ResolvedAlgorithmPlan,
834
+ run_id: str | None = None,
835
+ ) -> AlgorithmExecutionResult:
836
+ import numpy as np
837
+ from skl2onnx import convert_sklearn
838
+ from skl2onnx.common.data_types import FloatTensorType
839
+ from sklearn import __version__ as sklearn_version
840
+ from sklearn.linear_model import LinearRegression
841
+ from tributo.exporting.models import (
842
+ BundleOutputConfig,
843
+ CheckpointField,
844
+ ExportCheckpointV1,
845
+ ExportSource,
846
+ ExportTarget,
847
+ )
848
+ from tributo.exporting.service import BundleExportService
849
+
850
+ if not isinstance(model, CausalATEModel):
851
+ raise AlgorithmExecutionError("causal exporter received an invalid model")
852
+ estimator = LinearRegression().fit(
853
+ np.zeros((2, len(model.feature_names)), dtype=np.float32),
854
+ np.full(2, model.effect, dtype=np.float32),
855
+ )
856
+ converted = convert_sklearn(
857
+ estimator,
858
+ initial_types=[
859
+ ("float_input", FloatTensorType([None, len(model.feature_names)]))
860
+ ],
861
+ target_opset=18,
862
+ )
863
+ payload = converted.SerializeToString()
864
+ report = model.report()
865
+ report_payload = json.dumps(report, sort_keys=True).encode("utf-8")
866
+ report_artifact = ArtifactDraft.from_payload(
867
+ name="causal-report",
868
+ kind="report",
869
+ format="application/json",
870
+ payload=report_payload,
871
+ )
872
+ output = plan.algorithm_config.get("output")
873
+ if not isinstance(output, Mapping) or not isinstance(output.get("bundle_uri"), str):
874
+ raise AlgorithmConfigurationError("causal output.bundle_uri is required")
875
+ source = ExportSource(
876
+ source_kind="prebuilt_onnx",
877
+ model_object=payload,
878
+ architecture_id=plan.resolution.algorithm,
879
+ feature_schema={"feature_names": list(model.feature_names)},
880
+ metadata={
881
+ "framework": "sklearn",
882
+ "framework_version": sklearn_version,
883
+ "framework_versions": {"scikit-learn": sklearn_version},
884
+ "task_type": "causal_effect_estimation",
885
+ "causal_study": report,
886
+ "producer_distribution": _PACKAGE,
887
+ },
888
+ source_fingerprint=report_artifact.sha256,
889
+ checkpoint_contract=ExportCheckpointV1(
890
+ trainer_type="causal_ate",
891
+ architecture_id=plan.resolution.algorithm,
892
+ input_schema=(
893
+ CheckpointField(
894
+ name="float_input",
895
+ dtype="float32",
896
+ shape=("batch", len(model.feature_names)),
897
+ ),
898
+ ),
899
+ output_schema=(
900
+ CheckpointField(
901
+ name="variable",
902
+ dtype="float32",
903
+ shape=("batch", 1),
904
+ ),
905
+ ),
906
+ preprocessing={"type": "none"},
907
+ task_type="causal_effect_estimation",
908
+ framework="sklearn",
909
+ framework_version=sklearn_version,
910
+ checkpoint_format_version=1,
911
+ ),
912
+ )
913
+ bundle = BundleExportService().export_bundle(
914
+ source,
915
+ BundleOutputConfig(
916
+ bundle_uri=str(output["bundle_uri"]),
917
+ request_id=run_id,
918
+ run_id=run_id,
919
+ targets=[
920
+ ExportTarget(
921
+ name="effect-model",
922
+ format="onnx",
923
+ exporter_id="prebuilt-onnx-v1",
924
+ ),
925
+ ExportTarget(
926
+ name="causal-report",
927
+ format="json",
928
+ exporter_id="official-causal-report-v1",
929
+ ),
930
+ ],
931
+ roles={"inference": "effect-model", "report": "causal-report"},
932
+ ),
933
+ )
934
+ return AlgorithmExecutionResult(
935
+ status="succeeded",
936
+ metrics={
937
+ "effect": model.effect,
938
+ "standard_error": model.standard_error,
939
+ "treated_count": model.treated_count,
940
+ "control_count": model.control_count,
941
+ },
942
+ outputs={
943
+ "bundle_id": bundle.bundle_id,
944
+ "bundle_uri": bundle.canonical_uri,
945
+ "execution_id": bundle.execution_id,
946
+ "manifest_sha256": bundle.manifest_sha256,
947
+ "report_artifact_sha256": report_artifact.sha256,
948
+ },
949
+ artifacts=(report_artifact,),
950
+ )
951
+
952
+
953
+ def _contract(contract_id: str, digest: str, validator: str) -> ContractBinding:
954
+ return ContractBinding(
955
+ contract_id=contract_id,
956
+ schema_version=1,
957
+ schema_digest=digest * 64,
958
+ validator_ref=QualifiedReference.parse(
959
+ f"tributo_algorithms_causal_core.contracts:{validator}"
960
+ ),
961
+ )
962
+
963
+
964
+ _SPEC = AlgorithmSpec(
965
+ name="difference_in_means_ate",
966
+ trainer_cls=None,
967
+ version="1.0.0",
968
+ default_config={},
969
+ supported_tasks=("fit",),
970
+ operations=("fit",),
971
+ problem_types=(ProblemType.CAUSAL_EFFECT_ESTIMATION,),
972
+ capabilities=(Capability.DISTRIBUTED, Capability.EXPORTABLE, Capability.TUNABLE),
973
+ learning_paradigm="causal_inference",
974
+ model_family="difference_in_means",
975
+ data_modalities=("tabular",),
976
+ lifecycle_kind="identify_estimate_policy",
977
+ allowed_execution_modes=(ExecutionMode.MAP_REDUCE.value,),
978
+ config_contract_ref="tributo.official.causal.ate.config.v1",
979
+ input_contract_ref="tributo.official.causal.binary-treatment.v1",
980
+ output_contract_ref="tributo.official.causal.report-bundle.v1",
981
+ )
982
+
983
+ _DML_SPEC = AlgorithmSpec(
984
+ name="linear_dml_ate",
985
+ trainer_cls=None,
986
+ version="1.0.0",
987
+ default_config={},
988
+ supported_tasks=("fit",),
989
+ operations=("fit",),
990
+ problem_types=(ProblemType.CAUSAL_EFFECT_ESTIMATION,),
991
+ capabilities=(Capability.DISTRIBUTED, Capability.EXPORTABLE, Capability.TUNABLE),
992
+ learning_paradigm="causal_inference",
993
+ model_family="linear_dml",
994
+ data_modalities=("tabular",),
995
+ lifecycle_kind="identify_crossfit_estimate_policy",
996
+ allowed_execution_modes=(ExecutionMode.MAP_REDUCE.value,),
997
+ config_contract_ref="tributo.official.causal.linear-dml.config.v1",
998
+ input_contract_ref="tributo.official.causal.binary-treatment.v1",
999
+ output_contract_ref="tributo.official.causal.report-bundle.v1",
1000
+ )
1001
+
1002
+ _IV_SPEC = AlgorithmSpec(
1003
+ name="linear_iv_ate",
1004
+ trainer_cls=None,
1005
+ version="1.0.0",
1006
+ default_config={},
1007
+ supported_tasks=("fit",),
1008
+ operations=("fit",),
1009
+ problem_types=(ProblemType.CAUSAL_EFFECT_ESTIMATION,),
1010
+ capabilities=(Capability.DISTRIBUTED, Capability.EXPORTABLE, Capability.TUNABLE),
1011
+ learning_paradigm="causal_inference",
1012
+ model_family="linear_instrumental_variables",
1013
+ data_modalities=("tabular",),
1014
+ lifecycle_kind="identify_first_stage_estimate_policy",
1015
+ allowed_execution_modes=(ExecutionMode.MAP_REDUCE.value,),
1016
+ config_contract_ref="tributo.official.causal.linear-iv.config.v1",
1017
+ input_contract_ref="tributo.official.causal.binary-treatment-instrument.v1",
1018
+ output_contract_ref="tributo.official.causal.report-bundle.v1",
1019
+ )
1020
+
1021
+ ATE_DESCRIPTOR = AlgorithmBuilder.from_distributed_algorithm(
1022
+ spec=_SPEC,
1023
+ implementation_id="tributo.official.causal.difference_in_means",
1024
+ implementation_version="1.0.0",
1025
+ implementation="tributo_algorithms_causal_core.algorithm:DifferenceInMeansATE",
1026
+ executable_factory="tributo_algorithms_causal_core.algorithm:create_algorithm",
1027
+ distribution=_PACKAGE,
1028
+ framework=None,
1029
+ environment=EnvironmentSpec(
1030
+ environment_id="tributo.official.causal-core.v1",
1031
+ dependencies=(
1032
+ "numpy>=2,<3",
1033
+ "scikit-learn>=1.4,<2",
1034
+ "skl2onnx>=1.17",
1035
+ "tributo>=1.1",
1036
+ f"tributo-algorithms[causal-core]=={_VERSION}",
1037
+ ),
1038
+ ),
1039
+ allowed_config_keys=("confidence_z", "output", "policy_cost", "treatment_col"),
1040
+ strategy=DistributionStrategy.RAY_MAP_REDUCE,
1041
+ supported_worker_range=WorkerRange(2, 256),
1042
+ supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
1043
+ resources_per_worker=WorkerResources(num_cpus=1),
1044
+ policy=MapReducePolicy(
1045
+ state_schema=_STATE_SCHEMA,
1046
+ max_partial_state_bytes=4096,
1047
+ reducer_ref=(
1048
+ "tributo_algorithms_causal_core.algorithm:DifferenceInMeansATE.merge_states"
1049
+ ),
1050
+ finalizer_ref=(
1051
+ "tributo_algorithms_causal_core.algorithm:"
1052
+ "DifferenceInMeansATE.finalize_model"
1053
+ ),
1054
+ commutative=True,
1055
+ max_retries=0,
1056
+ ),
1057
+ package_name=_PACKAGE,
1058
+ package_version=_VERSION,
1059
+ tributo_version_spec=">=1.1",
1060
+ exporter="tributo_algorithms_causal_core.algorithm:export_model",
1061
+ flavor_id="onnx-runtime-v1",
1062
+ contract_bindings=ContractBindingSet(
1063
+ config=_contract(_SPEC.config_contract_ref or "", "6", "ATEConfigValidator"),
1064
+ input=_contract(_SPEC.input_contract_ref or "", "2", "CausalInputValidator"),
1065
+ output=_contract(_SPEC.output_contract_ref or "", "3", "CausalOutputValidator"),
1066
+ coverage=_contract(
1067
+ "tributo.official.causal.treatment-coverage.v1",
1068
+ "4",
1069
+ "TreatmentCoverageValidator",
1070
+ ),
1071
+ ),
1072
+ descriptor_api_version=2,
1073
+ is_default=True,
1074
+ )
1075
+
1076
+ LINEAR_DML_DESCRIPTOR = AlgorithmBuilder.from_distributed_algorithm(
1077
+ spec=_DML_SPEC,
1078
+ implementation_id="tributo.official.causal.linear_dml",
1079
+ implementation_version="1.0.0",
1080
+ implementation="tributo_algorithms_causal_core.algorithm:LinearDMLATE",
1081
+ executable_factory="tributo_algorithms_causal_core.algorithm:create_algorithm",
1082
+ distribution=_PACKAGE,
1083
+ framework=None,
1084
+ environment=ATE_DESCRIPTOR.registration.environment,
1085
+ allowed_config_keys=(
1086
+ "confidence_z",
1087
+ "cross_fit_folds",
1088
+ "fold_column",
1089
+ "output",
1090
+ "policy_cost",
1091
+ "treatment_col",
1092
+ ),
1093
+ strategy=DistributionStrategy.RAY_MAP_REDUCE,
1094
+ supported_worker_range=WorkerRange(2, 256),
1095
+ supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
1096
+ resources_per_worker=WorkerResources(num_cpus=1),
1097
+ policy=MapReducePolicy(
1098
+ state_schema=_DML_STATE_SCHEMA,
1099
+ max_partial_state_bytes=64 * 1024 * 1024,
1100
+ reducer_ref=(
1101
+ "tributo_algorithms_causal_core.algorithm:LinearDMLATE.merge_states"
1102
+ ),
1103
+ finalizer_ref=(
1104
+ "tributo_algorithms_causal_core.algorithm:LinearDMLATE.finalize_model"
1105
+ ),
1106
+ commutative=True,
1107
+ max_retries=0,
1108
+ ),
1109
+ package_name=_PACKAGE,
1110
+ package_version=_VERSION,
1111
+ tributo_version_spec=">=1.1",
1112
+ exporter="tributo_algorithms_causal_core.algorithm:export_model",
1113
+ flavor_id="onnx-runtime-v1",
1114
+ contract_bindings=ContractBindingSet(
1115
+ config=_contract(
1116
+ _DML_SPEC.config_contract_ref or "", "6", "ATEConfigValidator"
1117
+ ),
1118
+ input=_contract(
1119
+ _DML_SPEC.input_contract_ref or "", "2", "CausalInputValidator"
1120
+ ),
1121
+ output=_contract(
1122
+ _DML_SPEC.output_contract_ref or "", "3", "CausalOutputValidator"
1123
+ ),
1124
+ coverage=_contract(
1125
+ "tributo.official.causal.dml-treatment-coverage.v1",
1126
+ "4",
1127
+ "TreatmentCoverageValidator",
1128
+ ),
1129
+ ),
1130
+ descriptor_api_version=2,
1131
+ is_default=True,
1132
+ )
1133
+
1134
+ LINEAR_IV_DESCRIPTOR = AlgorithmBuilder.from_distributed_algorithm(
1135
+ spec=_IV_SPEC,
1136
+ implementation_id="tributo.official.causal.linear_iv",
1137
+ implementation_version="1.0.0",
1138
+ implementation="tributo_algorithms_causal_core.algorithm:LinearIVATE",
1139
+ executable_factory="tributo_algorithms_causal_core.algorithm:create_algorithm",
1140
+ distribution=_PACKAGE,
1141
+ framework=None,
1142
+ environment=ATE_DESCRIPTOR.registration.environment,
1143
+ allowed_config_keys=(
1144
+ "confidence_z",
1145
+ "instrument_col",
1146
+ "output",
1147
+ "policy_cost",
1148
+ "treatment_col",
1149
+ ),
1150
+ strategy=DistributionStrategy.RAY_MAP_REDUCE,
1151
+ supported_worker_range=WorkerRange(2, 256),
1152
+ supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
1153
+ resources_per_worker=WorkerResources(num_cpus=1),
1154
+ policy=MapReducePolicy(
1155
+ state_schema=_IV_STATE_SCHEMA,
1156
+ max_partial_state_bytes=64 * 1024 * 1024,
1157
+ reducer_ref="tributo_algorithms_causal_core.algorithm:LinearIVATE.merge_states",
1158
+ finalizer_ref=(
1159
+ "tributo_algorithms_causal_core.algorithm:LinearIVATE.finalize_model"
1160
+ ),
1161
+ commutative=True,
1162
+ max_retries=0,
1163
+ ),
1164
+ package_name=_PACKAGE,
1165
+ package_version=_VERSION,
1166
+ tributo_version_spec=">=1.1",
1167
+ exporter="tributo_algorithms_causal_core.algorithm:export_model",
1168
+ flavor_id="onnx-runtime-v1",
1169
+ contract_bindings=ContractBindingSet(
1170
+ config=_contract(_IV_SPEC.config_contract_ref or "", "5", "IVConfigValidator"),
1171
+ input=_contract(_IV_SPEC.input_contract_ref or "", "2", "CausalInputValidator"),
1172
+ output=_contract(
1173
+ _IV_SPEC.output_contract_ref or "", "3", "CausalOutputValidator"
1174
+ ),
1175
+ coverage=_contract(
1176
+ "tributo.official.causal.iv-treatment-coverage.v1",
1177
+ "4",
1178
+ "TreatmentCoverageValidator",
1179
+ ),
1180
+ ),
1181
+ descriptor_api_version=2,
1182
+ is_default=True,
1183
+ )
1184
+
1185
+ __all__ = [
1186
+ "ATE_DESCRIPTOR",
1187
+ "LINEAR_DML_DESCRIPTOR",
1188
+ "LINEAR_IV_DESCRIPTOR",
1189
+ "CausalATEModel",
1190
+ "DifferenceInMeansATE",
1191
+ "LinearDMLATE",
1192
+ "LinearIVATE",
1193
+ ]