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,294 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Leaderboard, tables and plots from result CSVs (one row per model and split).
4
+
5
+ Benchmarks (``benchmark``; TabArena, TALENT, BeyondArena, RamanBench -- same protocol for all):
6
+ every result CSV given is loaded (later files win on duplicate (model, split) rows); a split is
7
+ one (task, repeat, fold). A model without a valid ROC AUC /
8
+ TabArena error on a split (crash, timeout, class limit) gets the reference model's
9
+ (RandomForest's) scores for that split -- the usual convention of TabArena-style leaderboards --
10
+ and the imputation counts are reported. Runtimes are compared only on the tasks every model ran
11
+ itself. The leaderboard (improvability, Elo, win rate, mean rank, with bootstrap intervals) is
12
+ computed by TabArena's own ``bencheval`` package; runtimes follow tabarena.ai: median over tasks
13
+ of the train time per 1K training rows and of the inference time per 1K test rows. Outputs:
14
+ leaderboard (CSV + LaTeX), imputation report, per-task coverage and the plots.
15
+
16
+ Runtime (``runtime``): the time / memory scaling grid from the runtime CSVs.
17
+
18
+ python -m firepfn.eval.analysis benchmark --results results/tabarena/*.csv --out out/tabarena
19
+ python -m firepfn.eval.analysis benchmark --results results/talent/*.csv --out out/talent
20
+ python -m firepfn.eval.analysis runtime --results results/runtime/*.csv --out out/runtime
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+
30
+ SPLIT_KEY = ["task_id", "repeat", "fold"]
31
+ # Valid on every kept split: ROC AUC and TabArena's error (1 - AUC binary, log loss multiclass).
32
+ METRIC = ["roc_auc", "error"]
33
+ SCORE_COLS = ["accuracy", "roc_auc", "log_loss", "error"]
34
+ # As on tabarena.ai: fit time per 1K training rows and predict time per 1K test rows.
35
+ TIME_COLS = ["time_train_s_per_1K", "time_infer_s_per_1K"]
36
+ RUN_COLS = ["n_estimators", "hardware", "metric"]
37
+
38
+
39
+ # ---------------------------------------------------------------------------------------------- #
40
+ # Loading
41
+ # ---------------------------------------------------------------------------------------------- #
42
+
43
+ def load_results(files) -> pd.DataFrame:
44
+ """Concatenate result CSVs and add the per-1K times of tabarena.ai: fit time per 1K training
45
+ rows (n_train) and predict time per 1K test rows (n_test). Without n_train / n_test columns
46
+ all rows of the task count (a warning is printed)."""
47
+ df = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
48
+ if not {"n_train", "n_test"} <= set(df.columns) or df[["n_train", "n_test"]].isna().any().any():
49
+ print("WARNING: n_train / n_test missing in the results; per-1K times use n_samples.")
50
+ n_train = n_test = df["n_samples"]
51
+ else:
52
+ n_train, n_test = df["n_train"], df["n_test"]
53
+ df["time_train_s_per_1K"] = df["fit_time"] * 1000 / n_train
54
+ df["time_infer_s_per_1K"] = df["pred_time"] * 1000 / n_test
55
+ return df.drop(columns=["fit_time", "pred_time"])
56
+
57
+
58
+ def add_error_column(df: pd.DataFrame) -> pd.DataFrame:
59
+ """TabArena's per-split error: 1 - ROC AUC (binary), log loss (multiclass)."""
60
+ df = df.copy()
61
+ err = pd.Series(np.nan, index=df.index)
62
+ binary, multiclass = df["task_type"] == "binary", df["task_type"] == "multiclass"
63
+ err[binary] = 1 - df.loc[binary, "roc_auc"]
64
+ if "log_loss" in df.columns:
65
+ err[multiclass] = df.loc[multiclass, "log_loss"]
66
+ df["error"] = err
67
+ return df
68
+
69
+
70
+ def aggregate_results(df: pd.DataFrame) -> pd.DataFrame:
71
+ """Mean over folds, then mean (and std) over repeats, per task and model."""
72
+ info = ["i_dataset", "task_id", "task_type", "n_samples", "n_features", "n_classes"]
73
+ cols = ["accuracy", "roc_auc", *TIME_COLS]
74
+ per_repeat = df.groupby(info + ["repeat", "model"])[cols].mean().reset_index()
75
+ g = per_repeat.groupby(info + ["model"])[cols]
76
+ return g.mean().join(g.std().add_prefix("std_")).reset_index()
77
+
78
+
79
+ # ---------------------------------------------------------------------------------------------- #
80
+ # Missing splits
81
+ # ---------------------------------------------------------------------------------------------- #
82
+
83
+ def impute_missing_splits(df, reference="RandomForest", metric=METRIC, verbose=True):
84
+ """Fill every (split, model) without a valid `metric` with the reference model's scores
85
+ (score columns copied as a whole; runtimes NaN). Splits where the reference itself has no
86
+ valid value are dropped for all models.
87
+
88
+ Returns (df with one row per (split, model) and an `imputed` column, per-model report)."""
89
+ metrics = [metric] if isinstance(metric, str) else list(metric)
90
+ if reference not in set(df["model"]):
91
+ raise ValueError(f"reference model {reference!r} not in the results")
92
+ df = df.drop_duplicates(SPLIT_KEY + ["model"], keep="last").copy()
93
+ df["imputed"] = False
94
+ time_cols = [c for c in TIME_COLS if c in df.columns]
95
+ run_cols = [c for c in RUN_COLS if c in df.columns]
96
+
97
+ all_splits = df.set_index(SPLIT_KEY).index.unique()
98
+ ref = df[df["model"] == reference].set_index(SPLIT_KEY)
99
+ ref_ok = ref[ref[metrics].notna().all(axis=1)]
100
+ no_ref = all_splits.difference(ref_ok.index)
101
+ df = df[~df.set_index(SPLIT_KEY).index.isin(no_ref)]
102
+ target = ref_ok.index
103
+
104
+ parts, rows = [], []
105
+ for m in sorted(df["model"].unique()):
106
+ dm = df[df["model"] == m].set_index(SPLIT_KEY)
107
+ valid = dm[dm[metrics].notna().all(axis=1)].index
108
+ need = target.difference(valid)
109
+ new = ref_ok.loc[need].copy()
110
+ new["model"] = m
111
+ new[time_cols] = np.nan
112
+ for c in run_cols:
113
+ new[c] = None if c == "hardware" else np.nan
114
+ new["imputed"] = True
115
+ parts += [dm.loc[valid].reset_index(), new.reset_index()]
116
+ need_tasks = need.get_level_values("task_id").unique()
117
+ rows.append({
118
+ "model": m, "imputed_splits": len(need),
119
+ "missing_row": len(need.difference(dm.index)),
120
+ "invalid_metric": len(need.intersection(dm.index)), "splits": len(target),
121
+ "imputed_pct": 100 * len(need) / len(target) if len(target) else 0.0,
122
+ "tasks_affected": len(need_tasks),
123
+ "tasks_fully_imputed": int(sum(
124
+ (need.get_level_values("task_id") == t).sum()
125
+ == (target.get_level_values("task_id") == t).sum() for t in need_tasks))})
126
+ out = pd.concat(parts, ignore_index=True)
127
+ out = out[[c for c in df.columns if c in out.columns]]
128
+ report = pd.DataFrame(rows).sort_values(["imputed_splits", "model"], ascending=[False, True])
129
+
130
+ if verbose:
131
+ print(f"Imputation with {reference} on {metrics}: {len(target)}/{len(all_splits)} splits "
132
+ f"({target.get_level_values('task_id').nunique()} tasks).")
133
+ if len(no_ref):
134
+ print(f" {len(no_ref)} split(s) dropped for all models ({reference} has no valid "
135
+ "value there).")
136
+ for r in report[report["imputed_splits"] > 0].itertuples():
137
+ print(f" {r.model:30s} {r.imputed_splits:5d} imputed splits ({r.imputed_pct:.1f}%), "
138
+ f"{r.tasks_affected} tasks")
139
+ return out, report
140
+
141
+
142
+ def restrict_runtime_to_common_tasks(df, verbose=True):
143
+ """Runtimes -> NaN outside the tasks every model ran itself (no imputed split for any model),
144
+ so all runtime aggregates cover the same tasks. Scores are untouched."""
145
+ tasks = df["task_id"].unique()
146
+ has_imputed = set(df.loc[df["imputed"], "task_id"].unique())
147
+ common = [t for t in tasks if t not in has_imputed]
148
+ out = df.copy()
149
+ out.loc[~out["task_id"].isin(common), [c for c in TIME_COLS if c in out.columns]] = np.nan
150
+ if verbose:
151
+ print(f"Runtimes over the {len(common)}/{len(tasks)} tasks every model ran itself.")
152
+ return out, common
153
+
154
+
155
+ def drop_mostly_imputed(df, report, max_pct):
156
+ too_many = report.loc[report["imputed_pct"] > max_pct, "model"].tolist()
157
+ if too_many:
158
+ print(f"Dropped (> {max_pct:g}% of splits imputed): {', '.join(too_many)}")
159
+ return df[~df["model"].isin(too_many)], report[~report["model"].isin(too_many)]
160
+
161
+
162
+ def split_coverage(df_all, df_kept) -> pd.DataFrame:
163
+ """Per task: splits in the results vs. splits kept."""
164
+ info = [c for c in ["i_dataset", "task_type", "n_samples", "n_features", "n_classes"]
165
+ if c in df_all.columns]
166
+ total = df_all.drop_duplicates(SPLIT_KEY).groupby("task_id").size().rename("splits_total")
167
+ kept = df_kept.drop_duplicates(SPLIT_KEY).groupby("task_id").size().rename("splits_kept")
168
+ rep = (df_all.drop_duplicates("task_id").set_index("task_id")[info]
169
+ .join(kept, how="inner").join(total))
170
+ rep["fraction_kept"] = rep["splits_kept"] / rep["splits_total"]
171
+ return rep.sort_values(["fraction_kept"]).reset_index()
172
+
173
+
174
+ # ---------------------------------------------------------------------------------------------- #
175
+ # Leaderboard
176
+ # ---------------------------------------------------------------------------------------------- #
177
+
178
+ def improvability_leaderboard(df, reference="RandomForest", bootstrap_seed=0) -> pd.DataFrame:
179
+ """TabArena leaderboard from TabArena's ``bencheval`` package: improvability (per (model,
180
+ task) mean error over splits; 1 - best_error / error, averaged over tasks, in %), Elo
181
+ (calibrated to 1000 for `reference`), win rate and mean rank, with 95% bootstrap intervals
182
+ (``elo+/-``, ``improvability+/-``), plus the mean ROC AUC and the mean / median over tasks of
183
+ the train time per 1K training rows and the inference time per 1K test rows. Runtimes are
184
+ aggregated here, exactly as bencheval does (mean over splits per task, then mean / median over
185
+ tasks), because they are missing (NaN) on imputed splits and bencheval requires dense columns."""
186
+ try:
187
+ from bencheval.tabarena import TabArena
188
+ except ImportError as e: # pragma: no cover
189
+ raise ImportError("the leaderboard needs bencheval: pip install \"bencheval @ git+https://"
190
+ "github.com/autogluon/tabarena.git@1a394bd1d4e656c2834ac0b3c4cf0db9ed105400"
191
+ "#subdirectory=bencheval\"") from e
192
+ time_cols = [c for c in TIME_COLS if c in df.columns]
193
+ d = df.rename(columns={"model": "method", "task_id": "task", "error": "metric_error"})
194
+ d = d.assign(seed=d["repeat"].astype(str) + "_" + d["fold"].astype(str))
195
+ d = d[["method", "task", "seed", "metric_error"]]
196
+ bench = TabArena(method_col="method", task_col="task", error_col="metric_error",
197
+ columns_to_agg_extra=[], seed_column="seed")
198
+ np.random.seed(bootstrap_seed) # the bootstrap intervals
199
+ lb = bench.leaderboard(d, average_seeds=True, include_elo=True, include_winrate=True,
200
+ include_improvability=True,
201
+ elo_kwargs={"calibration_framework": reference, "calibration_elo": 1000})
202
+ keep = ["elo", "elo+", "elo-", "rank", "winrate", "improvability", "improvability+",
203
+ "improvability-"]
204
+ board = lb[[c for c in keep if c in lb.columns]].copy()
205
+ for c in ("improvability", "improvability+", "improvability-"):
206
+ board[c] *= 100
207
+ board = board.rename(columns={"rank": "mean_rank"})
208
+ per_task = df.groupby(["task_id", "model"])[["roc_auc", *time_cols]].mean().reset_index()
209
+ g = per_task.groupby("model")
210
+ extra = pd.concat([g.agg(mean_roc_auc=("roc_auc", "mean"), n_tasks=("task_id", "nunique")),
211
+ g[time_cols].mean(), g[time_cols].median().add_prefix("median_")], axis=1)
212
+ board = board.join(extra)
213
+ board.index.name = "model"
214
+ return board.sort_values("improvability").reset_index()
215
+
216
+
217
+ def leaderboard_latex(board: pd.DataFrame) -> str:
218
+ cols = {"model": "Method", "elo": "Elo $\\uparrow$",
219
+ "improvability": "Improvability (\\%) $\\downarrow$",
220
+ "mean_roc_auc": "ROC AUC $\\uparrow$",
221
+ "median_time_train_s_per_1K": "Train time (s / 1K) $\\downarrow$",
222
+ "median_time_infer_s_per_1K": "Predict time (s / 1K) $\\downarrow$",
223
+ "imputed_pct": "Imputed (\\%)"}
224
+ t = board[[c for c in cols if c in board.columns]].rename(columns=cols)
225
+ return t.to_latex(index=False, float_format=lambda v: f"{v:.3g}", escape=False)
226
+
227
+
228
+ # ---------------------------------------------------------------------------------------------- #
229
+ # CLI
230
+ # ---------------------------------------------------------------------------------------------- #
231
+
232
+ def run_benchmark(files, out: Path, reference="RandomForest", max_imputed_pct=None,
233
+ exclude=(), runtime_tasks="common"):
234
+ from firepfn.eval import plots
235
+
236
+ raw = load_results(files)
237
+ raw = raw[~raw["model"].isin(exclude)]
238
+ raw = add_error_column(raw)
239
+ imp, report = impute_missing_splits(raw, reference, METRIC)
240
+ if max_imputed_pct is not None:
241
+ imp, report = drop_mostly_imputed(imp, report, max_imputed_pct)
242
+ if runtime_tasks == "common":
243
+ imp, _ = restrict_runtime_to_common_tasks(imp)
244
+ agg = aggregate_results(imp)
245
+
246
+ out.mkdir(parents=True, exist_ok=True)
247
+ report.to_csv(out / "imputation_report.csv", index=False)
248
+ split_coverage(raw, imp).to_csv(out / "split_coverage.csv", index=False)
249
+ board = improvability_leaderboard(imp, reference)
250
+ board = board.merge(report[["model", "imputed_splits", "imputed_pct"]], on="model", how="left")
251
+ board.to_csv(out / "leaderboard.csv", index=False)
252
+ (out / "leaderboard.tex").write_text(leaderboard_latex(board))
253
+ with pd.option_context("display.width", 200):
254
+ print(board.to_string(index=False, float_format=lambda v: f"{v:.4g}"))
255
+
256
+ plots.performance_bars(agg, "roc_auc", out)
257
+ for c in TIME_COLS:
258
+ plots.performance_bars(agg, c, out)
259
+ plots.per_dataset_bars(agg, "roc_auc", out)
260
+ for c in TIME_COLS:
261
+ plots.pareto_front(agg, "roc_auc", c, out)
262
+ for c in TIME_COLS:
263
+ plots.improvability_vs_time(board, c, out)
264
+ print(f"Outputs in {out}/")
265
+
266
+
267
+ def main(argv=None):
268
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
269
+ sub = ap.add_subparsers(dest="cmd", required=True)
270
+ ta = sub.add_parser("benchmark", aliases=["tabarena"],
271
+ help="leaderboard, tables and plots of one benchmark")
272
+ ta.add_argument("--results", nargs="+", required=True, type=Path,
273
+ help="result CSVs (later files win on duplicate rows)")
274
+ ta.add_argument("--out", required=True, type=Path)
275
+ ta.add_argument("--reference", default="RandomForest", help="model that fills missing splits")
276
+ ta.add_argument("--exclude", nargs="*", default=[], help="models to leave out")
277
+ ta.add_argument("--max-imputed-pct", type=float, default=None,
278
+ help="leave out models with more imputed splits than this (%%)")
279
+ ta.add_argument("--runtime-tasks", choices=["common", "own"], default="common")
280
+ rt = sub.add_parser("runtime", help="time / memory scaling plots")
281
+ rt.add_argument("--results", nargs="+", required=True, type=Path)
282
+ rt.add_argument("--out", required=True, type=Path)
283
+ args = ap.parse_args(argv)
284
+
285
+ if args.cmd in ("benchmark", "tabarena"):
286
+ run_benchmark(args.results, args.out, args.reference, args.max_imputed_pct, args.exclude,
287
+ args.runtime_tasks)
288
+ else:
289
+ from firepfn.eval import plots
290
+ plots.runtime_scaling(args.results, args.out)
291
+
292
+
293
+ if __name__ == "__main__":
294
+ main()
firepfn/eval/plots.py ADDED
@@ -0,0 +1,330 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Plots of the paper: TabArena performance / runtime / improvability, runtime scaling grid."""
4
+ from __future__ import annotations
5
+
6
+ from pathlib import Path
7
+
8
+ import matplotlib
9
+
10
+ matplotlib.use("Agg")
11
+ import matplotlib.colors as mcolors # noqa: E402
12
+ import matplotlib.pyplot as plt # noqa: E402
13
+ import numpy as np # noqa: E402
14
+ import pandas as pd # noqa: E402
15
+ from matplotlib import colormaps # noqa: E402
16
+ from matplotlib.ticker import FixedLocator, FuncFormatter, NullLocator # noqa: E402
17
+
18
+ SURFACE, INK, INK2, GRID = "#fcfcfb", "#0b0b0b", "#52514e", "#e4e3df"
19
+ GRAY_DARK, GRAY_MID, GRAY_LIGHT = "#6f6d68", "#9a9893", "#b9b7b1"
20
+ ALPHA = 0.7
21
+
22
+ # Result-CSV model name -> (display name, color, marker, line style, group); group "fm" =
23
+ # foundation models, "sub" = methods that subsample the context, "cpu" = CPU tree models.
24
+ STYLE = {
25
+ "FirePFN": ("FirePFN (ours)", "#2a78d6", "o", "-", "fm"),
26
+ "TabPFN3_5_Fast": ("TabPFN 3.5 Fast", "#eb6834", "s", "-", "fm"),
27
+ "TabICLv2": ("TabICLv2", "#1baf7a", "^", "-", "fm"),
28
+ "Inpriora": ("Inpriora", "#eda100", "D", "-", "fm"),
29
+ "TabDPT1_3": ("TabDPT 1.3", "#e87ba4", "v", "-", "fm"),
30
+ "KumoTabularSmall": ("Kumo-Tabular Small", "#008300", "P", "-", "fm"),
31
+ "TabPFNv2_5": ("TabPFNv2.5", "#6250d6", "X", "-", "fm"),
32
+ "TabICLv1": ("TabICLv1", "#8fd0b6", "<", "-", "fm"),
33
+ "SeldonMini": ("Seldon-Mini", GRAY_DARK, "h", "--", "sub"),
34
+ "LightPFN1_5": ("LightPFN 1.5", GRAY_MID, "p", "--", "sub"),
35
+ "CatBoost": ("CatBoost", GRAY_DARK, "<", ":", "cpu"),
36
+ "XGBoost": ("XGBoost", GRAY_MID, ">", ":", "cpu"),
37
+ "RandomForest": ("RandomForest", GRAY_LIGHT, "*", ":", "cpu"),
38
+ }
39
+ SUBSAMPLE_NOTE = {"SeldonMini": " (subsamples to 200k)", "LightPFN1_5": " (subsamples to 20k)"}
40
+ CPU_NOTE = " (CPU)"
41
+
42
+
43
+ def display_name(model: str) -> str:
44
+ return STYLE[model][0] if model in STYLE else model
45
+
46
+
47
+ class _Palette(dict):
48
+ """Display name -> color; unknown methods get tab10/tab20 colors, stable once assigned."""
49
+
50
+ def __init__(self):
51
+ super().__init__({s[0]: s[1] for s in STYLE.values()})
52
+ used = {mcolors.to_hex(c) for c in self.values()}
53
+ cands = list(colormaps["tab10"].colors) + list(colormaps["tab20"].colors)
54
+ self._free = [c for c in dict.fromkeys(mcolors.to_hex(c) for c in cands) if c not in used]
55
+ self._next = 0
56
+
57
+ def __missing__(self, key):
58
+ self[key] = self._free[self._next % len(self._free)]
59
+ self._next += 1
60
+ return self[key]
61
+
62
+
63
+ PALETTE = _Palette()
64
+
65
+
66
+ def _named(df):
67
+ df = df.copy()
68
+ df["model"] = df["model"].map(display_name)
69
+ return df
70
+
71
+
72
+ def _save(fig, out: Path, name: str):
73
+ out.mkdir(parents=True, exist_ok=True)
74
+ for ext in ("png", "pdf"):
75
+ fig.savefig(out / f"{name}.{ext}", dpi=300, bbox_inches="tight", facecolor=SURFACE)
76
+ plt.close(fig)
77
+ print(f"Figure saved to {out / name}.png")
78
+
79
+
80
+ def _style_axes(ax):
81
+ ax.set_facecolor(SURFACE)
82
+ ax.grid(True, which="major", color=GRID, lw=0.6, zorder=0)
83
+ for s in ("top", "right"):
84
+ ax.spines[s].set_visible(False)
85
+
86
+
87
+ # ---------------------------------------------------------------------------------------------- #
88
+ # TabArena
89
+ # ---------------------------------------------------------------------------------------------- #
90
+
91
+ def performance_bars(agg: pd.DataFrame, metric: str, out: Path):
92
+ """Mean over tasks of `metric` per method, error bar = mean std over repeats."""
93
+ d = _named(agg).groupby("model")[[metric, f"std_{metric}"]].mean().reset_index()
94
+ is_time = metric.startswith("time_")
95
+ d = d.sort_values(metric, ascending=not is_time) # best method on the right
96
+ fig, ax = plt.subplots(figsize=(1.2 * len(d) + 1, 4), facecolor=SURFACE)
97
+ colors = [PALETTE[m] for m in d["model"]]
98
+ x = np.arange(len(d))
99
+ ax.bar(x, d[metric], width=0.55, color=colors, alpha=ALPHA, zorder=2)
100
+ ax.errorbar(x, d[metric], yerr=d[f"std_{metric}"], fmt="none", ecolor=colors, elinewidth=4,
101
+ capsize=0, zorder=3)
102
+ ax.set_xticks(x, d["model"], rotation=30, ha="right")
103
+ if is_time:
104
+ ax.set_yscale("log")
105
+ else:
106
+ ax.set_ylim(bottom=d[metric].min() - 0.01)
107
+ ax.set_ylabel(metric)
108
+ _style_axes(ax)
109
+ _save(fig, out, f"perf_{metric}")
110
+
111
+
112
+ def per_dataset_bars(agg: pd.DataFrame, metric: str, out: Path):
113
+ """`metric` per task (x: task position in the suite) and method."""
114
+ d = _named(agg)
115
+ models = sorted(d["model"].unique())
116
+ tasks = sorted(d["i_dataset"].unique())
117
+ w = 0.8 / len(models)
118
+ fig, ax = plt.subplots(figsize=(max(8, len(tasks) // 2), 4), facecolor=SURFACE)
119
+ for k, m in enumerate(models):
120
+ s = d[d["model"] == m].set_index("i_dataset")[metric].reindex(tasks)
121
+ ax.bar(np.arange(len(tasks)) + (k - (len(models) - 1) / 2) * w, s, width=w,
122
+ color=PALETTE[m], alpha=ALPHA, label=m, zorder=2)
123
+ ax.set_xticks(np.arange(len(tasks)), tasks)
124
+ ax.set_xlabel("task (position in the suite)")
125
+ ax.set_ylabel(metric)
126
+ if not metric.startswith("time_"):
127
+ ax.set_ylim(bottom=d[metric].min() - 0.01)
128
+ ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.15), ncol=min(len(models), 7),
129
+ frameon=False, fontsize=8)
130
+ _style_axes(ax)
131
+ _save(fig, out, f"perf_datasets_{metric}")
132
+
133
+
134
+ def _pareto(x, y, maximize_y):
135
+ """Points not dominated (lower x better; higher y better if maximize_y, else lower)."""
136
+ x, y = np.asarray(x), np.asarray(y) * (-1 if maximize_y else 1)
137
+ keep = np.ones(len(x), dtype=bool)
138
+ for i in range(len(x)):
139
+ keep[i] = not ((x <= x[i]) & (y <= y[i]) & ((x < x[i]) | (y < y[i]))).any()
140
+ return keep
141
+
142
+
143
+ def _front_plot(data, x_col, y_col, maximize_y, ax, step):
144
+ x, y = data[x_col].to_numpy(), data[y_col].to_numpy()
145
+ front = data[_pareto(x, y, maximize_y)].sort_values(x_col)
146
+ fx, fy = front[x_col].to_numpy(), front[y_col].to_numpy()
147
+ if step:
148
+ ax.step(np.append(fx, x.max() * 3), np.append(fy, fy[-1]), where="post",
149
+ color="mediumseagreen", lw=3, alpha=ALPHA / 2, zorder=1)
150
+ else:
151
+ ax.plot(fx, fy, color="mediumseagreen", lw=3, alpha=ALPHA / 2, zorder=1)
152
+ ax.scatter(fx, fy, s=140, facecolors="none", edgecolors="mediumseagreen", linewidths=2.5,
153
+ alpha=ALPHA, zorder=2)
154
+ texts = []
155
+ for _, r in data.iterrows():
156
+ c = PALETTE[r["model"]]
157
+ ax.scatter(r[x_col], r[y_col], s=60, color=c, zorder=3)
158
+ texts.append(ax.text(r[x_col] * 1.08, r[y_col], r["model"], fontsize=7, color=c,
159
+ va="center"))
160
+ ax.set_xscale("log")
161
+ ax.set_xlim(x.min() / 2, x.max() * 3)
162
+ try: # optional: move overlapping labels apart
163
+ from adjustText import adjust_text
164
+ adjust_text(texts, x=x, y=y, ax=ax, expand=(1.05, 1.3),
165
+ arrowprops=dict(arrowstyle="-", color="gray", lw=0.5))
166
+ except ImportError:
167
+ pass
168
+
169
+
170
+ TIME_LABELS = {
171
+ "time_train_s_per_1K": "train time per 1K training data points (s)",
172
+ "time_infer_s_per_1K": "inference time per 1K test data points (s)",
173
+ }
174
+
175
+
176
+ def pareto_front(agg: pd.DataFrame, perf: str, time_col: str, out: Path):
177
+ """Mean `perf` vs. mean `time_col` over tasks, with the Pareto front."""
178
+ d = _named(agg).groupby("model")[[perf, time_col]].mean().reset_index().dropna()
179
+ fig, ax = plt.subplots(figsize=(6, 6), facecolor=SURFACE)
180
+ _front_plot(d, time_col, perf, True, ax, step=False)
181
+ ax.set_xlabel(f"{TIME_LABELS.get(time_col, time_col)} (mean)")
182
+ ax.set_ylabel(f"{perf} (mean)")
183
+ _style_axes(ax)
184
+ _save(fig, out, f"pareto_{time_col}_{perf}")
185
+
186
+
187
+ def improvability_vs_time(board: pd.DataFrame, time_col: str, out: Path):
188
+ """Improvability vs. median runtime (as on the TabArena leaderboard), step Pareto front."""
189
+ x_col = f"median_{time_col}"
190
+ d = _named(board).dropna(subset=[x_col, "improvability"]).sort_values(x_col)
191
+ fig, ax = plt.subplots(figsize=(7, 5.25), facecolor=SURFACE)
192
+ _front_plot(d, x_col, "improvability", False, ax, step=True)
193
+ ax.set_ylim(bottom=min(0, d["improvability"].min()) - 0.5)
194
+ ax.set_xlabel(f"{TIME_LABELS.get(time_col, time_col)} (median)")
195
+ ax.set_ylabel("improvability (%) [lower is better]")
196
+ _style_axes(ax)
197
+ _save(fig, out, f"pareto_improvability_vs_{time_col}")
198
+
199
+
200
+ # ---------------------------------------------------------------------------------------------- #
201
+ # Runtime scaling
202
+ # ---------------------------------------------------------------------------------------------- #
203
+
204
+ B300_GB = 268 # usable device memory reported by torch on the paper's GPU
205
+ TIME_CAP_S = 1800 # a run above this ends a method's sweep
206
+ STOP_LABEL = {"oom": "OOM", "error": "error", "timeout": "time limit", "over_budget": "> 30 min"}
207
+ MEASURED = ("ok", "over_budget") # over_budget rows hold valid timings (last size tried)
208
+
209
+
210
+ def _stop_reason(g):
211
+ last = g.sort_values("n_train").iloc[-1]
212
+ if last["status"] != "ok":
213
+ return STOP_LABEL.get(last["status"], last["status"])
214
+ return "> 30 min" if last["total_time"] > TIME_CAP_S else None
215
+
216
+
217
+ def _fmt_rows(v, _):
218
+ return f"{v / 1e6:g}M" if v >= 1e6 else f"{v / 1e3:g}k" if v >= 1e3 else f"{v:g}"
219
+
220
+
221
+ def _runtime_label(model):
222
+ label, *_, group = STYLE[model]
223
+ return label + SUBSAMPLE_NOTE.get(model, "") + (CPU_NOTE if group == "cpu" else "")
224
+
225
+
226
+ def runtime_scaling(files, out: Path, widths=(20, 200, 500)):
227
+ """2 x len(widths) grid: fit + predict time and peak GPU memory against context rows."""
228
+ d = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
229
+ d = d[d["model"].isin(STYLE)]
230
+ plt.rcParams.update({"font.size": 9, "axes.edgecolor": INK2, "axes.labelcolor": INK2,
231
+ "xtick.color": INK2, "ytick.color": INK2, "text.color": INK})
232
+ fig, axes = plt.subplots(2, len(widths), figsize=(5 * len(widths), 8.6), sharex=True,
233
+ facecolor=SURFACE, squeeze=False)
234
+ placed = {(i, j): [] for i in range(2) for j in range(len(widths))}
235
+ x_max = max(2.4e7, 1.5 * d.loc[d["status"].isin(MEASURED), "n_train"].max())
236
+ if "host_offload" in d and d["host_offload"].eq(True).any():
237
+ x_max *= 2.5 # room for the host-memory label right of the offloaded sizes
238
+ for j, F in enumerate(widths):
239
+ for i, metric in enumerate(["total_time", "peak_gpu_mem_gb"]):
240
+ ax = axes[i, j]
241
+ for model, (_, color, marker, ls, group) in STYLE.items():
242
+ g = d[(d["model"] == model) & (d["n_features"] == F)].sort_values("n_train")
243
+ ok = g[g["status"].isin(MEASURED)]
244
+ if ok.empty or (metric == "peak_gpu_mem_gb" and group == "cpu"):
245
+ continue
246
+ lw, z = (2.4, 5) if model == "FirePFN" else (1.6, 3)
247
+ ax.plot(ok["n_train"], ok[metric], color=color, ls=ls, lw=lw, marker=marker,
248
+ ms=5.5, mec=SURFACE, mew=0.8, zorder=z, label=_runtime_label(model))
249
+ why = _stop_reason(g)
250
+ if why in ("OOM", "error") and group == "fm" and metric == "peak_gpu_mem_gb":
251
+ x, y = ok["n_train"].iloc[-1], ok[metric].iloc[-1]
252
+ dy = 3
253
+ for px, py in placed[(i, j)]:
254
+ if abs(np.log10(px) - np.log10(x)) < 0.35 and abs(py - (y + dy / 3)) < 12:
255
+ dy -= 11
256
+ placed[(i, j)].append((x, y + dy / 3))
257
+ ax.annotate(f"{why} ({STYLE[model][0].split(' (')[0]})", (x, y),
258
+ xytext=(5, dy), textcoords="offset points", fontsize=7, color=INK2,
259
+ zorder=6, bbox=dict(boxstyle="square,pad=0.1", fc=SURFACE,
260
+ ec="none", alpha=0.85))
261
+ if model == "FirePFN" and metric == "peak_gpu_mem_gb":
262
+ drop = ok[metric].values[1:] < 0.6 * ok[metric].values[:-1]
263
+ if drop.any():
264
+ k = int(np.argmax(drop)) + 1
265
+ ax.annotate("switches to\nlow-memory mode",
266
+ (ok["n_train"].iloc[k], ok[metric].iloc[k]), xytext=(10, 105),
267
+ textcoords="offset points", ha="left", fontsize=7, color=color,
268
+ zorder=7, bbox=dict(boxstyle="square,pad=0.15", fc=SURFACE,
269
+ ec="none", alpha=0.9),
270
+ arrowprops=dict(arrowstyle="-", color=color, lw=0.8))
271
+ if "host_offload" in ok and ok["host_offload"].eq(True).any():
272
+ # peak GPU memory excludes the context buffer once it is kept in host RAM
273
+ ax.annotate("context buffer\nin host RAM",
274
+ (ok["n_train"].iloc[-1], ok[metric].iloc[-1]), xytext=(4, 28),
275
+ textcoords="offset points", ha="left", fontsize=7, color=color,
276
+ zorder=7, bbox=dict(boxstyle="square,pad=0.15", fc=SURFACE,
277
+ ec="none", alpha=0.9),
278
+ arrowprops=dict(arrowstyle="-", color=color, lw=0.8))
279
+ ax.set_xscale("log")
280
+ if metric == "total_time":
281
+ ax.set_yscale("log")
282
+ ax.axhline(TIME_CAP_S, color=INK2, lw=0.8, ls=(0, (4, 3)), zorder=1)
283
+ ax.text(1.1e2, TIME_CAP_S * 1.12, "30 min", fontsize=7, color=INK2)
284
+ ax.set_title(f"{F} features", fontsize=11, color=INK, loc="left")
285
+ if j == 0:
286
+ ax.set_ylabel("fit + predict time (s), 1,000 test rows")
287
+ else:
288
+ ax.axhline(B300_GB, color=INK2, lw=0.8, ls=(0, (4, 3)), zorder=1)
289
+ ax.text(1.1e2, B300_GB - 14, "B300 memory (268 GB)", fontsize=7, color=INK2)
290
+ ax.set_ylim(0, 290)
291
+ if j == 0:
292
+ ax.set_ylabel("peak GPU memory (GB)")
293
+ ax.set_xlabel("context (training) rows")
294
+ ax.xaxis.set_major_locator(FixedLocator([10.0 ** k for k in range(2, 10) if 10.0 ** k <= x_max]))
295
+ ax.xaxis.set_major_formatter(FuncFormatter(_fmt_rows))
296
+ ax.xaxis.set_minor_locator(NullLocator())
297
+ ax.set_xlim(80, x_max)
298
+ _style_axes(ax)
299
+ handles, labels = [], []
300
+ for ax in axes[0]:
301
+ for h, lab in zip(*ax.get_legend_handles_labels()):
302
+ if lab not in labels:
303
+ handles.append(h)
304
+ labels.append(lab)
305
+ order = [_runtime_label(m) for m in STYLE if _runtime_label(m) in labels]
306
+ hl = dict(zip(labels, handles))
307
+ fig.legend([hl[lab] for lab in order], order, loc="upper center", ncol=6, frameon=False,
308
+ fontsize=8.5, bbox_to_anchor=(0.5, 1.0))
309
+ fig.text(0.5, 0.005, "Binary classification, 1 estimator, one NVIDIA B300; CPU models: no GPU "
310
+ "memory. A line ends where the next size ran out of memory (OOM), failed, or exceeded "
311
+ "the time budget (> 30 min or the per-run limit).", ha="center", fontsize=7.5,
312
+ color=INK2)
313
+ fig.tight_layout(rect=(0, 0.02, 1, 0.94))
314
+ _save(fig, out, "scaling_time_memory")
315
+
316
+ ok = d[d["status"].isin(MEASURED)]
317
+ ok.pivot_table(index=["n_features", "model"], columns="n_train", values="total_time",
318
+ aggfunc="first").to_csv(out / "scaling_table.csv", float_format="%.3f")
319
+ summ = []
320
+ for (F, model), g in d.groupby(["n_features", "model"]):
321
+ gok = g[g["status"].isin(MEASURED)].sort_values("n_train")
322
+ if gok.empty:
323
+ continue
324
+ summ.append(dict(features=F, method=_runtime_label(model),
325
+ max_rows=int(gok["n_train"].max()),
326
+ stop=_stop_reason(g) or f"reached {_fmt_rows(gok['n_train'].max(), 0)}",
327
+ time_1M_s=gok.set_index("n_train")["total_time"].get(1_000_000),
328
+ peak_mem_at_max_gb=round(float(gok["peak_gpu_mem_gb"].iloc[-1]), 1)))
329
+ pd.DataFrame(summ).to_csv(out / "scaling_summary.csv", index=False, float_format="%.3f")
330
+ print(f"Tables in {out}/")