htmldaniel commited on
Commit
f74767f
·
verified ·
1 Parent(s): 547d2e0

index.json, model card with results, code snapshot

Browse files
README.md CHANGED
@@ -1,112 +1,112 @@
1
- ---
2
- library_name: pytorch
3
- license: mit
4
- tags:
5
- - tabular-classification
6
- - tabular-regression
7
- - text-tabular
8
- - multabench
9
- - lora
10
- base_model: intfloat/e5-small-v2
11
- ---
12
-
13
- # Reading Agent v2: table-conditioned text reading with TabLoRA (MulTaBench)
14
-
15
- Trained models for *Reading What Matters: Table-Conditioned Text Reading for Text-Tabular
16
- Prediction* (NLP 097215 final project, Track 1, Technion, 2026).
17
- Code: <https://github.com/htmldanielpoly/nlp_final_project> (folder `reading_agent_v2`);
18
- a source snapshot is in this repo under `code/`.
19
-
20
- For each row, a table encoder initialises a recurrent reader that consumes field-tagged
21
- sentence items of the row's text fields. Items are encoded by `intfloat/e5-small-v2`
22
- (revision `ffb93f3bd4047442299a41ebb6fa998a38507c52`) whose last three layers carry
23
- **TabLoRA** adapters: LoRA (r=16, alpha=32) on query, key, value, attention output and both
24
- feed-forward maps, with the rank space gated per row by the table encoding,
25
- `W x + (alpha/r) B diag(1 + tanh(G h_tab)) A x`. Three readers are cross-fitted per split.
26
- The prediction is the mean of two validation-tuned blends of the reader with Joint-Frozen
27
- **TabM** and **TabPFN-2.5** (structured columns + PCA-30 of each field's whole-text E5
28
- embedding); beyond 10 classes only the TabM blend is used.
29
-
30
- ## Contents
31
-
32
- One folder per run: 20 MulTaBench text datasets x 5 paper holdout folds (`<dataset>_f<fold>`).
33
-
34
- ```text
35
- index.json per run: task, blend weights, data revision, test-row hash, test score
36
- <run>/manifest.json task, classes, target scaling, blend weights, TabM input columns, metadata
37
- <run>/preprocessing.pkl fitted feature pipeline and the frozen frame's PCAs (pickle: load only trusted files)
38
- <run>/reader_{0,1,2}.pt cross-fitted readers: reader, LoRA and gate parameters (frozen E5 is rebuilt from the checkpoint)
39
- <run>/tabm.pt Joint-Frozen TabM (pytabkit)
40
- <run>/context.parquet TabPFN-2.5 context: the frozen-frame training rows and their (encoded) targets
41
- code/ source snapshot (package, tests, scripts, pyproject.toml, uv.lock)
42
- ```
43
-
44
- TabPFN-2.5 is a pretrained in-context learner, so its "fitted model" is its context; it is
45
- re-conditioned on `context.parquet` at inference. Its weights are downloaded from Prior Labs and
46
- need a licence token (`TABPFN_TOKEN`).
47
-
48
- ## Inference mode
49
-
50
- ```bash
51
- uv sync --locked # in code/ or in the GitHub folder reading_agent_v2
52
- PYTHONPATH=src python -m reading_agent2.estimator2 predict --repo htmldaniel/reading-agent-v2-multabench \
53
- --dataset REG_TEXT_BOOK_PRICE --fold 0 --input rows.csv --output preds.csv
54
- ```
55
-
56
- The input needs the dataset's feature columns in the MulTaBench representation.
57
- Classification output: predicted label and one probability per class; regression output: the
58
- target in its original units. GPU recommended (CPU works but is slow).
59
- `python -m reading_agent2.estimator2 check --dataset <D> --fold <k> --repo htmldaniel/reading-agent-v2-multabench`
60
- replays a run's stored test predictions from raw rows.
61
-
62
- ## End-to-end training mode
63
-
64
- ```bash
65
- bash scripts/train_all.sh # E5 cache, frozen frame, TabLoRA readers, heads, export (one CUDA GPU)
66
- ```
67
-
68
- Data: MulTaBench Hugging Face datasets at the revisions pinned in `reading_agent2/revisions.py`
69
- (recorded per run in `index.json`). GPU training is not bit-identical across runs; retrained
70
- weights reproduce the scores closely, not exactly.
71
-
72
- ## Evaluation
73
-
74
- MulTaBench paper protocol: 20 text datasets x 5 random holdout splits (seed 42+fold), dataset means
75
- over folds, then means over the 10 classification (AUROC) and 10 regression (R^2) datasets.
76
- Local rows are run on exactly the test rows of these artifacts; p: two-sided Wilcoxon signed-rank
77
- test of Ours against that row over datasets.
78
-
79
- | Method | AUROC | Ours wins (p) | R^2 | Ours wins (p) |
80
- |---|---|---|---|---|
81
- | **Ours** (mean of the two blends, this repo) | **0.913** | | **0.738** | |
82
- | TabM Frozen + TabLoRA reader | 0.910 | 8/10 (0.008) | 0.724 | 9/10 (0.004) |
83
- | TabPFN-2.5 Frozen + TabLoRA reader | 0.897 (8 datasets) | 4/8 | 0.734 | 4/10 |
84
- | TabLoRA reader alone | 0.903 | 10/10 (0.002) | 0.672 | 10/10 (0.002) |
85
- | v1 Blend (CatBoost Frozen + frozen-item reader) | 0.900 | 9/10 (0.004) | 0.702 | 10/10 (0.002) |
86
- | CatBoost, Joint Frozen (local) | 0.887 | 10/10 (0.002) | 0.684 | 10/10 (0.002) |
87
- | TabM, Joint Frozen (local) | 0.895 | 10/10 (0.002) | 0.716 | 10/10 (0.002) |
88
- | TabPFN-2.5, Joint Frozen (local) | 0.884 (8 datasets) | 6/8 (0.148) | 0.729 | 5/10 (0.375) |
89
- | CatBoost, Joint TAR (leaderboard) | 0.907 | 9/10 | 0.716 | 9/10 |
90
- | TabM, Joint TAR (leaderboard) | 0.911 | 5/10 | 0.728 | 9/10 |
91
- | TabPFN-2.5, Joint TAR (leaderboard) | 0.900 (8 datasets) | 3/8 | 0.732 | 4/10 |
92
-
93
- TabPFN-2.5 is not used beyond 10 classes (Spotify, Wine). Per-dataset and per-fold scores:
94
- `code/evaluation/scores_per_dataset.csv`, `code/evaluation/scores_per_fold.csv`; the per-run test
95
- score is also in `index.json`.
96
-
97
- External leaderboard values use the same split seeds, but row identity with the original data
98
- is not verified, so no significance test is claimed against them.
99
-
100
- ## Limitations
101
-
102
- - Per-dataset models: each artifact is trained for one dataset and split; for new data use
103
- `TabLoRAStack.fit` (see the GitHub README).
104
- - TabPFN-2.5 needs its training rows (stored here as the frozen-frame context) at inference.
105
- - No test leakage: every reader, adapter, preprocessing step, head and blend weight is fit per
106
- dataset and split on that split's training rows only. Pretrained parts: E5-small-v2 (generic
107
- web text) and TabPFN-2.5, whose default *classifier* checkpoint is additionally fine-tuned on 43
108
- real datasets (TabPFN-2.5 report, App. C.1), none of them a MulTaBench dataset by name.
109
- - The per-row table gate of TabLoRA was level with plain LoRA in our fold-0 ablation; the gain
110
- over frozen items comes from the adapters.
111
- - Items are truncated at 128 tokens for TabLoRA, and at most `K = max(8, #fields)` items per row
112
- are kept, so very long texts are only partly read.
 
1
+ ---
2
+ library_name: pytorch
3
+ license: mit
4
+ tags:
5
+ - tabular-classification
6
+ - tabular-regression
7
+ - text-tabular
8
+ - multabench
9
+ - lora
10
+ base_model: intfloat/e5-small-v2
11
+ ---
12
+
13
+ # Reading Agent v2: table-conditioned text reading with TabLoRA (MulTaBench)
14
+
15
+ Trained models for *Reading What Matters: Table-Conditioned Text Reading for Text-Tabular
16
+ Prediction* (NLP 097215 final project, Track 1, Technion, 2026).
17
+ Code: <https://github.com/htmldanielpoly/nlp_final_project> (folder `reading_agent_v2`);
18
+ a source snapshot is in this repo under `code/`.
19
+
20
+ For each row, a table encoder initialises a recurrent reader that consumes field-tagged
21
+ sentence items of the row's text fields. Items are encoded by `intfloat/e5-small-v2`
22
+ (revision `ffb93f3bd4047442299a41ebb6fa998a38507c52`) whose last three layers carry
23
+ **TabLoRA** adapters: LoRA (r=16, alpha=32) on query, key, value, attention output and both
24
+ feed-forward maps, with the rank space gated per row by the table encoding,
25
+ `W x + (alpha/r) B diag(1 + tanh(G h_tab)) A x`. Three readers are cross-fitted per split.
26
+ The prediction is the mean of two validation-tuned blends of the reader with Joint-Frozen
27
+ **TabM** and **TabPFN-2.5** (structured columns + PCA-30 of each field's whole-text E5
28
+ embedding); beyond 10 classes only the TabM blend is used.
29
+
30
+ ## Contents
31
+
32
+ One folder per run: 20 MulTaBench text datasets x 5 paper holdout folds (`<dataset>_f<fold>`).
33
+
34
+ ```text
35
+ index.json per run: task, blend weights, data revision, test-row hash, test score
36
+ <run>/manifest.json task, classes, target scaling, blend weights, TabM input columns, metadata
37
+ <run>/preprocessing.pkl fitted feature pipeline and the frozen frame's PCAs (pickle: load only trusted files)
38
+ <run>/reader_{0,1,2}.pt cross-fitted readers: reader, LoRA and gate parameters (frozen E5 is rebuilt from the checkpoint)
39
+ <run>/tabm.pt Joint-Frozen TabM (pytabkit)
40
+ <run>/context.parquet TabPFN-2.5 context: the frozen-frame training rows and their (encoded) targets
41
+ code/ source snapshot (package, tests, scripts, pyproject.toml, uv.lock)
42
+ ```
43
+
44
+ TabPFN-2.5 is a pretrained in-context learner, so its "fitted model" is its context; it is
45
+ re-conditioned on `context.parquet` at inference. Its weights are downloaded from Prior Labs and
46
+ need a licence token (`TABPFN_TOKEN`).
47
+
48
+ ## Inference mode
49
+
50
+ ```bash
51
+ uv sync --locked # in code/ or in the GitHub folder reading_agent_v2
52
+ PYTHONPATH=src python -m reading_agent2.estimator2 predict --repo htmldaniel/reading-agent-v2-multabench \
53
+ --dataset REG_TEXT_BOOK_PRICE --fold 0 --input rows.csv --output preds.csv
54
+ ```
55
+
56
+ The input needs the dataset's feature columns in the MulTaBench representation.
57
+ Classification output: predicted label and one probability per class; regression output: the
58
+ target in its original units. GPU recommended (CPU works but is slow).
59
+ `python -m reading_agent2.estimator2 check --dataset <D> --fold <k> --repo htmldaniel/reading-agent-v2-multabench`
60
+ replays a run's stored test predictions from raw rows.
61
+
62
+ ## End-to-end training mode
63
+
64
+ ```bash
65
+ bash scripts/train_all.sh # E5 cache, frozen frame, TabLoRA readers, heads, export (one CUDA GPU)
66
+ ```
67
+
68
+ Data: MulTaBench Hugging Face datasets at the revisions pinned in `reading_agent2/revisions.py`
69
+ (recorded per run in `index.json`). GPU training is not bit-identical across runs; retrained
70
+ weights reproduce the scores closely, not exactly.
71
+
72
+ ## Evaluation
73
+
74
+ MulTaBench paper protocol: 20 text datasets x 5 random holdout splits (seed 42+fold), dataset means
75
+ over folds, then means over the 10 classification (AUROC) and 10 regression (R^2) datasets.
76
+ Local rows are run on exactly the test rows of these artifacts; p: two-sided Wilcoxon signed-rank
77
+ test of Ours against that row over datasets.
78
+
79
+ | Method | AUROC | Ours wins (p) | R^2 | Ours wins (p) |
80
+ |---|---|---|---|---|
81
+ | **Ours** (mean of the two blends, this repo) | **0.913** | | **0.738** | |
82
+ | TabM Frozen + TabLoRA reader | 0.910 | 8/10 (0.008) | 0.724 | 9/10 (0.004) |
83
+ | TabPFN-2.5 Frozen + TabLoRA reader | 0.897 (8 datasets) | 4/8 | 0.734 | 4/10 |
84
+ | TabLoRA reader alone | 0.903 | 10/10 (0.002) | 0.672 | 10/10 (0.002) |
85
+ | v1 Blend (CatBoost Frozen + frozen-item reader) | 0.900 | 9/10 (0.004) | 0.702 | 10/10 (0.002) |
86
+ | CatBoost, Joint Frozen (local) | 0.887 | 10/10 (0.002) | 0.684 | 10/10 (0.002) |
87
+ | TabM, Joint Frozen (local) | 0.895 | 10/10 (0.002) | 0.716 | 10/10 (0.002) |
88
+ | TabPFN-2.5, Joint Frozen (local) | 0.884 (8 datasets) | 6/8 (0.148) | 0.729 | 5/10 (0.375) |
89
+ | CatBoost, Joint TAR (leaderboard) | 0.907 | 9/10 | 0.716 | 9/10 |
90
+ | TabM, Joint TAR (leaderboard) | 0.911 | 5/10 | 0.728 | 9/10 |
91
+ | TabPFN-2.5, Joint TAR (leaderboard) | 0.900 (8 datasets) | 3/8 | 0.732 | 4/10 |
92
+
93
+ TabPFN-2.5 is not used beyond 10 classes (Spotify, Wine). Per-dataset and per-fold scores:
94
+ `code/evaluation/scores_per_dataset.csv`, `code/evaluation/scores_per_fold.csv`; the per-run test
95
+ score is also in `index.json`.
96
+
97
+ External leaderboard values use the same split seeds, but row identity with the original data
98
+ is not verified, so no significance test is claimed against them.
99
+
100
+ ## Limitations
101
+
102
+ - Per-dataset models: each artifact is trained for one dataset and split; for new data use
103
+ `TabLoRAStack.fit` (see the GitHub README).
104
+ - TabPFN-2.5 needs its training rows (stored here as the frozen-frame context) at inference.
105
+ - No test leakage: every reader, adapter, preprocessing step, head and blend weight is fit per
106
+ dataset and split on that split's training rows only. Pretrained parts: E5-small-v2 (generic
107
+ web text) and TabPFN-2.5, whose default *classifier* checkpoint is additionally fine-tuned on 43
108
+ real datasets (TabPFN-2.5 report, App. C.1), none of them a MulTaBench dataset by name.
109
+ - The per-row table gate of TabLoRA was level with plain LoRA in our fold-0 ablation; the gain
110
+ over frozen items comes from the adapters.
111
+ - Items are truncated at 128 tokens for TabLoRA, and at most `K = max(8, #fields)` items per row
112
+ are kept, so very long texts are only partly read.
code/README.md CHANGED
@@ -83,4 +83,19 @@ python -m unittest discover -s tests -v
83
 
84
  ## Results
85
 
86
- See `paper/main.pdf` (Tables 1-2, Appendix A) and `MODEL_CARD.md`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  ## Results
85
 
86
+ Dataset means over 5 folds, 10 classification (AUROC) and 10 regression (R²) datasets:
87
+
88
+ | | AUROC | R² |
89
+ |---|---|---|
90
+ | **v2** (`blend_mean@stackB`) | **0.913** | **0.738** |
91
+ | v1 Blend (CatBoost Frozen + reader) | 0.900 | 0.702 |
92
+ | TabM, Joint Frozen (local, same rows) | 0.895 | 0.716 |
93
+ | TabM, Joint TAR (MulTaBench leaderboard) | 0.911 | 0.728 |
94
+
95
+ v2 beats v1 on 9/10 classification and 10/10 regression datasets (Wilcoxon p = 0.004 / 0.002).
96
+ Per-dataset and per-fold scores: `evaluation/`. Full tables: `paper/main.pdf` (Tables 1-2,
97
+ Appendix A) and `MODEL_CARD.md`.
98
+
99
+ No test leakage: every reader, adapter, preprocessing step, head and blend weight is fit per
100
+ dataset and split on that split's training rows only (cross-fitting keeps the reader's
101
+ training-row predictions out-of-fold).
code/src/reading_agent2/estimator2.py CHANGED
@@ -1,486 +1,486 @@
1
- """The v2 model as one estimator: TabLoRA readers + Joint-Frozen TabM / TabPFN-2.5 heads, blended.
2
-
3
- model = TabLoRAStack(num_cols, cat_cols, text_cols, task="binary").fit(train_df, y) # any text-tabular data (GPU)
4
- model.save("artifact/"); TabLoRAStack.load("artifact/").predict_proba(test_df)
5
-
6
- An artifact holds the fitted preprocessing (`preprocessing.pkl`: feature pipeline and the PCAs of
7
- the frozen frame), the K cross-fitted TabLoRA readers (`reader_k.pt`: reader, LoRA and gate
8
- parameters only; the frozen E5 layers are rebuilt from the pinned checkpoint), the Joint-Frozen
9
- TabM (`tabm.pt`), the TabPFN-2.5 context (`context.parquet`: the frozen-frame training rows and
10
- their targets, which is what a fitted TabPFN consists of) and the blend weights (`manifest.json`).
11
-
12
- Inference from the published benchmark runs (downloads one run from the Hub):
13
-
14
- python -m reading_agent2.estimator2 --repo htmldaniel/reading-agent-v2-multabench \
15
- --dataset REG_TEXT_BOOK_PRICE --fold 0 --input rows.csv --output preds.csv
16
-
17
- `export` assembles artifacts from the training runs (stack features, tabcond, heads) and
18
- `check` replays a run's stored test predictions from raw rows.
19
- """
20
- import argparse
21
- import copy
22
- import hashlib
23
- import json
24
- import pickle
25
- from pathlib import Path
26
-
27
- import numpy as np
28
- import pandas as pd
29
- import torch
30
- from sklearn.model_selection import KFold, StratifiedKFold, train_test_split
31
-
32
- from reading_agent.baselines import frozen_frame
33
- from reading_agent.embed import MODEL_NAME, MODEL_REVISION, release_model
34
- from reading_agent.features import FeaturePipeline, whole_text_embeddings
35
- from reading_agent.run import score
36
- from reading_agent.train import Config
37
-
38
- from .stack import PRIMARY, ROOT, _full_probs, _ordinal, design, fit_tabm, fit_tabpfn, prepare, reader_feats, tabm_predict, tabpfn_predict
39
- from . import tabcond as tc
40
-
41
- FORMAT = 2
42
- HEADS = ("tabm", "tabpfn")
43
-
44
-
45
- def _device(device=None):
46
- return device or ("cuda" if torch.cuda.is_available() else "cpu")
47
-
48
-
49
- class ItemStatesAny(tc.ItemStates):
50
- """tc.ItemStates (fp16 on CUDA, as in training) that also runs on CPU in fp32."""
51
-
52
- def __init__(self, texts, device, batch_size=256):
53
- if str(device).startswith("cuda"):
54
- return super().__init__(texts, device, batch_size)
55
- from transformers import AutoModel, AutoTokenizer
56
- tok = AutoTokenizer.from_pretrained(MODEL_NAME, revision=MODEL_REVISION)
57
- self.e5 = AutoModel.from_pretrained(MODEL_NAME, revision=MODEL_REVISION).eval()
58
- lengths, chunks = np.zeros(len(texts), np.int64), [None] * len(texts)
59
- with torch.no_grad():
60
- for s in range(0, len(texts), batch_size):
61
- enc = tok(texts[s:s + batch_size], max_length=tc.MAX_TOKENS, truncation=True, padding=True, return_tensors="pt")
62
- hs = self.e5(**enc, output_hidden_states=True).hidden_states[-tc.N_TOP - 1]
63
- for j, n in enumerate(enc["attention_mask"].sum(1).tolist()):
64
- chunks[s + j], lengths[s + j] = hs[j, :n], n
65
- self.lengths = torch.as_tensor(lengths)
66
- self.offsets = torch.as_tensor(np.r_[0, np.cumsum(lengths)[:-1]])
67
- self.flat, self.device = torch.cat(chunks), device
68
-
69
-
70
- def _devices_to_cpu(obj, seen=None):
71
- """pytabkit keeps the training device in nested interfaces (`device`, `device_`); point them at the CPU."""
72
- seen = set() if seen is None else seen
73
- if id(obj) in seen or not hasattr(obj, "__dict__") or isinstance(obj, (torch.Tensor, torch.nn.Module)):
74
- return
75
- seen.add(id(obj))
76
- for k, v in vars(obj).items():
77
- if k in ("device", "device_") and str(v).startswith("cuda"):
78
- setattr(obj, k, torch.device("cpu") if isinstance(v, torch.device) else "cpu")
79
- elif isinstance(v, (list, tuple)):
80
- for x in v:
81
- _devices_to_cpu(x, seen)
82
- elif isinstance(v, dict):
83
- for x in v.values():
84
- _devices_to_cpu(x, seen)
85
- else:
86
- _devices_to_cpu(v, seen)
87
-
88
-
89
- def _id_matrix(layout, tid, K):
90
- m = np.zeros((len(layout), K), np.int64)
91
- for i, r in enumerate(layout):
92
- m[i, : len(r)] = [tid[t] for t in r]
93
- return m
94
-
95
-
96
- def _tabm_frame(F, flags, medians):
97
- """TabM input: frozen frame, missing flags for the training-time flagged columns, training medians
98
- (every numeric column, so rows with gaps unseen in training still get complete inputs)."""
99
- X, cats = design(F, None)
100
- for c in flags:
101
- X[f"{c}_missing"] = X[c].isna().astype(float)
102
- for c, med in medians.items():
103
- X[c] = X[c].fillna(med)
104
- return X, cats
105
-
106
-
107
- class TabLoRAStack:
108
- def __init__(self, num_cols, cat_cols, text_cols, *, task="binary", namespace="generic", max_items=8,
109
- n_splits=3, gate=True, heads=HEADS, seed=0, adapt_epochs=10, lora_lr=1e-3):
110
- if task not in {"binary", "multiclass", "regression"}:
111
- raise ValueError("task must be binary, multiclass or regression")
112
- self.task, self.n_splits, self.gate, self.heads, self.seed = task, n_splits, gate, tuple(heads), seed
113
- self.adapt_epochs, self.lora_lr = adapt_epochs, lora_lr
114
- self.pipe = FeaturePipeline(list(num_cols), list(cat_cols), list(text_cols), namespace,
115
- max_items=max(max_items, len(text_cols)))
116
- self.pcas, self.states_dicts, self.tabm, self.context = None, [], None, None
117
- self.weights, self.flags, self.medians = {}, [], {}
118
- self.classes_, self.target_mean, self.target_scale, self.n_out = None, 0.0, 1.0, None
119
- self.config, self.metadata = Config(epochs=100, patience=15), {}
120
-
121
- # ------------------------------------------------------------ readers
122
- def _reader(self, e5, device):
123
- cfg = self.config
124
- model = tc.TabCondReader(n_num=self.pipe.n_num_in, cat_cards=self.pipe.cat_cardinalities,
125
- col_name_emb=self.pipe.col_name_emb, field_name_emb=self.pipe.field_name_emb,
126
- n_out=self.n_out, d=cfg.d, layers=cfg.layers, cell=cfg.cell, dropout=cfg.dropout,
127
- max_items=self.pipe.max_items)
128
- return model, tc.TopE5(copy.deepcopy(e5), d_tab=cfg.d, gate=self.gate)
129
-
130
- def _reader_outputs(self, frame, P, device):
131
- """Mean over the K readers of the read-all reader features (probabilities / regression value)."""
132
- layout = tc.item_layout(self.pipe, frame)
133
- texts = sorted({t for r in layout for t in r}) or [""]
134
- tid = {t: i for i, t in enumerate(texts)}
135
- ids = _id_matrix(layout, tid, self.pipe.max_items)
136
- states = ItemStatesAny(texts, device)
137
- feats = 0.0
138
- for sd in self.states_dicts:
139
- model, top = self._reader(states.e5, device)
140
- model.attach(top, states)
141
- missing, unexpected = model.load_state_dict(sd, strict=False)
142
- bad = [k for k in missing if not (k.startswith("top.layers.") or ".base." in k)]
143
- if bad or unexpected:
144
- raise ValueError(f"reader weights do not match the model: missing {bad[:3]}, unexpected {unexpected[:3]}")
145
- top.adapt = True
146
- model.to(device)
147
- out, _ = tc.outputs(model, P, ids, np.arange(len(frame)), self.task, device)
148
- feats = feats + reader_feats(out, self.task) / len(self.states_dicts)
149
- del model, top
150
- return feats
151
-
152
- # ------------------------------------------------------------ fit (any dataset)
153
- def fit(self, frame, y, device=None):
154
- """End-to-end training on a DataFrame: cross-fitted TabLoRA readers, heads, blend weights."""
155
- device = _device(device)
156
- if device == "cpu":
157
- raise RuntimeError("TabLoRA training needs a CUDA GPU (inference also runs on CPU)")
158
- frame = frame.reset_index(drop=True)
159
- y = np.asarray(y)
160
- if self.task == "regression":
161
- self.target_mean, self.target_scale = float(y.astype(float).mean()), float(y.astype(float).std() + 1e-9)
162
- y_tr = (y.astype(float) - self.target_mean) / self.target_scale
163
- self.n_out = 1
164
- else:
165
- self.classes_ = np.unique(y)
166
- y_tr = np.searchsorted(self.classes_, y)
167
- self.n_out = len(self.classes_)
168
- strat = y_tr if self.task != "regression" and np.bincount(y_tr).min() >= 2 else None
169
- i_in, i_va = train_test_split(np.arange(len(y_tr)), test_size=0.2, random_state=self.seed, stratify=strat)
170
- # frozen frame (structured columns + PCA of each field's whole-text E5 embedding)
171
- self.pipe.fit(frame)
172
- E = whole_text_embeddings(frame, self.pipe.text_cols, self.pipe.namespace)
173
- F, self.pcas = frozen_frame(frame, self.pipe.num_cols, self.pipe.cat_cols, E)
174
- P = self.pipe.transform(frame, y_tr)
175
- release_model()
176
- # cross-fitted TabLoRA readers (as tabcond.run)
177
- layout = tc.item_layout(self.pipe, frame)
178
- texts = sorted({t for r in layout for t in r})
179
- tid = {t: i for i, t in enumerate(texts)}
180
- ids = _id_matrix(layout, tid, self.pipe.max_items)
181
- states = tc.ItemStates(texts, device)
182
- static = np.zeros((len(texts), 384), np.float32)
183
- probe = tc.TopE5(copy.deepcopy(states.e5), d_tab=self.config.d, gate=self.gate).to(device)
184
- with torch.no_grad():
185
- for s in range(0, len(texts), 512):
186
- st, mk = states.batch(torch.arange(s, min(s + 512, len(texts))))
187
- static[s:s + len(st)] = probe(st, mk).cpu().numpy()
188
- del probe
189
- P.items = static[ids].astype(np.float16) * P.item_mask[..., None]
190
- use_strat = self.task != "regression" and np.bincount(y_tr).min() >= self.n_splits
191
- kf = (StratifiedKFold if use_strat else KFold)(n_splits=self.n_splits, shuffle=True, random_state=self.seed)
192
- oof, self.states_dicts = None, []
193
- log = lambda s: print(s, flush=True)
194
- for k, (a, b_idx) in enumerate(kf.split(np.zeros(len(y_tr)), y_tr if use_strat else None)):
195
- a_in, a_va = train_test_split(a, test_size=0.15, random_state=self.seed + k)
196
- torch.manual_seed(self.seed + k)
197
- model, top = self._reader(states.e5, device)
198
- model.attach(top, states)
199
- model.to(device)
200
- reader_params = [p for n, p in model.named_parameters() if not n.startswith("top.")]
201
- tc.fit(model, P, ids, a_in, a_va, self.task, device, self.config.epochs, self.config.patience,
202
- [{"params": reader_params, "lr": self.config.lr}], log, seed=self.seed + k, amp=False)
203
- top.adapt = True
204
- adapt = [p for l in top.loras for p in (l.A, l.B)] + (list(top.gate_proj.parameters()) if self.gate else [])
205
- for p in reader_params:
206
- p.requires_grad_(False)
207
- tc.fit(model, P, ids, a_in, a_va, self.task, device, self.adapt_epochs, 3, [{"params": adapt, "lr": self.lora_lr}],
208
- log, seed=100 + self.seed + k, amp=True, batch_rows=64)
209
- out, _ = tc.outputs(model, P, ids, b_idx, self.task, device)
210
- f = reader_feats(out, self.task)
211
- oof = np.zeros((len(y_tr), f.shape[1]), np.float32) if oof is None else oof
212
- oof[b_idx] = f
213
- self.states_dicts.append(tc.adapted_state(model))
214
- del model, top
215
- torch.cuda.empty_cache()
216
- # heads on the frozen frame and validation-tuned blend weights (as stack.heads)
217
- full = lambda f: f if self.task == "regression" else _full_probs(f, self.task)
218
- r_val = full(oof[i_va])
219
- self.context = F.assign(__y__=y_tr)
220
- X, cats = design(F, None)
221
- self.flags = [c for c in X.columns if c not in cats and X[c].isna().any()]
222
- self.medians = {c: float(0.0 if pd.isna(X[c].median()) else X[c].median()) for c in X.columns if c not in cats}
223
- self.weights = {}
224
- for head in self.heads:
225
- if head == "tabpfn" and self.task != "regression" and self.n_out > 10:
226
- continue
227
- if head == "tabm":
228
- Xi, _ = _tabm_frame(F, self.flags, self.medians)
229
- self.tabm = fit_tabm(Xi.iloc[i_in], y_tr[i_in], Xi.iloc[i_va], y_tr[i_va], cats, self.task, seed=self.seed)
230
- val = tabm_predict(self.tabm, Xi.iloc[i_va], self.task)
231
- else:
232
- Xo, _ = _ordinal(X, X, cats)
233
- m = fit_tabpfn(Xo.iloc[i_in], y_tr[i_in], cats, self.task, seed=self.seed)
234
- val = tabpfn_predict(m, Xo.iloc[i_va], self.task)
235
- if np.asarray(val).size != r_val.size:
236
- continue
237
- ws = np.linspace(0, 1, 21)
238
- vs = [score(self.task, y_tr[i_va], w * np.asarray(val).reshape(r_val.shape) + (1 - w) * r_val) for w in ws]
239
- self.weights[head] = float(ws[int(np.argmax(vs))])
240
- return self
241
-
242
- # ------------------------------------------------------------ predict
243
- def predict_outputs(self, frame, device=None):
244
- """Probabilities (classes_ order) or raw-scale regression values, plus the parts that were blended."""
245
- device = _device(device)
246
- frame = frame.reset_index(drop=True)
247
- missing = [c for c in self.pipe.num_cols + self.pipe.cat_cols + self.pipe.text_cols if c not in frame]
248
- if missing:
249
- raise ValueError(f"input lacks columns {missing}")
250
- full = lambda f: np.asarray(f) if self.task == "regression" else _full_probs(np.asarray(f), self.task)
251
- P = self.pipe.transform(frame, np.zeros(len(frame), np.int64)) # placeholder targets (unused)
252
- reader = full(self._reader_outputs(frame, P, device))
253
- E = whole_text_embeddings(frame, self.pipe.text_cols, self.pipe.namespace)
254
- F, _ = frozen_frame(frame, self.pipe.num_cols, self.pipe.cat_cols, E, self.pcas)
255
- parts = {"reader": reader}
256
- for head, w in self.weights.items():
257
- if head == "tabm":
258
- X, _ = _tabm_frame(F, self.flags, self.medians)
259
- out = tabm_predict(self.tabm, X, self.task)
260
- else:
261
- ctx = self.context.drop(columns="__y__")
262
- Xc, cats = design(ctx, None)
263
- Xn, _ = design(F[ctx.columns], None)
264
- Xo_tr, Xo = _ordinal(Xc, Xn, cats)
265
- m = fit_tabpfn(Xo_tr, self.context["__y__"].to_numpy(), cats, self.task, seed=self.seed)
266
- out = tabpfn_predict(m, Xo, self.task)
267
- parts[head] = w * np.asarray(out).reshape(reader.shape) + (1 - w) * reader
268
- blends = [parts[h] for h in self.weights] or [reader]
269
- out = np.mean(blends, axis=0)
270
- if self.task == "regression":
271
- out = out.reshape(-1) * self.target_scale + self.target_mean
272
- return out, parts
273
-
274
- def predict_proba(self, frame, device=None):
275
- if self.task == "regression":
276
- raise ValueError("predict_proba is for classification")
277
- return self.predict_outputs(frame, device)[0]
278
-
279
- def predict(self, frame, device=None):
280
- out = self.predict_outputs(frame, device)[0]
281
- return out if self.task == "regression" else self.classes_[out.argmax(1)]
282
-
283
- # ------------------------------------------------------------ persistence
284
- def save(self, directory):
285
- path = Path(directory)
286
- path.mkdir(parents=True, exist_ok=True)
287
- with (path / "preprocessing.pkl").open("wb") as f:
288
- pickle.dump({"pipe": self.pipe, "pcas": self.pcas}, f, protocol=4)
289
- for k, sd in enumerate(self.states_dicts):
290
- torch.save(sd, path / f"reader_{k}.pt")
291
- if self.tabm is not None:
292
- torch.save(self.tabm, path / "tabm.pt", pickle_protocol=4)
293
- self.context.to_parquet(path / "context.parquet")
294
- manifest = {"format_version": FORMAT, "task": self.task, "n_out": self.n_out, "seed": self.seed,
295
- "classes": None if self.classes_ is None else [str(c) for c in self.classes_],
296
- "target_mean": self.target_mean, "target_scale": self.target_scale,
297
- "n_readers": len(self.states_dicts), "gate": self.gate, "config": {k: getattr(self.config, k) for k in ("d", "layers", "cell", "dropout")},
298
- "encoder": MODEL_NAME, "encoder_revision": MODEL_REVISION, "max_tokens": tc.MAX_TOKENS,
299
- "blend_weights": self.weights, "tabm_flags": self.flags, "tabm_medians": self.medians,
300
- "metadata": self.metadata}
301
- # manifest last: a directory without it is not a complete artifact
302
- (path / "manifest.json").write_text(json.dumps(manifest, indent=1), encoding="utf-8")
303
- return path
304
-
305
- @classmethod
306
- def load(cls, directory, device=None):
307
- path = Path(directory)
308
- man = json.loads((path / "manifest.json").read_text(encoding="utf-8"))
309
- if man["format_version"] != FORMAT:
310
- raise ValueError("unsupported artifact format")
311
- with (path / "preprocessing.pkl").open("rb") as f:
312
- prep = pickle.load(f)
313
- pipe = prep["pipe"]
314
- obj = cls(pipe.num_cols, pipe.cat_cols, pipe.text_cols, task=man["task"], namespace=pipe.namespace,
315
- max_items=pipe.max_items, n_splits=man["n_readers"], gate=man["gate"], seed=man["seed"])
316
- obj.pipe, obj.pcas, obj.n_out = pipe, prep["pcas"], man["n_out"]
317
- for k, v in man["config"].items():
318
- setattr(obj.config, k, v)
319
- obj.classes_ = None if man["classes"] is None else np.asarray(man["classes"])
320
- obj.target_mean, obj.target_scale = man["target_mean"], man["target_scale"]
321
- obj.weights, obj.flags, obj.medians, obj.metadata = man["blend_weights"], man["tabm_flags"], man["tabm_medians"], man["metadata"]
322
- loc = "cuda" if _device(device).startswith("cuda") else "cpu"
323
- obj.states_dicts = [torch.load(path / f"reader_{k}.pt", map_location="cpu", weights_only=True) for k in range(man["n_readers"])]
324
- if (path / "tabm.pt").exists():
325
- obj.tabm = torch.load(path / "tabm.pt", map_location=loc, weights_only=False)
326
- if loc == "cpu":
327
- _devices_to_cpu(obj.tabm)
328
- obj.context = pd.read_parquet(path / "context.parquet")
329
- return obj
330
-
331
-
332
- # ---------------------------------------------------------------- benchmark runs -> artifacts
333
- def run_id(dataset, fold):
334
- return f"{dataset}_f{fold}"
335
-
336
-
337
- def export(dataset, fold, tag="v2", out_root=None):
338
- """Assemble the artifact of one benchmark run from the stage A/B outputs and the heads (run on the VM)."""
339
- out_root = Path(out_root or ROOT / "results" / "models" / tag)
340
- a_dir, b_dir = ROOT / "results" / "stack" / run_id(dataset, fold), ROOT / "results" / "stackB" / run_id(dataset, fold)
341
- h_dir = ROOT / "results" / "heads" / tag / run_id(dataset, fold)
342
- info_a = json.loads((a_dir / "info.json").read_text(encoding="utf-8"))
343
- info_b = json.loads((b_dir / "info.json").read_text(encoding="utf-8"))
344
- blend = json.loads((h_dir / "blend.json").read_text(encoding="utf-8"))
345
- ds, x_tr, x_te, y_tr, y_te, te_idx, i_in, i_va, n_out, info = prepare(dataset, fold)
346
- F_tr = pd.read_parquet(a_dir / "F_tr.parquet")
347
- with (b_dir / "weights" / "pipe.pkl").open("rb") as f:
348
- pipe = pickle.load(f)
349
- E_tr = whole_text_embeddings(x_tr, ds.text_cols, f"e5_{dataset}")
350
- F_chk, pcas = frozen_frame(x_tr, ds.num_cols, ds.cat_cols, E_tr)
351
- pd.testing.assert_frame_equal(F_chk, F_tr, check_exact=False, atol=1e-5) # refit PCAs reproduce stage A
352
- F_te = pd.read_parquet(a_dir / "F_te.parquet")
353
- X_tr, cats = design(F_tr, None)
354
- X_te, _ = design(F_te, None)
355
- flags = [c for c in X_tr.columns if c not in cats and (X_tr[c].isna().any() or X_te[c].isna().any())]
356
- obj = TabLoRAStack(ds.num_cols, ds.cat_cols, ds.text_cols, task=ds.task, namespace=f"e5_{dataset}",
357
- max_items=pipe.max_items, n_splits=info_b["n_splits"], gate=info_b["gate"], seed=fold)
358
- obj.pipe, obj.pcas, obj.n_out = pipe, pcas, n_out
359
- obj.classes_ = None if info["classes"] is None else np.asarray(info["classes"])
360
- obj.target_mean, obj.target_scale = info["target_mean"], info["target_scale"]
361
- obj.states_dicts = [torch.load(b_dir / "weights" / f"reader_{k}.pt", map_location="cpu", weights_only=True)
362
- for k in range(info_b["n_splits"])]
363
- tabm_path = h_dir / "tabm.pt"
364
- obj.tabm = torch.load(tabm_path, map_location="cpu" if not torch.cuda.is_available() else None, weights_only=False) if tabm_path.exists() else None
365
- obj.weights = blend["weights"].get("stackB", {})
366
- obj.flags = flags
367
- obj.medians = {c: float(0.0 if pd.isna(X_tr[c].median()) else X_tr[c].median()) for c in X_tr.columns if c not in cats}
368
- obj.context = F_tr.assign(__y__=y_tr)
369
- preds = np.load(ROOT / "results" / "preds" / tag / f"{run_id(dataset, fold)}.npz")
370
- sha = lambda a: hashlib.sha256(np.ascontiguousarray(a).tobytes()).hexdigest()[:16]
371
- obj.metadata = dict(dataset=dataset, fold=fold, protocol="paper", data_revision=info["revision"],
372
- train_rows=len(y_tr), test_rows=len(y_te), test_index_sha=sha(te_idx),
373
- test_score=float(score(ds.task, y_te, preds[PRIMARY])),
374
- method=PRIMARY, versions=dict(stack=info_a["version"], tablora=info_b["version"], heads=blend["version"]))
375
- path = obj.save(out_root / run_id(dataset, fold))
376
- print(f"exported {path} (test score {obj.metadata['test_score']:.4f})")
377
- return path
378
-
379
-
380
- def check(dataset, fold, tag="v2", root=None, device=None, rows=None, tolerance=None):
381
- """Replay a run's stored test predictions from raw rows and the artifact (local or downloaded).
382
-
383
- Readers were trained and scored under fp16 autocast on GPU; an fp32 CPU replay differs slightly
384
- (e.g. 2.6e-3 in standardised target units on Montgomery f0, same score), hence the looser CPU tolerance."""
385
- if tolerance is None:
386
- tolerance = 1e-3 if _device(device) == "cuda" else 1e-2
387
- root = Path(root or ROOT / "results" / "models" / tag / run_id(dataset, fold))
388
- obj = TabLoRAStack.load(root, device)
389
- ds, x_tr, x_te, y_tr, y_te, te_idx, *_ = prepare(dataset, fold)
390
- stored = np.load(ROOT / "results" / "preds" / tag / f"{run_id(dataset, fold)}.npz")
391
- sel = np.arange(len(y_te)) if rows is None else np.arange(min(rows, len(y_te)))
392
- out, _ = obj.predict_outputs(x_te.iloc[sel], device)
393
- ref = np.asarray(stored[PRIMARY])[sel]
394
- if ds.task == "regression":
395
- out = (out - obj.target_mean) / obj.target_scale
396
- diff = float(np.abs(out.reshape(ref.shape) - ref).max())
397
- full_score = score(ds.task, y_te[sel], out.reshape(ref.shape))
398
- ok = diff <= tolerance
399
- print(f"{run_id(dataset, fold)}: max|diff| {diff:.2e} on {len(sel)} rows, replayed score {full_score:.4f} "
400
- f"(stored {score(ds.task, y_te[sel], ref):.4f}) {'OK' if ok else 'MISMATCH'}")
401
- return ok
402
-
403
-
404
- def publish(repo, tag="v2", private=True):
405
- """Upload results/models/<tag> (+ index.json, model card, code snapshot) to a Hugging Face model repo."""
406
- import shutil
407
- from huggingface_hub import HfApi
408
- root = ROOT / "results" / "models" / tag
409
- runs = {}
410
- for man in sorted(root.glob("*/manifest.json")):
411
- m = json.loads(man.read_text(encoding="utf-8"))
412
- runs[man.parent.name] = dict(task=m["task"], blend_weights=m["blend_weights"], **m["metadata"])
413
- (root / "index.json").write_text(json.dumps({"tag": tag, "method": PRIMARY, "runs": runs}, indent=1), encoding="utf-8")
414
- shutil.copyfile(ROOT / "MODEL_CARD.md", root / "README.md")
415
- code = root / "code"
416
- shutil.rmtree(code, ignore_errors=True)
417
- for name in ("src", "tests", "scripts", "reference", "evaluation"):
418
- shutil.copytree(ROOT / name, code / name, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
419
- for name in ("pyproject.toml", "uv.lock", "README.md", ".python-version"):
420
- if (ROOT / name).exists():
421
- shutil.copyfile(ROOT / name, code / name)
422
- api = HfApi()
423
- api.create_repo(repo, private=private, exist_ok=True)
424
- api.upload_large_folder(repo_id=repo, folder_path=str(root), repo_type="model")
425
- print(f"published {len(runs)} runs to https://huggingface.co/{repo}")
426
-
427
-
428
- def fetch(repo, dataset, fold, revision=None):
429
- from huggingface_hub import snapshot_download
430
- rid = run_id(dataset, fold)
431
- local = snapshot_download(repo, revision=revision, allow_patterns=[f"{rid}/*"])
432
- return Path(local) / rid
433
-
434
-
435
- def main(argv=None):
436
- ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
437
- sub = ap.add_subparsers(dest="cmd")
438
- p = sub.add_parser("predict", help="predict a CSV/Parquet file with a saved artifact")
439
- p.add_argument("--artifact")
440
- p.add_argument("--repo")
441
- p.add_argument("--dataset")
442
- p.add_argument("--fold", type=int, default=0)
443
- p.add_argument("--revision")
444
- p.add_argument("--input", required=True)
445
- p.add_argument("--output", required=True)
446
- p.add_argument("--device")
447
- e = sub.add_parser("export", help="assemble artifacts from the benchmark runs")
448
- e.add_argument("--dataset", required=True)
449
- e.add_argument("--folds", default="0,1,2,3,4")
450
- c = sub.add_parser("check", help="replay stored test predictions")
451
- c.add_argument("--dataset", required=True)
452
- c.add_argument("--fold", type=int, default=0)
453
- c.add_argument("--repo")
454
- c.add_argument("--rows", type=int)
455
- c.add_argument("--device")
456
- u = sub.add_parser("publish", help="upload all exported artifacts to a Hugging Face model repo")
457
- u.add_argument("--repo", required=True)
458
- u.add_argument("--public", action="store_true")
459
- args = ap.parse_args(argv)
460
- if args.cmd == "publish":
461
- publish(args.repo, private=not args.public)
462
- elif args.cmd == "export":
463
- for f in map(int, args.folds.split(",")):
464
- export(args.dataset, f)
465
- elif args.cmd == "check":
466
- root = fetch(args.repo, args.dataset, args.fold) if args.repo else None
467
- raise SystemExit(0 if check(args.dataset, args.fold, root=root, device=args.device, rows=args.rows) else 1)
468
- elif args.cmd == "predict":
469
- root = args.artifact or fetch(args.repo, args.dataset, args.fold, args.revision)
470
- obj = TabLoRAStack.load(root, args.device)
471
- src = Path(args.input)
472
- frame = pd.read_parquet(src) if src.suffix == ".parquet" else pd.read_csv(src)
473
- out, _ = obj.predict_outputs(frame, args.device)
474
- if obj.task == "regression":
475
- res = pd.DataFrame({"prediction": out})
476
- else:
477
- res = pd.DataFrame(out, columns=[f"proba_{c}" for c in obj.classes_])
478
- res.insert(0, "prediction", obj.classes_[out.argmax(1)])
479
- res.to_csv(args.output, index=False)
480
- print(f"wrote {len(res)} predictions to {args.output}")
481
- else:
482
- ap.print_help()
483
-
484
-
485
- if __name__ == "__main__":
486
- main()
 
1
+ """The v2 model as one estimator: TabLoRA readers + Joint-Frozen TabM / TabPFN-2.5 heads, blended.
2
+
3
+ model = TabLoRAStack(num_cols, cat_cols, text_cols, task="binary").fit(train_df, y) # any text-tabular data (GPU)
4
+ model.save("artifact/"); TabLoRAStack.load("artifact/").predict_proba(test_df)
5
+
6
+ An artifact holds the fitted preprocessing (`preprocessing.pkl`: feature pipeline and the PCAs of
7
+ the frozen frame), the K cross-fitted TabLoRA readers (`reader_k.pt`: reader, LoRA and gate
8
+ parameters only; the frozen E5 layers are rebuilt from the pinned checkpoint), the Joint-Frozen
9
+ TabM (`tabm.pt`), the TabPFN-2.5 context (`context.parquet`: the frozen-frame training rows and
10
+ their targets, which is what a fitted TabPFN consists of) and the blend weights (`manifest.json`).
11
+
12
+ Inference from the published benchmark runs (downloads one run from the Hub):
13
+
14
+ python -m reading_agent2.estimator2 --repo htmldaniel/reading-agent-v2-multabench \
15
+ --dataset REG_TEXT_BOOK_PRICE --fold 0 --input rows.csv --output preds.csv
16
+
17
+ `export` assembles artifacts from the training runs (stack features, tabcond, heads) and
18
+ `check` replays a run's stored test predictions from raw rows.
19
+ """
20
+ import argparse
21
+ import copy
22
+ import hashlib
23
+ import json
24
+ import pickle
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+ import torch
30
+ from sklearn.model_selection import KFold, StratifiedKFold, train_test_split
31
+
32
+ from reading_agent.baselines import frozen_frame
33
+ from reading_agent.embed import MODEL_NAME, MODEL_REVISION, release_model
34
+ from reading_agent.features import FeaturePipeline, whole_text_embeddings
35
+ from reading_agent.run import score
36
+ from reading_agent.train import Config
37
+
38
+ from .stack import PRIMARY, ROOT, _full_probs, _ordinal, design, fit_tabm, fit_tabpfn, prepare, reader_feats, tabm_predict, tabpfn_predict
39
+ from . import tabcond as tc
40
+
41
+ FORMAT = 2
42
+ HEADS = ("tabm", "tabpfn")
43
+
44
+
45
+ def _device(device=None):
46
+ return device or ("cuda" if torch.cuda.is_available() else "cpu")
47
+
48
+
49
+ class ItemStatesAny(tc.ItemStates):
50
+ """tc.ItemStates (fp16 on CUDA, as in training) that also runs on CPU in fp32."""
51
+
52
+ def __init__(self, texts, device, batch_size=256):
53
+ if str(device).startswith("cuda"):
54
+ return super().__init__(texts, device, batch_size)
55
+ from transformers import AutoModel, AutoTokenizer
56
+ tok = AutoTokenizer.from_pretrained(MODEL_NAME, revision=MODEL_REVISION)
57
+ self.e5 = AutoModel.from_pretrained(MODEL_NAME, revision=MODEL_REVISION).eval()
58
+ lengths, chunks = np.zeros(len(texts), np.int64), [None] * len(texts)
59
+ with torch.no_grad():
60
+ for s in range(0, len(texts), batch_size):
61
+ enc = tok(texts[s:s + batch_size], max_length=tc.MAX_TOKENS, truncation=True, padding=True, return_tensors="pt")
62
+ hs = self.e5(**enc, output_hidden_states=True).hidden_states[-tc.N_TOP - 1]
63
+ for j, n in enumerate(enc["attention_mask"].sum(1).tolist()):
64
+ chunks[s + j], lengths[s + j] = hs[j, :n], n
65
+ self.lengths = torch.as_tensor(lengths)
66
+ self.offsets = torch.as_tensor(np.r_[0, np.cumsum(lengths)[:-1]])
67
+ self.flat, self.device = torch.cat(chunks), device
68
+
69
+
70
+ def _devices_to_cpu(obj, seen=None):
71
+ """pytabkit keeps the training device in nested interfaces (`device`, `device_`); point them at the CPU."""
72
+ seen = set() if seen is None else seen
73
+ if id(obj) in seen or not hasattr(obj, "__dict__") or isinstance(obj, (torch.Tensor, torch.nn.Module)):
74
+ return
75
+ seen.add(id(obj))
76
+ for k, v in vars(obj).items():
77
+ if k in ("device", "device_") and str(v).startswith("cuda"):
78
+ setattr(obj, k, torch.device("cpu") if isinstance(v, torch.device) else "cpu")
79
+ elif isinstance(v, (list, tuple)):
80
+ for x in v:
81
+ _devices_to_cpu(x, seen)
82
+ elif isinstance(v, dict):
83
+ for x in v.values():
84
+ _devices_to_cpu(x, seen)
85
+ else:
86
+ _devices_to_cpu(v, seen)
87
+
88
+
89
+ def _id_matrix(layout, tid, K):
90
+ m = np.zeros((len(layout), K), np.int64)
91
+ for i, r in enumerate(layout):
92
+ m[i, : len(r)] = [tid[t] for t in r]
93
+ return m
94
+
95
+
96
+ def _tabm_frame(F, flags, medians):
97
+ """TabM input: frozen frame, missing flags for the training-time flagged columns, training medians
98
+ (every numeric column, so rows with gaps unseen in training still get complete inputs)."""
99
+ X, cats = design(F, None)
100
+ for c in flags:
101
+ X[f"{c}_missing"] = X[c].isna().astype(float)
102
+ for c, med in medians.items():
103
+ X[c] = X[c].fillna(med)
104
+ return X, cats
105
+
106
+
107
+ class TabLoRAStack:
108
+ def __init__(self, num_cols, cat_cols, text_cols, *, task="binary", namespace="generic", max_items=8,
109
+ n_splits=3, gate=True, heads=HEADS, seed=0, adapt_epochs=10, lora_lr=1e-3):
110
+ if task not in {"binary", "multiclass", "regression"}:
111
+ raise ValueError("task must be binary, multiclass or regression")
112
+ self.task, self.n_splits, self.gate, self.heads, self.seed = task, n_splits, gate, tuple(heads), seed
113
+ self.adapt_epochs, self.lora_lr = adapt_epochs, lora_lr
114
+ self.pipe = FeaturePipeline(list(num_cols), list(cat_cols), list(text_cols), namespace,
115
+ max_items=max(max_items, len(text_cols)))
116
+ self.pcas, self.states_dicts, self.tabm, self.context = None, [], None, None
117
+ self.weights, self.flags, self.medians = {}, [], {}
118
+ self.classes_, self.target_mean, self.target_scale, self.n_out = None, 0.0, 1.0, None
119
+ self.config, self.metadata = Config(epochs=100, patience=15), {}
120
+
121
+ # ------------------------------------------------------------ readers
122
+ def _reader(self, e5, device):
123
+ cfg = self.config
124
+ model = tc.TabCondReader(n_num=self.pipe.n_num_in, cat_cards=self.pipe.cat_cardinalities,
125
+ col_name_emb=self.pipe.col_name_emb, field_name_emb=self.pipe.field_name_emb,
126
+ n_out=self.n_out, d=cfg.d, layers=cfg.layers, cell=cfg.cell, dropout=cfg.dropout,
127
+ max_items=self.pipe.max_items)
128
+ return model, tc.TopE5(copy.deepcopy(e5), d_tab=cfg.d, gate=self.gate)
129
+
130
+ def _reader_outputs(self, frame, P, device):
131
+ """Mean over the K readers of the read-all reader features (probabilities / regression value)."""
132
+ layout = tc.item_layout(self.pipe, frame)
133
+ texts = sorted({t for r in layout for t in r}) or [""]
134
+ tid = {t: i for i, t in enumerate(texts)}
135
+ ids = _id_matrix(layout, tid, self.pipe.max_items)
136
+ states = ItemStatesAny(texts, device)
137
+ feats = 0.0
138
+ for sd in self.states_dicts:
139
+ model, top = self._reader(states.e5, device)
140
+ model.attach(top, states)
141
+ missing, unexpected = model.load_state_dict(sd, strict=False)
142
+ bad = [k for k in missing if not (k.startswith("top.layers.") or ".base." in k)]
143
+ if bad or unexpected:
144
+ raise ValueError(f"reader weights do not match the model: missing {bad[:3]}, unexpected {unexpected[:3]}")
145
+ top.adapt = True
146
+ model.to(device)
147
+ out, _ = tc.outputs(model, P, ids, np.arange(len(frame)), self.task, device)
148
+ feats = feats + reader_feats(out, self.task) / len(self.states_dicts)
149
+ del model, top
150
+ return feats
151
+
152
+ # ------------------------------------------------------------ fit (any dataset)
153
+ def fit(self, frame, y, device=None):
154
+ """End-to-end training on a DataFrame: cross-fitted TabLoRA readers, heads, blend weights."""
155
+ device = _device(device)
156
+ if device == "cpu":
157
+ raise RuntimeError("TabLoRA training needs a CUDA GPU (inference also runs on CPU)")
158
+ frame = frame.reset_index(drop=True)
159
+ y = np.asarray(y)
160
+ if self.task == "regression":
161
+ self.target_mean, self.target_scale = float(y.astype(float).mean()), float(y.astype(float).std() + 1e-9)
162
+ y_tr = (y.astype(float) - self.target_mean) / self.target_scale
163
+ self.n_out = 1
164
+ else:
165
+ self.classes_ = np.unique(y)
166
+ y_tr = np.searchsorted(self.classes_, y)
167
+ self.n_out = len(self.classes_)
168
+ strat = y_tr if self.task != "regression" and np.bincount(y_tr).min() >= 2 else None
169
+ i_in, i_va = train_test_split(np.arange(len(y_tr)), test_size=0.2, random_state=self.seed, stratify=strat)
170
+ # frozen frame (structured columns + PCA of each field's whole-text E5 embedding)
171
+ self.pipe.fit(frame)
172
+ E = whole_text_embeddings(frame, self.pipe.text_cols, self.pipe.namespace)
173
+ F, self.pcas = frozen_frame(frame, self.pipe.num_cols, self.pipe.cat_cols, E)
174
+ P = self.pipe.transform(frame, y_tr)
175
+ release_model()
176
+ # cross-fitted TabLoRA readers (as tabcond.run)
177
+ layout = tc.item_layout(self.pipe, frame)
178
+ texts = sorted({t for r in layout for t in r})
179
+ tid = {t: i for i, t in enumerate(texts)}
180
+ ids = _id_matrix(layout, tid, self.pipe.max_items)
181
+ states = tc.ItemStates(texts, device)
182
+ static = np.zeros((len(texts), 384), np.float32)
183
+ probe = tc.TopE5(copy.deepcopy(states.e5), d_tab=self.config.d, gate=self.gate).to(device)
184
+ with torch.no_grad():
185
+ for s in range(0, len(texts), 512):
186
+ st, mk = states.batch(torch.arange(s, min(s + 512, len(texts))))
187
+ static[s:s + len(st)] = probe(st, mk).cpu().numpy()
188
+ del probe
189
+ P.items = static[ids].astype(np.float16) * P.item_mask[..., None]
190
+ use_strat = self.task != "regression" and np.bincount(y_tr).min() >= self.n_splits
191
+ kf = (StratifiedKFold if use_strat else KFold)(n_splits=self.n_splits, shuffle=True, random_state=self.seed)
192
+ oof, self.states_dicts = None, []
193
+ log = lambda s: print(s, flush=True)
194
+ for k, (a, b_idx) in enumerate(kf.split(np.zeros(len(y_tr)), y_tr if use_strat else None)):
195
+ a_in, a_va = train_test_split(a, test_size=0.15, random_state=self.seed + k)
196
+ torch.manual_seed(self.seed + k)
197
+ model, top = self._reader(states.e5, device)
198
+ model.attach(top, states)
199
+ model.to(device)
200
+ reader_params = [p for n, p in model.named_parameters() if not n.startswith("top.")]
201
+ tc.fit(model, P, ids, a_in, a_va, self.task, device, self.config.epochs, self.config.patience,
202
+ [{"params": reader_params, "lr": self.config.lr}], log, seed=self.seed + k, amp=False)
203
+ top.adapt = True
204
+ adapt = [p for l in top.loras for p in (l.A, l.B)] + (list(top.gate_proj.parameters()) if self.gate else [])
205
+ for p in reader_params:
206
+ p.requires_grad_(False)
207
+ tc.fit(model, P, ids, a_in, a_va, self.task, device, self.adapt_epochs, 3, [{"params": adapt, "lr": self.lora_lr}],
208
+ log, seed=100 + self.seed + k, amp=True, batch_rows=64)
209
+ out, _ = tc.outputs(model, P, ids, b_idx, self.task, device)
210
+ f = reader_feats(out, self.task)
211
+ oof = np.zeros((len(y_tr), f.shape[1]), np.float32) if oof is None else oof
212
+ oof[b_idx] = f
213
+ self.states_dicts.append(tc.adapted_state(model))
214
+ del model, top
215
+ torch.cuda.empty_cache()
216
+ # heads on the frozen frame and validation-tuned blend weights (as stack.heads)
217
+ full = lambda f: f if self.task == "regression" else _full_probs(f, self.task)
218
+ r_val = full(oof[i_va])
219
+ self.context = F.assign(__y__=y_tr)
220
+ X, cats = design(F, None)
221
+ self.flags = [c for c in X.columns if c not in cats and X[c].isna().any()]
222
+ self.medians = {c: float(0.0 if pd.isna(X[c].median()) else X[c].median()) for c in X.columns if c not in cats}
223
+ self.weights = {}
224
+ for head in self.heads:
225
+ if head == "tabpfn" and self.task != "regression" and self.n_out > 10:
226
+ continue
227
+ if head == "tabm":
228
+ Xi, _ = _tabm_frame(F, self.flags, self.medians)
229
+ self.tabm = fit_tabm(Xi.iloc[i_in], y_tr[i_in], Xi.iloc[i_va], y_tr[i_va], cats, self.task, seed=self.seed)
230
+ val = tabm_predict(self.tabm, Xi.iloc[i_va], self.task)
231
+ else:
232
+ Xo, _ = _ordinal(X, X, cats)
233
+ m = fit_tabpfn(Xo.iloc[i_in], y_tr[i_in], cats, self.task, seed=self.seed)
234
+ val = tabpfn_predict(m, Xo.iloc[i_va], self.task)
235
+ if np.asarray(val).size != r_val.size:
236
+ continue
237
+ ws = np.linspace(0, 1, 21)
238
+ vs = [score(self.task, y_tr[i_va], w * np.asarray(val).reshape(r_val.shape) + (1 - w) * r_val) for w in ws]
239
+ self.weights[head] = float(ws[int(np.argmax(vs))])
240
+ return self
241
+
242
+ # ------------------------------------------------------------ predict
243
+ def predict_outputs(self, frame, device=None):
244
+ """Probabilities (classes_ order) or raw-scale regression values, plus the parts that were blended."""
245
+ device = _device(device)
246
+ frame = frame.reset_index(drop=True)
247
+ missing = [c for c in self.pipe.num_cols + self.pipe.cat_cols + self.pipe.text_cols if c not in frame]
248
+ if missing:
249
+ raise ValueError(f"input lacks columns {missing}")
250
+ full = lambda f: np.asarray(f) if self.task == "regression" else _full_probs(np.asarray(f), self.task)
251
+ P = self.pipe.transform(frame, np.zeros(len(frame), np.int64)) # placeholder targets (unused)
252
+ reader = full(self._reader_outputs(frame, P, device))
253
+ E = whole_text_embeddings(frame, self.pipe.text_cols, self.pipe.namespace)
254
+ F, _ = frozen_frame(frame, self.pipe.num_cols, self.pipe.cat_cols, E, self.pcas)
255
+ parts = {"reader": reader}
256
+ for head, w in self.weights.items():
257
+ if head == "tabm":
258
+ X, _ = _tabm_frame(F, self.flags, self.medians)
259
+ out = tabm_predict(self.tabm, X, self.task)
260
+ else:
261
+ ctx = self.context.drop(columns="__y__")
262
+ Xc, cats = design(ctx, None)
263
+ Xn, _ = design(F[ctx.columns], None)
264
+ Xo_tr, Xo = _ordinal(Xc, Xn, cats)
265
+ m = fit_tabpfn(Xo_tr, self.context["__y__"].to_numpy(), cats, self.task, seed=self.seed)
266
+ out = tabpfn_predict(m, Xo, self.task)
267
+ parts[head] = w * np.asarray(out).reshape(reader.shape) + (1 - w) * reader
268
+ blends = [parts[h] for h in self.weights] or [reader]
269
+ out = np.mean(blends, axis=0)
270
+ if self.task == "regression":
271
+ out = out.reshape(-1) * self.target_scale + self.target_mean
272
+ return out, parts
273
+
274
+ def predict_proba(self, frame, device=None):
275
+ if self.task == "regression":
276
+ raise ValueError("predict_proba is for classification")
277
+ return self.predict_outputs(frame, device)[0]
278
+
279
+ def predict(self, frame, device=None):
280
+ out = self.predict_outputs(frame, device)[0]
281
+ return out if self.task == "regression" else self.classes_[out.argmax(1)]
282
+
283
+ # ------------------------------------------------------------ persistence
284
+ def save(self, directory):
285
+ path = Path(directory)
286
+ path.mkdir(parents=True, exist_ok=True)
287
+ with (path / "preprocessing.pkl").open("wb") as f:
288
+ pickle.dump({"pipe": self.pipe, "pcas": self.pcas}, f, protocol=4)
289
+ for k, sd in enumerate(self.states_dicts):
290
+ torch.save(sd, path / f"reader_{k}.pt")
291
+ if self.tabm is not None:
292
+ torch.save(self.tabm, path / "tabm.pt", pickle_protocol=4)
293
+ self.context.to_parquet(path / "context.parquet")
294
+ manifest = {"format_version": FORMAT, "task": self.task, "n_out": self.n_out, "seed": self.seed,
295
+ "classes": None if self.classes_ is None else [str(c) for c in self.classes_],
296
+ "target_mean": self.target_mean, "target_scale": self.target_scale,
297
+ "n_readers": len(self.states_dicts), "gate": self.gate, "config": {k: getattr(self.config, k) for k in ("d", "layers", "cell", "dropout")},
298
+ "encoder": MODEL_NAME, "encoder_revision": MODEL_REVISION, "max_tokens": tc.MAX_TOKENS,
299
+ "blend_weights": self.weights, "tabm_flags": self.flags, "tabm_medians": self.medians,
300
+ "metadata": self.metadata}
301
+ # manifest last: a directory without it is not a complete artifact
302
+ (path / "manifest.json").write_text(json.dumps(manifest, indent=1), encoding="utf-8")
303
+ return path
304
+
305
+ @classmethod
306
+ def load(cls, directory, device=None):
307
+ path = Path(directory)
308
+ man = json.loads((path / "manifest.json").read_text(encoding="utf-8"))
309
+ if man["format_version"] != FORMAT:
310
+ raise ValueError("unsupported artifact format")
311
+ with (path / "preprocessing.pkl").open("rb") as f:
312
+ prep = pickle.load(f)
313
+ pipe = prep["pipe"]
314
+ obj = cls(pipe.num_cols, pipe.cat_cols, pipe.text_cols, task=man["task"], namespace=pipe.namespace,
315
+ max_items=pipe.max_items, n_splits=man["n_readers"], gate=man["gate"], seed=man["seed"])
316
+ obj.pipe, obj.pcas, obj.n_out = pipe, prep["pcas"], man["n_out"]
317
+ for k, v in man["config"].items():
318
+ setattr(obj.config, k, v)
319
+ obj.classes_ = None if man["classes"] is None else np.asarray(man["classes"])
320
+ obj.target_mean, obj.target_scale = man["target_mean"], man["target_scale"]
321
+ obj.weights, obj.flags, obj.medians, obj.metadata = man["blend_weights"], man["tabm_flags"], man["tabm_medians"], man["metadata"]
322
+ loc = "cuda" if _device(device).startswith("cuda") else "cpu"
323
+ obj.states_dicts = [torch.load(path / f"reader_{k}.pt", map_location="cpu", weights_only=True) for k in range(man["n_readers"])]
324
+ if (path / "tabm.pt").exists():
325
+ obj.tabm = torch.load(path / "tabm.pt", map_location=loc, weights_only=False)
326
+ if loc == "cpu":
327
+ _devices_to_cpu(obj.tabm)
328
+ obj.context = pd.read_parquet(path / "context.parquet")
329
+ return obj
330
+
331
+
332
+ # ---------------------------------------------------------------- benchmark runs -> artifacts
333
+ def run_id(dataset, fold):
334
+ return f"{dataset}_f{fold}"
335
+
336
+
337
+ def export(dataset, fold, tag="v2", out_root=None):
338
+ """Assemble the artifact of one benchmark run from the stage A/B outputs and the heads (run on the VM)."""
339
+ out_root = Path(out_root or ROOT / "results" / "models" / tag)
340
+ a_dir, b_dir = ROOT / "results" / "stack" / run_id(dataset, fold), ROOT / "results" / "stackB" / run_id(dataset, fold)
341
+ h_dir = ROOT / "results" / "heads" / tag / run_id(dataset, fold)
342
+ info_a = json.loads((a_dir / "info.json").read_text(encoding="utf-8"))
343
+ info_b = json.loads((b_dir / "info.json").read_text(encoding="utf-8"))
344
+ blend = json.loads((h_dir / "blend.json").read_text(encoding="utf-8"))
345
+ ds, x_tr, x_te, y_tr, y_te, te_idx, i_in, i_va, n_out, info = prepare(dataset, fold)
346
+ F_tr = pd.read_parquet(a_dir / "F_tr.parquet")
347
+ with (b_dir / "weights" / "pipe.pkl").open("rb") as f:
348
+ pipe = pickle.load(f)
349
+ E_tr = whole_text_embeddings(x_tr, ds.text_cols, f"e5_{dataset}")
350
+ F_chk, pcas = frozen_frame(x_tr, ds.num_cols, ds.cat_cols, E_tr)
351
+ pd.testing.assert_frame_equal(F_chk, F_tr, check_exact=False, atol=1e-5) # refit PCAs reproduce stage A
352
+ F_te = pd.read_parquet(a_dir / "F_te.parquet")
353
+ X_tr, cats = design(F_tr, None)
354
+ X_te, _ = design(F_te, None)
355
+ flags = [c for c in X_tr.columns if c not in cats and (X_tr[c].isna().any() or X_te[c].isna().any())]
356
+ obj = TabLoRAStack(ds.num_cols, ds.cat_cols, ds.text_cols, task=ds.task, namespace=f"e5_{dataset}",
357
+ max_items=pipe.max_items, n_splits=info_b["n_splits"], gate=info_b["gate"], seed=fold)
358
+ obj.pipe, obj.pcas, obj.n_out = pipe, pcas, n_out
359
+ obj.classes_ = None if info["classes"] is None else np.asarray(info["classes"])
360
+ obj.target_mean, obj.target_scale = info["target_mean"], info["target_scale"]
361
+ obj.states_dicts = [torch.load(b_dir / "weights" / f"reader_{k}.pt", map_location="cpu", weights_only=True)
362
+ for k in range(info_b["n_splits"])]
363
+ tabm_path = h_dir / "tabm.pt"
364
+ obj.tabm = torch.load(tabm_path, map_location="cpu" if not torch.cuda.is_available() else None, weights_only=False) if tabm_path.exists() else None
365
+ obj.weights = blend["weights"].get("stackB", {})
366
+ obj.flags = flags
367
+ obj.medians = {c: float(0.0 if pd.isna(X_tr[c].median()) else X_tr[c].median()) for c in X_tr.columns if c not in cats}
368
+ obj.context = F_tr.assign(__y__=y_tr)
369
+ preds = np.load(ROOT / "results" / "preds" / tag / f"{run_id(dataset, fold)}.npz")
370
+ sha = lambda a: hashlib.sha256(np.ascontiguousarray(a).tobytes()).hexdigest()[:16]
371
+ obj.metadata = dict(dataset=dataset, fold=fold, protocol="paper", data_revision=info["revision"],
372
+ train_rows=len(y_tr), test_rows=len(y_te), test_index_sha=sha(te_idx),
373
+ test_score=float(score(ds.task, y_te, preds[PRIMARY])),
374
+ method=PRIMARY, versions=dict(stack=info_a["version"], tablora=info_b["version"], heads=blend["version"]))
375
+ path = obj.save(out_root / run_id(dataset, fold))
376
+ print(f"exported {path} (test score {obj.metadata['test_score']:.4f})")
377
+ return path
378
+
379
+
380
+ def check(dataset, fold, tag="v2", root=None, device=None, rows=None, tolerance=None):
381
+ """Replay a run's stored test predictions from raw rows and the artifact (local or downloaded).
382
+
383
+ Readers were trained and scored under fp16 autocast on GPU; an fp32 CPU replay differs slightly
384
+ (e.g. 2.6e-3 in standardised target units on Montgomery f0, same score), hence the looser CPU tolerance."""
385
+ if tolerance is None:
386
+ tolerance = 1e-3 if _device(device) == "cuda" else 1e-2
387
+ root = Path(root or ROOT / "results" / "models" / tag / run_id(dataset, fold))
388
+ obj = TabLoRAStack.load(root, device)
389
+ ds, x_tr, x_te, y_tr, y_te, te_idx, *_ = prepare(dataset, fold)
390
+ stored = np.load(ROOT / "results" / "preds" / tag / f"{run_id(dataset, fold)}.npz")
391
+ sel = np.arange(len(y_te)) if rows is None else np.arange(min(rows, len(y_te)))
392
+ out, _ = obj.predict_outputs(x_te.iloc[sel], device)
393
+ ref = np.asarray(stored[PRIMARY])[sel]
394
+ if ds.task == "regression":
395
+ out = (out - obj.target_mean) / obj.target_scale
396
+ diff = float(np.abs(out.reshape(ref.shape) - ref).max())
397
+ full_score = score(ds.task, y_te[sel], out.reshape(ref.shape))
398
+ ok = diff <= tolerance
399
+ print(f"{run_id(dataset, fold)}: max|diff| {diff:.2e} on {len(sel)} rows, replayed score {full_score:.4f} "
400
+ f"(stored {score(ds.task, y_te[sel], ref):.4f}) {'OK' if ok else 'MISMATCH'}")
401
+ return ok
402
+
403
+
404
+ def publish(repo, tag="v2", private=True):
405
+ """Upload results/models/<tag> (+ index.json, model card, code snapshot) to a Hugging Face model repo."""
406
+ import shutil
407
+ from huggingface_hub import HfApi
408
+ root = ROOT / "results" / "models" / tag
409
+ runs = {}
410
+ for man in sorted(root.glob("*/manifest.json")):
411
+ m = json.loads(man.read_text(encoding="utf-8"))
412
+ runs[man.parent.name] = dict(task=m["task"], blend_weights=m["blend_weights"], **m["metadata"])
413
+ (root / "index.json").write_text(json.dumps({"tag": tag, "method": PRIMARY, "runs": runs}, indent=1), encoding="utf-8")
414
+ shutil.copyfile(ROOT / "MODEL_CARD.md", root / "README.md")
415
+ code = root / "code"
416
+ shutil.rmtree(code, ignore_errors=True)
417
+ for name in ("src", "tests", "scripts", "reference", "evaluation"):
418
+ shutil.copytree(ROOT / name, code / name, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
419
+ for name in ("pyproject.toml", "uv.lock", "README.md", ".python-version"):
420
+ if (ROOT / name).exists():
421
+ shutil.copyfile(ROOT / name, code / name)
422
+ api = HfApi()
423
+ api.create_repo(repo, private=private, exist_ok=True)
424
+ api.upload_large_folder(repo_id=repo, folder_path=str(root), repo_type="model")
425
+ print(f"published {len(runs)} runs to https://huggingface.co/{repo}")
426
+
427
+
428
+ def fetch(repo, dataset, fold, revision=None):
429
+ from huggingface_hub import snapshot_download
430
+ rid = run_id(dataset, fold)
431
+ local = snapshot_download(repo, revision=revision, allow_patterns=[f"{rid}/*"])
432
+ return Path(local) / rid
433
+
434
+
435
+ def main(argv=None):
436
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
437
+ sub = ap.add_subparsers(dest="cmd")
438
+ p = sub.add_parser("predict", help="predict a CSV/Parquet file with a saved artifact")
439
+ p.add_argument("--artifact")
440
+ p.add_argument("--repo")
441
+ p.add_argument("--dataset")
442
+ p.add_argument("--fold", type=int, default=0)
443
+ p.add_argument("--revision")
444
+ p.add_argument("--input", required=True)
445
+ p.add_argument("--output", required=True)
446
+ p.add_argument("--device")
447
+ e = sub.add_parser("export", help="assemble artifacts from the benchmark runs")
448
+ e.add_argument("--dataset", required=True)
449
+ e.add_argument("--folds", default="0,1,2,3,4")
450
+ c = sub.add_parser("check", help="replay stored test predictions")
451
+ c.add_argument("--dataset", required=True)
452
+ c.add_argument("--fold", type=int, default=0)
453
+ c.add_argument("--repo")
454
+ c.add_argument("--rows", type=int)
455
+ c.add_argument("--device")
456
+ u = sub.add_parser("publish", help="upload all exported artifacts to a Hugging Face model repo")
457
+ u.add_argument("--repo", required=True)
458
+ u.add_argument("--public", action="store_true")
459
+ args = ap.parse_args(argv)
460
+ if args.cmd == "publish":
461
+ publish(args.repo, private=not args.public)
462
+ elif args.cmd == "export":
463
+ for f in map(int, args.folds.split(",")):
464
+ export(args.dataset, f)
465
+ elif args.cmd == "check":
466
+ root = fetch(args.repo, args.dataset, args.fold) if args.repo else None
467
+ raise SystemExit(0 if check(args.dataset, args.fold, root=root, device=args.device, rows=args.rows) else 1)
468
+ elif args.cmd == "predict":
469
+ root = args.artifact or fetch(args.repo, args.dataset, args.fold, args.revision)
470
+ obj = TabLoRAStack.load(root, args.device)
471
+ src = Path(args.input)
472
+ frame = pd.read_parquet(src) if src.suffix == ".parquet" else pd.read_csv(src)
473
+ out, _ = obj.predict_outputs(frame, args.device)
474
+ if obj.task == "regression":
475
+ res = pd.DataFrame({"prediction": out})
476
+ else:
477
+ res = pd.DataFrame(out, columns=[f"proba_{c}" for c in obj.classes_])
478
+ res.insert(0, "prediction", obj.classes_[out.argmax(1)])
479
+ res.to_csv(args.output, index=False)
480
+ print(f"wrote {len(res)} predictions to {args.output}")
481
+ else:
482
+ ap.print_help()
483
+
484
+
485
+ if __name__ == "__main__":
486
+ main()
code/src/reading_agent2/stack.py CHANGED
@@ -1,340 +1,340 @@
1
- """Stage A: cross-fitted reader signals stacked into strong tabular heads.
2
-
3
- Two steps per (dataset, fold), on the paper protocol and the v1 rows (pinned revisions):
4
-
5
- python -m reading_agent2.stack features --dataset REG_TEXT_ROTTEN_TOMATOES --fold 0 # CPU
6
- python -m reading_agent2.stack heads --dataset REG_TEXT_ROTTEN_TOMATOES --fold 0 # GPU
7
-
8
- `features` builds the Joint-Frozen frame (structured columns + PCA-30 of each field's
9
- whole-text E5 embedding, as in v1) and K-fold cross-fitted reader predictions: each
10
- training row's reader features come from a reader that never saw that row, and test
11
- rows get the mean over the K readers. Nothing here sees the outer test labels.
12
-
13
- `heads` fits each tabular head twice on identical rows: on the frozen frame alone
14
- (the head's own Joint-Frozen baseline) and with the reader features appended (the
15
- stack), so their difference is what the reader adds.
16
- """
17
- import argparse
18
- import json
19
- import os
20
- import time
21
- from pathlib import Path
22
-
23
- import numpy as np
24
- import pandas as pd
25
- import torch
26
- from sklearn.model_selection import KFold, StratifiedKFold, train_test_split
27
-
28
- from reading_agent.baselines import frozen_frame
29
- from reading_agent.data import get_split, load_dataset
30
- from reading_agent.embed import release_model
31
- from reading_agent.features import FeaturePipeline, whole_text_embeddings
32
- from reading_agent.run import score
33
- from reading_agent.train import Config, build_model, predict, train_warmup
34
-
35
- ROOT = Path(__file__).resolve().parents[2]
36
- WORK = ROOT / "results" / "stack"
37
- VERSION = "2026-10-23-stackA"
38
-
39
-
40
- def prepare(dataset, fold):
41
- """Split, label mapping and target scaling exactly as v1's run.py (paper protocol)."""
42
- ds = load_dataset(dataset)
43
- tr_idx, te_idx = get_split(ds.y, ds.is_cls, fold, "paper")
44
- x_tr, x_te = ds.x.iloc[tr_idx].reset_index(drop=True), ds.x.iloc[te_idx].reset_index(drop=True)
45
- y_tr_raw, y_te_raw = ds.y.iloc[tr_idx].to_numpy(), ds.y.iloc[te_idx].to_numpy()
46
- info = dict(dataset=dataset, fold=fold, task=ds.task, revision=ds.source_revision,
47
- num_cols=ds.num_cols, cat_cols=ds.cat_cols, text_cols=ds.text_cols)
48
- if ds.is_cls:
49
- classes = np.unique(y_tr_raw)
50
- cmap = {c: i for i, c in enumerate(classes)}
51
- y_tr = np.array([cmap[v] for v in y_tr_raw])
52
- keep = np.array([v in cmap for v in y_te_raw])
53
- x_te, y_te = x_te[keep].reset_index(drop=True), np.array([cmap[v] for v in y_te_raw[keep]])
54
- te_idx, n_out = te_idx[keep], len(classes)
55
- info.update(classes=[str(c) for c in classes], target_mean=0.0, target_scale=1.0)
56
- else:
57
- mu, sd = y_tr_raw.astype(float).mean(), y_tr_raw.astype(float).std() + 1e-9
58
- y_tr, y_te = (y_tr_raw.astype(float) - mu) / sd, (y_te_raw.astype(float) - mu) / sd
59
- n_out = 1
60
- info.update(classes=None, target_mean=float(mu), target_scale=float(sd))
61
- strat = y_tr if ds.is_cls and np.bincount(y_tr).min() >= 2 else None
62
- i_in, i_va = train_test_split(np.arange(len(y_tr)), test_size=0.2, random_state=fold, stratify=strat)
63
- return ds, x_tr, x_te, y_tr, y_te, te_idx, i_in, i_va, n_out, info
64
-
65
-
66
- def reader_feats(out, task):
67
- """Reader output as features: class probabilities (binary: P(class 1)) or the regression value."""
68
- out = torch.as_tensor(out)
69
- if task == "regression":
70
- return out.reshape(-1, 1).numpy()
71
- p = torch.softmax(out, 1).numpy()
72
- return p[:, 1:] if task == "binary" else p
73
-
74
-
75
- def crossfit(pipe, P_tr, P_te, y_tr, task, n_out, cfg, n_splits, seed, log):
76
- """K-fold out-of-fold reader features on the training rows, fold-averaged features on the test rows."""
77
- use_strat = task != "regression" and np.bincount(y_tr).min() >= n_splits
78
- kf = (StratifiedKFold if use_strat else KFold)(n_splits=n_splits, shuffle=True, random_state=seed)
79
- modes = ("all", "none")
80
- oof, te = {m: None for m in modes}, {m: 0.0 for m in modes}
81
- for k, (a, b) in enumerate(kf.split(np.zeros(len(y_tr)), y_tr if use_strat else None)):
82
- t = time.time()
83
- a_in, a_va = train_test_split(a, test_size=0.15, random_state=seed + k)
84
- torch.manual_seed(seed + k)
85
- m = build_model(pipe, n_out, cfg)
86
- train_warmup(m, P_tr.subset(a_in), P_tr.subset(a_va), task, cfg, log=lambda s: None)
87
- for mode in modes:
88
- f_b = reader_feats(predict(m, P_tr.subset(b), mode)[0], task)
89
- if oof[mode] is None:
90
- oof[mode] = np.zeros((len(y_tr), f_b.shape[1]), np.float32)
91
- oof[mode][b] = f_b
92
- te[mode] = te[mode] + reader_feats(predict(m, P_te, mode)[0], task) / n_splits
93
- log(f" cross-fit {k + 1}/{n_splits}: best epoch {m.best_epoch}, {time.time() - t:.0f}s")
94
- return oof, te
95
-
96
-
97
- def features(dataset, fold, n_splits=3, epochs=100, patience=15, threads=2):
98
- t0 = time.time()
99
- log = lambda s: print(f"[{time.time() - t0:6.0f}s] {s}", flush=True)
100
- torch.set_num_threads(threads)
101
- ds, x_tr, x_te, y_tr, y_te, te_idx, i_in, i_va, n_out, info = prepare(dataset, fold)
102
- ns = f"e5_{dataset}"
103
- max_items = max(8, len(ds.text_cols))
104
- pipe = FeaturePipeline(ds.num_cols, ds.cat_cols, ds.text_cols, namespace=ns, max_items=max_items).fit(x_tr)
105
- P_tr, P_te = pipe.transform(x_tr, y_tr), pipe.transform(x_te, y_te)
106
- E_tr, E_te = whole_text_embeddings(x_tr, ds.text_cols, ns), whole_text_embeddings(x_te, ds.text_cols, ns)
107
- F_tr, pcas = frozen_frame(x_tr, ds.num_cols, ds.cat_cols, E_tr)
108
- F_te, _ = frozen_frame(x_te, ds.num_cols, ds.cat_cols, E_te, pcas)
109
- release_model()
110
- torch.set_num_threads(threads)
111
- log(f"{dataset} fold {fold}: train {len(y_tr)} test {len(y_te)}, frozen frame {F_tr.shape[1]} cols")
112
- cfg = Config(epochs=epochs, patience=patience)
113
- oof, te = crossfit(pipe, P_tr, P_te, y_tr, ds.task, n_out, cfg, n_splits, seed=fold, log=log)
114
- out = WORK / f"{dataset}_f{fold}"
115
- out.mkdir(parents=True, exist_ok=True)
116
- F_tr.to_parquet(out / "F_tr.parquet")
117
- F_te.to_parquet(out / "F_te.parquet")
118
- np.savez_compressed(out / "arrays.npz", y_tr=y_tr, y_te=y_te, te_idx=te_idx, i_in=i_in, i_va=i_va,
119
- oof_all=oof["all"], oof_none=oof["none"], te_all=te["all"], te_none=te["none"])
120
- info.update(n_splits=n_splits, epochs=epochs, patience=patience, version=VERSION, minutes=(time.time() - t0) / 60,
121
- reader_oof_score=score(ds.task, y_tr, oof["all"] if ds.task == "regression" else _full_probs(oof["all"], ds.task)),
122
- reader_test_score=score(ds.task, y_te, te["all"] if ds.task == "regression" else _full_probs(te["all"], ds.task)))
123
- (out / "info.json").write_text(json.dumps(info, indent=1), encoding="utf-8")
124
- log(f"saved {out} | reader OOF {info['reader_oof_score']:.4f} test {info['reader_test_score']:.4f}")
125
-
126
-
127
- def _full_probs(f, task):
128
- """Undo reader_feats' column drop for binary tasks so `score` sees one column per class."""
129
- return np.c_[1 - f, f] if task == "binary" else f
130
-
131
-
132
- def design(F, extra, cat_prefix="cat_"):
133
- """Head input: frozen frame plus optional reader features; returns (frame, categorical column names)."""
134
- X = F.copy()
135
- if extra is not None:
136
- for j in range(extra.shape[1]):
137
- X[f"reader_{j}"] = extra[:, j]
138
- cats = [c for c in X.columns if c.startswith(cat_prefix)]
139
- return X, cats
140
-
141
-
142
- def impute(X_tr, X_te, cats):
143
- """TabM needs complete numeric columns: training-row medians plus a missingness flag per affected column."""
144
- X_tr, X_te = X_tr.copy(), X_te.copy()
145
- for c in X_tr.columns:
146
- if c in cats or not (X_tr[c].isna().any() or X_te[c].isna().any()):
147
- continue
148
- med = X_tr[c].median()
149
- med = 0.0 if pd.isna(med) else med
150
- X_tr[f"{c}_missing"], X_te[f"{c}_missing"] = X_tr[c].isna().astype(float), X_te[c].isna().astype(float)
151
- X_tr[c], X_te[c] = X_tr[c].fillna(med), X_te[c].fillna(med)
152
- return X_tr, X_te
153
-
154
-
155
- def fit_tabm(X_tr, y_tr, X_va, y_va, cats, task, seed):
156
- from pytabkit import TabM_D_Classifier, TabM_D_Regressor
157
- cls = TabM_D_Regressor if task == "regression" else TabM_D_Classifier
158
- m = cls(device="cuda" if torch.cuda.is_available() else "cpu", random_state=seed, verbosity=0)
159
- m.fit(X_tr, y_tr, X_val=X_va, y_val=y_va, cat_col_names=cats)
160
- return m
161
-
162
-
163
- def tabm_predict(m, X, task):
164
- return m.predict(X) if task == "regression" else m.predict_proba(X)
165
-
166
-
167
- def fit_tabpfn(X_tr, y_tr, cats, task, seed):
168
- from tabpfn import TabPFNClassifier, TabPFNRegressor
169
- from tabpfn.constants import ModelVersion
170
- cls = TabPFNRegressor if task == "regression" else TabPFNClassifier
171
- m = cls.create_default_for_version(ModelVersion.V2_5, device="cuda" if torch.cuda.is_available() else "cpu",
172
- ignore_pretraining_limits=True, random_state=seed)
173
- m.fit(X_tr, y_tr)
174
- return m
175
-
176
-
177
- def tabpfn_predict(m, X, task):
178
- """TabPFN predictions. On GPU OOM (memory held by another job) first wait and retry; then predict in row
179
- chunks, halving down to 1/8 of the rows (at least 512). Each test row is conditioned only on the context, so
180
- chunking does not change the predictions, but every chunk re-encodes the context, hence the floor."""
181
- pred = m.predict if task == "regression" else m.predict_proba
182
- chunk, floor, waits = len(X), min(len(X), max(512, len(X) // 8)), 0
183
- for _ in range(20):
184
- try:
185
- return np.concatenate([np.asarray(pred(X.iloc[i:i + chunk])) for i in range(0, len(X), chunk)])
186
- except Exception as e: # tabpfn.errors.TabPFNCUDAOutOfMemoryError / torch.OutOfMemoryError
187
- if "out of memory" not in str(e).lower():
188
- raise
189
- torch.cuda.empty_cache()
190
- if waits < 3 or chunk <= floor:
191
- waits += 1
192
- time.sleep(90)
193
- else:
194
- chunk = max(floor, chunk // 2)
195
- print(f" TabPFN OOM; retrying with chunk {chunk}", flush=True)
196
- raise RuntimeError("TabPFN kept running out of GPU memory")
197
-
198
-
199
- def _ordinal(X_tr, X_te, cats):
200
- """TabPFN needs numeric input: ordinal-encode categoricals with the training-row vocabulary."""
201
- X_tr, X_te = X_tr.copy(), X_te.copy()
202
- for c in cats:
203
- vocab = {v: i for i, v in enumerate(pd.unique(X_tr[c]))}
204
- X_tr[c] = X_tr[c].map(vocab).astype(float)
205
- X_te[c] = X_te[c].map(vocab).astype(float) # unseen categories become NaN
206
- return X_tr, X_te
207
-
208
-
209
- PRIMARY = "blend_mean@stackB" # fixed before the fold-0 results: TabLoRA reader blended with the mean of the heads
210
-
211
-
212
- def heads(dataset, fold, which=("tabm", "tabpfn"), tag="v2", features=("stack", "stackB"), tabpfn_stack=False):
213
- """Fit each head once on the Joint-Frozen frame, then combine it with every available reader-feature set.
214
-
215
- For each feature set `feat` (stage A `stack`, stage B `stackB`, ...):
216
- reader_crossfit_all@feat the cross-fitted reader alone (test rows: mean of the K readers)
217
- {head}_blend@feat convex blend of the frozen head and that reader, weight tuned on the inner
218
- validation rows (reader predictions there are out-of-fold)
219
- {head}_stack@feat head refit with the reader features appended (TabPFN only if tabpfn_stack)
220
- blend_mean@feat equal-weight mean of the heads' blends (no further tuning)
221
- The frozen frame always comes from stage A's folder.
222
- """
223
- t0 = time.time()
224
- log = lambda s: print(f"[{time.time() - t0:6.0f}s] {s}", flush=True)
225
- src = WORK / f"{dataset}_f{fold}"
226
- info = json.loads((src / "info.json").read_text(encoding="utf-8"))
227
- base = np.load(src / "arrays.npz")
228
- F_tr, F_te = pd.read_parquet(src / "F_tr.parquet"), pd.read_parquet(src / "F_te.parquet")
229
- task, y_tr, y_te, i_in, i_va = info["task"], base["y_tr"], base["y_te"], base["i_in"], base["i_va"]
230
- full = lambda f: f if task == "regression" else _full_probs(f, task)
231
- readers = {}
232
- for feat in features:
233
- path = ROOT / "results" / feat / f"{dataset}_f{fold}" / "arrays.npz"
234
- if not path.exists():
235
- log(f" no {feat} features yet; skipped")
236
- continue
237
- a = np.load(path)
238
- assert np.array_equal(a["y_tr"], y_tr) and np.array_equal(a["y_te"], y_te), f"{feat} rows differ"
239
- readers[feat] = dict(tr=np.c_[a["oof_all"], a["oof_none"]], te=np.c_[a["te_all"], a["te_none"]],
240
- test=full(a["te_all"]), val=full(a["oof_all"][i_va]))
241
- n_classes = len(info["classes"] or [])
242
- results, preds, fitted, weights = [], {}, {}, {}
243
-
244
- def record(method, out, **kw):
245
- s = score(task, y_te, out)
246
- preds[method] = np.asarray(out, np.float32)
247
- results.append(dict(dataset=dataset, fold=fold, task=task, tag=tag, method=method, score=s, version=VERSION,
248
- revision=info["revision"], **kw))
249
- log(f" >> {method:28s} {s:.4f}")
250
-
251
- def fit_predict(head, ex_tr, ex_te, want_val):
252
- X_tr, cats = design(F_tr, ex_tr)
253
- X_te, _ = design(F_te, ex_te)
254
- if head == "tabm":
255
- Xi_tr, Xi_te = impute(X_tr, X_te, cats)
256
- m = fit_tabm(Xi_tr.iloc[i_in], y_tr[i_in], Xi_tr.iloc[i_va], y_tr[i_va], cats, task, seed=fold)
257
- if ex_tr is None:
258
- fitted[head] = m
259
- return tabm_predict(m, Xi_te, task), tabm_predict(m, Xi_tr.iloc[i_va], task)
260
- Xo_tr, Xo_te = _ordinal(X_tr, X_te, cats)
261
- out = tabpfn_predict(fit_tabpfn(Xo_tr, y_tr, cats, task, seed=fold), Xo_te, task)
262
- val = None
263
- if want_val: # TabPFN conditions on all training rows; validation predictions need an inner fit
264
- val = tabpfn_predict(fit_tabpfn(Xo_tr.iloc[i_in], y_tr[i_in], cats, task, seed=fold), Xo_tr.iloc[i_va], task)
265
- return out, val
266
-
267
- for feat, r in readers.items():
268
- record(f"reader_crossfit_all@{feat}", r["test"])
269
- blends = {feat: [] for feat in readers}
270
- for head in which:
271
- if head == "tabpfn" and task != "regression" and n_classes > 10:
272
- log(f" TabPFN skipped: {n_classes} classes > 10 (as in MulTaBench)")
273
- continue
274
- t = time.time()
275
- out, val = fit_predict(head, None, None, want_val=True)
276
- record(f"{head}_frozen", out, seconds=time.time() - t)
277
- for feat, r in readers.items():
278
- if np.asarray(val).size != r["val"].size:
279
- log(f" {head}_blend@{feat} skipped: output columns differ (class missing in a split)")
280
- continue
281
- ws = np.linspace(0, 1, 21)
282
- vs = [score(task, y_tr[i_va], w * np.asarray(val).reshape(r["val"].shape) + (1 - w) * r["val"]) for w in ws]
283
- w = float(ws[int(np.argmax(vs))])
284
- record(f"{head}_blend@{feat}", w * np.asarray(out).reshape(r["test"].shape) + (1 - w) * r["test"], w=w)
285
- weights.setdefault(feat, {})[head] = w
286
- blends[feat].append(f"{head}_blend@{feat}")
287
- if head == "tabm" or tabpfn_stack:
288
- for feat, r in readers.items():
289
- t = time.time()
290
- out_s, _ = fit_predict(head, r["tr"], r["te"], want_val=False)
291
- record(f"{head}_stack@{feat}", out_s, seconds=time.time() - t)
292
- torch.cuda.empty_cache()
293
- for feat, members in blends.items():
294
- if members:
295
- record(f"blend_mean@{feat}", np.mean([preds[k] for k in members], axis=0), members=members)
296
- out_dir = ROOT / "results"
297
- with open(out_dir / f"{tag}.jsonl", "a") as f:
298
- for r in results:
299
- f.write(json.dumps(r) + "\n")
300
- pdir = out_dir / "preds" / tag
301
- pdir.mkdir(parents=True, exist_ok=True)
302
- np.savez_compressed(pdir / f"{dataset}_f{fold}.npz", y_te=y_te, te_idx=base["te_idx"], **preds)
303
- # Inference artifacts: the fitted Joint-Frozen TabM and the blend weights (TabPFN-2.5 is refit on the
304
- # stored training frame at inference, which is how it conditions on training rows).
305
- mdir = out_dir / "heads" / tag / f"{dataset}_f{fold}"
306
- mdir.mkdir(parents=True, exist_ok=True)
307
- for head, m in fitted.items(): # torch.save so CUDA-trained heads load on CPU with map_location
308
- torch.save(m, mdir / f"{head}.pt", pickle_protocol=4)
309
- (mdir / "blend.json").write_text(json.dumps({"weights": weights, "heads": [h for h in which if any(h in v for v in weights.values())],
310
- "version": VERSION}, indent=1), encoding="utf-8")
311
- log("done")
312
-
313
-
314
- def main(argv=None):
315
- ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
316
- sub = ap.add_subparsers(dest="cmd", required=True)
317
- for name in ("features", "heads"):
318
- p = sub.add_parser(name)
319
- p.add_argument("--dataset", required=True)
320
- p.add_argument("--fold", type=int, default=0)
321
- if name == "features":
322
- p.add_argument("--n_splits", type=int, default=3)
323
- p.add_argument("--epochs", type=int, default=100)
324
- p.add_argument("--patience", type=int, default=15)
325
- p.add_argument("--threads", type=int, default=2)
326
- else:
327
- p.add_argument("--heads", default="tabm,tabpfn")
328
- p.add_argument("--tag", default="v2")
329
- p.add_argument("--features", default="stack,stackB", help="reader-feature folders: stack (A), stackB (TabLoRA), ...")
330
- p.add_argument("--tabpfn_stack", type=int, default=0)
331
- args = ap.parse_args(argv)
332
- if args.cmd == "features":
333
- features(args.dataset, args.fold, args.n_splits, args.epochs, args.patience, args.threads)
334
- else:
335
- heads(args.dataset, args.fold, tuple(args.heads.split(",")), args.tag, tuple(args.features.split(",")),
336
- bool(args.tabpfn_stack))
337
-
338
-
339
- if __name__ == "__main__":
340
- main()
 
1
+ """Stage A: cross-fitted reader signals stacked into strong tabular heads.
2
+
3
+ Two steps per (dataset, fold), on the paper protocol and the v1 rows (pinned revisions):
4
+
5
+ python -m reading_agent2.stack features --dataset REG_TEXT_ROTTEN_TOMATOES --fold 0 # CPU
6
+ python -m reading_agent2.stack heads --dataset REG_TEXT_ROTTEN_TOMATOES --fold 0 # GPU
7
+
8
+ `features` builds the Joint-Frozen frame (structured columns + PCA-30 of each field's
9
+ whole-text E5 embedding, as in v1) and K-fold cross-fitted reader predictions: each
10
+ training row's reader features come from a reader that never saw that row, and test
11
+ rows get the mean over the K readers. Nothing here sees the outer test labels.
12
+
13
+ `heads` fits each tabular head twice on identical rows: on the frozen frame alone
14
+ (the head's own Joint-Frozen baseline) and with the reader features appended (the
15
+ stack), so their difference is what the reader adds.
16
+ """
17
+ import argparse
18
+ import json
19
+ import os
20
+ import time
21
+ from pathlib import Path
22
+
23
+ import numpy as np
24
+ import pandas as pd
25
+ import torch
26
+ from sklearn.model_selection import KFold, StratifiedKFold, train_test_split
27
+
28
+ from reading_agent.baselines import frozen_frame
29
+ from reading_agent.data import get_split, load_dataset
30
+ from reading_agent.embed import release_model
31
+ from reading_agent.features import FeaturePipeline, whole_text_embeddings
32
+ from reading_agent.run import score
33
+ from reading_agent.train import Config, build_model, predict, train_warmup
34
+
35
+ ROOT = Path(__file__).resolve().parents[2]
36
+ WORK = ROOT / "results" / "stack"
37
+ VERSION = "2026-10-23-stackA"
38
+
39
+
40
+ def prepare(dataset, fold):
41
+ """Split, label mapping and target scaling exactly as v1's run.py (paper protocol)."""
42
+ ds = load_dataset(dataset)
43
+ tr_idx, te_idx = get_split(ds.y, ds.is_cls, fold, "paper")
44
+ x_tr, x_te = ds.x.iloc[tr_idx].reset_index(drop=True), ds.x.iloc[te_idx].reset_index(drop=True)
45
+ y_tr_raw, y_te_raw = ds.y.iloc[tr_idx].to_numpy(), ds.y.iloc[te_idx].to_numpy()
46
+ info = dict(dataset=dataset, fold=fold, task=ds.task, revision=ds.source_revision,
47
+ num_cols=ds.num_cols, cat_cols=ds.cat_cols, text_cols=ds.text_cols)
48
+ if ds.is_cls:
49
+ classes = np.unique(y_tr_raw)
50
+ cmap = {c: i for i, c in enumerate(classes)}
51
+ y_tr = np.array([cmap[v] for v in y_tr_raw])
52
+ keep = np.array([v in cmap for v in y_te_raw])
53
+ x_te, y_te = x_te[keep].reset_index(drop=True), np.array([cmap[v] for v in y_te_raw[keep]])
54
+ te_idx, n_out = te_idx[keep], len(classes)
55
+ info.update(classes=[str(c) for c in classes], target_mean=0.0, target_scale=1.0)
56
+ else:
57
+ mu, sd = y_tr_raw.astype(float).mean(), y_tr_raw.astype(float).std() + 1e-9
58
+ y_tr, y_te = (y_tr_raw.astype(float) - mu) / sd, (y_te_raw.astype(float) - mu) / sd
59
+ n_out = 1
60
+ info.update(classes=None, target_mean=float(mu), target_scale=float(sd))
61
+ strat = y_tr if ds.is_cls and np.bincount(y_tr).min() >= 2 else None
62
+ i_in, i_va = train_test_split(np.arange(len(y_tr)), test_size=0.2, random_state=fold, stratify=strat)
63
+ return ds, x_tr, x_te, y_tr, y_te, te_idx, i_in, i_va, n_out, info
64
+
65
+
66
+ def reader_feats(out, task):
67
+ """Reader output as features: class probabilities (binary: P(class 1)) or the regression value."""
68
+ out = torch.as_tensor(out)
69
+ if task == "regression":
70
+ return out.reshape(-1, 1).numpy()
71
+ p = torch.softmax(out, 1).numpy()
72
+ return p[:, 1:] if task == "binary" else p
73
+
74
+
75
+ def crossfit(pipe, P_tr, P_te, y_tr, task, n_out, cfg, n_splits, seed, log):
76
+ """K-fold out-of-fold reader features on the training rows, fold-averaged features on the test rows."""
77
+ use_strat = task != "regression" and np.bincount(y_tr).min() >= n_splits
78
+ kf = (StratifiedKFold if use_strat else KFold)(n_splits=n_splits, shuffle=True, random_state=seed)
79
+ modes = ("all", "none")
80
+ oof, te = {m: None for m in modes}, {m: 0.0 for m in modes}
81
+ for k, (a, b) in enumerate(kf.split(np.zeros(len(y_tr)), y_tr if use_strat else None)):
82
+ t = time.time()
83
+ a_in, a_va = train_test_split(a, test_size=0.15, random_state=seed + k)
84
+ torch.manual_seed(seed + k)
85
+ m = build_model(pipe, n_out, cfg)
86
+ train_warmup(m, P_tr.subset(a_in), P_tr.subset(a_va), task, cfg, log=lambda s: None)
87
+ for mode in modes:
88
+ f_b = reader_feats(predict(m, P_tr.subset(b), mode)[0], task)
89
+ if oof[mode] is None:
90
+ oof[mode] = np.zeros((len(y_tr), f_b.shape[1]), np.float32)
91
+ oof[mode][b] = f_b
92
+ te[mode] = te[mode] + reader_feats(predict(m, P_te, mode)[0], task) / n_splits
93
+ log(f" cross-fit {k + 1}/{n_splits}: best epoch {m.best_epoch}, {time.time() - t:.0f}s")
94
+ return oof, te
95
+
96
+
97
+ def features(dataset, fold, n_splits=3, epochs=100, patience=15, threads=2):
98
+ t0 = time.time()
99
+ log = lambda s: print(f"[{time.time() - t0:6.0f}s] {s}", flush=True)
100
+ torch.set_num_threads(threads)
101
+ ds, x_tr, x_te, y_tr, y_te, te_idx, i_in, i_va, n_out, info = prepare(dataset, fold)
102
+ ns = f"e5_{dataset}"
103
+ max_items = max(8, len(ds.text_cols))
104
+ pipe = FeaturePipeline(ds.num_cols, ds.cat_cols, ds.text_cols, namespace=ns, max_items=max_items).fit(x_tr)
105
+ P_tr, P_te = pipe.transform(x_tr, y_tr), pipe.transform(x_te, y_te)
106
+ E_tr, E_te = whole_text_embeddings(x_tr, ds.text_cols, ns), whole_text_embeddings(x_te, ds.text_cols, ns)
107
+ F_tr, pcas = frozen_frame(x_tr, ds.num_cols, ds.cat_cols, E_tr)
108
+ F_te, _ = frozen_frame(x_te, ds.num_cols, ds.cat_cols, E_te, pcas)
109
+ release_model()
110
+ torch.set_num_threads(threads)
111
+ log(f"{dataset} fold {fold}: train {len(y_tr)} test {len(y_te)}, frozen frame {F_tr.shape[1]} cols")
112
+ cfg = Config(epochs=epochs, patience=patience)
113
+ oof, te = crossfit(pipe, P_tr, P_te, y_tr, ds.task, n_out, cfg, n_splits, seed=fold, log=log)
114
+ out = WORK / f"{dataset}_f{fold}"
115
+ out.mkdir(parents=True, exist_ok=True)
116
+ F_tr.to_parquet(out / "F_tr.parquet")
117
+ F_te.to_parquet(out / "F_te.parquet")
118
+ np.savez_compressed(out / "arrays.npz", y_tr=y_tr, y_te=y_te, te_idx=te_idx, i_in=i_in, i_va=i_va,
119
+ oof_all=oof["all"], oof_none=oof["none"], te_all=te["all"], te_none=te["none"])
120
+ info.update(n_splits=n_splits, epochs=epochs, patience=patience, version=VERSION, minutes=(time.time() - t0) / 60,
121
+ reader_oof_score=score(ds.task, y_tr, oof["all"] if ds.task == "regression" else _full_probs(oof["all"], ds.task)),
122
+ reader_test_score=score(ds.task, y_te, te["all"] if ds.task == "regression" else _full_probs(te["all"], ds.task)))
123
+ (out / "info.json").write_text(json.dumps(info, indent=1), encoding="utf-8")
124
+ log(f"saved {out} | reader OOF {info['reader_oof_score']:.4f} test {info['reader_test_score']:.4f}")
125
+
126
+
127
+ def _full_probs(f, task):
128
+ """Undo reader_feats' column drop for binary tasks so `score` sees one column per class."""
129
+ return np.c_[1 - f, f] if task == "binary" else f
130
+
131
+
132
+ def design(F, extra, cat_prefix="cat_"):
133
+ """Head input: frozen frame plus optional reader features; returns (frame, categorical column names)."""
134
+ X = F.copy()
135
+ if extra is not None:
136
+ for j in range(extra.shape[1]):
137
+ X[f"reader_{j}"] = extra[:, j]
138
+ cats = [c for c in X.columns if c.startswith(cat_prefix)]
139
+ return X, cats
140
+
141
+
142
+ def impute(X_tr, X_te, cats):
143
+ """TabM needs complete numeric columns: training-row medians plus a missingness flag per affected column."""
144
+ X_tr, X_te = X_tr.copy(), X_te.copy()
145
+ for c in X_tr.columns:
146
+ if c in cats or not (X_tr[c].isna().any() or X_te[c].isna().any()):
147
+ continue
148
+ med = X_tr[c].median()
149
+ med = 0.0 if pd.isna(med) else med
150
+ X_tr[f"{c}_missing"], X_te[f"{c}_missing"] = X_tr[c].isna().astype(float), X_te[c].isna().astype(float)
151
+ X_tr[c], X_te[c] = X_tr[c].fillna(med), X_te[c].fillna(med)
152
+ return X_tr, X_te
153
+
154
+
155
+ def fit_tabm(X_tr, y_tr, X_va, y_va, cats, task, seed):
156
+ from pytabkit import TabM_D_Classifier, TabM_D_Regressor
157
+ cls = TabM_D_Regressor if task == "regression" else TabM_D_Classifier
158
+ m = cls(device="cuda" if torch.cuda.is_available() else "cpu", random_state=seed, verbosity=0)
159
+ m.fit(X_tr, y_tr, X_val=X_va, y_val=y_va, cat_col_names=cats)
160
+ return m
161
+
162
+
163
+ def tabm_predict(m, X, task):
164
+ return m.predict(X) if task == "regression" else m.predict_proba(X)
165
+
166
+
167
+ def fit_tabpfn(X_tr, y_tr, cats, task, seed):
168
+ from tabpfn import TabPFNClassifier, TabPFNRegressor
169
+ from tabpfn.constants import ModelVersion
170
+ cls = TabPFNRegressor if task == "regression" else TabPFNClassifier
171
+ m = cls.create_default_for_version(ModelVersion.V2_5, device="cuda" if torch.cuda.is_available() else "cpu",
172
+ ignore_pretraining_limits=True, random_state=seed)
173
+ m.fit(X_tr, y_tr)
174
+ return m
175
+
176
+
177
+ def tabpfn_predict(m, X, task):
178
+ """TabPFN predictions. On GPU OOM (memory held by another job) first wait and retry; then predict in row
179
+ chunks, halving down to 1/8 of the rows (at least 512). Each test row is conditioned only on the context, so
180
+ chunking does not change the predictions, but every chunk re-encodes the context, hence the floor."""
181
+ pred = m.predict if task == "regression" else m.predict_proba
182
+ chunk, floor, waits = len(X), min(len(X), max(512, len(X) // 8)), 0
183
+ for _ in range(20):
184
+ try:
185
+ return np.concatenate([np.asarray(pred(X.iloc[i:i + chunk])) for i in range(0, len(X), chunk)])
186
+ except Exception as e: # tabpfn.errors.TabPFNCUDAOutOfMemoryError / torch.OutOfMemoryError
187
+ if "out of memory" not in str(e).lower():
188
+ raise
189
+ torch.cuda.empty_cache()
190
+ if waits < 3 or chunk <= floor:
191
+ waits += 1
192
+ time.sleep(90)
193
+ else:
194
+ chunk = max(floor, chunk // 2)
195
+ print(f" TabPFN OOM; retrying with chunk {chunk}", flush=True)
196
+ raise RuntimeError("TabPFN kept running out of GPU memory")
197
+
198
+
199
+ def _ordinal(X_tr, X_te, cats):
200
+ """TabPFN needs numeric input: ordinal-encode categoricals with the training-row vocabulary."""
201
+ X_tr, X_te = X_tr.copy(), X_te.copy()
202
+ for c in cats:
203
+ vocab = {v: i for i, v in enumerate(pd.unique(X_tr[c]))}
204
+ X_tr[c] = X_tr[c].map(vocab).astype(float)
205
+ X_te[c] = X_te[c].map(vocab).astype(float) # unseen categories become NaN
206
+ return X_tr, X_te
207
+
208
+
209
+ PRIMARY = "blend_mean@stackB" # fixed before the fold-0 results: TabLoRA reader blended with the mean of the heads
210
+
211
+
212
+ def heads(dataset, fold, which=("tabm", "tabpfn"), tag="v2", features=("stack", "stackB"), tabpfn_stack=False):
213
+ """Fit each head once on the Joint-Frozen frame, then combine it with every available reader-feature set.
214
+
215
+ For each feature set `feat` (stage A `stack`, stage B `stackB`, ...):
216
+ reader_crossfit_all@feat the cross-fitted reader alone (test rows: mean of the K readers)
217
+ {head}_blend@feat convex blend of the frozen head and that reader, weight tuned on the inner
218
+ validation rows (reader predictions there are out-of-fold)
219
+ {head}_stack@feat head refit with the reader features appended (TabPFN only if tabpfn_stack)
220
+ blend_mean@feat equal-weight mean of the heads' blends (no further tuning)
221
+ The frozen frame always comes from stage A's folder.
222
+ """
223
+ t0 = time.time()
224
+ log = lambda s: print(f"[{time.time() - t0:6.0f}s] {s}", flush=True)
225
+ src = WORK / f"{dataset}_f{fold}"
226
+ info = json.loads((src / "info.json").read_text(encoding="utf-8"))
227
+ base = np.load(src / "arrays.npz")
228
+ F_tr, F_te = pd.read_parquet(src / "F_tr.parquet"), pd.read_parquet(src / "F_te.parquet")
229
+ task, y_tr, y_te, i_in, i_va = info["task"], base["y_tr"], base["y_te"], base["i_in"], base["i_va"]
230
+ full = lambda f: f if task == "regression" else _full_probs(f, task)
231
+ readers = {}
232
+ for feat in features:
233
+ path = ROOT / "results" / feat / f"{dataset}_f{fold}" / "arrays.npz"
234
+ if not path.exists():
235
+ log(f" no {feat} features yet; skipped")
236
+ continue
237
+ a = np.load(path)
238
+ assert np.array_equal(a["y_tr"], y_tr) and np.array_equal(a["y_te"], y_te), f"{feat} rows differ"
239
+ readers[feat] = dict(tr=np.c_[a["oof_all"], a["oof_none"]], te=np.c_[a["te_all"], a["te_none"]],
240
+ test=full(a["te_all"]), val=full(a["oof_all"][i_va]))
241
+ n_classes = len(info["classes"] or [])
242
+ results, preds, fitted, weights = [], {}, {}, {}
243
+
244
+ def record(method, out, **kw):
245
+ s = score(task, y_te, out)
246
+ preds[method] = np.asarray(out, np.float32)
247
+ results.append(dict(dataset=dataset, fold=fold, task=task, tag=tag, method=method, score=s, version=VERSION,
248
+ revision=info["revision"], **kw))
249
+ log(f" >> {method:28s} {s:.4f}")
250
+
251
+ def fit_predict(head, ex_tr, ex_te, want_val):
252
+ X_tr, cats = design(F_tr, ex_tr)
253
+ X_te, _ = design(F_te, ex_te)
254
+ if head == "tabm":
255
+ Xi_tr, Xi_te = impute(X_tr, X_te, cats)
256
+ m = fit_tabm(Xi_tr.iloc[i_in], y_tr[i_in], Xi_tr.iloc[i_va], y_tr[i_va], cats, task, seed=fold)
257
+ if ex_tr is None:
258
+ fitted[head] = m
259
+ return tabm_predict(m, Xi_te, task), tabm_predict(m, Xi_tr.iloc[i_va], task)
260
+ Xo_tr, Xo_te = _ordinal(X_tr, X_te, cats)
261
+ out = tabpfn_predict(fit_tabpfn(Xo_tr, y_tr, cats, task, seed=fold), Xo_te, task)
262
+ val = None
263
+ if want_val: # TabPFN conditions on all training rows; validation predictions need an inner fit
264
+ val = tabpfn_predict(fit_tabpfn(Xo_tr.iloc[i_in], y_tr[i_in], cats, task, seed=fold), Xo_tr.iloc[i_va], task)
265
+ return out, val
266
+
267
+ for feat, r in readers.items():
268
+ record(f"reader_crossfit_all@{feat}", r["test"])
269
+ blends = {feat: [] for feat in readers}
270
+ for head in which:
271
+ if head == "tabpfn" and task != "regression" and n_classes > 10:
272
+ log(f" TabPFN skipped: {n_classes} classes > 10 (as in MulTaBench)")
273
+ continue
274
+ t = time.time()
275
+ out, val = fit_predict(head, None, None, want_val=True)
276
+ record(f"{head}_frozen", out, seconds=time.time() - t)
277
+ for feat, r in readers.items():
278
+ if np.asarray(val).size != r["val"].size:
279
+ log(f" {head}_blend@{feat} skipped: output columns differ (class missing in a split)")
280
+ continue
281
+ ws = np.linspace(0, 1, 21)
282
+ vs = [score(task, y_tr[i_va], w * np.asarray(val).reshape(r["val"].shape) + (1 - w) * r["val"]) for w in ws]
283
+ w = float(ws[int(np.argmax(vs))])
284
+ record(f"{head}_blend@{feat}", w * np.asarray(out).reshape(r["test"].shape) + (1 - w) * r["test"], w=w)
285
+ weights.setdefault(feat, {})[head] = w
286
+ blends[feat].append(f"{head}_blend@{feat}")
287
+ if head == "tabm" or tabpfn_stack:
288
+ for feat, r in readers.items():
289
+ t = time.time()
290
+ out_s, _ = fit_predict(head, r["tr"], r["te"], want_val=False)
291
+ record(f"{head}_stack@{feat}", out_s, seconds=time.time() - t)
292
+ torch.cuda.empty_cache()
293
+ for feat, members in blends.items():
294
+ if members:
295
+ record(f"blend_mean@{feat}", np.mean([preds[k] for k in members], axis=0), members=members)
296
+ out_dir = ROOT / "results"
297
+ with open(out_dir / f"{tag}.jsonl", "a") as f:
298
+ for r in results:
299
+ f.write(json.dumps(r) + "\n")
300
+ pdir = out_dir / "preds" / tag
301
+ pdir.mkdir(parents=True, exist_ok=True)
302
+ np.savez_compressed(pdir / f"{dataset}_f{fold}.npz", y_te=y_te, te_idx=base["te_idx"], **preds)
303
+ # Inference artifacts: the fitted Joint-Frozen TabM and the blend weights (TabPFN-2.5 is refit on the
304
+ # stored training frame at inference, which is how it conditions on training rows).
305
+ mdir = out_dir / "heads" / tag / f"{dataset}_f{fold}"
306
+ mdir.mkdir(parents=True, exist_ok=True)
307
+ for head, m in fitted.items(): # torch.save so CUDA-trained heads load on CPU with map_location
308
+ torch.save(m, mdir / f"{head}.pt", pickle_protocol=4)
309
+ (mdir / "blend.json").write_text(json.dumps({"weights": weights, "heads": [h for h in which if any(h in v for v in weights.values())],
310
+ "version": VERSION}, indent=1), encoding="utf-8")
311
+ log("done")
312
+
313
+
314
+ def main(argv=None):
315
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
316
+ sub = ap.add_subparsers(dest="cmd", required=True)
317
+ for name in ("features", "heads"):
318
+ p = sub.add_parser(name)
319
+ p.add_argument("--dataset", required=True)
320
+ p.add_argument("--fold", type=int, default=0)
321
+ if name == "features":
322
+ p.add_argument("--n_splits", type=int, default=3)
323
+ p.add_argument("--epochs", type=int, default=100)
324
+ p.add_argument("--patience", type=int, default=15)
325
+ p.add_argument("--threads", type=int, default=2)
326
+ else:
327
+ p.add_argument("--heads", default="tabm,tabpfn")
328
+ p.add_argument("--tag", default="v2")
329
+ p.add_argument("--features", default="stack,stackB", help="reader-feature folders: stack (A), stackB (TabLoRA), ...")
330
+ p.add_argument("--tabpfn_stack", type=int, default=0)
331
+ args = ap.parse_args(argv)
332
+ if args.cmd == "features":
333
+ features(args.dataset, args.fold, args.n_splits, args.epochs, args.patience, args.threads)
334
+ else:
335
+ heads(args.dataset, args.fold, tuple(args.heads.split(",")), args.tag, tuple(args.features.split(",")),
336
+ bool(args.tabpfn_stack))
337
+
338
+
339
+ if __name__ == "__main__":
340
+ main()