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,396 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """FirePFN: frozen Kumo-Tabular row encoder + bidirectional SSM / linear-attention backbone over
4
+ the context rows + query -> context cross-attention + MLP decoder.
5
+
6
+ x (T, B, H), y (N, B) T = N context rows followed by the query rows
7
+ | Kumo input norm (per table and column, statistics of the context rows)
8
+ | KumoTableEncoder (frozen, pretrained): per-row embedding (B, T, D), labels of the context
9
+ | rows enter the encoder's column attention
10
+ context rows: + label embedding -> Backbone (layer_pattern) -> context_proj
11
+ query rows: query_proj
12
+ -> CrossAttention(query, context) -> decoder -> logits (Q, B, n_out)
13
+
14
+ Features are zero-padded on the right everywhere (prior batches, inference inputs), and real
15
+ columns are never all-zero after constant-feature removal, so a table's column count is the index
16
+ of its last column with a non-zero (or non-finite) cell + 1 (``_num_columns``). The batch is
17
+ trimmed to the widest table; narrower tables get their feature groups wrapped around their own
18
+ columns and their padded columns masked out of the encoder's row attention.
19
+
20
+ Inference is split (``build_context_cache`` / ``predict_from_cache``): the labelled rows are
21
+ encoded once, queries only run the encoder (with the cached column summaries), the cross-attention
22
+ and the decoder. Contexts longer than ``stream_infer.stream_ctx_rows()`` take a memory-bounded,
23
+ in-place streaming path.
24
+ """
25
+ import contextlib
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+ from torch import nn, Tensor
30
+
31
+ from firepfn.model import stream_infer
32
+ from firepfn.model.backbone import Backbone
33
+ from firepfn.model.cross_attention import CrossAttention
34
+ from firepfn.model.kumo import KumoTableEncoder, from_sdm_state_dict
35
+
36
+
37
+ def kumo_norm_stats(x: Tensor, train_size: int, threshold: float = 4.0):
38
+ """Kumo's Standardize + ClipSigma statistics from the context rows. x (B, R, C) fp32, may hold
39
+ NaN/inf (ignored). Returns (mean, scale, lower, upper), each (B, 1, C); lower/upper in
40
+ standardized units."""
41
+ ctx = x[:, :train_size]
42
+ fin = torch.isfinite(ctx)
43
+ cnt = fin.sum(1, keepdim=True).clamp(min=1)
44
+ mean = torch.where(fin, ctx, 0.0).sum(1, keepdim=True) / cnt
45
+ var = torch.where(fin, ctx - mean, 0.0).square().sum(1, keepdim=True) / cnt
46
+ scale = var.sqrt() + 1e-6
47
+ z = ((ctx - mean) / scale).clamp(-100.0, 100.0)
48
+ # ClipSigma: first pass on all finite values (sample std), second pass on those within bounds
49
+ m1 = torch.where(fin, z, 0.0).sum(1, keepdim=True) / cnt
50
+ s1 = (torch.where(fin, z - m1, 0.0).square().sum(1, keepdim=True) / (cnt - 1).clamp(min=1)).sqrt().clamp(min=1e-6)
51
+ keep = fin & (z >= m1 - threshold * s1) & (z <= m1 + threshold * s1)
52
+ k = keep.sum(1, keepdim=True)
53
+ m2 = torch.where(keep, z, 0.0).sum(1, keepdim=True) / k.clamp(min=1)
54
+ s2 = (torch.where(keep, z - m2, 0.0).square().sum(1, keepdim=True) / (k - 1).clamp(min=1)).sqrt().clamp(min=1e-6)
55
+ m, s_ = torch.where(k > 0, m2, m1), torch.where(k > 0, s2, s1)
56
+ return mean, scale, m - threshold * s_, m + threshold * s_
57
+
58
+
59
+ def kumo_norm_apply(x: Tensor, stats) -> Tensor:
60
+ """Standardize, clip to +-100 and log-soft-clip to the ClipSigma bounds; NaN stays NaN."""
61
+ mean, scale, lower, upper = stats
62
+ z = (x.float() - mean) / scale
63
+ z = torch.where(torch.isfinite(z), z.clamp(-100.0, 100.0), z)
64
+ la = z.abs().log1p()
65
+ return torch.minimum(la + upper, torch.maximum(lower - la, z))
66
+
67
+
68
+ class LabelEmbedding(nn.Linear):
69
+ """Class index -> embedding, as a Linear on the one-hot vector (weight (dim, num_classes))."""
70
+
71
+ def __init__(self, num_classes: int, dim: int):
72
+ super().__init__(num_classes, dim)
73
+ self.num_classes = num_classes
74
+
75
+ def forward(self, y: Tensor) -> Tensor:
76
+ return F.linear(F.one_hot(y.long(), self.num_classes).float(), self.weight, self.bias)
77
+
78
+
79
+ class FirePFN(nn.Module):
80
+ def __init__(
81
+ self,
82
+ n_out: int = 10,
83
+ ninp: int = 1024,
84
+ nhid: int = 2048,
85
+ num_heads: int = 4,
86
+ # backbone
87
+ layer_pattern=("ssm", "ssm", "attn", "ssm", "deltanet", "attn"),
88
+ ssm_config=None,
89
+ initializer_cfg=None,
90
+ attn_n_heads: int = 8,
91
+ attn_eps_z: float = 1e-4,
92
+ attn_eps_z_rel: float = 0.05,
93
+ deltanet_head_dim: int = 64,
94
+ deltanet_num_heads: int = 8,
95
+ deltanet_expand_v: float = 2.0,
96
+ # encoder
97
+ max_classes: int = 10,
98
+ num_readout: int = 4,
99
+ kumo_num_blocks: int = 6,
100
+ kumo_num_heads: int = 4,
101
+ kumo_num_inds: int = 256,
102
+ kumo_group_size: int = 3,
103
+ kumo_num_frequencies: int = 32,
104
+ kumo_categorical: bool = True,
105
+ kumo_row_gate_hidden: int = 64,
106
+ kumo_checkpoint_cells: bool = True,
107
+ kumo_recompute: bool = False,
108
+ kumo_recompute_min_elems: int = 0,
109
+ kumo_frozen: bool = True,
110
+ kumo_input_norm: bool = True,
111
+ kumo_clip_sigma: float = 4.0,
112
+ # head
113
+ cross_attn_len_temp: bool = True,
114
+ center_logits: bool = True,
115
+ device=None,
116
+ dtype=None,
117
+ ):
118
+ super().__init__()
119
+ self.max_classes = max_classes
120
+ self.num_readout = num_readout
121
+ self.center_logits = center_logits
122
+ self.kumo_frozen = kumo_frozen
123
+ self.kumo_input_norm = kumo_input_norm
124
+ self.kumo_clip_sigma = kumo_clip_sigma
125
+
126
+ self.table_encoder = KumoTableEncoder(
127
+ dim=ninp // num_readout,
128
+ num_blocks=kumo_num_blocks,
129
+ num_heads=kumo_num_heads,
130
+ num_inds=kumo_num_inds,
131
+ num_readout=num_readout,
132
+ group_size=kumo_group_size,
133
+ num_frequencies=kumo_num_frequencies,
134
+ max_classes=max_classes,
135
+ categorical=kumo_categorical,
136
+ row_gate_hidden=kumo_row_gate_hidden,
137
+ checkpoint_cells=kumo_checkpoint_cells,
138
+ recompute=kumo_recompute,
139
+ recompute_min_elems=kumo_recompute_min_elems,
140
+ )
141
+ if kumo_frozen:
142
+ self.table_encoder.requires_grad_(False)
143
+ self.table_encoder.eval()
144
+ # Label embedding added to the context rows on top of the encoder's own (target-aware) one.
145
+ self.col_y_encoder = LabelEmbedding(max_classes, ninp)
146
+
147
+ self.backbone = Backbone(
148
+ d_model=ninp, layer_pattern=layer_pattern, ssm_config=ssm_config or {},
149
+ initializer_cfg=initializer_cfg or {}, attn_n_heads=attn_n_heads, attn_eps_z=attn_eps_z,
150
+ attn_eps_z_rel=attn_eps_z_rel, deltanet_head_dim=deltanet_head_dim,
151
+ deltanet_num_heads=deltanet_num_heads, deltanet_expand_v=deltanet_expand_v,
152
+ device=device, dtype=dtype,
153
+ )
154
+ self.query_proj = nn.Linear(ninp, ninp)
155
+ self.context_proj = nn.Linear(ninp, ninp)
156
+ self.cross_attn = CrossAttention(ninp, num_heads, len_temp=cross_attn_len_temp)
157
+ self.decoder = nn.Sequential(nn.Linear(ninp, nhid), nn.GELU(), nn.Linear(nhid, n_out))
158
+
159
+ # ------------------------------------------------------------------ #
160
+ # Construction / weights
161
+ # ------------------------------------------------------------------ #
162
+
163
+ # Model hyperparameters with the defaults the checkpoints were trained with. Release
164
+ # checkpoints store all of them explicitly (see `resolve_config`).
165
+ CONFIG_DEFAULTS = {
166
+ "nhid_factor": 4, "num_heads": 4, "ssm_config": {}, "initializer_cfg": {},
167
+ "hybrid_attn_n_heads": 8, "attn_eps_z": 1e-4, "attn_eps_z_rel": 0.05,
168
+ "deltanet_head_dim": 64, "deltanet_num_heads": 8, "deltanet_expand_v": 2.0,
169
+ "col_max_classes": 10, "col_num_cls": 4,
170
+ "kumo_num_blocks": 4, "kumo_num_heads": 4, "kumo_num_inds": 128, "kumo_group_size": 3,
171
+ "kumo_num_frequencies": 32, "kumo_categorical": False, "kumo_row_gate_hidden": 64,
172
+ "kumo_checkpoint_cells": True, "kumo_recompute": False, "kumo_recompute_min_elems": 0,
173
+ "kumo_frozen": False, "kumo_input_norm": False, "kumo_clip_sigma": 4.0,
174
+ "cross_attn_len_temp": False, "center_logits": False,
175
+ }
176
+
177
+ @classmethod
178
+ def resolve_config(cls, config: dict) -> dict:
179
+ """(Training) config -> complete model config: every hyperparameter `from_config` reads,
180
+ with defaults filled in, as plain Python values."""
181
+ n_out = config["max_num_classes"]
182
+ out = {"max_num_classes": int(n_out.shape[0]) if hasattr(n_out, "shape") else int(n_out),
183
+ "emsize": int(config["emsize"]), "layer_pattern": list(config["layer_pattern"])}
184
+ for k, default in cls.CONFIG_DEFAULTS.items():
185
+ v = config.get(k, default)
186
+ out[k] = dict(v) if isinstance(v, dict) else v
187
+ return out
188
+
189
+ @classmethod
190
+ def from_config(cls, config: dict, device=None) -> "FirePFN":
191
+ """Build from a training config or a release model config (see `resolve_config`)."""
192
+ c = cls.resolve_config(config)
193
+ return cls(
194
+ n_out=c["max_num_classes"],
195
+ ninp=c["emsize"],
196
+ nhid=c["emsize"] * c["nhid_factor"],
197
+ num_heads=c["num_heads"],
198
+ layer_pattern=c["layer_pattern"],
199
+ ssm_config=c["ssm_config"],
200
+ initializer_cfg=c["initializer_cfg"],
201
+ attn_n_heads=c["hybrid_attn_n_heads"],
202
+ attn_eps_z=c["attn_eps_z"],
203
+ attn_eps_z_rel=c["attn_eps_z_rel"],
204
+ deltanet_head_dim=c["deltanet_head_dim"],
205
+ deltanet_num_heads=c["deltanet_num_heads"],
206
+ deltanet_expand_v=c["deltanet_expand_v"],
207
+ max_classes=c["col_max_classes"],
208
+ num_readout=c["col_num_cls"],
209
+ kumo_num_blocks=c["kumo_num_blocks"],
210
+ kumo_num_heads=c["kumo_num_heads"],
211
+ kumo_num_inds=c["kumo_num_inds"],
212
+ kumo_group_size=c["kumo_group_size"],
213
+ kumo_num_frequencies=c["kumo_num_frequencies"],
214
+ kumo_categorical=c["kumo_categorical"],
215
+ kumo_row_gate_hidden=c["kumo_row_gate_hidden"],
216
+ kumo_checkpoint_cells=c["kumo_checkpoint_cells"],
217
+ kumo_recompute=c["kumo_recompute"],
218
+ kumo_recompute_min_elems=c["kumo_recompute_min_elems"],
219
+ kumo_frozen=c["kumo_frozen"],
220
+ kumo_input_norm=c["kumo_input_norm"],
221
+ kumo_clip_sigma=c["kumo_clip_sigma"],
222
+ cross_attn_len_temp=c["cross_attn_len_temp"],
223
+ center_logits=c["center_logits"],
224
+ device=device,
225
+ dtype=config.get("dtype", None),
226
+ )
227
+
228
+ def load_kumo_pretrained(self, path: str) -> None:
229
+ """Row embedding of a released nvidia/Kumo-Tabular checkpoint (full ``classifier.pt`` with
230
+ ``row_embedding.``/``icl_block.`` keys, or the row embedding alone) -> table_encoder."""
231
+ sd = torch.load(path, map_location="cpu", weights_only=True)
232
+ if any(k.startswith("row_embedding.") for k in sd):
233
+ sd = {k[len("row_embedding."):]: v for k, v in sd.items() if k.startswith("row_embedding.")}
234
+ self.table_encoder.load_state_dict(from_sdm_state_dict(sd), strict=True)
235
+
236
+ def train(self, mode: bool = True):
237
+ super().train(mode)
238
+ if self.kumo_frozen:
239
+ self.table_encoder.eval()
240
+ return self
241
+
242
+ # ------------------------------------------------------------------ #
243
+ # Helpers
244
+ # ------------------------------------------------------------------ #
245
+
246
+ def _encoder_ctx(self):
247
+ return torch.no_grad() if self.kumo_frozen else contextlib.nullcontext()
248
+
249
+ def _encoder_input(self, x_bf: Tensor, train_size: int, stats=None):
250
+ if not self.kumo_input_norm:
251
+ return x_bf, None
252
+ if stats is None:
253
+ stats = kumo_norm_stats(x_bf.float(), train_size, self.kumo_clip_sigma)
254
+ return kumo_norm_apply(x_bf, stats), stats
255
+
256
+ @staticmethod
257
+ def _num_columns(x_bf: Tensor):
258
+ """x_bf: (B, T, H) -> (per-table column counts (B,) or None if all equal, widest count)."""
259
+ used = (x_bf != 0).any(dim=1) # NaN != 0: NaN columns count
260
+ pos = torch.arange(1, x_bf.shape[-1] + 1, device=x_bf.device)
261
+ num_columns = (used * pos).amax(dim=-1).clamp(min=1) # (B,)
262
+ widest, narrowest = torch.stack([num_columns.max(), num_columns.min()]).tolist()
263
+ return (None if widest == narrowest else num_columns), widest
264
+
265
+ def _prepare(self, x: Tensor):
266
+ """(T, B, H) -> trimmed (B, T, C), num_columns."""
267
+ x_bf = x.permute(1, 0, 2)
268
+ num_columns, C = self._num_columns(x_bf)
269
+ return x_bf[..., :C], num_columns
270
+
271
+ @staticmethod
272
+ def _labels(y: Tensor) -> Tensor:
273
+ # Tables a prior masked to y=-100 (loss ignore_index) are embedded as class 0.
274
+ return torch.nan_to_num(y, nan=0.0).clamp(min=0)
275
+
276
+ def _decode(self, x: Tensor) -> Tensor:
277
+ """(B, Q, ninp) -> logits (Q, B, n_out). Centering (softmax-invariant) removes the one
278
+ direction of the logits that gets no loss gradient."""
279
+ out = self.decoder(x)
280
+ if self.center_logits:
281
+ out = out - out.mean(dim=-1, keepdim=True)
282
+ return out.permute(1, 0, 2)
283
+
284
+ # ------------------------------------------------------------------ #
285
+ # Joint forward (training)
286
+ # ------------------------------------------------------------------ #
287
+
288
+ def forward(self, x: Tensor, y: Tensor, single_eval_pos: int) -> Tensor:
289
+ """x (T, B, H) features, y (T, B) or (N, B) labels, rows [0, single_eval_pos) are the
290
+ context. Returns logits (T - single_eval_pos, B, n_out) for the remaining rows."""
291
+ n = single_eval_pos
292
+ x_bf, num_columns = self._prepare(x)
293
+ y = self._labels(y)
294
+ with self._encoder_ctx():
295
+ x_bf, _ = self._encoder_input(x_bf, n)
296
+ encoded = self.table_encoder(x_bf, y.permute(1, 0)[:, :n], num_columns=num_columns)
297
+ encoded = encoded.float() # (B, T, ninp)
298
+ context = encoded[:, :n] + self.col_y_encoder(y[:n].long()).permute(1, 0, 2)
299
+ query = encoded[:, n:]
300
+ context_hidden = self.context_proj(self.backbone(context))
301
+ return self._decode(self.cross_attn(self.query_proj(query), context_hidden))
302
+
303
+ # ------------------------------------------------------------------ #
304
+ # Split inference
305
+ # ------------------------------------------------------------------ #
306
+
307
+ def _use_stream(self, n_ctx: int) -> bool:
308
+ thr = stream_infer.stream_ctx_rows()
309
+ return thr > 0 and n_ctx > thr and not torch.is_grad_enabled()
310
+
311
+ @torch.no_grad()
312
+ def build_context_cache(self, x_ctx: Tensor, y_ctx: Tensor) -> dict:
313
+ """Everything the forward pass computes from the labelled rows alone.
314
+ x_ctx (N, B, H) preprocessed features, y_ctx (N, B) labels."""
315
+ if self._use_stream(x_ctx.shape[0]):
316
+ return self._build_context_cache_stream(x_ctx, y_ctx)
317
+ x_bf, num_columns = self._prepare(x_ctx)
318
+ y = self._labels(y_ctx)
319
+ x_bf, norm_stats = self._encoder_input(x_bf, x_bf.shape[1])
320
+ rows, enc_cache = self.table_encoder.encode_context(x_bf, y.permute(1, 0), num_columns=num_columns)
321
+ context = rows.float()
322
+ del rows # don't hold the encoder output next to `context` through the backbone
323
+ context += self.col_y_encoder(y.long()).permute(1, 0, 2)
324
+ return {"width": x_bf.shape[-1], "num_columns": num_columns, "encoder": enc_cache,
325
+ "norm": norm_stats, "context_hidden": self.context_proj(self.backbone(context))}
326
+
327
+ @torch.no_grad()
328
+ def _build_context_cache_stream(self, x_ctx: Tensor, y_ctx: Tensor) -> dict:
329
+ """build_context_cache with O(row chunk) working memory beyond one (B, N, ninp) fp32
330
+ buffer: the Kumo input-norm statistics are computed column-chunked, the encoder streams
331
+ over row chunks (KumoTableEncoder.encode_context_stream) and writes its output plus the
332
+ label embedding straight into the buffer, and the backbone + context_proj then run in
333
+ place on it (stream_infer.backbone_inplace). Same computation as the default path up to
334
+ float summation order (or, with FIREPFN_STREAM_SUMMARY_ROWS, with the encoder's column
335
+ summaries estimated from a random subset of the context rows)."""
336
+ x_bf, num_columns = self._prepare(x_ctx) # (B, N, C) view
337
+ y = self._labels(y_ctx).permute(1, 0) # (B, N)
338
+ B, N, C = x_bf.shape
339
+ norm_stats, pre = None, None
340
+ if self.kumo_input_norm:
341
+ with stream_infer.phase("kumo input-norm stats"):
342
+ cc = max(1, 2**27 // max(B * N, 1))
343
+ parts = [kumo_norm_stats(x_bf[..., c:c + cc].float(), N, self.kumo_clip_sigma)
344
+ for c in range(0, C, cc)]
345
+ norm_stats = tuple(torch.cat(t, dim=-1) for t in zip(*parts))
346
+ del parts
347
+ pre = lambda t: kumo_norm_apply(t, norm_stats) # noqa: E731
348
+ # The one full-length tensor of this path, 4 bytes x ninp per context row; kept in host
349
+ # memory (stream_infer.HostBuffer) when it does not fit on the GPU next to the working sets.
350
+ buf = stream_infer.context_buffer((B, N, self.context_proj.in_features), x_bf.device)
351
+
352
+ def write(s, e, rows):
353
+ r = rows.float()
354
+ r += self.col_y_encoder(y[:, s:e].long())
355
+ buf[:, s:e] = r
356
+
357
+ enc = self.table_encoder
358
+ tok_bytes = B * N * (enc.num_readout + C) * enc.dim * 2 # bf16 (B, N, K + C, D) tokens
359
+ if stream_infer.token_buffer_fits(tok_bytes + B * N * C * 4 * 3):
360
+ # The whole encoder token state fits: run the encoder once (no recompute passes); the
361
+ # backbone / cross-attention still take the in-place, streamed paths.
362
+ with stream_infer.phase("encoder (full token buffer)"):
363
+ xin = pre(x_bf) if pre is not None else x_bf
364
+ rows, enc_cache = enc.encode_context(xin, y, num_columns=num_columns)
365
+ del xin
366
+ step = max(1, 2**26 // max(B * rows.shape[-1], 1))
367
+ for s in range(0, N, step):
368
+ write(s, min(N, s + step), rows[:, s:s + step])
369
+ del rows
370
+ else:
371
+ stream_infer._note_path(token_recompute=True)
372
+ enc_cache = enc.encode_context_stream(
373
+ x_bf, y, write, num_columns=num_columns, pre=pre,
374
+ chunk_elems=stream_infer.stream_chunk_elems(), summary_rows=stream_infer.stream_summary_rows())
375
+ stream_infer.backbone_inplace(self.backbone, buf, stream_infer.infer_segment_rows(), out_fn=self.context_proj)
376
+ return {"width": C, "num_columns": num_columns, "encoder": enc_cache, "norm": norm_stats,
377
+ "context_hidden": buf}
378
+
379
+ @torch.no_grad()
380
+ def predict_from_cache(self, cache: dict, x_q: Tensor) -> Tensor:
381
+ """Logits (M, B, n_out) for query rows x_q (M, B, H) against a build_context_cache()
382
+ result. Query rows are independent, so they run in chunks (bounded encoder tokens)."""
383
+ qc = stream_infer.query_chunk_rows()
384
+ if qc > 0:
385
+ qc = max(1, qc // max(x_q.shape[1], 1)) # budget is query rows x tables
386
+ if qc > 0 and x_q.shape[0] > qc:
387
+ return torch.cat([self._predict_from_cache(cache, x_q[s:s + qc]) for s in range(0, x_q.shape[0], qc)])
388
+ return self._predict_from_cache(cache, x_q)
389
+
390
+ def _predict_from_cache(self, cache: dict, x_q: Tensor) -> Tensor:
391
+ # Queries use the context's column layout (a query batch may be all-zero in a column).
392
+ x_bf = x_q.permute(1, 0, 2)[..., :cache["width"]]
393
+ if self.kumo_input_norm:
394
+ x_bf, _ = self._encoder_input(x_bf, 0, cache["norm"])
395
+ rows = self.table_encoder.encode_queries(x_bf, cache["encoder"], num_columns=cache["num_columns"]).float()
396
+ return self._decode(self.cross_attn(self.query_proj(rows), cache["context_hidden"]))
@@ -0,0 +1,73 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Stop flash-linear-attention (fla) kernels from re-autotuning for every new sequence length.
4
+
5
+ Several fla Triton kernels used by FirePFN's GatedDeltaNet branch (l2norm, gated layer norm,
6
+ short causal convolution, ...) take ``NB = cdiv(T, 2048)`` (or ``cdiv(B*T, 1024)``) as a
7
+ ``tl.constexpr`` *and* as an autotuning key, although the kernel bodies never read it -- it only
8
+ tells the autotuner how big the problem is. Every context size that lands on a new NB therefore
9
+ autotunes ~66 kernel variants from scratch: ~27 s on the first fit at that size on a B300,
10
+ cached on disk afterwards (FLA_CACHE_RESULTS, Triton cache).
11
+
12
+ patch() wraps those autotuners so NB is rounded up to the next power of two before dispatch:
13
+ at most ~log2(T_max / 2048) + 1 distinct values instead of one per 2048 rows. NB is unused in
14
+ the kernel bodies, so results are unchanged; only the config choice is shared within a bucket.
15
+
16
+ Disable with FIREPFN_FLA_NB_BUCKET=0.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import importlib
21
+ import os
22
+
23
+ _MODULES = ("fla.modules.l2norm", "fla.modules.fused_norm_gate", "fla.modules.layernorm",
24
+ "fla.modules.convolution", "fla.modules.token_shift")
25
+ _patched = False
26
+
27
+
28
+ def _bucket(nb):
29
+ nb = int(nb)
30
+ return 1 if nb <= 1 else 1 << (nb - 1).bit_length()
31
+
32
+
33
+ def _wrap(autotuner):
34
+ if getattr(autotuner, "_firepfn_nb_bucketed", False):
35
+ return False
36
+ orig = autotuner.run
37
+
38
+ def run(*args, **kwargs):
39
+ if "NB" in kwargs:
40
+ kwargs["NB"] = _bucket(kwargs["NB"])
41
+ return orig(*args, **kwargs)
42
+
43
+ autotuner.run = run
44
+ autotuner._firepfn_nb_bucketed = True
45
+ return True
46
+
47
+
48
+ def patch() -> int:
49
+ """Apply once per process; returns the number of kernels patched."""
50
+ global _patched
51
+ if _patched or os.environ.get("FIREPFN_FLA_NB_BUCKET", "1") == "0":
52
+ return 0
53
+ _patched = True
54
+ try:
55
+ from triton.runtime.autotuner import Autotuner
56
+ except ImportError:
57
+ return 0
58
+ n = 0
59
+ for name in _MODULES:
60
+ try:
61
+ mod = importlib.import_module(name)
62
+ except Exception:
63
+ continue
64
+ for obj in vars(mod).values():
65
+ # @triton.heuristics(...) wraps the Autotuner; follow .fn down the decorator chain.
66
+ seen = 0
67
+ while obj is not None and seen < 4:
68
+ if isinstance(obj, Autotuner) and "NB" in getattr(obj, "keys", ()):
69
+ n += _wrap(obj)
70
+ break
71
+ obj = getattr(obj, "fn", None)
72
+ seen += 1
73
+ return n