FirePFN 1.0.0.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of FirePFN might be problematic. Click here for more details.

Files changed (46) hide show
  1. firepfn/__init__.py +7 -0
  2. firepfn/class_tree.py +77 -0
  3. firepfn/classifier.py +301 -0
  4. firepfn/encoding.py +347 -0
  5. firepfn/ensemble.py +44 -0
  6. firepfn/eval/__init__.py +14 -0
  7. firepfn/eval/analysis.py +294 -0
  8. firepfn/eval/plots.py +330 -0
  9. firepfn/eval/runtime.py +205 -0
  10. firepfn/eval/tabarena.py +388 -0
  11. firepfn/loading.py +97 -0
  12. firepfn/many_class.py +157 -0
  13. firepfn/model/__init__.py +5 -0
  14. firepfn/model/_mamba_block.py +49 -0
  15. firepfn/model/backbone.py +110 -0
  16. firepfn/model/cross_attention.py +123 -0
  17. firepfn/model/deltanet.py +134 -0
  18. firepfn/model/fire_pfn.py +396 -0
  19. firepfn/model/fla_autotune.py +73 -0
  20. firepfn/model/hydra2.py +537 -0
  21. firepfn/model/int32_safe.py +122 -0
  22. firepfn/model/kumo.py +704 -0
  23. firepfn/model/linear_attention.py +167 -0
  24. firepfn/model/stream_infer.py +568 -0
  25. firepfn/model/triton_rmsnorm.py +119 -0
  26. firepfn/model/triton_rope.py +152 -0
  27. firepfn/preprocessing.py +301 -0
  28. firepfn/train/__init__.py +3 -0
  29. firepfn/train/__main__.py +57 -0
  30. firepfn/train/_tabicl_dataset.py +1762 -0
  31. firepfn/train/configs.py +113 -0
  32. firepfn/train/loop.py +224 -0
  33. firepfn/train/optim.py +109 -0
  34. firepfn/train/prior.py +74 -0
  35. firepfn/train/schedule.py +125 -0
  36. firepfn-1.0.0.dev0.dist-info/METADATA +270 -0
  37. firepfn-1.0.0.dev0.dist-info/RECORD +46 -0
  38. firepfn-1.0.0.dev0.dist-info/WHEEL +5 -0
  39. firepfn-1.0.0.dev0.dist-info/licenses/AUTHORS +14 -0
  40. firepfn-1.0.0.dev0.dist-info/licenses/LICENSE +33 -0
  41. firepfn-1.0.0.dev0.dist-info/licenses/LICENSES/Apache-2.0.txt +176 -0
  42. firepfn-1.0.0.dev0.dist-info/licenses/LICENSES/BSD-3-Clause-TabICL.txt +236 -0
  43. firepfn-1.0.0.dev0.dist-info/licenses/LICENSES/MIT-Hydra.txt +21 -0
  44. firepfn-1.0.0.dev0.dist-info/licenses/LICENSES/OpenMDW-1.1-Kumo-Tabular-weights.txt +52 -0
  45. firepfn-1.0.0.dev0.dist-info/licenses/NOTICE +39 -0
  46. firepfn-1.0.0.dev0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,205 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Fit + predict time and peak GPU memory of FirePFN against the number of context rows.
4
+
5
+ For every context size, in a fresh process (clean CUDA context and peak-memory counter; an
6
+ out-of-memory error cannot affect later sizes):
7
+
8
+ 1. warmup: an untimed fit + predict_proba on independently drawn data of exactly the same shape
9
+ (CUDA init, checkpoint loading, shape-specialised kernel autotuning, allocator growth);
10
+ 2. timed: ``fit(X_train, y_train)`` then ``predict_proba(X_test)``, with a CUDA synchronize before
11
+ every clock read; repeated while the timed total stays below ``--repeat-budget`` seconds (at
12
+ most ``--max-repeats`` times) and the medians are reported.
13
+
14
+ The number of test rows is fixed (default 1000), so the curve shows the cost of the labelled
15
+ context. Data: sklearn's make_classification. Once a size fails (OOM, error, timeout) or takes
16
+ longer than ``--max-seconds``, larger sizes are skipped.
17
+
18
+ ``status`` per row: ``ok``; ``oom`` / ``error`` (message in ``error``); ``timeout`` (the per-size
19
+ process was killed, no message); ``exit<code>``; ``over_budget`` -- a valid measurement (times,
20
+ memory and AUC filled in) that took longer than ``--max-seconds``, so it is the last size tried.
21
+ Treat ``ok`` and ``over_budget`` rows as measurements. Which context-encoding path the timed
22
+ runs took (firepfn.model.stream_infer): ``streaming`` (context longer than
23
+ FIREPFN_STREAM_CTX_ROWS), ``token_recompute`` (the encoder's full token buffer did not fit on the
24
+ GPU, so every column summary was recomputed in its own pass over the context -- markedly slower
25
+ per row), ``host_offload`` / ``host_buffer_gib`` (context buffer kept in host memory; not in
26
+ ``peak_gpu_mem_gb``). The paper's grid:
27
+
28
+ for F in 20 200 500; do
29
+ python -m firepfn.eval.runtime --n-features $F --output results/runtime/f${F}_mine.csv
30
+ done
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import json
36
+ import multiprocessing as mp
37
+ import os
38
+ import statistics
39
+ import time
40
+ from pathlib import Path
41
+
42
+ import numpy as np
43
+ import pandas as pd
44
+
45
+ DEFAULT_SIZES = [100, 250, 500, 1_000, 2_500, 5_000, 10_000, 25_000, 50_000, 100_000, 250_000,
46
+ 500_000, 1_000_000, 2_000_000, 4_000_000, 8_000_000, 12_000_000, 16_000_000]
47
+
48
+
49
+ def make_data(n_train, n_test, n_features, n_classes, seed):
50
+ from sklearn.datasets import make_classification
51
+ n_inf = max(2, min(n_features, n_features // 2))
52
+ X, y = make_classification(
53
+ n_samples=n_train + n_test, n_features=n_features, n_informative=n_inf,
54
+ n_redundant=min(n_features - n_inf, n_features // 4), n_classes=n_classes,
55
+ n_clusters_per_class=2, flip_y=0.05, class_sep=1.0, random_state=seed)
56
+ X = pd.DataFrame(X.astype(np.float32), columns=[f"f{i}" for i in range(n_features)])
57
+ y = pd.Series(y, name="target")
58
+ return (X.iloc[:n_train].reset_index(drop=True), y.iloc[:n_train].reset_index(drop=True),
59
+ X.iloc[n_train:].reset_index(drop=True), y.iloc[n_train:].reset_index(drop=True))
60
+
61
+
62
+ def _sync():
63
+ import torch
64
+ if torch.cuda.is_available():
65
+ torch.cuda.synchronize()
66
+
67
+
68
+ def _worker(q, model_name, model_kwargs, n_train, a):
69
+ import torch
70
+ from sklearn.metrics import roc_auc_score
71
+
72
+ from firepfn.eval.tabarena import make_model
73
+ from firepfn.model import stream_infer
74
+
75
+ row = {"model": model_name, "n_train": n_train, "status": "ok"}
76
+ try:
77
+ Xw, yw, Xwt, _ = make_data(n_train, a["n_test"], a["n_features"], a["n_classes"],
78
+ seed=10_000 + n_train)
79
+ t = time.perf_counter()
80
+ m = make_model(model_kwargs).fit(Xw, yw)
81
+ m.predict_proba(Xwt)
82
+ _sync()
83
+ row["warmup_time"] = time.perf_counter() - t
84
+ del m, Xw, yw, Xwt
85
+
86
+ X, y, Xt, yt = make_data(n_train, a["n_test"], a["n_features"], a["n_classes"],
87
+ seed=n_train)
88
+ if torch.cuda.is_available():
89
+ torch.cuda.empty_cache()
90
+ torch.cuda.reset_peak_memory_stats()
91
+ stream_infer.reset_path_stats() # inference path of the timed runs only
92
+ fits, preds = [], []
93
+ while len(fits) < a["max_repeats"]:
94
+ m = make_model(model_kwargs)
95
+ _sync()
96
+ t0 = time.perf_counter()
97
+ m.fit(X, y)
98
+ _sync()
99
+ t1 = time.perf_counter()
100
+ proba = m.predict_proba(Xt)
101
+ _sync()
102
+ t2 = time.perf_counter()
103
+ fits.append(t1 - t0)
104
+ preds.append(t2 - t1)
105
+ if sum(fits) + sum(preds) > a["repeat_budget"]:
106
+ break
107
+ classes = list(m.classes_)
108
+ row["roc_auc"] = (roc_auc_score(yt, proba[:, classes.index(1)]) if a["n_classes"] == 2
109
+ else roc_auc_score(yt, proba, multi_class="ovo", labels=classes))
110
+ row.update(
111
+ n_repeats=len(fits), fit_time=statistics.median(fits),
112
+ pred_time=statistics.median(preds),
113
+ total_time=statistics.median([f + p for f, p in zip(fits, preds)]),
114
+ total_time_min=min(f + p for f, p in zip(fits, preds)),
115
+ peak_gpu_mem_gb=(torch.cuda.max_memory_allocated() / 2**30
116
+ if torch.cuda.is_available() else np.nan),
117
+ hardware=torch.cuda.get_device_name() if torch.cuda.is_available() else "cpu")
118
+ st = stream_infer.path_stats() # which context-encoding path FirePFN took
119
+ row.update(streaming=st["any_stream"], token_recompute=st["token_recompute"],
120
+ host_offload=st["host_offload"], host_buffer_gib=st["host_buffer_gib"])
121
+ except Exception as e: # noqa: BLE001 -- recorded; decides the cutoff
122
+ msg = str(e).splitlines()[0][:300] if str(e) else type(e).__name__
123
+ row["status"] = "oom" if "out of memory" in msg.lower() else "error"
124
+ row["error"] = msg
125
+ print(f"[n={n_train}] {row['status']}: {msg}", flush=True)
126
+ q.put(row)
127
+
128
+
129
+ def run_one(ctx, model_name, model_kwargs, n_train, a, timeout):
130
+ q = ctx.Queue()
131
+ p = ctx.Process(target=_worker, args=(q, model_name, model_kwargs, n_train, a))
132
+ p.start()
133
+ try:
134
+ row = q.get(timeout=timeout)
135
+ except Exception: # noqa: BLE001
136
+ row = {"model": model_name, "n_train": n_train, "status": "timeout"}
137
+ p.join(timeout=60)
138
+ if p.is_alive():
139
+ p.terminate()
140
+ p.join()
141
+ if p.exitcode not in (0, None) and row.get("status") == "ok":
142
+ row["status"] = f"exit{p.exitcode}"
143
+ return row
144
+
145
+
146
+ def main(argv=None):
147
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
148
+ ap.add_argument("--output", required=True, type=Path, help="result CSV (resumed if present)")
149
+ ap.add_argument("--name", default="FirePFN", help="model name in the CSV")
150
+ ap.add_argument("--model-path", default=None, help="checkpoint (default: released weights)")
151
+ ap.add_argument("--set", action="append", default=[], metavar="KEY=JSON",
152
+ help="further FirePFNClassifier arguments")
153
+ ap.add_argument("--sizes", type=int, nargs="+", default=DEFAULT_SIZES)
154
+ ap.add_argument("--n-test", type=int, default=1000)
155
+ ap.add_argument("--n-features", type=int, default=20)
156
+ ap.add_argument("--n-classes", type=int, default=2)
157
+ ap.add_argument("--max-repeats", type=int, default=3)
158
+ ap.add_argument("--repeat-budget", type=float, default=120.0,
159
+ help="stop repeating once the timed seconds add up to more than this")
160
+ ap.add_argument("--max-seconds", type=float, default=1800.0,
161
+ help="skip larger sizes after a fit + predict above this")
162
+ ap.add_argument("--timeout", type=float, default=3 * 3600,
163
+ help="per-size process timeout, warmup included")
164
+ args = ap.parse_args(argv)
165
+
166
+ # The full training set as context (no 100k-row cap): the grid measures how FirePFN scales
167
+ # with the context size. --set max_context_rows=100000 gives the capped default instead.
168
+ kwargs = {"model_path": args.model_path, "max_context_rows": None}
169
+ for kv in args.set:
170
+ k, _, v = kv.partition("=")
171
+ kwargs[k] = json.loads(v)
172
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
173
+ out = args.output
174
+ out.parent.mkdir(parents=True, exist_ok=True)
175
+ df = pd.read_csv(out) if out.exists() else pd.DataFrame()
176
+ done = set(df["n_train"]) if not df.empty else set()
177
+ total = df["total_time"].fillna(0) if "total_time" in df else 0 # absent if every row failed
178
+ stopped = not df.empty and bool(((df["status"] != "ok") | (total > args.max_seconds)).any())
179
+
180
+ a = dict(n_test=args.n_test, n_features=args.n_features, n_classes=args.n_classes,
181
+ max_repeats=args.max_repeats, repeat_budget=args.repeat_budget)
182
+ meta = dict(n_test=args.n_test, n_features=args.n_features, n_classes=args.n_classes,
183
+ n_cpus=len(os.sched_getaffinity(0)))
184
+ ctx = mp.get_context("spawn")
185
+ for n in sorted(args.sizes):
186
+ if n in done or stopped:
187
+ continue
188
+ print(f"=== n_train={n} ===", flush=True)
189
+ row = {**run_one(ctx, args.name, kwargs, n, a, args.timeout), **meta}
190
+ if row["status"] == "ok" and row.get("total_time", 0) > args.max_seconds:
191
+ row["status"] = "over_budget"
192
+ print({k: row.get(k) for k in ("status", "fit_time", "pred_time", "total_time",
193
+ "peak_gpu_mem_gb", "roc_auc")}, flush=True)
194
+ df = pd.concat([df, pd.DataFrame([row])], ignore_index=True)
195
+ tmp = out.with_suffix(out.suffix + ".tmp")
196
+ df.to_csv(tmp, index=False)
197
+ tmp.replace(out)
198
+ if row["status"] != "ok":
199
+ print("--> no larger sizes", flush=True)
200
+ stopped = True
201
+ print(f"Results in {out}", flush=True)
202
+
203
+
204
+ if __name__ == "__main__":
205
+ main()
@@ -0,0 +1,388 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Evaluate FirePFN on the TabArena classification tasks (OpenML suite 457).
4
+
5
+ Protocol (as in the paper):
6
+
7
+ * every binary / multiclass task of the suite, with TabArena's official splits; all repeats x
8
+ folds, at most 3 repeats for tasks with >= 2500 samples (``--lite``: repeat 0, fold 0 only);
9
+ * each split runs in a fresh process: an untimed warmup fit + predict on random data with the
10
+ split's exact shape, dtypes, distinct values per column and class frequencies (pays for CUDA
11
+ init, checkpoint loading and shape-specialised kernel autotuning), then the timed ``fit`` and
12
+ ``predict``;
13
+ * metrics: accuracy and ROC AUC (binary), plus log loss (multiclass; TabArena's official
14
+ multiclass metric). Multiclass ROC AUC is one-vs-one, macro averaged.
15
+
16
+ Results are appended to a CSV (one row per split) and the run resumes from it: splits that
17
+ already have all metrics are skipped, failed / timed-out splits are retried.
18
+
19
+ Data: compute nodes often have no internet access. Download the suite first (same
20
+ ``OPENML_CACHE_DIR`` as the evaluation):
21
+
22
+ python -m firepfn.eval.tabarena prefetch
23
+ python -m firepfn.eval.tabarena run --output results/tabarena/fire-pfn_mine.csv
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import json
29
+ import multiprocessing as mp
30
+ import os
31
+ import queue
32
+ import time
33
+ from pathlib import Path
34
+
35
+ import numpy as np
36
+ import pandas as pd
37
+ from sklearn.metrics import accuracy_score, log_loss, roc_auc_score
38
+
39
+ TABARENA_SUITE = 457
40
+ RESULT_KEYS = ["model", "task_id", "repeat", "fold"]
41
+ METRICS = {"binary": ["accuracy", "roc_auc"], "multiclass": ["accuracy", "roc_auc", "log_loss"]}
42
+
43
+
44
+ # ---------------------------------------------------------------------------------------------- #
45
+ # Tasks
46
+ # ---------------------------------------------------------------------------------------------- #
47
+
48
+ def _suite_cache_file() -> Path:
49
+ import openml
50
+ return Path(openml.config.get_cache_directory()) / f"suite_{TABARENA_SUITE}_tasks.json"
51
+
52
+
53
+ def get_task_ids() -> list[int]:
54
+ """Task ids of the suite (cached locally: openml always asks the server for suites)."""
55
+ import openml
56
+ cache = _suite_cache_file()
57
+ if cache.exists():
58
+ return json.loads(cache.read_text())
59
+ task_ids = list(openml.study.get_suite(TABARENA_SUITE).tasks)
60
+ cache.parent.mkdir(parents=True, exist_ok=True)
61
+ cache.write_text(json.dumps(task_ids))
62
+ return task_ids
63
+
64
+
65
+ def prefetch() -> None:
66
+ """Download suite metadata, tasks, datasets and splits into the OpenML cache."""
67
+ import openml
68
+ if _suite_cache_file().exists():
69
+ _suite_cache_file().unlink()
70
+ task_ids = get_task_ids()
71
+ print(f"Prefetching {len(task_ids)} tasks into {openml.config.get_cache_directory()}.",
72
+ flush=True)
73
+ failed = []
74
+ for i, tid in enumerate(task_ids):
75
+ try: # same arguments as tabarena's get_task, plus the splits
76
+ task = openml.tasks.get_task(tid, download_splits=True, download_data=True,
77
+ download_qualities=True,
78
+ download_features_meta_data=True)
79
+ task.get_dataset().get_data(task.target_name)
80
+ print(f" [{i + 1}/{len(task_ids)}] task {tid}", flush=True)
81
+ except Exception as e: # noqa: BLE001
82
+ failed.append(tid)
83
+ print(f" [{i + 1}/{len(task_ids)}] task {tid} FAILED: {e}", flush=True)
84
+ if failed:
85
+ raise SystemExit(f"Failed to prefetch tasks: {failed}")
86
+
87
+
88
+ # ---------------------------------------------------------------------------------------------- #
89
+ # One split
90
+ # ---------------------------------------------------------------------------------------------- #
91
+
92
+ def make_model(model_kwargs: dict):
93
+ """FirePFNClassifier(**model_kwargs) behind the DataFrame encoding of firepfn.encoding.
94
+ The keys "target_encode_min_levels" (default 500; None = off) and "id_guard" (default True)
95
+ are passed to the encoding."""
96
+ from firepfn import FirePFNClassifier
97
+ from firepfn.encoding import make_dataframe_classifier
98
+ kw = dict(model_kwargs)
99
+ te = kw.pop("target_encode_min_levels", 500)
100
+ id_guard = kw.pop("id_guard", True)
101
+ return make_dataframe_classifier(FirePFNClassifier(**kw), target_encode_min_levels=te,
102
+ skip_id_like=id_guard)
103
+
104
+
105
+ def _synthetic_like(X: pd.DataFrame, n_rows: int, rng) -> pd.DataFrame:
106
+ """Random table with X's columns, dtypes, categories and per-column missing rate.
107
+
108
+ Continuous numeric columns are Gaussian with the column's mean / std; integer and
109
+ low-cardinality numeric columns and all other columns are drawn from the column's observed
110
+ values, each distinct value at least once when n_rows allows it. The number of distinct
111
+ values decides what the preprocessing keeps (constant columns are dropped, high-cardinality
112
+ categoricals are target-encoded, ...), i.e. the tensor shapes of the timed run; a warmup on
113
+ other shapes would leave shape-dependent first-call costs in the timed fit.
114
+ """
115
+ def _draw(observed, missing):
116
+ """n_rows values from `observed` (in random order), every distinct value at least once
117
+ among the non-missing rows if there are enough of them."""
118
+ vals = rng.choice(observed.to_numpy(), n_rows)
119
+ uniq = pd.unique(observed.to_numpy())
120
+ slots = np.flatnonzero(~missing)
121
+ if len(uniq) <= len(slots):
122
+ vals[rng.choice(slots, len(uniq), replace=False)] = uniq
123
+ return vals
124
+
125
+ cols = {}
126
+ for c in X.columns:
127
+ s = X[c]
128
+ observed = s.dropna()
129
+ missing = rng.random(n_rows) < s.isna().mean()
130
+ if s.isna().any() and not missing.any() and n_rows > 1:
131
+ missing[rng.integers(n_rows)] = True # keep "has missing values" (e.g. constant + NaN)
132
+ need = min(observed.nunique(), n_rows - int(s.isna().any()))
133
+ if (~missing).sum() < need: # mostly-missing columns: room for every value
134
+ missing[rng.choice(np.flatnonzero(missing), need - int((~missing).sum()),
135
+ replace=False)] = False
136
+ numeric = pd.api.types.is_numeric_dtype(s) and not pd.api.types.is_bool_dtype(s)
137
+ if len(observed) == 0:
138
+ cols[c] = pd.Series([s.iloc[0]] * n_rows, dtype=s.dtype)
139
+ elif numeric and (pd.api.types.is_integer_dtype(s) or observed.nunique() <= 32):
140
+ vals = pd.Series(_draw(observed, missing), dtype=s.dtype)
141
+ cols[c] = vals.mask(missing) if missing.any() else vals
142
+ elif numeric:
143
+ sd = float(observed.std()) if len(observed) > 1 else 1.0
144
+ vals = rng.normal(float(observed.mean()), sd if sd > 0 else 1.0, n_rows)
145
+ if pd.api.types.is_integer_dtype(s): # stay castable (e.g. unsigned dtypes)
146
+ vals = np.clip(np.round(vals), observed.min(), observed.max())
147
+ vals[missing] = np.nan
148
+ cols[c] = pd.Series(vals).astype(s.dtype)
149
+ else: # categorical, string, bool, datetime
150
+ vals = pd.Series(_draw(observed, missing), dtype=s.dtype)
151
+ cols[c] = vals.mask(missing) if missing.any() else vals
152
+ return pd.DataFrame(cols, columns=X.columns)
153
+
154
+
155
+ def cuda_sync() -> None:
156
+ """Wait for queued GPU work, so it is timed in the phase that launched it."""
157
+ import torch
158
+ if torch.cuda.is_available() and torch.cuda.is_initialized():
159
+ torch.cuda.synchronize()
160
+
161
+
162
+ def _warmup(model_kwargs, X_train, y_train, X_test, seed=0) -> None:
163
+ """Untimed fit + predict on random data shaped exactly like the split (rows, columns, dtypes,
164
+ categories, class frequencies). Do not shrink it: some kernels autotune per size bucket."""
165
+ rng = np.random.default_rng(seed)
166
+ X_fit = _synthetic_like(X_train, len(X_train), rng)
167
+ X_pred = _synthetic_like(X_train, len(X_test), rng)
168
+ y_fit = pd.Series(rng.permutation(np.asarray(y_train)), name=y_train.name)
169
+ if isinstance(y_train.dtype, pd.CategoricalDtype):
170
+ y_fit = y_fit.astype(y_train.dtype)
171
+ t = time.perf_counter()
172
+ try:
173
+ model = make_model(model_kwargs).fit(X_fit, y_fit)
174
+ model.predict(X_pred)
175
+ model.predict_proba(X_pred)
176
+ print(f"Warmup took {time.perf_counter() - t:.1f}s.", flush=True)
177
+ except Exception as e: # noqa: BLE001
178
+ print(f"Warmup failed (ignored): {e}", flush=True)
179
+
180
+
181
+ def score(metric, task_type, y_test, y_pred, y_score, classes):
182
+ """accuracy / roc_auc / log_loss. Probability columns are put in sorted label order first
183
+ (sklearn's log_loss and multiclass roc_auc read them in that order)."""
184
+ if metric == "accuracy":
185
+ return accuracy_score(y_test, y_pred)
186
+ order = np.argsort(np.asarray(classes), kind="stable")
187
+ y_score = np.asarray(y_score)[:, order]
188
+ classes = np.asarray(classes)[order]
189
+ if metric == "log_loss":
190
+ return log_loss(y_test, y_score, labels=list(classes))
191
+ if metric != "roc_auc":
192
+ raise ValueError(f"unsupported metric {metric!r}")
193
+ classes = list(classes)
194
+ if task_type == "binary":
195
+ pos_label = sorted(np.unique(y_test))[-1] # sklearn's positive class: largest label
196
+ pos_col = classes.index(pos_label) if pos_label in classes else 1
197
+ return roc_auc_score(y_test, y_score[:, pos_col])
198
+ try:
199
+ return roc_auc_score(y_test, y_score, average="macro", multi_class="ovo")
200
+ except ValueError:
201
+ # Classes missing from the test fold: score the present ones, renormalised.
202
+ present = np.isin(classes, np.unique(y_test))
203
+ y_score = y_score[:, present] / y_score[:, present].sum(axis=1, keepdims=True)
204
+ if present.sum() == 2:
205
+ return roc_auc_score(y_test, y_score[:, 1])
206
+ return roc_auc_score(y_test, y_score, labels=np.asarray(classes)[present],
207
+ average="macro", multi_class="ovo")
208
+
209
+
210
+ def _split_worker(result_queue, model_name, model_kwargs, X_train, y_train, X_test, y_test,
211
+ task_type, info, warmup=True):
212
+ """Fresh process per split: a CUDA error cannot affect later splits."""
213
+ try:
214
+ if warmup:
215
+ _warmup(model_kwargs, X_train, y_train, X_test)
216
+ model = make_model(model_kwargs)
217
+ t = time.perf_counter()
218
+ model.fit(X_train, y_train)
219
+ cuda_sync()
220
+ fit_time = time.perf_counter() - t
221
+ t = time.perf_counter()
222
+ y_pred = model.predict(X_test)
223
+ cuda_sync()
224
+ pred_time = time.perf_counter() - t
225
+ y_score = model.predict_proba(X_test)
226
+ scores = {}
227
+ for metric in METRICS[task_type]:
228
+ try:
229
+ scores[metric] = score(metric, task_type, y_test, y_pred, y_score, model.classes_)
230
+ except ValueError as e:
231
+ print(f"{metric} failed: {e}", flush=True)
232
+ scores[metric] = np.nan
233
+ import torch
234
+ hardware = torch.cuda.get_device_name() if torch.cuda.is_available() else "cpu"
235
+ row = {**info, "model": model_name, "fit_time": fit_time, "pred_time": pred_time,
236
+ **scores, "hardware": hardware}
237
+ print(f"fit {fit_time:.2f}s, predict {pred_time:.2f}s, {scores}", flush=True)
238
+ result_queue.put(row)
239
+ except Exception as e: # noqa: BLE001
240
+ print(f"ERROR: {e}", flush=True)
241
+ result_queue.put(None)
242
+
243
+
244
+ def run_split(ctx, timeout, label, *args, **kwargs) -> dict | None:
245
+ """_split_worker in a fresh process; its result row, or None on failure / timeout."""
246
+ q = ctx.Queue()
247
+ p = ctx.Process(target=_split_worker, args=(q, *args), kwargs=kwargs)
248
+ p.start()
249
+ row, deadline = None, time.monotonic() + timeout
250
+ while True:
251
+ remaining = deadline - time.monotonic()
252
+ if remaining <= 0:
253
+ print(f"Timed out: {label}.", flush=True)
254
+ break
255
+ try:
256
+ got = q.get(timeout=min(remaining, 30))
257
+ except queue.Empty:
258
+ if p.is_alive():
259
+ continue
260
+ print(f"Worker died: {label}.", flush=True)
261
+ break
262
+ if got is None:
263
+ break
264
+ row = got
265
+ p.join(timeout=60)
266
+ if p.is_alive():
267
+ p.terminate()
268
+ p.join()
269
+ return row
270
+
271
+
272
+ def _merge_rows(rows, path: Path) -> None:
273
+ """Merge rows into the CSV under a file lock (several runs may share one file); rows replace
274
+ existing rows with the same (model, task_id, repeat, fold)."""
275
+ import fcntl
276
+ path.parent.mkdir(parents=True, exist_ok=True)
277
+ with open(path.with_suffix(path.suffix + ".lock"), "w") as lock:
278
+ fcntl.flock(lock, fcntl.LOCK_EX)
279
+ df = pd.read_csv(path) if path.exists() else pd.DataFrame()
280
+ new = pd.DataFrame(rows)
281
+ if not df.empty:
282
+ old_keys = pd.MultiIndex.from_frame(df[RESULT_KEYS].astype(str))
283
+ df = df[~old_keys.isin(pd.MultiIndex.from_frame(new[RESULT_KEYS].astype(str)))]
284
+ tmp = path.with_suffix(path.suffix + ".tmp")
285
+ pd.concat([df, new], ignore_index=True).to_csv(tmp, index=False)
286
+ tmp.replace(path)
287
+
288
+
289
+ # ---------------------------------------------------------------------------------------------- #
290
+ # Suite
291
+ # ---------------------------------------------------------------------------------------------- #
292
+
293
+ def evaluate(output: Path, model_name="FirePFN", model_kwargs=None, lite=False,
294
+ task_indices=None, task_types=("binary", "multiclass"), split_timeout=1800,
295
+ warmup=True) -> None:
296
+ """Evaluate FirePFN on TabArena, resuming from `output` if it exists."""
297
+ from tabarena.benchmark.task.openml import OpenMLTaskWrapper
298
+
299
+ model_kwargs = dict(model_kwargs or {})
300
+ output = Path(output)
301
+ done = set()
302
+ if output.exists():
303
+ for _, r in pd.read_csv(output).iterrows():
304
+ if all(m in r.index and pd.notna(r[m]) for m in METRICS.get(r["task_type"], [])):
305
+ done.add((r["model"], r["task_id"], r["repeat"], r["fold"]))
306
+ print(f"Resuming from {output}: {len(done)} complete splits.", flush=True)
307
+
308
+ ctx = mp.get_context("spawn")
309
+ t0 = time.perf_counter()
310
+ for i_dataset, task_id in enumerate(get_task_ids()):
311
+ if task_indices is not None and i_dataset not in task_indices:
312
+ continue
313
+ task = OpenMLTaskWrapper.from_task_id(task_id=task_id)
314
+ task_type = task.problem_type
315
+ if task_type not in task_types:
316
+ continue
317
+ q = task.task.get_dataset().qualities
318
+ info = {"i_dataset": i_dataset, "task_id": task_id, "task_type": task_type,
319
+ "n_samples": q["NumberOfInstances"], "n_features": q["NumberOfFeatures"],
320
+ "n_classes": q["NumberOfClasses"]}
321
+ if lite:
322
+ n_repeats, n_folds = 1, 1
323
+ else:
324
+ n_repeats, n_folds, _ = task.get_split_dimensions()
325
+ if info["n_samples"] >= 2500:
326
+ n_repeats = min(n_repeats, 3)
327
+ for repeat in range(n_repeats):
328
+ for fold in range(n_folds):
329
+ if (model_name, task_id, repeat, fold) in done:
330
+ continue
331
+ label = f"task {i_dataset} ({task_id}), repeat {repeat}, fold {fold}"
332
+ print(f"====== {label} ======", flush=True)
333
+ X_train, y_train, X_test, y_test = task.get_train_test_split(repeat=repeat,
334
+ fold=fold)
335
+ row = run_split(ctx, split_timeout, label, model_name, model_kwargs, X_train,
336
+ y_train, X_test, y_test, task_type,
337
+ {**info, "repeat": repeat, "fold": fold,
338
+ "n_train": len(X_train), "n_test": len(X_test)}, warmup=warmup)
339
+ if row is not None:
340
+ _merge_rows([row], output)
341
+ done.add((model_name, task_id, repeat, fold))
342
+ print(f"Results in {output} ({time.perf_counter() - t0:.0f}s).", flush=True)
343
+
344
+
345
+ def main(argv=None):
346
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
347
+ sub = ap.add_subparsers(dest="cmd", required=True)
348
+ sub.add_parser("prefetch", help="download the suite into the OpenML cache")
349
+ run = sub.add_parser("run", help="evaluate FirePFN (resumes from --output)")
350
+ run.add_argument("--output", required=True, type=Path, help="result CSV")
351
+ run.add_argument("--name", default="FirePFN", help="model name in the CSV")
352
+ run.add_argument("--model-path", default=None, help="checkpoint (default: released weights)")
353
+ run.add_argument("--n-estimators", type=int, default=2)
354
+ run.add_argument("--set", action="append", default=[], metavar="KEY=JSON",
355
+ help="further FirePFNClassifier arguments, e.g. --set max_features=100")
356
+ run.add_argument("--lite", action="store_true", help="TabArena-Lite: repeat 0, fold 0 only")
357
+ run.add_argument("--tasks", type=int, nargs="+", default=None,
358
+ help="only these task positions in the suite (0-based)")
359
+ run.add_argument("--task-types", nargs="+", default=["binary", "multiclass"],
360
+ choices=["binary", "multiclass"])
361
+ run.add_argument("--split-timeout", type=int, default=1800, help="seconds per split")
362
+ run.add_argument("--no-warmup", action="store_true")
363
+ run.add_argument("--target-encode-min-levels", type=int, default=500,
364
+ help="target-encode categoricals with more levels than this (date-like kept)")
365
+ run.add_argument("--no-target-encode", action="store_true",
366
+ help="ordinal-encode every categorical (protocol of the shipped results)")
367
+ run.add_argument("--no-id-guard", action="store_true",
368
+ help="also target-encode entity-ID-like columns")
369
+ args = ap.parse_args(argv)
370
+
371
+ if args.cmd == "prefetch":
372
+ prefetch()
373
+ return
374
+ kwargs = {"model_path": args.model_path, "n_estimators": args.n_estimators,
375
+ "target_encode_min_levels": (None if args.no_target_encode
376
+ else args.target_encode_min_levels),
377
+ "id_guard": not args.no_id_guard}
378
+ for kv in args.set:
379
+ k, _, v = kv.partition("=")
380
+ kwargs[k] = json.loads(v)
381
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
382
+ evaluate(args.output, model_name=args.name, model_kwargs=kwargs, lite=args.lite,
383
+ task_indices=args.tasks, task_types=tuple(args.task_types),
384
+ split_timeout=args.split_timeout, warmup=not args.no_warmup)
385
+
386
+
387
+ if __name__ == "__main__":
388
+ main()