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,130 @@
|
|
|
1
|
+
"""Lightweight descriptor for distributed PC stability discovery."""
|
|
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
|
+
MapReducePolicy,
|
|
14
|
+
QualifiedReference,
|
|
15
|
+
StateField,
|
|
16
|
+
WorkerRange,
|
|
17
|
+
WorkerResources,
|
|
18
|
+
)
|
|
19
|
+
from tributo.training.algorithm_spec import AlgorithmSpec, Capability, ProblemType
|
|
20
|
+
|
|
21
|
+
_PACKAGE = "tributo-algorithms"
|
|
22
|
+
_VERSION = "0.1.0"
|
|
23
|
+
_STATE_SCHEMA = (
|
|
24
|
+
StateField("adjacency_votes", "int64", (None, None)),
|
|
25
|
+
StateField("arrow_votes", "int64", (None, None)),
|
|
26
|
+
StateField("tail_votes", "int64", (None, None)),
|
|
27
|
+
StateField("run_count", "int64", ()),
|
|
28
|
+
StateField("row_count", "int64", ()),
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _contract(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_discovery.contracts:{validator}"
|
|
39
|
+
),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
_SPEC = AlgorithmSpec(
|
|
44
|
+
name="pc_stability_discovery",
|
|
45
|
+
trainer_cls=None,
|
|
46
|
+
version="1.0.0",
|
|
47
|
+
default_config={},
|
|
48
|
+
supported_tasks=("fit",),
|
|
49
|
+
operations=("fit",),
|
|
50
|
+
problem_types=(ProblemType.CAUSAL_EFFECT_ESTIMATION,),
|
|
51
|
+
capabilities=(Capability.DISTRIBUTED, Capability.EXPORTABLE, Capability.TUNABLE),
|
|
52
|
+
learning_paradigm="causal_discovery",
|
|
53
|
+
model_family="pc_stability",
|
|
54
|
+
data_modalities=("tabular",),
|
|
55
|
+
lifecycle_kind="discover_validate_report",
|
|
56
|
+
allowed_execution_modes=(ExecutionMode.MAP_REDUCE.value,),
|
|
57
|
+
config_contract_ref="tributo.official.causal.pc.config.v1",
|
|
58
|
+
input_contract_ref="tributo.official.causal.discovery-table.v1",
|
|
59
|
+
output_contract_ref="tributo.official.causal.discovery-report.v1",
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
PC_DISCOVERY_DESCRIPTOR = AlgorithmBuilder.from_distributed_algorithm(
|
|
63
|
+
spec=_SPEC,
|
|
64
|
+
implementation_id="tributo.official.causal_discovery.pc_stability",
|
|
65
|
+
implementation_version="1.0.0",
|
|
66
|
+
implementation=(
|
|
67
|
+
"tributo_algorithms_causal_discovery.algorithm:DistributedPCStability"
|
|
68
|
+
),
|
|
69
|
+
executable_factory="tributo_algorithms_causal_discovery.algorithm:create_algorithm",
|
|
70
|
+
distribution=_PACKAGE,
|
|
71
|
+
framework="causal-learn",
|
|
72
|
+
environment=EnvironmentSpec(
|
|
73
|
+
environment_id="tributo.official.causal-discovery.v1",
|
|
74
|
+
dependencies=(
|
|
75
|
+
"causal-learn>=0.1.4,<0.2",
|
|
76
|
+
"numpy>=2,<3",
|
|
77
|
+
"onnx>=1.16",
|
|
78
|
+
"onnxruntime>=1.20",
|
|
79
|
+
"tributo>=1.1",
|
|
80
|
+
f"tributo-algorithms[causal-discovery]=={_VERSION}",
|
|
81
|
+
),
|
|
82
|
+
),
|
|
83
|
+
allowed_config_keys=("alpha", "max_condition_set", "output", "vote_threshold"),
|
|
84
|
+
strategy=DistributionStrategy.RAY_MAP_REDUCE,
|
|
85
|
+
supported_worker_range=WorkerRange(2, 64),
|
|
86
|
+
supported_execution_profiles=(ExecutionProfile.LOCAL, ExecutionProfile.CLUSTER),
|
|
87
|
+
resources_per_worker=WorkerResources(num_cpus=1),
|
|
88
|
+
policy=MapReducePolicy(
|
|
89
|
+
state_schema=_STATE_SCHEMA,
|
|
90
|
+
max_partial_state_bytes=64 * 1024 * 1024,
|
|
91
|
+
reducer_ref=(
|
|
92
|
+
"tributo_algorithms_causal_discovery.algorithm:"
|
|
93
|
+
"DistributedPCStability.merge_states"
|
|
94
|
+
),
|
|
95
|
+
finalizer_ref=(
|
|
96
|
+
"tributo_algorithms_causal_discovery.algorithm:"
|
|
97
|
+
"DistributedPCStability.finalize_model"
|
|
98
|
+
),
|
|
99
|
+
commutative=True,
|
|
100
|
+
max_retries=0,
|
|
101
|
+
),
|
|
102
|
+
package_name=_PACKAGE,
|
|
103
|
+
package_version=_VERSION,
|
|
104
|
+
tributo_version_spec=">=1.1",
|
|
105
|
+
exporter="tributo_algorithms_causal_discovery.algorithm:export_graph",
|
|
106
|
+
flavor_id="onnx-runtime-v1",
|
|
107
|
+
contract_bindings=ContractBindingSet(
|
|
108
|
+
config=_contract(_SPEC.config_contract_ref or "", "6", "PCConfigValidator"),
|
|
109
|
+
input=_contract(
|
|
110
|
+
_SPEC.input_contract_ref or "",
|
|
111
|
+
"7",
|
|
112
|
+
"DiscoveryInputValidator",
|
|
113
|
+
),
|
|
114
|
+
output=_contract(
|
|
115
|
+
_SPEC.output_contract_ref or "",
|
|
116
|
+
"8",
|
|
117
|
+
"DiscoveryOutputValidator",
|
|
118
|
+
),
|
|
119
|
+
coverage=_contract(
|
|
120
|
+
"tributo.official.causal.discovery-coverage.v1",
|
|
121
|
+
"9",
|
|
122
|
+
"DiscoveryCoverageValidator",
|
|
123
|
+
),
|
|
124
|
+
),
|
|
125
|
+
descriptor_api_version=2,
|
|
126
|
+
is_default=True,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
__all__ = ["PC_DISCOVERY_DESCRIPTOR"]
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Causal graph report exporter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, ClassVar
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, ConfigDict
|
|
8
|
+
from tributo.exporting.models import SupportRequest, SupportResult, ValidatorBinding
|
|
9
|
+
from tributo.training.exporters.causal_report import CausalReportExporter
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class DiscoveryReportOptions(BaseModel):
|
|
13
|
+
model_config = ConfigDict(extra="forbid")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CausalDiscoveryReportExporter(CausalReportExporter):
|
|
17
|
+
api_version: ClassVar[int] = 2
|
|
18
|
+
exporter_id: ClassVar[str] = "official-causal-discovery-report-v1"
|
|
19
|
+
output_format: ClassVar[str] = "json"
|
|
20
|
+
output_flavor_id: ClassVar[str] = "report"
|
|
21
|
+
artifact_kind: ClassVar[str] = "report"
|
|
22
|
+
priority: ClassVar[int] = 90
|
|
23
|
+
source_kinds: ClassVar[tuple[str, ...]] = ("causal_graph", "prebuilt_onnx")
|
|
24
|
+
options_model: ClassVar[type[BaseModel]] = DiscoveryReportOptions
|
|
25
|
+
validator_bindings: ClassVar[tuple[ValidatorBinding, ...]] = ()
|
|
26
|
+
mutates_source: ClassVar[bool] = False
|
|
27
|
+
upstream_requirements: ClassVar[tuple[Any, ...]] = ()
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
def supports(cls, request: SupportRequest) -> SupportResult:
|
|
31
|
+
supported = request.source_kind in cls.source_kinds
|
|
32
|
+
return SupportResult(
|
|
33
|
+
supported=supported,
|
|
34
|
+
code="OK" if supported else "UNSUPPORTED_SOURCE_KIND",
|
|
35
|
+
reason=(
|
|
36
|
+
"causal graph report source is supported"
|
|
37
|
+
if supported
|
|
38
|
+
else "causal discovery report requires causal_graph source"
|
|
39
|
+
),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
__all__ = ["CausalDiscoveryReportExporter"]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Official distributed DoWhy adapters with lazy runtime exports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from tributo_algorithms_causal_dowhy.descriptor import DOWHY_DESCRIPTOR
|
|
8
|
+
from tributo_algorithms_causal_dowhy.gcm_descriptor import GCM_DESCRIPTOR
|
|
9
|
+
|
|
10
|
+
_LAZY_EXPORTS = {
|
|
11
|
+
"DistributedDoWhyRefutation": (
|
|
12
|
+
"tributo_algorithms_causal_dowhy.algorithm",
|
|
13
|
+
"DistributedDoWhyRefutation",
|
|
14
|
+
),
|
|
15
|
+
"DistributedGCMRootCause": (
|
|
16
|
+
"tributo_algorithms_causal_dowhy.gcm",
|
|
17
|
+
"DistributedGCMRootCause",
|
|
18
|
+
),
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def __getattr__(name: str) -> Any:
|
|
23
|
+
target = _LAZY_EXPORTS.get(name)
|
|
24
|
+
if target is None:
|
|
25
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
26
|
+
import importlib
|
|
27
|
+
|
|
28
|
+
value = getattr(importlib.import_module(target[0]), target[1])
|
|
29
|
+
globals()[name] = value
|
|
30
|
+
return value
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"DOWHY_DESCRIPTOR",
|
|
35
|
+
"GCM_DESCRIPTOR",
|
|
36
|
+
"DistributedDoWhyRefutation",
|
|
37
|
+
"DistributedGCMRootCause",
|
|
38
|
+
]
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""Distributed shard-ensemble DoWhy estimate and placebo refutation."""
|
|
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
|
+
)
|
|
18
|
+
from tributo.algorithms.spi import FrameworkNativeAlgorithm
|
|
19
|
+
from tributo_algorithms_causal_core.algorithm import CausalATEModel, export_model
|
|
20
|
+
|
|
21
|
+
STAGES = ("estimate", "refute")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _run_shard(
|
|
25
|
+
shard: object,
|
|
26
|
+
*,
|
|
27
|
+
treatment_name: str,
|
|
28
|
+
outcome_name: str,
|
|
29
|
+
common_causes: tuple[str, ...],
|
|
30
|
+
seed: int,
|
|
31
|
+
rank: int,
|
|
32
|
+
world_size: int,
|
|
33
|
+
binding_digest: str,
|
|
34
|
+
) -> dict[str, object]:
|
|
35
|
+
import ray
|
|
36
|
+
from dowhy import CausalModel
|
|
37
|
+
|
|
38
|
+
frame = cast(Any, shard).materialize().to_pandas()
|
|
39
|
+
if frame.empty:
|
|
40
|
+
raise AlgorithmExecutionError("DoWhy shard is empty")
|
|
41
|
+
model = CausalModel(
|
|
42
|
+
data=frame,
|
|
43
|
+
treatment=treatment_name,
|
|
44
|
+
outcome=outcome_name,
|
|
45
|
+
common_causes=list(common_causes),
|
|
46
|
+
)
|
|
47
|
+
estimand = model.identify_effect(proceed_when_unidentifiable=True)
|
|
48
|
+
estimate = model.estimate_effect(
|
|
49
|
+
estimand,
|
|
50
|
+
method_name="backdoor.linear_regression",
|
|
51
|
+
)
|
|
52
|
+
refutation = model.refute_estimate(
|
|
53
|
+
estimand,
|
|
54
|
+
estimate,
|
|
55
|
+
method_name="placebo_treatment_refuter",
|
|
56
|
+
random_seed=seed + rank,
|
|
57
|
+
)
|
|
58
|
+
runtime = ray.get_runtime_context()
|
|
59
|
+
assigned = runtime.get_assigned_resources()
|
|
60
|
+
treatment = frame[treatment_name]
|
|
61
|
+
treated = treatment == 1
|
|
62
|
+
control = treatment == 0
|
|
63
|
+
return {
|
|
64
|
+
"rank": rank,
|
|
65
|
+
"world_size": world_size,
|
|
66
|
+
"worker_id": str(runtime.get_worker_id()),
|
|
67
|
+
"node_id": str(runtime.get_node_id()),
|
|
68
|
+
"shard_id": hashlib.sha256(
|
|
69
|
+
f"{binding_digest}:{rank}/{world_size}".encode("ascii")
|
|
70
|
+
).hexdigest(),
|
|
71
|
+
"rows": int(frame.shape[0]),
|
|
72
|
+
"effect": float(estimate.value),
|
|
73
|
+
"placebo_effect": float(refutation.new_effect),
|
|
74
|
+
"treated_count": int(treated.sum()),
|
|
75
|
+
"control_count": int(control.sum()),
|
|
76
|
+
"treated_sum": float(frame.loc[treated, outcome_name].sum()),
|
|
77
|
+
"control_sum": float(frame.loc[control, outcome_name].sum()),
|
|
78
|
+
"resources": {
|
|
79
|
+
"num_cpus": float(assigned.get("CPU", 0.0)),
|
|
80
|
+
"num_gpus": float(assigned.get("GPU", 0.0)),
|
|
81
|
+
"custom": {
|
|
82
|
+
str(name): float(value)
|
|
83
|
+
for name, value in assigned.items()
|
|
84
|
+
if name not in {"CPU", "GPU", "memory", "object_store_memory"}
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass(frozen=True)
|
|
91
|
+
class DoWhyResult:
|
|
92
|
+
model: CausalATEModel
|
|
93
|
+
stage_evidence: Mapping[str, Mapping[str, object]]
|
|
94
|
+
composition_digest: str
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class _DoWhyDriver:
|
|
98
|
+
def __init__(self, *, plan: ResolvedAlgorithmPlan, dataset: object) -> None:
|
|
99
|
+
self.plan = plan
|
|
100
|
+
self.dataset = dataset
|
|
101
|
+
|
|
102
|
+
def fit(self) -> DoWhyResult:
|
|
103
|
+
import numpy as np
|
|
104
|
+
import ray
|
|
105
|
+
|
|
106
|
+
config = self.plan.algorithm_config
|
|
107
|
+
data = cast(Mapping[str, Any], config["data"])
|
|
108
|
+
refutation = cast(Mapping[str, Any], config["refutation"])
|
|
109
|
+
treatment_name = str(data["treatment_col"])
|
|
110
|
+
outcome_name = str(data["outcome_col"])
|
|
111
|
+
common_causes = tuple(str(name) for name in data["common_causes"])
|
|
112
|
+
world_size = self.plan.runtime.worker_count
|
|
113
|
+
shards = cast(Any, self.dataset).split(world_size, equal=True)
|
|
114
|
+
remote: Any = ray.remote(cast(Any, _run_shard)).options(
|
|
115
|
+
num_cpus=self.plan.runtime.num_cpus,
|
|
116
|
+
num_gpus=self.plan.runtime.num_gpus,
|
|
117
|
+
resources=dict(self.plan.runtime.custom_resources),
|
|
118
|
+
)
|
|
119
|
+
results = cast(
|
|
120
|
+
list[dict[str, Any]],
|
|
121
|
+
ray.get(
|
|
122
|
+
[
|
|
123
|
+
remote.remote(
|
|
124
|
+
shard,
|
|
125
|
+
treatment_name=treatment_name,
|
|
126
|
+
outcome_name=outcome_name,
|
|
127
|
+
common_causes=common_causes,
|
|
128
|
+
seed=int(refutation.get("seed", 7)),
|
|
129
|
+
rank=rank,
|
|
130
|
+
world_size=world_size,
|
|
131
|
+
binding_digest=self.plan.primary_input_descriptor.binding_digest,
|
|
132
|
+
)
|
|
133
|
+
for rank, shard in enumerate(shards)
|
|
134
|
+
]
|
|
135
|
+
),
|
|
136
|
+
)
|
|
137
|
+
rows = sum(int(item["rows"]) for item in results)
|
|
138
|
+
effects = np.asarray([float(item["effect"]) for item in results])
|
|
139
|
+
placebo = np.asarray([float(item["placebo_effect"]) for item in results])
|
|
140
|
+
weights = np.asarray([int(item["rows"]) for item in results], dtype=np.float64)
|
|
141
|
+
effect = float(np.average(effects, weights=weights))
|
|
142
|
+
standard_error = (
|
|
143
|
+
float(np.std(effects, ddof=1) / math.sqrt(world_size))
|
|
144
|
+
if world_size > 1
|
|
145
|
+
else 0.0
|
|
146
|
+
)
|
|
147
|
+
treated_count = sum(int(item["treated_count"]) for item in results)
|
|
148
|
+
control_count = sum(int(item["control_count"]) for item in results)
|
|
149
|
+
if treated_count < 2 or control_count < 2:
|
|
150
|
+
raise AlgorithmExecutionError("DoWhy ensemble requires treatment overlap")
|
|
151
|
+
policy_cost = float(refutation.get("policy_cost", 0.0))
|
|
152
|
+
causal_model = CausalATEModel(
|
|
153
|
+
method="distributed_dowhy_linear_ensemble",
|
|
154
|
+
treatment=treatment_name,
|
|
155
|
+
outcome=outcome_name,
|
|
156
|
+
feature_names=common_causes,
|
|
157
|
+
treated_count=treated_count,
|
|
158
|
+
control_count=control_count,
|
|
159
|
+
treated_mean=sum(float(item["treated_sum"]) for item in results)
|
|
160
|
+
/ treated_count,
|
|
161
|
+
control_mean=sum(float(item["control_sum"]) for item in results)
|
|
162
|
+
/ control_count,
|
|
163
|
+
effect=effect,
|
|
164
|
+
standard_error=standard_error,
|
|
165
|
+
confidence_interval=(
|
|
166
|
+
effect - 1.959963984540054 * standard_error,
|
|
167
|
+
effect + 1.959963984540054 * standard_error,
|
|
168
|
+
),
|
|
169
|
+
policy_cost=policy_cost,
|
|
170
|
+
treat_all_policy=effect > policy_cost,
|
|
171
|
+
diagnostics={
|
|
172
|
+
"placebo_effect_mean": float(np.average(placebo, weights=weights)),
|
|
173
|
+
"shard_estimate_std": float(np.std(effects)),
|
|
174
|
+
"shard_count": float(world_size),
|
|
175
|
+
},
|
|
176
|
+
)
|
|
177
|
+
estimate_digest = hashlib.sha256(
|
|
178
|
+
json.dumps({"effect": effect, "rows": rows}, sort_keys=True).encode("utf-8")
|
|
179
|
+
).hexdigest()
|
|
180
|
+
refute_digest = hashlib.sha256(
|
|
181
|
+
json.dumps(
|
|
182
|
+
{"placebo": placebo.tolist(), "rows": rows}, sort_keys=True
|
|
183
|
+
).encode("utf-8")
|
|
184
|
+
).hexdigest()
|
|
185
|
+
|
|
186
|
+
def workers(digest: str) -> list[dict[str, object]]:
|
|
187
|
+
return [
|
|
188
|
+
{
|
|
189
|
+
"worker_id": item["worker_id"],
|
|
190
|
+
"node_id": item["node_id"],
|
|
191
|
+
"rank": item["rank"],
|
|
192
|
+
"world_size": item["world_size"],
|
|
193
|
+
"shard_id": item["shard_id"],
|
|
194
|
+
"resources": item["resources"],
|
|
195
|
+
"model_state_digest": digest,
|
|
196
|
+
"rows_processed": item["rows"],
|
|
197
|
+
"input_rows": {"train": item["rows"]},
|
|
198
|
+
"batch_count": 1,
|
|
199
|
+
"collective_steps": 1,
|
|
200
|
+
}
|
|
201
|
+
for item in results
|
|
202
|
+
]
|
|
203
|
+
|
|
204
|
+
stages = {
|
|
205
|
+
"estimate": {
|
|
206
|
+
"workers": workers(estimate_digest),
|
|
207
|
+
"state": {
|
|
208
|
+
"coordination": "framework_native",
|
|
209
|
+
"synchronized": True,
|
|
210
|
+
"bounded": True,
|
|
211
|
+
"global_model_digest": estimate_digest,
|
|
212
|
+
"details": {"framework": "dowhy", "stage": "estimate"},
|
|
213
|
+
},
|
|
214
|
+
"input_complete": True,
|
|
215
|
+
"expected_training_rows": rows,
|
|
216
|
+
},
|
|
217
|
+
"refute": {
|
|
218
|
+
"workers": workers(refute_digest),
|
|
219
|
+
"state": {
|
|
220
|
+
"coordination": "framework_native",
|
|
221
|
+
"synchronized": True,
|
|
222
|
+
"bounded": True,
|
|
223
|
+
"global_model_digest": refute_digest,
|
|
224
|
+
"details": {"framework": "dowhy", "stage": "refute"},
|
|
225
|
+
},
|
|
226
|
+
"input_complete": True,
|
|
227
|
+
"expected_training_rows": rows,
|
|
228
|
+
},
|
|
229
|
+
}
|
|
230
|
+
composition_digest = hashlib.sha256(
|
|
231
|
+
f"{estimate_digest}:{refute_digest}".encode("ascii")
|
|
232
|
+
).hexdigest()
|
|
233
|
+
return DoWhyResult(
|
|
234
|
+
model=causal_model,
|
|
235
|
+
stage_evidence=stages,
|
|
236
|
+
composition_digest=composition_digest,
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class DistributedDoWhyRefutation(FrameworkNativeAlgorithm):
|
|
241
|
+
def __init__(self, plan: ResolvedAlgorithmPlan) -> None:
|
|
242
|
+
self.plan = plan
|
|
243
|
+
|
|
244
|
+
def validate_environment(self) -> None:
|
|
245
|
+
try:
|
|
246
|
+
import dowhy
|
|
247
|
+
except ImportError as exc:
|
|
248
|
+
raise AlgorithmConfigurationError("DoWhy dependency is required") from exc
|
|
249
|
+
if not dowhy.__version__:
|
|
250
|
+
raise AlgorithmConfigurationError("DoWhy environment is invalid")
|
|
251
|
+
|
|
252
|
+
def bind_datasets(self, datasets: Mapping[str, object]) -> Mapping[str, object]:
|
|
253
|
+
if len(datasets) != 1:
|
|
254
|
+
raise AlgorithmConfigurationError("DoWhy requires one Dataset")
|
|
255
|
+
data = cast(Mapping[str, Any], self.plan.algorithm_config["data"])
|
|
256
|
+
required = (
|
|
257
|
+
*tuple(data["common_causes"]),
|
|
258
|
+
str(data["treatment_col"]),
|
|
259
|
+
str(data["outcome_col"]),
|
|
260
|
+
)
|
|
261
|
+
binding = self.plan.primary_input_binding
|
|
262
|
+
if set(binding.feature_names) != set(required) - {str(data["outcome_col"])}:
|
|
263
|
+
raise AlgorithmConfigurationError("DoWhy InputBinding columns drifted")
|
|
264
|
+
if binding.label_name != data["outcome_col"]:
|
|
265
|
+
raise AlgorithmConfigurationError("DoWhy outcome label drifted")
|
|
266
|
+
dataset = next(iter(datasets.values()))
|
|
267
|
+
return {"train": cast(Any, dataset).select_columns(list(required))}
|
|
268
|
+
|
|
269
|
+
def build_trainer(
|
|
270
|
+
self, config: Mapping[str, Any], datasets: Mapping[str, object]
|
|
271
|
+
) -> object:
|
|
272
|
+
del config
|
|
273
|
+
return _DoWhyDriver(plan=self.plan, dataset=datasets["train"])
|
|
274
|
+
|
|
275
|
+
def collect_evidence(self, result: object) -> Mapping[str, Any]:
|
|
276
|
+
if not isinstance(result, DoWhyResult):
|
|
277
|
+
raise AlgorithmExecutionError("DoWhy returned an invalid result")
|
|
278
|
+
return {
|
|
279
|
+
"stages": dict(result.stage_evidence),
|
|
280
|
+
"composition_digest": result.composition_digest,
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
def checkpoint_source(self, result: object) -> object:
|
|
284
|
+
if not isinstance(result, DoWhyResult):
|
|
285
|
+
raise AlgorithmExecutionError("DoWhy result is invalid")
|
|
286
|
+
return result
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def create_algorithm(
|
|
290
|
+
*,
|
|
291
|
+
plan: ResolvedAlgorithmPlan,
|
|
292
|
+
implementation: object,
|
|
293
|
+
artifacts: tuple[object, ...],
|
|
294
|
+
) -> DistributedDoWhyRefutation:
|
|
295
|
+
del artifacts
|
|
296
|
+
if implementation is not DistributedDoWhyRefutation:
|
|
297
|
+
raise AlgorithmConfigurationError("DoWhy implementation drifted")
|
|
298
|
+
return DistributedDoWhyRefutation(plan)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def export_result(
|
|
302
|
+
*, result: object, checkpoint: object, plan: ResolvedAlgorithmPlan, run_id: str
|
|
303
|
+
) -> AlgorithmExecutionResult:
|
|
304
|
+
del checkpoint
|
|
305
|
+
if not isinstance(result, DoWhyResult):
|
|
306
|
+
raise AlgorithmExecutionError("DoWhy export result is invalid")
|
|
307
|
+
execution = export_model(model=result.model, plan=plan, run_id=run_id)
|
|
308
|
+
return AlgorithmExecutionResult(
|
|
309
|
+
status=execution.status,
|
|
310
|
+
metrics=execution.metrics,
|
|
311
|
+
outputs={
|
|
312
|
+
**dict(execution.outputs),
|
|
313
|
+
"composition_digest": result.composition_digest,
|
|
314
|
+
},
|
|
315
|
+
artifacts=execution.artifacts,
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
__all__ = [
|
|
320
|
+
"DoWhyResult",
|
|
321
|
+
"DistributedDoWhyRefutation",
|
|
322
|
+
"STAGES",
|
|
323
|
+
"create_algorithm",
|
|
324
|
+
"export_result",
|
|
325
|
+
]
|