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/train/configs.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Copyright (c) 2025-2026, the FirePFN authors.
|
|
3
|
+
"""Training configurations of FirePFN.
|
|
4
|
+
|
|
5
|
+
FirePFN is trained in two stages, the second in three cosine lr cycles:
|
|
6
|
+
|
|
7
|
+
``stage1`` (research run hydrapfn7_124_kumo_large): from scratch, the Kumo-Tabular large encoder
|
|
8
|
+
loaded from nvidia/Kumo-Tabular and frozen; 2048-row tables with 200..1024 context rows, up to
|
|
9
|
+
200 features; 1000 epochs, 4 GPUs.
|
|
10
|
+
``stage2`` (research run hydrapfn7_131_124_ctx100): continued from the final stage-1 model on the
|
|
11
|
+
context-bucket schedule (256 .. 32768 context rows per table), up to 100 features; 250-epoch
|
|
12
|
+
cosine cycle, peak lr 1e-4, 8 GPUs.
|
|
13
|
+
``stage2_cyc2`` (hydrapfn7_133_131_ctx100_cyc2b) and ``stage2_cyc3`` (hydrapfn7_135_133_ctx100_cyc3):
|
|
14
|
+
two more 250-epoch cycles of stage 2 at peak lr 5e-5, each from the previous cycle's final model
|
|
15
|
+
(``--init``) with its own context-bucket seed. The released FirePFN checkpoint is the final
|
|
16
|
+
model of ``stage2_cyc3`` (epoch 250).
|
|
17
|
+
|
|
18
|
+
Batch sizes are per GPU (each rank draws its own tables); "epoch" = num_steps optimizer steps.
|
|
19
|
+
"""
|
|
20
|
+
import copy
|
|
21
|
+
|
|
22
|
+
MODEL = {
|
|
23
|
+
"emsize": 1024,
|
|
24
|
+
"nhid_factor": 2,
|
|
25
|
+
"max_num_classes": 10,
|
|
26
|
+
"num_heads": 4,
|
|
27
|
+
"layer_pattern": ["ssm", "ssm", "attn", "ssm", "deltanet", "attn"],
|
|
28
|
+
"ssm_config": {"rope_fraction": 0.0, "d_state": 64, "expand": 2},
|
|
29
|
+
"col_max_classes": 10,
|
|
30
|
+
"col_num_cls": 4,
|
|
31
|
+
"kumo_num_blocks": 6,
|
|
32
|
+
"kumo_num_heads": 4,
|
|
33
|
+
"kumo_num_inds": 256,
|
|
34
|
+
"kumo_group_size": 3,
|
|
35
|
+
"kumo_num_frequencies": 32,
|
|
36
|
+
"kumo_categorical": True,
|
|
37
|
+
"kumo_row_gate_hidden": 64,
|
|
38
|
+
"kumo_frozen": True,
|
|
39
|
+
"kumo_input_norm": True,
|
|
40
|
+
"cross_attn_len_temp": True,
|
|
41
|
+
"center_logits": True,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
STAGE1 = {
|
|
45
|
+
**MODEL,
|
|
46
|
+
# pretrained encoder (Hugging Face repo, file, revision) -- loaded only when training from scratch
|
|
47
|
+
"kumo_pretrained": ("nvidia/Kumo-Tabular", "large/classifier.pt", "v1.0.1"),
|
|
48
|
+
"num_features": 200,
|
|
49
|
+
# optimisation
|
|
50
|
+
"epochs": 1000,
|
|
51
|
+
"schedule_epochs": 1000,
|
|
52
|
+
"warmup_epochs": 200,
|
|
53
|
+
"lr": 1e-4,
|
|
54
|
+
"weight_decay": 0.02,
|
|
55
|
+
"cross_attn_wd": 0.2,
|
|
56
|
+
"linattn_qk_wd": 0.2,
|
|
57
|
+
"loss_label_smoothing": 0.01,
|
|
58
|
+
"s_norm_penalty_coef": 0.01,
|
|
59
|
+
"s_norm_penalty_mult": 3.0,
|
|
60
|
+
"grad_clip_floor": 0.3,
|
|
61
|
+
"grad_clip_max": 1.0,
|
|
62
|
+
"grad_clip_ema_decay": 0.98,
|
|
63
|
+
"grad_clip_ema_mult": 3.0,
|
|
64
|
+
"bf16": True,
|
|
65
|
+
"num_steps": 32, # optimizer steps per epoch
|
|
66
|
+
"aggregate_k_gradients": 1, # micro-steps per optimizer step
|
|
67
|
+
"batch_size": 32, # tables per optimizer step and GPU
|
|
68
|
+
"save_every_n_epochs": 10,
|
|
69
|
+
# data: TabICLv2 graph_scm prior
|
|
70
|
+
"normalize_by_used_features": True,
|
|
71
|
+
"bptt": 2048, # rows per table
|
|
72
|
+
"tabicl_min_train_size": 200,
|
|
73
|
+
"tabicl_max_train_size": 1025,
|
|
74
|
+
"tabicl_min_features": 1,
|
|
75
|
+
"tabicl_max_features": 200,
|
|
76
|
+
"tabicl_batch_size_per_gp": 8,
|
|
77
|
+
"tabicl_prior_type": "graph_scm",
|
|
78
|
+
"tabicl_graph_noise": False,
|
|
79
|
+
"tabicl_filter_unpredictable_graphs": True,
|
|
80
|
+
"tabicl_filter_unpredictable_datasets": True,
|
|
81
|
+
"tabicl_allow_act_warping": False,
|
|
82
|
+
"tabicl_min_n_nodes": 2,
|
|
83
|
+
"tabicl_max_n_nodes": 32,
|
|
84
|
+
"tabicl_cauchy_dag_offset": 0.0,
|
|
85
|
+
"tabicl_n_jobs": 4, # prior DataLoader workers per GPU
|
|
86
|
+
"ctx_bucket_schedule": None,
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
STAGE2 = copy.deepcopy(STAGE1)
|
|
90
|
+
STAGE2.update({
|
|
91
|
+
"kumo_pretrained": None, # the encoder comes with the stage-1 checkpoint
|
|
92
|
+
"num_features": 100,
|
|
93
|
+
"tabicl_max_features": 100,
|
|
94
|
+
"epochs": 250,
|
|
95
|
+
"schedule_epochs": 250,
|
|
96
|
+
"warmup_epochs": 5,
|
|
97
|
+
"lr": 1e-4,
|
|
98
|
+
# one micro-step per context bucket: 128 tables x 256 rows ... 1 table x 32768 rows (+ 25% queries)
|
|
99
|
+
"ctx_bucket_schedule": {"seed": 131},
|
|
100
|
+
"aggregate_k_gradients": 8,
|
|
101
|
+
"bptt": 10240,
|
|
102
|
+
"tabicl_min_train_size": 200,
|
|
103
|
+
"tabicl_max_train_size": 8193,
|
|
104
|
+
"tabicl_batch_size_per_gp": 4,
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
# Further stage-2 cycles (lr 5e-5 peak, otherwise unchanged), started from the previous cycle's final model.
|
|
108
|
+
STAGE2_CYC2 = copy.deepcopy(STAGE2)
|
|
109
|
+
STAGE2_CYC2.update({"lr": 5e-5, "ctx_bucket_schedule": {"seed": 133}})
|
|
110
|
+
STAGE2_CYC3 = copy.deepcopy(STAGE2)
|
|
111
|
+
STAGE2_CYC3.update({"lr": 5e-5, "ctx_bucket_schedule": {"seed": 135}})
|
|
112
|
+
|
|
113
|
+
CONFIGS = {"stage1": STAGE1, "stage2": STAGE2, "stage2_cyc2": STAGE2_CYC2, "stage2_cyc3": STAGE2_CYC3}
|
firepfn/train/loop.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Copyright (c) 2025-2026, the FirePFN authors.
|
|
3
|
+
"""FirePFN training loop (single GPU or DDP via torchrun).
|
|
4
|
+
|
|
5
|
+
Every optimizer step accumulates ``aggregate_k_gradients`` micro-steps; each micro-step is one
|
|
6
|
+
batch of synthetic tables from the prior (with the context-bucket schedule: one bucket). Loss per
|
|
7
|
+
micro-step: cross-entropy (label smoothing) on the query rows, averaged over rows and then over
|
|
8
|
+
tables, plus the linear-attention S-norm penalty, scaled by the micro-step's share of the step.
|
|
9
|
+
Gradients are clipped per backbone mixer kind with an adaptive threshold; the learning rate follows
|
|
10
|
+
a per-epoch warmup + cosine schedule.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import datetime
|
|
15
|
+
import json
|
|
16
|
+
import math
|
|
17
|
+
import os
|
|
18
|
+
import random
|
|
19
|
+
import time
|
|
20
|
+
from contextlib import nullcontext
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
import torch
|
|
24
|
+
import torch.nn.functional as F
|
|
25
|
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
|
26
|
+
|
|
27
|
+
from firepfn.model import FirePFN
|
|
28
|
+
from firepfn.train.optim import (AdaptiveClipThreshold, clip_grad_norm_per_group, cosine_schedule_with_warmup,
|
|
29
|
+
make_optimizer, s_norm_penalty)
|
|
30
|
+
from firepfn.train.prior import build_prior_dataset, build_prior_loader, to_micro_batch
|
|
31
|
+
from firepfn.train.schedule import BucketedTabICLStream, CtxBucketSchedule
|
|
32
|
+
|
|
33
|
+
CHECKPOINT_FORMAT = "firepfn-train-v1"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _init_distributed():
|
|
37
|
+
if "LOCAL_RANK" not in os.environ:
|
|
38
|
+
return False, 0, 1, torch.device("cuda", 0)
|
|
39
|
+
local_rank = int(os.environ["LOCAL_RANK"])
|
|
40
|
+
torch.cuda.set_device(local_rank)
|
|
41
|
+
device = torch.device("cuda", local_rank)
|
|
42
|
+
torch.distributed.init_process_group(
|
|
43
|
+
backend="nccl", init_method="env://", device_id=device,
|
|
44
|
+
# a slow prior draw on one rank must not trip the NCCL watchdog
|
|
45
|
+
timeout=datetime.timedelta(seconds=int(os.environ.get("FIREPFN_NCCL_TIMEOUT_S", 600))))
|
|
46
|
+
return True, torch.distributed.get_rank(), torch.distributed.get_world_size(), device
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _seed_everything(seed: int):
|
|
50
|
+
random.seed(seed)
|
|
51
|
+
np.random.seed(seed % 2**32)
|
|
52
|
+
torch.manual_seed(seed)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _load_kumo(model: FirePFN, spec):
|
|
56
|
+
"""spec: local path, or (hf_repo, filename, revision)."""
|
|
57
|
+
if isinstance(spec, (list, tuple)):
|
|
58
|
+
from huggingface_hub import hf_hub_download
|
|
59
|
+
repo, filename, revision = spec
|
|
60
|
+
spec = hf_hub_download(repo_id=repo, filename=filename, revision=revision)
|
|
61
|
+
model.load_kumo_pretrained(spec)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _json_config(cfg: dict) -> dict:
|
|
65
|
+
return json.loads(json.dumps(cfg, default=str))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def save_checkpoint(path, model, optimizer, scheduler, clip, epoch, cfg):
|
|
69
|
+
tmp = path + ".tmp"
|
|
70
|
+
torch.save({"format": CHECKPOINT_FORMAT, "model_state_dict": model.state_dict(),
|
|
71
|
+
"optimizer": optimizer.state_dict(), "scheduler": scheduler.state_dict(),
|
|
72
|
+
"clip": clip.state_dict(), "epoch": epoch, "config": _json_config(cfg)}, tmp)
|
|
73
|
+
os.replace(tmp, path)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def train(cfg: dict, out_dir: str, init_checkpoint: str | None = None, resume: str | None = None,
|
|
77
|
+
seed: int = 0, use_wandb: bool = False, run_name: str = "firepfn"):
|
|
78
|
+
"""Train FirePFN.
|
|
79
|
+
|
|
80
|
+
init_checkpoint: start from these model weights (any FirePFN / research checkpoint) with a
|
|
81
|
+
fresh optimizer and the schedule at epoch 0 (stage 2 starts from the stage-1 model).
|
|
82
|
+
resume: continue an interrupted run of this loop (model, optimizer, scheduler, epoch).
|
|
83
|
+
"""
|
|
84
|
+
is_dist, rank, world, device = _init_distributed()
|
|
85
|
+
_seed_everything(seed * 1000 + rank) # every rank draws its own tables
|
|
86
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
87
|
+
from firepfn.model.fla_autotune import patch as _patch_fla
|
|
88
|
+
_patch_fla()
|
|
89
|
+
|
|
90
|
+
# ------------------------------------------------------------------ model / optimizer
|
|
91
|
+
start_epoch = 0
|
|
92
|
+
resume_ckpt = torch.load(resume, map_location="cpu", weights_only=True) if resume else None
|
|
93
|
+
if resume_ckpt is not None:
|
|
94
|
+
model = FirePFN.from_config(resume_ckpt["config"])
|
|
95
|
+
model.load_state_dict(resume_ckpt["model_state_dict"], strict=True)
|
|
96
|
+
start_epoch = int(resume_ckpt["epoch"])
|
|
97
|
+
elif init_checkpoint:
|
|
98
|
+
from firepfn.loading import _read
|
|
99
|
+
init_cfg, state, _ = _read(init_checkpoint)
|
|
100
|
+
model = FirePFN.from_config(init_cfg)
|
|
101
|
+
model.load_state_dict(state, strict=True)
|
|
102
|
+
else:
|
|
103
|
+
model = FirePFN.from_config(cfg)
|
|
104
|
+
if cfg.get("kumo_pretrained"):
|
|
105
|
+
_load_kumo(model, cfg["kumo_pretrained"])
|
|
106
|
+
model.to(device)
|
|
107
|
+
model.train()
|
|
108
|
+
optimizer = make_optimizer(model, lr=cfg["lr"], weight_decay=cfg["weight_decay"],
|
|
109
|
+
cross_attn_wd=cfg["cross_attn_wd"], linattn_qk_wd=cfg["linattn_qk_wd"])
|
|
110
|
+
scheduler = cosine_schedule_with_warmup(optimizer, cfg["warmup_epochs"], cfg["schedule_epochs"])
|
|
111
|
+
clip = AdaptiveClipThreshold(cfg["grad_clip_floor"], cfg["grad_clip_max"],
|
|
112
|
+
cfg["grad_clip_ema_decay"], cfg["grad_clip_ema_mult"])
|
|
113
|
+
if resume_ckpt is not None:
|
|
114
|
+
optimizer.load_state_dict(resume_ckpt["optimizer"])
|
|
115
|
+
scheduler.load_state_dict(resume_ckpt["scheduler"])
|
|
116
|
+
clip.load_state_dict(resume_ckpt["clip"])
|
|
117
|
+
del resume_ckpt
|
|
118
|
+
net = DDP(model, device_ids=[device.index], bucket_cap_mb=400) if is_dist else model
|
|
119
|
+
if rank == 0:
|
|
120
|
+
n_train = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
|
121
|
+
n_all = sum(p.numel() for p in model.parameters())
|
|
122
|
+
print(f"FirePFN: {n_all / 1e6:.1f}M parameters ({n_train / 1e6:.1f}M trained), "
|
|
123
|
+
f"{world} GPU(s), epochs {start_epoch + 1}..{cfg['epochs']}", flush=True)
|
|
124
|
+
|
|
125
|
+
# ------------------------------------------------------------------ data
|
|
126
|
+
k = cfg["aggregate_k_gradients"]
|
|
127
|
+
steps_per_epoch = cfg["num_steps"] # optimizer steps
|
|
128
|
+
schedule = None
|
|
129
|
+
if cfg.get("ctx_bucket_schedule"):
|
|
130
|
+
schedule = CtxBucketSchedule(**cfg["ctx_bucket_schedule"])
|
|
131
|
+
if schedule.k != k:
|
|
132
|
+
raise ValueError(f"the bucket schedule has {schedule.k} micro-steps per step; "
|
|
133
|
+
f"aggregate_k_gradients must equal that, got {k}")
|
|
134
|
+
stream = BucketedTabICLStream(build_prior_dataset(cfg), schedule, start_step=start_epoch * steps_per_epoch)
|
|
135
|
+
workers = cfg["tabicl_n_jobs"]
|
|
136
|
+
batches = iter(torch.utils.data.DataLoader(
|
|
137
|
+
stream, batch_size=None, num_workers=workers, prefetch_factor=4 if workers else None,
|
|
138
|
+
persistent_workers=workers > 0, pin_memory=True))
|
|
139
|
+
if rank == 0:
|
|
140
|
+
print(schedule.describe(), flush=True)
|
|
141
|
+
else:
|
|
142
|
+
batches = iter(build_prior_loader(cfg))
|
|
143
|
+
n_out = cfg["max_num_classes"]
|
|
144
|
+
|
|
145
|
+
wandb_run = None
|
|
146
|
+
if use_wandb and rank == 0:
|
|
147
|
+
import wandb
|
|
148
|
+
wandb_run = wandb.init(project="fire-pfn", name=run_name, config=_json_config(cfg))
|
|
149
|
+
|
|
150
|
+
# ------------------------------------------------------------------ epochs
|
|
151
|
+
step = start_epoch * steps_per_epoch
|
|
152
|
+
for epoch in range(start_epoch + 1, cfg["epochs"] + 1):
|
|
153
|
+
t0 = time.time()
|
|
154
|
+
net.train()
|
|
155
|
+
loss_sum, loss_n, gn_sum, gn_max, skipped = 0.0, 0, 0.0, 0.0, 0
|
|
156
|
+
for _ in range(steps_per_epoch):
|
|
157
|
+
plan = schedule.plan(step) if schedule is not None else None
|
|
158
|
+
for j in range(k):
|
|
159
|
+
sync = j == k - 1
|
|
160
|
+
x, y, n_ctx = to_micro_batch(next(batches), cfg["num_features"],
|
|
161
|
+
cfg["normalize_by_used_features"])
|
|
162
|
+
if plan is not None and n_ctx != plan[j].ctx:
|
|
163
|
+
raise RuntimeError(f"prior stream out of step with the schedule ({n_ctx} != {plan[j].ctx})")
|
|
164
|
+
x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
|
|
165
|
+
scale = plan[j].weight / schedule.n_buckets if plan is not None else 1.0 / k
|
|
166
|
+
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=cfg["bf16"]):
|
|
167
|
+
logits = net(x, y, n_ctx) # (Q, B, n_out)
|
|
168
|
+
target = y[n_ctx:].long()
|
|
169
|
+
losses = F.cross_entropy(logits.reshape(-1, n_out), target.flatten(), reduction="none",
|
|
170
|
+
label_smoothing=cfg["loss_label_smoothing"]).view(target.shape)
|
|
171
|
+
per_table = losses.mean(0)
|
|
172
|
+
ok = ~torch.isnan(per_table)
|
|
173
|
+
loss = torch.where(ok, per_table, 0.0).sum() / ok.sum()
|
|
174
|
+
if cfg["s_norm_penalty_coef"] > 0:
|
|
175
|
+
pen = s_norm_penalty(model, cfg["s_norm_penalty_mult"])
|
|
176
|
+
if pen is not None:
|
|
177
|
+
loss = loss + cfg["s_norm_penalty_coef"] * pen
|
|
178
|
+
loss = loss * scale
|
|
179
|
+
finite = bool(torch.isfinite(loss))
|
|
180
|
+
if is_dist and sync: # all ranks must agree on the step's last micro-step
|
|
181
|
+
flag = torch.tensor(int(finite), device=device)
|
|
182
|
+
torch.distributed.all_reduce(flag, op=torch.distributed.ReduceOp.MIN)
|
|
183
|
+
finite = bool(flag.item())
|
|
184
|
+
with (net.no_sync() if is_dist and not sync else nullcontext()):
|
|
185
|
+
(loss if finite else torch.nan_to_num(loss) * 0.0).backward()
|
|
186
|
+
if finite:
|
|
187
|
+
loss_sum += float(losses.mean())
|
|
188
|
+
loss_n += 1
|
|
189
|
+
# ---- optimizer step
|
|
190
|
+
norms = clip_grad_norm_per_group(model, clip.value())
|
|
191
|
+
grad_norm = float(torch.stack(list(norms.values())).max()) if norms else 0.0
|
|
192
|
+
if math.isfinite(grad_norm):
|
|
193
|
+
optimizer.step()
|
|
194
|
+
clip.update(grad_norm)
|
|
195
|
+
gn_sum += grad_norm
|
|
196
|
+
gn_max = max(gn_max, grad_norm)
|
|
197
|
+
else:
|
|
198
|
+
skipped += 1
|
|
199
|
+
optimizer.zero_grad()
|
|
200
|
+
step += 1
|
|
201
|
+
|
|
202
|
+
lr = scheduler.get_last_lr()[0]
|
|
203
|
+
scheduler.step()
|
|
204
|
+
if rank == 0:
|
|
205
|
+
done = steps_per_epoch - skipped
|
|
206
|
+
msg = {"epoch": epoch, "loss": loss_sum / max(loss_n, 1), "lr": lr,
|
|
207
|
+
"grad_norm": gn_sum / max(done, 1), "grad_norm_max": gn_max,
|
|
208
|
+
"skipped_steps": skipped, "time_s": time.time() - t0}
|
|
209
|
+
print(" | ".join(f"{k_}: {v:.4g}" if isinstance(v, float) else f"{k_}: {v}" for k_, v in msg.items()),
|
|
210
|
+
flush=True)
|
|
211
|
+
if wandb_run is not None:
|
|
212
|
+
wandb_run.log(msg, step=epoch)
|
|
213
|
+
if epoch % cfg["save_every_n_epochs"] == 0 or epoch == cfg["epochs"]:
|
|
214
|
+
path = os.path.join(out_dir, f"{run_name}_epoch{epoch}.ckpt")
|
|
215
|
+
save_checkpoint(path, model, optimizer, scheduler, clip, epoch, cfg)
|
|
216
|
+
save_checkpoint(os.path.join(out_dir, f"{run_name}_last.ckpt"), model, optimizer, scheduler,
|
|
217
|
+
clip, epoch, cfg)
|
|
218
|
+
print(f"saved {path}", flush=True)
|
|
219
|
+
|
|
220
|
+
if wandb_run is not None:
|
|
221
|
+
wandb_run.finish()
|
|
222
|
+
if is_dist:
|
|
223
|
+
torch.distributed.destroy_process_group()
|
|
224
|
+
return model
|
firepfn/train/optim.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Copyright (c) 2025-2026, the FirePFN authors.
|
|
3
|
+
"""Optimizer, learning-rate schedule, gradient clipping and the linear-attention penalty."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
from torch.optim.lr_scheduler import LambdaLR
|
|
11
|
+
|
|
12
|
+
from firepfn.model.linear_attention import RowLinearAttentionBranch
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def make_optimizer(model, lr: float, weight_decay: float, cross_attn_wd: float, linattn_qk_wd: float):
|
|
16
|
+
"""AdamW with parameter groups:
|
|
17
|
+
|
|
18
|
+
* Hydra2's D skip parameters (``*.D``): no weight decay, 0.1x learning rate;
|
|
19
|
+
* parameters tagged ``_no_weight_decay`` (biases of the SSM gates, B/C biases, dt bias,
|
|
20
|
+
length-temperature alphas): no weight decay;
|
|
21
|
+
* the linear attention's q/k projections (``_qk_weight_decay``): ``linattn_qk_wd``;
|
|
22
|
+
* cross-attention q/k/v/out and the linear attention's v projection
|
|
23
|
+
(``_extra_weight_decay``): ``cross_attn_wd``;
|
|
24
|
+
* everything else: ``weight_decay``.
|
|
25
|
+
|
|
26
|
+
Frozen parameters (the pretrained Kumo encoder) are not optimized.
|
|
27
|
+
"""
|
|
28
|
+
decay, no_decay, d_slow, decay_extra, decay_qk = [], [], [], [], []
|
|
29
|
+
for name, p in model.named_parameters():
|
|
30
|
+
if not p.requires_grad:
|
|
31
|
+
continue
|
|
32
|
+
if name.endswith(".D") and p.dim() == 1:
|
|
33
|
+
d_slow.append(p)
|
|
34
|
+
elif getattr(p, "_no_weight_decay", False):
|
|
35
|
+
no_decay.append(p)
|
|
36
|
+
elif getattr(p, "_qk_weight_decay", False):
|
|
37
|
+
decay_qk.append(p)
|
|
38
|
+
elif getattr(p, "_extra_weight_decay", False):
|
|
39
|
+
decay_extra.append(p)
|
|
40
|
+
else:
|
|
41
|
+
decay.append(p)
|
|
42
|
+
groups = [
|
|
43
|
+
{"params": decay, "weight_decay": weight_decay},
|
|
44
|
+
{"params": no_decay, "weight_decay": 0.0},
|
|
45
|
+
{"params": d_slow, "weight_decay": 0.0, "lr": lr * 0.1},
|
|
46
|
+
{"params": decay_extra, "weight_decay": cross_attn_wd},
|
|
47
|
+
{"params": decay_qk, "weight_decay": linattn_qk_wd},
|
|
48
|
+
]
|
|
49
|
+
return torch.optim.AdamW([g for g in groups if g["params"]], lr=lr)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def cosine_schedule_with_warmup(optimizer, warmup_epochs: int, total_epochs: int, last_epoch: int = -1):
|
|
53
|
+
"""Linear warmup to the base learning rate, then half a cosine down to 0 (stepped per epoch)."""
|
|
54
|
+
def lr_lambda(epoch):
|
|
55
|
+
if epoch < warmup_epochs:
|
|
56
|
+
return epoch / max(1, warmup_epochs)
|
|
57
|
+
progress = (epoch - warmup_epochs) / max(1, total_epochs - warmup_epochs)
|
|
58
|
+
return max(0.0, 0.5 * (1.0 + math.cos(math.pi * progress)))
|
|
59
|
+
return LambdaLR(optimizer, lr_lambda, last_epoch)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
_MIXER_PARAM_RE = re.compile(r"\.mixer\.(ssm|attn|deltanet)\.")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def clip_grad_norm_per_group(model, max_norm: float) -> dict:
|
|
66
|
+
"""Clip the gradients of each backbone mixer kind (ssm / attn / deltanet, across all blocks)
|
|
67
|
+
and of everything else ("trunk") separately, so one diverging component cannot rescale the
|
|
68
|
+
others' updates. Returns {group: pre-clip norm}."""
|
|
69
|
+
groups = {"ssm": [], "attn": [], "deltanet": [], "trunk": []}
|
|
70
|
+
for name, p in model.named_parameters():
|
|
71
|
+
if p.grad is None:
|
|
72
|
+
continue
|
|
73
|
+
m = _MIXER_PARAM_RE.search(name)
|
|
74
|
+
groups[m.group(1) if m else "trunk"].append(p)
|
|
75
|
+
return {g: torch.nn.utils.clip_grad_norm_(ps, max_norm) for g, ps in groups.items() if ps}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class AdaptiveClipThreshold:
|
|
79
|
+
"""Clip threshold max(floor, mult * EMA of recent accepted pre-clip norms), capped at `cap`."""
|
|
80
|
+
|
|
81
|
+
def __init__(self, floor: float = 0.3, cap: float = 1.0, decay: float = 0.98, mult: float = 3.0):
|
|
82
|
+
self.floor, self.cap, self.decay, self.mult = floor, cap, decay, mult
|
|
83
|
+
self.ema = None
|
|
84
|
+
|
|
85
|
+
def value(self) -> float:
|
|
86
|
+
v = self.floor if self.ema is None else max(self.floor, self.ema * self.mult)
|
|
87
|
+
return min(v, self.cap) if self.cap is not None else v
|
|
88
|
+
|
|
89
|
+
def update(self, grad_norm: float):
|
|
90
|
+
self.ema = grad_norm if self.ema is None else self.decay * self.ema + (1 - self.decay) * grad_norm
|
|
91
|
+
|
|
92
|
+
def state_dict(self):
|
|
93
|
+
return {"ema": self.ema}
|
|
94
|
+
|
|
95
|
+
def load_state_dict(self, sd):
|
|
96
|
+
self.ema = sd.get("ema")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def s_norm_penalty(model, mult: float):
|
|
100
|
+
"""Penalty on the linear attention's context-matrix norms ||S|| of the last forward pass:
|
|
101
|
+
each layer's ||S|| is compared with mult * median over the layers (detached) and penalised by
|
|
102
|
+
relu(||S|| / threshold - 1)^2 -- catches one layer's S running away from the others. None if
|
|
103
|
+
fewer than two linear-attention layers ran."""
|
|
104
|
+
s = [m._last_s_norm for m in model.modules()
|
|
105
|
+
if isinstance(m, RowLinearAttentionBranch) and m._last_s_norm is not None]
|
|
106
|
+
if len(s) < 2:
|
|
107
|
+
return None
|
|
108
|
+
threshold = torch.stack([v.detach() for v in s]).median() * mult
|
|
109
|
+
return torch.stack([torch.relu(v / threshold - 1.0) ** 2 for v in s]).mean()
|
firepfn/train/prior.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Copyright (c) 2025-2026, the FirePFN authors.
|
|
3
|
+
"""Synthetic training data: the TabICLv2 graph_scm prior (``tabicl`` package) as a DataLoader."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import math
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
import torch.nn.functional as F
|
|
10
|
+
from torch.utils.data import DataLoader
|
|
11
|
+
|
|
12
|
+
from firepfn.train._tabicl_dataset import PriorDataset
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def build_prior_dataset(cfg: dict) -> PriorDataset:
|
|
16
|
+
"""TabICL PriorDataset for the training config (see firepfn/train/configs.py)."""
|
|
17
|
+
from tabicl.prior.graph_lib._config import PriorConfig
|
|
18
|
+
prior_config = PriorConfig(
|
|
19
|
+
add_gaussian_noise=cfg["tabicl_graph_noise"],
|
|
20
|
+
filter_unpredictable_graphs=cfg["tabicl_filter_unpredictable_graphs"],
|
|
21
|
+
filter_unpredictable_datasets=cfg["tabicl_filter_unpredictable_datasets"],
|
|
22
|
+
allow_act_warping=cfg["tabicl_allow_act_warping"],
|
|
23
|
+
min_n_nodes=cfg["tabicl_min_n_nodes"],
|
|
24
|
+
max_n_nodes=cfg["tabicl_max_n_nodes"],
|
|
25
|
+
cauchy_dag_offset=cfg["tabicl_cauchy_dag_offset"],
|
|
26
|
+
)
|
|
27
|
+
tables_per_micro_step = math.ceil(cfg["batch_size"] / cfg["aggregate_k_gradients"])
|
|
28
|
+
return PriorDataset(
|
|
29
|
+
batch_size=tables_per_micro_step,
|
|
30
|
+
batch_size_per_gp=cfg["tabicl_batch_size_per_gp"],
|
|
31
|
+
min_features=cfg["tabicl_min_features"],
|
|
32
|
+
max_features=cfg["tabicl_max_features"],
|
|
33
|
+
max_classes=cfg["max_num_classes"],
|
|
34
|
+
min_seq_len=None,
|
|
35
|
+
max_seq_len=cfg["bptt"],
|
|
36
|
+
log_seq_len=False,
|
|
37
|
+
log_n_features=False,
|
|
38
|
+
seq_len_per_gp=False,
|
|
39
|
+
min_train_size=cfg["tabicl_min_train_size"],
|
|
40
|
+
max_train_size=cfg["tabicl_max_train_size"],
|
|
41
|
+
replay_small=False,
|
|
42
|
+
prior_type=cfg["tabicl_prior_type"],
|
|
43
|
+
regression=False,
|
|
44
|
+
config=prior_config,
|
|
45
|
+
n_jobs=1, # parallelism comes from the DataLoader workers
|
|
46
|
+
device="cpu",
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build_prior_loader(cfg: dict) -> DataLoader:
|
|
51
|
+
"""Infinite DataLoader of TabICL batches, one micro-step of tables per item."""
|
|
52
|
+
workers = cfg["tabicl_n_jobs"]
|
|
53
|
+
return DataLoader(build_prior_dataset(cfg), batch_size=None, shuffle=False, num_workers=workers,
|
|
54
|
+
prefetch_factor=4 if workers > 0 else None, pin_memory=True)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def to_micro_batch(batch_item, num_features: int, normalize_by_used_features: bool = True):
|
|
58
|
+
"""One PriorDataset batch (X (B, T, F), y (B, T), d (B,), seq_lens, train_sizes) ->
|
|
59
|
+
x (T, B, num_features), y (T, B) float, train size.
|
|
60
|
+
|
|
61
|
+
TabICL standardizes every feature column, but inference (FeatureCountScaler) and the original
|
|
62
|
+
TabPFN prior divide by n_features / max_features; the same rescaling is applied here (d = real
|
|
63
|
+
width of each table). Padded columns are zero and stay zero.
|
|
64
|
+
"""
|
|
65
|
+
X, y, d, _, train_sizes = batch_item
|
|
66
|
+
if X.is_nested:
|
|
67
|
+
raise ValueError("expected dense batches (seq_len_per_gp=False)")
|
|
68
|
+
y = y.float()
|
|
69
|
+
if normalize_by_used_features:
|
|
70
|
+
X = X * (num_features / d.to(torch.float32).clamp(min=1)).to(X.device, X.dtype)[:, None, None]
|
|
71
|
+
x = X.transpose(0, 1)
|
|
72
|
+
if x.shape[-1] < num_features:
|
|
73
|
+
x = F.pad(x, (0, num_features - x.shape[-1]))
|
|
74
|
+
return x, y.transpose(0, 1), int(train_sizes[0])
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Copyright (c) 2025-2026, the FirePFN authors.
|
|
3
|
+
"""Context-size bucket schedule: every optimizer step covers the whole range of table sizes.
|
|
4
|
+
|
|
5
|
+
Each optimizer step consists of one micro-step per context-size bucket, in a shuffled order. A
|
|
6
|
+
bucket fixes the context (train) size around a doubling size c_k, the number of query rows (a
|
|
7
|
+
fraction of the context) and the number of tables. The default geometry keeps every micro-step
|
|
8
|
+
the same size in rows -- 128 tables x 256 context rows, 64 x 512, ..., 1 x 32768 -- and each
|
|
9
|
+
bucket carries equal weight in the step's loss.
|
|
10
|
+
|
|
11
|
+
``plan(step)`` depends only on (seed, step), so all ranks agree on the bucket order and shapes
|
|
12
|
+
without communicating; the data itself differs per rank. The TabICL micro-steps are generated by
|
|
13
|
+
DataLoader workers from the same plan (``BucketedTabICLStream``), so the stream's n-th item is the
|
|
14
|
+
n-th micro-step the training loop asks for.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import random
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import List, Optional
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
import torch
|
|
24
|
+
from torch.utils.data import IterableDataset, get_worker_info
|
|
25
|
+
|
|
26
|
+
DEFAULT_CONTEXTS = [256 * 2**k for k in range(8)] # 256 .. 32768
|
|
27
|
+
DEFAULT_TABLES = [128 >> k for k in range(8)] # 128 .. 1
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class MicroStep:
|
|
32
|
+
bucket: int
|
|
33
|
+
ctx: int # context (train) rows
|
|
34
|
+
n_query: int # query rows
|
|
35
|
+
n_tables: int
|
|
36
|
+
weight: float = 1.0 # share of its bucket's tables (< 1 when the bucket is split)
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def seq_len(self) -> int:
|
|
40
|
+
return self.ctx + self.n_query
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class CtxBucketSchedule:
|
|
44
|
+
def __init__(self, contexts: Optional[List[int]] = None, tables: Optional[List[int]] = None,
|
|
45
|
+
query_frac: float = 0.25, min_query: int = 32, jitter: bool = True, seed: int = 0,
|
|
46
|
+
round_to: int = 64, splits: Optional[List[int]] = None):
|
|
47
|
+
self.contexts = list(contexts or DEFAULT_CONTEXTS)
|
|
48
|
+
self.tables = list(tables or DEFAULT_TABLES)
|
|
49
|
+
if len(self.contexts) != len(self.tables):
|
|
50
|
+
raise ValueError("contexts and tables must have the same length")
|
|
51
|
+
self.query_frac = query_frac
|
|
52
|
+
self.min_query = min_query
|
|
53
|
+
self.jitter = jitter
|
|
54
|
+
self.seed = seed
|
|
55
|
+
self.round_to = round_to
|
|
56
|
+
self.lo, self.hi = min(self.contexts), max(self.contexts)
|
|
57
|
+
# splits[b] > 1 runs bucket b as that many micro-steps, each with a share of the tables.
|
|
58
|
+
self.splits = list(splits) if splits is not None else [1] * len(self.contexts)
|
|
59
|
+
if len(self.splits) != len(self.contexts) or any(s < 1 or s > t for s, t in zip(self.splits, self.tables)):
|
|
60
|
+
raise ValueError("splits must have one entry per bucket, 1 <= s <= tables")
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def k(self) -> int:
|
|
64
|
+
"""Micro-steps per optimizer step."""
|
|
65
|
+
return sum(self.splits)
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def n_buckets(self) -> int:
|
|
69
|
+
return len(self.contexts)
|
|
70
|
+
|
|
71
|
+
def plan(self, step: int) -> List[MicroStep]:
|
|
72
|
+
"""The micro-steps of optimizer step `step` (identical on every rank)."""
|
|
73
|
+
rng = random.Random((self.seed * 1_000_003 + step) & 0xFFFFFFFF)
|
|
74
|
+
order = list(range(self.n_buckets))
|
|
75
|
+
rng.shuffle(order)
|
|
76
|
+
out = []
|
|
77
|
+
for b in order:
|
|
78
|
+
c = self.contexts[b]
|
|
79
|
+
if self.jitter: # log-uniform within the bucket's doubling range around c
|
|
80
|
+
c = int(round(c * 2 ** rng.uniform(-0.5, 0.5)))
|
|
81
|
+
c = min(self.hi, max(self.lo, c))
|
|
82
|
+
if self.round_to: # fewer distinct shapes -> fewer Triton (re)compiles
|
|
83
|
+
c = max(self.round_to, int(round(c / self.round_to)) * self.round_to)
|
|
84
|
+
q = max(self.min_query, int(round(c * self.query_frac)))
|
|
85
|
+
rng.random() # (was: per-bucket prior choice; kept so plans match the original runs)
|
|
86
|
+
T = self.tables[b]
|
|
87
|
+
for chunk in np.array_split(np.arange(T), self.splits[b]):
|
|
88
|
+
out.append(MicroStep(b, c, q, len(chunk), weight=len(chunk) / T))
|
|
89
|
+
return out
|
|
90
|
+
|
|
91
|
+
def describe(self) -> str:
|
|
92
|
+
rows = " ".join(f"{c}x{n}" for c, n in zip(self.contexts, self.tables))
|
|
93
|
+
return (f"ctx bucket schedule: {self.k} micro-steps/step, ctx x tables = {rows}, "
|
|
94
|
+
f"queries = {self.query_frac:g} x ctx (>= {self.min_query}), jitter={self.jitter}")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class BucketedTabICLStream(IterableDataset):
|
|
98
|
+
"""The schedule's micro-steps in plan order, generated with a PriorDataset's prior, starting at
|
|
99
|
+
optimizer step `start_step`. Worker w of W produces items w, w+W, ...; the DataLoader yields them
|
|
100
|
+
round-robin by worker, i.e. back in item order."""
|
|
101
|
+
|
|
102
|
+
def __init__(self, prior_dataset, schedule: CtxBucketSchedule, start_step: int = 0):
|
|
103
|
+
self.ds = prior_dataset
|
|
104
|
+
self.schedule = schedule
|
|
105
|
+
self.start_step = start_step
|
|
106
|
+
|
|
107
|
+
def _items(self):
|
|
108
|
+
step = self.start_step
|
|
109
|
+
while True:
|
|
110
|
+
yield from self.schedule.plan(step)
|
|
111
|
+
step += 1
|
|
112
|
+
|
|
113
|
+
def __iter__(self):
|
|
114
|
+
info = get_worker_info()
|
|
115
|
+
wid, nw = (info.id, info.num_workers) if info is not None else (0, 1)
|
|
116
|
+
if info is not None: # numpy is not reseeded per worker by torch
|
|
117
|
+
np.random.seed(torch.initial_seed() % 2**32)
|
|
118
|
+
from firepfn.train._tabicl_dataset import sample_group_hp
|
|
119
|
+
prior = self.ds.prior
|
|
120
|
+
for i, ms in enumerate(self._items()):
|
|
121
|
+
if i % nw != wid:
|
|
122
|
+
continue
|
|
123
|
+
hp = sample_group_hp(prior) # num_features / num_classes / sampled_hp
|
|
124
|
+
hp["seq_len"], hp["train_size"] = ms.seq_len, ms.ctx
|
|
125
|
+
yield self.ds.get_batch(ms.n_tables, forced_group_hp=hp)
|