Release 0.1.0
Browse files- LICENSE-CausalPFN +175 -0
- NOTICE +14 -0
- README.md +53 -89
- config.json +6 -27
- model.safetensors +2 -2
- pyproject.toml +3 -3
- src/axiom_effect/__init__.py +10 -7
- src/axiom_effect/graph.py +69 -0
- src/axiom_effect/inference.py +343 -204
- src/axiom_effect/model.py +363 -418
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
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
where
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
Check its answers against what you know about your data.
|
| 21 |
|
| 22 |
-
|
| 23 |
-
the
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
[maxpagels.com/axiom](https://maxpagels.com/axiom).
|
| 30 |
|
| 31 |
## Recommended use (ballpark)
|
| 32 |
|
| 33 |
| | recommendation |
|
| 34 |
|---|---|
|
| 35 |
-
|
|
| 36 |
-
|
|
| 37 |
-
|
|
| 38 |
-
| rows | trained on 128-
|
| 39 |
-
|
|
| 40 |
-
| missing values | not supported in the
|
| 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 |
-
|
| 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 |
-
|
|
|
|
| 82 |
|
|
|
|
| 83 |
g = Axiom.from_pretrained("maxpagels/axiom-discovery").discover(df)
|
| 84 |
-
r = model.effect(df,
|
|
|
|
| 85 |
```
|
| 86 |
|
| 87 |
-
A
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 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 |
-
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
-
|
| 124 |
-
- Trained
|
| 125 |
-
|
| 126 |
-
|
|
|
|
| 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
|
| 132 |
-
install its code and load its weights by tag:
|
| 133 |
|
| 134 |
```bash
|
| 135 |
-
pip install "git+https://huggingface.co/maxpagels/axiom-effect@v0.
|
| 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":
|
| 3 |
-
"H":
|
| 4 |
-
"
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 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:
|
| 3 |
-
size
|
|
|
|
| 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.
|
| 4 |
-
description = "AxiomEffect: causal
|
| 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
|
|
|
|
|
|
|
| 2 |
|
| 3 |
from axiom_effect import AxiomEffect
|
| 4 |
model = AxiomEffect.from_pretrained("path/or/hub-repo")
|
| 5 |
-
print(model.effect(df,
|
| 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
|
| 12 |
|
| 13 |
-
__all__ = ["AxiomEffect", "EffectResult", "effect", "TRAIN_N", "
|
| 14 |
-
"
|
|
|
|
|
|
| 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 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
"""
|
| 17 |
import warnings
|
| 18 |
-
from dataclasses import dataclass
|
|
|
|
| 19 |
|
| 20 |
import numpy as np
|
| 21 |
|
| 22 |
-
from .graph import descendants, is_dag,
|
| 23 |
-
from .model import
|
| 24 |
|
| 25 |
-
#
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
@property
|
| 62 |
def estimate(self):
|
| 63 |
-
return float(self.
|
| 64 |
|
| 65 |
@property
|
| 66 |
def interval(self):
|
| 67 |
-
|
| 68 |
-
return float(
|
| 69 |
|
| 70 |
@property
|
| 71 |
def interval50(self):
|
| 72 |
-
|
| 73 |
-
return float(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
def to_frame(self):
|
| 76 |
-
"""
|
| 77 |
-
50% interval bounds."""
|
| 78 |
import pandas as pd
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
| 83 |
|
| 84 |
def __repr__(self):
|
| 85 |
-
g = lambda
|
| 86 |
-
|
| 87 |
-
adj = ", ".join(self.
|
| 88 |
-
rows = f"{self.n_rows} rows" + (f"
|
| 89 |
-
head = f"Effect of {self.treatment} on {self.outcome} ({rows}; adjusted for {adj})"
|
|
|
|
|
|
|
| 90 |
if self.zero_by_graph:
|
| 91 |
-
return head + f"
|
| 92 |
-
|
| 93 |
a, b = self.contrast
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 120 |
-
|
| 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 =
|
| 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)
|
| 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
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
def
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
if not np.isfinite(X[:, used]).all():
|
| 198 |
-
|
| 199 |
-
|
| 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 |
-
|
| 220 |
-
|
| 221 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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:
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
from axiom_effect import AxiomEffect
|
| 39 |
-
model = AxiomEffect.from_pretrained("path/or/hub-repo")
|
| 40 |
-
|
| 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
|
| 59 |
-
from .graph import
|
| 60 |
|
| 61 |
-
|
|
|
|
| 62 |
MID = QUANTILES.index(0.5)
|
| 63 |
-
|
| 64 |
-
N_REF = 2048 # log(
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 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 |
-
"""
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 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.
|
| 184 |
-
self.
|
| 185 |
-
|
|
|
|
|
|
|
|
|
|
| 186 |
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
|
| 192 |
def release_tag():
|
| 193 |
-
"""The Hub tag of the weights released with this package version ("v0.
|
| 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
|
| 205 |
-
|
| 206 |
-
|
| 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 |
-
|
| 223 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
super().__init__()
|
| 225 |
-
self.config = dict(architecture=
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
self.
|
| 237 |
-
self.
|
| 238 |
-
self.
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
self.
|
| 247 |
-
self.
|
| 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
|
| 267 |
-
"""
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
B,
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 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 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 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
|
| 436 |
-
"""
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 441 |
|
| 442 |
@torch.no_grad()
|
| 443 |
-
def
|
| 444 |
-
"""
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 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 |
-
|
| 468 |
-
W =
|
| 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(
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|