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/loading.py ADDED
@@ -0,0 +1,97 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Load FirePFN checkpoints.
4
+
5
+ Two formats are accepted:
6
+
7
+ * release checkpoints: ``{"format": "firepfn-v1", "config": {...}, "meta": {...},
8
+ "state_dict": {...}}`` -- plain tensors, the complete model config and string metadata, loaded
9
+ with ``weights_only=True``;
10
+ * training checkpoints: ``{"model_state_dict": ..., "config": ..., "optimizer": ...}`` as written
11
+ by the training script. Their config may hold Python callables, so they are unpickled in full
12
+ (``weights_only=False``): only load training checkpoints you trust.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import os
18
+
19
+ import torch
20
+
21
+ from firepfn import __version__
22
+ from firepfn.model import FirePFN
23
+
24
+ RELEASE_FORMAT = "firepfn-v1"
25
+
26
+ # Released weights on the Hugging Face Hub (used when no model_path is given).
27
+ HF_REPO_ID = "LUHAI/FirePFN"
28
+ HF_FILENAME = "fire-pfn.ckpt"
29
+ HF_REVISION = "30bb0e95b0b1eb19ba7b746b0951c6f0933be7b6" # Hub commit of the release upload
30
+
31
+
32
+ def default_model_path() -> str:
33
+ """Local path of the released checkpoint, downloaded from the Hugging Face Hub on first use
34
+ (cached by huggingface_hub). ``FIREPFN_MODEL_PATH`` overrides it with a local file."""
35
+ local = os.environ.get("FIREPFN_MODEL_PATH")
36
+ if local:
37
+ return local
38
+ from huggingface_hub import hf_hub_download
39
+ return hf_hub_download(repo_id=HF_REPO_ID, filename=HF_FILENAME, revision=HF_REVISION)
40
+
41
+
42
+ def _read(path: str) -> tuple[dict, dict, dict]:
43
+ """-> (config, state_dict, meta) of a release or training checkpoint."""
44
+ try:
45
+ ckpt = torch.load(path, map_location="cpu", weights_only=True)
46
+ except Exception:
47
+ ckpt = torch.load(path, map_location="cpu", weights_only=False)
48
+ if ckpt.get("format") == RELEASE_FORMAT:
49
+ return dict(ckpt["config"]), ckpt["state_dict"], dict(ckpt.get("meta", {}))
50
+ state = {k.replace("module.", "", 1) if k.startswith("module.") else k: v
51
+ for k, v in ckpt["model_state_dict"].items() if not k.startswith("criterion.")}
52
+ return dict(ckpt["config"]), state, {}
53
+
54
+
55
+ def load_model(path: str, device: str = "cpu") -> tuple[FirePFN, dict]:
56
+ """-> (model in eval mode on `device`, complete model config)."""
57
+ config, state, _ = _read(path)
58
+ model = FirePFN.from_config(config)
59
+ model.load_state_dict(state, strict=True)
60
+ model.to(device).eval()
61
+ return model, FirePFN.resolve_config(config)
62
+
63
+
64
+ def _sha256(path: str) -> str:
65
+ h = hashlib.sha256()
66
+ with open(path, "rb") as f:
67
+ for block in iter(lambda: f.read(1 << 24), b""):
68
+ h.update(block)
69
+ return h.hexdigest()
70
+
71
+
72
+ def export_release_checkpoint(src: str, dst: str, meta: dict | None = None) -> dict:
73
+ """Training checkpoint -> release checkpoint: model weights, the complete model config and
74
+ string metadata only (no optimizer state, no training config), loadable with
75
+ ``weights_only=True``. The written file is read back and compared tensor by tensor.
76
+
77
+ Returns the metadata written, plus the file's sha256.
78
+ """
79
+ config, state, _ = _read(src)
80
+ model = FirePFN.from_config(config)
81
+ model.load_state_dict(state, strict=True) # validate before writing
82
+ cfg = FirePFN.resolve_config(config)
83
+ # Keys in the order of the model's own state dict; frozen Kumo encoder included.
84
+ state = {k: state[k].detach().clone().contiguous() for k in model.state_dict()}
85
+ meta = {str(k): str(v) for k, v in (meta or {}).items()}
86
+ meta.setdefault("firepfn_version", __version__)
87
+ meta.setdefault("n_parameters", str(sum(v.numel() for v in state.values())))
88
+ torch.save({"format": RELEASE_FORMAT, "config": cfg, "meta": meta, "state_dict": state}, dst)
89
+
90
+ ckpt = torch.load(dst, map_location="cpu", weights_only=True)
91
+ assert ckpt["format"] == RELEASE_FORMAT and ckpt["config"] == cfg and ckpt["meta"] == meta
92
+ assert list(ckpt["state_dict"]) == list(state), "state_dict keys changed on reload"
93
+ for k, v in state.items():
94
+ w = ckpt["state_dict"][k]
95
+ assert w.dtype == v.dtype and w.shape == v.shape and torch.equal(w, v), f"tensor {k} differs"
96
+ FirePFN.from_config(ckpt["config"]).load_state_dict(ckpt["state_dict"], strict=True)
97
+ return {**meta, "sha256": _sha256(dst)}
firepfn/many_class.py ADDED
@@ -0,0 +1,157 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Many-class classification by decomposition into problems the base model handles natively.
4
+
5
+ FirePFN's decoder has a fixed number of logits (10). ``ClassDecomposition`` turns a K-class
6
+ problem into a set of base problems with at most ``max_classes`` classes each and recombines
7
+ their probabilities. Strategies:
8
+
9
+ ovr
10
+ One binary problem per class (class k vs. rest); P(k|x) proportional to p_k(1|x).
11
+
12
+ ecoc
13
+ Error-correcting output codes, as in TabPFN Extensions and Seldon: every code column gives
14
+ ``max_classes - 1`` classes their own label and merges all other classes into one "rest" label,
15
+ so each base problem is one native multiclass fit on all rows. The number of columns is
16
+ ``max(ceil(K / (max_classes - 1)), 4 * ceil(log_max_classes K))``; columns pick the
17
+ least-covered classes first, so every class has its own label in at least one column, and of 50
18
+ random codebooks (1 above 200 classes) the one with the largest minimum pairwise code distance
19
+ is kept. The score of a class is the mean log-probability of its label over the columns where
20
+ it has its own label; a softmax over the classes normalises the scores.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import math
25
+
26
+ import numpy as np
27
+ from sklearn.base import BaseEstimator, ClassifierMixin, clone
28
+ from sklearn.utils.validation import check_is_fitted
29
+
30
+ STRATEGIES = ("ecoc", "ovr")
31
+ _EPS = 1e-7
32
+
33
+
34
+ def _proba_columns(est, X, n):
35
+ """predict_proba with columns aligned to labels 0..n-1 (absent labels -> 0)."""
36
+ p = est.predict_proba(X)
37
+ out = np.zeros((p.shape[0], n))
38
+ for j, c in enumerate(np.asarray(est.classes_).astype(int)):
39
+ out[:, c] = p[:, j]
40
+ return out
41
+
42
+
43
+ class ClassDecomposition(ClassifierMixin, BaseEstimator):
44
+ """K-class classifier from base problems with <= ``max_classes`` classes each.
45
+
46
+ Parameters
47
+ ----------
48
+ base_estimator : classifier with predict_proba, cloned per base problem. Labels it sees
49
+ are always 0..g-1.
50
+ strategy : {"ecoc", "ovr"}
51
+ max_classes : int -- the base model's native class budget.
52
+ n_columns : int or None -- ecoc only, number of code columns (base fits), default
53
+ max(ceil(K / (max_classes - 1)), 4 * ceil(log_max_classes K)).
54
+ n_code_draws : int or None -- ecoc only, random codebooks drawn, the one with the largest
55
+ minimum pairwise code distance is kept; default 50 (1 above 200 classes).
56
+ random_state : int
57
+ """
58
+
59
+ def __init__(self, base_estimator, strategy="ecoc", max_classes=10, n_columns=None,
60
+ n_code_draws=None, random_state=0):
61
+ self.base_estimator = base_estimator
62
+ self.strategy = strategy
63
+ self.max_classes = max_classes
64
+ self.n_columns = n_columns
65
+ self.n_code_draws = n_code_draws
66
+ self.random_state = random_state
67
+
68
+ # ------------------------------------------------------------------ helpers
69
+
70
+ def _fit_base(self, X, labels):
71
+ est = clone(self.base_estimator)
72
+ est.fit(X, labels)
73
+ self.n_base_fits_ += 1
74
+ return est
75
+
76
+ # ------------------------------------------------------------------ OvR
77
+
78
+ def _fit_ovr(self, X, y):
79
+ self.ovr_ = [self._fit_base(X, (y == k).astype(np.int64)) for k in range(self.n_classes_)]
80
+
81
+ def _proba_ovr(self, X):
82
+ p = np.stack([_proba_columns(e, X, 2)[:, 1] for e in self.ovr_], axis=1)
83
+ return p
84
+
85
+ # ------------------------------------------------------------------ ECOC
86
+
87
+ def _make_code(self, K, rng):
88
+ """Codebook (T, K) of labels 0..max_classes-1: in every column ``max_classes - 1``
89
+ classes keep their own label and all others share the last label ("rest"). Columns pick
90
+ the least-covered classes first, so every class gets its own label in at least one column;
91
+ of several random draws the codebook with the largest minimum pairwise distance is kept."""
92
+ m = self.max_classes
93
+ rest = m - 1
94
+ n_own = min(rest, K)
95
+ T = self.n_columns or max(math.ceil(K / rest), 4 * math.ceil(math.log(K, m)) if K > 1 else 1)
96
+ D = self.n_code_draws or (50 if K <= 200 else 1)
97
+ codes = np.full((D, T, K), rest, dtype=np.int64)
98
+ coverage = np.zeros((D, K))
99
+ ar = np.arange(D)[:, None]
100
+ for t in range(T):
101
+ chosen = np.argsort(coverage + 0.1 * rng.random((D, K)), axis=1)[:, :n_own]
102
+ codes[ar, t, chosen] = np.argsort(rng.random((D, n_own)), axis=1)
103
+ coverage[ar, chosen] += 1.0
104
+ if D == 1:
105
+ return codes[0]
106
+ dist = np.zeros((D, K, K), dtype=np.int64)
107
+ for t in range(T):
108
+ dist += codes[:, t, :, None] != codes[:, t, None, :]
109
+ i, j = np.triu_indices(K, k=1)
110
+ pair = dist[:, i, j]
111
+ score = pair.min(axis=1) * (pair.shape[1] * T + 1) + pair.sum(axis=1)
112
+ return codes[int(score.argmax())]
113
+
114
+ def _fit_ecoc(self, X, y, rng):
115
+ self.code_ = self._make_code(self.n_classes_, rng) # (T, K)
116
+ self.ecoc_ = [self._fit_base(X, self.code_[t][y]) for t in range(self.code_.shape[0])]
117
+
118
+ def _proba_ecoc(self, X):
119
+ """Per class: mean log-probability of its label over the columns where it has its own
120
+ label (not "rest"); a softmax over classes normalises the scores."""
121
+ rest = self.max_classes - 1
122
+ score = np.zeros((X.shape[0], self.n_classes_))
123
+ n_active = np.zeros(self.n_classes_)
124
+ for t, est in enumerate(self.ecoc_):
125
+ code = self.code_[t]
126
+ own = code != rest
127
+ logp = np.log(np.clip(_proba_columns(est, X, self.max_classes), _EPS, 1.0)[:, code])
128
+ score += np.where(own, logp, 0.0)
129
+ n_active += own
130
+ score /= np.maximum(n_active, 1)
131
+ score -= score.max(axis=1, keepdims=True)
132
+ return np.exp(score)
133
+
134
+ # ------------------------------------------------------------------ public API
135
+
136
+ def fit(self, X, y):
137
+ if self.strategy not in STRATEGIES:
138
+ raise ValueError(f"unknown strategy {self.strategy!r} (choose from {STRATEGIES})")
139
+ X = np.asarray(X, dtype=np.float32)
140
+ y = np.asarray(y)
141
+ self.classes_, y = np.unique(y, return_inverse=True)
142
+ self.n_classes_ = len(self.classes_)
143
+ self.n_base_fits_ = 0
144
+ rng = np.random.default_rng(self.random_state)
145
+ {"ovr": lambda: self._fit_ovr(X, y),
146
+ "ecoc": lambda: self._fit_ecoc(X, y, rng)}[self.strategy]()
147
+ return self
148
+
149
+ def predict_proba(self, X):
150
+ check_is_fitted(self, "n_base_fits_")
151
+ X = np.asarray(X, dtype=np.float32)
152
+ p = {"ovr": self._proba_ovr, "ecoc": self._proba_ecoc}[self.strategy](X)
153
+ p = np.clip(p, 0, None)
154
+ return p / np.clip(p.sum(1, keepdims=True), 1e-12, None)
155
+
156
+ def predict(self, X):
157
+ return self.classes_[np.argmax(self.predict_proba(X), axis=1)]
@@ -0,0 +1,5 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ from firepfn.model.fire_pfn import FirePFN
4
+
5
+ __all__ = ["FirePFN"]
@@ -0,0 +1,49 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2023-2025, Tri Dao, Albert Gu.
3
+ # Copyright (c) 2025-2026, the FirePFN authors (modifications).
4
+ #
5
+ # Adapted from Mamba (https://github.com/state-spaces/mamba): mamba_ssm/modules/block.py (Block)
6
+ # and mamba_ssm/models/mixer_seq_simple.py (_init_weights), licensed under the Apache License 2.0.
7
+ # Modified by the FirePFN authors: reduced to the configuration FirePFN uses (LayerNorm pre-norm,
8
+ # no fused add+norm, no MLP, residual kept in the activation dtype).
9
+ """Pre-norm residual block and weight initialisation of the backbone."""
10
+ import math
11
+ from typing import Optional
12
+
13
+ import torch
14
+ from torch import nn, Tensor
15
+
16
+
17
+ class HydraBlock(nn.Module):
18
+ """``residual = hidden + residual; hidden = mixer(norm(residual))``.
19
+
20
+ Returns (hidden, residual); the caller adds the last pair (see Backbone.forward).
21
+ """
22
+
23
+ def __init__(self, dim: int, mixer: nn.Module, norm: nn.Module):
24
+ super().__init__()
25
+ self.norm = norm
26
+ self.mixer = mixer
27
+
28
+ def forward(self, hidden_states: Tensor, residual: Optional[Tensor] = None):
29
+ residual = (hidden_states + residual) if residual is not None else hidden_states
30
+ hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
31
+ return self.mixer(hidden_states), residual
32
+
33
+
34
+ def _init_weights(module, n_layer, initializer_range=0.02, rescale_prenorm_residual=True,
35
+ n_residuals_per_layer=1):
36
+ """Zero biases, N(0, 0.02) embeddings, and depth-scaled init of residual output projections."""
37
+ if isinstance(module, nn.Linear):
38
+ if module.bias is not None:
39
+ if not getattr(module.bias, "_no_reinit", False):
40
+ nn.init.zeros_(module.bias)
41
+ elif isinstance(module, nn.Embedding):
42
+ nn.init.normal_(module.weight, std=initializer_range)
43
+
44
+ if rescale_prenorm_residual:
45
+ for name, p in module.named_parameters():
46
+ if name in ["out_proj.weight", "fc2.weight"]:
47
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
48
+ with torch.no_grad():
49
+ p /= math.sqrt(n_residuals_per_layer * n_layer)
@@ -0,0 +1,110 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Row-axis backbone: a stack of pre-norm residual blocks with one sequence mixer each.
4
+
5
+ The mixer of block i is chosen by ``layer_pattern[i]``:
6
+
7
+ "ssm" Hydra2 -- bidirectional Mamba-3 scan (hydra2.py)
8
+ "attn" RowLinearAttentionBranch -- non-causal gated linear attention (linear_attention.py)
9
+ "deltanet" GatedDeltaNetBranch -- bidirectional Gated DeltaNet (deltanet.py)
10
+
11
+ FirePFN uses ``["ssm", "ssm", "attn", "ssm", "deltanet", "attn"]``. The backbone runs over the
12
+ context rows only (queries read them through the cross-attention). Parameter names
13
+ (``blocks.{i}.mixer.{kind}.*``, ``blocks.{i}.norm``, ``norm_f``) are those of the released
14
+ checkpoints.
15
+ """
16
+ import math
17
+ from functools import partial
18
+
19
+ import torch
20
+ from torch import nn
21
+
22
+ from firepfn.model._mamba_block import HydraBlock, _init_weights
23
+
24
+ MIXER_KINDS = ("ssm", "attn", "deltanet")
25
+
26
+
27
+ class SequentialMixer(nn.Module):
28
+ """Exactly one mixer, stored under the attribute named after its kind."""
29
+
30
+ def __init__(self, d_model, kind, layer_idx=None, ssm_cfg=None, attn_n_heads=8, attn_eps_z=1e-4,
31
+ attn_eps_z_rel=0.05, deltanet_head_dim=64, deltanet_num_heads=8, deltanet_expand_v=2.0,
32
+ device=None, dtype=None):
33
+ super().__init__()
34
+ factory_kwargs = {"device": device, "dtype": dtype}
35
+ self.kind = kind
36
+ if kind == "ssm":
37
+ from firepfn.model.hydra2 import Hydra2
38
+ self.ssm = Hydra2(d_model, layer_idx=layer_idx, **(ssm_cfg or {}), **factory_kwargs)
39
+ elif kind == "attn":
40
+ from firepfn.model.linear_attention import RowLinearAttentionBranch
41
+ self.attn = RowLinearAttentionBranch(
42
+ d_model, n_heads=attn_n_heads, stabilize_norm=True,
43
+ eps_z=attn_eps_z, eps_z_rel=attn_eps_z_rel, **factory_kwargs,
44
+ )
45
+ elif kind == "deltanet":
46
+ from firepfn.model.deltanet import GatedDeltaNetBranch
47
+ self.deltanet = GatedDeltaNetBranch(
48
+ d_model, head_dim=deltanet_head_dim, num_heads=deltanet_num_heads,
49
+ expand_v=deltanet_expand_v, layer_idx=layer_idx, **factory_kwargs,
50
+ )
51
+ else:
52
+ raise ValueError(f"Unknown mixer kind {kind!r}; valid: {MIXER_KINDS}")
53
+
54
+ def forward(self, x):
55
+ return getattr(self, self.kind)(x)
56
+
57
+ def output_projection(self) -> nn.Linear:
58
+ """The Linear whose output is this mixer's residual-stream contribution."""
59
+ if self.kind == "ssm":
60
+ return self.ssm.out_proj
61
+ if self.kind == "attn":
62
+ return self.attn.o_proj
63
+ return self.deltanet.gdn.o_proj
64
+
65
+
66
+ class Backbone(nn.Module):
67
+ def __init__(self, d_model: int, layer_pattern, ssm_config=None, norm_epsilon: float = 1e-5,
68
+ initializer_cfg=None, attn_n_heads=8, attn_eps_z=1e-4, attn_eps_z_rel=0.05,
69
+ deltanet_head_dim=64, deltanet_num_heads=8, deltanet_expand_v=2.0,
70
+ device=None, dtype=None):
71
+ super().__init__()
72
+ factory_kwargs = {"device": device, "dtype": dtype}
73
+ if not layer_pattern or any(k not in MIXER_KINDS for k in layer_pattern):
74
+ raise ValueError(f"layer_pattern must be a non-empty list of {MIXER_KINDS}, got {layer_pattern!r}")
75
+ self.layer_pattern = list(layer_pattern)
76
+ n_layer = len(self.layer_pattern)
77
+
78
+ blocks = []
79
+ for i, kind in enumerate(self.layer_pattern):
80
+ mixer = SequentialMixer(
81
+ d_model, kind=kind, layer_idx=i, ssm_cfg=ssm_config,
82
+ attn_n_heads=attn_n_heads, attn_eps_z=attn_eps_z, attn_eps_z_rel=attn_eps_z_rel,
83
+ deltanet_head_dim=deltanet_head_dim, deltanet_num_heads=deltanet_num_heads,
84
+ deltanet_expand_v=deltanet_expand_v, **factory_kwargs,
85
+ )
86
+ block = HydraBlock(d_model, mixer, nn.LayerNorm(d_model, eps=norm_epsilon, **factory_kwargs))
87
+ block.layer_idx = i
88
+ blocks.append(block)
89
+ self.blocks = nn.ModuleList(blocks)
90
+ self.norm_f = nn.LayerNorm(d_model, eps=norm_epsilon, **factory_kwargs)
91
+
92
+ initializer_cfg = initializer_cfg or {}
93
+ self.apply(partial(_init_weights, n_layer=n_layer, **initializer_cfg, n_residuals_per_layer=1))
94
+ # _init_weights' depth rescale only matches parameters named "out_proj.weight" (Hydra2's).
95
+ # Every mixer writes straight into the residual stream, so the linear attention's and
96
+ # Gated DeltaNet's o_proj get the same treatment.
97
+ if initializer_cfg.get("rescale_prenorm_residual", True):
98
+ for block in self.blocks:
99
+ if block.mixer.kind in ("attn", "deltanet"):
100
+ w = block.mixer.output_projection().weight
101
+ nn.init.kaiming_uniform_(w, a=math.sqrt(5))
102
+ with torch.no_grad():
103
+ w /= math.sqrt(n_layer)
104
+
105
+ def forward(self, x):
106
+ hidden_states, residual = x, None
107
+ for block in self.blocks:
108
+ hidden_states, residual = block(hidden_states, residual)
109
+ residual = (hidden_states + residual) if residual is not None else hidden_states
110
+ return self.norm_f(residual.to(dtype=self.norm_f.weight.dtype))
@@ -0,0 +1,123 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Query -> context cross-attention with a length-aware temperature."""
4
+ import math
5
+
6
+ import torch
7
+ from torch import nn, Tensor
8
+
9
+ from firepfn.model import stream_infer
10
+
11
+ # Fused SDPA kernels index with int32: one flattened (batch, head) item above 2**31 elements
12
+ # (as the kernels pad it) overflows. Beyond that, attention runs key-chunked (exact).
13
+ _SDPA_MAX_CHUNK_ELEMS = 2**31 - 1
14
+
15
+
16
+ def _padded_item_elems(q: Tensor, k: Tensor, v: Tensor) -> int:
17
+ """Elements of one flattened-batch item as the fused SDPA kernels pad it."""
18
+ padded_len = -(-max(q.shape[-2], k.shape[-2]) // 256) * 256
19
+ padded_hd = -(-max(q.shape[-1], v.shape[-1]) // 64) * 64
20
+ return q.shape[-3] * padded_len * padded_hd
21
+
22
+
23
+ def _sdpa_key_chunked(q: Tensor, k: Tensor, v: Tensor, max_score_elems: int = 2**28) -> Tensor:
24
+ """softmax(q k^T / sqrt(d)) v for inputs too large for one fused SDPA call (no mask/dropout).
25
+
26
+ Exact attention over query and key chunks with an online (running max / sum) softmax in fp32,
27
+ so no tensor ever exceeds int32 indexing. q: (b, h, Lq, d); k, v: (b, h, Lk, d).
28
+ """
29
+ b, h, Lq, d = q.shape
30
+ Lk = k.shape[-2]
31
+ scale = 1.0 / math.sqrt(d)
32
+ cq = max(1, min(Lq, max_score_elems // max(b * h * 1024, 1)))
33
+ ck = max(1, max_score_elems // max(b * h * cq, 1))
34
+ out = torch.empty(b, h, Lq, v.shape[-1], device=q.device, dtype=q.dtype)
35
+ for qs in range(0, Lq, cq):
36
+ qc = q[:, :, qs:qs + cq].float() * scale
37
+ m = torch.full(qc.shape[:-1], float("-inf"), device=q.device)
38
+ l = torch.zeros(qc.shape[:-1], device=q.device)
39
+ acc = torch.zeros(*qc.shape[:-1], v.shape[-1], device=q.device)
40
+ for ks in range(0, Lk, ck):
41
+ s = torch.matmul(qc, k[:, :, ks:ks + ck].float().transpose(-2, -1)) # (b, h, cq, ck)
42
+ m_new = torch.maximum(m, s.amax(dim=-1))
43
+ p = torch.exp(s - m_new.unsqueeze(-1))
44
+ corr = torch.exp(m - m_new)
45
+ l = l * corr + p.sum(dim=-1)
46
+ acc = acc * corr.unsqueeze(-1) + torch.matmul(p, v[:, :, ks:ks + ck].float())
47
+ m = m_new
48
+ del s, p
49
+ out[:, :, qs:qs + cq] = (acc / l.unsqueeze(-1)).to(q.dtype)
50
+ return out
51
+
52
+
53
+ class CrossAttention(nn.Module):
54
+ """Each query row independently attends over the context rows.
55
+
56
+ Pre-norm on query and context; the residual uses the unnormalised query. With ``len_temp``
57
+ the queries are scaled by tau(n) = alpha_h * log(n), n = number of context rows (learned
58
+ alpha_h per head, initialised so that tau = 1 at n = len_temp_ref_n), so the softmax does not
59
+ flatten out as the context grows.
60
+ """
61
+
62
+ def __init__(self, dim: int, n_heads: int = 4, len_temp: bool = False, len_temp_ref_n: int = 1024):
63
+ super().__init__()
64
+ assert dim % n_heads == 0, "dim must be divisible by n_heads"
65
+ self.n_heads = n_heads
66
+ self.head_dim = dim // n_heads
67
+ self.len_temp = len_temp
68
+ if len_temp:
69
+ self.len_temp_alpha = nn.Parameter(torch.full((n_heads,), 1.0 / math.log(len_temp_ref_n)))
70
+ self.len_temp_alpha._no_weight_decay = True
71
+
72
+ self.q_proj = nn.Linear(dim, dim)
73
+ self.k_proj = nn.Linear(dim, dim)
74
+ self.v_proj = nn.Linear(dim, dim)
75
+ self.out_proj = nn.Linear(dim, dim)
76
+ # Optimizer group with extra weight decay (training: cross_attn_wd) -- unchecked growth of
77
+ # these weights saturates the softmax / inflates the residual stream over long runs.
78
+ for lin in (self.q_proj, self.k_proj, self.v_proj, self.out_proj):
79
+ lin.weight._extra_weight_decay = True
80
+
81
+ self.norm_q = nn.LayerNorm(dim)
82
+ self.norm_kv = nn.LayerNorm(dim)
83
+
84
+ def _len_temp_tau(self, n_ctx: int) -> Tensor:
85
+ return self.len_temp_alpha * math.log(max(n_ctx, 2))
86
+
87
+ def forward(self, query: Tensor, context: Tensor) -> Tensor:
88
+ """query (B, Nq, D), context (B, Nc, D) -> (B, Nq, D)."""
89
+ residual = query
90
+ query = self.norm_q(query)
91
+ B, Nq, D = query.shape
92
+ Nc = context.shape[1]
93
+
94
+ if not self.training and stream_infer.use_streamed_cross_attn(Nc):
95
+ # Very long context: norm_kv + K/V projections one key chunk at a time (exact).
96
+ Q = self.q_proj(query).view(B, Nq, self.n_heads, self.head_dim).transpose(1, 2)
97
+ if self.len_temp:
98
+ Q = Q * self._len_temp_tau(Nc).to(Q.dtype).view(1, -1, 1, 1)
99
+ out = stream_infer.cross_attn_streamed(Q, context, self.norm_kv, self.k_proj, self.v_proj)
100
+ return residual + self.out_proj(out.transpose(1, 2).contiguous().view(B, Nq, D))
101
+
102
+ context = self.norm_kv(context)
103
+ Q = self.q_proj(query).view(B, Nq, self.n_heads, self.head_dim).transpose(1, 2)
104
+ K = self.k_proj(context).view(B, Nc, self.n_heads, self.head_dim).transpose(1, 2)
105
+ V = self.v_proj(context).view(B, Nc, self.n_heads, self.head_dim).transpose(1, 2)
106
+ if self.len_temp:
107
+ Q = Q * self._len_temp_tau(Nc).to(Q.dtype).view(1, -1, 1, 1)
108
+
109
+ if not self.training:
110
+ # Fused SDPA (same math: softmax(Q K^T / sqrt(head_dim)) V) instead of materialising
111
+ # the (B, heads, Nq, Nc) attention matrix.
112
+ if not torch.is_grad_enabled() and _padded_item_elems(Q, K, V) > _SDPA_MAX_CHUNK_ELEMS:
113
+ out = _sdpa_key_chunked(Q, K, V)
114
+ else:
115
+ out = torch.nn.functional.scaled_dot_product_attention(Q, K, V)
116
+ elif Q.shape[0] * Q.shape[1] * Q.shape[2] * K.shape[2] > 2**28:
117
+ # Long-context training: fused SDPA instead of the materialised matrix.
118
+ out = torch.nn.functional.scaled_dot_product_attention(Q, K.to(Q.dtype), V.to(Q.dtype))
119
+ else:
120
+ attn = torch.softmax(torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.head_dim), dim=-1)
121
+ out = torch.matmul(attn, V)
122
+ out = out.transpose(1, 2).contiguous().view(B, Nq, D)
123
+ return residual + self.out_proj(out)
@@ -0,0 +1,134 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ # Copyright (c) 2025-2026, the FirePFN authors.
3
+ """Bidirectional Gated DeltaNet over the row axis (backbone mixer "deltanet").
4
+
5
+ Wraps fla's GatedDeltaNet (Yang et al., "Gated Delta Networks: Improving Mamba2 with Delta Rule",
6
+ arXiv:2412.06464; flash-linear-attention, MIT) with the same batch-doubling + roll-by-one trick
7
+ Hydra2 uses: stack [x, flip(x)] on the batch axis, run the causal layer once, roll the output by
8
+ one position (zeroing position 0) so each row excludes its own contribution, un-flip the backward
9
+ half and sum. Each row's representation is then built from every other row, in both directions.
10
+ """
11
+ import os
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ from fla.layers.gated_deltanet import GatedDeltaNet
16
+
17
+ from firepfn.model.stream_infer import infer_segment_rows, use_segmented_inference
18
+
19
+
20
+ class _SegmentState:
21
+ """Minimal stand-in for fla's Cache when one GatedDeltaNet layer is run over consecutive
22
+ sequence segments: holds the last segment's recurrent state and short-conv tails (what
23
+ GatedDeltaNet.forward reads via past_key_values[layer_idx] and writes via update())."""
24
+
25
+ def __init__(self):
26
+ self.state = None
27
+
28
+ def __len__(self):
29
+ return 0 if self.state is None else 2**31
30
+
31
+ def __getitem__(self, layer_idx):
32
+ return self.state
33
+
34
+ def update(self, recurrent_state=None, conv_state=None, layer_idx=None, offset=None, **kw):
35
+ self.state = {"recurrent_state": recurrent_state, "conv_state": conv_state}
36
+
37
+
38
+ class GatedDeltaNetBranch(nn.Module):
39
+ def __init__(self, d_model, head_dim=64, num_heads=8, expand_v=2.0, layer_idx=None,
40
+ device=None, dtype=None):
41
+ super().__init__()
42
+ self.gdn = GatedDeltaNet(
43
+ hidden_size=d_model,
44
+ head_dim=head_dim,
45
+ num_heads=num_heads,
46
+ expand_v=expand_v,
47
+ layer_idx=layer_idx,
48
+ mode='chunk',
49
+ )
50
+ self.gdn.to(device=device, dtype=dtype)
51
+
52
+ def _gdn_rows_per_segment(self, batch):
53
+ """Most sequence positions one fla call may take before its int32 offsets overflow.
54
+
55
+ fla's kernels address tensors as ``(bos*H + i_h) * K`` etc. in int32 (bos = i_b * T), so
56
+ every tensor they touch must stay below 2**31 elements: q/k/v/o and the short-conv
57
+ inputs (key_dim / value_dim per row), the per-chunk states h (H*K*V per 64 rows) and the
58
+ chunk-local A matrices (H*64 per row). Half of 2**31 as margin. FIREPFN_GDN_SEG_ROWS
59
+ overrides it (testing: forces segmentation on small inputs).
60
+ """
61
+ env = os.environ.get("FIREPFN_GDN_SEG_ROWS")
62
+ if env:
63
+ return int(env)
64
+ g = self.gdn
65
+ hv = getattr(g, "num_v_heads", g.num_heads)
66
+ per_row = max(g.key_dim * hv // g.num_heads, g.value_dim,
67
+ hv * g.head_k_dim * g.head_v_dim // 64, hv * 64)
68
+ return max(1024, (2**30) // (batch * per_row))
69
+
70
+ def _gdn_int32_safe(self, x2):
71
+ """self.gdn(x2), run over sequence segments with carried state when it is too long
72
+ (chunked prefill through past_key_values; equals the single call up to float rounding)."""
73
+ seg = self._gdn_rows_per_segment(x2.shape[0])
74
+ L = x2.shape[1]
75
+ if L <= seg:
76
+ o2, _, _ = self.gdn(x2, use_cache=False)
77
+ return o2
78
+ state = _SegmentState()
79
+ layer_idx = self.gdn.layer_idx
80
+ if layer_idx is None: # the Cache protocol compares len(cache) > layer_idx
81
+ self.gdn.layer_idx = 0
82
+ try:
83
+ outs = [self.gdn(x2[:, i:i + seg], past_key_values=state, use_cache=True)[0]
84
+ for i in range(0, L, seg)]
85
+ finally:
86
+ self.gdn.layer_idx = layer_idx
87
+ return torch.cat(outs, dim=1)
88
+
89
+ @torch.no_grad()
90
+ def _forward_segmented(self, x, seg):
91
+ """forward(x) without gradients, one direction and one segment of `seg` rows at a time.
92
+
93
+ With the post-scan roll, the unsegmented output at position i is fw[i-1] + bw[i+1]. The
94
+ forward pass runs over segments in order and the backward pass over flipped segments in
95
+ reverse order, each carrying fla's recurrent and short-conv state, and both add straight
96
+ into the (B, L, D) output.
97
+ """
98
+ B, L, _ = x.shape
99
+ out = None
100
+ layer_idx = self.gdn.layer_idx
101
+ if layer_idx is None:
102
+ self.gdn.layer_idx = 0
103
+ try:
104
+ state = _SegmentState()
105
+ for s in range(0, L, seg):
106
+ e = min(L, s + seg)
107
+ o = self.gdn(x[:, s:e], past_key_values=state, use_cache=True)[0]
108
+ if out is None:
109
+ out = torch.zeros(B, L, o.shape[-1], device=x.device, dtype=o.dtype)
110
+ hi = min(e + 1, L)
111
+ out[:, s + 1:hi] += o[:, :hi - (s + 1)]
112
+ del o
113
+ state = _SegmentState()
114
+ for s in reversed(range(0, L, seg)):
115
+ e = min(L, s + seg)
116
+ o = self.gdn(torch.flip(x[:, s:e], dims=(1,)), past_key_values=state, use_cache=True)[0]
117
+ o = torch.flip(o, dims=(1,)) # bw[s:e] in original order
118
+ lo = max(s - 1, 0)
119
+ out[:, lo:e - 1] += o[:, lo - s + 1:]
120
+ del o
121
+ finally:
122
+ self.gdn.layer_idx = layer_idx
123
+ return out
124
+
125
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
126
+ """x: (B, L, D) -> (B, L, D)"""
127
+ B = x.shape[0]
128
+ if use_segmented_inference(x.shape[1]):
129
+ return self._forward_segmented(x, min(infer_segment_rows(), self._gdn_rows_per_segment(B)))
130
+ x2 = torch.cat([x, torch.flip(x, dims=(1,))], dim=0) # (2B, L, D): [fw | reversed-for-bw]
131
+ o2 = self._gdn_int32_safe(x2)
132
+ o2 = torch.roll(o2, shifts=1, dims=1)
133
+ o2[:, 0, :] = 0.0
134
+ return o2[:B] + torch.flip(o2[B:], dims=(1,))