Download src/axiom_effect/model.py from liminalplanes/axiom-effect: direct link, hf CLI and curl.
- Browser
- Download file 48.2 kB
-
https://huggingface.co/liminalplanes/axiom-effect/resolve/main/src/axiom_effect/model.py
- Command line
-
hf download hf://liminalplanes/axiom-effect/src/axiom_effect/model.py
-
curl -L -o model.py https://huggingface.co/liminalplanes/axiom-effect/resolve/main/src/axiom_effect/model.py
48.2 kB
| """ | |
| 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 zero | |
| pretrained 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 math | |
| import os | |
| import warnings | |
| from importlib.metadata import PackageNotFoundError, version | |
| from typing import NamedTuple | |
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from huggingface_hub import PyTorchModelHubMixin | |
| from huggingface_hub.errors import RevisionNotFoundError | |
| from torch.utils.checkpoint import checkpoint | |
| from .blocks import eval_mode, mlp | |
| from .graph import N_ROLES | |
| ARCHITECTURE = "factorized tabular PFN v3" | |
| 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 slopes | |
| N_INT_STATS = 7 # experimental vs observational summary + covariate shift | |
| N_DR_FEATS = 7 # doubly-robust gate summary features | |
| N_REF = 2048 # sample-size reference for the width head | |
| CLIP_SIGMA = 10.0 | |
| NBINS, 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, 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 | |
| prop_logits: torch.Tensor # (B, n_qry) neural propensity logits logit P(T = 1 | W_i) | |
| t_qry: torch.Tensor | None = None # (B, n_qry) observed query treatments (for internal DR gate) | |
| y_qry: torch.Tensor | None = None # (B, n_qry) observed query outcomes (for internal DR gate) | |
| has_int: torch.Tensor | None = None # (B,) bool: whether table has experimental interventions | |
| class RMSNorm(nn.Module): | |
| """Root-mean-square layer normalization in float32.""" | |
| def __init__(self, dim, eps=1e-6): | |
| super().__init__() | |
| self.eps = eps | |
| self.weight = nn.Parameter(torch.ones(dim)) | |
| def forward(self, x): | |
| y = x.float() | |
| return (y * torch.rsqrt(y.pow(2).mean(-1, keepdim=True) + self.eps)).type_as(x) * self.weight | |
| 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.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) | |
| self.int_bias = nn.Parameter(torch.zeros(H)) | |
| def keys(self, ctx): | |
| """(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 = 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, key_int=None, int_bias=None): | |
| """x (B, L, E) tokens attending to context k, v (B, H, n_ctx, d); optional mask (L, n_ctx), | |
| key_int (B, n_ctx) bool/float mask for experimentally intervened context rows, and optional | |
| per-table int_bias (B, H).""" | |
| 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) | |
| attn_mask = mask | |
| if key_int is not None: | |
| ib = self.int_bias[None, :] if int_bias is None else int_bias | |
| bias = key_int[:, None, None, :].to(q.dtype) * ib[:, :, None, None] | |
| attn_mask = bias if mask is None else mask[None, None, :, :] + bias | |
| a = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_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)) | |
| class CrossArmBlock(nn.Module): | |
| """Within-row self-attention across the K asked treatment arms: O(n_qry * K^2). | |
| Lets arms for the same unit share baseline information so f_0(w_i) noise cancels in CATE | |
| and continuous dose-response curves. Zero-initialized residual so step 0 is identity.""" | |
| def __init__(self, E, H): | |
| super().__init__() | |
| self.H, self.d = H, E // H | |
| self.attn_norm = RMSNorm(E) | |
| self.qkv = nn.Linear(E, 3 * E, bias=False) | |
| self.out_proj = nn.Linear(E, 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) | |
| nn.init.normal_(self.out_proj.weight, std=1e-3) | |
| nn.init.normal_(self.ff_out.weight, std=1e-3) | |
| def forward(self, q): | |
| """q (B, K, n_q, E) -> (B, K, n_q, E).""" | |
| B, K, n_q, E = q.shape | |
| if K <= 1: | |
| return q | |
| x = q.permute(0, 2, 1, 3).reshape(B * n_q, K, E) | |
| q_, k_, v_ = self.qkv(self.attn_norm(x)).chunk(3, -1) | |
| q_ = q_.view(B * n_q, K, self.H, self.d).transpose(1, 2) | |
| k_ = k_.view(B * n_q, K, self.H, self.d).transpose(1, 2) | |
| v_ = v_.view(B * n_q, K, self.H, self.d).transpose(1, 2) | |
| a = F.scaled_dot_product_attention(q_, k_, v_).transpose(1, 2).reshape(B * n_q, K, E) | |
| x = x + self.out_proj(a) | |
| h, g = self.ff_in(self.ff_norm(x)).chunk(2, -1) | |
| x = x + self.ff_out(h * F.silu(g)) | |
| return x.view(B, n_q, K, E).permute(0, 2, 1, 3) | |
| def _arm_scales(T, Y, values, binary, t_int=None): | |
| """Standardize Y within each arm for binary treatments (over all context rows for continuous). | |
| When intervened rows `t_int` have >=4 rows in each binary arm, anchor the arm shifts to the | |
| intervened arm means so confounded observational pools do not bake bias into the output shift. | |
| 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 | |
| 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().clamp(min=1e-6) | |
| return m, s, c | |
| m1, s1, c1 = stats(treated) | |
| m0, s0, c0 = stats(1 - treated) | |
| has1, has0 = c1 > 0, c0 > 0 | |
| m1 = torch.where(has1, m1, m0) | |
| s1 = torch.where(has1, s1, s0) | |
| m0 = torch.where(has0, m0, m1) | |
| s0 = torch.where(has0, s0, s1) | |
| if t_int is not None: | |
| ti = t_int.to(Y.dtype) | |
| m1_i, _, c1_i = stats(treated * ti) | |
| m0_i, _, c0_i = stats((1 - treated) * ti) | |
| use_int = (c1_i >= 4) & (c0_i >= 4) | |
| m1 = torch.where(use_int, m1_i, m1) | |
| m0 = torch.where(use_int, m0_i, m0) | |
| ma, sa, _ = stats(torch.ones_like(Y)) | |
| b = binary[:, None] | |
| row_shift = torch.where(b, torch.where(treated > 0, m1, m0), ma) | |
| row_scale = torch.where(b, torch.where(treated > 0, s1, s0), sa) | |
| shift = torch.where(b, torch.where(asked, m1, m0), ma) | |
| scale = torch.where(b, torch.where(asked, s1, s0), sa) | |
| 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, or None when running from source.""" | |
| try: | |
| return f"v{version('axiom-effect')}" | |
| except PackageNotFoundError: | |
| return None | |
| class AxiomEffect(nn.Module, PyTorchModelHubMixin, library_name="axiom-effect", repo_url=None, | |
| tags=["causal-inference", "effect-estimation", "tabular"]): | |
| """Pure, from-scratch factorized tabular PFN for causal effect estimation.""" | |
| def from_pretrained(cls, pretrained_model_name_or_path, *, revision=None, strict=True, **kwargs): | |
| path = str(pretrained_model_name_or_path) | |
| tag = release_tag() | |
| if revision is None and tag is not None and not os.path.isdir(path): | |
| try: | |
| return super().from_pretrained(path, revision=tag, strict=strict, **kwargs) | |
| except RevisionNotFoundError: | |
| warnings.warn(f"{path} has no {tag} tag; loading its latest weights (main), which may " | |
| f"not match this version of the code", stacklevel=2) | |
| return super().from_pretrained(path, revision=revision, strict=strict, **kwargs) | |
| def __init__(self, E=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 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) | |
| self.cell_int = nn.Linear(1, col_dim, bias=False) | |
| nn.init.zeros_(self.cell_int.weight) | |
| # 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.t_int_embed = nn.Linear(1, E, bias=False) # per-row treatment intervention flag | |
| nn.init.zeros_(self.t_int_embed.weight) | |
| # 7-dim summary of experimental vs observational contrast + covariate shift: | |
| # [has_t_int, frac_t_int, log_frac_t_int, inv_sqrt_n_int, delta_int, delta_int - delta_obs, cov_shift] | |
| self.int_summary_embed = nn.Linear(N_INT_STATS, E, bias=False) | |
| nn.init.zeros_(self.int_summary_embed.weight) | |
| # Table-adaptive attention bias delta for intervened context rows: (B, N_INT_STATS) -> (B, layers * H) | |
| self.int_bias_net = mlp(N_INT_STATS, 64, layers * H) | |
| nn.init.zeros_(self.int_bias_net[-1].weight) | |
| nn.init.zeros_(self.int_bias_net[-1].bias) | |
| self.ctx_norm = RMSNorm(E) | |
| self.qry_norm = RMSNorm(E) | |
| self.blocks = nn.ModuleList(Block(E, H) for _ in range(layers)) | |
| self.cross_arm = CrossArmBlock(E, H) | |
| # Stage 4: Direct HL-Gauss head + in-context neural propensity + learned DR gate + 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.prop_head = nn.Linear(E, 1) | |
| self.dr_gate = mlp(N_DR_FEATS, 64, 1) | |
| nn.init.normal_(self.dr_gate[-1].weight, std=1e-3) | |
| nn.init.constant_(self.dr_gate[-1].bias, -2.5) | |
| 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 = False | |
| def _run(self, fn, *args, pool=False): | |
| active = self.recompute is True or (self.recompute == "pool" and pool) | |
| if active 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 _int_summary(Wz_ctx, w_mask, Tz_ctx, Yg_ctx, t_int_ctx, binary): | |
| """(B, 7) float tensor summarizing experimental-vs-observational contrast, RCT sample | |
| fraction/precision, and obs-vs-RCT covariate shift so intervened rows are weighted | |
| Bayes-optimally against observational tables.""" | |
| B, n = Tz_ctx.shape | |
| device, dtype = Tz_ctx.device, Tz_ctx.dtype | |
| if t_int_ctx is None: | |
| return torch.zeros(B, N_INT_STATS, device=device, dtype=dtype) | |
| ti = t_int_ctx.float() | |
| ti_cnt = ti.sum(1) | |
| has_int = (ti_cnt >= 2).float() | |
| frac_int = ti_cnt / max(n, 1) | |
| log_frac = has_int * torch.log(frac_int.clamp(min=1e-4)).clamp(-6.0, 0.0) / 6.0 | |
| inv_sqrt_n = has_int / ti_cnt.clamp(min=1.0).sqrt() | |
| mid = (Tz_ctx.amax(1, keepdim=True) + Tz_ctx.amin(1, keepdim=True)) / 2 | |
| med = Tz_ctx.median(1, keepdim=True).values | |
| thresh = torch.where(binary[:, None], mid, med) | |
| hi = (Tz_ctx > thresh).float() | |
| lo = 1.0 - hi | |
| def arm_diff(row_w): | |
| w1 = row_w * hi | |
| w0 = row_w * lo | |
| c1 = w1.sum(1) | |
| c0 = w0.sum(1) | |
| valid = (c1 >= 1) & (c0 >= 1) | |
| m1 = (w1 * Yg_ctx.float()).sum(1) / c1.clamp(min=1.0) | |
| m0 = (w0 * Yg_ctx.float()).sum(1) / c0.clamp(min=1.0) | |
| return torch.where(valid, (m1 - m0).clamp(-5.0, 5.0), torch.zeros_like(m1)) | |
| d_int = arm_diff(ti) * has_int | |
| d_obs = arm_diff(1.0 - ti) | |
| d_gap = (d_int - d_obs).clamp(-5.0, 5.0) * has_int | |
| P = Wz_ctx.shape[2] | |
| if P > 0: | |
| w_obs = 1.0 - ti | |
| c_int = ti.sum(1, keepdim=True).clamp(min=1.0) | |
| c_obs = w_obs.sum(1, keepdim=True).clamp(min=1.0) | |
| m_int = (ti[..., None] * Wz_ctx.float()).sum(1) / c_int | |
| m_obs = (w_obs[..., None] * Wz_ctx.float()).sum(1) / c_obs | |
| mf = w_mask.float() | |
| p_cnt = mf.sum(1).clamp(min=1.0) | |
| sq_diff = (((m_int - m_obs) ** 2) * mf).sum(1) / p_cnt | |
| valid_shift = has_int * ((ti_cnt >= 2) & (w_obs.sum(1) >= 2) & (mf.sum(1) > 0)).float() | |
| cov_shift = torch.log1p(sq_diff.clamp(max=25.0)) * valid_shift | |
| else: | |
| cov_shift = torch.zeros(B, device=device, dtype=torch.float32) | |
| return torch.stack([has_int, frac_int, log_frac, inv_sqrt_n, d_int, d_gap, cov_shift], -1).to(dtype) | |
| def _pool_rows(self, Wz, Rk, col_emb, w_mask, w_int=None): | |
| """RowPool forward with optional per-cell intervention embedding.""" | |
| if w_int is None: | |
| return self.row_pool(Wz, Rk, col_emb, w_mask) | |
| rp = self.row_pool | |
| B, n, P = Wz.shape | |
| E = rp.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 = rp.cell_val(torch.stack([Wz, Rk], -1)) + self.cell_int(w_int.to(Wz.dtype)[..., None]) | |
| scale = 1.0 + torch.tanh(rp.col_scale(col_emb)) | |
| cells = rp.cell_norm(val * scale[:, None] + col_emb[:, None]).reshape(B * n, P, D) | |
| q = rp.q_proj(rp.queries).view(1, rp.slots, rp.H, rp.d).transpose(1, 2).expand(B * n, -1, -1, -1) | |
| k, v = rp.kv_proj(cells).chunk(2, -1) | |
| k = k.view(B * n, P, rp.H, rp.d).transpose(1, 2) | |
| v = v.view(B * n, P, rp.H, rp.d).transpose(1, 2) | |
| has_any = w_mask.any(1) | |
| 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, rp.slots, P).reshape(B * n, 1, rp.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, rp.slots * D) | |
| x = rp.out_proj(pooled) | |
| h, g = rp.ff_in(rp.ff_norm(x)).chunk(2, -1) | |
| x = x + rp.ff_out(h * F.silu(g)) | |
| return x * has_any[:, None, None].to(x.dtype) | |
| def forward(self, W, T, Y, w_mask, features, binary, values, n_ctx=None, W_qry=None, | |
| chunk=None, self_mask=True, self_idx=None, t_int=None, w_int=None, | |
| T_qry=None, Y_qry=None): | |
| """ | |
| 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), or when | |
| `self_idx` is given, mask each query row from attending to its own context token. | |
| self_idx: optional (n_qry,) integer index of each query row inside W_ctx (-1 if absent). | |
| t_int: optional (B, n) bool mask of rows where treatment T was experimentally intervened on. | |
| w_int: optional (B, n, P) bool mask of cells where covariates W were experimentally intervened on. | |
| T_qry, Y_qry: optional (B, n_qry) observed query treatment/outcome when W_qry is given | |
| (used only by the detached DR gate inside estimands(), never seen by the backbone). | |
| """ | |
| B, n, P = W.shape | |
| E, 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 None | |
| if W_qry is not None: | |
| W_ctx, T_ctx, Y_ctx = W, T, Y | |
| t_int_ctx, w_int_ctx = t_int, w_int | |
| t_q_obs, y_q_obs = T_qry, Y_qry | |
| 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:] | |
| t_int_ctx = t_int[:, :n_ctx] if t_int is not None else None | |
| w_int_ctx = w_int[:, :n_ctx] if w_int is not None else None | |
| t_q_obs, y_q_obs = T[:, n_ctx:], Y[:, n_ctx:] | |
| else: | |
| W_ctx, T_ctx, Y_ctx, W_qry = W, T, Y, W | |
| t_int_ctx, w_int_ctx = t_int, w_int | |
| t_q_obs, y_q_obs = T, Y | |
| 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, t_int_ctx) | |
| 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 | |
| with torch.amp.autocast(device_type=W.device.type, enabled=False): | |
| 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._pool_rows, Wz_ctx, Rk_ctx, col_emb, w_mask, w_int_ctx, pool=True) | |
| if same_table and w_int_ctx is None: | |
| x_qry = x_ctx | |
| else: | |
| x_qry = self._run(self._pool_rows, Wz_qry, Rk_qry, col_emb, w_mask, None, pool=True) | |
| # Stage 3: Row transformer (context self-attention, then query cross-attention) | |
| with torch.amp.autocast(device_type=W.device.type, enabled=False): | |
| int_stats = self._int_summary(Wz_ctx, w_mask, Tz_ctx, Yg_ctx, t_int_ctx, binary) | |
| int_sum = self.int_summary_embed(int_stats) # (B, E) | |
| if t_int_ctx is not None: | |
| int_delta = self.int_bias_net(int_stats).view(B, len(self.blocks), self.config["H"]) | |
| layer_ib = [blk.int_bias[None, :] + int_delta[:, l, :] for l, blk in enumerate(self.blocks)] | |
| else: | |
| layer_ib = [None] * len(self.blocks) | |
| ctx_in = x_ctx + self._embed_t(Tz_ctx, binary) + self.y_embed(Yz_ctx[..., None]) + int_sum[:, None] | |
| if t_int_ctx is not None: | |
| ctx_in = ctx_in + self.t_int_embed(t_int_ctx.to(ctx_in.dtype)[..., None]) | |
| ctx = self.ctx_norm(ctx_in) | |
| def ctx_step(h, blk, ki, ib): | |
| k, v = blk.keys(h) | |
| return blk(h, k, v, key_int=ki, int_bias=ib), k, v | |
| kvs = [] | |
| for blk, ib in zip(self.blocks, layer_ib): | |
| ctx, k, v = self._run(ctx_step, ctx, blk, t_int_ctx, ib) | |
| kvs.append((k, v)) | |
| t_val_emb = self._embed_t(Vz, binary) + int_sum[:, None] # (B, K, E) | |
| self_idx_t = torch.as_tensor(self_idx, dtype=torch.long, device=W.device) if self_idx is not None else None | |
| step = max(1, chunk // K) if chunk else n_q | |
| out = [] | |
| 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 = None | |
| if self_mask and n_c > 1: | |
| if self_idx_t is not None: | |
| idx = self_idx_t[s:s + Q] | |
| valid = idx >= 0 | |
| if valid.any(): | |
| mask = torch.zeros(Q, n_c, dtype=q.dtype, device=W.device) | |
| mask[torch.arange(Q, device=W.device)[valid], idx[valid]] = float("-inf") | |
| mask = mask.repeat(K, 1) | |
| elif same_table: | |
| 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), ib in zip(self.blocks, kvs, layer_ib): | |
| q = self._run(blk, q, k, v, mask, t_int_ctx, ib) | |
| out.append(q.view(B, K, Q, E)) | |
| q = torch.cat(out, 2) # (B, K, n_q, E) | |
| q = self._run(self.cross_arm, q) | |
| # Stage 4: Direct HL-Gauss outcome distribution + in-context neural propensity (in fp32) | |
| q_norm = self.head_norm(q) | |
| q_mean = q_norm.mean(1) # (B, n_q, E) | |
| logits = self.head(q_norm).float() # (B, K, n_q, nbins) | |
| bin_mean = (logits.softmax(-1) * self.centers.float()).sum(-1) | |
| mu = shift[..., None].float() + scale[..., None].float() * bin_mean | |
| prop_logits = self.prop_head(q_mean).squeeze(-1).float() # (B, n_q) | |
| has_int = t_int_ctx.any(1) if t_int_ctx is not None else torch.zeros(B, dtype=torch.bool, device=W.device) | |
| return Rows(q_mean.float(), self.head_norm(ctx).mean(1).float(), mu, logits, | |
| shift.float(), scale.float(), values.float(), binary, prop_logits, | |
| t_q_obs.float() if t_q_obs is not None else None, | |
| y_q_obs.float() if y_q_obs is not None else None, has_int) | |
| def mu_nll_and_floor(self, rows, target): | |
| """(nll, floor), each (B, K, n_qry): computes HL-Gauss target `p` once instead of twice.""" | |
| p = self._hl_target(rows, target) | |
| nll = -(p * rows.logits.log_softmax(-1)).sum(-1) | |
| floor = -torch.special.xlogy(p, p).sum(-1) | |
| return nll, floor | |
| 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. | |
| For binary observational tables with observed (T_qry, Y_qry), applies a learned per-table | |
| doubly-robust gate blending plug-in and neural-propensity AIPW estimates. | |
| 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) | |
| has_obs = rows.t_qry is not None and rows.y_qry is not None | |
| if has_obs: | |
| has_int = rows.has_int if rows.has_int is not None else torch.zeros_like(rows.binary) | |
| e = torch.sigmoid(rows.prop_logits.detach()).clamp(0.02, 0.98) | |
| mid = (rows.values.amax(1, keepdim=True) + rows.values.amin(1, keepdim=True)) / 2 | |
| t_bin = (rows.t_qry.detach() > mid).float() | |
| y_q = rows.y_qry.detach().float() | |
| has_both = (t_bin.sum(-1) >= 2) & ((1.0 - t_bin).sum(-1) >= 2) | |
| can_dr = rows.binary & (~has_int) & has_both | |
| ext_ate = ((e < 0.05) | (e > 0.95)).float().mean(-1) | |
| ext_att = (e > 0.95).float().mean(-1) | |
| w_ipw = t_bin / e + (1.0 - t_bin) / (1.0 - e) | |
| ess_ate = (w_ipw.sum(-1).pow(2) / (w_ipw.pow(2).sum(-1).clamp(min=1e-6) * max(n, 1))).clamp(0.0, 1.0) | |
| w_att = (1.0 - t_bin) * e / (1.0 - e) | |
| n0 = (1.0 - t_bin).sum(-1).clamp(min=1.0) | |
| ess_att = (w_att.sum(-1).pow(2) / (w_att.pow(2).sum(-1).clamp(min=1e-6) * n0)).clamp(0.0, 1.0) | |
| else: | |
| can_dr = torch.zeros_like(rows.binary) | |
| def one_way(a, b): | |
| d = mu[:, b] - mu[:, a] | |
| est_pi = (w * d).sum(-1) / tot | |
| est = est_pi | |
| if has_obs and can_dr.any(): | |
| sgn = torch.sign(rows.values[:, b] - rows.values[:, a]) | |
| mu0_s = torch.where(sgn[..., None] >= 0, mu[:, a], mu[:, b]) | |
| mu1_s = torch.where(sgn[..., None] >= 0, mu[:, b], mu[:, a]) | |
| psi = ((mu1_s - mu0_s) | |
| + t_bin[:, None] * (y_q[:, None] - mu1_s) / e[:, None] | |
| - (1.0 - t_bin[:, None]) * (y_q[:, None] - mu0_s) / (1.0 - e[:, None])) | |
| est_ate_dr = (w * psi).sum(-1) / tot | |
| se_ate_dr = ((w * (psi - est_ate_dr[..., None]).pow(2)).sum(-1) | |
| / (tot * tot.clamp(min=1.0))).clamp(min=0.0).sqrt() | |
| is_att = ((w - t_bin[:, None]).abs().amax(-1) < 1e-4) & (t_bin.sum(-1, keepdim=True) >= 2) | |
| n1 = t_bin.sum(-1, keepdim=True).clamp(min=1.0) | |
| p_t = t_bin.mean(-1, keepdim=True).clamp(min=1e-4) | |
| odds = e / (1.0 - e) | |
| att_num = (t_bin[:, None] * (y_q[:, None] - mu0_s) | |
| - (1.0 - t_bin[:, None]) * odds[:, None] * (y_q[:, None] - mu0_s)).sum(-1) | |
| est_att_dr = att_num / n1 | |
| phi_att = (t_bin[:, None] * (y_q[:, None] - mu0_s - est_att_dr[..., None]) | |
| - (1.0 - t_bin[:, None]) * odds[:, None] * (y_q[:, None] - mu0_s)) / p_t[:, None] | |
| se_att_dr = (phi_att.pow(2).mean(-1) / max(n, 1)).clamp(min=0.0).sqrt() | |
| est_dr = sgn * torch.where(is_att, est_att_dr, est_ate_dr) | |
| se_dr = torch.where(is_att, se_att_dr, se_ate_dr) | |
| diff = (est_dr - est_pi).clamp(-10.0, 10.0) | |
| diff_abs = diff.abs() | |
| ext_f = torch.where(is_att, ext_att[:, None].expand_as(est_pi), ext_ate[:, None].expand_as(est_pi)) | |
| ess_f = torch.where(is_att, ess_att[:, None].expand_as(est_pi), ess_ate[:, None].expand_as(est_pi)) | |
| dr_feats = torch.stack([ | |
| diff_abs.clamp(max=5.0), | |
| torch.asinh(diff_abs / (se_dr + 1e-3)), | |
| torch.log1p(se_dr.clamp(max=100.0)), | |
| ext_f, | |
| ess_f, | |
| torch.log(tot) / math.log(N_REF), | |
| is_att.float(), | |
| ], -1) | |
| alpha = torch.sigmoid(self.dr_gate(dr_feats)).squeeze(-1) * can_dr[:, None].float() * (sgn != 0).float() | |
| est = est_pi + alpha * diff | |
| spread = ((w * (d - est_pi[..., 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)) * moved | |
| lower = est[..., None] - steps[..., :MID].flip(-1).cumsum(-1).flip(-1) | |
| upper = est[..., None] + steps[..., MID:].cumsum(-1) | |
| return torch.cat([lower, est[..., None], upper], -1) | |
| return (one_way(i, j) - one_way(j, i).flip(-1)) / 2 | |
| def dr_blend(self, mu0, mu1, prop, T, Y, target="ate"): | |
| """Apply the learned doubly-robust gate globally across a full assembled binary table | |
| (in raw outcome units) for multi-stratum inference (n > TRAIN_N[1]). Returns the blended | |
| point estimate in outcome units.""" | |
| device = next(self.parameters()).device | |
| y_sd = float(np.std(Y)) | |
| if y_sd < 1e-12: | |
| y_sd = 1.0 | |
| y_mean = float(np.mean(Y)) | |
| m0 = (np.asarray(mu0, dtype=np.float64) - y_mean) / y_sd | |
| m1 = (np.asarray(mu1, dtype=np.float64) - y_mean) / y_sd | |
| y = (np.asarray(Y, dtype=np.float64) - y_mean) / y_sd | |
| t = np.asarray(T, dtype=np.float64) | |
| e = np.clip(np.asarray(prop, dtype=np.float64), 0.02, 0.98) | |
| n = len(y) | |
| n1, n0 = float(t.sum()), float((1.0 - t).sum()) | |
| if n1 < 2 or n0 < 2: | |
| return float((m1 - m0).mean() if target == "ate" else (m1[t > 0.5] - m0[t > 0.5]).mean()) * y_sd | |
| if target == "att": | |
| est_pi = float((m1[t > 0.5] - m0[t > 0.5]).mean()) | |
| odds = e / (1.0 - e) | |
| est_dr = float((t * (y - m0) - (1.0 - t) * odds * (y - m0)).sum() / n1) | |
| p_t = max(n1 / n, 1e-4) | |
| phi = (t * (y - m0 - est_dr) - (1.0 - t) * odds * (y - m0)) / p_t | |
| se_dr = float(np.sqrt(max(np.mean(phi ** 2) / max(n, 1), 0.0))) | |
| ext_f = float(np.mean(e > 0.95)) | |
| w_att = (1.0 - t) * odds | |
| ess_f = float(np.clip((w_att.sum() ** 2) / (max((w_att ** 2).sum(), 1e-6) * n0), 0.0, 1.0)) | |
| tot, is_att = n1, 1.0 | |
| else: | |
| est_pi = float((m1 - m0).mean()) | |
| psi = (m1 - m0) + t * (y - m1) / e - (1.0 - t) * (y - m0) / (1.0 - e) | |
| est_dr = float(psi.mean()) | |
| se_dr = float(np.sqrt(max(np.mean((psi - est_dr) ** 2) / max(n, 1), 0.0))) | |
| ext_f = float(np.mean((e < 0.05) | (e > 0.95))) | |
| w_ipw = t / e + (1.0 - t) / (1.0 - e) | |
| ess_f = float(np.clip((w_ipw.sum() ** 2) / (max((w_ipw ** 2).sum(), 1e-6) * max(n, 1)), 0.0, 1.0)) | |
| tot, is_att = float(n), 0.0 | |
| diff = float(np.clip(est_dr - est_pi, -10.0, 10.0)) | |
| diff_abs = abs(diff) | |
| feats = torch.tensor([[ | |
| min(diff_abs, 5.0), | |
| math.asinh(diff_abs / (se_dr + 1e-3)), | |
| math.log1p(min(se_dr, 100.0)), | |
| ext_f, | |
| ess_f, | |
| math.log(max(tot, 1.0)) / math.log(N_REF), | |
| is_att, | |
| ]], dtype=torch.float32, device=device) | |
| with eval_mode(self): | |
| alpha = float(torch.sigmoid(self.dr_gate(feats)).item()) | |
| return float((est_pi + alpha * diff) * y_sd) | |
| def predict(self, W, T, Y, features, binary, values, estimands=(), chunk=4096, W_qry=None, | |
| self_idx=None, tta=1, seed=0, t_int=None, w_int=None, T_qry=None, Y_qry=None): | |
| """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), self_idx (n_qry,), | |
| optional intervention masks t_int (n_ctx,) bool and w_int (n_ctx, p) bool, and optional | |
| observed query (T_qry, Y_qry) when W_qry is given (for the internal DR gate). | |
| 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 | |
| Tq_t = f(T_qry) if T_qry is not None else None | |
| Yq_t = f(Y_qry) if Y_qry is not None else None | |
| ti_t = torch.as_tensor(np.asarray(t_int, dtype=bool), dtype=torch.bool, device=device)[None] \ | |
| if t_int is not None else None | |
| wi_t = torch.as_tensor(np.asarray(w_int, dtype=bool).reshape(len(T), P), dtype=torch.bool, device=device)[None] \ | |
| if (w_int is not None and P > 0) else None | |
| with 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, self_idx=self_idx, t_int=ti_t, w_int=wi_t, | |
| T_qry=Tq_t, Y_qry=Yq_t) | |
| out = {"mu": rows.mu[0].cpu().numpy(), | |
| "propensity": torch.sigmoid(rows.prop_logits[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 out | |
| def effect(self, data, treatment, outcome, **kwargs): | |
| """The causal effect of `treatment` on `outcome` in a table, in the data's units: | |
| `axiom_effect.inference.effect(self, ...)`, which see.""" | |
| from .inference import effect | |
| return effect(self, data, treatment, outcome, **kwargs) | |