File size: 29,669 Bytes
bcae6cd
df166a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcae6cd
 
 
 
 
 
 
 
 
 
 
df166a5
bcae6cd
 
 
adbc13b
 
bcae6cd
df166a5
 
bcae6cd
df166a5
 
 
 
 
 
 
2003312
 
bcae6cd
df166a5
 
 
 
 
 
 
 
adbc13b
 
 
 
df166a5
adbc13b
bcae6cd
adbc13b
 
 
 
 
 
bcae6cd
adbc13b
df166a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adbc13b
 
 
df166a5
 
adbc13b
 
 
df166a5
 
 
adbc13b
 
df166a5
 
adbc13b
df166a5
 
 
adbc13b
 
df166a5
 
 
 
 
 
 
 
adbc13b
 
 
df166a5
 
adbc13b
df166a5
adbc13b
 
 
 
df166a5
adbc13b
 
 
 
df166a5
 
 
 
adbc13b
 
 
 
 
 
 
bcae6cd
 
df166a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcae6cd
df166a5
bcae6cd
 
 
 
 
 
 
 
df166a5
 
bcae6cd
 
 
 
 
 
 
 
 
 
 
 
df166a5
 
bcae6cd
df166a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adbc13b
 
 
 
df166a5
bcae6cd
 
 
 
 
 
df166a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1178ec
df166a5
 
 
 
 
 
 
 
b1178ec
 
 
df166a5
adbc13b
 
 
df166a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adbc13b
 
df166a5
 
adbc13b
 
df166a5
b1178ec
df166a5
adbc13b
df166a5
 
adbc13b
df166a5
adbc13b
b1178ec
 
 
 
 
 
 
 
 
 
 
 
df166a5
 
 
 
 
 
 
 
 
 
 
adbc13b
 
df166a5
adbc13b
 
 
 
df166a5
adbc13b
 
 
 
 
 
 
 
 
df166a5
 
bcae6cd
adbc13b
 
df166a5
adbc13b
df166a5
 
adbc13b
 
 
df166a5
adbc13b
df166a5
adbc13b
df166a5
adbc13b
df166a5
adbc13b
bcae6cd
 
 
 
 
 
 
b1178ec
 
df166a5
b1178ec
df166a5
bcae6cd
adbc13b
 
df166a5
 
bcae6cd
df166a5
 
b1178ec
 
adbc13b
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
"""
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 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 slopes
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


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)

    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):
        """x (B, L, E) tokens attending to context k, v (B, H, n_ctx, d); optional mask (L, n_ctx)."""
        B, L, E = x.shape
        q = self.q_proj(self.attn_norm(x)).view(B, L, self.H, self.d).transpose(1, 2)
        q = self.q_norm(q) * (math.log2(max(k.shape[2], 2)) / 8.0)
        a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask).transpose(1, 2).reshape(B, L, E)
        x = x + self.out_proj(a)
        h, g = self.ff_in(self.ff_norm(x)).chunk(2, -1)
        return x + self.ff_out(h * F.silu(g))


def _arm_scales(T, Y, values, binary):
    """Standardize Y within each arm for binary treatments (over all context rows for continuous).
    Returns (row_shift, row_scale) (B, n_ctx) and (shift, scale) (B, K)."""
    mid = (T.amax(1, keepdim=True) + T.amin(1, keepdim=True)) / 2
    treated, asked = (T > mid).float(), values > mid

    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 > 0

    m1, 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)
    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."""

    @classmethod
    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)
        # Stage 3: Row transformer
        self.t_embed = mlp(2, E, E)                       # [standardized T, binary flag]
        self.y_embed = nn.Linear(1, E)                    # standardized Y (arm-scaled for binary)
        self.ctx_norm = RMSNorm(E)
        self.qry_norm = RMSNorm(E)
        self.blocks = nn.ModuleList(Block(E, H) for _ in range(layers))
        # Stage 4: Direct HL-Gauss head + detached width head
        self.head_norm = RMSNorm(E)
        self.head = nn.Sequential(nn.Linear(E, 2 * E, bias=False), nn.GELU(),
                                  nn.Linear(2 * E, nbins, bias=False))
        self.widths = mlp(2 + 4 * E + 3, E, len(QUANTILES) - 1)
        edges = torch.linspace(-vmax, vmax, nbins + 1)
        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):
        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, self_idx=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).
        """
        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
        elif n_ctx is not None:
            W_ctx, T_ctx, Y_ctx = W[:, :n_ctx], T[:, :n_ctx], Y[:, :n_ctx]
            W_qry = W[:, n_ctx:]
        else:
            W_ctx, T_ctx, Y_ctx, W_qry = W, T, Y, W

        n_c, n_q = W_ctx.shape[1], W_qry.shape[1]

        # Standardize W, T, Y strictly from context rows
        if P > 0:
            w_mean = W_ctx.mean(1, keepdim=True)
            w_sd = W_ctx.std(1, keepdim=True, unbiased=False).clamp(min=1e-6)
            Wz_ctx = ((W_ctx - w_mean) / w_sd).clamp(-CLIP_SIGMA, CLIP_SIGMA) * w_mask[:, None].to(W.dtype)
            Wz_qry = ((W_qry - w_mean) / w_sd).clamp(-CLIP_SIGMA, CLIP_SIGMA) * w_mask[:, None].to(W.dtype)
        else:
            Wz_ctx, Wz_qry = W_ctx, W_qry

        t_mean = T_ctx.mean(1, keepdim=True)
        t_sd = T_ctx.std(1, keepdim=True, unbiased=False).clamp(min=1e-6)
        Tz_ctx = ((T_ctx - t_mean) / t_sd).clamp(-CLIP_SIGMA, CLIP_SIGMA)
        Vz = ((values - t_mean) / t_sd).clamp(-CLIP_SIGMA, CLIP_SIGMA)

        y_gmean = Y_ctx.mean(1, keepdim=True)
        y_gsd = Y_ctx.std(1, keepdim=True, unbiased=False).clamp(min=1e-6)
        Yg_ctx = ((Y_ctx - y_gmean) / y_gsd).clamp(-CLIP_SIGMA, CLIP_SIGMA)
        row_shift, row_scale, shift, scale = _arm_scales(T_ctx, Y_ctx, values, binary)
        Yz_ctx = ((Y_ctx - row_shift) / row_scale).clamp(-CLIP_SIGMA, CLIP_SIGMA)

        # Stage 1: Column self-attention over exact context statistics + correlation matrix R_jk
        Rk_ctx, Rk_qry = _context_ranks(Wz_ctx, Wz_qry)
        col_stats, R = _column_stats_and_corr(Wz_ctx, Tz_ctx, Yg_ctx, w_mask, Rk_ctx, binary)
        col_emb = self._encode_columns(col_stats, features, R, w_mask)

        # Stage 2: Multi-slot cross-attention row encoder
        x_ctx = self._run(self.row_pool, Wz_ctx, Rk_ctx, col_emb, w_mask)
        x_qry = x_ctx if same_table else self._run(self.row_pool, Wz_qry, Rk_qry, col_emb, w_mask)

        # Stage 3: Row transformer (context self-attention, then query cross-attention)
        ctx = self.ctx_norm(x_ctx + self._embed_t(Tz_ctx, binary) + self.y_embed(Yz_ctx[..., None]))

        def ctx_step(h, blk):
            k, v = blk.keys(h)
            return blk(h, k, v), k, v

        kvs = []
        for 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)
        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) in zip(self.blocks, kvs):
                q = self._run(blk, q, k, v, mask)
            out.append(q.view(B, K, Q, E))
        q = torch.cat(out, 2)                                                # (B, K, n_q, E)

        # Stage 4: Direct HL-Gauss outcome distribution
        q_norm = self.head_norm(q)
        logits = self.head(q_norm)                                           # (B, K, n_q, nbins)
        bin_mean = (logits.softmax(-1) * self.centers).sum(-1)
        mu = shift[..., None] + scale[..., None] * bin_mean
        return Rows(q_norm.mean(1), self.head_norm(ctx).mean(1), mu, logits, shift, scale, values, binary)

    def mu_nll(self, rows, target):
        """(B, K, n_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) / tot
            spread = ((w * (d - est[..., None]) ** 2).sum(-1) / tot).clamp(min=0).sqrt()
            feats = torch.cat([est[..., None], spread[..., None], pooled, context, phi[:, a], phi[:, b],
                               (torch.log(tot) / 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

    @torch.no_grad()
    def predict(self, W, T, Y, features, binary, values, estimands=(), chunk=4096, W_qry=None,
                self_idx=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) and self_idx (n_qry,).
        Deterministic (no random column codes); `tta` and `seed` kept for API compatibility."""
        device = next(self.parameters()).device
        f = lambda a: torch.as_tensor(np.asarray(a, dtype=np.float32), device=device)[None]
        W = np.asarray(W, dtype=np.float32).reshape(len(T), -1)
        P = W.shape[1]
        Wq_t = f(np.asarray(W_qry, dtype=np.float32).reshape(-1, P)) if W_qry is not None else None
        with eval_mode(self):
            rows = self(f(W), f(T), f(Y), torch.ones(1, 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)
            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 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)