Release 0.0.1
Browse filesFiles changed (10)
- LICENSEAdded+202
- README.mdAdded+142
- config.jsonAdded+28
- model.safetensorsAdded+3
- pyproject.tomlAdded+21
- src/axiom_effect/__init__.pyAdded+14
- src/axiom_effect/blocks.pyAdded+57
- src/axiom_effect/graph.pyAdded+47
- src/axiom_effect/inference.pyAdded+278
- src/axiom_effect/model.pyAdded+413
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142---library_name: axiom-effecttags:- causal-inference- effect-estimation- tabular- pytorchlicense: apache-2.0---
# AxiomEffect
Causal effect estimation for tabular data. Given a table, its causal graph and a treatment /outcome pair, AxiomEffect estimates what happens to the outcome when the treatment is *set*to one value instead of another, E[Y | do(T = b)] - E[Y | do(T = a)], with 90% and 50%intervals, and the whole dose-response curve. It is trained on simulated causal models,where the true effect is known.
> **Version 0.0.1 is experimental.** The API and the weights will change in 0.0.x> releases. Check its answers against what you know about your data.
The graph decides what to adjust for: the model reads only the treatment, the outcome andthe graph's optimal adjustment set, so mediators, colliders and other variables that wouldbias the answer never enter. The graph can come from domain knowledge or from[Axiom](https://huggingface.co/maxpagels/axiom-discovery), the causal discovery model this is asibling of.
6.5M parameters, fp32 safetensors (26 MB). Project page:[maxpagels.com/axiom](https://maxpagels.com/axiom).
## Recommended use (ballpark)
| | recommendation ||---|---|| 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. || treatment | continuous: at least 20 distinct values. Binary and categorical treatments are not supported yet. || 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. || 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. || adjustment set | up to 18 variables, as in training (the table itself can have more columns: only the adjustment set is read). || missing values | not supported in the treatment, the outcome and the adjustment set; other columns may have them. |
## Usage
```bashpip install "git+https://huggingface.co/maxpagels/axiom-effect"```
```pythonfrom axiom_effect import AxiomEffect
model = AxiomEffect.from_pretrained("maxpagels/axiom-effect")
graph = [("age", "price"), ("age", "sales"), ("price", "visits"), ("visits", "sales")]r = model.effect(df, graph, treatment="price", outcome="sales")print(r)```
For example, on a simulated table:
```Effect of price on sales (800 rows; adjusted for age) price 29.74 -> 36.89: -10.14 90% [-12.53, -7.738] 50% [-10.99, -9.248] dose-response, from price = 33.36: 26.28 +9.224 90% [5.852, 12.66] 29.74 +5.172 90% [3.908, 6.547] 33.36 +0 90% [-0.8777, 0.8777] 36.89 -4.971 90% [-6.539, -3.388] 40.34 -9.736 90% [-13.38, -6.002]```
Everything is in the data's own units: the treatment values in the treatment's, the effectsin the outcome's (`effect` standardizes the columns it reads, as in training, and convertsback). The graph can be:
- a list of (cause, effect) column-name pairs, as above;- a (d, d) adjacency matrix in the table's column order (`A[i, j] = 1` means i -> j);- a pandas DataFrame adjacency matrix with the column names as index and columns;- a `discover()` result from Axiom: its directed edges.
```pythonfrom axiom import Axiom
g = Axiom.from_pretrained("maxpagels/axiom-discovery").discover(df)r = model.effect(df, g, treatment="price", outcome="sales")```
A discovered graph is only as good as its edges. Undirected or confounded relations nearthe treatment or outcome are ignored with a warning, and if the discovered graph has nodirected path from the treatment to the outcome the effect is exactly 0, with a warningtoo: one wrong edge is enough for that.
### Reading the result
```pythonr.estimate # the headline contrast: moving the treatment from its 25% to its 75% quantiler.contrast # those two treatment values, (a, b)r.interval # 90% interval of the contrast; r.interval50 the 50% oner.adjustment # the variables adjusted forr.to_frame() # the dose-response curve: each value's effect from the reference, with intervals```
| argument | default | meaning ||---|---|---|| `contrast=(a, b)` | the 25% and 75% quantiles | the headline effect: moving the treatment from a to b || `values` | the 10/25/50/75/90% quantiles | treatment values on the dose-response curve || `reference` | the median | where the curve starts (its effect is 0) |
The curve's intervals are pointwise, not simultaneous. The intervals are the model's ownquantiles, conformally calibrated on held-out simulated data from its trainingdistribution. How well they cover on real data is not yet known.
If the graph has no directed path from the treatment to the outcome, setting the treatmentcannot move the outcome: the effect is exactly 0, with a zero-width interval, whatevertheir correlation (`r.zero_by_graph`).
## Limitations
- The graph is taken as true. A missing confounder or a reversed edge biases the answer, and the interval does not widen for it.- No hidden confounders: front-door, instrumental-variable and other identification strategies beyond adjustment are not supported, and the model never says "not identifiable".- Continuous treatments only; average effects only (no per-row or conditional effects).- Trained and validated on simulated data only: no evaluation on real data yet.- Where the adjustment set nearly determines the treatment (poor overlap), and on purely linear data, classical estimators can be more accurate.
## Versions
Each release is a tagged commit in this repo; `main` is the latest. The package loads theweights released with it, so code and weights always match. To use a specific release,install its code and load its weights by tag:
```bashpip install "git+https://huggingface.co/maxpagels/axiom-effect@v0.0.1"```
```pythonmodel = AxiomEffect.from_pretrained("maxpagels/axiom-effect") # this package's release: v0.0.1```
- **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.12345678910111213141516171819202122232425262728{ "E": 192, "H": 8, "calibration": { "by_n": false, "inner": [ 1.1984461545944214, 1.1984461545944214 ], "n": [ 256, 1024 ], "outer": [ 1.168336033821106, 1.168336033821106 ], "pairs": "contrast", "seed": 1, "tasks": 750 }, "context_layers": 6, "doubly_robust": true, "inducing": 64, "positivity": true, "query_layers": 4, "row_layers": 2}123version https://git-lfs.github.com/spec/v1oid sha256:b4d3d26a3c247f48ef0f8cd1e54d32465c79a021123180cec12b96a424c1e5b8size 26148328123456789101112131415161718192021[project]name = "axiom-effect"version = "0.0.1"description = "AxiomEffect: causal effect estimation from a table and its causal graph"readme = "README.md"authors = [{ name = "Max Pagels" }]requires-python = ">=3.11"license = "Apache-2.0"license-files = ["LICENSE"]dependencies = ["huggingface-hub>=2.1", "numpy>=2.0", "safetensors>=0.4", "torch>=2.4"]
[project.urls]Homepage = "https://maxpagels.com/axiom"Repository = "https://huggingface.co/maxpagels/axiom-effect"
[build-system]requires = ["uv_build>=0.12.18,<0.13.0"]build-backend = "uv_build"
[tool.uv.build-backend]module-name = "axiom_effect"1234567891011121314"""AxiomEffect: causal effect estimation from a table and its causal graph.
from axiom_effect import AxiomEffect model = AxiomEffect.from_pretrained("path/or/hub-repo") print(model.effect(df, graph, treatment="price", outcome="sales"))
See axiom_effect.inference (the table-level call) and axiom_effect.model (the network);trained and benchmarked from the axiom repository (train_effect.py)."""from .graph import causal_nodes, descendants, is_dag, optimal_adjustmentfrom .inference import TRAIN_N, EffectResult, effectfrom .model import INTERVALS, MID, QUANTILES, AxiomEffect, calibrate, calibration_factors, release_tag
__all__ = ["AxiomEffect", "EffectResult", "effect", "TRAIN_N", "QUANTILES", "MID", "INTERVALS", "calibrate", "calibration_factors", "release_tag", "descendants", "is_dag", "causal_nodes", "optimal_adjustment"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657"""Network building blocks, the same as Axiom's (axiom.model), copied so that axiom-effectdoes not depend on axiom-discovery's internals. Keep the attribute names: they are the weights'names in every checkpoint."""from contextlib import contextmanager
import torchimport torch.nn as nn
def mlp(i, h, o): return nn.Sequential(nn.Linear(i, h), nn.GELU(), nn.Linear(h, o))
class Attention(nn.Module): """Pre-norm residual self-attention over the middle axis of (N, L, E). With `inducing` > 0 the tokens attend through that many learned inducing points (as in Set Transformer's ISAB): cost O(L * inducing) instead of O(L^2), so L can be large. `mask` (N, L), True = padding: those tokens are updated but not attended to (a sequence with every token masked attends to all of them, to stay finite).""" def __init__(self, E, H, inducing=0): super().__init__() self.norm = nn.LayerNorm(E) self.attn = nn.MultiheadAttention(E, H, batch_first=True) self.points = nn.Parameter(torch.randn(inducing, E) / E ** 0.5) if inducing else None self.gather = nn.MultiheadAttention(E, H, batch_first=True) if inducing else None
def forward(self, x, mask=None): h = self.norm(x) if mask is not None: mask = mask & ~mask.all(1, keepdim=True) if self.points is None: return x + self.attn(h, h, h, key_padding_mask=mask, need_weights=False)[0] p = self.points.expand(x.shape[0], -1, -1) s = self.gather(p, h, h, key_padding_mask=mask, need_weights=False)[0] # summarize the tokens return x + self.attn(h, s, s, need_weights=False)[0] # every token reads the summary
class FeedForward(nn.Module): """Pre-norm residual MLP over the last axis.""" def __init__(self, E, mult=4): super().__init__() self.norm = nn.LayerNorm(E) self.net = mlp(E, mult * E, E)
def forward(self, x): return x + self.net(self.norm(x))
@contextmanagerdef eval_mode(model): """The model in eval mode inside the block, then back in whichever mode it was in.""" was_training = model.training model.eval() try: yield model finally: model.train(was_training)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""The graph logic of causal effects: which variables a DAG says to adjust for.A[i, j] = 1 means i -> j throughout."""import numpy as np
def descendants(A, t): """The variables t reaches along directed edges of A (t itself excluded), sorted. descendants(A.T, t) gives the ancestors.""" seen, stack = set(), [t] while stack: for c in np.flatnonzero(A[stack.pop()]): if c not in seen: seen.add(int(c)) stack.append(c) return sorted(seen)
def is_dag(A): """Whether A has no directed cycle (Kahn's algorithm: peel off variables without parents until none are left, or a cycle blocks the rest).""" A = (np.asarray(A) != 0).astype(np.int64) indegree, ready, seen = A.sum(0), [v for v in range(len(A)) if A[:, v].sum() == 0], 0 while ready: v = ready.pop() seen += 1 for c in np.flatnonzero(A[v]): indegree[c] -= 1 if indegree[c] == 0: ready.append(int(c)) return seen == len(A)
def causal_nodes(A, t, y): """The variables on directed paths from t to y: y and the mediators (t excluded).""" ancestors_of_y = set(descendants(A.T, y)) return {v for v in descendants(A, t) if v == y or v in ancestors_of_y}
def optimal_adjustment(A, t, y): """The optimal adjustment set O(t, y) of a DAG without hidden variables (Henckel, Perkovic & Maathuis, 2022): the valid set with the smallest asymptotic variance. It is pa(cn) minus forb, with cn = causal_nodes(A, t, y) and forb = t, cn and everything downstream of cn; in effect, the parents of the outcome and of the mediators, minus anything t causes.""" cn = causal_nodes(A, t, y) forb = {t} | cn | {w for v in cn for w in descendants(A, v)} return sorted({int(p) for v in cn for p in np.flatnonzero(A[:, v])} - forb)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278"""Run a trained AxiomEffect on a real table: column names, the graph in any of the usualforms, the original units in and out, the training range checked, and a readable result.
from axiom_effect import AxiomEffect model = AxiomEffect.from_pretrained("path/or/hub-repo") r = model.effect(df, graph, treatment="price", outcome="sales") print(r) # the 25%-to-75% contrast and the dose-response curve r.estimate, r.interval # the contrast and its 90% interval, in units of sales r.to_frame() # the curve as a DataFrame
`graph` is the causal graph over the table's columns: a (d, d) adjacency matrix in thecolumn order (A[i, j] = 1 means i -> j), a pandas DataFrame with the column names as indexand columns, a list of (cause, effect) name pairs, or a `discover()` result of axiom-discovery(its directed edges). The graph is taken as true: a DAG, no hidden confounders."""import warningsfrom dataclasses import dataclass
import numpy as np
from .graph import descendants, is_dag, optimal_adjustmentfrom .model import INTERVALS, MID, QUANTILES
# The range the released model was trained on (train_effect.py); outside it, extrapolation.TRAIN_N = (128, 1024) # rows; larger tables are split into subsets of TRAIN_N[1]TRAIN_ADJUST = 18 # variables in the adjustment set (tables of 3-20 variables)TRAIN_LEVELS = (0.02, 0.98) # treatment values were asked about between these quantilesMIN_LEVELS = 20 # distinct treatment values below which it counts as discreteCURVE_LEVELS = (0.1, 0.25, 0.5, 0.75, 0.9) # default dose-response values: these quantilesCONTRAST_LEVELS = (0.25, 0.75) # default contrast: from the first to the second
@dataclass(repr=False)class EffectResult: """Result of `effect`, in the outcome's units throughout.
The contrast: `estimate` is E[Y | do(T = b)] - E[Y | do(T = a)] for (a, b) = `contrast`, with its 90% `interval` and 50% `interval50`. The dose-response curve: for each treatment value in `values`, the effect of moving the treatment from `reference` to it (`curve[k]` holds the QUANTILES of that effect; 0 at the reference), pointwise intervals.
`adjustment` is the set the graph says to adjust for (the optimal one), the only columns besides the treatment and outcome the model reads. `zero_by_graph` means the graph has no directed path from the treatment to the outcome, so every effect is exactly 0, whatever their association. `n_rows` is the rows behind each estimate (tables over TRAIN_N[1] rows are split into `n_subsets` subsets of that many and the quantiles averaged, so intervals are those of TRAIN_N[1] rows: conservative).""" treatment: str outcome: str adjustment: list zero_by_graph: bool contrast: tuple contrast_quantiles: np.ndarray # (len(QUANTILES),) reference: float values: np.ndarray # (K,) curve: np.ndarray # (K, len(QUANTILES)) n_rows: int n_subsets: int
@property def estimate(self): return float(self.contrast_quantiles[MID])
@property def interval(self): lo, hi = (QUANTILES.index(p) for p in INTERVALS["outer"]) return float(self.contrast_quantiles[lo]), float(self.contrast_quantiles[hi])
@property def interval50(self): lo, hi = (QUANTILES.index(p) for p in INTERVALS["inner"]) return float(self.contrast_quantiles[lo]), float(self.contrast_quantiles[hi])
def to_frame(self): """pandas DataFrame of the curve: value, effect (from the reference), and the 90% and 50% interval bounds.""" import pandas as pd o, i = ([QUANTILES.index(p) for p in INTERVALS[k]] for k in ("outer", "inner")) c = self.curve return pd.DataFrame({self.treatment: self.values, "effect": c[:, MID], "lo90": c[:, o[0]], "lo50": c[:, i[0]], "hi50": c[:, i[1]], "hi90": c[:, o[1]]})
def __repr__(self): g = lambda x: f"{x:.4g}" adj = ", ".join(self.adjustment) if self.adjustment else "nothing" rows = f"{self.n_rows} rows" + (f" x {self.n_subsets} subsets" if self.n_subsets > 1 else "") head = f"Effect of {self.treatment} on {self.outcome} ({rows}; adjusted for {adj})" if self.zero_by_graph: return head + f"\n 0: the graph has no directed path from {self.treatment} to {self.outcome}" (lo, hi), (lo50, hi50) = self.interval, self.interval50 a, b = self.contrast lines = [head, f" {self.treatment} {g(a)} -> {g(b)}: {self.estimate:+.4g} " f"90% [{g(lo)}, {g(hi)}] 50% [{g(lo50)}, {g(hi50)}]", f" dose-response, from {self.treatment} = {g(self.reference)}:"] o = [QUANTILES.index(p) for p in INTERVALS["outer"]] w = max(len(g(v)) for v in self.values) lines += [f" {g(v):>{w}} {q[MID]:+.4g} 90% [{g(q[o[0]])}, {g(q[o[1]])}]" for v, q in zip(self.values, self.curve)] return "\n".join(lines)
def _table(data, names): """(n, d) float64 values and column names from a DataFrame or an array.""" if hasattr(data, "columns") and hasattr(data, "to_numpy"): names = list(map(str, data.columns)) if names is None else list(names) data = data.to_numpy(dtype=np.float64, na_value=np.nan) X = np.asarray(data, dtype=np.float64) if X.ndim != 2 or X.shape[1] < 2: raise ValueError(f"expected an (n, d) table with d >= 2, got shape {X.shape}") names = [f"X{k + 1}" for k in range(X.shape[1])] if names is None else list(map(str, names)) if len(names) != X.shape[1] or len(set(names)) != len(names): raise ValueError(f"need {X.shape[1]} distinct column names; got {names}") return X, names
def _adjacency(graph, names): """(d, d) 0/1 adjacency in the table's column order, from any accepted graph form, and the relations of a discover() result that the DAG cannot express: [(a, b, kind)].""" d, index = len(names), {name: k for k, name in enumerate(names)}
def reorder(A, graph_names): graph_names = list(map(str, graph_names)) if sorted(graph_names) != sorted(names): raise ValueError(f"the graph's variables {graph_names} are not the table's columns {names}") p = [graph_names.index(name) for name in names] return np.asarray(A)[np.ix_(p, p)]
other = [] if hasattr(graph, "directed") and hasattr(graph, "names"): # axiom's CausalGraph A = reorder(graph.directed, graph.names) for kind in ("undirected", "confounded"): M = getattr(graph, kind, None) if M is not None: M = reorder(M, graph.names) other += [(names[i], names[j], kind) for i, j in zip(*np.nonzero(np.triu(M, 1)))] elif hasattr(graph, "columns") and hasattr(graph, "index"): # adjacency DataFrame if list(map(str, graph.index)) != list(map(str, graph.columns)): raise ValueError("an adjacency DataFrame needs the same variables, in the same order, as index and columns") A = reorder(graph.to_numpy(), graph.columns) elif isinstance(graph, (list, tuple)) and all( isinstance(e, (list, tuple)) and len(e) == 2 and all(isinstance(v, str) for v in e) for e in graph): A = np.zeros((d, d), dtype=np.int64) # edge list: (cause, effect) names for a, b in graph: for v in (a, b): if v not in index: raise ValueError(f"edge ({a!r}, {b!r}): {v!r} is not a column; columns are {names}") A[index[a], index[b]] = 1 else: A = np.asarray(graph) if A.shape != (d, d): raise ValueError(f"a {d}-column table needs a ({d}, {d}) adjacency matrix; got shape {A.shape}") A = (np.asarray(A, dtype=float) != 0).astype(np.int64) if np.any(np.diag(A)): raise ValueError("the graph has a self-loop") if not is_dag(A): raise ValueError("the graph has a directed cycle; the effect model needs a DAG") return A, other
def _column(v, names, what): if isinstance(v, (int, np.integer)) and not isinstance(v, bool): if not 0 <= v < len(names): raise ValueError(f"{what} index {v} is out of range for {len(names)} columns") return int(v) if str(v) not in names: raise ValueError(f"{what} {v!r} is not a column; columns are {names}") return names.index(str(v))
def effect(model, data, graph, treatment, outcome, values=None, reference=None, contrast=None, names=None, extrapolate=False, n_subsets=8, seed=0): """The causal effect of `treatment` on `outcome` (column names, or indices), from a table and its causal graph (module docstring), in the outcome's units.
values: treatment values for the dose-response curve (default: its 10/25/50/75/90% quantiles); reference: the value the curve starts from (default: the median); contrast: (a, b), the headline effect of moving the treatment from a to b (default: its 25% and 75% quantiles). All in the treatment's units. extrapolate: allow treatment values outside its 2-98% quantiles (warned instead of refused): the model was never asked about them, and the data hardly has them.
Refused: missing values in the treatment, the outcome or the adjustment set; a constant treatment or outcome; a discrete one (fewer than 20 distinct values: version 0.0.x is for continuous treatments). Warned: fewer rows than the training range, an adjustment set larger than in training, and relations of a discover() result that a DAG cannot express (undirected, confounded) near the treatment or outcome, which are ignored; and an exact 0 from a discover() result (no directed path), which one wrong edge can cause.""" X, names = _table(data, names) A, other = _adjacency(graph, names) t, y = _column(treatment, names, "treatment"), _column(outcome, names, "outcome") if t == y: raise ValueError("treatment and outcome are the same column") W = optimal_adjustment(A, t, y) used = [t, y] + W if not np.isfinite(X[:, used]).all(): bad = [names[c] for c in used if not np.isfinite(X[:, c]).all()] raise ValueError(f"missing or infinite values in {bad}; the effect model needs complete columns " f"for the treatment, the outcome and the adjustment set") T, Y = X[:, t], X[:, y] for c, what in ((t, "treatment"), (y, "outcome")): if np.ptp(X[:, c]) == 0: raise ValueError(f"the {what} {names[c]!r} is constant") if len(np.unique(T)) < MIN_LEVELS: raise ValueError(f"the treatment {names[t]!r} has {len(np.unique(T))} distinct values; version 0.0.x " f"estimates effects of continuous treatments only (at least {MIN_LEVELS} values)")
near = {t, y} | set(descendants(A.T, t)) | set(descendants(A.T, y)) ignored = [(a, b, k) for a, b, k in other if names.index(a) in near or names.index(b) in near] if ignored: warnings.warn(f"the graph also has {len(ignored)} relation(s) a DAG cannot express near the treatment " f"or outcome, ignored here (the effect assumes no hidden confounders): " + ", ".join(f"{a} {'--' if k == 'undirected' else '<->'} {b}" for a, b, k in ignored), stacklevel=3) n = len(X) if n < TRAIN_N[0]: warnings.warn(f"{n} rows is below the training range {TRAIN_N}", stacklevel=3) if len(W) > TRAIN_ADJUST: warnings.warn(f"the adjustment set has {len(W)} variables, more than in training (up to {TRAIN_ADJUST})", stacklevel=3)
q = lambda p: float(np.quantile(T, p)) values = np.array([q(p) for p in CURVE_LEVELS] if values is None else values, dtype=np.float64).ravel() reference = q(0.5) if reference is None else float(reference) contrast = (q(CONTRAST_LEVELS[0]), q(CONTRAST_LEVELS[1])) if contrast is None else tuple(map(float, contrast)) if len(contrast) != 2: raise ValueError(f"contrast is a pair (a, b) of treatment values; got {contrast}") lo, hi = q(TRAIN_LEVELS[0]), q(TRAIN_LEVELS[1]) outside = sorted({v for v in [*values, reference, *contrast] if not lo <= v <= hi}) if outside: msg = (f"treatment values {[float(f'{v:.4g}') for v in outside]} are outside the 2-98% quantiles of " f"{names[t]!r}, [{lo:.4g}, {hi:.4g}], where the model was trained and the data has support") if not extrapolate: raise ValueError(msg + "; pass extrapolate=True to estimate them anyway") warnings.warn(msg, stacklevel=3)
pairs = [(reference, v) for v in values] + [contrast] rng = np.random.default_rng(seed) rows = [np.arange(n)] if n <= TRAIN_N[1] else \ [np.sort(rng.choice(n, TRAIN_N[1], replace=False)) for _ in range(n_subsets)] out = [] for r in rows: # each subset standardized on its own, as in training Z = np.zeros((len(r), len(names))) # the model reads only the used columns U = X[np.ix_(r, used)] mu, sd = U.mean(0), U.std(0) if np.any(sd[:2] == 0): raise ValueError("a subset of the rows has a constant treatment or outcome; use fewer, larger subsets") Z[:, used] = (U - mu) / np.where(sd > 0, sd, 1.0) z = lambda v: (v - mu[0]) / sd[0] qz = model.effects(Z, A, t, y, [(z(a), z(b)) for a, b in pairs]) # the full graph: it decides W out.append(qz.astype(np.float64) * sd[1]) # effects are differences: no shift, only scale Q = np.mean(out, 0) zero = y not in descendants(A, t) if zero and _discovered(graph): warnings.warn(_zero_warning(graph, names[t], names[y]), stacklevel=3) return EffectResult(names[t], names[y], [names[c] for c in W], zero, contrast, Q[-1], reference, values, Q[:-1], len(rows[0]), len(rows))
def _discovered(graph): """Whether the graph is a discover() result (axiom's CausalGraph), read by its attributes.""" return hasattr(graph, "directed") and hasattr(graph, "names")
def _zero_warning(graph, t, y): """Why an exact 0 from a discovered graph deserves a second look, with what the graph says about the pair itself when it can (CausalGraph.relation).""" msg = (f"the discovered graph has no directed path from {t} to {y}, so the effect is exactly 0. That " f"holds only if the graph is right, and discovered edges are uncertain: one missing or " f"reversed edge can cut every path") relation = getattr(graph, "relation", None) if callable(relation): try: probs = relation(t, y).probs msg += f" ({t} vs {y} directly: " + ", ".join(f"{k} {p:.2f}" for k, p in probs.items()) + ")" except (KeyError, ValueError, AttributeError): pass return msg + ". Check the graph's edges (print it), or pass a graph you trust"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413"""AxiomEffect: causal effect estimation given a causal graph, built as an in-contextg-formula with a doubly robust correction (design-effect.md, "Architecture v2").
Given a table, its DAG and a treatment t / outcome y, the dose-response E[Y | do(T = v)] is,by the g-formula, the average over the rows of E[Y | T = v, W = w_r], with W the optimaladjustment set. The model follows that recipe:
1. The graph decides the inputs: each row is reduced to (W, T, Y), W = O(t, y) (axiom_effect.graph.optimal_adjustment). Mediators and other descendants of T, which would bias the answer, are never seen. 2. An in-context regressor (as in TabPFN): the observed rows are the context; query rows carry a row's W with T set to a query value and Y unknown, attend to the context, and a head predicts E[Y | T = v, W = w_r] for each. 3. The average over the rows is computed exactly. 4. With doubly_robust, a correction from the observed rows whose treatment is near v (Kennedy et al. 2017, for continuous treatments): their residuals Y_i - E[Y | T_i, W_i], weighted by f(T_i) / pi(T_i | W_i), the treatment's marginal over its conditional density, kernel-averaged around v. The residuals and densities come from two more query rows per observed row (its own T, and T unknown), each blind to its own context row. If the outcome regression is off, the correction pulls the estimate back to the data. A learned gate per value scales the correction by how many rows effectively support v. With positivity, the gate also sees how many rows could plausibly have received v (their predicted treatment density at v) and the predicted overlap of the table: where the parents nearly fix the treatment, the average at v is mostly extrapolation, which the correction, built from the few rows near v, cannot fix (design-effect.md, run 3).
Effects are differences of the dose-response, so effect(a -> b) = -effect(b -> a) and themedian of a -> a is 0. Only the uncertainty is learned on top: quantiles (QUANTILES) of eacheffect, from the spread of the per-row predictions, the correction, a summary of the contextand the sample size; they never cross. A split-conformal calibration (calibrate_effect.py),stored in the config, then scales the 90% and 50% intervals around the median.
from axiom_effect import AxiomEffect model = AxiomEffect.from_pretrained("path/or/hub-repo") # trained with train_effect.py q = model.effects(X, A, t, y, pairs=[(x25, x75)]) # (1, len(QUANTILES))
Everything is on the table's standardized scale."""import mathimport osimport warningsfrom importlib.metadata import PackageNotFoundError, versionfrom typing import NamedTuple
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom huggingface_hub import PyTorchModelHubMixinfrom huggingface_hub.errors import RevisionNotFoundErrorfrom torch.utils.checkpoint import checkpoint
from .blocks import Attention, FeedForward, eval_mode, mlpfrom .graph import descendants, is_dag, optimal_adjustment
QUANTILES = (0.05, 0.25, 0.5, 0.75, 0.95) # the outer two make a 90% intervalMID = QUANTILES.index(0.5)INTERVALS = {"outer": (0.05, 0.95), "inner": (0.25, 0.75)} # 90% and 50%, each calibrated on its ownN_REF = 2048 # log(n) / log(N_REF): the sample-size inputCLIP = 8.0 # inputs clipped to +-CLIP sd, as Axiom's preprocessW_ROLE, T_ROLE, Y_ROLE = 0, 1, 2 # what a cell of a row isMAX_WEIGHT = 10.0 # the correction's density-ratio weights are clipped here
def ranks(values, reference): """Each value's rank among the observed `reference` values of its column, in [-1, 1] (ties count half). values (B, C, R), reference (B, C, n).""" s = reference.sort(-1).values.contiguous() lo = torch.searchsorted(s, values.contiguous(), right=False) hi = torch.searchsorted(s, values.contiguous(), right=True) return (lo + hi).float() / reference.shape[-1] - 1
def check_calibration(cal): """A calibration (calibrate_effect.py): {"n": sample sizes, increasing, and per interval in INTERVALS, one widening factor > 0 per sample size}.""" n = np.asarray(cal["n"], dtype=float) if n.ndim != 1 or len(n) == 0 or np.any(np.diff(n) <= 0) or np.any(n <= 0): raise ValueError(f"calibration n must be increasing positive sample sizes; got {cal['n']}") for name in INTERVALS: f = np.asarray(cal[name], dtype=float) if f.shape != n.shape or np.any(f <= 0): raise ValueError(f"calibration {name!r} needs one positive factor per n; got {cal[name]}")
def calibration_factors(cal, n): """The widening factor of each interval in INTERVALS for a table of n rows: interpolated linearly in log n between the calibrated sample sizes, constant beyond them.""" logn = np.log(np.asarray(cal["n"], dtype=float)) return {name: float(np.interp(np.log(n), logn, cal[name])) for name in INTERVALS}
def calibrate(q, factors): """Quantiles q (..., len(QUANTILES)) with each interval's distance from the median scaled by its factor, the 90% interval's (outer quantiles) and the 50% interval's (inner) on both sides alike, so antisymmetry holds; the inner ones never pass the outer ones.""" med = q[..., MID:MID + 1] dev = q - med scale = np.ones(len(QUANTILES)) for name, (lo, hi) in INTERVALS.items(): scale[[QUANTILES.index(lo), QUANTILES.index(hi)]] = factors[name] out = dev * scale inner, outer = [QUANTILES.index(p) for p in INTERVALS["inner"]], [QUANTILES.index(p) for p in INTERVALS["outer"]] out[..., inner[0]] = np.maximum(out[..., inner[0]], out[..., outer[0]]) out[..., inner[1]] = np.minimum(out[..., inner[1]], out[..., outer[1]]) return (med + out).astype(q.dtype)
class Rows(NamedTuple): """The model's predictions for one batch of tables and K treatment values.""" mu: torch.Tensor # (B, K, R) E[Y | T = values[k], W] for each query row n_avg: int # the first n_avg query rows are observed rows: the g-formula averages them tokens: torch.Tensor # (B, K, E) their final representations, averaged context: torch.Tensor # (B, E) a summary of the context rows value_rank: torch.Tensor # (B, K) each treatment value's rank among the observed T dose: torch.Tensor # (B, K) E[Y | do(T = values[k])]: the average, plus the gated correction correction: torch.Tensor # (B, K) the doubly robust correction before the gate (0 without) gate: torch.Tensor # (B, K) how much of it is used support: torch.Tensor # (B, K) log(1 + effective number of observed rows near the value) positivity: torch.Tensor # (B, K) effective share of rows that could receive the value (1 without) overlap: torch.Tensor # (B,) predicted R² of the treatment given W (0 without) own_mu: torch.Tensor # (B, r) E[Y | T_i, W_i] for the first r observed rows, blind to row i own_mean: torch.Tensor # (B, r) the treatment's predicted mean given W_i, blind to row i own_logsd: torch.Tensor # (B, r) and its log standard deviation
class CrossBlock(nn.Module): """Pre-norm: queries attend to the context rows (minus any `blocked` (Q, n) pairs), then a feed-forward. Queries do not attend to each other, so each query's answer depends on the context only.""" def __init__(self, E, H): super().__init__() self.norm_q, self.norm_ctx = nn.LayerNorm(E), nn.LayerNorm(E) self.attn = nn.MultiheadAttention(E, H, batch_first=True) self.ff = FeedForward(E)
def forward(self, q, ctx, blocked=None): # q (B, Q, E), ctx (B, n, E) c = self.norm_ctx(ctx) return self.ff(q + self.attn(self.norm_q(q), c, c, attn_mask=blocked, need_weights=False)[0])
def release_tag(): """The Hub tag of the weights released with this package version ("v0.0.1"), or None when the package is not installed (running from source without metadata).""" try: return f"v{version('axiom-effect')}" except PackageNotFoundError: return None
class AxiomEffect(nn.Module, PyTorchModelHubMixin, library_name="axiom-effect", repo_url=None, tags=["causal-inference", "effect-estimation", "tabular"]): """Hugging Face: `save_pretrained(dir)` / `push_to_hub(repo)` write model.safetensors and config.json (the __init__ arguments, the calibration included); `from_pretrained` rebuilds it. From a Hub repo it loads the weights released with this package version (the repo's `v<version>` tag) unless `revision` says otherwise.""" @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *, revision=None, strict=True, **kwargs): """As PyTorchModelHubMixin.from_pretrained, with Axiom's two safeguards: a Hub repo defaults to the weights tagged with this package's version (falling back to main, with a warning, if the tag is missing), and the weights load strictly.""" path = str(pretrained_model_name_or_path) tag = release_tag() if revision is None and tag is not None and not os.path.isdir(path): try: return super().from_pretrained(path, revision=tag, strict=strict, **kwargs) except RevisionNotFoundError: warnings.warn(f"{path} has no {tag} tag; loading its latest weights (main), which may " f"not match this version of the code", stacklevel=2) return super().from_pretrained(path, revision=revision, strict=strict, **kwargs)
def __init__(self, E=128, H=8, row_layers=2, context_layers=4, query_layers=3, inducing=64, doubly_robust=False, positivity=False, calibration=None): super().__init__() self.config = dict(architecture="in-context g-formula", E=E, H=H, row_layers=row_layers, context_layers=context_layers, query_layers=query_layers, inducing=inducing, doubly_robust=doubly_robust, positivity=positivity) if calibration is not None: check_calibration(calibration) self.config["calibration"] = calibration if positivity and not doubly_robust: raise ValueError("positivity inputs belong to the doubly robust gate: needs doubly_robust=True") extra = 2 if positivity else 0 # positivity, overlap # A row: its cells (value, rank) with their role (W, T or Y), attended across, pooled. self.cell = mlp(2, E, E) self.role = nn.Embedding(3, E) self.unknown = nn.Parameter(torch.zeros(E)) # a cell the query asks about self.row_attn = nn.ModuleList(Attention(E, H) for _ in range(row_layers)) self.row_ff = nn.ModuleList(FeedForward(E) for _ in range(row_layers)) self.row_out = mlp(E, E, E) # The context rows attend to each other through inducing points. self.context_attn = nn.ModuleList(Attention(E, H, inducing) for _ in range(context_layers)) self.context_ff = nn.ModuleList(FeedForward(E) for _ in range(context_layers)) # Query rows -> E[Y | T = v, W = w] (and, doubly robust, the treatment's density given W). self.query_blocks = nn.ModuleList(CrossBlock(E, H) for _ in range(query_layers)) self.mu = nn.Linear(E, 1) self.treatment = nn.Linear(E, 2) if doubly_robust else None # mean, log sd of T given W self.gate = mlp(4 + extra, E, 1) if doubly_robust else None # support, rank, size, correction (+ extra) # The effect's quantiles around the estimate, from: estimate, spread of the per-row # differences, the query tokens' difference and sum, context, size, a, b, b - a with # the ranks of a and b, (doubly robust) the corrections' difference, gates and supports, # and (positivity) both values' positivity and the overlap. self.spread = mlp(2 + 3 * E + 1 + 5 + (5 if doubly_robust else 0) + (3 if positivity else 0), E, len(QUANTILES) - 1) # In training, recompute each layer's activations in the backward pass instead of # storing them: much less memory, about 30% more compute (train_effect.py --recompute). self.recompute = False
def _run(self, fn, *args): if self.recompute and self.training and torch.is_grad_enabled(): return checkpoint(fn, *args, use_reentrant=False) return fn(*args)
def _rows(self, w, t, y, w_mask, refs): """Row tokens (B, R, E) from a row's W values w (B, R, P) (w_mask (B, P): which of the P slots are real), its treatment t and outcome y (B, R) (NaN = unknown), with ranks relative to the observed columns refs = (ctx_w, ctx_t, ctx_y).""" B, R, P = w.shape v = torch.cat([w, t[..., None], y[..., None]], -1) # (B, R, P + 2) ref = torch.cat([refs[0], refs[1][..., None], refs[2][..., None]], -1) # (B, n, P + 2) unknown = torch.isnan(v) v = v.nan_to_num(0.0).clamp(-CLIP, CLIP) r = ranks(v.transpose(1, 2), ref.clamp(-CLIP, CLIP).transpose(1, 2)).transpose(1, 2) role = torch.tensor([W_ROLE] * P + [T_ROLE, Y_ROLE], device=w.device) e = torch.where(unknown[..., None], self.unknown, self.cell(torch.stack([v, r], -1))) + self.role(role) pad = torch.cat([~w_mask, torch.zeros(B, 2, dtype=torch.bool, device=w.device)], -1) pad = pad[:, None].expand(B, R, P + 2).reshape(B * R, P + 2) e = e.reshape(B * R, P + 2, -1) for attn, ff in zip(self.row_attn, self.row_ff): e = self._run(lambda e, pad, attn=attn, ff=ff: ff(attn(e, pad)), e, pad) keep = (~pad).float()[..., None] return self.row_out((e * keep).sum(1) / keep.sum(1)).reshape(B, R, -1)
def _decode(self, q, ctx, blocked=None): for blk in self.query_blocks: q = self._run(blk, q, ctx, blocked) return q
def forward(self, ctx_w, ctx_t, ctx_y, w_mask, query_w, values, n_avg=None, own=None, chunk=None): """Every prediction for a batch. ctx_w (B, n, P), ctx_t and ctx_y (B, n): the observed rows, reduced to (W, T, Y); w_mask (B, P); query_w (B, K, R, P): the W of R query rows for each of K treatment values, values (B, K), the first n_avg of them observed rows (default: all); own: how many of the first observed rows give the doubly robust correction its residuals and densities (default: all). Queries go `chunk` rows at a time (default: all at once).""" B, K, R, P = query_w.shape n, dev = ctx_t.shape[1], ctx_t.device n_avg = R if n_avg is None else n_avg refs = (ctx_w, ctx_t, ctx_y) ctx = self._rows(ctx_w, ctx_t, ctx_y, w_mask, refs) for attn, ff in zip(self.context_attn, self.context_ff): ctx = self._run(lambda c, attn=attn, ff=ff: ff(attn(c)), ctx)
step = chunk or R mus, pooled = [], 0.0 for s in range(0, R, step): qw = query_w[:, :, s:s + step] r = qw.shape[2] q_t = values[..., None].expand(B, K, r).reshape(B, K * r) q = self._decode(self._rows(qw.reshape(B, K * r, P), q_t, torch.full_like(q_t, float("nan")), w_mask, refs), ctx).reshape(B, K, r, -1) mus.append(self.mu(q)[..., 0]) pooled = pooled + q[:, :, :max(0, min(r, n_avg - s))].sum(2) mu = torch.cat(mus, 2)
own = n if own is None else min(own, n) own_mu, own_mean, own_logsd = [], [], [] if self.config["doubly_robust"]: ostep = chunk or own for s in range(0, own, ostep): idx = torch.arange(s, min(s + ostep, own), device=dev) m = len(idx) w_i, t_i = ctx_w[:, idx], ctx_t[:, idx] nan = torch.full_like(t_i, float("nan")) q = torch.cat([self._rows(w_i, t_i, nan, w_mask, refs), # its own T: its outcome self._rows(w_i, nan, nan, w_mask, refs)], 1) # T unknown: T's density blocked = torch.zeros(2 * m, n, dtype=torch.bool, device=dev) blocked[torch.arange(2 * m, device=dev), idx.repeat(2)] = True # blind to its own row q = self._decode(q, ctx, blocked) own_mu.append(self.mu(q[:, :m])[..., 0]) mean, logsd = self.treatment(q[:, m:]).unbind(-1) own_mean.append(mean) own_logsd.append(logsd.clamp(-5, 3)) cat = lambda xs: torch.cat(xs, 1) if xs else ctx_t.new_zeros(B, 0) own_mu, own_mean, own_logsd = cat(own_mu), cat(own_mean), cat(own_logsd)
value_rank = ranks(values.clamp(-CLIP, CLIP)[:, None], ctx_t.clamp(-CLIP, CLIP)[:, None])[:, 0] g = mu[..., :n_avg].mean(2) if self.config["doubly_robust"]: correction, support = self._correction(own_mu, own_mean, own_logsd, ctx_t, ctx_y, values, n) size = torch.full_like(g, float(np.log(n) / np.log(N_REF))) gate_in = [support, value_rank, size, correction] positivity, overlap = self._positivity(own_mean, own_logsd, values) if self.config["positivity"]: gate_in += [positivity, overlap[:, None].expand_as(g)] gate = torch.sigmoid(self.gate(torch.stack(gate_in, -1)))[..., 0] else: correction = support = torch.zeros_like(g) gate, positivity, overlap = torch.ones_like(g), torch.ones_like(g), g.new_zeros(B) return Rows(mu, n_avg, pooled / n_avg, ctx.mean(1), value_rank, g + gate * correction, correction, gate, support, positivity, overlap, own_mu, own_mean, own_logsd)
@staticmethod def _positivity(own_mean, own_logsd, values): """Positivity at each value, (B, K): the effective share of the own rows that could receive it, (sum_i p_i)² / (r sum_i p_i²) with p_i = pi(v | W_i) the predicted treatment density, 1 when every row could equally, 1 / r when one row could. And the table's predicted overlap, (B,): 1 - mean_i Var(T | W_i), the R² of the (standardized) treatment given W, near 1 where the parents nearly fix it.""" r = own_mean.shape[1] log_p = torch.distributions.Normal(own_mean[:, None], own_logsd.exp()[:, None]).log_prob( values.clamp(-CLIP, CLIP)[..., None]) # (B, K, r) ess = torch.exp(2 * torch.logsumexp(log_p, -1) - torch.logsumexp(2 * log_p, -1)) return ess / r, (1 - (2 * own_logsd).exp().mean(-1)).clamp(0, 1)
@staticmethod def _correction(own_mu, own_mean, own_logsd, ctx_t, ctx_y, values, n): """The doubly robust correction to each value's dose-response, (B, K), and the log of 1 + the effective number of observed rows behind it. Kernel regression on T of the own rows' residuals Y_i - E[Y | T_i, W_i], weighted by f(T_i) / pi(T_i | W_i) (clipped at MAX_WEIGHT); f is a kernel density of the observed T, pi the predicted conditional density; the bandwidth is Silverman's rule for a standardized variable.""" r = own_mu.shape[1] t_all = ctx_t.clamp(-CLIP, CLIP) t_i, resid = t_all[:, :r], ctx_y[:, :r].clamp(-CLIP, CLIP) - own_mu h = 1.06 * n ** -0.2 kern = lambda u: torch.exp(-0.5 * u * u) log_f = torch.log(kern((t_i[..., None] - t_all[:, None]) / h).mean(-1) / (h * math.sqrt(2 * math.pi)) + 1e-12) log_pi = torch.distributions.Normal(own_mean, own_logsd.exp()).log_prob(t_i) weight = (log_f - log_pi).clamp(max=math.log(MAX_WEIGHT)).exp() K = kern((t_i[:, None] - values.clamp(-CLIP, CLIP)[..., None]) / h) # (B, K, r) Kw = K * weight[:, None] correction = (Kw * resid[:, None]).sum(-1) / (K.sum(-1) + 1e-6) support = torch.log1p(Kw.sum(-1) ** 2 / (Kw ** 2).sum(-1).clamp(min=1e-12)) return correction, support
def quantiles(self, rows, values, pairs, n): """Quantiles (B, len(pairs), len(QUANTILES)) of the effect of moving the treatment from values[:, i] to values[:, j], for each (i, j) in pairs (indices into the K values), from `rows` (see forward()) of a table with n rows.""" i, j = pairs[:, 0], pairs[:, 1] size = float(np.log(n) / np.log(N_REF)) mu = rows.mu[..., :rows.n_avg]
def one_way(i, j): est = rows.dose[:, j] - rows.dose[:, i] # (B, P) a, b = values[:, i], values[:, j] feats = [est[..., None], (mu[:, j] - mu[:, i]).std(-1, unbiased=False)[..., None], rows.tokens[:, j] - rows.tokens[:, i], rows.tokens[:, j] + rows.tokens[:, i], rows.context[:, None].expand(-1, len(i), -1), torch.full_like(est[..., None], size), torch.stack([a, b, b - a, rows.value_rank[:, i], rows.value_rank[:, j]], -1)] if self.config["doubly_robust"]: feats.append(torch.stack([rows.correction[:, j] - rows.correction[:, i], rows.gate[:, i], rows.gate[:, j], rows.support[:, i], rows.support[:, j]], -1)) if self.config["positivity"]: feats.append(torch.stack([rows.positivity[:, i], rows.positivity[:, j], rows.overlap[:, None].expand_as(est)], -1)) steps = F.softplus(self.spread(torch.cat(feats, -1))) lower = est[..., None] - steps[..., :MID].flip(-1).cumsum(-1).flip(-1) upper = est[..., None] + steps[..., MID:].cumsum(-1) return torch.cat([lower, est[..., None], upper], -1)
# The estimate is antisymmetric already; averaging both directions makes the spread # symmetric too: quantile p of a -> b is minus quantile 1 - p of b -> a. return (one_way(i, j) - one_way(j, i).flip(-1)) / 2
def effect(self, data, graph, treatment, outcome, **kwargs): """The causal effect of `treatment` on `outcome` in a table, given its causal graph, in the outcome's units: `axiom_effect.inference.effect(self, ...)`, which see. effects() below is the low-level call on standardized arrays.""" from .inference import effect return effect(self, data, graph, treatment, outcome, **kwargs)
@torch.no_grad() def effects(self, X, A, t, y, pairs, chunk=256, calibrated=True): """Quantiles (len(pairs), len(QUANTILES)) of the effect on column y of moving column t from a to b, for each (a, b) in pairs: X (n, d) a table standardized per column (as the treatment values are), A (d, d) its DAG, A[i, j] = 1 meaning i -> j. Every row is a query row and gives the correction its residuals, `chunk` rows at a time.
With a calibration in the config (calibrate_effect.py) and `calibrated`, the 90% and 50% intervals are widened (or narrowed) around the median by split-conformal factors for this n; the median, the estimate, is never changed.
The graph is taken as true: a DAG over the table's variables, so no hidden confounders and every effect identified. If it gives no directed path from t to y, intervening on t cannot move y, and every effect is exactly 0 (a zero-width interval), whatever the data shows: their association then comes from common causes.""" X, A = np.asarray(X, dtype=np.float32), np.asarray(A) if X.ndim != 2 or A.shape != (X.shape[1], X.shape[1]): raise ValueError(f"X {X.shape} needs a (d, d) graph with d = its columns; got {A.shape}") if not (0 <= t < X.shape[1] and 0 <= y < X.shape[1]) or t == y: raise ValueError(f"treatment {t} and outcome {y} must be two different columns of X") if not is_dag(A): raise ValueError("the graph has a directed cycle; effects() needs a DAG") if y not in descendants(A, t): return np.zeros((len(pairs), len(QUANTILES)), dtype=np.float32) device = next(self.parameters()).device X = torch.as_tensor(X, device=device) W = torch.as_tensor(optimal_adjustment(A, t, y), dtype=torch.long, device=device) values, idx = np.unique(np.asarray(pairs, dtype=np.float32), return_inverse=True) idx = torch.as_tensor(idx.reshape(-1, 2), device=device) vals = torch.as_tensor(values, device=device)[None] ctx_w, ctx_t, ctx_y = X[None][:, :, W], X[None, :, t], X[None, :, y] w_mask = torch.ones(1, len(W), dtype=torch.bool, device=device) with eval_mode(self): rows = self(ctx_w, ctx_t, ctx_y, w_mask, ctx_w[:, None].expand(-1, len(values), -1, -1), vals, chunk=chunk) q = self.quantiles(rows, vals, idx, len(X)) q = q[0].cpu().numpy() cal = self.config.get("calibration") return calibrate(q, calibration_factors(cal, len(X))) if calibrated and cal else qLICENSEAdded+202
README.mdAdded+142
config.jsonAdded+28
model.safetensorsAdded+3
pyproject.tomlAdded+21
src/axiom_effect/__init__.pyAdded+14
src/axiom_effect/blocks.pyAdded+57
src/axiom_effect/graph.pyAdded+47
src/axiom_effect/inference.pyAdded+278
src/axiom_effect/model.pyAdded+413