Release 0.0.1
Browse files- LICENSE +202 -0
- README.md +142 -0
- config.json +28 -0
- model.safetensors +3 -0
- pyproject.toml +21 -0
- src/axiom_effect/__init__.py +14 -0
- src/axiom_effect/blocks.py +57 -0
- src/axiom_effect/graph.py +47 -0
- src/axiom_effect/inference.py +278 -0
- src/axiom_effect/model.py +413 -0
LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
README.md
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: axiom-effect
|
| 3 |
+
tags:
|
| 4 |
+
- causal-inference
|
| 5 |
+
- effect-estimation
|
| 6 |
+
- tabular
|
| 7 |
+
- pytorch
|
| 8 |
+
license: apache-2.0
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# AxiomEffect
|
| 12 |
+
|
| 13 |
+
Causal effect estimation for tabular data. Given a table, its causal graph and a treatment /
|
| 14 |
+
outcome pair, AxiomEffect estimates what happens to the outcome when the treatment is *set*
|
| 15 |
+
to one value instead of another, E[Y | do(T = b)] - E[Y | do(T = a)], with 90% and 50%
|
| 16 |
+
intervals, and the whole dose-response curve. It is trained on simulated causal models,
|
| 17 |
+
where the true effect is known.
|
| 18 |
+
|
| 19 |
+
> **Version 0.0.1 is experimental.** The API and the weights will change in 0.0.x
|
| 20 |
+
> releases. Check its answers against what you know about your data.
|
| 21 |
+
|
| 22 |
+
The graph decides what to adjust for: the model reads only the treatment, the outcome and
|
| 23 |
+
the graph's optimal adjustment set, so mediators, colliders and other variables that would
|
| 24 |
+
bias the answer never enter. The graph can come from domain knowledge or from
|
| 25 |
+
[Axiom](https://huggingface.co/maxpagels/axiom-discovery), the causal discovery model this is a
|
| 26 |
+
sibling of.
|
| 27 |
+
|
| 28 |
+
6.5M parameters, fp32 safetensors (26 MB). Project page:
|
| 29 |
+
[maxpagels.com/axiom](https://maxpagels.com/axiom).
|
| 30 |
+
|
| 31 |
+
## Recommended use (ballpark)
|
| 32 |
+
|
| 33 |
+
| | recommendation |
|
| 34 |
+
|---|---|
|
| 35 |
+
| graph | a DAG over the table's columns that you trust, with no unmeasured common causes of the treatment and the outcome. The model takes it as true. |
|
| 36 |
+
| treatment | continuous: at least 20 distinct values. Binary and categorical treatments are not supported yet. |
|
| 37 |
+
| treatment values | inside the 2-98% quantiles of the observed treatment (refused outside them unless `extrapolate=True`): beyond them the data has no support for the answer. |
|
| 38 |
+
| rows | trained on 128-1024. Below 128 it warns. Over 1024 rows, `effect` averages 8 random 1024-row subsets, whose intervals are those of 1024 rows: on the wide side. |
|
| 39 |
+
| adjustment set | up to 18 variables, as in training (the table itself can have more columns: only the adjustment set is read). |
|
| 40 |
+
| missing values | not supported in the treatment, the outcome and the adjustment set; other columns may have them. |
|
| 41 |
+
|
| 42 |
+
## Usage
|
| 43 |
+
|
| 44 |
+
```bash
|
| 45 |
+
pip install "git+https://huggingface.co/maxpagels/axiom-effect"
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
```python
|
| 49 |
+
from axiom_effect import AxiomEffect
|
| 50 |
+
|
| 51 |
+
model = AxiomEffect.from_pretrained("maxpagels/axiom-effect")
|
| 52 |
+
|
| 53 |
+
graph = [("age", "price"), ("age", "sales"), ("price", "visits"), ("visits", "sales")]
|
| 54 |
+
r = model.effect(df, graph, treatment="price", outcome="sales")
|
| 55 |
+
print(r)
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
For example, on a simulated table:
|
| 59 |
+
|
| 60 |
+
```
|
| 61 |
+
Effect of price on sales (800 rows; adjusted for age)
|
| 62 |
+
price 29.74 -> 36.89: -10.14 90% [-12.53, -7.738] 50% [-10.99, -9.248]
|
| 63 |
+
dose-response, from price = 33.36:
|
| 64 |
+
26.28 +9.224 90% [5.852, 12.66]
|
| 65 |
+
29.74 +5.172 90% [3.908, 6.547]
|
| 66 |
+
33.36 +0 90% [-0.8777, 0.8777]
|
| 67 |
+
36.89 -4.971 90% [-6.539, -3.388]
|
| 68 |
+
40.34 -9.736 90% [-13.38, -6.002]
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
Everything is in the data's own units: the treatment values in the treatment's, the effects
|
| 72 |
+
in the outcome's (`effect` standardizes the columns it reads, as in training, and converts
|
| 73 |
+
back). The graph can be:
|
| 74 |
+
|
| 75 |
+
- a list of (cause, effect) column-name pairs, as above;
|
| 76 |
+
- a (d, d) adjacency matrix in the table's column order (`A[i, j] = 1` means i -> j);
|
| 77 |
+
- a pandas DataFrame adjacency matrix with the column names as index and columns;
|
| 78 |
+
- a `discover()` result from Axiom: its directed edges.
|
| 79 |
+
|
| 80 |
+
```python
|
| 81 |
+
from axiom import Axiom
|
| 82 |
+
|
| 83 |
+
g = Axiom.from_pretrained("maxpagels/axiom-discovery").discover(df)
|
| 84 |
+
r = model.effect(df, g, treatment="price", outcome="sales")
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
A discovered graph is only as good as its edges. Undirected or confounded relations near
|
| 88 |
+
the treatment or outcome are ignored with a warning, and if the discovered graph has no
|
| 89 |
+
directed path from the treatment to the outcome the effect is exactly 0, with a warning
|
| 90 |
+
too: one wrong edge is enough for that.
|
| 91 |
+
|
| 92 |
+
### Reading the result
|
| 93 |
+
|
| 94 |
+
```python
|
| 95 |
+
r.estimate # the headline contrast: moving the treatment from its 25% to its 75% quantile
|
| 96 |
+
r.contrast # those two treatment values, (a, b)
|
| 97 |
+
r.interval # 90% interval of the contrast; r.interval50 the 50% one
|
| 98 |
+
r.adjustment # the variables adjusted for
|
| 99 |
+
r.to_frame() # the dose-response curve: each value's effect from the reference, with intervals
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
| argument | default | meaning |
|
| 103 |
+
|---|---|---|
|
| 104 |
+
| `contrast=(a, b)` | the 25% and 75% quantiles | the headline effect: moving the treatment from a to b |
|
| 105 |
+
| `values` | the 10/25/50/75/90% quantiles | treatment values on the dose-response curve |
|
| 106 |
+
| `reference` | the median | where the curve starts (its effect is 0) |
|
| 107 |
+
|
| 108 |
+
The curve's intervals are pointwise, not simultaneous. The intervals are the model's own
|
| 109 |
+
quantiles, conformally calibrated on held-out simulated data from its training
|
| 110 |
+
distribution. How well they cover on real data is not yet known.
|
| 111 |
+
|
| 112 |
+
If the graph has no directed path from the treatment to the outcome, setting the treatment
|
| 113 |
+
cannot move the outcome: the effect is exactly 0, with a zero-width interval, whatever
|
| 114 |
+
their correlation (`r.zero_by_graph`).
|
| 115 |
+
|
| 116 |
+
## Limitations
|
| 117 |
+
|
| 118 |
+
- The graph is taken as true. A missing confounder or a reversed edge biases the answer,
|
| 119 |
+
and the interval does not widen for it.
|
| 120 |
+
- No hidden confounders: front-door, instrumental-variable and other identification
|
| 121 |
+
strategies beyond adjustment are not supported, and the model never says "not
|
| 122 |
+
identifiable".
|
| 123 |
+
- Continuous treatments only; average effects only (no per-row or conditional effects).
|
| 124 |
+
- Trained and validated on simulated data only: no evaluation on real data yet.
|
| 125 |
+
- Where the adjustment set nearly determines the treatment (poor overlap), and on purely
|
| 126 |
+
linear data, classical estimators can be more accurate.
|
| 127 |
+
|
| 128 |
+
## Versions
|
| 129 |
+
|
| 130 |
+
Each release is a tagged commit in this repo; `main` is the latest. The package loads the
|
| 131 |
+
weights released with it, so code and weights always match. To use a specific release,
|
| 132 |
+
install its code and load its weights by tag:
|
| 133 |
+
|
| 134 |
+
```bash
|
| 135 |
+
pip install "git+https://huggingface.co/maxpagels/axiom-effect@v0.0.1"
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
```python
|
| 139 |
+
model = AxiomEffect.from_pretrained("maxpagels/axiom-effect") # this package's release: v0.0.1
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
- **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
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"E": 192,
|
| 3 |
+
"H": 8,
|
| 4 |
+
"calibration": {
|
| 5 |
+
"by_n": false,
|
| 6 |
+
"inner": [
|
| 7 |
+
1.1984461545944214,
|
| 8 |
+
1.1984461545944214
|
| 9 |
+
],
|
| 10 |
+
"n": [
|
| 11 |
+
256,
|
| 12 |
+
1024
|
| 13 |
+
],
|
| 14 |
+
"outer": [
|
| 15 |
+
1.168336033821106,
|
| 16 |
+
1.168336033821106
|
| 17 |
+
],
|
| 18 |
+
"pairs": "contrast",
|
| 19 |
+
"seed": 1,
|
| 20 |
+
"tasks": 750
|
| 21 |
+
},
|
| 22 |
+
"context_layers": 6,
|
| 23 |
+
"doubly_robust": true,
|
| 24 |
+
"inducing": 64,
|
| 25 |
+
"positivity": true,
|
| 26 |
+
"query_layers": 4,
|
| 27 |
+
"row_layers": 2
|
| 28 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b4d3d26a3c247f48ef0f8cd1e54d32465c79a021123180cec12b96a424c1e5b8
|
| 3 |
+
size 26148328
|
pyproject.toml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "axiom-effect"
|
| 3 |
+
version = "0.0.1"
|
| 4 |
+
description = "AxiomEffect: causal effect estimation from a table and its causal graph"
|
| 5 |
+
readme = "README.md"
|
| 6 |
+
authors = [{ name = "Max Pagels" }]
|
| 7 |
+
requires-python = ">=3.11"
|
| 8 |
+
license = "Apache-2.0"
|
| 9 |
+
license-files = ["LICENSE"]
|
| 10 |
+
dependencies = ["huggingface-hub>=2.1", "numpy>=2.0", "safetensors>=0.4", "torch>=2.4"]
|
| 11 |
+
|
| 12 |
+
[project.urls]
|
| 13 |
+
Homepage = "https://maxpagels.com/axiom"
|
| 14 |
+
Repository = "https://huggingface.co/maxpagels/axiom-effect"
|
| 15 |
+
|
| 16 |
+
[build-system]
|
| 17 |
+
requires = ["uv_build>=0.12.18,<0.13.0"]
|
| 18 |
+
build-backend = "uv_build"
|
| 19 |
+
|
| 20 |
+
[tool.uv.build-backend]
|
| 21 |
+
module-name = "axiom_effect"
|
src/axiom_effect/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AxiomEffect: causal effect estimation from a table and its causal graph.
|
| 2 |
+
|
| 3 |
+
from axiom_effect import AxiomEffect
|
| 4 |
+
model = AxiomEffect.from_pretrained("path/or/hub-repo")
|
| 5 |
+
print(model.effect(df, graph, treatment="price", outcome="sales"))
|
| 6 |
+
|
| 7 |
+
See axiom_effect.inference (the table-level call) and axiom_effect.model (the network);
|
| 8 |
+
trained and benchmarked from the axiom repository (train_effect.py)."""
|
| 9 |
+
from .graph import causal_nodes, descendants, is_dag, optimal_adjustment
|
| 10 |
+
from .inference import TRAIN_N, EffectResult, effect
|
| 11 |
+
from .model import INTERVALS, MID, QUANTILES, AxiomEffect, calibrate, calibration_factors, release_tag
|
| 12 |
+
|
| 13 |
+
__all__ = ["AxiomEffect", "EffectResult", "effect", "TRAIN_N", "QUANTILES", "MID", "INTERVALS", "calibrate",
|
| 14 |
+
"calibration_factors", "release_tag", "descendants", "is_dag", "causal_nodes", "optimal_adjustment"]
|
src/axiom_effect/blocks.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Network building blocks, the same as Axiom's (axiom.model), copied so that axiom-effect
|
| 2 |
+
does not depend on axiom-discovery's internals. Keep the attribute names: they are the weights'
|
| 3 |
+
names in every checkpoint."""
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def mlp(i, h, o):
|
| 11 |
+
return nn.Sequential(nn.Linear(i, h), nn.GELU(), nn.Linear(h, o))
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Attention(nn.Module):
|
| 15 |
+
"""Pre-norm residual self-attention over the middle axis of (N, L, E). With
|
| 16 |
+
`inducing` > 0 the tokens attend through that many learned inducing points (as in
|
| 17 |
+
Set Transformer's ISAB): cost O(L * inducing) instead of O(L^2), so L can be large.
|
| 18 |
+
`mask` (N, L), True = padding: those tokens are updated but not attended to (a
|
| 19 |
+
sequence with every token masked attends to all of them, to stay finite)."""
|
| 20 |
+
def __init__(self, E, H, inducing=0):
|
| 21 |
+
super().__init__()
|
| 22 |
+
self.norm = nn.LayerNorm(E)
|
| 23 |
+
self.attn = nn.MultiheadAttention(E, H, batch_first=True)
|
| 24 |
+
self.points = nn.Parameter(torch.randn(inducing, E) / E ** 0.5) if inducing else None
|
| 25 |
+
self.gather = nn.MultiheadAttention(E, H, batch_first=True) if inducing else None
|
| 26 |
+
|
| 27 |
+
def forward(self, x, mask=None):
|
| 28 |
+
h = self.norm(x)
|
| 29 |
+
if mask is not None:
|
| 30 |
+
mask = mask & ~mask.all(1, keepdim=True)
|
| 31 |
+
if self.points is None:
|
| 32 |
+
return x + self.attn(h, h, h, key_padding_mask=mask, need_weights=False)[0]
|
| 33 |
+
p = self.points.expand(x.shape[0], -1, -1)
|
| 34 |
+
s = self.gather(p, h, h, key_padding_mask=mask, need_weights=False)[0] # summarize the tokens
|
| 35 |
+
return x + self.attn(h, s, s, need_weights=False)[0] # every token reads the summary
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class FeedForward(nn.Module):
|
| 39 |
+
"""Pre-norm residual MLP over the last axis."""
|
| 40 |
+
def __init__(self, E, mult=4):
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.norm = nn.LayerNorm(E)
|
| 43 |
+
self.net = mlp(E, mult * E, E)
|
| 44 |
+
|
| 45 |
+
def forward(self, x):
|
| 46 |
+
return x + self.net(self.norm(x))
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@contextmanager
|
| 50 |
+
def eval_mode(model):
|
| 51 |
+
"""The model in eval mode inside the block, then back in whichever mode it was in."""
|
| 52 |
+
was_training = model.training
|
| 53 |
+
model.eval()
|
| 54 |
+
try:
|
| 55 |
+
yield model
|
| 56 |
+
finally:
|
| 57 |
+
model.train(was_training)
|
src/axiom_effect/graph.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The graph logic of causal effects: which variables a DAG says to adjust for.
|
| 2 |
+
A[i, j] = 1 means i -> j throughout."""
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def descendants(A, t):
|
| 7 |
+
"""The variables t reaches along directed edges of A (t itself excluded), sorted.
|
| 8 |
+
descendants(A.T, t) gives the ancestors."""
|
| 9 |
+
seen, stack = set(), [t]
|
| 10 |
+
while stack:
|
| 11 |
+
for c in np.flatnonzero(A[stack.pop()]):
|
| 12 |
+
if c not in seen:
|
| 13 |
+
seen.add(int(c))
|
| 14 |
+
stack.append(c)
|
| 15 |
+
return sorted(seen)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def is_dag(A):
|
| 19 |
+
"""Whether A has no directed cycle (Kahn's algorithm: peel off variables without parents
|
| 20 |
+
until none are left, or a cycle blocks the rest)."""
|
| 21 |
+
A = (np.asarray(A) != 0).astype(np.int64)
|
| 22 |
+
indegree, ready, seen = A.sum(0), [v for v in range(len(A)) if A[:, v].sum() == 0], 0
|
| 23 |
+
while ready:
|
| 24 |
+
v = ready.pop()
|
| 25 |
+
seen += 1
|
| 26 |
+
for c in np.flatnonzero(A[v]):
|
| 27 |
+
indegree[c] -= 1
|
| 28 |
+
if indegree[c] == 0:
|
| 29 |
+
ready.append(int(c))
|
| 30 |
+
return seen == len(A)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def causal_nodes(A, t, y):
|
| 34 |
+
"""The variables on directed paths from t to y: y and the mediators (t excluded)."""
|
| 35 |
+
ancestors_of_y = set(descendants(A.T, y))
|
| 36 |
+
return {v for v in descendants(A, t) if v == y or v in ancestors_of_y}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def optimal_adjustment(A, t, y):
|
| 40 |
+
"""The optimal adjustment set O(t, y) of a DAG without hidden variables (Henckel,
|
| 41 |
+
Perkovic & Maathuis, 2022): the valid set with the smallest asymptotic variance. It is
|
| 42 |
+
pa(cn) minus forb, with cn = causal_nodes(A, t, y) and forb = t, cn and everything
|
| 43 |
+
downstream of cn; in effect, the parents of the outcome and of the mediators, minus
|
| 44 |
+
anything t causes."""
|
| 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)
|
src/axiom_effect/inference.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Run a trained AxiomEffect on a real table: column names, the graph in any of the usual
|
| 3 |
+
forms, the original units in and out, the training range checked, and a readable result.
|
| 4 |
+
|
| 5 |
+
from axiom_effect import AxiomEffect
|
| 6 |
+
model = AxiomEffect.from_pretrained("path/or/hub-repo")
|
| 7 |
+
r = model.effect(df, graph, treatment="price", outcome="sales")
|
| 8 |
+
print(r) # the 25%-to-75% contrast and the dose-response curve
|
| 9 |
+
r.estimate, r.interval # the contrast and its 90% interval, in units of sales
|
| 10 |
+
r.to_frame() # the curve as a DataFrame
|
| 11 |
+
|
| 12 |
+
`graph` is the causal graph over the table's columns: a (d, d) adjacency matrix in the
|
| 13 |
+
column order (A[i, j] = 1 means i -> j), a pandas DataFrame with the column names as index
|
| 14 |
+
and columns, a list of (cause, effect) name pairs, or a `discover()` result of axiom-discovery
|
| 15 |
+
(its directed edges). The graph is taken as true: a DAG, no hidden confounders.
|
| 16 |
+
"""
|
| 17 |
+
import warnings
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from .graph import descendants, is_dag, optimal_adjustment
|
| 23 |
+
from .model import INTERVALS, MID, QUANTILES
|
| 24 |
+
|
| 25 |
+
# The range the released model was trained on (train_effect.py); outside it, extrapolation.
|
| 26 |
+
TRAIN_N = (128, 1024) # rows; larger tables are split into subsets of TRAIN_N[1]
|
| 27 |
+
TRAIN_ADJUST = 18 # variables in the adjustment set (tables of 3-20 variables)
|
| 28 |
+
TRAIN_LEVELS = (0.02, 0.98) # treatment values were asked about between these quantiles
|
| 29 |
+
MIN_LEVELS = 20 # distinct treatment values below which it counts as discrete
|
| 30 |
+
CURVE_LEVELS = (0.1, 0.25, 0.5, 0.75, 0.9) # default dose-response values: these quantiles
|
| 31 |
+
CONTRAST_LEVELS = (0.25, 0.75) # default contrast: from the first to the second
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@dataclass(repr=False)
|
| 35 |
+
class EffectResult:
|
| 36 |
+
"""Result of `effect`, in the outcome's units throughout.
|
| 37 |
+
|
| 38 |
+
The contrast: `estimate` is E[Y | do(T = b)] - E[Y | do(T = a)] for (a, b) = `contrast`,
|
| 39 |
+
with its 90% `interval` and 50% `interval50`. The dose-response curve: for each treatment
|
| 40 |
+
value in `values`, the effect of moving the treatment from `reference` to it
|
| 41 |
+
(`curve[k]` holds the QUANTILES of that effect; 0 at the reference), pointwise intervals.
|
| 42 |
+
|
| 43 |
+
`adjustment` is the set the graph says to adjust for (the optimal one), the only
|
| 44 |
+
columns besides the treatment and outcome the model reads. `zero_by_graph` means the graph
|
| 45 |
+
has no directed path from the treatment to the outcome, so every effect is exactly 0,
|
| 46 |
+
whatever their association. `n_rows` is the rows behind each estimate (tables over
|
| 47 |
+
TRAIN_N[1] rows are split into `n_subsets` subsets of that many and the quantiles
|
| 48 |
+
averaged, so intervals are those of TRAIN_N[1] rows: conservative)."""
|
| 49 |
+
treatment: str
|
| 50 |
+
outcome: str
|
| 51 |
+
adjustment: list
|
| 52 |
+
zero_by_graph: bool
|
| 53 |
+
contrast: tuple
|
| 54 |
+
contrast_quantiles: np.ndarray # (len(QUANTILES),)
|
| 55 |
+
reference: float
|
| 56 |
+
values: np.ndarray # (K,)
|
| 57 |
+
curve: np.ndarray # (K, len(QUANTILES))
|
| 58 |
+
n_rows: int
|
| 59 |
+
n_subsets: int
|
| 60 |
+
|
| 61 |
+
@property
|
| 62 |
+
def estimate(self):
|
| 63 |
+
return float(self.contrast_quantiles[MID])
|
| 64 |
+
|
| 65 |
+
@property
|
| 66 |
+
def interval(self):
|
| 67 |
+
lo, hi = (QUANTILES.index(p) for p in INTERVALS["outer"])
|
| 68 |
+
return float(self.contrast_quantiles[lo]), float(self.contrast_quantiles[hi])
|
| 69 |
+
|
| 70 |
+
@property
|
| 71 |
+
def interval50(self):
|
| 72 |
+
lo, hi = (QUANTILES.index(p) for p in INTERVALS["inner"])
|
| 73 |
+
return float(self.contrast_quantiles[lo]), float(self.contrast_quantiles[hi])
|
| 74 |
+
|
| 75 |
+
def to_frame(self):
|
| 76 |
+
"""pandas DataFrame of the curve: value, effect (from the reference), and the 90% and
|
| 77 |
+
50% interval bounds."""
|
| 78 |
+
import pandas as pd
|
| 79 |
+
o, i = ([QUANTILES.index(p) for p in INTERVALS[k]] for k in ("outer", "inner"))
|
| 80 |
+
c = self.curve
|
| 81 |
+
return pd.DataFrame({self.treatment: self.values, "effect": c[:, MID],
|
| 82 |
+
"lo90": c[:, o[0]], "lo50": c[:, i[0]], "hi50": c[:, i[1]], "hi90": c[:, o[1]]})
|
| 83 |
+
|
| 84 |
+
def __repr__(self):
|
| 85 |
+
g = lambda x: f"{x:.4g}"
|
| 86 |
+
adj = ", ".join(self.adjustment) if self.adjustment else "nothing"
|
| 87 |
+
rows = f"{self.n_rows} rows" + (f" x {self.n_subsets} subsets" if self.n_subsets > 1 else "")
|
| 88 |
+
head = f"Effect of {self.treatment} on {self.outcome} ({rows}; adjusted for {adj})"
|
| 89 |
+
if self.zero_by_graph:
|
| 90 |
+
return head + f"\n 0: the graph has no directed path from {self.treatment} to {self.outcome}"
|
| 91 |
+
(lo, hi), (lo50, hi50) = self.interval, self.interval50
|
| 92 |
+
a, b = self.contrast
|
| 93 |
+
lines = [head, f" {self.treatment} {g(a)} -> {g(b)}: {self.estimate:+.4g} "
|
| 94 |
+
f"90% [{g(lo)}, {g(hi)}] 50% [{g(lo50)}, {g(hi50)}]",
|
| 95 |
+
f" dose-response, from {self.treatment} = {g(self.reference)}:"]
|
| 96 |
+
o = [QUANTILES.index(p) for p in INTERVALS["outer"]]
|
| 97 |
+
w = max(len(g(v)) for v in self.values)
|
| 98 |
+
lines += [f" {g(v):>{w}} {q[MID]:+.4g} 90% [{g(q[o[0]])}, {g(q[o[1]])}]"
|
| 99 |
+
for v, q in zip(self.values, self.curve)]
|
| 100 |
+
return "\n".join(lines)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _table(data, names):
|
| 104 |
+
"""(n, d) float64 values and column names from a DataFrame or an array."""
|
| 105 |
+
if hasattr(data, "columns") and hasattr(data, "to_numpy"):
|
| 106 |
+
names = list(map(str, data.columns)) if names is None else list(names)
|
| 107 |
+
data = data.to_numpy(dtype=np.float64, na_value=np.nan)
|
| 108 |
+
X = np.asarray(data, dtype=np.float64)
|
| 109 |
+
if X.ndim != 2 or X.shape[1] < 2:
|
| 110 |
+
raise ValueError(f"expected an (n, d) table with d >= 2, got shape {X.shape}")
|
| 111 |
+
names = [f"X{k + 1}" for k in range(X.shape[1])] if names is None else list(map(str, names))
|
| 112 |
+
if len(names) != X.shape[1] or len(set(names)) != len(names):
|
| 113 |
+
raise ValueError(f"need {X.shape[1]} distinct column names; got {names}")
|
| 114 |
+
return X, names
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _adjacency(graph, names):
|
| 118 |
+
"""(d, d) 0/1 adjacency in the table's column order, from any accepted graph form, and the
|
| 119 |
+
relations of a discover() result that the DAG cannot express: [(a, b, kind)]."""
|
| 120 |
+
d, index = len(names), {name: k for k, name in enumerate(names)}
|
| 121 |
+
|
| 122 |
+
def reorder(A, graph_names):
|
| 123 |
+
graph_names = list(map(str, graph_names))
|
| 124 |
+
if sorted(graph_names) != sorted(names):
|
| 125 |
+
raise ValueError(f"the graph's variables {graph_names} are not the table's columns {names}")
|
| 126 |
+
p = [graph_names.index(name) for name in names]
|
| 127 |
+
return np.asarray(A)[np.ix_(p, p)]
|
| 128 |
+
|
| 129 |
+
other = []
|
| 130 |
+
if hasattr(graph, "directed") and hasattr(graph, "names"): # axiom's CausalGraph
|
| 131 |
+
A = reorder(graph.directed, graph.names)
|
| 132 |
+
for kind in ("undirected", "confounded"):
|
| 133 |
+
M = getattr(graph, kind, None)
|
| 134 |
+
if M is not None:
|
| 135 |
+
M = reorder(M, graph.names)
|
| 136 |
+
other += [(names[i], names[j], kind) for i, j in zip(*np.nonzero(np.triu(M, 1)))]
|
| 137 |
+
elif hasattr(graph, "columns") and hasattr(graph, "index"): # adjacency DataFrame
|
| 138 |
+
if list(map(str, graph.index)) != list(map(str, graph.columns)):
|
| 139 |
+
raise ValueError("an adjacency DataFrame needs the same variables, in the same order, as index and columns")
|
| 140 |
+
A = reorder(graph.to_numpy(), graph.columns)
|
| 141 |
+
elif isinstance(graph, (list, tuple)) and all(
|
| 142 |
+
isinstance(e, (list, tuple)) and len(e) == 2 and all(isinstance(v, str) for v in e) for e in graph):
|
| 143 |
+
A = np.zeros((d, d), dtype=np.int64) # edge list: (cause, effect) names
|
| 144 |
+
for a, b in graph:
|
| 145 |
+
for v in (a, b):
|
| 146 |
+
if v not in index:
|
| 147 |
+
raise ValueError(f"edge ({a!r}, {b!r}): {v!r} is not a column; columns are {names}")
|
| 148 |
+
A[index[a], index[b]] = 1
|
| 149 |
+
else:
|
| 150 |
+
A = np.asarray(graph)
|
| 151 |
+
if A.shape != (d, d):
|
| 152 |
+
raise ValueError(f"a {d}-column table needs a ({d}, {d}) adjacency matrix; got shape {A.shape}")
|
| 153 |
+
A = (np.asarray(A, dtype=float) != 0).astype(np.int64)
|
| 154 |
+
if np.any(np.diag(A)):
|
| 155 |
+
raise ValueError("the graph has a self-loop")
|
| 156 |
+
if not is_dag(A):
|
| 157 |
+
raise ValueError("the graph has a directed cycle; the effect model needs a DAG")
|
| 158 |
+
return A, other
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _column(v, names, what):
|
| 162 |
+
if isinstance(v, (int, np.integer)) and not isinstance(v, bool):
|
| 163 |
+
if not 0 <= v < len(names):
|
| 164 |
+
raise ValueError(f"{what} index {v} is out of range for {len(names)} columns")
|
| 165 |
+
return int(v)
|
| 166 |
+
if str(v) not in names:
|
| 167 |
+
raise ValueError(f"{what} {v!r} is not a column; columns are {names}")
|
| 168 |
+
return names.index(str(v))
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def effect(model, data, graph, treatment, outcome, values=None, reference=None, contrast=None, names=None,
|
| 172 |
+
extrapolate=False, n_subsets=8, seed=0):
|
| 173 |
+
"""The causal effect of `treatment` on `outcome` (column names, or indices), from a
|
| 174 |
+
table and its causal graph (module docstring), in the outcome's units.
|
| 175 |
+
|
| 176 |
+
values: treatment values for the dose-response curve (default: its 10/25/50/75/90%
|
| 177 |
+
quantiles); reference: the value the curve starts from (default: the median);
|
| 178 |
+
contrast: (a, b), the headline effect of moving the treatment from a to b (default:
|
| 179 |
+
its 25% and 75% quantiles). All in the treatment's units.
|
| 180 |
+
extrapolate: allow treatment values outside its 2-98% quantiles (warned instead of
|
| 181 |
+
refused): the model was never asked about them, and the data hardly has them.
|
| 182 |
+
|
| 183 |
+
Refused: missing values in the treatment, the outcome or the adjustment set; a constant
|
| 184 |
+
treatment or outcome; a discrete one (fewer than 20 distinct values: version 0.0.x is for
|
| 185 |
+
continuous treatments). Warned: fewer rows than the training range, an adjustment set
|
| 186 |
+
larger than in training, and relations of a discover() result that a DAG cannot express
|
| 187 |
+
(undirected, confounded) near the treatment or outcome, which are ignored; and an exact 0
|
| 188 |
+
from a discover() result (no directed path), which one wrong edge can cause."""
|
| 189 |
+
X, names = _table(data, names)
|
| 190 |
+
A, other = _adjacency(graph, names)
|
| 191 |
+
t, y = _column(treatment, names, "treatment"), _column(outcome, names, "outcome")
|
| 192 |
+
if t == y:
|
| 193 |
+
raise ValueError("treatment and outcome are the same column")
|
| 194 |
+
W = optimal_adjustment(A, t, y)
|
| 195 |
+
used = [t, y] + W
|
| 196 |
+
if not np.isfinite(X[:, used]).all():
|
| 197 |
+
bad = [names[c] for c in used if not np.isfinite(X[:, c]).all()]
|
| 198 |
+
raise ValueError(f"missing or infinite values in {bad}; the effect model needs complete columns "
|
| 199 |
+
f"for the treatment, the outcome and the adjustment set")
|
| 200 |
+
T, Y = X[:, t], X[:, y]
|
| 201 |
+
for c, what in ((t, "treatment"), (y, "outcome")):
|
| 202 |
+
if np.ptp(X[:, c]) == 0:
|
| 203 |
+
raise ValueError(f"the {what} {names[c]!r} is constant")
|
| 204 |
+
if len(np.unique(T)) < MIN_LEVELS:
|
| 205 |
+
raise ValueError(f"the treatment {names[t]!r} has {len(np.unique(T))} distinct values; version 0.0.x "
|
| 206 |
+
f"estimates effects of continuous treatments only (at least {MIN_LEVELS} values)")
|
| 207 |
+
|
| 208 |
+
near = {t, y} | set(descendants(A.T, t)) | set(descendants(A.T, y))
|
| 209 |
+
ignored = [(a, b, k) for a, b, k in other if names.index(a) in near or names.index(b) in near]
|
| 210 |
+
if ignored:
|
| 211 |
+
warnings.warn(f"the graph also has {len(ignored)} relation(s) a DAG cannot express near the treatment "
|
| 212 |
+
f"or outcome, ignored here (the effect assumes no hidden confounders): "
|
| 213 |
+
+ ", ".join(f"{a} {'--' if k == 'undirected' else '<->'} {b}" for a, b, k in ignored),
|
| 214 |
+
stacklevel=3)
|
| 215 |
+
n = len(X)
|
| 216 |
+
if n < TRAIN_N[0]:
|
| 217 |
+
warnings.warn(f"{n} rows is below the training range {TRAIN_N}", stacklevel=3)
|
| 218 |
+
if len(W) > TRAIN_ADJUST:
|
| 219 |
+
warnings.warn(f"the adjustment set has {len(W)} variables, more than in training (up to {TRAIN_ADJUST})",
|
| 220 |
+
stacklevel=3)
|
| 221 |
+
|
| 222 |
+
q = lambda p: float(np.quantile(T, p))
|
| 223 |
+
values = np.array([q(p) for p in CURVE_LEVELS] if values is None else values, dtype=np.float64).ravel()
|
| 224 |
+
reference = q(0.5) if reference is None else float(reference)
|
| 225 |
+
contrast = (q(CONTRAST_LEVELS[0]), q(CONTRAST_LEVELS[1])) if contrast is None else tuple(map(float, contrast))
|
| 226 |
+
if len(contrast) != 2:
|
| 227 |
+
raise ValueError(f"contrast is a pair (a, b) of treatment values; got {contrast}")
|
| 228 |
+
lo, hi = q(TRAIN_LEVELS[0]), q(TRAIN_LEVELS[1])
|
| 229 |
+
outside = sorted({v for v in [*values, reference, *contrast] if not lo <= v <= hi})
|
| 230 |
+
if outside:
|
| 231 |
+
msg = (f"treatment values {[float(f'{v:.4g}') for v in outside]} are outside the 2-98% quantiles of "
|
| 232 |
+
f"{names[t]!r}, [{lo:.4g}, {hi:.4g}], where the model was trained and the data has support")
|
| 233 |
+
if not extrapolate:
|
| 234 |
+
raise ValueError(msg + "; pass extrapolate=True to estimate them anyway")
|
| 235 |
+
warnings.warn(msg, stacklevel=3)
|
| 236 |
+
|
| 237 |
+
pairs = [(reference, v) for v in values] + [contrast]
|
| 238 |
+
rng = np.random.default_rng(seed)
|
| 239 |
+
rows = [np.arange(n)] if n <= TRAIN_N[1] else \
|
| 240 |
+
[np.sort(rng.choice(n, TRAIN_N[1], replace=False)) for _ in range(n_subsets)]
|
| 241 |
+
out = []
|
| 242 |
+
for r in rows: # each subset standardized on its own, as in training
|
| 243 |
+
Z = np.zeros((len(r), len(names))) # the model reads only the used columns
|
| 244 |
+
U = X[np.ix_(r, used)]
|
| 245 |
+
mu, sd = U.mean(0), U.std(0)
|
| 246 |
+
if np.any(sd[:2] == 0):
|
| 247 |
+
raise ValueError("a subset of the rows has a constant treatment or outcome; use fewer, larger subsets")
|
| 248 |
+
Z[:, used] = (U - mu) / np.where(sd > 0, sd, 1.0)
|
| 249 |
+
z = lambda v: (v - mu[0]) / sd[0]
|
| 250 |
+
qz = model.effects(Z, A, t, y, [(z(a), z(b)) for a, b in pairs]) # the full graph: it decides W
|
| 251 |
+
out.append(qz.astype(np.float64) * sd[1]) # effects are differences: no shift, only scale
|
| 252 |
+
Q = np.mean(out, 0)
|
| 253 |
+
zero = y not in descendants(A, t)
|
| 254 |
+
if zero and _discovered(graph):
|
| 255 |
+
warnings.warn(_zero_warning(graph, names[t], names[y]), stacklevel=3)
|
| 256 |
+
return EffectResult(names[t], names[y], [names[c] for c in W], zero,
|
| 257 |
+
contrast, Q[-1], reference, values, Q[:-1], len(rows[0]), len(rows))
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _discovered(graph):
|
| 261 |
+
"""Whether the graph is a discover() result (axiom's CausalGraph), read by its attributes."""
|
| 262 |
+
return hasattr(graph, "directed") and hasattr(graph, "names")
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _zero_warning(graph, t, y):
|
| 266 |
+
"""Why an exact 0 from a discovered graph deserves a second look, with what the graph says
|
| 267 |
+
about the pair itself when it can (CausalGraph.relation)."""
|
| 268 |
+
msg = (f"the discovered graph has no directed path from {t} to {y}, so the effect is exactly 0. That "
|
| 269 |
+
f"holds only if the graph is right, and discovered edges are uncertain: one missing or "
|
| 270 |
+
f"reversed edge can cut every path")
|
| 271 |
+
relation = getattr(graph, "relation", None)
|
| 272 |
+
if callable(relation):
|
| 273 |
+
try:
|
| 274 |
+
probs = relation(t, y).probs
|
| 275 |
+
msg += f" ({t} vs {y} directly: " + ", ".join(f"{k} {p:.2f}" for k, p in probs.items()) + ")"
|
| 276 |
+
except (KeyError, ValueError, AttributeError):
|
| 277 |
+
pass
|
| 278 |
+
return msg + ". Check the graph's edges (print it), or pass a graph you trust"
|
src/axiom_effect/model.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AxiomEffect: causal effect estimation given a causal graph, built as an in-context
|
| 3 |
+
g-formula with a doubly robust correction (design-effect.md, "Architecture v2").
|
| 4 |
+
|
| 5 |
+
Given a table, its DAG and a treatment t / outcome y, the dose-response E[Y | do(T = v)] is,
|
| 6 |
+
by the g-formula, the average over the rows of E[Y | T = v, W = w_r], with W the optimal
|
| 7 |
+
adjustment set. The model follows that recipe:
|
| 8 |
+
|
| 9 |
+
1. The graph decides the inputs: each row is reduced to (W, T, Y), W = O(t, y)
|
| 10 |
+
(axiom_effect.graph.optimal_adjustment). Mediators and other descendants of T, which would bias
|
| 11 |
+
the answer, are never seen.
|
| 12 |
+
2. An in-context regressor (as in TabPFN): the observed rows are the context; query rows
|
| 13 |
+
carry a row's W with T set to a query value and Y unknown, attend to the context, and
|
| 14 |
+
a head predicts E[Y | T = v, W = w_r] for each.
|
| 15 |
+
3. The average over the rows is computed exactly.
|
| 16 |
+
4. With doubly_robust, a correction from the observed rows whose treatment is near v
|
| 17 |
+
(Kennedy et al. 2017, for continuous treatments): their residuals Y_i - E[Y | T_i, W_i],
|
| 18 |
+
weighted by f(T_i) / pi(T_i | W_i), the treatment's marginal over its conditional
|
| 19 |
+
density, kernel-averaged around v. The residuals and densities come from two more query
|
| 20 |
+
rows per observed row (its own T, and T unknown), each blind to its own context row. If
|
| 21 |
+
the outcome regression is off, the correction pulls the estimate back to the data. A
|
| 22 |
+
learned gate per value scales the correction by how many rows effectively support v.
|
| 23 |
+
With positivity, the gate also sees how many rows could plausibly have received v
|
| 24 |
+
(their predicted treatment density at v) and the predicted overlap of the table: where
|
| 25 |
+
the parents nearly fix the treatment, the average at v is mostly extrapolation, which
|
| 26 |
+
the correction, built from the few rows near v, cannot fix (design-effect.md, run 3).
|
| 27 |
+
|
| 28 |
+
Effects are differences of the dose-response, so effect(a -> b) = -effect(b -> a) and the
|
| 29 |
+
median of a -> a is 0. Only the uncertainty is learned on top: quantiles (QUANTILES) of each
|
| 30 |
+
effect, from the spread of the per-row predictions, the correction, a summary of the context
|
| 31 |
+
and the sample size; they never cross. A split-conformal calibration (calibrate_effect.py),
|
| 32 |
+
stored in the config, then scales the 90% and 50% intervals around the median.
|
| 33 |
+
|
| 34 |
+
from axiom_effect import AxiomEffect
|
| 35 |
+
model = AxiomEffect.from_pretrained("path/or/hub-repo") # trained with train_effect.py
|
| 36 |
+
q = model.effects(X, A, t, y, pairs=[(x25, x75)]) # (1, len(QUANTILES))
|
| 37 |
+
|
| 38 |
+
Everything is on the table's standardized scale.
|
| 39 |
+
"""
|
| 40 |
+
import math
|
| 41 |
+
import os
|
| 42 |
+
import warnings
|
| 43 |
+
from importlib.metadata import PackageNotFoundError, version
|
| 44 |
+
from typing import NamedTuple
|
| 45 |
+
|
| 46 |
+
import numpy as np
|
| 47 |
+
import torch
|
| 48 |
+
import torch.nn as nn
|
| 49 |
+
import torch.nn.functional as F
|
| 50 |
+
from huggingface_hub import PyTorchModelHubMixin
|
| 51 |
+
from huggingface_hub.errors import RevisionNotFoundError
|
| 52 |
+
from torch.utils.checkpoint import checkpoint
|
| 53 |
+
|
| 54 |
+
from .blocks import Attention, FeedForward, eval_mode, mlp
|
| 55 |
+
from .graph import descendants, is_dag, optimal_adjustment
|
| 56 |
+
|
| 57 |
+
QUANTILES = (0.05, 0.25, 0.5, 0.75, 0.95) # the outer two make a 90% interval
|
| 58 |
+
MID = QUANTILES.index(0.5)
|
| 59 |
+
INTERVALS = {"outer": (0.05, 0.95), "inner": (0.25, 0.75)} # 90% and 50%, each calibrated on its own
|
| 60 |
+
N_REF = 2048 # log(n) / log(N_REF): the sample-size input
|
| 61 |
+
CLIP = 8.0 # inputs clipped to +-CLIP sd, as Axiom's preprocess
|
| 62 |
+
W_ROLE, T_ROLE, Y_ROLE = 0, 1, 2 # what a cell of a row is
|
| 63 |
+
MAX_WEIGHT = 10.0 # the correction's density-ratio weights are clipped here
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def ranks(values, reference):
|
| 67 |
+
"""Each value's rank among the observed `reference` values of its column, in [-1, 1]
|
| 68 |
+
(ties count half). values (B, C, R), reference (B, C, n)."""
|
| 69 |
+
s = reference.sort(-1).values.contiguous()
|
| 70 |
+
lo = torch.searchsorted(s, values.contiguous(), right=False)
|
| 71 |
+
hi = torch.searchsorted(s, values.contiguous(), right=True)
|
| 72 |
+
return (lo + hi).float() / reference.shape[-1] - 1
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def check_calibration(cal):
|
| 76 |
+
"""A calibration (calibrate_effect.py): {"n": sample sizes, increasing, and per interval
|
| 77 |
+
in INTERVALS, one widening factor > 0 per sample size}."""
|
| 78 |
+
n = np.asarray(cal["n"], dtype=float)
|
| 79 |
+
if n.ndim != 1 or len(n) == 0 or np.any(np.diff(n) <= 0) or np.any(n <= 0):
|
| 80 |
+
raise ValueError(f"calibration n must be increasing positive sample sizes; got {cal['n']}")
|
| 81 |
+
for name in INTERVALS:
|
| 82 |
+
f = np.asarray(cal[name], dtype=float)
|
| 83 |
+
if f.shape != n.shape or np.any(f <= 0):
|
| 84 |
+
raise ValueError(f"calibration {name!r} needs one positive factor per n; got {cal[name]}")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def calibration_factors(cal, n):
|
| 88 |
+
"""The widening factor of each interval in INTERVALS for a table of n rows: interpolated
|
| 89 |
+
linearly in log n between the calibrated sample sizes, constant beyond them."""
|
| 90 |
+
logn = np.log(np.asarray(cal["n"], dtype=float))
|
| 91 |
+
return {name: float(np.interp(np.log(n), logn, cal[name])) for name in INTERVALS}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def calibrate(q, factors):
|
| 95 |
+
"""Quantiles q (..., len(QUANTILES)) with each interval's distance from the median scaled
|
| 96 |
+
by its factor, the 90% interval's (outer quantiles) and the 50% interval's (inner) on both
|
| 97 |
+
sides alike, so antisymmetry holds; the inner ones never pass the outer ones."""
|
| 98 |
+
med = q[..., MID:MID + 1]
|
| 99 |
+
dev = q - med
|
| 100 |
+
scale = np.ones(len(QUANTILES))
|
| 101 |
+
for name, (lo, hi) in INTERVALS.items():
|
| 102 |
+
scale[[QUANTILES.index(lo), QUANTILES.index(hi)]] = factors[name]
|
| 103 |
+
out = dev * scale
|
| 104 |
+
inner, outer = [QUANTILES.index(p) for p in INTERVALS["inner"]], [QUANTILES.index(p) for p in INTERVALS["outer"]]
|
| 105 |
+
out[..., inner[0]] = np.maximum(out[..., inner[0]], out[..., outer[0]])
|
| 106 |
+
out[..., inner[1]] = np.minimum(out[..., inner[1]], out[..., outer[1]])
|
| 107 |
+
return (med + out).astype(q.dtype)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class Rows(NamedTuple):
|
| 111 |
+
"""The model's predictions for one batch of tables and K treatment values."""
|
| 112 |
+
mu: torch.Tensor # (B, K, R) E[Y | T = values[k], W] for each query row
|
| 113 |
+
n_avg: int # the first n_avg query rows are observed rows: the g-formula averages them
|
| 114 |
+
tokens: torch.Tensor # (B, K, E) their final representations, averaged
|
| 115 |
+
context: torch.Tensor # (B, E) a summary of the context rows
|
| 116 |
+
value_rank: torch.Tensor # (B, K) each treatment value's rank among the observed T
|
| 117 |
+
dose: torch.Tensor # (B, K) E[Y | do(T = values[k])]: the average, plus the gated correction
|
| 118 |
+
correction: torch.Tensor # (B, K) the doubly robust correction before the gate (0 without)
|
| 119 |
+
gate: torch.Tensor # (B, K) how much of it is used
|
| 120 |
+
support: torch.Tensor # (B, K) log(1 + effective number of observed rows near the value)
|
| 121 |
+
positivity: torch.Tensor # (B, K) effective share of rows that could receive the value (1 without)
|
| 122 |
+
overlap: torch.Tensor # (B,) predicted R² of the treatment given W (0 without)
|
| 123 |
+
own_mu: torch.Tensor # (B, r) E[Y | T_i, W_i] for the first r observed rows, blind to row i
|
| 124 |
+
own_mean: torch.Tensor # (B, r) the treatment's predicted mean given W_i, blind to row i
|
| 125 |
+
own_logsd: torch.Tensor # (B, r) and its log standard deviation
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class CrossBlock(nn.Module):
|
| 129 |
+
"""Pre-norm: queries attend to the context rows (minus any `blocked` (Q, n) pairs), then a
|
| 130 |
+
feed-forward. Queries do not attend to each other, so each query's answer depends on the
|
| 131 |
+
context only."""
|
| 132 |
+
def __init__(self, E, H):
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.norm_q, self.norm_ctx = nn.LayerNorm(E), nn.LayerNorm(E)
|
| 135 |
+
self.attn = nn.MultiheadAttention(E, H, batch_first=True)
|
| 136 |
+
self.ff = FeedForward(E)
|
| 137 |
+
|
| 138 |
+
def forward(self, q, ctx, blocked=None): # q (B, Q, E), ctx (B, n, E)
|
| 139 |
+
c = self.norm_ctx(ctx)
|
| 140 |
+
return self.ff(q + self.attn(self.norm_q(q), c, c, attn_mask=blocked, need_weights=False)[0])
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def release_tag():
|
| 144 |
+
"""The Hub tag of the weights released with this package version ("v0.0.1"), or None
|
| 145 |
+
when the package is not installed (running from source without metadata)."""
|
| 146 |
+
try:
|
| 147 |
+
return f"v{version('axiom-effect')}"
|
| 148 |
+
except PackageNotFoundError:
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class AxiomEffect(nn.Module, PyTorchModelHubMixin, library_name="axiom-effect", repo_url=None,
|
| 153 |
+
tags=["causal-inference", "effect-estimation", "tabular"]):
|
| 154 |
+
"""Hugging Face: `save_pretrained(dir)` / `push_to_hub(repo)` write model.safetensors and
|
| 155 |
+
config.json (the __init__ arguments, the calibration included); `from_pretrained` rebuilds
|
| 156 |
+
it. From a Hub repo it loads the weights released with this package version (the repo's
|
| 157 |
+
`v<version>` tag) unless `revision` says otherwise."""
|
| 158 |
+
@classmethod
|
| 159 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *, revision=None, strict=True, **kwargs):
|
| 160 |
+
"""As PyTorchModelHubMixin.from_pretrained, with Axiom's two safeguards: a Hub repo
|
| 161 |
+
defaults to the weights tagged with this package's version (falling back to main,
|
| 162 |
+
with a warning, if the tag is missing), and the weights load strictly."""
|
| 163 |
+
path = str(pretrained_model_name_or_path)
|
| 164 |
+
tag = release_tag()
|
| 165 |
+
if revision is None and tag is not None and not os.path.isdir(path):
|
| 166 |
+
try:
|
| 167 |
+
return super().from_pretrained(path, revision=tag, strict=strict, **kwargs)
|
| 168 |
+
except RevisionNotFoundError:
|
| 169 |
+
warnings.warn(f"{path} has no {tag} tag; loading its latest weights (main), which may "
|
| 170 |
+
f"not match this version of the code", stacklevel=2)
|
| 171 |
+
return super().from_pretrained(path, revision=revision, strict=strict, **kwargs)
|
| 172 |
+
|
| 173 |
+
def __init__(self, E=128, H=8, row_layers=2, context_layers=4, query_layers=3, inducing=64,
|
| 174 |
+
doubly_robust=False, positivity=False, calibration=None):
|
| 175 |
+
super().__init__()
|
| 176 |
+
self.config = dict(architecture="in-context g-formula", E=E, H=H, row_layers=row_layers,
|
| 177 |
+
context_layers=context_layers, query_layers=query_layers, inducing=inducing,
|
| 178 |
+
doubly_robust=doubly_robust, positivity=positivity)
|
| 179 |
+
if calibration is not None:
|
| 180 |
+
check_calibration(calibration)
|
| 181 |
+
self.config["calibration"] = calibration
|
| 182 |
+
if positivity and not doubly_robust:
|
| 183 |
+
raise ValueError("positivity inputs belong to the doubly robust gate: needs doubly_robust=True")
|
| 184 |
+
extra = 2 if positivity else 0 # positivity, overlap
|
| 185 |
+
# A row: its cells (value, rank) with their role (W, T or Y), attended across, pooled.
|
| 186 |
+
self.cell = mlp(2, E, E)
|
| 187 |
+
self.role = nn.Embedding(3, E)
|
| 188 |
+
self.unknown = nn.Parameter(torch.zeros(E)) # a cell the query asks about
|
| 189 |
+
self.row_attn = nn.ModuleList(Attention(E, H) for _ in range(row_layers))
|
| 190 |
+
self.row_ff = nn.ModuleList(FeedForward(E) for _ in range(row_layers))
|
| 191 |
+
self.row_out = mlp(E, E, E)
|
| 192 |
+
# The context rows attend to each other through inducing points.
|
| 193 |
+
self.context_attn = nn.ModuleList(Attention(E, H, inducing) for _ in range(context_layers))
|
| 194 |
+
self.context_ff = nn.ModuleList(FeedForward(E) for _ in range(context_layers))
|
| 195 |
+
# Query rows -> E[Y | T = v, W = w] (and, doubly robust, the treatment's density given W).
|
| 196 |
+
self.query_blocks = nn.ModuleList(CrossBlock(E, H) for _ in range(query_layers))
|
| 197 |
+
self.mu = nn.Linear(E, 1)
|
| 198 |
+
self.treatment = nn.Linear(E, 2) if doubly_robust else None # mean, log sd of T given W
|
| 199 |
+
self.gate = mlp(4 + extra, E, 1) if doubly_robust else None # support, rank, size, correction (+ extra)
|
| 200 |
+
# The effect's quantiles around the estimate, from: estimate, spread of the per-row
|
| 201 |
+
# differences, the query tokens' difference and sum, context, size, a, b, b - a with
|
| 202 |
+
# the ranks of a and b, (doubly robust) the corrections' difference, gates and supports,
|
| 203 |
+
# and (positivity) both values' positivity and the overlap.
|
| 204 |
+
self.spread = mlp(2 + 3 * E + 1 + 5 + (5 if doubly_robust else 0) + (3 if positivity else 0), E,
|
| 205 |
+
len(QUANTILES) - 1)
|
| 206 |
+
# In training, recompute each layer's activations in the backward pass instead of
|
| 207 |
+
# storing them: much less memory, about 30% more compute (train_effect.py --recompute).
|
| 208 |
+
self.recompute = False
|
| 209 |
+
|
| 210 |
+
def _run(self, fn, *args):
|
| 211 |
+
if self.recompute and self.training and torch.is_grad_enabled():
|
| 212 |
+
return checkpoint(fn, *args, use_reentrant=False)
|
| 213 |
+
return fn(*args)
|
| 214 |
+
|
| 215 |
+
def _rows(self, w, t, y, w_mask, refs):
|
| 216 |
+
"""Row tokens (B, R, E) from a row's W values w (B, R, P) (w_mask (B, P): which of the
|
| 217 |
+
P slots are real), its treatment t and outcome y (B, R) (NaN = unknown), with ranks
|
| 218 |
+
relative to the observed columns refs = (ctx_w, ctx_t, ctx_y)."""
|
| 219 |
+
B, R, P = w.shape
|
| 220 |
+
v = torch.cat([w, t[..., None], y[..., None]], -1) # (B, R, P + 2)
|
| 221 |
+
ref = torch.cat([refs[0], refs[1][..., None], refs[2][..., None]], -1) # (B, n, P + 2)
|
| 222 |
+
unknown = torch.isnan(v)
|
| 223 |
+
v = v.nan_to_num(0.0).clamp(-CLIP, CLIP)
|
| 224 |
+
r = ranks(v.transpose(1, 2), ref.clamp(-CLIP, CLIP).transpose(1, 2)).transpose(1, 2)
|
| 225 |
+
role = torch.tensor([W_ROLE] * P + [T_ROLE, Y_ROLE], device=w.device)
|
| 226 |
+
e = torch.where(unknown[..., None], self.unknown, self.cell(torch.stack([v, r], -1))) + self.role(role)
|
| 227 |
+
pad = torch.cat([~w_mask, torch.zeros(B, 2, dtype=torch.bool, device=w.device)], -1)
|
| 228 |
+
pad = pad[:, None].expand(B, R, P + 2).reshape(B * R, P + 2)
|
| 229 |
+
e = e.reshape(B * R, P + 2, -1)
|
| 230 |
+
for attn, ff in zip(self.row_attn, self.row_ff):
|
| 231 |
+
e = self._run(lambda e, pad, attn=attn, ff=ff: ff(attn(e, pad)), e, pad)
|
| 232 |
+
keep = (~pad).float()[..., None]
|
| 233 |
+
return self.row_out((e * keep).sum(1) / keep.sum(1)).reshape(B, R, -1)
|
| 234 |
+
|
| 235 |
+
def _decode(self, q, ctx, blocked=None):
|
| 236 |
+
for blk in self.query_blocks:
|
| 237 |
+
q = self._run(blk, q, ctx, blocked)
|
| 238 |
+
return q
|
| 239 |
+
|
| 240 |
+
def forward(self, ctx_w, ctx_t, ctx_y, w_mask, query_w, values, n_avg=None, own=None, chunk=None):
|
| 241 |
+
"""Every prediction for a batch. ctx_w (B, n, P), ctx_t and ctx_y (B, n): the observed
|
| 242 |
+
rows, reduced to (W, T, Y); w_mask (B, P); query_w (B, K, R, P): the W of R query rows
|
| 243 |
+
for each of K treatment values, values (B, K), the first n_avg of them observed rows
|
| 244 |
+
(default: all); own: how many of the first observed rows give the doubly robust
|
| 245 |
+
correction its residuals and densities (default: all). Queries go `chunk` rows at a
|
| 246 |
+
time (default: all at once)."""
|
| 247 |
+
B, K, R, P = query_w.shape
|
| 248 |
+
n, dev = ctx_t.shape[1], ctx_t.device
|
| 249 |
+
n_avg = R if n_avg is None else n_avg
|
| 250 |
+
refs = (ctx_w, ctx_t, ctx_y)
|
| 251 |
+
ctx = self._rows(ctx_w, ctx_t, ctx_y, w_mask, refs)
|
| 252 |
+
for attn, ff in zip(self.context_attn, self.context_ff):
|
| 253 |
+
ctx = self._run(lambda c, attn=attn, ff=ff: ff(attn(c)), ctx)
|
| 254 |
+
|
| 255 |
+
step = chunk or R
|
| 256 |
+
mus, pooled = [], 0.0
|
| 257 |
+
for s in range(0, R, step):
|
| 258 |
+
qw = query_w[:, :, s:s + step]
|
| 259 |
+
r = qw.shape[2]
|
| 260 |
+
q_t = values[..., None].expand(B, K, r).reshape(B, K * r)
|
| 261 |
+
q = self._decode(self._rows(qw.reshape(B, K * r, P), q_t, torch.full_like(q_t, float("nan")),
|
| 262 |
+
w_mask, refs), ctx).reshape(B, K, r, -1)
|
| 263 |
+
mus.append(self.mu(q)[..., 0])
|
| 264 |
+
pooled = pooled + q[:, :, :max(0, min(r, n_avg - s))].sum(2)
|
| 265 |
+
mu = torch.cat(mus, 2)
|
| 266 |
+
|
| 267 |
+
own = n if own is None else min(own, n)
|
| 268 |
+
own_mu, own_mean, own_logsd = [], [], []
|
| 269 |
+
if self.config["doubly_robust"]:
|
| 270 |
+
ostep = chunk or own
|
| 271 |
+
for s in range(0, own, ostep):
|
| 272 |
+
idx = torch.arange(s, min(s + ostep, own), device=dev)
|
| 273 |
+
m = len(idx)
|
| 274 |
+
w_i, t_i = ctx_w[:, idx], ctx_t[:, idx]
|
| 275 |
+
nan = torch.full_like(t_i, float("nan"))
|
| 276 |
+
q = torch.cat([self._rows(w_i, t_i, nan, w_mask, refs), # its own T: its outcome
|
| 277 |
+
self._rows(w_i, nan, nan, w_mask, refs)], 1) # T unknown: T's density
|
| 278 |
+
blocked = torch.zeros(2 * m, n, dtype=torch.bool, device=dev)
|
| 279 |
+
blocked[torch.arange(2 * m, device=dev), idx.repeat(2)] = True # blind to its own row
|
| 280 |
+
q = self._decode(q, ctx, blocked)
|
| 281 |
+
own_mu.append(self.mu(q[:, :m])[..., 0])
|
| 282 |
+
mean, logsd = self.treatment(q[:, m:]).unbind(-1)
|
| 283 |
+
own_mean.append(mean)
|
| 284 |
+
own_logsd.append(logsd.clamp(-5, 3))
|
| 285 |
+
cat = lambda xs: torch.cat(xs, 1) if xs else ctx_t.new_zeros(B, 0)
|
| 286 |
+
own_mu, own_mean, own_logsd = cat(own_mu), cat(own_mean), cat(own_logsd)
|
| 287 |
+
|
| 288 |
+
value_rank = ranks(values.clamp(-CLIP, CLIP)[:, None], ctx_t.clamp(-CLIP, CLIP)[:, None])[:, 0]
|
| 289 |
+
g = mu[..., :n_avg].mean(2)
|
| 290 |
+
if self.config["doubly_robust"]:
|
| 291 |
+
correction, support = self._correction(own_mu, own_mean, own_logsd, ctx_t, ctx_y, values, n)
|
| 292 |
+
size = torch.full_like(g, float(np.log(n) / np.log(N_REF)))
|
| 293 |
+
gate_in = [support, value_rank, size, correction]
|
| 294 |
+
positivity, overlap = self._positivity(own_mean, own_logsd, values)
|
| 295 |
+
if self.config["positivity"]:
|
| 296 |
+
gate_in += [positivity, overlap[:, None].expand_as(g)]
|
| 297 |
+
gate = torch.sigmoid(self.gate(torch.stack(gate_in, -1)))[..., 0]
|
| 298 |
+
else:
|
| 299 |
+
correction = support = torch.zeros_like(g)
|
| 300 |
+
gate, positivity, overlap = torch.ones_like(g), torch.ones_like(g), g.new_zeros(B)
|
| 301 |
+
return Rows(mu, n_avg, pooled / n_avg, ctx.mean(1), value_rank, g + gate * correction, correction,
|
| 302 |
+
gate, support, positivity, overlap, own_mu, own_mean, own_logsd)
|
| 303 |
+
|
| 304 |
+
@staticmethod
|
| 305 |
+
def _positivity(own_mean, own_logsd, values):
|
| 306 |
+
"""Positivity at each value, (B, K): the effective share of the own rows that could
|
| 307 |
+
receive it, (sum_i p_i)² / (r sum_i p_i²) with p_i = pi(v | W_i) the predicted
|
| 308 |
+
treatment density, 1 when every row could equally, 1 / r when one row could. And the
|
| 309 |
+
table's predicted overlap, (B,): 1 - mean_i Var(T | W_i), the R² of the (standardized)
|
| 310 |
+
treatment given W, near 1 where the parents nearly fix it."""
|
| 311 |
+
r = own_mean.shape[1]
|
| 312 |
+
log_p = torch.distributions.Normal(own_mean[:, None], own_logsd.exp()[:, None]).log_prob(
|
| 313 |
+
values.clamp(-CLIP, CLIP)[..., None]) # (B, K, r)
|
| 314 |
+
ess = torch.exp(2 * torch.logsumexp(log_p, -1) - torch.logsumexp(2 * log_p, -1))
|
| 315 |
+
return ess / r, (1 - (2 * own_logsd).exp().mean(-1)).clamp(0, 1)
|
| 316 |
+
|
| 317 |
+
@staticmethod
|
| 318 |
+
def _correction(own_mu, own_mean, own_logsd, ctx_t, ctx_y, values, n):
|
| 319 |
+
"""The doubly robust correction to each value's dose-response, (B, K), and the log of
|
| 320 |
+
1 + the effective number of observed rows behind it. Kernel regression on T of the
|
| 321 |
+
own rows' residuals Y_i - E[Y | T_i, W_i], weighted by f(T_i) / pi(T_i | W_i)
|
| 322 |
+
(clipped at MAX_WEIGHT); f is a kernel density of the observed T, pi the predicted
|
| 323 |
+
conditional density; the bandwidth is Silverman's rule for a standardized variable."""
|
| 324 |
+
r = own_mu.shape[1]
|
| 325 |
+
t_all = ctx_t.clamp(-CLIP, CLIP)
|
| 326 |
+
t_i, resid = t_all[:, :r], ctx_y[:, :r].clamp(-CLIP, CLIP) - own_mu
|
| 327 |
+
h = 1.06 * n ** -0.2
|
| 328 |
+
kern = lambda u: torch.exp(-0.5 * u * u)
|
| 329 |
+
log_f = torch.log(kern((t_i[..., None] - t_all[:, None]) / h).mean(-1) / (h * math.sqrt(2 * math.pi)) + 1e-12)
|
| 330 |
+
log_pi = torch.distributions.Normal(own_mean, own_logsd.exp()).log_prob(t_i)
|
| 331 |
+
weight = (log_f - log_pi).clamp(max=math.log(MAX_WEIGHT)).exp()
|
| 332 |
+
K = kern((t_i[:, None] - values.clamp(-CLIP, CLIP)[..., None]) / h) # (B, K, r)
|
| 333 |
+
Kw = K * weight[:, None]
|
| 334 |
+
correction = (Kw * resid[:, None]).sum(-1) / (K.sum(-1) + 1e-6)
|
| 335 |
+
support = torch.log1p(Kw.sum(-1) ** 2 / (Kw ** 2).sum(-1).clamp(min=1e-12))
|
| 336 |
+
return correction, support
|
| 337 |
+
|
| 338 |
+
def quantiles(self, rows, values, pairs, n):
|
| 339 |
+
"""Quantiles (B, len(pairs), len(QUANTILES)) of the effect of moving the treatment from
|
| 340 |
+
values[:, i] to values[:, j], for each (i, j) in pairs (indices into the K values),
|
| 341 |
+
from `rows` (see forward()) of a table with n rows."""
|
| 342 |
+
i, j = pairs[:, 0], pairs[:, 1]
|
| 343 |
+
size = float(np.log(n) / np.log(N_REF))
|
| 344 |
+
mu = rows.mu[..., :rows.n_avg]
|
| 345 |
+
|
| 346 |
+
def one_way(i, j):
|
| 347 |
+
est = rows.dose[:, j] - rows.dose[:, i] # (B, P)
|
| 348 |
+
a, b = values[:, i], values[:, j]
|
| 349 |
+
feats = [est[..., None], (mu[:, j] - mu[:, i]).std(-1, unbiased=False)[..., None],
|
| 350 |
+
rows.tokens[:, j] - rows.tokens[:, i], rows.tokens[:, j] + rows.tokens[:, i],
|
| 351 |
+
rows.context[:, None].expand(-1, len(i), -1), torch.full_like(est[..., None], size),
|
| 352 |
+
torch.stack([a, b, b - a, rows.value_rank[:, i], rows.value_rank[:, j]], -1)]
|
| 353 |
+
if self.config["doubly_robust"]:
|
| 354 |
+
feats.append(torch.stack([rows.correction[:, j] - rows.correction[:, i], rows.gate[:, i],
|
| 355 |
+
rows.gate[:, j], rows.support[:, i], rows.support[:, j]], -1))
|
| 356 |
+
if self.config["positivity"]:
|
| 357 |
+
feats.append(torch.stack([rows.positivity[:, i], rows.positivity[:, j],
|
| 358 |
+
rows.overlap[:, None].expand_as(est)], -1))
|
| 359 |
+
steps = F.softplus(self.spread(torch.cat(feats, -1)))
|
| 360 |
+
lower = est[..., None] - steps[..., :MID].flip(-1).cumsum(-1).flip(-1)
|
| 361 |
+
upper = est[..., None] + steps[..., MID:].cumsum(-1)
|
| 362 |
+
return torch.cat([lower, est[..., None], upper], -1)
|
| 363 |
+
|
| 364 |
+
# The estimate is antisymmetric already; averaging both directions makes the spread
|
| 365 |
+
# symmetric too: quantile p of a -> b is minus quantile 1 - p of b -> a.
|
| 366 |
+
return (one_way(i, j) - one_way(j, i).flip(-1)) / 2
|
| 367 |
+
|
| 368 |
+
def effect(self, data, graph, treatment, outcome, **kwargs):
|
| 369 |
+
"""The causal effect of `treatment` on `outcome` in a table, given its causal graph, in
|
| 370 |
+
the outcome's units: `axiom_effect.inference.effect(self, ...)`, which see. effects()
|
| 371 |
+
below is the low-level call on standardized arrays."""
|
| 372 |
+
from .inference import effect
|
| 373 |
+
return effect(self, data, graph, treatment, outcome, **kwargs)
|
| 374 |
+
|
| 375 |
+
@torch.no_grad()
|
| 376 |
+
def effects(self, X, A, t, y, pairs, chunk=256, calibrated=True):
|
| 377 |
+
"""Quantiles (len(pairs), len(QUANTILES)) of the effect on column y of moving column t
|
| 378 |
+
from a to b, for each (a, b) in pairs: X (n, d) a table standardized per column (as
|
| 379 |
+
the treatment values are), A (d, d) its DAG, A[i, j] = 1 meaning i -> j. Every row is
|
| 380 |
+
a query row and gives the correction its residuals, `chunk` rows at a time.
|
| 381 |
+
|
| 382 |
+
With a calibration in the config (calibrate_effect.py) and `calibrated`, the 90% and
|
| 383 |
+
50% intervals are widened (or narrowed) around the median by split-conformal factors
|
| 384 |
+
for this n; the median, the estimate, is never changed.
|
| 385 |
+
|
| 386 |
+
The graph is taken as true: a DAG over the table's variables, so no hidden confounders
|
| 387 |
+
and every effect identified. If it gives no directed path from t to y, intervening on t
|
| 388 |
+
cannot move y, and every effect is exactly 0 (a zero-width interval), whatever the data
|
| 389 |
+
shows: their association then comes from common causes."""
|
| 390 |
+
X, A = np.asarray(X, dtype=np.float32), np.asarray(A)
|
| 391 |
+
if X.ndim != 2 or A.shape != (X.shape[1], X.shape[1]):
|
| 392 |
+
raise ValueError(f"X {X.shape} needs a (d, d) graph with d = its columns; got {A.shape}")
|
| 393 |
+
if not (0 <= t < X.shape[1] and 0 <= y < X.shape[1]) or t == y:
|
| 394 |
+
raise ValueError(f"treatment {t} and outcome {y} must be two different columns of X")
|
| 395 |
+
if not is_dag(A):
|
| 396 |
+
raise ValueError("the graph has a directed cycle; effects() needs a DAG")
|
| 397 |
+
if y not in descendants(A, t):
|
| 398 |
+
return np.zeros((len(pairs), len(QUANTILES)), dtype=np.float32)
|
| 399 |
+
device = next(self.parameters()).device
|
| 400 |
+
X = torch.as_tensor(X, device=device)
|
| 401 |
+
W = torch.as_tensor(optimal_adjustment(A, t, y), dtype=torch.long, device=device)
|
| 402 |
+
values, idx = np.unique(np.asarray(pairs, dtype=np.float32), return_inverse=True)
|
| 403 |
+
idx = torch.as_tensor(idx.reshape(-1, 2), device=device)
|
| 404 |
+
vals = torch.as_tensor(values, device=device)[None]
|
| 405 |
+
ctx_w, ctx_t, ctx_y = X[None][:, :, W], X[None, :, t], X[None, :, y]
|
| 406 |
+
w_mask = torch.ones(1, len(W), dtype=torch.bool, device=device)
|
| 407 |
+
with eval_mode(self):
|
| 408 |
+
rows = self(ctx_w, ctx_t, ctx_y, w_mask, ctx_w[:, None].expand(-1, len(values), -1, -1), vals,
|
| 409 |
+
chunk=chunk)
|
| 410 |
+
q = self.quantiles(rows, vals, idx, len(X))
|
| 411 |
+
q = q[0].cpu().numpy()
|
| 412 |
+
cal = self.config.get("calibration")
|
| 413 |
+
return calibrate(q, calibration_factors(cal, len(X))) if calibrated and cal else q
|