Release 0.2.0
Browse filesFiles changed (9)
- LICENSE-CausalPFNDeleted-175
- NOTICEDeleted-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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175 CausalPFN License Version 1.0, April 2025
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 CONDITIONS1234567891011121314AxiomEffect
This product includes a reimplementation of the network of CausalPFN ("CausalPFN: AmortizedCausal Effect Estimation via In-Context Learning", Balazadeh et al. 2025, arXiv:2506.07918;https://huggingface.co/vdblm/causalpfn), by the CausalPFN authors, licensed under the CausalPFNLicense, Version 1.0 (the terms of the Apache License, Version 2.0): see LICENSE-CausalPFN.CausalPFN's network is TabDPT's (Layer 6, https://huggingface.co/Layer6/TabDPT, Apache 2.0).
Changes: src/axiom_effect/model.py reimplements causalpfn's models/model.py andmodels/transformer_layer.py, keeping their parameter names, and adds graph-role inputs,continuous treatments, a query token told no treatment value (read by propensity heads) and ahead for the estimands' intervals. AxiomEffect's training starts from CausalPFN's weights(causalpfn_v0.pt) and continues on AxiomEffect's own prior, so its released weights are derivedfrom CausalPFN's.15 unmodified lines161718192021222324192021222329242526272834293031323 unmodified lines363738443940414248 unmodified lines9192939994959697102989910410510610715 unmodified lineseffect between two values, the dose-response curve and every row's effect, each with 90% and50% intervals. Trained on simulated data where every row's effect is known.
The network is [CausalPFN](https://huggingface.co/vdblm/causalpfn)'s (Balazadeh et al. 2025,arXiv:2506.07918; itself TabDPT's), and training starts from CausalPFN's weights, extended tocontinuous treatments and causal graphs. CausalPFN is used under its license (the Apache 2.0terms): see NOTICE and LICENSE-CausalPFN.
**Version 0.1.0 is experimental.** The API and the weights will change in 0.x releases.**Version 0.2.0 is experimental.** The API and the weights will change in 0.x releases.Check its answers against what you know about your data.
It works without a causal graph, the usual assumption being that every covariate is measuredbefore the treatment, and better with one. It is the sibling of[Axiom](https://huggingface.co/maxpagels/axiom-discovery), the causal discovery model: given a[Axiom Discovery](https://huggingface.co/maxpagels/axiom-discovery), the causal discovery model: given adiscovered graph, it reads each covariate's role (confounder, instrument, mediator, collider,...) as probabilities, so a discovered graph helps it tell the columns that must be adjustedfor from the ones that would bias the answer.
19.8M parameters, fp32 safetensors (79 MB). Project page:20.3M parameters, fp32 safetensors (81 MB). Project page:[maxpagels.com/axiom](https://maxpagels.com/axiom).
## Recommended use (ballpark)3 unmodified lines| treatment | binary (two values) or continuous (at least 10 distinct values); continuous values inside its 2-98% quantiles || covariates | trained on up to 84; without a graph they must all be pre-treatment (not caused by the treatment) || graph | none; a DAG you trust (the treatment's descendants are then dropped); or an Axiom `discover()` result || rows | trained on 128-2048; larger tables are split into disjoint subsets of up to 2048 rows (1024 with more than 34 covariates) and combined || rows | trained on 128-1024; larger tables are split into disjoint subsets of up to 1024 rows and combined || hidden confounders | not handled: no unmeasured common causes of the treatment and the outcome || missing values | not supported in the columns used |
48 unmodified lines## 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:weights released with it, so code and weights always match. To install a specific release,an earlier one included, use its tag:
```bashpip install "git+https://huggingface.co/maxpagels/axiom-effect@v0.1.0"pip install "git+https://huggingface.co/maxpagels/axiom-effect@v0.2.0" # or an earlier tag, e.g. @v0.1.0```
- **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).- **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.- **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.1234564567891011{ "E": 384, "H": 6, "layers": 20, "nbins": 1024, "sigma": 0.5, "col_dim": 64, "col_layers": 2, "layers": 12, "nbins": 256, "row_slots": 16, "sigma": 0.4, "vmax": 10.0}12323version https://git-lfs.github.com/spec/v1oid sha256:0166cfb102eebd773db587f9e92326e5663d53299aa99f0c809fbb4be8df6d9csize 79287324oid sha256:a45233de83ce1ba99df0f33fdbca52cc5ebb6572b44e895155a7a0c4370cfc71size 8133228012334567899101112[project]name = "axiom-effect"version = "0.1.0"version = "0.2.0"description = "AxiomEffect: causal effects (ATE, ATT, CATE, dose-response) from a table, with or without a causal graph"readme = "README.md"authors = [{ name = "Max Pagels" }]requires-python = ">=3.11"license = "Apache-2.0"license-files = ["LICENSE", "NOTICE", "LICENSE-CausalPFN"]license-files = ["LICENSE"]dependencies = ["huggingface-hub>=2.1", "numpy>=2.0", "safetensors>=0.4", "torch>=2.4"]
[project.urls]122345"""AxiomEffect: causal effects (ATE, ATT, per-row CATE, dose-response) from a table, for binaryand continuous treatments, with or without a causal graph; the sibling of Axiom (axiom-discovery),and continuous treatments, with or without a causal graph; the sibling of Axiom Discovery (axiom-discovery),whose discovered graphs it reads.
from axiom_effect import AxiomEffect6 unmodified lines78910101112134 unmodified lines1819202122232425212223242526272 unmodified lines3031323433343637383940353637383940414243464445464759 unmodified lines10710810911211011111211314 unmodified lines12812913013313113213313469 unmodified lines2042052062092102112122132142152162072182082092102114 unmodified lines21621721821922022122222322422522622722822923023123223323423523623723823923023124024124224310 unmodified lines25425525624824925725825926022 unmodified lines28328428527828628728028128228328428528628828929029129229329429528 unmodified lines32432532632132232332432532632732832932732832933033122 unmodified lines3543553563583593573583593603633643653663613623633643653663673683693703713683693723733743713723753763773783793803743753813823833843853864 unmodified lines3913923933863873943953963893973983913994003934014024034045 unmodified lines4104114124054064074134144154164174186 unmodified lines print(r) r.ate, r.att, r.cate, r.curve, r.debiased
What the graph does (design-effect.md, "Axiom discovery and the effect model"):What the graph does: none every other column (or `covariates`) is taken as pre-treatment: none of them may be caused by the treatment. Their roles are unknown to the model. a DAG taken as true: the treatment's descendants (mediators, colliders, ...) are4 unmodified lines covariate's role probabilities (averaged over DAGs sampled from them), and the model reads them; nothing is dropped, since a discovered edge can be wrong.
A treatment with two values is binary: the ATE, the ATT (treated) and the ATC (controls), eachrow's effect, and a doubly robust (AIPW) estimate built outside the network from the model'soutcome predictions and a cross-fitted logistic propensity (the network's own propensity headis not used: a row's treatment reaches it through the other rows' context tokens). Otherwise (at least MIN_LEVELS values) continuous: the contrast between twovalues, the dose-response curve, each row's effect of the contrast.For large tables (more than TRAIN_N[1] rows), inference keeps memory small (< 1 GB) bypartitioning the table into disjoint i.i.d. subsets of at most TRAIN_N[1] rows (stratifiedby treatment arm for binary treatments so every subset preserves prevalence) and combiningtheir independent estimates."""import warningsfrom dataclasses import dataclass, field2 unmodified linesimport numpy as np
from .graph import CONF, N_ROLES, ROLE_NAMES, descendants, discovered_roles, is_dag, rolesfrom .model import MAX_COVARIATES, MID, N_FEATURES, QUANTILESfrom .model import MID, N_FEATURES, QUANTILES
TRAIN_N = (128, 2048) # rows; larger tables are split into disjoint subsets of up to TRAIN_N[1]TRAIN_COVARIATES = 84 # covariates (80 pre-treatment, up to 4 post-treatment)# Tables with more than NARROW_COVARIATES covariates were trained on at most WIDE_N rows, so# they are split into subsets of up to WIDE_N.NARROW_COVARIATES, WIDE_N = 34, 1024TRAIN_N = (128, 1024) # context rows; larger tables use localized retrieval of TRAIN_N[1] rowsTRAIN_COVARIATES = 84 # covariates seen in training (network accepts any number natively)WIDE_N = TRAIN_N[1] # kept for compatibility with export_effect_hf / train_effectNARROW_COVARIATES = 34MIN_LEVELS = 10 # a continuous treatment needs at least this many distinct valuesTRAIN_LEVELS = (0.02, 0.98) # continuous treatment values were asked about between these quantilesCURVE_LEVELS = (0.1, 0.25, 0.5, 0.75, 0.9)CONTRAST_LEVELS = (0.25, 0.75)E_CLIP = 0.01 # propensities clipped to [E_CLIP, 1 - E_CLIP] in the doubly robust estimatePROPENSITY_FOLDS, PROPENSITY_RIDGE = 5, 1.0 # the cross-fitted logistic propensityPROPENSITY_FOLDS, PROPENSITY_RIDGE = 5, 1.0 # cross-fitted logistic propensityZ90 = NormalDist().inv_cdf(0.95)
59 unmodified lines g = lambda v: f"{v:.4g}" sig = lambda v: ("+" if v > 0 else "") + g(v) adj = ", ".join(self.covariates) or "nothing" rows = f"{self.n_rows} rows" + (f" in {self.n_subsets} subsets" if self.n_subsets > 1 else "") rows = f"{self.n_rows} rows" + (f" in {self.n_subsets} strata" if self.n_subsets > 1 else "") head = [f"Effect of {self.treatment} on {self.outcome} ({rows}; graph: {self.graph}; adjusted for {adj})"] if self.dropped: head.append(f" not adjusted for (the graph says the treatment causes them): {', '.join(self.dropped)}")14 unmodified lines f" dose-response, from {self.treatment} = {g(self.reference)}:"] lines += [f" {g(v):>10s} {sig(q[MID])} 90% [{g(q[0])}, {g(q[-1])}]" for v, q in zip(self.values, self.curve)] lines.append(f" per-row effects (cate): median {sig(np.median(self.cate))}, " lines.append(f" per-row effects (CATE): median {sig(np.median(self.cate))}, " f"10-90% {g(np.quantile(self.cate, 0.1))} to {g(np.quantile(self.cate, 0.9))}") return "\n".join(lines)
69 unmodified lines return (v - mu) / np.where(sd > 0, sd, 1.0), mu, np.where(sd > 0, sd, 1.0)
def _components(C, k): """(n, k) the first k principal components of the standardized columns of C (CausalPFN's TruncatedSVD for tables wider than its network).""" Z, _, _ = _standardize(C) U, S, _ = np.linalg.svd(Z - Z.mean(0), full_matrices=False) return U[:, :k] * S[:k]
def _combine(qs, counts): """Quantiles of one estimand from disjoint subsets: the count-weighted mean of the """Quantiles of one estimand from disjoint query strata: the count-weighted mean of the medians, and each quantile's distance from the median combined as for a mean of independent estimates, sqrt(sum (m_k d_k)^2) / sum m_k.""" qs, m = np.asarray(qs), np.asarray(counts, dtype=float)4 unmodified lines return mid + np.sign(off.mean(0)) * np.sqrt(((m[:, None] * off) ** 2).sum(0)) / m.sum()
def _disjoint_strata(T, binary, max_ctx, rng): """Partition `n` rows into disjoint i.i.d. subsets of at most `max_ctx` rows (stratified by treatment arm for binary treatments so every subset preserves prevalence). Returns [(rows, rows)].""" n = len(T) if n <= max_ctx: all_rows = np.arange(n) return [(all_rows, all_rows)]
n_strata = -(-n // max_ctx) if binary: mid = (T.min() + T.max()) / 2 tr = rng.permutation(np.flatnonzero(T > mid)) ct = rng.permutation(np.flatnonzero(T <= mid)) parts = [np.concatenate([a, b]) for a, b in zip(np.array_split(tr, n_strata), np.array_split(ct, n_strata))] else: parts = np.array_split(rng.permutation(n), n_strata) return [(p, p) for p in parts]
def _logistic(X, t, ridge, iters=25): """Ridge-penalized logistic regression by Newton's method: the weights (intercept first, unpenalized) of P(t = 1 | X).""" """Ridge-penalized logistic regression by Newton's method: weights (intercept first).""" A = np.column_stack([np.ones(len(X)), X]) P = ridge * np.eye(A.shape[1]) P[0, 0] = 0.010 unmodified lines
def _propensity(C, t, seed=0): """(n,) P(t = 1 | C), each row's from a logistic regression fitted on the other folds, on standardized covariates: a row's own treatment never enters its propensity.""" """(n,) P(t = 1 | C), each row's from a logistic regression fitted on the other folds.""" n = len(t) 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)) folds = np.random.default_rng(seed).permutation(n) % min(PROPENSITY_FOLDS, n)22 unmodified lines
def effect(model, data, treatment, outcome, graph=None, covariates=None, values=None, contrast=None, reference=None, names=None, extrapolate=False, discovery_samples=64, seed=0): reference=None, names=None, extrapolate=False, discovery_samples=64, tta=1, seed=0): """The effect of setting `treatment` on `outcome` in a table (a DataFrame or an (n, d) array; `names` for an array's columns), given an optional graph (see the module docstring): a DAG as an edge list of (cause, effect) names, a (d, d) matrix or an adjacency DataFrame, or a discover() result. `covariates`: the columns to adjust for (default: all others). Continuous treatments: `contrast` (a, b), default its 25% and 75% quantiles; `values` the curve's treatment values, default its 10/25/50/75/90% quantiles; `reference` where the curve starts, default the median; values outside the 2-98% quantiles are refused unless `extrapolate`. Returns an EffectResult.""" array; `names` for an array's columns), given an optional graph: a DAG as an edge list of (cause, effect) names, a (d, d) matrix or an adjacency DataFrame, or a discover() result. `covariates`: the columns to adjust for (default: all others). `tta`: test-time augmentation passes (default 4; averages over random column tie-breaker codes with zero extra peak RAM). Returns an EffectResult.""" X, names = _table(data, names) t, y = _column(treatment, names, "treatment"), _column(outcome, names, "outcome") if t == y:28 unmodified lines n = len(X) if n < TRAIN_N[0]: warnings.warn(f"{n} rows is below the training range {TRAIN_N}", stacklevel=3) C = X[:, cov] # the covariates the network reads if len(cov) > MAX_COVARIATES: if kind != "none": raise ValueError(f"{len(cov)} covariates with a graph: the network has slots for {MAX_COVARIATES}, and " f"roles do not survive a projection; pass fewer `covariates`") C, features = _components(C, MAX_COVARIATES), np.zeros((MAX_COVARIATES, N_FEATURES)) warnings.warn(f"{len(cov)} covariates, more than the network's {MAX_COVARIATES} slots: adjusting for their " f"first {MAX_COVARIATES} principal components instead, as CausalPFN does", stacklevel=3) elif len(cov) > TRAIN_COVARIATES: C = X[:, cov] if len(cov) > TRAIN_COVARIATES: warnings.warn(f"{len(cov)} covariates, more than in training (up to {TRAIN_COVARIATES})", stacklevel=3) T, Y = X[:, t], X[:, y] levels = np.unique(T)22 unmodified lines k = {v: i for i, v in enumerate(vals)}
rng = np.random.default_rng(seed) most = TRAIN_N[1] if len(cov) <= NARROW_COVARIATES else WIDE_N parts = [np.arange(n)] if n <= most else np.array_split(rng.permutation(n), -(-n // most)) strata = _disjoint_strata(T, binary, TRAIN_N[1], rng) est = {"contrast": [], "att": [], "atc": []} if binary else {"contrast": [], "curve": []} counts = {key: [] for key in est} cate, mu0, mu1 = np.empty(n), np.empty(n), np.empty(n) for rows in parts: Wz, _, _ = _standardize(C[rows]) if cov else (np.zeros((len(rows), 0)), 0, 1) Tz, tm, ts = _standardize(T[rows]) Yz, ym, ys = _standardize(Y[rows]) for idx_s, (q_rows, ctx_rows) in enumerate(strata): same = len(q_rows) == len(ctx_rows) and np.array_equal(q_rows, ctx_rows) if cov: Wz_ctx, wm, ws = _standardize(C[ctx_rows]) Wz_qry = None if same else (C[q_rows] - wm) / ws else: Wz_ctx = np.zeros((len(ctx_rows), 0)) Wz_qry = None if same else np.zeros((len(q_rows), 0)) Tz_ctx, tm, ts = _standardize(T[ctx_rows]) Yz_ctx, ym, ys = _standardize(Y[ctx_rows]) vz = (np.array(vals) - tm) / ts all_rows = np.ones(len(rows), dtype=bool) jobs = [(k[a], k[b], all_rows, "contrast")] all_q = np.ones(len(q_rows), dtype=bool) jobs = [(k[a], k[b], all_q, "contrast")] if binary: treated = T[rows] == levels[1] jobs += [(k[a], k[b], treated, "att"), (k[a], k[b], ~treated, "atc")] treated_q = T[q_rows] == levels[1] if treated_q.any(): jobs.append((k[a], k[b], treated_q, "att")) if (~treated_q).any(): jobs.append((k[a], k[b], ~treated_q, "atc")) else: jobs += [(k[ref], k[v], all_rows, "curve") for v in curve_vals] out = model.predict(Wz, Tz, Yz, features, binary, vz, [(i, j, r) for i, j, r, _ in jobs]) jobs += [(k[ref], k[v], all_q, "curve") for v in curve_vals] out = model.predict(Wz_ctx, Tz_ctx, Yz_ctx, features, binary, vz, [(i, j, r) for i, j, r, _ in jobs], W_qry=Wz_qry, tta=tta, seed=seed + idx_s * 97) Q = out["quantiles"] * ys curve = [] for (_, _, r, name), q in zip(jobs, Q):4 unmodified lines counts[name].append(r.sum()) if curve: est["curve"].append(np.stack(curve)) counts["curve"].append(len(rows)) cate[rows] = (out["mu"][k[b]] - out["mu"][k[a]]) * ys counts["curve"].append(len(q_rows)) cate[q_rows] = (out["mu"][k[b]] - out["mu"][k[a]]) * ys if binary: mu0[rows], mu1[rows] = out["mu"][k[a]] * ys + ym, out["mu"][k[b]] * ys + ym mu0[q_rows], mu1[q_rows] = out["mu"][k[a]] * ys + ym, out["mu"][k[b]] * ys + ym
quantiles = {name: _combine(est[name], counts[name]) for name in est if name != "curve"} quantiles = {name: _combine(est[name], counts[name]) for name in est if name != "curve" and est[name]} result = EffectResult(names[t], names[y], binary, [names[c] for c in cov], [names[c] for c in dropped], kind, (a, b), quantiles, cate, n_rows=n, n_subsets=len(parts), (a, b), quantiles, cate, n_rows=n, n_subsets=len(strata), roles={names[c]: dict(zip(ROLE_NAMES, map(float, R[c]))) for c in cov} if kind != "none" else {}) if binary: treated = (T == levels[1]).astype(float)5 unmodified lines f"estimates there rest on extrapolation", stacklevel=3) else: result.values, result.reference = curve_vals, ref C = np.asarray(est["curve"]) # (subsets, K, Q) result.curve = np.stack([_combine(C[:, j], counts["curve"]) for j in range(C.shape[1])]) result.curve[curve_vals == ref] = 0.0 # from the reference to itself: nothing C_arr = np.asarray(est["curve"]) # (strata, K, Q) result.curve = np.stack([_combine(C_arr[:, j], counts["curve"]) for j in range(C_arr.shape[1])]) result.curve[curve_vals == ref] = 0.0 if zero: warnings.warn(f"the graph has no directed path from {names[t]} to {names[y]}: every effect is exactly 0", stacklevel=3)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152234567891011121314151617181920212223242526272829305 unmodified lines3637386439404142434445717246474874757677787980818283495051525354555657588788899091929394959697596061626364656667686970102717273744 unmodified lines7980811131141151161178283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671221681241691701711721731741281291751761771311321331781791801811821361371381391401411421431441451461471481491501511521531541551561571581591601831841851861871881891901911921931641651661941951961681971981992002011732022032042052061782072082092102112122133 unmodified lines2172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363371891903383393403412 unmodified lines3443453461992002012023473483493503516 unmodified lines3583593602152162172182192202212222232242252262272282292302312322332342352362373613623632392402412422432442452462472482492502512522532542553643653663673683693703713723733743753763773783793803813823832583843852613863873883893903913922682692702712722732742752762772782792802812822832842852863933943953963973983994004014024034044054064074084094104114124134144154164174184194202882894214222922932942952962972982993003013023034234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704713063074724734744753103113124764774783143154794804813174824833193203213223233243253263273283293303313323334844854864874884894904914924934944954964974984995003363373383395015025035045053443455065075085095103503515115125135145153573583593603613625165175185195203665215223683695235245255265273735285293755305313775325333795345355365371 unmodified line5395405413873883893903913923933943953963973983995424014024034044055435445455465475485495505515524104114125535545555565575585595604184194204215615625631 unmodified line565566567429430431"""AxiomEffect: a prior-fitted network for causal effects (design-effect.md, "The model"). Itsnetwork is CausalPFN's (Balazadeh et al. 2025, https://huggingface.co/vdblm/causalpfn, Apache2.0; the network is TabDPT's), parameter for parameter, so CausalPFN's trained weights load intoit (`AxiomEffect.from_causalpfn`) and training starts from them. NOTICE: this file reimplementscausalpfn's models/model.py and models/transformer_layer.py, with the additions below.
It predicts one thing, every row's expected outcome under any treatment value,mu(t, w_i) = E[Y | do(T = t), W = w_i], from the table itself: the covariates W, the treatmentT and the outcome Y of every row. Every causal quantity is arithmetic on mu, not a head of itsown: a row's effect (CATE) is mu(b, w_i) - mu(a, w_i), the ATE its mean over the rows, the ATTits mean over the treated rows, the dose-response the mean of mu(t, w_i) at each t. Binary andcontinuous treatments are the same computation (a binary one asks about its two levels).
CausalPFN's network, as it is: 1. Inputs. A row is MAX_FEATURES slots: the treatment, then the covariates, zero-padded. Each slot is standardized with the context rows' mean and sd and clipped at OUTLIER_SIGMA sd (TabDPT's normalize_data and clip_outliers), and one linear map (`encoder`) embeds the row. A context row's token is that embedding, layer-normalized, plus its outcome's (`y_encoder`, layer-normalized); a query row's token is the embedding with the treatment slot set to the value asked about. Outcomes are standardized within each arm for a binary treatment, as CausalPFN does (over the table for a continuous one), and mu is predicted on that scale. 2. Layers (TabDPT's): from the RMS-normalized input, attention to the context tokens and a gated feed-forward in parallel; their sum projected, normalized and added to the residual. Queries and keys normalized per head (twice, with the queries scaled by log2(context) / 10 between: TabDPT's layer, kept exactly so its weights mean the same). 3. Head: mu(t, w_i) as a distribution over `nbins` bins on [-vmax, vmax] (the first N_OUT outputs are TabDPT's class logits, unused), soft-capped at +-30; trained with the HL-Gauss loss (mu_nll); mu is its mean.
Additions, none of them on mu's path at the start, so the untrained network is CausalPFN's: - Graph roles: each covariate's role features (whether a graph was given, and its role relative to T and Y: axiom_effect.graph.roles) enter the row's embedding through `roles`, a linear map of the slot's role features and their products with its value, initialized to 0 (and exactly 0 without a graph). - Continuous treatments: the treatment slot holds any value, as it holds 0 / 1 for a binary one. - Context and query rows are the same rows: a row's query never attends to its own context token (CausalPFN trains on held-out query rows), so it never reads its own outcome or treatment directly (exactly, with one layer; deeper, the context rows have read each other). - The t-blind token: a query told no treatment value (`t_unknown` in the treatment slot's place), read by the propensity heads (binary: P(T = 1 | W); continuous: a Gaussian T | W). - Estimands: quantiles of an average effect over a set of rows (the ATE, the ATT, any subgroup): the median is the plug-in, the mean of the rows' effects; the widths are a head of their own that reads the network's outputs detached, so its loss never moves them.
from axiom_effect import AxiomEffect model = AxiomEffect.from_pretrained("path/or/hub-repo") r = model.effect(df, treatment="price", outcome="sales", graph=g) # axiom_effect.inference
Everything inside is on the table's standardized scale.AxiomEffect: a pure, from-scratch factorized tabular PFN for causal effects.
Supports binary and continuous treatments, ATE / ATT / ATC / CATE / dose-response curves,and optional causal graphs (trusted DAGs or discovered graphs from Axiom), with zeropretrained dependencies and < 4 GB training RAM.
Architecture ("factorized tabular PFN", ~12.5M parameters by default): 1. Column encoder (2 layers of column self-attention, O(P^2)): each covariate column j starts from exact context statistics (marginal correlations with Y, T, W_j^2, W_j * T; joint partial ridge slopes on Y, W*T, and T; and optional graph role features) and attends to all other columns biased by the P x P covariate correlation matrix R_jk. Completely deterministic and column-permutation equivariant. 2. Multi-slot row encoder (Set-Transformer / TabICL-style cross-attention, O(n * P * M)): each cell (i, j) combines [w_ij, rank(w_ij)] with its column embedding c_j; M = 8 learned row slots cross-attend over the P cells of row i, automatically gating out noise and post-treatment columns while capturing multi-covariate interactions, then project into R^E. Works for any number of covariates P without slot limits or PCA truncation. 3. Row transformer (8 Pre-RMSNorm + SwiGLU layers, E = 384, H = 6): context rows (x_i + embed(T_i) + embed(Y_i)) self-attend; query rows (x_i + embed(t)) cross-attend to the context keys and values at every layer. Training uses disjoint (context, query) splits; full-table inference masks each query from its own context row. 4. Direct HL-Gauss head: predicts mu(t, w_i) directly as a 256-bin distribution on [-10, 10] on the arm's standardized outcome scale (global for continuous). Every causal estimand (CATE, ATE, ATT, ATC, dose-response) is arithmetic on mu; a detached width head predicts calibrated 5/25/75/95% uncertainty intervals."""import mathimport os5 unmodified linesimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom huggingface_hub import PyTorchModelHubMixin, hf_hub_downloadfrom huggingface_hub import PyTorchModelHubMixinfrom huggingface_hub.errors import RevisionNotFoundErrorfrom torch.utils.checkpoint import checkpoint
from .blocks import eval_mode, mlpfrom .graph import N_ROLES
ARCHITECTURE = "CausalPFN" # config["architecture"]: checkpoints of other networks are refusedQUANTILES = (0.05, 0.25, 0.5, 0.75, 0.95) # the outer two make a 90% interval, the inner two 50%ARCHITECTURE = "factorized tabular PFN v2"QUANTILES = (0.05, 0.25, 0.5, 0.75, 0.95) # outer pair: 90% interval; inner pair: 50%MID = QUANTILES.index(0.5)N_FEATURES = 1 + N_ROLES # per covariate: graph given, then its role indicatorsN_REF = 2048 # log(rows) / log(N_REF): the sample-size inputMAX_FEATURES = 100 # input slots: the treatment, then up to 99 covariatesMAX_COVARIATES = MAX_FEATURES - 1N_OUT = 10 # TabDPT's class logits ahead of the bins (unused)OUTLIER_SIGMA = 10.0 # inputs are clipped at this many sd (TabDPT's clip_outliers)NBINS, VMAX, SIGMA = 1024, 10.0, 0.5 # CausalPFN's bins on [-VMAX, VMAX], its HL-Gauss sdLOGIT_CAP = 30.0 # TabDPT's soft cap on the head's outputsCAUSALPFN_REPO, CAUSALPFN_FILE = "vdblm/causalpfn", "causalpfn_v0.pt"CAUSALPFN_CONFIG = dict(E=384, H=6, layers=20, nbins=NBINS)N_FEATURES = 1 + N_ROLES # [graph given, 4 role indicators]N_COL_STATS = 14 # global, rank, arm-conditional correlations + partial slopesN_REF = 2048 # sample-size reference for the width headCLIP_SIGMA = 10.0NBINS, VMAX, SIGMA = 256, 10.0, 0.4 # HL-Gauss bins on [-VMAX, VMAX]DEFAULT_CONFIG = dict(E=384, H=6, layers=12, col_dim=64, col_layers=2, row_slots=16, nbins=NBINS, vmax=VMAX, sigma=SIGMA)
class Rows(NamedTuple): """Everything forward() predicts for a batch of B tables of n rows.""" query: torch.Tensor # (B, n, E) each row's t-blind query token, normalized context: torch.Tensor # (B, E) mean context token, normalized: a summary of the table mu: torch.Tensor # (B, K, n) mu(values[k], w_i), standardized outcome: the mean of mu's distribution logits: torch.Tensor # (B, K, n, nbins) mu's distribution over the bins, on the arm's scale shift: torch.Tensor # (B, K) the outcome's mean in value k's arm: mu = shift + scale * (the bins' mean) scale: torch.Tensor # (B, K) and its sd logit: torch.Tensor # (B, n) binary tables: logit of P(T = 1 | w_i) t_mean: torch.Tensor # (B, n) continuous tables: mean of T | w_i t_logsd: torch.Tensor # (B, n) continuous tables: log sd of T | w_i values: torch.Tensor # (B, K) the treatment values asked about """Everything forward() predicts for a batch of B tables.""" query: torch.Tensor # (B, n_qry, E) mean query representation across asked values, normalized context: torch.Tensor # (B, E) mean context representation, normalized mu: torch.Tensor # (B, K, n_qry) predicted E[Y | do(T = values[k]), W = w_i] logits: torch.Tensor # (B, K, n_qry, nbins) distribution over bins on arm's standardized scale shift: torch.Tensor # (B, K) outcome shift per asked value's arm scale: torch.Tensor # (B, K) outcome scale per asked value's arm values: torch.Tensor # (B, K) treatment values asked about binary: torch.Tensor # (B,) bool
class RMSNorm(nn.Module): """TabDPT's RMSNorm (eps 1e-6, computed in float32).""" """Root-mean-square layer normalization in float32.""" def __init__(self, dim, eps=1e-6): super().__init__() self.eps = eps4 unmodified lines return (y * torch.rsqrt(y.pow(2).mean(-1, keepdim=True) + self.eps)).type_as(x) * self.weight
class Layer(nn.Module): """TabDPT's layer (causalpfn's TransformerEncoderLayer), its parameter names kept: from the normalized input, attention to the context tokens and a gated feed-forward (of width E, from the same projection as the attention's queries) in parallel; their sum, projected and normalized, is added to the residual."""class ColBlock(nn.Module): """Column-to-column Pre-RMSNorm self-attention biased by the P x P correlation matrix R_jk.""" def __init__(self, dim, heads=4): super().__init__() self.H, self.d = heads, dim // heads self.attn_norm = RMSNorm(dim) self.qkv = nn.Linear(dim, 3 * dim, bias=False) self.out = nn.Linear(dim, dim, bias=False) self.bias_proj = nn.Linear(2, heads, bias=False) # [R_jk, |R_jk|] -> per-head bias self.ff_norm = RMSNorm(dim) self.ff_in = nn.Linear(dim, 4 * dim, bias=False) self.ff_out = nn.Linear(2 * dim, dim, bias=False)
def forward(self, c, R, w_mask): """c (B, P, D), R (B, P, P), w_mask (B, P) True = real column.""" B, P, D = c.shape q, k, v = self.qkv(self.attn_norm(c)).chunk(3, -1) q = q.view(B, P, self.H, self.d).transpose(1, 2) k = k.view(B, P, self.H, self.d).transpose(1, 2) v = v.view(B, P, self.H, self.d).transpose(1, 2) bias = self.bias_proj(torch.stack([R, R.abs()], -1)).permute(0, 3, 1, 2) # (B, H, P, P) # Mask out padded keys (keep self-diagonal valid so all-masked rows never produce NaN) pad = (~w_mask)[:, None, None, :].expand(B, 1, P, P) eye = torch.eye(P, dtype=torch.bool, device=c.device)[None, None] bias = bias.masked_fill(pad & ~eye, float("-inf")) a = F.scaled_dot_product_attention(q, k, v, attn_mask=bias).transpose(1, 2).reshape(B, P, D) c = c + self.out(a) h, g = self.ff_in(self.ff_norm(c)).chunk(2, -1) return (c + self.ff_out(h * F.silu(g))) * w_mask[..., None].to(c.dtype)
class RowPool(nn.Module): """Multi-slot cross-attention pooling over a row's P covariate cells: O(n * P * M).""" def __init__(self, col_dim, E, slots=8, heads=4): super().__init__() self.slots, self.H, self.d = slots, heads, col_dim // heads self.cell_val = mlp(2, col_dim, col_dim) # [w_ij, rank_ij] -> col_dim self.col_scale = nn.Linear(col_dim, col_dim) # multiplicative column modulation self.cell_norm = RMSNorm(col_dim) self.queries = nn.Parameter(torch.randn(slots, col_dim) / math.sqrt(col_dim)) self.q_proj = nn.Linear(col_dim, col_dim, bias=False) self.kv_proj = nn.Linear(col_dim, 2 * col_dim, bias=False) self.out_proj = nn.Linear(slots * col_dim, E, bias=False) self.ff_norm = RMSNorm(E) self.ff_in = nn.Linear(E, 4 * E, bias=False) self.ff_out = nn.Linear(2 * E, E, bias=False)
def forward(self, Wz, Rk, col_emb, w_mask): """Wz, Rk (B, n, P), col_emb (B, P, col_dim), w_mask (B, P) -> (B, n, E).""" B, n, P = Wz.shape E = self.ff_out.out_features if P == 0: return torch.zeros(B, n, E, device=Wz.device, dtype=Wz.dtype) D = col_emb.shape[-1] val = self.cell_val(torch.stack([Wz, Rk], -1)) # (B, n, P, D) scale = 1.0 + torch.tanh(self.col_scale(col_emb)) # (B, P, D) cells = self.cell_norm(val * scale[:, None] + col_emb[:, None]) cells = cells.reshape(B * n, P, D)
q = self.q_proj(self.queries).view(1, self.slots, self.H, self.d).transpose(1, 2) q = q.expand(B * n, -1, -1, -1) # (B*n, H, M, d) k, v = self.kv_proj(cells).chunk(2, -1) k = k.view(B * n, P, self.H, self.d).transpose(1, 2) # (B*n, H, P, d) v = v.view(B * n, P, self.H, self.d).transpose(1, 2)
# Mask padded covariate columns; if a table has 0 real columns, zero its output afterward has_any = w_mask.any(1) # (B,) safe_mask = torch.where(has_any[:, None], w_mask, torch.ones_like(w_mask)) attn_mask = (~safe_mask)[:, None, None, None, :].expand(B, n, 1, self.slots, P).reshape(B * n, 1, self.slots, P) attn_bias = torch.zeros_like(attn_mask, dtype=q.dtype).masked_fill(attn_mask, float("-inf")) pooled = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_bias) pooled = pooled.transpose(1, 2).reshape(B, n, self.slots * D) x = self.out_proj(pooled) h, g = self.ff_in(self.ff_norm(x)).chunk(2, -1) x = x + self.ff_out(h * F.silu(g)) return x * has_any[:, None, None].to(x.dtype)
class Block(nn.Module): """Pre-RMSNorm row attention to context keys/values + SwiGLU feed-forward.""" def __init__(self, E, H): super().__init__() self.H, self.d = H, E // H self.attn_norm = RMSNorm(E) self.q_proj = nn.Linear(E, E, bias=False) self.kv_proj = nn.Linear(E, 2 * E, bias=False) self.q_proj = nn.Linear(E, 3 * E, bias=False) # the queries, the feed-forward's value and gate self.out_proj = nn.Linear(E, E, bias=False) self.attn_norm, self.ff_norm = RMSNorm(E), RMSNorm(E) self.q_norm, self.k_norm = RMSNorm(self.d), RMSNorm(self.d) self.ff_norm = RMSNorm(E) self.ff_in = nn.Linear(E, 4 * E, bias=False) self.ff_out = nn.Linear(2 * E, E, bias=False)
def keys(self, ctx): """(k, v), each (N, H, n, d): the context tokens' keys and values for this layer.""" N, n, _ = ctx.shape """(k, v), each (B, H, n_ctx, d): context keys and values for this layer.""" B, n, _ = ctx.shape k, v = self.kv_proj(self.attn_norm(ctx)).chunk(2, -1) k = k.view(N, n, self.H, self.d).transpose(1, 2) v = v.view(N, n, self.H, self.d).transpose(1, 2) return self.k_norm(self.k_norm(k)), v # normalized twice, as TabDPT's are k = self.k_norm(k.view(B, n, self.H, self.d).transpose(1, 2)) v = v.view(B, n, self.H, self.d).transpose(1, 2) return k, v
def forward(self, x, k, v, mask=None): """x (N, L, E) tokens reading the context's keys and values k, v (N, H, n, d); mask (L, n) added to the attention logits (-inf: may not attend), or None.""" N, L, E = x.shape q, ff_h, ff_gate = self.q_proj(self.attn_norm(x)).chunk(3, -1) q = q.view(N, L, self.H, self.d).transpose(1, 2) q = self.q_norm(self.q_norm(q) * (math.log2(k.shape[2]) / 10)) a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask).transpose(1, 2).reshape(N, L, E) return x + self.ff_norm(self.out_proj(a + ff_h * F.silu(ff_gate)))
def _column_stats(X): """TabDPT's normalize_data and clip_outliers over the context rows X (B, n, F): the mean and sd (+1e-6) to standardize with, then the clip bounds of the standardized values (OUTLIER_SIGMA sd, the sd recomputed without the rows beyond them, around the first mean).""" n = X.shape[1] mean = X.mean(1, keepdim=True) sd = ((X - mean) ** 2).sum(1, keepdim=True).div(max(n - 1, 1)).sqrt() + 1e-6 Z = (X - mean) / sd zm = Z.mean(1, keepdim=True) cut = OUTLIER_SIGMA * ((Z - zm) ** 2).sum(1, keepdim=True).div(max(n - 1, 1)).sqrt() keep = ((Z - zm).abs() <= cut).float() km = (Z * keep).sum(1, keepdim=True) / keep.sum(1, keepdim=True).clamp(min=1) cut = OUTLIER_SIGMA * (((km - Z) * keep) ** 2).sum(1, keepdim=True).div( (keep.sum(1, keepdim=True) - 1).clamp(min=1)).sqrt() return mean, sd, zm - cut, zm + cut """x (B, L, E) tokens attending to context k, v (B, H, n_ctx, d); optional mask (L, n_ctx).""" B, L, E = x.shape q = self.q_proj(self.attn_norm(x)).view(B, L, self.H, self.d).transpose(1, 2) q = self.q_norm(q) * (math.log2(max(k.shape[2], 2)) / 8.0) a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask).transpose(1, 2).reshape(B, L, E) x = x + self.out_proj(a) h, g = self.ff_in(self.ff_norm(x)).chunk(2, -1) return x + self.ff_out(h * F.silu(g))
def _arm_scales(T, Y, values, binary): """CausalPFN's outcome scaling: binary tables, the mean and sd of Y within each arm (the other arm's if one is empty); continuous ones, over the table. Returns (row_shift, row_scale) (B, n) for each row's own arm and (shift, scale) (B, K) for each value's.""" """Standardize Y within each arm for binary treatments (over all context rows for continuous). Returns (row_shift, row_scale) (B, n_ctx) and (shift, scale) (B, K).""" mid = (T.amax(1, keepdim=True) + T.amin(1, keepdim=True)) / 2 treated, asked = (T > mid).float(), values > mid # (B, n), (B, K) treated, asked = (T > mid).float(), values > mid
def stats(w): c = w.sum(1, keepdim=True) m = (w * Y).sum(1, keepdim=True) / c.clamp(min=1) s = ((w * (Y - m) ** 2).sum(1, keepdim=True) / c.clamp(min=1)).sqrt() + 1e-20 s = ((w * (Y - m) ** 2).sum(1, keepdim=True) / c.clamp(min=1)).sqrt().clamp(min=1e-6) return m, s, c > 0
m1, s1, has1 = stats(treated) m0, s0, has0 = stats(1 - treated) m1, s1, m0, s0 = torch.where(has1, m1, m0), torch.where(has1, s1, s0), torch.where(has0, m0, m1), torch.where(has0, s0, s1) m1 = torch.where(has1, m1, m0) s1 = torch.where(has1, s1, s0) m0 = torch.where(has0, m0, m1) s0 = torch.where(has0, s0, s1) ma, sa, _ = stats(torch.ones_like(Y)) b = binary[:, None] row_shift = torch.where(b, torch.where(treated > 0, m1, m0), ma)3 unmodified lines return row_shift, row_scale, shift, scale
def _context_ranks(W_ctx, W_qry): """Within-column ranks in [-1, 1] for context and query rows, using the context distribution.""" B, n_ctx, P = W_ctx.shape if P == 0: return torch.zeros_like(W_ctx), torch.zeros_like(W_qry) srt = W_ctx.transpose(1, 2).contiguous().sort(-1).values
def rank_of(W): x = W.transpose(1, 2).contiguous() lo = torch.searchsorted(srt, x, right=False) hi = torch.searchsorted(srt, x, right=True) r = (lo + hi - 1).float() / max(n_ctx - 1, 1) - 1.0 return r.clamp(-1.0, 1.0).transpose(1, 2)
return rank_of(W_ctx), rank_of(W_qry)
def _column_stats_and_corr(Wz_ctx, Tz_ctx, Yg_ctx, w_mask, Rk_ctx, binary): """Exact permutation-equivariant column statistics (B, P, N_COL_STATS) and covariate correlation matrix R (B, P, P), computed strictly from context rows in float32. Includes global, rank (Spearman), and arm-conditional (high-T vs low-T) correlations and partial ridge slopes so treatment-effect modifiers are visible even under strong main effects.""" B, n, P = Wz_ctx.shape device, dtype = Wz_ctx.device, Wz_ctx.dtype if P == 0: return (torch.zeros(B, 0, N_COL_STATS, device=device, dtype=dtype), torch.zeros(B, 0, 0, device=device, dtype=dtype))
mask_f = w_mask.float() W = Wz_ctx.float() * mask_f[:, None, :] Rk = Rk_ctx.float() * mask_f[:, None, :] T = Tz_ctx.float() Y = Yg_ctx.float() ones = torch.ones(B, n, 1, device=device)
# Covariate correlation matrix R_jk (B, P, P) Wc = W - W.mean(1, keepdim=True) Wn = Wc / Wc.pow(2).sum(1, keepdim=True).sqrt().clamp(min=1e-6) R = torch.bmm(Wn.transpose(1, 2), Wn).clamp(-1.0, 1.0) pair_mask = mask_f[:, :, None] * mask_f[:, None, :] R = R * pair_mask
# Partial slopes of Y on [1, T, W, W * T] and T on [1, W] (algebraic invariants, as in axiom) D_y = torch.cat([ones, T[..., None], W, W * T[..., None]], -1) dy = D_y.shape[-1] pen_y = torch.empty(dy, device=device) pen_y[0], pen_y[1] = 1e-3 * n, 1e-2 * n pen_y[2:2 + P] = 0.05 * n pen_y[2 + P:] = 0.25 * n G_y = torch.bmm(D_y.transpose(1, 2), D_y) + torch.diag(pen_y)[None] beta_y = torch.linalg.solve(G_y, torch.bmm(D_y.transpose(1, 2), Y[..., None])).squeeze(-1) bw, bwt = beta_y[:, 2:2 + P], beta_y[:, 2 + P:]
D_t = torch.cat([ones, W], -1) pen_t = torch.full((1 + P,), 0.05 * n, device=device) pen_t[0] = 1e-3 * n G_t = torch.bmm(D_t.transpose(1, 2), D_t) + torch.diag(pen_t)[None] beta_t = torch.linalg.solve(G_t, torch.bmm(D_t.transpose(1, 2), T[..., None])).squeeze(-1)[:, 1:]
# Arm split: exact treated vs control for binary, above vs below median T for continuous mid = (T.amax(1, keepdim=True) + T.amin(1, keepdim=True)) / 2 med = T.median(1, keepdim=True).values thresh = torch.where(binary[:, None], mid, med) w_hi = (T > thresh).float() w_lo = 1.0 - w_hi
def arm_ridge(arm_w): cnt = arm_w.sum(1).clamp(min=1.0) # (B,) Dw = D_t * arm_w[..., None] G = torch.bmm(Dw.transpose(1, 2), D_t) pen = torch.full((B, 1 + P), 0.05, device=device) * cnt[:, None] pen[:, 0] = 1e-3 * cnt G = G + torch.diag_embed(pen) rhs = torch.bmm(Dw.transpose(1, 2), Y[..., None]) return torch.linalg.solve(G, rhs).squeeze(-1)[:, 1:] * mask_f
b_hi = arm_ridge(w_hi) b_lo = arm_ridge(w_lo)
def wcorr(A, b, w=None): if w is None: ac, bc = A - A.mean(1, keepdim=True), b - b.mean(1, keepdim=True) num = (ac * bc[..., None]).sum(1) den = (ac.pow(2).sum(1) * bc.pow(2).sum(1, keepdim=True)).sqrt().clamp(min=1e-6) else: ws = w.sum(1, keepdim=True).clamp(min=1.0) am = (w[..., None] * A).sum(1, keepdim=True) / ws[..., None] bm = (w * b).sum(1, keepdim=True) / ws ac, bc = A - am, b - bm num = (w[..., None] * ac * bc[..., None]).sum(1) den = ((w[..., None] * ac.pow(2)).sum(1) * (w * bc.pow(2)).sum(1, keepdim=True)).sqrt().clamp(min=1e-6) return (num / den).clamp(-1.0, 1.0)
# Context rank of Y in [-1, 1] for Spearman rank correlation (robust to heavy tails / exp links) y_srt = Y.sort(-1).values y_lo = torch.searchsorted(y_srt, Y, right=False) y_hi = torch.searchsorted(y_srt, Y, right=True) y_rk = ((y_lo + y_hi - 1).float() / max(n - 1, 1) - 1.0).clamp(-1.0, 1.0)
W2 = W.pow(2).clamp(max=25.0) c_hi = wcorr(W, Y, w_hi) c_lo = wcorr(W, Y, w_lo) c2_hi = wcorr(W2, Y, w_hi) c2_lo = wcorr(W2, Y, w_lo)
stats = torch.stack([ wcorr(W, Y), wcorr(W, T), wcorr(W2, Y), wcorr((W * T[..., None]).clamp(-25.0, 25.0), Y), wcorr(Rk, y_rk), c_hi, c_lo, c_hi - c_lo, c2_hi - c2_lo, torch.asinh(bw), torch.asinh(bwt), torch.asinh(beta_t), torch.asinh(b_hi), torch.asinh(b_hi - b_lo), ], -1) * mask_f[..., None] return stats.to(dtype), R.to(dtype)
def release_tag(): """The Hub tag of the weights released with this package version ("v0.1.0"), or None when the package is not installed (running from source without metadata).""" """The Hub tag of the weights released with this package version, or None when running from source.""" try: return f"v{version('axiom-effect')}" except PackageNotFoundError:2 unmodified lines
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); `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. `from_causalpfn` starts from CausalPFN's weights.""" """Pure, from-scratch factorized tabular PFN for causal effect estimation."""
@classmethod def from_pretrained(cls, pretrained_model_name_or_path, *, revision=None, strict=True, **kwargs): path = str(pretrained_model_name_or_path)6 unmodified lines f"not match this version of the code", stacklevel=2) return super().from_pretrained(path, revision=revision, strict=strict, **kwargs)
@classmethod def from_causalpfn(cls, path=None): """A network with CausalPFN's trained weights (causalpfn_v0.pt; default: downloaded from the Hub into ~/.cache/causalpfn, where the causalpfn package keeps it too) and the additions at their starting values. With a binary treatment and no graph it computes exactly what CausalPFN's network does.""" if path is None: path = hf_hub_download(CAUSALPFN_REPO, CAUSALPFN_FILE, cache_dir=os.path.join(os.path.expanduser("~"), ".cache", "causalpfn")) ckpt = torch.load(path, map_location="cpu", weights_only=True) # tensors and plain types only cfg = ckpt["model_config"]["model"] found = dict(E=cfg["emsize"], H=cfg["nhead"], layers=cfg["nlayers"], nbins=cfg["nbins"]) if found != CAUSALPFN_CONFIG or cfg["max_num_features"] != MAX_FEATURES or cfg["nhid_factor"] != 2: raise ValueError(f"{path}: a CausalPFN network of {cfg}, not the {CAUSALPFN_CONFIG} this code builds") model = cls(**CAUSALPFN_CONFIG) state = {k[len("model."):]: v for k, v in ckpt["model_state_dict"].items() if k.startswith("model.")} missing, unexpected = model.load_state_dict(state, strict=False) additions = {n for n, _ in model.named_parameters()} - set(state) if unexpected or set(missing) != additions or any(n.split(".")[0] not in ADDITIONS for n in additions): raise ValueError(f"{path} does not match the network: missing {missing}, unexpected {unexpected}") return model
def __init__(self, E=384, H=6, layers=20, nbins=NBINS, vmax=VMAX, sigma=SIGMA): def __init__(self, E=384, H=6, layers=12, col_dim=64, col_layers=2, row_slots=16, nbins=NBINS, vmax=VMAX, sigma=SIGMA): super().__init__() self.config = dict(architecture=ARCHITECTURE, E=E, H=H, layers=layers, nbins=nbins, vmax=vmax, sigma=sigma) # CausalPFN's network, its parameter names kept (the checkpoint's, without "model.") self.encoder = nn.Linear(MAX_FEATURES, E) self.y_encoder = nn.Linear(1, E) self.xnorm, self.ynorm = nn.LayerNorm(E, bias=False), nn.LayerNorm(E, bias=False) self.transformer_encoder = nn.ModuleList(Layer(E, H) for _ in range(layers)) self.head = nn.Sequential(nn.Linear(E, 2 * E, bias=False), nn.GELU(), nn.Linear(2 * E, N_OUT + nbins, bias=False)) # the additions (ADDITIONS), none on mu's path at the start self.roles = nn.Linear(2 * MAX_COVARIATES * N_FEATURES, E, bias=False) # role features, and x role nn.init.zeros_(self.roles.weight) self.t_unknown = nn.Parameter(0.02 * torch.randn(E)) # the t-blind query's treatment self.final = RMSNorm(E) # the t-blind and context tokens, for the heads below self.propensity = nn.Linear(E, 1) # binary: logit P(T = 1 | W) self.treatment = nn.Linear(E, 2) # continuous: mean, log sd of T | W # an estimand's quantile widths, from: the plug-in, the spread of the rows' effects, # the rows' mean query token, the table summary, both values' embeddings, the rows' # count and share, binary self.config = dict(architecture=ARCHITECTURE, E=E, H=H, layers=layers, col_dim=col_dim, col_layers=col_layers, row_slots=row_slots, nbins=nbins, vmax=vmax, sigma=sigma) # Stage 1: Column self-attention encoder self.col_in = mlp(N_COL_STATS + N_FEATURES, col_dim, col_dim) self.col_blocks = nn.ModuleList(ColBlock(col_dim, heads=4) for _ in range(col_layers)) self.col_norm = RMSNorm(col_dim) # Stage 2: Multi-slot cross-attention row encoder self.row_pool = RowPool(col_dim, E, slots=row_slots, heads=4) # Stage 3: Row transformer self.t_embed = mlp(2, E, E) # [standardized T, binary flag] self.y_embed = nn.Linear(1, E) # standardized Y (arm-scaled for binary) self.ctx_norm = RMSNorm(E) self.qry_norm = RMSNorm(E) self.blocks = nn.ModuleList(Block(E, H) for _ in range(layers)) # Stage 4: Direct HL-Gauss head + detached width head self.head_norm = RMSNorm(E) self.head = nn.Sequential(nn.Linear(E, 2 * E, bias=False), nn.GELU(), nn.Linear(2 * E, nbins, bias=False)) self.widths = mlp(2 + 4 * E + 3, E, len(QUANTILES) - 1) edges = torch.linspace(-vmax, vmax, nbins + 1) # buffers rebuilt from the config, not saved with the weights self.register_buffer("edges", edges, persistent=False) self.register_buffer("centers", (edges[1:] + edges[:-1]) / 2, persistent=False) self.recompute = False # training: recompute activations in the backward pass (less memory) 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 _embed(self, W, features, w_mask): """(B, n, E) each row's embedding without its treatment slot's term (the covariate slots through `encoder`, plus their roles through `roles`), and the treatment slot's weight (E,): a row's embedding at a standardized treatment z is the first + z * the second, as `encoder` of the full row would give.""" B, n, P = W.shape W = F.pad(W, (0, MAX_COVARIATES - P)) # zero slots, as CausalPFN pads feats = F.pad(features * w_mask[..., None], (0, 0, 0, MAX_COVARIATES - P)) # (B, 99, N_FEATURES) prod = (W[..., None] * feats[:, None]).flatten(-2) # (B, n, 99 * N_FEATURES) role_in = torch.cat([prod, feats.flatten(-2)[:, None].expand(B, n, -1)], -1) x = F.linear(W, self.encoder.weight[:, 1:], self.encoder.bias) + self.roles(role_in) return x, self.encoder.weight[:, 0]
def forward(self, W, T, Y, w_mask, features, binary, values, chunk=None, self_mask=True): """W (B, n, P) covariates, w_mask (B, P) True = a real covariate, features (B, P, N_FEATURES), T and Y (B, n), binary (B,) bool, values (B, K) treatment values to predict mu at (on T's scale). `chunk`: query tokens at a time (each row is K + 1 of them; default all). self_mask=False lets a row's query read its own context token, as CausalPFN's estimator does at inference (for comparison with it only).""" def _encode_columns(self, col_stats, features, R, w_mask): if col_stats.shape[1] == 0: return torch.zeros(col_stats.shape[0], 0, self.config["col_dim"], device=col_stats.device, dtype=col_stats.dtype) c = self.col_in(torch.cat([col_stats, features], -1)) * w_mask[..., None].to(col_stats.dtype) for blk in self.col_blocks: c = blk(c, R, w_mask) return self.col_norm(c) * w_mask[..., None].to(col_stats.dtype)
def _embed_t(self, t_vals, binary): """t_vals (B, L) -> (B, L, E).""" b = binary.to(t_vals.dtype)[:, None].expand_as(t_vals) return self.t_embed(torch.stack([t_vals, b], -1))
def forward(self, W, T, Y, w_mask, features, binary, values, n_ctx=None, W_qry=None, chunk=None, self_mask=True): """ W (B, n, P), T (B, n), Y (B, n): context (and, when n_ctx is None and W_qry is None, query) rows. w_mask (B, P): True for real covariates (False for batch padding). features (B, P, N_FEATURES): [graph_given, 4 role indicators]. binary (B,) bool: treatment type per table. values (B, K): treatment values to evaluate mu at (on T's scale). n_ctx: if given (training), first n_ctx rows are context and remaining rows are queries. W_qry: if given (localized inference), explicit (B, n_qry, P) query covariates. self_mask: when predicting on the same table (n_ctx is None and W_qry is None), mask each query row from attending to its own context token. """ B, n, P = W.shape if P > MAX_COVARIATES: raise ValueError(f"{P} covariates: the network has slots for at most {MAX_COVARIATES}") E, K = self.config["E"], values.shape[1] binary = torch.as_tensor(binary, dtype=torch.bool, device=W.device) cols = torch.cat([T[..., None], W * w_mask[:, None].float()], -1) # (B, n, 1 + P) mean, sd, lo, hi = _column_stats(cols) Z = torch.minimum(torch.maximum((cols - mean) / sd, lo), hi) tz = lambda t: torch.minimum(torch.maximum((t - mean[..., 0]) / sd[..., 0], lo[..., 0]), hi[..., 0]) x, w_t = self._run(self._embed, Z[..., 1:], features, w_mask) # (B, n, E), (E,) row_shift, row_scale, shift, scale = _arm_scales(T, Y, values, binary) y = (Y - row_shift) / row_scale ctx = self.xnorm(x + Z[..., :1] * w_t) + self.ynorm(self.y_encoder(y[..., None]))
def context_layer(ctx, layer): k, v = layer.keys(ctx) return layer(ctx, k, v), k, v
same_table = W_qry is None and n_ctx is None if W_qry is not None: W_ctx, T_ctx, Y_ctx = W, T, Y elif n_ctx is not None: W_ctx, T_ctx, Y_ctx = W[:, :n_ctx], T[:, :n_ctx], Y[:, :n_ctx] W_qry = W[:, n_ctx:] else: W_ctx, T_ctx, Y_ctx, W_qry = W, T, Y, W
n_c, n_q = W_ctx.shape[1], W_qry.shape[1]
# Standardize W, T, Y strictly from context rows if P > 0: w_mean = W_ctx.mean(1, keepdim=True) w_sd = W_ctx.std(1, keepdim=True, unbiased=False).clamp(min=1e-6) Wz_ctx = ((W_ctx - w_mean) / w_sd).clamp(-CLIP_SIGMA, CLIP_SIGMA) * w_mask[:, None].to(W.dtype) Wz_qry = ((W_qry - w_mean) / w_sd).clamp(-CLIP_SIGMA, CLIP_SIGMA) * w_mask[:, None].to(W.dtype) else: Wz_ctx, Wz_qry = W_ctx, W_qry
t_mean = T_ctx.mean(1, keepdim=True) t_sd = T_ctx.std(1, keepdim=True, unbiased=False).clamp(min=1e-6) Tz_ctx = ((T_ctx - t_mean) / t_sd).clamp(-CLIP_SIGMA, CLIP_SIGMA) Vz = ((values - t_mean) / t_sd).clamp(-CLIP_SIGMA, CLIP_SIGMA)
y_gmean = Y_ctx.mean(1, keepdim=True) y_gsd = Y_ctx.std(1, keepdim=True, unbiased=False).clamp(min=1e-6) Yg_ctx = ((Y_ctx - y_gmean) / y_gsd).clamp(-CLIP_SIGMA, CLIP_SIGMA) row_shift, row_scale, shift, scale = _arm_scales(T_ctx, Y_ctx, values, binary) Yz_ctx = ((Y_ctx - row_shift) / row_scale).clamp(-CLIP_SIGMA, CLIP_SIGMA)
# Stage 1: Column self-attention over exact context statistics + correlation matrix R_jk Rk_ctx, Rk_qry = _context_ranks(Wz_ctx, Wz_qry) col_stats, R = _column_stats_and_corr(Wz_ctx, Tz_ctx, Yg_ctx, w_mask, Rk_ctx, binary) col_emb = self._encode_columns(col_stats, features, R, w_mask)
# Stage 2: Multi-slot cross-attention row encoder x_ctx = self._run(self.row_pool, Wz_ctx, Rk_ctx, col_emb, w_mask) x_qry = x_ctx if same_table else self._run(self.row_pool, Wz_qry, Rk_qry, col_emb, w_mask)
# Stage 3: Row transformer (context self-attention, then query cross-attention) ctx = self.ctx_norm(x_ctx + self._embed_t(Tz_ctx, binary) + self.y_embed(Yz_ctx[..., None]))
def ctx_step(h, blk): k, v = blk.keys(h) return blk(h, k, v), k, v
kvs = [] for layer in self.transformer_encoder: ctx, k, v = self._run(context_layer, ctx, layer) for blk in self.blocks: ctx, k, v = self._run(ctx_step, ctx, blk) kvs.append((k, v))
J = K + 1 # the values asked about, then the t-blind token told = torch.cat([tz(values)[..., None] * w_t, self.t_unknown.expand(B, 1, E)], 1) # (B, J, E) step = max(1, chunk // J) if chunk else n t_val_emb = self._embed_t(Vz, binary) # (B, K, E) step = max(1, chunk // K) if chunk else n_q out = [] for s in range(0, n, step): xs = x[:, s:s + step] for s in range(0, n_q, step): xs = x_qry[:, s:s + step] Q = xs.shape[1] q = self.xnorm(xs[:, None] + told[:, :, None]).reshape(B, J * Q, E) q = self.qry_norm(xs[:, None] + t_val_emb[:, :, None]).reshape(B, K * Q, E) mask = None if self_mask: mask = torch.zeros(Q, n, dtype=q.dtype, device=W.device) mask[torch.arange(Q), torch.arange(s, s + Q)] = float("-inf") # not its own row mask = mask.repeat(J, 1) for layer, (k, v) in zip(self.transformer_encoder, kvs): q = self._run(layer, q, k, v, mask) out.append(q.view(B, J, Q, E)) q = torch.cat(out, 2) # (B, J, n, E) pred = self.head(q[:, :K]) logits = (LOGIT_CAP * torch.tanh(pred / (7.5 * E ** 0.5)))[..., -self.config["nbins"]:] # (B, K, n, nbins) mu = (logits.softmax(-1) * self.centers).sum(-1) * scale[..., None] + shift[..., None] blind = self.final(q[:, K]) t_mean, t_logsd = self.treatment(blind).unbind(-1) return Rows(blind, self.final(ctx).mean(1), mu, logits, shift, scale, self.propensity(blind)[..., 0], t_mean, t_logsd.clamp(-5, 3), values, binary) if same_table and self_mask and n_c > 1: mask = torch.zeros(Q, n_c, dtype=q.dtype, device=W.device) mask[torch.arange(Q, device=W.device), torch.arange(s, s + Q, device=W.device)] = float("-inf") mask = mask.repeat(K, 1) for blk, (k, v) in zip(self.blocks, kvs): q = self._run(blk, q, k, v, mask) out.append(q.view(B, K, Q, E)) q = torch.cat(out, 2) # (B, K, n_q, E)
# Stage 4: Direct HL-Gauss outcome distribution q_norm = self.head_norm(q) logits = self.head(q_norm) # (B, K, n_q, nbins) bin_mean = (logits.softmax(-1) * self.centers).sum(-1) mu = shift[..., None] + scale[..., None] * bin_mean return Rows(q_norm.mean(1), self.head_norm(ctx).mean(1), mu, logits, shift, scale, values, binary)
def mu_nll(self, rows, target): """(B, K, n) CausalPFN's HL-Gauss loss of mu's distribution against the true mu (B, K, n), on the scale the network predicts on (each value's arm's): the cross-entropy with a Gaussian of sd `sigma` around the truth, integrated over the bins (the truth clipped to the bins' range).""" """(B, K, n_qry) HL-Gauss cross-entropy against target on the arm's standardized scale.""" p = self._hl_target(rows, target) return -(p * rows.logits.log_softmax(-1)).sum(-1)
def mu_floor(self, rows, target): """(B, K, n) the entropy of mu_nll's target distribution: its value for a perfect prediction, so mu_nll minus it (the KL from the target) is the part training can lower.""" """(B, K, n_qry) entropy of the HL-Gauss target: the loss of a perfect prediction.""" p = self._hl_target(rows, target) return -torch.special.xlogy(p, p).sum(-1)
def _hl_target(self, rows, target): """(B, K, n, nbins) the HL-Gauss target: a Gaussian of sd `sigma` around the true mu on the arm's scale (clipped to the bins' range), integrated over the bins.""" t = ((target - rows.shift[..., None]) / rows.scale[..., None]).clamp(-self.config["vmax"], self.config["vmax"]) p = torch.special.ndtr((self.edges - t[..., None]) / self.config["sigma"]).diff(dim=-1) return p / (p.sum(-1, keepdim=True) + 1e-8)
def estimands(self, rows, pairs, weights): """Quantiles (B, S, len(QUANTILES)) of S average effects: estimand s moves the treatment from values[:, pairs[s, 0]] to values[:, pairs[s, 1]], averaged over the rows with weights[:, s] (B, S, n) (1 / 0 masks: all rows the ATE, the treated rows the ATT). The median is the weighted mean of the rows' effects; the widths are learned, from the network's outputs detached (their loss trains `widths` alone), and antisymmetric: a -> b is minus b -> a.""" """Quantiles (B, S, len(QUANTILES)) of S average effects, detached from the main network. Antisymmetric (a -> b is minus b -> a) and exactly 0 for a -> a.""" i, j = pairs[:, 0], pairs[:, 1] mu, query, context = rows.mu.detach(), rows.query.detach(), rows.context.detach() w = weights.float() tot = w.sum(-1).clamp(min=1e-6) # (B, S) tot = w.sum(-1).clamp(min=1e-6) n = w.shape[-1] phi = self._value_features(rows.values) pooled = (w[..., None] * query[:, None]).sum(2) / tot[..., None] # (B, S, E) phi = self._embed_t(rows.values, rows.binary).detach() pooled = (w[..., None] * query[:, None]).sum(2) / tot[..., None] context = context[:, None].expand_as(pooled)
def one_way(a, b): d = mu[:, b] - mu[:, a] # (B, S, n) d = mu[:, b] - mu[:, a] est = (w * d).sum(-1) / tot spread = ((w * (d - est[..., None]) ** 2).sum(-1) / tot).sqrt() spread = ((w * (d - est[..., None]) ** 2).sum(-1) / tot).clamp(min=0).sqrt() feats = torch.cat([est[..., None], spread[..., None], pooled, context, phi[:, a], phi[:, b], (torch.log(tot) / np.log(N_REF))[..., None], (tot / n)[..., None], (torch.log(tot) / math.log(N_REF))[..., None], (tot / n)[..., None], rows.binary.float()[:, None, None].expand_as(est[..., None])], -1) moved = (rows.values[:, a] != rows.values[:, b]).float()[..., None] # a -> a: exactly 0 moved = (rows.values[:, a] != rows.values[:, b]).float()[..., None] steps = F.softplus(self.widths(feats)) * moved lower = est[..., None] - steps[..., :MID].flip(-1).cumsum(-1).flip(-1) upper = est[..., None] + steps[..., MID:].cumsum(-1)1 unmodified line
return (one_way(i, j) - one_way(j, i).flip(-1)) / 2
def _value_features(self, values): """(B, K, E) a treatment value's embedding for the width head: the treatment slot's term of the row embedding, detached.""" return (values[..., None] * self.encoder.weight[:, 0]).detach()
def treatment_nll(self, rows, T): """(B, n) negative log-likelihood of each row's treatment given its covariates: Bernoulli on binary tables, Gaussian on continuous ones.""" mid = (T.amax(1, keepdim=True) + T.amin(1, keepdim=True)) / 2 bern = F.binary_cross_entropy_with_logits(rows.logit, (T > mid).float(), reduction="none") gauss = -torch.distributions.Normal(rows.t_mean, rows.t_logsd.exp()).log_prob(T.clamp(-OUTLIER_SIGMA, OUTLIER_SIGMA)) return torch.where(rows.binary[:, None], bern, gauss)
@torch.no_grad() def predict(self, W, T, Y, features, binary, values, estimands=(), chunk=4096): """One standardized table, as numpy: W (n, p), T and Y (n,), features (p, N_FEATURES), binary, values (K,), estimands [(a, b, rows)] with a, b indices into values and rows an (n,) bool mask. Returns mu (K, n), quantiles (len(estimands), len(QUANTILES)), and the propensity: e (n,) P(T = 1 | w_i) for a binary treatment, else t_mean and t_sd (n,).""" def predict(self, W, T, Y, features, binary, values, estimands=(), chunk=4096, W_qry=None, tta=1, seed=0): """One standardized table, as numpy: W (n_ctx, p), T and Y (n_ctx,), features (p, N_FEATURES), binary, values (K,), estimands [(a, b, rows)], optional W_qry (n_qry, p). Deterministic (no random column codes); `tta` and `seed` kept for API compatibility.""" device = next(self.parameters()).device f = lambda a: torch.as_tensor(np.asarray(a, dtype=np.float32), device=device)[None] W = np.asarray(W, dtype=np.float32).reshape(len(T), -1) P = W.shape[1] Wq_t = f(np.asarray(W_qry, dtype=np.float32).reshape(-1, P)) if W_qry is not None else None with eval_mode(self): rows = self(f(W), f(T), f(Y), torch.ones(1, W.shape[1], dtype=torch.bool, device=device), f(np.asarray(features, dtype=np.float32).reshape(W.shape[1], N_FEATURES)), torch.tensor([bool(binary)], device=device), f(values), chunk=chunk) rows = self(f(W), f(T), f(Y), torch.ones(1, P, dtype=torch.bool, device=device), f(np.asarray(features, dtype=np.float32).reshape(P, N_FEATURES)), torch.tensor([bool(binary)], device=device), f(values), W_qry=Wq_t, chunk=chunk) out = {"mu": rows.mu[0].cpu().numpy()} if estimands: pairs = torch.tensor([[a, b] for a, b, _ in estimands], device=device) weights = f(np.stack([np.asarray(r, dtype=np.float32) for _, _, r in estimands])) out["quantiles"] = self.estimands(rows, pairs, weights)[0].cpu().numpy() if binary: out["e"] = torch.sigmoid(rows.logit[0]).cpu().numpy() else: out["t_mean"], out["t_sd"] = rows.t_mean[0].cpu().numpy(), rows.t_logsd[0].exp().cpu().numpy() return out
def effect(self, data, treatment, outcome, **kwargs):1 unmodified line `axiom_effect.inference.effect(self, ...)`, which see.""" from .inference import effect return effect(self, data, treatment, outcome, **kwargs)
ADDITIONS = ("roles", "t_unknown", "final", "propensity", "treatment", "widths") # parameters CausalPFN has notLICENSE-CausalPFNDeleted-175
NOTICEDeleted-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