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.
- firepfn/__init__.py +7 -0
- firepfn/class_tree.py +77 -0
- firepfn/classifier.py +301 -0
- firepfn/encoding.py +347 -0
- firepfn/ensemble.py +44 -0
- firepfn/eval/__init__.py +14 -0
- firepfn/eval/analysis.py +294 -0
- firepfn/eval/plots.py +330 -0
- firepfn/eval/runtime.py +205 -0
- firepfn/eval/tabarena.py +388 -0
- firepfn/loading.py +97 -0
- firepfn/many_class.py +157 -0
- firepfn/model/__init__.py +5 -0
- firepfn/model/_mamba_block.py +49 -0
- firepfn/model/backbone.py +110 -0
- firepfn/model/cross_attention.py +123 -0
- firepfn/model/deltanet.py +134 -0
- firepfn/model/fire_pfn.py +396 -0
- firepfn/model/fla_autotune.py +73 -0
- firepfn/model/hydra2.py +537 -0
- firepfn/model/int32_safe.py +122 -0
- firepfn/model/kumo.py +704 -0
- firepfn/model/linear_attention.py +167 -0
- firepfn/model/stream_infer.py +568 -0
- firepfn/model/triton_rmsnorm.py +119 -0
- firepfn/model/triton_rope.py +152 -0
- firepfn/preprocessing.py +301 -0
- firepfn/train/__init__.py +3 -0
- firepfn/train/__main__.py +57 -0
- firepfn/train/_tabicl_dataset.py +1762 -0
- firepfn/train/configs.py +113 -0
- firepfn/train/loop.py +224 -0
- firepfn/train/optim.py +109 -0
- firepfn/train/prior.py +74 -0
- firepfn/train/schedule.py +125 -0
- firepfn-1.0.0.dev0.dist-info/METADATA +270 -0
- firepfn-1.0.0.dev0.dist-info/RECORD +46 -0
- firepfn-1.0.0.dev0.dist-info/WHEEL +5 -0
- firepfn-1.0.0.dev0.dist-info/licenses/AUTHORS +14 -0
- firepfn-1.0.0.dev0.dist-info/licenses/LICENSE +33 -0
- firepfn-1.0.0.dev0.dist-info/licenses/LICENSES/Apache-2.0.txt +176 -0
- firepfn-1.0.0.dev0.dist-info/licenses/LICENSES/BSD-3-Clause-TabICL.txt +236 -0
- firepfn-1.0.0.dev0.dist-info/licenses/LICENSES/MIT-Hydra.txt +21 -0
- firepfn-1.0.0.dev0.dist-info/licenses/LICENSES/OpenMDW-1.1-Kumo-Tabular-weights.txt +52 -0
- firepfn-1.0.0.dev0.dist-info/licenses/NOTICE +39 -0
- firepfn-1.0.0.dev0.dist-info/top_level.txt +1 -0
firepfn/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Copyright (c) 2025-2026, the FirePFN authors.
|
|
3
|
+
"""FirePFN: a tabular foundation model for in-context classification."""
|
|
4
|
+
__version__ = "1.0.0.dev0"
|
|
5
|
+
|
|
6
|
+
from firepfn.classifier import FirePFNClassifier # noqa: E402
|
|
7
|
+
__all__ = ["FirePFNClassifier", "__version__"]
|
firepfn/class_tree.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Copyright (c) 2025-2026, the FirePFN authors.
|
|
3
|
+
"""Balanced class tree for problems with more classes than the model's decoder has outputs.
|
|
4
|
+
|
|
5
|
+
A node with at most ``max_classes`` classes is a leaf (its labels are the class indices within the
|
|
6
|
+
node). Any other node splits its classes into ``min(ceil(K / max_classes), max_classes)``
|
|
7
|
+
consecutive groups of (almost) equal size and predicts the group; it has one child per group.
|
|
8
|
+
``FirePFNClassifier`` (many_class_strategy="tree") fits one model state per node on the rows of the
|
|
9
|
+
node's classes and multiplies the branch probabilities along the path from the root to a class.
|
|
10
|
+
The grouping follows TabICL's hierarchical classification (as in Inpriora).
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import math
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Any, Iterator, List, Optional, Tuple
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class Node:
|
|
23
|
+
classes: List[int] # class ids of the node (consecutive, sorted)
|
|
24
|
+
groups: Optional[List[List[int]]] = None # internal node: the classes of each child
|
|
25
|
+
children: List["Node"] = field(default_factory=list)
|
|
26
|
+
state: Any = None # fitted model state of the node
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def is_leaf(self) -> bool:
|
|
30
|
+
return self.groups is None
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def n_outputs(self) -> int:
|
|
34
|
+
return len(self.classes) if self.is_leaf else len(self.groups)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def balanced_groups(classes: List[int], max_classes: int) -> List[List[int]]:
|
|
38
|
+
"""``min(ceil(K / max_classes), max_classes)`` consecutive groups of (almost) equal size."""
|
|
39
|
+
k = len(classes)
|
|
40
|
+
g = min(math.ceil(k / max_classes), max_classes)
|
|
41
|
+
out, pos, left_classes, left_groups = [], 0, k, g
|
|
42
|
+
for _ in range(g):
|
|
43
|
+
size = math.ceil(left_classes / left_groups)
|
|
44
|
+
out.append(classes[pos:pos + size])
|
|
45
|
+
pos += size
|
|
46
|
+
left_classes -= size
|
|
47
|
+
left_groups -= 1
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def build_tree(classes: List[int], max_classes: int) -> Node:
|
|
52
|
+
node = Node(classes=list(classes))
|
|
53
|
+
if len(classes) > max_classes:
|
|
54
|
+
node.groups = balanced_groups(node.classes, max_classes)
|
|
55
|
+
node.children = [build_tree(g, max_classes) for g in node.groups]
|
|
56
|
+
return node
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def node_data(root: Node, y: np.ndarray) -> Iterator[Tuple[Node, np.ndarray, np.ndarray]]:
|
|
60
|
+
"""Yield (node, row indices of the node's classes, the node's labels of those rows), parents
|
|
61
|
+
before children. Internal nodes are labelled with the group index, leaves with the class index
|
|
62
|
+
within the node; rows keep their original order."""
|
|
63
|
+
n_classes = int(y.max()) + 1
|
|
64
|
+
|
|
65
|
+
def rec(node: Node, idx: np.ndarray):
|
|
66
|
+
lut = np.full(n_classes, -1, dtype=np.int64)
|
|
67
|
+
if node.is_leaf:
|
|
68
|
+
lut[node.classes] = np.arange(len(node.classes))
|
|
69
|
+
else:
|
|
70
|
+
for gi, g in enumerate(node.groups):
|
|
71
|
+
lut[g] = gi
|
|
72
|
+
yield node, idx, lut[y[idx]]
|
|
73
|
+
if not node.is_leaf:
|
|
74
|
+
for g, child in zip(node.groups, node.children):
|
|
75
|
+
yield from rec(child, idx[np.isin(y[idx], g)])
|
|
76
|
+
|
|
77
|
+
yield from rec(root, np.arange(len(y)))
|
firepfn/classifier.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Copyright (c) 2025-2026, the FirePFN authors.
|
|
3
|
+
"""scikit-learn interface of FirePFN.
|
|
4
|
+
|
|
5
|
+
from firepfn import FirePFNClassifier
|
|
6
|
+
clf = FirePFNClassifier().fit(X_train, y_train) # released weights from Hugging Face
|
|
7
|
+
proba = clf.predict_proba(X_test)
|
|
8
|
+
|
|
9
|
+
``fit`` preprocesses the training rows and encodes them once per ensemble member (encoder, label
|
|
10
|
+
embedding, backbone); ``predict_proba`` only encodes the query rows and cross-attends to that
|
|
11
|
+
cache.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import warnings
|
|
17
|
+
from typing import Optional
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
import sklearn.base
|
|
21
|
+
import torch
|
|
22
|
+
from sklearn.base import BaseEstimator, ClassifierMixin
|
|
23
|
+
from sklearn.preprocessing import LabelEncoder
|
|
24
|
+
from sklearn.utils.validation import check_is_fitted
|
|
25
|
+
|
|
26
|
+
# Loaded models, keyed by (model_path, device): fitting many classifiers (e.g. the base problems of
|
|
27
|
+
# a class decomposition) loads the weights once.
|
|
28
|
+
_model_cache: dict = {}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _member_batch_rows() -> int:
|
|
32
|
+
"""Context rows (members x rows) one batched context-cache build may use."""
|
|
33
|
+
v = os.environ.get("FIREPFN_MEMBER_BATCH_ROWS")
|
|
34
|
+
if v:
|
|
35
|
+
return int(v)
|
|
36
|
+
from firepfn.model.stream_infer import stream_ctx_rows
|
|
37
|
+
return stream_ctx_rows() or 262144
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class FirePFNClassifier(ClassifierMixin, BaseEstimator):
|
|
41
|
+
"""FirePFN classifier.
|
|
42
|
+
|
|
43
|
+
Parameters
|
|
44
|
+
----------
|
|
45
|
+
model_path : str or None, default=None
|
|
46
|
+
Checkpoint file (release or training format, see firepfn.loading). None downloads the
|
|
47
|
+
released weights from the Hugging Face Hub (``LUHAI/FirePFN``, cached after the first
|
|
48
|
+
call; the environment variable ``FIREPFN_MODEL_PATH`` points to a local file instead).
|
|
49
|
+
n_estimators : int, default=2
|
|
50
|
+
Ensemble members; each sees its own circular class shift, feature shift and context-row
|
|
51
|
+
shift of the data (see firepfn.ensemble). Logits are averaged.
|
|
52
|
+
max_features : int, default=200
|
|
53
|
+
Feature budget: wider tables are reduced to this many columns by ``feature_selection``;
|
|
54
|
+
also the reference of the feature-count scaling.
|
|
55
|
+
feature_selection : str, default="f_classif_sub"
|
|
56
|
+
See firepfn.preprocessing.make_preprocessing_pipeline.
|
|
57
|
+
softmax_temperature : float, default=1.0
|
|
58
|
+
Logits are divided by this before the softmax.
|
|
59
|
+
average_logits : bool, default=True
|
|
60
|
+
Average member logits (True) or probabilities (False).
|
|
61
|
+
feature_shift, row_shift : bool, default=True
|
|
62
|
+
Use feature / context-row shifts across ensemble members.
|
|
63
|
+
many_class_strategy : {"tree", "ecoc", "ovr", "error"}, default="tree"
|
|
64
|
+
More classes than the model's 10 outputs. "tree": a balanced class tree with at most 10
|
|
65
|
+
classes per node (firepfn.class_tree); every node is fitted on the rows of its own classes
|
|
66
|
+
and branch probabilities multiply along the path (fast: no full-table pass per base
|
|
67
|
+
problem). "ecoc" (error-correcting output codes: more accurate, slower) and "ovr"
|
|
68
|
+
(one-vs-rest) decompose into base problems that are each fitted by a copy of this
|
|
69
|
+
classifier on all rows (firepfn.many_class). "error" raises instead.
|
|
70
|
+
many_class_kwargs : dict or None
|
|
71
|
+
Options for ClassDecomposition ("ecoc", "ovr"), e.g. {"n_columns": 12} for "ecoc".
|
|
72
|
+
max_context_rows : int or None, default=100_000
|
|
73
|
+
Fit on a stratified random subset (seeded by ``random_state``) of at most this many
|
|
74
|
+
training rows. FirePFN was trained on contexts of up to 32,768 rows; beyond ~100k rows
|
|
75
|
+
more context no longer pays for its cost. None uses every training row (linear cost, runs
|
|
76
|
+
to millions of rows on one GPU).
|
|
77
|
+
precision : {"bf16", "fp16", "fp32"}, default="bf16"
|
|
78
|
+
Autocast precision on GPU.
|
|
79
|
+
device : str or None
|
|
80
|
+
None picks CUDA when available.
|
|
81
|
+
random_state : int, default=42
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def __init__(
|
|
85
|
+
self,
|
|
86
|
+
model_path: Optional[str] = None,
|
|
87
|
+
n_estimators: int = 2,
|
|
88
|
+
max_features: int = 200,
|
|
89
|
+
feature_selection: str = "f_classif_sub",
|
|
90
|
+
softmax_temperature: float = 1.0,
|
|
91
|
+
average_logits: bool = True,
|
|
92
|
+
feature_shift: bool = True,
|
|
93
|
+
row_shift: bool = True,
|
|
94
|
+
many_class_strategy: str = "tree",
|
|
95
|
+
many_class_kwargs: Optional[dict] = None,
|
|
96
|
+
max_context_rows: Optional[int] = 100_000,
|
|
97
|
+
precision: str = "bf16",
|
|
98
|
+
device: Optional[str] = None,
|
|
99
|
+
random_state: int = 42,
|
|
100
|
+
):
|
|
101
|
+
self.model_path = model_path
|
|
102
|
+
self.n_estimators = n_estimators
|
|
103
|
+
self.max_features = max_features
|
|
104
|
+
self.feature_selection = feature_selection
|
|
105
|
+
self.softmax_temperature = softmax_temperature
|
|
106
|
+
self.average_logits = average_logits
|
|
107
|
+
self.feature_shift = feature_shift
|
|
108
|
+
self.row_shift = row_shift
|
|
109
|
+
self.many_class_strategy = many_class_strategy
|
|
110
|
+
self.many_class_kwargs = many_class_kwargs
|
|
111
|
+
self.max_context_rows = max_context_rows
|
|
112
|
+
self.precision = precision
|
|
113
|
+
self.device = device
|
|
114
|
+
self.random_state = random_state
|
|
115
|
+
|
|
116
|
+
# ------------------------------------------------------------------ #
|
|
117
|
+
# Helpers
|
|
118
|
+
# ------------------------------------------------------------------ #
|
|
119
|
+
|
|
120
|
+
def _resolve_device(self) -> str:
|
|
121
|
+
if self.device is not None:
|
|
122
|
+
return self.device
|
|
123
|
+
return "cuda" if torch.cuda.is_available() else "cpu"
|
|
124
|
+
|
|
125
|
+
def _load_model(self, device: str):
|
|
126
|
+
from firepfn.loading import default_model_path, load_model
|
|
127
|
+
path = self.model_path if self.model_path is not None else default_model_path()
|
|
128
|
+
key = (path, device)
|
|
129
|
+
if key not in _model_cache:
|
|
130
|
+
# fla kernels otherwise re-autotune at every new context-size class.
|
|
131
|
+
from firepfn.model.fla_autotune import patch as _patch_fla
|
|
132
|
+
_patch_fla()
|
|
133
|
+
_model_cache[key] = load_model(path, device=device)
|
|
134
|
+
return _model_cache[key]
|
|
135
|
+
|
|
136
|
+
def _autocast(self):
|
|
137
|
+
dtype = {"bf16": torch.bfloat16, "fp16": torch.float16}.get(self.precision)
|
|
138
|
+
if self.precision not in ("bf16", "fp16", "fp32"):
|
|
139
|
+
raise ValueError(f"precision must be 'bf16', 'fp16' or 'fp32', got {self.precision!r}")
|
|
140
|
+
return torch.amp.autocast("cuda", enabled=dtype is not None and self.device_ != "cpu",
|
|
141
|
+
dtype=dtype or torch.float16)
|
|
142
|
+
|
|
143
|
+
# ------------------------------------------------------------------ #
|
|
144
|
+
# fit
|
|
145
|
+
# ------------------------------------------------------------------ #
|
|
146
|
+
|
|
147
|
+
def fit(self, X, y):
|
|
148
|
+
if self.max_context_rows is not None and len(y) > self.max_context_rows:
|
|
149
|
+
from sklearn.model_selection import train_test_split
|
|
150
|
+
y_arr = np.asarray(y)
|
|
151
|
+
idx = np.arange(len(y_arr))
|
|
152
|
+
_, counts = np.unique(y_arr, return_counts=True)
|
|
153
|
+
strat = y_arr if counts.min() >= 2 and len(counts) <= self.max_context_rows else None
|
|
154
|
+
idx, _ = train_test_split(idx, train_size=int(self.max_context_rows),
|
|
155
|
+
random_state=self.random_state, stratify=strat)
|
|
156
|
+
idx = np.sort(idx)
|
|
157
|
+
X = X.iloc[idx] if hasattr(X, "iloc") else np.asarray(X)[idx]
|
|
158
|
+
y = y.iloc[idx] if hasattr(y, "iloc") else y_arr[idx]
|
|
159
|
+
|
|
160
|
+
self.device_ = self._resolve_device()
|
|
161
|
+
self.model_, self.config_ = self._load_model(self.device_)
|
|
162
|
+
self.label_encoder_ = LabelEncoder()
|
|
163
|
+
y_enc = self.label_encoder_.fit_transform(y)
|
|
164
|
+
self.classes_ = self.label_encoder_.classes_
|
|
165
|
+
self.n_classes_ = len(self.classes_)
|
|
166
|
+
n_out = self.model_.decoder[-1].out_features
|
|
167
|
+
X_num = np.asarray(X, dtype=np.float32)
|
|
168
|
+
|
|
169
|
+
self.decomposition_ = None
|
|
170
|
+
self.tree_ = None
|
|
171
|
+
self.state_ = None
|
|
172
|
+
if self.n_classes_ > n_out:
|
|
173
|
+
if self.many_class_strategy == "tree":
|
|
174
|
+
return self._fit_class_tree(X_num, y_enc, n_out)
|
|
175
|
+
if self.many_class_strategy == "error":
|
|
176
|
+
raise ValueError(f"{self.n_classes_} classes but the model predicts at most {n_out}; "
|
|
177
|
+
f"set many_class_strategy to 'tree', 'ecoc' or 'ovr'.")
|
|
178
|
+
from firepfn.many_class import ClassDecomposition
|
|
179
|
+
base = sklearn.base.clone(self).set_params(many_class_strategy="error")
|
|
180
|
+
self.decomposition_ = ClassDecomposition(
|
|
181
|
+
base, strategy=self.many_class_strategy, max_classes=n_out,
|
|
182
|
+
random_state=self.random_state, **(self.many_class_kwargs or {})).fit(X_num, y_enc)
|
|
183
|
+
return self
|
|
184
|
+
|
|
185
|
+
X_train = self._fit_pipeline(X_num, y_enc)
|
|
186
|
+
self.state_ = self._make_state(X_train, torch.tensor(y_enc, dtype=torch.float32))
|
|
187
|
+
return self
|
|
188
|
+
|
|
189
|
+
def _fit_pipeline(self, X_num: np.ndarray, y_enc: np.ndarray) -> torch.Tensor:
|
|
190
|
+
from firepfn.preprocessing import make_preprocessing_pipeline
|
|
191
|
+
self.pipeline_ = make_preprocessing_pipeline(max_features=self.max_features,
|
|
192
|
+
feature_selection=self.feature_selection,
|
|
193
|
+
random_state=self.random_state)
|
|
194
|
+
with warnings.catch_warnings():
|
|
195
|
+
warnings.simplefilter("ignore")
|
|
196
|
+
X_train = self.pipeline_.fit_transform(X_num, y_enc)
|
|
197
|
+
return torch.tensor(X_train, dtype=torch.float32)
|
|
198
|
+
|
|
199
|
+
def _fit_class_tree(self, X_num: np.ndarray, y_enc: np.ndarray, n_out: int):
|
|
200
|
+
"""Preprocess once (feature selection on all classes), then fit one model state per node of
|
|
201
|
+
the balanced class tree on the rows of the node's classes."""
|
|
202
|
+
from firepfn.class_tree import build_tree, node_data
|
|
203
|
+
X_train = self._fit_pipeline(X_num, y_enc)
|
|
204
|
+
self.tree_ = build_tree(list(range(self.n_classes_)), n_out)
|
|
205
|
+
for node, idx, labels in node_data(self.tree_, y_enc):
|
|
206
|
+
node.state = self._make_state(X_train[torch.as_tensor(idx)],
|
|
207
|
+
torch.tensor(labels, dtype=torch.float32))
|
|
208
|
+
return self
|
|
209
|
+
|
|
210
|
+
def _make_state(self, X_train: torch.Tensor, y_train: torch.Tensor) -> dict:
|
|
211
|
+
"""Encode the labelled rows once per ensemble member; returns what predicting needs."""
|
|
212
|
+
from firepfn.ensemble import apply_ensemble_member, make_ensemble_configurations
|
|
213
|
+
from firepfn.model.stream_infer import stream_ctx_rows
|
|
214
|
+
dev = self.device_
|
|
215
|
+
n_train = X_train.shape[0]
|
|
216
|
+
# Long contexts: build each member's input on the host and move only that to the GPU.
|
|
217
|
+
thr = stream_ctx_rows()
|
|
218
|
+
member_dev = "cpu" if thr > 0 and n_train > thr else dev
|
|
219
|
+
xs = X_train.unsqueeze(1).to(member_dev) # (N, 1, H)
|
|
220
|
+
ys = y_train.unsqueeze(1).to(member_dev) # (N, 1)
|
|
221
|
+
n_cls = len(torch.unique(ys))
|
|
222
|
+
configs = make_ensemble_configurations(
|
|
223
|
+
xs.shape[2], n_cls, n_train, self.n_estimators,
|
|
224
|
+
self.feature_shift, self.row_shift, self.random_state)
|
|
225
|
+
self.model_.to(dev).eval()
|
|
226
|
+
# Members share every shape, so several of them run as one batch of tables; a group's
|
|
227
|
+
# context rows stay within FIREPFN_MEMBER_BATCH_ROWS (FIREPFN_MEMBER_BATCH caps the group size).
|
|
228
|
+
E = len(configs)
|
|
229
|
+
g = 1 if member_dev == "cpu" else max(1, min(E, _member_batch_rows() // max(n_train, 1)))
|
|
230
|
+
cap = int(os.environ.get("FIREPFN_MEMBER_BATCH", 0))
|
|
231
|
+
if cap > 0:
|
|
232
|
+
g = min(g, cap)
|
|
233
|
+
groups = [list(range(i, min(E, i + g))) for i in range(0, E, g)]
|
|
234
|
+
caches = []
|
|
235
|
+
with torch.inference_mode(), self._autocast():
|
|
236
|
+
for grp in groups:
|
|
237
|
+
members = [apply_ensemble_member(xs, ys, configs[j], n_train, n_cls) for j in grp]
|
|
238
|
+
x_ = torch.cat([m[0] for m in members], dim=1).to(dev) # (N, g, H)
|
|
239
|
+
y_ = torch.cat([m[1] for m in members], dim=1).to(dev) # (N, g)
|
|
240
|
+
del members
|
|
241
|
+
caches.append(self.model_.build_context_cache(x_, y_))
|
|
242
|
+
del x_, y_
|
|
243
|
+
return {"n_cls": n_cls, "configs": configs, "groups": groups, "caches": caches}
|
|
244
|
+
|
|
245
|
+
# ------------------------------------------------------------------ #
|
|
246
|
+
# predict
|
|
247
|
+
# ------------------------------------------------------------------ #
|
|
248
|
+
|
|
249
|
+
def predict_proba(self, X) -> np.ndarray:
|
|
250
|
+
check_is_fitted(self)
|
|
251
|
+
X_num = np.asarray(X, dtype=np.float32)
|
|
252
|
+
if self.decomposition_ is not None:
|
|
253
|
+
return self.decomposition_.predict_proba(X_num)
|
|
254
|
+
with warnings.catch_warnings():
|
|
255
|
+
warnings.simplefilter("ignore")
|
|
256
|
+
X_test = self.pipeline_.transform(X_num)
|
|
257
|
+
if self.tree_ is not None:
|
|
258
|
+
return self._tree_proba(self.tree_, X_test)
|
|
259
|
+
return self._predict_state(self.state_, X_test)
|
|
260
|
+
|
|
261
|
+
def _tree_proba(self, node, X_test: np.ndarray) -> np.ndarray:
|
|
262
|
+
"""(M, len(node.classes)) probabilities in node.classes order: a leaf's probabilities, or
|
|
263
|
+
for an internal node its group probabilities times each child's class probabilities."""
|
|
264
|
+
p = self._predict_state(node.state, X_test)
|
|
265
|
+
if node.is_leaf:
|
|
266
|
+
return p
|
|
267
|
+
return np.concatenate([p[:, i:i + 1] * self._tree_proba(child, X_test)
|
|
268
|
+
for i, child in enumerate(node.children)], axis=1)
|
|
269
|
+
|
|
270
|
+
def _predict_state(self, state: dict, X_test: np.ndarray) -> np.ndarray:
|
|
271
|
+
dev = self.device_
|
|
272
|
+
xq = torch.tensor(X_test, dtype=torch.float32).unsqueeze(1).to(dev) # (M, 1, H)
|
|
273
|
+
n_cls, configs = state["n_cls"], state["configs"]
|
|
274
|
+
cls_idx = torch.arange(n_cls, device=dev)
|
|
275
|
+
total = None
|
|
276
|
+
with torch.inference_mode(), self._autocast():
|
|
277
|
+
for grp, cache in zip(state["groups"], state["caches"]):
|
|
278
|
+
xs_, shifts = [], []
|
|
279
|
+
for j in grp:
|
|
280
|
+
class_shift, feature_shift, _ = configs[j]
|
|
281
|
+
fs = int(feature_shift)
|
|
282
|
+
xs_.append(torch.cat([xq[..., fs:], xq[..., :fs]], dim=-1))
|
|
283
|
+
shifts.append(int(class_shift))
|
|
284
|
+
x_ = torch.cat(xs_, dim=1) # (M, g, H)
|
|
285
|
+
del xs_
|
|
286
|
+
out = self.model_.predict_from_cache(cache, x_) # (M, g, n_out)
|
|
287
|
+
out = out[:, :, :n_cls].float() / self.softmax_temperature
|
|
288
|
+
# undo each member's class rotation: new[c] = out[(c + cs) % n_cls]
|
|
289
|
+
idx = (cls_idx[None, :] + torch.tensor(shifts, device=dev)[:, None]) % n_cls
|
|
290
|
+
out = out.gather(2, idx.unsqueeze(0).expand(out.shape[0], -1, -1))
|
|
291
|
+
if not self.average_logits:
|
|
292
|
+
out = torch.nn.functional.softmax(out, dim=-1)
|
|
293
|
+
out = out.sum(dim=1, keepdim=True) # (M, 1, n_cls)
|
|
294
|
+
total = out if total is None else total + out
|
|
295
|
+
out = total / len(configs)
|
|
296
|
+
if self.average_logits:
|
|
297
|
+
out = torch.nn.functional.softmax(out, dim=-1)
|
|
298
|
+
return out.squeeze(1).cpu().numpy()
|
|
299
|
+
|
|
300
|
+
def predict(self, X) -> np.ndarray:
|
|
301
|
+
return self.classes_[np.argmax(self.predict_proba(X), axis=1)]
|