maxpagels commited on
Commit
adbc13b
·
verified ·
1 Parent(s): 2003312

Release 0.1.0

Browse files
LICENSE-CausalPFN ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CausalPFN License
2
+ Version 1.0, April 2025
3
+
4
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
5
+
6
+ 1. Definitions.
7
+
8
+ "License" shall mean the terms and conditions for use, reproduction,
9
+ and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by
12
+ the copyright owner that is granting the License.
13
+
14
+ "Legal Entity" shall mean the union of the acting entity and all
15
+ other entities that control, are controlled by, or are under common
16
+ control with that entity. For the purposes of this definition,
17
+ "control" means (i) the power, direct or indirect, to cause the
18
+ direction or management of such entity, whether by contract or
19
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity
23
+ exercising permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications,
26
+ including but not limited to software source code, documentation
27
+ source, and configuration files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical
30
+ transformation or translation of a Source form, including but
31
+ not limited to compiled object code, generated documentation,
32
+ and conversions to other media types.
33
+
34
+ "Work" shall mean the work of authorship, whether in Source or
35
+ Object form, made available under the License, as indicated by a
36
+ copyright notice that is included in or attached to the work
37
+ (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including
48
+ the original version of the Work and any modifications or additions
49
+ to that Work or Derivative Works thereof, that is intentionally
50
+ submitted to Licensor for inclusion in the Work by the copyright owner
51
+ or by an individual or Legal Entity authorized to submit on behalf of
52
+ the copyright owner. For the purposes of this definition, "submitted"
53
+ means any form of electronic, verbal, or written communication sent
54
+ to the Licensor or its representatives, including but not limited to
55
+ communication on electronic mailing lists, source code control systems,
56
+ and issue tracking systems that are managed by, or on behalf of, the
57
+ Licensor for the purpose of discussing and improving the Work, but
58
+ excluding communication that is conspicuously marked or otherwise
59
+ designated in writing by the copyright owner as "Not a Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity
62
+ on behalf of whom a Contribution has been received by Licensor and
63
+ subsequently incorporated within the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of
66
+ this License, each Contributor hereby grants to You a perpetual,
67
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
+ copyright license to reproduce, prepare Derivative Works of,
69
+ publicly display, publicly perform, sublicense, and distribute the
70
+ Work and such Derivative Works in Source or Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ (except as stated in this section) patent license to make, have made,
76
+ use, offer to sell, sell, import, and otherwise transfer the Work,
77
+ where such license applies only to those patent claims licensable
78
+ by such Contributor that are necessarily infringed by their
79
+ Contribution(s) alone or by combination of their Contribution(s)
80
+ with the Work to which such Contribution(s) was submitted. If You
81
+ institute patent litigation against any entity (including a
82
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
83
+ or a Contribution incorporated within the Work constitutes direct
84
+ or contributory patent infringement, then any patent licenses
85
+ granted to You under this License for that Work shall terminate
86
+ as of the date such litigation is filed.
87
+
88
+ 4. Redistribution. You may reproduce and distribute copies of the
89
+ Work or Derivative Works thereof in any medium, with or without
90
+ modifications, and in Source or Object form, provided that You
91
+ meet the following conditions:
92
+
93
+ (a) You must give any other recipients of the Work or
94
+ Derivative Works a copy of this License; and
95
+
96
+ (b) You must cause any modified files to carry prominent notices
97
+ stating that You changed the files; and
98
+
99
+ (c) You must retain, in the Source form of any Derivative Works
100
+ that You distribute, all copyright, patent, trademark, and
101
+ attribution notices from the Source form of the Work,
102
+ excluding those notices that do not pertain to any part of
103
+ the Derivative Works; and
104
+
105
+ (d) If the Work includes a "NOTICE" text file as part of its
106
+ distribution, then any Derivative Works that You distribute must
107
+ include a readable copy of the attribution notices contained
108
+ within such NOTICE file, excluding those notices that do not
109
+ pertain to any part of the Derivative Works, in at least one
110
+ of the following places: within a NOTICE text file distributed
111
+ as part of the Derivative Works; within the Source form or
112
+ documentation, if provided along with the Derivative Works; or,
113
+ within a display generated by the Derivative Works, if and
114
+ wherever such third-party notices normally appear. The contents
115
+ of the NOTICE file are for informational purposes only and
116
+ do not modify the License. You may add Your own attribution
117
+ notices within Derivative Works that You distribute, alongside
118
+ or as an addendum to the NOTICE text from the Work, provided
119
+ that such additional attribution notices cannot be construed
120
+ as modifying the License.
121
+
122
+ You may add Your own copyright statement to Your modifications and
123
+ may provide additional or different license terms and conditions
124
+ for use, reproduction, or distribution of Your modifications, or
125
+ for any such Derivative Works as a whole, provided Your use,
126
+ reproduction, and distribution of the Work otherwise complies with
127
+ the conditions stated in this License.
128
+
129
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
130
+ any Contribution intentionally submitted for inclusion in the Work
131
+ by You to the Licensor shall be under the terms and conditions of
132
+ this License, without any additional terms or conditions.
133
+ Notwithstanding the above, nothing herein shall supersede or modify
134
+ the terms of any separate license agreement you may have executed
135
+ with Licensor regarding such Contributions.
136
+
137
+ 6. Trademarks. This License does not grant permission to use the trade
138
+ names, trademarks, service marks, or product names of the Licensor,
139
+ except as required for reasonable and customary use in describing the
140
+ origin of the Work and reproducing the content of the NOTICE file.
141
+
142
+ 7. Disclaimer of Warranty. Unless required by applicable law or
143
+ agreed to in writing, Licensor provides the Work (and each
144
+ Contributor provides its Contributions) on an "AS IS" BASIS,
145
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
146
+ implied, including, without limitation, any warranties or conditions
147
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148
+ PARTICULAR PURPOSE. You are solely responsible for determining the
149
+ appropriateness of using or redistributing the Work and assume any
150
+ risks associated with Your exercise of permissions under this License.
151
+
152
+ 8. Limitation of Liability. In no event and under no legal theory,
153
+ whether in tort (including negligence), contract, or otherwise,
154
+ unless required by applicable law (such as deliberate and grossly
155
+ negligent acts) or agreed to in writing, shall any Contributor be
156
+ liable to You for damages, including any direct, indirect, special,
157
+ incidental, or consequential damages of any character arising as a
158
+ result of this License or out of the use or inability to use the
159
+ Work (including but not limited to damages for loss of goodwill,
160
+ work stoppage, computer failure or malfunction, or any and all
161
+ other commercial damages or losses), even if such Contributor
162
+ has been advised of the possibility of such damages.
163
+
164
+ 9. Accepting Warranty or Additional Liability. While redistributing
165
+ the Work or Derivative Works thereof, You may choose to offer,
166
+ and charge a fee for, acceptance of support, warranty, indemnity,
167
+ or other liability obligations and/or rights consistent with this
168
+ License. However, in accepting such obligations, You may act only
169
+ on Your own behalf and on Your sole responsibility, not on behalf
170
+ of any other Contributor, and only if You agree to indemnify,
171
+ defend, and hold each Contributor harmless for any liability
172
+ incurred by, or claims asserted against, such Contributor by reason
173
+ of your accepting any such warranty or additional liability.
174
+
175
+ END OF TERMS AND CONDITIONS
NOTICE ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ AxiomEffect
2
+
3
+ This product includes a reimplementation of the network of CausalPFN ("CausalPFN: Amortized
4
+ Causal Effect Estimation via In-Context Learning", Balazadeh et al. 2025, arXiv:2506.07918;
5
+ https://huggingface.co/vdblm/causalpfn), by the CausalPFN authors, licensed under the CausalPFN
6
+ License, Version 1.0 (the terms of the Apache License, Version 2.0): see LICENSE-CausalPFN.
7
+ CausalPFN's network is TabDPT's (Layer 6, https://huggingface.co/Layer6/TabDPT, Apache 2.0).
8
+
9
+ Changes: src/axiom_effect/model.py reimplements causalpfn's models/model.py and
10
+ models/transformer_layer.py, keeping their parameter names, and adds graph-role inputs,
11
+ continuous treatments, a query token told no treatment value (read by propensity heads) and a
12
+ head for the estimands' intervals. AxiomEffect's training starts from CausalPFN's weights
13
+ (causalpfn_v0.pt) and continues on AxiomEffect's own prior, so its released weights are derived
14
+ from CausalPFN's.
README.md CHANGED
@@ -10,34 +10,40 @@ license: apache-2.0
10
 
11
  # Axiom Effect
12
 
13
- Causal effect estimation for tabular data. Given a table, its causal graph and a treatment /
14
- outcome pair, Axiom Effect estimates what happens to the outcome when the treatment is *set*
15
- to one value instead of another, E[Y | do(T = b)] - E[Y | do(T = a)], with 90% and 50%
16
- intervals, and the whole dose-response curve. It is trained on simulated causal models,
17
- where the true effect is known.
18
-
19
- **Version 0.0.2 is experimental.** The API and the weights will change in 0.0.x releases.
 
 
 
 
 
20
  Check its answers against what you know about your data.
21
 
22
- The graph decides what to adjust for: the model reads only the treatment, the outcome and
23
- the graph's optimal adjustment set, so mediators, colliders and other variables that would
24
- bias the answer never enter. The graph can come from domain knowledge or from
25
- [Axiom](https://huggingface.co/maxpagels/axiom-discovery), the causal discovery model this is a
26
- sibling of.
 
27
 
28
- 6.5M parameters, fp32 safetensors (26 MB). Project page:
29
  [maxpagels.com/axiom](https://maxpagels.com/axiom).
30
 
31
  ## Recommended use (ballpark)
32
 
33
  | | recommendation |
34
  |---|---|
35
- | graph | a DAG over the table's columns that you trust, with no unmeasured common causes of the treatment and the outcome. The model takes it as true. |
36
- | treatment | continuous: at least 20 distinct values. Binary and categorical treatments are not supported yet. |
37
- | treatment values | inside the 2-98% quantiles of the observed treatment (refused outside them unless `extrapolate=True`): beyond them the data has no support for the answer. |
38
- | rows | trained on 128-1024. Below 128 it warns. Over 1024 rows, `effect` averages 8 random 1024-row subsets, whose intervals are those of 1024 rows: on the wide side. |
39
- | adjustment set | up to 18 variables, as in training (the table itself can have more columns: only the adjustment set is read). |
40
- | missing values | not supported in the treatment, the outcome and the adjustment set; other columns may have them. |
41
 
42
  ## Usage
43
 
@@ -49,95 +55,53 @@ pip install "git+https://huggingface.co/maxpagels/axiom-effect"
49
  from axiom_effect import AxiomEffect
50
 
51
  model = AxiomEffect.from_pretrained("maxpagels/axiom-effect")
52
-
53
- graph = [("age", "price"), ("age", "sales"), ("price", "visits"), ("visits", "sales")]
54
- r = model.effect(df, graph, treatment="price", outcome="sales")
55
  print(r)
 
 
 
56
  ```
57
 
58
- For example, on a simulated table:
59
-
60
- ```
61
- Effect of price on sales (800 rows; adjusted for age)
62
- price 29.74 -> 36.89: -10.14 90% [-12.53, -7.738] 50% [-10.99, -9.248]
63
- dose-response, from price = 33.36:
64
- 26.28 +9.224 90% [5.852, 12.66]
65
- 29.74 +5.172 90% [3.908, 6.547]
66
- 33.36 0 90% [0, 0]
67
- 36.89 -4.971 90% [-6.539, -3.388]
68
- 40.34 -9.736 90% [-13.38, -6.002]
69
- ```
70
-
71
- Everything is in the data's own units: the treatment values in the treatment's, the effects
72
- in the outcome's (`effect` standardizes the columns it reads, as in training, and converts
73
- back). The graph can be:
74
-
75
- - a list of (cause, effect) column-name pairs, as above;
76
- - a (d, d) adjacency matrix in the table's column order (`A[i, j] = 1` means i -> j);
77
- - a pandas DataFrame adjacency matrix with the column names as index and columns;
78
- - a `discover()` result from Axiom: its directed edges.
79
 
80
  ```python
81
- from axiom import Axiom
 
82
 
 
83
  g = Axiom.from_pretrained("maxpagels/axiom-discovery").discover(df)
84
- r = model.effect(df, g, treatment="price", outcome="sales")
 
85
  ```
86
 
87
- A discovered graph is only as good as its edges. Undirected or confounded relations near
88
- the treatment or outcome are ignored with a warning, and if the discovered graph has no
89
- directed path from the treatment to the outcome the effect is exactly 0, with a warning
90
- too: one wrong edge is enough for that.
91
-
92
- ### Reading the result
93
-
94
- ```python
95
- r.estimate # the headline contrast: moving the treatment from its 25% to its 75% quantile
96
- r.contrast # those two treatment values, (a, b)
97
- r.interval # 90% interval of the contrast; r.interval50 the 50% one
98
- r.adjustment # the variables adjusted for
99
- r.to_frame() # the dose-response curve: each value's effect from the reference, with intervals
100
- ```
101
-
102
- | argument | default | meaning |
103
- |---|---|---|
104
- | `contrast=(a, b)` | the 25% and 75% quantiles | the headline effect: moving the treatment from a to b |
105
- | `values` | the 10/25/50/75/90% quantiles | treatment values on the dose-response curve |
106
- | `reference` | the median | where the curve starts (its effect is 0) |
107
-
108
- The curve's intervals are pointwise, not simultaneous. The intervals are the model's own
109
- quantiles, conformally calibrated on held-out simulated data from its training
110
- distribution. How well they cover on real data is not yet known.
111
-
112
- If the graph has no directed path from the treatment to the outcome, setting the treatment
113
- cannot move the outcome: the effect is exactly 0, with a zero-width interval, whatever
114
- their correlation (`r.zero_by_graph`).
115
 
116
  ## Limitations
117
 
118
- - The graph is taken as true. A missing confounder or a reversed edge biases the answer,
119
- and the interval does not widen for it.
120
- - No hidden confounders: front-door, instrumental-variable and other identification
121
- strategies beyond adjustment are not supported, and the model never says "not
122
- identifiable".
123
- - Continuous treatments only; average effects only (no per-row or conditional effects).
124
- - Trained and validated on simulated data only: no evaluation on real data yet.
125
- - On purely linear data, least squares is slightly more accurate; on strongly nonlinear
126
- dose-responses, a few estimates are further off than the typical one.
 
127
 
128
  ## Versions
129
 
130
  Each release is a tagged commit in this repo; `main` is the latest. The package loads the
131
- weights released with it, so code and weights always match. To use a specific release,
132
- install its code and load its weights by tag:
133
 
134
  ```bash
135
- pip install "git+https://huggingface.co/maxpagels/axiom-effect@v0.0.2"
136
- ```
137
-
138
- ```python
139
- model = AxiomEffect.from_pretrained("maxpagels/axiom-effect") # this package's release: v0.0.2
140
  ```
141
 
 
142
  - **v0.0.2**: new weights: a least-squares fit of the outcome as an input and baseline, much more accurate on linear data and under poor overlap, with narrower intervals; an effect from a value to itself is exactly 0.
143
  - **v0.0.1**: first release: continuous treatments, a known DAG without hidden confounders, adjustment by the optimal adjustment set; conformally calibrated 90% and 50% intervals.
 
10
 
11
  # Axiom Effect
12
 
13
+ Causal effects from a table: what happens to an outcome when a treatment is *set* to one
14
+ value instead of another. For binary treatments the average effect (ATE), the effect on the
15
+ treated (ATT) and on the controls, and every row's own effect (CATE); for continuous ones the
16
+ effect between two values, the dose-response curve and every row's effect, each with 90% and
17
+ 50% intervals. Trained on simulated data where every row's effect is known.
18
+
19
+ The network is [CausalPFN](https://huggingface.co/vdblm/causalpfn)'s (Balazadeh et al. 2025,
20
+ arXiv:2506.07918; itself TabDPT's), and training starts from CausalPFN's weights, extended to
21
+ continuous treatments and causal graphs. CausalPFN is used under its license (the Apache 2.0
22
+ terms): see NOTICE and LICENSE-CausalPFN.
23
+
24
+ **Version 0.1.0 is experimental.** The API and the weights will change in 0.x releases.
25
  Check its answers against what you know about your data.
26
 
27
+ It works without a causal graph, the usual assumption being that every covariate is measured
28
+ before the treatment, and better with one. It is the sibling of
29
+ [Axiom](https://huggingface.co/maxpagels/axiom-discovery), the causal discovery model: given a
30
+ discovered graph, it reads each covariate's role (confounder, instrument, mediator, collider,
31
+ ...) as probabilities, so a discovered graph helps it tell the columns that must be adjusted
32
+ for from the ones that would bias the answer.
33
 
34
+ 19.8M parameters, fp32 safetensors (79 MB). Project page:
35
  [maxpagels.com/axiom](https://maxpagels.com/axiom).
36
 
37
  ## Recommended use (ballpark)
38
 
39
  | | recommendation |
40
  |---|---|
41
+ | treatment | binary (two values) or continuous (at least 10 distinct values); continuous values inside its 2-98% quantiles |
42
+ | covariates | trained on up to 84; without a graph they must all be pre-treatment (not caused by the treatment) |
43
+ | graph | none; a DAG you trust (the treatment's descendants are then dropped); or an Axiom `discover()` result |
44
+ | rows | trained on 128-2048; larger tables are split into disjoint subsets of up to 2048 rows (1024 with more than 34 covariates) and combined |
45
+ | hidden confounders | not handled: no unmeasured common causes of the treatment and the outcome |
46
+ | missing values | not supported in the columns used |
47
 
48
  ## Usage
49
 
 
55
  from axiom_effect import AxiomEffect
56
 
57
  model = AxiomEffect.from_pretrained("maxpagels/axiom-effect")
58
+ r = model.effect(df, treatment="discount", outcome="spend") # no graph
 
 
59
  print(r)
60
+ r.ate, r.att # (estimate, lo, hi), 90%
61
+ r.cate # every row's effect
62
+ r.debiased # binary: doubly robust (AIPW), the model's outcome predictions + a logistic propensity
63
  ```
64
 
65
+ With a graph:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  ```python
68
+ graph = [("age", "discount"), ("age", "spend"), ("discount", "visits"), ("visits", "spend")]
69
+ r = model.effect(df, "discount", "spend", graph=graph) # visits (a mediator) is not adjusted for
70
 
71
+ from axiom import Axiom
72
  g = Axiom.from_pretrained("maxpagels/axiom-discovery").discover(df)
73
+ r = model.effect(df, "discount", "spend", graph=g) # role probabilities from the discovered graph
74
+ r.roles # what the model was told about each covariate
75
  ```
76
 
77
+ A graph can be a list of (cause, effect) column names, a (d, d) adjacency matrix in the
78
+ table's column order, an adjacency DataFrame, or a `discover()` result. Continuous
79
+ treatments take `contrast=(a, b)` (default: the 25% and 75% quantiles), `values`
80
+ for the curve (default: the 10/25/50/75/90% quantiles) and `reference` (default: the median).
81
+ Everything is in the data's own units.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  ## Limitations
84
 
85
+ - No hidden confounders; identification by adjustment only.
86
+ - A DAG is taken as true; a discovered graph is read as probabilities, but it can still be
87
+ wrong in ways the probabilities do not show.
88
+ - Large, wide tables are split into row subsets (see above), and it is weaker on them than on
89
+ smaller ones.
90
+ - `r.debiased` is not reliably better than `r.ate`; it is there to compare against.
91
+ - Trained on simulated data; benchmarked on semi-synthetic data (IHDP, ACIC 2016) with real
92
+ covariates; no evaluation on real effects yet.
93
+ - The intervals are the model's own quantiles, trained to cover on its simulated data; how
94
+ well they cover elsewhere is not yet known.
95
 
96
  ## Versions
97
 
98
  Each release is a tagged commit in this repo; `main` is the latest. The package loads the
99
+ weights released with it, so code and weights always match:
 
100
 
101
  ```bash
102
+ pip install "git+https://huggingface.co/maxpagels/axiom-effect@v0.1.0"
 
 
 
 
103
  ```
104
 
105
+ - **v0.1.0**: new network and weights, trained from CausalPFN's: binary treatments (ATE, ATT, ATC and every row's effect) as well as continuous ones; works without a graph, or with a DAG or a discover() result read as covariate roles. Breaking: effect(df, treatment, outcome, graph=None) replaces effect(df, graph, treatment, outcome).
106
  - **v0.0.2**: new weights: a least-squares fit of the outcome as an input and baseline, much more accurate on linear data and under poor overlap, with narrower intervals; an effect from a value to itself is exactly 0.
107
  - **v0.0.1**: first release: continuous treatments, a known DAG without hidden confounders, adjustment by the optimal adjustment set; conformally calibrated 90% and 50% intervals.
config.json CHANGED
@@ -1,29 +1,8 @@
1
  {
2
- "E": 192,
3
- "H": 8,
4
- "calibration": {
5
- "by_n": false,
6
- "inner": [
7
- 1.2894757986068726,
8
- 1.2894757986068726
9
- ],
10
- "n": [
11
- 256,
12
- 1024
13
- ],
14
- "outer": [
15
- 1.1929446458816528,
16
- 1.1929446458816528
17
- ],
18
- "pairs": "contrast",
19
- "seed": 1,
20
- "tasks": 750
21
- },
22
- "context_layers": 6,
23
- "doubly_robust": true,
24
- "inducing": 64,
25
- "linear": true,
26
- "positivity": true,
27
- "query_layers": 4,
28
- "row_layers": 2
29
  }
 
1
  {
2
+ "E": 384,
3
+ "H": 6,
4
+ "layers": 20,
5
+ "nbins": 1024,
6
+ "sigma": 0.5,
7
+ "vmax": 10.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  }
model.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2196020d71eefb97e7a8befe885f09bfd8501f2f965f04aa3693a270a90fb3d2
3
- size 26150632
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0166cfb102eebd773db587f9e92326e5663d53299aa99f0c809fbb4be8df6d9c
3
+ size 79287324
pyproject.toml CHANGED
@@ -1,12 +1,12 @@
1
  [project]
2
  name = "axiom-effect"
3
- version = "0.0.2"
4
- description = "AxiomEffect: causal effect estimation from a table and its causal graph"
5
  readme = "README.md"
6
  authors = [{ name = "Max Pagels" }]
7
  requires-python = ">=3.11"
8
  license = "Apache-2.0"
9
- license-files = ["LICENSE"]
10
  dependencies = ["huggingface-hub>=2.1", "numpy>=2.0", "safetensors>=0.4", "torch>=2.4"]
11
 
12
  [project.urls]
 
1
  [project]
2
  name = "axiom-effect"
3
+ version = "0.1.0"
4
+ description = "AxiomEffect: causal effects (ATE, ATT, CATE, dose-response) from a table, with or without a causal graph"
5
  readme = "README.md"
6
  authors = [{ name = "Max Pagels" }]
7
  requires-python = ">=3.11"
8
  license = "Apache-2.0"
9
+ license-files = ["LICENSE", "NOTICE", "LICENSE-CausalPFN"]
10
  dependencies = ["huggingface-hub>=2.1", "numpy>=2.0", "safetensors>=0.4", "torch>=2.4"]
11
 
12
  [project.urls]
src/axiom_effect/__init__.py CHANGED
@@ -1,14 +1,17 @@
1
- """AxiomEffect: causal effect estimation from a table and its causal graph.
 
 
2
 
3
  from axiom_effect import AxiomEffect
4
  model = AxiomEffect.from_pretrained("path/or/hub-repo")
5
- print(model.effect(df, graph, treatment="price", outcome="sales"))
6
 
7
  See axiom_effect.inference (the table-level call) and axiom_effect.model (the network);
8
  trained and benchmarked from the axiom repository (train_effect.py)."""
9
- from .graph import causal_nodes, descendants, is_dag, optimal_adjustment
10
- from .inference import TRAIN_N, EffectResult, effect
11
- from .model import INTERVALS, MID, QUANTILES, AxiomEffect, calibrate, calibration_factors, release_tag
12
 
13
- __all__ = ["AxiomEffect", "EffectResult", "effect", "TRAIN_N", "QUANTILES", "MID", "INTERVALS", "calibrate",
14
- "calibration_factors", "release_tag", "descendants", "is_dag", "causal_nodes", "optimal_adjustment"]
 
 
1
+ """AxiomEffect: causal effects (ATE, ATT, per-row CATE, dose-response) from a table, for binary
2
+ and continuous treatments, with or without a causal graph; the sibling of Axiom (axiom-discovery),
3
+ whose discovered graphs it reads.
4
 
5
  from axiom_effect import AxiomEffect
6
  model = AxiomEffect.from_pretrained("path/or/hub-repo")
7
+ print(model.effect(df, treatment="price", outcome="sales", graph=g))
8
 
9
  See axiom_effect.inference (the table-level call) and axiom_effect.model (the network);
10
  trained and benchmarked from the axiom repository (train_effect.py)."""
11
+ from .graph import ROLE_NAMES, causal_nodes, descendants, discovered_roles, is_dag, optimal_adjustment, roles
12
+ from .inference import TRAIN_COVARIATES, TRAIN_N, EffectResult, effect
13
+ from .model import MID, N_FEATURES, QUANTILES, AxiomEffect, release_tag
14
 
15
+ __all__ = ["AxiomEffect", "EffectResult", "effect", "TRAIN_N", "TRAIN_COVARIATES", "QUANTILES", "MID",
16
+ "N_FEATURES", "ROLE_NAMES", "release_tag", "descendants", "is_dag", "causal_nodes",
17
+ "optimal_adjustment", "roles", "discovered_roles"]
src/axiom_effect/graph.py CHANGED
@@ -45,3 +45,72 @@ def optimal_adjustment(A, t, y):
45
  cn = causal_nodes(A, t, y)
46
  forb = {t} | cn | {w for v in cn for w in descendants(A, v)}
47
  return sorted({int(p) for v in cn for p in np.flatnonzero(A[:, v])} - forb)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  cn = causal_nodes(A, t, y)
46
  forb = {t} | cn | {w for v in cn for w in descendants(A, v)}
47
  return sorted({int(p) for v in cn for p in np.flatnonzero(A[:, v])} - forb)
48
+
49
+
50
+ # Covariate roles: what the model is told about each covariate, from a graph. Four indicators
51
+ # relative to the treatment t and the outcome y, which together separate every role that
52
+ # matters for adjustment: a confounder is (1, 0, 1, 0), an instrument (1, 0, 0, 0), a
53
+ # precision variable (0, 0, 1, 0), a mediator (0, 1, 1, 0), a collider or other descendant of
54
+ # t (0, 1, 0, *), a descendant of y (*, 1, 0, 1). Adjusting for a descendant of t biases the
55
+ # effect; the rest are safe, and the confounders are the ones that must be adjusted for.
56
+ ROLE_NAMES = ("ancestor of T", "descendant of T", "affects Y not via T", "descendant of Y")
57
+ N_ROLES = len(ROLE_NAMES)
58
+ # Pair classes of a discover() result, in its order (axiom.inference.KINDS): none, i -> j,
59
+ # j -> i, undirected, confounded. Read by position: axiom-effect does not import axiom.
60
+ NONE, FWD, BWD, UND, CONF = range(5)
61
+
62
+
63
+ def roles(A, t, y):
64
+ """(d, N_ROLES) 0/1 role indicators of every variable of the DAG A (rows t and y are
65
+ meaningless): ancestor of t, descendant of t, ancestor of y once t's outgoing edges are
66
+ removed (an effect on y not through t), descendant of y."""
67
+ A = (np.asarray(A) != 0).astype(np.int64)
68
+ R = np.zeros((len(A), N_ROLES))
69
+ cut = A.copy()
70
+ cut[t] = 0
71
+ for col, members in enumerate((descendants(A.T, t), descendants(A, t), descendants(cut.T, y), descendants(A, y))):
72
+ R[members, col] = 1
73
+ return R
74
+
75
+
76
+ def _reaches(adj, a, b):
77
+ """Whether b is reachable from a along adj's directed edges (adj: list of child sets)."""
78
+ seen, stack = {a}, [a]
79
+ while stack:
80
+ v = stack.pop()
81
+ if v == b:
82
+ return True
83
+ for c in adj[v]:
84
+ if c not in seen:
85
+ seen.add(c)
86
+ stack.append(c)
87
+ return False
88
+
89
+
90
+ def sample_dag(probs, rng):
91
+ """One DAG from a discover() result's pair probabilities, probs (d, d, 5) read from (i, j):
92
+ each pair draws its class; i -> j and j -> i become that edge, undirected a random
93
+ direction, none and confounded no edge. Drawn edges are added in random order, and one
94
+ that would close a cycle is dropped."""
95
+ d = probs.shape[0]
96
+ i, j = np.triu_indices(d, 1)
97
+ p = np.clip(probs[i, j], 0, None)
98
+ p = p / np.maximum(p.sum(-1, keepdims=True), 1e-12)
99
+ k = (rng.random(len(i))[:, None] > np.cumsum(p, -1)).sum(-1)
100
+ k = np.where(k == UND, np.where(rng.random(len(i)) < 0.5, FWD, BWD), k)
101
+ edges = [(a, b) if c == FWD else (b, a) for a, b, c in zip(i, j, k) if c in (FWD, BWD)]
102
+ adj, A = [set() for _ in range(d)], np.zeros((d, d), dtype=np.int64)
103
+ for e in rng.permutation(len(edges)):
104
+ a, b = edges[e]
105
+ if not _reaches(adj, b, a):
106
+ adj[a].add(b)
107
+ A[a, b] = 1
108
+ return A
109
+
110
+
111
+ def discovered_roles(probs, t, y, samples=64, seed=0):
112
+ """(d, N_ROLES) role probabilities from a discover() result's pair probabilities: the
113
+ roles averaged over `samples` DAGs drawn by sample_dag."""
114
+ rng = np.random.default_rng(seed)
115
+ probs = np.asarray(probs, dtype=np.float64)
116
+ return np.mean([roles(sample_dag(probs, rng), t, y) for _ in range(samples)], 0)
src/axiom_effect/inference.py CHANGED
@@ -1,103 +1,137 @@
1
  """
2
- Run a trained AxiomEffect on a real table: column names, the graph in any of the usual
3
- forms, the original units in and out, the training range checked, and a readable result.
4
-
5
- from axiom_effect import AxiomEffect
6
- model = AxiomEffect.from_pretrained("path/or/hub-repo")
7
- r = model.effect(df, graph, treatment="price", outcome="sales")
8
- print(r) # the 25%-to-75% contrast and the dose-response curve
9
- r.estimate, r.interval # the contrast and its 90% interval, in units of sales
10
- r.to_frame() # the curve as a DataFrame
11
-
12
- `graph` is the causal graph over the table's columns: a (d, d) adjacency matrix in the
13
- column order (A[i, j] = 1 means i -> j), a pandas DataFrame with the column names as index
14
- and columns, a list of (cause, effect) name pairs, or a `discover()` result of axiom-discovery
15
- (its directed edges). The graph is taken as true: a DAG, no hidden confounders.
 
 
 
 
 
 
 
 
 
 
16
  """
17
  import warnings
18
- from dataclasses import dataclass
 
19
 
20
  import numpy as np
21
 
22
- from .graph import descendants, is_dag, optimal_adjustment
23
- from .model import INTERVALS, MID, QUANTILES
24
 
25
- # The range the released model was trained on (train_effect.py); outside it, extrapolation.
26
- TRAIN_N = (128, 1024) # rows; larger tables are split into subsets of TRAIN_N[1]
27
- TRAIN_ADJUST = 18 # variables in the adjustment set (tables of 3-20 variables)
28
- TRAIN_LEVELS = (0.02, 0.98) # treatment values were asked about between these quantiles
29
- MIN_LEVELS = 20 # distinct treatment values below which it counts as discrete
30
- CURVE_LEVELS = (0.1, 0.25, 0.5, 0.75, 0.9) # default dose-response values: these quantiles
31
- CONTRAST_LEVELS = (0.25, 0.75) # default contrast: from the first to the second
 
 
 
 
 
32
 
33
 
34
  @dataclass(repr=False)
35
  class EffectResult:
36
- """Result of `effect`, in the outcome's units throughout.
37
-
38
- The contrast: `estimate` is E[Y | do(T = b)] - E[Y | do(T = a)] for (a, b) = `contrast`,
39
- with its 90% `interval` and 50% `interval50`. The dose-response curve: for each treatment
40
- value in `values`, the effect of moving the treatment from `reference` to it
41
- (`curve[k]` holds the QUANTILES of that effect; 0 at the reference), pointwise intervals.
42
-
43
- `adjustment` is the set the graph says to adjust for (the optimal one), the only
44
- columns besides the treatment and outcome the model reads. `zero_by_graph` means the graph
45
- has no directed path from the treatment to the outcome, so every effect is exactly 0,
46
- whatever their association. `n_rows` is the rows behind each estimate (tables over
47
- TRAIN_N[1] rows are split into `n_subsets` subsets of that many and the quantiles
48
- averaged, so intervals are those of TRAIN_N[1] rows: conservative)."""
49
  treatment: str
50
  outcome: str
51
- adjustment: list
52
- zero_by_graph: bool
53
- contrast: tuple
54
- contrast_quantiles: np.ndarray # (len(QUANTILES),)
55
- reference: float
56
- values: np.ndarray # (K,)
57
- curve: np.ndarray # (K, len(QUANTILES))
58
- n_rows: int
59
- n_subsets: int
 
 
 
 
 
 
 
60
 
61
  @property
62
  def estimate(self):
63
- return float(self.contrast_quantiles[MID])
64
 
65
  @property
66
  def interval(self):
67
- lo, hi = (QUANTILES.index(p) for p in INTERVALS["outer"])
68
- return float(self.contrast_quantiles[lo]), float(self.contrast_quantiles[hi])
69
 
70
  @property
71
  def interval50(self):
72
- lo, hi = (QUANTILES.index(p) for p in INTERVALS["inner"])
73
- return float(self.contrast_quantiles[lo]), float(self.contrast_quantiles[hi])
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  def to_frame(self):
76
- """pandas DataFrame of the curve: value, effect (from the reference), and the 90% and
77
- 50% interval bounds."""
78
  import pandas as pd
79
- o, i = ([QUANTILES.index(p) for p in INTERVALS[k]] for k in ("outer", "inner"))
80
- c = self.curve
81
- return pd.DataFrame({self.treatment: self.values, "effect": c[:, MID],
82
- "lo90": c[:, o[0]], "lo50": c[:, i[0]], "hi50": c[:, i[1]], "hi90": c[:, o[1]]})
 
83
 
84
  def __repr__(self):
85
- g = lambda x: f"{x:.4g}"
86
- signed = lambda x: "0" if x == 0 else f"{x:+.4g}" # an exact 0 (the reference) unsigned
87
- adj = ", ".join(self.adjustment) if self.adjustment else "nothing"
88
- rows = f"{self.n_rows} rows" + (f" x {self.n_subsets} subsets" if self.n_subsets > 1 else "")
89
- head = f"Effect of {self.treatment} on {self.outcome} ({rows}; adjusted for {adj})"
 
 
90
  if self.zero_by_graph:
91
- return head + f"\n 0: the graph has no directed path from {self.treatment} to {self.outcome}"
92
- (lo, hi), (lo50, hi50) = self.interval, self.interval50
93
  a, b = self.contrast
94
- lines = [head, f" {self.treatment} {g(a)} -> {g(b)}: {signed(self.estimate)} "
95
- f"90% [{g(lo)}, {g(hi)}] 50% [{g(lo50)}, {g(hi50)}]",
96
- f" dose-response, from {self.treatment} = {g(self.reference)}:"]
97
- o = [QUANTILES.index(p) for p in INTERVALS["outer"]]
98
- w = max(len(g(v)) for v in self.values)
99
- lines += [f" {g(v):>{w}} {signed(q[MID])} 90% [{g(q[o[0]])}, {g(q[o[1]])}]"
100
- for v, q in zip(self.values, self.curve)]
 
 
 
 
 
 
 
 
101
  return "\n".join(lines)
102
 
103
 
@@ -115,33 +149,41 @@ def _table(data, names):
115
  return X, names
116
 
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  def _adjacency(graph, names):
119
- """(d, d) 0/1 adjacency in the table's column order, from any accepted graph form, and the
120
- relations of a discover() result that the DAG cannot express: [(a, b, kind)]."""
121
  d, index = len(names), {name: k for k, name in enumerate(names)}
122
-
123
- def reorder(A, graph_names):
124
- graph_names = list(map(str, graph_names))
125
- if sorted(graph_names) != sorted(names):
126
- raise ValueError(f"the graph's variables {graph_names} are not the table's columns {names}")
127
- p = [graph_names.index(name) for name in names]
128
- return np.asarray(A)[np.ix_(p, p)]
129
-
130
- other = []
131
- if hasattr(graph, "directed") and hasattr(graph, "names"): # axiom's CausalGraph
132
- A = reorder(graph.directed, graph.names)
133
- for kind in ("undirected", "confounded"):
134
- M = getattr(graph, kind, None)
135
- if M is not None:
136
- M = reorder(M, graph.names)
137
- other += [(names[i], names[j], kind) for i, j in zip(*np.nonzero(np.triu(M, 1)))]
138
- elif hasattr(graph, "columns") and hasattr(graph, "index"): # adjacency DataFrame
139
  if list(map(str, graph.index)) != list(map(str, graph.columns)):
140
  raise ValueError("an adjacency DataFrame needs the same variables, in the same order, as index and columns")
141
- A = reorder(graph.to_numpy(), graph.columns)
142
  elif isinstance(graph, (list, tuple)) and all(
143
  isinstance(e, (list, tuple)) and len(e) == 2 and all(isinstance(v, str) for v in e) for e in graph):
144
- A = np.zeros((d, d), dtype=np.int64) # edge list: (cause, effect) names
145
  for a, b in graph:
146
  for v in (a, b):
147
  if v not in index:
@@ -156,124 +198,221 @@ def _adjacency(graph, names):
156
  raise ValueError("the graph has a self-loop")
157
  if not is_dag(A):
158
  raise ValueError("the graph has a directed cycle; the effect model needs a DAG")
159
- return A, other
160
-
161
-
162
- def _column(v, names, what):
163
- if isinstance(v, (int, np.integer)) and not isinstance(v, bool):
164
- if not 0 <= v < len(names):
165
- raise ValueError(f"{what} index {v} is out of range for {len(names)} columns")
166
- return int(v)
167
- if str(v) not in names:
168
- raise ValueError(f"{what} {v!r} is not a column; columns are {names}")
169
- return names.index(str(v))
170
-
171
-
172
- def effect(model, data, graph, treatment, outcome, values=None, reference=None, contrast=None, names=None,
173
- extrapolate=False, n_subsets=8, seed=0):
174
- """The causal effect of `treatment` on `outcome` (column names, or indices), from a
175
- table and its causal graph (module docstring), in the outcome's units.
176
-
177
- values: treatment values for the dose-response curve (default: its 10/25/50/75/90%
178
- quantiles); reference: the value the curve starts from (default: the median);
179
- contrast: (a, b), the headline effect of moving the treatment from a to b (default:
180
- its 25% and 75% quantiles). All in the treatment's units.
181
- extrapolate: allow treatment values outside its 2-98% quantiles (warned instead of
182
- refused): the model was never asked about them, and the data hardly has them.
183
-
184
- Refused: missing values in the treatment, the outcome or the adjustment set; a constant
185
- treatment or outcome; a discrete one (fewer than 20 distinct values: version 0.0.x is for
186
- continuous treatments). Warned: fewer rows than the training range, an adjustment set
187
- larger than in training, and relations of a discover() result that a DAG cannot express
188
- (undirected, confounded) near the treatment or outcome, which are ignored; and an exact 0
189
- from a discover() result (no directed path), which one wrong edge can cause."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  X, names = _table(data, names)
191
- A, other = _adjacency(graph, names)
192
  t, y = _column(treatment, names, "treatment"), _column(outcome, names, "outcome")
193
  if t == y:
194
- raise ValueError("treatment and outcome are the same column")
195
- W = optimal_adjustment(A, t, y)
196
- used = [t, y] + W
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  if not np.isfinite(X[:, used]).all():
198
- bad = [names[c] for c in used if not np.isfinite(X[:, c]).all()]
199
- raise ValueError(f"missing or infinite values in {bad}; the effect model needs complete columns "
200
- f"for the treatment, the outcome and the adjustment set")
201
- T, Y = X[:, t], X[:, y]
202
- for c, what in ((t, "treatment"), (y, "outcome")):
203
- if np.ptp(X[:, c]) == 0:
204
- raise ValueError(f"the {what} {names[c]!r} is constant")
205
- if len(np.unique(T)) < MIN_LEVELS:
206
- raise ValueError(f"the treatment {names[t]!r} has {len(np.unique(T))} distinct values; version 0.0.x "
207
- f"estimates effects of continuous treatments only (at least {MIN_LEVELS} values)")
208
-
209
- near = {t, y} | set(descendants(A.T, t)) | set(descendants(A.T, y))
210
- ignored = [(a, b, k) for a, b, k in other if names.index(a) in near or names.index(b) in near]
211
- if ignored:
212
- warnings.warn(f"the graph also has {len(ignored)} relation(s) a DAG cannot express near the treatment "
213
- f"or outcome, ignored here (the effect assumes no hidden confounders): "
214
- + ", ".join(f"{a} {'--' if k == 'undirected' else '<->'} {b}" for a, b, k in ignored),
215
- stacklevel=3)
216
  n = len(X)
217
  if n < TRAIN_N[0]:
218
  warnings.warn(f"{n} rows is below the training range {TRAIN_N}", stacklevel=3)
219
- if len(W) > TRAIN_ADJUST:
220
- warnings.warn(f"the adjustment set has {len(W)} variables, more than in training (up to {TRAIN_ADJUST})",
221
- stacklevel=3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
 
223
- q = lambda p: float(np.quantile(T, p))
224
- values = np.array([q(p) for p in CURVE_LEVELS] if values is None else values, dtype=np.float64).ravel()
225
- reference = q(0.5) if reference is None else float(reference)
226
- contrast = (q(CONTRAST_LEVELS[0]), q(CONTRAST_LEVELS[1])) if contrast is None else tuple(map(float, contrast))
227
- if len(contrast) != 2:
228
- raise ValueError(f"contrast is a pair (a, b) of treatment values; got {contrast}")
229
- lo, hi = q(TRAIN_LEVELS[0]), q(TRAIN_LEVELS[1])
230
- outside = sorted({v for v in [*values, reference, *contrast] if not lo <= v <= hi})
231
- if outside:
232
- msg = (f"treatment values {[float(f'{v:.4g}') for v in outside]} are outside the 2-98% quantiles of "
233
- f"{names[t]!r}, [{lo:.4g}, {hi:.4g}], where the model was trained and the data has support")
234
- if not extrapolate:
235
- raise ValueError(msg + "; pass extrapolate=True to estimate them anyway")
236
- warnings.warn(msg, stacklevel=3)
237
-
238
- pairs = [(reference, v) for v in values] + [contrast]
239
  rng = np.random.default_rng(seed)
240
- rows = [np.arange(n)] if n <= TRAIN_N[1] else \
241
- [np.sort(rng.choice(n, TRAIN_N[1], replace=False)) for _ in range(n_subsets)]
242
- out = []
243
- for r in rows: # each subset standardized on its own, as in training
244
- Z = np.zeros((len(r), len(names))) # the model reads only the used columns
245
- U = X[np.ix_(r, used)]
246
- mu, sd = U.mean(0), U.std(0)
247
- if np.any(sd[:2] == 0):
248
- raise ValueError("a subset of the rows has a constant treatment or outcome; use fewer, larger subsets")
249
- Z[:, used] = (U - mu) / np.where(sd > 0, sd, 1.0)
250
- z = lambda v: (v - mu[0]) / sd[0]
251
- qz = model.effects(Z, A, t, y, [(z(a), z(b)) for a, b in pairs]) # the full graph: it decides W
252
- out.append(qz.astype(np.float64) * sd[1]) # effects are differences: no shift, only scale
253
- Q = np.mean(out, 0)
254
- zero = y not in descendants(A, t)
255
- if zero and _discovered(graph):
256
- warnings.warn(_zero_warning(graph, names[t], names[y]), stacklevel=3)
257
- return EffectResult(names[t], names[y], [names[c] for c in W], zero,
258
- contrast, Q[-1], reference, values, Q[:-1], len(rows[0]), len(rows))
259
-
260
-
261
- def _discovered(graph):
262
- """Whether the graph is a discover() result (axiom's CausalGraph), read by its attributes."""
263
- return hasattr(graph, "directed") and hasattr(graph, "names")
264
-
265
-
266
- def _zero_warning(graph, t, y):
267
- """Why an exact 0 from a discovered graph deserves a second look, with what the graph says
268
- about the pair itself when it can (CausalGraph.relation)."""
269
- msg = (f"the discovered graph has no directed path from {t} to {y}, so the effect is exactly 0. That "
270
- f"holds only if the graph is right, and discovered edges are uncertain: one missing or "
271
- f"reversed edge can cut every path")
272
- relation = getattr(graph, "relation", None)
273
- if callable(relation):
274
- try:
275
- probs = relation(t, y).probs
276
- msg += f" ({t} vs {y} directly: " + ", ".join(f"{k} {p:.2f}" for k, p in probs.items()) + ")"
277
- except (KeyError, ValueError, AttributeError):
278
- pass
279
- return msg + ". Check the graph's edges (print it), or pass a graph you trust"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ The table-level call: AxiomEffect on a real table, in the data's own units.
3
+
4
+ r = model.effect(df, treatment="price", outcome="sales") # no graph
5
+ r = model.effect(df, "price", "sales", graph=[("age", "price"), ...]) # a DAG you trust
6
+ r = model.effect(df, "price", "sales", graph=Axiom(...).discover(df)) # a discovered graph
7
+ print(r)
8
+ r.ate, r.att, r.cate, r.curve, r.debiased
9
+
10
+ What the graph does (design-effect.md, "Axiom discovery and the effect model"):
11
+ none every other column (or `covariates`) is taken as pre-treatment: none of them
12
+ may be caused by the treatment. Their roles are unknown to the model.
13
+ a DAG taken as true: the treatment's descendants (mediators, colliders, ...) are
14
+ dropped, since adjusting for them biases the effect, and the model is told every
15
+ remaining covariate's role (confounder, instrument, precision variable, noise).
16
+ No directed path from the treatment to the outcome: every effect is exactly 0.
17
+ discovered a discover() result from Axiom (axiom-discovery): its pair probabilities give each
18
+ covariate's role probabilities (averaged over DAGs sampled from them), and the
19
+ model reads them; nothing is dropped, since a discovered edge can be wrong.
20
+
21
+ A treatment with two values is binary: the ATE, the ATT (treated) and the ATC (controls), each
22
+ row's effect, and a doubly robust (AIPW) estimate built outside the network from the model's
23
+ outcome predictions and a cross-fitted logistic propensity (the network's own propensity head
24
+ is not used: a row's treatment reaches it through the other rows' context tokens). Otherwise (at least MIN_LEVELS values) continuous: the contrast between two
25
+ values, the dose-response curve, each row's effect of the contrast.
26
  """
27
  import warnings
28
+ from dataclasses import dataclass, field
29
+ from statistics import NormalDist
30
 
31
  import numpy as np
32
 
33
+ from .graph import CONF, N_ROLES, ROLE_NAMES, descendants, discovered_roles, is_dag, roles
34
+ from .model import MAX_COVARIATES, MID, N_FEATURES, QUANTILES
35
 
36
+ TRAIN_N = (128, 2048) # rows; larger tables are split into disjoint subsets of up to TRAIN_N[1]
37
+ TRAIN_COVARIATES = 84 # covariates (80 pre-treatment, up to 4 post-treatment)
38
+ # Tables with more than NARROW_COVARIATES covariates were trained on at most WIDE_N rows, so
39
+ # they are split into subsets of up to WIDE_N.
40
+ NARROW_COVARIATES, WIDE_N = 34, 1024
41
+ MIN_LEVELS = 10 # a continuous treatment needs at least this many distinct values
42
+ TRAIN_LEVELS = (0.02, 0.98) # continuous treatment values were asked about between these quantiles
43
+ CURVE_LEVELS = (0.1, 0.25, 0.5, 0.75, 0.9)
44
+ CONTRAST_LEVELS = (0.25, 0.75)
45
+ E_CLIP = 0.01 # propensities clipped to [E_CLIP, 1 - E_CLIP] in the doubly robust estimate
46
+ PROPENSITY_FOLDS, PROPENSITY_RIDGE = 5, 1.0 # the cross-fitted logistic propensity
47
+ Z90 = NormalDist().inv_cdf(0.95)
48
 
49
 
50
  @dataclass(repr=False)
51
  class EffectResult:
52
+ """Result of `effect`, in the outcome's units throughout. Quantiles are QUANTILES (5, 25,
53
+ 50, 75, 95%): the median is the estimate, the outer pair a 90% interval, the inner 50%."""
 
 
 
 
 
 
 
 
 
 
 
54
  treatment: str
55
  outcome: str
56
+ binary: bool
57
+ covariates: list # the columns adjusted for
58
+ dropped: list # columns a DAG marked as the treatment's descendants
59
+ graph: str # "none", "dag" or "discovered"
60
+ contrast: tuple # (a, b): the treatment values of the headline effect
61
+ quantiles: dict # estimand -> (len(QUANTILES),): "contrast", binary "att" / "atc"
62
+ cate: np.ndarray # (n,) each row's effect of moving the treatment from a to b
63
+ values: np.ndarray = None # continuous: the curve's treatment values
64
+ reference: float = None # continuous: where the curve starts
65
+ curve: np.ndarray = None # continuous: (K, len(QUANTILES)) effect of reference -> value
66
+ propensity: np.ndarray = None # binary: (n,) P(treated | covariates), cross-fitted logistic
67
+ debiased: dict = None # binary: {"ate"/"att": (estimate, lo, hi)}, AIPW, 90%
68
+ roles: dict = field(default_factory=dict) # covariate -> role probabilities (ROLE_NAMES), with a graph
69
+ zero_by_graph: bool = False
70
+ n_rows: int = 0
71
+ n_subsets: int = 1
72
 
73
  @property
74
  def estimate(self):
75
+ return float(self.quantiles["contrast"][MID])
76
 
77
  @property
78
  def interval(self):
79
+ q = self.quantiles["contrast"]
80
+ return float(q[0]), float(q[-1])
81
 
82
  @property
83
  def interval50(self):
84
+ q = self.quantiles["contrast"]
85
+ return float(q[1]), float(q[-2])
86
+
87
+ @property
88
+ def ate(self):
89
+ """(estimate, lo, hi) of the average effect over all rows, 90%."""
90
+ q = self.quantiles["contrast"]
91
+ return float(q[MID]), float(q[0]), float(q[-1])
92
+
93
+ @property
94
+ def att(self):
95
+ """Binary: (estimate, lo, hi) of the average effect on the treated, 90%."""
96
+ q = self.quantiles.get("att")
97
+ return None if q is None else (float(q[MID]), float(q[0]), float(q[-1]))
98
 
99
  def to_frame(self):
100
+ """The estimands (binary) or the dose-response curve (continuous), as a DataFrame."""
 
101
  import pandas as pd
102
+ if self.binary:
103
+ return pd.DataFrame([{"estimand": k, **{f"q{int(p * 100)}": float(v) for p, v in zip(QUANTILES, q)}}
104
+ for k, q in self.quantiles.items()])
105
+ return pd.DataFrame({self.treatment: self.values, **{f"q{int(p * 100)}": self.curve[:, k]
106
+ for k, p in enumerate(QUANTILES)}})
107
 
108
  def __repr__(self):
109
+ g = lambda v: f"{v:.4g}"
110
+ sig = lambda v: ("+" if v > 0 else "") + g(v)
111
+ adj = ", ".join(self.covariates) or "nothing"
112
+ rows = f"{self.n_rows} rows" + (f" in {self.n_subsets} subsets" if self.n_subsets > 1 else "")
113
+ head = [f"Effect of {self.treatment} on {self.outcome} ({rows}; graph: {self.graph}; adjusted for {adj})"]
114
+ if self.dropped:
115
+ head.append(f" not adjusted for (the graph says the treatment causes them): {', '.join(self.dropped)}")
116
  if self.zero_by_graph:
117
+ return "\n".join(head + [f" 0: the graph has no directed path from {self.treatment} to {self.outcome}"])
118
+ iv = lambda q: f"{sig(q[MID])} 90% [{g(q[0])}, {g(q[-1])}] 50% [{g(q[1])}, {g(q[-2])}]"
119
  a, b = self.contrast
120
+ if self.binary:
121
+ lines = head + [f" ATE ({g(a)} -> {g(b)}): {iv(self.quantiles['contrast'])}",
122
+ f" ATT (the treated): {iv(self.quantiles['att'])}",
123
+ f" ATC (the controls): {iv(self.quantiles['atc'])}"]
124
+ if self.debiased:
125
+ lines += [f" doubly robust (AIPW, logistic propensity): ATE {sig(e)} [{g(lo)}, {g(hi)}], "
126
+ f"ATT {sig(f)} [{g(flo)}, {g(fhi)}]"
127
+ for (e, lo, hi), (f, flo, fhi) in [(self.debiased["ate"], self.debiased["att"])]]
128
+ else:
129
+ lines = head + [f" {self.treatment} {g(a)} -> {g(b)}: {iv(self.quantiles['contrast'])}",
130
+ f" dose-response, from {self.treatment} = {g(self.reference)}:"]
131
+ lines += [f" {g(v):>10s} {sig(q[MID])} 90% [{g(q[0])}, {g(q[-1])}]"
132
+ for v, q in zip(self.values, self.curve)]
133
+ lines.append(f" per-row effects (cate): median {sig(np.median(self.cate))}, "
134
+ f"10-90% {g(np.quantile(self.cate, 0.1))} to {g(np.quantile(self.cate, 0.9))}")
135
  return "\n".join(lines)
136
 
137
 
 
149
  return X, names
150
 
151
 
152
+ def _column(v, names, what):
153
+ if isinstance(v, (int, np.integer)) and not isinstance(v, bool):
154
+ if not 0 <= v < len(names):
155
+ raise ValueError(f"{what} index {v} is out of range for {len(names)} columns")
156
+ return int(v)
157
+ if str(v) not in names:
158
+ raise ValueError(f"{what} {v!r} is not a column; columns are {names}")
159
+ return names.index(str(v))
160
+
161
+
162
+ def _reorder(M, graph_names, names):
163
+ """A (d, d, ...) array over graph_names in the table's column order."""
164
+ graph_names = list(map(str, graph_names))
165
+ if sorted(graph_names) != sorted(names):
166
+ raise ValueError(f"the graph's variables {graph_names} are not the table's columns {names}")
167
+ p = [graph_names.index(name) for name in names]
168
+ return np.asarray(M)[np.ix_(p, p)]
169
+
170
+
171
+ def _is_discovered(graph):
172
+ """Whether the graph is a discover() result (axiom's CausalGraph), read by its attributes."""
173
+ return hasattr(graph, "probs") and hasattr(graph, "names")
174
+
175
+
176
  def _adjacency(graph, names):
177
+ """(d, d) 0/1 DAG in the table's column order from an edge list of (cause, effect) names,
178
+ a (d, d) matrix or an adjacency DataFrame."""
179
  d, index = len(names), {name: k for k, name in enumerate(names)}
180
+ if hasattr(graph, "columns") and hasattr(graph, "index"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  if list(map(str, graph.index)) != list(map(str, graph.columns)):
182
  raise ValueError("an adjacency DataFrame needs the same variables, in the same order, as index and columns")
183
+ A = _reorder(graph.to_numpy(), graph.columns, names)
184
  elif isinstance(graph, (list, tuple)) and all(
185
  isinstance(e, (list, tuple)) and len(e) == 2 and all(isinstance(v, str) for v in e) for e in graph):
186
+ A = np.zeros((d, d), dtype=np.int64)
187
  for a, b in graph:
188
  for v in (a, b):
189
  if v not in index:
 
198
  raise ValueError("the graph has a self-loop")
199
  if not is_dag(A):
200
  raise ValueError("the graph has a directed cycle; the effect model needs a DAG")
201
+ return A
202
+
203
+
204
+ def _standardize(v):
205
+ mu, sd = v.mean(0), v.std(0)
206
+ return (v - mu) / np.where(sd > 0, sd, 1.0), mu, np.where(sd > 0, sd, 1.0)
207
+
208
+
209
+ def _components(C, k):
210
+ """(n, k) the first k principal components of the standardized columns of C (CausalPFN's
211
+ TruncatedSVD for tables wider than its network)."""
212
+ Z, _, _ = _standardize(C)
213
+ U, S, _ = np.linalg.svd(Z - Z.mean(0), full_matrices=False)
214
+ return U[:, :k] * S[:k]
215
+
216
+
217
+ def _combine(qs, counts):
218
+ """Quantiles of one estimand from disjoint subsets: the count-weighted mean of the
219
+ medians, and each quantile's distance from the median combined as for a mean of
220
+ independent estimates, sqrt(sum (m_k d_k)^2) / sum m_k."""
221
+ qs, m = np.asarray(qs), np.asarray(counts, dtype=float)
222
+ if len(qs) == 1:
223
+ return qs[0]
224
+ mid = (m * qs[:, MID]).sum() / m.sum()
225
+ off = qs - qs[:, MID:MID + 1]
226
+ return mid + np.sign(off.mean(0)) * np.sqrt(((m[:, None] * off) ** 2).sum(0)) / m.sum()
227
+
228
+
229
+ def _logistic(X, t, ridge, iters=25):
230
+ """Ridge-penalized logistic regression by Newton's method: the weights (intercept first,
231
+ unpenalized) of P(t = 1 | X)."""
232
+ A = np.column_stack([np.ones(len(X)), X])
233
+ P = ridge * np.eye(A.shape[1])
234
+ P[0, 0] = 0.0
235
+ w = np.zeros(A.shape[1])
236
+ for _ in range(iters):
237
+ p = 1 / (1 + np.exp(-np.clip(A @ w, -30, 30)))
238
+ g = A.T @ (p - t) + P @ w
239
+ H = (A * (p * (1 - p))[:, None]).T @ A + P + 1e-9 * np.eye(A.shape[1])
240
+ step = np.linalg.solve(H, g)
241
+ w -= step
242
+ if np.abs(step).max() < 1e-8:
243
+ break
244
+ return w
245
+
246
+
247
+ def _propensity(C, t, seed=0):
248
+ """(n,) P(t = 1 | C), each row's from a logistic regression fitted on the other folds, on
249
+ standardized covariates: a row's own treatment never enters its propensity."""
250
+ n = len(t)
251
+ X = (C - C.mean(0)) / np.where(C.std(0) > 0, C.std(0), 1.0) if C.shape[1] else np.zeros((n, 0))
252
+ folds = np.random.default_rng(seed).permutation(n) % min(PROPENSITY_FOLDS, n)
253
+ e = np.empty(n)
254
+ for f in np.unique(folds):
255
+ fit, held = folds != f, folds == f
256
+ if 0 < t[fit].mean() < 1:
257
+ w = _logistic(X[fit], t[fit], PROPENSITY_RIDGE)
258
+ e[held] = 1 / (1 + np.exp(-np.clip(w[0] + X[held] @ w[1:], -30, 30)))
259
+ else:
260
+ e[held] = t[fit].mean()
261
+ return e
262
+
263
+
264
+ def _aipw(mu0, mu1, e, T, Y):
265
+ """Doubly robust ATE and ATT from per-row predictions, with 90% influence-function intervals."""
266
+ e = np.clip(e, E_CLIP, 1 - E_CLIP)
267
+ psi = mu1 - mu0 + T * (Y - mu1) / e - (1 - T) * (Y - mu0) / (1 - e)
268
+ ate, se = psi.mean(), psi.std() / np.sqrt(len(Y))
269
+ p = T.mean()
270
+ att = (T * (Y - mu0) - (1 - T) * e / (1 - e) * (Y - mu0)).sum() / T.sum()
271
+ phi = (T * (Y - mu0 - att) - (1 - T) * e / (1 - e) * (Y - mu0)) / p
272
+ se_t = phi.std() / np.sqrt(len(Y))
273
+ return {"ate": (float(ate), float(ate - Z90 * se), float(ate + Z90 * se)),
274
+ "att": (float(att), float(att - Z90 * se_t), float(att + Z90 * se_t))}
275
+
276
+
277
+ def effect(model, data, treatment, outcome, graph=None, covariates=None, values=None, contrast=None,
278
+ reference=None, names=None, extrapolate=False, discovery_samples=64, seed=0):
279
+ """The effect of setting `treatment` on `outcome` in a table (a DataFrame or an (n, d)
280
+ array; `names` for an array's columns), given an optional graph (see the module
281
+ docstring): a DAG as an edge list of (cause, effect) names, a (d, d) matrix or an
282
+ adjacency DataFrame, or a discover() result. `covariates`: the columns to adjust for
283
+ (default: all others). Continuous treatments: `contrast` (a, b), default its 25% and
284
+ 75% quantiles; `values` the curve's treatment values, default its 10/25/50/75/90%
285
+ quantiles; `reference` where the curve starts, default the median; values outside
286
+ the 2-98% quantiles are refused unless `extrapolate`. Returns an EffectResult."""
287
  X, names = _table(data, names)
 
288
  t, y = _column(treatment, names, "treatment"), _column(outcome, names, "outcome")
289
  if t == y:
290
+ raise ValueError("the treatment and the outcome are the same column")
291
+ cov = [c for c in range(len(names)) if c not in (t, y)] if covariates is None else \
292
+ [_column(c, names, "covariate") for c in covariates]
293
+ if t in cov or y in cov:
294
+ raise ValueError("the covariates must not include the treatment or the outcome")
295
+
296
+ kind, dropped, R, zero = "none", [], np.zeros((len(names), N_ROLES)), False
297
+ if graph is not None and _is_discovered(graph):
298
+ kind = "discovered"
299
+ probs = _reorder(graph.probs, graph.names, names)
300
+ R = discovered_roles(probs, t, y, discovery_samples, seed)
301
+ if probs[t, y, CONF] > 0.2:
302
+ warnings.warn(f"the discovered graph gives {names[t]} and {names[y]} a hidden common cause with "
303
+ f"probability {probs[t, y, CONF]:.2f}: adjusting for measured covariates cannot remove "
304
+ f"its bias", stacklevel=3)
305
+ elif graph is not None:
306
+ kind = "dag"
307
+ A = _adjacency(graph, names)
308
+ R = roles(A, t, y)
309
+ zero = y not in descendants(A, t)
310
+ dropped = [c for c in cov if R[c, 1] == 1]
311
+ cov = [c for c in cov if R[c, 1] == 0]
312
+ features = np.column_stack([np.full(len(cov), float(kind != "none")), R[cov]]).reshape(len(cov), N_FEATURES)
313
+
314
+ used = [t, y] + cov
315
  if not np.isfinite(X[:, used]).all():
316
+ raise ValueError("missing or non-finite values in the treatment, the outcome or the covariates; "
317
+ "drop or impute those rows first")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  n = len(X)
319
  if n < TRAIN_N[0]:
320
  warnings.warn(f"{n} rows is below the training range {TRAIN_N}", stacklevel=3)
321
+ C = X[:, cov] # the covariates the network reads
322
+ if len(cov) > MAX_COVARIATES:
323
+ if kind != "none":
324
+ raise ValueError(f"{len(cov)} covariates with a graph: the network has slots for {MAX_COVARIATES}, and "
325
+ f"roles do not survive a projection; pass fewer `covariates`")
326
+ C, features = _components(C, MAX_COVARIATES), np.zeros((MAX_COVARIATES, N_FEATURES))
327
+ warnings.warn(f"{len(cov)} covariates, more than the network's {MAX_COVARIATES} slots: adjusting for their "
328
+ f"first {MAX_COVARIATES} principal components instead, as CausalPFN does", stacklevel=3)
329
+ elif len(cov) > TRAIN_COVARIATES:
330
+ warnings.warn(f"{len(cov)} covariates, more than in training (up to {TRAIN_COVARIATES})", stacklevel=3)
331
+ T, Y = X[:, t], X[:, y]
332
+ levels = np.unique(T)
333
+ binary = len(levels) == 2
334
+ if not binary and len(levels) < MIN_LEVELS:
335
+ raise ValueError(f"the treatment has {len(levels)} distinct values: binary (2) and continuous (at least "
336
+ f"{MIN_LEVELS}) treatments are supported")
337
+ if binary:
338
+ vals = [float(levels[0]), float(levels[1])]
339
+ a, b = vals
340
+ curve_vals, ref = None, None
341
+ else:
342
+ lo, hi = np.quantile(T, TRAIN_LEVELS)
343
+ a, b = contrast if contrast is not None else tuple(float(v) for v in np.quantile(T, CONTRAST_LEVELS))
344
+ curve_vals = np.asarray(values if values is not None else np.quantile(T, CURVE_LEVELS), dtype=np.float64)
345
+ ref = float(np.median(T) if reference is None else reference)
346
+ asked = np.concatenate([[a, b, ref], curve_vals])
347
+ outside = asked[(asked < lo) | (asked > hi)]
348
+ if len(outside):
349
+ msg = (f"treatment value(s) {sorted(set(outside.round(6)))} outside its 2-98% quantiles "
350
+ f"[{lo:.4g}, {hi:.4g}]: the data hardly covers them")
351
+ if not extrapolate:
352
+ raise ValueError(msg + "; pass extrapolate=True to estimate anyway")
353
+ warnings.warn(msg, stacklevel=3)
354
+ vals = sorted(set(float(v) for v in asked))
355
+ k = {v: i for i, v in enumerate(vals)}
356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357
  rng = np.random.default_rng(seed)
358
+ most = TRAIN_N[1] if len(cov) <= NARROW_COVARIATES else WIDE_N
359
+ parts = [np.arange(n)] if n <= most else np.array_split(rng.permutation(n), -(-n // most))
360
+ est = {"contrast": [], "att": [], "atc": []} if binary else {"contrast": [], "curve": []}
361
+ counts = {key: [] for key in est}
362
+ cate, mu0, mu1 = np.empty(n), np.empty(n), np.empty(n)
363
+ for rows in parts:
364
+ Wz, _, _ = _standardize(C[rows]) if cov else (np.zeros((len(rows), 0)), 0, 1)
365
+ Tz, tm, ts = _standardize(T[rows])
366
+ Yz, ym, ys = _standardize(Y[rows])
367
+ vz = (np.array(vals) - tm) / ts
368
+ all_rows = np.ones(len(rows), dtype=bool)
369
+ jobs = [(k[a], k[b], all_rows, "contrast")]
370
+ if binary:
371
+ treated = T[rows] == levels[1]
372
+ jobs += [(k[a], k[b], treated, "att"), (k[a], k[b], ~treated, "atc")]
373
+ else:
374
+ jobs += [(k[ref], k[v], all_rows, "curve") for v in curve_vals]
375
+ out = model.predict(Wz, Tz, Yz, features, binary, vz, [(i, j, r) for i, j, r, _ in jobs])
376
+ Q = out["quantiles"] * ys
377
+ curve = []
378
+ for (_, _, r, name), q in zip(jobs, Q):
379
+ if name == "curve":
380
+ curve.append(q)
381
+ else:
382
+ est[name].append(q)
383
+ counts[name].append(r.sum())
384
+ if curve:
385
+ est["curve"].append(np.stack(curve))
386
+ counts["curve"].append(len(rows))
387
+ cate[rows] = (out["mu"][k[b]] - out["mu"][k[a]]) * ys
388
+ if binary:
389
+ mu0[rows], mu1[rows] = out["mu"][k[a]] * ys + ym, out["mu"][k[b]] * ys + ym
390
+
391
+ quantiles = {name: _combine(est[name], counts[name]) for name in est if name != "curve"}
392
+ result = EffectResult(names[t], names[y], binary, [names[c] for c in cov], [names[c] for c in dropped], kind,
393
+ (a, b), quantiles, cate, n_rows=n, n_subsets=len(parts),
394
+ roles={names[c]: dict(zip(ROLE_NAMES, map(float, R[c]))) for c in cov} if kind != "none" else {})
395
+ if binary:
396
+ treated = (T == levels[1]).astype(float)
397
+ e = result.propensity = _propensity(C, treated, seed)
398
+ result.debiased = _aipw(mu0, mu1, e, treated, Y)
399
+ extreme = np.mean((e < 0.02) | (e > 0.98))
400
+ if extreme > 0.1:
401
+ warnings.warn(f"{extreme:.0%} of rows have a predicted propensity outside 2-98%: poor overlap, the "
402
+ f"estimates there rest on extrapolation", stacklevel=3)
403
+ else:
404
+ result.values, result.reference = curve_vals, ref
405
+ C = np.asarray(est["curve"]) # (subsets, K, Q)
406
+ result.curve = np.stack([_combine(C[:, j], counts["curve"]) for j in range(C.shape[1])])
407
+ result.curve[curve_vals == ref] = 0.0 # from the reference to itself: nothing
408
+ if zero:
409
+ warnings.warn(f"the graph has no directed path from {names[t]} to {names[y]}: every effect is exactly 0",
410
+ stacklevel=3)
411
+ result.zero_by_graph = True
412
+ result.quantiles = {name: np.zeros(len(QUANTILES)) for name in result.quantiles}
413
+ result.cate = np.zeros(n)
414
+ if result.curve is not None:
415
+ result.curve = np.zeros_like(result.curve)
416
+ if result.debiased:
417
+ result.debiased = {name: (0.0, 0.0, 0.0) for name in result.debiased}
418
+ return result
src/axiom_effect/model.py CHANGED
@@ -1,45 +1,55 @@
1
  """
2
- AxiomEffect: causal effect estimation given a causal graph, built as an in-context
3
- g-formula with a doubly robust correction (design-effect.md, "Architecture v2").
4
-
5
- Given a table, its DAG and a treatment t / outcome y, the dose-response E[Y | do(T = v)] is,
6
- by the g-formula, the average over the rows of E[Y | T = v, W = w_r], with W the optimal
7
- adjustment set. The model follows that recipe:
8
-
9
- 1. The graph decides the inputs: each row is reduced to (W, T, Y), W = O(t, y)
10
- (axiom_effect.graph.optimal_adjustment). Mediators and other descendants of T, which would bias
11
- the answer, are never seen.
12
- 2. An in-context regressor (as in TabPFN): the observed rows are the context; query rows
13
- carry a row's W with T set to a query value and Y unknown, attend to the context, and
14
- a head predicts E[Y | T = v, W = w_r] for each.
15
- With linear, the regression starts from least squares: Y on 1, T and W over the observed
16
- rows (linear adjustment), whose prediction for each row is an extra cell of the row and
17
- the baseline the head adds to, so the head learns only the departure from a line and
18
- extrapolates linearly where the data runs out (design-effect.md, run 5).
19
- 3. The average over the rows is computed exactly.
20
- 4. With doubly_robust, a correction from the observed rows whose treatment is near v
21
- (Kennedy et al. 2017, for continuous treatments): their residuals Y_i - E[Y | T_i, W_i],
22
- weighted by f(T_i) / pi(T_i | W_i), the treatment's marginal over its conditional
23
- density, kernel-averaged around v. The residuals and densities come from two more query
24
- rows per observed row (its own T, and T unknown), each blind to its own context row. If
25
- the outcome regression is off, the correction pulls the estimate back to the data. A
26
- learned gate per value scales the correction by how many rows effectively support v.
27
- With positivity, the gate also sees how many rows could plausibly have received v
28
- (their predicted treatment density at v) and the predicted overlap of the table: where
29
- the parents nearly fix the treatment, the average at v is mostly extrapolation, which
30
- the correction, built from the few rows near v, cannot fix (design-effect.md, run 3).
31
-
32
- Effects are differences of the dose-response, so effect(a -> b) = -effect(b -> a) and the
33
- median of a -> a is 0. Only the uncertainty is learned on top: quantiles (QUANTILES) of each
34
- effect, from the spread of the per-row predictions, the correction, a summary of the context
35
- and the sample size; they never cross. A split-conformal calibration (calibrate_effect.py),
36
- stored in the config, then scales the 90% and 50% intervals around the median.
 
 
 
 
 
 
 
 
 
 
37
 
38
  from axiom_effect import AxiomEffect
39
- model = AxiomEffect.from_pretrained("path/or/hub-repo") # trained with train_effect.py
40
- q = model.effects(X, A, t, y, pairs=[(x25, x75)]) # (1, len(QUANTILES))
41
 
42
- Everything is on the table's standardized scale.
43
  """
44
  import math
45
  import os
@@ -51,146 +61,132 @@ import numpy as np
51
  import torch
52
  import torch.nn as nn
53
  import torch.nn.functional as F
54
- from huggingface_hub import PyTorchModelHubMixin
55
  from huggingface_hub.errors import RevisionNotFoundError
56
  from torch.utils.checkpoint import checkpoint
57
 
58
- from .blocks import Attention, FeedForward, eval_mode, mlp
59
- from .graph import descendants, is_dag, optimal_adjustment
60
 
61
- QUANTILES = (0.05, 0.25, 0.5, 0.75, 0.95) # the outer two make a 90% interval
 
62
  MID = QUANTILES.index(0.5)
63
- INTERVALS = {"outer": (0.05, 0.95), "inner": (0.25, 0.75)} # 90% and 50%, each calibrated on its own
64
- N_REF = 2048 # log(n) / log(N_REF): the sample-size input
65
- CLIP = 8.0 # inputs clipped to +-CLIP sd, as Axiom's preprocess
66
- W_ROLE, T_ROLE, Y_ROLE, L_ROLE = 0, 1, 2, 3 # what a cell of a row is (L: the linear fit's prediction)
67
- RIDGE = 1e-3 # keeps the least-squares system solvable (a Gram diagonal ~ n)
68
- MAX_WEIGHT = 10.0 # the correction's density-ratio weights are clipped here
69
-
70
-
71
- def ranks(values, reference):
72
- """Each value's rank among the observed `reference` values of its column, in [-1, 1]
73
- (ties count half). values (B, C, R), reference (B, C, n)."""
74
- s = reference.sort(-1).values.contiguous()
75
- lo = torch.searchsorted(s, values.contiguous(), right=False)
76
- hi = torch.searchsorted(s, values.contiguous(), right=True)
77
- return (lo + hi).float() / reference.shape[-1] - 1
78
-
79
-
80
- def check_calibration(cal):
81
- """A calibration (calibrate_effect.py): {"n": sample sizes, increasing, and per interval
82
- in INTERVALS, one widening factor > 0 per sample size}."""
83
- n = np.asarray(cal["n"], dtype=float)
84
- if n.ndim != 1 or len(n) == 0 or np.any(np.diff(n) <= 0) or np.any(n <= 0):
85
- raise ValueError(f"calibration n must be increasing positive sample sizes; got {cal['n']}")
86
- for name in INTERVALS:
87
- f = np.asarray(cal[name], dtype=float)
88
- if f.shape != n.shape or np.any(f <= 0):
89
- raise ValueError(f"calibration {name!r} needs one positive factor per n; got {cal[name]}")
90
-
91
-
92
- def calibration_factors(cal, n):
93
- """The widening factor of each interval in INTERVALS for a table of n rows: interpolated
94
- linearly in log n between the calibrated sample sizes, constant beyond them."""
95
- logn = np.log(np.asarray(cal["n"], dtype=float))
96
- return {name: float(np.interp(np.log(n), logn, cal[name])) for name in INTERVALS}
97
-
98
-
99
- def calibrate(q, factors):
100
- """Quantiles q (..., len(QUANTILES)) with each interval's distance from the median scaled
101
- by its factor, the 90% interval's (outer quantiles) and the 50% interval's (inner) on both
102
- sides alike, so antisymmetry holds; the inner ones never pass the outer ones."""
103
- med = q[..., MID:MID + 1]
104
- dev = q - med
105
- scale = np.ones(len(QUANTILES))
106
- for name, (lo, hi) in INTERVALS.items():
107
- scale[[QUANTILES.index(lo), QUANTILES.index(hi)]] = factors[name]
108
- out = dev * scale
109
- inner, outer = [QUANTILES.index(p) for p in INTERVALS["inner"]], [QUANTILES.index(p) for p in INTERVALS["outer"]]
110
- out[..., inner[0]] = np.maximum(out[..., inner[0]], out[..., outer[0]])
111
- out[..., inner[1]] = np.minimum(out[..., inner[1]], out[..., outer[1]])
112
- return (med + out).astype(q.dtype)
113
-
114
-
115
- class LinearFit(NamedTuple):
116
- """Least squares of Y on 1, T and W over a table's observed rows."""
117
- coef: torch.Tensor # (B, P + 2) intercept, T, then W (0 on padded slots)
118
- se: torch.Tensor # (B,) the T coefficient's standard error
119
- loo: torch.Tensor # (B, n) each observed row's leave-one-out prediction, clipped
120
-
121
-
122
- def _design(w, t, w_mask):
123
- """Least-squares design rows (B, ..., P + 2): 1, T, W with padded slots 0, inputs clipped.
124
- w (B, ..., P), t (B, ...), w_mask (B, P)."""
125
- m = w_mask.reshape(w_mask.shape[0], *[1] * (t.dim() - 1), w_mask.shape[1])
126
- t = t.clamp(-CLIP, CLIP)
127
- return torch.cat([torch.ones_like(t)[..., None], t[..., None], torch.where(m, w.clamp(-CLIP, CLIP), 0.0)], -1)
128
-
129
-
130
- def linear_fit(ctx_w, ctx_t, ctx_y, w_mask):
131
- """Linear adjustment (bench.effects.linear_adjustment, with W the optimal set): least
132
- squares of Y on 1, T and W over the observed rows, clipped as the model's inputs; its
133
- T coefficient is the effect of one unit of T if every mechanism is linear. Leave-one-out
134
- predictions come from the leverages, y_i - e_i / (1 - h_ii), exactly."""
135
- B, n, P = ctx_w.shape
136
- D = _design(ctx_w, ctx_t, w_mask) # (B, n, P + 2)
137
- y = ctx_y.clamp(-CLIP, CLIP)
138
- pad = torch.cat([w_mask.new_zeros(B, 2), ~w_mask], -1).float() # padded slots: coefficient 0
139
- G = D.transpose(1, 2) @ D + torch.diag_embed(pad + RIDGE)
140
- eye = torch.eye(P + 2, device=D.device).expand(B, -1, -1)
141
- sol = torch.linalg.solve(G, torch.cat([D.transpose(1, 2) @ y[..., None], eye], -1))
142
- coef, G_inv = sol[..., 0], sol[..., 1:]
143
- resid = y - (D @ coef[..., None])[..., 0]
144
- h = ((D @ G_inv) * D).sum(-1) # leverages
145
- loo = (y - resid / (1 - h).clamp(min=0.05)).clamp(-CLIP, CLIP)
146
- s2 = (resid ** 2).sum(-1) / (n - 2 - w_mask.sum(-1)).clamp(min=1)
147
- return LinearFit(coef, (s2 * G_inv[:, 1, 1]).clamp(min=0).sqrt(), loo)
148
-
149
-
150
- def linear_predict(fit, w, t, w_mask):
151
- """The fit's prediction (B, ...) at W = w (B, ..., P), T = t (B, ...), clipped."""
152
- D = _design(w, t, w_mask)
153
- coef = fit.coef.reshape(fit.coef.shape[0], *[1] * (t.dim() - 1), -1)
154
- return (D * coef).sum(-1).clamp(-CLIP, CLIP)
155
 
156
 
157
  class Rows(NamedTuple):
158
- """The model's predictions for one batch of tables and K treatment values."""
159
- mu: torch.Tensor # (B, K, R) E[Y | T = values[k], W] for each query row
160
- n_avg: int # the first n_avg query rows are observed rows: the g-formula averages them
161
- tokens: torch.Tensor # (B, K, E) their final representations, averaged
162
- context: torch.Tensor # (B, E) a summary of the context rows
163
- value_rank: torch.Tensor # (B, K) each treatment value's rank among the observed T
164
- dose: torch.Tensor # (B, K) E[Y | do(T = values[k])]: the average, plus the gated correction
165
- correction: torch.Tensor # (B, K) the doubly robust correction before the gate (0 without)
166
- gate: torch.Tensor # (B, K) how much of it is used
167
- support: torch.Tensor # (B, K) log(1 + effective number of observed rows near the value)
168
- positivity: torch.Tensor # (B, K) effective share of rows that could receive the value (1 without)
169
- overlap: torch.Tensor # (B,) predicted R² of the treatment given W (0 without)
170
- own_mu: torch.Tensor # (B, r) E[Y | T_i, W_i] for the first r observed rows, blind to row i
171
- own_mean: torch.Tensor # (B, r) the treatment's predicted mean given W_i, blind to row i
172
- own_logsd: torch.Tensor # (B, r) and its log standard deviation
173
- slope: torch.Tensor # (B,) linear adjustment's effect of one unit of T (0 without linear)
174
- slope_se: torch.Tensor # (B,) and its standard error
175
-
176
-
177
- class CrossBlock(nn.Module):
178
- """Pre-norm: queries attend to the context rows (minus any `blocked` (Q, n) pairs), then a
179
- feed-forward. Queries do not attend to each other, so each query's answer depends on the
180
- context only."""
181
- def __init__(self, E, H):
182
  super().__init__()
183
- self.norm_q, self.norm_ctx = nn.LayerNorm(E), nn.LayerNorm(E)
184
- self.attn = nn.MultiheadAttention(E, H, batch_first=True)
185
- self.ff = FeedForward(E)
 
 
 
186
 
187
- def forward(self, q, ctx, blocked=None): # q (B, Q, E), ctx (B, n, E)
188
- c = self.norm_ctx(ctx)
189
- return self.ff(q + self.attn(self.norm_q(q), c, c, attn_mask=blocked, need_weights=False)[0])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
 
192
  def release_tag():
193
- """The Hub tag of the weights released with this package version ("v0.0.1"), or None
194
  when the package is not installed (running from source without metadata)."""
195
  try:
196
  return f"v{version('axiom-effect')}"
@@ -201,14 +197,11 @@ def release_tag():
201
  class AxiomEffect(nn.Module, PyTorchModelHubMixin, library_name="axiom-effect", repo_url=None,
202
  tags=["causal-inference", "effect-estimation", "tabular"]):
203
  """Hugging Face: `save_pretrained(dir)` / `push_to_hub(repo)` write model.safetensors and
204
- config.json (the __init__ arguments, the calibration included); `from_pretrained` rebuilds
205
- it. From a Hub repo it loads the weights released with this package version (the repo's
206
- `v<version>` tag) unless `revision` says otherwise."""
207
  @classmethod
208
  def from_pretrained(cls, pretrained_model_name_or_path, *, revision=None, strict=True, **kwargs):
209
- """As PyTorchModelHubMixin.from_pretrained, with Axiom's two safeguards: a Hub repo
210
- defaults to the weights tagged with this package's version (falling back to main,
211
- with a warning, if the tag is missing), and the weights load strictly."""
212
  path = str(pretrained_model_name_or_path)
213
  tag = release_tag()
214
  if revision is None and tag is not None and not os.path.isdir(path):
@@ -219,268 +212,220 @@ class AxiomEffect(nn.Module, PyTorchModelHubMixin, library_name="axiom-effect",
219
  f"not match this version of the code", stacklevel=2)
220
  return super().from_pretrained(path, revision=revision, strict=strict, **kwargs)
221
 
222
- def __init__(self, E=128, H=8, row_layers=2, context_layers=4, query_layers=3, inducing=64,
223
- doubly_robust=False, positivity=False, linear=False, calibration=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  super().__init__()
225
- self.config = dict(architecture="in-context g-formula", E=E, H=H, row_layers=row_layers,
226
- context_layers=context_layers, query_layers=query_layers, inducing=inducing,
227
- doubly_robust=doubly_robust, positivity=positivity, linear=linear)
228
- if calibration is not None:
229
- check_calibration(calibration)
230
- self.config["calibration"] = calibration
231
- if positivity and not doubly_robust:
232
- raise ValueError("positivity inputs belong to the doubly robust gate: needs doubly_robust=True")
233
- extra = 2 if positivity else 0 # positivity, overlap
234
- # A row: its cells (value, rank) with their role (W, T, Y and, with linear, the linear
235
- # fit's prediction), attended across, pooled.
236
- self.cell = mlp(2, E, E)
237
- self.role = nn.Embedding(4 if linear else 3, E)
238
- self.unknown = nn.Parameter(torch.zeros(E)) # a cell the query asks about
239
- self.row_attn = nn.ModuleList(Attention(E, H) for _ in range(row_layers))
240
- self.row_ff = nn.ModuleList(FeedForward(E) for _ in range(row_layers))
241
- self.row_out = mlp(E, E, E)
242
- # The context rows attend to each other through inducing points.
243
- self.context_attn = nn.ModuleList(Attention(E, H, inducing) for _ in range(context_layers))
244
- self.context_ff = nn.ModuleList(FeedForward(E) for _ in range(context_layers))
245
- # Query rows -> E[Y | T = v, W = w] (and, doubly robust, the treatment's density given W).
246
- self.query_blocks = nn.ModuleList(CrossBlock(E, H) for _ in range(query_layers))
247
- self.mu = nn.Linear(E, 1)
248
- self.treatment = nn.Linear(E, 2) if doubly_robust else None # mean, log sd of T given W
249
- self.gate = mlp(4 + extra, E, 1) if doubly_robust else None # support, rank, size, correction (+ extra)
250
- # The effect's quantiles around the estimate, from: estimate, spread of the per-row
251
- # differences, the query tokens' difference and sum, context, size, a, b, b - a with
252
- # the ranks of a and b, (doubly robust) the corrections' difference, gates and supports,
253
- # (positivity) both values' positivity and the overlap, and (linear) linear adjustment's
254
- # effect and its standard error.
255
- self.spread = mlp(2 + 3 * E + 1 + 5 + (5 if doubly_robust else 0) + (3 if positivity else 0)
256
- + (2 if linear else 0), E, len(QUANTILES) - 1)
257
- # In training, recompute each layer's activations in the backward pass instead of
258
- # storing them: much less memory, about 30% more compute (train_effect.py --recompute).
259
- self.recompute = False
260
 
261
  def _run(self, fn, *args):
262
  if self.recompute and self.training and torch.is_grad_enabled():
263
  return checkpoint(fn, *args, use_reentrant=False)
264
  return fn(*args)
265
 
266
- def _rows(self, w, t, y, w_mask, refs, lin=None):
267
- """Row tokens (B, R, E) from a row's W values w (B, R, P) (w_mask (B, P): which of the
268
- P slots are real), its treatment t and outcome y (B, R) (NaN = unknown) and, with
269
- linear, the linear fit's prediction lin (B, R) (NaN = unknown), with ranks relative to
270
- the observed columns refs = (ctx_w, ctx_t, ctx_y[, the observed rows' predictions])."""
271
- B, R, P = w.shape
272
- cols, ref_cols = [w, t[..., None], y[..., None]], [refs[0], refs[1][..., None], refs[2][..., None]]
273
- role = [W_ROLE] * P + [T_ROLE, Y_ROLE]
274
- if self.config["linear"]:
275
- cols.append(lin[..., None]); ref_cols.append(refs[3][..., None]); role.append(L_ROLE)
276
- C = len(role)
277
- v, ref = torch.cat(cols, -1), torch.cat(ref_cols, -1) # (B, R, C), (B, n, C)
278
- unknown = torch.isnan(v)
279
- v = v.nan_to_num(0.0).clamp(-CLIP, CLIP)
280
- r = ranks(v.transpose(1, 2), ref.clamp(-CLIP, CLIP).transpose(1, 2)).transpose(1, 2)
281
- role = torch.tensor(role, device=w.device)
282
- e = torch.where(unknown[..., None], self.unknown, self.cell(torch.stack([v, r], -1))) + self.role(role)
283
- pad = torch.cat([~w_mask, torch.zeros(B, C - P, dtype=torch.bool, device=w.device)], -1)
284
- pad = pad[:, None].expand(B, R, C).reshape(B * R, C)
285
- e = e.reshape(B * R, C, -1)
286
- for attn, ff in zip(self.row_attn, self.row_ff):
287
- e = self._run(lambda e, pad, attn=attn, ff=ff: ff(attn(e, pad)), e, pad)
288
- keep = (~pad).float()[..., None]
289
- return self.row_out((e * keep).sum(1) / keep.sum(1)).reshape(B, R, -1)
290
-
291
- def _decode(self, q, ctx, blocked=None):
292
- for blk in self.query_blocks:
293
- q = self._run(blk, q, ctx, blocked)
294
- return q
295
-
296
- def forward(self, ctx_w, ctx_t, ctx_y, w_mask, query_w, values, n_avg=None, own=None, chunk=None):
297
- """Every prediction for a batch. ctx_w (B, n, P), ctx_t and ctx_y (B, n): the observed
298
- rows, reduced to (W, T, Y); w_mask (B, P); query_w (B, K, R, P): the W of R query rows
299
- for each of K treatment values, values (B, K), the first n_avg of them observed rows
300
- (default: all); own: how many of the first observed rows give the doubly robust
301
- correction its residuals and densities (default: all). Queries go `chunk` rows at a
302
- time (default: all at once)."""
303
- B, K, R, P = query_w.shape
304
- n, dev = ctx_t.shape[1], ctx_t.device
305
- n_avg = R if n_avg is None else n_avg
306
- linear = self.config["linear"]
307
- fit = linear_fit(ctx_w, ctx_t, ctx_y, w_mask) if linear else None
308
- refs = (ctx_w, ctx_t, ctx_y, fit.loo) if linear else (ctx_w, ctx_t, ctx_y)
309
- ctx = self._rows(ctx_w, ctx_t, ctx_y, w_mask, refs, fit.loo if linear else None)
310
- for attn, ff in zip(self.context_attn, self.context_ff):
311
- ctx = self._run(lambda c, attn=attn, ff=ff: ff(attn(c)), ctx)
312
-
313
- step = chunk or R
314
- mus, pooled = [], 0.0
315
- for s in range(0, R, step):
316
- qw = query_w[:, :, s:s + step]
317
- r = qw.shape[2]
318
- q_t = values[..., None].expand(B, K, r).reshape(B, K * r)
319
- q_w = qw.reshape(B, K * r, P)
320
- lin = linear_predict(fit, q_w, q_t, w_mask) if linear else None
321
- q = self._decode(self._rows(q_w, q_t, torch.full_like(q_t, float("nan")), w_mask, refs, lin),
322
- ctx).reshape(B, K, r, -1)
323
- mus.append(self.mu(q)[..., 0] + (lin.reshape(B, K, r) if linear else 0.0))
324
- pooled = pooled + q[:, :, :max(0, min(r, n_avg - s))].sum(2)
325
- mu = torch.cat(mus, 2)
326
-
327
- own = n if own is None else min(own, n)
328
- own_mu, own_mean, own_logsd = [], [], []
329
- if self.config["doubly_robust"]:
330
- ostep = chunk or own
331
- for s in range(0, own, ostep):
332
- idx = torch.arange(s, min(s + ostep, own), device=dev)
333
- m = len(idx)
334
- w_i, t_i = ctx_w[:, idx], ctx_t[:, idx]
335
- nan = torch.full_like(t_i, float("nan"))
336
- lin = fit.loo[:, idx] if linear else None # the fit without row i
337
- q = torch.cat([self._rows(w_i, t_i, nan, w_mask, refs, lin), # its own T: its outcome
338
- self._rows(w_i, nan, nan, w_mask, refs, nan)], 1) # T unknown: T's density
339
- blocked = torch.zeros(2 * m, n, dtype=torch.bool, device=dev)
340
- blocked[torch.arange(2 * m, device=dev), idx.repeat(2)] = True # blind to its own row
341
- q = self._decode(q, ctx, blocked)
342
- own_mu.append(self.mu(q[:, :m])[..., 0] + (lin if linear else 0.0))
343
- mean, logsd = self.treatment(q[:, m:]).unbind(-1)
344
- own_mean.append(mean)
345
- own_logsd.append(logsd.clamp(-5, 3))
346
- cat = lambda xs: torch.cat(xs, 1) if xs else ctx_t.new_zeros(B, 0)
347
- own_mu, own_mean, own_logsd = cat(own_mu), cat(own_mean), cat(own_logsd)
348
-
349
- value_rank = ranks(values.clamp(-CLIP, CLIP)[:, None], ctx_t.clamp(-CLIP, CLIP)[:, None])[:, 0]
350
- g = mu[..., :n_avg].mean(2)
351
- if self.config["doubly_robust"]:
352
- correction, support = self._correction(own_mu, own_mean, own_logsd, ctx_t, ctx_y, values, n)
353
- size = torch.full_like(g, float(np.log(n) / np.log(N_REF)))
354
- gate_in = [support, value_rank, size, correction]
355
- positivity, overlap = self._positivity(own_mean, own_logsd, values)
356
- if self.config["positivity"]:
357
- gate_in += [positivity, overlap[:, None].expand_as(g)]
358
- gate = torch.sigmoid(self.gate(torch.stack(gate_in, -1)))[..., 0]
359
- else:
360
- correction = support = torch.zeros_like(g)
361
- gate, positivity, overlap = torch.ones_like(g), torch.ones_like(g), g.new_zeros(B)
362
- slope, slope_se = (fit.coef[:, 1], fit.se) if linear else (g.new_zeros(B), g.new_zeros(B))
363
- return Rows(mu, n_avg, pooled / n_avg, ctx.mean(1), value_rank, g + gate * correction, correction,
364
- gate, support, positivity, overlap, own_mu, own_mean, own_logsd, slope, slope_se)
365
-
366
- @staticmethod
367
- def _positivity(own_mean, own_logsd, values):
368
- """Positivity at each value, (B, K): the effective share of the own rows that could
369
- receive it, (sum_i p_i)² / (r sum_i p_i²) with p_i = pi(v | W_i) the predicted
370
- treatment density, 1 when every row could equally, 1 / r when one row could. And the
371
- table's predicted overlap, (B,): 1 - mean_i Var(T | W_i), the R² of the (standardized)
372
- treatment given W, near 1 where the parents nearly fix it."""
373
- r = own_mean.shape[1]
374
- log_p = torch.distributions.Normal(own_mean[:, None], own_logsd.exp()[:, None]).log_prob(
375
- values.clamp(-CLIP, CLIP)[..., None]) # (B, K, r)
376
- ess = torch.exp(2 * torch.logsumexp(log_p, -1) - torch.logsumexp(2 * log_p, -1))
377
- return ess / r, (1 - (2 * own_logsd).exp().mean(-1)).clamp(0, 1)
378
-
379
- @staticmethod
380
- def _correction(own_mu, own_mean, own_logsd, ctx_t, ctx_y, values, n):
381
- """The doubly robust correction to each value's dose-response, (B, K), and the log of
382
- 1 + the effective number of observed rows behind it. Kernel regression on T of the
383
- own rows' residuals Y_i - E[Y | T_i, W_i], weighted by f(T_i) / pi(T_i | W_i)
384
- (clipped at MAX_WEIGHT); f is a kernel density of the observed T, pi the predicted
385
- conditional density; the bandwidth is Silverman's rule for a standardized variable."""
386
- r = own_mu.shape[1]
387
- t_all = ctx_t.clamp(-CLIP, CLIP)
388
- t_i, resid = t_all[:, :r], ctx_y[:, :r].clamp(-CLIP, CLIP) - own_mu
389
- h = 1.06 * n ** -0.2
390
- kern = lambda u: torch.exp(-0.5 * u * u)
391
- log_f = torch.log(kern((t_i[..., None] - t_all[:, None]) / h).mean(-1) / (h * math.sqrt(2 * math.pi)) + 1e-12)
392
- log_pi = torch.distributions.Normal(own_mean, own_logsd.exp()).log_prob(t_i)
393
- weight = (log_f - log_pi).clamp(max=math.log(MAX_WEIGHT)).exp()
394
- K = kern((t_i[:, None] - values.clamp(-CLIP, CLIP)[..., None]) / h) # (B, K, r)
395
- Kw = K * weight[:, None]
396
- correction = (Kw * resid[:, None]).sum(-1) / (K.sum(-1) + 1e-6)
397
- support = torch.log1p(Kw.sum(-1) ** 2 / (Kw ** 2).sum(-1).clamp(min=1e-12))
398
- return correction, support
399
-
400
- def quantiles(self, rows, values, pairs, n):
401
- """Quantiles (B, len(pairs), len(QUANTILES)) of the effect of moving the treatment from
402
- values[:, i] to values[:, j], for each (i, j) in pairs (indices into the K values),
403
- from `rows` (see forward()) of a table with n rows."""
404
  i, j = pairs[:, 0], pairs[:, 1]
405
- size = float(np.log(n) / np.log(N_REF))
406
- mu = rows.mu[..., :rows.n_avg]
407
-
408
- def one_way(i, j):
409
- est = rows.dose[:, j] - rows.dose[:, i] # (B, P)
410
- a, b = values[:, i], values[:, j]
411
- feats = [est[..., None], (mu[:, j] - mu[:, i]).std(-1, unbiased=False)[..., None],
412
- rows.tokens[:, j] - rows.tokens[:, i], rows.tokens[:, j] + rows.tokens[:, i],
413
- rows.context[:, None].expand(-1, len(i), -1), torch.full_like(est[..., None], size),
414
- torch.stack([a, b, b - a, rows.value_rank[:, i], rows.value_rank[:, j]], -1)]
415
- if self.config["doubly_robust"]:
416
- feats.append(torch.stack([rows.correction[:, j] - rows.correction[:, i], rows.gate[:, i],
417
- rows.gate[:, j], rows.support[:, i], rows.support[:, j]], -1))
418
- if self.config["positivity"]:
419
- feats.append(torch.stack([rows.positivity[:, i], rows.positivity[:, j],
420
- rows.overlap[:, None].expand_as(est)], -1))
421
- if self.config["linear"]:
422
- # clipped like every input: the standard error can blow up where T is nearly
423
- # a linear function of W (up to ~20 in training tasks, 0.05% of them above CLIP)
424
- feats.append(torch.stack([rows.slope[:, None] * (b - a), rows.slope_se[:, None] * (b - a).abs()],
425
- -1).clamp(-CLIP, CLIP))
426
- steps = F.softplus(self.spread(torch.cat(feats, -1)))
427
  lower = est[..., None] - steps[..., :MID].flip(-1).cumsum(-1).flip(-1)
428
  upper = est[..., None] + steps[..., MID:].cumsum(-1)
429
  return torch.cat([lower, est[..., None], upper], -1)
430
 
431
- # The estimate is antisymmetric already; averaging both directions makes the spread
432
- # symmetric too: quantile p of a -> b is minus quantile 1 - p of b -> a.
433
  return (one_way(i, j) - one_way(j, i).flip(-1)) / 2
434
 
435
- def effect(self, data, graph, treatment, outcome, **kwargs):
436
- """The causal effect of `treatment` on `outcome` in a table, given its causal graph, in
437
- the outcome's units: `axiom_effect.inference.effect(self, ...)`, which see. effects()
438
- below is the low-level call on standardized arrays."""
439
- from .inference import effect
440
- return effect(self, data, graph, treatment, outcome, **kwargs)
 
 
 
 
 
 
441
 
442
  @torch.no_grad()
443
- def effects(self, X, A, t, y, pairs, chunk=256, calibrated=True):
444
- """Quantiles (len(pairs), len(QUANTILES)) of the effect on column y of moving column t
445
- from a to b, for each (a, b) in pairs: X (n, d) a table standardized per column (as
446
- the treatment values are), A (d, d) its DAG, A[i, j] = 1 meaning i -> j. Every row is
447
- a query row and gives the correction its residuals, `chunk` rows at a time.
448
-
449
- With a calibration in the config (calibrate_effect.py) and `calibrated`, the 90% and
450
- 50% intervals are widened (or narrowed) around the median by split-conformal factors
451
- for this n; the median, the estimate, is never changed.
452
-
453
- The graph is taken as true: a DAG over the table's variables, so no hidden confounders
454
- and every effect identified. If it gives no directed path from t to y, intervening on t
455
- cannot move y, and every effect is exactly 0 (a zero-width interval), whatever the data
456
- shows: their association then comes from common causes. A pair (a, a) is exactly 0 too."""
457
- X, A = np.asarray(X, dtype=np.float32), np.asarray(A)
458
- if X.ndim != 2 or A.shape != (X.shape[1], X.shape[1]):
459
- raise ValueError(f"X {X.shape} needs a (d, d) graph with d = its columns; got {A.shape}")
460
- if not (0 <= t < X.shape[1] and 0 <= y < X.shape[1]) or t == y:
461
- raise ValueError(f"treatment {t} and outcome {y} must be two different columns of X")
462
- if not is_dag(A):
463
- raise ValueError("the graph has a directed cycle; effects() needs a DAG")
464
- if y not in descendants(A, t):
465
- return np.zeros((len(pairs), len(QUANTILES)), dtype=np.float32)
466
  device = next(self.parameters()).device
467
- X = torch.as_tensor(X, device=device)
468
- W = torch.as_tensor(optimal_adjustment(A, t, y), dtype=torch.long, device=device)
469
- values, idx = np.unique(np.asarray(pairs, dtype=np.float32), return_inverse=True)
470
- idx = torch.as_tensor(idx.reshape(-1, 2), device=device)
471
- vals = torch.as_tensor(values, device=device)[None]
472
- ctx_w, ctx_t, ctx_y = X[None][:, :, W], X[None, :, t], X[None, :, y]
473
- w_mask = torch.ones(1, len(W), dtype=torch.bool, device=device)
474
  with eval_mode(self):
475
- rows = self(ctx_w, ctx_t, ctx_y, w_mask, ctx_w[:, None].expand(-1, len(values), -1, -1), vals,
476
- chunk=chunk)
477
- q = self.quantiles(rows, vals, idx, len(X))
478
- q = q[0].cpu().numpy()
479
- cal = self.config.get("calibration")
480
- if calibrated and cal:
481
- q = calibrate(q, calibration_factors(cal, len(X)))
482
- # Moving the treatment from a value to itself changes nothing: exactly 0, no interval
483
- # (the quantile head always gives positive widths, even for a -> a).
484
- same = np.asarray(pairs, dtype=np.float32).reshape(-1, 2)
485
- q[same[:, 0] == same[:, 1]] = 0.0
486
- return q
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ AxiomEffect: a prior-fitted network for causal effects (design-effect.md, "The model"). Its
3
+ network is CausalPFN's (Balazadeh et al. 2025, https://huggingface.co/vdblm/causalpfn, Apache
4
+ 2.0; the network is TabDPT's), parameter for parameter, so CausalPFN's trained weights load into
5
+ it (`AxiomEffect.from_causalpfn`) and training starts from them. NOTICE: this file reimplements
6
+ causalpfn's models/model.py and models/transformer_layer.py, with the additions below.
7
+
8
+ It predicts one thing, every row's expected outcome under any treatment value,
9
+ mu(t, w_i) = E[Y | do(T = t), W = w_i], from the table itself: the covariates W, the treatment
10
+ T and the outcome Y of every row. Every causal quantity is arithmetic on mu, not a head of its
11
+ own: a row's effect (CATE) is mu(b, w_i) - mu(a, w_i), the ATE its mean over the rows, the ATT
12
+ its mean over the treated rows, the dose-response the mean of mu(t, w_i) at each t. Binary and
13
+ continuous treatments are the same computation (a binary one asks about its two levels).
14
+
15
+ CausalPFN's network, as it is:
16
+ 1. Inputs. A row is MAX_FEATURES slots: the treatment, then the covariates, zero-padded.
17
+ Each slot is standardized with the context rows' mean and sd and clipped at
18
+ OUTLIER_SIGMA sd (TabDPT's normalize_data and clip_outliers), and one linear map
19
+ (`encoder`) embeds the row. A context row's token is that embedding, layer-normalized,
20
+ plus its outcome's (`y_encoder`, layer-normalized); a query row's token is the embedding
21
+ with the treatment slot set to the value asked about. Outcomes are standardized within
22
+ each arm for a binary treatment, as CausalPFN does (over the table for a continuous one),
23
+ and mu is predicted on that scale.
24
+ 2. Layers (TabDPT's): from the RMS-normalized input, attention to the context tokens and a
25
+ gated feed-forward in parallel; their sum projected, normalized and added to the
26
+ residual. Queries and keys normalized per head (twice, with the queries scaled by
27
+ log2(context) / 10 between: TabDPT's layer, kept exactly so its weights mean the same).
28
+ 3. Head: mu(t, w_i) as a distribution over `nbins` bins on [-vmax, vmax] (the first N_OUT
29
+ outputs are TabDPT's class logits, unused), soft-capped at +-30; trained with the HL-Gauss
30
+ loss (mu_nll); mu is its mean.
31
+
32
+ Additions, none of them on mu's path at the start, so the untrained network is CausalPFN's:
33
+ - Graph roles: each covariate's role features (whether a graph was given, and its role
34
+ relative to T and Y: axiom_effect.graph.roles) enter the row's embedding through
35
+ `roles`, a linear map of the slot's role features and their products with its value,
36
+ initialized to 0 (and exactly 0 without a graph).
37
+ - Continuous treatments: the treatment slot holds any value, as it holds 0 / 1 for a binary
38
+ one.
39
+ - Context and query rows are the same rows: a row's query never attends to its own context
40
+ token (CausalPFN trains on held-out query rows), so it never reads its own outcome or
41
+ treatment directly (exactly, with one layer; deeper, the context rows have read each other).
42
+ - The t-blind token: a query told no treatment value (`t_unknown` in the treatment slot's
43
+ place), read by the propensity heads (binary: P(T = 1 | W); continuous: a Gaussian T | W).
44
+ - Estimands: quantiles of an average effect over a set of rows (the ATE, the ATT, any
45
+ subgroup): the median is the plug-in, the mean of the rows' effects; the widths are a
46
+ head of their own that reads the network's outputs detached, so its loss never moves them.
47
 
48
  from axiom_effect import AxiomEffect
49
+ model = AxiomEffect.from_pretrained("path/or/hub-repo")
50
+ r = model.effect(df, treatment="price", outcome="sales", graph=g) # axiom_effect.inference
51
 
52
+ Everything inside is on the table's standardized scale.
53
  """
54
  import math
55
  import os
 
61
  import torch
62
  import torch.nn as nn
63
  import torch.nn.functional as F
64
+ from huggingface_hub import PyTorchModelHubMixin, hf_hub_download
65
  from huggingface_hub.errors import RevisionNotFoundError
66
  from torch.utils.checkpoint import checkpoint
67
 
68
+ from .blocks import eval_mode, mlp
69
+ from .graph import N_ROLES
70
 
71
+ ARCHITECTURE = "CausalPFN" # config["architecture"]: checkpoints of other networks are refused
72
+ QUANTILES = (0.05, 0.25, 0.5, 0.75, 0.95) # the outer two make a 90% interval, the inner two 50%
73
  MID = QUANTILES.index(0.5)
74
+ N_FEATURES = 1 + N_ROLES # per covariate: graph given, then its role indicators
75
+ N_REF = 2048 # log(rows) / log(N_REF): the sample-size input
76
+ MAX_FEATURES = 100 # input slots: the treatment, then up to 99 covariates
77
+ MAX_COVARIATES = MAX_FEATURES - 1
78
+ N_OUT = 10 # TabDPT's class logits ahead of the bins (unused)
79
+ OUTLIER_SIGMA = 10.0 # inputs are clipped at this many sd (TabDPT's clip_outliers)
80
+ NBINS, VMAX, SIGMA = 1024, 10.0, 0.5 # CausalPFN's bins on [-VMAX, VMAX], its HL-Gauss sd
81
+ LOGIT_CAP = 30.0 # TabDPT's soft cap on the head's outputs
82
+ CAUSALPFN_REPO, CAUSALPFN_FILE = "vdblm/causalpfn", "causalpfn_v0.pt"
83
+ CAUSALPFN_CONFIG = dict(E=384, H=6, layers=20, nbins=NBINS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
 
86
  class Rows(NamedTuple):
87
+ """Everything forward() predicts for a batch of B tables of n rows."""
88
+ query: torch.Tensor # (B, n, E) each row's t-blind query token, normalized
89
+ context: torch.Tensor # (B, E) mean context token, normalized: a summary of the table
90
+ mu: torch.Tensor # (B, K, n) mu(values[k], w_i), standardized outcome: the mean of mu's distribution
91
+ logits: torch.Tensor # (B, K, n, nbins) mu's distribution over the bins, on the arm's scale
92
+ shift: torch.Tensor # (B, K) the outcome's mean in value k's arm: mu = shift + scale * (the bins' mean)
93
+ scale: torch.Tensor # (B, K) and its sd
94
+ logit: torch.Tensor # (B, n) binary tables: logit of P(T = 1 | w_i)
95
+ t_mean: torch.Tensor # (B, n) continuous tables: mean of T | w_i
96
+ t_logsd: torch.Tensor # (B, n) continuous tables: log sd of T | w_i
97
+ values: torch.Tensor # (B, K) the treatment values asked about
98
+ binary: torch.Tensor # (B,) bool
99
+
100
+
101
+ class RMSNorm(nn.Module):
102
+ """TabDPT's RMSNorm (eps 1e-6, computed in float32)."""
103
+ def __init__(self, dim, eps=1e-6):
 
 
 
 
 
 
 
104
  super().__init__()
105
+ self.eps = eps
106
+ self.weight = nn.Parameter(torch.ones(dim))
107
+
108
+ def forward(self, x):
109
+ y = x.float()
110
+ return (y * torch.rsqrt(y.pow(2).mean(-1, keepdim=True) + self.eps)).type_as(x) * self.weight
111
 
112
+
113
+ class Layer(nn.Module):
114
+ """TabDPT's layer (causalpfn's TransformerEncoderLayer), its parameter names kept: from the
115
+ normalized input, attention to the context tokens and a gated feed-forward (of width E,
116
+ from the same projection as the attention's queries) in parallel; their sum, projected and
117
+ normalized, is added to the residual."""
118
+ def __init__(self, E, H):
119
+ super().__init__()
120
+ self.H, self.d = H, E // H
121
+ self.kv_proj = nn.Linear(E, 2 * E, bias=False)
122
+ self.q_proj = nn.Linear(E, 3 * E, bias=False) # the queries, the feed-forward's value and gate
123
+ self.out_proj = nn.Linear(E, E, bias=False)
124
+ self.attn_norm, self.ff_norm = RMSNorm(E), RMSNorm(E)
125
+ self.q_norm, self.k_norm = RMSNorm(self.d), RMSNorm(self.d)
126
+
127
+ def keys(self, ctx):
128
+ """(k, v), each (N, H, n, d): the context tokens' keys and values for this layer."""
129
+ N, n, _ = ctx.shape
130
+ k, v = self.kv_proj(self.attn_norm(ctx)).chunk(2, -1)
131
+ k = k.view(N, n, self.H, self.d).transpose(1, 2)
132
+ v = v.view(N, n, self.H, self.d).transpose(1, 2)
133
+ return self.k_norm(self.k_norm(k)), v # normalized twice, as TabDPT's are
134
+
135
+ def forward(self, x, k, v, mask=None):
136
+ """x (N, L, E) tokens reading the context's keys and values k, v (N, H, n, d); mask
137
+ (L, n) added to the attention logits (-inf: may not attend), or None."""
138
+ N, L, E = x.shape
139
+ q, ff_h, ff_gate = self.q_proj(self.attn_norm(x)).chunk(3, -1)
140
+ q = q.view(N, L, self.H, self.d).transpose(1, 2)
141
+ q = self.q_norm(self.q_norm(q) * (math.log2(k.shape[2]) / 10))
142
+ a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask).transpose(1, 2).reshape(N, L, E)
143
+ return x + self.ff_norm(self.out_proj(a + ff_h * F.silu(ff_gate)))
144
+
145
+
146
+ def _column_stats(X):
147
+ """TabDPT's normalize_data and clip_outliers over the context rows X (B, n, F): the mean and
148
+ sd (+1e-6) to standardize with, then the clip bounds of the standardized values (OUTLIER_SIGMA
149
+ sd, the sd recomputed without the rows beyond them, around the first mean)."""
150
+ n = X.shape[1]
151
+ mean = X.mean(1, keepdim=True)
152
+ sd = ((X - mean) ** 2).sum(1, keepdim=True).div(max(n - 1, 1)).sqrt() + 1e-6
153
+ Z = (X - mean) / sd
154
+ zm = Z.mean(1, keepdim=True)
155
+ cut = OUTLIER_SIGMA * ((Z - zm) ** 2).sum(1, keepdim=True).div(max(n - 1, 1)).sqrt()
156
+ keep = ((Z - zm).abs() <= cut).float()
157
+ km = (Z * keep).sum(1, keepdim=True) / keep.sum(1, keepdim=True).clamp(min=1)
158
+ cut = OUTLIER_SIGMA * (((km - Z) * keep) ** 2).sum(1, keepdim=True).div(
159
+ (keep.sum(1, keepdim=True) - 1).clamp(min=1)).sqrt()
160
+ return mean, sd, zm - cut, zm + cut
161
+
162
+
163
+ def _arm_scales(T, Y, values, binary):
164
+ """CausalPFN's outcome scaling: binary tables, the mean and sd of Y within each arm (the
165
+ other arm's if one is empty); continuous ones, over the table. Returns (row_shift,
166
+ row_scale) (B, n) for each row's own arm and (shift, scale) (B, K) for each value's."""
167
+ mid = (T.amax(1, keepdim=True) + T.amin(1, keepdim=True)) / 2
168
+ treated, asked = (T > mid).float(), values > mid # (B, n), (B, K)
169
+
170
+ def stats(w):
171
+ c = w.sum(1, keepdim=True)
172
+ m = (w * Y).sum(1, keepdim=True) / c.clamp(min=1)
173
+ s = ((w * (Y - m) ** 2).sum(1, keepdim=True) / c.clamp(min=1)).sqrt() + 1e-20
174
+ return m, s, c > 0
175
+
176
+ m1, s1, has1 = stats(treated)
177
+ m0, s0, has0 = stats(1 - treated)
178
+ m1, s1, m0, s0 = torch.where(has1, m1, m0), torch.where(has1, s1, s0), torch.where(has0, m0, m1), torch.where(has0, s0, s1)
179
+ ma, sa, _ = stats(torch.ones_like(Y))
180
+ b = binary[:, None]
181
+ row_shift = torch.where(b, torch.where(treated > 0, m1, m0), ma)
182
+ row_scale = torch.where(b, torch.where(treated > 0, s1, s0), sa)
183
+ shift = torch.where(b, torch.where(asked, m1, m0), ma)
184
+ scale = torch.where(b, torch.where(asked, s1, s0), sa)
185
+ return row_shift, row_scale, shift, scale
186
 
187
 
188
  def release_tag():
189
+ """The Hub tag of the weights released with this package version ("v0.1.0"), or None
190
  when the package is not installed (running from source without metadata)."""
191
  try:
192
  return f"v{version('axiom-effect')}"
 
197
  class AxiomEffect(nn.Module, PyTorchModelHubMixin, library_name="axiom-effect", repo_url=None,
198
  tags=["causal-inference", "effect-estimation", "tabular"]):
199
  """Hugging Face: `save_pretrained(dir)` / `push_to_hub(repo)` write model.safetensors and
200
+ config.json (the __init__ arguments); `from_pretrained` rebuilds it. From a Hub repo it
201
+ loads the weights released with this package version (the repo's `v<version>` tag)
202
+ unless `revision` says otherwise. `from_causalpfn` starts from CausalPFN's weights."""
203
  @classmethod
204
  def from_pretrained(cls, pretrained_model_name_or_path, *, revision=None, strict=True, **kwargs):
 
 
 
205
  path = str(pretrained_model_name_or_path)
206
  tag = release_tag()
207
  if revision is None and tag is not None and not os.path.isdir(path):
 
212
  f"not match this version of the code", stacklevel=2)
213
  return super().from_pretrained(path, revision=revision, strict=strict, **kwargs)
214
 
215
+ @classmethod
216
+ def from_causalpfn(cls, path=None):
217
+ """A network with CausalPFN's trained weights (causalpfn_v0.pt; default: downloaded
218
+ from the Hub into ~/.cache/causalpfn, where the causalpfn package keeps it too) and the
219
+ additions at their starting values. With a binary treatment and no graph it computes
220
+ exactly what CausalPFN's network does."""
221
+ if path is None:
222
+ path = hf_hub_download(CAUSALPFN_REPO, CAUSALPFN_FILE,
223
+ cache_dir=os.path.join(os.path.expanduser("~"), ".cache", "causalpfn"))
224
+ ckpt = torch.load(path, map_location="cpu", weights_only=True) # tensors and plain types only
225
+ cfg = ckpt["model_config"]["model"]
226
+ found = dict(E=cfg["emsize"], H=cfg["nhead"], layers=cfg["nlayers"], nbins=cfg["nbins"])
227
+ if found != CAUSALPFN_CONFIG or cfg["max_num_features"] != MAX_FEATURES or cfg["nhid_factor"] != 2:
228
+ raise ValueError(f"{path}: a CausalPFN network of {cfg}, not the {CAUSALPFN_CONFIG} this code builds")
229
+ model = cls(**CAUSALPFN_CONFIG)
230
+ state = {k[len("model."):]: v for k, v in ckpt["model_state_dict"].items() if k.startswith("model.")}
231
+ missing, unexpected = model.load_state_dict(state, strict=False)
232
+ additions = {n for n, _ in model.named_parameters()} - set(state)
233
+ if unexpected or set(missing) != additions or any(n.split(".")[0] not in ADDITIONS for n in additions):
234
+ raise ValueError(f"{path} does not match the network: missing {missing}, unexpected {unexpected}")
235
+ return model
236
+
237
+ def __init__(self, E=384, H=6, layers=20, nbins=NBINS, vmax=VMAX, sigma=SIGMA):
238
  super().__init__()
239
+ self.config = dict(architecture=ARCHITECTURE, E=E, H=H, layers=layers, nbins=nbins, vmax=vmax, sigma=sigma)
240
+ # CausalPFN's network, its parameter names kept (the checkpoint's, without "model.")
241
+ self.encoder = nn.Linear(MAX_FEATURES, E)
242
+ self.y_encoder = nn.Linear(1, E)
243
+ self.xnorm, self.ynorm = nn.LayerNorm(E, bias=False), nn.LayerNorm(E, bias=False)
244
+ self.transformer_encoder = nn.ModuleList(Layer(E, H) for _ in range(layers))
245
+ self.head = nn.Sequential(nn.Linear(E, 2 * E, bias=False), nn.GELU(), nn.Linear(2 * E, N_OUT + nbins, bias=False))
246
+ # the additions (ADDITIONS), none on mu's path at the start
247
+ self.roles = nn.Linear(2 * MAX_COVARIATES * N_FEATURES, E, bias=False) # role features, and x role
248
+ nn.init.zeros_(self.roles.weight)
249
+ self.t_unknown = nn.Parameter(0.02 * torch.randn(E)) # the t-blind query's treatment
250
+ self.final = RMSNorm(E) # the t-blind and context tokens, for the heads below
251
+ self.propensity = nn.Linear(E, 1) # binary: logit P(T = 1 | W)
252
+ self.treatment = nn.Linear(E, 2) # continuous: mean, log sd of T | W
253
+ # an estimand's quantile widths, from: the plug-in, the spread of the rows' effects,
254
+ # the rows' mean query token, the table summary, both values' embeddings, the rows'
255
+ # count and share, binary
256
+ self.widths = mlp(2 + 4 * E + 3, E, len(QUANTILES) - 1)
257
+ edges = torch.linspace(-vmax, vmax, nbins + 1)
258
+ # buffers rebuilt from the config, not saved with the weights
259
+ self.register_buffer("edges", edges, persistent=False)
260
+ self.register_buffer("centers", (edges[1:] + edges[:-1]) / 2, persistent=False)
261
+ self.recompute = False # training: recompute activations in the backward pass (less memory)
 
 
 
 
 
 
 
 
 
 
 
 
262
 
263
  def _run(self, fn, *args):
264
  if self.recompute and self.training and torch.is_grad_enabled():
265
  return checkpoint(fn, *args, use_reentrant=False)
266
  return fn(*args)
267
 
268
+ def _embed(self, W, features, w_mask):
269
+ """(B, n, E) each row's embedding without its treatment slot's term (the covariate
270
+ slots through `encoder`, plus their roles through `roles`), and the treatment slot's
271
+ weight (E,): a row's embedding at a standardized treatment z is the first + z * the
272
+ second, as `encoder` of the full row would give."""
273
+ B, n, P = W.shape
274
+ W = F.pad(W, (0, MAX_COVARIATES - P)) # zero slots, as CausalPFN pads
275
+ feats = F.pad(features * w_mask[..., None], (0, 0, 0, MAX_COVARIATES - P)) # (B, 99, N_FEATURES)
276
+ prod = (W[..., None] * feats[:, None]).flatten(-2) # (B, n, 99 * N_FEATURES)
277
+ role_in = torch.cat([prod, feats.flatten(-2)[:, None].expand(B, n, -1)], -1)
278
+ x = F.linear(W, self.encoder.weight[:, 1:], self.encoder.bias) + self.roles(role_in)
279
+ return x, self.encoder.weight[:, 0]
280
+
281
+ def forward(self, W, T, Y, w_mask, features, binary, values, chunk=None, self_mask=True):
282
+ """W (B, n, P) covariates, w_mask (B, P) True = a real covariate, features (B, P,
283
+ N_FEATURES), T and Y (B, n), binary (B,) bool, values (B, K) treatment values to
284
+ predict mu at (on T's scale). `chunk`: query tokens at a time (each row is K + 1 of
285
+ them; default all). self_mask=False lets a row's query read its own context token,
286
+ as CausalPFN's estimator does at inference (for comparison with it only)."""
287
+ B, n, P = W.shape
288
+ if P > MAX_COVARIATES:
289
+ raise ValueError(f"{P} covariates: the network has slots for at most {MAX_COVARIATES}")
290
+ E, K = self.config["E"], values.shape[1]
291
+ binary = torch.as_tensor(binary, dtype=torch.bool, device=W.device)
292
+ cols = torch.cat([T[..., None], W * w_mask[:, None].float()], -1) # (B, n, 1 + P)
293
+ mean, sd, lo, hi = _column_stats(cols)
294
+ Z = torch.minimum(torch.maximum((cols - mean) / sd, lo), hi)
295
+ tz = lambda t: torch.minimum(torch.maximum((t - mean[..., 0]) / sd[..., 0], lo[..., 0]), hi[..., 0])
296
+ x, w_t = self._run(self._embed, Z[..., 1:], features, w_mask) # (B, n, E), (E,)
297
+ row_shift, row_scale, shift, scale = _arm_scales(T, Y, values, binary)
298
+ y = (Y - row_shift) / row_scale
299
+ ctx = self.xnorm(x + Z[..., :1] * w_t) + self.ynorm(self.y_encoder(y[..., None]))
300
+
301
+ def context_layer(ctx, layer):
302
+ k, v = layer.keys(ctx)
303
+ return layer(ctx, k, v), k, v
304
+
305
+ kvs = []
306
+ for layer in self.transformer_encoder:
307
+ ctx, k, v = self._run(context_layer, ctx, layer)
308
+ kvs.append((k, v))
309
+
310
+ J = K + 1 # the values asked about, then the t-blind token
311
+ told = torch.cat([tz(values)[..., None] * w_t, self.t_unknown.expand(B, 1, E)], 1) # (B, J, E)
312
+ step = max(1, chunk // J) if chunk else n
313
+ out = []
314
+ for s in range(0, n, step):
315
+ xs = x[:, s:s + step]
316
+ Q = xs.shape[1]
317
+ q = self.xnorm(xs[:, None] + told[:, :, None]).reshape(B, J * Q, E)
318
+ mask = None
319
+ if self_mask:
320
+ mask = torch.zeros(Q, n, dtype=q.dtype, device=W.device)
321
+ mask[torch.arange(Q), torch.arange(s, s + Q)] = float("-inf") # not its own row
322
+ mask = mask.repeat(J, 1)
323
+ for layer, (k, v) in zip(self.transformer_encoder, kvs):
324
+ q = self._run(layer, q, k, v, mask)
325
+ out.append(q.view(B, J, Q, E))
326
+ q = torch.cat(out, 2) # (B, J, n, E)
327
+ pred = self.head(q[:, :K])
328
+ logits = (LOGIT_CAP * torch.tanh(pred / (7.5 * E ** 0.5)))[..., -self.config["nbins"]:] # (B, K, n, nbins)
329
+ mu = (logits.softmax(-1) * self.centers).sum(-1) * scale[..., None] + shift[..., None]
330
+ blind = self.final(q[:, K])
331
+ t_mean, t_logsd = self.treatment(blind).unbind(-1)
332
+ return Rows(blind, self.final(ctx).mean(1), mu, logits, shift, scale, self.propensity(blind)[..., 0],
333
+ t_mean, t_logsd.clamp(-5, 3), values, binary)
334
+
335
+ def mu_nll(self, rows, target):
336
+ """(B, K, n) CausalPFN's HL-Gauss loss of mu's distribution against the true mu (B, K,
337
+ n), on the scale the network predicts on (each value's arm's): the cross-entropy with a
338
+ Gaussian of sd `sigma` around the truth, integrated over the bins (the truth clipped to
339
+ the bins' range)."""
340
+ p = self._hl_target(rows, target)
341
+ return -(p * rows.logits.log_softmax(-1)).sum(-1)
342
+
343
+ def mu_floor(self, rows, target):
344
+ """(B, K, n) the entropy of mu_nll's target distribution: its value for a perfect
345
+ prediction, so mu_nll minus it (the KL from the target) is the part training can lower."""
346
+ p = self._hl_target(rows, target)
347
+ return -torch.special.xlogy(p, p).sum(-1)
348
+
349
+ def _hl_target(self, rows, target):
350
+ """(B, K, n, nbins) the HL-Gauss target: a Gaussian of sd `sigma` around the true mu on
351
+ the arm's scale (clipped to the bins' range), integrated over the bins."""
352
+ t = ((target - rows.shift[..., None]) / rows.scale[..., None]).clamp(-self.config["vmax"], self.config["vmax"])
353
+ p = torch.special.ndtr((self.edges - t[..., None]) / self.config["sigma"]).diff(dim=-1)
354
+ return p / (p.sum(-1, keepdim=True) + 1e-8)
355
+
356
+ def estimands(self, rows, pairs, weights):
357
+ """Quantiles (B, S, len(QUANTILES)) of S average effects: estimand s moves the
358
+ treatment from values[:, pairs[s, 0]] to values[:, pairs[s, 1]], averaged over the
359
+ rows with weights[:, s] (B, S, n) (1 / 0 masks: all rows the ATE, the treated rows
360
+ the ATT). The median is the weighted mean of the rows' effects; the widths are
361
+ learned, from the network's outputs detached (their loss trains `widths` alone), and
362
+ antisymmetric: a -> b is minus b -> a."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
  i, j = pairs[:, 0], pairs[:, 1]
364
+ mu, query, context = rows.mu.detach(), rows.query.detach(), rows.context.detach()
365
+ w = weights.float()
366
+ tot = w.sum(-1).clamp(min=1e-6) # (B, S)
367
+ n = w.shape[-1]
368
+ phi = self._value_features(rows.values)
369
+ pooled = (w[..., None] * query[:, None]).sum(2) / tot[..., None] # (B, S, E)
370
+ context = context[:, None].expand_as(pooled)
371
+
372
+ def one_way(a, b):
373
+ d = mu[:, b] - mu[:, a] # (B, S, n)
374
+ est = (w * d).sum(-1) / tot
375
+ spread = ((w * (d - est[..., None]) ** 2).sum(-1) / tot).sqrt()
376
+ feats = torch.cat([est[..., None], spread[..., None], pooled, context, phi[:, a], phi[:, b],
377
+ (torch.log(tot) / np.log(N_REF))[..., None], (tot / n)[..., None],
378
+ rows.binary.float()[:, None, None].expand_as(est[..., None])], -1)
379
+ moved = (rows.values[:, a] != rows.values[:, b]).float()[..., None] # a -> a: exactly 0
380
+ steps = F.softplus(self.widths(feats)) * moved
 
 
 
 
 
381
  lower = est[..., None] - steps[..., :MID].flip(-1).cumsum(-1).flip(-1)
382
  upper = est[..., None] + steps[..., MID:].cumsum(-1)
383
  return torch.cat([lower, est[..., None], upper], -1)
384
 
 
 
385
  return (one_way(i, j) - one_way(j, i).flip(-1)) / 2
386
 
387
+ def _value_features(self, values):
388
+ """(B, K, E) a treatment value's embedding for the width head: the treatment slot's
389
+ term of the row embedding, detached."""
390
+ return (values[..., None] * self.encoder.weight[:, 0]).detach()
391
+
392
+ def treatment_nll(self, rows, T):
393
+ """(B, n) negative log-likelihood of each row's treatment given its covariates:
394
+ Bernoulli on binary tables, Gaussian on continuous ones."""
395
+ mid = (T.amax(1, keepdim=True) + T.amin(1, keepdim=True)) / 2
396
+ bern = F.binary_cross_entropy_with_logits(rows.logit, (T > mid).float(), reduction="none")
397
+ gauss = -torch.distributions.Normal(rows.t_mean, rows.t_logsd.exp()).log_prob(T.clamp(-OUTLIER_SIGMA, OUTLIER_SIGMA))
398
+ return torch.where(rows.binary[:, None], bern, gauss)
399
 
400
  @torch.no_grad()
401
+ def predict(self, W, T, Y, features, binary, values, estimands=(), chunk=4096):
402
+ """One standardized table, as numpy: W (n, p), T and Y (n,), features (p, N_FEATURES),
403
+ binary, values (K,), estimands [(a, b, rows)] with a, b indices into values and rows an
404
+ (n,) bool mask. Returns mu (K, n), quantiles (len(estimands), len(QUANTILES)), and the
405
+ propensity: e (n,) P(T = 1 | w_i) for a binary treatment, else t_mean and t_sd (n,)."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
  device = next(self.parameters()).device
407
+ f = lambda a: torch.as_tensor(np.asarray(a, dtype=np.float32), device=device)[None]
408
+ W = np.asarray(W, dtype=np.float32).reshape(len(T), -1)
 
 
 
 
 
409
  with eval_mode(self):
410
+ rows = self(f(W), f(T), f(Y), torch.ones(1, W.shape[1], dtype=torch.bool, device=device),
411
+ f(np.asarray(features, dtype=np.float32).reshape(W.shape[1], N_FEATURES)),
412
+ torch.tensor([bool(binary)], device=device), f(values), chunk=chunk)
413
+ out = {"mu": rows.mu[0].cpu().numpy()}
414
+ if estimands:
415
+ pairs = torch.tensor([[a, b] for a, b, _ in estimands], device=device)
416
+ weights = f(np.stack([np.asarray(r, dtype=np.float32) for _, _, r in estimands]))
417
+ out["quantiles"] = self.estimands(rows, pairs, weights)[0].cpu().numpy()
418
+ if binary:
419
+ out["e"] = torch.sigmoid(rows.logit[0]).cpu().numpy()
420
+ else:
421
+ out["t_mean"], out["t_sd"] = rows.t_mean[0].cpu().numpy(), rows.t_logsd[0].exp().cpu().numpy()
422
+ return out
423
+
424
+ def effect(self, data, treatment, outcome, **kwargs):
425
+ """The causal effect of `treatment` on `outcome` in a table, in the data's units:
426
+ `axiom_effect.inference.effect(self, ...)`, which see."""
427
+ from .inference import effect
428
+ return effect(self, data, treatment, outcome, **kwargs)
429
+
430
+
431
+ ADDITIONS = ("roles", "t_unknown", "final", "propensity", "treatment", "widths") # parameters CausalPFN has not