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,120 @@
1
+ """Descriptor for official distributed five-stage X-Learner."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from tributo.algorithms import AlgorithmBuilder
6
+ from tributo.algorithms.api import (
7
+ ContractBinding,
8
+ ContractBindingSet,
9
+ DistributionStrategy,
10
+ EnvironmentSpec,
11
+ ExecutionMode,
12
+ ExecutionProfile,
13
+ FrameworkNativePolicy,
14
+ QualifiedReference,
15
+ WorkerRange,
16
+ WorkerResources,
17
+ )
18
+ from tributo.training.algorithm_spec import (
19
+ AlgorithmSpec,
20
+ Capability,
21
+ DataLoadingMode,
22
+ ProblemType,
23
+ ResourceHints,
24
+ )
25
+
26
+ STAGES = ("mu0", "mu1", "tau0", "tau1", "propensity")
27
+
28
+ _PACKAGE = "tributo-algorithms"
29
+ _VERSION = "0.1.0"
30
+
31
+
32
+ def _binding(contract_id: str, digest: str, validator: str) -> ContractBinding:
33
+ return ContractBinding(
34
+ contract_id=contract_id,
35
+ schema_version=1,
36
+ schema_digest=digest * 64,
37
+ validator_ref=QualifiedReference.parse(
38
+ f"tributo_algorithms_causal_xlearner.contracts:{validator}"
39
+ ),
40
+ )
41
+
42
+
43
+ _SPEC = AlgorithmSpec(
44
+ name="x_learner",
45
+ trainer_cls=None,
46
+ version="1.0.0",
47
+ default_config={},
48
+ resource_hints=ResourceHints(gpu_required=False),
49
+ extras_group="training",
50
+ problem_types=(ProblemType.CAUSAL_EFFECT_ESTIMATION,),
51
+ data_modality=("tabular",),
52
+ capabilities=(Capability.DISTRIBUTED, Capability.EXPORTABLE),
53
+ data_loading=DataLoadingMode.LEGACY_DRIVER,
54
+ operations=("fit",),
55
+ learning_paradigm="causal_meta_learner",
56
+ model_family="x_learner",
57
+ data_modalities=("tabular",),
58
+ lifecycle_kind="causal_estimate",
59
+ allowed_execution_modes=(ExecutionMode.FRAMEWORK_NATIVE.value,),
60
+ config_contract_ref="tributo.x_learner.config.v1",
61
+ input_contract_ref="tributo.causal.binary_tabular.v1",
62
+ output_contract_ref="tributo.causal.x_learner_bundle.v1",
63
+ )
64
+
65
+ X_LEARNER_DESCRIPTOR = AlgorithmBuilder.from_distributed_algorithm(
66
+ spec=_SPEC,
67
+ implementation_id="tributo.official.causal_xlearner.xgboost",
68
+ implementation_version="1.0.0",
69
+ implementation="tributo_algorithms_causal_xlearner.algorithm:DistributedXLearner",
70
+ executable_factory="tributo_algorithms_causal_xlearner.algorithm:create_algorithm",
71
+ distribution=_PACKAGE,
72
+ framework="xgboost",
73
+ environment=EnvironmentSpec(
74
+ environment_id="tributo.official.causal-xlearner.v1",
75
+ dependencies=(
76
+ "xgboost>=2.1,<4",
77
+ "onnx>=1.16",
78
+ "onnxmltools>=1.13",
79
+ "onnxruntime>=1.20",
80
+ "tributo>=1.1",
81
+ f"tributo-algorithms[causal-xlearner]=={_VERSION}",
82
+ ),
83
+ ),
84
+ allowed_config_keys=("data", "model", "output", "ray", "training"),
85
+ strategy=DistributionStrategy.FRAMEWORK_NATIVE,
86
+ supported_worker_range=WorkerRange(2, 128),
87
+ supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
88
+ resources_per_worker=WorkerResources(num_cpus=1),
89
+ policy=FrameworkNativePolicy(
90
+ framework="xgboost-x-learner",
91
+ evidence_collector_ref=(
92
+ "tributo_algorithms_causal_xlearner.algorithm:"
93
+ "DistributedXLearner.collect_evidence"
94
+ ),
95
+ component_stages=STAGES,
96
+ ),
97
+ package_name=_PACKAGE,
98
+ package_version=_VERSION,
99
+ tributo_version_spec=">=1.1",
100
+ exporter="tributo_algorithms_causal_xlearner.exporter:export_result",
101
+ flavor_id="official-x-learner-v1",
102
+ contract_bindings=ContractBindingSet(
103
+ config=_binding(
104
+ _SPEC.config_contract_ref or "", "6", "XLearnerConfigValidator"
105
+ ),
106
+ input=_binding(_SPEC.input_contract_ref or "", "2", "XLearnerInputValidator"),
107
+ output=_binding(
108
+ _SPEC.output_contract_ref or "", "3", "XLearnerOutputValidator"
109
+ ),
110
+ coverage=_binding(
111
+ "tributo.official.x-learner.stage-coverage.v1",
112
+ "4",
113
+ "XLearnerCoverageValidator",
114
+ ),
115
+ ),
116
+ descriptor_api_version=2,
117
+ is_default=True,
118
+ )
119
+
120
+ __all__ = ["X_LEARNER_DESCRIPTOR"]
@@ -0,0 +1,432 @@
1
+ """X-Learner composite and causal-report Bundle exporters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Mapping
7
+ from typing import Any, ClassVar
8
+
9
+ from pydantic import BaseModel, ConfigDict
10
+ from tributo.algorithms.api import (
11
+ AlgorithmConfigurationError,
12
+ AlgorithmExecutionError,
13
+ AlgorithmExecutionResult,
14
+ ResolvedAlgorithmPlan,
15
+ )
16
+ from tributo.exporting.models import (
17
+ ArtifactDraft,
18
+ BundleOutputConfig,
19
+ CheckpointField,
20
+ DraftFile,
21
+ ExportCheckpointV1,
22
+ ExportContext,
23
+ ExportSource,
24
+ ExportTarget,
25
+ PlannedTarget,
26
+ ProducerInfo,
27
+ ResolvedArtifact,
28
+ SupportRequest,
29
+ SupportResult,
30
+ ValidatorBinding,
31
+ )
32
+ from tributo.exporting.service import BundleExportService
33
+ from tributo.training.exporters.causal_report import CausalReportExporter
34
+
35
+ from tributo_algorithms_causal_xlearner.algorithm import XLearnerResult
36
+ from tributo_algorithms_causal_xlearner.model import FORMULA, QUADRANT_CODES, STAGES
37
+
38
+
39
+ class _Options(BaseModel):
40
+ model_config = ConfigDict(extra="forbid")
41
+
42
+
43
+ class XLearnerExporter:
44
+ api_version: ClassVar[int] = 2
45
+ exporter_id: ClassVar[str] = "official-x-learner-v1"
46
+ output_format: ClassVar[str] = "x-learner"
47
+ output_flavor_id: ClassVar[str] = "official-x-learner-v1"
48
+ priority: ClassVar[int] = 90
49
+ source_kinds: ClassVar[tuple[str, ...]] = ("official_x_learner",)
50
+ options_model: ClassVar[type[BaseModel]] = _Options
51
+ validator_bindings: ClassVar[tuple[ValidatorBinding, ...]] = (
52
+ ValidatorBinding(validator_id="structure-v1", required=True),
53
+ )
54
+ mutates_source: ClassVar[bool] = False
55
+ upstream_requirements: ClassVar[tuple[Any, ...]] = ()
56
+
57
+ @classmethod
58
+ def supports(cls, request: SupportRequest) -> SupportResult:
59
+ supported = request.source_kind == "official_x_learner"
60
+ return SupportResult(
61
+ supported=supported,
62
+ code="OK" if supported else "UNSUPPORTED_SOURCE_KIND",
63
+ reason="official X-Learner source" if supported else "wrong source kind",
64
+ )
65
+
66
+ def export(
67
+ self,
68
+ context: ExportContext,
69
+ source: ExportSource,
70
+ upstream: Mapping[str, ResolvedArtifact],
71
+ target: PlannedTarget,
72
+ ) -> ArtifactDraft:
73
+ del upstream
74
+ result = source.model_object
75
+ if not isinstance(result, XLearnerResult):
76
+ raise TypeError("official X-Learner exporter requires XLearnerResult")
77
+ files = []
78
+ for stage in STAGES:
79
+ name = f"{stage}.ubj"
80
+ (context.artifact_dir / name).write_bytes(result.booster_raw[stage])
81
+ files.append(DraftFile(relative_path=name, role="model"))
82
+ metadata = {
83
+ "api_version": 1,
84
+ "feature_names": list(result.feature_names),
85
+ "response_threshold": result.response_threshold,
86
+ "propensity_clip": list(result.propensity_clip),
87
+ "components": {stage: f"{stage}.ubj" for stage in STAGES},
88
+ "formula": FORMULA,
89
+ "quadrant_codes": QUADRANT_CODES,
90
+ "composition_digest": result.composition_digest,
91
+ }
92
+ (context.artifact_dir / "x_learner.json").write_text(
93
+ json.dumps(metadata, sort_keys=True), encoding="utf-8"
94
+ )
95
+ files.append(DraftFile(relative_path="x_learner.json", role="config"))
96
+ return ArtifactDraft(
97
+ name=target.target.name,
98
+ format=self.output_format,
99
+ flavor_id=self.output_flavor_id,
100
+ files=tuple(files),
101
+ entrypoint="x_learner.json",
102
+ producer=ProducerInfo(exporter_id=self.exporter_id),
103
+ )
104
+
105
+
106
+ class XLearnerONNXExporter:
107
+ """Export the five XGBoost stages and CATE formula as one ONNX graph."""
108
+
109
+ api_version: ClassVar[int] = 2
110
+ exporter_id: ClassVar[str] = "official-x-learner-onnx-v1"
111
+ output_format: ClassVar[str] = "onnx"
112
+ output_flavor_id: ClassVar[str] = "onnx-runtime-v1"
113
+ priority: ClassVar[int] = 90
114
+ source_kinds: ClassVar[tuple[str, ...]] = ("official_x_learner",)
115
+ options_model: ClassVar[type[BaseModel]] = _Options
116
+ validator_bindings: ClassVar[tuple[ValidatorBinding, ...]] = (
117
+ ValidatorBinding(validator_id="structure-v1", required=True),
118
+ ValidatorBinding(validator_id="onnx-runtime-v1", required=True),
119
+ )
120
+ mutates_source: ClassVar[bool] = False
121
+ upstream_requirements: ClassVar[tuple[Any, ...]] = ()
122
+
123
+ @classmethod
124
+ def supports(cls, request: SupportRequest) -> SupportResult:
125
+ supported = request.source_kind == "official_x_learner"
126
+ return SupportResult(
127
+ supported=supported,
128
+ code="OK" if supported else "UNSUPPORTED_SOURCE_KIND",
129
+ reason="official X-Learner ONNX graph"
130
+ if supported
131
+ else "wrong source kind",
132
+ )
133
+
134
+ def export(
135
+ self,
136
+ context: ExportContext,
137
+ source: ExportSource,
138
+ upstream: Mapping[str, ResolvedArtifact],
139
+ target: PlannedTarget,
140
+ ) -> ArtifactDraft:
141
+ del upstream
142
+ import copy
143
+
144
+ import onnx
145
+ import onnxmltools
146
+ import xgboost
147
+ from onnx import TensorProto, helper
148
+ from onnxmltools.convert.common.data_types import FloatTensorType
149
+
150
+ result = source.model_object
151
+ if not isinstance(result, XLearnerResult):
152
+ raise TypeError("official X-Learner ONNX exporter requires XLearnerResult")
153
+ converted = []
154
+ for stage in STAGES:
155
+ booster = xgboost.Booster()
156
+ booster.load_model(bytearray(result.booster_raw[stage]))
157
+ converted.append(
158
+ onnxmltools.convert_xgboost(
159
+ booster,
160
+ initial_types=[
161
+ (
162
+ "float_input",
163
+ FloatTensorType([None, len(result.feature_names)]),
164
+ )
165
+ ],
166
+ target_opset=15,
167
+ )
168
+ )
169
+ nodes = []
170
+ for stage, model in zip(STAGES, converted, strict=True):
171
+ if len(model.graph.node) != 1:
172
+ raise AlgorithmExecutionError(
173
+ "X-Learner ONNX conversion produced an unexpected graph"
174
+ )
175
+ node = copy.deepcopy(model.graph.node[0])
176
+ node.name = stage
177
+ if stage == "propensity":
178
+ if node.op_type != "TreeEnsembleClassifier" or len(node.output) != 2:
179
+ raise AlgorithmExecutionError(
180
+ "X-Learner propensity conversion requires label and probability outputs"
181
+ )
182
+ node.output[0] = "propensity_label"
183
+ node.output[1] = "propensity_probabilities"
184
+ nodes.extend(
185
+ [
186
+ node,
187
+ helper.make_node(
188
+ "Gather",
189
+ ["propensity_probabilities", "positive_class_index"],
190
+ ["propensity"],
191
+ name="propensity_positive_class",
192
+ axis=1,
193
+ ),
194
+ ]
195
+ )
196
+ else:
197
+ node.output[0] = stage
198
+ nodes.append(node)
199
+
200
+ def constant(name: str, value: float) -> Any:
201
+ return helper.make_node(
202
+ "Constant",
203
+ [],
204
+ [name],
205
+ name=name,
206
+ value=helper.make_tensor(
207
+ f"{name}_value", TensorProto.FLOAT, [], [value]
208
+ ),
209
+ )
210
+
211
+ nodes.extend(
212
+ [
213
+ constant("clip_min", result.propensity_clip[0]),
214
+ constant("clip_max", result.propensity_clip[1]),
215
+ helper.make_node(
216
+ "Cast",
217
+ ["propensity"],
218
+ ["propensity_float"],
219
+ name="propensity_float",
220
+ to=TensorProto.FLOAT,
221
+ ),
222
+ helper.make_node(
223
+ "Clip",
224
+ ["propensity_float", "clip_min", "clip_max"],
225
+ ["propensity_clipped"],
226
+ name="propensity_clip",
227
+ ),
228
+ constant("one", 1.0),
229
+ helper.make_node(
230
+ "Sub", ["one", "propensity_clipped"], ["one_minus_propensity"]
231
+ ),
232
+ helper.make_node(
233
+ "Mul", ["propensity_clipped", "tau0"], ["treated_effect"]
234
+ ),
235
+ helper.make_node(
236
+ "Mul", ["one_minus_propensity", "tau1"], ["control_effect"]
237
+ ),
238
+ helper.make_node("Add", ["treated_effect", "control_effect"], ["cate"]),
239
+ ]
240
+ )
241
+ graph = helper.make_graph(
242
+ nodes,
243
+ "tributo_x_learner",
244
+ [
245
+ helper.make_tensor_value_info(
246
+ "float_input",
247
+ TensorProto.FLOAT,
248
+ [None, len(result.feature_names)],
249
+ )
250
+ ],
251
+ [helper.make_tensor_value_info("cate", TensorProto.FLOAT, [None, 1])],
252
+ initializer=[
253
+ helper.make_tensor("positive_class_index", TensorProto.INT64, [1], [1])
254
+ ],
255
+ )
256
+ model = helper.make_model_gen_version(
257
+ graph,
258
+ opset_imports=[
259
+ helper.make_operatorsetid("", 15),
260
+ helper.make_operatorsetid("ai.onnx.ml", 3),
261
+ ],
262
+ producer_name="tributo-algorithms",
263
+ )
264
+ onnx.checker.check_model(model)
265
+ (context.artifact_dir / "model.onnx").write_bytes(model.SerializeToString())
266
+ return ArtifactDraft(
267
+ name=target.target.name,
268
+ format=self.output_format,
269
+ flavor_id=self.output_flavor_id,
270
+ files=(DraftFile(relative_path="model.onnx", role="model"),),
271
+ entrypoint="model.onnx",
272
+ producer=ProducerInfo(exporter_id=self.exporter_id),
273
+ )
274
+
275
+
276
+ class XLearnerReportExporter(CausalReportExporter):
277
+ api_version: ClassVar[int] = 2
278
+ exporter_id: ClassVar[str] = "official-x-learner-report-v1"
279
+ output_format: ClassVar[str] = "json"
280
+ output_flavor_id: ClassVar[str] = "report"
281
+ artifact_kind: ClassVar[str] = "report"
282
+ priority: ClassVar[int] = 90
283
+ source_kinds: ClassVar[tuple[str, ...]] = ("official_x_learner",)
284
+ options_model: ClassVar[type[BaseModel]] = _Options
285
+ validator_bindings: ClassVar[tuple[ValidatorBinding, ...]] = ()
286
+ mutates_source: ClassVar[bool] = False
287
+ upstream_requirements: ClassVar[tuple[Any, ...]] = ()
288
+
289
+ @classmethod
290
+ def supports(cls, request: SupportRequest) -> SupportResult:
291
+ supported = request.source_kind == "official_x_learner"
292
+ return SupportResult(
293
+ supported=supported,
294
+ code="OK" if supported else "UNSUPPORTED_SOURCE_KIND",
295
+ reason="official X-Learner report" if supported else "wrong source kind",
296
+ )
297
+
298
+ def export(
299
+ self,
300
+ context: ExportContext,
301
+ source: ExportSource,
302
+ upstream: Mapping[str, ResolvedArtifact],
303
+ target: PlannedTarget,
304
+ ) -> ArtifactDraft:
305
+ # Keep the report target self-contained if a caller constructs an
306
+ # ExportSource without copying the study metadata. The canonical
307
+ # X-Learner path already supplies this field; this fallback preserves
308
+ # the report contract for direct/plugin callers.
309
+ if source.metadata.get("causal_study") is None:
310
+ result = source.model_object
311
+ if not isinstance(result, XLearnerResult):
312
+ raise TypeError("X-Learner report requires XLearnerResult")
313
+ source = source.model_copy(
314
+ update={
315
+ "metadata": {
316
+ **source.metadata,
317
+ "causal_study": {
318
+ "api_version": 1,
319
+ "kind": "causal_meta_learner",
320
+ "method": "distributed_x_learner",
321
+ "effect": dict(result.metrics),
322
+ "component_stages": list(STAGES),
323
+ "composition_digest": result.composition_digest,
324
+ "formula": FORMULA,
325
+ },
326
+ }
327
+ }
328
+ )
329
+ return super().export(context, source, upstream, target)
330
+
331
+
332
+ def export_result(
333
+ *, result: object, checkpoint: object, plan: ResolvedAlgorithmPlan, run_id: str
334
+ ) -> AlgorithmExecutionResult:
335
+ del checkpoint
336
+ if not isinstance(result, XLearnerResult):
337
+ raise AlgorithmExecutionError("X-Learner export requires XLearnerResult")
338
+ output = plan.algorithm_config.get("output")
339
+ if not isinstance(output, Mapping) or not isinstance(output.get("bundle_uri"), str):
340
+ raise AlgorithmConfigurationError("X-Learner output.bundle_uri is required")
341
+ report = {
342
+ "api_version": 1,
343
+ "kind": "causal_meta_learner",
344
+ "method": "distributed_x_learner",
345
+ "effect": dict(result.metrics),
346
+ "component_stages": list(STAGES),
347
+ "composition_digest": result.composition_digest,
348
+ "formula": FORMULA,
349
+ }
350
+ source = ExportSource(
351
+ source_kind="official_x_learner",
352
+ model_object=result,
353
+ architecture_id="x_learner",
354
+ feature_schema={"feature_names": list(result.feature_names)},
355
+ metadata={"causal_study": report, "framework": "xgboost"},
356
+ source_fingerprint=result.composition_digest,
357
+ checkpoint_contract=ExportCheckpointV1(
358
+ trainer_type="x_learner",
359
+ architecture_id="x_learner",
360
+ input_schema=(
361
+ CheckpointField(
362
+ name="float_input",
363
+ dtype="float32",
364
+ shape=("batch", len(result.feature_names)),
365
+ ),
366
+ ),
367
+ output_schema=tuple(
368
+ CheckpointField(
369
+ name=name,
370
+ dtype="int64" if name == "quadrant" else "float32",
371
+ shape=("batch",),
372
+ )
373
+ for name in (
374
+ "mu0",
375
+ "mu1",
376
+ "tau0",
377
+ "tau1",
378
+ "propensity",
379
+ "cate",
380
+ "quadrant",
381
+ )
382
+ ),
383
+ task_type="causal_effect_estimation",
384
+ framework="xgboost",
385
+ framework_version="2.1+",
386
+ ),
387
+ )
388
+ bundle = BundleExportService().export_bundle(
389
+ source,
390
+ BundleOutputConfig(
391
+ bundle_uri=str(output["bundle_uri"]),
392
+ request_id=run_id,
393
+ run_id=run_id,
394
+ targets=[
395
+ ExportTarget(
396
+ name="x-learner-onnx",
397
+ format="onnx",
398
+ exporter_id="official-x-learner-onnx-v1",
399
+ ),
400
+ ExportTarget(
401
+ name="x-learner-model",
402
+ format="x-learner",
403
+ exporter_id="official-x-learner-v1",
404
+ ),
405
+ ExportTarget(
406
+ name="causal-report",
407
+ format="json",
408
+ exporter_id="official-x-learner-report-v1",
409
+ ),
410
+ ],
411
+ roles={"inference": "x-learner-model", "report": "causal-report"},
412
+ ),
413
+ )
414
+ return AlgorithmExecutionResult(
415
+ status="succeeded",
416
+ metrics=dict(result.metrics),
417
+ outputs={
418
+ "bundle_id": bundle.bundle_id,
419
+ "bundle_uri": bundle.canonical_uri,
420
+ "execution_id": bundle.execution_id,
421
+ "manifest_sha256": bundle.manifest_sha256,
422
+ "composition_digest": result.composition_digest,
423
+ },
424
+ )
425
+
426
+
427
+ __all__ = [
428
+ "XLearnerExporter",
429
+ "XLearnerONNXExporter",
430
+ "XLearnerReportExporter",
431
+ "export_result",
432
+ ]
@@ -0,0 +1,120 @@
1
+ """Safe fixed-composition X-Learner Bundle flavor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, ClassVar, cast
7
+
8
+ import numpy as np
9
+ from tributo.exceptions import ModelLoadError, UnsupportedArtifactFormat
10
+ from tributo.exporting.models import ResolvedArtifact
11
+ from tributo.exporting.runtime import SECURITY_MODE_SAFE, BundleModel
12
+
13
+ from tributo_algorithms_causal_xlearner.model import (
14
+ FORMULA,
15
+ QUADRANT_CODES,
16
+ STAGE_OBJECTIVES,
17
+ STAGES,
18
+ XLearnerModel,
19
+ )
20
+
21
+
22
+ def _objective(booster: object) -> str:
23
+ config = json.loads(cast(Any, booster).save_config())
24
+ return str(config["learner"]["objective"]["name"])
25
+
26
+
27
+ class XLearnerFlavor:
28
+ api_version: ClassVar[int] = 1
29
+ flavor_id: ClassVar[str] = "official-x-learner-v1"
30
+ supported_formats: ClassVar[tuple[str, ...]] = ("x-learner",)
31
+ batch_supported: ClassVar[bool] = True
32
+ serveable: ClassVar[bool] = False
33
+ security_mode: ClassVar[str] = SECURITY_MODE_SAFE
34
+ signature_required: ClassVar[bool] = True
35
+ required_dependencies: ClassVar[tuple[str, ...]] = ("xgboost",)
36
+
37
+ def load(
38
+ self,
39
+ artifact: ResolvedArtifact,
40
+ *,
41
+ role: str,
42
+ unsafe: bool = False,
43
+ architecture_id: str | None = None,
44
+ ) -> BundleModel:
45
+ del role, unsafe
46
+ if architecture_id not in (None, "x_learner"):
47
+ raise UnsupportedArtifactFormat(
48
+ "official-x-learner-v1 requires x_learner architecture"
49
+ )
50
+ try:
51
+ import xgboost
52
+
53
+ metadata = json.loads(artifact.entrypoint_path.read_text(encoding="utf-8"))
54
+ if metadata.get("api_version") != 1 or metadata.get("formula") != FORMULA:
55
+ raise ValueError("metadata contract")
56
+ if metadata.get("quadrant_codes") != QUADRANT_CODES:
57
+ raise ValueError("quadrant contract")
58
+ components = metadata.get("components")
59
+ if not isinstance(components, dict) or set(components) != set(STAGES):
60
+ raise ValueError("component set")
61
+ boosters = {}
62
+ for stage in STAGES:
63
+ booster = xgboost.Booster()
64
+ booster.load_model(str(artifact.path_for(components[stage])))
65
+ if _objective(booster) != STAGE_OBJECTIVES[stage]:
66
+ raise ValueError(f"component objective {stage}")
67
+ boosters[stage] = booster
68
+ model = XLearnerModel(
69
+ boosters,
70
+ feature_names=tuple(metadata["feature_names"]),
71
+ response_threshold=float(metadata["response_threshold"]),
72
+ propensity_clip=tuple(metadata["propensity_clip"]),
73
+ )
74
+ except Exception as exc:
75
+ raise ModelLoadError(
76
+ f"official X-Learner artifact is invalid ({type(exc).__name__})"
77
+ ) from None
78
+ return _XLearnerBundleModel(model)
79
+
80
+
81
+ class _XLearnerBundleModel:
82
+ input_names = ("float_input",)
83
+ output_names = ("mu0", "mu1", "tau0", "tau1", "propensity", "cate", "quadrant")
84
+ input_dtypes = ("float32",)
85
+ output_dtypes = (
86
+ "float32",
87
+ "float32",
88
+ "float32",
89
+ "float32",
90
+ "float32",
91
+ "float32",
92
+ "int64",
93
+ )
94
+
95
+ def __init__(self, model: XLearnerModel) -> None:
96
+ self.model = model
97
+
98
+ @property
99
+ def input_shapes(self) -> tuple[tuple[int | None, ...], ...]:
100
+ return ((None, len(self.model.feature_names)),)
101
+
102
+ @property
103
+ def output_shapes(self) -> tuple[tuple[int | None, ...], ...]:
104
+ return tuple((None,) for _ in self.output_names)
105
+
106
+ def predict(self, inputs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
107
+ result = self.model.predict(inputs["float_input"])
108
+ outputs = {
109
+ name: np.asarray(getattr(result, name), dtype=np.float32)
110
+ for name in self.output_names
111
+ if name != "quadrant"
112
+ }
113
+ outputs["quadrant"] = np.asarray(
114
+ [QUADRANT_CODES[str(value)] for value in result.quadrant],
115
+ dtype=np.int64,
116
+ )
117
+ return outputs
118
+
119
+
120
+ __all__ = ["XLearnerFlavor"]