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.
- tributo_algorithms-0.1.0.dist-info/METADATA +328 -0
- tributo_algorithms-0.1.0.dist-info/RECORD +110 -0
- tributo_algorithms-0.1.0.dist-info/WHEEL +4 -0
- tributo_algorithms-0.1.0.dist-info/entry_points.txt +57 -0
- tributo_algorithms-0.1.0.dist-info/licenses/LICENSE +202 -0
- tributo_algorithms_boosting/__init__.py +42 -0
- tributo_algorithms_boosting/algorithm.py +825 -0
- tributo_algorithms_boosting/checkpointing.py +441 -0
- tributo_algorithms_boosting/contracts.py +232 -0
- tributo_algorithms_boosting/data_config.py +59 -0
- tributo_algorithms_boosting/descriptor.py +124 -0
- tributo_algorithms_boosting/lightgbm.py +511 -0
- tributo_algorithms_boosting/lightgbm_contracts.py +186 -0
- tributo_algorithms_boosting/lightgbm_descriptor.py +112 -0
- tributo_algorithms_boosting/native.py +557 -0
- tributo_algorithms_boosting/stages.py +150 -0
- tributo_algorithms_catboost/__init__.py +5 -0
- tributo_algorithms_catboost/algorithm.py +379 -0
- tributo_algorithms_catboost/contracts.py +145 -0
- tributo_algorithms_catboost/descriptor.py +121 -0
- tributo_algorithms_catboost/exporter.py +106 -0
- tributo_algorithms_catboost/flavor.py +191 -0
- tributo_algorithms_causal_core/__init__.py +41 -0
- tributo_algorithms_causal_core/algorithm.py +1193 -0
- tributo_algorithms_causal_core/contracts.py +136 -0
- tributo_algorithms_causal_core/descriptor.py +270 -0
- tributo_algorithms_causal_core/exporter.py +52 -0
- tributo_algorithms_causal_discovery/__init__.py +23 -0
- tributo_algorithms_causal_discovery/algorithm.py +526 -0
- tributo_algorithms_causal_discovery/contracts.py +97 -0
- tributo_algorithms_causal_discovery/descriptor.py +130 -0
- tributo_algorithms_causal_discovery/exporter.py +43 -0
- tributo_algorithms_causal_dowhy/__init__.py +38 -0
- tributo_algorithms_causal_dowhy/algorithm.py +325 -0
- tributo_algorithms_causal_dowhy/contracts.py +209 -0
- tributo_algorithms_causal_dowhy/descriptor.py +106 -0
- tributo_algorithms_causal_dowhy/exporter.py +43 -0
- tributo_algorithms_causal_dowhy/gcm.py +634 -0
- tributo_algorithms_causal_dowhy/gcm_descriptor.py +110 -0
- tributo_algorithms_causal_dr/__init__.py +22 -0
- tributo_algorithms_causal_dr/algorithm.py +446 -0
- tributo_algorithms_causal_dr/contracts.py +94 -0
- tributo_algorithms_causal_dr/descriptor.py +104 -0
- tributo_algorithms_causal_xlearner/__init__.py +29 -0
- tributo_algorithms_causal_xlearner/algorithm.py +448 -0
- tributo_algorithms_causal_xlearner/contracts.py +97 -0
- tributo_algorithms_causal_xlearner/descriptor.py +120 -0
- tributo_algorithms_causal_xlearner/exporter.py +432 -0
- tributo_algorithms_causal_xlearner/flavor.py +120 -0
- tributo_algorithms_causal_xlearner/model.py +116 -0
- tributo_algorithms_classical/__init__.py +41 -0
- tributo_algorithms_classical/contracts.py +139 -0
- tributo_algorithms_classical/descriptors.py +370 -0
- tributo_algorithms_classical/exporter.py +166 -0
- tributo_algorithms_classical/isolation_forest.py +172 -0
- tributo_algorithms_classical/isolation_forest_descriptor.py +122 -0
- tributo_algorithms_classical/kmeans.py +315 -0
- tributo_algorithms_classical/kmeans_descriptor.py +147 -0
- tributo_algorithms_classical/linear_regression.py +206 -0
- tributo_algorithms_classical/logistic_regression.py +238 -0
- tributo_algorithms_classical/models.py +28 -0
- tributo_algorithms_classical/multinomial_nb.py +643 -0
- tributo_algorithms_classical/multinomial_nb_descriptor.py +183 -0
- tributo_algorithms_classical/pca.py +187 -0
- tributo_algorithms_classical/pca_descriptor.py +111 -0
- tributo_algorithms_classical/random_forest.py +304 -0
- tributo_algorithms_classical/sgd.py +331 -0
- tributo_algorithms_classical/sgd_contracts.py +121 -0
- tributo_algorithms_classical/sgd_descriptor.py +143 -0
- tributo_algorithms_classical/unsupervised_contracts.py +198 -0
- tributo_algorithms_classical/unsupervised_exporter.py +427 -0
- tributo_algorithms_classical/unsupervised_models.py +90 -0
- tributo_algorithms_graph_pyg/__init__.py +37 -0
- tributo_algorithms_graph_pyg/algorithm.py +883 -0
- tributo_algorithms_graph_pyg/contracts.py +260 -0
- tributo_algorithms_graph_pyg/descriptor.py +201 -0
- tributo_algorithms_multistage_torch/__init__.py +40 -0
- tributo_algorithms_multistage_torch/algorithm.py +532 -0
- tributo_algorithms_multistage_torch/contracts.py +220 -0
- tributo_algorithms_multistage_torch/descriptor.py +146 -0
- tributo_algorithms_multistage_torch/pretrain.py +570 -0
- tributo_algorithms_multistage_torch/pretrain_descriptor.py +153 -0
- tributo_algorithms_recsys_torch/__init__.py +35 -0
- tributo_algorithms_recsys_torch/contracts.py +295 -0
- tributo_algorithms_recsys_torch/descriptor.py +136 -0
- tributo_algorithms_recsys_torch/jagged.py +707 -0
- tributo_algorithms_recsys_torch/jagged_descriptor.py +130 -0
- tributo_algorithms_recsys_torch/recipe.py +192 -0
- tributo_algorithms_representation/__init__.py +20 -0
- tributo_algorithms_representation/contracts.py +117 -0
- tributo_algorithms_representation/descriptor.py +137 -0
- tributo_algorithms_representation/recipe.py +162 -0
- tributo_algorithms_tabular_torch/__init__.py +46 -0
- tributo_algorithms_tabular_torch/contracts.py +228 -0
- tributo_algorithms_tabular_torch/descriptor.py +223 -0
- tributo_algorithms_tabular_torch/priors.py +216 -0
- tributo_algorithms_tabular_torch/pu_metrics.py +269 -0
- tributo_algorithms_tabular_torch/pu_reducer.py +129 -0
- tributo_algorithms_tabular_torch/recipe.py +294 -0
- tributo_algorithms_timeseries/__init__.py +36 -0
- tributo_algorithms_timeseries/contracts.py +120 -0
- tributo_algorithms_timeseries/descriptor.py +137 -0
- tributo_algorithms_timeseries/recipe.py +195 -0
- tributo_algorithms_timeseries/rnn_contracts.py +170 -0
- tributo_algorithms_timeseries/rnn_descriptor.py +167 -0
- tributo_algorithms_timeseries/rnn_recipe.py +223 -0
- tributo_algorithms_transformers_nlp/__init__.py +20 -0
- tributo_algorithms_transformers_nlp/contracts.py +109 -0
- tributo_algorithms_transformers_nlp/descriptor.py +137 -0
- tributo_algorithms_transformers_nlp/recipe.py +235 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Descriptor for official distributed doubly robust ATE."""
|
|
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 AlgorithmSpec, Capability, ProblemType
|
|
19
|
+
|
|
20
|
+
STAGES = ("mu0", "mu1", "propensity")
|
|
21
|
+
|
|
22
|
+
_PACKAGE = "tributo-algorithms"
|
|
23
|
+
_VERSION = "0.1.0"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _binding(contract_id: str, digest: str, validator: str) -> ContractBinding:
|
|
27
|
+
return ContractBinding(
|
|
28
|
+
contract_id=contract_id,
|
|
29
|
+
schema_version=1,
|
|
30
|
+
schema_digest=digest * 64,
|
|
31
|
+
validator_ref=QualifiedReference.parse(
|
|
32
|
+
f"tributo_algorithms_causal_dr.contracts:{validator}"
|
|
33
|
+
),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
_SPEC = AlgorithmSpec(
|
|
38
|
+
name="doubly_robust_ate",
|
|
39
|
+
trainer_cls=None,
|
|
40
|
+
version="1.0.0",
|
|
41
|
+
default_config={},
|
|
42
|
+
supported_tasks=("fit",),
|
|
43
|
+
operations=("fit",),
|
|
44
|
+
problem_types=(ProblemType.CAUSAL_EFFECT_ESTIMATION,),
|
|
45
|
+
capabilities=(Capability.DISTRIBUTED, Capability.EXPORTABLE, Capability.TUNABLE),
|
|
46
|
+
learning_paradigm="causal_inference",
|
|
47
|
+
model_family="aipw_doubly_robust",
|
|
48
|
+
data_modalities=("tabular",),
|
|
49
|
+
lifecycle_kind="nuisance_fit_estimate_refute_policy",
|
|
50
|
+
allowed_execution_modes=(ExecutionMode.FRAMEWORK_NATIVE.value,),
|
|
51
|
+
config_contract_ref="tributo.official.causal.dr.config.v1",
|
|
52
|
+
input_contract_ref="tributo.official.causal.binary-treatment.v1",
|
|
53
|
+
output_contract_ref="tributo.official.causal.report-bundle.v1",
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
DR_DESCRIPTOR = AlgorithmBuilder.from_distributed_algorithm(
|
|
57
|
+
spec=_SPEC,
|
|
58
|
+
implementation_id="tributo.official.causal_dr.aipw",
|
|
59
|
+
implementation_version="1.0.0",
|
|
60
|
+
implementation="tributo_algorithms_causal_dr.algorithm:DistributedDRLearner",
|
|
61
|
+
executable_factory="tributo_algorithms_causal_dr.algorithm:create_algorithm",
|
|
62
|
+
distribution=_PACKAGE,
|
|
63
|
+
framework="xgboost",
|
|
64
|
+
environment=EnvironmentSpec(
|
|
65
|
+
environment_id="tributo.official.causal-dr.v1",
|
|
66
|
+
dependencies=(
|
|
67
|
+
"xgboost>=2.1,<4",
|
|
68
|
+
"tributo>=1.1",
|
|
69
|
+
f"tributo-algorithms[causal-dr]=={_VERSION}",
|
|
70
|
+
),
|
|
71
|
+
),
|
|
72
|
+
allowed_config_keys=("data", "model", "output", "ray", "training"),
|
|
73
|
+
strategy=DistributionStrategy.FRAMEWORK_NATIVE,
|
|
74
|
+
supported_worker_range=WorkerRange(2, 128),
|
|
75
|
+
supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
|
|
76
|
+
resources_per_worker=WorkerResources(num_cpus=1),
|
|
77
|
+
policy=FrameworkNativePolicy(
|
|
78
|
+
framework="xgboost-aipw",
|
|
79
|
+
evidence_collector_ref=(
|
|
80
|
+
"tributo_algorithms_causal_dr.algorithm:"
|
|
81
|
+
"DistributedDRLearner.collect_evidence"
|
|
82
|
+
),
|
|
83
|
+
component_stages=STAGES,
|
|
84
|
+
),
|
|
85
|
+
package_name=_PACKAGE,
|
|
86
|
+
package_version=_VERSION,
|
|
87
|
+
tributo_version_spec=">=1.1",
|
|
88
|
+
exporter="tributo_algorithms_causal_dr.algorithm:export_result",
|
|
89
|
+
flavor_id="onnx-runtime-v1",
|
|
90
|
+
contract_bindings=ContractBindingSet(
|
|
91
|
+
config=_binding(_SPEC.config_contract_ref or "", "e", "DRConfigValidator"),
|
|
92
|
+
input=_binding(_SPEC.input_contract_ref or "", "b", "DRInputValidator"),
|
|
93
|
+
output=_binding(_SPEC.output_contract_ref or "", "c", "DROutputValidator"),
|
|
94
|
+
coverage=_binding(
|
|
95
|
+
"tributo.official.causal.dr-stage-coverage.v1",
|
|
96
|
+
"d",
|
|
97
|
+
"DRCoverageValidator",
|
|
98
|
+
),
|
|
99
|
+
),
|
|
100
|
+
descriptor_api_version=2,
|
|
101
|
+
is_default=True,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
__all__ = ["DR_DESCRIPTOR"]
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Official distributed X-Learner with lazy runtime exports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from tributo_algorithms_causal_xlearner.descriptor import X_LEARNER_DESCRIPTOR
|
|
8
|
+
|
|
9
|
+
_LAZY_EXPORTS = {
|
|
10
|
+
"DistributedXLearner": (
|
|
11
|
+
"tributo_algorithms_causal_xlearner.algorithm",
|
|
12
|
+
"DistributedXLearner",
|
|
13
|
+
),
|
|
14
|
+
"XLearnerModel": ("tributo_algorithms_causal_xlearner.model", "XLearnerModel"),
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def __getattr__(name: str) -> Any:
|
|
19
|
+
target = _LAZY_EXPORTS.get(name)
|
|
20
|
+
if target is None:
|
|
21
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
22
|
+
import importlib
|
|
23
|
+
|
|
24
|
+
value = getattr(importlib.import_module(target[0]), target[1])
|
|
25
|
+
globals()[name] = value
|
|
26
|
+
return value
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
__all__ = ["DistributedXLearner", "XLearnerModel", "X_LEARNER_DESCRIPTOR"]
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
"""Five-stage distributed X-Learner using the official boosting StageRunner."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any, cast
|
|
10
|
+
|
|
11
|
+
from tributo.algorithms.api import (
|
|
12
|
+
AlgorithmConfigurationError,
|
|
13
|
+
AlgorithmExecutionError,
|
|
14
|
+
ResolvedAlgorithmPlan,
|
|
15
|
+
WorkerResources,
|
|
16
|
+
)
|
|
17
|
+
from tributo.algorithms.spi import FrameworkNativeAlgorithm
|
|
18
|
+
from tributo_algorithms_boosting import XGBoostStageRunner
|
|
19
|
+
|
|
20
|
+
from tributo_algorithms_causal_xlearner.model import STAGES, XLearnerModel
|
|
21
|
+
|
|
22
|
+
_STAGE_LABEL = "__tributo_xlearner_label"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _split_rows(materialized: object, fold_count: int) -> tuple[object, ...]:
|
|
26
|
+
"""Split a materialized Dataset by row indices without dropping rows."""
|
|
27
|
+
rows = int(cast(Any, materialized).count())
|
|
28
|
+
base, remainder = divmod(rows, fold_count)
|
|
29
|
+
boundaries: list[int] = []
|
|
30
|
+
cursor = 0
|
|
31
|
+
for index in range(fold_count - 1):
|
|
32
|
+
cursor += base + (1 if index < remainder else 0)
|
|
33
|
+
boundaries.append(cursor)
|
|
34
|
+
return tuple(cast(Any, materialized).split_at_indices(boundaries))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _validate_treatment_batch(batch: object, *, treatment_name: str) -> object:
|
|
38
|
+
"""Reject missing, non-finite, or non-binary treatment values."""
|
|
39
|
+
import numpy as np
|
|
40
|
+
|
|
41
|
+
frame = cast(Any, batch)
|
|
42
|
+
if treatment_name not in frame.columns:
|
|
43
|
+
raise ValueError(f"treatment column {treatment_name!r} is missing")
|
|
44
|
+
try:
|
|
45
|
+
treatment = frame[treatment_name].to_numpy(dtype=np.float64)
|
|
46
|
+
except (TypeError, ValueError, OverflowError) as error:
|
|
47
|
+
raise ValueError(
|
|
48
|
+
"X-Learner treatment values must be numeric binary values"
|
|
49
|
+
) from error
|
|
50
|
+
if not np.isfinite(treatment).all():
|
|
51
|
+
raise ValueError("X-Learner treatment values must be finite")
|
|
52
|
+
if not np.isin(treatment, (0.0, 1.0)).all():
|
|
53
|
+
raise ValueError("X-Learner treatment values must be exactly 0 or 1")
|
|
54
|
+
normalized = frame.copy()
|
|
55
|
+
normalized[treatment_name] = treatment.astype(np.int8)
|
|
56
|
+
return normalized
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _lossless_folds(
|
|
60
|
+
dataset: object,
|
|
61
|
+
treatment_name: str,
|
|
62
|
+
fold_count: int,
|
|
63
|
+
*,
|
|
64
|
+
seed: int,
|
|
65
|
+
) -> tuple[object, ...]:
|
|
66
|
+
"""Create stratified disjoint folds while retaining every row."""
|
|
67
|
+
treated = (
|
|
68
|
+
cast(Any, dataset)
|
|
69
|
+
.filter(lambda row: row[treatment_name] == 1)
|
|
70
|
+
.random_shuffle(seed=seed)
|
|
71
|
+
.materialize()
|
|
72
|
+
)
|
|
73
|
+
control = (
|
|
74
|
+
cast(Any, dataset)
|
|
75
|
+
.filter(lambda row: row[treatment_name] == 0)
|
|
76
|
+
.random_shuffle(seed=seed + 1)
|
|
77
|
+
.materialize()
|
|
78
|
+
)
|
|
79
|
+
if int(treated.count()) < fold_count or int(control.count()) < fold_count:
|
|
80
|
+
raise AlgorithmExecutionError(
|
|
81
|
+
"X-Learner cross-fitting requires treated and control rows in every fold"
|
|
82
|
+
)
|
|
83
|
+
treated_folds = _split_rows(treated, fold_count)
|
|
84
|
+
control_folds = _split_rows(control, fold_count)
|
|
85
|
+
return tuple(
|
|
86
|
+
cast(Any, treated_folds[index]).union(control_folds[index])
|
|
87
|
+
for index in range(fold_count)
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _label_batch(
|
|
92
|
+
batch: object,
|
|
93
|
+
*,
|
|
94
|
+
feature_names: tuple[str, ...],
|
|
95
|
+
label_name: str,
|
|
96
|
+
) -> object:
|
|
97
|
+
frame = cast(Any, batch)
|
|
98
|
+
result = frame.loc[:, list(feature_names)].copy()
|
|
99
|
+
result[_STAGE_LABEL] = frame[label_name].to_numpy()
|
|
100
|
+
return result
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _pseudo_batch(
|
|
104
|
+
batch: object,
|
|
105
|
+
*,
|
|
106
|
+
feature_names: tuple[str, ...],
|
|
107
|
+
outcome_name: str,
|
|
108
|
+
booster_raw: bytes,
|
|
109
|
+
treated: bool,
|
|
110
|
+
) -> object:
|
|
111
|
+
import numpy as np
|
|
112
|
+
import xgboost
|
|
113
|
+
|
|
114
|
+
frame = cast(Any, batch)
|
|
115
|
+
features = frame.loc[:, list(feature_names)]
|
|
116
|
+
booster = xgboost.Booster()
|
|
117
|
+
booster.load_model(bytearray(booster_raw))
|
|
118
|
+
prediction = booster.predict(xgboost.DMatrix(features.to_numpy()))
|
|
119
|
+
observed = frame[outcome_name].to_numpy(dtype=np.float64)
|
|
120
|
+
result = features.copy()
|
|
121
|
+
result[_STAGE_LABEL] = observed - prediction if treated else prediction - observed
|
|
122
|
+
return result
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _cate_batch(
|
|
126
|
+
batch: object,
|
|
127
|
+
*,
|
|
128
|
+
feature_names: tuple[str, ...],
|
|
129
|
+
booster_raw: Mapping[str, bytes],
|
|
130
|
+
propensity_clip: tuple[float, float],
|
|
131
|
+
) -> dict[str, object]:
|
|
132
|
+
frame = cast(Any, batch)
|
|
133
|
+
model = XLearnerModel.from_raw(
|
|
134
|
+
booster_raw,
|
|
135
|
+
feature_names=feature_names,
|
|
136
|
+
response_threshold=0.5,
|
|
137
|
+
propensity_clip=propensity_clip,
|
|
138
|
+
)
|
|
139
|
+
prediction = model.predict(frame.loc[:, list(feature_names)].to_numpy())
|
|
140
|
+
return {"cate": prediction.cate}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@dataclass(frozen=True)
|
|
144
|
+
class XLearnerResult:
|
|
145
|
+
booster_raw: Mapping[str, bytes]
|
|
146
|
+
stage_evidence: Mapping[str, Mapping[str, object]]
|
|
147
|
+
feature_names: tuple[str, ...]
|
|
148
|
+
response_threshold: float
|
|
149
|
+
propensity_clip: tuple[float, float]
|
|
150
|
+
metrics: Mapping[str, object]
|
|
151
|
+
composition_digest: str
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class _XLearnerDriver:
|
|
155
|
+
def __init__(
|
|
156
|
+
self,
|
|
157
|
+
*,
|
|
158
|
+
plan: ResolvedAlgorithmPlan,
|
|
159
|
+
dataset: object,
|
|
160
|
+
) -> None:
|
|
161
|
+
self.plan = plan
|
|
162
|
+
self.dataset = dataset
|
|
163
|
+
|
|
164
|
+
def fit(self) -> XLearnerResult:
|
|
165
|
+
config = self.plan.algorithm_config
|
|
166
|
+
data = cast(Mapping[str, Any], config["data"])
|
|
167
|
+
model = cast(Mapping[str, Any], config["model"])
|
|
168
|
+
training = cast(Mapping[str, Any], config["training"])
|
|
169
|
+
ray_config = cast(Mapping[str, Any], config["ray"])
|
|
170
|
+
features = tuple(str(name) for name in data["feature_columns"])
|
|
171
|
+
treatment_name = str(data["treatment_col"])
|
|
172
|
+
outcome_name = str(data["outcome_col"])
|
|
173
|
+
dataset = cast(Any, self.dataset)
|
|
174
|
+
dataset = dataset.map_batches(
|
|
175
|
+
_validate_treatment_batch,
|
|
176
|
+
batch_format="pandas",
|
|
177
|
+
fn_kwargs={"treatment_name": treatment_name},
|
|
178
|
+
)
|
|
179
|
+
treated = dataset.filter(lambda row: row[treatment_name] == 1)
|
|
180
|
+
control = dataset.filter(lambda row: row[treatment_name] == 0)
|
|
181
|
+
treated_rows = int(treated.count())
|
|
182
|
+
control_rows = int(control.count())
|
|
183
|
+
rows = treated_rows + control_rows
|
|
184
|
+
fold_count = int(training.get("cross_fit_folds", 5))
|
|
185
|
+
if fold_count < 2 or fold_count > 20:
|
|
186
|
+
raise AlgorithmConfigurationError(
|
|
187
|
+
"training.cross_fit_folds must be between 2 and 20"
|
|
188
|
+
)
|
|
189
|
+
if treated_rows < max(
|
|
190
|
+
self.plan.runtime.worker_count, fold_count
|
|
191
|
+
) or control_rows < max(self.plan.runtime.worker_count, fold_count):
|
|
192
|
+
raise AlgorithmExecutionError(
|
|
193
|
+
"X-Learner treatment groups are too small for worker and fold coverage"
|
|
194
|
+
)
|
|
195
|
+
if rows < fold_count * 2:
|
|
196
|
+
raise AlgorithmExecutionError(
|
|
197
|
+
"X-Learner cross-fitting requires one treated and control row per fold"
|
|
198
|
+
)
|
|
199
|
+
folds = _lossless_folds(
|
|
200
|
+
dataset,
|
|
201
|
+
treatment_name,
|
|
202
|
+
fold_count,
|
|
203
|
+
seed=int(training.get("seed", 7)),
|
|
204
|
+
)
|
|
205
|
+
runner = XGBoostStageRunner(
|
|
206
|
+
worker_count=self.plan.runtime.worker_count,
|
|
207
|
+
resources_per_worker=WorkerResources(
|
|
208
|
+
num_cpus=self.plan.runtime.num_cpus,
|
|
209
|
+
num_gpus=self.plan.runtime.num_gpus,
|
|
210
|
+
custom=self.plan.runtime.custom_resources,
|
|
211
|
+
),
|
|
212
|
+
storage_path=str(ray_config["storage_path"]),
|
|
213
|
+
input_binding_digest=self.plan.primary_input_descriptor.binding_digest,
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
def labelled(source: object, label: str) -> object:
|
|
217
|
+
return cast(Any, source).map_batches(
|
|
218
|
+
_label_batch,
|
|
219
|
+
batch_format="pandas",
|
|
220
|
+
fn_kwargs={"feature_names": features, "label_name": label},
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
outcome_params = dict(cast(Mapping[str, object], model.get("outcome", {})))
|
|
224
|
+
outcome_params.setdefault("objective", "reg:squarederror")
|
|
225
|
+
effect_params = dict(cast(Mapping[str, object], model.get("effect", {})))
|
|
226
|
+
effect_params.setdefault("objective", "reg:squarederror")
|
|
227
|
+
propensity_params = dict(
|
|
228
|
+
cast(Mapping[str, object], model.get("propensity", {}))
|
|
229
|
+
)
|
|
230
|
+
propensity_params.setdefault("objective", "binary:logistic")
|
|
231
|
+
rounds = int(training.get("num_rounds", 10))
|
|
232
|
+
clip_value = training.get("propensity_clip", (0.01, 0.99))
|
|
233
|
+
propensity_clip = (float(clip_value[0]), float(clip_value[1]))
|
|
234
|
+
response_threshold = float(training.get("response_threshold", 0.5))
|
|
235
|
+
scored_folds: list[object] = []
|
|
236
|
+
stage_folds: dict[str, list[dict[str, object]]] = {name: [] for name in STAGES}
|
|
237
|
+
stage_digests: dict[str, list[str]] = {name: [] for name in STAGES}
|
|
238
|
+
for fold_index, heldout in enumerate(folds):
|
|
239
|
+
training_parts = folds[:fold_index] + folds[fold_index + 1 :]
|
|
240
|
+
train_data = cast(
|
|
241
|
+
Any,
|
|
242
|
+
(
|
|
243
|
+
training_parts[0]
|
|
244
|
+
if len(training_parts) == 1
|
|
245
|
+
else cast(Any, training_parts[0]).union(*training_parts[1:])
|
|
246
|
+
),
|
|
247
|
+
)
|
|
248
|
+
heldout_data = cast(Any, heldout)
|
|
249
|
+
train_treated = train_data.filter(lambda row: row[treatment_name] == 1)
|
|
250
|
+
train_control = train_data.filter(lambda row: row[treatment_name] == 0)
|
|
251
|
+
train_treated_rows = int(train_treated.count())
|
|
252
|
+
train_control_rows = int(train_control.count())
|
|
253
|
+
heldout_treated_rows = int(
|
|
254
|
+
heldout_data.filter(lambda row: row[treatment_name] == 1).count()
|
|
255
|
+
)
|
|
256
|
+
heldout_control_rows = int(
|
|
257
|
+
heldout_data.filter(lambda row: row[treatment_name] == 0).count()
|
|
258
|
+
)
|
|
259
|
+
if (
|
|
260
|
+
train_treated_rows < self.plan.runtime.worker_count
|
|
261
|
+
or train_control_rows < self.plan.runtime.worker_count
|
|
262
|
+
or heldout_treated_rows < 1
|
|
263
|
+
or heldout_control_rows < 1
|
|
264
|
+
):
|
|
265
|
+
raise AlgorithmExecutionError(
|
|
266
|
+
"X-Learner cross-fitting fold lacks treatment/control overlap"
|
|
267
|
+
)
|
|
268
|
+
stages = {}
|
|
269
|
+
stages["mu0"] = runner.fit(
|
|
270
|
+
f"fold-{fold_index}-mu0",
|
|
271
|
+
labelled(train_control, outcome_name),
|
|
272
|
+
feature_names=features,
|
|
273
|
+
label_name=_STAGE_LABEL,
|
|
274
|
+
params=outcome_params,
|
|
275
|
+
num_boost_round=rounds,
|
|
276
|
+
)
|
|
277
|
+
stages["mu1"] = runner.fit(
|
|
278
|
+
f"fold-{fold_index}-mu1",
|
|
279
|
+
labelled(train_treated, outcome_name),
|
|
280
|
+
feature_names=features,
|
|
281
|
+
label_name=_STAGE_LABEL,
|
|
282
|
+
params=outcome_params,
|
|
283
|
+
num_boost_round=rounds,
|
|
284
|
+
)
|
|
285
|
+
tau0_data = train_control.map_batches(
|
|
286
|
+
_pseudo_batch,
|
|
287
|
+
batch_format="pandas",
|
|
288
|
+
fn_kwargs={
|
|
289
|
+
"feature_names": features,
|
|
290
|
+
"outcome_name": outcome_name,
|
|
291
|
+
"booster_raw": stages["mu1"].booster_raw,
|
|
292
|
+
"treated": False,
|
|
293
|
+
},
|
|
294
|
+
)
|
|
295
|
+
tau1_data = train_treated.map_batches(
|
|
296
|
+
_pseudo_batch,
|
|
297
|
+
batch_format="pandas",
|
|
298
|
+
fn_kwargs={
|
|
299
|
+
"feature_names": features,
|
|
300
|
+
"outcome_name": outcome_name,
|
|
301
|
+
"booster_raw": stages["mu0"].booster_raw,
|
|
302
|
+
"treated": True,
|
|
303
|
+
},
|
|
304
|
+
)
|
|
305
|
+
stages["tau0"] = runner.fit(
|
|
306
|
+
f"fold-{fold_index}-tau0",
|
|
307
|
+
tau0_data,
|
|
308
|
+
feature_names=features,
|
|
309
|
+
label_name=_STAGE_LABEL,
|
|
310
|
+
params=effect_params,
|
|
311
|
+
num_boost_round=rounds,
|
|
312
|
+
)
|
|
313
|
+
stages["tau1"] = runner.fit(
|
|
314
|
+
f"fold-{fold_index}-tau1",
|
|
315
|
+
tau1_data,
|
|
316
|
+
feature_names=features,
|
|
317
|
+
label_name=_STAGE_LABEL,
|
|
318
|
+
params=effect_params,
|
|
319
|
+
num_boost_round=rounds,
|
|
320
|
+
)
|
|
321
|
+
stages["propensity"] = runner.fit(
|
|
322
|
+
f"fold-{fold_index}-propensity",
|
|
323
|
+
labelled(train_data, treatment_name),
|
|
324
|
+
feature_names=features,
|
|
325
|
+
label_name=_STAGE_LABEL,
|
|
326
|
+
params=propensity_params,
|
|
327
|
+
num_boost_round=rounds,
|
|
328
|
+
)
|
|
329
|
+
raw = {name: stages[name].booster_raw for name in STAGES}
|
|
330
|
+
scored_folds.append(
|
|
331
|
+
heldout_data.map_batches(
|
|
332
|
+
_cate_batch,
|
|
333
|
+
batch_format="pandas",
|
|
334
|
+
fn_kwargs={
|
|
335
|
+
"feature_names": features,
|
|
336
|
+
"booster_raw": raw,
|
|
337
|
+
"propensity_clip": propensity_clip,
|
|
338
|
+
},
|
|
339
|
+
)
|
|
340
|
+
)
|
|
341
|
+
for name in STAGES:
|
|
342
|
+
evidence = dict(cast(Mapping[str, object], stages[name].evidence))
|
|
343
|
+
evidence["heldout_rows"] = heldout_treated_rows + heldout_control_rows
|
|
344
|
+
evidence["fold_index"] = fold_index
|
|
345
|
+
stage_folds[name].append(evidence)
|
|
346
|
+
stage_digests[name].append(
|
|
347
|
+
str(
|
|
348
|
+
cast(Mapping[str, Any], stages[name].evidence["state"])[
|
|
349
|
+
"global_model_digest"
|
|
350
|
+
]
|
|
351
|
+
)
|
|
352
|
+
)
|
|
353
|
+
cate_mean = float(
|
|
354
|
+
cast(Any, scored_folds[0]).union(*scored_folds[1:]).mean("cate")
|
|
355
|
+
)
|
|
356
|
+
stage_evidence = {
|
|
357
|
+
name: {
|
|
358
|
+
"workers": stage_folds[name][0]["workers"],
|
|
359
|
+
"state": stage_folds[name][0]["state"],
|
|
360
|
+
"input_complete": True,
|
|
361
|
+
"expected_training_rows": rows,
|
|
362
|
+
"cross_fit_folds": stage_folds[name],
|
|
363
|
+
}
|
|
364
|
+
for name in STAGES
|
|
365
|
+
}
|
|
366
|
+
composition_digest = hashlib.sha256(
|
|
367
|
+
json.dumps(stage_digests, sort_keys=True, separators=(",", ":")).encode()
|
|
368
|
+
).hexdigest()
|
|
369
|
+
return XLearnerResult(
|
|
370
|
+
booster_raw=raw,
|
|
371
|
+
stage_evidence=stage_evidence,
|
|
372
|
+
feature_names=features,
|
|
373
|
+
response_threshold=response_threshold,
|
|
374
|
+
propensity_clip=propensity_clip,
|
|
375
|
+
metrics={
|
|
376
|
+
"ate": cate_mean,
|
|
377
|
+
"treated_rows": treated_rows,
|
|
378
|
+
"control_rows": control_rows,
|
|
379
|
+
"cross_fit_folds": fold_count,
|
|
380
|
+
},
|
|
381
|
+
composition_digest=composition_digest,
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
class DistributedXLearner(FrameworkNativeAlgorithm):
|
|
386
|
+
def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
|
|
387
|
+
self.plan = plan
|
|
388
|
+
|
|
389
|
+
def validate_environment(self) -> None:
|
|
390
|
+
try:
|
|
391
|
+
import xgboost
|
|
392
|
+
except ImportError as exc:
|
|
393
|
+
raise AlgorithmConfigurationError("X-Learner requires XGBoost") from exc
|
|
394
|
+
if not xgboost.__version__:
|
|
395
|
+
raise AlgorithmConfigurationError("X-Learner environment is invalid")
|
|
396
|
+
|
|
397
|
+
def bind_datasets(self, datasets: Mapping[str, object]) -> Mapping[str, object]:
|
|
398
|
+
if len(datasets) != 1:
|
|
399
|
+
raise AlgorithmConfigurationError("X-Learner requires one Dataset")
|
|
400
|
+
dataset = next(iter(datasets.values()))
|
|
401
|
+
data = cast(Mapping[str, Any], self.plan.algorithm_config["data"])
|
|
402
|
+
features = tuple(data["feature_columns"])
|
|
403
|
+
required = (
|
|
404
|
+
*features,
|
|
405
|
+
str(data["treatment_col"]),
|
|
406
|
+
str(data["outcome_col"]),
|
|
407
|
+
str(data["identity_col"]),
|
|
408
|
+
)
|
|
409
|
+
binding = self.plan.primary_input_binding
|
|
410
|
+
if set(binding.feature_names) != set(required) - {str(data["outcome_col"])}:
|
|
411
|
+
raise AlgorithmConfigurationError("X-Learner InputBinding columns drifted")
|
|
412
|
+
if binding.label_name != data["outcome_col"]:
|
|
413
|
+
raise AlgorithmConfigurationError("X-Learner outcome label drifted")
|
|
414
|
+
return {"train": cast(Any, dataset).select_columns(list(required))}
|
|
415
|
+
|
|
416
|
+
def build_trainer(
|
|
417
|
+
self, config: Mapping[str, Any], datasets: Mapping[str, object]
|
|
418
|
+
) -> object:
|
|
419
|
+
del config
|
|
420
|
+
return _XLearnerDriver(plan=self.plan, dataset=datasets["train"])
|
|
421
|
+
|
|
422
|
+
def collect_evidence(self, result: object) -> Mapping[str, Any]:
|
|
423
|
+
if not isinstance(result, XLearnerResult):
|
|
424
|
+
raise AlgorithmExecutionError("X-Learner returned an invalid result")
|
|
425
|
+
return {
|
|
426
|
+
"stages": dict(result.stage_evidence),
|
|
427
|
+
"composition_digest": result.composition_digest,
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
def checkpoint_source(self, result: object) -> object:
|
|
431
|
+
if not isinstance(result, XLearnerResult):
|
|
432
|
+
raise AlgorithmExecutionError("X-Learner checkpoint result is invalid")
|
|
433
|
+
return result
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def create_algorithm(
|
|
437
|
+
*,
|
|
438
|
+
plan: ResolvedAlgorithmPlan,
|
|
439
|
+
implementation: object,
|
|
440
|
+
artifacts: tuple[object, ...],
|
|
441
|
+
) -> DistributedXLearner:
|
|
442
|
+
del artifacts
|
|
443
|
+
if implementation is not DistributedXLearner:
|
|
444
|
+
raise AlgorithmConfigurationError("X-Learner implementation drifted")
|
|
445
|
+
return DistributedXLearner(plan)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
__all__ = ["DistributedXLearner", "XLearnerResult", "create_algorithm"]
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Executable contracts for official X-Learner."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class XLearnerConfigValidator:
|
|
10
|
+
api_version = 1
|
|
11
|
+
schema_digest = "6" * 64
|
|
12
|
+
|
|
13
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
14
|
+
allowed = {"data", "model", "output", "ray", "training"}
|
|
15
|
+
if unknown := sorted(set(value) - allowed):
|
|
16
|
+
raise ValueError(f"unknown X-Learner config keys: {unknown}")
|
|
17
|
+
training = value.get("training")
|
|
18
|
+
if not isinstance(training, Mapping):
|
|
19
|
+
raise ValueError("training config is required")
|
|
20
|
+
folds = training.get("cross_fit_folds", 5)
|
|
21
|
+
if (
|
|
22
|
+
not isinstance(folds, int)
|
|
23
|
+
or isinstance(folds, bool)
|
|
24
|
+
or not 2 <= folds <= 20
|
|
25
|
+
):
|
|
26
|
+
raise ValueError("training.cross_fit_folds must be between 2 and 20")
|
|
27
|
+
for name in allowed:
|
|
28
|
+
if not isinstance(value.get(name), Mapping):
|
|
29
|
+
raise ValueError(f"{name} config is required")
|
|
30
|
+
data = value["data"]
|
|
31
|
+
for name in ("feature_columns", "treatment_col", "outcome_col", "identity_col"):
|
|
32
|
+
if not data.get(name):
|
|
33
|
+
raise ValueError(f"data.{name} is required")
|
|
34
|
+
if not value["ray"].get("storage_path") or not value["output"].get(
|
|
35
|
+
"bundle_uri"
|
|
36
|
+
):
|
|
37
|
+
raise ValueError("ray.storage_path and output.bundle_uri are required")
|
|
38
|
+
return dict(value)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class XLearnerInputValidator:
|
|
42
|
+
api_version = 1
|
|
43
|
+
schema_digest = "2" * 64
|
|
44
|
+
|
|
45
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
46
|
+
bindings = value.get("bindings")
|
|
47
|
+
if not isinstance(bindings, list) or len(bindings) != 1:
|
|
48
|
+
raise ValueError("X-Learner requires one train binding")
|
|
49
|
+
binding = bindings[0]
|
|
50
|
+
if (
|
|
51
|
+
not isinstance(binding, Mapping)
|
|
52
|
+
or len(binding.get("feature_names", ())) < 3
|
|
53
|
+
or not binding.get("label_name")
|
|
54
|
+
):
|
|
55
|
+
raise ValueError("X-Learner input roles are incomplete")
|
|
56
|
+
return value
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class XLearnerOutputValidator:
|
|
60
|
+
api_version = 1
|
|
61
|
+
schema_digest = "3" * 64
|
|
62
|
+
|
|
63
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
64
|
+
outputs = value.get("outputs")
|
|
65
|
+
if value.get("status") != "succeeded" or not isinstance(outputs, Mapping):
|
|
66
|
+
raise ValueError("X-Learner execution failed")
|
|
67
|
+
if not outputs.get("bundle_uri") or not outputs.get("composition_digest"):
|
|
68
|
+
raise ValueError("X-Learner output requires Bundle and composition digest")
|
|
69
|
+
return value
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class XLearnerCoverageValidator:
|
|
73
|
+
api_version = 1
|
|
74
|
+
schema_digest = "4" * 64
|
|
75
|
+
|
|
76
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
77
|
+
if (
|
|
78
|
+
value.get("input_complete") is not True
|
|
79
|
+
or value.get("distributed") is not True
|
|
80
|
+
):
|
|
81
|
+
raise ValueError("X-Learner coverage is incomplete")
|
|
82
|
+
state = value.get("state")
|
|
83
|
+
details = state.get("details") if isinstance(state, Mapping) else None
|
|
84
|
+
if not isinstance(details, Mapping):
|
|
85
|
+
raise ValueError("X-Learner stage evidence is missing")
|
|
86
|
+
expected = "mu0,mu1,tau0,tau1,propensity"
|
|
87
|
+
if details.get("component_stages") != expected:
|
|
88
|
+
raise ValueError("X-Learner stage set drifted")
|
|
89
|
+
return value
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
__all__ = [
|
|
93
|
+
"XLearnerConfigValidator",
|
|
94
|
+
"XLearnerCoverageValidator",
|
|
95
|
+
"XLearnerInputValidator",
|
|
96
|
+
"XLearnerOutputValidator",
|
|
97
|
+
]
|