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,568 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """In-place, memory-bounded context encoding for very long contexts (no-grad inference only).
4
+
5
+ The backbone (pre-norm residual blocks, one mixer each, no MLP) computes
6
+
7
+ r_0 = x, r_k = r_{k-1} + mixer_k(LN_k(r_{k-1})), out = LN_f(r_K)
8
+
9
+ (the block's `residual = hidden + residual` is exactly this). `backbone_inplace` runs it on ONE
10
+ (B, L, D) buffer that holds r and is updated in place, segment by segment: every mixer reads
11
+ LN_k(r_{k-1}) one segment at a time (the norm is row-local) and adds its output straight into the
12
+ buffer. The only full-length tensor is the buffer itself; everything else is per segment.
13
+
14
+ The mixers' existing segmented paths (hydra2._forward_segmented etc.) already bound the per-segment
15
+ temporaries but still materialize full-length inputs/outputs; the versions here differ in that:
16
+ - inputs come from `src(s, e)` (LN of the buffer rows) instead of a full-length tensor,
17
+ - outputs are added into the buffer as soon as no later read needs the old rows,
18
+ - the bidirectional scans (Hydra2, GatedDeltaNet) no longer keep a full-length forward-output
19
+ buffer for the backward pass: pass 1 stores only the forward state at each segment start
20
+ (plus the segment's last forward output row); pass 2, going backwards, recomputes the
21
+ segment's forward scan from that state. ~1 extra forward scan per segment.
22
+ Arithmetic per position follows the original paths (same dtypes, same order of the fw+bw add), so
23
+ results match them up to kernel nondeterminism.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import os
28
+ import warnings
29
+
30
+ import torch
31
+ import torch.nn.functional as F
32
+ from einops import repeat
33
+
34
+
35
+ def infer_segment_rows() -> int:
36
+ """Sequence-segment length for memory-bounded inference over very long contexts.
37
+
38
+ Without gradients, the backbone mixers (Hydra2, GatedDeltaNetBranch, RowLinearAttentionBranch)
39
+ process sequences longer than this in segments, carrying the recurrent state (scans) or the
40
+ global sums (linear attention) across segments; a mixer's transient memory is then bounded by
41
+ one segment instead of growing with the context. Override with FIREPFN_INFER_SEG_ROWS; 0
42
+ disables.
43
+ """
44
+ return int(os.environ.get("FIREPFN_INFER_SEG_ROWS", 262144))
45
+
46
+
47
+ def use_segmented_inference(seqlen: int) -> bool:
48
+ seg = infer_segment_rows()
49
+ return seg > 0 and seqlen > seg and not torch.is_grad_enabled()
50
+
51
+
52
+ def stream_ctx_rows() -> int:
53
+ """Contexts longer than this are encoded by the streaming path; 0 disables it."""
54
+ return int(os.environ.get("FIREPFN_STREAM_CTX_ROWS", 262144))
55
+
56
+
57
+ def stream_chunk_elems() -> int:
58
+ """Element budget of one encoder row chunk's (B, n, K + C, D) token tensor."""
59
+ return int(os.environ.get("FIREPFN_STREAM_CHUNK_ELEMS", 2**30))
60
+
61
+
62
+ def stream_summary_rows():
63
+ """If set, the encoder's column summaries use this many random context rows (approximation)."""
64
+ v = os.environ.get("FIREPFN_STREAM_SUMMARY_ROWS")
65
+ return int(v) if v else None
66
+
67
+
68
+ class phase:
69
+ """`with phase("name"):` prints synchronized wall time and peak memory of the block when
70
+ FIREPFN_STREAM_PROFILE=1 (no-op otherwise)."""
71
+
72
+ def __init__(self, name):
73
+ self.name = name
74
+ self.on = os.environ.get("FIREPFN_STREAM_PROFILE") == "1"
75
+
76
+ def __enter__(self):
77
+ if self.on:
78
+ import time
79
+ torch.cuda.synchronize()
80
+ self.t0 = time.perf_counter()
81
+ return self
82
+
83
+ def __exit__(self, *exc):
84
+ if self.on:
85
+ import time
86
+ torch.cuda.synchronize()
87
+ print(f"[stream] {self.name:28s} {time.perf_counter() - self.t0:8.2f} s "
88
+ f"alloc {torch.cuda.memory_allocated() / 2**30:6.1f} GB peak {torch.cuda.max_memory_allocated() / 2**30:6.1f} GB",
89
+ flush=True)
90
+ return False
91
+
92
+
93
+ # Which streaming paths the context-cache builds since the last reset_path_stats() took (read by
94
+ # the runtime benchmark, firepfn.eval.runtime): any_stream = the streaming path ran at all,
95
+ # token_recompute = the encoder could not keep its full token buffer and recomputed per summary
96
+ # pass (KumoTableEncoder.encode_context_stream), host_offload = the context buffer was kept in
97
+ # host memory (host_buffer_gib: its size).
98
+ _PATH_STATS = {}
99
+
100
+
101
+ def reset_path_stats():
102
+ _PATH_STATS.clear()
103
+ _PATH_STATS.update(any_stream=False, token_recompute=False, host_offload=False,
104
+ host_buffer_gib=float("nan"))
105
+
106
+
107
+ def path_stats() -> dict:
108
+ return dict(_PATH_STATS)
109
+
110
+
111
+ def _note_path(**flags):
112
+ if not _PATH_STATS:
113
+ reset_path_stats()
114
+ _PATH_STATS["any_stream"] = True
115
+ for k, v in flags.items():
116
+ _PATH_STATS[k] = (_PATH_STATS[k] or v) if isinstance(v, bool) else v
117
+
118
+
119
+ def token_buffer_fits(nbytes: int) -> bool:
120
+ """Whether the streaming context path can afford the encoder's full token buffer (nbytes)
121
+ instead of recomputing it per summary pass. FIREPFN_STREAM_TOKEN_BUDGET_GB sets the budget
122
+ explicitly (0 = always recompute); otherwise it is the memory still free for this process --
123
+ device free memory, or FIREPFN_GPU_CAP_GB (an emulated smaller card) minus what is allocated
124
+ -- less a margin for the encoder/backbone working sets."""
125
+ v = os.environ.get("FIREPFN_STREAM_TOKEN_BUDGET_GB")
126
+ if v is not None and v != "":
127
+ return nbytes <= float(v) * 2**30
128
+ allocated = torch.cuda.memory_allocated()
129
+ free_dev, _ = torch.cuda.mem_get_info()
130
+ free = free_dev + torch.cuda.memory_reserved() - allocated
131
+ cap = os.environ.get("FIREPFN_GPU_CAP_GB")
132
+ if cap:
133
+ free = min(free, float(cap) * 2**30 - allocated)
134
+ return nbytes * 1.1 + 12 * 2**30 <= free
135
+
136
+
137
+ def offload_mode() -> str:
138
+ """FIREPFN_STREAM_OFFLOAD: where the streaming path keeps its (B, N, D) fp32 context buffer.
139
+ "auto" (default): host memory when the buffer plus a working-set margin does not fit in the
140
+ free GPU memory; "1": always host; "0": always GPU."""
141
+ return os.environ.get("FIREPFN_STREAM_OFFLOAD", "auto").strip().lower()
142
+
143
+
144
+ def offload_margin_bytes() -> int:
145
+ """GPU memory kept free for the encoder / backbone / cross-attention working sets when "auto"
146
+ decides whether the context buffer stays on the GPU (FIREPFN_STREAM_OFFLOAD_MARGIN_GB, 40)."""
147
+ return int(float(os.environ.get("FIREPFN_STREAM_OFFLOAD_MARGIN_GB", 40)) * 2**30)
148
+
149
+
150
+ def _free_gpu_bytes() -> int:
151
+ allocated = torch.cuda.memory_allocated()
152
+ free_dev, _ = torch.cuda.mem_get_info()
153
+ free = free_dev + torch.cuda.memory_reserved() - allocated
154
+ cap = os.environ.get("FIREPFN_GPU_CAP_GB")
155
+ if cap:
156
+ free = min(free, int(float(cap) * 2**30) - allocated)
157
+ return free
158
+
159
+
160
+ class HostBuffer:
161
+ """A (B, L, D) buffer in (page-locked) host memory that the streaming code indexes like a
162
+ device tensor: `buf[:, s:e]` returns a device copy of those rows, `buf[:, s:e] = t` writes
163
+ them back, and `buf[:, s:e] += t` (Python: get, add on the device, set) updates them. Every
164
+ access in stream_infer / FirePFN streaming goes through one row range at a time, so the
165
+ device only ever holds one segment / key chunk of the buffer. Copies are synchronous, so
166
+ the read-before-write order of the streamed mixers is kept as is; values are bit-identical
167
+ to the device buffer (fp32 in, fp32 out, same arithmetic on the device).
168
+
169
+ The memory is pinned with cudaHostRegister instead of torch's pinned allocator, which rounds
170
+ a block up to the next power of two (a 366 GiB buffer would take 512 GiB). The driver
171
+ rejects a single registration above 512 GiB, and a copy may not span two registrations, so
172
+ the rows are kept in separate pieces of at most FIREPFN_STREAM_OFFLOAD_PIN_CHUNK_GB (default
173
+ 256) GiB, each registered on its own, and an access that crosses a piece boundary is split
174
+ there. If any registration fails, the buffer stays pageable. Set FIREPFN_STREAM_OFFLOAD_PIN=0
175
+ to keep it pageable (slower copies)."""
176
+
177
+ def __init__(self, shape, device, dtype=torch.float32):
178
+ B, L, D = shape
179
+ self.device = torch.device(device)
180
+ self.dtype = dtype
181
+ self.shape = torch.Size(shape)
182
+ chunk_gb = float(os.environ.get("FIREPFN_STREAM_OFFLOAD_PIN_CHUNK_GB", "256"))
183
+ row_bytes = max(1, B * D * torch.tensor([], dtype=dtype).element_size())
184
+ rows = max(1, int(chunk_gb * 2**30) // row_bytes)
185
+ self.starts = list(range(0, L, rows)) or [0]
186
+ self.pieces = [torch.empty(B, min(rows, L - s), D, dtype=dtype) for s in self.starts]
187
+ self._registered = [] # pieces registered with cudaHostRegister
188
+ if os.environ.get("FIREPFN_STREAM_OFFLOAD_PIN", "1") != "0" and L > 0:
189
+ self._register()
190
+
191
+ def _register(self):
192
+ cudart = torch.cuda.cudart()
193
+ for t in self.pieces:
194
+ err = cudart.cudaHostRegister(t.data_ptr(), t.numel() * t.element_size(), 0)
195
+ if int(err) != 0: # not cudaSuccess: undo, clear the error, stay pageable
196
+ _clear_cuda_error()
197
+ self._unregister()
198
+ nbytes = sum(p.numel() * p.element_size() for p in self.pieces)
199
+ warnings.warn(f"FirePFN: could not pin the {nbytes / 2**30:.1f} GiB host context "
200
+ f"buffer ({err}); using pageable memory (slower copies)")
201
+ return
202
+ self._registered.append(t)
203
+
204
+ def _unregister(self):
205
+ cudart = torch.cuda.cudart()
206
+ for t in self._registered:
207
+ cudart.cudaHostUnregister(t.data_ptr())
208
+ self._registered = []
209
+
210
+ @property
211
+ def pinned(self) -> bool:
212
+ return bool(self._registered)
213
+
214
+ def _parts(self, key):
215
+ """(piece, start, end, offset in the requested range) for `buf[:, s:e]`."""
216
+ if not (isinstance(key, tuple) and len(key) == 2 and key[0] == slice(None)
217
+ and isinstance(key[1], slice) and key[1].step in (None, 1)):
218
+ raise TypeError(f"HostBuffer supports buf[:, s:e] only, got {key!r}")
219
+ s, e, _ = key[1].indices(self.shape[1])
220
+ out = []
221
+ for p0, t in zip(self.starts, self.pieces):
222
+ a, b = max(s, p0), min(e, p0 + t.shape[1])
223
+ if a < b:
224
+ out.append((t, a - p0, b - p0, a - s))
225
+ return out, max(0, e - s)
226
+
227
+ def __getitem__(self, key):
228
+ parts, n = self._parts(key)
229
+ if len(parts) == 1:
230
+ t, a, b, _ = parts[0]
231
+ return t[:, a:b].to(self.device)
232
+ if not parts:
233
+ return torch.empty(self.shape[0], n, self.shape[2], dtype=self.dtype, device=self.device)
234
+ return torch.cat([t[:, a:b].to(self.device) for t, a, b, _ in parts], dim=1)
235
+
236
+ def __setitem__(self, key, value):
237
+ parts, _ = self._parts(key)
238
+ for t, a, b, o in parts:
239
+ t[:, a:b].copy_(value[:, o:o + (b - a)])
240
+
241
+ def __del__(self):
242
+ if getattr(self, "_registered", None):
243
+ try:
244
+ self._unregister()
245
+ except Exception:
246
+ pass
247
+
248
+
249
+ def _clear_cuda_error():
250
+ """Reset the runtime's last-error state after a failed cudaHostRegister, which would
251
+ otherwise be reported by the next, unrelated CUDA call."""
252
+ fn = getattr(torch.cuda.cudart(), "cudaGetLastError", None)
253
+ if fn is not None:
254
+ fn()
255
+ return
256
+ import ctypes
257
+ try:
258
+ ctypes.CDLL("libcudart.so.12").cudaGetLastError()
259
+ except OSError:
260
+ pass
261
+
262
+
263
+ def context_buffer(shape, device):
264
+ """The streaming path's (B, N, D) fp32 context buffer: on the device, or a HostBuffer
265
+ (offload_mode())."""
266
+ mode = offload_mode()
267
+ nbytes = 4
268
+ for n in shape:
269
+ nbytes *= int(n)
270
+ host = mode in ("1", "true", "host") or (
271
+ mode == "auto" and torch.device(device).type == "cuda"
272
+ and nbytes + offload_margin_bytes() > _free_gpu_bytes())
273
+ if host:
274
+ _note_path(host_offload=True, host_buffer_gib=round(nbytes / 2**30, 1))
275
+ with phase(f"host context buffer ({nbytes / 2**30:.1f} GiB)"):
276
+ return HostBuffer(shape, device)
277
+ _note_path()
278
+ return torch.empty(shape, device=device, dtype=torch.float32)
279
+
280
+
281
+ def query_chunk_rows() -> int:
282
+ """predict_from_cache processes query rows in chunks of this size; 0 disables chunking."""
283
+ return int(os.environ.get("FIREPFN_QUERY_CHUNK_ROWS", 16384))
284
+
285
+
286
+ def _clone_state(st):
287
+ if st is None:
288
+ return None
289
+ if isinstance(st, torch.Tensor):
290
+ return st.clone()
291
+ if isinstance(st, dict):
292
+ return {k: _clone_state(v) for k, v in st.items()}
293
+ if isinstance(st, (tuple, list)):
294
+ return type(st)(_clone_state(v) for v in st)
295
+ return st
296
+
297
+
298
+ # ---------------------------------------------------------------------- #
299
+ # Hydra2 (bidirectional Mamba-3 SISO scan)
300
+ # ---------------------------------------------------------------------- #
301
+
302
+ def _hydra2_inputs(m, src, L, s, e):
303
+ """hydra2._segment_inputs with the input rows taken from src (halo for the symmetric conv)."""
304
+ p = m.d_conv // 2
305
+ hs, he = max(0, s - p), min(L, e + p)
306
+ uh = src(hs, he)
307
+ z_xBC_angles = m.in_proj(uh)
308
+ z, xBC, angles = torch.split(
309
+ z_xBC_angles,
310
+ [m.d_inner, m.d_inner + 2 * (2 * m.ngroups * m.d_state), m.num_rope_angles],
311
+ dim=-1,
312
+ )
313
+ xBC = m.act(m.conv1d(xBC.transpose(1, 2)).transpose(1, 2))
314
+ a, b = s - hs, s - hs + (e - s)
315
+ z, xBC, angles = z[:, a:b], xBC[:, a:b], angles[:, a:b]
316
+ x, BC = torch.split(xBC, [m.d_inner, 2 * (2 * m.ngroups * m.d_state)], dim=-1)
317
+ us = uh[:, a:b]
318
+ return dict(z=z, x=x, BC=BC, angles=angles,
319
+ dd_dt=m.dt_proj(us), dd_A=m.A_proj(us), trap=m.trap_proj(us))
320
+
321
+
322
+ @torch.no_grad()
323
+ def hydra2_stream(m, src, buf, seg):
324
+ from firepfn.model.hydra2 import _gated_norm_int32_safe
325
+ L = buf.shape[1]
326
+ starts = list(range(0, L, seg))
327
+ fw_state_at, fw_last = {}, {}
328
+ state = None
329
+ for s in starts: # pass 1: forward states only
330
+ e = min(L, s + seg)
331
+ inp = _hydra2_inputs(m, src, L, s, e)
332
+ fw_state_at[s] = _clone_state(state)
333
+ yf, state = m._scan_direction(inp, "fw", state)
334
+ fw_last[s] = yf[:, -1:].clone()
335
+ del inp, yf
336
+ del state
337
+ pending = None
338
+ bw_state, bw_next = None, None # bw_next: bw output at position e
339
+ for s in reversed(starts): # pass 2: recompute fw, run bw, emit
340
+ e = min(L, s + seg)
341
+ inp = _hydra2_inputs(m, src, L, s, e) # reads rows [s-p, e+p): before writing e..
342
+ if pending is not None:
343
+ ps, pe, po = pending
344
+ buf[:, ps:pe] += po
345
+ pending = None
346
+ yf, _ = m._scan_direction(inp, "fw", fw_state_at.pop(s))
347
+ prev = fw_last[s - seg] if s > 0 else torch.zeros_like(yf[:, :1])
348
+ ysum = torch.cat([prev, yf[:, :-1]], dim=1) # position i <- fw[i-1]
349
+ del yf
350
+ yb, bw_state = m._scan_direction(inp, "bw", bw_state)
351
+ yb = torch.flip(yb, dims=(1,)) # bw[s:e] in original order
352
+ nxt = bw_next if bw_next is not None else torch.zeros_like(yb[:, :1])
353
+ ysum += torch.cat([yb[:, 1:], nxt], dim=1) # position i <- bw[i+1]
354
+ bw_next = yb[:, :1].clone()
355
+ del yb
356
+ x_og = inp["x"]
357
+ D_scale = F.linear(x_og, m.fc_D.weight, bias=m.D)
358
+ skip = x_og * repeat(D_scale, "b l h -> b l (h p)", p=m.headdim)
359
+ y = _gated_norm_int32_safe(m.norm, ysum + skip, inp["z"])
360
+ pending = (s, e, m.out_proj(y))
361
+ del inp, ysum, skip, y
362
+ ps, pe, po = pending
363
+ buf[:, ps:pe] += po
364
+
365
+
366
+ # ---------------------------------------------------------------------- #
367
+ # Row linear attention (global sums only)
368
+ # ---------------------------------------------------------------------- #
369
+
370
+ _INT_MAX = 2**31 - 1
371
+
372
+
373
+ @torch.no_grad()
374
+ def median_all(x, chunk=2**28):
375
+ """x.median() (the lower median of all elements, NaN if any is NaN) for any size. torch's median
376
+ sorts, which refuses more than INT_MAX elements (row linear attention: B * H * L values, i.e.
377
+ above ~268M context rows with 8 heads); larger inputs use an exact radix select over the float32
378
+ bit patterns, in chunks of `chunk` elements: 4 passes of 8-bit histograms find the k-th smallest
379
+ key. Same value as torch's median (up to the sign of a zero median)."""
380
+ if x.numel() <= _INT_MAX:
381
+ return x.median()
382
+ flat = x.reshape(-1)
383
+ if bool(torch.isnan(flat).any()):
384
+ return flat.new_tensor(float("nan"))
385
+ n = flat.numel()
386
+ k = (n - 1) // 2 # 0-based rank of the lower median
387
+
388
+ def keys(t): # float32 -> int64 in [0, 2^32), same order
389
+ i = t.float().view(torch.int32)
390
+ i = torch.where(i < 0, i ^ 0x7FFFFFFF, i)
391
+ return i.to(torch.int64) + 2**31
392
+
393
+ prefix = 0
394
+ for p in range(4):
395
+ shift = 24 - 8 * p
396
+ hist = torch.zeros(256, dtype=torch.int64, device=flat.device)
397
+ for s in range(0, n, chunk):
398
+ key = keys(flat[s:s + chunk])
399
+ if p:
400
+ key = key[(key >> (shift + 8)) == prefix]
401
+ hist += torch.bincount((key >> shift) & 255, minlength=256)
402
+ cum = hist.cumsum(0)
403
+ b = int(torch.searchsorted(cum, torch.tensor([k + 1], device=cum.device))[0])
404
+ k -= int(cum[b - 1]) if b else 0
405
+ prefix = prefix * 256 + b
406
+ i = torch.tensor([prefix - 2**31], dtype=torch.int64).to(torch.int32)
407
+ i = torch.where(i < 0, i ^ 0x7FFFFFFF, i)
408
+ return i.view(torch.float32)[0].to(flat.device).to(x.dtype)
409
+
410
+
411
+ @torch.no_grad()
412
+ def linattn_stream(m, src, buf, seg):
413
+ """RowLinearAttentionBranch._forward_segmented with src input and in-place accumulation."""
414
+ B, L, D = buf.shape
415
+ S = K_sum = None
416
+ for s in range(0, L, seg):
417
+ _, K, V = m._qkvg(src(s, min(L, s + seg)), need_q=False)
418
+ dS = torch.matmul(K.float().transpose(-2, -1), V.float())
419
+ dK = K.float().sum(dim=2, keepdim=True)
420
+ S = dS if S is None else S + dS
421
+ K_sum = dK if K_sum is None else K_sum + dK
422
+ dt = torch.matmul(K[..., :1, :].transpose(-2, -1), V[..., :1, :]).dtype
423
+ kdt = K.dtype
424
+ del K, V, dS, dK
425
+ S, K_sum = S.to(dt), K_sum.to(kdt)
426
+ if m.eps_z_rel is not None:
427
+ z_all = torch.cat([(m._qkvg(src(s, min(L, s + seg)), need_kv=False)[0] * K_sum).sum(-1, keepdim=True)
428
+ for s in range(0, L, seg)], dim=2)
429
+ z_floor = m.eps_z_rel * median_all(z_all.float())
430
+ del z_all
431
+ else:
432
+ z_floor = m.eps_z
433
+ for s in range(0, L, seg):
434
+ Q = m._qkvg(src(s, min(L, s + seg)), need_kv=False)[0]
435
+ Z = (Q * K_sum).sum(dim=-1, keepdim=True).clamp(min=z_floor)
436
+ O = m.out_norm(torch.matmul(Q, S) / Z)
437
+ n = O.shape[2]
438
+ buf[:, s:s + n] += m.o_proj(O.transpose(1, 2).contiguous().view(B, n, D))
439
+ del Q, Z, O
440
+
441
+
442
+ # ---------------------------------------------------------------------- #
443
+ # Gated DeltaNet (bidirectional via batch doubling in the original)
444
+ # ---------------------------------------------------------------------- #
445
+
446
+ @torch.no_grad()
447
+ def gdn_stream(m, src, buf, seg):
448
+ from firepfn.model.deltanet import _SegmentState
449
+ B, L, _ = buf.shape
450
+ seg = min(seg, m._gdn_rows_per_segment(B))
451
+ starts = list(range(0, L, seg))
452
+ layer_idx = m.gdn.layer_idx
453
+ if layer_idx is None:
454
+ m.gdn.layer_idx = 0
455
+ try:
456
+ fw_state_at, fw_last = {}, {}
457
+ st = _SegmentState()
458
+ for s in starts:
459
+ e = min(L, s + seg)
460
+ fw_state_at[s] = _clone_state(st.state)
461
+ o = m.gdn(src(s, e), past_key_values=st, use_cache=True)[0]
462
+ fw_last[s] = o[:, -1:].clone()
463
+ del o
464
+ del st
465
+ bw = _SegmentState()
466
+ bw_next = None
467
+ for s in reversed(starts):
468
+ e = min(L, s + seg)
469
+ u = src(s, e) # GDN reads only rows [s, e)
470
+ fst = _SegmentState()
471
+ fst.state = fw_state_at.pop(s)
472
+ of = m.gdn(u, past_key_values=fst, use_cache=True)[0]
473
+ prev = fw_last[s - seg] if s > 0 else torch.zeros_like(of[:, :1])
474
+ out = torch.cat([prev, of[:, :-1]], dim=1)
475
+ del of, fst
476
+ ob = torch.flip(m.gdn(torch.flip(u, dims=(1,)), past_key_values=bw, use_cache=True)[0], dims=(1,))
477
+ nxt = bw_next if bw_next is not None else torch.zeros_like(ob[:, :1])
478
+ out += torch.cat([ob[:, 1:], nxt], dim=1)
479
+ bw_next = ob[:, :1].clone()
480
+ del ob, u
481
+ buf[:, s:e] += out
482
+ del out
483
+ finally:
484
+ m.gdn.layer_idx = layer_idx
485
+
486
+
487
+ # ---------------------------------------------------------------------- #
488
+ # Cross-attention over a long context (predict)
489
+ # ---------------------------------------------------------------------- #
490
+
491
+ def use_streamed_cross_attn(n_ctx: int) -> bool:
492
+ thr = stream_ctx_rows()
493
+ return thr > 0 and n_ctx > thr and not torch.is_grad_enabled()
494
+
495
+
496
+ @torch.no_grad()
497
+ def cross_attn_streamed(q, context, norm_kv, k_proj, v_proj, key_rows=65536, max_score_elems=2**28):
498
+ """softmax(q K^T / sqrt(d)) V with K, V = k_proj/v_proj(norm_kv(context)) built one key chunk
499
+ at a time (exact; online softmax in fp32). The unchunked path materializes norm_kv(context)
500
+ (fp32) plus full K and V -- ~8 KB per context row at width 1024 -- on every cross-attention
501
+ call. q: (B, H, Nq, d) already scaled (length temperature); context: (B, Nc, D).
502
+ Returns (B, H, Nq, d) in q's dtype."""
503
+ B, H, Nq, d = q.shape
504
+ Nc = context.shape[1]
505
+ qf = q.float() * (d ** -0.5)
506
+ m = torch.full((B, H, Nq), float("-inf"), device=q.device)
507
+ l = torch.zeros((B, H, Nq), device=q.device)
508
+ acc = torch.zeros((B, H, Nq, d), device=q.device)
509
+ cq = max(1, max_score_elems // max(B * H * key_rows, 1))
510
+ for ks in range(0, Nc, key_rows):
511
+ kv = norm_kv(context[:, ks:ks + key_rows])
512
+ n = kv.shape[1]
513
+ k = k_proj(kv).view(B, n, H, d).transpose(1, 2).float()
514
+ v = v_proj(kv).view(B, n, H, d).transpose(1, 2).float()
515
+ del kv
516
+ for qs in range(0, Nq, cq):
517
+ qe = min(Nq, qs + cq)
518
+ s = torch.matmul(qf[:, :, qs:qe], k.transpose(-2, -1)) # (B, H, cq, n)
519
+ m_old = m[:, :, qs:qe]
520
+ m_new = torch.maximum(m_old, s.amax(dim=-1))
521
+ p = torch.exp(s - m_new.unsqueeze(-1))
522
+ del s
523
+ corr = torch.exp(m_old - m_new)
524
+ l[:, :, qs:qe] = l[:, :, qs:qe] * corr + p.sum(dim=-1)
525
+ acc[:, :, qs:qe] = acc[:, :, qs:qe] * corr.unsqueeze(-1) + torch.matmul(p, v)
526
+ m[:, :, qs:qe] = m_new
527
+ del p
528
+ del k, v
529
+ return (acc / l.unsqueeze(-1)).to(q.dtype)
530
+
531
+
532
+ # ---------------------------------------------------------------------- #
533
+ # Backbone
534
+ # ---------------------------------------------------------------------- #
535
+
536
+ def supports_inplace(backbone) -> bool:
537
+ from firepfn.model.backbone import Backbone
538
+ return isinstance(backbone, Backbone)
539
+
540
+
541
+ @torch.no_grad()
542
+ def backbone_inplace(backbone, buf, seg, out_fn=None):
543
+ """buf (B, L, D) fp32 = backbone input; on return buf holds out_fn(LN_f(r_K)) (or LN_f(r_K)).
544
+ out_fn maps a segment of the final-norm output to the cached representation (context_proj);
545
+ it must keep the width D."""
546
+ assert supports_inplace(backbone)
547
+ L = buf.shape[1]
548
+ for bi, block in enumerate(backbone.blocks):
549
+ norm = block.norm
550
+
551
+ def src(s, e, norm=norm):
552
+ return norm(buf[:, s:e].to(dtype=norm.weight.dtype))
553
+
554
+ kind = block.mixer.kind
555
+ mixer = getattr(block.mixer, kind)
556
+ with phase(f"backbone block{bi}[{kind}]"):
557
+ if kind == "ssm":
558
+ hydra2_stream(mixer, src, buf, seg)
559
+ elif kind == "attn":
560
+ linattn_stream(mixer, src, buf, seg)
561
+ else:
562
+ gdn_stream(mixer, src, buf, seg)
563
+ nf = backbone.norm_f
564
+ with phase("norm_f + context_proj"):
565
+ for s in range(0, L, seg):
566
+ h = nf(buf[:, s:s + seg].to(dtype=nf.weight.dtype))
567
+ buf[:, s:s + seg] = out_fn(h) if out_fn is not None else h
568
+ return buf
@@ -0,0 +1,119 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Fused RMSNorm forward (one read, one write, fp32 math in registers) for no-grad inference.
4
+
5
+ torch 2.9's F.rms_norm runs as a chain of elementwise/reduction kernels with full-size
6
+ intermediates; on the frozen Kumo encoder's token tensors (rows x 256, and rows x 64 for the
7
+ per-head q/k norms) it reaches ~0.4-1.3 TB/s, this kernel ~6 TB/s
8
+ (one encoder block 1.6x faster). The reduction is over one row (<= a few K elements), so each
9
+ program normalizes BLOCK_M whole rows and needs no workspace.
10
+
11
+ Same semantics as F.rms_norm(x, (N,), weight, eps): eps=None -> fp32 epsilon for bf16/fp16 (ATen opmath); output
12
+ in x's dtype. Forward only -- use it only without autograd (rms_norm() falls back otherwise).
13
+ Disable with FIREPFN_FUSED_RMSNORM=0 (strided inputs: FIREPFN_FUSED_RMSNORM_STRIDED=0).
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import os
18
+
19
+ import torch
20
+ import torch.nn.functional as F
21
+
22
+ try:
23
+ import triton
24
+ import triton.language as tl
25
+ except ImportError: # pragma: no cover
26
+ triton = None
27
+
28
+
29
+ if triton is not None:
30
+ @triton.jit
31
+ def _rms_kernel(X, W, Y, M, N, eps, HAS_W: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
32
+ pid = tl.program_id(0)
33
+ rows = pid.to(tl.int64) * BLOCK_M + tl.arange(0, BLOCK_M).to(tl.int64)
34
+ cols = tl.arange(0, BLOCK_N)
35
+ mask = (rows[:, None] < M) & (cols[None, :] < N)
36
+ offs = rows[:, None] * N + cols[None, :]
37
+ x = tl.load(X + offs, mask=mask, other=0.0).to(tl.float32)
38
+ r = tl.rsqrt(tl.sum(x * x, axis=1) / N + eps)
39
+ y = x * r[:, None]
40
+ if HAS_W:
41
+ w = tl.load(W + cols, mask=cols < N, other=0.0).to(tl.float32)
42
+ y = y * w[None, :]
43
+ tl.store(Y + offs, y.to(Y.dtype.element_ty), mask=mask)
44
+
45
+
46
+ @triton.jit
47
+ def _rms_kernel_strided(X, W, Y, M, N, eps, S1, S2, S3, st0, st1, st2, st3,
48
+ HAS_W: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
49
+ """_rms_kernel on a strided input (last dim contiguous, up to 4 leading dims): same
50
+ per-row arithmetic, reads the rows in place instead of after a .contiguous() copy;
51
+ output contiguous."""
52
+ pid = tl.program_id(0)
53
+ rows = pid.to(tl.int64) * BLOCK_M + tl.arange(0, BLOCK_M).to(tl.int64)
54
+ i3 = rows % S3
55
+ t = rows // S3
56
+ i2 = t % S2
57
+ t = t // S2
58
+ i1 = t % S1
59
+ i0 = t // S1
60
+ base = i0 * st0 + i1 * st1 + i2 * st2 + i3 * st3
61
+ cols = tl.arange(0, BLOCK_N)
62
+ mask = (rows[:, None] < M) & (cols[None, :] < N)
63
+ x = tl.load(X + base[:, None] + cols[None, :], mask=mask, other=0.0).to(tl.float32)
64
+ r = tl.rsqrt(tl.sum(x * x, axis=1) / N + eps)
65
+ y = x * r[:, None]
66
+ if HAS_W:
67
+ w = tl.load(W + cols, mask=cols < N, other=0.0).to(tl.float32)
68
+ y = y * w[None, :]
69
+ tl.store(Y + rows[:, None] * N + cols[None, :], y.to(Y.dtype.element_ty), mask=mask)
70
+
71
+
72
+ def strided_enabled() -> bool:
73
+ return os.environ.get("FIREPFN_FUSED_RMSNORM_STRIDED", "1") != "0"
74
+
75
+
76
+ def enabled() -> bool:
77
+ return triton is not None and os.environ.get("FIREPFN_FUSED_RMSNORM", "1") != "0"
78
+
79
+
80
+ def _fused(x: torch.Tensor, weight, eps: float) -> torch.Tensor:
81
+ N = x.shape[-1]
82
+ BLOCK_N = triton.next_power_of_2(N)
83
+ BLOCK_M = max(1, 4096 // BLOCK_N)
84
+ if (not x.is_contiguous() and x.dim() >= 2 and x.stride(-1) == 1 and x.numel() > 0
85
+ and strided_enabled()):
86
+ from firepfn.model.triton_rope import _lead_dims
87
+ lead = _lead_dims(x.shape[:-1], x.stride()[:-1], 4)
88
+ if lead is not None:
89
+ M = x.numel() // N
90
+ y = torch.empty(x.shape, device=x.device, dtype=x.dtype)
91
+ (_, st0), (S1, st1), (S2, st2), (S3, st3) = lead
92
+ w = weight if weight is not None else y
93
+ _rms_kernel_strided[(triton.cdiv(M, BLOCK_M),)](
94
+ x, w, y, M, N, eps, S1, S2, S3, st0, st1, st2, st3,
95
+ HAS_W=weight is not None, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N)
96
+ return y
97
+ x2 = x.reshape(-1, N)
98
+ if not x2.is_contiguous():
99
+ x2 = x2.contiguous()
100
+ y = torch.empty(x2.shape, device=x.device, dtype=x.dtype)
101
+ M = x2.shape[0]
102
+ w = weight if weight is not None else x2
103
+ _rms_kernel[(triton.cdiv(M, BLOCK_M),)](x2, w, y, M, N, eps, HAS_W=weight is not None,
104
+ BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N)
105
+ return y.view(x.shape)
106
+
107
+
108
+ def rms_norm(x: torch.Tensor, normalized_shape, weight=None, eps=None) -> torch.Tensor:
109
+ """F.rms_norm over the last dim; fused kernel when no autograd graph is needed."""
110
+ if (not enabled() or not x.is_cuda or torch.is_grad_enabled() or len(normalized_shape) != 1
111
+ or x.dtype not in (torch.float32, torch.bfloat16, torch.float16) or x.shape[-1] > 8192):
112
+ return F.rms_norm(x, normalized_shape, weight, eps)
113
+ if eps is None:
114
+ # ATen's rms_norm defaults to the epsilon of the *opmath* type (fp32 for bf16/fp16 inputs),
115
+ # not finfo(x.dtype).eps as the docs suggest; 2^-7 (bf16) visibly shrinks small rows.
116
+ eps = torch.finfo(torch.float32 if x.dtype in (torch.bfloat16, torch.float16) else x.dtype).eps
117
+ if weight is not None and weight.dtype != x.dtype:
118
+ weight = weight.to(x.dtype)
119
+ return _fused(x, weight, float(eps))