From dab68537212c2addc17cb9dd7fb309047d99a0fc Mon Sep 17 00:00:00 2001 From: Amrit Krishnan Date: Sat, 21 Nov 2026 15:26:41 -0500 Subject: [PATCH 1/3] CausalPFN: keep a rare treatment arm whole in the context A table larger than the context was subsampled keeping each arm's share, so a rare treatment (Lalonde CPS: 173 of 16,177 rows) left the model ~44 treated rows. Each arm now gets up to an equal share of the context, a smaller arm whole, still stratified by outcome within the arm; CausalPFN's own estimator likewise takes up to half its context from each arm. Lalonde CPS, first 10 realizations (the authors' splits): PEHE 9,444 -> 8,851 (CausalPFN's estimator 8,828), ATE error 0.346 -> 0.128. ACIC 2016 (10): PEHE 0.975 -> 0.964 (estimator 0.963). IHDP and PSID fit the context whole and are unchanged. The reference test gains a CPS check that fails on the old sampling. Co-Authored-By: Claude Opus 5.5 --- docs/getting-started/python.md | 5 +- docs/reference/configuration.md | 2 +- src/tabctx/backends/causalpfn.py | 44 +++++++-- tests/integration/test_causalpfn_reference.py | 91 +++++++++++++++++-- tests/unit/test_pfn_backends.py | 50 +++++++++- 5 files changed, 172 insertions(+), 20 deletions(-) diff --git a/docs/getting-started/python.md b/docs/getting-started/python.md index 1392e35..9469a05 100644 --- a/docs/getting-started/python.md +++ b/docs/getting-started/python.md @@ -108,8 +108,9 @@ 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, a rare arm whole, +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. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 3a66983..39b29d9 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -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, giving each arm up to half the context (a rarer arm whole, so a rare treatment isn't left a few dozen rows) and keeping 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. | The `TABCTX_KV_*` and `TABCTX_COMPILE*` settings apply to TabICL only. diff --git a/src/tabctx/backends/causalpfn.py b/src/tabctx/backends/causalpfn.py index 51e3d59..e0a80e8 100644 --- a/src/tabctx/backends/causalpfn.py +++ b/src/tabctx/backends/causalpfn.py @@ -34,9 +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 -every test row is predicted against that same context. CausalPFN's +larger table is subsampled at fit, seeded: each arm gets up to an equal +share of the context, a rarer arm whole, and 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 row's answer depends on which other rows share its call, and a server @@ -100,6 +100,40 @@ _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. + + Not each arm's share of the table: the model estimates each arm's + expected outcome from that arm's rows, so a rare treatment (1% of + Lalonde CPS's rows) would leave it about 40 rows to learn from. + CausalPFN's own estimator likewise takes up to half its context from + each arm. Measured on Lalonde CPS (100 realizations, the authors' + splits): PEHE 9,552 and ATE error 0.39 keeping shares, against 8,955 + and 0.13 for CausalPFN's estimator; tests/integration/ + test_causalpfn_reference.py checks this sampling there.""" + 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 @@ -180,9 +214,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) diff --git a/tests/integration/test_causalpfn_reference.py b/tests/integration/test_causalpfn_reference.py index 8326285..fae905e 100644 --- a/tests/integration/test_causalpfn_reference.py +++ b/tests/integration/test_causalpfn_reference.py @@ -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 @@ -15,9 +15,13 @@ 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; runs on CPU in a few minutes. """ from __future__ import annotations @@ -48,24 +52,49 @@ # 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", +} 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 @@ -133,3 +162,45 @@ def test_matches_the_published_benchmark(backend, ihdp): 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 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, which picks up + to half its context from each arm. Measured over these 10: PEHE 8,851 + vs 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.""" + import pandas as pd + 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): + d = pd.read_csv(cache / name) + X = d.iloc[:, :-5].to_numpy(np.float32) + t = d["t"].astype(bool).to_numpy(np.float32) + y = d["y"].to_numpy(np.float32) + ite = d["ite"].to_numpy(np.float32) + order = np.random.default_rng(42 + i).permutation(len(X)) + train, test = order[: int(len(X) * 0.9)], order[int(len(X) * 0.9) :] + assert len(train) > 4096 and t[train].sum() < 4096 // 2 + + fit = backend.fit(X[train], np.column_stack([y[train], t[train]]), "causal") + ours.append(_pehe(backend.predict(fit, X[test]).predictions, ite[test])) + est = CATEEstimator(device=DEVICE) + est.load_model = lambda est=est: setattr( + est, "icl_model", backend._shared_network() + ) + 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) <= 1.02 * np.mean(theirs) + assert np.mean(ate_error) <= 0.2 + + +def _pehe(estimate, effect) -> float: + return float(np.sqrt(np.mean((np.asarray(estimate) - effect) ** 2))) diff --git a/tests/unit/test_pfn_backends.py b/tests/unit/test_pfn_backends.py index e24546e..64b6a59 100644 --- a/tests/unit/test_pfn_backends.py +++ b/tests/unit/test_pfn_backends.py @@ -13,7 +13,7 @@ tagged_dumps, tagged_loads, ) -from tabctx.backends.causalpfn import _column_medians, _fill +from tabctx.backends.causalpfn import _column_medians, _fill, context_rows from tabctx.backends.survivalpfn import _within @@ -144,3 +144,51 @@ def test_a_context_spills_without_its_network(): def test_array_bytes(): assert array_bytes(np.zeros((3, 2), dtype=np.float32), None) == 24 + + +class TestCausalContextRows: + """Which training rows a causal context keeps (context_rows).""" + + def test_a_table_that_fits_is_kept_whole(self): + treated = np.array([0.0, 1.0, 0.0]) + assert context_rows(treated, np.zeros(3), 3, seed=0).tolist() == [0, 1, 2] + + def test_a_rare_arm_is_kept_whole(self): + # Lalonde CPS's shape: 173 of 16,177 rows treated. + rng = np.random.default_rng(0) + treated = np.zeros(16_177) + treated[rng.choice(16_177, 173, replace=False)] = 1 + keep = context_rows(treated, rng.normal(size=16_177), 4096, seed=0) + assert len(keep) == 4096 and len(set(keep)) == 4096 + assert (keep == np.sort(keep)).all() + assert treated[keep].sum() == 173 # every treated row + # The rare arm's unused share goes to the other arm. + assert (treated[keep] == 0).sum() == 4096 - 173 + + def test_two_large_arms_get_half_each(self): + rng = np.random.default_rng(1) + treated = (rng.random(20_000) < 0.3).astype(float) + keep = context_rows(treated, rng.normal(size=20_000), 1_000, seed=0) + assert len(keep) == 1_000 + assert treated[keep].sum() == 500 + + def test_an_arm_keeps_the_spread_of_its_outcomes(self): + rng = np.random.default_rng(2) + treated = (rng.random(20_000) < 0.3).astype(float) + outcome = rng.lognormal(sigma=2.0, size=20_000) # long right tail + keep = context_rows(treated, outcome, 1_000, seed=0) + levels = np.linspace(0.05, 0.95, 10) + for arm in (0.0, 1.0): + full = np.sort(outcome[treated == arm]) + kept = outcome[keep][treated[keep] == arm] + ranks = np.searchsorted(full, np.quantile(kept, levels)) / len(full) + assert np.abs(ranks - levels).max() < 0.03 + + def test_one_arm_only_and_the_same_rows_every_time(self): + rng = np.random.default_rng(3) + outcome = rng.normal(size=5_000) + keep = context_rows(np.ones(5_000), outcome, 500, seed=0) + assert len(keep) == 500 + assert ( + keep.tolist() == context_rows(np.ones(5_000), outcome, 500, seed=0).tolist() + ) From 094824ecb8144604afbd2a01096bdba91f5fbab8 Mon Sep 17 00:00:00 2001 From: Amrit Krishnan Date: Sat, 21 Nov 2026 15:45:12 -0500 Subject: [PATCH 2/3] Address review: upstream wording, docs, changelog, test constants Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/getting-started/python.md | 5 +- docs/reference/configuration.md | 2 +- src/tabctx/backends/_pfn_common.py | 14 ++-- src/tabctx/backends/causalpfn.py | 29 ++++--- tests/integration/test_causalpfn_reference.py | 79 ++++++++++++------- tests/unit/test_pfn_backends.py | 8 +- 7 files changed, 87 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a85d5fc..448ddf5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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; its first 10 realizations) tabctx's effects had a PEHE of 9,444 and an ATE error of 0.346, against 8,828 and 0.073 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,851 and 0.128. 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 diff --git a/docs/getting-started/python.md b/docs/getting-started/python.md index 9469a05..c06fd77 100644 --- a/docs/getting-started/python.md +++ b/docs/getting-started/python.md @@ -109,8 +109,9 @@ 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: SurvivalPFN keeps the share of events and the spread of -times; CausalPFN gives each arm up to half the context, a rare arm whole, -and keeps the spread of outcomes; +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. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 39b29d9..fd2f41e 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -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, giving each arm up to half the context (a rarer arm whole, so a rare treatment isn't left a few dozen rows) and keeping 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. diff --git a/src/tabctx/backends/_pfn_common.py b/src/tabctx/backends/_pfn_common.py index f449805..64c03e1 100644 --- a/src/tabctx/backends/_pfn_common.py +++ b/src/tabctx/backends/_pfn_common.py @@ -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 @@ -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 diff --git a/src/tabctx/backends/causalpfn.py b/src/tabctx/backends/causalpfn.py index e0a80e8..d8ea199 100644 --- a/src/tabctx/backends/causalpfn.py +++ b/src/tabctx/backends/causalpfn.py @@ -34,9 +34,10 @@ 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: each arm gets up to an equal -share of the context, a rarer arm whole, and keeps the spread of its -outcomes; see context_rows), and every test row is predicted against that same context. CausalPFN's +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 row's answer depends on which other rows share its call, and a server @@ -110,14 +111,20 @@ def context_rows( Within an arm, rows are sampled across equal-count bands of the outcome (strata), so the arm keeps its spread of outcomes. - Not each arm's share of the table: the model estimates each arm's - expected outcome from that arm's rows, so a rare treatment (1% of - Lalonde CPS's rows) would leave it about 40 rows to learn from. - CausalPFN's own estimator likewise takes up to half its context from - each arm. Measured on Lalonde CPS (100 realizations, the authors' - splits): PEHE 9,552 and ATE error 0.39 keeping shares, against 8,955 - and 0.13 for CausalPFN's estimator; tests/integration/ - test_causalpfn_reference.py checks this sampling there.""" + 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 (its first 10 realizations, the authors' + splits; tests/integration/test_causalpfn_reference.py): PEHE 8,851 and + ATE error 0.128, against 9,444 and 0.346 keeping shares and 8,828 and + 0.073 for CausalPFN's estimator. 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) diff --git a/tests/integration/test_causalpfn_reference.py b/tests/integration/test_causalpfn_reference.py index fae905e..3cd5ca6 100644 --- a/tests/integration/test_causalpfn_reference.py +++ b/tests/integration/test_causalpfn_reference.py @@ -21,7 +21,9 @@ 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; runs on CPU in a few minutes. +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 @@ -36,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 = { @@ -71,6 +76,11 @@ "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" @@ -99,6 +109,14 @@ def ihdp(request) -> tuple[dict, dict]: 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) @@ -138,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 @@ -152,10 +167,7 @@ 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)) @@ -164,33 +176,42 @@ def test_matches_the_published_benchmark(backend, ihdp): 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, which picks up - to half its context from each arm. Measured over these 10: PEHE 8,851 - vs 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.""" - import pandas as pd + 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): - d = pd.read_csv(cache / name) - X = d.iloc[:, :-5].to_numpy(np.float32) - t = d["t"].astype(bool).to_numpy(np.float32) - y = d["y"].to_numpy(np.float32) - ite = d["ite"].to_numpy(np.float32) - order = np.random.default_rng(42 + i).permutation(len(X)) - train, test = order[: int(len(X) * 0.9)], order[int(len(X) * 0.9) :] - assert len(train) > 4096 and t[train].sum() < 4096 // 2 + 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 = CATEEstimator(device=DEVICE) - est.load_model = lambda est=est: setattr( - est, "icl_model", backend._shared_network() - ) + est = upstream(CATEEstimator, backend) est.fit(X[train], t[train], y[train]) theirs.append(_pehe(est.estimate_cate(X[test]), ite[test])) @@ -198,8 +219,8 @@ def test_a_rare_treatment_in_a_table_larger_than_the_context(backend, request): ate = np.mean(backend.predict(whole, X).predictions) ate_error.append(abs(ate - ite.mean()) / abs(ite.mean())) - assert np.mean(ours) <= 1.02 * np.mean(theirs) - assert np.mean(ate_error) <= 0.2 + assert np.mean(ours) <= CPS_PEHE_RATIO * np.mean(theirs) + assert np.mean(ate_error) <= CPS_ATE_ERROR def _pehe(estimate, effect) -> float: diff --git a/tests/unit/test_pfn_backends.py b/tests/unit/test_pfn_backends.py index 64b6a59..d1851d7 100644 --- a/tests/unit/test_pfn_backends.py +++ b/tests/unit/test_pfn_backends.py @@ -162,8 +162,6 @@ def test_a_rare_arm_is_kept_whole(self): assert len(keep) == 4096 and len(set(keep)) == 4096 assert (keep == np.sort(keep)).all() assert treated[keep].sum() == 173 # every treated row - # The rare arm's unused share goes to the other arm. - assert (treated[keep] == 0).sum() == 4096 - 173 def test_two_large_arms_get_half_each(self): rng = np.random.default_rng(1) @@ -172,6 +170,12 @@ def test_two_large_arms_get_half_each(self): assert len(keep) == 1_000 assert treated[keep].sum() == 500 + def test_an_odd_size_and_an_arm_just_over_half(self): + treated = np.r_[np.ones(600), np.zeros(500)] # 600 of 1,100 + keep = context_rows(treated, np.arange(1_100.0), 999, seed=0) + assert len(keep) == 999 and len(set(keep)) == 999 + assert treated[keep].sum() == 500 # the larger arm, half (rounded up) + def test_an_arm_keeps_the_spread_of_its_outcomes(self): rng = np.random.default_rng(2) treated = (rng.random(20_000) < 0.3).astype(float) From 035ee20b7aac3a17b70d9c40a29ffa3f9e7e3a45 Mon Sep 17 00:00:00 2001 From: Amrit Krishnan Date: Sat, 21 Nov 2026 17:11:19 -0500 Subject: [PATCH 3/3] Quote the full 100-realization Lalonde CPS numbers Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- src/tabctx/backends/causalpfn.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 448ddf5..e4415ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +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; its first 10 realizations) tabctx's effects had a PEHE of 9,444 and an ATE error of 0.346, against 8,828 and 0.073 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,851 and 0.128. 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. +- **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 diff --git a/src/tabctx/backends/causalpfn.py b/src/tabctx/backends/causalpfn.py index d8ea199..e990d92 100644 --- a/src/tabctx/backends/causalpfn.py +++ b/src/tabctx/backends/causalpfn.py @@ -118,10 +118,10 @@ def context_rows( (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 (its first 10 realizations, the authors' - splits; tests/integration/test_causalpfn_reference.py): PEHE 8,851 and - ATE error 0.128, against 9,444 and 0.346 keeping shares and 8,828 and - 0.073 for CausalPFN's estimator. On simulated 20,000-row + 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)."""