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,110 @@
|
|
|
1
|
+
"""Descriptor for distributed DoWhy GCM root-cause analysis."""
|
|
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 = ("fit_gcm", "attribute_root_cause")
|
|
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_dowhy.contracts:{validator}"
|
|
33
|
+
),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
_SPEC = AlgorithmSpec(
|
|
38
|
+
name="gcm_root_cause",
|
|
39
|
+
trainer_cls=None,
|
|
40
|
+
version="1.0.0",
|
|
41
|
+
default_config={},
|
|
42
|
+
supported_tasks=("fit",),
|
|
43
|
+
operations=("fit",),
|
|
44
|
+
problem_types=(
|
|
45
|
+
ProblemType.ANOMALY_DETECTION,
|
|
46
|
+
ProblemType.CAUSAL_EFFECT_ESTIMATION,
|
|
47
|
+
),
|
|
48
|
+
capabilities=(Capability.DISTRIBUTED, Capability.EXPORTABLE, Capability.TUNABLE),
|
|
49
|
+
learning_paradigm="causal_root_cause_and_counterfactual",
|
|
50
|
+
model_family="dowhy_gcm_shard_ensemble",
|
|
51
|
+
data_modalities=("tabular",),
|
|
52
|
+
lifecycle_kind="fit_attribute_counterfactual_report",
|
|
53
|
+
allowed_execution_modes=(ExecutionMode.FRAMEWORK_NATIVE.value,),
|
|
54
|
+
config_contract_ref="tributo.official.causal.gcm.config.v1",
|
|
55
|
+
input_contract_ref="tributo.official.causal.gcm.train-anomaly.v1",
|
|
56
|
+
output_contract_ref="tributo.official.causal.gcm.report-bundle.v1",
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
GCM_DESCRIPTOR = AlgorithmBuilder.from_distributed_algorithm(
|
|
60
|
+
spec=_SPEC,
|
|
61
|
+
implementation_id="tributo.official.causal_dowhy.gcm_root_cause",
|
|
62
|
+
implementation_version="1.0.0",
|
|
63
|
+
implementation="tributo_algorithms_causal_dowhy.gcm:DistributedGCMRootCause",
|
|
64
|
+
executable_factory=("tributo_algorithms_causal_dowhy.gcm:create_gcm_algorithm"),
|
|
65
|
+
distribution=_PACKAGE,
|
|
66
|
+
framework="dowhy-gcm",
|
|
67
|
+
environment=EnvironmentSpec(
|
|
68
|
+
environment_id="tributo.official.causal-dowhy-gcm.v1",
|
|
69
|
+
dependencies=(
|
|
70
|
+
"dowhy>=0.14,<0.15",
|
|
71
|
+
"networkx>=3.0",
|
|
72
|
+
"onnx>=1.16",
|
|
73
|
+
"onnxruntime>=1.20",
|
|
74
|
+
"tributo>=1.1",
|
|
75
|
+
f"tributo-algorithms[causal-dowhy]=={_VERSION}",
|
|
76
|
+
),
|
|
77
|
+
),
|
|
78
|
+
allowed_config_keys=("data", "gcm", "output", "runtime"),
|
|
79
|
+
strategy=DistributionStrategy.FRAMEWORK_NATIVE,
|
|
80
|
+
supported_worker_range=WorkerRange(2, 64),
|
|
81
|
+
supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
|
|
82
|
+
resources_per_worker=WorkerResources(num_cpus=1),
|
|
83
|
+
policy=FrameworkNativePolicy(
|
|
84
|
+
framework="dowhy-gcm-shard-ensemble",
|
|
85
|
+
evidence_collector_ref=(
|
|
86
|
+
"tributo_algorithms_causal_dowhy.gcm:"
|
|
87
|
+
"DistributedGCMRootCause.collect_evidence"
|
|
88
|
+
),
|
|
89
|
+
component_stages=STAGES,
|
|
90
|
+
),
|
|
91
|
+
package_name=_PACKAGE,
|
|
92
|
+
package_version=_VERSION,
|
|
93
|
+
tributo_version_spec=">=1.1",
|
|
94
|
+
exporter="tributo_algorithms_causal_dowhy.gcm:export_gcm_result",
|
|
95
|
+
flavor_id="onnx-runtime-v1",
|
|
96
|
+
contract_bindings=ContractBindingSet(
|
|
97
|
+
config=_binding(_SPEC.config_contract_ref or "", "2", "GCMConfigValidator"),
|
|
98
|
+
input=_binding(_SPEC.input_contract_ref or "", "3", "GCMInputValidator"),
|
|
99
|
+
output=_binding(_SPEC.output_contract_ref or "", "4", "GCMOutputValidator"),
|
|
100
|
+
coverage=_binding(
|
|
101
|
+
"tributo.official.causal.gcm-coverage.v1",
|
|
102
|
+
"5",
|
|
103
|
+
"GCMCoverageValidator",
|
|
104
|
+
),
|
|
105
|
+
),
|
|
106
|
+
descriptor_api_version=2,
|
|
107
|
+
is_default=True,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
__all__ = ["GCM_DESCRIPTOR"]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Official distributed doubly robust estimators with lazy runtime exports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from tributo_algorithms_causal_dr.descriptor import DR_DESCRIPTOR
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def __getattr__(name: str) -> Any:
|
|
11
|
+
if name != "DistributedDRLearner":
|
|
12
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
13
|
+
import importlib
|
|
14
|
+
|
|
15
|
+
value = getattr(
|
|
16
|
+
importlib.import_module("tributo_algorithms_causal_dr.algorithm"), name
|
|
17
|
+
)
|
|
18
|
+
globals()[name] = value
|
|
19
|
+
return value
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
__all__ = ["DR_DESCRIPTOR", "DistributedDRLearner"]
|
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
"""Three-stage distributed AIPW/Doubly Robust ATE estimator."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any, cast
|
|
11
|
+
|
|
12
|
+
from tributo.algorithms.api import (
|
|
13
|
+
AlgorithmConfigurationError,
|
|
14
|
+
AlgorithmExecutionError,
|
|
15
|
+
AlgorithmExecutionResult,
|
|
16
|
+
ResolvedAlgorithmPlan,
|
|
17
|
+
WorkerResources,
|
|
18
|
+
)
|
|
19
|
+
from tributo.algorithms.spi import FrameworkNativeAlgorithm
|
|
20
|
+
from tributo_algorithms_boosting import XGBoostStageRunner
|
|
21
|
+
from tributo_algorithms_causal_core.algorithm import CausalATEModel, export_model
|
|
22
|
+
|
|
23
|
+
STAGES = ("mu0", "mu1", "propensity")
|
|
24
|
+
_LABEL = "__tributo_dr_label"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _split_rows(materialized: object, fold_count: int) -> tuple[object, ...]:
|
|
28
|
+
"""Split a materialized Dataset by row indices without dropping rows."""
|
|
29
|
+
rows = int(cast(Any, materialized).count())
|
|
30
|
+
base, remainder = divmod(rows, fold_count)
|
|
31
|
+
boundaries: list[int] = []
|
|
32
|
+
cursor = 0
|
|
33
|
+
for index in range(fold_count - 1):
|
|
34
|
+
cursor += base + (1 if index < remainder else 0)
|
|
35
|
+
boundaries.append(cursor)
|
|
36
|
+
return tuple(cast(Any, materialized).split_at_indices(boundaries))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _validate_treatment_batch(batch: object, *, treatment_name: str) -> object:
|
|
40
|
+
"""Reject missing, non-finite, or non-binary treatment values."""
|
|
41
|
+
import numpy as np
|
|
42
|
+
|
|
43
|
+
frame = cast(Any, batch)
|
|
44
|
+
if treatment_name not in frame.columns:
|
|
45
|
+
raise ValueError(f"treatment column {treatment_name!r} is missing")
|
|
46
|
+
try:
|
|
47
|
+
treatment = frame[treatment_name].to_numpy(dtype=np.float64)
|
|
48
|
+
except (TypeError, ValueError, OverflowError) as error:
|
|
49
|
+
raise ValueError("DR treatment values must be numeric binary values") from error
|
|
50
|
+
if not np.isfinite(treatment).all():
|
|
51
|
+
raise ValueError("DR treatment values must be finite")
|
|
52
|
+
if not np.isin(treatment, (0.0, 1.0)).all():
|
|
53
|
+
raise ValueError("DR 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
|
+
"DR 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[_LABEL] = frame[label_name].to_numpy()
|
|
100
|
+
return result
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _score_batch(
|
|
104
|
+
batch: object,
|
|
105
|
+
*,
|
|
106
|
+
feature_names: tuple[str, ...],
|
|
107
|
+
treatment_name: str,
|
|
108
|
+
outcome_name: str,
|
|
109
|
+
booster_raw: Mapping[str, bytes],
|
|
110
|
+
propensity_clip: tuple[float, float],
|
|
111
|
+
) -> dict[str, object]:
|
|
112
|
+
import numpy as np
|
|
113
|
+
import xgboost
|
|
114
|
+
|
|
115
|
+
frame = cast(Any, batch)
|
|
116
|
+
matrix = xgboost.DMatrix(frame.loc[:, list(feature_names)].to_numpy())
|
|
117
|
+
|
|
118
|
+
def predict(stage: str) -> Any:
|
|
119
|
+
booster = xgboost.Booster()
|
|
120
|
+
booster.load_model(bytearray(booster_raw[stage]))
|
|
121
|
+
return booster.predict(matrix)
|
|
122
|
+
|
|
123
|
+
mu0 = predict("mu0")
|
|
124
|
+
mu1 = predict("mu1")
|
|
125
|
+
propensity = np.clip(predict("propensity"), propensity_clip[0], propensity_clip[1])
|
|
126
|
+
treatment = frame[treatment_name].to_numpy(dtype=np.float64)
|
|
127
|
+
outcome = frame[outcome_name].to_numpy(dtype=np.float64)
|
|
128
|
+
score = (
|
|
129
|
+
mu1
|
|
130
|
+
- mu0
|
|
131
|
+
+ treatment * (outcome - mu1) / propensity
|
|
132
|
+
- (1.0 - treatment) * (outcome - mu0) / (1.0 - propensity)
|
|
133
|
+
)
|
|
134
|
+
return {"dr_score": score}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(frozen=True)
|
|
138
|
+
class DRResult:
|
|
139
|
+
model: CausalATEModel
|
|
140
|
+
stage_evidence: Mapping[str, Mapping[str, object]]
|
|
141
|
+
composition_digest: str
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class _DRDriver:
|
|
145
|
+
def __init__(self, *, plan: ResolvedAlgorithmPlan, dataset: object) -> None:
|
|
146
|
+
self.plan = plan
|
|
147
|
+
self.dataset = dataset
|
|
148
|
+
|
|
149
|
+
def fit(self) -> DRResult:
|
|
150
|
+
config = self.plan.algorithm_config
|
|
151
|
+
data = cast(Mapping[str, Any], config["data"])
|
|
152
|
+
model_config = cast(Mapping[str, Any], config["model"])
|
|
153
|
+
training = cast(Mapping[str, Any], config["training"])
|
|
154
|
+
ray_config = cast(Mapping[str, Any], config["ray"])
|
|
155
|
+
features = tuple(str(name) for name in data["feature_columns"])
|
|
156
|
+
treatment_name = str(data["treatment_col"])
|
|
157
|
+
outcome_name = str(data["outcome_col"])
|
|
158
|
+
dataset = cast(Any, self.dataset)
|
|
159
|
+
dataset = dataset.map_batches(
|
|
160
|
+
_validate_treatment_batch,
|
|
161
|
+
batch_format="pandas",
|
|
162
|
+
fn_kwargs={"treatment_name": treatment_name},
|
|
163
|
+
)
|
|
164
|
+
treated = dataset.filter(lambda row: row[treatment_name] == 1)
|
|
165
|
+
control = dataset.filter(lambda row: row[treatment_name] == 0)
|
|
166
|
+
treated_rows = int(treated.count())
|
|
167
|
+
control_rows = int(control.count())
|
|
168
|
+
rows = treated_rows + control_rows
|
|
169
|
+
fold_count = int(training.get("cross_fit_folds", 5))
|
|
170
|
+
if fold_count < 2 or fold_count > 20:
|
|
171
|
+
raise AlgorithmConfigurationError(
|
|
172
|
+
"training.cross_fit_folds must be between 2 and 20"
|
|
173
|
+
)
|
|
174
|
+
if treated_rows < max(
|
|
175
|
+
self.plan.runtime.worker_count, fold_count
|
|
176
|
+
) or control_rows < max(self.plan.runtime.worker_count, fold_count):
|
|
177
|
+
raise AlgorithmExecutionError(
|
|
178
|
+
"DR treatment groups are too small for worker and fold coverage"
|
|
179
|
+
)
|
|
180
|
+
if rows < fold_count * 2:
|
|
181
|
+
raise AlgorithmExecutionError(
|
|
182
|
+
"DR cross-fitting requires at least one treated and control row per fold"
|
|
183
|
+
)
|
|
184
|
+
folds = _lossless_folds(
|
|
185
|
+
dataset,
|
|
186
|
+
treatment_name,
|
|
187
|
+
fold_count,
|
|
188
|
+
seed=int(training.get("seed", 7)),
|
|
189
|
+
)
|
|
190
|
+
if len(folds) != fold_count:
|
|
191
|
+
raise AlgorithmExecutionError(
|
|
192
|
+
"DR cross-fitting produced an invalid fold set"
|
|
193
|
+
)
|
|
194
|
+
runner = XGBoostStageRunner(
|
|
195
|
+
worker_count=self.plan.runtime.worker_count,
|
|
196
|
+
resources_per_worker=WorkerResources(
|
|
197
|
+
num_cpus=self.plan.runtime.num_cpus,
|
|
198
|
+
num_gpus=self.plan.runtime.num_gpus,
|
|
199
|
+
custom=self.plan.runtime.custom_resources,
|
|
200
|
+
),
|
|
201
|
+
storage_path=str(ray_config["storage_path"]),
|
|
202
|
+
input_binding_digest=self.plan.primary_input_descriptor.binding_digest,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
def labelled(source: object, label: str) -> object:
|
|
206
|
+
return cast(Any, source).map_batches(
|
|
207
|
+
_label_batch,
|
|
208
|
+
batch_format="pandas",
|
|
209
|
+
fn_kwargs={"feature_names": features, "label_name": label},
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
outcome_params = dict(
|
|
213
|
+
cast(Mapping[str, object], model_config.get("outcome", {}))
|
|
214
|
+
)
|
|
215
|
+
outcome_params.setdefault("objective", "reg:squarederror")
|
|
216
|
+
propensity_params = dict(
|
|
217
|
+
cast(Mapping[str, object], model_config.get("propensity", {}))
|
|
218
|
+
)
|
|
219
|
+
propensity_params.setdefault("objective", "binary:logistic")
|
|
220
|
+
rounds = int(training.get("num_rounds", 10))
|
|
221
|
+
clip_value = training.get("propensity_clip", (0.01, 0.99))
|
|
222
|
+
propensity_clip = (float(clip_value[0]), float(clip_value[1]))
|
|
223
|
+
scored_folds: list[object] = []
|
|
224
|
+
stage_folds: dict[str, list[dict[str, object]]] = {name: [] for name in STAGES}
|
|
225
|
+
stage_digests: dict[str, list[str]] = {name: [] for name in STAGES}
|
|
226
|
+
for fold_index, heldout in enumerate(folds):
|
|
227
|
+
training_parts = folds[:fold_index] + folds[fold_index + 1 :]
|
|
228
|
+
train_data = cast(
|
|
229
|
+
Any,
|
|
230
|
+
(
|
|
231
|
+
training_parts[0]
|
|
232
|
+
if len(training_parts) == 1
|
|
233
|
+
else cast(Any, training_parts[0]).union(*training_parts[1:])
|
|
234
|
+
),
|
|
235
|
+
)
|
|
236
|
+
heldout_data = cast(Any, heldout)
|
|
237
|
+
train_treated = train_data.filter(lambda row: row[treatment_name] == 1)
|
|
238
|
+
train_control = train_data.filter(lambda row: row[treatment_name] == 0)
|
|
239
|
+
train_treated_rows = int(train_treated.count())
|
|
240
|
+
train_control_rows = int(train_control.count())
|
|
241
|
+
heldout_treated_rows = int(
|
|
242
|
+
heldout_data.filter(lambda row: row[treatment_name] == 1).count()
|
|
243
|
+
)
|
|
244
|
+
heldout_control_rows = int(
|
|
245
|
+
heldout_data.filter(lambda row: row[treatment_name] == 0).count()
|
|
246
|
+
)
|
|
247
|
+
if (
|
|
248
|
+
train_treated_rows < self.plan.runtime.worker_count
|
|
249
|
+
or train_control_rows < self.plan.runtime.worker_count
|
|
250
|
+
or heldout_treated_rows < 1
|
|
251
|
+
or heldout_control_rows < 1
|
|
252
|
+
):
|
|
253
|
+
raise AlgorithmExecutionError(
|
|
254
|
+
"DR cross-fitting fold lacks treatment/control overlap"
|
|
255
|
+
)
|
|
256
|
+
stages = {
|
|
257
|
+
"mu0": runner.fit(
|
|
258
|
+
f"fold-{fold_index}-mu0",
|
|
259
|
+
labelled(train_control, outcome_name),
|
|
260
|
+
feature_names=features,
|
|
261
|
+
label_name=_LABEL,
|
|
262
|
+
params=outcome_params,
|
|
263
|
+
num_boost_round=rounds,
|
|
264
|
+
),
|
|
265
|
+
"mu1": runner.fit(
|
|
266
|
+
f"fold-{fold_index}-mu1",
|
|
267
|
+
labelled(train_treated, outcome_name),
|
|
268
|
+
feature_names=features,
|
|
269
|
+
label_name=_LABEL,
|
|
270
|
+
params=outcome_params,
|
|
271
|
+
num_boost_round=rounds,
|
|
272
|
+
),
|
|
273
|
+
"propensity": runner.fit(
|
|
274
|
+
f"fold-{fold_index}-propensity",
|
|
275
|
+
labelled(train_data, treatment_name),
|
|
276
|
+
feature_names=features,
|
|
277
|
+
label_name=_LABEL,
|
|
278
|
+
params=propensity_params,
|
|
279
|
+
num_boost_round=rounds,
|
|
280
|
+
),
|
|
281
|
+
}
|
|
282
|
+
raw = {name: stages[name].booster_raw for name in STAGES}
|
|
283
|
+
scored_folds.append(
|
|
284
|
+
heldout_data.map_batches(
|
|
285
|
+
_score_batch,
|
|
286
|
+
batch_format="pandas",
|
|
287
|
+
fn_kwargs={
|
|
288
|
+
"feature_names": features,
|
|
289
|
+
"treatment_name": treatment_name,
|
|
290
|
+
"outcome_name": outcome_name,
|
|
291
|
+
"booster_raw": raw,
|
|
292
|
+
"propensity_clip": propensity_clip,
|
|
293
|
+
},
|
|
294
|
+
)
|
|
295
|
+
)
|
|
296
|
+
for name in STAGES:
|
|
297
|
+
stage = stages[name]
|
|
298
|
+
evidence = dict(cast(Mapping[str, object], stage.evidence))
|
|
299
|
+
evidence["heldout_rows"] = int(
|
|
300
|
+
heldout_treated_rows + heldout_control_rows
|
|
301
|
+
)
|
|
302
|
+
evidence["fold_index"] = fold_index
|
|
303
|
+
stage_folds[name].append(evidence)
|
|
304
|
+
stage_digests[name].append(
|
|
305
|
+
str(
|
|
306
|
+
cast(Mapping[str, Any], stage.evidence["state"])[
|
|
307
|
+
"global_model_digest"
|
|
308
|
+
]
|
|
309
|
+
)
|
|
310
|
+
)
|
|
311
|
+
scores = cast(Any, scored_folds[0]).union(*scored_folds[1:])
|
|
312
|
+
effect = float(scores.mean("dr_score"))
|
|
313
|
+
standard_error = float(scores.std("dr_score")) / math.sqrt(rows)
|
|
314
|
+
z = float(training.get("confidence_z", 1.959963984540054))
|
|
315
|
+
policy_cost = float(training.get("policy_cost", 0.0))
|
|
316
|
+
treated_mean = float(treated.mean(outcome_name))
|
|
317
|
+
control_mean = float(control.mean(outcome_name))
|
|
318
|
+
stage_evidence = {
|
|
319
|
+
name: {
|
|
320
|
+
"workers": stage_folds[name][0]["workers"],
|
|
321
|
+
"state": stage_folds[name][0]["state"],
|
|
322
|
+
"input_complete": True,
|
|
323
|
+
"expected_training_rows": rows,
|
|
324
|
+
"cross_fit_folds": stage_folds[name],
|
|
325
|
+
}
|
|
326
|
+
for name in STAGES
|
|
327
|
+
}
|
|
328
|
+
composition_digest = hashlib.sha256(
|
|
329
|
+
json.dumps(stage_digests, sort_keys=True, separators=(",", ":")).encode()
|
|
330
|
+
).hexdigest()
|
|
331
|
+
causal_model = CausalATEModel(
|
|
332
|
+
method="distributed_aipw_dr",
|
|
333
|
+
treatment=treatment_name,
|
|
334
|
+
outcome=outcome_name,
|
|
335
|
+
feature_names=features,
|
|
336
|
+
treated_count=treated_rows,
|
|
337
|
+
control_count=control_rows,
|
|
338
|
+
treated_mean=treated_mean,
|
|
339
|
+
control_mean=control_mean,
|
|
340
|
+
effect=effect,
|
|
341
|
+
standard_error=standard_error,
|
|
342
|
+
confidence_interval=(
|
|
343
|
+
effect - z * standard_error,
|
|
344
|
+
effect + z * standard_error,
|
|
345
|
+
),
|
|
346
|
+
policy_cost=policy_cost,
|
|
347
|
+
treat_all_policy=effect > policy_cost,
|
|
348
|
+
diagnostics={
|
|
349
|
+
"propensity_clip_low": propensity_clip[0],
|
|
350
|
+
"propensity_clip_high": propensity_clip[1],
|
|
351
|
+
"cross_fit_folds": fold_count,
|
|
352
|
+
},
|
|
353
|
+
)
|
|
354
|
+
return DRResult(
|
|
355
|
+
model=causal_model,
|
|
356
|
+
stage_evidence=stage_evidence,
|
|
357
|
+
composition_digest=composition_digest,
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
class DistributedDRLearner(FrameworkNativeAlgorithm):
|
|
362
|
+
def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
|
|
363
|
+
self.plan = plan
|
|
364
|
+
|
|
365
|
+
def validate_environment(self) -> None:
|
|
366
|
+
try:
|
|
367
|
+
import xgboost
|
|
368
|
+
except ImportError as exc:
|
|
369
|
+
raise AlgorithmConfigurationError("DR estimator requires XGBoost") from exc
|
|
370
|
+
if not xgboost.__version__:
|
|
371
|
+
raise AlgorithmConfigurationError("DR environment is invalid")
|
|
372
|
+
|
|
373
|
+
def bind_datasets(self, datasets: Mapping[str, object]) -> Mapping[str, object]:
|
|
374
|
+
if len(datasets) != 1:
|
|
375
|
+
raise AlgorithmConfigurationError("DR estimator requires one Dataset")
|
|
376
|
+
dataset = next(iter(datasets.values()))
|
|
377
|
+
data = cast(Mapping[str, Any], self.plan.algorithm_config["data"])
|
|
378
|
+
required = (
|
|
379
|
+
*tuple(data["feature_columns"]),
|
|
380
|
+
str(data["treatment_col"]),
|
|
381
|
+
str(data["outcome_col"]),
|
|
382
|
+
)
|
|
383
|
+
binding = self.plan.primary_input_binding
|
|
384
|
+
if set(binding.feature_names) != set(required) - {str(data["outcome_col"])}:
|
|
385
|
+
raise AlgorithmConfigurationError("DR InputBinding columns drifted")
|
|
386
|
+
if binding.label_name != data["outcome_col"]:
|
|
387
|
+
raise AlgorithmConfigurationError("DR outcome label drifted")
|
|
388
|
+
return {"train": cast(Any, dataset).select_columns(list(required))}
|
|
389
|
+
|
|
390
|
+
def build_trainer(
|
|
391
|
+
self, config: Mapping[str, Any], datasets: Mapping[str, object]
|
|
392
|
+
) -> object:
|
|
393
|
+
del config
|
|
394
|
+
return _DRDriver(plan=self.plan, dataset=datasets["train"])
|
|
395
|
+
|
|
396
|
+
def collect_evidence(self, result: object) -> Mapping[str, Any]:
|
|
397
|
+
if not isinstance(result, DRResult):
|
|
398
|
+
raise AlgorithmExecutionError("DR returned an invalid result")
|
|
399
|
+
return {
|
|
400
|
+
"stages": dict(result.stage_evidence),
|
|
401
|
+
"composition_digest": result.composition_digest,
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
def checkpoint_source(self, result: object) -> object:
|
|
405
|
+
if not isinstance(result, DRResult):
|
|
406
|
+
raise AlgorithmExecutionError("DR checkpoint result is invalid")
|
|
407
|
+
return result
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def create_algorithm(
|
|
411
|
+
*,
|
|
412
|
+
plan: ResolvedAlgorithmPlan,
|
|
413
|
+
implementation: object,
|
|
414
|
+
artifacts: tuple[object, ...],
|
|
415
|
+
) -> DistributedDRLearner:
|
|
416
|
+
del artifacts
|
|
417
|
+
if implementation is not DistributedDRLearner:
|
|
418
|
+
raise AlgorithmConfigurationError("DR implementation drifted")
|
|
419
|
+
return DistributedDRLearner(plan)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def export_result(
|
|
423
|
+
*, result: object, checkpoint: object, plan: ResolvedAlgorithmPlan, run_id: str
|
|
424
|
+
) -> AlgorithmExecutionResult:
|
|
425
|
+
del checkpoint
|
|
426
|
+
if not isinstance(result, DRResult):
|
|
427
|
+
raise AlgorithmExecutionError("DR export result is invalid")
|
|
428
|
+
execution = export_model(model=result.model, plan=plan, run_id=run_id)
|
|
429
|
+
return AlgorithmExecutionResult(
|
|
430
|
+
status=execution.status,
|
|
431
|
+
metrics=execution.metrics,
|
|
432
|
+
outputs={
|
|
433
|
+
**dict(execution.outputs),
|
|
434
|
+
"composition_digest": result.composition_digest,
|
|
435
|
+
},
|
|
436
|
+
artifacts=execution.artifacts,
|
|
437
|
+
)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
__all__ = [
|
|
441
|
+
"DRResult",
|
|
442
|
+
"DistributedDRLearner",
|
|
443
|
+
"STAGES",
|
|
444
|
+
"create_algorithm",
|
|
445
|
+
"export_result",
|
|
446
|
+
]
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Executable contracts for distributed doubly robust estimation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class DRConfigValidator:
|
|
10
|
+
api_version = 1
|
|
11
|
+
schema_digest = "e" * 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 DR config keys: {unknown}")
|
|
17
|
+
for name in allowed:
|
|
18
|
+
if not isinstance(value.get(name), Mapping):
|
|
19
|
+
raise ValueError(f"{name} config is required")
|
|
20
|
+
data = value["data"]
|
|
21
|
+
for name in ("feature_columns", "treatment_col", "outcome_col"):
|
|
22
|
+
if not data.get(name):
|
|
23
|
+
raise ValueError(f"data.{name} is required")
|
|
24
|
+
training = value["training"]
|
|
25
|
+
folds = training.get("cross_fit_folds", 5)
|
|
26
|
+
if (
|
|
27
|
+
not isinstance(folds, int)
|
|
28
|
+
or isinstance(folds, bool)
|
|
29
|
+
or not 2 <= folds <= 20
|
|
30
|
+
):
|
|
31
|
+
raise ValueError("training.cross_fit_folds must be between 2 and 20")
|
|
32
|
+
if not value["ray"].get("storage_path") or not value["output"].get(
|
|
33
|
+
"bundle_uri"
|
|
34
|
+
):
|
|
35
|
+
raise ValueError("ray.storage_path and output.bundle_uri are required")
|
|
36
|
+
return dict(value)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class DRInputValidator:
|
|
40
|
+
api_version = 1
|
|
41
|
+
schema_digest = "b" * 64
|
|
42
|
+
|
|
43
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
44
|
+
bindings = value.get("bindings")
|
|
45
|
+
if not isinstance(bindings, list) or len(bindings) != 1:
|
|
46
|
+
raise ValueError("DR estimator requires one train binding")
|
|
47
|
+
binding = bindings[0]
|
|
48
|
+
if (
|
|
49
|
+
not isinstance(binding, Mapping)
|
|
50
|
+
or len(binding.get("feature_names", ())) < 2
|
|
51
|
+
or not binding.get("label_name")
|
|
52
|
+
):
|
|
53
|
+
raise ValueError("DR input requires features, treatment, and outcome")
|
|
54
|
+
return value
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class DROutputValidator:
|
|
58
|
+
api_version = 1
|
|
59
|
+
schema_digest = "c" * 64
|
|
60
|
+
|
|
61
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
62
|
+
outputs = value.get("outputs")
|
|
63
|
+
if value.get("status") != "succeeded" or not isinstance(outputs, Mapping):
|
|
64
|
+
raise ValueError("DR estimation failed")
|
|
65
|
+
if not outputs.get("bundle_uri") or not outputs.get("composition_digest"):
|
|
66
|
+
raise ValueError("DR output requires Bundle and composition digest")
|
|
67
|
+
return value
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class DRCoverageValidator:
|
|
71
|
+
api_version = 1
|
|
72
|
+
schema_digest = "d" * 64
|
|
73
|
+
|
|
74
|
+
def validate(self, value: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
75
|
+
if (
|
|
76
|
+
value.get("input_complete") is not True
|
|
77
|
+
or value.get("distributed") is not True
|
|
78
|
+
):
|
|
79
|
+
raise ValueError("DR coverage is incomplete")
|
|
80
|
+
state = value.get("state")
|
|
81
|
+
details = state.get("details") if isinstance(state, Mapping) else None
|
|
82
|
+
if not isinstance(details, Mapping):
|
|
83
|
+
raise ValueError("DR stage evidence is missing")
|
|
84
|
+
if details.get("component_stages") != "mu0,mu1,propensity":
|
|
85
|
+
raise ValueError("DR stage set drifted")
|
|
86
|
+
return value
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
__all__ = [
|
|
90
|
+
"DRConfigValidator",
|
|
91
|
+
"DRCoverageValidator",
|
|
92
|
+
"DRInputValidator",
|
|
93
|
+
"DROutputValidator",
|
|
94
|
+
]
|