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 lines161718192021222324252627282930313233343536373 unmodified lines4142434445464748 unmodified lines9697989910010110210310410510610715 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.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 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:[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 || 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## VersionsEach 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:```bashpip install "git+https://huggingface.co/maxpagels/axiom-effect@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.15 unmodified lines16171819202122232425262728293031323 unmodified lines3637383940414248 unmodified lines91929394959697989915 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.**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 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.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-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## VersionsEach 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 install a specific release,an earlier one included, use its tag:```bashpip install "git+https://huggingface.co/maxpagels/axiom-effect@v0.2.0" # or an earlier tag, e.g. @v0.1.0```
12345678{"E": 384,"H": 6,"layers": 20,"nbins": 1024,"sigma": 0.5,"vmax": 10.0}1234567891011{"E": 384,"H": 6,"col_dim": 64,"col_layers": 2,"layers": 12,"nbins": 256,"row_slots": 16,"sigma": 0.4,"vmax": 10.0}
123version https://git-lfs.github.com/spec/v1oid sha256:0166cfb102eebd773db587f9e92326e5663d53299aa99f0c809fbb4be8df6d9csize 79287324123version https://git-lfs.github.com/spec/v1oid sha256:a45233de83ce1ba99df0f33fdbca52cc5ebb6572b44e895155a7a0c4370cfc71size 81332280
123456789101112[project]name = "axiom-effect"version = "0.1.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"]dependencies = ["huggingface-hub>=2.1", "numpy>=2.0", "safetensors>=0.4", "torch>=2.4"][project.urls]123456789101112[project]name = "axiom-effect"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"]dependencies = ["huggingface-hub>=2.1", "numpy>=2.0", "safetensors>=0.4", "torch>=2.4"][project.urls]
12345"""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),whose discovered graphs it reads.from axiom_effect import AxiomEffect12345"""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 Discovery (axiom-discovery),whose discovered graphs it reads.from axiom_effect import AxiomEffect
6 unmodified lines789101112134 unmodified lines18192021222324252627282 unmodified lines3132333435363738394041424344454647484959 unmodified lines10911011111211311411514 unmodified lines13013113213313413513669 unmodified lines2062072082092102112122132142152162172182192202214 unmodified lines22622722822923023123223323410 unmodified lines24524624724824925025125222 unmodified lines27527627727827928028128228328428528628728828928 unmodified lines31831932032132232332432532632732832933033133222 unmodified lines3553563573583593603613623633643653663673683693703713723733743753763773784 unmodified lines3833843853863873883893903913923933943953965 unmodified lines4024034044054064074084094106 unmodified linesprint(r)r.ate, r.att, r.cate, r.curve, r.debiasedWhat the graph does (design-effect.md, "Axiom discovery and the effect model"):none every other column (or `covariates`) is taken as pre-treatment: none of themmay 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 linescovariate's role probabilities (averaged over DAGs sampled from them), and themodel 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."""import warningsfrom dataclasses import dataclass, field2 unmodified linesimport numpy as npfrom .graph import CONF, N_ROLES, ROLE_NAMES, descendants, discovered_roles, is_dag, rolesfrom .model import MAX_COVARIATES, MID, N_FEATURES, QUANTILESTRAIN_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, 1024MIN_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 propensityZ90 = NormalDist().inv_cdf(0.95)59 unmodified linesg = 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 "")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 linesf" 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))}, "f"10-90% {g(np.quantile(self.cate, 0.1))} to {g(np.quantile(self.cate, 0.9))}")return "\n".join(lines)69 unmodified linesreturn (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'sTruncatedSVD 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 themedians, and each quantile's distance from the median combined as for a mean ofindependent estimates, sqrt(sum (m_k d_k)^2) / sum m_k."""qs, m = np.asarray(qs), np.asarray(counts, dtype=float)4 unmodified linesreturn mid + np.sign(off.mean(0)) * np.sqrt(((m[:, None] * off) ** 2).sum(0)) / m.sum()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)."""A = np.column_stack([np.ones(len(X)), X])P = ridge * np.eye(A.shape[1])P[0, 0] = 0.010 unmodified linesdef _propensity(C, t, seed=0):"""(n,) P(t = 1 | C), each row's from a logistic regression fitted on the other folds, onstandardized covariates: a row's own treatment never enters its propensity."""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 linesdef effect(model, data, treatment, outcome, graph=None, covariates=None, values=None, contrast=None,reference=None, names=None, extrapolate=False, discovery_samples=64, 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 moduledocstring): a DAG as an edge list of (cause, effect) names, a (d, d) matrix or anadjacency DataFrame, or a discover() result. `covariates`: the columns to adjust for(default: all others). Continuous treatments: `contrast` (a, b), default its 25% and75% quantiles; `values` the curve's treatment values, default its 10/25/50/75/90%quantiles; `reference` where the curve starts, default the median; values outsidethe 2-98% quantiles are refused unless `extrapolate`. Returns an EffectResult."""X, names = _table(data, names)t, y = _column(treatment, names, "treatment"), _column(outcome, names, "outcome")if t == y:28 unmodified linesn = 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 readsif 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: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 linesk = {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_Nparts = [np.arange(n)] if n <= most else np.array_split(rng.permutation(n), -(-n // most))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])vz = (np.array(vals) - tm) / tsall_rows = np.ones(len(rows), dtype=bool)jobs = [(k[a], k[b], all_rows, "contrast")]if binary:treated = T[rows] == levels[1]jobs += [(k[a], k[b], treated, "att"), (k[a], k[b], ~treated, "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])Q = out["quantiles"] * yscurve = []for (_, _, r, name), q in zip(jobs, Q):4 unmodified linescounts[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]]) * ysif binary:mu0[rows], mu1[rows] = out["mu"][k[a]] * ys + ym, out["mu"][k[b]] * ys + ymquantiles = {name: _combine(est[name], counts[name]) for name in est if name != "curve"}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),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 linesf"estimates there rest on extrapolation", stacklevel=3)else:result.values, result.reference = curve_vals, refC = 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: nothingif zero:warnings.warn(f"the graph has no directed path from {names[t]} to {names[y]}: every effect is exactly 0",stacklevel=3)6 unmodified lines789101112134 unmodified lines181920212223242526272 unmodified lines30313233343536373839404142434445464759 unmodified lines10710810911011111211314 unmodified lines12812913013113213313469 unmodified lines2042052062072082092102114 unmodified lines21621721821922022122222322422522622722822923023123223323423523623723823924024124224310 unmodified lines25425525625725825926022 unmodified lines28328428528628728828929029129229329429528 unmodified lines32432532632732832933033122 unmodified lines3543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853864 unmodified lines3913923933943953963973983994004014024034045 unmodified lines4104114124134144154164174186 unmodified linesprint(r)r.ate, r.att, r.cate, r.curve, r.debiasedWhat the graph does:none every other column (or `covariates`) is taken as pre-treatment: none of themmay 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 linescovariate's role probabilities (averaged over DAGs sampled from them), and themodel reads them; nothing is dropped, since a discovered edge can be wrong.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 npfrom .graph import CONF, N_ROLES, ROLE_NAMES, descendants, discovered_roles, is_dag, rolesfrom .model import MID, N_FEATURES, QUANTILESTRAIN_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 # cross-fitted logistic propensityZ90 = NormalDist().inv_cdf(0.95)59 unmodified linesg = 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} 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 linesf" 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))}, "f"10-90% {g(np.quantile(self.cate, 0.1))} to {g(np.quantile(self.cate, 0.9))}")return "\n".join(lines)69 unmodified linesreturn (v - mu) / np.where(sd > 0, sd, 1.0), mu, np.where(sd > 0, sd, 1.0)def _combine(qs, counts):"""Quantiles of one estimand from disjoint query strata: the count-weighted mean of themedians, and each quantile's distance from the median combined as for a mean ofindependent estimates, sqrt(sum (m_k d_k)^2) / sum m_k."""qs, m = np.asarray(qs), np.asarray(counts, dtype=float)4 unmodified linesreturn 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 bytreatment 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()) / 2tr = 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: 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 linesdef _propensity(C, t, seed=0):"""(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 linesdef effect(model, data, treatment, outcome, graph=None, covariates=None, values=None, contrast=None,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: 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-timeaugmentation passes (default 4; averages over random column tie-breaker codes with zeroextra 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 linesn = len(X)if n < TRAIN_N[0]:warnings.warn(f"{n} rows is below the training range {TRAIN_N}", stacklevel=3)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 linesk = {v: i for i, v in enumerate(vals)}rng = np.random.default_rng(seed)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 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) / wselse: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) / tsall_q = np.ones(len(q_rows), dtype=bool)jobs = [(k[a], k[b], all_q, "contrast")]if binary: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_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"] * yscurve = []for (_, _, r, name), q in zip(jobs, Q):4 unmodified linescounts[name].append(r.sum())if curve:est["curve"].append(np.stack(curve))counts["curve"].append(len(q_rows))cate[q_rows] = (out["mu"][k[b]] - out["mu"][k[a]]) * ysif binary:mu0[q_rows], mu1[q_rows] = out["mu"][k[a]] * ys + ym, out["mu"][k[b]] * ys + ymquantiles = {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(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 linesf"estimates there rest on extrapolation", stacklevel=3)else:result.values, result.reference = curve_vals, refC_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.0if zero:warnings.warn(f"the graph has no directed path from {names[t]} to {names[y]}: every effect is exactly 0",stacklevel=3)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555 unmodified lines6162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041054 unmodified lines1101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801813 unmodified lines1851861871881891901911921932 unmodified lines1961971981992002012022032042056 unmodified lines2122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813821 unmodified line3843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234241 unmodified line426427428429430431"""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 atOUTLIER_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 embeddingwith the treatment slot set to the value asked about. Outcomes are standardized withineach 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 agated feed-forward in parallel; their sum projected, normalized and added to theresidual. Queries and keys normalized per head (twice, with the queries scaled bylog2(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_OUToutputs are TabDPT's class logits, unused), soft-capped at +-30; trained with the HL-Gaussloss (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 rolerelative 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 binaryone.- Context and query rows are the same rows: a row's query never attends to its own contexttoken (CausalPFN trains on held-out query rows), so it never reads its own outcome ortreatment 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'splace), 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, anysubgroup): the median is the plug-in, the mean of the rows' effects; the widths are ahead of their own that reads the network's outputs detached, so its loss never moves them.from axiom_effect import AxiomEffectmodel = AxiomEffect.from_pretrained("path/or/hub-repo")r = model.effect(df, treatment="price", outcome="sales", graph=g) # axiom_effect.inferenceEverything inside is on the table's standardized scale."""import mathimport os5 unmodified linesimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom huggingface_hub import PyTorchModelHubMixin, hf_hub_downloadfrom huggingface_hub.errors import RevisionNotFoundErrorfrom torch.utils.checkpoint import checkpointfrom .blocks import eval_mode, mlpfrom .graph import N_ROLESARCHITECTURE = "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%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)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, normalizedcontext: torch.Tensor # (B, E) mean context token, normalized: a summary of the tablemu: torch.Tensor # (B, K, n) mu(values[k], w_i), standardized outcome: the mean of mu's distributionlogits: torch.Tensor # (B, K, n, nbins) mu's distribution over the bins, on the arm's scaleshift: 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 sdlogit: 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_it_logsd: torch.Tensor # (B, n) continuous tables: log sd of T | w_ivalues: torch.Tensor # (B, K) the treatment values asked aboutbinary: torch.Tensor # (B,) boolclass RMSNorm(nn.Module):"""TabDPT's RMSNorm (eps 1e-6, computed in float32)."""def __init__(self, dim, eps=1e-6):super().__init__()self.eps = eps4 unmodified linesreturn (y * torch.rsqrt(y.pow(2).mean(-1, keepdim=True) + self.eps)).type_as(x) * self.weightclass Layer(nn.Module):"""TabDPT's layer (causalpfn's TransformerEncoderLayer), its parameter names kept: from thenormalized 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 andnormalized, is added to the residual."""def __init__(self, E, H):super().__init__()self.H, self.d = H, E // Hself.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 gateself.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)def keys(self, ctx):"""(k, v), each (N, H, n, d): the context tokens' keys and values for this layer."""N, n, _ = ctx.shapek, 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 aredef 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.shapeq, 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 andsd (+1e-6) to standardize with, then the clip bounds of the standardized values (OUTLIER_SIGMAsd, 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-6Z = (X - mean) / sdzm = 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 + cutdef _arm_scales(T, Y, values, binary):"""CausalPFN's outcome scaling: binary tables, the mean and sd of Y within each arm (theother 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."""mid = (T.amax(1, keepdim=True) + T.amin(1, keepdim=True)) / 2treated, asked = (T > mid).float(), values > mid # (B, n), (B, K)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-20return m, s, c > 0m1, 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)ma, sa, _ = stats(torch.ones_like(Y))b = binary[:, None]row_shift = torch.where(b, torch.where(treated > 0, m1, m0), ma)3 unmodified linesreturn row_shift, row_scale, shift, scaledef release_tag():"""The Hub tag of the weights released with this package version ("v0.1.0"), or Nonewhen the package is not installed (running from source without metadata)."""try:return f"v{version('axiom-effect')}"except PackageNotFoundError:2 unmodified linesclass 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 andconfig.json (the __init__ arguments); `from_pretrained` rebuilds it. From a Hub repo itloads the weights released with this package version (the repo's `v<version>` tag)unless `revision` says otherwise. `from_causalpfn` starts from CausalPFN's weights."""@classmethoddef from_pretrained(cls, pretrained_model_name_or_path, *, revision=None, strict=True, **kwargs):path = str(pretrained_model_name_or_path)6 unmodified linesf"not match this version of the code", stacklevel=2)return super().from_pretrained(path, revision=revision, strict=strict, **kwargs)@classmethoddef from_causalpfn(cls, path=None):"""A network with CausalPFN's trained weights (causalpfn_v0.pt; default: downloadedfrom the Hub into ~/.cache/causalpfn, where the causalpfn package keeps it too) and theadditions at their starting values. With a binary treatment and no graph it computesexactly 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 onlycfg = 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 modeldef __init__(self, E=384, H=6, layers=20, 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 startself.roles = nn.Linear(2 * MAX_COVARIATES * N_FEATURES, E, bias=False) # role features, and x rolenn.init.zeros_(self.roles.weight)self.t_unknown = nn.Parameter(0.02 * torch.randn(E)) # the t-blind query's treatmentself.final = RMSNorm(E) # the t-blind and context tokens, for the heads belowself.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, binaryself.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 weightsself.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)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 covariateslots through `encoder`, plus their roles through `roles`), and the treatment slot'sweight (E,): a row's embedding at a standardized treatment z is the first + z * thesecond, as `encoder` of the full row would give."""B, n, P = W.shapeW = F.pad(W, (0, MAX_COVARIATES - P)) # zero slots, as CausalPFN padsfeats = 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 topredict mu at (on T's scale). `chunk`: query tokens at a time (each row is K + 1 ofthem; 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)."""B, n, P = W.shapeif 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_scalectx = 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, vkvs = []for layer in self.transformer_encoder:ctx, k, v = self._run(context_layer, ctx, layer)kvs.append((k, v))J = K + 1 # the values asked about, then the t-blind tokentold = 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 nout = []for s in range(0, n, step):xs = x[:, s:s + step]Q = xs.shape[1]q = self.xnorm(xs[:, None] + told[:, :, None]).reshape(B, J * Q, E)mask = Noneif 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 rowmask = 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)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 aGaussian of sd `sigma` around the truth, integrated over the bins (the truth clipped tothe bins' range)."""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 perfectprediction, so mu_nll minus it (the KL from the target) is the part training can lower."""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 onthe 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 thetreatment from values[:, pairs[s, 0]] to values[:, pairs[s, 1]], averaged over therows with weights[:, s] (B, S, n) (1 / 0 masks: all rows the ATE, the treated rowsthe ATT). The median is the weighted mean of the rows' effects; the widths arelearned, from the network's outputs detached (their loss trains `widths` alone), andantisymmetric: a -> b is minus b -> 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)n = w.shape[-1]phi = self._value_features(rows.values)pooled = (w[..., None] * query[:, None]).sum(2) / tot[..., None] # (B, S, E)context = context[:, None].expand_as(pooled)def one_way(a, b):d = mu[:, b] - mu[:, a] # (B, S, n)est = (w * d).sum(-1) / totspread = ((w * (d - est[..., None]) ** 2).sum(-1) / tot).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],rows.binary.float()[:, None, None].expand_as(est[..., None])], -1)moved = (rows.values[:, a] != rows.values[:, b]).float()[..., None] # a -> a: exactly 0steps = F.softplus(self.widths(feats)) * movedlower = est[..., None] - steps[..., :MID].flip(-1).cumsum(-1).flip(-1)upper = est[..., None] + steps[..., MID:].cumsum(-1)1 unmodified linereturn (one_way(i, j) - one_way(j, i).flip(-1)) / 2def _value_features(self, values):"""(B, K, E) a treatment value's embedding for the width head: the treatment slot'sterm 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)) / 2bern = 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 thepropensity: e (n,) P(T = 1 | w_i) for a binary treatment, else t_mean and t_sd (n,)."""device = next(self.parameters()).devicef = 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)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)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 outdef effect(self, data, treatment, outcome, **kwargs):1 unmodified line`axiom_effect.inference.effect(self, ...)`, which see."""from .inference import effectreturn effect(self, data, treatment, outcome, **kwargs)ADDITIONS = ("roles", "t_unknown", "final", "propensity", "treatment", "widths") # parameters CausalPFN has not1234567891011121314151617181920212223242526272829305 unmodified lines3637383940414243444546474849505152535455565758596061626364656667686970717273744 unmodified lines7980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122133 unmodified lines2172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403412 unmodified lines3443453463473483493503516 unmodified lines3583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365371 unmodified line5395405415425435445455465475485495505515525535545555565575585595605615625631 unmodified line565566567"""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 withY, T, W_j^2, W_j * T; joint partial ridge slopes on Y, W*T, and T; and optional graphrole features) and attends to all other columns biased by the P x P covariate correlationmatrix 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 learnedrow slots cross-attend over the P cells of row i, automatically gating out noise andpost-treatment columns while capturing multi-covariate interactions, then project intoR^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'sstandardized outcome scale (global for continuous). Every causal estimand (CATE, ATE,ATT, ATC, dose-response) is arithmetic on mu; a detached width head predicts calibrated5/25/75/95% uncertainty intervals."""import mathimport os5 unmodified linesimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom huggingface_hub import PyTorchModelHubMixinfrom huggingface_hub.errors import RevisionNotFoundErrorfrom torch.utils.checkpoint import checkpointfrom .blocks import eval_mode, mlpfrom .graph import N_ROLESARCHITECTURE = "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 # [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."""query: torch.Tensor # (B, n_qry, E) mean query representation across asked values, normalizedcontext: torch.Tensor # (B, E) mean context representation, normalizedmu: 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 scaleshift: torch.Tensor # (B, K) outcome shift per asked value's armscale: torch.Tensor # (B, K) outcome scale per asked value's armvalues: torch.Tensor # (B, K) treatment values asked aboutbinary: torch.Tensor # (B,) boolclass RMSNorm(nn.Module):"""Root-mean-square layer normalization in float32."""def __init__(self, dim, eps=1e-6):super().__init__()self.eps = eps4 unmodified linesreturn (y * torch.rsqrt(y.pow(2).mean(-1, keepdim=True) + self.eps)).type_as(x) * self.weightclass 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 // headsself.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 biasself.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.shapeq, 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 // headsself.cell_val = mlp(2, col_dim, col_dim) # [w_ij, rank_ij] -> col_dimself.col_scale = nn.Linear(col_dim, col_dim) # multiplicative column modulationself.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.shapeE = self.ff_out.out_featuresif 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 afterwardhas_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 // Hself.attn_norm = RMSNorm(E)self.q_proj = nn.Linear(E, E, bias=False)self.kv_proj = nn.Linear(E, 2 * E, bias=False)self.out_proj = nn.Linear(E, E, bias=False)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 (B, H, n_ctx, d): context keys and values for this layer."""B, n, _ = ctx.shapek, v = self.kv_proj(self.attn_norm(ctx)).chunk(2, -1)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, vdef forward(self, x, k, v, mask=None):"""x (B, L, E) tokens attending to context k, v (B, H, n_ctx, d); optional mask (L, n_ctx)."""B, L, E = x.shapeq = 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):"""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)) / 2treated, asked = (T > mid).float(), values > middef 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().clamp(min=1e-6)return m, s, c > 0m1, s1, has1 = stats(treated)m0, s0, has0 = stats(1 - treated)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 linesreturn row_shift, row_scale, shift, scaledef _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.shapeif P == 0:return torch.zeros_like(W_ctx), torch.zeros_like(W_qry)srt = W_ctx.transpose(1, 2).contiguous().sort(-1).valuesdef 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.0return 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 covariatecorrelation 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 andpartial ridge slopes so treatment-effect modifiers are visible even under strong main effects."""B, n, P = Wz_ctx.shapedevice, dtype = Wz_ctx.device, Wz_ctx.dtypeif 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 * npen_y[2:2 + P] = 0.05 * npen_y[2 + P:] = 0.25 * nG_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 * nG_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 continuousmid = (T.amax(1, keepdim=True) + T.amin(1, keepdim=True)) / 2med = T.median(1, keepdim=True).valuesthresh = torch.where(binary[:, None], mid, med)w_hi = (T > thresh).float()w_lo = 1.0 - w_hidef 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 * cntG = G + torch.diag_embed(pen)rhs = torch.bmm(Dw.transpose(1, 2), Y[..., None])return torch.linalg.solve(G, rhs).squeeze(-1)[:, 1:] * mask_fb_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) / wsac, bc = A - am, b - bmnum = (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).valuesy_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, or None when running from source."""try:return f"v{version('axiom-effect')}"except PackageNotFoundError:2 unmodified linesclass AxiomEffect(nn.Module, PyTorchModelHubMixin, library_name="axiom-effect", repo_url=None,tags=["causal-inference", "effect-estimation", "tabular"]):"""Pure, from-scratch factorized tabular PFN for causal effect estimation."""@classmethoddef from_pretrained(cls, pretrained_model_name_or_path, *, revision=None, strict=True, **kwargs):path = str(pretrained_model_name_or_path)6 unmodified linesf"not match this version of the code", stacklevel=2)return super().from_pretrained(path, revision=revision, strict=strict, **kwargs)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, col_dim=col_dim,col_layers=col_layers, row_slots=row_slots, nbins=nbins, vmax=vmax, sigma=sigma)# Stage 1: Column self-attention encoderself.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 encoderself.row_pool = RowPool(col_dim, E, slots=row_slots, heads=4)# Stage 3: Row transformerself.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 headself.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)self.register_buffer("edges", edges, persistent=False)self.register_buffer("centers", (edges[1:] + edges[:-1]) / 2, persistent=False)self.recompute = Falsedef _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 _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 eachquery row from attending to its own context token."""B, n, P = W.shapeE, K = self.config["E"], values.shape[1]binary = torch.as_tensor(binary, dtype=torch.bool, device=W.device)same_table = W_qry is None and n_ctx is Noneif W_qry is not None:W_ctx, T_ctx, Y_ctx = W, T, Yelif 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, Wn_c, n_q = W_ctx.shape[1], W_qry.shape[1]# Standardize W, T, Y strictly from context rowsif 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_qryt_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_jkRk_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 encoderx_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, vkvs = []for blk in self.blocks:ctx, k, v = self._run(ctx_step, ctx, blk)kvs.append((k, v))t_val_emb = self._embed_t(Vz, binary) # (B, K, E)step = max(1, chunk // K) if chunk else n_qout = []for s in range(0, n_q, step):xs = x_qry[:, s:s + step]Q = xs.shape[1]q = self.qry_norm(xs[:, None] + t_val_emb[:, :, None]).reshape(B, K * Q, E)mask = Noneif 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 distributionq_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_meanreturn 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_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_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):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, 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)n = w.shape[-1]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]est = (w * d).sum(-1) / totspread = ((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) / 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]steps = F.softplus(self.widths(feats)) * movedlower = est[..., None] - steps[..., :MID].flip(-1).cumsum(-1).flip(-1)upper = est[..., None] + steps[..., MID:].cumsum(-1)1 unmodified linereturn (one_way(i, j) - one_way(j, i).flip(-1)) / 2@torch.no_grad()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()).devicef = 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 Nonewith eval_mode(self):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()return outdef effect(self, data, treatment, outcome, **kwargs):1 unmodified line`axiom_effect.inference.effect(self, ...)`, which see."""from .inference import effectreturn effect(self, data, treatment, outcome, **kwargs)
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