Release 0.2.0
Browse files- LICENSE-CausalPFN +0 -175
- NOTICE +0 -14
- README.md +7 -15
- config.json +6 -3
- model.safetensors +2 -2
- pyproject.toml +2 -2
- src/axiom_effect/__init__.py +1 -1
- src/axiom_effect/inference.py +73 -65
- src/axiom_effect/model.py +408 -272
LICENSE-CausalPFN
DELETED
|
@@ -1,175 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,14 +0,0 @@
|
|
| 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
|
@@ -16,22 +16,17 @@ treated (ATT) and on the controls, and every row's own effect (CATE); for contin
|
|
| 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 |
-
|
| 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 |
-
|
| 35 |
[maxpagels.com/axiom](https://maxpagels.com/axiom).
|
| 36 |
|
| 37 |
## Recommended use (ballpark)
|
|
@@ -41,7 +36,7 @@ for from the ones that would bias the answer.
|
|
| 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-
|
| 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 |
|
|
@@ -96,12 +91,9 @@ Everything is in the data's own units.
|
|
| 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.
|
| 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.
|
|
|
|
| 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 |
+
**Version 0.2.0 is experimental.** The API and the weights will change in 0.x releases.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
Check its answers against what you know about your data.
|
| 21 |
|
| 22 |
It works without a causal graph, the usual assumption being that every covariate is measured
|
| 23 |
before the treatment, and better with one. It is the sibling of
|
| 24 |
+
[Axiom Discovery](https://huggingface.co/maxpagels/axiom-discovery), the causal discovery model: given a
|
| 25 |
discovered graph, it reads each covariate's role (confounder, instrument, mediator, collider,
|
| 26 |
...) as probabilities, so a discovered graph helps it tell the columns that must be adjusted
|
| 27 |
for from the ones that would bias the answer.
|
| 28 |
|
| 29 |
+
20.3M parameters, fp32 safetensors (81 MB). Project page:
|
| 30 |
[maxpagels.com/axiom](https://maxpagels.com/axiom).
|
| 31 |
|
| 32 |
## Recommended use (ballpark)
|
|
|
|
| 36 |
| treatment | binary (two values) or continuous (at least 10 distinct values); continuous values inside its 2-98% quantiles |
|
| 37 |
| covariates | trained on up to 84; without a graph they must all be pre-treatment (not caused by the treatment) |
|
| 38 |
| graph | none; a DAG you trust (the treatment's descendants are then dropped); or an Axiom `discover()` result |
|
| 39 |
+
| rows | trained on 128-1024; larger tables are split into disjoint subsets of up to 1024 rows and combined |
|
| 40 |
| hidden confounders | not handled: no unmeasured common causes of the treatment and the outcome |
|
| 41 |
| missing values | not supported in the columns used |
|
| 42 |
|
|
|
|
| 91 |
## Versions
|
| 92 |
|
| 93 |
Each release is a tagged commit in this repo; `main` is the latest. The package loads the
|
| 94 |
+
weights released with it, so code and weights always match. To install a specific release,
|
| 95 |
+
an earlier one included, use its tag:
|
| 96 |
|
| 97 |
```bash
|
| 98 |
+
pip install "git+https://huggingface.co/maxpagels/axiom-effect@v0.2.0" # or an earlier tag, e.g. @v0.1.0
|
| 99 |
```
|
|
|
|
|
|
|
|
|
|
|
|
config.json
CHANGED
|
@@ -1,8 +1,11 @@
|
|
| 1 |
{
|
| 2 |
"E": 384,
|
| 3 |
"H": 6,
|
| 4 |
-
"
|
| 5 |
-
"
|
| 6 |
-
"
|
|
|
|
|
|
|
|
|
|
| 7 |
"vmax": 10.0
|
| 8 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"E": 384,
|
| 3 |
"H": 6,
|
| 4 |
+
"col_dim": 64,
|
| 5 |
+
"col_layers": 2,
|
| 6 |
+
"layers": 12,
|
| 7 |
+
"nbins": 256,
|
| 8 |
+
"row_slots": 16,
|
| 9 |
+
"sigma": 0.4,
|
| 10 |
"vmax": 10.0
|
| 11 |
}
|
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:a45233de83ce1ba99df0f33fdbca52cc5ebb6572b44e895155a7a0c4370cfc71
|
| 3 |
+
size 81332280
|
pyproject.toml
CHANGED
|
@@ -1,12 +1,12 @@
|
|
| 1 |
[project]
|
| 2 |
name = "axiom-effect"
|
| 3 |
-
version = "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"
|
| 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.2.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"]
|
| 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,5 +1,5 @@
|
|
| 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
|
|
|
|
| 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 Discovery (axiom-discovery),
|
| 3 |
whose discovered graphs it reads.
|
| 4 |
|
| 5 |
from axiom_effect import AxiomEffect
|
src/axiom_effect/inference.py
CHANGED
|
@@ -7,7 +7,7 @@ The table-level call: AxiomEffect on a real table, in the data's own units.
|
|
| 7 |
print(r)
|
| 8 |
r.ate, r.att, r.cate, r.curve, r.debiased
|
| 9 |
|
| 10 |
-
What the graph does
|
| 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
|
|
@@ -18,11 +18,10 @@ What the graph does (design-effect.md, "Axiom discovery and the effect model"):
|
|
| 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 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
values, the dose-response curve, each row's effect of the contrast.
|
| 26 |
"""
|
| 27 |
import warnings
|
| 28 |
from dataclasses import dataclass, field
|
|
@@ -31,19 +30,18 @@ from statistics import NormalDist
|
|
| 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
|
| 35 |
|
| 36 |
-
TRAIN_N = (128,
|
| 37 |
-
TRAIN_COVARIATES = 84 # covariates
|
| 38 |
-
|
| 39 |
-
|
| 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 #
|
| 47 |
Z90 = NormalDist().inv_cdf(0.95)
|
| 48 |
|
| 49 |
|
|
@@ -109,7 +107,7 @@ class EffectResult:
|
|
| 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}
|
| 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)}")
|
|
@@ -130,7 +128,7 @@ class EffectResult:
|
|
| 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 (
|
| 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 |
|
|
@@ -206,16 +204,8 @@ def _standardize(v):
|
|
| 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
|
| 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)
|
|
@@ -226,9 +216,28 @@ def _combine(qs, counts):
|
|
| 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:
|
| 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
|
|
@@ -245,8 +254,7 @@ def _logistic(X, t, ridge, iters=25):
|
|
| 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
|
| 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)
|
|
@@ -275,15 +283,13 @@ def _aipw(mu0, mu1, e, T, Y):
|
|
| 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
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
(default
|
| 284 |
-
|
| 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:
|
|
@@ -318,15 +324,8 @@ def effect(model, data, treatment, outcome, graph=None, covariates=None, values=
|
|
| 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]
|
| 322 |
-
if len(cov) >
|
| 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)
|
|
@@ -355,24 +354,33 @@ def effect(model, data, treatment, outcome, graph=None, covariates=None, values=
|
|
| 355 |
k = {v: i for i, v in enumerate(vals)}
|
| 356 |
|
| 357 |
rng = np.random.default_rng(seed)
|
| 358 |
-
|
| 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
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 367 |
vz = (np.array(vals) - tm) / ts
|
| 368 |
-
|
| 369 |
-
jobs = [(k[a], k[b],
|
| 370 |
if binary:
|
| 371 |
-
|
| 372 |
-
|
|
|
|
|
|
|
|
|
|
| 373 |
else:
|
| 374 |
-
jobs += [(k[ref], k[v],
|
| 375 |
-
out = model.predict(
|
|
|
|
| 376 |
Q = out["quantiles"] * ys
|
| 377 |
curve = []
|
| 378 |
for (_, _, r, name), q in zip(jobs, Q):
|
|
@@ -383,14 +391,14 @@ def effect(model, data, treatment, outcome, graph=None, covariates=None, values=
|
|
| 383 |
counts[name].append(r.sum())
|
| 384 |
if curve:
|
| 385 |
est["curve"].append(np.stack(curve))
|
| 386 |
-
counts["curve"].append(len(
|
| 387 |
-
cate[
|
| 388 |
if binary:
|
| 389 |
-
mu0[
|
| 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(
|
| 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)
|
|
@@ -402,9 +410,9 @@ def effect(model, data, treatment, outcome, graph=None, covariates=None, values=
|
|
| 402 |
f"estimates there rest on extrapolation", stacklevel=3)
|
| 403 |
else:
|
| 404 |
result.values, result.reference = curve_vals, ref
|
| 405 |
-
|
| 406 |
-
result.curve = np.stack([_combine(
|
| 407 |
-
result.curve[curve_vals == ref] = 0.0
|
| 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)
|
|
|
|
| 7 |
print(r)
|
| 8 |
r.ate, r.att, r.cate, r.curve, r.debiased
|
| 9 |
|
| 10 |
+
What the graph does:
|
| 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
|
|
|
|
| 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 |
+
For large tables (more than TRAIN_N[1] rows), inference keeps memory small (< 1 GB) by
|
| 22 |
+
partitioning the table into disjoint i.i.d. subsets of at most TRAIN_N[1] rows (stratified
|
| 23 |
+
by treatment arm for binary treatments so every subset preserves prevalence) and combining
|
| 24 |
+
their independent estimates.
|
|
|
|
| 25 |
"""
|
| 26 |
import warnings
|
| 27 |
from dataclasses import dataclass, field
|
|
|
|
| 30 |
import numpy as np
|
| 31 |
|
| 32 |
from .graph import CONF, N_ROLES, ROLE_NAMES, descendants, discovered_roles, is_dag, roles
|
| 33 |
+
from .model import MID, N_FEATURES, QUANTILES
|
| 34 |
|
| 35 |
+
TRAIN_N = (128, 1024) # context rows; larger tables use localized retrieval of TRAIN_N[1] rows
|
| 36 |
+
TRAIN_COVARIATES = 84 # covariates seen in training (network accepts any number natively)
|
| 37 |
+
WIDE_N = TRAIN_N[1] # kept for compatibility with export_effect_hf / train_effect
|
| 38 |
+
NARROW_COVARIATES = 34
|
|
|
|
| 39 |
MIN_LEVELS = 10 # a continuous treatment needs at least this many distinct values
|
| 40 |
TRAIN_LEVELS = (0.02, 0.98) # continuous treatment values were asked about between these quantiles
|
| 41 |
CURVE_LEVELS = (0.1, 0.25, 0.5, 0.75, 0.9)
|
| 42 |
CONTRAST_LEVELS = (0.25, 0.75)
|
| 43 |
E_CLIP = 0.01 # propensities clipped to [E_CLIP, 1 - E_CLIP] in the doubly robust estimate
|
| 44 |
+
PROPENSITY_FOLDS, PROPENSITY_RIDGE = 5, 1.0 # cross-fitted logistic propensity
|
| 45 |
Z90 = NormalDist().inv_cdf(0.95)
|
| 46 |
|
| 47 |
|
|
|
|
| 107 |
g = lambda v: f"{v:.4g}"
|
| 108 |
sig = lambda v: ("+" if v > 0 else "") + g(v)
|
| 109 |
adj = ", ".join(self.covariates) or "nothing"
|
| 110 |
+
rows = f"{self.n_rows} rows" + (f" in {self.n_subsets} strata" if self.n_subsets > 1 else "")
|
| 111 |
head = [f"Effect of {self.treatment} on {self.outcome} ({rows}; graph: {self.graph}; adjusted for {adj})"]
|
| 112 |
if self.dropped:
|
| 113 |
head.append(f" not adjusted for (the graph says the treatment causes them): {', '.join(self.dropped)}")
|
|
|
|
| 128 |
f" dose-response, from {self.treatment} = {g(self.reference)}:"]
|
| 129 |
lines += [f" {g(v):>10s} {sig(q[MID])} 90% [{g(q[0])}, {g(q[-1])}]"
|
| 130 |
for v, q in zip(self.values, self.curve)]
|
| 131 |
+
lines.append(f" per-row effects (CATE): median {sig(np.median(self.cate))}, "
|
| 132 |
f"10-90% {g(np.quantile(self.cate, 0.1))} to {g(np.quantile(self.cate, 0.9))}")
|
| 133 |
return "\n".join(lines)
|
| 134 |
|
|
|
|
| 204 |
return (v - mu) / np.where(sd > 0, sd, 1.0), mu, np.where(sd > 0, sd, 1.0)
|
| 205 |
|
| 206 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
def _combine(qs, counts):
|
| 208 |
+
"""Quantiles of one estimand from disjoint query strata: the count-weighted mean of the
|
| 209 |
medians, and each quantile's distance from the median combined as for a mean of
|
| 210 |
independent estimates, sqrt(sum (m_k d_k)^2) / sum m_k."""
|
| 211 |
qs, m = np.asarray(qs), np.asarray(counts, dtype=float)
|
|
|
|
| 216 |
return mid + np.sign(off.mean(0)) * np.sqrt(((m[:, None] * off) ** 2).sum(0)) / m.sum()
|
| 217 |
|
| 218 |
|
| 219 |
+
def _disjoint_strata(T, binary, max_ctx, rng):
|
| 220 |
+
"""Partition `n` rows into disjoint i.i.d. subsets of at most `max_ctx` rows (stratified by
|
| 221 |
+
treatment arm for binary treatments so every subset preserves prevalence).
|
| 222 |
+
Returns [(rows, rows)]."""
|
| 223 |
+
n = len(T)
|
| 224 |
+
if n <= max_ctx:
|
| 225 |
+
all_rows = np.arange(n)
|
| 226 |
+
return [(all_rows, all_rows)]
|
| 227 |
+
|
| 228 |
+
n_strata = -(-n // max_ctx)
|
| 229 |
+
if binary:
|
| 230 |
+
mid = (T.min() + T.max()) / 2
|
| 231 |
+
tr = rng.permutation(np.flatnonzero(T > mid))
|
| 232 |
+
ct = rng.permutation(np.flatnonzero(T <= mid))
|
| 233 |
+
parts = [np.concatenate([a, b]) for a, b in zip(np.array_split(tr, n_strata), np.array_split(ct, n_strata))]
|
| 234 |
+
else:
|
| 235 |
+
parts = np.array_split(rng.permutation(n), n_strata)
|
| 236 |
+
return [(p, p) for p in parts]
|
| 237 |
+
|
| 238 |
+
|
| 239 |
def _logistic(X, t, ridge, iters=25):
|
| 240 |
+
"""Ridge-penalized logistic regression by Newton's method: weights (intercept first)."""
|
|
|
|
| 241 |
A = np.column_stack([np.ones(len(X)), X])
|
| 242 |
P = ridge * np.eye(A.shape[1])
|
| 243 |
P[0, 0] = 0.0
|
|
|
|
| 254 |
|
| 255 |
|
| 256 |
def _propensity(C, t, seed=0):
|
| 257 |
+
"""(n,) P(t = 1 | C), each row's from a logistic regression fitted on the other folds."""
|
|
|
|
| 258 |
n = len(t)
|
| 259 |
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))
|
| 260 |
folds = np.random.default_rng(seed).permutation(n) % min(PROPENSITY_FOLDS, n)
|
|
|
|
| 283 |
|
| 284 |
|
| 285 |
def effect(model, data, treatment, outcome, graph=None, covariates=None, values=None, contrast=None,
|
| 286 |
+
reference=None, names=None, extrapolate=False, discovery_samples=64, tta=1, seed=0):
|
| 287 |
"""The effect of setting `treatment` on `outcome` in a table (a DataFrame or an (n, d)
|
| 288 |
+
array; `names` for an array's columns), given an optional graph: a DAG as an edge list of
|
| 289 |
+
(cause, effect) names, a (d, d) matrix or an adjacency DataFrame, or a discover() result.
|
| 290 |
+
`covariates`: the columns to adjust for (default: all others). `tta`: test-time
|
| 291 |
+
augmentation passes (default 4; averages over random column tie-breaker codes with zero
|
| 292 |
+
extra peak RAM). Returns an EffectResult."""
|
|
|
|
|
|
|
| 293 |
X, names = _table(data, names)
|
| 294 |
t, y = _column(treatment, names, "treatment"), _column(outcome, names, "outcome")
|
| 295 |
if t == y:
|
|
|
|
| 324 |
n = len(X)
|
| 325 |
if n < TRAIN_N[0]:
|
| 326 |
warnings.warn(f"{n} rows is below the training range {TRAIN_N}", stacklevel=3)
|
| 327 |
+
C = X[:, cov]
|
| 328 |
+
if len(cov) > TRAIN_COVARIATES:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
warnings.warn(f"{len(cov)} covariates, more than in training (up to {TRAIN_COVARIATES})", stacklevel=3)
|
| 330 |
T, Y = X[:, t], X[:, y]
|
| 331 |
levels = np.unique(T)
|
|
|
|
| 354 |
k = {v: i for i, v in enumerate(vals)}
|
| 355 |
|
| 356 |
rng = np.random.default_rng(seed)
|
| 357 |
+
strata = _disjoint_strata(T, binary, TRAIN_N[1], rng)
|
|
|
|
| 358 |
est = {"contrast": [], "att": [], "atc": []} if binary else {"contrast": [], "curve": []}
|
| 359 |
counts = {key: [] for key in est}
|
| 360 |
cate, mu0, mu1 = np.empty(n), np.empty(n), np.empty(n)
|
| 361 |
+
for idx_s, (q_rows, ctx_rows) in enumerate(strata):
|
| 362 |
+
same = len(q_rows) == len(ctx_rows) and np.array_equal(q_rows, ctx_rows)
|
| 363 |
+
if cov:
|
| 364 |
+
Wz_ctx, wm, ws = _standardize(C[ctx_rows])
|
| 365 |
+
Wz_qry = None if same else (C[q_rows] - wm) / ws
|
| 366 |
+
else:
|
| 367 |
+
Wz_ctx = np.zeros((len(ctx_rows), 0))
|
| 368 |
+
Wz_qry = None if same else np.zeros((len(q_rows), 0))
|
| 369 |
+
Tz_ctx, tm, ts = _standardize(T[ctx_rows])
|
| 370 |
+
Yz_ctx, ym, ys = _standardize(Y[ctx_rows])
|
| 371 |
vz = (np.array(vals) - tm) / ts
|
| 372 |
+
all_q = np.ones(len(q_rows), dtype=bool)
|
| 373 |
+
jobs = [(k[a], k[b], all_q, "contrast")]
|
| 374 |
if binary:
|
| 375 |
+
treated_q = T[q_rows] == levels[1]
|
| 376 |
+
if treated_q.any():
|
| 377 |
+
jobs.append((k[a], k[b], treated_q, "att"))
|
| 378 |
+
if (~treated_q).any():
|
| 379 |
+
jobs.append((k[a], k[b], ~treated_q, "atc"))
|
| 380 |
else:
|
| 381 |
+
jobs += [(k[ref], k[v], all_q, "curve") for v in curve_vals]
|
| 382 |
+
out = model.predict(Wz_ctx, Tz_ctx, Yz_ctx, features, binary, vz,
|
| 383 |
+
[(i, j, r) for i, j, r, _ in jobs], W_qry=Wz_qry, tta=tta, seed=seed + idx_s * 97)
|
| 384 |
Q = out["quantiles"] * ys
|
| 385 |
curve = []
|
| 386 |
for (_, _, r, name), q in zip(jobs, Q):
|
|
|
|
| 391 |
counts[name].append(r.sum())
|
| 392 |
if curve:
|
| 393 |
est["curve"].append(np.stack(curve))
|
| 394 |
+
counts["curve"].append(len(q_rows))
|
| 395 |
+
cate[q_rows] = (out["mu"][k[b]] - out["mu"][k[a]]) * ys
|
| 396 |
if binary:
|
| 397 |
+
mu0[q_rows], mu1[q_rows] = out["mu"][k[a]] * ys + ym, out["mu"][k[b]] * ys + ym
|
| 398 |
|
| 399 |
+
quantiles = {name: _combine(est[name], counts[name]) for name in est if name != "curve" and est[name]}
|
| 400 |
result = EffectResult(names[t], names[y], binary, [names[c] for c in cov], [names[c] for c in dropped], kind,
|
| 401 |
+
(a, b), quantiles, cate, n_rows=n, n_subsets=len(strata),
|
| 402 |
roles={names[c]: dict(zip(ROLE_NAMES, map(float, R[c]))) for c in cov} if kind != "none" else {})
|
| 403 |
if binary:
|
| 404 |
treated = (T == levels[1]).astype(float)
|
|
|
|
| 410 |
f"estimates there rest on extrapolation", stacklevel=3)
|
| 411 |
else:
|
| 412 |
result.values, result.reference = curve_vals, ref
|
| 413 |
+
C_arr = np.asarray(est["curve"]) # (strata, K, Q)
|
| 414 |
+
result.curve = np.stack([_combine(C_arr[:, j], counts["curve"]) for j in range(C_arr.shape[1])])
|
| 415 |
+
result.curve[curve_vals == ref] = 0.0
|
| 416 |
if zero:
|
| 417 |
warnings.warn(f"the graph has no directed path from {names[t]} to {names[y]}: every effect is exactly 0",
|
| 418 |
stacklevel=3)
|
src/axiom_effect/model.py
CHANGED
|
@@ -1,55 +1,30 @@
|
|
| 1 |
"""
|
| 2 |
-
AxiomEffect: a
|
| 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 |
-
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,45 +36,39 @@ import numpy as np
|
|
| 61 |
import torch
|
| 62 |
import torch.nn as nn
|
| 63 |
import torch.nn.functional as F
|
| 64 |
-
from huggingface_hub import PyTorchModelHubMixin
|
| 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 = "
|
| 72 |
-
QUANTILES = (0.05, 0.25, 0.5, 0.75, 0.95) #
|
| 73 |
MID = QUANTILES.index(0.5)
|
| 74 |
-
N_FEATURES = 1 + N_ROLES #
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
NBINS,
|
| 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
|
| 88 |
-
query: torch.Tensor # (B,
|
| 89 |
-
context: torch.Tensor # (B, E) mean context
|
| 90 |
-
mu: torch.Tensor # (B, K,
|
| 91 |
-
logits: torch.Tensor # (B, K,
|
| 92 |
-
shift: torch.Tensor # (B, K)
|
| 93 |
-
scale: torch.Tensor # (B, K)
|
| 94 |
-
|
| 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 |
-
"""
|
| 103 |
def __init__(self, dim, eps=1e-6):
|
| 104 |
super().__init__()
|
| 105 |
self.eps = eps
|
|
@@ -110,72 +79,135 @@ class RMSNorm(nn.Module):
|
|
| 110 |
return (y * torch.rsqrt(y.pow(2).mean(-1, keepdim=True) + self.eps)).type_as(x) * self.weight
|
| 111 |
|
| 112 |
|
| 113 |
-
class
|
| 114 |
-
"""
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 (
|
| 129 |
-
|
| 130 |
k, v = self.kv_proj(self.attn_norm(ctx)).chunk(2, -1)
|
| 131 |
-
k = k.view(
|
| 132 |
-
v = v.view(
|
| 133 |
-
return
|
| 134 |
|
| 135 |
def forward(self, x, k, v, mask=None):
|
| 136 |
-
"""x (
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
q
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
return x + self.
|
| 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 |
-
"""
|
| 165 |
-
|
| 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
|
| 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()
|
| 174 |
return m, s, c > 0
|
| 175 |
|
| 176 |
m1, s1, has1 = stats(treated)
|
| 177 |
m0, s0, has0 = stats(1 - treated)
|
| 178 |
-
m1
|
|
|
|
|
|
|
|
|
|
| 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)
|
|
@@ -185,9 +217,125 @@ def _arm_scales(T, Y, values, binary):
|
|
| 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
|
| 190 |
-
when the package is not installed (running from source without metadata)."""
|
| 191 |
try:
|
| 192 |
return f"v{version('axiom-effect')}"
|
| 193 |
except PackageNotFoundError:
|
|
@@ -196,10 +344,8 @@ def release_tag():
|
|
| 196 |
|
| 197 |
class AxiomEffect(nn.Module, PyTorchModelHubMixin, library_name="axiom-effect", repo_url=None,
|
| 198 |
tags=["causal-inference", "effect-estimation", "tabular"]):
|
| 199 |
-
"""
|
| 200 |
-
|
| 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)
|
|
@@ -212,171 +358,180 @@ class AxiomEffect(nn.Module, PyTorchModelHubMixin, library_name="axiom-effect",
|
|
| 212 |
f"not match this version of the code", stacklevel=2)
|
| 213 |
return super().from_pretrained(path, revision=revision, strict=strict, **kwargs)
|
| 214 |
|
| 215 |
-
|
| 216 |
-
|
| 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,
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
self.
|
| 243 |
-
self.
|
| 244 |
-
self.
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
self.
|
| 250 |
-
self.
|
| 251 |
-
self.
|
| 252 |
-
self.
|
| 253 |
-
#
|
| 254 |
-
|
| 255 |
-
|
|
|
|
| 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
|
| 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
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
|
| 305 |
kvs = []
|
| 306 |
-
for
|
| 307 |
-
ctx, k, v = self._run(
|
| 308 |
kvs.append((k, v))
|
| 309 |
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
step = max(1, chunk // J) if chunk else n
|
| 313 |
out = []
|
| 314 |
-
for s in range(0,
|
| 315 |
-
xs =
|
| 316 |
Q = xs.shape[1]
|
| 317 |
-
q = self.
|
| 318 |
mask = None
|
| 319 |
-
if self_mask:
|
| 320 |
-
mask = torch.zeros(Q,
|
| 321 |
-
mask[torch.arange(Q), torch.arange(s, s + Q)] = float("-inf")
|
| 322 |
-
mask = mask.repeat(
|
| 323 |
-
for
|
| 324 |
-
q = self._run(
|
| 325 |
-
out.append(q.view(B,
|
| 326 |
-
q = torch.cat(out, 2)
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
|
| 335 |
def mu_nll(self, rows, target):
|
| 336 |
-
"""(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,
|
| 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
|
| 358 |
-
|
| 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)
|
| 367 |
n = w.shape[-1]
|
| 368 |
-
phi = self.
|
| 369 |
-
pooled = (w[..., None] * query[:, None]).sum(2) / tot[..., None]
|
| 370 |
context = context[:, None].expand_as(pooled)
|
| 371 |
|
| 372 |
def one_way(a, b):
|
| 373 |
-
d = mu[:, b] - mu[:, a]
|
| 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) /
|
| 378 |
rows.binary.float()[:, None, None].expand_as(est[..., None])], -1)
|
| 379 |
-
moved = (rows.values[:, a] != rows.values[:, b]).float()[..., None]
|
| 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)
|
|
@@ -384,41 +539,25 @@ class AxiomEffect(nn.Module, PyTorchModelHubMixin, library_name="axiom-effect",
|
|
| 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 (
|
| 403 |
-
binary, values (K,), estimands [(a, b, rows)]
|
| 404 |
-
(
|
| 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,
|
| 411 |
-
f(np.asarray(features, dtype=np.float32).reshape(
|
| 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):
|
|
@@ -426,6 +565,3 @@ class AxiomEffect(nn.Module, PyTorchModelHubMixin, library_name="axiom-effect",
|
|
| 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
|
|
|
|
| 1 |
"""
|
| 2 |
+
AxiomEffect: a pure, from-scratch factorized tabular PFN for causal effects.
|
| 3 |
+
|
| 4 |
+
Supports binary and continuous treatments, ATE / ATT / ATC / CATE / dose-response curves,
|
| 5 |
+
and optional causal graphs (trusted DAGs or discovered graphs from Axiom), with zero
|
| 6 |
+
pretrained dependencies and < 4 GB training RAM.
|
| 7 |
+
|
| 8 |
+
Architecture ("factorized tabular PFN", ~12.5M parameters by default):
|
| 9 |
+
1. Column encoder (2 layers of column self-attention, O(P^2)):
|
| 10 |
+
each covariate column j starts from exact context statistics (marginal correlations with
|
| 11 |
+
Y, T, W_j^2, W_j * T; joint partial ridge slopes on Y, W*T, and T; and optional graph
|
| 12 |
+
role features) and attends to all other columns biased by the P x P covariate correlation
|
| 13 |
+
matrix R_jk. Completely deterministic and column-permutation equivariant.
|
| 14 |
+
2. Multi-slot row encoder (Set-Transformer / TabICL-style cross-attention, O(n * P * M)):
|
| 15 |
+
each cell (i, j) combines [w_ij, rank(w_ij)] with its column embedding c_j; M = 8 learned
|
| 16 |
+
row slots cross-attend over the P cells of row i, automatically gating out noise and
|
| 17 |
+
post-treatment columns while capturing multi-covariate interactions, then project into
|
| 18 |
+
R^E. Works for any number of covariates P without slot limits or PCA truncation.
|
| 19 |
+
3. Row transformer (8 Pre-RMSNorm + SwiGLU layers, E = 384, H = 6):
|
| 20 |
+
context rows (x_i + embed(T_i) + embed(Y_i)) self-attend; query rows (x_i + embed(t))
|
| 21 |
+
cross-attend to the context keys and values at every layer. Training uses disjoint
|
| 22 |
+
(context, query) splits; full-table inference masks each query from its own context row.
|
| 23 |
+
4. Direct HL-Gauss head:
|
| 24 |
+
predicts mu(t, w_i) directly as a 256-bin distribution on [-10, 10] on the arm's
|
| 25 |
+
standardized outcome scale (global for continuous). Every causal estimand (CATE, ATE,
|
| 26 |
+
ATT, ATC, dose-response) is arithmetic on mu; a detached width head predicts calibrated
|
| 27 |
+
5/25/75/95% uncertainty intervals.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
"""
|
| 29 |
import math
|
| 30 |
import os
|
|
|
|
| 36 |
import torch
|
| 37 |
import torch.nn as nn
|
| 38 |
import torch.nn.functional as F
|
| 39 |
+
from huggingface_hub import PyTorchModelHubMixin
|
| 40 |
from huggingface_hub.errors import RevisionNotFoundError
|
| 41 |
from torch.utils.checkpoint import checkpoint
|
| 42 |
|
| 43 |
from .blocks import eval_mode, mlp
|
| 44 |
from .graph import N_ROLES
|
| 45 |
|
| 46 |
+
ARCHITECTURE = "factorized tabular PFN v2"
|
| 47 |
+
QUANTILES = (0.05, 0.25, 0.5, 0.75, 0.95) # outer pair: 90% interval; inner pair: 50%
|
| 48 |
MID = QUANTILES.index(0.5)
|
| 49 |
+
N_FEATURES = 1 + N_ROLES # [graph given, 4 role indicators]
|
| 50 |
+
N_COL_STATS = 14 # global, rank, arm-conditional correlations + partial slopes
|
| 51 |
+
N_REF = 2048 # sample-size reference for the width head
|
| 52 |
+
CLIP_SIGMA = 10.0
|
| 53 |
+
NBINS, VMAX, SIGMA = 256, 10.0, 0.4 # HL-Gauss bins on [-VMAX, VMAX]
|
| 54 |
+
DEFAULT_CONFIG = dict(E=384, H=6, layers=12, col_dim=64, col_layers=2, row_slots=16,
|
| 55 |
+
nbins=NBINS, vmax=VMAX, sigma=SIGMA)
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
|
| 58 |
class Rows(NamedTuple):
|
| 59 |
+
"""Everything forward() predicts for a batch of B tables."""
|
| 60 |
+
query: torch.Tensor # (B, n_qry, E) mean query representation across asked values, normalized
|
| 61 |
+
context: torch.Tensor # (B, E) mean context representation, normalized
|
| 62 |
+
mu: torch.Tensor # (B, K, n_qry) predicted E[Y | do(T = values[k]), W = w_i]
|
| 63 |
+
logits: torch.Tensor # (B, K, n_qry, nbins) distribution over bins on arm's standardized scale
|
| 64 |
+
shift: torch.Tensor # (B, K) outcome shift per asked value's arm
|
| 65 |
+
scale: torch.Tensor # (B, K) outcome scale per asked value's arm
|
| 66 |
+
values: torch.Tensor # (B, K) treatment values asked about
|
|
|
|
|
|
|
|
|
|
| 67 |
binary: torch.Tensor # (B,) bool
|
| 68 |
|
| 69 |
|
| 70 |
class RMSNorm(nn.Module):
|
| 71 |
+
"""Root-mean-square layer normalization in float32."""
|
| 72 |
def __init__(self, dim, eps=1e-6):
|
| 73 |
super().__init__()
|
| 74 |
self.eps = eps
|
|
|
|
| 79 |
return (y * torch.rsqrt(y.pow(2).mean(-1, keepdim=True) + self.eps)).type_as(x) * self.weight
|
| 80 |
|
| 81 |
|
| 82 |
+
class ColBlock(nn.Module):
|
| 83 |
+
"""Column-to-column Pre-RMSNorm self-attention biased by the P x P correlation matrix R_jk."""
|
| 84 |
+
def __init__(self, dim, heads=4):
|
| 85 |
+
super().__init__()
|
| 86 |
+
self.H, self.d = heads, dim // heads
|
| 87 |
+
self.attn_norm = RMSNorm(dim)
|
| 88 |
+
self.qkv = nn.Linear(dim, 3 * dim, bias=False)
|
| 89 |
+
self.out = nn.Linear(dim, dim, bias=False)
|
| 90 |
+
self.bias_proj = nn.Linear(2, heads, bias=False) # [R_jk, |R_jk|] -> per-head bias
|
| 91 |
+
self.ff_norm = RMSNorm(dim)
|
| 92 |
+
self.ff_in = nn.Linear(dim, 4 * dim, bias=False)
|
| 93 |
+
self.ff_out = nn.Linear(2 * dim, dim, bias=False)
|
| 94 |
+
|
| 95 |
+
def forward(self, c, R, w_mask):
|
| 96 |
+
"""c (B, P, D), R (B, P, P), w_mask (B, P) True = real column."""
|
| 97 |
+
B, P, D = c.shape
|
| 98 |
+
q, k, v = self.qkv(self.attn_norm(c)).chunk(3, -1)
|
| 99 |
+
q = q.view(B, P, self.H, self.d).transpose(1, 2)
|
| 100 |
+
k = k.view(B, P, self.H, self.d).transpose(1, 2)
|
| 101 |
+
v = v.view(B, P, self.H, self.d).transpose(1, 2)
|
| 102 |
+
bias = self.bias_proj(torch.stack([R, R.abs()], -1)).permute(0, 3, 1, 2) # (B, H, P, P)
|
| 103 |
+
# Mask out padded keys (keep self-diagonal valid so all-masked rows never produce NaN)
|
| 104 |
+
pad = (~w_mask)[:, None, None, :].expand(B, 1, P, P)
|
| 105 |
+
eye = torch.eye(P, dtype=torch.bool, device=c.device)[None, None]
|
| 106 |
+
bias = bias.masked_fill(pad & ~eye, float("-inf"))
|
| 107 |
+
a = F.scaled_dot_product_attention(q, k, v, attn_mask=bias).transpose(1, 2).reshape(B, P, D)
|
| 108 |
+
c = c + self.out(a)
|
| 109 |
+
h, g = self.ff_in(self.ff_norm(c)).chunk(2, -1)
|
| 110 |
+
return (c + self.ff_out(h * F.silu(g))) * w_mask[..., None].to(c.dtype)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class RowPool(nn.Module):
|
| 114 |
+
"""Multi-slot cross-attention pooling over a row's P covariate cells: O(n * P * M)."""
|
| 115 |
+
def __init__(self, col_dim, E, slots=8, heads=4):
|
| 116 |
+
super().__init__()
|
| 117 |
+
self.slots, self.H, self.d = slots, heads, col_dim // heads
|
| 118 |
+
self.cell_val = mlp(2, col_dim, col_dim) # [w_ij, rank_ij] -> col_dim
|
| 119 |
+
self.col_scale = nn.Linear(col_dim, col_dim) # multiplicative column modulation
|
| 120 |
+
self.cell_norm = RMSNorm(col_dim)
|
| 121 |
+
self.queries = nn.Parameter(torch.randn(slots, col_dim) / math.sqrt(col_dim))
|
| 122 |
+
self.q_proj = nn.Linear(col_dim, col_dim, bias=False)
|
| 123 |
+
self.kv_proj = nn.Linear(col_dim, 2 * col_dim, bias=False)
|
| 124 |
+
self.out_proj = nn.Linear(slots * col_dim, E, bias=False)
|
| 125 |
+
self.ff_norm = RMSNorm(E)
|
| 126 |
+
self.ff_in = nn.Linear(E, 4 * E, bias=False)
|
| 127 |
+
self.ff_out = nn.Linear(2 * E, E, bias=False)
|
| 128 |
+
|
| 129 |
+
def forward(self, Wz, Rk, col_emb, w_mask):
|
| 130 |
+
"""Wz, Rk (B, n, P), col_emb (B, P, col_dim), w_mask (B, P) -> (B, n, E)."""
|
| 131 |
+
B, n, P = Wz.shape
|
| 132 |
+
E = self.ff_out.out_features
|
| 133 |
+
if P == 0:
|
| 134 |
+
return torch.zeros(B, n, E, device=Wz.device, dtype=Wz.dtype)
|
| 135 |
+
D = col_emb.shape[-1]
|
| 136 |
+
val = self.cell_val(torch.stack([Wz, Rk], -1)) # (B, n, P, D)
|
| 137 |
+
scale = 1.0 + torch.tanh(self.col_scale(col_emb)) # (B, P, D)
|
| 138 |
+
cells = self.cell_norm(val * scale[:, None] + col_emb[:, None])
|
| 139 |
+
cells = cells.reshape(B * n, P, D)
|
| 140 |
+
|
| 141 |
+
q = self.q_proj(self.queries).view(1, self.slots, self.H, self.d).transpose(1, 2)
|
| 142 |
+
q = q.expand(B * n, -1, -1, -1) # (B*n, H, M, d)
|
| 143 |
+
k, v = self.kv_proj(cells).chunk(2, -1)
|
| 144 |
+
k = k.view(B * n, P, self.H, self.d).transpose(1, 2) # (B*n, H, P, d)
|
| 145 |
+
v = v.view(B * n, P, self.H, self.d).transpose(1, 2)
|
| 146 |
+
|
| 147 |
+
# Mask padded covariate columns; if a table has 0 real columns, zero its output afterward
|
| 148 |
+
has_any = w_mask.any(1) # (B,)
|
| 149 |
+
safe_mask = torch.where(has_any[:, None], w_mask, torch.ones_like(w_mask))
|
| 150 |
+
attn_mask = (~safe_mask)[:, None, None, None, :].expand(B, n, 1, self.slots, P).reshape(B * n, 1, self.slots, P)
|
| 151 |
+
attn_bias = torch.zeros_like(attn_mask, dtype=q.dtype).masked_fill(attn_mask, float("-inf"))
|
| 152 |
+
pooled = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_bias)
|
| 153 |
+
pooled = pooled.transpose(1, 2).reshape(B, n, self.slots * D)
|
| 154 |
+
x = self.out_proj(pooled)
|
| 155 |
+
h, g = self.ff_in(self.ff_norm(x)).chunk(2, -1)
|
| 156 |
+
x = x + self.ff_out(h * F.silu(g))
|
| 157 |
+
return x * has_any[:, None, None].to(x.dtype)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class Block(nn.Module):
|
| 161 |
+
"""Pre-RMSNorm row attention to context keys/values + SwiGLU feed-forward."""
|
| 162 |
def __init__(self, E, H):
|
| 163 |
super().__init__()
|
| 164 |
self.H, self.d = H, E // H
|
| 165 |
+
self.attn_norm = RMSNorm(E)
|
| 166 |
+
self.q_proj = nn.Linear(E, E, bias=False)
|
| 167 |
self.kv_proj = nn.Linear(E, 2 * E, bias=False)
|
|
|
|
| 168 |
self.out_proj = nn.Linear(E, E, bias=False)
|
|
|
|
| 169 |
self.q_norm, self.k_norm = RMSNorm(self.d), RMSNorm(self.d)
|
| 170 |
+
self.ff_norm = RMSNorm(E)
|
| 171 |
+
self.ff_in = nn.Linear(E, 4 * E, bias=False)
|
| 172 |
+
self.ff_out = nn.Linear(2 * E, E, bias=False)
|
| 173 |
|
| 174 |
def keys(self, ctx):
|
| 175 |
+
"""(k, v), each (B, H, n_ctx, d): context keys and values for this layer."""
|
| 176 |
+
B, n, _ = ctx.shape
|
| 177 |
k, v = self.kv_proj(self.attn_norm(ctx)).chunk(2, -1)
|
| 178 |
+
k = self.k_norm(k.view(B, n, self.H, self.d).transpose(1, 2))
|
| 179 |
+
v = v.view(B, n, self.H, self.d).transpose(1, 2)
|
| 180 |
+
return k, v
|
| 181 |
|
| 182 |
def forward(self, x, k, v, mask=None):
|
| 183 |
+
"""x (B, L, E) tokens attending to context k, v (B, H, n_ctx, d); optional mask (L, n_ctx)."""
|
| 184 |
+
B, L, E = x.shape
|
| 185 |
+
q = self.q_proj(self.attn_norm(x)).view(B, L, self.H, self.d).transpose(1, 2)
|
| 186 |
+
q = self.q_norm(q) * (math.log2(max(k.shape[2], 2)) / 8.0)
|
| 187 |
+
a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask).transpose(1, 2).reshape(B, L, E)
|
| 188 |
+
x = x + self.out_proj(a)
|
| 189 |
+
h, g = self.ff_in(self.ff_norm(x)).chunk(2, -1)
|
| 190 |
+
return x + self.ff_out(h * F.silu(g))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
|
| 193 |
def _arm_scales(T, Y, values, binary):
|
| 194 |
+
"""Standardize Y within each arm for binary treatments (over all context rows for continuous).
|
| 195 |
+
Returns (row_shift, row_scale) (B, n_ctx) and (shift, scale) (B, K)."""
|
|
|
|
| 196 |
mid = (T.amax(1, keepdim=True) + T.amin(1, keepdim=True)) / 2
|
| 197 |
+
treated, asked = (T > mid).float(), values > mid
|
| 198 |
|
| 199 |
def stats(w):
|
| 200 |
c = w.sum(1, keepdim=True)
|
| 201 |
m = (w * Y).sum(1, keepdim=True) / c.clamp(min=1)
|
| 202 |
+
s = ((w * (Y - m) ** 2).sum(1, keepdim=True) / c.clamp(min=1)).sqrt().clamp(min=1e-6)
|
| 203 |
return m, s, c > 0
|
| 204 |
|
| 205 |
m1, s1, has1 = stats(treated)
|
| 206 |
m0, s0, has0 = stats(1 - treated)
|
| 207 |
+
m1 = torch.where(has1, m1, m0)
|
| 208 |
+
s1 = torch.where(has1, s1, s0)
|
| 209 |
+
m0 = torch.where(has0, m0, m1)
|
| 210 |
+
s0 = torch.where(has0, s0, s1)
|
| 211 |
ma, sa, _ = stats(torch.ones_like(Y))
|
| 212 |
b = binary[:, None]
|
| 213 |
row_shift = torch.where(b, torch.where(treated > 0, m1, m0), ma)
|
|
|
|
| 217 |
return row_shift, row_scale, shift, scale
|
| 218 |
|
| 219 |
|
| 220 |
+
def _context_ranks(W_ctx, W_qry):
|
| 221 |
+
"""Within-column ranks in [-1, 1] for context and query rows, using the context distribution."""
|
| 222 |
+
B, n_ctx, P = W_ctx.shape
|
| 223 |
+
if P == 0:
|
| 224 |
+
return torch.zeros_like(W_ctx), torch.zeros_like(W_qry)
|
| 225 |
+
srt = W_ctx.transpose(1, 2).contiguous().sort(-1).values
|
| 226 |
+
|
| 227 |
+
def rank_of(W):
|
| 228 |
+
x = W.transpose(1, 2).contiguous()
|
| 229 |
+
lo = torch.searchsorted(srt, x, right=False)
|
| 230 |
+
hi = torch.searchsorted(srt, x, right=True)
|
| 231 |
+
r = (lo + hi - 1).float() / max(n_ctx - 1, 1) - 1.0
|
| 232 |
+
return r.clamp(-1.0, 1.0).transpose(1, 2)
|
| 233 |
+
|
| 234 |
+
return rank_of(W_ctx), rank_of(W_qry)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def _column_stats_and_corr(Wz_ctx, Tz_ctx, Yg_ctx, w_mask, Rk_ctx, binary):
|
| 238 |
+
"""Exact permutation-equivariant column statistics (B, P, N_COL_STATS) and covariate
|
| 239 |
+
correlation matrix R (B, P, P), computed strictly from context rows in float32.
|
| 240 |
+
Includes global, rank (Spearman), and arm-conditional (high-T vs low-T) correlations and
|
| 241 |
+
partial ridge slopes so treatment-effect modifiers are visible even under strong main effects."""
|
| 242 |
+
B, n, P = Wz_ctx.shape
|
| 243 |
+
device, dtype = Wz_ctx.device, Wz_ctx.dtype
|
| 244 |
+
if P == 0:
|
| 245 |
+
return (torch.zeros(B, 0, N_COL_STATS, device=device, dtype=dtype),
|
| 246 |
+
torch.zeros(B, 0, 0, device=device, dtype=dtype))
|
| 247 |
+
|
| 248 |
+
mask_f = w_mask.float()
|
| 249 |
+
W = Wz_ctx.float() * mask_f[:, None, :]
|
| 250 |
+
Rk = Rk_ctx.float() * mask_f[:, None, :]
|
| 251 |
+
T = Tz_ctx.float()
|
| 252 |
+
Y = Yg_ctx.float()
|
| 253 |
+
ones = torch.ones(B, n, 1, device=device)
|
| 254 |
+
|
| 255 |
+
# Covariate correlation matrix R_jk (B, P, P)
|
| 256 |
+
Wc = W - W.mean(1, keepdim=True)
|
| 257 |
+
Wn = Wc / Wc.pow(2).sum(1, keepdim=True).sqrt().clamp(min=1e-6)
|
| 258 |
+
R = torch.bmm(Wn.transpose(1, 2), Wn).clamp(-1.0, 1.0)
|
| 259 |
+
pair_mask = mask_f[:, :, None] * mask_f[:, None, :]
|
| 260 |
+
R = R * pair_mask
|
| 261 |
+
|
| 262 |
+
# Partial slopes of Y on [1, T, W, W * T] and T on [1, W] (algebraic invariants, as in axiom)
|
| 263 |
+
D_y = torch.cat([ones, T[..., None], W, W * T[..., None]], -1)
|
| 264 |
+
dy = D_y.shape[-1]
|
| 265 |
+
pen_y = torch.empty(dy, device=device)
|
| 266 |
+
pen_y[0], pen_y[1] = 1e-3 * n, 1e-2 * n
|
| 267 |
+
pen_y[2:2 + P] = 0.05 * n
|
| 268 |
+
pen_y[2 + P:] = 0.25 * n
|
| 269 |
+
G_y = torch.bmm(D_y.transpose(1, 2), D_y) + torch.diag(pen_y)[None]
|
| 270 |
+
beta_y = torch.linalg.solve(G_y, torch.bmm(D_y.transpose(1, 2), Y[..., None])).squeeze(-1)
|
| 271 |
+
bw, bwt = beta_y[:, 2:2 + P], beta_y[:, 2 + P:]
|
| 272 |
+
|
| 273 |
+
D_t = torch.cat([ones, W], -1)
|
| 274 |
+
pen_t = torch.full((1 + P,), 0.05 * n, device=device)
|
| 275 |
+
pen_t[0] = 1e-3 * n
|
| 276 |
+
G_t = torch.bmm(D_t.transpose(1, 2), D_t) + torch.diag(pen_t)[None]
|
| 277 |
+
beta_t = torch.linalg.solve(G_t, torch.bmm(D_t.transpose(1, 2), T[..., None])).squeeze(-1)[:, 1:]
|
| 278 |
+
|
| 279 |
+
# Arm split: exact treated vs control for binary, above vs below median T for continuous
|
| 280 |
+
mid = (T.amax(1, keepdim=True) + T.amin(1, keepdim=True)) / 2
|
| 281 |
+
med = T.median(1, keepdim=True).values
|
| 282 |
+
thresh = torch.where(binary[:, None], mid, med)
|
| 283 |
+
w_hi = (T > thresh).float()
|
| 284 |
+
w_lo = 1.0 - w_hi
|
| 285 |
+
|
| 286 |
+
def arm_ridge(arm_w):
|
| 287 |
+
cnt = arm_w.sum(1).clamp(min=1.0) # (B,)
|
| 288 |
+
Dw = D_t * arm_w[..., None]
|
| 289 |
+
G = torch.bmm(Dw.transpose(1, 2), D_t)
|
| 290 |
+
pen = torch.full((B, 1 + P), 0.05, device=device) * cnt[:, None]
|
| 291 |
+
pen[:, 0] = 1e-3 * cnt
|
| 292 |
+
G = G + torch.diag_embed(pen)
|
| 293 |
+
rhs = torch.bmm(Dw.transpose(1, 2), Y[..., None])
|
| 294 |
+
return torch.linalg.solve(G, rhs).squeeze(-1)[:, 1:] * mask_f
|
| 295 |
+
|
| 296 |
+
b_hi = arm_ridge(w_hi)
|
| 297 |
+
b_lo = arm_ridge(w_lo)
|
| 298 |
+
|
| 299 |
+
def wcorr(A, b, w=None):
|
| 300 |
+
if w is None:
|
| 301 |
+
ac, bc = A - A.mean(1, keepdim=True), b - b.mean(1, keepdim=True)
|
| 302 |
+
num = (ac * bc[..., None]).sum(1)
|
| 303 |
+
den = (ac.pow(2).sum(1) * bc.pow(2).sum(1, keepdim=True)).sqrt().clamp(min=1e-6)
|
| 304 |
+
else:
|
| 305 |
+
ws = w.sum(1, keepdim=True).clamp(min=1.0)
|
| 306 |
+
am = (w[..., None] * A).sum(1, keepdim=True) / ws[..., None]
|
| 307 |
+
bm = (w * b).sum(1, keepdim=True) / ws
|
| 308 |
+
ac, bc = A - am, b - bm
|
| 309 |
+
num = (w[..., None] * ac * bc[..., None]).sum(1)
|
| 310 |
+
den = ((w[..., None] * ac.pow(2)).sum(1) * (w * bc.pow(2)).sum(1, keepdim=True)).sqrt().clamp(min=1e-6)
|
| 311 |
+
return (num / den).clamp(-1.0, 1.0)
|
| 312 |
+
|
| 313 |
+
# Context rank of Y in [-1, 1] for Spearman rank correlation (robust to heavy tails / exp links)
|
| 314 |
+
y_srt = Y.sort(-1).values
|
| 315 |
+
y_lo = torch.searchsorted(y_srt, Y, right=False)
|
| 316 |
+
y_hi = torch.searchsorted(y_srt, Y, right=True)
|
| 317 |
+
y_rk = ((y_lo + y_hi - 1).float() / max(n - 1, 1) - 1.0).clamp(-1.0, 1.0)
|
| 318 |
+
|
| 319 |
+
W2 = W.pow(2).clamp(max=25.0)
|
| 320 |
+
c_hi = wcorr(W, Y, w_hi)
|
| 321 |
+
c_lo = wcorr(W, Y, w_lo)
|
| 322 |
+
c2_hi = wcorr(W2, Y, w_hi)
|
| 323 |
+
c2_lo = wcorr(W2, Y, w_lo)
|
| 324 |
+
|
| 325 |
+
stats = torch.stack([
|
| 326 |
+
wcorr(W, Y), wcorr(W, T),
|
| 327 |
+
wcorr(W2, Y),
|
| 328 |
+
wcorr((W * T[..., None]).clamp(-25.0, 25.0), Y),
|
| 329 |
+
wcorr(Rk, y_rk),
|
| 330 |
+
c_hi, c_lo, c_hi - c_lo, c2_hi - c2_lo,
|
| 331 |
+
torch.asinh(bw), torch.asinh(bwt), torch.asinh(beta_t),
|
| 332 |
+
torch.asinh(b_hi), torch.asinh(b_hi - b_lo),
|
| 333 |
+
], -1) * mask_f[..., None]
|
| 334 |
+
return stats.to(dtype), R.to(dtype)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
def release_tag():
|
| 338 |
+
"""The Hub tag of the weights released with this package version, or None when running from source."""
|
|
|
|
| 339 |
try:
|
| 340 |
return f"v{version('axiom-effect')}"
|
| 341 |
except PackageNotFoundError:
|
|
|
|
| 344 |
|
| 345 |
class AxiomEffect(nn.Module, PyTorchModelHubMixin, library_name="axiom-effect", repo_url=None,
|
| 346 |
tags=["causal-inference", "effect-estimation", "tabular"]):
|
| 347 |
+
"""Pure, from-scratch factorized tabular PFN for causal effect estimation."""
|
| 348 |
+
|
|
|
|
|
|
|
| 349 |
@classmethod
|
| 350 |
def from_pretrained(cls, pretrained_model_name_or_path, *, revision=None, strict=True, **kwargs):
|
| 351 |
path = str(pretrained_model_name_or_path)
|
|
|
|
| 358 |
f"not match this version of the code", stacklevel=2)
|
| 359 |
return super().from_pretrained(path, revision=revision, strict=strict, **kwargs)
|
| 360 |
|
| 361 |
+
def __init__(self, E=384, H=6, layers=12, col_dim=64, col_layers=2, row_slots=16,
|
| 362 |
+
nbins=NBINS, vmax=VMAX, sigma=SIGMA):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
super().__init__()
|
| 364 |
+
self.config = dict(architecture=ARCHITECTURE, E=E, H=H, layers=layers, col_dim=col_dim,
|
| 365 |
+
col_layers=col_layers, row_slots=row_slots, nbins=nbins, vmax=vmax, sigma=sigma)
|
| 366 |
+
# Stage 1: Column self-attention encoder
|
| 367 |
+
self.col_in = mlp(N_COL_STATS + N_FEATURES, col_dim, col_dim)
|
| 368 |
+
self.col_blocks = nn.ModuleList(ColBlock(col_dim, heads=4) for _ in range(col_layers))
|
| 369 |
+
self.col_norm = RMSNorm(col_dim)
|
| 370 |
+
# Stage 2: Multi-slot cross-attention row encoder
|
| 371 |
+
self.row_pool = RowPool(col_dim, E, slots=row_slots, heads=4)
|
| 372 |
+
# Stage 3: Row transformer
|
| 373 |
+
self.t_embed = mlp(2, E, E) # [standardized T, binary flag]
|
| 374 |
+
self.y_embed = nn.Linear(1, E) # standardized Y (arm-scaled for binary)
|
| 375 |
+
self.ctx_norm = RMSNorm(E)
|
| 376 |
+
self.qry_norm = RMSNorm(E)
|
| 377 |
+
self.blocks = nn.ModuleList(Block(E, H) for _ in range(layers))
|
| 378 |
+
# Stage 4: Direct HL-Gauss head + detached width head
|
| 379 |
+
self.head_norm = RMSNorm(E)
|
| 380 |
+
self.head = nn.Sequential(nn.Linear(E, 2 * E, bias=False), nn.GELU(),
|
| 381 |
+
nn.Linear(2 * E, nbins, bias=False))
|
| 382 |
self.widths = mlp(2 + 4 * E + 3, E, len(QUANTILES) - 1)
|
| 383 |
edges = torch.linspace(-vmax, vmax, nbins + 1)
|
|
|
|
| 384 |
self.register_buffer("edges", edges, persistent=False)
|
| 385 |
self.register_buffer("centers", (edges[1:] + edges[:-1]) / 2, persistent=False)
|
| 386 |
+
self.recompute = False
|
| 387 |
|
| 388 |
def _run(self, fn, *args):
|
| 389 |
if self.recompute and self.training and torch.is_grad_enabled():
|
| 390 |
return checkpoint(fn, *args, use_reentrant=False)
|
| 391 |
return fn(*args)
|
| 392 |
|
| 393 |
+
def _encode_columns(self, col_stats, features, R, w_mask):
|
| 394 |
+
if col_stats.shape[1] == 0:
|
| 395 |
+
return torch.zeros(col_stats.shape[0], 0, self.config["col_dim"],
|
| 396 |
+
device=col_stats.device, dtype=col_stats.dtype)
|
| 397 |
+
c = self.col_in(torch.cat([col_stats, features], -1)) * w_mask[..., None].to(col_stats.dtype)
|
| 398 |
+
for blk in self.col_blocks:
|
| 399 |
+
c = blk(c, R, w_mask)
|
| 400 |
+
return self.col_norm(c) * w_mask[..., None].to(col_stats.dtype)
|
| 401 |
+
|
| 402 |
+
def _embed_t(self, t_vals, binary):
|
| 403 |
+
"""t_vals (B, L) -> (B, L, E)."""
|
| 404 |
+
b = binary.to(t_vals.dtype)[:, None].expand_as(t_vals)
|
| 405 |
+
return self.t_embed(torch.stack([t_vals, b], -1))
|
| 406 |
+
|
| 407 |
+
def forward(self, W, T, Y, w_mask, features, binary, values, n_ctx=None, W_qry=None,
|
| 408 |
+
chunk=None, self_mask=True):
|
| 409 |
+
"""
|
| 410 |
+
W (B, n, P), T (B, n), Y (B, n): context (and, when n_ctx is None and W_qry is None, query) rows.
|
| 411 |
+
w_mask (B, P): True for real covariates (False for batch padding).
|
| 412 |
+
features (B, P, N_FEATURES): [graph_given, 4 role indicators].
|
| 413 |
+
binary (B,) bool: treatment type per table.
|
| 414 |
+
values (B, K): treatment values to evaluate mu at (on T's scale).
|
| 415 |
+
n_ctx: if given (training), first n_ctx rows are context and remaining rows are queries.
|
| 416 |
+
W_qry: if given (localized inference), explicit (B, n_qry, P) query covariates.
|
| 417 |
+
self_mask: when predicting on the same table (n_ctx is None and W_qry is None), mask each
|
| 418 |
+
query row from attending to its own context token.
|
| 419 |
+
"""
|
| 420 |
B, n, P = W.shape
|
|
|
|
|
|
|
| 421 |
E, K = self.config["E"], values.shape[1]
|
| 422 |
binary = torch.as_tensor(binary, dtype=torch.bool, device=W.device)
|
| 423 |
+
|
| 424 |
+
same_table = W_qry is None and n_ctx is None
|
| 425 |
+
if W_qry is not None:
|
| 426 |
+
W_ctx, T_ctx, Y_ctx = W, T, Y
|
| 427 |
+
elif n_ctx is not None:
|
| 428 |
+
W_ctx, T_ctx, Y_ctx = W[:, :n_ctx], T[:, :n_ctx], Y[:, :n_ctx]
|
| 429 |
+
W_qry = W[:, n_ctx:]
|
| 430 |
+
else:
|
| 431 |
+
W_ctx, T_ctx, Y_ctx, W_qry = W, T, Y, W
|
| 432 |
+
|
| 433 |
+
n_c, n_q = W_ctx.shape[1], W_qry.shape[1]
|
| 434 |
+
|
| 435 |
+
# Standardize W, T, Y strictly from context rows
|
| 436 |
+
if P > 0:
|
| 437 |
+
w_mean = W_ctx.mean(1, keepdim=True)
|
| 438 |
+
w_sd = W_ctx.std(1, keepdim=True, unbiased=False).clamp(min=1e-6)
|
| 439 |
+
Wz_ctx = ((W_ctx - w_mean) / w_sd).clamp(-CLIP_SIGMA, CLIP_SIGMA) * w_mask[:, None].to(W.dtype)
|
| 440 |
+
Wz_qry = ((W_qry - w_mean) / w_sd).clamp(-CLIP_SIGMA, CLIP_SIGMA) * w_mask[:, None].to(W.dtype)
|
| 441 |
+
else:
|
| 442 |
+
Wz_ctx, Wz_qry = W_ctx, W_qry
|
| 443 |
+
|
| 444 |
+
t_mean = T_ctx.mean(1, keepdim=True)
|
| 445 |
+
t_sd = T_ctx.std(1, keepdim=True, unbiased=False).clamp(min=1e-6)
|
| 446 |
+
Tz_ctx = ((T_ctx - t_mean) / t_sd).clamp(-CLIP_SIGMA, CLIP_SIGMA)
|
| 447 |
+
Vz = ((values - t_mean) / t_sd).clamp(-CLIP_SIGMA, CLIP_SIGMA)
|
| 448 |
+
|
| 449 |
+
y_gmean = Y_ctx.mean(1, keepdim=True)
|
| 450 |
+
y_gsd = Y_ctx.std(1, keepdim=True, unbiased=False).clamp(min=1e-6)
|
| 451 |
+
Yg_ctx = ((Y_ctx - y_gmean) / y_gsd).clamp(-CLIP_SIGMA, CLIP_SIGMA)
|
| 452 |
+
row_shift, row_scale, shift, scale = _arm_scales(T_ctx, Y_ctx, values, binary)
|
| 453 |
+
Yz_ctx = ((Y_ctx - row_shift) / row_scale).clamp(-CLIP_SIGMA, CLIP_SIGMA)
|
| 454 |
+
|
| 455 |
+
# Stage 1: Column self-attention over exact context statistics + correlation matrix R_jk
|
| 456 |
+
Rk_ctx, Rk_qry = _context_ranks(Wz_ctx, Wz_qry)
|
| 457 |
+
col_stats, R = _column_stats_and_corr(Wz_ctx, Tz_ctx, Yg_ctx, w_mask, Rk_ctx, binary)
|
| 458 |
+
col_emb = self._encode_columns(col_stats, features, R, w_mask)
|
| 459 |
+
|
| 460 |
+
# Stage 2: Multi-slot cross-attention row encoder
|
| 461 |
+
x_ctx = self._run(self.row_pool, Wz_ctx, Rk_ctx, col_emb, w_mask)
|
| 462 |
+
x_qry = x_ctx if same_table else self._run(self.row_pool, Wz_qry, Rk_qry, col_emb, w_mask)
|
| 463 |
+
|
| 464 |
+
# Stage 3: Row transformer (context self-attention, then query cross-attention)
|
| 465 |
+
ctx = self.ctx_norm(x_ctx + self._embed_t(Tz_ctx, binary) + self.y_embed(Yz_ctx[..., None]))
|
| 466 |
+
|
| 467 |
+
def ctx_step(h, blk):
|
| 468 |
+
k, v = blk.keys(h)
|
| 469 |
+
return blk(h, k, v), k, v
|
| 470 |
|
| 471 |
kvs = []
|
| 472 |
+
for blk in self.blocks:
|
| 473 |
+
ctx, k, v = self._run(ctx_step, ctx, blk)
|
| 474 |
kvs.append((k, v))
|
| 475 |
|
| 476 |
+
t_val_emb = self._embed_t(Vz, binary) # (B, K, E)
|
| 477 |
+
step = max(1, chunk // K) if chunk else n_q
|
|
|
|
| 478 |
out = []
|
| 479 |
+
for s in range(0, n_q, step):
|
| 480 |
+
xs = x_qry[:, s:s + step]
|
| 481 |
Q = xs.shape[1]
|
| 482 |
+
q = self.qry_norm(xs[:, None] + t_val_emb[:, :, None]).reshape(B, K * Q, E)
|
| 483 |
mask = None
|
| 484 |
+
if same_table and self_mask and n_c > 1:
|
| 485 |
+
mask = torch.zeros(Q, n_c, dtype=q.dtype, device=W.device)
|
| 486 |
+
mask[torch.arange(Q, device=W.device), torch.arange(s, s + Q, device=W.device)] = float("-inf")
|
| 487 |
+
mask = mask.repeat(K, 1)
|
| 488 |
+
for blk, (k, v) in zip(self.blocks, kvs):
|
| 489 |
+
q = self._run(blk, q, k, v, mask)
|
| 490 |
+
out.append(q.view(B, K, Q, E))
|
| 491 |
+
q = torch.cat(out, 2) # (B, K, n_q, E)
|
| 492 |
+
|
| 493 |
+
# Stage 4: Direct HL-Gauss outcome distribution
|
| 494 |
+
q_norm = self.head_norm(q)
|
| 495 |
+
logits = self.head(q_norm) # (B, K, n_q, nbins)
|
| 496 |
+
bin_mean = (logits.softmax(-1) * self.centers).sum(-1)
|
| 497 |
+
mu = shift[..., None] + scale[..., None] * bin_mean
|
| 498 |
+
return Rows(q_norm.mean(1), self.head_norm(ctx).mean(1), mu, logits, shift, scale, values, binary)
|
| 499 |
|
| 500 |
def mu_nll(self, rows, target):
|
| 501 |
+
"""(B, K, n_qry) HL-Gauss cross-entropy against target on the arm's standardized scale."""
|
|
|
|
|
|
|
|
|
|
| 502 |
p = self._hl_target(rows, target)
|
| 503 |
return -(p * rows.logits.log_softmax(-1)).sum(-1)
|
| 504 |
|
| 505 |
def mu_floor(self, rows, target):
|
| 506 |
+
"""(B, K, n_qry) entropy of the HL-Gauss target: the loss of a perfect prediction."""
|
|
|
|
| 507 |
p = self._hl_target(rows, target)
|
| 508 |
return -torch.special.xlogy(p, p).sum(-1)
|
| 509 |
|
| 510 |
def _hl_target(self, rows, target):
|
|
|
|
|
|
|
| 511 |
t = ((target - rows.shift[..., None]) / rows.scale[..., None]).clamp(-self.config["vmax"], self.config["vmax"])
|
| 512 |
p = torch.special.ndtr((self.edges - t[..., None]) / self.config["sigma"]).diff(dim=-1)
|
| 513 |
return p / (p.sum(-1, keepdim=True) + 1e-8)
|
| 514 |
|
| 515 |
def estimands(self, rows, pairs, weights):
|
| 516 |
+
"""Quantiles (B, S, len(QUANTILES)) of S average effects, detached from the main network.
|
| 517 |
+
Antisymmetric (a -> b is minus b -> a) and exactly 0 for a -> a."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 518 |
i, j = pairs[:, 0], pairs[:, 1]
|
| 519 |
mu, query, context = rows.mu.detach(), rows.query.detach(), rows.context.detach()
|
| 520 |
w = weights.float()
|
| 521 |
+
tot = w.sum(-1).clamp(min=1e-6)
|
| 522 |
n = w.shape[-1]
|
| 523 |
+
phi = self._embed_t(rows.values, rows.binary).detach()
|
| 524 |
+
pooled = (w[..., None] * query[:, None]).sum(2) / tot[..., None]
|
| 525 |
context = context[:, None].expand_as(pooled)
|
| 526 |
|
| 527 |
def one_way(a, b):
|
| 528 |
+
d = mu[:, b] - mu[:, a]
|
| 529 |
est = (w * d).sum(-1) / tot
|
| 530 |
+
spread = ((w * (d - est[..., None]) ** 2).sum(-1) / tot).clamp(min=0).sqrt()
|
| 531 |
feats = torch.cat([est[..., None], spread[..., None], pooled, context, phi[:, a], phi[:, b],
|
| 532 |
+
(torch.log(tot) / math.log(N_REF))[..., None], (tot / n)[..., None],
|
| 533 |
rows.binary.float()[:, None, None].expand_as(est[..., None])], -1)
|
| 534 |
+
moved = (rows.values[:, a] != rows.values[:, b]).float()[..., None]
|
| 535 |
steps = F.softplus(self.widths(feats)) * moved
|
| 536 |
lower = est[..., None] - steps[..., :MID].flip(-1).cumsum(-1).flip(-1)
|
| 537 |
upper = est[..., None] + steps[..., MID:].cumsum(-1)
|
|
|
|
| 539 |
|
| 540 |
return (one_way(i, j) - one_way(j, i).flip(-1)) / 2
|
| 541 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 542 |
@torch.no_grad()
|
| 543 |
+
def predict(self, W, T, Y, features, binary, values, estimands=(), chunk=4096, W_qry=None, tta=1, seed=0):
|
| 544 |
+
"""One standardized table, as numpy: W (n_ctx, p), T and Y (n_ctx,), features (p, N_FEATURES),
|
| 545 |
+
binary, values (K,), estimands [(a, b, rows)], optional W_qry (n_qry, p).
|
| 546 |
+
Deterministic (no random column codes); `tta` and `seed` kept for API compatibility."""
|
|
|
|
| 547 |
device = next(self.parameters()).device
|
| 548 |
f = lambda a: torch.as_tensor(np.asarray(a, dtype=np.float32), device=device)[None]
|
| 549 |
W = np.asarray(W, dtype=np.float32).reshape(len(T), -1)
|
| 550 |
+
P = W.shape[1]
|
| 551 |
+
Wq_t = f(np.asarray(W_qry, dtype=np.float32).reshape(-1, P)) if W_qry is not None else None
|
| 552 |
with eval_mode(self):
|
| 553 |
+
rows = self(f(W), f(T), f(Y), torch.ones(1, P, dtype=torch.bool, device=device),
|
| 554 |
+
f(np.asarray(features, dtype=np.float32).reshape(P, N_FEATURES)),
|
| 555 |
+
torch.tensor([bool(binary)], device=device), f(values), W_qry=Wq_t, chunk=chunk)
|
| 556 |
out = {"mu": rows.mu[0].cpu().numpy()}
|
| 557 |
if estimands:
|
| 558 |
pairs = torch.tensor([[a, b] for a, b, _ in estimands], device=device)
|
| 559 |
weights = f(np.stack([np.asarray(r, dtype=np.float32) for _, _, r in estimands]))
|
| 560 |
out["quantiles"] = self.estimands(rows, pairs, weights)[0].cpu().numpy()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 561 |
return out
|
| 562 |
|
| 563 |
def effect(self, data, treatment, outcome, **kwargs):
|
|
|
|
| 565 |
`axiom_effect.inference.effect(self, ...)`, which see."""
|
| 566 |
from .inference import effect
|
| 567 |
return effect(self, data, treatment, outcome, **kwargs)
|
|
|
|
|
|
|
|
|