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
firepfn/model/kumo.py ADDED
@@ -0,0 +1,704 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3
+ # Copyright (c) 2025-2026, the FirePFN authors (modifications).
4
+ #
5
+ # Re-implementation of the Kumo-Tabular row embedding from NVIDIA structured-data-models
6
+ # (https://github.com/NVIDIA/structured-data-models), licensed under the Apache License 2.0.
7
+ # Modified by the FirePFN authors: state-dict compatible re-implementation with the efficiency
8
+ # changes listed below (shared group projection, chunked/streamed no-grad inference, recompute),
9
+ # per-table column counts and split context/query encoding. The pretrained weights it loads are
10
+ # licensed separately under OpenMDW-1.1 (see LICENSES/).
11
+ """Kumo-Tabular table encoder, ported from NVIDIA structured-data-models (sdm, Apache-2.0):
12
+ sdm/models/kumo/tabular/{row_embedding,cell_embedding,block}.py, sdm/models/tabfm/cell_embedding.py,
13
+ sdm/nn/{attention,scaling,set_transformer,rope}.py.
14
+
15
+ x (B, R, C) --mean-impute (context rows)--> CellEmbedding --> (B, R, C, D) one token per column
16
+ + label embedding on the context rows
17
+ for i in 1..K:
18
+ column attention inducing points <- context rows (LogScale), every row <- inducing points
19
+ row attention [readout x Kr, C cells] per row (RoPE, GatedLogScale, padded columns masked);
20
+ the last one is the read-out: only the readout tokens are queries
21
+ -> RMSNorm -> concat readout tokens -> (B, R, Kr * D)
22
+
23
+ Main components (as in sdm):
24
+ * cell embedding: sin/cos features only (no raw value), F frequencies per position in the
25
+ feature group, one Linear shared by the group's cells, separate frequencies/Linear for
26
+ categorical columns (optional), learned missingness projection (always on);
27
+ * Kumo's transformer block: RMSNorm with separate norms for the query and key/value inputs,
28
+ per-head QK RMSNorm (no affine), fused QKV, 2x GELU MLP, attention-out and MLP-out zero-init;
29
+ * temperatures: LogScale (a_h * log n) for inducing points -> rows, GatedLogScale on the row
30
+ axis (n = readout tokens + valid columns), none for rows -> inducing points;
31
+ * per-table column counts: feature groups wrap around each table's own columns and padded
32
+ columns are masked out of row attention;
33
+ * labels >= max_classes raise instead of being folded onto other classes.
34
+
35
+ Efficiency (training is gradient-enabled; everything else takes the no-grad path):
36
+ * the group's cells share one Linear, so the projection runs on the per-group SUM of the sin/cos
37
+ features: (B, R, C, 2F) instead of (B, R, C, G * 2F) -- G times less matmul input -- and the
38
+ cell embedding is recomputed in backward instead of keeping the fp32 (B, R, C, G, F) sin/cos
39
+ tensors alive (checkpoint_cells);
40
+ * the inducing points' query projection runs once on (M, D), not on a (B, C, M, D) expansion;
41
+ * RoPE cos/sin are built once per forward and shared by all row blocks;
42
+ * recompute: tables are independent, so each layer is checkpointed per chunk of tables --
43
+ backward holds one chunk's activations, not the micro-batch's (~4 GB per table and layer at
44
+ 2048 rows x 100 columns, D=192: per-block checkpointing over the whole batch does not fit);
45
+ * affine RMSNorms run their weight in the input dtype (fused kernel under autocast);
46
+ * padding columns are trimmed by the caller; masks (which rule out the flash kernel) only appear
47
+ when the tables of a batch differ in width;
48
+ * no-grad path: one preallocated (B, R, Kr + C, D) buffer written in place (no torch.cat per
49
+ block), column summaries computed in column chunks, everything else in row chunks of at most
50
+ ~infer_chunk_elems elements -- both axes are independent there, so results are identical.
51
+ """
52
+ from __future__ import annotations
53
+
54
+ import math
55
+ from typing import Optional, Union
56
+
57
+ import torch
58
+ import torch.nn.functional as F
59
+ from torch import nn, Tensor
60
+ from torch.utils.checkpoint import checkpoint
61
+
62
+ # CUDA attention kernels accept at most 65,535 batch entries per call (sdm/nn/attention.py).
63
+ _MAX_SDPA_BATCH = 65_535
64
+
65
+ from firepfn.model.triton_rmsnorm import rms_norm as _rms_norm # noqa: E402 (F.rms_norm; fused when no grad)
66
+ from firepfn.model.triton_rope import apply_rope as _fused_rope # noqa: E402 (None if not applicable)
67
+ from firepfn.model.triton_rope import gated_log_scale as _fused_gate, gate_enabled as _gate_on # noqa: E402
68
+
69
+
70
+ def _gate_fusable(q: Tensor) -> bool:
71
+ return q.is_cuda and not torch.is_grad_enabled() and _gate_on()
72
+
73
+
74
+ def _no_wd(p: nn.Parameter) -> nn.Parameter:
75
+ p._no_weight_decay = True
76
+ return p
77
+
78
+
79
+ class _RMSNorm(nn.RMSNorm):
80
+ """nn.RMSNorm with its weight cast to the input dtype. Under autocast the residual stream is
81
+ bf16, and an fp32 weight rules out the fused kernel (slower, fp32 intermediates kept for
82
+ backward). Same parameters/state-dict keys as nn.RMSNorm."""
83
+
84
+ def forward(self, x: Tensor) -> Tensor:
85
+ w = None if self.weight is None else self.weight.to(x.dtype)
86
+ return _rms_norm(x, self.normalized_shape, w, self.eps)
87
+
88
+
89
+ def _head_norm(norm: nn.RMSNorm, x: Tensor) -> Tensor:
90
+ """The per-head q/k nn.RMSNorm, through the fused no-grad kernel when possible."""
91
+ return _rms_norm(x, norm.normalized_shape, norm.weight, norm.eps)
92
+
93
+
94
+ # ---------------------------------------------------------------------- #
95
+ # Attention pieces
96
+ # ---------------------------------------------------------------------- #
97
+
98
+ class LogScale(nn.Module):
99
+ """q * a_h * log(max(n, 1)) with a_h ~ U[0, 1) per head (sdm.nn.LogScale). q: (..., H, L, d);
100
+ key_len: int, or a tensor broadcastable against q (one length per table)."""
101
+
102
+ def __init__(self, num_heads: int):
103
+ super().__init__()
104
+ self.head_scale = _no_wd(nn.Parameter(torch.rand(num_heads)))
105
+
106
+ def forward(self, q: Tensor, key_len: Union[int, Tensor]) -> Tensor:
107
+ if isinstance(key_len, Tensor):
108
+ log_n = key_len.float().clamp(min=1.0).log().to(q.dtype)
109
+ else:
110
+ log_n = math.log(max(key_len, 1))
111
+ return q * (self.head_scale.to(q.dtype).view(-1, 1, 1) * log_n)
112
+
113
+
114
+ class GatedLogScale(LogScale):
115
+ """LogScale * (1 + tanh(g(q))), g a per-head MLP with zero-init output (sdm.nn.GatedLogScale)."""
116
+
117
+ def __init__(self, head_dim: int, num_heads: int, hidden: int = 64):
118
+ super().__init__(num_heads)
119
+ self.gate = nn.Sequential(nn.Linear(head_dim, hidden), nn.GELU(), nn.Linear(hidden, head_dim))
120
+ nn.init.zeros_(self.gate[-1].weight)
121
+ nn.init.zeros_(self.gate[-1].bias)
122
+
123
+ def forward(self, q: Tensor, key_len: Union[int, Tensor]) -> Tensor:
124
+ g = self.gate(q)
125
+ if isinstance(key_len, int) and _gate_fusable(q):
126
+ # one fused pass instead of mul / tanh / add / mul, bit-identical (triton_rope.py)
127
+ sc = self.head_scale.to(q.dtype).view(-1, 1, 1) * math.log(max(key_len, 1))
128
+ y = _fused_gate(q, sc, g)
129
+ if y is not None:
130
+ return y
131
+ return super().forward(q, key_len) * (1 + g.tanh())
132
+
133
+
134
+ def _apply_rope(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor:
135
+ """split_half RoPE over positions 0..L-1. x: (..., L, d); cos/sin: (>= L, d/2) fp32.
136
+ Without autograd on CUDA: fused Triton kernel, bit-identical (triton_rope.py)."""
137
+ y = _fused_rope(x, cos, sin)
138
+ if y is not None:
139
+ return y
140
+ L = x.shape[-2]
141
+ cos, sin = cos[:L].to(x.dtype), sin[:L].to(x.dtype)
142
+ x1, x2 = x.chunk(2, dim=-1)
143
+ return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1)
144
+
145
+
146
+ def _sdpa(q: Tensor, k: Tensor, v: Tensor, mask: Optional[Tensor]) -> Tensor:
147
+ """SDPA over arbitrary, broadcastable batch dims. q: (..., H, Lq, d), k/v: (..., H, Lk, d),
148
+ mask: (..., 1, 1, Lk) bool (True = attend) or None."""
149
+ shapes = [q.shape[:-3], k.shape[:-3]] + ([mask.shape[:-3]] if mask is not None else [])
150
+ batch = torch.broadcast_shapes(*shapes)
151
+ q = q.expand(batch + q.shape[-3:]).reshape(-1, *q.shape[-3:])
152
+ k = k.expand(batch + k.shape[-3:]).reshape(-1, *k.shape[-3:])
153
+ v = v.expand(batch + v.shape[-3:]).reshape(-1, *v.shape[-3:])
154
+ if mask is not None:
155
+ mask = mask.expand(batch + mask.shape[-3:]).reshape(-1, *mask.shape[-3:])
156
+ n = q.shape[0]
157
+ if n <= _MAX_SDPA_BATCH:
158
+ out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
159
+ else:
160
+ out = torch.cat([
161
+ F.scaled_dot_product_attention(
162
+ q[i:i + _MAX_SDPA_BATCH], k[i:i + _MAX_SDPA_BATCH], v[i:i + _MAX_SDPA_BATCH],
163
+ attn_mask=None if mask is None else mask[i:i + _MAX_SDPA_BATCH],
164
+ )
165
+ for i in range(0, n, _MAX_SDPA_BATCH)
166
+ ])
167
+ return out.view(batch + out.shape[-3:])
168
+
169
+
170
+ class KumoBlock(nn.Module):
171
+ """sdm's KumoTabularTransformerBlock: x = q + Attn(norm_q(q), norm_kv(kv)); x = x + MLP(x).
172
+
173
+ Fused QKV weight; q/k get (RoPE then) a per-head RMSNorm without affine, then the optional
174
+ query scaling; attention-out and the MLP's last Linear start at zero, so every block starts as
175
+ the identity. query may have fewer batch dims than kv (inducing points: (M, D))."""
176
+
177
+ def __init__(self, dim: int, num_heads: int, query_scaling: Optional[nn.Module] = None):
178
+ super().__init__()
179
+ self.dim, self.num_heads, self.head_dim = dim, num_heads, dim // num_heads
180
+ self.query_norm = _RMSNorm(dim)
181
+ self.kv_norm = _RMSNorm(dim)
182
+ self.qkv = nn.Linear(dim, 3 * dim)
183
+ self.q_head_norm = nn.RMSNorm(self.head_dim, eps=1e-6, elementwise_affine=False)
184
+ self.k_head_norm = nn.RMSNorm(self.head_dim, eps=1e-6, elementwise_affine=False)
185
+ self.query_scaling = query_scaling
186
+ self.out = nn.Linear(dim, dim)
187
+ self.mlp = nn.Sequential(_RMSNorm(dim), nn.Linear(dim, 2 * dim), nn.GELU(), nn.Linear(2 * dim, dim))
188
+ for lin in (self.out, self.mlp[-1]):
189
+ nn.init.zeros_(lin.weight)
190
+ nn.init.zeros_(lin.bias)
191
+
192
+ def _heads(self, x: Tensor) -> Tensor:
193
+ return x.unflatten(-1, (self.num_heads, self.head_dim)).transpose(-3, -2) # (..., H, L, d)
194
+
195
+ def forward(
196
+ self,
197
+ query: Tensor, # (..., Lq, D)
198
+ kv: Tensor, # (..., Lk, D)
199
+ key_len: Union[int, Tensor, None] = None, # for query_scaling
200
+ key_mask: Optional[Tensor] = None, # (..., 1, 1, Lk) bool
201
+ rope: Optional[tuple] = None, # (cos, sin)
202
+ ) -> Tensor:
203
+ D = self.dim
204
+ w_q, w_kv = self.qkv.weight.split([D, 2 * D])
205
+ b_q, b_kv = self.qkv.bias.split([D, 2 * D])
206
+ q = self._heads(F.linear(self.query_norm(query), w_q, b_q))
207
+ k, v = (self._heads(t) for t in F.linear(self.kv_norm(kv), w_kv, b_kv).chunk(2, dim=-1))
208
+ if rope is not None:
209
+ q, k = _apply_rope(q, *rope), _apply_rope(k, *rope)
210
+ q, k = _head_norm(self.q_head_norm, q), _head_norm(self.k_head_norm, k)
211
+ if self.query_scaling is not None:
212
+ q = self.query_scaling(q, key_len)
213
+ # Autocast runs RMSNorm in fp32 while v comes out of the Linear in bf16/fp16.
214
+ attn = _sdpa(q.to(v.dtype), k.to(v.dtype), v, key_mask)
215
+ x = query + self.out(attn.transpose(-3, -2).flatten(-2))
216
+ return x + self.mlp(x)
217
+
218
+
219
+ class KumoInducedBlock(nn.Module):
220
+ """Column attention (sdm InducedTransformerBlock): M inducing points read the context rows
221
+ (LogScale over the number of context rows), then every row reads the inducing points."""
222
+
223
+ def __init__(self, dim: int, num_heads: int, num_inds: int):
224
+ super().__init__()
225
+ self.inducing_points = nn.Parameter(torch.empty(num_inds, dim))
226
+ nn.init.trunc_normal_(self.inducing_points, std=0.02)
227
+ self.inducing_block = KumoBlock(dim, num_heads, LogScale(num_heads))
228
+ self.output_block = KumoBlock(dim, num_heads, None)
229
+
230
+ def summarize(self, ctx: Tensor) -> Tensor:
231
+ """(..., N_ctx, D) -> (..., M, D)."""
232
+ return self.inducing_block(self.inducing_points.to(ctx.dtype), ctx, key_len=ctx.shape[-2])
233
+
234
+ def read(self, x: Tensor, summary: Tensor) -> Tensor:
235
+ """(..., R, D), (..., M, D) -> (..., R, D)."""
236
+ return self.output_block(x, summary)
237
+
238
+
239
+ # ---------------------------------------------------------------------- #
240
+ # Cell embedding
241
+ # ---------------------------------------------------------------------- #
242
+
243
+ class KumoCellEmbedding(nn.Module):
244
+ """One token per column c from its feature group (c, c+1, c+3, ..., c + 2^(G-1) - 1), wrapped
245
+ around the table's own column count:
246
+
247
+ token = sum_g (W_t(g) [sin(x_g f_{t,g}), cos(x_g f_{t,g})] + b_t(g)) + W_nan m
248
+
249
+ t(g) = numerical/categorical type of the g-th cell, f_{t,g} in R^F learned per type and group
250
+ position (N(0, 1) init, no 2*pi, as in sdm), W_t one Linear per type shared by all group
251
+ positions, m the group's missingness indicators. Because W_t is shared, the projection is
252
+ applied to the per-type SUM of the group's sin/cos features.
253
+ """
254
+
255
+ def __init__(self, dim: int, group_size: int = 3, num_frequencies: int = 32, categorical: bool = False):
256
+ super().__init__()
257
+ self.group_size = group_size
258
+ self.num_freq = _no_wd(nn.Parameter(torch.randn(group_size, num_frequencies)))
259
+ self.num_lin = nn.Linear(2 * num_frequencies, dim)
260
+ # Only built when a categorical mask will actually be passed: parameters that never get a
261
+ # gradient break DDP without find_unused_parameters.
262
+ self.categorical = categorical
263
+ if categorical:
264
+ self.cat_freq = _no_wd(nn.Parameter(torch.randn(group_size, num_frequencies)))
265
+ self.cat_lin = nn.Linear(2 * num_frequencies, dim)
266
+ self.nan_lin = nn.Linear(group_size, dim, bias=False)
267
+
268
+ def group_index(self, C: int, num_columns: Optional[Tensor], device) -> Tensor:
269
+ """(C, G), or (B, C, G) wrapping around each table's num_columns."""
270
+ idx = torch.arange(C, device=device)[:, None] + (2 ** torch.arange(self.group_size, device=device) - 1)
271
+ if num_columns is None:
272
+ return idx % C
273
+ return idx % num_columns.clamp(min=1)[:, None, None]
274
+
275
+ @staticmethod
276
+ def _gather(t: Tensor, idx: Tensor) -> Tensor:
277
+ """t: (B, R, C) or (B, C); idx (C, G) or (B, C, G) -> (B, R, C, G) or (B, C, G)."""
278
+ if idx.dim() == 2:
279
+ return t[..., idx]
280
+ if t.dim() == 2:
281
+ return t.gather(-1, idx.flatten(1)).view_as(idx)
282
+ B, R, _ = t.shape
283
+ return t.gather(-1, idx.flatten(1)[:, None, :].expand(B, R, -1)).unflatten(-1, idx.shape[1:])
284
+
285
+ @staticmethod
286
+ def _fourier_sum(xg: Tensor, freq: Tensor, weight: Optional[Tensor] = None) -> Tensor:
287
+ """sum_g [sin(x_g f_g), cos(x_g f_g)] (* weight_g): (B, R, C, G) -> (B, R, C, 2F), fp32."""
288
+ z = xg.float().unsqueeze(-1) * freq.float() # (B, R, C, G, F)
289
+ s, c = z.sin(), z.cos()
290
+ if weight is not None:
291
+ s, c = s * weight, c * weight
292
+ return torch.cat([s.sum(-2), c.sum(-2)], dim=-1)
293
+
294
+ def forward(
295
+ self,
296
+ x: Tensor, # (B, R, C), finite
297
+ missing: Tensor, # (B, R, C) bool
298
+ num_columns: Optional[Tensor] = None, # (B,)
299
+ categorical_mask: Optional[Tensor] = None, # (B, C) bool
300
+ ) -> Tensor: # (B, R, C, D)
301
+ idx = self.group_index(x.shape[-1], num_columns, x.device)
302
+ xg = self._gather(x, idx) # (B, R, C, G)
303
+ mg = self._gather(missing, idx)
304
+ dtype = torch.get_autocast_dtype("cuda") if x.is_cuda and torch.is_autocast_enabled("cuda") else x.dtype
305
+ if categorical_mask is None or not self.categorical:
306
+ s = self._fourier_sum(xg, self.num_freq)
307
+ out = F.linear(s.to(dtype), self.num_lin.weight.to(dtype)) + self.group_size * self.num_lin.bias.to(dtype)
308
+ else:
309
+ cg = self._gather(categorical_mask, idx).unsqueeze(1).unsqueeze(-1) # (B, 1, C, G, 1)
310
+ s_num = self._fourier_sum(xg, self.num_freq, (~cg).to(torch.float32))
311
+ s_cat = self._fourier_sum(xg, self.cat_freq, cg.to(torch.float32))
312
+ n_cat = cg.sum(-2).to(dtype) # (B, 1, C, 1)
313
+ out = (F.linear(s_num.to(dtype), self.num_lin.weight.to(dtype))
314
+ + F.linear(s_cat.to(dtype), self.cat_lin.weight.to(dtype))
315
+ + (self.group_size - n_cat) * self.num_lin.bias.to(dtype)
316
+ + n_cat * self.cat_lin.bias.to(dtype))
317
+ return out + F.linear(mg.to(dtype), self.nan_lin.weight.to(dtype))
318
+
319
+
320
+ # ---------------------------------------------------------------------- #
321
+ # Encoder
322
+ # ---------------------------------------------------------------------- #
323
+
324
+ class KumoTableEncoder(nn.Module):
325
+ """Kumo-Tabular row embedding; returns (B, R, num_readout * dim)."""
326
+
327
+ def __init__(
328
+ self,
329
+ dim: int,
330
+ num_blocks: int = 4,
331
+ num_heads: int = 4,
332
+ num_inds: int = 128,
333
+ num_readout: int = 4,
334
+ group_size: int = 3,
335
+ num_frequencies: int = 32,
336
+ max_classes: int = 10,
337
+ categorical: bool = False,
338
+ rope_base: float = 100_000,
339
+ row_gate_hidden: int = 64,
340
+ checkpoint_cells: bool = True,
341
+ recompute: bool = False,
342
+ recompute_min_elems: int = 0,
343
+ recompute_chunk_elems: int = 2**26,
344
+ infer_chunk_elems: int = 2**26,
345
+ ):
346
+ super().__init__()
347
+ self.dim = dim
348
+ self.num_readout = num_readout
349
+ self.max_classes = max_classes
350
+ self.checkpoint_cells = checkpoint_cells
351
+ # Gradient checkpointing for micro-steps whose (B, R, Kr + C, D) token tensor has at least
352
+ # recompute_min_elems elements (decided once per forward). Tables are
353
+ # independent in the encoder, so every layer is checkpointed per chunk of tables with at
354
+ # most ~recompute_chunk_elems token elements: backward then holds one chunk's activations
355
+ # (~50 token-sized tensors per layer) instead of the whole micro-batch's.
356
+ self.recompute = recompute
357
+ self.recompute_min_elems = recompute_min_elems
358
+ self.recompute_chunk_elems = recompute_chunk_elems
359
+ self.infer_chunk_elems = infer_chunk_elems
360
+
361
+ self.cell = KumoCellEmbedding(dim, group_size, num_frequencies, categorical)
362
+ self.y_emb = nn.Embedding(max_classes, dim)
363
+ self.readout_tokens = nn.Parameter(torch.empty(num_readout, dim))
364
+ nn.init.trunc_normal_(self.readout_tokens, std=0.02)
365
+
366
+ head_dim = dim // num_heads
367
+ assert head_dim % 2 == 0, "RoPE needs an even head dimension"
368
+ self.register_buffer(
369
+ "rope_inv_freq", 1.0 / (rope_base ** (torch.arange(0, head_dim, 2).float() / head_dim)),
370
+ persistent=False,
371
+ )
372
+ self.col_blocks = nn.ModuleList([KumoInducedBlock(dim, num_heads, num_inds) for _ in range(num_blocks)])
373
+ self.row_blocks = nn.ModuleList([
374
+ KumoBlock(dim, num_heads, GatedLogScale(head_dim, num_heads, row_gate_hidden))
375
+ for _ in range(num_blocks)
376
+ ])
377
+ self.out_norm = _RMSNorm(dim)
378
+
379
+ # ------------------------------------------------------------------ #
380
+ # helpers
381
+ # ------------------------------------------------------------------ #
382
+
383
+ def _rope(self, length: int):
384
+ f = torch.arange(length, device=self.rope_inv_freq.device, dtype=torch.float32)[:, None] * self.rope_inv_freq
385
+ return f.cos(), f.sin()
386
+
387
+ def _row_key_info(self, num_columns: Optional[Tensor], C: int):
388
+ """key_len for GatedLogScale and the padded-column mask; shaped for (B, R, H, L, d)."""
389
+ K = self.num_readout
390
+ if num_columns is None:
391
+ return K + C, None
392
+ n = (K + num_columns.clamp(max=C)).view(-1, 1, 1, 1, 1)
393
+ mask = torch.arange(K + C, device=num_columns.device).view(1, 1, 1, 1, -1) < n
394
+ return n, mask
395
+
396
+ def impute(self, x: Tensor, train_size: int, impute_mean: Optional[Tensor] = None):
397
+ """NaN/inf -> column mean over the finite context rows (0 if none), as Kumo's cell embedding.
398
+ Returns (x, missing, impute_mean (B, 1, C))."""
399
+ missing = ~torch.isfinite(x)
400
+ if impute_mean is None:
401
+ ctx, ok = x[:, :train_size], ~missing[:, :train_size]
402
+ impute_mean = torch.where(ok, ctx, 0.0).sum(1, keepdim=True) / ok.sum(1, keepdim=True).clamp(min=1)
403
+ return torch.where(missing, impute_mean, x), missing, impute_mean
404
+
405
+ def _label_emb(self, y: Tensor) -> Tensor:
406
+ """(B, R_train) class indices -> (B, R_train, D)."""
407
+ return self.y_emb(y.long())
408
+
409
+ def _check_labels(self, y: Tensor):
410
+ if not self.training and y.numel() and int(y.max()) >= self.max_classes:
411
+ raise ValueError(
412
+ f"label {int(y.max())} >= max_classes={self.max_classes}: the Kumo encoder does not fold "
413
+ "classes; reduce the class count first (Kumo uses an ECOC wrapper for this)."
414
+ )
415
+
416
+ def _embed(self, x, missing, num_columns, categorical_mask):
417
+ if self.checkpoint_cells and torch.is_grad_enabled():
418
+ return checkpoint(self.cell, x, missing, num_columns, categorical_mask, use_reentrant=False)
419
+ return self.cell(x, missing, num_columns, categorical_mask)
420
+
421
+
422
+ # ------------------------------------------------------------------ #
423
+ # forward
424
+ # ------------------------------------------------------------------ #
425
+
426
+ def forward(
427
+ self,
428
+ x: Tensor, # (B, R, C), may contain NaN/inf
429
+ y_train: Tensor, # (B, R_train) labels >= 0
430
+ num_columns: Optional[Tensor] = None, # (B,) valid (leading) columns per table
431
+ categorical_mask: Optional[Tensor] = None, # (B, C) bool
432
+ ) -> Tensor: # (B, R, Kr * D)
433
+ if not torch.is_grad_enabled():
434
+ return self.encode(x, y_train, num_columns, categorical_mask)[0]
435
+ B, R, C = x.shape
436
+ Rt, K = y_train.shape[1], self.num_readout
437
+ self._check_labels(y_train)
438
+ x, missing, _ = self.impute(x, Rt)
439
+ cells = self._embed(x, missing, num_columns, categorical_mask) # (B, R, C, D)
440
+ cells = cells + F.pad(self._label_emb(y_train), (0, 0, 0, R - Rt)).unsqueeze(2).to(cells.dtype)
441
+ key_len, key_mask = self._row_key_info(num_columns, C)
442
+ rope = self._rope(K + C)
443
+ readout = self.readout_tokens.to(cells.dtype).expand(B, R, K, self.dim)
444
+ last = len(self.col_blocks) - 1
445
+ if not (self.recompute and B * R * (K + C) * self.dim >= self.recompute_min_elems):
446
+ for i in range(last + 1):
447
+ cells, readout = self._layer(i, cells, readout, Rt, key_len, key_mask, rope)
448
+ return self.out_norm(readout).flatten(-2)
449
+
450
+ step = max(1, self.recompute_chunk_elems // (R * (K + C) * self.dim))
451
+ chunks = [slice(b, b + step) for b in range(0, B, step)]
452
+ per_table = lambda t, s: t[s] if isinstance(t, Tensor) and t.shape[0] == B else t # noqa: E731
453
+ for i in range(last + 1):
454
+ outs = [
455
+ checkpoint(self._layer, i, cells[s], readout[s], Rt, per_table(key_len, s),
456
+ per_table(key_mask, s), rope, use_reentrant=False)
457
+ for s in chunks
458
+ ]
459
+ readout = torch.cat([o[1] for o in outs])
460
+ cells = None if i == last else torch.cat([o[0] for o in outs])
461
+ return self.out_norm(readout).flatten(-2)
462
+
463
+ def _layer(self, i, cells, readout, train_size, key_len, key_mask, rope):
464
+ """Column then row attention of block i -> (cells, readout); the last block only updates
465
+ the readout tokens (cells is returned as None)."""
466
+ K = self.num_readout
467
+ cells = self._col_step(self.col_blocks[i], cells, train_size)
468
+ tokens = torch.cat([readout.to(cells.dtype), cells], dim=2) # (B, R, K + C, D)
469
+ row = self.row_blocks[i]
470
+ if i < len(self.row_blocks) - 1:
471
+ tokens = row(tokens, tokens, key_len, key_mask, rope)
472
+ readout, cells = tokens.split([K, tokens.shape[2] - K], dim=2)
473
+ return cells, readout
474
+ return None, row(tokens[:, :, :K], tokens, key_len, key_mask, rope)
475
+
476
+ @staticmethod
477
+ def _col_step(col: KumoInducedBlock, cells: Tensor, train_size: int) -> Tensor:
478
+ ct = cells.transpose(1, 2) # (B, C, R, D)
479
+ return col.read(ct, col.summarize(ct[:, :, :train_size])).transpose(1, 2)
480
+
481
+ # ------------------------------------------------------------------ #
482
+ # no-grad path / split inference
483
+ # ------------------------------------------------------------------ #
484
+
485
+ @torch.no_grad()
486
+ def encode(
487
+ self,
488
+ x: Tensor,
489
+ y_train: Optional[Tensor],
490
+ num_columns: Optional[Tensor] = None,
491
+ categorical_mask: Optional[Tensor] = None,
492
+ cache: Optional[dict] = None,
493
+ ):
494
+ """No-grad forward. Without `cache`, the first y_train.shape[1] rows are the context and the
495
+ returned cache holds what queries need later (impute means, per-block column summaries).
496
+ With `cache` (from a context-only call), every row of x is a query (y_train is ignored).
497
+ Returns (rows (B, R, Kr * D), cache)."""
498
+ B, R, C = x.shape
499
+ K, D = self.num_readout, self.dim
500
+ if cache is None:
501
+ Rt = y_train.shape[1]
502
+ self._check_labels(y_train)
503
+ x, missing, impute_mean = self.impute(x, Rt)
504
+ else:
505
+ Rt = 0
506
+ x, missing, impute_mean = self.impute(x, 0, cache["impute_mean"])
507
+ # Cell embedding in row chunks written straight into the block buffer: each row is embedded
508
+ # independently, and the full-size fp32 Fourier temporaries (B, R, C, G, F) plus a separate
509
+ # (B, R, C, D) cells tensor next to `buf` used to set the peak memory on wide/long tables.
510
+ cell_step = max(1, self.infer_chunk_elems // max(B * C * self.cell.num_freq.numel(), 1))
511
+ buf = None
512
+ for r in range(0, max(R, 1), cell_step):
513
+ cells = self.cell(x[:, r:r + cell_step], missing[:, r:r + cell_step], num_columns,
514
+ categorical_mask) # (B, r_chunk, C, D)
515
+ if buf is None:
516
+ buf = cells.new_empty(B, R, K + C, D)
517
+ buf[:, :, :K] = self.readout_tokens.to(buf.dtype)
518
+ buf[:, r:r + cell_step, K:] = cells
519
+ del cells
520
+ if Rt:
521
+ buf[:, :Rt, K:] += self._label_emb(y_train).unsqueeze(2).to(buf.dtype)
522
+ key_len, key_mask = self._row_key_info(num_columns, C)
523
+ rope = self._rope(K + C)
524
+
525
+ summaries = []
526
+ row_step = max(1, self.infer_chunk_elems // max(B * (K + C) * D, 1))
527
+ last = len(self.col_blocks) - 1
528
+ for i, (col, row) in enumerate(zip(self.col_blocks, self.row_blocks)):
529
+ if cache is None:
530
+ ctx = buf[:, :Rt, K:].transpose(1, 2) # (B, C, Rt, D)
531
+ col_step = max(1, self.infer_chunk_elems // max(B * Rt * D, 1))
532
+ summary = torch.cat([col.summarize(ctx[:, c:c + col_step]) for c in range(0, C, col_step)], dim=1)
533
+ else:
534
+ summary = cache["summaries"][i]
535
+ summaries.append(summary)
536
+ for r in range(0, R, row_step):
537
+ chunk = buf[:, r:r + row_step]
538
+ chunk[:, :, K:] = col.read(chunk[:, :, K:].transpose(1, 2), summary).transpose(1, 2)
539
+ if i < last:
540
+ chunk.copy_(row(chunk, chunk, key_len, key_mask, rope))
541
+ else:
542
+ chunk[:, :, :K] = row(chunk[:, :, :K], chunk, key_len, key_mask, rope)
543
+ rows = self.out_norm(buf[:, :, :K]).flatten(-2)
544
+ return rows, {"impute_mean": impute_mean, "summaries": summaries}
545
+
546
+ # ------------------------------------------------------------------ #
547
+ # streaming context encoding (very long contexts)
548
+ # ------------------------------------------------------------------ #
549
+
550
+ @staticmethod
551
+ def _online_summary(col: "KumoInducedBlock", key_len: int, chunks):
552
+ """col.summarize(all context cells) from an iterator of cell chunks (B, C, n, D), with the
553
+ inducing-point attention accumulated by online softmax (fp32) over the chunks. Mirrors
554
+ KumoBlock.forward(inducing_points, ctx, key_len) with LogScale query scaling; q/k are
555
+ rounded to the value dtype first, as _sdpa does."""
556
+ blk = col.inducing_block
557
+ D = blk.dim
558
+ w_q, w_kv = blk.qkv.weight.split([D, 2 * D])
559
+ b_q, b_kv = blk.qkv.bias.split([D, 2 * D])
560
+ m = l = acc = q = query = None
561
+ scale = blk.head_dim ** -0.5
562
+ for ct in chunks:
563
+ if q is None:
564
+ query = col.inducing_points.to(ct.dtype)
565
+ q = blk._heads(F.linear(blk.query_norm(query), w_q, b_q)) # (H, M, d)
566
+ q = blk.query_scaling(_head_norm(blk.q_head_norm, q), key_len)
567
+ k, v = (blk._heads(t) for t in F.linear(blk.kv_norm(ct), w_kv, b_kv).chunk(2, dim=-1))
568
+ k = _head_norm(blk.k_head_norm, k) # (B, C, H, n, d)
569
+ qf = q.to(v.dtype).float()
570
+ s = torch.matmul(qf, k.to(v.dtype).float().transpose(-1, -2)) * scale # (B, C, H, M, n)
571
+ del k
572
+ m_new = s.amax(-1) if m is None else torch.maximum(m, s.amax(-1))
573
+ p = torch.exp(s - m_new.unsqueeze(-1))
574
+ del s
575
+ pv = torch.matmul(p, v.float())
576
+ if m is None:
577
+ l, acc = p.sum(-1), pv
578
+ else:
579
+ corr = torch.exp(m - m_new)
580
+ l = l * corr + p.sum(-1)
581
+ acc = acc * corr.unsqueeze(-1) + pv
582
+ m = m_new
583
+ del p, pv, v
584
+ attn = (acc / l.unsqueeze(-1)).to(query.dtype) # (B, C, H, M, d)
585
+ x = query + blk.out(attn.transpose(-3, -2).flatten(-2))
586
+ return x + blk.mlp(x)
587
+
588
+ @torch.no_grad()
589
+ def encode_context_stream(self, x, y, write, num_columns=None, pre=None, chunk_elems=2**28,
590
+ summary_rows=None, generator=None):
591
+ """encode_context() for contexts whose (B, R, K + C, D) token tensor does not fit.
592
+
593
+ Rows interact only through the per-block column summaries (inducing points attending over
594
+ all context rows); given summaries 0..i-1, a row's cells entering block i depend on that
595
+ row alone. So summary i is computed in a streaming pass over the context rows that
596
+ re-embeds each row chunk and re-runs blocks 0..i-1 on it (online-softmax accumulation),
597
+ and a final pass runs all blocks per chunk with the finished summaries. Memory: one row
598
+ chunk of tokens; compute: 1 + sum_i i block passes over the summary rows instead of one.
599
+
600
+ x: (B, N, C) raw features (may hold NaN/inf); pre(x_chunk) -> float input of the encoder
601
+ (Kumo input norm) or None; y: (B, N) labels; write(s, e, rows) receives the (B, n, Kr * D)
602
+ output of rows [s, e). summary_rows: compute the summaries on that many randomly chosen
603
+ context rows instead of all (approximation; LogScale still uses the full row count).
604
+ Returns the encoder cache (impute means, summaries) for encode_queries()."""
605
+ B, N, C = x.shape
606
+ K, D = self.num_readout, self.dim
607
+ self._check_labels(y)
608
+ pre = pre if pre is not None else (lambda t: t.float())
609
+ step = max(1, chunk_elems // max(B * (K + C) * D, 1))
610
+ # Impute means: finite mean of the (normalized) context column, as impute() computes it.
611
+ tot = cnt = None
612
+ for s in range(0, N, step):
613
+ xc = pre(x[:, s:s + step])
614
+ ok = torch.isfinite(xc)
615
+ ts = torch.where(ok, xc, 0.0).sum(1, keepdim=True, dtype=torch.float64)
616
+ tc = ok.sum(1, keepdim=True)
617
+ tot, cnt = (ts, tc) if tot is None else (tot + ts, cnt + tc)
618
+ del xc, ok
619
+ impute_mean = (tot / cnt.clamp(min=1)).float() # (B, 1, C)
620
+ key_len, key_mask = self._row_key_info(num_columns, C)
621
+ rope = self._rope(K + C)
622
+ last = len(self.col_blocks) - 1
623
+
624
+ def tokens(rows):
625
+ if isinstance(rows, slice):
626
+ xc, yc = x[:, rows], y[:, rows]
627
+ else:
628
+ xc, yc = x.index_select(1, rows), y.index_select(1, rows)
629
+ xc = pre(xc)
630
+ missing = ~torch.isfinite(xc)
631
+ xc = torch.where(missing, impute_mean, xc)
632
+ cells = self.cell(xc, missing, num_columns, None) # (B, n, C, D)
633
+ buf = cells.new_empty(B, cells.shape[1], K + C, D)
634
+ buf[:, :, :K] = self.readout_tokens.to(buf.dtype)
635
+ buf[:, :, K:] = cells
636
+ del cells, xc, missing
637
+ buf[:, :, K:] += self._label_emb(yc).unsqueeze(2).to(buf.dtype)
638
+ return buf
639
+
640
+ def run_blocks(t, summaries, upto):
641
+ for i in range(upto):
642
+ col, row = self.col_blocks[i], self.row_blocks[i]
643
+ t[:, :, K:] = col.read(t[:, :, K:].transpose(1, 2), summaries[i]).transpose(1, 2)
644
+ if i < last:
645
+ t.copy_(row(t, t, key_len, key_mask, rope))
646
+ else:
647
+ t[:, :, :K] = row(t[:, :, :K], t, key_len, key_mask, rope)
648
+ return t
649
+
650
+ if summary_rows is not None and summary_rows < N:
651
+ idx = torch.randperm(N, device=x.device, generator=generator)[:summary_rows].sort().values
652
+ sum_chunks = [idx[s:s + step] for s in range(0, len(idx), step)]
653
+ else:
654
+ sum_chunks = [slice(s, min(N, s + step)) for s in range(0, N, step)]
655
+ # online-softmax scores are (B, C, H, M, n) fp32: sub-chunk the rows to bound them
656
+ blk0 = self.col_blocks[0].inducing_block
657
+ M = self.col_blocks[0].inducing_points.shape[0]
658
+ sub = max(1, (chunk_elems // 4) // max(B * C * blk0.num_heads * M, 1))
659
+
660
+ from firepfn.model.stream_infer import phase
661
+ summaries = []
662
+ for i in range(last + 1):
663
+ def chunks(i=i):
664
+ for rows in sum_chunks:
665
+ ct = run_blocks(tokens(rows), summaries, i)[:, :, K:].transpose(1, 2) # (B, C, n, D)
666
+ for a in range(0, ct.shape[2], sub):
667
+ yield ct[:, :, a:a + sub]
668
+ del ct
669
+ with phase(f"encoder summary pass {i}"):
670
+ summaries.append(self._online_summary(self.col_blocks[i], N, chunks()))
671
+ with phase("encoder final pass"):
672
+ for s in range(0, N, step):
673
+ t = run_blocks(tokens(slice(s, min(N, s + step))), summaries, last + 1)
674
+ write(s, min(N, s + step), self.out_norm(t[:, :, :K]).flatten(-2))
675
+ del t
676
+ return {"impute_mean": impute_mean, "summaries": summaries}
677
+
678
+ def encode_context(self, x, y, num_columns=None, categorical_mask=None):
679
+ """Labelled rows only. Returns (rows (B, N, Kr * D), cache)."""
680
+ return self.encode(x, y, num_columns, categorical_mask)
681
+
682
+ def encode_queries(self, x, cache, num_columns=None, categorical_mask=None):
683
+ """Unlabelled rows against an encode_context() cache. Returns (B, M, Kr * D)."""
684
+ return self.encode(x, None, num_columns, categorical_mask, cache=cache)[0]
685
+
686
+
687
+ def from_sdm_state_dict(state_dict: dict) -> dict:
688
+ """Renames an sdm Kumo-Tabular RowEmbedding state_dict (`model.row_embedding.state_dict()`,
689
+ or the `row_embedding.` entries of a released nvidia/Kumo-Tabular checkpoint with that prefix
690
+ stripped) to KumoTableEncoder's names. RoPE frequencies are dropped (fixed buffer here)."""
691
+ out = {}
692
+ for name, value in state_dict.items():
693
+ if name.endswith("inv_freq"):
694
+ continue
695
+ if name == "norm.weight":
696
+ name = "out_norm.weight"
697
+ name = (name.replace("readout_token", "readout_tokens")
698
+ .replace("cell_embedding.", "cell.")
699
+ .replace(".key_value_norm.", ".kv_norm.")
700
+ .replace(".attn.qkv_lin.", ".qkv.")
701
+ .replace(".attn.out_lin.", ".out.")
702
+ .replace(".attn.sdpa.query_scaling.", ".query_scaling."))
703
+ out[name] = value
704
+ return out