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
|
@@ -0,0 +1,1762 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Copyright (c) 2025, Soda team @ Inria.
|
|
3
|
+
# Copyright (c) 2026, the FirePFN authors (modifications).
|
|
4
|
+
#
|
|
5
|
+
# From TabICL (https://github.com/soda-inria/tabicl), src/tabicl/prior/_dataset.py, BSD 3-Clause
|
|
6
|
+
# License (see LICENSES/BSD-3-Clause-TabICL.txt). Everything else of the prior is imported from the
|
|
7
|
+
# `tabicl` package (== 2.2.0), whose remaining prior modules are unchanged. Modified by the
|
|
8
|
+
# FirePFN authors:
|
|
9
|
+
# * get_batch(..., forced_group_hp=...) and sample_group_hp(): fix seq_len / train_size /
|
|
10
|
+
# num_features / num_classes / sampled hyperparameters for a whole call (used by the
|
|
11
|
+
# context-bucket schedule, firepfn/train/schedule.py);
|
|
12
|
+
# * the number of classes is drawn once per subgroup (shared by its tables) instead of once per
|
|
13
|
+
# table;
|
|
14
|
+
# * GraphPrior's rejection loop is bounded (100 attempts) instead of `while True`.
|
|
15
|
+
"""
|
|
16
|
+
The module offers a flexible framework for creating diverse, realistic tabular datasets
|
|
17
|
+
with controlled properties, which can be used for training and evaluating in-context
|
|
18
|
+
learning models. Key features include:
|
|
19
|
+
|
|
20
|
+
- Controlled feature relationships and causal structures via multiple generation methods
|
|
21
|
+
- Customizable feature distributions with mixed continuous and categorical variables
|
|
22
|
+
- Flexible train/test splits optimized for in-context learning evaluation
|
|
23
|
+
- Batch generation capabilities with hierarchical parameter sharing
|
|
24
|
+
- Memory-efficient handling of variable-length datasets
|
|
25
|
+
|
|
26
|
+
The main class is PriorDataset, which provides an iterable interface for generating
|
|
27
|
+
an infinite stream of synthetic datasets with diverse characteristics.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import functools
|
|
33
|
+
import os
|
|
34
|
+
|
|
35
|
+
import sys
|
|
36
|
+
import math
|
|
37
|
+
import warnings
|
|
38
|
+
from typing import Dict, Tuple, Union, Optional, Any, List, Callable
|
|
39
|
+
|
|
40
|
+
import numpy as np
|
|
41
|
+
import psutil
|
|
42
|
+
import threadpoolctl
|
|
43
|
+
from scipy.stats import loguniform
|
|
44
|
+
import multiprocessing as mp
|
|
45
|
+
|
|
46
|
+
import torch
|
|
47
|
+
import torch.nn.functional as F
|
|
48
|
+
from sklearn.ensemble import ExtraTreesRegressor
|
|
49
|
+
from torch import Tensor
|
|
50
|
+
from torch.nested import nested_tensor
|
|
51
|
+
from torch.utils.data import IterableDataset
|
|
52
|
+
|
|
53
|
+
from tabicl.prior.graph_lib._config import PriorConfig
|
|
54
|
+
from tabicl.prior._mlp_scm import MLPSCM
|
|
55
|
+
from tabicl.prior._tree_scm import TreeSCM
|
|
56
|
+
from tabicl.prior._graph_scm import GraphSCM
|
|
57
|
+
|
|
58
|
+
from tabicl.prior._hp_sampling import HpSamplerList
|
|
59
|
+
from tabicl.prior._reg2cls import Reg2Cls
|
|
60
|
+
from tabicl.prior._prior_config import DEFAULT_FIXED_HP, DEFAULT_SAMPLED_HP
|
|
61
|
+
|
|
62
|
+
warnings.filterwarnings(
|
|
63
|
+
"ignore", message=".*The PyTorch API of nested tensors is in prototype stage.*", category=UserWarning
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def run_parallel(func: Callable, args: List[Any], n_jobs: int = -1) -> List[Any]:
|
|
68
|
+
"""
|
|
69
|
+
Uses a multiprocessing.Pool to evaluate func on all values in args, with n_jobs processes running in parallel.
|
|
70
|
+
|
|
71
|
+
:param func: Function to be called.
|
|
72
|
+
:param args: List of arguments to call the function with.
|
|
73
|
+
:param n_jobs: Number of jobs (if -1, set to the number of physical cores).
|
|
74
|
+
:return: Returns the list of values returned by the function evaluated on different values from args.
|
|
75
|
+
"""
|
|
76
|
+
ctx = mp.get_context(method='fork') # not sure if this is necessary
|
|
77
|
+
with ctx.Pool(processes=n_jobs if n_jobs >= 1 else psutil.cpu_count(logical=False),
|
|
78
|
+
initializer=functools.partial(torch.set_num_threads, 1)) as pool:
|
|
79
|
+
return pool.map(func, args)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Prior:
|
|
83
|
+
"""
|
|
84
|
+
Abstract base class for dataset prior generators.
|
|
85
|
+
|
|
86
|
+
Defines the interface and common functionality for different types of
|
|
87
|
+
synthetic dataset generators.
|
|
88
|
+
|
|
89
|
+
Parameters
|
|
90
|
+
----------
|
|
91
|
+
regression : bool, default=False
|
|
92
|
+
If True, generates regression datasets. Otherwise, generates classification datasets.
|
|
93
|
+
|
|
94
|
+
batch_size : int, default=256
|
|
95
|
+
Total number of datasets to generate per batch
|
|
96
|
+
|
|
97
|
+
min_features : int, default=2
|
|
98
|
+
Minimum number of features per dataset
|
|
99
|
+
|
|
100
|
+
max_features : int, default=100
|
|
101
|
+
Maximum number of features per dataset
|
|
102
|
+
|
|
103
|
+
max_classes : int, default=10
|
|
104
|
+
Maximum number of target classes
|
|
105
|
+
|
|
106
|
+
min_seq_len : int, default=None
|
|
107
|
+
Minimum samples per dataset. If None, uses max_seq_len
|
|
108
|
+
|
|
109
|
+
max_seq_len : int, default=1024
|
|
110
|
+
Maximum samples per dataset
|
|
111
|
+
|
|
112
|
+
log_seq_len : bool, default=False
|
|
113
|
+
If True, sample sequence length from a log-uniform distribution
|
|
114
|
+
|
|
115
|
+
min_train_size : int|float, default=0.1
|
|
116
|
+
Position or ratio for train/test split start. If int, absolute position.
|
|
117
|
+
If float between 0 and 1, specifies a fraction of sequence length.
|
|
118
|
+
|
|
119
|
+
max_train_size : int|float, default=0.9
|
|
120
|
+
Position or ratio for train/test split end. If int, absolute position.
|
|
121
|
+
If float between 0 and 1, specifies a fraction of sequence length.
|
|
122
|
+
|
|
123
|
+
replay_small : bool, default=False
|
|
124
|
+
If True, occasionally sample smaller sequence lengths with
|
|
125
|
+
specific distributions to ensure model robustness on smaller datasets
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
def __init__(
|
|
129
|
+
self,
|
|
130
|
+
regression: bool = False,
|
|
131
|
+
batch_size: int = 256,
|
|
132
|
+
min_features: int = 2,
|
|
133
|
+
max_features: int = 100,
|
|
134
|
+
max_classes: int = 10,
|
|
135
|
+
min_seq_len: Optional[int] = None,
|
|
136
|
+
max_seq_len: int = 1024,
|
|
137
|
+
log_seq_len: bool = False,
|
|
138
|
+
min_train_size: Union[int, float] = 0.1,
|
|
139
|
+
max_train_size: Union[int, float] = 0.9,
|
|
140
|
+
replay_small: bool = False,
|
|
141
|
+
):
|
|
142
|
+
self.regression = regression
|
|
143
|
+
self.batch_size = batch_size
|
|
144
|
+
|
|
145
|
+
assert min_features <= max_features, "Invalid feature range"
|
|
146
|
+
self.min_features = min_features
|
|
147
|
+
self.max_features = max_features
|
|
148
|
+
|
|
149
|
+
self.max_classes = 0 if regression else max_classes
|
|
150
|
+
self.min_seq_len = min_seq_len
|
|
151
|
+
self.max_seq_len = max_seq_len
|
|
152
|
+
self.log_seq_len = log_seq_len
|
|
153
|
+
|
|
154
|
+
self.validate_train_size_range(min_train_size, max_train_size)
|
|
155
|
+
self.min_train_size = min_train_size
|
|
156
|
+
self.max_train_size = max_train_size
|
|
157
|
+
self.replay_small = replay_small
|
|
158
|
+
|
|
159
|
+
@staticmethod
|
|
160
|
+
def validate_train_size_range(min_train_size: Union[int, float], max_train_size: Union[int, float]) -> None:
|
|
161
|
+
"""
|
|
162
|
+
Checks if the training size range is valid.
|
|
163
|
+
|
|
164
|
+
Parameters
|
|
165
|
+
----------
|
|
166
|
+
min_train_size : int|float
|
|
167
|
+
Minimum training size (position or ratio)
|
|
168
|
+
|
|
169
|
+
max_train_size : int|float
|
|
170
|
+
Maximum training size (position or ratio)
|
|
171
|
+
|
|
172
|
+
Raises
|
|
173
|
+
------
|
|
174
|
+
AssertionError
|
|
175
|
+
If training size range is invalid
|
|
176
|
+
ValueError
|
|
177
|
+
If training size types are mismatched or invalid
|
|
178
|
+
"""
|
|
179
|
+
# Check for numeric types only
|
|
180
|
+
if not isinstance(min_train_size, (int, float)) or not isinstance(max_train_size, (int, float)):
|
|
181
|
+
raise TypeError("Training sizes must be int or float")
|
|
182
|
+
|
|
183
|
+
# Check for valid ranges based on type
|
|
184
|
+
if isinstance(min_train_size, int) and isinstance(max_train_size, int):
|
|
185
|
+
assert 0 < min_train_size < max_train_size, "0 < min_train_size < max_train_size"
|
|
186
|
+
elif isinstance(min_train_size, float) and isinstance(max_train_size, float):
|
|
187
|
+
# Allow min == max to express a fixed train fraction (e.g. the 80% used in
|
|
188
|
+
# TabICLv2 pretraining stages 2 & 3); the float sampler uses np.random.uniform.
|
|
189
|
+
assert 0 < min_train_size <= max_train_size < 1, "0 < min_train_size <= max_train_size < 1"
|
|
190
|
+
else:
|
|
191
|
+
raise ValueError("Both training sizes must be of the same type (int or float)")
|
|
192
|
+
|
|
193
|
+
@staticmethod
|
|
194
|
+
def sample_seq_len(
|
|
195
|
+
min_seq_len: Optional[int], max_seq_len: int, log: bool = False, replay_small: bool = False
|
|
196
|
+
) -> int:
|
|
197
|
+
"""
|
|
198
|
+
Selects a random sequence length within the specified range.
|
|
199
|
+
|
|
200
|
+
This method provides flexible sampling strategies for dataset sizes, including
|
|
201
|
+
occasional re-sampling of smaller sequence lengths for better training diversity.
|
|
202
|
+
|
|
203
|
+
Parameters
|
|
204
|
+
----------
|
|
205
|
+
min_seq_len : int, optional
|
|
206
|
+
Minimum sequence length. If None, returns max_seq_len directly.
|
|
207
|
+
|
|
208
|
+
max_seq_len : int
|
|
209
|
+
Maximum sequence length
|
|
210
|
+
|
|
211
|
+
log : bool, default=False
|
|
212
|
+
If True, sample from a log-uniform distribution to better
|
|
213
|
+
cover the range of possible sizes
|
|
214
|
+
|
|
215
|
+
replay_small : bool, default=False
|
|
216
|
+
If True, occasionally sample smaller sequence lengths with
|
|
217
|
+
specific distributions to ensure model robustness on smaller datasets
|
|
218
|
+
|
|
219
|
+
Returns
|
|
220
|
+
-------
|
|
221
|
+
int
|
|
222
|
+
The sampled sequence length
|
|
223
|
+
"""
|
|
224
|
+
if min_seq_len is None:
|
|
225
|
+
return max_seq_len
|
|
226
|
+
|
|
227
|
+
if log:
|
|
228
|
+
seq_len = int(loguniform.rvs(min_seq_len, max_seq_len))
|
|
229
|
+
else:
|
|
230
|
+
seq_len = np.random.randint(min_seq_len, max_seq_len)
|
|
231
|
+
|
|
232
|
+
if replay_small:
|
|
233
|
+
p = np.random.random()
|
|
234
|
+
if p < 0.05:
|
|
235
|
+
return np.random.randint(200, 1000)
|
|
236
|
+
elif p < 0.3:
|
|
237
|
+
return int(loguniform.rvs(1000, 10000))
|
|
238
|
+
else:
|
|
239
|
+
return seq_len
|
|
240
|
+
else:
|
|
241
|
+
return seq_len
|
|
242
|
+
|
|
243
|
+
@staticmethod
|
|
244
|
+
def sample_train_size(min_train_size: Union[int, float], max_train_size: Union[int, float], seq_len: int) -> int:
|
|
245
|
+
"""
|
|
246
|
+
Selects a random training size within the specified range.
|
|
247
|
+
|
|
248
|
+
This method handles both absolute position and fractional ratio approaches
|
|
249
|
+
for determining the training/test split point.
|
|
250
|
+
|
|
251
|
+
Parameters
|
|
252
|
+
----------
|
|
253
|
+
min_train_size : int|float
|
|
254
|
+
Minimum training size. If int, used as absolute position.
|
|
255
|
+
If float between 0 and 1, used as ratio of sequence length.
|
|
256
|
+
|
|
257
|
+
max_train_size : int|float
|
|
258
|
+
Maximum training size. If int, used as absolute position.
|
|
259
|
+
If float between 0 and 1, used as ratio of sequence length.
|
|
260
|
+
|
|
261
|
+
seq_len : int
|
|
262
|
+
Total sequence length
|
|
263
|
+
|
|
264
|
+
Returns
|
|
265
|
+
-------
|
|
266
|
+
int
|
|
267
|
+
The sampled training size position
|
|
268
|
+
|
|
269
|
+
Raises
|
|
270
|
+
------
|
|
271
|
+
ValueError
|
|
272
|
+
If training size range has incompatible types
|
|
273
|
+
"""
|
|
274
|
+
if isinstance(min_train_size, int) and isinstance(max_train_size, int):
|
|
275
|
+
train_size = np.random.randint(min_train_size, max_train_size)
|
|
276
|
+
elif isinstance(min_train_size, float) and isinstance(min_train_size, float):
|
|
277
|
+
train_size = np.random.uniform(min_train_size, max_train_size)
|
|
278
|
+
train_size = int(seq_len * train_size)
|
|
279
|
+
else:
|
|
280
|
+
raise ValueError("Invalid training size range.")
|
|
281
|
+
return train_size
|
|
282
|
+
|
|
283
|
+
@staticmethod
|
|
284
|
+
def adjust_max_features(seq_len: int, max_features: int) -> int:
|
|
285
|
+
"""
|
|
286
|
+
Adjusts the maximum number of features based on the sequence length.
|
|
287
|
+
|
|
288
|
+
This method implements an adaptive feature limit that scales inversely
|
|
289
|
+
with sequence length. Longer sequences are restricted to fewer features
|
|
290
|
+
to prevent memory issues and excessive computation times while still
|
|
291
|
+
maintaining dataset diversity and learning difficulty.
|
|
292
|
+
|
|
293
|
+
Parameters
|
|
294
|
+
----------
|
|
295
|
+
seq_len : int
|
|
296
|
+
Sequence length (number of samples)
|
|
297
|
+
|
|
298
|
+
max_features : int
|
|
299
|
+
Original maximum number of features
|
|
300
|
+
|
|
301
|
+
Returns
|
|
302
|
+
-------
|
|
303
|
+
int
|
|
304
|
+
Adjusted maximum number of features, ensuring computational feasibility
|
|
305
|
+
"""
|
|
306
|
+
if seq_len <= 10240:
|
|
307
|
+
return max_features
|
|
308
|
+
elif 10240 < seq_len <= 20000:
|
|
309
|
+
return min(80, max_features)
|
|
310
|
+
elif 20000 < seq_len <= 30000:
|
|
311
|
+
return min(60, max_features)
|
|
312
|
+
elif 30000 < seq_len <= 40000:
|
|
313
|
+
return min(40, max_features)
|
|
314
|
+
elif 40000 < seq_len <= 50000:
|
|
315
|
+
return min(30, max_features)
|
|
316
|
+
elif 50000 < seq_len <= 60000:
|
|
317
|
+
return min(20, max_features)
|
|
318
|
+
elif 60000 < seq_len <= 65000:
|
|
319
|
+
return min(15, max_features)
|
|
320
|
+
else:
|
|
321
|
+
return 10
|
|
322
|
+
|
|
323
|
+
@staticmethod
|
|
324
|
+
def delete_unique_features(X: Tensor, d: Tensor) -> Tuple[Tensor, Tensor]:
|
|
325
|
+
"""
|
|
326
|
+
Removes features that have only one unique value across all samples.
|
|
327
|
+
|
|
328
|
+
Single-value features provide no useful information for learning since they
|
|
329
|
+
have zero variance. This method identifies and removes such constant features
|
|
330
|
+
to improve model training efficiency and stability. The removed features are
|
|
331
|
+
replaced with zero padding to maintain tensor dimensions.
|
|
332
|
+
|
|
333
|
+
Parameters
|
|
334
|
+
----------
|
|
335
|
+
X : Tensor
|
|
336
|
+
Input features tensor of shape (B, T, H) where:
|
|
337
|
+
- B is batch size
|
|
338
|
+
- T is sequence length
|
|
339
|
+
- H is feature dimensionality
|
|
340
|
+
|
|
341
|
+
d : Tensor
|
|
342
|
+
Number of features per dataset of shape (B,), indicating how many
|
|
343
|
+
features are actually used in each dataset (rest is padding)
|
|
344
|
+
|
|
345
|
+
Returns
|
|
346
|
+
-------
|
|
347
|
+
tuple
|
|
348
|
+
(X_new, d_new) where:
|
|
349
|
+
- X_new is the filtered tensor with non-informative features removed
|
|
350
|
+
- d_new is the updated feature count per dataset
|
|
351
|
+
"""
|
|
352
|
+
|
|
353
|
+
def filter_unique_features(xi: Tensor, di: int) -> Tuple[Tensor, Tensor]:
|
|
354
|
+
"""Filters features with only one unique value from a single dataset."""
|
|
355
|
+
num_features = xi.shape[-1]
|
|
356
|
+
# Only consider actual features (up to di, ignoring padding)
|
|
357
|
+
xi = xi[:, :di]
|
|
358
|
+
# Identify features with more than one unique value (informative features)
|
|
359
|
+
unique_mask = [len(torch.unique(xi[:, j])) > 1 for j in range(di)]
|
|
360
|
+
di_new = sum(unique_mask)
|
|
361
|
+
# Create new tensor with only informative features, padding the rest
|
|
362
|
+
xi_new = F.pad(xi[:, unique_mask], pad=(0, num_features - di_new), mode="constant", value=0)
|
|
363
|
+
return xi_new, torch.tensor(di_new, device=xi.device)
|
|
364
|
+
|
|
365
|
+
# Process each dataset in the batch independently
|
|
366
|
+
filtered_results = [filter_unique_features(xi, di) for xi, di in zip(X, d)]
|
|
367
|
+
X_new, d_new = [torch.stack(res) for res in zip(*filtered_results)]
|
|
368
|
+
|
|
369
|
+
return X_new, d_new
|
|
370
|
+
|
|
371
|
+
@staticmethod
|
|
372
|
+
def cls_sanity_check(X: Tensor, y: Tensor, train_size: int, n_attempts: int = 10, min_classes: int = 2) -> bool:
|
|
373
|
+
"""
|
|
374
|
+
Verifies that both train and test sets contain all classes for classification datasets.
|
|
375
|
+
|
|
376
|
+
For in-context learning to work properly, we need both the train and test
|
|
377
|
+
sets to contain examples from all classes. This method checks this condition
|
|
378
|
+
and attempts to fix invalid splits by randomly permuting the data.
|
|
379
|
+
|
|
380
|
+
Parameters
|
|
381
|
+
----------
|
|
382
|
+
X : Tensor
|
|
383
|
+
Input features tensor of shape (B, T, H)
|
|
384
|
+
|
|
385
|
+
y : Tensor
|
|
386
|
+
Target Targets tensor of shape (B, T)
|
|
387
|
+
|
|
388
|
+
train_size : int
|
|
389
|
+
Position to split the data into train and test sets
|
|
390
|
+
|
|
391
|
+
n_attempts : int, default=10
|
|
392
|
+
Number of random permutations to try for fixing invalid splits
|
|
393
|
+
|
|
394
|
+
min_classes : int, default=2
|
|
395
|
+
Minimum number of classes required in both train and test sets
|
|
396
|
+
|
|
397
|
+
Returns
|
|
398
|
+
-------
|
|
399
|
+
bool
|
|
400
|
+
True if all datasets have valid splits, False otherwise
|
|
401
|
+
"""
|
|
402
|
+
|
|
403
|
+
def is_valid_split(yi: Tensor) -> bool:
|
|
404
|
+
"""Check if a single dataset has a valid train/test split."""
|
|
405
|
+
# Guard against invalid train_size
|
|
406
|
+
if train_size <= 0 or train_size >= yi.shape[0]:
|
|
407
|
+
return False
|
|
408
|
+
|
|
409
|
+
# A valid split requires both train and test sets to have the same classes
|
|
410
|
+
# and at least min_classes different classes must be present
|
|
411
|
+
unique_tr = torch.unique(yi[:train_size])
|
|
412
|
+
unique_te = torch.unique(yi[train_size:])
|
|
413
|
+
return set(unique_tr.tolist()) == set(unique_te.tolist()) and len(unique_tr) >= min_classes
|
|
414
|
+
|
|
415
|
+
# Check each dataset in the batch
|
|
416
|
+
for i, (xi, yi) in enumerate(zip(X, y)):
|
|
417
|
+
if is_valid_split(yi):
|
|
418
|
+
continue
|
|
419
|
+
|
|
420
|
+
# If the dataset has an invalid split, try to fix it with random permutations
|
|
421
|
+
succeeded = False
|
|
422
|
+
for _ in range(n_attempts):
|
|
423
|
+
# Generate a random permutation of the samples
|
|
424
|
+
perm = torch.randperm(yi.shape[0])
|
|
425
|
+
yi_perm = yi[perm]
|
|
426
|
+
xi_perm = xi[perm]
|
|
427
|
+
# Check if the permutation results in a valid split
|
|
428
|
+
if is_valid_split(yi_perm):
|
|
429
|
+
X[i], y[i] = xi_perm, yi_perm
|
|
430
|
+
succeeded = True
|
|
431
|
+
break
|
|
432
|
+
|
|
433
|
+
if not succeeded: # No valid split was found after all attempts
|
|
434
|
+
return False
|
|
435
|
+
|
|
436
|
+
return True
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
class SCMPrior(Prior):
|
|
440
|
+
"""
|
|
441
|
+
Generates synthetic datasets using Structural Causal Models (SCM).
|
|
442
|
+
|
|
443
|
+
The data generation process follows a hierarchical structure:
|
|
444
|
+
1. Generate a list of parameters for each dataset, respecting group/subgroup sharing.
|
|
445
|
+
2. Process the parameter list to generate datasets, applying necessary transformations and checks.
|
|
446
|
+
|
|
447
|
+
Parameters
|
|
448
|
+
----------
|
|
449
|
+
regression : bool, default=False
|
|
450
|
+
If True, generates regression datasets. Otherwise, generates classification datasets.
|
|
451
|
+
|
|
452
|
+
batch_size : int, default=256
|
|
453
|
+
Total number of datasets to generate per batch
|
|
454
|
+
|
|
455
|
+
batch_size_per_gp : int, default=4
|
|
456
|
+
Number of datasets per group, sharing similar characteristics
|
|
457
|
+
|
|
458
|
+
batch_size_per_subgp : int, default=None
|
|
459
|
+
Number of datasets per subgroup, with more similar causal structures
|
|
460
|
+
If None, defaults to batch_size_per_gp
|
|
461
|
+
|
|
462
|
+
min_features : int, default=2
|
|
463
|
+
Minimum number of features per dataset
|
|
464
|
+
|
|
465
|
+
max_features : int, default=100
|
|
466
|
+
Maximum number of features per dataset
|
|
467
|
+
|
|
468
|
+
max_classes : int, default=10
|
|
469
|
+
Maximum number of target classes
|
|
470
|
+
|
|
471
|
+
min_seq_len : int, default=None
|
|
472
|
+
Minimum samples per dataset. If None, uses max_seq_len directly.
|
|
473
|
+
|
|
474
|
+
max_seq_len : int, default=1024
|
|
475
|
+
Maximum samples per dataset
|
|
476
|
+
|
|
477
|
+
log_seq_len : bool, default=False
|
|
478
|
+
If True, sample sequence length from a log-uniform distribution
|
|
479
|
+
|
|
480
|
+
seq_len_per_gp : bool = False
|
|
481
|
+
If True, sample sequence length per group, allowing variable-sized datasets
|
|
482
|
+
|
|
483
|
+
min_train_size : int|float, default=0.1
|
|
484
|
+
Position or ratio for train/test split start. If int, absolute position.
|
|
485
|
+
If float between 0 and 1, specifies a fraction of sequence length.
|
|
486
|
+
|
|
487
|
+
max_train_size : int|float, default=0.9
|
|
488
|
+
Position or ratio for train/test split end. If int, absolute position.
|
|
489
|
+
If float between 0 and 1, specifies a fraction of sequence length.
|
|
490
|
+
|
|
491
|
+
replay_small : bool, default=False
|
|
492
|
+
If True, occasionally sample smaller sequence lengths with
|
|
493
|
+
specific distributions to ensure model robustness on smaller datasets
|
|
494
|
+
|
|
495
|
+
prior_type : str, default="mlp_scm"
|
|
496
|
+
Type of prior: 'mlp_scm' (default), 'tree_scm', or 'mix_scm'
|
|
497
|
+
'mix_scm' randomly selects between 'mlp_scm' and 'tree_scm' based on probabilities.
|
|
498
|
+
|
|
499
|
+
fixed_hp : dict, default=DEFAULT_FIXED_HP
|
|
500
|
+
Fixed structural configuration parameters
|
|
501
|
+
|
|
502
|
+
sampled_hp : dict, default=DEFAULT_SAMPLED_HP
|
|
503
|
+
Parameters sampled during generation
|
|
504
|
+
|
|
505
|
+
n_jobs : int, default=-1
|
|
506
|
+
Number of parallel jobs to run (-1 means using all processors).
|
|
507
|
+
|
|
508
|
+
num_threads_per_generate : int, default=1
|
|
509
|
+
Number of threads per job for dataset generation
|
|
510
|
+
|
|
511
|
+
device : str, default="cpu"
|
|
512
|
+
Computation device ('cpu' or 'cuda')
|
|
513
|
+
"""
|
|
514
|
+
|
|
515
|
+
def __init__(
|
|
516
|
+
self,
|
|
517
|
+
regression: bool = False,
|
|
518
|
+
batch_size: int = 256,
|
|
519
|
+
batch_size_per_gp: int = 4,
|
|
520
|
+
batch_size_per_subgp: Optional[int] = None,
|
|
521
|
+
min_features: int = 2,
|
|
522
|
+
max_features: int = 100,
|
|
523
|
+
max_classes: int = 10,
|
|
524
|
+
min_seq_len: Optional[int] = None,
|
|
525
|
+
max_seq_len: int = 1024,
|
|
526
|
+
log_seq_len: bool = False,
|
|
527
|
+
log_n_features: bool = False,
|
|
528
|
+
seq_len_per_gp: bool = False,
|
|
529
|
+
min_train_size: Union[int, float] = 0.1,
|
|
530
|
+
max_train_size: Union[int, float] = 0.9,
|
|
531
|
+
replay_small: bool = False,
|
|
532
|
+
prior_type: str = "mlp_scm",
|
|
533
|
+
fixed_hp: Dict[str, Any] = DEFAULT_FIXED_HP,
|
|
534
|
+
sampled_hp: Dict[str, Any] = DEFAULT_SAMPLED_HP,
|
|
535
|
+
n_jobs: int = -1,
|
|
536
|
+
num_threads_per_generate: int = 1,
|
|
537
|
+
device: str = "cpu",
|
|
538
|
+
config: Optional[PriorConfig] = None,
|
|
539
|
+
):
|
|
540
|
+
super().__init__(
|
|
541
|
+
regression=regression,
|
|
542
|
+
batch_size=batch_size,
|
|
543
|
+
min_features=min_features,
|
|
544
|
+
max_features=max_features,
|
|
545
|
+
max_classes=max_classes,
|
|
546
|
+
min_seq_len=min_seq_len,
|
|
547
|
+
max_seq_len=max_seq_len,
|
|
548
|
+
log_seq_len=log_seq_len,
|
|
549
|
+
min_train_size=min_train_size,
|
|
550
|
+
max_train_size=max_train_size,
|
|
551
|
+
replay_small=replay_small,
|
|
552
|
+
)
|
|
553
|
+
|
|
554
|
+
self.batch_size_per_gp = batch_size_per_gp
|
|
555
|
+
self.batch_size_per_subgp = batch_size_per_subgp or batch_size_per_gp
|
|
556
|
+
self.seq_len_per_gp = seq_len_per_gp
|
|
557
|
+
self.prior_type = prior_type
|
|
558
|
+
self.fixed_hp = fixed_hp
|
|
559
|
+
self.sampled_hp = sampled_hp
|
|
560
|
+
self.n_jobs = n_jobs
|
|
561
|
+
self.num_threads_per_generate = num_threads_per_generate
|
|
562
|
+
self.device = device
|
|
563
|
+
self.log_n_features = log_n_features
|
|
564
|
+
self.config = config or PriorConfig()
|
|
565
|
+
|
|
566
|
+
def hp_sampling(self) -> Dict[str, Any]:
|
|
567
|
+
"""
|
|
568
|
+
Sample hyperparameters for dataset generation.
|
|
569
|
+
|
|
570
|
+
Returns
|
|
571
|
+
-------
|
|
572
|
+
dict
|
|
573
|
+
Dictionary with sampled hyperparameters merged with fixed ones
|
|
574
|
+
"""
|
|
575
|
+
hp_sampler = HpSamplerList(self.sampled_hp, device=self.device)
|
|
576
|
+
return hp_sampler.sample()
|
|
577
|
+
|
|
578
|
+
@torch.no_grad()
|
|
579
|
+
def generate_dataset(self, params: Dict[str, Any]) -> Tuple[Tensor, Tensor, Tensor]:
|
|
580
|
+
"""
|
|
581
|
+
Generates a single valid dataset based on the provided parameters.
|
|
582
|
+
|
|
583
|
+
Parameters
|
|
584
|
+
----------
|
|
585
|
+
params : dict
|
|
586
|
+
Hyperparameters for generating this specific dataset, including seq_len,
|
|
587
|
+
train_size, num_features, num_classes, prior_type, device, etc.
|
|
588
|
+
|
|
589
|
+
Returns
|
|
590
|
+
-------
|
|
591
|
+
tuple
|
|
592
|
+
(X, y, d) where:
|
|
593
|
+
- X: Features tensor of shape (seq_len, max_features)
|
|
594
|
+
- y: Targets tensor of shape (seq_len,)
|
|
595
|
+
- d: Number of active features after filtering (scalar Tensor)
|
|
596
|
+
"""
|
|
597
|
+
|
|
598
|
+
# print(f'{params["prior_type"]=}')
|
|
599
|
+
if params["prior_type"] == "mlp_scm":
|
|
600
|
+
prior_cls = MLPSCM
|
|
601
|
+
elif params["prior_type"] == "tree_scm":
|
|
602
|
+
prior_cls = TreeSCM
|
|
603
|
+
else:
|
|
604
|
+
raise ValueError(f"Unknown prior type {params['prior_type']}")
|
|
605
|
+
|
|
606
|
+
for idx in range(100):
|
|
607
|
+
X, y = prior_cls(**params)()
|
|
608
|
+
X, y = Reg2Cls(params)(X, y)
|
|
609
|
+
|
|
610
|
+
# Add batch dim for single dataset to be compatible with delete_unique_features and sanity_check
|
|
611
|
+
X, y = X.unsqueeze(0), y.unsqueeze(0)
|
|
612
|
+
d = torch.tensor([params["num_features"]], device=self.device, dtype=torch.long)
|
|
613
|
+
|
|
614
|
+
# Only keep valid datasets with sufficient features and balanced classes
|
|
615
|
+
X, d = self.delete_unique_features(X, d)
|
|
616
|
+
if not (d > 0).all():
|
|
617
|
+
continue
|
|
618
|
+
|
|
619
|
+
if not (self.regression or self.cls_sanity_check(X, y, params["train_size"])):
|
|
620
|
+
continue
|
|
621
|
+
|
|
622
|
+
#
|
|
623
|
+
# if idx <= 5 and self.config.filter_unpredictable_datasets \
|
|
624
|
+
# and compute_predictability_pvalue(X[0], y[0], is_classif=not self.regression) >= 0.05:
|
|
625
|
+
if idx <= 5 and should_filter(X[0], y[0], self.config, is_classif=not self.regression):
|
|
626
|
+
# print(f'filter', flush=True)
|
|
627
|
+
continue
|
|
628
|
+
|
|
629
|
+
# print(f'no filter', flush=True)
|
|
630
|
+
break
|
|
631
|
+
|
|
632
|
+
return X.squeeze(0), y.squeeze(0), d.squeeze(0)
|
|
633
|
+
|
|
634
|
+
@torch.no_grad()
|
|
635
|
+
def get_batch(
|
|
636
|
+
self, batch_size: Optional[int] = None, forced_group_hp: Optional[Dict[str, Any]] = None
|
|
637
|
+
) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
|
|
638
|
+
"""
|
|
639
|
+
Generates a batch of datasets by first creating a parameter list and then processing it.
|
|
640
|
+
|
|
641
|
+
Parameters
|
|
642
|
+
----------
|
|
643
|
+
batch_size : int, optional
|
|
644
|
+
Batch size override. If None, uses self.batch_size
|
|
645
|
+
|
|
646
|
+
forced_group_hp : dict, optional
|
|
647
|
+
When given, skips this call's own sampling of seq_len/train_size/the HpSamplerList
|
|
648
|
+
hyperparameters/num_features/num_classes and uses these fixed values for every
|
|
649
|
+
group/subgroup instead (expected keys: 'seq_len', 'train_size', 'sampled_hp',
|
|
650
|
+
'num_features', 'num_classes'). Used by the context-bucket schedule
|
|
651
|
+
(firepfn/train/schedule.py) to give every micro-step its scheduled shape.
|
|
652
|
+
|
|
653
|
+
Returns
|
|
654
|
+
-------
|
|
655
|
+
X : Tensor or NestedTensor
|
|
656
|
+
Features tensor. If seq_len_per_gp=False, shape is (batch_size, seq_len, max_features).
|
|
657
|
+
If seq_len_per_gp=True, returns a NestedTensor.
|
|
658
|
+
|
|
659
|
+
y : Tensor or NestedTensor
|
|
660
|
+
Targets tensor. If seq_len_per_gp=False, shape is (batch_size, seq_len).
|
|
661
|
+
If seq_len_per_gp=True, returns a NestedTensor.
|
|
662
|
+
|
|
663
|
+
d : Tensor
|
|
664
|
+
Number of active features per dataset after filtering, shape (batch_size,)
|
|
665
|
+
|
|
666
|
+
seq_lens : Tensor
|
|
667
|
+
Sequence length for each dataset, shape (batch_size,)
|
|
668
|
+
|
|
669
|
+
train_sizes : Tensor
|
|
670
|
+
Position for train/test split for each dataset, shape (batch_size,)
|
|
671
|
+
"""
|
|
672
|
+
batch_size = batch_size or self.batch_size
|
|
673
|
+
|
|
674
|
+
# Calculate number of groups and subgroups
|
|
675
|
+
size_per_gp = min(self.batch_size_per_gp, batch_size)
|
|
676
|
+
num_gps = math.ceil(batch_size / size_per_gp)
|
|
677
|
+
|
|
678
|
+
size_per_subgp = min(self.batch_size_per_subgp, size_per_gp)
|
|
679
|
+
|
|
680
|
+
# Generate parameters list for all datasets, preserving group and subgroup structure
|
|
681
|
+
param_list = []
|
|
682
|
+
global_seq_len = None
|
|
683
|
+
global_train_size = None
|
|
684
|
+
|
|
685
|
+
# Determine global seq_len/train_size if not per-group
|
|
686
|
+
if not self.seq_len_per_gp:
|
|
687
|
+
if forced_group_hp is not None:
|
|
688
|
+
global_seq_len = forced_group_hp["seq_len"]
|
|
689
|
+
global_train_size = forced_group_hp["train_size"]
|
|
690
|
+
else:
|
|
691
|
+
global_seq_len = self.sample_seq_len(
|
|
692
|
+
self.min_seq_len, self.max_seq_len, log=self.log_seq_len, replay_small=self.replay_small
|
|
693
|
+
)
|
|
694
|
+
global_train_size = self.sample_train_size(self.min_train_size, self.max_train_size, global_seq_len)
|
|
695
|
+
|
|
696
|
+
# Generate parameters for each group
|
|
697
|
+
for gp_idx in range(num_gps):
|
|
698
|
+
# Determine actual size for this group (may be smaller for the last group)
|
|
699
|
+
actual_gp_size = min(size_per_gp, batch_size - gp_idx * size_per_gp)
|
|
700
|
+
if actual_gp_size <= 0:
|
|
701
|
+
break
|
|
702
|
+
|
|
703
|
+
group_sampled_hp = forced_group_hp["sampled_hp"] if forced_group_hp is not None else self.hp_sampling()
|
|
704
|
+
# If per-group, sample seq_len and train_size for this group. Otherwise, use global ones
|
|
705
|
+
if self.seq_len_per_gp:
|
|
706
|
+
if forced_group_hp is not None:
|
|
707
|
+
gp_seq_len = forced_group_hp["seq_len"]
|
|
708
|
+
gp_train_size = forced_group_hp["train_size"]
|
|
709
|
+
else:
|
|
710
|
+
gp_seq_len = self.sample_seq_len(
|
|
711
|
+
self.min_seq_len, self.max_seq_len, log=self.log_seq_len, replay_small=self.replay_small
|
|
712
|
+
)
|
|
713
|
+
gp_train_size = self.sample_train_size(self.min_train_size, self.max_train_size, gp_seq_len)
|
|
714
|
+
# Adjust max features based on seq_len for this group
|
|
715
|
+
gp_max_features = self.adjust_max_features(gp_seq_len, self.max_features)
|
|
716
|
+
else:
|
|
717
|
+
gp_seq_len = global_seq_len
|
|
718
|
+
gp_train_size = global_train_size
|
|
719
|
+
gp_max_features = self.max_features
|
|
720
|
+
|
|
721
|
+
if self.config.seq_lens_multiple_of > 1:
|
|
722
|
+
k = self.config.seq_lens_multiple_of
|
|
723
|
+
gp_seq_len = k * round(gp_seq_len / k)
|
|
724
|
+
gp_train_size = k * round(gp_train_size / k)
|
|
725
|
+
|
|
726
|
+
# Calculate number of subgroups for this group
|
|
727
|
+
num_subgps_in_gp = math.ceil(actual_gp_size / size_per_subgp)
|
|
728
|
+
|
|
729
|
+
# Generate parameters for each subgroup
|
|
730
|
+
for subgp_idx in range(num_subgps_in_gp):
|
|
731
|
+
# Determine actual size for this subgroup
|
|
732
|
+
actual_subgp_size = min(size_per_subgp, actual_gp_size - subgp_idx * size_per_subgp)
|
|
733
|
+
if actual_subgp_size <= 0:
|
|
734
|
+
break
|
|
735
|
+
|
|
736
|
+
# Subgroups share prior type, number of features, number of classes, and sampled HPs
|
|
737
|
+
subgp_prior_type = self.get_prior()
|
|
738
|
+
if forced_group_hp is not None:
|
|
739
|
+
subgp_num_features = forced_group_hp["num_features"]
|
|
740
|
+
elif self.log_n_features:
|
|
741
|
+
subgp_num_features = int(loguniform.rvs(self.min_features, gp_max_features))
|
|
742
|
+
else:
|
|
743
|
+
subgp_num_features = round(np.random.uniform(self.min_features, gp_max_features))
|
|
744
|
+
subgp_sampled_hp = {k: v() if callable(v) else v for k, v in group_sampled_hp.items()}
|
|
745
|
+
|
|
746
|
+
if forced_group_hp is not None:
|
|
747
|
+
subgp_num_classes = forced_group_hp["num_classes"]
|
|
748
|
+
elif self.regression:
|
|
749
|
+
subgp_num_classes = None
|
|
750
|
+
elif np.random.random() > 0.5:
|
|
751
|
+
subgp_num_classes = np.random.randint(2, self.max_classes + 1)
|
|
752
|
+
else:
|
|
753
|
+
subgp_num_classes = 2
|
|
754
|
+
|
|
755
|
+
# Generate parameters for each dataset in this subgroup
|
|
756
|
+
for ds_idx in range(actual_subgp_size):
|
|
757
|
+
# Create parameters dictionary for this dataset
|
|
758
|
+
params = {
|
|
759
|
+
# -----------------
|
|
760
|
+
# Global parameters
|
|
761
|
+
# -----------------
|
|
762
|
+
"regression": self.regression,
|
|
763
|
+
"device": self.device,
|
|
764
|
+
**self.fixed_hp, # Fixed HPs
|
|
765
|
+
# -------------------------
|
|
766
|
+
# Group-specific parameters
|
|
767
|
+
# -------------------------
|
|
768
|
+
"seq_len": gp_seq_len,
|
|
769
|
+
"train_size": gp_train_size,
|
|
770
|
+
# If per-gp setting, use adjusted max features for this group because we use nested tensors
|
|
771
|
+
# If not per-gp setting, use global max features to fix size for concatenation
|
|
772
|
+
"max_features": gp_max_features if self.seq_len_per_gp else self.max_features,
|
|
773
|
+
# ----------------------------
|
|
774
|
+
# Subgroup-specific parameters
|
|
775
|
+
# ----------------------------
|
|
776
|
+
**subgp_sampled_hp, # sampled HPs for this group
|
|
777
|
+
"prior_type": subgp_prior_type,
|
|
778
|
+
"num_features": subgp_num_features,
|
|
779
|
+
"num_classes": subgp_num_classes,
|
|
780
|
+
}
|
|
781
|
+
param_list.append(params)
|
|
782
|
+
|
|
783
|
+
# Use joblib to generate datasets in parallel.
|
|
784
|
+
# Note: the 'loky' backend does not support nested parallelism during DDP, whereas the 'threading' backend does.
|
|
785
|
+
# However, 'threading' does not respect `inner_max_num_threads`.
|
|
786
|
+
# Therefore, we stick with the 'loky' backend for parallelism, but this requires generating
|
|
787
|
+
# the prior datasets separately from the training process and loading them from disk,
|
|
788
|
+
# rather than generating them on-the-fly.
|
|
789
|
+
# if self.n_jobs == 1:
|
|
790
|
+
# results = [self.generate_dataset(params) for params in param_list]
|
|
791
|
+
# else:
|
|
792
|
+
# with joblib.parallel_config(
|
|
793
|
+
# n_jobs=self.n_jobs, backend="loky", inner_max_num_threads=self.num_threads_per_generate
|
|
794
|
+
# ):
|
|
795
|
+
# results = joblib.Parallel()(joblib.delayed(self.generate_dataset)(params) for params in param_list)
|
|
796
|
+
|
|
797
|
+
with threadpoolctl.threadpool_limits(limits=1):
|
|
798
|
+
if self.n_jobs == 1:
|
|
799
|
+
n_threads_old = torch.get_num_threads()
|
|
800
|
+
torch.set_num_threads(1)
|
|
801
|
+
results = [self.generate_dataset(params) for params in param_list]
|
|
802
|
+
torch.set_num_threads(n_threads_old)
|
|
803
|
+
else:
|
|
804
|
+
results = run_parallel(self.generate_dataset, args=param_list, n_jobs=self.n_jobs)
|
|
805
|
+
|
|
806
|
+
X_list, y_list, d_list = zip(*results)
|
|
807
|
+
|
|
808
|
+
# Combine Results
|
|
809
|
+
if self.seq_len_per_gp:
|
|
810
|
+
# Use nested tensors for variable sequence lengths
|
|
811
|
+
X = nested_tensor([x.to(self.device) for x in X_list], device=self.device)
|
|
812
|
+
y = nested_tensor([y.to(self.device) for y in y_list], device=self.device)
|
|
813
|
+
else:
|
|
814
|
+
# Stack into regular tensors for fixed sequence length
|
|
815
|
+
X = torch.stack(X_list).to(self.device) # (B, T, H)
|
|
816
|
+
y = torch.stack(y_list).to(self.device) # (B, T)
|
|
817
|
+
|
|
818
|
+
# Metadata (always regular tensors)
|
|
819
|
+
d = torch.stack(d_list).to(self.device) # Actual number of features after filtering out constant ones
|
|
820
|
+
seq_lens = torch.tensor([params["seq_len"] for params in param_list], device=self.device, dtype=torch.long)
|
|
821
|
+
train_sizes = torch.tensor(
|
|
822
|
+
[params["train_size"] for params in param_list], device=self.device, dtype=torch.long
|
|
823
|
+
)
|
|
824
|
+
|
|
825
|
+
return X, y, d, seq_lens, train_sizes
|
|
826
|
+
|
|
827
|
+
def get_prior(self) -> str:
|
|
828
|
+
"""
|
|
829
|
+
Determine which prior type to use for generation.
|
|
830
|
+
|
|
831
|
+
For 'mix_scm' prior type, randomly selects between available priors
|
|
832
|
+
based on configured probabilities.
|
|
833
|
+
|
|
834
|
+
Returns
|
|
835
|
+
-------
|
|
836
|
+
str
|
|
837
|
+
The selected prior type name
|
|
838
|
+
"""
|
|
839
|
+
if self.prior_type == "mix_scm":
|
|
840
|
+
return np.random.choice(["mlp_scm", "tree_scm"], p=self.fixed_hp.get("mix_probs", [0.7, 0.3]))
|
|
841
|
+
else:
|
|
842
|
+
return self.prior_type
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
class GraphPrior(Prior):
|
|
846
|
+
"""
|
|
847
|
+
Generates synthetic datasets using Graph-based Structural Causal Models (SCM).
|
|
848
|
+
|
|
849
|
+
Parameters
|
|
850
|
+
----------
|
|
851
|
+
regression : bool, default=False
|
|
852
|
+
If True, generates regression datasets. Otherwise, generates classification datasets.
|
|
853
|
+
|
|
854
|
+
batch_size : int, default=256
|
|
855
|
+
Total number of datasets to generate per batch
|
|
856
|
+
|
|
857
|
+
batch_size_per_gp : int, default=4
|
|
858
|
+
Number of datasets per group, sharing similar characteristics
|
|
859
|
+
|
|
860
|
+
batch_size_per_subgp : int, default=None
|
|
861
|
+
Number of datasets per subgroup, with more similar causal structures
|
|
862
|
+
If None, defaults to batch_size_per_gp
|
|
863
|
+
|
|
864
|
+
min_features : int, default=2
|
|
865
|
+
Minimum number of features per dataset
|
|
866
|
+
|
|
867
|
+
max_features : int, default=100
|
|
868
|
+
Maximum number of features per dataset
|
|
869
|
+
|
|
870
|
+
max_classes : int, default=10
|
|
871
|
+
Maximum number of target classes
|
|
872
|
+
|
|
873
|
+
min_seq_len : int, default=None
|
|
874
|
+
Minimum samples per dataset. If None, uses max_seq_len directly.
|
|
875
|
+
|
|
876
|
+
max_seq_len : int, default=1024
|
|
877
|
+
Maximum samples per dataset
|
|
878
|
+
|
|
879
|
+
log_seq_len : bool, default=False
|
|
880
|
+
If True, sample sequence length from a log-uniform distribution
|
|
881
|
+
|
|
882
|
+
log_n_features : bool, default=False
|
|
883
|
+
If True, sample the number of features from a log-uniform distribution
|
|
884
|
+
|
|
885
|
+
seq_len_per_gp : bool = False
|
|
886
|
+
If True, sample sequence length per group, allowing variable-sized datasets
|
|
887
|
+
|
|
888
|
+
min_train_size : int|float, default=0.1
|
|
889
|
+
Position or ratio for train/test split start. If int, absolute position.
|
|
890
|
+
If float between 0 and 1, specifies a fraction of sequence length.
|
|
891
|
+
|
|
892
|
+
max_train_size : int|float, default=0.9
|
|
893
|
+
Position or ratio for train/test split end. If int, absolute position.
|
|
894
|
+
If float between 0 and 1, specifies a fraction of sequence length.
|
|
895
|
+
|
|
896
|
+
replay_small : bool, default=False
|
|
897
|
+
If True, occasionally sample smaller sequence lengths with
|
|
898
|
+
specific distributions to ensure model robustness on smaller datasets
|
|
899
|
+
|
|
900
|
+
config : PriorConfig | None, default=None
|
|
901
|
+
Prior configuration.
|
|
902
|
+
|
|
903
|
+
n_jobs : int, default=-1
|
|
904
|
+
Number of parallel jobs to run (-1 means using all processors).
|
|
905
|
+
|
|
906
|
+
num_threads_per_generate : int, default=1
|
|
907
|
+
Number of threads per job for dataset generation
|
|
908
|
+
|
|
909
|
+
device : str, default="cpu"
|
|
910
|
+
Computation device ('cpu' or 'cuda')
|
|
911
|
+
"""
|
|
912
|
+
|
|
913
|
+
def __init__(
|
|
914
|
+
self,
|
|
915
|
+
regression: bool = False,
|
|
916
|
+
batch_size: int = 256,
|
|
917
|
+
batch_size_per_gp: int = 4,
|
|
918
|
+
batch_size_per_subgp: Optional[int] = None,
|
|
919
|
+
min_features: int = 2,
|
|
920
|
+
max_features: int = 100,
|
|
921
|
+
max_classes: int = 10,
|
|
922
|
+
min_seq_len: Optional[int] = None,
|
|
923
|
+
max_seq_len: int = 1024,
|
|
924
|
+
log_seq_len: bool = False,
|
|
925
|
+
log_n_features: bool = False,
|
|
926
|
+
seq_len_per_gp: bool = False,
|
|
927
|
+
min_train_size: Union[int, float] = 0.1,
|
|
928
|
+
max_train_size: Union[int, float] = 0.9,
|
|
929
|
+
replay_small: bool = False,
|
|
930
|
+
config: Optional[PriorConfig] = None,
|
|
931
|
+
n_jobs: int = -1,
|
|
932
|
+
num_threads_per_generate: int = 1,
|
|
933
|
+
device: str = "cpu",
|
|
934
|
+
):
|
|
935
|
+
super().__init__(
|
|
936
|
+
regression=regression,
|
|
937
|
+
batch_size=batch_size,
|
|
938
|
+
min_features=min_features,
|
|
939
|
+
max_features=max_features,
|
|
940
|
+
max_classes=max_classes,
|
|
941
|
+
min_seq_len=min_seq_len,
|
|
942
|
+
max_seq_len=max_seq_len,
|
|
943
|
+
log_seq_len=log_seq_len,
|
|
944
|
+
min_train_size=min_train_size,
|
|
945
|
+
max_train_size=max_train_size,
|
|
946
|
+
replay_small=replay_small,
|
|
947
|
+
)
|
|
948
|
+
|
|
949
|
+
self.batch_size_per_gp = batch_size_per_gp
|
|
950
|
+
self.batch_size_per_subgp = batch_size_per_subgp or batch_size_per_gp
|
|
951
|
+
self.seq_len_per_gp = seq_len_per_gp
|
|
952
|
+
self.log_n_features = log_n_features
|
|
953
|
+
self.config = config or PriorConfig()
|
|
954
|
+
self.n_jobs = n_jobs
|
|
955
|
+
self.num_threads_per_generate = num_threads_per_generate
|
|
956
|
+
self.device = device
|
|
957
|
+
|
|
958
|
+
@torch.no_grad()
|
|
959
|
+
def generate_dataset(self, params: Dict[str, Any]) -> Tuple[Tensor, Tensor, Tensor]:
|
|
960
|
+
"""
|
|
961
|
+
Generates a single valid dataset based on the provided parameters.
|
|
962
|
+
|
|
963
|
+
This method implements a robust generation process with:
|
|
964
|
+
1. Multiple retry attempts for generating valid datasets
|
|
965
|
+
2. Feature filtering to remove non-informative columns
|
|
966
|
+
3. Validation checks to ensure class balance in train/test splits
|
|
967
|
+
|
|
968
|
+
Parameters
|
|
969
|
+
----------
|
|
970
|
+
params : dict
|
|
971
|
+
Parameters accepted by `GraphSCM` for dataset generation including:
|
|
972
|
+
- regression: boolean flag for regression/classification
|
|
973
|
+
- seq_len: number of samples
|
|
974
|
+
- train_size: position to split train/test sets
|
|
975
|
+
- num_features: number of features
|
|
976
|
+
- max_features: maximum number of features
|
|
977
|
+
- num_classes: number of target classes
|
|
978
|
+
- device: computation device
|
|
979
|
+
- config: PriorConfig object
|
|
980
|
+
|
|
981
|
+
Returns
|
|
982
|
+
-------
|
|
983
|
+
tuple
|
|
984
|
+
(X, y, d) where:
|
|
985
|
+
- X: Features tensor of shape (seq_len, max_features)
|
|
986
|
+
- y: Targets tensor of shape (seq_len,)
|
|
987
|
+
- d: Number of active features after filtering (scalar Tensor)
|
|
988
|
+
"""
|
|
989
|
+
|
|
990
|
+
# Bounded like SCMPrior.generate_dataset's `for idx in range(100)` above — this used to be
|
|
991
|
+
# `while True`, genuinely unbounded. With filter_unpredictable_graphs/datasets=True (the
|
|
992
|
+
# TabICLv2 recipe) and min_n_nodes as low as 2, a real fraction of random graphs have no
|
|
993
|
+
# predictable X->Y path and get rejected on every retry — classic rejection-sampling long
|
|
994
|
+
# tail. Under DDP, whichever rank's independent random draw hits a long unlucky streak
|
|
995
|
+
# stalls indefinitely, which starves the other ranks' collective ops and crashes the whole
|
|
996
|
+
# job on an NCCL watchdog timeout (observed: runs 7523722, 7523761, 7523791). Falls through
|
|
997
|
+
# to returning the last attempt's (possibly still-filtered) dataset if none validate in time,
|
|
998
|
+
# exactly like SCMPrior does — occasionally training on one, vs. hanging forever.
|
|
999
|
+
for _attempt in range(100):
|
|
1000
|
+
X, y = GraphSCM(**params)()
|
|
1001
|
+
|
|
1002
|
+
# Add batch dim for single dataset to be compatible with delete_unique_features and sanity_check
|
|
1003
|
+
X, y = X.unsqueeze(0), y.unsqueeze(0)
|
|
1004
|
+
d = torch.tensor([params["num_features"]], device=self.device, dtype=torch.long)
|
|
1005
|
+
|
|
1006
|
+
# Only keep valid datasets with sufficient features and balanced classes
|
|
1007
|
+
X, d = self.delete_unique_features(X, d)
|
|
1008
|
+
if not (d > 0).all():
|
|
1009
|
+
continue
|
|
1010
|
+
|
|
1011
|
+
if not (self.regression or self.cls_sanity_check(X, y, params["train_size"])):
|
|
1012
|
+
continue
|
|
1013
|
+
|
|
1014
|
+
if should_filter(X[0], y[0], self.config, is_classif=not self.regression):
|
|
1015
|
+
continue
|
|
1016
|
+
|
|
1017
|
+
break
|
|
1018
|
+
|
|
1019
|
+
return X.squeeze(0), y.squeeze(0), d.squeeze(0)
|
|
1020
|
+
|
|
1021
|
+
@torch.no_grad()
|
|
1022
|
+
def get_batch(
|
|
1023
|
+
self, batch_size: Optional[int] = None, forced_group_hp: Optional[Dict[str, Any]] = None
|
|
1024
|
+
) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
|
|
1025
|
+
"""
|
|
1026
|
+
Generates a batch of datasets by first creating a parameter list and then processing it.
|
|
1027
|
+
|
|
1028
|
+
Parameters
|
|
1029
|
+
----------
|
|
1030
|
+
batch_size : int, optional
|
|
1031
|
+
Batch size override. If None, uses self.batch_size
|
|
1032
|
+
|
|
1033
|
+
forced_group_hp : dict, optional
|
|
1034
|
+
When given, skips this call's own sampling of seq_len/train_size/num_features/
|
|
1035
|
+
num_classes and uses these fixed values for every group/subgroup instead (expected
|
|
1036
|
+
keys: 'seq_len', 'train_size', 'num_features', 'num_classes'). Used by the
|
|
1037
|
+
context-bucket schedule (firepfn/train/schedule.py).
|
|
1038
|
+
|
|
1039
|
+
Returns
|
|
1040
|
+
-------
|
|
1041
|
+
X : Tensor or NestedTensor
|
|
1042
|
+
Features tensor. If seq_len_per_gp=False, shape is (batch_size, seq_len, max_features).
|
|
1043
|
+
If seq_len_per_gp=True, returns a NestedTensor.
|
|
1044
|
+
|
|
1045
|
+
y : Tensor or NestedTensor
|
|
1046
|
+
Targets tensor. If seq_len_per_gp=False, shape is (batch_size, seq_len).
|
|
1047
|
+
If seq_len_per_gp=True, returns a NestedTensor.
|
|
1048
|
+
|
|
1049
|
+
d : Tensor
|
|
1050
|
+
Number of active features per dataset after filtering, shape (batch_size,)
|
|
1051
|
+
|
|
1052
|
+
seq_lens : Tensor
|
|
1053
|
+
Sequence length for each dataset, shape (batch_size,)
|
|
1054
|
+
|
|
1055
|
+
train_sizes : Tensor
|
|
1056
|
+
Position for train/test split for each dataset, shape (batch_size,)
|
|
1057
|
+
"""
|
|
1058
|
+
batch_size = batch_size or self.batch_size
|
|
1059
|
+
|
|
1060
|
+
# Calculate number of groups and subgroups
|
|
1061
|
+
size_per_gp = min(self.batch_size_per_gp, batch_size)
|
|
1062
|
+
num_gps = math.ceil(batch_size / size_per_gp)
|
|
1063
|
+
|
|
1064
|
+
size_per_subgp = min(self.batch_size_per_subgp, size_per_gp)
|
|
1065
|
+
|
|
1066
|
+
# Generate parameters list for all datasets, preserving group and subgroup structure
|
|
1067
|
+
param_list = []
|
|
1068
|
+
global_seq_len = None
|
|
1069
|
+
global_train_size = None
|
|
1070
|
+
|
|
1071
|
+
# Determine global seq_len/train_size if not per-group
|
|
1072
|
+
if not self.seq_len_per_gp:
|
|
1073
|
+
if forced_group_hp is not None:
|
|
1074
|
+
global_seq_len = forced_group_hp["seq_len"]
|
|
1075
|
+
global_train_size = forced_group_hp["train_size"]
|
|
1076
|
+
else:
|
|
1077
|
+
global_seq_len = self.sample_seq_len(
|
|
1078
|
+
self.min_seq_len, self.max_seq_len, log=self.log_seq_len, replay_small=self.replay_small
|
|
1079
|
+
)
|
|
1080
|
+
global_train_size = self.sample_train_size(self.min_train_size, self.max_train_size, global_seq_len)
|
|
1081
|
+
|
|
1082
|
+
# Generate parameters for each group
|
|
1083
|
+
for gp_idx in range(num_gps):
|
|
1084
|
+
# Determine actual size for this group (may be smaller for the last group)
|
|
1085
|
+
actual_gp_size = min(size_per_gp, batch_size - gp_idx * size_per_gp)
|
|
1086
|
+
if actual_gp_size <= 0:
|
|
1087
|
+
break
|
|
1088
|
+
|
|
1089
|
+
# If per-group, sample seq_len and train_size for this group. Otherwise, use global ones
|
|
1090
|
+
if self.seq_len_per_gp:
|
|
1091
|
+
if forced_group_hp is not None:
|
|
1092
|
+
gp_seq_len = forced_group_hp["seq_len"]
|
|
1093
|
+
gp_train_size = forced_group_hp["train_size"]
|
|
1094
|
+
else:
|
|
1095
|
+
gp_seq_len = self.sample_seq_len(
|
|
1096
|
+
self.min_seq_len, self.max_seq_len, log=self.log_seq_len, replay_small=self.replay_small
|
|
1097
|
+
)
|
|
1098
|
+
gp_train_size = self.sample_train_size(self.min_train_size, self.max_train_size, gp_seq_len)
|
|
1099
|
+
# Adjust max features based on seq_len for this group
|
|
1100
|
+
gp_max_features = self.adjust_max_features(gp_seq_len, self.max_features)
|
|
1101
|
+
else:
|
|
1102
|
+
gp_seq_len = global_seq_len
|
|
1103
|
+
gp_train_size = global_train_size
|
|
1104
|
+
gp_max_features = self.max_features
|
|
1105
|
+
|
|
1106
|
+
# Calculate number of subgroups for this group
|
|
1107
|
+
num_subgps_in_gp = math.ceil(actual_gp_size / size_per_subgp)
|
|
1108
|
+
|
|
1109
|
+
# Generate parameters for each subgroup
|
|
1110
|
+
for subgp_idx in range(num_subgps_in_gp):
|
|
1111
|
+
# Determine actual size for this subgroup
|
|
1112
|
+
actual_subgp_size = min(size_per_subgp, actual_gp_size - subgp_idx * size_per_subgp)
|
|
1113
|
+
if actual_subgp_size <= 0:
|
|
1114
|
+
break
|
|
1115
|
+
|
|
1116
|
+
# Each subgroup shares the same number of features and number of classes
|
|
1117
|
+
if forced_group_hp is not None:
|
|
1118
|
+
subgp_num_features = forced_group_hp["num_features"]
|
|
1119
|
+
elif self.log_n_features:
|
|
1120
|
+
subgp_num_features = int(loguniform.rvs(self.min_features, gp_max_features))
|
|
1121
|
+
else:
|
|
1122
|
+
subgp_num_features = round(np.random.uniform(self.min_features, gp_max_features))
|
|
1123
|
+
|
|
1124
|
+
if forced_group_hp is not None:
|
|
1125
|
+
subgp_num_classes = forced_group_hp["num_classes"]
|
|
1126
|
+
elif self.regression:
|
|
1127
|
+
subgp_num_classes = None
|
|
1128
|
+
else:
|
|
1129
|
+
subgp_num_classes = np.random.randint(2, self.max_classes + 1)
|
|
1130
|
+
|
|
1131
|
+
# Generate parameters for each dataset in this subgroup
|
|
1132
|
+
for ds_idx in range(actual_subgp_size):
|
|
1133
|
+
# Create parameters dictionary for this dataset
|
|
1134
|
+
params = {
|
|
1135
|
+
# -----------------
|
|
1136
|
+
# Global parameters
|
|
1137
|
+
# -----------------
|
|
1138
|
+
"regression": self.regression,
|
|
1139
|
+
"device": self.device,
|
|
1140
|
+
"config": self.config,
|
|
1141
|
+
# -------------------------
|
|
1142
|
+
# Group-specific parameters
|
|
1143
|
+
# -------------------------
|
|
1144
|
+
"seq_len": gp_seq_len,
|
|
1145
|
+
"train_size": gp_train_size,
|
|
1146
|
+
"max_features": gp_max_features,
|
|
1147
|
+
# ----------------------------
|
|
1148
|
+
# Subgroup-specific parameters
|
|
1149
|
+
# ----------------------------
|
|
1150
|
+
"num_features": subgp_num_features,
|
|
1151
|
+
"num_classes": subgp_num_classes,
|
|
1152
|
+
# ---------------------------
|
|
1153
|
+
# DAG generation parameters
|
|
1154
|
+
# ---------------------------
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
param_list.append(params)
|
|
1158
|
+
|
|
1159
|
+
with threadpoolctl.threadpool_limits(limits=1):
|
|
1160
|
+
if self.n_jobs == 1:
|
|
1161
|
+
n_threads_old = torch.get_num_threads()
|
|
1162
|
+
torch.set_num_threads(1)
|
|
1163
|
+
results = [self.generate_dataset(params) for params in param_list]
|
|
1164
|
+
torch.set_num_threads(n_threads_old)
|
|
1165
|
+
else:
|
|
1166
|
+
results = run_parallel(self.generate_dataset, args=param_list, n_jobs=self.n_jobs)
|
|
1167
|
+
|
|
1168
|
+
X_list, y_list, d_list = zip(*results)
|
|
1169
|
+
|
|
1170
|
+
# Combine Results
|
|
1171
|
+
if self.seq_len_per_gp:
|
|
1172
|
+
# Use nested tensors for variable sequence lengths
|
|
1173
|
+
X = nested_tensor([x.to(self.device) for x in X_list], device=self.device)
|
|
1174
|
+
y = nested_tensor([y.to(self.device) for y in y_list], device=self.device)
|
|
1175
|
+
else:
|
|
1176
|
+
# Stack into regular tensors for fixed sequence length
|
|
1177
|
+
X = torch.stack(X_list).to(self.device) # (B, T, H)
|
|
1178
|
+
y = torch.stack(y_list).to(self.device) # (B, T)
|
|
1179
|
+
|
|
1180
|
+
# Metadata (always regular tensors)
|
|
1181
|
+
d = torch.stack(d_list).to(self.device) # Actual number of features after filtering out constant ones
|
|
1182
|
+
seq_lens = torch.tensor([params["seq_len"] for params in param_list], device=self.device, dtype=torch.long)
|
|
1183
|
+
train_sizes = torch.tensor(
|
|
1184
|
+
[params["train_size"] for params in param_list], device=self.device, dtype=torch.long
|
|
1185
|
+
)
|
|
1186
|
+
|
|
1187
|
+
return X, y, d, seq_lens, train_sizes
|
|
1188
|
+
|
|
1189
|
+
|
|
1190
|
+
def sample_group_hp(prior: "SCMPrior | GraphPrior") -> Dict[str, Any]:
|
|
1191
|
+
"""Realizes one "group" worth of the hyperparameters get_batch would otherwise sample fresh
|
|
1192
|
+
per group/subgroup -- seq_len, train_size, num_features, num_classes, and (for SCMPrior only)
|
|
1193
|
+
the HpSamplerList-derived hyperparameters. Pass the result as `forced_group_hp` to get_batch
|
|
1194
|
+
to reuse these exact values instead of resampling.
|
|
1195
|
+
|
|
1196
|
+
The context-bucket schedule (firepfn/train/schedule.py) draws these per micro-step and then
|
|
1197
|
+
overrides seq_len / train_size with the scheduled shape.
|
|
1198
|
+
"""
|
|
1199
|
+
seq_len = prior.sample_seq_len(
|
|
1200
|
+
prior.min_seq_len, prior.max_seq_len, log=prior.log_seq_len, replay_small=prior.replay_small
|
|
1201
|
+
)
|
|
1202
|
+
train_size = prior.sample_train_size(prior.min_train_size, prior.max_train_size, seq_len)
|
|
1203
|
+
max_features = prior.adjust_max_features(seq_len, prior.max_features) if prior.seq_len_per_gp else prior.max_features
|
|
1204
|
+
if prior.log_n_features:
|
|
1205
|
+
num_features = int(loguniform.rvs(prior.min_features, max_features))
|
|
1206
|
+
else:
|
|
1207
|
+
num_features = round(np.random.uniform(prior.min_features, max_features))
|
|
1208
|
+
|
|
1209
|
+
if prior.regression:
|
|
1210
|
+
num_classes = None
|
|
1211
|
+
elif hasattr(prior, "hp_sampling"):
|
|
1212
|
+
# SCMPrior's 50%-chance-of-binary rule, matching SCMPrior.get_batch's subgroup sampling.
|
|
1213
|
+
num_classes = np.random.randint(2, prior.max_classes + 1) if np.random.random() > 0.5 else 2
|
|
1214
|
+
else:
|
|
1215
|
+
num_classes = np.random.randint(2, prior.max_classes + 1)
|
|
1216
|
+
|
|
1217
|
+
sampled_hp = prior.hp_sampling() if hasattr(prior, "hp_sampling") else {}
|
|
1218
|
+
|
|
1219
|
+
return {
|
|
1220
|
+
"seq_len": seq_len,
|
|
1221
|
+
"train_size": train_size,
|
|
1222
|
+
"num_features": num_features,
|
|
1223
|
+
"num_classes": num_classes,
|
|
1224
|
+
"sampled_hp": sampled_hp,
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
|
|
1228
|
+
class DummyPrior(Prior):
|
|
1229
|
+
"""This class creates purely random data. This is useful for testing and debugging
|
|
1230
|
+
without the computational overhead of SCM-based generation.
|
|
1231
|
+
|
|
1232
|
+
Parameters
|
|
1233
|
+
----------
|
|
1234
|
+
regression : bool, default=False
|
|
1235
|
+
If True, generates regression datasets. Otherwise, generates classification datasets.
|
|
1236
|
+
|
|
1237
|
+
batch_size : int, default=256
|
|
1238
|
+
Number of datasets to generate
|
|
1239
|
+
|
|
1240
|
+
min_features : int, default=2
|
|
1241
|
+
Minimum number of features per dataset
|
|
1242
|
+
|
|
1243
|
+
max_features : int, default=100
|
|
1244
|
+
Maximum number of features per dataset
|
|
1245
|
+
|
|
1246
|
+
max_classes : int, default=10
|
|
1247
|
+
Maximum number of target classes
|
|
1248
|
+
|
|
1249
|
+
min_seq_len : int, default=None
|
|
1250
|
+
Minimum samples per dataset. If None, uses max_seq_len directly.
|
|
1251
|
+
|
|
1252
|
+
max_seq_len : int, default=1024
|
|
1253
|
+
Maximum samples per dataset
|
|
1254
|
+
|
|
1255
|
+
log_seq_len : bool, default=False
|
|
1256
|
+
If True, sample sequence length from a log-uniform distribution
|
|
1257
|
+
|
|
1258
|
+
min_train_size : int|float, default=0.1
|
|
1259
|
+
Position or ratio for train/test split start. If int, absolute position.
|
|
1260
|
+
If float between 0 and 1, specifies a fraction of sequence length.
|
|
1261
|
+
|
|
1262
|
+
max_train_size : int|float, default=0.9
|
|
1263
|
+
Position or ratio for train/test split end. If int, absolute position.
|
|
1264
|
+
If float between 0 and 1, specifies a fraction of sequence length.
|
|
1265
|
+
|
|
1266
|
+
device : str, default="cpu"
|
|
1267
|
+
Computation device
|
|
1268
|
+
"""
|
|
1269
|
+
|
|
1270
|
+
def __init__(
|
|
1271
|
+
self,
|
|
1272
|
+
regression: bool = False,
|
|
1273
|
+
batch_size: int = 256,
|
|
1274
|
+
min_features: int = 2,
|
|
1275
|
+
max_features: int = 100,
|
|
1276
|
+
max_classes: int = 10,
|
|
1277
|
+
min_seq_len: Optional[int] = None,
|
|
1278
|
+
max_seq_len: int = 1024,
|
|
1279
|
+
log_seq_len: bool = False,
|
|
1280
|
+
min_train_size: Union[int, float] = 0.1,
|
|
1281
|
+
max_train_size: Union[int, float] = 0.9,
|
|
1282
|
+
device: str = "cpu",
|
|
1283
|
+
):
|
|
1284
|
+
super().__init__(
|
|
1285
|
+
regression=regression,
|
|
1286
|
+
batch_size=batch_size,
|
|
1287
|
+
min_features=min_features,
|
|
1288
|
+
max_features=max_features,
|
|
1289
|
+
max_classes=max_classes,
|
|
1290
|
+
min_seq_len=min_seq_len,
|
|
1291
|
+
max_seq_len=max_seq_len,
|
|
1292
|
+
log_seq_len=log_seq_len,
|
|
1293
|
+
min_train_size=min_train_size,
|
|
1294
|
+
max_train_size=max_train_size,
|
|
1295
|
+
)
|
|
1296
|
+
self.device = device
|
|
1297
|
+
|
|
1298
|
+
@torch.no_grad()
|
|
1299
|
+
def get_batch(
|
|
1300
|
+
self, batch_size: Optional[int] = None, forced_group_hp: Optional[Dict[str, Any]] = None
|
|
1301
|
+
) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
|
|
1302
|
+
"""
|
|
1303
|
+
Generates a batch of random datasets for testing purposes.
|
|
1304
|
+
|
|
1305
|
+
Parameters
|
|
1306
|
+
----------
|
|
1307
|
+
batch_size : int, optional
|
|
1308
|
+
Batch size override, if None, uses self.batch_size
|
|
1309
|
+
|
|
1310
|
+
forced_group_hp : dict, optional
|
|
1311
|
+
Unused -- accepted only so DummyPrior is interchangeable with SCMPrior/GraphPrior
|
|
1312
|
+
behind PriorDataset.get_batch.
|
|
1313
|
+
|
|
1314
|
+
Returns
|
|
1315
|
+
-------
|
|
1316
|
+
X : Tensor
|
|
1317
|
+
Features tensor of shape (batch_size, seq_len, max_features).
|
|
1318
|
+
Contains random Gaussian values for all features.
|
|
1319
|
+
|
|
1320
|
+
y : Tensor
|
|
1321
|
+
Targets tensor of shape (batch_size, seq_len).
|
|
1322
|
+
Contains randomly assigned class Targets.
|
|
1323
|
+
|
|
1324
|
+
d : Tensor
|
|
1325
|
+
Number of features per dataset of shape (batch_size,).
|
|
1326
|
+
Always set to max_features for DummyPrior.
|
|
1327
|
+
|
|
1328
|
+
seq_lens : Tensor
|
|
1329
|
+
Sequence length for each dataset of shape (batch_size,).
|
|
1330
|
+
All datasets share the same sequence length.
|
|
1331
|
+
|
|
1332
|
+
train_sizes : Tensor
|
|
1333
|
+
Position for train/test split for each dataset of shape (batch_size,).
|
|
1334
|
+
All datasets share the same split position.
|
|
1335
|
+
"""
|
|
1336
|
+
|
|
1337
|
+
batch_size = batch_size or self.batch_size
|
|
1338
|
+
seq_len = self.sample_seq_len(self.min_seq_len, self.max_seq_len, log=self.log_seq_len)
|
|
1339
|
+
train_size = self.sample_train_size(self.min_train_size, self.max_train_size, seq_len)
|
|
1340
|
+
|
|
1341
|
+
X = torch.randn(batch_size, seq_len, self.max_features, device=self.device)
|
|
1342
|
+
|
|
1343
|
+
num_classes = np.random.randint(2, self.max_classes + 1)
|
|
1344
|
+
if self.regression:
|
|
1345
|
+
y = torch.randn(batch_size, seq_len, device=self.device)
|
|
1346
|
+
else:
|
|
1347
|
+
y = torch.randint(0, num_classes, (batch_size, seq_len), device=self.device)
|
|
1348
|
+
|
|
1349
|
+
d = torch.full((batch_size,), self.max_features, device=self.device)
|
|
1350
|
+
seq_lens = torch.full((batch_size,), seq_len, device=self.device)
|
|
1351
|
+
train_sizes = torch.full((batch_size,), train_size, device=self.device)
|
|
1352
|
+
|
|
1353
|
+
return X, y, d, seq_lens, train_sizes
|
|
1354
|
+
|
|
1355
|
+
|
|
1356
|
+
class PriorDataset(IterableDataset):
|
|
1357
|
+
"""
|
|
1358
|
+
Main dataset class that provides an infinite iterator over synthetic tabular datasets.
|
|
1359
|
+
|
|
1360
|
+
Parameters
|
|
1361
|
+
----------
|
|
1362
|
+
regression : bool, default=False
|
|
1363
|
+
If True, generates regression datasets. Otherwise, generates classification datasets.
|
|
1364
|
+
|
|
1365
|
+
batch_size : int, default=256
|
|
1366
|
+
Total number of datasets to generate per batch
|
|
1367
|
+
|
|
1368
|
+
batch_size_per_gp : int, default=4
|
|
1369
|
+
Number of datasets per group, sharing similar characteristics
|
|
1370
|
+
|
|
1371
|
+
batch_size_per_subgp : int, default=None
|
|
1372
|
+
Number of datasets per subgroup, with more similar causal structures
|
|
1373
|
+
If None, defaults to batch_size_per_gp
|
|
1374
|
+
|
|
1375
|
+
min_features : int, default=2
|
|
1376
|
+
Minimum number of features per dataset
|
|
1377
|
+
|
|
1378
|
+
max_features : int, default=100
|
|
1379
|
+
Maximum number of features per dataset
|
|
1380
|
+
|
|
1381
|
+
max_classes : int, default=10
|
|
1382
|
+
Maximum number of target classes
|
|
1383
|
+
|
|
1384
|
+
min_seq_len : int, default=None
|
|
1385
|
+
Minimum samples per dataset. If None, uses max_seq_len directly.
|
|
1386
|
+
|
|
1387
|
+
max_seq_len : int, default=1024
|
|
1388
|
+
Maximum samples per dataset
|
|
1389
|
+
|
|
1390
|
+
log_seq_len : bool, default=False
|
|
1391
|
+
If True, sample sequence length from a log-uniform distribution
|
|
1392
|
+
|
|
1393
|
+
seq_len_per_gp : bool = False
|
|
1394
|
+
If True, sample sequence length per group, allowing variable-sized datasets
|
|
1395
|
+
|
|
1396
|
+
min_train_size : int|float, default=0.1
|
|
1397
|
+
Position or ratio for train/test split start. If int, absolute position.
|
|
1398
|
+
If float between 0 and 1, specifies a fraction of sequence length.
|
|
1399
|
+
|
|
1400
|
+
max_train_size : int|float, default=0.9
|
|
1401
|
+
Position or ratio for train/test split end. If int, absolute position.
|
|
1402
|
+
If float between 0 and 1, specifies a fraction of sequence length.
|
|
1403
|
+
|
|
1404
|
+
replay_small : bool, default=False
|
|
1405
|
+
If True, occasionally sample smaller sequence lengths with
|
|
1406
|
+
specific distributions to ensure model robustness on smaller datasets
|
|
1407
|
+
|
|
1408
|
+
prior_type : str, default="mlp_scm"
|
|
1409
|
+
Type of prior: 'mlp_scm' (default), 'tree_scm', 'mix_scm', or 'dummy'
|
|
1410
|
+
|
|
1411
|
+
1. SCM-based: Structural causal models with complex feature relationships
|
|
1412
|
+
- 'mlp_scm': MLP-based causal models
|
|
1413
|
+
- 'tree_scm': Tree-based causal models
|
|
1414
|
+
- 'mix_scm': Probabilistic mix of the above models
|
|
1415
|
+
|
|
1416
|
+
2. Dummy: Randomly generated datasets for debugging
|
|
1417
|
+
|
|
1418
|
+
scm_fixed_hp : dict, default=DEFAULT_FIXED_HP
|
|
1419
|
+
Fixed parameters for SCM-based priors
|
|
1420
|
+
|
|
1421
|
+
scm_sampled_hp : dict, default=DEFAULT_SAMPLED_HP
|
|
1422
|
+
Parameters sampled during generation
|
|
1423
|
+
|
|
1424
|
+
config : PriorConfig | None, default=None
|
|
1425
|
+
Prior configuration when using 'graph_scm' prior_type
|
|
1426
|
+
|
|
1427
|
+
n_jobs : int, default=-1
|
|
1428
|
+
Number of parallel jobs to run (-1 means using all processors)
|
|
1429
|
+
|
|
1430
|
+
num_threads_per_generate : int, default=1
|
|
1431
|
+
Number of threads per job for dataset generation
|
|
1432
|
+
|
|
1433
|
+
device : str, default="cpu"
|
|
1434
|
+
Computation device ('cpu' or 'cuda')
|
|
1435
|
+
"""
|
|
1436
|
+
|
|
1437
|
+
def __init__(
|
|
1438
|
+
self,
|
|
1439
|
+
regression: bool = False,
|
|
1440
|
+
batch_size: int = 256,
|
|
1441
|
+
batch_size_per_gp: int = 4,
|
|
1442
|
+
batch_size_per_subgp: Optional[int] = None,
|
|
1443
|
+
min_features: int = 2,
|
|
1444
|
+
max_features: int = 100,
|
|
1445
|
+
max_classes: int = 10,
|
|
1446
|
+
min_seq_len: Optional[int] = None,
|
|
1447
|
+
max_seq_len: int = 1024,
|
|
1448
|
+
log_seq_len: bool = False,
|
|
1449
|
+
log_n_features: bool = False,
|
|
1450
|
+
seq_len_per_gp: bool = False,
|
|
1451
|
+
min_train_size: Union[int, float] = 0.1,
|
|
1452
|
+
max_train_size: Union[int, float] = 0.9,
|
|
1453
|
+
replay_small: bool = False,
|
|
1454
|
+
prior_type: str = "mlp_scm",
|
|
1455
|
+
scm_fixed_hp: Dict[str, Any] = DEFAULT_FIXED_HP,
|
|
1456
|
+
scm_sampled_hp: Dict[str, Any] = DEFAULT_SAMPLED_HP,
|
|
1457
|
+
config: Optional[PriorConfig] = None,
|
|
1458
|
+
n_jobs: int = -1,
|
|
1459
|
+
num_threads_per_generate: int = 1,
|
|
1460
|
+
device: str = "cpu",
|
|
1461
|
+
):
|
|
1462
|
+
super().__init__()
|
|
1463
|
+
if prior_type == "dummy":
|
|
1464
|
+
self.prior = DummyPrior(
|
|
1465
|
+
regression=regression,
|
|
1466
|
+
batch_size=batch_size,
|
|
1467
|
+
min_features=min_features,
|
|
1468
|
+
max_features=max_features,
|
|
1469
|
+
max_classes=max_classes,
|
|
1470
|
+
min_seq_len=min_seq_len,
|
|
1471
|
+
max_seq_len=max_seq_len,
|
|
1472
|
+
log_seq_len=log_seq_len,
|
|
1473
|
+
min_train_size=min_train_size,
|
|
1474
|
+
max_train_size=max_train_size,
|
|
1475
|
+
device=device,
|
|
1476
|
+
)
|
|
1477
|
+
elif prior_type in ["mlp_scm", "tree_scm", "mix_scm"]:
|
|
1478
|
+
self.prior = SCMPrior(
|
|
1479
|
+
regression=regression,
|
|
1480
|
+
batch_size=batch_size,
|
|
1481
|
+
batch_size_per_gp=batch_size_per_gp,
|
|
1482
|
+
batch_size_per_subgp=batch_size_per_subgp,
|
|
1483
|
+
min_features=min_features,
|
|
1484
|
+
max_features=max_features,
|
|
1485
|
+
max_classes=max_classes,
|
|
1486
|
+
min_seq_len=min_seq_len,
|
|
1487
|
+
max_seq_len=max_seq_len,
|
|
1488
|
+
log_seq_len=log_seq_len,
|
|
1489
|
+
log_n_features=log_n_features,
|
|
1490
|
+
seq_len_per_gp=seq_len_per_gp,
|
|
1491
|
+
min_train_size=min_train_size,
|
|
1492
|
+
max_train_size=max_train_size,
|
|
1493
|
+
replay_small=replay_small,
|
|
1494
|
+
prior_type=prior_type,
|
|
1495
|
+
fixed_hp=scm_fixed_hp,
|
|
1496
|
+
sampled_hp=scm_sampled_hp,
|
|
1497
|
+
n_jobs=n_jobs,
|
|
1498
|
+
num_threads_per_generate=num_threads_per_generate,
|
|
1499
|
+
device=device,
|
|
1500
|
+
config=config,
|
|
1501
|
+
)
|
|
1502
|
+
elif prior_type == "graph_scm":
|
|
1503
|
+
self.prior = GraphPrior(
|
|
1504
|
+
regression=regression,
|
|
1505
|
+
batch_size=batch_size,
|
|
1506
|
+
batch_size_per_gp=batch_size_per_gp,
|
|
1507
|
+
batch_size_per_subgp=batch_size_per_subgp,
|
|
1508
|
+
min_features=min_features,
|
|
1509
|
+
max_features=max_features,
|
|
1510
|
+
max_classes=max_classes,
|
|
1511
|
+
min_seq_len=min_seq_len,
|
|
1512
|
+
max_seq_len=max_seq_len,
|
|
1513
|
+
log_seq_len=log_seq_len,
|
|
1514
|
+
log_n_features=log_n_features,
|
|
1515
|
+
seq_len_per_gp=seq_len_per_gp,
|
|
1516
|
+
min_train_size=min_train_size,
|
|
1517
|
+
max_train_size=max_train_size,
|
|
1518
|
+
replay_small=replay_small,
|
|
1519
|
+
config=config,
|
|
1520
|
+
n_jobs=n_jobs,
|
|
1521
|
+
num_threads_per_generate=num_threads_per_generate,
|
|
1522
|
+
device=device,
|
|
1523
|
+
)
|
|
1524
|
+
else:
|
|
1525
|
+
raise ValueError(
|
|
1526
|
+
f"Unknown prior type '{prior_type}'. Available options: 'mlp_scm', 'tree_scm', 'mix_scm', 'graph_scm', or 'dummy'."
|
|
1527
|
+
)
|
|
1528
|
+
|
|
1529
|
+
self.regression = regression
|
|
1530
|
+
self.batch_size = batch_size
|
|
1531
|
+
self.batch_size_per_gp = batch_size_per_gp
|
|
1532
|
+
self.batch_size_per_subgp = batch_size_per_subgp or batch_size_per_gp
|
|
1533
|
+
self.min_features = min_features
|
|
1534
|
+
self.max_features = max_features
|
|
1535
|
+
self.max_classes = 0 if regression else max_classes
|
|
1536
|
+
self.min_seq_len = min_seq_len
|
|
1537
|
+
self.max_seq_len = max_seq_len
|
|
1538
|
+
self.log_seq_len = log_seq_len
|
|
1539
|
+
self.seq_len_per_gp = seq_len_per_gp
|
|
1540
|
+
self.min_train_size = min_train_size
|
|
1541
|
+
self.max_train_size = max_train_size
|
|
1542
|
+
self.device = device
|
|
1543
|
+
self.prior_type = prior_type
|
|
1544
|
+
|
|
1545
|
+
def get_batch(
|
|
1546
|
+
self, batch_size: Optional[int] = None, forced_group_hp: Optional[Dict[str, Any]] = None
|
|
1547
|
+
) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
|
|
1548
|
+
"""
|
|
1549
|
+
Generate a new batch of datasets.
|
|
1550
|
+
|
|
1551
|
+
Parameters
|
|
1552
|
+
----------
|
|
1553
|
+
batch_size : int, optional
|
|
1554
|
+
If provided, overrides the default batch size for this call
|
|
1555
|
+
|
|
1556
|
+
forced_group_hp : dict, optional
|
|
1557
|
+
Forwarded to the underlying prior's get_batch -- see SCMPrior/GraphPrior.get_batch's
|
|
1558
|
+
docstring. Used to pin dataset shape across the aggregate_k_gradients micro-steps of
|
|
1559
|
+
one optimizer step.
|
|
1560
|
+
|
|
1561
|
+
Returns
|
|
1562
|
+
-------
|
|
1563
|
+
X : Tensor or NestedTensor
|
|
1564
|
+
1. For SCM-based priors:
|
|
1565
|
+
- If seq_len_per_gp=False, shape is (batch_size, seq_len, max_features).
|
|
1566
|
+
- If seq_len_per_gp=True, returns a NestedTensor.
|
|
1567
|
+
|
|
1568
|
+
2. For DummyPrior, random Gaussian values of (batch_size, seq_len, max_features).
|
|
1569
|
+
|
|
1570
|
+
y : Tensor or NestedTensor
|
|
1571
|
+
1. For SCM-based priors:
|
|
1572
|
+
- If seq_len_per_gp=False, shape is (batch_size, seq_len).
|
|
1573
|
+
- If seq_len_per_gp=True, returns a NestedTensor.
|
|
1574
|
+
|
|
1575
|
+
2. For DummyPrior, random class Targets of (batch_size, seq_len).
|
|
1576
|
+
|
|
1577
|
+
d : Tensor
|
|
1578
|
+
Number of active features per dataset of shape (batch_size,).
|
|
1579
|
+
|
|
1580
|
+
seq_lens : Tensor
|
|
1581
|
+
Sequence length for each dataset of shape (batch_size,).
|
|
1582
|
+
|
|
1583
|
+
train_sizes : Tensor
|
|
1584
|
+
Position for train/test split for each dataset of shape (batch_size,).
|
|
1585
|
+
"""
|
|
1586
|
+
return self.prior.get_batch(batch_size or self.batch_size, forced_group_hp=forced_group_hp)
|
|
1587
|
+
|
|
1588
|
+
def __iter__(self) -> "PriorDataset":
|
|
1589
|
+
"""
|
|
1590
|
+
Returns an iterator that yields batches indefinitely.
|
|
1591
|
+
|
|
1592
|
+
Returns
|
|
1593
|
+
-------
|
|
1594
|
+
self
|
|
1595
|
+
Returns self as an iterator
|
|
1596
|
+
"""
|
|
1597
|
+
return self
|
|
1598
|
+
|
|
1599
|
+
def __next__(self) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
|
|
1600
|
+
"""
|
|
1601
|
+
Returns the next batch from the iterator. Since this is an infinite
|
|
1602
|
+
iterator, it never raises StopIteration and instead continuously generates
|
|
1603
|
+
new synthetic data batches.
|
|
1604
|
+
"""
|
|
1605
|
+
# with DisablePrinting():
|
|
1606
|
+
# return self.get_batch()
|
|
1607
|
+
return self.get_batch()
|
|
1608
|
+
|
|
1609
|
+
def __repr__(self) -> str:
|
|
1610
|
+
"""
|
|
1611
|
+
Returns a string representation of the dataset.
|
|
1612
|
+
|
|
1613
|
+
Provides a detailed view of the dataset configuration for debugging
|
|
1614
|
+
and logging purposes.
|
|
1615
|
+
|
|
1616
|
+
Returns
|
|
1617
|
+
-------
|
|
1618
|
+
str
|
|
1619
|
+
A formatted string with dataset parameters
|
|
1620
|
+
"""
|
|
1621
|
+
return (
|
|
1622
|
+
f"PriorDataset(\n"
|
|
1623
|
+
f" task: {'regression' if self.regression else 'classification'}\n"
|
|
1624
|
+
f" prior_type: {self.prior_type}\n"
|
|
1625
|
+
f" batch_size: {self.batch_size}\n"
|
|
1626
|
+
f" batch_size_per_gp: {self.batch_size_per_gp}\n"
|
|
1627
|
+
f" features: {self.min_features} - {self.max_features}\n"
|
|
1628
|
+
f" max classes: {self.max_classes}\n"
|
|
1629
|
+
f" seq_len: {self.min_seq_len or 'None'} - {self.max_seq_len}\n"
|
|
1630
|
+
f" sequence length varies across groups: {self.seq_len_per_gp}\n"
|
|
1631
|
+
f" train_size: {self.min_train_size} - {self.max_train_size}\n"
|
|
1632
|
+
f" device: {self.device}\n"
|
|
1633
|
+
f")"
|
|
1634
|
+
)
|
|
1635
|
+
|
|
1636
|
+
|
|
1637
|
+
class DisablePrinting:
|
|
1638
|
+
"""Context manager to temporarily suppress printed output."""
|
|
1639
|
+
|
|
1640
|
+
def __enter__(self):
|
|
1641
|
+
self.original_stdout = sys.stdout
|
|
1642
|
+
sys.stdout = open(os.devnull, "w")
|
|
1643
|
+
|
|
1644
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
1645
|
+
sys.stdout.close()
|
|
1646
|
+
sys.stdout = self.original_stdout
|
|
1647
|
+
|
|
1648
|
+
|
|
1649
|
+
def should_filter(
|
|
1650
|
+
X: torch.Tensor,
|
|
1651
|
+
y: torch.Tensor,
|
|
1652
|
+
config: PriorConfig,
|
|
1653
|
+
*,
|
|
1654
|
+
is_classif: bool,
|
|
1655
|
+
n_estimators: int = 25,
|
|
1656
|
+
n_boot: int = 200,
|
|
1657
|
+
) -> bool:
|
|
1658
|
+
if not (config.remove_trivial_datasets or config.filter_unpredictable_datasets):
|
|
1659
|
+
return False
|
|
1660
|
+
|
|
1661
|
+
if is_classif:
|
|
1662
|
+
y_int = y.to(torch.long)
|
|
1663
|
+
C = int(y_int.max().item() + 1)
|
|
1664
|
+
Y = F.one_hot(y_int, num_classes=C).to(torch.float32) # (n, C)
|
|
1665
|
+
if C == 2:
|
|
1666
|
+
# drop one dimension to make it faster
|
|
1667
|
+
Y = Y[:, :1]
|
|
1668
|
+
else:
|
|
1669
|
+
Y = y.reshape(-1, 1).to(torch.float32) # (n, 1)
|
|
1670
|
+
|
|
1671
|
+
# sklearn needs numpy
|
|
1672
|
+
X_np = X.detach().cpu().numpy()
|
|
1673
|
+
Y_np = Y.detach().cpu().numpy()
|
|
1674
|
+
|
|
1675
|
+
# do the squeeze to avoid a sklearn warning
|
|
1676
|
+
et = ExtraTreesRegressor(
|
|
1677
|
+
n_estimators=n_estimators,
|
|
1678
|
+
bootstrap=True,
|
|
1679
|
+
oob_score=True,
|
|
1680
|
+
n_jobs=1,
|
|
1681
|
+
random_state=1, # don't set to 0 because it doesn't give OOB scores for all samples for some 133 <= n <= 257
|
|
1682
|
+
max_depth=6, # make it faster
|
|
1683
|
+
).fit(X_np, np.squeeze(Y_np, axis=-1) if Y_np.shape[-1] == 1 else Y_np)
|
|
1684
|
+
|
|
1685
|
+
Yhat = et.oob_prediction_ # (n, d)
|
|
1686
|
+
if len(Yhat.shape) == 1:
|
|
1687
|
+
Yhat = Yhat[:, None]
|
|
1688
|
+
mask = ~np.isnan(Yhat).any(axis=1) # keep valid OOB rows
|
|
1689
|
+
Yv, Yhatv = Y_np[mask], Yhat[mask]
|
|
1690
|
+
|
|
1691
|
+
baseline = Y_np.mean(axis=0, keepdims=True) # (1, d)
|
|
1692
|
+
imp = ((Yv - baseline) ** 2).sum(axis=1) - ((Yv - Yhatv) ** 2).sum(axis=1)
|
|
1693
|
+
|
|
1694
|
+
baseline_mse = ((Yv - baseline) ** 2).sum(axis=1).mean()
|
|
1695
|
+
extratrees_mse = ((Yv - Yhatv) ** 2).sum(axis=1).mean()
|
|
1696
|
+
|
|
1697
|
+
# Vectorized bootstrap (no retraining)
|
|
1698
|
+
rng = np.random.default_rng(0)
|
|
1699
|
+
n = imp.shape[0]
|
|
1700
|
+
idx = rng.integers(0, n, size=(n_boot, n))
|
|
1701
|
+
pval = float(np.mean(imp[idx].mean(axis=1) <= 0.0))
|
|
1702
|
+
|
|
1703
|
+
if config.remove_trivial_datasets and np.sqrt(extratrees_mse) <= config.trivial_dataset_threshold * np.sqrt(baseline_mse):
|
|
1704
|
+
return True
|
|
1705
|
+
if config.filter_unpredictable_datasets and pval >= 0.05:
|
|
1706
|
+
return True
|
|
1707
|
+
return False
|
|
1708
|
+
|
|
1709
|
+
|
|
1710
|
+
def compute_predictability_pvalue(
|
|
1711
|
+
X: torch.Tensor,
|
|
1712
|
+
y: torch.Tensor,
|
|
1713
|
+
*,
|
|
1714
|
+
is_classif: bool,
|
|
1715
|
+
n_estimators: int = 25,
|
|
1716
|
+
n_boot: int = 200,
|
|
1717
|
+
) -> float:
|
|
1718
|
+
"""
|
|
1719
|
+
Single-fit ExtraTreesRegressor with OOB predictions.
|
|
1720
|
+
Metric: MSE (== multiclass Brier; binary up to a constant factor).
|
|
1721
|
+
Baseline: mean target (== class-prior vector for classification).
|
|
1722
|
+
Returns a one-sided bootstrap p-value for 'model > baseline'.
|
|
1723
|
+
"""
|
|
1724
|
+
if is_classif:
|
|
1725
|
+
y_int = y.to(torch.long)
|
|
1726
|
+
C = int(y_int.max().item() + 1)
|
|
1727
|
+
Y = F.one_hot(y_int, num_classes=C).to(torch.float32) # (n, C)
|
|
1728
|
+
if C == 2:
|
|
1729
|
+
# drop one dimension to make it faster
|
|
1730
|
+
Y = Y[:, :1]
|
|
1731
|
+
else:
|
|
1732
|
+
Y = y.reshape(-1, 1).to(torch.float32) # (n, 1)
|
|
1733
|
+
|
|
1734
|
+
# sklearn needs numpy
|
|
1735
|
+
X_np = X.detach().cpu().numpy()
|
|
1736
|
+
Y_np = Y.detach().cpu().numpy()
|
|
1737
|
+
|
|
1738
|
+
# do the squeeze to avoid a sklearn warning
|
|
1739
|
+
et = ExtraTreesRegressor(
|
|
1740
|
+
n_estimators=n_estimators,
|
|
1741
|
+
bootstrap=True,
|
|
1742
|
+
oob_score=True,
|
|
1743
|
+
n_jobs=1,
|
|
1744
|
+
random_state=1, # don't set to 0 because it doesn't give OOB scores for all samples for some 133 <= n <= 257
|
|
1745
|
+
max_depth=6, # make it faster
|
|
1746
|
+
).fit(X_np, np.squeeze(Y_np, axis=-1) if Y_np.shape[-1] == 1 else Y_np)
|
|
1747
|
+
|
|
1748
|
+
Yhat = et.oob_prediction_ # (n, d)
|
|
1749
|
+
if len(Yhat.shape) == 1:
|
|
1750
|
+
Yhat = Yhat[:, None]
|
|
1751
|
+
mask = ~np.isnan(Yhat).any(axis=1) # keep valid OOB rows
|
|
1752
|
+
Yv, Yhatv = Y_np[mask], Yhat[mask]
|
|
1753
|
+
|
|
1754
|
+
baseline = Y_np.mean(axis=0, keepdims=True) # (1, d)
|
|
1755
|
+
imp = ((Yv - baseline) ** 2).sum(axis=1) - ((Yv - Yhatv) ** 2).sum(axis=1)
|
|
1756
|
+
|
|
1757
|
+
# Vectorized bootstrap (no retraining)
|
|
1758
|
+
rng = np.random.default_rng(0)
|
|
1759
|
+
n = imp.shape[0]
|
|
1760
|
+
idx = rng.integers(0, n, size=(n_boot, n))
|
|
1761
|
+
pval = float(np.mean(imp[idx].mean(axis=1) <= 0.0))
|
|
1762
|
+
return pval
|