01RAI commited on
Commit
d303b8b
·
verified ·
1 Parent(s): e7d3c7d

PredictLM v11.0 + Mini ship-bundle

Browse files
.gitattributes CHANGED
@@ -1,35 +1,3 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
  *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  *.pt filter=lfs diff=lfs merge=lfs -text
2
+ *.bin filter=lfs diff=lfs merge=lfs -text
 
3
  *.safetensors filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may accept additional
167
+ acceptance of support, warranty, indemnity, or other liability
168
+ obligations and/or rights consistent with this License. However,
169
+ in accepting such obligations, You may act only on Your own behalf
170
+ and on Your sole responsibility, not on behalf of any other
171
+ Contributor, and only if You agree to indemnify, defend, and hold
172
+ each Contributor harmless for any liability incurred by, or claims
173
+ asserted against, such Contributor by reason of your accepting any
174
+ such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 ZeroOne Research
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
200
+ implied. See the License for the specific language governing permissions
201
+ and limitations under the License.
README.md ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: predictlm
4
+ pipeline_tag: tabular-classification
5
+ tags:
6
+ - tabular
7
+ - tabular-classification
8
+ - tabular-regression
9
+ - in-context-learning
10
+ - foundation-model
11
+ - prior-fitted-network
12
+ - tabpfn-style
13
+ - distilled
14
+ - compact
15
+ metrics:
16
+ - accuracy
17
+ - r2
18
+ co2_eq_emissions:
19
+ emissions: 700
20
+ source: estimated from Azure EU-North grid factor (~0.3 kg CO₂/kWh) and ~3.3 GPU-hours at T4 ~70W TDP
21
+ training_type: distillation
22
+ geographical_location: Netherlands
23
+ hardware_used: 1× NVIDIA Tesla T4 16GB (commodity)
24
+ model-index:
25
+ - name: predictlm-mini-13m
26
+ results:
27
+ - task:
28
+ type: tabular-classification
29
+ name: Tabular Classification
30
+ dataset:
31
+ type: openml
32
+ name: Locked OpenML eval (CC-18 + AMLB + TabPFN-extras), fair-set n_features ≤ 128
33
+ metrics:
34
+ - type: accuracy
35
+ value: 0.684
36
+ name: mean accuracy (n=12, seed=42, fair-set n_features ≤ 128)
37
+ - task:
38
+ type: tabular-regression
39
+ name: Tabular Regression
40
+ dataset:
41
+ type: openml
42
+ name: Locked OpenML eval (CTR-23 + AMLB), fair-set n_features ≤ 128
43
+ metrics:
44
+ - type: r2
45
+ value: 0.551
46
+ name: mean R² (n=13, seed=42, fair-set n_features ≤ 128)
47
+ ---
48
+
49
+ # predictlm-mini-13m
50
+
51
+ A 13.5M-parameter **distilled tabular foundation model** trained on a single Tesla T4 in 3.3 hours for ~$1.30. Half the parameters of [PredictLM Base (26M)](https://huggingface.co/zerooneresearch/predictlm-base-26m); **statistically tied with Base on classification accuracy** and within ~4 pp R² on regression.
52
+
53
+ This is the **compact deployment variant** of PredictLM, designed to run inference on any modern laptop or commodity GPU. Same single-forward-pass in-context-learning API as Base, same architecture family — just smaller, distilled, and re-trainable on hardware most teams already have.
54
+
55
+ ## Getting started — the published 0.751 cls / 0.609 reg recipe, by default
56
+
57
+ ```bash
58
+ pip install predictlm
59
+ ```
60
+
61
+ ```python
62
+ from predictlm import PredictLM
63
+
64
+ model = PredictLM.from_pretrained("zerooneresearch/predictlm-mini-13m") # cpu / mps / cuda all OK
65
+
66
+ # Regression — pass float y, get continuous predictions
67
+ preds = model.fit(X_train_reg, y_train_reg).predict(X_test_reg)
68
+
69
+ # Classification — same model, same API; auto-routed via y_train dtype
70
+ preds = model.fit(X_train_cls, y_train_cls).predict(X_test_cls)
71
+ probs = model.predict_proba(X_test_cls)
72
+ ```
73
+
74
+ That's it. On the first `.predict()` call the package silently downloads its partner checkpoint (`predictlm-base-26m`), forms the published **Duo + TTT** ensemble under the hood, and returns the **0.751 cls / 0.609 reg** result on the locked 25-dataset OpenML eval. You never manage the ensemble; the partner is cached in `~/.cache/huggingface/`.
75
+
76
+ | Recipe (chosen via `auto_duo=` flag) | cls mean acc | reg mean R² |
77
+ |---|:---:|:---:|
78
+ | Default `.predict()` (Duo + TTT under the hood) | **0.751** | **0.609** |
79
+ | `auto_duo=False` (Mini-only, zero-tuning) | 0.673 | 0.536 |
80
+ | `auto_duo=False` + `fit_and_predict_with_ttt()` (Mini-only TTT) | 0.742 | 0.595 |
81
+
82
+ **Edge cases:**
83
+
84
+ - **No internet / air-gapped.** Pass `auto_duo=False` at load to disable partner download — `.predict()` returns the single-model in-context result.
85
+ - **Want explicit Duo control** (custom `w`, `n_inner`, manual orchestration)? Use the explicit `duo_ttt_predict(mini, base, ...)` helper documented below.
86
+ - **Real-time inference** (<10 ms latency)? Use `auto_duo=False` zero-tuning. Duo + TTT adds ~1-60 s per query depending on table size.
87
+
88
+ **TTT** ([Test-Time Training](https://arxiv.org/abs/2503.11842), grounded in TabPFN-2.5's [recipe](https://arxiv.org/abs/2511.08667)) does ~15 inner Adam steps of self-supervised fine-tuning on the user's in-context examples before predicting. Per-task specialization on top of a generic ICL prior. 19 / 20 datasets improved vs zero-tuning; no dataset regressed by more than 0.006.
89
+
90
+ ### Advanced — explicit Duo + TTT (manual orchestration)
91
+
92
+ ```python
93
+ from predictlm import PredictLM, duo_ttt_predict
94
+
95
+ mini = PredictLM.from_pretrained("zerooneresearch/predictlm-mini-13m", auto_duo=False)
96
+ base = PredictLM.from_pretrained("zerooneresearch/predictlm-base-26m", auto_duo=False)
97
+ preds = duo_ttt_predict(mini, base, X_train, y_train, X_test, w=0.40, n_inner=15)
98
+ ```
99
+
100
+ Same numerical result as the default `.predict()`, but you control `w` (mini logit weight), `n_inner`, `lr`, etc.
101
+
102
+ ## Developers and affiliations
103
+
104
+ - **Developed by**: ZeroOne Research
105
+ - **Distilled from**: [predictlm-base-26m](https://huggingface.co/zerooneresearch/predictlm-base-26m) (v11.0)
106
+ - **Model card contact**: open an issue at the [code repo](https://github.com/zerooneresearch/predictlm-v11) or message the org on the Hub
107
+ - **License**: Apache 2.0 — permissive, commercial use allowed
108
+
109
+ ## Why Mini (when to prefer this over Base)
110
+
111
+ - **GPU memory budget < 8 GB at inference** �� Mini fits comfortably on a Tesla T4, RTX 3060, or M-series MPS
112
+ - **You want to re-distill / fine-tune yourself** — Mini's training recipe runs end-to-end on a single T4 in 3.3 hours for ~$1.30; Base requires an A100/H100
113
+ - **You want a smaller artifact to ship inside a product** — 55 MB inference weights vs Base's 105 MB
114
+ - **You're running many concurrent inference jobs** — 4× as many parallel Mini instances fit per GPU vs Base
115
+ - **You can tolerate ~4 pp lower regression R²** (CI [-6.5, -1.5]; cls accuracy is statistically tied with Base)
116
+
117
+ Prefer **Base** instead if you have an A100/H100, value the last ~4 pp of regression accuracy, and don't need to re-distill.
118
+
119
+ ## Performance benchmarks
120
+
121
+ ### Locked OpenML eval (held-out, contamination-audited)
122
+
123
+ Same 30-dataset stratified sample, seed=42, fair-set filter `n_features ≤ 128`, 4-way comparison. Same eval pipeline as Base (`scripts/eval_v11.py`).
124
+
125
+ | | reg-R² (n=13) | cls-acc (n=12) |
126
+ |---|:---:|:---:|
127
+ | predictlm-base-26m (teacher) | +0.589 | 0.685 |
128
+ | **predictlm-mini-13m (this model, 13.5M)** | **+0.551** | **0.684** |
129
+ | XGBoost (200 trees, depth 6) | +0.516 | 0.743 |
130
+ | TabPFN-2.5 (hosted, ~100M, non-commercial license) | +0.662 | 0.780 |
131
+ | TabICLv2 (open, BSD-3, ~50M) | *(cls-only)* | 0.792 |
132
+
133
+ ### Paired-bootstrap 95% CIs (10,000 resamples, seed=42)
134
+
135
+ Per-dataset deltas (predictlm-mini-13m minus baseline):
136
+
137
+ | comparison | mean Δ | 95% CI | n | significant? |
138
+ |---|:---:|:---:|:---:|:---:|
139
+ | **Mini vs Base (compression cost)** | | | | |
140
+ | Reg R² | **-0.038** | [-0.065, -0.015] | 13 | ✅ real (~4 pp loss) |
141
+ | Cls acc | **-0.001** | [-0.027, +0.029] | 12 | ✅ **statistical tie** |
142
+ | **vs other peers (Mini)** | | | | |
143
+ | Reg vs XGBoost | +0.035 | [-0.076, +0.158] | 13 | within noise |
144
+ | Reg vs TabPFN-2.5 | -0.111 | [-0.152, -0.067] | 13 | ✅ significant loss |
145
+ | Cls vs XGBoost | -0.059 | [-0.089, -0.031] | 12 | ✅ significant loss |
146
+ | Cls vs TabPFN-2.5 | -0.097 | [-0.132, -0.059] | 12 | ✅ significant loss |
147
+ | Cls vs TabICLv2 | -0.109 | [-0.147, -0.069] | 12 | ✅ significant loss |
148
+
149
+ **Retention vs Base — the headline compression story:**
150
+ - **Classification: statistical tie** with Base (delta -0.001, CI [-0.027, +0.029]). At half the parameters, Mini is indistinguishable from the 26M teacher on classification accuracy.
151
+ - **Regression: ~4 pp R² cost** vs Base, CI [-6.5, -1.5] (statistically real but small).
152
+
153
+ **Honest read on the peer comparisons.** Like Base, Mini's regression-vs-XGBoost point estimate is positive (+3.5 pp) but the 95% CI on this 13-dataset sample crosses zero. We can't claim a statistically significant XGBoost win on regression from this single-seed eval. What we *can* say: Mini and XGBoost are competitive on regression on this benchmark, with Mini's distribution being slightly better on most datasets.
154
+
155
+ **Significant losses (real, not noise):** loses to XGBoost on classification (-5.9 pp), and to TabPFN-2.5 / TabICLv2 on both axes — these are commercial / SOTA models 2-8× Mini's parameter count.
156
+
157
+ ### Model size vs accuracy
158
+
159
+ | model | params | params (%) | reg-R² | cls-acc |
160
+ |---|:---:|:---:|:---:|:---:|
161
+ | TabPFN-2.5 | ~100M | 740% | 0.662 | 0.780 |
162
+ | TabICLv2 | ~50M | 370% | — | 0.792 |
163
+ | **predictlm-base-26m** | 26M | 192% | 0.589 | 0.685 |
164
+ | **predictlm-mini-13m** | 13.5M | 100% (baseline) | 0.551 | 0.684 |
165
+
166
+ Mini is the smallest open-source ICL tabular FM in this comparison and the only one that trains on a single commodity GPU.
167
+
168
+ ## Architecture
169
+
170
+ Identical architecture family to PredictLM Base, with cross-layer parameter sharing (ALBERT-style) to halve the trunk parameter count.
171
+
172
+ | field | value |
173
+ |---|---|
174
+ | Parameters | 13.5 M |
175
+ | Layers (effective depth) | 12 (4 unique × 3 shares — ALBERT-style sharing in shared trunk; 2 unique × 2 shares per task head) |
176
+ | d_model | 256 |
177
+ | n_heads | 8 |
178
+ | max_features | 128 |
179
+ | max_classes | 10 |
180
+ | max_context | 1024 |
181
+ | max_query | 256 |
182
+ | Regression head | BarDistribution, 1024 bins (bins identical to Base — required for KL distillation) |
183
+ | Classification head | Per-task masked softmax |
184
+ | Attention | row-axis transformer (same as Base) |
185
+ | Inference precision | fp16 (T4-compatible — Base uses bf16 on A100/H100) |
186
+
187
+ Cross-layer sharing means Mini has 4 unique trunk blocks each applied 3 times during forward pass (vs Base's 8 unique blocks each applied once). The effective compute graph depth is preserved; only the parameter count is halved.
188
+
189
+ ## Training recipe (distillation from Base)
190
+
191
+ Mini was trained via **warm-start sliced distillation**: a novel recipe for compressing in-context-learning models that preserves real-data transfer ability.
192
+
193
+ **Three-stage recipe:**
194
+ 1. **Warm-start by slicing.** Copy every-Nth layer from the Base model (26M) into Mini's smaller unique-block list. Non-layer modules (feature embeddings, normalization, heads) copy verbatim. This initializes Mini at ~v11.0-half quality — student starts with the teacher's transfer ability already.
195
+ 2. **Distill via teacher logits.** Train Mini on synthetic SCM tasks using Base as a frozen teacher. Loss = 0.7 × KL(student || teacher, T=2) + 0.2 × hard-label CE + 0.1 × feature MSE. Online distillation with replay buffer.
196
+ 3. **30,000 training steps** with AdamW, cosine lr 3e-5 → 3e-6, fp16 mixed precision on a single Tesla T4.
197
+
198
+ The critical insight: distillation from scratch (Option A in our experiments) **failed to transfer to real OpenML data** — student matched teacher on synthetic but couldn't generalize. Warm-start sliced distillation (Option B, this release) succeeded because the student inherits the teacher's transfer ability as the starting point; distillation only needs to refine.
199
+
200
+ ### Compute
201
+
202
+ - **Hardware**: 1× Tesla T4 16GB (commodity)
203
+ - **Wall time**: 3.3 hours
204
+ - **Cost**: ~$1.30 at $0.40/hr spot
205
+ - **Carbon**: ~0.7 kg CO₂ (Azure EU-North grid)
206
+
207
+ Mini is the **cheapest tabular foundation model release on Hugging Face** by training cost as of 2026-05-14. Reproducible from scratch with `scripts/train_v11_06_tiny.py` in the code repo.
208
+
209
+ ## Intended use, limitations, ethical considerations
210
+
211
+ Identical to [predictlm-base-26m](https://huggingface.co/zerooneresearch/predictlm-base-26m) — see that model card for full details:
212
+
213
+ - **Intended**: drop-in tabular predictor for ≤128 features, ≤1024 training rows, ≤10 classes
214
+ - **Not intended**: high-stakes decisions without domain validation; wide tables (>128 features); many-class cls (>10); very large training sets (>10K rows); non-numeric features without encoding
215
+ - **No personal data in training**: distilled from Base, which was trained on synthetic priors + cleared real-data copulas. No raw eval-set rows seen.
216
+ - **Bias inheritance**: predictions reflect the labeled context the user supplies at inference time
217
+
218
+ The known weaknesses (cls below XGBoost; below TabPFN-2.5 / TabICLv2 on both axes) are inherited from Base; Mini does not amplify them but cannot fix them either. Closing the cls gap is targeted in v11.0.6 (Muon + QASSMax + mixed prior).
219
+
220
+ ## Reproducibility
221
+
222
+ - **Weights file**: `v11_06_tiny_final.pt` (inference-only, EMA-preferred state)
223
+ - **SHA-256**: `e27c8af6cda7a3426ffed33cb98eb8338966a8190712b5d37ff9e5f442b75a17`
224
+ - **Size**: 54.4 MB (inference-only, optimizer + curriculum + buffer + L2-SP state stripped from 217 MB raw)
225
+ - **Training step**: 30,000 (final)
226
+ - **Training seed**: 42
227
+ - **Teacher**: `predictlm-base-26m` (v11.0)
228
+ - **Distillation recipe**: warm-start slice + online KL distillation, see `scripts/train_v11_06_tiny.py`
229
+ - **Eval-lock manifest SHA-256**: `fe4da8cccfc78fc3c7746579f604154af7d37e525c4fd575965ba77ce4fe0841` (identical to Base)
230
+ - **Code**: pinned at the v11.0 release tag of [zerooneresearch/predictlm-v11](https://github.com/zerooneresearch/predictlm-v11)
231
+
232
+ To reproduce from scratch:
233
+
234
+ ```bash
235
+ # Pull the v11.0 teacher
236
+ huggingface-cli download zerooneresearch/predictlm-base-26m v11_final.pt --local-dir ./
237
+
238
+ # Reproduce Mini (single T4, ~3.3 hr, ~$1.30)
239
+ python3 scripts/train_v11_06_tiny.py \
240
+ --teacher-ckpt v11_final.pt \
241
+ --warm-start-from-v11 v11_final.pt \
242
+ --mlp-variant gelu --norm-variant layernorm --share-factor 2 \
243
+ --corpus-manifest data/v11_05_corpus_manifest.json \
244
+ --copula-dir data/copulas \
245
+ --steps 30000 --batch-size 1 --accum-steps 8 \
246
+ --lr 3e-5 --min-lr 3e-6 --warmup-steps 500 \
247
+ --n-context-max 256 --n-query-max 64 \
248
+ --device cuda --precision fp16 \
249
+ --probe-interval 2500 --probe-warmup-steps 0 --probe-floor 0.30 \
250
+ --out-dir runs/v11_06_tiny_reproduce --seed 42
251
+ ```
252
+
253
+ ## Licensing
254
+
255
+ Apache 2.0 — see [LICENSE](./LICENSE). Permissive, commercial use allowed.
256
+
257
+ The distillation recipe uses our own [predictlm-base-26m](https://huggingface.co/zerooneresearch/predictlm-base-26m) (Apache 2.0) as the teacher — no third-party license obligations propagate to this model. Mini is fully commercially usable.
258
+
259
+ ## Version
260
+
261
+ - **v11.0.6-tiny** (current) — first public release of the compact distilled variant.
262
+ - Sibling: [predictlm-base-26m](https://huggingface.co/zerooneresearch/predictlm-base-26m) (full-size, 26M)
263
+ - Future releases under the same `predictlm` Python package.
264
+
265
+ ## Citation
266
+
267
+ ### BibTeX
268
+
269
+ ```bibtex
270
+ @misc{predictlm_mini_2026,
271
+ author = {ZeroOne Research},
272
+ title = {predictlm-mini-13m: a compact distilled tabular foundation model for commodity hardware},
273
+ year = {2026},
274
+ publisher = {Hugging Face},
275
+ howpublished = {\url{https://huggingface.co/zerooneresearch/predictlm-mini-13m}}
276
+ }
277
+ ```
278
+
279
+ ### APA
280
+
281
+ ZeroOne Research. (2026). *predictlm-mini-13m: a compact distilled tabular foundation model for commodity hardware.* Hugging Face. https://huggingface.co/zerooneresearch/predictlm-mini-13m
predictlm_v11/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ predictlm_v11 — inference-only public API for the PredictLM tabular FM family.
3
+
4
+ Quick start:
5
+
6
+ from predictlm_v11 import PredictLM
7
+ model = PredictLM.from_pretrained("zerooneresearch/predictlm-mini-13m")
8
+
9
+ # Zero-tuning (fastest)
10
+ preds = model.fit(X_train, y_train).predict(X_test)
11
+
12
+ # Test-Time Training (TTT) — +0.07 cls / +0.06 reg over zero-tuning
13
+ preds = model.fit_and_predict_with_ttt(
14
+ X_train, y_train, X_test, n_inner=15, lr=1e-4)
15
+
16
+ # Full Duo + TTT recipe (Mini + Base ensemble, best results)
17
+ from predictlm_v11 import duo_ttt_predict
18
+ base = PredictLM.from_pretrained("zerooneresearch/predictlm-base-26m")
19
+ preds = duo_ttt_predict(model, base, X_train, y_train, X_test, w=0.40)
20
+
21
+ PredictLM auto-detects regression vs classification from y_train and routes
22
+ through the correct head. Same model, single fit/predict for both tasks.
23
+
24
+ The training stack (synthetic SCM, copula augmentation, curriculum, etc.)
25
+ is NOT shipped here — see https://github.com/zerooneresearch/predictlm-v11
26
+ for the full training repo.
27
+ """
28
+ from .inference import PredictLM, PredictLMOutput, duo_ttt_predict
29
+ from .model import PredictLMv11, V11Config
30
+
31
+ __all__ = ["PredictLM", "PredictLMOutput", "PredictLMv11", "V11Config",
32
+ "duo_ttt_predict"]
33
+ __version__ = "11.1.0"
predictlm_v11/heads.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ v11 prediction heads: bar-distribution regression + bin-based classification.
3
+
4
+ Both heads are ICL-friendly: they take trunk output [B, n_query, d_model]
5
+ and produce per-query predictions over a fixed-size output space (1024 bins
6
+ for regression, MAX_CLASSES=10 logits for classification).
7
+
8
+ ## Why bar-dist for regression
9
+ Verified in v10: a single-Gaussian (μ, log_σ²) head can collapse to a
10
+ constant when the trunk's output drifts (v9 failure mode). Bar-dist's
11
+ 1024-bin cross-entropy can't collapse — every bin is independently
12
+ supervised. Also matches TabPFN v2's reg head exactly.
13
+
14
+ ## Why bin-based for classification
15
+ v8/v10 used Linear(d_model, n_classes_max). For v11 we keep that structure
16
+ but add per-task masking: a task with n_classes=3 only computes CE over
17
+ the first 3 logits. This avoids the per-task linear-head trick used by
18
+ TabPFN (where the head is built from class prototypes inside each task)
19
+ which is harder to fit and gives no measurable gain at this scale per
20
+ Expert 4's pre-mortem on v11.
21
+
22
+ ## Trunk interface contract
23
+ The trunk returns one tensor per task type:
24
+ reg_out: [B, n_query, d_model] - last column, query rows, after reg trunk layers
25
+ cls_out: [B, n_query, d_model] - last column, query rows, after cls trunk layers
26
+
27
+ Both heads take this shape and produce per-query outputs.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import math
32
+ from typing import Optional
33
+
34
+ import torch
35
+ import torch.nn as nn
36
+ import torch.nn.functional as F
37
+
38
+
39
+ # Shared constants — keep aligned with task_sampler.SCMConfig.max_classes
40
+ MAX_CLASSES: int = 10
41
+
42
+
43
+ # ─── 1. bar-distribution regression head (proven in v10) ─────────────────────
44
+
45
+
46
+ def default_bin_edges(n_bins: int = 1024, tail: float = 0.0001) -> torch.Tensor:
47
+ """Quantile-based bin edges on N(0,1), symmetric around 0.
48
+
49
+ With n_bins=1024 + tail=0.0001, outer bins cover N⁻¹(0.0001) ≈ -3.72 to
50
+ N⁻¹(0.9999) ≈ +3.72 — wide enough to keep the heavy-tailed targets
51
+ that v11's `apply_heavy_tail_noise` extension is supposed to be
52
+ teaching from saturating the outermost bins. Earlier (tail=0.001)
53
+ capped at ±3.09, which forced ~0.5% of any heavy-tailed task's
54
+ targets into the outermost two bins (each ≈3σ wide) where CE has
55
+ no resolution.
56
+ """
57
+ probs = torch.linspace(tail, 1.0 - tail, n_bins + 1)
58
+ edges = math.sqrt(2) * torch.erfinv(2 * probs - 1)
59
+ return edges
60
+
61
+
62
+ class BarDistributionHead(nn.Module):
63
+ """
64
+ Bar-distribution (Riemann) regression head.
65
+
66
+ Forward: x [..., d_model] → logits [..., n_bins].
67
+ Loss is CE between predicted bin distribution and the bin containing
68
+ the (per-task standardized) target.
69
+ """
70
+
71
+ def __init__(
72
+ self,
73
+ d_model: int,
74
+ n_bins: int = 1024,
75
+ hidden_multiplier: int = 2,
76
+ dropout: float = 0.0,
77
+ bin_edges: Optional[torch.Tensor] = None,
78
+ ):
79
+ super().__init__()
80
+ self.d_model = d_model
81
+ self.n_bins = n_bins
82
+
83
+ if bin_edges is None:
84
+ bin_edges = default_bin_edges(n_bins)
85
+ assert bin_edges.shape == (n_bins + 1,)
86
+ self.register_buffer("bin_edges", bin_edges.float())
87
+ centers = 0.5 * (bin_edges[:-1] + bin_edges[1:])
88
+ self.register_buffer("bin_centers", centers.float())
89
+
90
+ hidden = d_model * hidden_multiplier
91
+ self.mlp = nn.Sequential(
92
+ nn.Linear(d_model, hidden),
93
+ nn.GELU(),
94
+ nn.Dropout(dropout) if dropout > 0 else nn.Identity(),
95
+ nn.Linear(hidden, n_bins),
96
+ )
97
+
98
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
99
+ return self.mlp(x)
100
+
101
+ def predict_bin_ids(self, y_standardized: torch.Tensor) -> torch.Tensor:
102
+ idx = torch.bucketize(y_standardized, self.bin_edges[1:-1].to(y_standardized.device))
103
+ return torch.clamp(idx, min=0, max=self.n_bins - 1)
104
+
105
+
106
+ def standardize_y_per_task(
107
+ y_ctx: torch.Tensor,
108
+ y_query: Optional[torch.Tensor] = None,
109
+ std_clip: float = 1e-3,
110
+ ):
111
+ """Per-task z-score using context-only stats, clipping std before division."""
112
+ assert y_ctx.dtype == torch.float32, "y must be float32 for stable z-scoring"
113
+ mean = y_ctx.mean(dim=-1, keepdim=True)
114
+ std = y_ctx.std(dim=-1, keepdim=True, unbiased=False)
115
+ std_clipped = torch.clamp(std, min=std_clip)
116
+ y_ctx_std = (y_ctx - mean) / std_clipped
117
+ y_q_std = None if y_query is None else (y_query - mean) / std_clipped
118
+ return y_ctx_std, y_q_std, mean.squeeze(-1), std_clipped.squeeze(-1)
119
+
120
+
121
+ def bar_distribution_loss(
122
+ logits: torch.Tensor,
123
+ y_standardized: torch.Tensor,
124
+ head: BarDistributionHead,
125
+ label_smoothing: float = 0.0,
126
+ row_mask: Optional[torch.Tensor] = None,
127
+ reduction: str = "mean",
128
+ ) -> torch.Tensor:
129
+ """Cross-entropy over n_bins with optional row-mask for padded query rows.
130
+
131
+ Args:
132
+ logits: [..., n_bins]
133
+ y_standardized: [...] standardized targets (per-task z-scored)
134
+ head: BarDistributionHead — needed for its bin structure
135
+ row_mask: optional bool mask, True = padded (excluded from loss)
136
+ reduction: "mean" returns a scalar; "none" returns per-task means [B]
137
+ """
138
+ bin_ids = head.predict_bin_ids(y_standardized)
139
+ flat_logits = logits.reshape(-1, head.n_bins)
140
+ flat_targets = bin_ids.reshape(-1)
141
+ per_token = F.cross_entropy(
142
+ flat_logits, flat_targets,
143
+ label_smoothing=label_smoothing,
144
+ reduction="none",
145
+ ).reshape(*y_standardized.shape)
146
+
147
+ if row_mask is not None:
148
+ keep = (~row_mask).float()
149
+ else:
150
+ keep = torch.ones_like(per_token)
151
+
152
+ if reduction == "none":
153
+ denom = keep.sum(dim=-1).clamp(min=1)
154
+ return (per_token * keep).sum(dim=-1) / denom
155
+ total = (per_token * keep).sum()
156
+ n = keep.sum().clamp(min=1)
157
+ return total / n
158
+
159
+
160
+ def decode_bar_distribution(
161
+ logits: torch.Tensor,
162
+ head: BarDistributionHead,
163
+ mode: str = "mean",
164
+ quantile: float = 0.5,
165
+ y_mean: Optional[torch.Tensor] = None,
166
+ y_std: Optional[torch.Tensor] = None,
167
+ ) -> torch.Tensor:
168
+ """Decode bar-dist logits to point predictions in original y space."""
169
+ probs = F.softmax(logits, dim=-1)
170
+ centers = head.bin_centers.to(logits.device)
171
+ if mode == "mean":
172
+ pred_std = (probs * centers).sum(dim=-1)
173
+ elif mode in ("median", "quantile"):
174
+ q = 0.5 if mode == "median" else quantile
175
+ cdf = probs.cumsum(dim=-1)
176
+ idx = torch.searchsorted(cdf, torch.full_like(cdf[..., :1], q)).squeeze(-1)
177
+ idx = torch.clamp(idx, 0, head.n_bins - 1)
178
+ pred_std = centers[idx]
179
+ else:
180
+ raise ValueError(f"Unknown mode: {mode}")
181
+ if y_mean is not None and y_std is not None:
182
+ if y_mean.dim() != pred_std.dim():
183
+ y_mean = y_mean.unsqueeze(-1)
184
+ y_std = y_std.unsqueeze(-1)
185
+ return pred_std * y_std + y_mean
186
+ return pred_std
187
+
188
+
189
+ def predict_variance(
190
+ logits: torch.Tensor,
191
+ head: BarDistributionHead,
192
+ y_std: Optional[torch.Tensor] = None,
193
+ ) -> torch.Tensor:
194
+ """Predictive variance from the bar distribution (for coverage / calibration)."""
195
+ probs = F.softmax(logits, dim=-1)
196
+ centers = head.bin_centers.to(logits.device)
197
+ mean = (probs * centers).sum(dim=-1, keepdim=True)
198
+ var_std = (probs * (centers - mean) ** 2).sum(dim=-1)
199
+ if y_std is not None:
200
+ if y_std.dim() != var_std.dim():
201
+ y_std = y_std.unsqueeze(-1)
202
+ return var_std * y_std * y_std
203
+ return var_std
204
+
205
+
206
+ # ─── 2. bin-based classification head (variable n_classes per task) ──────────
207
+
208
+
209
+ class BinClassificationHead(nn.Module):
210
+ """
211
+ Classification head that emits MAX_CLASSES logits; the trainer masks
212
+ out logits ≥ task.n_classes before computing CE.
213
+
214
+ Architecture: same 2-layer MLP as the bar-dist head, but output is
215
+ over MAX_CLASSES (default 10) instead of n_bins.
216
+
217
+ Forward: x [..., d_model] → logits [..., MAX_CLASSES].
218
+ """
219
+
220
+ def __init__(
221
+ self,
222
+ d_model: int,
223
+ max_classes: int = MAX_CLASSES,
224
+ hidden_multiplier: int = 2,
225
+ dropout: float = 0.0,
226
+ ):
227
+ super().__init__()
228
+ self.d_model = d_model
229
+ self.max_classes = max_classes
230
+
231
+ hidden = d_model * hidden_multiplier
232
+ self.mlp = nn.Sequential(
233
+ nn.Linear(d_model, hidden),
234
+ nn.GELU(),
235
+ nn.Dropout(dropout) if dropout > 0 else nn.Identity(),
236
+ nn.Linear(hidden, max_classes),
237
+ )
238
+
239
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
240
+ return self.mlp(x)
241
+
242
+
243
+ def cls_masked_loss(
244
+ logits: torch.Tensor,
245
+ y: torch.Tensor,
246
+ n_classes: torch.Tensor,
247
+ label_smoothing: float = 0.0,
248
+ row_mask: Optional[torch.Tensor] = None,
249
+ reduction: str = "mean",
250
+ ) -> torch.Tensor:
251
+ """
252
+ Cross-entropy with per-task masking of unused class logits.
253
+
254
+ Args:
255
+ logits: [B, n_query, MAX_CLASSES]
256
+ y: [B, n_query] integer labels in [0, n_classes_b)
257
+ n_classes: [B] integer count of valid classes per task in batch
258
+ label_smoothing: smoothing distributed ONLY across the valid class
259
+ range per task. Naive `F.cross_entropy(label_smoothing=ls)` over
260
+ logits-with-(-1e9)-on-invalid produces ls/C * 1e9 ≈ 5e6 per row
261
+ for invalid classes; here we smooth only over valid classes so
262
+ the invalid-class contribution is exactly zero.
263
+ row_mask: [B, n_query] bool, True = padded row to skip in loss
264
+ reduction: "mean" (scalar) or "none" (per-task tensor [B])
265
+
266
+ Each batch entry's unused logits are set to -inf so softmax respects
267
+ the per-task class count.
268
+ """
269
+ B, N, C = logits.shape
270
+ device = logits.device
271
+
272
+ # Per-class validity mask
273
+ arange_C = torch.arange(C, device=device)[None, :]
274
+ valid_mask = arange_C < n_classes[:, None] # [B, C]
275
+ valid_mask_full = valid_mask[:, None, :].expand(B, N, C) # [B, N, C]
276
+
277
+ # Mask invalid logits and compute log_softmax over valid range
278
+ masked_logits = logits.masked_fill(~valid_mask_full, float("-inf"))
279
+ log_probs = F.log_softmax(masked_logits, dim=-1) # [B, N, C]
280
+
281
+ y_long = y.long()
282
+ nll = -log_probs.gather(-1, y_long.unsqueeze(-1)).squeeze(-1) # [B, N]
283
+
284
+ if label_smoothing > 0:
285
+ # Smooth only across valid classes: target_dist[c valid] = (1-ls)*[c==y] + ls/n_valid
286
+ n_valid = n_classes.float().clamp(min=1)[:, None] # [B, 1]
287
+ # Smoothed loss = (1-ls) * NLL + ls * mean_over_valid_classes(-log_probs)
288
+ # mean of -log_probs over valid classes is what we want as the smoothing term
289
+ valid_count = valid_mask.sum(dim=-1, keepdim=True).clamp(min=1).float() # [B, 1]
290
+ # Sum log_probs over valid only (invalid rows have -inf, masked_fill them to 0
291
+ # for the sum so the smoothing term stays finite)
292
+ log_probs_valid_only = log_probs.masked_fill(~valid_mask_full, 0.0)
293
+ mean_neg_log = -log_probs_valid_only.sum(dim=-1) / valid_count # [B, N]
294
+ loss_per_row = (1.0 - label_smoothing) * nll + label_smoothing * mean_neg_log
295
+ else:
296
+ loss_per_row = nll
297
+
298
+ if row_mask is not None:
299
+ keep = (~row_mask).float()
300
+ else:
301
+ keep = torch.ones_like(loss_per_row)
302
+
303
+ if reduction == "none":
304
+ denom = keep.sum(dim=-1).clamp(min=1) # [B]
305
+ return (loss_per_row * keep).sum(dim=-1) / denom
306
+ # "mean"
307
+ total = (loss_per_row * keep).sum()
308
+ n = keep.sum().clamp(min=1)
309
+ return total / n
310
+
311
+
312
+ def cls_predict(
313
+ logits: torch.Tensor,
314
+ n_classes: torch.Tensor,
315
+ ) -> torch.Tensor:
316
+ """Argmax over the valid logit range per task. Returns [B, n_query]."""
317
+ B, N, C = logits.shape
318
+ device = logits.device
319
+ arange_C = torch.arange(C, device=device)[None, :]
320
+ valid_mask = arange_C < n_classes[:, None]
321
+ valid_mask_full = valid_mask[:, None, :].expand(B, N, C)
322
+ masked_logits = logits.masked_fill(~valid_mask_full, -1e9)
323
+ return masked_logits.argmax(dim=-1)
324
+
325
+
326
+ def cls_probs(
327
+ logits: torch.Tensor,
328
+ n_classes: torch.Tensor,
329
+ ) -> torch.Tensor:
330
+ """Softmax over the valid logit range per task. Invalid classes → 0 prob."""
331
+ B, N, C = logits.shape
332
+ device = logits.device
333
+ arange_C = torch.arange(C, device=device)[None, :]
334
+ valid_mask = arange_C < n_classes[:, None]
335
+ valid_mask_full = valid_mask[:, None, :].expand(B, N, C)
336
+ masked_logits = logits.masked_fill(~valid_mask_full, -1e9)
337
+ return F.softmax(masked_logits, dim=-1)
338
+
339
+
340
+ # ─── 3. self-test: shapes, masking, decoding all roundtrip ───────────────────
341
+
342
+
343
+ if __name__ == "__main__":
344
+ torch.manual_seed(0)
345
+
346
+ # Reg head smoke
347
+ head_r = BarDistributionHead(d_model=256, n_bins=1024)
348
+ trunk_out = torch.randn(2, 64, 256) # [B=2, n_query=64, d_model=256]
349
+ logits_r = head_r(trunk_out)
350
+ assert logits_r.shape == (2, 64, 1024)
351
+
352
+ y_ctx = torch.randn(2, 256) # [B, n_ctx]
353
+ y_q = torch.randn(2, 64)
354
+ y_ctx_s, y_q_s, mu, sigma = standardize_y_per_task(y_ctx, y_q)
355
+ assert y_ctx_s.shape == y_ctx.shape and y_q_s.shape == y_q.shape
356
+
357
+ loss_r = bar_distribution_loss(logits_r, y_q_s, head_r)
358
+ assert torch.isfinite(loss_r).item()
359
+ pred_mean = decode_bar_distribution(logits_r, head_r, mode="mean", y_mean=mu, y_std=sigma)
360
+ assert pred_mean.shape == (2, 64)
361
+
362
+ var_pred = predict_variance(logits_r, head_r, y_std=sigma)
363
+ assert var_pred.shape == (2, 64)
364
+ print(f"[reg] logits {tuple(logits_r.shape)} loss={loss_r.item():.4f} pred_mean[0,0]={pred_mean[0,0].item():+.3f}")
365
+
366
+ # Cls head smoke
367
+ head_c = BinClassificationHead(d_model=256, max_classes=10)
368
+ logits_c = head_c(trunk_out)
369
+ assert logits_c.shape == (2, 64, 10)
370
+
371
+ # Task 0: 3-class, Task 1: 7-class
372
+ n_classes = torch.tensor([3, 7])
373
+ y_c = torch.stack([
374
+ torch.randint(0, 3, (64,)),
375
+ torch.randint(0, 7, (64,)),
376
+ ])
377
+ loss_c = cls_masked_loss(logits_c, y_c, n_classes)
378
+ assert torch.isfinite(loss_c).item()
379
+ preds = cls_predict(logits_c, n_classes)
380
+ probs = cls_probs(logits_c, n_classes)
381
+ # Verify masking: invalid classes have 0 probability
382
+ assert (probs[0, :, 3:] == 0.0).all(), "task 0 should have 0 prob on classes >= 3"
383
+ assert (probs[1, :, 7:] == 0.0).all(), "task 1 should have 0 prob on classes >= 7"
384
+ # Verify predictions stay within valid range
385
+ assert (preds[0] < 3).all() and (preds[1] < 7).all()
386
+ # Verify softmax sums to 1 over valid logits
387
+ sums = probs.sum(dim=-1)
388
+ assert torch.allclose(sums, torch.ones_like(sums), atol=1e-5)
389
+ print(f"[cls] logits {tuple(logits_c.shape)} loss={loss_c.item():.4f} "
390
+ f"preds[0]={preds[0,:5].tolist()} preds[1]={preds[1,:5].tolist()}")
391
+
392
+ print("[OK] heads self-test passed")
predictlm_v11/inference.py ADDED
@@ -0,0 +1,856 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ v11 inference API — sklearn-style ergonomics for in-context learning.
3
+
4
+ This is the single front-door users see. Two ways to call it:
5
+
6
+ # sklearn-style (recommended for most users)
7
+ from predictlm_v11 import PredictLM
8
+ model = PredictLM.from_pretrained("path/to/v11_step250000.pt")
9
+ model.fit(X_train, y_train)
10
+ preds = model.predict(X_test) # reg → mean prediction; cls → argmax label
11
+ probs = model.predict_proba(X_test) # cls → softmax over valid classes
12
+
13
+ # one-shot ICL (no .fit() — pass context every call)
14
+ preds = model.predict_with_context(X_train, y_train, X_test)
15
+
16
+ Auto-detect:
17
+ - y dtype int / low-cardinality → classification
18
+ - y dtype float / high-cardinality → regression
19
+ Override with `task_type="regression"` or `"classification"` to fit().
20
+
21
+ Feature handling:
22
+ - n_features < max_features → padded with zeros + feature_mask
23
+ - n_features > max_features → truncated to first max_features columns
24
+
25
+ Designed to be the import target for HuggingFace Hub downloads. After
26
+ publishing the v11 weights, `from_pretrained("zerooneresearch/predictlm-v11")`
27
+ will fetch from the hub via `huggingface_hub`.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import sys
32
+ import types
33
+ from dataclasses import dataclass
34
+ from pathlib import Path
35
+ from typing import Optional, Union
36
+
37
+ import numpy as np
38
+ import torch
39
+
40
+ from .model import PredictLMv11, V11Config
41
+ from .heads import (
42
+ standardize_y_per_task,
43
+ decode_bar_distribution,
44
+ cls_predict,
45
+ cls_probs,
46
+ )
47
+
48
+
49
+ def _setup_v8_compat_stubs():
50
+ """Stub modules so v8/v11 ckpts that pickle classes can be loaded."""
51
+ for mod_name in [
52
+ "predictlm", "predictlm.config", "predictlm.tokenizer",
53
+ "predictlm.metadata", "predictlm.model_v8", "predictlm.synthetic",
54
+ "predictlm.synthetic_v2", "predictlm.categorical",
55
+ ]:
56
+ if mod_name not in sys.modules:
57
+ sys.modules[mod_name] = types.ModuleType(mod_name)
58
+
59
+ class _StubAny:
60
+ def __init__(self, *a, **kw):
61
+ self.__dict__.update(kw)
62
+ def __setstate__(self, state):
63
+ if isinstance(state, dict):
64
+ self.__dict__.update(state)
65
+ for attr in ("PredictLMConfig", "MEDIUM", "LARGE", "SMALL"):
66
+ sys.modules["predictlm.config"].__dict__[attr] = _StubAny
67
+
68
+
69
+ @dataclass
70
+ class PredictLMOutput:
71
+ """Convenience container for a single prediction call."""
72
+ predictions: np.ndarray # shape [n_query]; reg → float, cls → int label
73
+ probabilities: Optional[np.ndarray] = None # cls only: [n_query, n_classes]
74
+ task_type: str = "regression"
75
+ n_classes: int = 1
76
+
77
+
78
+ class PredictLM:
79
+ """
80
+ Unified in-context-learning model for tabular regression and classification.
81
+
82
+ Usage:
83
+ model = PredictLM.from_pretrained("path/to/checkpoint.pt")
84
+ model.fit(X_train, y_train)
85
+ preds = model.predict(X_test)
86
+
87
+ The model handles regression and classification in one architecture — the
88
+ task type is detected automatically from `y_train`'s dtype and cardinality.
89
+
90
+ Performance characteristics:
91
+ - Inference is ~10-50 ms per query batch on a single GPU (A100/H100)
92
+ - Context (X_train, y_train) is cached in memory; no per-query refetch
93
+ - For large `n_test`, calls are batched internally
94
+ """
95
+
96
+ DEFAULT_DTYPE = torch.float32
97
+ MAX_CONTEXT_ROWS = 1024
98
+ MAX_QUERY_ROWS_PER_BATCH = 256
99
+
100
+ # Auto-Duo: when a PredictLM is loaded from one of these HF repos, the
101
+ # default `.predict()` path silently downloads the partner repo (cached
102
+ # by huggingface_hub) and returns the published Duo+TTT recipe — the
103
+ # 0.751 cls / 0.609 reg result. Disable via `auto_duo=False` to get the
104
+ # raw single-model in-context prediction instead.
105
+ _PARTNER_REPOS = {
106
+ "zerooneresearch/predictlm-mini-13m": "zerooneresearch/predictlm-base-26m",
107
+ "zerooneresearch/predictlm-base-26m": "zerooneresearch/predictlm-mini-13m",
108
+ }
109
+
110
+ def __init__(self, model: PredictLMv11, cfg: V11Config, step: int = 0,
111
+ device: Optional[Union[str, torch.device]] = None,
112
+ auto_duo: bool = True):
113
+ self._model = model
114
+ self._cfg = cfg
115
+ self._step = step
116
+ if device is None:
117
+ device = "cuda" if torch.cuda.is_available() else (
118
+ "mps" if torch.backends.mps.is_available() else "cpu"
119
+ )
120
+ self._device = torch.device(device)
121
+ self._model.to(self._device).eval()
122
+ # Context cache (set by fit())
123
+ self._X_ctx: Optional[np.ndarray] = None
124
+ self._y_ctx: Optional[np.ndarray] = None
125
+ self._task_type: Optional[str] = None
126
+ self._n_classes: int = 1
127
+ self._class_label_map: Optional[dict] = None # for cls: original label → int
128
+ self._class_label_inv: Optional[dict] = None # for cls: int → original label
129
+ # Auto-Duo state: set by from_pretrained() when loaded from a known
130
+ # HF repo; raw cache populated by fit(); partner lazy-loaded on
131
+ # first predict() call.
132
+ self._auto_duo: bool = auto_duo
133
+ self._repo_id: Optional[str] = None
134
+ self._partner_cached: Optional["PredictLM"] = None
135
+ self._X_raw_cache: Optional[np.ndarray] = None
136
+ self._y_raw_cache: Optional[np.ndarray] = None
137
+
138
+ # ──────────────────────────────────────────────────────────────
139
+ # Loading
140
+ # ──────────────────────────────────────────────────────────────
141
+
142
+ @classmethod
143
+ def from_pretrained(
144
+ cls,
145
+ path: Union[str, Path],
146
+ device: Optional[Union[str, torch.device]] = None,
147
+ auto_duo: bool = True,
148
+ ) -> "PredictLM":
149
+ """
150
+ Load a v11 checkpoint. Path can be:
151
+ - Local file path: "/path/to/v11_step250000.pt"
152
+ - HuggingFace Hub repo: "zerooneresearch/predictlm-mini-13m"
153
+ "zerooneresearch/predictlm-base-26m"
154
+
155
+ `auto_duo` (default True): when loading from one of the published
156
+ HF repos, the default `.predict()` path silently downloads the
157
+ partner repo and returns the published Duo+TTT recipe (0.751 cls /
158
+ 0.609 reg). Set False to get raw single-model in-context inference.
159
+ """
160
+ _setup_v8_compat_stubs()
161
+
162
+ # Track the original HF repo id BEFORE we rewrite `path` to the
163
+ # downloaded local file. This lets the auto-Duo path know which
164
+ # partner ckpt to fetch on first .predict().
165
+ orig_repo_id: Optional[str] = None
166
+ if isinstance(path, str) and "/" in path and not Path(path).exists():
167
+ orig_repo_id = path
168
+ try:
169
+ from huggingface_hub import hf_hub_download
170
+ # Mini ships with v11_06_tiny_final.pt; Base ships with
171
+ # v11_final.pt. Try the Mini filename first; fall back to
172
+ # Base's so this loader works against either repo.
173
+ try:
174
+ path = hf_hub_download(
175
+ repo_id=orig_repo_id, filename="v11_06_tiny_final.pt"
176
+ )
177
+ except Exception:
178
+ path = hf_hub_download(
179
+ repo_id=orig_repo_id, filename="v11_final.pt"
180
+ )
181
+ except ImportError:
182
+ raise ImportError(
183
+ "To load from HuggingFace Hub, `pip install huggingface_hub`. "
184
+ "Or pass a local file path instead."
185
+ )
186
+
187
+ path = Path(path)
188
+ if not path.exists():
189
+ raise FileNotFoundError(f"Checkpoint not found: {path}")
190
+
191
+ payload = torch.load(path, map_location="cpu", weights_only=False)
192
+
193
+ if isinstance(payload, dict) and "cfg" in payload and "model" in payload:
194
+ # v11 native ckpt
195
+ cfg_dict = payload["cfg"]
196
+ cfg = V11Config(
197
+ d_model=cfg_dict.get("d_model", 256),
198
+ n_layers=cfg_dict.get("n_layers", 12),
199
+ n_heads=cfg_dict.get("n_heads", 8),
200
+ max_features=cfg_dict.get("max_features", 128),
201
+ max_classes=cfg_dict.get("max_classes", 10),
202
+ n_bins=cfg_dict.get("n_bins", 1024),
203
+ )
204
+ step = int(payload.get("step", 0))
205
+ # Prefer EMA weights for inference (better generalization)
206
+ state = payload.get("ema", payload["model"])
207
+ model = PredictLMv11(cfg)
208
+ model.load_state_dict(state, strict=False)
209
+ else:
210
+ raise ValueError(
211
+ "Checkpoint format not recognized. Expected v11 ckpt with "
212
+ "{'cfg': {...}, 'model': state_dict, 'ema': state_dict, ...}."
213
+ )
214
+
215
+ instance = cls(model, cfg, step=step, device=device, auto_duo=auto_duo)
216
+ instance._repo_id = orig_repo_id
217
+ return instance
218
+
219
+ @property
220
+ def step(self) -> int:
221
+ """Training step the loaded checkpoint was saved at."""
222
+ return self._step
223
+
224
+ @property
225
+ def cfg(self) -> V11Config:
226
+ """Model configuration."""
227
+ return self._cfg
228
+
229
+ @property
230
+ def device(self) -> torch.device:
231
+ return self._device
232
+
233
+ @property
234
+ def max_features(self) -> int:
235
+ return self._cfg.max_features
236
+
237
+ @property
238
+ def max_classes(self) -> int:
239
+ return self._cfg.max_classes
240
+
241
+ @property
242
+ def max_context(self) -> int:
243
+ return min(self._cfg.max_context, self.MAX_CONTEXT_ROWS)
244
+
245
+ # ──────────────────────────────────────────────────────────────
246
+ # Auto-detection helpers
247
+ # ──────────────────��───────────────────────────────────────────
248
+
249
+ @staticmethod
250
+ def _detect_task_type(y: np.ndarray, threshold: int = 10) -> str:
251
+ """Heuristic: int / string / few-unique-values → cls; numeric continuous → reg."""
252
+ y_arr = np.asarray(y)
253
+ # String / object labels are always classification
254
+ if y_arr.dtype.kind in ("U", "S", "O"):
255
+ return "classification"
256
+ # Bool / int dtypes are usually classification (rare exception: large-range int regression)
257
+ if y_arr.dtype.kind in ("i", "u", "b"):
258
+ n_unique = int(np.unique(y_arr).size)
259
+ return "classification" if n_unique <= threshold else "regression"
260
+ # Float: cls only if values are integer-valued AND have few unique values
261
+ valid = y_arr[~np.isnan(y_arr)]
262
+ n_unique = int(np.unique(valid).size)
263
+ if n_unique <= threshold and np.allclose(valid, np.round(valid)):
264
+ return "classification"
265
+ return "regression"
266
+
267
+ # ──────────────────────────────────────────────────────────────
268
+ # sklearn-style API
269
+ # ──────────────────────────────────────────────────────────────
270
+
271
+ def fit(
272
+ self,
273
+ X: np.ndarray,
274
+ y: np.ndarray,
275
+ task_type: str = "auto",
276
+ ) -> "PredictLM":
277
+ """
278
+ Cache training context for in-context learning.
279
+
280
+ Args:
281
+ X: [n_train, n_features] feature matrix (numeric only)
282
+ y: [n_train] labels — float for regression, int/string for cls
283
+ task_type: "auto", "regression", or "classification"
284
+ """
285
+ X_arr = np.ascontiguousarray(np.asarray(X, dtype=np.float32))
286
+ y_arr = np.asarray(y)
287
+
288
+ # Cache raw inputs so the auto-Duo path can re-pass them through
289
+ # both models' own fit() (each does its own standardization +
290
+ # label encoding). Cheap copies; sizes are at most ~1500 rows.
291
+ self._X_raw_cache = X_arr.copy()
292
+ self._y_raw_cache = np.asarray(y).copy()
293
+
294
+ if task_type == "auto":
295
+ task_type = self._detect_task_type(y_arr)
296
+ if task_type not in ("regression", "classification"):
297
+ raise ValueError(f"task_type must be 'auto', 'regression', or 'classification'")
298
+
299
+ # Encode cls labels to consecutive ints if needed
300
+ if task_type == "classification":
301
+ unique_labels = sorted(np.unique(y_arr).tolist(), key=lambda x: str(x))
302
+ n_classes = len(unique_labels)
303
+ if n_classes > self._cfg.max_classes:
304
+ raise ValueError(
305
+ f"Cls task has {n_classes} classes; model supports up to "
306
+ f"{self._cfg.max_classes}. Reduce class count or use a v12+ model."
307
+ )
308
+ self._class_label_map = {orig: i for i, orig in enumerate(unique_labels)}
309
+ self._class_label_inv = {i: orig for i, orig in enumerate(unique_labels)}
310
+ y_arr = np.array([self._class_label_map[v] for v in y_arr], dtype=np.int64)
311
+ self._n_classes = n_classes
312
+ else:
313
+ self._n_classes = 1
314
+ y_arr = y_arr.astype(np.float32)
315
+
316
+ # Standardize X (z-score per feature, fit-time only — query rows are
317
+ # standardized using fit-time stats to avoid distribution shift)
318
+ self._X_mean = X_arr.mean(axis=0, keepdims=True)
319
+ self._X_std = X_arr.std(axis=0, keepdims=True) + 1e-8
320
+ self._X_ctx = np.clip((X_arr - self._X_mean) / self._X_std, -10.0, 10.0)
321
+ self._y_ctx = y_arr
322
+ self._task_type = task_type
323
+ return self
324
+
325
+ def predict(self, X_test: np.ndarray) -> np.ndarray:
326
+ """Return point predictions for test rows.
327
+
328
+ Reg: returns float predictions (in original y scale).
329
+ Cls: returns the predicted class labels (in original label set).
330
+
331
+ When loaded from a published HF repo and `auto_duo=True` (default),
332
+ this transparently runs the Duo+TTT ship recipe (Mini + Base
333
+ ensemble with test-time training, 0.751 cls / 0.609 reg on the
334
+ locked 25-dataset OpenML eval). Set `auto_duo=False` at load time
335
+ to disable and get raw single-model in-context prediction.
336
+ """
337
+ if self._can_auto_duo():
338
+ return self._predict_auto_duo(X_test, return_probs=False)
339
+ out = self._predict_internal(X_test, return_probs=False)
340
+ return out.predictions
341
+
342
+ def predict_proba(self, X_test: np.ndarray) -> np.ndarray:
343
+ """For classification only: return [n_test, n_classes] probability matrix.
344
+
345
+ Class index ordering matches `self.classes_`. See `predict()` for
346
+ the auto-Duo behavior on HF-loaded models.
347
+ """
348
+ if self._task_type != "classification":
349
+ raise ValueError("predict_proba() is for classification tasks only.")
350
+ if self._can_auto_duo():
351
+ return self._predict_auto_duo(X_test, return_probs=True)
352
+ out = self._predict_internal(X_test, return_probs=True)
353
+ return out.probabilities
354
+
355
+ # ──────────────────────────────────────────────────────────────
356
+ # Auto-Duo: silently use the published Duo+TTT ship recipe on .predict()
357
+ # ──────────────────────────────────────────────────────────────
358
+
359
+ def _can_auto_duo(self) -> bool:
360
+ return (
361
+ self._auto_duo
362
+ and self._repo_id in self._PARTNER_REPOS
363
+ and self._X_raw_cache is not None
364
+ and self._y_raw_cache is not None
365
+ )
366
+
367
+ def _get_or_load_partner(self) -> "PredictLM":
368
+ """Lazy-load the partner ckpt from HF on first predict()."""
369
+ if self._partner_cached is None:
370
+ partner_repo = self._PARTNER_REPOS[self._repo_id]
371
+ # Load partner with auto_duo=False to prevent recursive Duo loops.
372
+ self._partner_cached = PredictLM.from_pretrained(
373
+ partner_repo, device=self._device, auto_duo=False
374
+ )
375
+ return self._partner_cached
376
+
377
+ def _predict_auto_duo(self, X_test: np.ndarray, return_probs: bool = False):
378
+ """Run the published Duo+TTT ship recipe under the hood."""
379
+ partner = self._get_or_load_partner()
380
+ # Figure out which is the Mini-side and which is the Base-side so
381
+ # `w` (Mini weight) lands on the right model. Reuses the module-
382
+ # level `duo_ttt_predict` to keep the recipe in one place.
383
+ if "mini" in (self._repo_id or ""):
384
+ mini, base = self, partner
385
+ else:
386
+ mini, base = partner, self
387
+ return duo_ttt_predict(
388
+ mini, base,
389
+ self._X_raw_cache, self._y_raw_cache, X_test,
390
+ return_probs=return_probs,
391
+ )
392
+
393
+ @property
394
+ def classes_(self) -> np.ndarray:
395
+ """sklearn-compatible: original class labels in canonical order."""
396
+ if self._task_type != "classification" or self._class_label_inv is None:
397
+ raise ValueError("classes_ is only defined after fit() on a cls task.")
398
+ return np.array([self._class_label_inv[i] for i in range(self._n_classes)])
399
+
400
+ # ──────────────────────────────────────────────────────────────
401
+ # Single-call form (skips .fit() — useful for benchmark loops)
402
+ # ──────────────────────────────────────────────────────────────
403
+
404
+ def predict_with_context(
405
+ self,
406
+ X_train: np.ndarray,
407
+ y_train: np.ndarray,
408
+ X_test: np.ndarray,
409
+ task_type: str = "auto",
410
+ return_probs: bool = False,
411
+ ) -> Union[np.ndarray, PredictLMOutput]:
412
+ """
413
+ One-shot ICL: predict on X_test using (X_train, y_train) as context,
414
+ without permanently modifying internal state.
415
+
416
+ Useful for benchmarking loops that iterate over many tasks.
417
+ """
418
+ # Save and restore state so we don't leak between calls
419
+ saved = (self._X_ctx, self._y_ctx, self._task_type, self._n_classes,
420
+ self._class_label_map, self._class_label_inv,
421
+ getattr(self, "_X_mean", None), getattr(self, "_X_std", None))
422
+ try:
423
+ self.fit(X_train, y_train, task_type=task_type)
424
+ if return_probs and self._task_type == "classification":
425
+ return self.predict_proba(X_test)
426
+ return self.predict(X_test)
427
+ finally:
428
+ (self._X_ctx, self._y_ctx, self._task_type, self._n_classes,
429
+ self._class_label_map, self._class_label_inv,
430
+ self._X_mean, self._X_std) = saved
431
+
432
+ # ──────────────────────────────────────────────────────────────
433
+ # Test-Time Training recipe (Real-TabPFN / TabPFN-2.5 style)
434
+ # ──────────────────────────────────────────────────────────────
435
+
436
+ def fit_and_predict_with_ttt(
437
+ self,
438
+ X_train: np.ndarray,
439
+ y_train: np.ndarray,
440
+ X_test: np.ndarray,
441
+ n_inner: int = 15,
442
+ lr: float = 1e-4,
443
+ inner_train_frac: float = 0.8,
444
+ task_type: str = "auto",
445
+ return_probs: bool = False,
446
+ grad_clip: float = 1.0,
447
+ ) -> Union[np.ndarray, PredictLMOutput]:
448
+ """Test-time training (TTT) inference: fine-tune the model on the
449
+ user-provided training set for `n_inner` inner Adam steps, then
450
+ predict on `X_test`. Model state is RESTORED after, so calling
451
+ this twice with different (X_train, y_train) does not leak.
452
+
453
+ Compared to plain `.fit().predict()`, TTT specializes the model
454
+ per task. On the locked 25-dataset OpenML eval, this lifts the
455
+ mean classification accuracy from 0.673 → 0.742 (Mini-v1) /
456
+ 0.685 → 0.748 (Base) with no other changes. See model card for
457
+ details.
458
+
459
+ Args:
460
+ X_train: [n_train, n_features] feature matrix (numeric only).
461
+ y_train: [n_train] labels — float for reg, int / str for cls.
462
+ X_test: [n_test, n_features] held-out features to predict on.
463
+ n_inner: Number of inner Adam steps (default 15). 15 is the
464
+ sweet spot for our 25-task benchmark; values 5-30 work.
465
+ lr: Inner Adam learning rate (default 1e-4 per TabPFN-2.5).
466
+ inner_train_frac: Fraction of X_train used as inner-context
467
+ during fine-tuning; the rest is inner-val
468
+ (the model is fit to predict inner-val from
469
+ inner-train). Default 0.8.
470
+ task_type: "auto", "regression", or "classification".
471
+ return_probs: Cls only — return softmax probs instead of labels.
472
+ grad_clip: Inner-step gradient clipping (default 1.0). Light
473
+ clip stabilizes TTT.
474
+
475
+ Returns:
476
+ Predictions in the same format as `.predict()`. Original
477
+ model state is restored before return.
478
+ """
479
+ import torch.nn.functional as F
480
+ from .heads import (
481
+ standardize_y_per_task, decode_bar_distribution, cls_predict,
482
+ bar_distribution_loss,
483
+ )
484
+
485
+ if n_inner <= 0:
486
+ # Degenerates to plain in-context inference
487
+ return self.predict_with_context(
488
+ X_train, y_train, X_test, task_type=task_type,
489
+ return_probs=return_probs)
490
+
491
+ # 1. Cache a snapshot of all trainable weights so we can restore.
492
+ orig_state = {
493
+ k: v.detach().clone()
494
+ for k, v in self._model.state_dict().items()
495
+ }
496
+
497
+ # 2. Set up the user context the same way `.fit` does (so X is
498
+ # standardized and y labels are encoded). We piggyback on
499
+ # self.fit() because it already does the bookkeeping.
500
+ saved = (self._X_ctx, self._y_ctx, self._task_type, self._n_classes,
501
+ self._class_label_map, self._class_label_inv,
502
+ getattr(self, "_X_mean", None), getattr(self, "_X_std", None))
503
+ self.fit(X_train, y_train, task_type=task_type)
504
+ X_ctx_full = self._X_ctx # already standardized
505
+ y_ctx_full = self._y_ctx # cls: int-encoded; reg: float
506
+ tt = self._task_type
507
+ n_cls = self._n_classes
508
+ n_train = len(X_ctx_full)
509
+ n_feat = min(X_ctx_full.shape[1], self._cfg.max_features)
510
+ X_ctx_full = X_ctx_full[:, :n_feat]
511
+
512
+ # 3. Set up inner optimizer (fresh each call; never carries state)
513
+ try:
514
+ optimizer = torch.optim.Adam(
515
+ [p for p in self._model.parameters() if p.requires_grad],
516
+ lr=lr,
517
+ )
518
+ rng = np.random.RandomState(123)
519
+ n_inner_ctx = min(int(inner_train_frac * n_train), 384)
520
+ n_inner_val = max(1, n_train - n_inner_ctx)
521
+
522
+ self._model.train()
523
+ for step in range(n_inner):
524
+ perm = rng.permutation(n_train)
525
+ idx_ctx = perm[:n_inner_ctx]
526
+ idx_val = perm[n_inner_ctx:n_inner_ctx + n_inner_val]
527
+ X_in_ctx = X_ctx_full[idx_ctx]
528
+ y_in_ctx = y_ctx_full[idx_ctx]
529
+ X_in_val = X_ctx_full[idx_val]
530
+ y_in_val = y_ctx_full[idx_val]
531
+
532
+ X_in_ctx_t = torch.from_numpy(X_in_ctx).float().unsqueeze(0).to(self._device)
533
+ X_in_val_t = torch.from_numpy(X_in_val).float().unsqueeze(0).to(self._device)
534
+ feat_mask = torch.zeros(1, n_feat, dtype=torch.bool, device=self._device)
535
+
536
+ if tt == "regression":
537
+ y_in_ctx_t = torch.from_numpy(y_in_ctx).float().unsqueeze(0).to(self._device)
538
+ y_in_val_t = torch.from_numpy(y_in_val).float().unsqueeze(0).to(self._device)
539
+ y_ctx_s, y_val_s, mu, sigma = standardize_y_per_task(
540
+ y_in_ctx_t.float(), y_in_val_t.float())
541
+ logits = self._model(X_in_ctx_t, y_ctx_s, X_in_val_t,
542
+ feat_mask, task_type="regression")
543
+ loss = bar_distribution_loss(logits, y_val_s,
544
+ self._model.reg_head)
545
+ else:
546
+ y_in_ctx_t = torch.from_numpy(
547
+ y_in_ctx.astype(np.int64)).long().unsqueeze(0).to(self._device)
548
+ y_in_val_t = torch.from_numpy(
549
+ y_in_val.astype(np.int64)).long().unsqueeze(0).to(self._device)
550
+ logits = self._model(X_in_ctx_t, y_in_ctx_t, X_in_val_t,
551
+ feat_mask, task_type="classification")
552
+ B, N, C = logits.shape
553
+ arange_C = torch.arange(C, device=self._device)[None, :]
554
+ valid = arange_C < n_cls
555
+ valid_full = valid[:, None, :].expand(B, N, C)
556
+ logits_m = logits.masked_fill(~valid_full, -1e9)
557
+ loss = F.cross_entropy(
558
+ logits_m.reshape(-1, C), y_in_val_t.reshape(-1))
559
+
560
+ if not torch.isfinite(loss):
561
+ optimizer.zero_grad(set_to_none=True)
562
+ continue
563
+ optimizer.zero_grad(set_to_none=True)
564
+ loss.backward()
565
+ torch.nn.utils.clip_grad_norm_(self._model.parameters(), grad_clip)
566
+ optimizer.step()
567
+
568
+ # 4. Predict on the actual test set using the fine-tuned weights
569
+ # with the FULL user-provided train as context.
570
+ self._model.eval()
571
+ out = self._predict_internal(X_test, return_probs=return_probs)
572
+ finally:
573
+ # 5. Restore original model weights AND the cached context state
574
+ self._model.load_state_dict(orig_state)
575
+ (self._X_ctx, self._y_ctx, self._task_type, self._n_classes,
576
+ self._class_label_map, self._class_label_inv,
577
+ self._X_mean, self._X_std) = saved
578
+
579
+ if return_probs and tt == "classification":
580
+ return out.probabilities
581
+ return out.predictions
582
+
583
+ # ──────────────────────────────────────────────────────────────
584
+ # Internals
585
+ # ──────────────────────────────────────────────────────────────
586
+
587
+ def _predict_internal(self, X_test: np.ndarray, return_probs: bool) -> PredictLMOutput:
588
+ if self._X_ctx is None:
589
+ raise RuntimeError("Call fit() before predict().")
590
+
591
+ X_test = np.ascontiguousarray(np.asarray(X_test, dtype=np.float32))
592
+ # Apply same standardization as fit-time (no leak)
593
+ X_test_z = np.clip((X_test - self._X_mean) / self._X_std, -10.0, 10.0)
594
+ n_test = X_test_z.shape[0]
595
+ n_features = X_test_z.shape[1]
596
+
597
+ # Truncate features beyond max_features (silent — can't avoid)
598
+ if n_features > self._cfg.max_features:
599
+ X_ctx_t = self._X_ctx[:, : self._cfg.max_features]
600
+ X_test_t = X_test_z[:, : self._cfg.max_features]
601
+ n_features = self._cfg.max_features
602
+ else:
603
+ X_ctx_t = self._X_ctx
604
+ X_test_t = X_test_z
605
+
606
+ # Cap context size (use the most recent rows if too many)
607
+ if X_ctx_t.shape[0] > self.max_context:
608
+ ctx_idx = np.random.RandomState(42).choice(
609
+ X_ctx_t.shape[0], self.max_context, replace=False,
610
+ )
611
+ X_ctx_use = X_ctx_t[ctx_idx]
612
+ y_ctx_use = self._y_ctx[ctx_idx]
613
+ else:
614
+ X_ctx_use = X_ctx_t
615
+ y_ctx_use = self._y_ctx
616
+
617
+ # Batch the queries to stay within VRAM
618
+ all_preds = []
619
+ all_probs = [] if return_probs else None
620
+ for q_start in range(0, n_test, self.MAX_QUERY_ROWS_PER_BATCH):
621
+ q_end = min(q_start + self.MAX_QUERY_ROWS_PER_BATCH, n_test)
622
+ X_q = X_test_t[q_start:q_end]
623
+ preds, probs = self._predict_batch(X_ctx_use, y_ctx_use, X_q, return_probs)
624
+ all_preds.append(preds)
625
+ if return_probs:
626
+ all_probs.append(probs)
627
+
628
+ preds_arr = np.concatenate(all_preds, axis=0)
629
+ probs_arr = np.concatenate(all_probs, axis=0) if return_probs else None
630
+
631
+ # Map cls predictions back to original labels
632
+ if self._task_type == "classification" and self._class_label_inv is not None:
633
+ preds_arr = np.array(
634
+ [self._class_label_inv[int(p)] for p in preds_arr],
635
+ dtype=object if not all(
636
+ isinstance(v, (int, np.integer)) for v in self._class_label_inv.values()
637
+ ) else None,
638
+ )
639
+
640
+ return PredictLMOutput(
641
+ predictions=preds_arr,
642
+ probabilities=probs_arr,
643
+ task_type=self._task_type or "regression",
644
+ n_classes=self._n_classes,
645
+ )
646
+
647
+ @torch.no_grad()
648
+ def _predict_batch(
649
+ self,
650
+ X_ctx: np.ndarray,
651
+ y_ctx: np.ndarray,
652
+ X_q: np.ndarray,
653
+ return_probs: bool,
654
+ ):
655
+ device = self._device
656
+ X_ctx_t = torch.from_numpy(X_ctx).float().unsqueeze(0).to(device)
657
+ X_q_t = torch.from_numpy(X_q).float().unsqueeze(0).to(device)
658
+ if self._task_type == "regression":
659
+ y_ctx_t = torch.from_numpy(y_ctx).float().unsqueeze(0).to(device)
660
+ else:
661
+ y_ctx_t = torch.from_numpy(y_ctx.astype(np.int64)).long().unsqueeze(0).to(device)
662
+
663
+ feat_mask = torch.zeros(1, X_ctx_t.shape[-1], dtype=torch.bool, device=device)
664
+
665
+ if self._task_type == "regression":
666
+ y_ctx_s, _, mu, sigma = standardize_y_per_task(y_ctx_t.float())
667
+ logits = self._model(X_ctx_t, y_ctx_s, X_q_t, feat_mask, task_type="regression")
668
+ preds = decode_bar_distribution(
669
+ logits, self._model.reg_head, mode="mean", y_mean=mu, y_std=sigma,
670
+ ).squeeze(0).cpu().numpy()
671
+ return preds, None
672
+ else:
673
+ logits = self._model(X_ctx_t, y_ctx_t, X_q_t, feat_mask, task_type="classification")
674
+ n_classes_t = torch.tensor([self._n_classes], dtype=torch.int64, device=device)
675
+ if return_probs:
676
+ probs = cls_probs(logits, n_classes_t).squeeze(0)[:, : self._n_classes].cpu().numpy()
677
+ preds = probs.argmax(axis=-1)
678
+ return preds, probs
679
+ else:
680
+ preds = cls_predict(logits, n_classes_t).squeeze(0).cpu().numpy()
681
+ return preds, None
682
+
683
+ # ──────────────────────────────────────────────────────────────
684
+ # Diagnostics
685
+ # ──────────────────────────────────────────────────────────────
686
+
687
+ def __repr__(self) -> str:
688
+ ctx = "no context" if self._X_ctx is None else (
689
+ f"{self._X_ctx.shape[0]} ctx rows × {self._X_ctx.shape[1]} features, "
690
+ f"task={self._task_type}, n_classes={self._n_classes}"
691
+ )
692
+ return (
693
+ f"PredictLM(d_model={self._cfg.d_model}, n_layers={self._cfg.n_layers}, "
694
+ f"max_features={self._cfg.max_features}, max_classes={self._cfg.max_classes}, "
695
+ f"step={self._step}, device={self._device}, {ctx})"
696
+ )
697
+
698
+
699
+ # ─── Duo + TTT recipe (Mini + Base ensemble) ────────────────────────────────
700
+
701
+
702
+ def duo_ttt_predict(
703
+ mini: "PredictLM",
704
+ base: "PredictLM",
705
+ X_train: np.ndarray,
706
+ y_train: np.ndarray,
707
+ X_test: np.ndarray,
708
+ w: Optional[float] = None,
709
+ n_inner: int = 15,
710
+ lr: float = 1e-4,
711
+ task_type: str = "auto",
712
+ return_probs: bool = False,
713
+ ) -> np.ndarray:
714
+ """The published PredictLM v1 ship recipe: Duo (Mini + Base) + TTT.
715
+
716
+ For each task:
717
+ 1. TTT-finetune Mini on (X_train, y_train) → softmax probs on X_test.
718
+ 2. TTT-finetune Base on (X_train, y_train) → softmax probs on X_test.
719
+ 3. Ensemble: p = w * p_mini + (1 - w) * p_base.
720
+
721
+ Defaults: w = 0.40 for classification, 0.25 for regression (these were
722
+ the optima on our locked 25-dataset OpenML eval; pass `w` explicitly
723
+ to override). On that benchmark this recipe hits **0.751 mean cls
724
+ accuracy / 0.609 mean reg R²** — a +7.8 / +7.3 percentage-point lift
725
+ over zero-tuning Mini-v1 alone.
726
+
727
+ Args:
728
+ mini: A `PredictLM` instance loaded from `predictlm-mini-13m`.
729
+ base: A `PredictLM` instance loaded from `predictlm-base-26m`.
730
+ X_train, y_train, X_test: standard sklearn-style table inputs.
731
+ w: Mini logit weight. None → 0.40 (cls) or 0.25 (reg). Pass a
732
+ float to override.
733
+ n_inner, lr: passed to TTT inner loop (defaults 15, 1e-4).
734
+ task_type: "auto" (default), "regression", or "classification".
735
+ return_probs: classification only — return softmax probs.
736
+
737
+ Returns:
738
+ Predictions (or probs) in the same shape as `mini.predict(X_test)`.
739
+ Both models' internal weights are restored to their pre-call state.
740
+ """
741
+ # Determine task type from y_train if "auto" (use mini's detector;
742
+ # both models share the same _detect_task_type implementation).
743
+ if task_type == "auto":
744
+ task_type = mini._detect_task_type(np.asarray(y_train))
745
+
746
+ if w is None:
747
+ w = 0.40 if task_type == "classification" else 0.25
748
+ if not (0.0 <= w <= 1.0):
749
+ raise ValueError(f"w must be in [0, 1]; got {w}")
750
+
751
+ # Get probs from each TTT-finetuned model. We re-use the public
752
+ # `fit_and_predict_with_ttt(... return_probs=True)` API to keep state
753
+ # save/restore in one place. For regression, `return_probs=True`
754
+ # returns the predicted point estimates (the ensemble is over those —
755
+ # a softmax-over-bins ensemble of two different bar-dist heads is
756
+ # less clean than averaging the decoded means).
757
+ if task_type == "classification":
758
+ p_mini = mini.fit_and_predict_with_ttt(
759
+ X_train, y_train, X_test, n_inner=n_inner, lr=lr,
760
+ task_type=task_type, return_probs=True)
761
+ p_base = base.fit_and_predict_with_ttt(
762
+ X_train, y_train, X_test, n_inner=n_inner, lr=lr,
763
+ task_type=task_type, return_probs=True)
764
+ p_ens = w * p_mini + (1.0 - w) * p_base
765
+ if return_probs:
766
+ return p_ens
767
+ preds_int = p_ens.argmax(axis=-1)
768
+ # Decode back to original cls labels via Mini's label map
769
+ # (both models' fit() encoded the SAME y_train → same map).
770
+ if mini._class_label_inv is not None:
771
+ return np.array([mini._class_label_inv[int(i)] for i in preds_int])
772
+ return preds_int
773
+ else:
774
+ # Regression: average decoded point predictions (in original y scale)
775
+ y_mini = mini.fit_and_predict_with_ttt(
776
+ X_train, y_train, X_test, n_inner=n_inner, lr=lr,
777
+ task_type=task_type)
778
+ y_base = base.fit_and_predict_with_ttt(
779
+ X_train, y_train, X_test, n_inner=n_inner, lr=lr,
780
+ task_type=task_type)
781
+ return w * y_mini + (1.0 - w) * y_base
782
+
783
+
784
+ # ─── helpers ─────────────────────────────────────────────────────────────────
785
+
786
+
787
+ def _pd_isnull_mask(y_arr: np.ndarray) -> np.ndarray:
788
+ """NaN-mask for object/non-numeric arrays."""
789
+ if y_arr.dtype.kind in ("i", "u", "b"):
790
+ return np.zeros(y_arr.shape, dtype=bool)
791
+ if y_arr.dtype.kind == "O":
792
+ return np.array([v is None or (isinstance(v, float) and np.isnan(v)) for v in y_arr])
793
+ return np.isnan(y_arr.astype(float))
794
+
795
+
796
+ # ─── self-test ───────────────────────────────────────────────────────────────
797
+
798
+
799
+ if __name__ == "__main__":
800
+ import tempfile, os, sys as _sys
801
+
802
+ # Build a fresh untrained model for the smoke test (real users load_pretrained)
803
+ cfg = V11Config(d_model=64, n_layers=4, n_heads=4, n_bins=256, max_features=32)
804
+ model = PredictLMv11(cfg)
805
+ # Save as v11-format ckpt
806
+ with tempfile.NamedTemporaryFile(suffix=".pt", delete=False) as f:
807
+ torch.save({
808
+ "step": 0, "cfg": vars(cfg),
809
+ "model": model.state_dict(),
810
+ "ema": model.state_dict(),
811
+ }, f.name)
812
+ ckpt_path = f.name
813
+
814
+ print(f"Loading {ckpt_path}...")
815
+ pl = PredictLM.from_pretrained(ckpt_path, device="cpu")
816
+ print(pl)
817
+
818
+ rng = np.random.default_rng(0)
819
+
820
+ # ─── reg ─────────────────────────────────────────────────────────────
821
+ n_train, n_test, n_feat = 100, 20, 8
822
+ X_tr = rng.normal(size=(n_train, n_feat)).astype(np.float32)
823
+ y_tr = (X_tr[:, 0] - 0.5 * X_tr[:, 1] + 0.1 * rng.normal(size=n_train)).astype(np.float32)
824
+ X_te = rng.normal(size=(n_test, n_feat)).astype(np.float32)
825
+
826
+ pl.fit(X_tr, y_tr) # auto-detects regression
827
+ print(f"\nReg fit: {pl}")
828
+ preds = pl.predict(X_te)
829
+ print(f" reg preds shape: {preds.shape}, dtype: {preds.dtype}")
830
+ print(f" first 3: {preds[:3]}")
831
+
832
+ # ─── cls ─────────────────────────────────────────────────────────────
833
+ y_tr_cls = (rng.normal(size=n_train) > 0).astype(np.int64)
834
+ pl.fit(X_tr, y_tr_cls) # auto-detects classification
835
+ print(f"\nCls fit: {pl}")
836
+ preds_cls = pl.predict(X_te)
837
+ probs = pl.predict_proba(X_te)
838
+ print(f" cls preds: {preds_cls[:5]}, probs shape: {probs.shape}")
839
+ print(f" classes_: {pl.classes_}")
840
+
841
+ # ─── multi-class with string labels ─────────────────────────────────
842
+ labels = np.array(["red", "green", "blue"])[
843
+ rng.integers(0, 3, size=n_train)
844
+ ]
845
+ pl.fit(X_tr, labels)
846
+ print(f"\nMulti-cls (string labels) fit: {pl}")
847
+ preds_str = pl.predict(X_te)
848
+ print(f" preds: {preds_str[:5]}, classes_: {pl.classes_}")
849
+
850
+ # ─── one-shot form ──────────────────────────────────────────────────
851
+ one_shot = pl.predict_with_context(X_tr, y_tr, X_te)
852
+ print(f"\nOne-shot reg preds: {one_shot[:3]}")
853
+
854
+ # cleanup
855
+ os.unlink(ckpt_path)
856
+ print("\n[OK] inference API self-test passed")
predictlm_v11/model.py ADDED
@@ -0,0 +1,743 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ v11 model — same trunk as v8 so we can warm-start from v8's final checkpoint.
3
+ The architecture differences vs v8 are the prediction heads:
4
+
5
+ v8: reg_head = Linear(d_model, 2) # mean, log_var
6
+ v8: cls_head = Linear(d_model, max_classes)
7
+ v11: reg_head = BarDistributionHead(d_model, n_bins=1024)
8
+ v11: cls_head = BinClassificationHead(d_model, max_classes=10)
9
+
10
+ Everything else (feature_weights, y_embed, class_embed, type_embed,
11
+ shared_layers, reg_layers, cls_layers, *_norm) keeps the same module
12
+ names and parameter shapes, so:
13
+
14
+ v11_model.load_state_dict(v8_ckpt, strict=False)
15
+
16
+ will load the trunk and leave only the heads as randomly-initialized.
17
+ The v11 trainer's head-warmup phase trains only the heads + reg_norm /
18
+ cls_norm for the first 5k steps, exactly as v10 did.
19
+
20
+ Tokenization is identical to v8: 2D grid [B, n_rows, n_cols, d_model]
21
+ with one token per cell. Each layer alternates feature-attention (within
22
+ a row) and datapoint-attention (within a column with the
23
+ context-vs-query mask).
24
+
25
+ For now, v11 SKIPS v8's metadata conditioning (the column-statistics
26
+ encoder). The v11 plan defers architectural cleanups to v13; the goal
27
+ here is data-prior work, not arch work. Once warm-started, the
28
+ metadata-related parameters in the v8 ckpt are simply ignored.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import math
33
+ from dataclasses import dataclass
34
+ from typing import Optional
35
+
36
+ import torch
37
+ import torch.nn as nn
38
+ import torch.nn.functional as F
39
+ from torch.utils.checkpoint import checkpoint as grad_checkpoint
40
+
41
+ from .heads import (
42
+ BarDistributionHead,
43
+ BinClassificationHead,
44
+ bar_distribution_loss,
45
+ cls_masked_loss,
46
+ standardize_y_per_task,
47
+ decode_bar_distribution,
48
+ cls_predict,
49
+ )
50
+
51
+
52
+ # ─── config ──────────────────────────────────────────────────────────────────
53
+
54
+
55
+ @dataclass
56
+ class V11Config:
57
+ d_model: int = 256
58
+ n_layers: int = 12 # 8 shared + 4 task-specific per branch
59
+ n_heads: int = 8
60
+ d_ffn: int = 1024
61
+ dropout: float = 0.0
62
+
63
+ max_features: int = 128 # warm-start slices v8's feature_weights[500] → [128] in warm_start_from_v8
64
+ max_classes: int = 10
65
+ max_context: int = 1024
66
+ max_query: int = 256
67
+
68
+ n_periodic_freqs: int = 8
69
+
70
+ n_bins: int = 1024
71
+ cls_label_smoothing: float = 0.05
72
+
73
+ # v11.0.6-tiny architecture toggles. Defaults preserve v11.0 behavior so
74
+ # existing ckpts load unchanged via warm_start_from_v8 / strict=False.
75
+ mlp_variant: str = "gelu" # "gelu" (legacy) or "swiglu"
76
+ norm_variant: str = "layernorm" # "layernorm" (legacy) or "rmsnorm"
77
+ # ALBERT-style cross-layer parameter sharing. share_factor>1 means the
78
+ # `n_layers`-deep stack uses only `n_layers // share_factor` UNIQUE
79
+ # modules; each unique block is applied `share_factor` times via index
80
+ # cycling. share_factor=1 = legacy (no sharing).
81
+ share_factor: int = 1
82
+
83
+
84
+ def v11_default_config() -> V11Config:
85
+ return V11Config()
86
+
87
+
88
+ # ─── v11.0.6-tiny blocks (drop-in upgrades behind config flag) ──────────────
89
+
90
+
91
+ class SwiGLUFFN(nn.Module):
92
+ """SwiGLU MLP (Shazeer 2020, arXiv 2002.05202). Default in PaLM/LLaMA.
93
+
94
+ Pattern: Linear(d, 8d/3) gate + Linear(d, 8d/3) value, silu*gate, Linear(8d/3, d).
95
+ Hidden dim scaled to (8/3)d_ffn/4 = (2/3)d_ffn to hold param count constant
96
+ vs the legacy GELU FFN (Linear(d, d_ffn), GELU, Linear(d_ffn, d)).
97
+ """
98
+ def __init__(self, d_model: int, d_ffn: int):
99
+ super().__init__()
100
+ # Match legacy FFN's parameter count: legacy is 2 * d_model * d_ffn.
101
+ # SwiGLU is 3 linears (gate, value, out), each d_model * d_hidden.
102
+ # So set d_hidden = (2/3) * d_ffn for parity.
103
+ d_hidden = int(round(d_ffn * 2 / 3))
104
+ self.w_gate = nn.Linear(d_model, d_hidden, bias=False)
105
+ self.w_value = nn.Linear(d_model, d_hidden, bias=False)
106
+ self.w_out = nn.Linear(d_hidden, d_model, bias=False)
107
+
108
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
109
+ return self.w_out(F.silu(self.w_gate(x)) * self.w_value(x))
110
+
111
+
112
+ class RMSNorm(nn.Module):
113
+ """Root Mean Square Layer Norm (Zhang & Sennrich 2019). LLaMA default.
114
+
115
+ No mean subtraction, no learned bias. Cheaper than LayerNorm; works as
116
+ a drop-in for transformer pre-norm.
117
+ """
118
+ def __init__(self, d_model: int, eps: float = 1e-6):
119
+ super().__init__()
120
+ self.weight = nn.Parameter(torch.ones(d_model))
121
+ self.eps = eps
122
+
123
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
124
+ return self.weight * (x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps))
125
+
126
+
127
+ def _build_ffn(d_model: int, d_ffn: int, variant: str = "gelu") -> nn.Module:
128
+ """Factory: return GELU MLP (legacy) or SwiGLU MLP based on variant."""
129
+ if variant == "swiglu":
130
+ return SwiGLUFFN(d_model, d_ffn)
131
+ return nn.Sequential(
132
+ nn.Linear(d_model, d_ffn),
133
+ nn.GELU(),
134
+ nn.Linear(d_ffn, d_model),
135
+ )
136
+
137
+
138
+ def _build_norm(d_model: int, variant: str = "layernorm") -> nn.Module:
139
+ """Factory: return LayerNorm (legacy) or RMSNorm based on variant."""
140
+ if variant == "rmsnorm":
141
+ return RMSNorm(d_model)
142
+ return nn.LayerNorm(d_model)
143
+
144
+
145
+ # ─── blocks (verbatim from v8 so state_dict keys match) ───────────────────────
146
+
147
+
148
+ class FlashPreLNAttention(nn.Module):
149
+ """Pre-LN attention + FFN using F.scaled_dot_product_attention (Flash)."""
150
+
151
+ def __init__(self, d_model: int, n_heads: int, d_ffn: int, dropout: float = 0.0,
152
+ mlp_variant: str = "gelu", norm_variant: str = "layernorm"):
153
+ super().__init__()
154
+ self.n_heads = n_heads
155
+ self.head_dim = d_model // n_heads
156
+ self.d_model = d_model
157
+
158
+ self.norm1 = _build_norm(d_model, norm_variant)
159
+ self.q_proj = nn.Linear(d_model, d_model)
160
+ self.k_proj = nn.Linear(d_model, d_model)
161
+ self.v_proj = nn.Linear(d_model, d_model)
162
+ self.o_proj = nn.Linear(d_model, d_model)
163
+
164
+ self.norm2 = _build_norm(d_model, norm_variant)
165
+ self.ffn = _build_ffn(d_model, d_ffn, mlp_variant)
166
+
167
+ def _heads(self, x: torch.Tensor) -> torch.Tensor:
168
+ B, S, _ = x.shape
169
+ return x.view(B, S, self.n_heads, self.head_dim).transpose(1, 2)
170
+
171
+ def forward(
172
+ self,
173
+ x: torch.Tensor,
174
+ key_padding_mask: Optional[torch.Tensor] = None,
175
+ attn_mask: Optional[torch.Tensor] = None,
176
+ ) -> torch.Tensor:
177
+ residual = x
178
+ x = self.norm1(x)
179
+ q = self._heads(self.q_proj(x))
180
+ k = self._heads(self.k_proj(x))
181
+ v = self._heads(self.v_proj(x))
182
+
183
+ sdpa_mask = None
184
+ if attn_mask is not None:
185
+ # attn_mask may be 2D [seq, seq] (shared across batch) or 3D [B, seq, seq]
186
+ if attn_mask.dim() == 2:
187
+ amask = torch.zeros_like(attn_mask, dtype=q.dtype)
188
+ amask.masked_fill_(attn_mask, float("-inf"))
189
+ sdpa_mask = amask.unsqueeze(0).unsqueeze(0) # [1,1,seq,seq]
190
+ else:
191
+ amask = torch.zeros_like(attn_mask, dtype=q.dtype)
192
+ amask.masked_fill_(attn_mask, float("-inf"))
193
+ sdpa_mask = amask.unsqueeze(1) # [B,1,seq,seq]
194
+ if key_padding_mask is not None:
195
+ pad_mask = torch.zeros(
196
+ key_padding_mask.shape[0], 1, 1, key_padding_mask.shape[1],
197
+ dtype=q.dtype, device=q.device,
198
+ )
199
+ pad_mask.masked_fill_(key_padding_mask.unsqueeze(1).unsqueeze(2), float("-inf"))
200
+ sdpa_mask = pad_mask if sdpa_mask is None else sdpa_mask + pad_mask
201
+
202
+ attn_out = F.scaled_dot_product_attention(q, k, v, attn_mask=sdpa_mask, dropout_p=0.0)
203
+ attn_out = attn_out.transpose(1, 2).contiguous().view(x.shape[0], x.shape[1], self.d_model)
204
+ x = self.o_proj(attn_out) + residual
205
+
206
+ residual = x
207
+ x = self.norm2(x)
208
+ x = self.ffn(x) + residual
209
+ return x
210
+
211
+
212
+ class AlternatingLayerV8(nn.Module):
213
+ """Feature attention (within rows) → Datapoint attention (within cols).
214
+
215
+ Name matches v8 verbatim so state_dict keys align for warm-start.
216
+ """
217
+
218
+ def __init__(self, d_model: int, n_heads: int, d_ffn: int, dropout: float = 0.0,
219
+ mlp_variant: str = "gelu", norm_variant: str = "layernorm"):
220
+ super().__init__()
221
+ self.feature_attn = FlashPreLNAttention(d_model, n_heads, d_ffn, dropout,
222
+ mlp_variant=mlp_variant, norm_variant=norm_variant)
223
+ self.datapoint_attn = FlashPreLNAttention(d_model, n_heads, d_ffn, dropout,
224
+ mlp_variant=mlp_variant, norm_variant=norm_variant)
225
+
226
+ def forward(
227
+ self,
228
+ x: torch.Tensor, # [B, n_rows, n_cols, d_model]
229
+ feature_pad_mask: torch.Tensor,
230
+ datapoint_mask: torch.Tensor, # [n_rows, n_rows] OR [B, n_rows, n_rows]
231
+ ) -> torch.Tensor:
232
+ B, n_rows, n_cols, d_model = x.shape
233
+ # within-row feature attn
234
+ x_feat = x.reshape(B * n_rows, n_cols, d_model)
235
+ feat_pad = feature_pad_mask.unsqueeze(1).expand(B, n_rows, n_cols).reshape(B * n_rows, n_cols)
236
+ x_feat = self.feature_attn(x_feat, key_padding_mask=feat_pad)
237
+ x = x_feat.reshape(B, n_rows, n_cols, d_model)
238
+ # within-col datapoint attn — expand per-batch mask along n_cols if needed
239
+ x_data = x.permute(0, 2, 1, 3).reshape(B * n_cols, n_rows, d_model)
240
+ if datapoint_mask.dim() == 3:
241
+ # [B, n_rows, n_rows] → [B*n_cols, n_rows, n_rows]
242
+ dp_mask = (
243
+ datapoint_mask.unsqueeze(1)
244
+ .expand(B, n_cols, n_rows, n_rows)
245
+ .reshape(B * n_cols, n_rows, n_rows)
246
+ )
247
+ else:
248
+ dp_mask = datapoint_mask
249
+ x_data = self.datapoint_attn(x_data, attn_mask=dp_mask)
250
+ x = x_data.reshape(B, n_cols, n_rows, d_model).permute(0, 2, 1, 3)
251
+ return x
252
+
253
+
254
+ # ─── numerical-value embedding (matches v8's NumericalFeatureEmbedding) ──────
255
+
256
+
257
+ class NumericalFeatureEmbedding(nn.Module):
258
+ """Embed a scalar numerical value into a d_model vector via Fourier features."""
259
+
260
+ def __init__(self, d_model: int = 256, n_freqs: int = 8):
261
+ super().__init__()
262
+ self.d_model = d_model
263
+ self.n_freqs = n_freqs
264
+ freqs = 2.0 ** torch.arange(n_freqs, dtype=torch.float32)
265
+ self.register_buffer("freqs", freqs)
266
+ in_dim = 1 + 1 + 2 * n_freqs # sign + log_mag + sin/cos at each freq
267
+ self.mlp = nn.Sequential(
268
+ nn.Linear(in_dim, d_model),
269
+ nn.GELU(),
270
+ nn.Linear(d_model, d_model),
271
+ )
272
+ self.missing_token = nn.Parameter(torch.randn(d_model) * 0.02)
273
+
274
+ def forward(self, values: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
275
+ sign = torch.sign(values)
276
+ log_mag = torch.log1p(torch.abs(values))
277
+ # Sinusoidal features at multiple frequencies
278
+ f = self.freqs.to(values.device).view(*([1] * (values.dim() - 1)), self.n_freqs)
279
+ scaled = values.unsqueeze(-1) * f
280
+ sins = torch.sin(scaled)
281
+ coss = torch.cos(scaled)
282
+ feats = torch.cat([sign.unsqueeze(-1), log_mag.unsqueeze(-1), sins, coss], dim=-1)
283
+ emb = self.mlp(feats)
284
+ if mask is not None:
285
+ emb = torch.where(mask.unsqueeze(-1), self.missing_token.expand_as(emb), emb)
286
+ return emb
287
+
288
+
289
+ # ─── main v11 model ──────────────────────────────────────────────────────────
290
+
291
+
292
+ @dataclass
293
+ class V11Output:
294
+ """Single forward pass output."""
295
+ reg_logits: Optional[torch.Tensor] = None # [B, n_query, n_bins] for reg
296
+ cls_logits: Optional[torch.Tensor] = None # [B, n_query, max_classes] for cls
297
+ y_mean: Optional[torch.Tensor] = None # [B] context y mean (reg only)
298
+ y_std: Optional[torch.Tensor] = None # [B] context y std (reg only)
299
+
300
+
301
+ class PredictLMv11(nn.Module):
302
+ """
303
+ v11 model: same trunk as v8, new heads.
304
+
305
+ Forward returns either reg_logits (for regression) or cls_logits (for
306
+ classification). For mixed-batch joint training, the trainer should
307
+ call the model twice — once with task_type='regression' and once with
308
+ task_type='classification' — sharing the trunk pass via gradient
309
+ accumulation. (Per-batch-element task_type would require padding to
310
+ a max-class shape and we keep it simple.)
311
+
312
+ State-dict keys match v8's PredictLMv8 exactly EXCEPT:
313
+ - reg_head (Linear → BarDistributionHead.mlp)
314
+ - cls_head (Linear → BinClassificationHead.mlp)
315
+ All other keys load via load_state_dict(strict=False).
316
+ """
317
+
318
+ def __init__(self, cfg: V11Config = None):
319
+ super().__init__()
320
+ cfg = cfg or v11_default_config()
321
+ self.cfg = cfg
322
+ # Toggle gradient checkpointing. Default True (memory-conservative,
323
+ # for H100/T4 sized batches). On A100 80GB we can disable for ~2-3×
324
+ # throughput when memory permits. Set via `model.use_grad_checkpoint = False`.
325
+ self.use_grad_checkpoint = True
326
+
327
+ # Per-feature projection (same as v8)
328
+ self.feature_weights = nn.Parameter(torch.randn(cfg.max_features, cfg.d_model) * 0.02)
329
+ self.feature_biases = nn.Parameter(torch.zeros(cfg.max_features, cfg.d_model))
330
+
331
+ # y embeddings
332
+ self.y_embed = NumericalFeatureEmbedding(cfg.d_model, n_freqs=cfg.n_periodic_freqs)
333
+ self.class_embed = nn.Embedding(cfg.max_classes, cfg.d_model)
334
+ nn.init.normal_(self.class_embed.weight, std=0.02)
335
+
336
+ # tokens
337
+ self.query_token = nn.Parameter(torch.randn(cfg.d_model) * 0.02)
338
+ self.type_embed = nn.Embedding(2, cfg.d_model)
339
+ nn.init.normal_(self.type_embed.weight, std=0.02)
340
+ self.col_type_embed = nn.Embedding(2, cfg.d_model)
341
+ nn.init.normal_(self.col_type_embed.weight, std=0.02)
342
+
343
+ # trunk: 8 shared + 4 reg + 4 cls
344
+ # v11.0.6-tiny: variant flags flow through to FFN/norm choice; defaults
345
+ # preserve v11.0 layout for backward-compat with existing ckpts.
346
+ mv = getattr(cfg, "mlp_variant", "gelu")
347
+ nv = getattr(cfg, "norm_variant", "layernorm")
348
+ share = max(1, int(getattr(cfg, "share_factor", 1)))
349
+ _layer = lambda: AlternatingLayerV8(
350
+ cfg.d_model, cfg.n_heads, cfg.d_ffn, cfg.dropout,
351
+ mlp_variant=mv, norm_variant=nv,
352
+ )
353
+ n_shared = cfg.n_layers - 4
354
+ # Under share_factor>1, build only n//share unique blocks; the
355
+ # forward pass cycles through them. n_shared and n_branch (=4) must
356
+ # both be divisible by share_factor.
357
+ if n_shared % share != 0 or 4 % share != 0:
358
+ raise ValueError(
359
+ f"share_factor={share} must divide both n_shared={n_shared} and 4 (branch layers)"
360
+ )
361
+ n_shared_unique = n_shared // share
362
+ n_branch_unique = 4 // share
363
+ self.shared_layers = nn.ModuleList([_layer() for _ in range(n_shared_unique)])
364
+ self.reg_layers = nn.ModuleList([_layer() for _ in range(n_branch_unique)])
365
+ self.cls_layers = nn.ModuleList([_layer() for _ in range(n_branch_unique)])
366
+ self.shared_norm = _build_norm(cfg.d_model, nv)
367
+ self.reg_norm = _build_norm(cfg.d_model, nv)
368
+ self.cls_norm = _build_norm(cfg.d_model, nv)
369
+ # Stored for forward to know how many depth-passes to do.
370
+ self.effective_n_shared = n_shared
371
+ self.effective_n_branch = 4
372
+
373
+ # v11 heads
374
+ self.reg_head = BarDistributionHead(
375
+ d_model=cfg.d_model, n_bins=cfg.n_bins, dropout=cfg.dropout,
376
+ )
377
+ self.cls_head = BinClassificationHead(
378
+ d_model=cfg.d_model, max_classes=cfg.max_classes, dropout=cfg.dropout,
379
+ )
380
+
381
+ # NOTE: v8's `log_var_reg` / `log_var_cls` Kendall-style task weights
382
+ # are intentionally NOT instantiated here. They were declared but
383
+ # never read in the v11 trainer, and ratio-balancing reg/cls via
384
+ # alternation + curriculum bias is sufficient at this scale per
385
+ # Expert 4. If they appear in a v8 checkpoint, `warm_start_from_v8`
386
+ # filters them out via `strict=False` (they land in `unexpected_keys`).
387
+ self._init_weights()
388
+
389
+ def _init_weights(self):
390
+ for m in self.modules():
391
+ if isinstance(m, nn.Linear):
392
+ nn.init.xavier_uniform_(m.weight)
393
+ if m.bias is not None:
394
+ nn.init.zeros_(m.bias)
395
+
396
+ # ──────────────────────────────────────────────────────────────
397
+ # Internal: build the [B, n_rows, n_cols, d_model] grid
398
+ # ──────────────────────────────────────────────────────────────
399
+ def _build_grid(
400
+ self,
401
+ X_ctx: torch.Tensor, # [B, n_ctx, n_features]
402
+ y_ctx: torch.Tensor, # [B, n_ctx]
403
+ X_query: torch.Tensor, # [B, n_query, n_features]
404
+ feature_mask: torch.Tensor, # [B, n_features] bool, True=padded
405
+ task_type: str,
406
+ ctx_row_mask: Optional[torch.Tensor] = None, # [B, n_ctx] bool, True=padded
407
+ query_row_mask: Optional[torch.Tensor] = None, # [B, n_query] bool, True=padded
408
+ ):
409
+ B, n_ctx, n_features = X_ctx.shape
410
+ n_query = X_query.shape[1]
411
+ n_rows = n_ctx + n_query
412
+ max_f = self.cfg.max_features
413
+ device = X_ctx.device
414
+
415
+ # Effective feature count
416
+ if feature_mask.any():
417
+ real_per_item = (~feature_mask).sum(dim=1)
418
+ n_real = min(int(real_per_item.max().item()), max_f)
419
+ else:
420
+ n_real = min(n_features, max_f)
421
+ n_real = max(n_real, 2)
422
+ n_cols = n_real + 1
423
+
424
+ X_all = torch.cat([X_ctx, X_query], dim=1) # [B, n_rows, n_features]
425
+ X_real = X_all[:, :, :n_real] # [B, n_rows, n_real]
426
+
427
+ # Per-feature projection
428
+ feat_grid = (
429
+ X_real.unsqueeze(-1) * self.feature_weights[:n_real]
430
+ + self.feature_biases[:n_real]
431
+ ) # [B, n_rows, n_real, d_model]
432
+
433
+ # Target column embedding
434
+ if task_type == "classification":
435
+ y_clamped = y_ctx.long().clamp(0, self.cfg.max_classes - 1)
436
+ y_emb_ctx = self.class_embed(y_clamped) # [B, n_ctx, d_model]
437
+ else:
438
+ y_emb_ctx = self.y_embed(y_ctx.float()) # [B, n_ctx, d_model]
439
+
440
+ y_emb_q = self.query_token.unsqueeze(0).unsqueeze(0).expand(B, n_query, -1)
441
+ y_emb = torch.cat([y_emb_ctx, y_emb_q], dim=1).unsqueeze(2) # [B, n_rows, 1, d_model]
442
+
443
+ grid = torch.cat([feat_grid, y_emb], dim=2) # [B, n_rows, n_cols, d_model]
444
+
445
+ # Type (ctx vs query) and column-type (feature vs target) embeds
446
+ type_ids = torch.zeros(B, n_rows, dtype=torch.long, device=device)
447
+ type_ids[:, n_ctx:] = 1
448
+ grid = grid + self.type_embed(type_ids).unsqueeze(2)
449
+
450
+ col_types = torch.zeros(n_cols, dtype=torch.long, device=device)
451
+ col_types[-1] = 1
452
+ grid = grid + self.col_type_embed(col_types).unsqueeze(0).unsqueeze(0)
453
+
454
+ # Feature-pad mask
455
+ feature_pad_mask = torch.zeros(B, n_cols, dtype=torch.bool, device=device)
456
+ if feature_mask.shape[1] >= n_real:
457
+ feature_pad_mask[:, :n_real] = feature_mask[:, :n_real]
458
+
459
+ # Datapoint mask: query rows can't attend to other query rows (they each
460
+ # predict independently). If ctx_row_mask / query_row_mask are provided,
461
+ # padded rows are also blocked from being keys (per-batch [B, n_rows, n_rows]).
462
+ # Without row-pad masks, build the simple [n_rows, n_rows] shared mask.
463
+ if ctx_row_mask is None and query_row_mask is None:
464
+ datapoint_mask = torch.zeros(n_rows, n_rows, dtype=torch.bool, device=device)
465
+ datapoint_mask[n_ctx:, n_ctx:] = True
466
+ for i in range(n_query):
467
+ datapoint_mask[n_ctx + i, n_ctx + i] = False
468
+ else:
469
+ row_pad = torch.zeros(B, n_rows, dtype=torch.bool, device=device)
470
+ if ctx_row_mask is not None:
471
+ row_pad[:, :n_ctx] = ctx_row_mask
472
+ if query_row_mask is not None:
473
+ row_pad[:, n_ctx:] = query_row_mask
474
+ # base [n_rows, n_rows] block-mask: query↔query disallowed except diag
475
+ base = torch.zeros(n_rows, n_rows, dtype=torch.bool, device=device)
476
+ base[n_ctx:, n_ctx:] = True
477
+ for i in range(n_query):
478
+ base[n_ctx + i, n_ctx + i] = False
479
+ base = base.unsqueeze(0).expand(B, n_rows, n_rows).clone()
480
+ # block any KEY row that is padded (broadcast over queries)
481
+ base = base | row_pad.unsqueeze(1).expand(B, n_rows, n_rows)
482
+ datapoint_mask = base
483
+
484
+ return grid, feature_pad_mask, datapoint_mask, n_ctx
485
+
486
+ # ──────────────────────────────────────────────────────────────
487
+ # Forward
488
+ # ──────────────────────────────────────────────────────────────
489
+ def forward(
490
+ self,
491
+ X_ctx: torch.Tensor,
492
+ y_ctx: torch.Tensor,
493
+ X_query: torch.Tensor,
494
+ feature_mask: torch.Tensor,
495
+ task_type: str = "regression",
496
+ ctx_row_mask: Optional[torch.Tensor] = None,
497
+ query_row_mask: Optional[torch.Tensor] = None,
498
+ ) -> torch.Tensor:
499
+ """Returns logits over bins (reg) or classes (cls).
500
+
501
+ For regression, the trainer is responsible for calling
502
+ `standardize_y_per_task(y_ctx_orig)` BEFORE this forward to obtain
503
+ the standardized y_ctx (and stash mean/std for un-standardization).
504
+
505
+ Optional ctx_row_mask / query_row_mask (bool, True=padded row)
506
+ block padded rows from attention as keys, preventing
507
+ zero-padded fake-context contamination.
508
+ """
509
+ grid, feat_pad, dp_mask, n_ctx = self._build_grid(
510
+ X_ctx, y_ctx, X_query, feature_mask, task_type,
511
+ ctx_row_mask=ctx_row_mask, query_row_mask=query_row_mask,
512
+ )
513
+
514
+ # Shared trunk. Under share_factor>1, len(self.shared_layers) may be
515
+ # < effective_n_shared; cycle via modulo index (ALBERT pattern).
516
+ n_uniq_shared = len(self.shared_layers)
517
+ for i in range(self.effective_n_shared):
518
+ layer = self.shared_layers[i % n_uniq_shared]
519
+ if self.training and torch.is_grad_enabled() and self.use_grad_checkpoint:
520
+ grid = grad_checkpoint(layer, grid, feat_pad, dp_mask, use_reentrant=False)
521
+ else:
522
+ grid = layer(grid, feat_pad, dp_mask)
523
+ grid = self.shared_norm(grid)
524
+
525
+ # Task-specific layers
526
+ if task_type == "regression":
527
+ h = grid
528
+ n_uniq_branch = len(self.reg_layers)
529
+ for i in range(self.effective_n_branch):
530
+ layer = self.reg_layers[i % n_uniq_branch]
531
+ if self.training and torch.is_grad_enabled() and self.use_grad_checkpoint:
532
+ h = grad_checkpoint(layer, h, feat_pad, dp_mask, use_reentrant=False)
533
+ else:
534
+ h = layer(h, feat_pad, dp_mask)
535
+ h = self.reg_norm(h)
536
+ query_target = h[:, n_ctx:, -1, :] # [B, n_query, d_model]
537
+ return self.reg_head(query_target) # [B, n_query, n_bins]
538
+
539
+ # classification — symmetric grad flow with reg path. Earlier
540
+ # versions had `h = 0.5*grid + 0.5*grid.detach()` here, which
541
+ # halved the cls branch's gradient into the shared trunk while
542
+ # the reg branch passed full gradient. Combined with bar-dist
543
+ # reg loss being ~3× larger by magnitude than cls (ln(1024) vs
544
+ # ln(10)) and 50/50 step alternation, the trunk was receiving
545
+ # ~6× more reg signal than cls signal per step. Removed.
546
+ h = grid
547
+ n_uniq_branch = len(self.cls_layers)
548
+ for i in range(self.effective_n_branch):
549
+ layer = self.cls_layers[i % n_uniq_branch]
550
+ if self.training and torch.is_grad_enabled() and self.use_grad_checkpoint:
551
+ h = grad_checkpoint(layer, h, feat_pad, dp_mask, use_reentrant=False)
552
+ else:
553
+ h = layer(h, feat_pad, dp_mask)
554
+ h = self.cls_norm(h)
555
+ query_target = h[:, n_ctx:, -1, :]
556
+ return self.cls_head(query_target) # [B, n_query, max_classes]
557
+
558
+ # ──────────────────────────────────────────────────────────────
559
+ # Convenience: warm-start from v8 checkpoint
560
+ # ──────────────────────────────────────────────────────────────
561
+ @torch.no_grad()
562
+ def warm_start_from_v8(self, v8_state_dict: dict, verbose: bool = True) -> dict:
563
+ """Load v8 trunk weights, leave heads at random init.
564
+
565
+ Args:
566
+ v8_state_dict: a v8 checkpoint's state_dict
567
+ Returns:
568
+ dict with `loaded`, `missing`, `unexpected` key counts
569
+ """
570
+ # Filter out v8's old reg_head / cls_head (shape-incompatible) and
571
+ # the dead log_var weights (removed in v11).
572
+ skip_prefixes = ("reg_head.", "cls_head.", "log_var_reg", "log_var_cls")
573
+ filtered = {
574
+ k: v for k, v in v8_state_dict.items()
575
+ if not k.startswith(skip_prefixes)
576
+ }
577
+ # Slice feature_weights / feature_biases if v8 ckpt has more features
578
+ # than v11's max_features (v8 used 500, v11 default 128 for VRAM).
579
+ # Keep the first N rows (v8 trained on tasks that primarily used the
580
+ # earliest column slots).
581
+ target_max = self.cfg.max_features
582
+ for k in ("feature_weights", "feature_biases"):
583
+ if k in filtered and filtered[k].shape[0] > target_max:
584
+ filtered[k] = filtered[k][:target_max]
585
+ result = self.load_state_dict(filtered, strict=False)
586
+ if verbose:
587
+ print(f"[v11.warm_start_from_v8] loaded {len(filtered)} keys")
588
+ if result.missing_keys:
589
+ print(f" missing ({len(result.missing_keys)}): {result.missing_keys[:5]}…")
590
+ if result.unexpected_keys:
591
+ print(f" unexpected ({len(result.unexpected_keys)}): {result.unexpected_keys[:5]}…")
592
+ return {
593
+ "loaded": len(filtered),
594
+ "missing": len(result.missing_keys),
595
+ "unexpected": len(result.unexpected_keys),
596
+ }
597
+
598
+
599
+ @torch.no_grad()
600
+ def warm_start_slice_from_v11(self, v11_state_dict: dict, verbose: bool = True) -> dict:
601
+ """Initialize this (smaller) model from a v11.0 ckpt by SLICING layers.
602
+
603
+ Used when this model has `share_factor > 1`: the v11.0 trunk has
604
+ `n_layers` unique blocks, but this model has only `n_layers /
605
+ share_factor` unique blocks (each used `share_factor` times via
606
+ cycling). We copy every-`share_factor`-th v11.0 block into the
607
+ student's unique-blocks list.
608
+
609
+ Non-layer modules (feature_weights, y_embed, class_embed, query_token,
610
+ col_type_embed, shared_norm/reg_norm/cls_norm, reg_head, cls_head)
611
+ copy verbatim — they're share-factor-independent.
612
+
613
+ Requires this model use legacy (gelu + layernorm) MLP/norm variants
614
+ for the layer slicing to be shape-compatible.
615
+ """
616
+ if self.cfg.mlp_variant != "gelu" or self.cfg.norm_variant != "layernorm":
617
+ raise ValueError(
618
+ "warm_start_slice_from_v11 requires mlp_variant=gelu, "
619
+ "norm_variant=layernorm for shape compatibility with v11.0 ckpt. "
620
+ f"Got mlp_variant={self.cfg.mlp_variant}, norm_variant={self.cfg.norm_variant}."
621
+ )
622
+ share = max(1, int(self.cfg.share_factor))
623
+
624
+ # Build the source→target index map for layer slicing.
625
+ # v11.0 trunk: 8 shared + 4 reg + 4 cls
626
+ v11_n_shared = self.cfg.n_layers - 4 # 8 typically
627
+ v11_n_branch = 4
628
+ # Student unique counts
629
+ s_n_shared = v11_n_shared // share
630
+ s_n_branch = v11_n_branch // share
631
+ # Pick every share-th index from v11.0
632
+ shared_src = list(range(0, v11_n_shared, share))[:s_n_shared]
633
+ branch_src = list(range(0, v11_n_branch, share))[:s_n_branch]
634
+
635
+ new_state = {}
636
+ layer_keys_copied = 0
637
+ non_layer_keys_copied = 0
638
+
639
+ for k, v in v11_state_dict.items():
640
+ # Layer-keyed weights: rewrite the layer index per the slicing map.
641
+ if k.startswith("shared_layers."):
642
+ # k = "shared_layers.<idx>.<rest>"
643
+ parts = k.split(".", 2)
644
+ src_idx = int(parts[1])
645
+ if src_idx in shared_src:
646
+ tgt_idx = shared_src.index(src_idx)
647
+ new_state[f"shared_layers.{tgt_idx}.{parts[2]}"] = v
648
+ layer_keys_copied += 1
649
+ elif k.startswith("reg_layers."):
650
+ parts = k.split(".", 2)
651
+ src_idx = int(parts[1])
652
+ if src_idx in branch_src:
653
+ tgt_idx = branch_src.index(src_idx)
654
+ new_state[f"reg_layers.{tgt_idx}.{parts[2]}"] = v
655
+ layer_keys_copied += 1
656
+ elif k.startswith("cls_layers."):
657
+ parts = k.split(".", 2)
658
+ src_idx = int(parts[1])
659
+ if src_idx in branch_src:
660
+ tgt_idx = branch_src.index(src_idx)
661
+ new_state[f"cls_layers.{tgt_idx}.{parts[2]}"] = v
662
+ layer_keys_copied += 1
663
+ else:
664
+ # Non-layer weights copy verbatim.
665
+ new_state[k] = v
666
+ non_layer_keys_copied += 1
667
+
668
+ result = self.load_state_dict(new_state, strict=False)
669
+ param_names = {n for n, _ in self.named_parameters()}
670
+ missing_params = [k for k in result.missing_keys if k in param_names]
671
+
672
+ if verbose:
673
+ print(f"[v11.warm_start_slice] share_factor={share}, slice indices: "
674
+ f"shared={shared_src}, branch={branch_src}")
675
+ print(f" copied {layer_keys_copied} layer-keys + {non_layer_keys_copied} non-layer keys")
676
+ if missing_params:
677
+ print(f" WARN: {len(missing_params)} trainable params unmatched: "
678
+ f"{missing_params[:5]}{'...' if len(missing_params) > 5 else ''}")
679
+ if result.unexpected_keys:
680
+ print(f" ignored {len(result.unexpected_keys)} unexpected keys (e.g., v11.0 layers we didn't slice)")
681
+ return {
682
+ "share_factor": share,
683
+ "layer_keys_copied": layer_keys_copied,
684
+ "non_layer_keys_copied": non_layer_keys_copied,
685
+ "missing_params": len(missing_params),
686
+ "unexpected": len(result.unexpected_keys),
687
+ }
688
+
689
+
690
+ def count_params(model: nn.Module) -> int:
691
+ return sum(p.numel() for p in model.parameters() if p.requires_grad)
692
+
693
+
694
+ # ─── self-test: forward pass shapes + warm-start sanity ───────────────────────
695
+
696
+
697
+ if __name__ == "__main__":
698
+ torch.manual_seed(0)
699
+ cfg = V11Config()
700
+ model = PredictLMv11(cfg)
701
+ print(f"v11 model: {count_params(model)/1e6:.1f}M params (cfg={cfg})")
702
+
703
+ B, n_ctx, n_q, n_f = 2, 64, 16, 8
704
+ X_ctx = torch.randn(B, n_ctx, n_f)
705
+ y_ctx = torch.randn(B, n_ctx)
706
+ X_q = torch.randn(B, n_q, n_f)
707
+ feat_mask = torch.zeros(B, n_f, dtype=torch.bool)
708
+
709
+ # Regression path
710
+ reg_logits = model(X_ctx, y_ctx, X_q, feat_mask, task_type="regression")
711
+ print(f"[reg] logits shape: {tuple(reg_logits.shape)} (expected (2,16,1024))")
712
+ assert reg_logits.shape == (B, n_q, cfg.n_bins)
713
+
714
+ loss = bar_distribution_loss(reg_logits, y_ctx[:, :n_q], model.reg_head)
715
+ print(f"[reg] uniform-prior loss: {loss.item():.3f} (≈ ln(1024) = 6.93)")
716
+
717
+ # Classification path
718
+ y_ctx_cls = torch.randint(0, 5, (B, n_ctx))
719
+ cls_logits = model(X_ctx, y_ctx_cls, X_q, feat_mask, task_type="classification")
720
+ print(f"[cls] logits shape: {tuple(cls_logits.shape)} (expected (2,16,10))")
721
+ assert cls_logits.shape == (B, n_q, cfg.max_classes)
722
+
723
+ n_classes_per_task = torch.tensor([3, 5])
724
+ y_q_cls = torch.stack([
725
+ torch.randint(0, 3, (n_q,)),
726
+ torch.randint(0, 5, (n_q,)),
727
+ ])
728
+ loss_c = cls_masked_loss(cls_logits, y_q_cls, n_classes_per_task)
729
+ print(f"[cls] masked loss: {loss_c.item():.3f}")
730
+
731
+ # Warm-start dry run: simulate a v8 ckpt with wrong-shape heads
732
+ fake_v8_ckpt = {k: v.clone() for k, v in model.state_dict().items()
733
+ if not k.startswith("reg_head.") and not k.startswith("cls_head.")}
734
+ fake_v8_ckpt["reg_head.weight"] = torch.zeros(2, cfg.d_model) # v8 shape
735
+ fake_v8_ckpt["reg_head.bias"] = torch.zeros(2)
736
+ fake_v8_ckpt["cls_head.weight"] = torch.zeros(cfg.max_classes, cfg.d_model)
737
+ fake_v8_ckpt["cls_head.bias"] = torch.zeros(cfg.max_classes)
738
+ fresh = PredictLMv11(cfg)
739
+ info = fresh.warm_start_from_v8(fake_v8_ckpt)
740
+ print(f"[warm-start] loaded={info['loaded']}, missing={info['missing']}, unexpected={info['unexpected']}")
741
+ assert info['unexpected'] == 0, "v8 reg/cls heads should be filtered, got unexpected"
742
+
743
+ print("[OK] v11 model self-test passed")
pyproject.toml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "predictlm"
7
+ version = "11.1.0"
8
+ description = "Compact distilled tabular foundation model for in-context regression and classification."
9
+ readme = "README.md"
10
+ license = { text = "Apache-2.0" }
11
+ authors = [{ name = "ZeroOne Research" }]
12
+ requires-python = ">=3.10"
13
+ classifiers = [
14
+ "License :: OSI Approved :: Apache Software License",
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
17
+ ]
18
+ dependencies = [
19
+ "torch>=2.0",
20
+ "numpy>=1.24",
21
+ "scikit-learn>=1.2",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ hub = ["huggingface_hub>=0.20"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://huggingface.co/zerooneresearch/predictlm-mini-13m"
29
+ Repository = "https://github.com/zerooneresearch/predictlm-v11"
30
+
31
+ [tool.setuptools.packages.find]
32
+ include = ["predictlm_v11*"]
v11_06_tiny_final.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e27c8af6cda7a3426ffed33cb98eb8338966a8190712b5d37ff9e5f442b75a17
3
+ size 54379587