Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
### Added
- **A quickstart notebook you can run in Colab** (`examples/quickstart.ipynb`, #113): install, start a server, classify, regress with prediction quantiles checked on held-out rows, and list and delete contexts. Colab badges in the README and the docs quickstart. (From @tylrcc in #134.)
### Fixed
- **CausalPFN is as accurate as its own estimator on a rare treatment.** A training table larger than the context (4,096 rows) was subsampled keeping each arm's share, so a rare treatment left the model a few dozen treated rows: on Lalonde CPS (173 of 16,177 rows treated, the CausalPFN paper's benchmark; 100 realizations) tabctx's effects had a PEHE of 9,552 and an ATE error of 0.39, against 8,955 and 0.13 for CausalPFN's estimator. Each arm now gets up to half the context, a smaller arm is kept whole and the other arm takes the rest: 8,947 and 0.18. Tables that fit the context are unchanged. `tests/integration/test_causalpfn_reference.py` (`uv sync --extra causalpfn`) checks IHDP against the paper and CPS against the estimator.
- The `python-multipart` floor is now 0.0.13: the server imports `python_multipart`, which older releases don't have, so an environment that already had one failed at startup.

## [0.21.0] - 2026-11-13
Expand Down
6 changes: 4 additions & 2 deletions docs/getting-started/python.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,10 @@ rows by risk, ask for `rmst` with `rmst_horizon` at that longest time
defined, while with heavy censoring many medians are `None`. A higher
`rmst` is a longer expected event-free time, so a lower risk. Each model
uses at most 4,096 training rows as its context (a larger table is
subsampled, keeping the share of events or of each arm and the spread of
times or outcomes;
subsampled: SurvivalPFN keeps the share of events and the spread of
times; CausalPFN gives each arm up to half the context, keeps a smaller
arm whole and gives the other arm the rest, and keeps the spread of
outcomes;
`TABCTX_SURVIVALPFN_CONTEXT_SIZE`, `TABCTX_CAUSALPFN_CONTEXT_SIZE`), and
every test row is predicted against that same context, so a row's answer
never depends on the other rows sent with it.
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ Flags take `1`/`true` or `0`/`false`.
| Variable | Default | |
|---|---|---|
| `TABCTX_SURVIVALPFN_CONTEXT_SIZE` | `4096` | The most training rows SurvivalPFN keeps as context; a larger table is subsampled at fit (seeded), keeping the share of events and the spread of times among events and among censored rows. The model takes any number; the cost is predict time, which grows roughly with the context's square (1,000 test rows on an A40: 0.12 s at 4,096, 5.4 s at 32,768, 50 s at 100,000). On four of SurvivalPFN's benchmark datasets larger than that (up to 36,695 rows), 4,096 rows scored within 0.01 C-index of the whole table. |
| `TABCTX_CAUSALPFN_CONTEXT_SIZE` | `4096` | The same for CausalPFN, keeping each arm's share and the spread of outcomes within it. Every test row is predicted against this one context, so a row's answer never depends on the rest of its request. The model takes any number; 2,000 test rows on an A40 took 0.26 s against 4,096 and 101 s against 100,000, with the same effect error on simulated data. |
| `TABCTX_CAUSALPFN_CONTEXT_SIZE` | `4096` | The same for CausalPFN, where each arm gets up to half the context: a smaller arm is kept whole and the other arm takes the rest, and each arm keeps the spread of its outcomes. Every test row is predicted against this one context, so a row's answer never depends on the rest of its request. The model takes any number; 2,000 test rows on an A40 took 0.26 s against 4,096 and 101 s against 100,000, with the same effect error on simulated data. |

The `TABCTX_KV_*` and `TABCTX_COMPILE*` settings apply to TabICL only.

Expand Down
14 changes: 8 additions & 6 deletions src/tabctx/backends/_pfn_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@
- One network per device, shared by every context (the context is the
table; the network is the same for every tenant).
- The context is the training table, at most a fixed number of rows of
it: a larger table is subsampled at fit, seeded, stratified on both
targets (strata()): each flag's share (events and censored rows;
treated and control rows) and, within each, the spread of times or
outcomes. Test rows
it: a larger table is subsampled at fit, seeded, with strata() and
subsample(): SurvivalPFN keeps the share of events and censored rows
and, within each, the spread of times; CausalPFN gives each arm up to
half the context and keeps the spread of outcomes within each arm
(causalpfn.context_rows). Test rows
attend only to the context, so a row's answer never depends on the
other rows in its request (the server merges and splits requests).
- A cached context lives on the host; the spill tier pickles it without
Expand Down Expand Up @@ -62,8 +63,9 @@ def strata(
or censored; treated or control) split into equal-count bands of
`values` (time; outcome) ranked within that flag. A sample keeping
every group's share keeps the flag's share and, within it, the spread
of times or outcomes (stratified on both, as the SurvivalPFN authors
suggested).
of times (stratified on both, as the SurvivalPFN authors suggested).
CausalPFN calls it once per arm, with one flag, for the outcome bands
alone (causalpfn.context_rows).

A flag gets as many bands as its share of a `size`-row sample holds
rows, at most `bands` and at least one: so there are never more groups
Expand Down
49 changes: 44 additions & 5 deletions src/tabctx/backends/causalpfn.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@

How it is served, and how that differs from CausalPFN's own estimator:
the context is the training table, at most `context_size` rows of it (a
larger table is subsampled at fit, seeded, keeping each arm's share and
the spread of outcomes within it), and
larger table is subsampled at fit, seeded: each arm gets up to half the
context, a smaller arm is kept whole and the other arm takes the rest,
and each arm keeps the spread of its outcomes; see context_rows), and
every test row is predicted against that same context. CausalPFN's
estimator instead picks a context per group of test rows (the training
rows nearest them by a gradient-boosting model's effect estimate), so a
Expand Down Expand Up @@ -100,6 +101,46 @@
_SEED = 0


def context_rows(
treated: np.ndarray, outcome: np.ndarray, size: int, seed: int
) -> np.ndarray:
"""Sorted indices of the training rows a context keeps: all of them
when there are at most `size`, else exactly `size`, with each arm
given up to an equal share (half, for treated and control) and a
smaller arm kept whole, its unused share going to the other arm.
Within an arm, rows are sampled across equal-count bands of the
outcome (strata), so the arm keeps its spread of outcomes.

It does not keep each arm's share of the table, because the model
learns each arm's expected outcome mostly from that arm's rows: a rare
treatment (1% of Lalonde CPS's rows) would leave it about 40 treated
rows. CausalPFN's own estimator also caps each arm at half its context
(of the rows nearest each group of test rows); giving a smaller arm's
unused share to the other arm is tabctx's choice.

Measured on Lalonde CPS (100 realizations, the authors' splits): PEHE
8,947 and ATE error 0.177, against 9,552 and 0.39 keeping shares and
8,955 and 0.133 for CausalPFN's estimator (the paper: 8,960 and 0.13);
tests/integration/test_causalpfn_reference.py checks the first 10. On simulated 20,000-row
tables (5 seeds), PEHE with 10% treated went from 0.63 to 0.17; with
30% and 50% treated, where both arms are larger than half the context,
it was the same or better (0.207 to 0.203, 0.192 to 0.181)."""
n = len(treated)
if n <= size:
return np.arange(n)
arms = sorted((np.flatnonzero(treated == v) for v in np.unique(treated)), key=len)
keep, left = [], size
for i, rows in enumerate(arms):
k = min(len(rows), left // (len(arms) - i))
left -= k
if k == len(rows):
keep.append(rows)
else:
groups = strata(np.zeros(len(rows)), outcome[rows], k)
keep.append(rows[subsample(groups, k, seed)])
return np.sort(np.concatenate(keep))


@dataclass
class CausalPFNContext:
"""The context table, as the model gets it (missing values filled, a
Expand Down Expand Up @@ -180,9 +221,7 @@ def prepare_fit(self, X: ArrayLike, y: ArrayLike, task: Task) -> CausalPFNContex
raise InvalidInputError(f"{self.name} fits causal, not {task}")
X_arr = float32_rows(X)
outcome, treated = (a.astype(np.float32) for a in split_targets(y))
keep = subsample(
strata(treated, outcome, self._context_size), self._context_size, _SEED
)
keep = context_rows(treated, outcome, self._context_size, _SEED)
X_arr, outcome, treated = X_arr[keep], outcome[keep], treated[keep]
medians = _column_medians(X_arr)
X_arr = _fill(X_arr, medians)
Expand Down
130 changes: 111 additions & 19 deletions tests/integration/test_causalpfn_reference.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""CausalPFNBackend against CausalPFN's own published benchmark on IHDP.
"""CausalPFNBackend against CausalPFN's own benchmarks: IHDP and Lalonde CPS.

The CausalPFN authors' reference: Table 1 of their paper (arXiv:2506.07918v2,
"Mean PEHE ± Standard Error"), CausalPFN's out-of-sample CATE error on the
Expand All @@ -15,9 +15,15 @@
is as close to the true average as CausalPFN's ATE estimator's, and
reproduces the published ATE error.

The data (17 MB, from the authors' repository at that commit, checked by
sha256) is downloaded once into pytest's cache. Needs the causalpfn extra
and its weights; runs on CPU in about a minute.
Lalonde CPS (RealCause's effects, the authors' first 10 realizations) is
larger than the context and only 1% treated, so it checks how a context is
sampled: as accurate as CausalPFN's estimator (see the test's docstring).

The data (17 MB for IHDP, 13 MB for CPS, from the authors' repository at
that commit, checked by sha256) is downloaded once into pytest's cache.
Needs the causalpfn extra and its weights (`uv sync --extra causalpfn`;
CI's integration job doesn't install it, so there it skips); runs on CPU
in about five minutes.
"""

from __future__ import annotations
Expand All @@ -32,7 +38,10 @@
pytest.importorskip("causalpfn")
torch = pytest.importorskip("torch")

from tabctx.backends.causalpfn import CausalPFNBackend # noqa: E402
from tabctx.backends.causalpfn import ( # noqa: E402
DEFAULT_CONTEXT_SIZE,
CausalPFNBackend,
)

COMMIT = "b7ed2f1e1d58a83c608d08ced3dee955f0a7c221"
FILES = {
Expand All @@ -48,28 +57,66 @@
# Table 1, CausalPFN, IHDP: mean ATE relative error 0.20 ± 0.04 (measured 0.203).
PUBLISHED_ATE_ERROR = 0.20
ATE_MARGIN = 0.02
# Lalonde CPS with RealCause's effects, the authors' first 10 realizations
# (benchmarks/realcause.py): 16,177 rows, 173 treated (1%), so a training
# table (90%) is larger than the 4,096-row context.
CPS_URL = (
f"https://raw.githubusercontent.com/vdblm/CausalPFN/{COMMIT}/"
"benchmarks/realcause_datasets/{}"
)
CPS_FILES = {
"lalonde_cps_sample0.csv": "20ce33e76b4dd68c3a81cacbf802c768a45ce0133084785bd7d2f98d80c6f865",
"lalonde_cps_sample1.csv": "84ecb89bbc1b158e9cd00e4d6806fb05f84db7c7bbd93ddc0c7ff49657c47305",
"lalonde_cps_sample2.csv": "8946bf8c14885049e9bab3e9c95affa1e4cae9b36f6fbd7def414efeddfaf920",
"lalonde_cps_sample3.csv": "45d2011ce890349f2288a973b41bf8c2f1bc8c85e54406be7173a251e16bcd8a",
"lalonde_cps_sample4.csv": "d2b8edf7988d5f13b1e695212e427db4fe198eaed14f10bdc34e6263e821cc56",
"lalonde_cps_sample5.csv": "936e9087a6afc97fe888007289babdef7519a44041bcc94aa53d9a1b1b0e372e",
"lalonde_cps_sample6.csv": "ffc6aaa830819657a7c897e85e08459dbf62004654c1b29b8849a59b3ffe479b",
"lalonde_cps_sample7.csv": "9db19839d8bb8dce5188d32cd0305afe0cb63abae343157d85ae2b27095b88bd",
"lalonde_cps_sample8.csv": "614b5e2aabe60a8c372c97bbc1f3d64cfd6b1a9478af16bf4f04dda67b64029a",
"lalonde_cps_sample9.csv": "bc4ad40ad305e12ab3c4ce2a5bb120331c747256b214dad3ac75c10fdc6e9b2f",
}
# CPS: tabctx's mean PEHE over these 10, at most this times CausalPFN's
# estimator's (measured 1.003; keeping each arm's share, 1.070), and the
# mean ATE error at most this (measured 0.128; keeping shares, 0.346).
CPS_PEHE_RATIO = 1.02
CPS_ATE_ERROR = 0.2
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"


@pytest.fixture(scope="module")
def ihdp(request) -> tuple[dict, dict]:
cache = Path(request.config.cache.mkdir("causalpfn-ihdp"))
for name, digest in FILES.items():
def fetch(request, folder: str, url: str, files: dict[str, str]) -> Path:
"""files (name: sha256) from url, kept in pytest's cache under folder."""
cache = Path(request.config.cache.mkdir(folder))
for name, digest in files.items():
path = cache / name
if not path.exists() or hashlib.sha256(path.read_bytes()).hexdigest() != digest:
try:
with urllib.request.urlopen(URL.format(name), timeout=60) as r:
with urllib.request.urlopen(url.format(name), timeout=60) as r:
body = r.read()
except OSError as e: # offline
pytest.skip(f"IHDP data unavailable: {e}")
pytest.skip(f"benchmark data unavailable: {e}")
assert hashlib.sha256(body).hexdigest() == digest, (
f"{name} changed upstream"
)
path.write_bytes(body)
return cache


@pytest.fixture(scope="module")
def ihdp(request) -> tuple[dict, dict]:
cache = fetch(request, "causalpfn-ihdp", URL, FILES)
train, test = (dict(np.load(cache / name)) for name in FILES)
return train, test


def upstream(cls, backend):
"""CausalPFN's own estimator (CATEEstimator, ATEEstimator) on the
backend's network, so both sides run the same weights."""
est = cls(device=DEVICE)
est.load_model = lambda: setattr(est, "icl_model", backend._shared_network())
return est


@pytest.fixture(scope="module")
def backend():
b = CausalPFNBackend(device=DEVICE)
Expand Down Expand Up @@ -109,10 +156,7 @@ def test_matches_the_published_benchmark(backend, ihdp):
X, y, X_test, effect, X_all, y_all, ate = realization(train, test, i)
ours = backend.predict(backend.fit(X, y, "causal"), X_test).predictions

theirs = CATEEstimator(device=DEVICE)
theirs.load_model = lambda theirs=theirs: setattr(
theirs, "icl_model", backend._shared_network()
)
theirs = upstream(CATEEstimator, backend)
theirs.fit(X, y[:, 1], y[:, 0])
np.testing.assert_allclose(
ours, theirs.estimate_cate(X_test), rtol=1e-4, atol=1e-4
Expand All @@ -123,13 +167,61 @@ def test_matches_the_published_benchmark(backend, ihdp):
ate_ours.append(
abs(np.mean(backend.predict(whole, X_all).predictions) - ate) / abs(ate)
)
est = ATEEstimator(device=DEVICE)
est.load_model = lambda est=est: setattr(
est, "icl_model", backend._shared_network()
)
est = upstream(ATEEstimator, backend)
est.fit(X_all, y_all[:, 1], y_all[:, 0])
ate_theirs.append(abs(est.estimate_ate() - ate) / abs(ate))

assert np.mean(pehe) == pytest.approx(PUBLISHED_PEHE, abs=PEHE_MARGIN)
assert np.mean(ate_ours) == pytest.approx(np.mean(ate_theirs), abs=1e-3)
assert np.mean(ate_ours) == pytest.approx(PUBLISHED_ATE_ERROR, abs=ATE_MARGIN)


def lalonde_cps(path: Path, i: int):
"""The authors' RealCauseLalondeCPSDataset[i] (benchmarks/realcause.py at
COMMIT): covariates, then t, y, y0, y1 and ite (the row's true effect);
a 90/10 train/test split by default_rng(42 + i)."""
with path.open() as fh:
names = fh.readline().strip().split(",")
rows = np.loadtxt(path, delimiter=",", skiprows=1, dtype=np.float64)
col = {name: rows[:, j] for j, name in enumerate(names)}
X = rows[:, : len(names) - 5].astype(np.float32)
t = (col["t"] != 0).astype(np.float32)
y, ite = col["y"].astype(np.float32), col["ite"].astype(np.float32)
order = np.random.default_rng(42 + i).permutation(len(X))
cut = int(len(X) * 0.9)
return X, t, y, ite, order[:cut], order[cut:]


def test_a_rare_treatment_in_a_table_larger_than_the_context(backend, request):
"""Lalonde CPS: the context keeps every treated row (context_rows), so
the effects are as accurate as CausalPFN's estimator's. Measured over
these 10: PEHE 8,851 against the estimator's 8,828, ATE error 0.128; a
context keeping each arm's share (44 treated rows) scored 9,444 and
0.346. The ATE is checked against a bound, not the ATE estimator."""
from causalpfn import CATEEstimator

cache = fetch(request, "causalpfn-lalonde-cps", CPS_URL, CPS_FILES)
ours, theirs, ate_error = [], [], []
for i, name in enumerate(CPS_FILES):
X, t, y, ite, train, test = lalonde_cps(cache / name, i)
assert len(train) > DEFAULT_CONTEXT_SIZE
assert t[train].sum() < DEFAULT_CONTEXT_SIZE // 2

fit = backend.fit(X[train], np.column_stack([y[train], t[train]]), "causal")
assert len(fit.treated) == DEFAULT_CONTEXT_SIZE
assert fit.treated.sum() == t[train].sum() # every treated row
ours.append(_pehe(backend.predict(fit, X[test]).predictions, ite[test]))
est = upstream(CATEEstimator, backend)
est.fit(X[train], t[train], y[train])
theirs.append(_pehe(est.estimate_cate(X[test]), ite[test]))

whole = backend.fit(X, np.column_stack([y, t]), "causal")
ate = np.mean(backend.predict(whole, X).predictions)
ate_error.append(abs(ate - ite.mean()) / abs(ite.mean()))

assert np.mean(ours) <= CPS_PEHE_RATIO * np.mean(theirs)
assert np.mean(ate_error) <= CPS_ATE_ERROR


def _pehe(estimate, effect) -> float:
return float(np.sqrt(np.mean((np.asarray(estimate) - effect) ** 2)))
Loading