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,152 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Fused split-half RoPE forward for no-grad inference.
4
+
5
+ kumo._apply_rope in eager mode costs ~8 full passes over q/k (4 muls, sub, add, cat, on strided
6
+ half-tensors): about a fifth of the encoder's GPU time on wide tables. This kernel
7
+ reads x once (any strides, last dim contiguous) and writes the rotated tensor contiguously.
8
+
9
+ Bit-identical to the eager code: PyTorch computes each bf16/fp16 elementwise op in fp32 and rounds
10
+ to the tensor dtype after every op, so the kernel rounds after each mul and after the sub/add too:
11
+ a = rnd(rnd(x1 * c) - rnd(x2 * s)), b = rnd(rnd(x2 * c) + rnd(x1 * s))
12
+ with c, s = cos/sin already cast to x's dtype (as eager). Disable with FIREPFN_FUSED_ROPE=0.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import os
17
+
18
+ import torch
19
+
20
+ try:
21
+ import triton
22
+ import triton.language as tl
23
+ from triton.language.extra import libdevice
24
+ except ImportError: # pragma: no cover
25
+ triton = None
26
+
27
+ _MAX_LEAD = 3
28
+
29
+
30
+ if triton is not None:
31
+ @triton.jit
32
+ def _rope_kernel(X, C, S, Y, M, L, S1, S2,
33
+ st0, st1, st2, stL, HALF: tl.constexpr,
34
+ BLOCK_M: tl.constexpr, BLOCK_H: tl.constexpr):
35
+ pid = tl.program_id(0)
36
+ rows = pid.to(tl.int64) * BLOCK_M + tl.arange(0, BLOCK_M).to(tl.int64)
37
+ rmask = rows < M
38
+ l = rows % L
39
+ t = rows // L
40
+ i2 = t % S2
41
+ t = t // S2
42
+ i1 = t % S1
43
+ i0 = t // S1
44
+ base = i0 * st0 + i1 * st1 + i2 * st2 + l * stL
45
+ cols = tl.arange(0, BLOCK_H)
46
+ cmask = cols < HALF
47
+ mask = rmask[:, None] & cmask[None, :]
48
+ p1 = X + base[:, None] + cols[None, :]
49
+ x1 = tl.load(p1, mask=mask, other=0.0).to(tl.float32)
50
+ x2 = tl.load(p1 + HALF, mask=mask, other=0.0).to(tl.float32)
51
+ tab = l[:, None] * HALF + cols[None, :]
52
+ c = tl.load(C + tab, mask=mask, other=0.0).to(tl.float32)
53
+ s = tl.load(S + tab, mask=mask, other=0.0).to(tl.float32)
54
+ dt = Y.dtype.element_ty
55
+ # mul_rn / sub_rn / add_rn: IEEE ops the compiler may not contract into FMAs (eager rounds
56
+ # every op); explicit round-to-nearest-even downcasts, as c10's float -> bf16/fp16.
57
+ t1 = libdevice.mul_rn(x1, c).to(dt, fp_downcast_rounding="rtne").to(tl.float32)
58
+ t2 = libdevice.mul_rn(x2, s).to(dt, fp_downcast_rounding="rtne").to(tl.float32)
59
+ t3 = libdevice.mul_rn(x2, c).to(dt, fp_downcast_rounding="rtne").to(tl.float32)
60
+ t4 = libdevice.mul_rn(x1, s).to(dt, fp_downcast_rounding="rtne").to(tl.float32)
61
+ out = rows[:, None] * (2 * HALF) + cols[None, :]
62
+ tl.store(Y + out, libdevice.sub_rn(t1, t2).to(dt, fp_downcast_rounding="rtne"), mask=mask)
63
+ tl.store(Y + out + HALF, libdevice.add_rn(t3, t4).to(dt, fp_downcast_rounding="rtne"), mask=mask)
64
+
65
+
66
+ def enabled() -> bool:
67
+ return triton is not None and os.environ.get("FIREPFN_FUSED_ROPE", "1") != "0"
68
+
69
+
70
+ def _lead_dims(shape, strides, max_dims):
71
+ """Coalesce leading dims (sizes, strides) where possible; None if more than max_dims remain."""
72
+ dims = [(s, st) for s, st in zip(shape, strides) if s != 1]
73
+ out = []
74
+ for s, st in dims:
75
+ if out and out[-1][1] == s * st: # previous dim steps exactly over this one
76
+ out[-1] = (out[-1][0] * s, st)
77
+ else:
78
+ out.append((s, st))
79
+ if len(out) > max_dims:
80
+ return None
81
+ while len(out) < max_dims:
82
+ out.insert(0, (1, 0))
83
+ return out
84
+
85
+
86
+ def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
87
+ """x (..., L, d) with cos/sin (>= L, d/2) fp32 tables -> rotated x, or None if the fused kernel
88
+ does not apply (caller falls back to eager)."""
89
+ if (not enabled() or not x.is_cuda or torch.is_grad_enabled() or x.dim() < 2
90
+ or x.dtype not in (torch.bfloat16, torch.float16, torch.float32)
91
+ or x.stride(-1) != 1 or x.shape[-1] % 2 or x.numel() == 0):
92
+ return None
93
+ L, d = x.shape[-2], x.shape[-1]
94
+ lead = _lead_dims(x.shape[:-2], x.stride()[:-2], _MAX_LEAD)
95
+ if lead is None:
96
+ return None
97
+ c = cos[:L].to(x.dtype).contiguous()
98
+ s = sin[:L].to(x.dtype).contiguous()
99
+ y = torch.empty(x.shape, device=x.device, dtype=x.dtype)
100
+ M = x.numel() // d
101
+ half = d // 2
102
+ BLOCK_H = triton.next_power_of_2(half)
103
+ BLOCK_M = max(1, 4096 // BLOCK_H)
104
+ (_, st0), (S1, st1), (S2, st2) = lead
105
+ _rope_kernel[(triton.cdiv(M, BLOCK_M),)](x, c, s, y, M, L, S1, S2, st0, st1, st2, x.stride(-2),
106
+ HALF=half, BLOCK_M=BLOCK_M, BLOCK_H=BLOCK_H)
107
+ return y
108
+
109
+
110
+ # ---------------------------------------------------------------------- #
111
+ # GatedLogScale elementwise tail
112
+ # ---------------------------------------------------------------------- #
113
+ # Eager: out = (q * sc) * (1 + tanh(g)) with sc = head_scale.to(q.dtype).view(H, 1, 1) * log(n):
114
+ # 4 full passes (mul, tanh, add, mul), each rounded to q's dtype. Fused: one pass, same per-op
115
+ # rounding (libdevice tanh = CUDA tanhf, *_rn ops, rtne downcasts). Disable: FIREPFN_FUSED_GATE=0.
116
+
117
+ if triton is not None:
118
+ @triton.jit
119
+ def _gate_kernel(Q, G, SC, Y, N, LD, H, BLOCK: tl.constexpr):
120
+ pid = tl.program_id(0)
121
+ offs = pid.to(tl.int64) * BLOCK + tl.arange(0, BLOCK).to(tl.int64)
122
+ mask = offs < N
123
+ head = (offs // LD) % H
124
+ q = tl.load(Q + offs, mask=mask, other=0.0).to(tl.float32)
125
+ g = tl.load(G + offs, mask=mask, other=0.0).to(tl.float32)
126
+ sc = tl.load(SC + head, mask=mask, other=0.0).to(tl.float32)
127
+ dt = Y.dtype.element_ty
128
+ a = libdevice.mul_rn(q, sc).to(dt, fp_downcast_rounding="rtne").to(tl.float32)
129
+ t = libdevice.tanh(g).to(dt, fp_downcast_rounding="rtne").to(tl.float32)
130
+ u = libdevice.add_rn(t, 1.0).to(dt, fp_downcast_rounding="rtne").to(tl.float32)
131
+ tl.store(Y + offs, libdevice.mul_rn(a, u).to(dt, fp_downcast_rounding="rtne"), mask=mask)
132
+
133
+
134
+ def gate_enabled() -> bool:
135
+ return triton is not None and os.environ.get("FIREPFN_FUSED_GATE", "1") != "0"
136
+
137
+
138
+ def gated_log_scale(q: torch.Tensor, sc: torch.Tensor, g: torch.Tensor):
139
+ """q (..., H, L, d), sc (H, 1, 1) in q's dtype, g = gate(q) like q -> (q * sc) * (1 + tanh(g)),
140
+ or None if the fused kernel does not apply."""
141
+ if (not gate_enabled() or not q.is_cuda or torch.is_grad_enabled() or q.dim() < 3
142
+ or q.dtype not in (torch.bfloat16, torch.float16, torch.float32)
143
+ or g.dtype != q.dtype or g.shape != q.shape or sc.dtype != q.dtype
144
+ or not (q.is_contiguous() and g.is_contiguous()) or sc.numel() != q.shape[-3]
145
+ or q.numel() == 0):
146
+ return None
147
+ H, L, d = q.shape[-3], q.shape[-2], q.shape[-1]
148
+ y = torch.empty_like(q)
149
+ N = q.numel()
150
+ BLOCK = 1024
151
+ _gate_kernel[(triton.cdiv(N, BLOCK),)](q, g, sc.contiguous().view(-1), y, N, L * d, H, BLOCK=BLOCK)
152
+ return y
@@ -0,0 +1,301 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Input preprocessing (scikit-learn transformers), fit on the training rows:
4
+
5
+ 1. feature selection -- cap the table at max_features columns (FirePFN: 200, f_classif_sub)
6
+ 2. DataNormalizer -- standardize with training mean/std, clip to +-100
7
+ 3. ConstantFeatureRemover -- drop columns constant in the training rows
8
+ 4. OutlierClipper -- two-pass 4-sigma bounds, log-soft clipping beyond them
9
+ 5. FeatureCountScaler -- divide by n_features / max_features
10
+
11
+ Steps 2, 4 and 5 follow TabPFN v1's input preprocessing. NaNs are passed through; the model
12
+ imputes them itself (column means of the context rows).
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import warnings
17
+
18
+ import numpy as np
19
+ from sklearn.base import BaseEstimator, TransformerMixin
20
+ from sklearn.feature_selection import f_classif
21
+ from sklearn.pipeline import Pipeline
22
+
23
+ FEATURE_SELECTION = ("f_classif", "f_classif_sub", "random", "mutual_info", "extra_trees",
24
+ "extra_trees_fast", "none")
25
+
26
+
27
+ # ---------------------------------------------------------------------------------------------- #
28
+ # Faster, bit-identical numpy
29
+ # Steps 2-4 touch every cell of the table several times (0.3 s for 50k rows x 170 columns). Two
30
+ # changes keep every output bit for bit while cutting that by about a quarter
31
+ # (checked bit for bit against the original research code before release):
32
+ # * the elementwise transforms of steps 2 and 4 run on blocks of about 1 MB, so the chain of
33
+ # temporaries stays in cache (elementwise results do not depend on the blocking; threads were
34
+ # tried and made the whole pipeline slower and noisier);
35
+ # * ConstantFeatureRemover tests min == max per column instead of sorting every column.
36
+ # The fits stay single-pass numpy: their column sums depend on summation order and on the memory
37
+ # layout, so they are not blocked.
38
+ # ---------------------------------------------------------------------------------------------- #
39
+
40
+ _BLOCK_ELEMS = 2 ** 18
41
+
42
+
43
+ def _blockwise(X, fn):
44
+ """float32 array of fn(block, columns) over blocks of X of about _BLOCK_ELEMS cells: row blocks
45
+ of a C-ordered table, column slabs of a Fortran-ordered one (X[:, mask] returns one), so every
46
+ block is a contiguous stretch of memory. ``columns`` is the block's column slice, for per-column
47
+ parameters. fn must be elementwise: the result then does not depend on the blocking."""
48
+ n, f = X.shape
49
+ k = -(-X.size // _BLOCK_ELEMS)
50
+ if k <= 1 or f < 32 or not (X.flags.c_contiguous or X.flags.f_contiguous): # narrow: no gain
51
+ return np.asarray(fn(X, slice(None)), dtype=np.float32)
52
+ out = np.empty(X.shape, dtype=np.float32)
53
+ if X.flags.f_contiguous and not X.flags.c_contiguous:
54
+ w = max(1, f // k)
55
+ for a in range(0, f, w):
56
+ cols = slice(a, min(f, a + w))
57
+ out[:, cols] = fn(X[:, cols], cols)
58
+ else:
59
+ h = max(1, n // k)
60
+ for a in range(0, n, h):
61
+ rows = slice(a, min(n, a + h))
62
+ out[rows] = fn(X[rows], slice(None))
63
+ return out
64
+
65
+
66
+ def _stratified_rows(n_samples, y, max_rows, random_state):
67
+ from sklearn.model_selection import train_test_split
68
+ try:
69
+ idx, _ = train_test_split(np.arange(n_samples), train_size=max_rows, stratify=y,
70
+ random_state=random_state)
71
+ except ValueError:
72
+ idx = np.random.RandomState(random_state).choice(n_samples, max_rows, replace=False)
73
+ return idx
74
+
75
+
76
+ class RandomFeatureSampler(TransformerMixin, BaseEstimator):
77
+ """Random subset of at most max_features columns."""
78
+
79
+ def __init__(self, max_features: int = 200, random_state: int = 0):
80
+ self.max_features = max_features
81
+ self.random_state = random_state
82
+
83
+ def fit(self, X, y=None):
84
+ n_features = np.asarray(X).shape[1]
85
+ if n_features > self.max_features:
86
+ rng = np.random.RandomState(self.random_state)
87
+ self.selected_cols_ = np.sort(rng.choice(n_features, self.max_features, replace=False))
88
+ else:
89
+ self.selected_cols_ = np.arange(n_features)
90
+ return self
91
+
92
+ def transform(self, X):
93
+ return np.asarray(X)[:, self.selected_cols_]
94
+
95
+
96
+ class UnivariateFeatureSelector(TransformerMixin, BaseEstimator):
97
+ """The max_features columns with the highest ANOVA F-score w.r.t. y (as SelectKBest(f_classif)).
98
+
99
+ max_rows: score on at most this many stratified-random rows (None = all rows). NaNs are
100
+ mean-imputed for scoring only; the selected columns are returned unchanged.
101
+ """
102
+
103
+ def __init__(self, max_features: int = 200, max_rows: int | None = None, random_state: int = 0):
104
+ self.max_features = max_features
105
+ self.max_rows = max_rows
106
+ self.random_state = random_state
107
+
108
+ def fit(self, X, y=None):
109
+ n_samples, n_features = np.shape(X)
110
+ if n_features <= self.max_features:
111
+ self.selected_cols_ = np.arange(n_features)
112
+ return self
113
+ if y is None:
114
+ raise ValueError("UnivariateFeatureSelector requires y.")
115
+ if self.max_rows is not None and n_samples > self.max_rows:
116
+ y_arr = np.asarray(y)
117
+ idx = np.sort(_stratified_rows(n_samples, y_arr, self.max_rows, self.random_state))
118
+ X, y = np.asarray(X)[idx], y_arr[idx]
119
+ X = np.asarray(X, dtype=np.float64)
120
+ with warnings.catch_warnings():
121
+ warnings.simplefilter("ignore")
122
+ col_mean = np.nan_to_num(np.nanmean(X, axis=0))
123
+ X = np.where(np.isnan(X), col_mean, X)
124
+ scores, _ = f_classif(X, np.asarray(y))
125
+ scores = np.nan_to_num(scores, nan=-np.inf, posinf=np.finfo(np.float64).max)
126
+ self.selected_cols_ = np.sort(np.argsort(-scores, kind="stable")[:self.max_features])
127
+ return self
128
+
129
+ def transform(self, X):
130
+ return np.asarray(X)[:, self.selected_cols_]
131
+
132
+
133
+ class ScoreFeatureSelector(TransformerMixin, BaseEstimator):
134
+ """The max_features columns with the highest 'mutual_info' (mutual_info_classif) or
135
+ 'extra_trees' (ExtraTreesClassifier impurity importance) score, computed on at most max_rows
136
+ stratified-random rows. NaNs are mean-imputed for scoring only."""
137
+
138
+ def __init__(self, max_features: int = 200, score_func: str = "extra_trees", max_rows: int = 10000,
139
+ random_state: int = 0, n_estimators: int = 200):
140
+ self.max_features = max_features
141
+ self.score_func = score_func
142
+ self.max_rows = max_rows
143
+ self.random_state = random_state
144
+ self.n_estimators = n_estimators
145
+
146
+ def fit(self, X, y=None):
147
+ X = np.asarray(X, dtype=np.float64)
148
+ n_samples, n_features = X.shape
149
+ if n_features <= self.max_features:
150
+ self.selected_cols_ = np.arange(n_features)
151
+ return self
152
+ if y is None:
153
+ raise ValueError("ScoreFeatureSelector requires y.")
154
+ y = np.asarray(y)
155
+ if n_samples > self.max_rows:
156
+ idx = _stratified_rows(n_samples, y, self.max_rows, self.random_state)
157
+ X, y = X[idx], y[idx]
158
+ with warnings.catch_warnings():
159
+ warnings.simplefilter("ignore")
160
+ col_mean = np.nan_to_num(np.nanmean(X, axis=0))
161
+ X = np.where(np.isnan(X), col_mean, X)
162
+ if self.score_func == "mutual_info":
163
+ from sklearn.feature_selection import mutual_info_classif
164
+ scores = mutual_info_classif(X, y, random_state=self.random_state)
165
+ elif self.score_func == "extra_trees":
166
+ from sklearn.ensemble import ExtraTreesClassifier
167
+ et = ExtraTreesClassifier(n_estimators=self.n_estimators, max_features="sqrt", min_samples_leaf=2,
168
+ class_weight="balanced", n_jobs=-1, random_state=self.random_state)
169
+ scores = et.fit(X, y).feature_importances_
170
+ else:
171
+ raise ValueError(f"Unknown score_func: {self.score_func!r}")
172
+ scores = np.nan_to_num(scores, nan=-np.inf)
173
+ self.selected_cols_ = np.sort(np.argsort(-scores, kind="stable")[:self.max_features])
174
+ return self
175
+
176
+ def transform(self, X):
177
+ return np.asarray(X)[:, self.selected_cols_]
178
+
179
+
180
+ class DataNormalizer(TransformerMixin, BaseEstimator):
181
+ """Standardize with the training mean/std, then clip to [-100, 100]."""
182
+
183
+ def fit(self, X, y=None):
184
+ X = np.asarray(X, dtype=np.float32)
185
+ self.mean_ = np.nanmean(X, axis=0)
186
+ self.std_ = np.nanstd(X, axis=0) + 1e-6
187
+ return self
188
+
189
+ def transform(self, X):
190
+ return _blockwise(np.asarray(X, dtype=np.float32), lambda Xb, c: np.clip(
191
+ (Xb - self.mean_[c]) / self.std_[c], -100.0, 100.0))
192
+
193
+
194
+ class ConstantFeatureRemover(TransformerMixin, BaseEstimator):
195
+ """Drop columns that are constant (<= 1 unique value) in the training rows."""
196
+
197
+ def fit(self, X, y=None):
198
+ X = np.asarray(X)
199
+ if X.dtype.kind != "f":
200
+ self.mask_ = np.array([len(np.unique(X[:, col])) > 1 for col in range(X.shape[1])])
201
+ return self
202
+ # Same as len(np.unique(column)) > 1 per column (NaNs count as one value), without sorting
203
+ # every column: constant <=> all non-NaN values equal and no NaN next to them.
204
+ nan = np.isnan(X)
205
+ has_nan, all_nan = nan.any(axis=0), nan.all(axis=0)
206
+ distinct = np.where(all_nan, 0, np.where(np.fmax.reduce(X, axis=0) != np.fmin.reduce(X, axis=0), 2, 1))
207
+ self.mask_ = distinct + has_nan > 1
208
+ return self
209
+
210
+ def transform(self, X):
211
+ return np.asarray(X)[:, self.mask_]
212
+
213
+
214
+ class OutlierClipper(TransformerMixin, BaseEstimator):
215
+ """Soft outlier clipping: bounds mean +- n_sigma * std from a first pass, recomputed on the
216
+ inliers in a second pass; values beyond them are pulled back logarithmically."""
217
+
218
+ def __init__(self, n_sigma: int = 4):
219
+ self.n_sigma = n_sigma
220
+
221
+ def _bounds(self, X):
222
+ mean1 = np.nanmean(X, axis=0)
223
+ std1 = np.nanstd(X, axis=0)
224
+ cut1 = std1 * self.n_sigma
225
+ inlier = (X >= mean1 - cut1) & (X <= mean1 + cut1) & ~np.isnan(X)
226
+ count = inlier.sum(axis=0)
227
+ masked_sum = np.where(inlier, X, 0.0).sum(axis=0)
228
+ mean2 = np.where(count > 0, masked_sum / np.maximum(count, 1), mean1)
229
+ masked_sq = np.where(inlier, (X - mean2) ** 2, 0.0).sum(axis=0)
230
+ std2 = np.sqrt(np.where(count > 0, masked_sq / np.maximum(count, 1), std1 ** 2))
231
+ cut2 = std2 * self.n_sigma
232
+ return mean2 - cut2, mean2 + cut2
233
+
234
+ def fit(self, X, y=None):
235
+ self.lower_, self.upper_ = self._bounds(np.asarray(X, dtype=np.float32))
236
+ return self
237
+
238
+ def transform(self, X):
239
+ # The bounds are float64 (a float32 sum divided by an integer count), so the clipping is
240
+ # computed in float64; the result is rounded to float32 here, exactly as the next step
241
+ # (FeatureCountScaler) did to the float64 output before.
242
+ def clip(Xb, c):
243
+ Z = Xb.copy()
244
+ Z = np.maximum(-np.log1p(np.abs(Z)) + self.lower_[c], Z)
245
+ return np.minimum(np.log1p(np.abs(Z)) + self.upper_[c], Z)
246
+
247
+ return _blockwise(np.asarray(X, dtype=np.float32), clip)
248
+
249
+
250
+ class FeatureCountScaler(TransformerMixin, BaseEstimator):
251
+ """Divide by n_features / max_features (the feature-count normalisation of training)."""
252
+
253
+ def __init__(self, max_features: int = 200):
254
+ self.max_features = max_features
255
+
256
+ def fit(self, X, y=None):
257
+ self.n_features_in_ = np.asarray(X).shape[1]
258
+ return self
259
+
260
+ def transform(self, X):
261
+ return np.asarray(X, dtype=np.float32) / (self.n_features_in_ / self.max_features)
262
+
263
+
264
+ def make_preprocessing_pipeline(max_features: int = 200, feature_selection: str = "f_classif_sub",
265
+ random_state: int = 0) -> Pipeline:
266
+ """Unfitted preprocessing pipeline.
267
+
268
+ feature_selection: how to cap the table at max_features columns --
269
+ 'f_classif' top ANOVA F-scores on all rows
270
+ 'f_classif_sub' the same, scored on <= 20k stratified rows (FirePFN default; faster
271
+ on large tables)
272
+ 'random' random subset
273
+ 'mutual_info' / 'extra_trees' top supervised scores on <= 10k rows
274
+ 'extra_trees_fast' extra_trees with 50 trees on <= 5k rows
275
+ 'none' keep every column (max_features then only sets the scaling reference)
276
+ """
277
+ if feature_selection == "random":
278
+ sampler = RandomFeatureSampler(max_features=max_features, random_state=random_state)
279
+ elif feature_selection == "f_classif":
280
+ sampler = UnivariateFeatureSelector(max_features=max_features)
281
+ elif feature_selection == "f_classif_sub":
282
+ sampler = UnivariateFeatureSelector(max_features=max_features, max_rows=20000, random_state=random_state)
283
+ elif feature_selection in ("mutual_info", "extra_trees"):
284
+ sampler = ScoreFeatureSelector(max_features=max_features, score_func=feature_selection,
285
+ random_state=random_state)
286
+ elif feature_selection == "extra_trees_fast":
287
+ sampler = ScoreFeatureSelector(max_features=max_features, score_func="extra_trees",
288
+ max_rows=5000, n_estimators=50, random_state=random_state)
289
+ elif feature_selection == "none":
290
+ sampler = None
291
+ else:
292
+ raise ValueError(f"Unknown feature_selection {feature_selection!r}; valid: {FEATURE_SELECTION}")
293
+
294
+ steps = [("feature_sampler", sampler)] if sampler is not None else []
295
+ steps += [
296
+ ("normalizer", DataNormalizer()),
297
+ ("constant_remover", ConstantFeatureRemover()),
298
+ ("outlier_clipper", OutlierClipper()),
299
+ ("feature_scaler", FeatureCountScaler(max_features=max_features)),
300
+ ]
301
+ return Pipeline(steps)
@@ -0,0 +1,3 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Training of FirePFN on the TabICLv2 graph_scm prior (needs the `train` extra: pip install FirePFN[train])."""
@@ -0,0 +1,57 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Train FirePFN.
4
+
5
+ # stage 1 (from scratch), 4 GPUs
6
+ torchrun --nproc_per_node=4 -m firepfn.train --config stage1 --out runs/stage1
7
+ # stage 2, 8 GPUs, from the final stage-1 model
8
+ torchrun --nproc_per_node=8 -m firepfn.train --config stage2 --out runs/stage2 \\
9
+ --init runs/stage1/stage1_epoch1000.ckpt
10
+ # two more stage-2 lr cycles, each from the previous cycle's final model (released: cyc3 e250)
11
+ torchrun --nproc_per_node=8 -m firepfn.train --config stage2_cyc2 --out runs/stage2_cyc2 \\
12
+ --init runs/stage2/stage2_epoch250.ckpt
13
+ torchrun --nproc_per_node=8 -m firepfn.train --config stage2_cyc3 --out runs/stage2_cyc3 \\
14
+ --init runs/stage2_cyc2/stage2_cyc2_epoch250.ckpt
15
+
16
+ Override single config values with --set key=value (JSON values), e.g. --set epochs=10.
17
+ """
18
+ import argparse
19
+ import copy
20
+ import json
21
+
22
+ from firepfn.train.configs import CONFIGS
23
+ from firepfn.train.loop import train
24
+
25
+
26
+ def main(argv=None):
27
+ ap = argparse.ArgumentParser(prog="python -m firepfn.train", description=__doc__,
28
+ formatter_class=argparse.RawDescriptionHelpFormatter)
29
+ ap.add_argument("--config", choices=sorted(CONFIGS), required=True)
30
+ ap.add_argument("--out", required=True, help="output directory for checkpoints")
31
+ ap.add_argument("--init", default=None, help="initial model weights (stage 2: the stage-1 model)")
32
+ ap.add_argument("--resume", default=None, help="checkpoint of this training loop to continue from")
33
+ ap.add_argument("--seed", type=int, default=0)
34
+ ap.add_argument("--name", default=None, help="run name (checkpoint prefix, wandb run name)")
35
+ ap.add_argument("--wandb", action="store_true", help="log to Weights & Biases (project fire-pfn)")
36
+ ap.add_argument("--set", action="append", default=[], metavar="KEY=VALUE",
37
+ help="override a config value (VALUE parsed as JSON, else as a string)")
38
+ args = ap.parse_args(argv)
39
+
40
+ cfg = copy.deepcopy(CONFIGS[args.config])
41
+ for kv in args.set:
42
+ key, _, value = kv.partition("=")
43
+ if key not in cfg:
44
+ ap.error(f"unknown config key {key!r}")
45
+ try:
46
+ cfg[key] = json.loads(value)
47
+ except json.JSONDecodeError:
48
+ cfg[key] = value
49
+ if args.config.startswith("stage2") and not (args.init or args.resume):
50
+ ap.error(f"{args.config} starts from the previous model (stage 1 or the previous stage-2 "
51
+ "cycle): pass --init <checkpoint>")
52
+ train(cfg, args.out, init_checkpoint=args.init, resume=args.resume, seed=args.seed,
53
+ use_wandb=args.wandb, run_name=args.name or args.config)
54
+
55
+
56
+ if __name__ == "__main__":
57
+ main()