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,537 @@
1
+ # SPDX-License-Identifier: MIT AND Apache-2.0
2
+ # Copyright (c) 2024, Sukjun Hwang, Aakash Lahoti, Ratish Puduppully, Tri Dao, Albert Gu.
3
+ # Copyright (c) 2025-2026, the FirePFN authors (modifications).
4
+ #
5
+ # Hydra2: bidirectional SSM block built on the Mamba-3 SISO scan kernel.
6
+ # Derived from Hydra (https://github.com/goombalab/hydra, hydra.py, MIT License), which builds on
7
+ # Mamba-2 (https://github.com/state-spaces/mamba, Apache License 2.0). Modified by the FirePFN
8
+ # authors: Mamba-3 upgrades below, separate dt/A/trap projections, int32-safe gated norm, and
9
+ # memory-bounded segmented inference for very long contexts.
10
+ #
11
+ # Upgrades from Mamba-3:
12
+ # 1. Data-dependent A - A is no longer a fixed per-head scalar; instead a
13
+ # `dd_A` term is projected from the input, making A input-dependent.
14
+ # 2. Trapezoid gate - a `trap` term (sigmoid-gated) improves the numerical
15
+ # stability of the discretised integration step.
16
+ # 3. RoPE angles - rotary positional embeddings (controlled by
17
+ # `rope_fraction`) are woven directly into the SSM scan (FirePFN uses
18
+ # rope_fraction=0: rows are an exchangeable set).
19
+ #
20
+ # The bidirectionality is kept through the same batch-doubling trick as Hydra:
21
+ # both the forward sequence and a time-reversed copy are stacked on the batch
22
+ # dimension and processed in a single kernel call, then summed.
23
+
24
+ import math
25
+ import torch
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+
29
+ from einops import rearrange, repeat
30
+
31
+ try:
32
+ from mamba_ssm.ops.triton.layernorm_gated import RMSNorm as RMSNormGated
33
+ except ImportError:
34
+ RMSNormGated = None
35
+
36
+ _INT32_MAX = 2**31 - 1
37
+
38
+
39
+ def _gated_norm_int32_safe(norm, y, z):
40
+ """norm(y, z), split into row chunks when one call would overflow int32 offsets.
41
+
42
+ mamba_ssm's gated-RMSNorm Triton kernels (fwd and bwd) address rows as ``row * stride_row``
43
+ in int32. ``z`` is a strided view into the input projection, so its row stride is
44
+ d_in_proj, not d_inner; with ~1M context rows ``rows * stride`` passes 2**31 and the kernel
45
+ reads out of bounds (CUDA illegal memory access at ~1M context rows).
46
+ Each chunk is a separate autograd call, so the backward kernel stays in range too. Below the
47
+ limit this is exactly one call, as before.
48
+ """
49
+ N = y.shape[-1]
50
+ y2, z2 = y.reshape(-1, N), z.reshape(-1, N)
51
+ stride = max(y2.stride(0), z2.stride(0), N)
52
+ rows = (_INT32_MAX - stride) // stride # row * stride + col must stay < 2**31
53
+ if y2.shape[0] <= rows:
54
+ return norm(y, z)
55
+ out = torch.cat([norm(y2[i:i + rows], z2[i:i + rows]) for i in range(0, y2.shape[0], rows)])
56
+ return out.view(*y.shape[:-1], out.shape[-1])
57
+
58
+
59
+ # mamba_ssm's fused layer norm indexes rows in int32 (silently wrong beyond ~2.8M context rows);
60
+ # every model that builds Hydra2 blocks also runs those norms over the context.
61
+ from firepfn.model import int32_safe as _int32_safe
62
+ from firepfn.model.stream_infer import infer_segment_rows, use_segmented_inference
63
+ _int32_safe.patch()
64
+
65
+ # Mamba-3 SISO scan kernel (mamba-ssm >= 2.3.2 with Mamba-3).
66
+ from mamba_ssm.ops.triton.mamba3.mamba3_siso_combined import mamba3_siso_combined
67
+
68
+
69
+ class Hydra2(nn.Module):
70
+ """
71
+ Bidirectional Mamba-3 SISO block.
72
+
73
+ Key differences from Hydra (Mamba-2):
74
+ - `A_log` removed: A is now data-dependent (projected as `dd_A`).
75
+ - `trap` (trapezoid gate) added for stable integration.
76
+ - RoPE angles injected into the SSM scan via `rope_fraction`.
77
+ - `B_bias` / `C_bias` learned normalization biases for the K/Q paths.
78
+ - Uses `mamba3_siso_combined` instead of `mamba_chunk_scan_combined`.
79
+
80
+ Everything else — the conv1d, the batch-doubling for bidirectionality,
81
+ the causal roll, the data-dependent D skip, and the RMSNormGated output
82
+ gate — is unchanged from Hydra.
83
+ """
84
+
85
+ def __init__(
86
+ self,
87
+ d_model,
88
+ d_state=64,
89
+ d_conv=7,
90
+ conv_init=None,
91
+ expand=2,
92
+ headdim=64,
93
+ ngroups=1,
94
+ rope_fraction=0.5, # fraction of d_state used for RoPE angles
95
+ dt_min=0.001,
96
+ dt_max=0.1,
97
+ dt_init_floor=1e-4,
98
+ A_floor=1e-4, # minimum |A| enforced after data-dependent A
99
+ # Runtime clamp on softplus(dd_dt + dt_bias). Previously (0.0, 50.0) — 500x
100
+ # past dt_max=0.1's own init range, so dt was effectively unclamped in
101
+ # practice. At eval sequence lengths far beyond training (bptt 2048-4096),
102
+ # a handful of positions would push dt (and ADT = A*DT) into that unused
103
+ # headroom, overflowing the SSM scan to inf/nan by mid-network depth.
104
+ # Tightening this to actually match the init range keeps ADT bounded
105
+ # regardless of sequence length. Empirically: eliminates the inf/nan at
106
+ # 32k-100k context, at the cost of some accuracy on the lengths the model
107
+ # was trained on (its dt_bias/dd_dt weights were fit assuming headroom up
108
+ # to 50) — expected to recover with continued training under this clamp.
109
+ dt_limit=(0.0, 1.0),
110
+ learnable_init_states=False, # NOTE: not yet wired to Mamba-3 state tuple
111
+ activation="swish",
112
+ bias=False,
113
+ conv_bias=True,
114
+ chunk_size=64, # Mamba-3 default (vs 256 in Mamba-2)
115
+ layer_idx=None,
116
+ device=None,
117
+ dtype=None,
118
+ ):
119
+ factory_kwargs = {"device": device, "dtype": dtype}
120
+ super().__init__()
121
+
122
+ self.d_model = d_model
123
+ self.d_state = d_state
124
+ self.d_conv = d_conv
125
+ self.conv_init = conv_init
126
+ self.expand = expand
127
+ self.d_inner = self.expand * self.d_model
128
+ self.headdim = headdim
129
+ self.ngroups = ngroups
130
+ assert self.d_inner % self.headdim == 0
131
+ self.nheads = self.d_inner // self.headdim
132
+ self.rope_fraction = rope_fraction
133
+ self.A_floor = A_floor
134
+ self.dt_limit = dt_limit
135
+ self.activation = activation
136
+ self.chunk_size = chunk_size
137
+ self.layer_idx = layer_idx
138
+
139
+ # Number of RoPE angle scalars per position.
140
+ # Must be even (sin/cos pairs); derived from d_state * rope_fraction.
141
+ _num_raw = int(self.d_state * rope_fraction)
142
+ self.num_rope_angles = _num_raw - (_num_raw % 2)
143
+
144
+ # ------------------------------------------------------------------ #
145
+ # Input projection
146
+ #
147
+ # in_proj output layout: [z | xBC | angles]
148
+ #
149
+ # xBC = x + B_fw + C_fw + B_bw + C_bw
150
+ # = d_inner + 4 * ngroups * d_state (same layout as Hydra)
151
+ #
152
+ # angles (num_rope_angles) are shared; the backward pass receives the
153
+ # time-reversed angle sequence.
154
+ #
155
+ # dd_dt, dd_A, trap get their OWN separate Linear layers (dt_proj,
156
+ # A_proj, trap_proj below) rather than sharing rows of in_proj.
157
+ # Reason: under Muon, a 2-D weight matrix is orthogonalized as one
158
+ # coupled unit across all its output rows. dd_A's gradient is weak
159
+ # (it saturates against the A_floor clamp often) next to dd_dt's
160
+ # strong, always-active one; sharing a matrix let Muon's whitening
161
+ # suppress the dd_A rows almost to zero over training, collapsing
162
+ # Hydra2's "data-dependent A" into a near-constant value and pushing
163
+ # all input-dependent gating onto dt alone — which is what let dt
164
+ # drift toward its (previously unused) clamp ceiling at long
165
+ # sequences. Each gets its own matrix, and (like B_bias/C_bias
166
+ # below) is marked _no_weight_decay so it's optimized by AdamW
167
+ # rather than Muon at all — these are low-dimensional control
168
+ # signals, not the kind of large matrix Muon is meant for.
169
+ # ------------------------------------------------------------------ #
170
+ d_in_proj = (
171
+ self.d_inner # z – output gate
172
+ + self.d_inner # x – values (goes through conv)
173
+ + 4 * self.ngroups * self.d_state # B_fw, C_fw, B_bw, C_bw
174
+ + self.num_rope_angles # angles (shared)
175
+ )
176
+ self.in_proj = nn.Linear(self.d_model, d_in_proj, bias=bias, **factory_kwargs)
177
+
178
+ d_gate = 2 * self.nheads # fw + bw
179
+ self.dt_proj = nn.Linear(self.d_model, d_gate, bias=bias, **factory_kwargs)
180
+ self.A_proj = nn.Linear(self.d_model, d_gate, bias=bias, **factory_kwargs)
181
+ self.trap_proj = nn.Linear(self.d_model, d_gate, bias=bias, **factory_kwargs)
182
+ for proj in (self.dt_proj, self.A_proj, self.trap_proj):
183
+ proj.weight._no_weight_decay = True
184
+ if proj.bias is not None:
185
+ proj.bias._no_weight_decay = True
186
+
187
+ # Conv1d operates on x + both B/C directions (same as Hydra).
188
+ conv_dim = self.d_inner + 2 * (2 * self.ngroups * self.d_state)
189
+ self.conv1d = nn.Conv1d(
190
+ in_channels=conv_dim,
191
+ out_channels=conv_dim,
192
+ bias=conv_bias,
193
+ kernel_size=d_conv,
194
+ groups=conv_dim,
195
+ padding=d_conv // 2,
196
+ **factory_kwargs,
197
+ )
198
+ if self.conv_init is not None:
199
+ nn.init.uniform_(self.conv1d.weight, -self.conv_init, self.conv_init)
200
+
201
+ self.act = nn.SiLU()
202
+
203
+ # dt bias — shared between fw and bw (directional variation comes
204
+ # from the separate dd_dt_fw / dd_dt_bw projections).
205
+ dt = torch.exp(
206
+ torch.rand(self.nheads, **factory_kwargs)
207
+ * (math.log(dt_max) - math.log(dt_min))
208
+ + math.log(dt_min)
209
+ )
210
+ dt = torch.clamp(dt, min=dt_init_floor)
211
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
212
+ self.dt_bias = nn.Parameter(inv_dt)
213
+ self.dt_bias._no_weight_decay = True
214
+
215
+ # NOTE: A_log is removed. A is now fully data-dependent via dd_A.
216
+
217
+ # D skip + data-dependent scale (unchanged from Hydra).
218
+ self.D = nn.Parameter(torch.ones(self.nheads, device=device))
219
+ self.D._no_weight_decay = True
220
+ self.fc_D = nn.Linear(self.d_inner, self.nheads, bias=False, **factory_kwargs)
221
+
222
+ # Learned biases for B (K) and C (Q) — Mamba-3 addition.
223
+ # Shape: (ngroups, d_state) — one bias vector per SSM group.
224
+ # _no_weight_decay keeps these in the AdamW group even though they are
225
+ # 2-D: Muon's unit-magnitude orthogonalized updates would drive them
226
+ # away from zero at a fixed rate (≈ muon_lr per step) regardless of
227
+ # gradient magnitude, destabilising the SSM state transitions.
228
+ self.B_bias = nn.Parameter(torch.zeros(self.ngroups, self.d_state, **factory_kwargs))
229
+ self.B_bias._no_weight_decay = True
230
+ self.C_bias = nn.Parameter(torch.zeros(self.ngroups, self.d_state, **factory_kwargs))
231
+ self.C_bias._no_weight_decay = True
232
+
233
+ # Gated output normalisation (unchanged from Hydra).
234
+ assert RMSNormGated is not None, "mamba_ssm RMSNormGated is not available"
235
+ self.norm = RMSNormGated(
236
+ self.d_inner, eps=1e-5, norm_before_gate=True, **factory_kwargs
237
+ )
238
+
239
+ self.out_proj = nn.Linear(self.d_inner, self.d_model, bias=bias, **factory_kwargs)
240
+
241
+
242
+ # ---------------------------------------------------------------------- #
243
+ # Forward
244
+ # ---------------------------------------------------------------------- #
245
+
246
+ def forward(self, u, seq_idx=None):
247
+ """
248
+ u: (B, L, D)
249
+ Returns: same shape as u.
250
+ """
251
+ batch, seqlen, dim = u.shape
252
+ if seq_idx is None and use_segmented_inference(seqlen):
253
+ return self._forward_segmented(u, infer_segment_rows())
254
+
255
+ z_xBC_angles = self.in_proj(u) # (B, L, d_in_proj)
256
+
257
+ # ------------------------------------------------------------------ #
258
+ # 1. Split projection output; dd_dt/dd_A/trap come from their own
259
+ # dedicated projections (see __init__ comment) rather than a
260
+ # shared in_proj slice.
261
+ # ------------------------------------------------------------------ #
262
+ z, xBC, angles = torch.split(
263
+ z_xBC_angles,
264
+ [
265
+ self.d_inner,
266
+ self.d_inner + 2 * (2 * self.ngroups * self.d_state), # xBC
267
+ self.num_rope_angles,
268
+ ],
269
+ dim=-1,
270
+ )
271
+ dd_dt = self.dt_proj(u)
272
+ dd_A = self.A_proj(u)
273
+ trap = self.trap_proj(u)
274
+
275
+ # ------------------------------------------------------------------ #
276
+ # 2. Depthwise conv on x + B/C (same as Hydra)
277
+ # ------------------------------------------------------------------ #
278
+ xBC = self.act(self.conv1d(xBC.transpose(1, 2)).transpose(1, 2))
279
+
280
+ # ------------------------------------------------------------------ #
281
+ # 3. Split xBC → values (x) and SSM inputs (B, C per direction)
282
+ # ------------------------------------------------------------------ #
283
+ x, BC = torch.split(
284
+ xBC,
285
+ [self.d_inner, 2 * (2 * self.ngroups * self.d_state)],
286
+ dim=-1,
287
+ )
288
+ x_og = x # save for D skip connection
289
+
290
+ # ------------------------------------------------------------------ #
291
+ # 4. Batch-double: stack [forward | flipped-backward] on the batch dim
292
+ # ------------------------------------------------------------------ #
293
+ # Values: same sequence, time-flipped for bw.
294
+ x = torch.cat([x, torch.flip(x, dims=(1,))], dim=0) # (2B, L, d_inner)
295
+
296
+ # B/C: first half of BC is fw, second half is bw (time-flipped).
297
+ BC_fw = BC[:, :, :2 * self.ngroups * self.d_state]
298
+ BC_bw = torch.flip(BC[:, :, 2 * self.ngroups * self.d_state:], dims=(1,))
299
+ BC = torch.cat([BC_fw, BC_bw], dim=0) # (2B, L, 2*ngroups*d_state)
300
+ B, C = torch.split(
301
+ BC,
302
+ [self.ngroups * self.d_state, self.ngroups * self.d_state],
303
+ dim=-1,
304
+ )
305
+
306
+ # dd_dt: first nheads = fw, last nheads = bw (time-flipped).
307
+ dd_dt = torch.cat(
308
+ [dd_dt[:, :, :self.nheads],
309
+ torch.flip(dd_dt[:, :, self.nheads:], dims=(1,))],
310
+ dim=0,
311
+ ) # (2B, L, nheads)
312
+
313
+ # dd_A: same pattern.
314
+ dd_A = torch.cat(
315
+ [dd_A[:, :, :self.nheads],
316
+ torch.flip(dd_A[:, :, self.nheads:], dims=(1,))],
317
+ dim=0,
318
+ ) # (2B, L, nheads)
319
+
320
+ # trap: same pattern.
321
+ trap = torch.cat(
322
+ [trap[:, :, :self.nheads],
323
+ torch.flip(trap[:, :, self.nheads:], dims=(1,))],
324
+ dim=0,
325
+ ) # (2B, L, nheads)
326
+
327
+ # Angles: fw uses original positions 0..L-1,
328
+ # bw uses flipped positions L-1..0 so RoPE is consistent with
329
+ # the reversed sequence direction.
330
+ angles = torch.cat([angles, torch.flip(angles, dims=(1,))], dim=0) # (2B, L, num_rope_angles)
331
+
332
+ # ------------------------------------------------------------------ #
333
+ # 5. Compute DT, ADT (A*DT), and Trap
334
+ # Kernel expects shape (batch, nheads, seqlen) — note the transpose.
335
+ # ------------------------------------------------------------------ #
336
+ # DT: same as Mamba-2 (softplus of projected + bias).
337
+ # mamba3_siso_combined (unlike Mamba-2's mamba_chunk_scan_combined) has no
338
+ # built-in dt_limit clamp, so we apply it here on the caller side.
339
+ DT = F.softplus(dd_dt + self.dt_bias).to(torch.float32) # (2B, L, nheads)
340
+ DT = DT.clamp(min=self.dt_limit[0], max=self.dt_limit[1])
341
+
342
+ # A: data-dependent, always negative, magnitude >= A_floor. Was
343
+ # `.clamp(max=-self.A_floor)`, applied (per Python precedence, tighter than unary
344
+ # `-`) to softplus(dd_A) itself -- a value that's always >= 0 and therefore always
345
+ # greater than the negative bound -A_floor, so that clamp fired unconditionally and
346
+ # collapsed _A to a constant +A_floor, completely ignoring dd_A and with the wrong
347
+ # sign. `.clamp(min=self.A_floor)` enforces the intended magnitude floor on the
348
+ # (still-positive, still data-dependent) softplus output before negation.
349
+ _A = -F.softplus(dd_A.to(torch.float32)).clamp(min=self.A_floor) # (2B, L, nheads)
350
+ ADT = _A * DT # (2B, L, nheads)
351
+
352
+ # Transpose to (2B, nheads, L) for the kernel.
353
+ DT = DT.transpose(1, 2)
354
+ ADT = ADT.transpose(1, 2)
355
+ Trap = trap.transpose(1, 2).to(torch.float32)
356
+
357
+ # ------------------------------------------------------------------ #
358
+ # 6. Reshape tensors to mamba3_siso_combined signature
359
+ # ------------------------------------------------------------------ #
360
+ # V = x: (2B, L, nheads, headdim)
361
+ V = rearrange(x, "b l (h p) -> b l h p", p=self.headdim)
362
+
363
+ # Q = C, K = B: (2B, L, ngroups, d_state)
364
+ Q = rearrange(C, "b l (g n) -> b l g n", g=self.ngroups)
365
+ K = rearrange(B, "b l (g n) -> b l g n", g=self.ngroups)
366
+
367
+ # Angles: expand the shared angle vector across all heads.
368
+ # (2B, L, num_rope_angles) → (2B, L, nheads, num_rope_angles)
369
+ # mamba3_siso_combined requires at least 1 rope dimension (BLOCK_D > 0).
370
+ # When rope_fraction=0.0, pass dummy zero angles — zero rotation rate is
371
+ # an identity transform, so the SSM behaves as if no RoPE is applied.
372
+ if self.num_rope_angles == 0:
373
+ Angles = torch.zeros(
374
+ angles.shape[0], angles.shape[1], self.nheads, 2,
375
+ device=angles.device, dtype=torch.float32,
376
+ )
377
+ else:
378
+ Angles = angles.unsqueeze(2).expand(-1, -1, self.nheads, -1).to(torch.float32)
379
+
380
+ # ------------------------------------------------------------------ #
381
+ # 7. Mamba-3 SISO scan
382
+ # Z=None: gate is applied manually below via RMSNormGated so both
383
+ # the fw and bw outputs share the same gate after summing.
384
+ # D=None: skip connection handled manually via fc_D below.
385
+ # ------------------------------------------------------------------ #
386
+ y = mamba3_siso_combined(
387
+ Q=Q,
388
+ K=K,
389
+ V=V,
390
+ ADT=ADT,
391
+ DT=DT,
392
+ Trap=Trap,
393
+ Q_bias=self.C_bias.repeat_interleave(self.nheads // self.ngroups, dim=0), # (nheads, d_state)
394
+ K_bias=self.B_bias.repeat_interleave(self.nheads // self.ngroups, dim=0), # (nheads, d_state)
395
+ Angles=Angles,
396
+ D=None, # skip handled below
397
+ Z=None, # gate handled below via RMSNormGated
398
+ chunk_size=self.chunk_size,
399
+ Input_States=None,
400
+ return_final_states=False,
401
+ ) # (2B, L, nheads, headdim)
402
+
403
+ # ------------------------------------------------------------------ #
404
+ # 8. Causal shift + recombine (identical to Hydra)
405
+ # ------------------------------------------------------------------ #
406
+ y = rearrange(y, "b l h p -> b l (h p)") # (2B, L, d_inner)
407
+
408
+ # Shift by 1 so position i only attends to 0..i-1 via the recurrence.
409
+ y = torch.roll(y, shifts=1, dims=1)
410
+ y[:, 0, :] = 0.0
411
+
412
+ y_fw = y[:batch]
413
+ y_bw = torch.flip(y[batch:], dims=(1,))
414
+
415
+ # Data-dependent D skip (unchanged from Hydra).
416
+ D_scale = F.linear(x_og, self.fc_D.weight, bias=self.D) # (B, L, nheads)
417
+ skip = x_og * repeat(D_scale, "b l h -> b l (h p)", p=self.headdim)
418
+
419
+ y = y_fw + y_bw + skip # (B, L, d_inner)
420
+
421
+ # ------------------------------------------------------------------ #
422
+ # 9. Gated norm + output projection (unchanged from Hydra)
423
+ # ------------------------------------------------------------------ #
424
+ y = _gated_norm_int32_safe(self.norm, y, z)
425
+ out = self.out_proj(y)
426
+ return out
427
+
428
+ # ---------------------------------------------------------------------- #
429
+ # Memory-bounded inference over very long sequences
430
+ # ---------------------------------------------------------------------- #
431
+
432
+ def _segment_inputs(self, u, s, e):
433
+ """Per-position quantities for rows [s, e) of u, computed from rows [s-p, e+p) so the
434
+ symmetric depthwise conv (kernel d_conv, padding p = d_conv // 2) sees its real
435
+ neighbours across segment boundaries (zero padding only at the true sequence ends)."""
436
+ L = u.shape[1]
437
+ p = self.d_conv // 2
438
+ hs, he = max(0, s - p), min(L, e + p)
439
+ z_xBC_angles = self.in_proj(u[:, hs:he])
440
+ z, xBC, angles = torch.split(
441
+ z_xBC_angles,
442
+ [self.d_inner, self.d_inner + 2 * (2 * self.ngroups * self.d_state), self.num_rope_angles],
443
+ dim=-1,
444
+ )
445
+ xBC = self.act(self.conv1d(xBC.transpose(1, 2)).transpose(1, 2))
446
+ a, b = s - hs, s - hs + (e - s)
447
+ z, xBC, angles = z[:, a:b], xBC[:, a:b], angles[:, a:b]
448
+ x, BC = torch.split(xBC, [self.d_inner, 2 * (2 * self.ngroups * self.d_state)], dim=-1)
449
+ us = u[:, s:e]
450
+ return dict(z=z, x=x, BC=BC, angles=angles,
451
+ dd_dt=self.dt_proj(us), dd_A=self.A_proj(us), trap=self.trap_proj(us))
452
+
453
+ def _scan_direction(self, inp, direction, state):
454
+ """One direction of the bidirectional scan over one segment (time-reversed for 'bw'),
455
+ continuing from `state` (None at the sequence start). Mirrors forward() steps 3-7 for
456
+ one half of the doubled batch. Returns (y in scan order, final state)."""
457
+ g = 2 * self.ngroups * self.d_state
458
+ h = self.nheads
459
+ if direction == "fw":
460
+ BC, sl = inp["BC"][..., :g], slice(None, h)
461
+ else:
462
+ BC, sl = inp["BC"][..., g:], slice(h, None)
463
+ x, angles = inp["x"], inp["angles"]
464
+ dd_dt, dd_A, trap = inp["dd_dt"][..., sl], inp["dd_A"][..., sl], inp["trap"][..., sl]
465
+ if direction == "bw":
466
+ x, BC, angles, dd_dt, dd_A, trap = (torch.flip(t, dims=(1,)) for t in (x, BC, angles, dd_dt, dd_A, trap))
467
+ B, C = torch.split(BC, [self.ngroups * self.d_state, self.ngroups * self.d_state], dim=-1)
468
+ DT = F.softplus(dd_dt + self.dt_bias).to(torch.float32)
469
+ DT = DT.clamp(min=self.dt_limit[0], max=self.dt_limit[1])
470
+ _A = -F.softplus(dd_A.to(torch.float32)).clamp(min=self.A_floor)
471
+ ADT = (_A * DT).transpose(1, 2)
472
+ DT = DT.transpose(1, 2)
473
+ Trap = trap.transpose(1, 2).to(torch.float32)
474
+ V = rearrange(x, "b l (h p) -> b l h p", p=self.headdim)
475
+ Q = rearrange(C, "b l (g n) -> b l g n", g=self.ngroups)
476
+ K = rearrange(B, "b l (g n) -> b l g n", g=self.ngroups)
477
+ if self.num_rope_angles == 0:
478
+ Angles = torch.zeros(angles.shape[0], angles.shape[1], self.nheads, 2,
479
+ device=angles.device, dtype=torch.float32)
480
+ else:
481
+ Angles = angles.unsqueeze(2).expand(-1, -1, self.nheads, -1).to(torch.float32)
482
+ y, *final = mamba3_siso_combined(
483
+ Q=Q, K=K, V=V, ADT=ADT, DT=DT, Trap=Trap,
484
+ Q_bias=self.C_bias.repeat_interleave(self.nheads // self.ngroups, dim=0),
485
+ K_bias=self.B_bias.repeat_interleave(self.nheads // self.ngroups, dim=0),
486
+ Angles=Angles, D=None, Z=None, chunk_size=self.chunk_size,
487
+ Input_States=state, return_final_states=True,
488
+ )
489
+ return rearrange(y, "b l h p -> b l (h p)"), tuple(final)
490
+
491
+ @torch.no_grad()
492
+ def _forward_segmented(self, u, seg):
493
+ """forward(u) without gradients, in sequence segments of `seg` rows.
494
+
495
+ Same result as forward() up to float rounding, but the large per-position
496
+ intermediates (projections, both scan directions, gate, norm) exist for one segment at a
497
+ time. With the post-scan roll, the unsegmented output at position i is
498
+ norm(fw[i-1] + bw[i+1] + skip[i], z[i]) @ out_proj
499
+ where fw/bw are the forward / backward scan outputs at original positions (zero outside
500
+ the sequence). Pass 1 runs the forward scan over segments in order, carrying the Mamba-3
501
+ state (angle, SSM, K, V), and writes fw[i-1] into a (B, L, d_inner) buffer. Pass 2 runs
502
+ the backward scan over segments in reverse order, adds bw[i+1], and -- since every
503
+ position of the current segment is then complete -- applies skip, gated norm and
504
+ out_proj for that segment.
505
+ """
506
+ Bsz, L, _ = u.shape
507
+ ysum = out = None
508
+ state = None
509
+ for s in range(0, L, seg):
510
+ e = min(L, s + seg)
511
+ inp = self._segment_inputs(u, s, e)
512
+ yf, state = self._scan_direction(inp, "fw", state)
513
+ if ysum is None:
514
+ ysum = torch.zeros(Bsz, L, self.d_inner, device=u.device, dtype=yf.dtype)
515
+ hi = min(e + 1, L)
516
+ ysum[:, s + 1:hi] = yf[:, :hi - (s + 1)]
517
+ del inp, yf
518
+ state = None
519
+ starts = list(range(0, L, seg))
520
+ for s in reversed(starts):
521
+ e = min(L, s + seg)
522
+ inp = self._segment_inputs(u, s, e)
523
+ yb, state = self._scan_direction(inp, "bw", state)
524
+ yb = torch.flip(yb, dims=(1,)) # back to original order: bw[s:e]
525
+ lo = max(s - 1, 0)
526
+ ysum[:, lo:e - 1] += yb[:, lo - s + 1:]
527
+ x_og = inp["x"]
528
+ D_scale = F.linear(x_og, self.fc_D.weight, bias=self.D)
529
+ skip = x_og * repeat(D_scale, "b l h -> b l (h p)", p=self.headdim)
530
+ y = ysum[:, s:e] + skip
531
+ y = _gated_norm_int32_safe(self.norm, y, inp["z"])
532
+ o = self.out_proj(y)
533
+ if out is None:
534
+ out = torch.empty(Bsz, L, o.shape[-1], device=u.device, dtype=o.dtype)
535
+ out[:, s:e] = o
536
+ del inp, yb, y, o, skip
537
+ return out
@@ -0,0 +1,122 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """32-bit indexing guards for kernels that FirePFN runs over the full context at inference.
4
+
5
+ See _patch_torch_layernorm (torch.nn.LayerNorm > 2**32 elements) and, below, mamba_ssm's fused
6
+ layer norm.
7
+
8
+ mamba_ssm's fused layer norm (`mamba_ssm.ops.triton.layer_norm._layer_norm_fwd`, used by every
9
+ HydraBlock's pre-norm / fused add+norm, RMSNorm modules and the backbone's final norm_f) addresses
10
+ rows as ``row * stride_x_row`` with ``row = tl.program_id(0)`` in int32. On a (N, 768) context
11
+ that overflows from row 2**31 / 768 ~ 2.8M on: those rows silently read and write the wrong
12
+ memory -- finite garbage at 3-4M context rows (AUC barely moved, since the first 2.8M rows were
13
+ intact), garbage blowing up to NaN predictions at 6M.
14
+
15
+ patch() wraps _layer_norm_fwd so calls whose ``rows * max(row strides)`` would reach 2**31 run
16
+ over row chunks written into preallocated outputs. Below that it is the original single call.
17
+ Only the inference configuration is chunked (no dropout / x1 / rowscale / weight1); anything
18
+ else at that size raises instead of silently corrupting.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import torch
23
+
24
+ _INT32_MAX = 2**31 - 1
25
+ _patched = False
26
+
27
+
28
+ def _rows_per_chunk(*tensors):
29
+ stride = max([t.stride(0) for t in tensors if t is not None] + [1])
30
+ n = max([t.shape[-1] for t in tensors if t is not None] + [1])
31
+ return max(1, (_INT32_MAX - n) // max(stride, n))
32
+
33
+
34
+ def _make_chunked(orig):
35
+ def _layer_norm_fwd(x, weight, bias, eps, residual=None, x1=None, weight1=None, bias1=None,
36
+ dropout_p=0.0, rowscale=None, out_dtype=None, residual_dtype=None,
37
+ is_rms_norm=False, return_dropout_mask=False, **kw):
38
+ M = x.shape[0]
39
+ rows = _rows_per_chunk(x, residual)
40
+ args = dict(x1=x1, weight1=weight1, bias1=bias1, dropout_p=dropout_p, rowscale=rowscale,
41
+ out_dtype=out_dtype, residual_dtype=residual_dtype, is_rms_norm=is_rms_norm,
42
+ return_dropout_mask=return_dropout_mask, **kw)
43
+ if M <= rows:
44
+ return orig(x, weight, bias, eps, residual=residual, **args)
45
+ if x1 is not None or weight1 is not None or rowscale is not None or dropout_p > 0.0:
46
+ raise RuntimeError(
47
+ f"mamba_ssm layer norm over {M} rows would overflow int32 offsets, and the "
48
+ "row-chunked fallback (firepfn.model.int32_safe) only covers the inference "
49
+ "configuration (no dropout / x1 / rowscale / weight1)")
50
+ y = mean = rstd = residual_out = None
51
+ aliases_x = False
52
+ for s in range(0, M, rows):
53
+ e = min(M, s + rows)
54
+ xs = x[s:e]
55
+ ys, _, ms, rs, ros, *_ = orig(xs, weight, bias, eps,
56
+ residual=None if residual is None else residual[s:e], **args)
57
+ if y is None:
58
+ y = torch.empty(M, ys.shape[1], device=x.device, dtype=ys.dtype)
59
+ rstd = torch.empty(M, device=x.device, dtype=rs.dtype)
60
+ mean = None if ms is None else torch.empty(M, device=x.device, dtype=ms.dtype)
61
+ aliases_x = ros is xs
62
+ if not aliases_x:
63
+ residual_out = torch.empty(M, ros.shape[1], device=x.device, dtype=ros.dtype)
64
+ y[s:e] = ys
65
+ rstd[s:e] = rs
66
+ if mean is not None:
67
+ mean[s:e] = ms
68
+ if not aliases_x:
69
+ residual_out[s:e] = ros
70
+ del ys, ros
71
+ return y, None, mean, rstd, (x if aliases_x else residual_out), None, None, None
72
+
73
+ _layer_norm_fwd._firepfn_int32_safe = True
74
+ return _layer_norm_fwd
75
+
76
+
77
+ def _patch_torch_layernorm():
78
+ """torch.nn.LayerNorm (CUDA, torch 2.9.1) is wrong on one tensor of more than 2**32 elements:
79
+ on (6M, 768) the rows past 2**32 / 768 ~ 5.59M come out wrong and the overflowing writes wrap
80
+ onto the first rows. FirePFN's block norms, norm_f and
81
+ the cross-attention's norm_kv run over all context rows, which gave NaN predictions at 6M.
82
+ Without gradients, inputs of >= 2**31 elements are normalized in row chunks instead."""
83
+ import torch.nn as nn
84
+ import torch.nn.functional as F
85
+ if getattr(nn.LayerNorm.forward, "_firepfn_int32_safe", False):
86
+ return
87
+ orig = nn.LayerNorm.forward
88
+
89
+ def forward(self, input):
90
+ if torch.is_grad_enabled() or input.numel() < 2**31:
91
+ return orig(self, input)
92
+ n = 1
93
+ for s in self.normalized_shape:
94
+ n *= s
95
+ flat = input.reshape(-1, n)
96
+ out = torch.empty_like(flat)
97
+ rows = max(1, (2**31 - 1) // n)
98
+ for s in range(0, flat.shape[0], rows):
99
+ out[s:s + rows] = F.layer_norm(flat[s:s + rows].view(-1, *self.normalized_shape),
100
+ self.normalized_shape, self.weight, self.bias,
101
+ self.eps).view(-1, n)
102
+ return out.view(input.shape)
103
+
104
+ forward._firepfn_int32_safe = True
105
+ nn.LayerNorm.forward = forward
106
+
107
+
108
+ def patch() -> bool:
109
+ """Apply once per process. Returns True if mamba_ssm's layer norm was patched."""
110
+ global _patched
111
+ if _patched:
112
+ return False
113
+ _patched = True
114
+ _patch_torch_layernorm()
115
+ try:
116
+ import mamba_ssm.ops.triton.layer_norm as ln
117
+ except ImportError:
118
+ return False
119
+ if getattr(ln._layer_norm_fwd, "_firepfn_int32_safe", False):
120
+ return False
121
+ ln._layer_norm_fwd = _make_chunked(ln._layer_norm_fwd)
122
+ return True