juinron commited on
Commit
ebd2f40
·
verified ·
1 Parent(s): a32a555

Publish Hummingbird-V2 10B base model and model card

Browse files
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 reasonable and customary use in describing the
141
+ origin of the Work and 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 choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any 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 [yyyy] [name of copyright owner]
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 implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
NOTICE ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Hummingbird-V2
2
+ Copyright 2026 Hummingbird contributors
3
+
4
+ The Hummingbird-V2 model package is licensed under the Apache License, Version 2.0.
5
+ Third-party training datasets retain their own terms. The release includes attribution
6
+ and provenance in TRAINING_DATA.md and training/corpus_contract.yaml.
7
+
8
+ The training mix includes material from FineWeb-Edu, SmolLM-Corpus
9
+ (FineWeb-Edu-Dedup and Cosmopedia v2), FineMath, DCLM baseline 1.0,
10
+ Dolma 3 Dolmino, and FinePDFs-Edu. The corpus contract records the pinned
11
+ source revisions and the dataset licenses declared for this training run.
README.md ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ license: apache-2.0
5
+ library_name: transformers
6
+ pipeline_tag: text-generation
7
+ tags:
8
+ - causal-lm
9
+ - base-model
10
+ - small-language-model
11
+ - custom_code
12
+ - muon
13
+ - hummingbird
14
+ - hummingbird-v2
15
+ datasets:
16
+ - HuggingFaceFW/fineweb-edu
17
+ - HuggingFaceTB/smollm-corpus
18
+ - HuggingFaceTB/finemath
19
+ - mlfoundations/dclm-baseline-1.0
20
+ - allenai/dolma3_dolmino_mix-100B-1025
21
+ - allenai/dolma3_dolmino_mix-10B-1025
22
+ - HuggingFaceFW/finepdfs-edu
23
+ ---
24
+
25
+ # Hummingbird-V2
26
+
27
+ Hummingbird-V2 is a 9,592,720-parameter English causal language model trained from scratch
28
+ on 10 billion tokens of the balanced FlightMix corpus. It is a base model for text completion
29
+ and continuation likelihood ranking, not an instruction-tuned assistant.
30
+
31
+ ## Model series
32
+
33
+ Hummingbird-V2 is the successor to [Hummingbird-V1](https://huggingface.co/juinron/Hummingbird-V1)
34
+ in the Hummingbird small language model series. The models share a 14-layer, 240-hidden-size
35
+ backbone design and a 4,096-token digit-aware tokenizer. V2 was trained from a fresh
36
+ initialization on a new 10B-token corpus; it is not a continuation or fine-tune of V1's weights.
37
+
38
+ ## Architecture
39
+
40
+ | Property | Value |
41
+ |---|---:|
42
+ | Parameters | 9,592,720 |
43
+ | Layers / hidden size | 14 / 240 |
44
+ | Attention | 6 query heads, 2 KV heads, head dimension 40 |
45
+ | MLP | SwiGLU, intermediate size 640 |
46
+ | Vocabulary | 4,096-token digit-aware byte-level BPE |
47
+ | Maximum context | 2,048 tokens |
48
+ | Training context | 512 tokens |
49
+ | Embeddings | tied input/output |
50
+ | Position / normalization | RoPE / RMSNorm, per-head QK normalization before RoPE |
51
+
52
+ The historical Python class name is `MicroLoopForDiffusionLM`. This checkpoint used ordinary
53
+ left-to-right causal language modeling with one layer-loop pass; it was not trained with a
54
+ diffusion objective.
55
+
56
+ ## Training and data
57
+
58
+ - Selected checkpoint: 10,000,000,000 tokens, step 31,250.
59
+ - Unique packed training tokens: 10,000,000,000; validation and held-out splits: 25,000,000
60
+ tokens each, excluded from training.
61
+ - Optimizer: Muon for eligible two-dimensional weights and AdamW for other weights.
62
+ - Peak learning rate: 3e-4; warmup/stable/decay schedule; effective batch: 320,000 tokens.
63
+ - Seed: 42; training precision: bfloat16.
64
+ - Final recorded validation loss: 2.6568.
65
+
66
+ The packed training split used a constant source mixture:
67
+
68
+ | Source | Training tokens | Share |
69
+ |---|---:|---:|
70
+ | FineWeb-Edu | 2.05B | 20.5% |
71
+ | FineWeb-Edu-Dedup reserve | 3.45B | 34.5% |
72
+ | Cosmopedia v2 | 1.50B | 15% |
73
+ | FineMath 4+ | 1.00B | 10% |
74
+ | DCLM baseline | 1.00B | 10% |
75
+ | Dolma 3 science exposition | 0.40B | 4% |
76
+ | Dolma 3 grounded QA | 0.20B | 2% |
77
+ | FinePDFs-Edu | 0.30B | 3% |
78
+ | Dolma 3 educational code | 0.10B | 1% |
79
+
80
+ The [corpus contract](training/corpus_contract.yaml)
81
+ records source revisions, licenses, selection rules, splitting, deduplication, and evaluation
82
+ protection. Its preparation rules exclude exact and near matches to protected renderings of
83
+ HellaSwag, ARC-Easy, ARC-Challenge, PIQA, and ArithMark-3 prompts and choices. This does not
84
+ prove that all benchmark-related content was absent from upstream data.
85
+
86
+ ## Zero-shot evaluation
87
+
88
+ These are author-run evaluations of the 10B-token checkpoint. Task scores are normalized
89
+ continuation accuracy in percent; the Intelligence Index is a chance-normalized composite score.
90
+
91
+ | Benchmark | Score |
92
+ |---|---:|
93
+ | HellaSwag | 27.63 |
94
+ | ARC-Easy | 39.39 |
95
+ | ARC-Challenge | 21.16 |
96
+ | PIQA | 57.40 |
97
+ | ArithMark-3 | 36.00 |
98
+ | Chance-normalized Intelligence Index | **9.556** |
99
+
100
+ The public tasks were evaluated at multiple checkpoints, and the V2 release choice was
101
+ informed by comparisons with other training runs, including a 16-layer candidate. This
102
+ introduces model and checkpoint selection bias. Scores are author-reproduced and have not
103
+ been independently verified by a leaderboard. The full local result files are in the
104
+ `checkpoint_evals/10000000000` directory of the source run named below.
105
+
106
+ ## Use
107
+
108
+ Load `juinron/Hummingbird-V2` with Transformers and the packaged custom code:
109
+
110
+ ```python
111
+ import torch
112
+ from transformers import AutoModelForCausalLM, AutoTokenizer
113
+
114
+ model_id = "juinron/Hummingbird-V2"
115
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
116
+ model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True).eval()
117
+
118
+ inputs = tokenizer("The color of the sky is", return_tensors="pt")
119
+ with torch.inference_mode():
120
+ output = model.generate(**inputs, max_new_tokens=32, do_sample=False, use_cache=False)
121
+ print(tokenizer.decode(output[0], skip_special_tokens=True))
122
+ ```
123
+
124
+ `trust_remote_code=True` executes the model repository's custom Python code. Review that code
125
+ before loading it. The export was checked against the source checkpoint for weights, tokenizer, logits,
126
+ and generation before publication.
127
+
128
+ ## Limitations
129
+
130
+ Hummingbird-V2 is small and English-focused. Its factual knowledge, reasoning, and long-form
131
+ generation are limited. It is not safety-aligned and should not be used as the sole source for
132
+ consequential medical, legal, financial, or safety decisions. Web-derived and synthetic
133
+ training data can contain errors, biases, and undesirable material.
134
+
135
+ ## Provenance and license
136
+
137
+ - Source run: `artifacts/runs/flightmix_10b_balanced_10m_muon_lrfix_20260921`.
138
+ - Selected source checkpoint: `checkpoint-tokens-10000000000`.
139
+ - Planned model license: Apache-2.0. The release package should include `LICENSE`, `NOTICE`,
140
+ and training data notices before publication.
141
+
TRAINING_DATA.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hummingbird-V2 training data
2
+
3
+ Hummingbird-V2 was trained from scratch on the 10,000,000,000-token packed
4
+ FlightMix Balanced training split. Separate 25,000,000-token validation and
5
+ 25,000,000-token held-out splits were not used as training records. The selected
6
+ checkpoint is the 10B-token checkpoint at step 31,250.
7
+
8
+ | Source | Hub repository | Training tokens | Declared source license |
9
+ |---|---|---:|---|
10
+ | FineWeb-Edu | `HuggingFaceFW/fineweb-edu` | 2,050,000,000 | ODC-By 1.0 |
11
+ | FineWeb-Edu-Dedup | `HuggingFaceTB/smollm-corpus` | 3,450,000,000 | ODC-By 1.0 |
12
+ | Cosmopedia v2 | `HuggingFaceTB/smollm-corpus` | 1,500,000,000 | ODC-By 1.0 |
13
+ | FineMath 4+ | `HuggingFaceTB/finemath` | 1,000,000,000 | ODC-By 1.0 |
14
+ | DCLM baseline 1.0 | `mlfoundations/dclm-baseline-1.0` | 1,000,000,000 | CC-BY 4.0 |
15
+ | Science exposition | `allenai/dolma3_dolmino_mix-100B-1025` | 400,000,000 | ODC-By 1.0 |
16
+ | Grounded QA | `allenai/dolma3_dolmino_mix-100B-1025` | 200,000,000 | ODC-By 1.0 |
17
+ | FinePDFs-Edu | `HuggingFaceFW/finepdfs-edu` | 300,000,000 | ODC-By 1.0 |
18
+ | Educational code | `allenai/dolma3_dolmino_mix-10B-1025` | 100,000,000 | ODC-By 1.0 |
19
+
20
+ The bundled `training/corpus_contract.yaml` records pinned upstream revisions,
21
+ source selections, quality filters, deduplication, and split assignment. The
22
+ bundled `training/packed_metadata.json` records the realized packed token and
23
+ document totals. The pipeline used a benchmark protection index for rendered
24
+ HellaSwag, ARC-Easy, ARC-Challenge, PIQA, and ArithMark-3 prompts and choices.
25
+ Protected matching reduces direct overlap but cannot prove complete absence
26
+ of benchmark-related content in upstream data.
27
+
28
+ Public task scores across checkpoints and comparisons with other candidate
29
+ runs informed the release choice. This selection bias is disclosed in README.md.
30
+ Dataset licenses and notices remain applicable to the upstream data; the
31
+ Apache-2.0 license for this model package does not replace them.
chat_template.jinja ADDED
@@ -0,0 +1 @@
 
 
1
+ {% for message in messages %}{{ '<' + message['role'] + '>\n' }}{{ message['content'] }}{{ '<turn_end>\n' }}{% endfor %}{% if add_generation_prompt %}{{ '<assistant>\n' }}{% endif %}
config.json ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "swiglu",
3
+ "architecture": "MicroLoopForDiffusionLM",
4
+ "architectures": [
5
+ "MicroLoopForDiffusionLM"
6
+ ],
7
+ "attention_implementation": "sdpa",
8
+ "attention_output_gate": false,
9
+ "attention_output_gate_activation": "silu",
10
+ "attn_res_block_size": null,
11
+ "auto_map": {
12
+ "AutoConfig": "configuration_microloop.MicroLoopConfig",
13
+ "AutoModelForCausalLM": "modeling_microloop.MicroLoopForDiffusionLM"
14
+ },
15
+ "bos_token_id": 1,
16
+ "diffusion": {
17
+ "fallback_block_size": 16,
18
+ "objective": "absorbing_mask_mdlm",
19
+ "primary_block_size": 32,
20
+ "training_block_sizes": {
21
+ "16": 0.35,
22
+ "32": 0.6,
23
+ "64": 0.05
24
+ }
25
+ },
26
+ "digit_position_embedding": {},
27
+ "dropout": 0.0,
28
+ "dtype": "float32",
29
+ "eos_token_id": 2,
30
+ "ffn_factor_activation": "silu",
31
+ "ffn_rank": null,
32
+ "head_dimension": 40,
33
+ "hidden_size": 240,
34
+ "intermediate_size": 640,
35
+ "is_decoder": true,
36
+ "looping": {
37
+ "layers": [
38
+ 4,
39
+ 5,
40
+ 6
41
+ ],
42
+ "maximum_serving_loops": 3,
43
+ "training_loop_counts": [
44
+ 1
45
+ ]
46
+ },
47
+ "max_position_embeddings": 2048,
48
+ "mhc_eps": 1e-06,
49
+ "mhc_init_scale": 0.01,
50
+ "mhc_multiplier": 1,
51
+ "mhc_sinkhorn_iterations": 20,
52
+ "model_type": "microloop_diffusion",
53
+ "mtp_enabled": false,
54
+ "ngram_memory": {},
55
+ "normalization": "rmsnorm",
56
+ "num_attention_heads": 6,
57
+ "num_hidden_layers": 14,
58
+ "num_key_value_heads": 2,
59
+ "pad_token_id": 0,
60
+ "positional_encoding": "rope",
61
+ "qk_norm": "per_head",
62
+ "qk_norm_position": "pre_rope",
63
+ "rms_norm_eps": 1e-05,
64
+ "rope_theta": 10000.0,
65
+ "swiglu_clamp": {
66
+ "enabled": true,
67
+ "gate_max": 10.0,
68
+ "linear_max": 10.0,
69
+ "linear_min": -10.0
70
+ },
71
+ "target_parameters": 10000000,
72
+ "tie_word_embeddings": true,
73
+ "tokenizer": {
74
+ "required_special_tokens": [
75
+ "<pad>",
76
+ "<bos>",
77
+ "<eos>",
78
+ "<mask>",
79
+ "<system>",
80
+ "<user>",
81
+ "<assistant>",
82
+ "<turn_end>",
83
+ "<doc_end>"
84
+ ],
85
+ "type": "byte_level_bpe",
86
+ "vocabulary_size": 4096
87
+ },
88
+ "transformers_version": "5.14.1",
89
+ "use_cache": false,
90
+ "value_residual": {},
91
+ "vocab_size": 4096
92
+ }
configuration_microloop.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration for the MicroLoop-Diffusion model.
2
+
3
+ The configuration is intentionally explicit. It is the single source of truth for
4
+ the parameter-count gate and is serializable by Hugging Face when Transformers is
5
+ installed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import yaml
14
+
15
+ try: # Keep config inspection useful before optional HF integration is installed.
16
+ from transformers import PretrainedConfig
17
+ except ImportError: # pragma: no cover - exercised only in a minimal environment.
18
+
19
+ class PretrainedConfig: # type: ignore[no-redef]
20
+ model_type = "microloop_diffusion"
21
+
22
+ def __init__(self, **kwargs: Any) -> None:
23
+ for key, value in kwargs.items():
24
+ setattr(self, key, value)
25
+
26
+ def to_dict(self) -> dict[str, Any]:
27
+ return dict(self.__dict__)
28
+
29
+
30
+ class MicroLoopConfig(PretrainedConfig):
31
+ """Model, diffusion, and selective-looping configuration.
32
+
33
+ The defaults match the locked 10M specification. Feature configuration is
34
+ stored on the model config for deterministic HF save/reload and is also emitted
35
+ separately as ``diffusion_config.json`` by the eventual release exporter.
36
+ """
37
+
38
+ model_type = "microloop_diffusion"
39
+ keys_to_ignore_at_inference = ["past_key_values"]
40
+
41
+ def __init__(
42
+ self,
43
+ vocab_size: int = 8192,
44
+ hidden_size: int = 240,
45
+ num_hidden_layers: int = 12,
46
+ num_attention_heads: int = 6,
47
+ num_key_value_heads: int = 2,
48
+ head_dimension: int = 40,
49
+ intermediate_size: int = 640,
50
+ ffn_rank: int | None = None,
51
+ ffn_factor_activation: str = "silu",
52
+ activation: str = "swiglu",
53
+ normalization: str = "rmsnorm",
54
+ positional_encoding: str = "rope",
55
+ tie_word_embeddings: bool = True,
56
+ max_position_embeddings: int = 2048,
57
+ dropout: float = 0.0,
58
+ attention_implementation: str = "eager",
59
+ qk_norm: str = "none",
60
+ qk_norm_position: str = "pre_rope",
61
+ attention_output_gate: bool = False,
62
+ attention_output_gate_activation: str = "silu",
63
+ attn_res_block_size: int | None = None,
64
+ mhc_multiplier: int = 1,
65
+ mhc_sinkhorn_iterations: int = 20,
66
+ mhc_eps: float = 1e-6,
67
+ mhc_init_scale: float = 0.01,
68
+ mtp_enabled: bool = False,
69
+ swiglu_clamp: dict[str, Any] | None = None,
70
+ rms_norm_eps: float = 1e-5,
71
+ rope_theta: float = 10000.0,
72
+ architecture: str = "MicroLoopForDiffusionLM",
73
+ target_parameters: int = 10_000_000,
74
+ diffusion: dict[str, Any] | None = None,
75
+ looping: dict[str, Any] | None = None,
76
+ tokenizer: dict[str, Any] | None = None,
77
+ digit_position_embedding: dict[str, Any] | None = None,
78
+ ngram_memory: dict[str, Any] | None = None,
79
+ value_residual: dict[str, Any] | None = None,
80
+ **kwargs: Any,
81
+ ) -> None:
82
+ kwargs.setdefault("is_decoder", True)
83
+ kwargs.setdefault("is_encoder_decoder", False)
84
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
85
+ self.vocab_size = int(vocab_size)
86
+ self.hidden_size = int(hidden_size)
87
+ self.num_hidden_layers = int(num_hidden_layers)
88
+ self.num_attention_heads = int(num_attention_heads)
89
+ self.num_key_value_heads = int(num_key_value_heads)
90
+ self.head_dimension = int(head_dimension)
91
+ self.intermediate_size = int(intermediate_size)
92
+ self.ffn_rank = ffn_rank
93
+ self.ffn_factor_activation = str(ffn_factor_activation)
94
+ self.activation = activation
95
+ self.normalization = normalization
96
+ self.positional_encoding = positional_encoding
97
+ self.tie_word_embeddings = bool(tie_word_embeddings)
98
+ self.max_position_embeddings = int(max_position_embeddings)
99
+ self.dropout = float(dropout)
100
+ self.attention_implementation = str(attention_implementation)
101
+ self.qk_norm = str(qk_norm)
102
+ self.qk_norm_position = str(qk_norm_position)
103
+ self.attention_output_gate = bool(attention_output_gate)
104
+ self.attention_output_gate_activation = str(attention_output_gate_activation)
105
+ self.attn_res_block_size = (
106
+ int(attn_res_block_size) if attn_res_block_size is not None else None
107
+ )
108
+ self.mhc_multiplier = int(mhc_multiplier)
109
+ self.mhc_sinkhorn_iterations = int(mhc_sinkhorn_iterations)
110
+ self.mhc_eps = float(mhc_eps)
111
+ self.mhc_init_scale = float(mhc_init_scale)
112
+ self.mtp_enabled = bool(mtp_enabled)
113
+ self.swiglu_clamp = dict(swiglu_clamp or {})
114
+ self.rms_norm_eps = float(rms_norm_eps)
115
+ self.rope_theta = float(rope_theta)
116
+ self.architecture = architecture
117
+ self.target_parameters = int(target_parameters)
118
+ self.diffusion = dict(diffusion or {})
119
+ self.looping = dict(looping or {})
120
+ self.tokenizer = dict(tokenizer or {})
121
+ self.digit_position_embedding = dict(digit_position_embedding or {})
122
+ self.ngram_memory = dict(ngram_memory or {})
123
+ self.value_residual = dict(value_residual or {})
124
+ if self.ngram_memory:
125
+ # Unversioned checkpoints were trained with the original linear hash.
126
+ self.ngram_memory.setdefault("hash_version", "legacy_v1")
127
+ self.validate()
128
+
129
+ @property
130
+ def head_dim(self) -> int:
131
+ return self.head_dimension
132
+
133
+ @classmethod
134
+ def from_yaml(cls, path: str | Path) -> "MicroLoopConfig":
135
+ """Load the locked nested YAML layout used by the project configs."""
136
+
137
+ payload = yaml.safe_load(Path(path).read_text(encoding="utf-8")) or {}
138
+ model = dict(payload.get("model", payload))
139
+ model.pop("architecture", None) if model.get("architecture") is None else None
140
+ return cls(
141
+ **model,
142
+ diffusion=payload.get("diffusion", {}),
143
+ looping=payload.get("looping", {}),
144
+ tokenizer=payload.get("tokenizer", {}),
145
+ )
146
+
147
+ def validate(self) -> None:
148
+ """Raise a clear error for shape or locked-spec inconsistencies."""
149
+
150
+ positive = {
151
+ "vocab_size": self.vocab_size,
152
+ "hidden_size": self.hidden_size,
153
+ "num_hidden_layers": self.num_hidden_layers,
154
+ "num_attention_heads": self.num_attention_heads,
155
+ "num_key_value_heads": self.num_key_value_heads,
156
+ "head_dimension": self.head_dimension,
157
+ "intermediate_size": self.intermediate_size,
158
+ "max_position_embeddings": self.max_position_embeddings,
159
+ }
160
+ invalid = [name for name, value in positive.items() if value <= 0]
161
+ if invalid:
162
+ raise ValueError(f"Configuration values must be positive: {', '.join(invalid)}")
163
+ if self.ffn_rank is not None and (
164
+ type(self.ffn_rank) is not int
165
+ or not 0 < self.ffn_rank <= min(self.hidden_size, self.intermediate_size)
166
+ ):
167
+ raise ValueError(
168
+ "ffn_rank must be an integer in [1, min(hidden_size, intermediate_size)]"
169
+ )
170
+ if self.ffn_factor_activation not in {"silu", "identity"}:
171
+ raise ValueError("ffn_factor_activation must be silu or identity")
172
+ if self.hidden_size != self.num_attention_heads * self.head_dimension:
173
+ raise ValueError(
174
+ "hidden_size must equal num_attention_heads * head_dimension: "
175
+ f"{self.hidden_size} != {self.num_attention_heads} * {self.head_dimension}"
176
+ )
177
+ if self.num_attention_heads % self.num_key_value_heads:
178
+ raise ValueError("num_attention_heads must be divisible by num_key_value_heads")
179
+ if self.head_dimension % 2:
180
+ raise ValueError("RoPE requires an even head_dimension")
181
+ if self.dropout < 0.0 or self.dropout >= 1.0:
182
+ raise ValueError("dropout must be in [0, 1)")
183
+ if self.attention_implementation not in {"eager", "sdpa"}:
184
+ raise ValueError("attention_implementation must be eager or sdpa")
185
+ if self.qk_norm not in {"none", "per_head"}:
186
+ raise ValueError("qk_norm must be none or per_head")
187
+ if self.qk_norm_position not in {"pre_rope", "post_rope"}:
188
+ raise ValueError("qk_norm_position must be pre_rope or post_rope")
189
+ if self.attention_output_gate_activation not in {"silu", "sigmoid"}:
190
+ raise ValueError("attention_output_gate_activation must be silu or sigmoid")
191
+ if self.attn_res_block_size is not None and self.attn_res_block_size < 2:
192
+ raise ValueError("attn_res_block_size must be at least two when enabled")
193
+ loop_mode = str(self.looping.get("mode", "layer"))
194
+ if loop_mode not in {"layer", "block"}:
195
+ raise ValueError("looping mode must be layer or block")
196
+ loop_gated = bool(self.looping.get("gated", False))
197
+ if loop_gated and loop_mode != "block":
198
+ raise ValueError("gated looping requires looping mode=block")
199
+ max_loop_count = int(
200
+ self.looping.get("max_loop_count", self.looping.get("maximum_serving_loops", 3))
201
+ )
202
+ if max_loop_count < 1:
203
+ raise ValueError("looping max_loop_count must be positive")
204
+ loop_layers = [int(layer) for layer in self.looping.get("layers", [4, 5, 6])]
205
+ if loop_mode == "block" and loop_layers:
206
+ valid_layers = sorted(
207
+ {layer for layer in loop_layers if 1 <= layer <= self.num_hidden_layers}
208
+ )
209
+ if valid_layers and valid_layers != list(range(valid_layers[0], valid_layers[-1] + 1)):
210
+ raise ValueError("block looping layers must form a contiguous range")
211
+ if self.mhc_multiplier < 1:
212
+ raise ValueError("mhc_multiplier must be at least one")
213
+ if self.mhc_sinkhorn_iterations < 1:
214
+ raise ValueError("mhc_sinkhorn_iterations must be at least one")
215
+ if self.mhc_eps <= 0:
216
+ raise ValueError("mhc_eps must be positive")
217
+ if self.mhc_init_scale <= 0:
218
+ raise ValueError("mhc_init_scale must be positive")
219
+ if self.mhc_multiplier > 1 and self.attn_res_block_size is not None:
220
+ raise ValueError("mHC and attn_res_block_size cannot be enabled together")
221
+ if self.swiglu_clamp:
222
+ enabled = bool(self.swiglu_clamp.get("enabled", False))
223
+ if enabled:
224
+ linear_min = float(self.swiglu_clamp.get("linear_min", -10.0))
225
+ linear_max = float(self.swiglu_clamp.get("linear_max", 10.0))
226
+ gate_max = float(self.swiglu_clamp.get("gate_max", 10.0))
227
+ if linear_min >= linear_max:
228
+ raise ValueError("swiglu_clamp linear_min must be below linear_max")
229
+ if gate_max <= 0:
230
+ raise ValueError("swiglu_clamp gate_max must be positive")
231
+ if self.ngram_memory.get("enabled", False):
232
+ if self.ngram_memory["hash_version"] not in {"legacy_v1", "polynomial_v2"}:
233
+ raise ValueError("ngram_memory hash_version must be legacy_v1 or polynomial_v2")
234
+ orders = self.ngram_memory.get("orders", [2, 3])
235
+ if not isinstance(orders, (list, tuple)) or not orders:
236
+ raise ValueError("ngram_memory orders must be a non-empty list")
237
+ if any(not isinstance(order, int) or order < 2 for order in orders):
238
+ raise ValueError("ngram_memory orders must contain integers >= 2")
239
+ if len(set(orders)) != len(orders):
240
+ raise ValueError("ngram_memory orders must be unique")
241
+ if self.ngram_memory.get("mode", "lookup") not in {"lookup", "parameter_free"}:
242
+ raise ValueError("ngram_memory mode must be lookup or parameter_free")
243
+ for name in ("num_hash_heads", "num_buckets", "embedding_dim", "insertion_layer"):
244
+ value = int(self.ngram_memory.get(name, 0))
245
+ if value <= 0:
246
+ raise ValueError(f"ngram_memory {name} must be positive")
247
+ insertion_layer = int(self.ngram_memory["insertion_layer"])
248
+ if insertion_layer > self.num_hidden_layers:
249
+ raise ValueError("ngram_memory insertion_layer exceeds num_hidden_layers")
250
+ if self.ngram_memory.get("canonicalization", "raw_math_safe") != "raw_math_safe":
251
+ raise ValueError("ngram_memory canonicalization must be raw_math_safe")
252
+ if self.value_residual.get("enabled", False) and self.mhc_multiplier > 1:
253
+ raise ValueError("value_residual is not supported with mHC")
254
+ digit_settings = self.digit_position_embedding
255
+ if digit_settings.get("enabled", False):
256
+ max_positions = int(digit_settings.get("max_positions", 128))
257
+ digit_token_ids = digit_settings.get("digit_token_ids", [])
258
+ if max_positions < 1:
259
+ raise ValueError("digit_position_embedding max_positions must be positive")
260
+ if len(digit_token_ids) != 10 or len(set(digit_token_ids)) != 10:
261
+ raise ValueError(
262
+ "digit_position_embedding digit_token_ids must contain ten unique IDs"
263
+ )
264
+ if any(
265
+ int(token_id) < 0 or int(token_id) >= self.vocab_size
266
+ for token_id in digit_token_ids
267
+ ):
268
+ raise ValueError("digit_position_embedding digit_token_ids must be in vocabulary")
269
+ if self.activation.lower() != "swiglu":
270
+ raise ValueError("M0 only implements the locked SwiGLU activation")
271
+ if self.normalization.lower() != "rmsnorm":
272
+ raise ValueError("M0 only implements the locked RMSNorm normalization")
273
+ if self.positional_encoding.lower() != "rope":
274
+ raise ValueError("M0 only implements the locked RoPE positional encoding")
275
+
276
+ def diffusion_dict(self) -> dict[str, Any]:
277
+ """Return a copy suitable for a standalone diffusion config artifact."""
278
+
279
+ return dict(self.diffusion)
280
+
281
+ def looping_dict(self) -> dict[str, Any]:
282
+ """Return a copy suitable for experiment logging."""
283
+
284
+ return dict(self.looping)
evaluation/arithmark_3.json ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "acc": 35.699999999999996,
3
+ "acc_norm": 36.0,
4
+ "categories": {
5
+ "elementary_school_math_continuation::addition::grades_1_2::easy": {
6
+ "acc": 28.125,
7
+ "acc_norm": 28.125,
8
+ "norm_correct": 36,
9
+ "raw_correct": 36,
10
+ "total": 128
11
+ },
12
+ "elementary_school_math_continuation::comparison::grades_2_3::medium": {
13
+ "acc": 27.27272727272727,
14
+ "acc_norm": 27.27272727272727,
15
+ "norm_correct": 12,
16
+ "raw_correct": 12,
17
+ "total": 44
18
+ },
19
+ "elementary_school_math_continuation::comparison_difference::grades_2_3::medium": {
20
+ "acc": 25.0,
21
+ "acc_norm": 25.0,
22
+ "norm_correct": 12,
23
+ "raw_correct": 12,
24
+ "total": 48
25
+ },
26
+ "elementary_school_math_continuation::data::grades_2_3::easy": {
27
+ "acc": 23.25581395348837,
28
+ "acc_norm": 25.581395348837212,
29
+ "norm_correct": 11,
30
+ "raw_correct": 10,
31
+ "total": 43
32
+ },
33
+ "elementary_school_math_continuation::division::grades_3_4::medium": {
34
+ "acc": 25.925925925925924,
35
+ "acc_norm": 24.074074074074073,
36
+ "norm_correct": 13,
37
+ "raw_correct": 14,
38
+ "total": 54
39
+ },
40
+ "elementary_school_math_continuation::fractions_counting::grades_3_4::medium": {
41
+ "acc": 20.0,
42
+ "acc_norm": 20.0,
43
+ "norm_correct": 10,
44
+ "raw_correct": 10,
45
+ "total": 50
46
+ },
47
+ "elementary_school_math_continuation::geometry_area::grades_4_5::medium": {
48
+ "acc": 51.92307692307693,
49
+ "acc_norm": 53.84615384615385,
50
+ "norm_correct": 28,
51
+ "raw_correct": 27,
52
+ "total": 52
53
+ },
54
+ "elementary_school_math_continuation::geometry_perimeter::grades_4_5::medium": {
55
+ "acc": 62.22222222222222,
56
+ "acc_norm": 62.22222222222222,
57
+ "norm_correct": 28,
58
+ "raw_correct": 28,
59
+ "total": 45
60
+ },
61
+ "elementary_school_math_continuation::measurement::grades_2_3::easy": {
62
+ "acc": 32.89473684210527,
63
+ "acc_norm": 32.89473684210527,
64
+ "norm_correct": 25,
65
+ "raw_correct": 25,
66
+ "total": 76
67
+ },
68
+ "elementary_school_math_continuation::money::grades_3_4::medium": {
69
+ "acc": 29.6875,
70
+ "acc_norm": 29.6875,
71
+ "norm_correct": 19,
72
+ "raw_correct": 19,
73
+ "total": 64
74
+ },
75
+ "elementary_school_math_continuation::multiplication::grades_3_4::medium": {
76
+ "acc": 51.35135135135135,
77
+ "acc_norm": 52.702702702702695,
78
+ "norm_correct": 39,
79
+ "raw_correct": 38,
80
+ "total": 74
81
+ },
82
+ "elementary_school_math_continuation::patterns::grades_3_4::medium": {
83
+ "acc": 24.528301886792452,
84
+ "acc_norm": 24.528301886792452,
85
+ "norm_correct": 13,
86
+ "raw_correct": 13,
87
+ "total": 53
88
+ },
89
+ "elementary_school_math_continuation::subtraction::grades_1_2::easy": {
90
+ "acc": 30.76923076923077,
91
+ "acc_norm": 31.62393162393162,
92
+ "norm_correct": 37,
93
+ "raw_correct": 36,
94
+ "total": 117
95
+ },
96
+ "elementary_school_math_continuation::time::grades_2_3::easy": {
97
+ "acc": 100.0,
98
+ "acc_norm": 100.0,
99
+ "norm_correct": 55,
100
+ "raw_correct": 55,
101
+ "total": 55
102
+ },
103
+ "elementary_school_math_continuation::two_step_add_subtract::grades_2_3::medium": {
104
+ "acc": 21.73913043478261,
105
+ "acc_norm": 21.73913043478261,
106
+ "norm_correct": 10,
107
+ "raw_correct": 10,
108
+ "total": 46
109
+ },
110
+ "elementary_school_math_continuation::two_step_addition::grades_2_3::medium": {
111
+ "acc": 15.789473684210526,
112
+ "acc_norm": 15.789473684210526,
113
+ "norm_correct": 3,
114
+ "raw_correct": 3,
115
+ "total": 19
116
+ },
117
+ "elementary_school_math_continuation::two_step_subtraction::grades_2_3::medium": {
118
+ "acc": 28.125,
119
+ "acc_norm": 28.125,
120
+ "norm_correct": 9,
121
+ "raw_correct": 9,
122
+ "total": 32
123
+ }
124
+ },
125
+ "frost_evaluation": {
126
+ "checkpoint": "D:\\llm\\hummingbird\\artifacts\\runs\\flightmix_10b_balanced_10m_muon_lrfix_20260921\\checkpoint-tokens-10000000000",
127
+ "data_sha256": "bf8ab1a5193d52cdf0e05ff0b3ca226bdfcf416cb6e75562dcbe72e7e4559435",
128
+ "dataset": "AxiomicLabs/Arithmark-3.0",
129
+ "dataset_revision": "6f6e59dd9b7e2c63455f7af7f838f9ecc3d0a746",
130
+ "device": "cuda",
131
+ "evaluator_sha256": "09667e1ea05ecd8b91dbfea14a47365b555c72622afed9fc284c127ecd5e1bcd",
132
+ "limit": null,
133
+ "loop_count": 1,
134
+ "numeric_serialization": "none",
135
+ "precision": "bfloat16",
136
+ "qk_norm_position": null,
137
+ "tokenizer": "D:\\llm\\hummingbird\\artifacts\\runs\\e3_tokenizers\\tok_4k_digit"
138
+ },
139
+ "norm_correct": 360,
140
+ "raw_correct": 357,
141
+ "timing": {
142
+ "evaluation_seconds": 0.8658304999989923,
143
+ "examples_per_second": 1154.9604685919055,
144
+ "tokenization_seconds": 0.30124549998436123
145
+ },
146
+ "total": 1000
147
+ }
evaluation/open_slm.json ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "config": {
3
+ "batch_size": 64,
4
+ "batch_sizes": [],
5
+ "bootstrap_iters": 100000,
6
+ "device": "cuda",
7
+ "fewshot_seed": 1234,
8
+ "gen_kwargs": null,
9
+ "limit": null,
10
+ "model": "MicroLoopHarnessLM",
11
+ "model_args": null,
12
+ "numpy_seed": 1234,
13
+ "random_seed": 0,
14
+ "torch_seed": 1234,
15
+ "use_cache": null
16
+ },
17
+ "configs": {
18
+ "arc_challenge": {
19
+ "dataset_name": "ARC-Challenge",
20
+ "dataset_path": "allenai/ai2_arc",
21
+ "description": "",
22
+ "doc_to_choice": "{{choices.text}}",
23
+ "doc_to_decontamination_query": "Question: {{question}}\nAnswer:",
24
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
25
+ "doc_to_text": "Question: {{question}}\nAnswer:",
26
+ "fewshot_config": {
27
+ "doc_to_choice": "{{choices.text}}",
28
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
29
+ "doc_to_text": "Question: {{question}}\nAnswer:",
30
+ "fewshot_delimiter": "\n\n",
31
+ "fewshot_indices": null,
32
+ "gen_prefix": null,
33
+ "process_docs": null,
34
+ "sampler": "default",
35
+ "samples": null,
36
+ "split": null,
37
+ "target_delimiter": " "
38
+ },
39
+ "fewshot_delimiter": "\n\n",
40
+ "metadata": {
41
+ "config_source": "D:\\llm\\hummingbird\\.venv\\Lib\\site-packages\\lm_eval\\tasks\\arc\\arc_challenge.yaml",
42
+ "version": 1.0
43
+ },
44
+ "metric_list": [
45
+ {
46
+ "aggregation": "mean",
47
+ "higher_is_better": true,
48
+ "metric": "acc"
49
+ },
50
+ {
51
+ "aggregation": "mean",
52
+ "higher_is_better": true,
53
+ "metric": "acc_norm"
54
+ }
55
+ ],
56
+ "num_fewshot": 0,
57
+ "output_type": "multiple_choice",
58
+ "repeats": 1,
59
+ "should_decontaminate": true,
60
+ "target_delimiter": " ",
61
+ "task": "arc_challenge",
62
+ "test_split": "test",
63
+ "training_split": "train",
64
+ "unsafe_code": false,
65
+ "validation_split": "validation"
66
+ },
67
+ "arc_easy": {
68
+ "dataset_name": "ARC-Easy",
69
+ "dataset_path": "allenai/ai2_arc",
70
+ "description": "",
71
+ "doc_to_choice": "{{choices.text}}",
72
+ "doc_to_decontamination_query": "Question: {{question}}\nAnswer:",
73
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
74
+ "doc_to_text": "Question: {{question}}\nAnswer:",
75
+ "fewshot_config": {
76
+ "doc_to_choice": "{{choices.text}}",
77
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
78
+ "doc_to_text": "Question: {{question}}\nAnswer:",
79
+ "fewshot_delimiter": "\n\n",
80
+ "fewshot_indices": null,
81
+ "gen_prefix": null,
82
+ "process_docs": null,
83
+ "sampler": "default",
84
+ "samples": null,
85
+ "split": null,
86
+ "target_delimiter": " "
87
+ },
88
+ "fewshot_delimiter": "\n\n",
89
+ "metadata": {
90
+ "config_source": "D:\\llm\\hummingbird\\.venv\\Lib\\site-packages\\lm_eval\\tasks\\arc\\arc_easy.yaml",
91
+ "version": 1.0
92
+ },
93
+ "metric_list": [
94
+ {
95
+ "aggregation": "mean",
96
+ "higher_is_better": true,
97
+ "metric": "acc"
98
+ },
99
+ {
100
+ "aggregation": "mean",
101
+ "higher_is_better": true,
102
+ "metric": "acc_norm"
103
+ }
104
+ ],
105
+ "num_fewshot": 0,
106
+ "output_type": "multiple_choice",
107
+ "repeats": 1,
108
+ "should_decontaminate": true,
109
+ "target_delimiter": " ",
110
+ "task": "arc_easy",
111
+ "test_split": "test",
112
+ "training_split": "train",
113
+ "unsafe_code": false,
114
+ "validation_split": "validation"
115
+ },
116
+ "hellaswag": {
117
+ "dataset_path": "Rowan/hellaswag",
118
+ "description": "",
119
+ "doc_to_choice": "choices",
120
+ "doc_to_target": "{{label}}",
121
+ "doc_to_text": "{{query}}",
122
+ "fewshot_config": {
123
+ "doc_to_choice": "choices",
124
+ "doc_to_target": "{{label}}",
125
+ "doc_to_text": "{{query}}",
126
+ "fewshot_delimiter": "\n\n",
127
+ "fewshot_indices": null,
128
+ "gen_prefix": null,
129
+ "process_docs": "<callable function>",
130
+ "sampler": "default",
131
+ "samples": null,
132
+ "split": null,
133
+ "target_delimiter": " "
134
+ },
135
+ "fewshot_delimiter": "\n\n",
136
+ "metadata": {
137
+ "config_source": "D:\\llm\\hummingbird\\.venv\\Lib\\site-packages\\lm_eval\\tasks\\hellaswag\\hellaswag.yaml",
138
+ "version": 1.0
139
+ },
140
+ "metric_list": [
141
+ {
142
+ "aggregation": "mean",
143
+ "higher_is_better": true,
144
+ "metric": "acc"
145
+ },
146
+ {
147
+ "aggregation": "mean",
148
+ "higher_is_better": true,
149
+ "metric": "acc_norm"
150
+ }
151
+ ],
152
+ "num_fewshot": 0,
153
+ "output_type": "multiple_choice",
154
+ "process_docs": "def process_docs(dataset: datasets.Dataset) -> datasets.Dataset:\n def _process_doc(doc):\n ctx = doc[\"ctx_a\"] + \" \" + doc[\"ctx_b\"].capitalize()\n out_doc = {\n \"query\": preprocess(doc[\"activity_label\"] + \": \" + ctx),\n \"choices\": [preprocess(ending) for ending in doc[\"endings\"]],\n \"gold\": int(doc[\"label\"]),\n }\n return out_doc\n\n return dataset.map(_process_doc)\n",
155
+ "repeats": 1,
156
+ "should_decontaminate": false,
157
+ "target_delimiter": " ",
158
+ "task": "hellaswag",
159
+ "training_split": "train",
160
+ "unsafe_code": false,
161
+ "validation_split": "validation"
162
+ },
163
+ "piqa": {
164
+ "dataset_path": "baber/piqa",
165
+ "description": "",
166
+ "doc_to_choice": "{{[sol1, sol2]}}",
167
+ "doc_to_decontamination_query": "goal",
168
+ "doc_to_target": "label",
169
+ "doc_to_text": "Question: {{goal}}\nAnswer:",
170
+ "fewshot_config": {
171
+ "doc_to_choice": "{{[sol1, sol2]}}",
172
+ "doc_to_target": "label",
173
+ "doc_to_text": "Question: {{goal}}\nAnswer:",
174
+ "fewshot_delimiter": "\n\n",
175
+ "fewshot_indices": null,
176
+ "gen_prefix": null,
177
+ "process_docs": null,
178
+ "sampler": "default",
179
+ "samples": null,
180
+ "split": null,
181
+ "target_delimiter": " "
182
+ },
183
+ "fewshot_delimiter": "\n\n",
184
+ "metadata": {
185
+ "config_source": "D:\\llm\\hummingbird\\.venv\\Lib\\site-packages\\lm_eval\\tasks\\piqa\\piqa.yaml",
186
+ "version": 1.0
187
+ },
188
+ "metric_list": [
189
+ {
190
+ "aggregation": "mean",
191
+ "higher_is_better": true,
192
+ "metric": "acc"
193
+ },
194
+ {
195
+ "aggregation": "mean",
196
+ "higher_is_better": true,
197
+ "metric": "acc_norm"
198
+ }
199
+ ],
200
+ "num_fewshot": 0,
201
+ "output_type": "multiple_choice",
202
+ "repeats": 1,
203
+ "should_decontaminate": true,
204
+ "target_delimiter": " ",
205
+ "task": "piqa",
206
+ "training_split": "train",
207
+ "unsafe_code": false,
208
+ "validation_split": "validation"
209
+ }
210
+ },
211
+ "date": 1790004139.4918497,
212
+ "frost_evaluation": {
213
+ "batch_size": 64,
214
+ "checkpoint": "D:\\llm\\hummingbird\\artifacts\\runs\\flightmix_10b_balanced_10m_muon_lrfix_20260921\\checkpoint-tokens-10000000000",
215
+ "device": "cuda",
216
+ "loop_count": 1,
217
+ "num_fewshot": 0,
218
+ "numeric_serialization": "none",
219
+ "qk_norm_position": null,
220
+ "tokenizer": "D:\\llm\\hummingbird\\artifacts\\runs\\e3_tokenizers\\tok_4k_digit"
221
+ },
222
+ "git_hash": "9ac6cbb",
223
+ "group_subtasks": {},
224
+ "higher_is_better": {
225
+ "arc_challenge": {
226
+ "acc": true,
227
+ "acc_norm": true
228
+ },
229
+ "arc_easy": {
230
+ "acc": true,
231
+ "acc_norm": true
232
+ },
233
+ "hellaswag": {
234
+ "acc": true,
235
+ "acc_norm": true
236
+ },
237
+ "piqa": {
238
+ "acc": true,
239
+ "acc_norm": true
240
+ }
241
+ },
242
+ "lm_eval_version": "0.4.12",
243
+ "n-samples": {
244
+ "arc_challenge": {
245
+ "effective": 1172,
246
+ "original": 1172
247
+ },
248
+ "arc_easy": {
249
+ "effective": 2376,
250
+ "original": 2376
251
+ },
252
+ "hellaswag": {
253
+ "effective": 10042,
254
+ "original": 10042
255
+ },
256
+ "piqa": {
257
+ "effective": 1838,
258
+ "original": 1838
259
+ }
260
+ },
261
+ "n-shot": {
262
+ "arc_challenge": 0,
263
+ "arc_easy": 0,
264
+ "hellaswag": 0,
265
+ "piqa": 0
266
+ },
267
+ "pretty_env_info": "PyTorch version: 2.10.0+cu128\nIs debug build: False\nCUDA used to build PyTorch: 12.8\nROCM used to build PyTorch: N/A\n\nOS: Microsoft Windows 11 Pro (10.0.26200 64-bit)\nGCC version: Could not collect\nClang version: Could not collect\nCMake version: version 4.3.3\nLibc version: N/A\n\nPython version: 3.13.2 (tags/v3.13.2:4f8bb39, Feb 4 2025, 15:23:48) [MSC v.1942 64 bit (AMD64)] (64-bit runtime)\nPython platform: Windows-11-10.0.26200-SP0\nIs CUDA available: True\nCUDA runtime version: 13.3.73\r\nCUDA_MODULE_LOADING set to: \nGPU models and configuration: GPU 0: NVIDIA GeForce RTX 4070\nNvidia driver version: Could not collect\ncuDNN version: Could not collect\nIs XPU available: False\nHIP runtime version: N/A\nMIOpen runtime version: N/A\nIs XNNPACK available: True\nCaching allocator config: N/A\n\nCPU:\nName: AMD Ryzen 5 5600X 6-Core Processor \nManufacturer: AuthenticAMD\nFamily: 107\nArchitecture: 9\nProcessorType: 3\nDeviceID: CPU0\nCurrentClockSpeed: 3701\nMaxClockSpeed: 3701\nL2CacheSize: 3072\nL2CacheSpeed: None\nRevision: 8450\n\nVersions of relevant libraries:\n[pip3] numpy==2.3.5\n[pip3] torch==2.10.0+cu128\n[pip3] triton-windows==3.6.0.post26\n[conda] Could not collect",
268
+ "results": {
269
+ "arc_challenge": {
270
+ "acc,none": 0.17918088737201365,
271
+ "acc_norm,none": 0.21160409556313994,
272
+ "acc_norm_stderr,none": 0.011935916358632793,
273
+ "acc_stderr,none": 0.011207045216615686,
274
+ "alias": "arc_challenge",
275
+ "name": "arc_challenge",
276
+ "sample_len": 1172
277
+ },
278
+ "arc_easy": {
279
+ "acc,none": 0.4048821548821549,
280
+ "acc_norm,none": 0.3939393939393939,
281
+ "acc_norm_stderr,none": 0.010026305355981951,
282
+ "acc_stderr,none": 0.010072423960395665,
283
+ "alias": "arc_easy",
284
+ "name": "arc_easy",
285
+ "sample_len": 2376
286
+ },
287
+ "hellaswag": {
288
+ "acc,none": 0.2689703246365266,
289
+ "acc_norm,none": 0.27633937462656843,
290
+ "acc_norm_stderr,none": 0.004462727543055927,
291
+ "acc_stderr,none": 0.004425182676353205,
292
+ "alias": "hellaswag",
293
+ "name": "hellaswag",
294
+ "sample_len": 10042
295
+ },
296
+ "piqa": {
297
+ "acc,none": 0.588683351468988,
298
+ "acc_norm,none": 0.573993471164309,
299
+ "acc_norm_stderr,none": 0.011537375448519308,
300
+ "acc_stderr,none": 0.01148086057719274,
301
+ "alias": "piqa",
302
+ "name": "piqa",
303
+ "sample_len": 1838
304
+ }
305
+ },
306
+ "transformers_version": "5.14.1",
307
+ "upper_git_hash": null,
308
+ "versions": {
309
+ "arc_challenge": 1.0,
310
+ "arc_easy": 1.0,
311
+ "hellaswag": 1.0,
312
+ "piqa": 1.0
313
+ }
314
+ }
export_manifest.json ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_token_presentations": 0,
3
+ "checkpoint": "artifacts/runs/flightmix_10b_balanced_10m_muon_lrfix_20260921/checkpoint-tokens-10000000000",
4
+ "checkpoint_model_sha256": "4a7070feab2f6e6231597566e7049bab9e4acb283035674b357e33a1eabbda5f",
5
+ "cumulative_token_presentations": 10000000000,
6
+ "files": {
7
+ "LICENSE": {
8
+ "bytes": 11357,
9
+ "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4"
10
+ },
11
+ "NOTICE": {
12
+ "bytes": 581,
13
+ "sha256": "6125f403571b9c2bdf9995946836026822688f56db5ee15ac3e93292573e1ff2"
14
+ },
15
+ "README.md": {
16
+ "bytes": 5591,
17
+ "sha256": "59bcf55b27217ac76c00ecb3161c5f77c688076f6c8bfdaf046985d6e8e34120"
18
+ },
19
+ "TRAINING_DATA.md": {
20
+ "bytes": 1953,
21
+ "sha256": "29ede51040f52d51f6fd867c0e4c2f539021decbb598249b93cceccc0c929d12"
22
+ },
23
+ "chat_template.jinja": {
24
+ "bytes": 184,
25
+ "sha256": "df23563531f85f90a16699e28d1fe2458f8d6e46e9a4ab61a9ce0d3b1459bf8c"
26
+ },
27
+ "config.json": {
28
+ "bytes": 2205,
29
+ "sha256": "4d0918c0c25f9b8ab211f99c3636e3f70e2398800d5723b4dd768752448dc763"
30
+ },
31
+ "configuration_microloop.py": {
32
+ "bytes": 14396,
33
+ "sha256": "b30c3e8002d64a3cb3ce79b562bf7d28a35c6a5f5cd5ab03fb8cacb5e5aed640"
34
+ },
35
+ "evaluation/arithmark_3.json": {
36
+ "bytes": 4814,
37
+ "sha256": "f22aec4d51a6702830f280328a0df5141741e5752cf816c5c82b62e4bcd278c2"
38
+ },
39
+ "evaluation/open_slm.json": {
40
+ "bytes": 10854,
41
+ "sha256": "c47c9cf09f055e75842d158c0933e57612115f186ae69c66462374915a4d2fa9"
42
+ },
43
+ "generation_config.json": {
44
+ "bytes": 250,
45
+ "sha256": "c086c408dba55e547bac299549a8b7713c768cb94a52fd2043429b1564d76094"
46
+ },
47
+ "model.safetensors": {
48
+ "bytes": 39041336,
49
+ "sha256": "4a7070feab2f6e6231597566e7049bab9e4acb283035674b357e33a1eabbda5f"
50
+ },
51
+ "modeling_microloop.py": {
52
+ "bytes": 56187,
53
+ "sha256": "8c0c2e82238c562bceb740b251c3515e080c34adf8b6e32d719c071fc7e65312"
54
+ },
55
+ "prefix_lm.py": {
56
+ "bytes": 1792,
57
+ "sha256": "21c20eb64f9e6a83740f9cc65265cc962e73656b5bb560422824cd84c9c11363"
58
+ },
59
+ "tokenizer.json": {
60
+ "bytes": 265304,
61
+ "sha256": "c063fd42efccd8416d0375230767949356088cc430c8e74d4547438479889077"
62
+ },
63
+ "tokenizer_config.json": {
64
+ "bytes": 482,
65
+ "sha256": "87e2a284910c5738892c66e027fa8d9a9d2a4cdc7311a4e9503cffbb7997eeb8"
66
+ },
67
+ "training/corpus_contract.yaml": {
68
+ "bytes": 6657,
69
+ "sha256": "73cd71ff4f7849d939606bd77434df4697d590bdfe2202ba1681b267c63f6786"
70
+ },
71
+ "training/packed_metadata.json": {
72
+ "bytes": 7849,
73
+ "sha256": "299c06fc6281817997b2ac1f90a176d18b10136b8567f62d58013a0c2b7838ef"
74
+ },
75
+ "training/provenance.json": {
76
+ "bytes": 3026,
77
+ "sha256": "01ebc88c052474820381609e2a613a2c7209add45e9f4da3c777d441bd4d51b2"
78
+ }
79
+ },
80
+ "format_version": 1,
81
+ "license": "apache-2.0",
82
+ "model_id": "juinron/Hummingbird-V2",
83
+ "parameter_count": 9592720,
84
+ "release_name": "Hummingbird-V2",
85
+ "scores": {
86
+ "arc_challenge": 21.160409556313994,
87
+ "arc_easy": 39.39393939393939,
88
+ "arithmark_3": 36.0,
89
+ "hellaswag": 27.633937462656842,
90
+ "int_index": 9.556212826458404,
91
+ "piqa": 57.399347116430896
92
+ },
93
+ "tokenizer": "artifacts/runs/e3_tokenizers/tok_4k_digit",
94
+ "tokens_seen": 10000000000
95
+ }
generation_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "do_sample": false,
5
+ "eos_token_id": 2,
6
+ "output_attentions": false,
7
+ "output_hidden_states": false,
8
+ "pad_token_id": 0,
9
+ "transformers_version": "5.14.1",
10
+ "use_cache": false
11
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a7070feab2f6e6231597566e7049bab9e4acb283035674b357e33a1eabbda5f
3
+ size 39041336
modeling_microloop.py ADDED
@@ -0,0 +1,1192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small, HF-compatible causal bootstrap model used by the M0 gate.
2
+
3
+ The diffusion objective and sampler are deliberately separate modules. This model
4
+ provides the shared transformer backbone and a causal forward path so that the
5
+ project can validate shape correctness, parameter accounting, and reproducibility
6
+ before any expensive data work begins.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from hashlib import sha256
13
+ from typing import Optional
14
+
15
+ import torch
16
+ from torch import Tensor, nn
17
+ from torch.nn import functional as F
18
+
19
+ from .configuration_microloop import MicroLoopConfig
20
+ from .prefix_lm import build_prefix_lm_mask
21
+
22
+ try:
23
+ from transformers import PreTrainedModel
24
+ from transformers.generation import GenerationMixin
25
+ from transformers.utils import ModelOutput
26
+ except ImportError: # pragma: no cover - only used in a minimal environment.
27
+
28
+ class GenerationMixin: # type: ignore[no-redef]
29
+ pass
30
+
31
+ class ModelOutput: # type: ignore[no-redef]
32
+ pass
33
+
34
+ class PreTrainedModel(nn.Module): # type: ignore[no-redef]
35
+ config_class = MicroLoopConfig
36
+ base_model_prefix = "microloop"
37
+
38
+ def __init__(self, config: MicroLoopConfig) -> None:
39
+ super().__init__()
40
+ self.config = config
41
+
42
+
43
+ @dataclass
44
+ class MicroLoopCausalLMOutput(ModelOutput):
45
+ """Minimal output object with both attribute and mapping-style access."""
46
+
47
+ logits: Optional[Tensor] = None
48
+ loss: Optional[Tensor] = None
49
+ hidden_states: Optional[Tensor] = None
50
+ loop_applications: Optional[int] = None
51
+
52
+ def __getitem__(self, key: str):
53
+ return getattr(self, key)
54
+
55
+
56
+ class RMSNorm(nn.Module):
57
+ def __init__(self, hidden_size: int, eps: float) -> None:
58
+ super().__init__()
59
+ self.weight = nn.Parameter(torch.ones(hidden_size))
60
+ self.eps = eps
61
+
62
+ def forward(self, hidden_states: Tensor) -> Tensor:
63
+ # Explicit computation rather than the fused ``F.rms_norm`` kernel:
64
+ # the fused kernel selects implementations based on process-level state
65
+ # and produces context-dependent numerics inside the training process
66
+ # (the 2026-08-05 provenance incident). This explicit path is
67
+ # deterministic everywhere; the small speed cost is acceptable here.
68
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
69
+ return (hidden_states / torch.sqrt(variance + self.eps)) * self.weight
70
+
71
+
72
+ class UnweightedRMSNorm(nn.Module):
73
+ """Parameter-free RMS normalization used by the mHC routing projections."""
74
+
75
+ def __init__(self, eps: float) -> None:
76
+ super().__init__()
77
+ self.eps = eps
78
+
79
+ def forward(self, hidden_states: Tensor) -> Tensor:
80
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
81
+ return hidden_states * torch.rsqrt(variance + self.eps).to(hidden_states.dtype)
82
+
83
+
84
+ class NGramMemory(nn.Module):
85
+ """Small causal suffix-N-gram memory for controlled experiments.
86
+
87
+ The lookup mode keeps raw token IDs unchanged, which is deliberately safe for
88
+ digits and mathematical symbols. Each order/head has its own deterministic
89
+ hash table; the projected value is gated by the current hidden state and the
90
+ value projection is zero-initialized by ``MicroLoopForDiffusionLM``.
91
+ """
92
+
93
+ def __init__(self, config: MicroLoopConfig) -> None:
94
+ super().__init__()
95
+ settings = dict(config.ngram_memory)
96
+ self.mode = str(settings.get("mode", "lookup"))
97
+ self.hash_version = str(settings.get("hash_version", "legacy_v1"))
98
+ self.orders = tuple(int(order) for order in settings.get("orders", [2, 3]))
99
+ self.num_hash_heads = int(settings.get("num_hash_heads", 2))
100
+ self.num_buckets = int(settings.get("num_buckets", 16_384))
101
+ self.embedding_dim = int(settings.get("embedding_dim", 16))
102
+ self.composition_scale = float(settings.get("composition_scale", 0.1))
103
+ self.eps = config.rms_norm_eps
104
+ # Fixed, independent bases; no global RNG or checkpoint tensors needed.
105
+ # Arithmetic modulo 2**31-1 keeps int64 products below 2**62.
106
+ self.hash_bases = tuple(
107
+ 2 + int.from_bytes(sha256(f"microloop-ngram-v2:{i}".encode()).digest()[:4], "big")
108
+ % (2**31 - 3)
109
+ for i in range(len(self.orders) * self.num_hash_heads)
110
+ )
111
+
112
+ if self.mode == "lookup":
113
+ table_count = len(self.orders) * self.num_hash_heads
114
+ self.tables = nn.ModuleList(
115
+ nn.Embedding(self.num_buckets, self.embedding_dim)
116
+ for _ in range(table_count)
117
+ )
118
+ memory_width = table_count * self.embedding_dim
119
+ self.key_proj = nn.Linear(memory_width, config.hidden_size, bias=False)
120
+ self.value_proj = nn.Linear(memory_width, config.hidden_size, bias=False)
121
+ else:
122
+ self.tables = nn.ModuleList()
123
+ self.key_proj = None
124
+ self.value_proj = None
125
+
126
+ def _hash_indices(
127
+ self,
128
+ input_ids: Tensor,
129
+ order: int,
130
+ table_index: int,
131
+ document_ids: Tensor | None = None,
132
+ ) -> tuple[Tensor, Tensor]:
133
+ multiplier = 1_000_003 + table_index * 104_729
134
+ coefficients = torch.arange(1, order + 1, device=input_ids.device, dtype=torch.long)
135
+ coefficients = coefficients * multiplier
136
+ if self.hash_version == "polynomial_v2":
137
+ prime = 2**31 - 1
138
+ base = self.hash_bases[table_index]
139
+ padded = F.pad(input_ids, (order - 1, 0), value=0)
140
+ windows = padded.unfold(1, order, 1)
141
+ hashed = torch.zeros_like(input_ids)
142
+ for position in range(order):
143
+ hashed = (hashed * base + windows[..., position] + 1) % prime
144
+ hashed = hashed % self.num_buckets
145
+ elif order in (2, 3) and input_ids.size(1) >= order:
146
+ hashed = input_ids * coefficients[-1]
147
+ for lag in range(1, order):
148
+ shifted = F.pad(input_ids[:, :-lag], (lag, 0), value=0)
149
+ hashed = hashed + shifted * coefficients[-lag - 1]
150
+ else:
151
+ padded = F.pad(input_ids, (order - 1, 0), value=0)
152
+ windows = padded.unfold(1, order, 1)
153
+ hashed = (windows * coefficients).sum(dim=-1)
154
+ if self.hash_version == "legacy_v1":
155
+ hashed = (hashed + (table_index + 1) * 7_919) % self.num_buckets
156
+ positions = torch.arange(input_ids.size(1), device=input_ids.device)
157
+ valid = positions.unsqueeze(0) >= order - 1
158
+ if document_ids is not None:
159
+ if order in (2, 3) and input_ids.size(1) >= order:
160
+ for lag in range(1, order):
161
+ shifted_documents = F.pad(document_ids[:, :-lag], (lag, 0), value=-1)
162
+ valid = valid & document_ids.eq(shifted_documents)
163
+ else:
164
+ padded_documents = F.pad(document_ids, (order - 1, 0), value=-1)
165
+ document_windows = padded_documents.unfold(1, order, 1)
166
+ valid = valid & document_windows.eq(document_windows[..., :1]).all(dim=-1)
167
+ return hashed, valid
168
+
169
+ def _rms_normalize(self, hidden_states: Tensor) -> Tensor:
170
+ variance = hidden_states.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
171
+ return hidden_states * torch.rsqrt(variance + self.eps).to(hidden_states.dtype)
172
+
173
+ def _forward_flat(
174
+ self,
175
+ input_ids: Tensor,
176
+ hidden_states: Tensor,
177
+ token_embeddings: Tensor | None = None,
178
+ document_ids: Tensor | None = None,
179
+ ) -> Tensor:
180
+ if self.mode == "parameter_free":
181
+ if token_embeddings is None:
182
+ raise ValueError("parameter-free ngram memory requires token embeddings")
183
+ embeddings = token_embeddings
184
+ outputs = []
185
+ for order in self.orders:
186
+ padded = F.pad(embeddings, (0, 0, order - 1, 0))
187
+ windows = padded.unfold(1, order, 1)
188
+ outputs.append(windows.mean(dim=-1))
189
+ result = torch.stack(outputs, dim=0).mean(dim=0)
190
+ positions = torch.arange(input_ids.size(1), device=input_ids.device)
191
+ valid = positions.unsqueeze(0) >= max(self.orders) - 1
192
+ if document_ids is not None:
193
+ padded_documents = F.pad(
194
+ document_ids, (max(self.orders) - 1, 0), value=-1
195
+ )
196
+ document_windows = padded_documents.unfold(1, max(self.orders), 1)
197
+ valid = valid & document_windows.eq(document_windows[..., :1]).all(dim=-1)
198
+ return result * valid.unsqueeze(-1).to(result.dtype) * self.composition_scale
199
+
200
+ retrieved = []
201
+ table_index = 0
202
+ for order in self.orders:
203
+ for _ in range(self.num_hash_heads):
204
+ indices, valid = self._hash_indices(
205
+ input_ids, order, table_index, document_ids=document_ids
206
+ )
207
+ values = self.tables[table_index](indices)
208
+ retrieved.append(values * valid.unsqueeze(-1).to(values.dtype))
209
+ table_index += 1
210
+ memory = torch.cat(retrieved, dim=-1)
211
+ assert self.key_proj is not None and self.value_proj is not None
212
+ key = self.key_proj(memory)
213
+ value = self.value_proj(memory)
214
+ query_norm = self._rms_normalize(hidden_states)
215
+ key_norm = self._rms_normalize(key)
216
+ gate = torch.sigmoid((query_norm * key_norm).sum(dim=-1) / self.key_proj.out_features**0.5)
217
+ return value * gate.unsqueeze(-1)
218
+
219
+ def forward(
220
+ self,
221
+ input_ids: Tensor,
222
+ hidden_states: Tensor,
223
+ token_embeddings: Tensor | None = None,
224
+ document_ids: Tensor | None = None,
225
+ ) -> Tensor:
226
+ """Return a residual update with the same shape as ``hidden_states``."""
227
+
228
+ if input_ids.dim() != 2:
229
+ raise ValueError("ngram memory input_ids must have shape [batch, sequence]")
230
+ if hidden_states.dim() == 3:
231
+ if hidden_states.shape[:2] != input_ids.shape:
232
+ raise ValueError("ngram memory inputs must have matching batch and sequence")
233
+ return self._forward_flat(
234
+ input_ids, hidden_states, token_embeddings, document_ids
235
+ )
236
+ if hidden_states.dim() == 4:
237
+ batch, sequence, streams, hidden = hidden_states.shape
238
+ if (batch, sequence) != input_ids.shape:
239
+ raise ValueError("ngram memory inputs must have matching batch and sequence")
240
+ flat_ids = input_ids.unsqueeze(1).expand(-1, streams, -1).reshape(-1, sequence)
241
+ flat_hidden = hidden_states.permute(0, 2, 1, 3).reshape(-1, sequence, hidden)
242
+ flat_documents = None
243
+ if document_ids is not None:
244
+ if document_ids.shape != (batch, sequence):
245
+ raise ValueError("document_ids must match input_ids")
246
+ flat_documents = document_ids.unsqueeze(1).expand(
247
+ -1, streams, -1
248
+ ).reshape(-1, sequence)
249
+ flat_embeddings = None
250
+ if token_embeddings is not None:
251
+ if token_embeddings.shape != (batch, sequence, hidden):
252
+ raise ValueError("token_embeddings must match the unstreamed hidden shape")
253
+ flat_embeddings = token_embeddings.unsqueeze(1).expand(
254
+ -1, streams, -1, -1
255
+ ).reshape(-1, sequence, hidden)
256
+ update = self._forward_flat(
257
+ flat_ids, flat_hidden, flat_embeddings, flat_documents
258
+ )
259
+ return update.view(batch, streams, sequence, hidden).permute(0, 2, 1, 3)
260
+ raise ValueError("ngram memory hidden_states must have shape [batch, sequence, hidden]")
261
+
262
+
263
+ class ManifoldHyperConnection(nn.Module):
264
+ """Dynamic manifold-constrained routing around one residual sublayer.
265
+
266
+ The residual state has shape ``[batch, sequence, streams, hidden]``. The
267
+ routing matrix is projected onto the Birkhoff polytope with Sinkhorn-Knopp
268
+ iterations, while sigmoid-constrained read/write weights collapse the
269
+ streams for the inner sublayer and place its output back onto the streams.
270
+ """
271
+
272
+ def __init__(self, config: MicroLoopConfig) -> None:
273
+ super().__init__()
274
+ self.multiplier = config.mhc_multiplier
275
+ self.sinkhorn_iterations = config.mhc_sinkhorn_iterations
276
+ self.eps = config.mhc_eps
277
+ self.input_norm = UnweightedRMSNorm(config.rms_norm_eps)
278
+ mix = (2 + self.multiplier) * self.multiplier
279
+ self.fn = nn.Parameter(torch.empty(mix, self.multiplier * config.hidden_size))
280
+ self.base = nn.Parameter(torch.empty(mix))
281
+ self.scale = nn.Parameter(torch.empty(3))
282
+
283
+ def forward(self, hidden_streams: Tensor) -> tuple[Tensor, Tensor, Tensor]:
284
+ streams = self.multiplier
285
+ flat = self.input_norm(hidden_streams.flatten(start_dim=2).float())
286
+ raw = F.linear(flat, self.fn.float())
287
+ pre_raw, post_raw, residual_raw = raw.split(
288
+ [streams, streams, streams * streams], dim=-1
289
+ )
290
+ pre_base, post_base, residual_base = self.base.float().split(
291
+ [streams, streams, streams * streams]
292
+ )
293
+ pre_scale, post_scale, residual_scale = self.scale.float().unbind(0)
294
+ pre = torch.sigmoid(pre_raw * pre_scale + pre_base) + self.eps
295
+ post = 2.0 * torch.sigmoid(post_raw * post_scale + post_base)
296
+ residual_logits = (
297
+ residual_raw.view(*residual_raw.shape[:-1], streams, streams) * residual_scale
298
+ + residual_base.view(streams, streams)
299
+ )
300
+ residual = torch.softmax(residual_logits, dim=-1) + self.eps
301
+ residual = residual / (residual.sum(dim=-2, keepdim=True) + self.eps)
302
+ for _ in range(self.sinkhorn_iterations - 1):
303
+ residual = residual / (residual.sum(dim=-1, keepdim=True) + self.eps)
304
+ residual = residual / (residual.sum(dim=-2, keepdim=True) + self.eps)
305
+ collapsed = (pre.unsqueeze(-1) * hidden_streams.float()).sum(dim=2)
306
+ return (
307
+ post.to(hidden_streams.dtype),
308
+ residual.to(hidden_streams.dtype),
309
+ collapsed.to(hidden_streams.dtype),
310
+ )
311
+
312
+ @staticmethod
313
+ def merge(
314
+ hidden_streams: Tensor, sublayer_output: Tensor, post: Tensor, residual: Tensor
315
+ ) -> Tensor:
316
+ mixed = torch.matmul(residual, hidden_streams)
317
+ return mixed + post.unsqueeze(-1) * sublayer_output.unsqueeze(2)
318
+
319
+
320
+ class ManifoldHyperHead(nn.Module):
321
+ """Dynamically collapse the final mHC residual streams back to model width."""
322
+
323
+ def __init__(self, config: MicroLoopConfig) -> None:
324
+ super().__init__()
325
+ self.multiplier = config.mhc_multiplier
326
+ self.eps = config.mhc_eps
327
+ self.input_norm = UnweightedRMSNorm(config.rms_norm_eps)
328
+ self.fn = nn.Parameter(
329
+ torch.empty(self.multiplier, self.multiplier * config.hidden_size)
330
+ )
331
+ self.base = nn.Parameter(torch.empty(self.multiplier))
332
+ self.scale = nn.Parameter(torch.empty(1))
333
+
334
+ def forward(self, hidden_streams: Tensor) -> Tensor:
335
+ flat = self.input_norm(hidden_streams.flatten(start_dim=2).float())
336
+ raw = F.linear(flat, self.fn.float())
337
+ pre = torch.sigmoid(raw * self.scale.float() + self.base.float()) + self.eps
338
+ return (pre.unsqueeze(-1) * hidden_streams.float()).sum(dim=2).to(hidden_streams.dtype)
339
+
340
+
341
+ def _rotate_half(x: Tensor) -> Tensor:
342
+ x_even = x[..., ::2]
343
+ x_odd = x[..., 1::2]
344
+ return torch.stack((-x_odd, x_even), dim=-1).flatten(-2)
345
+
346
+
347
+ def _rope_tables(max_position: int, head_dim: int, theta: float) -> tuple[Tensor, Tensor]:
348
+ """Build interleaved rotary tables once, in float32 for stable reuse."""
349
+
350
+ inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.float32) / head_dim))
351
+ positions = torch.arange(max_position, device=inv_freq.device, dtype=torch.float32)
352
+ angles = positions.unsqueeze(-1) * inv_freq
353
+ angles = torch.stack((angles, angles), dim=-1).flatten(-2)
354
+ return angles.cos(), angles.sin()
355
+
356
+
357
+ def _apply_rope(q: Tensor, k: Tensor, cos: Tensor, sin: Tensor) -> tuple[Tensor, Tensor]:
358
+ """Apply cached interleaved rotary embeddings to query and key tensors."""
359
+
360
+ return q * cos + _rotate_half(q) * sin, k * cos + _rotate_half(k) * sin
361
+
362
+
363
+ class GroupedQueryAttention(nn.Module):
364
+ """Grouped-query self-attention with explicit Q/K/V projections.
365
+
366
+ Attention uses an explicit scaled-dot-product implementation (matmul +
367
+ softmax) rather than ``F.scaled_dot_product_attention`` because the fused
368
+ kernels select implementations based on process-level state and produce
369
+ deterministic but context-dependent results: evaluations inside the
370
+ training process then disagree with evaluations of the same saved
371
+ checkpoint in a fresh process (the 2026-08-05 provenance incident). The
372
+ explicit math path is deterministic everywhere at the cost of a small
373
+ amount of speed, which is acceptable at this model size.
374
+ """
375
+
376
+ def __init__(self, config: MicroLoopConfig) -> None:
377
+ super().__init__()
378
+ self.num_heads = config.num_attention_heads
379
+ self.num_key_value_heads = config.num_key_value_heads
380
+ self.head_dim = config.head_dimension
381
+ self.num_groups = self.num_heads // self.num_key_value_heads
382
+ self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
383
+ self.k_proj = nn.Linear(
384
+ config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
385
+ )
386
+ self.v_proj = nn.Linear(
387
+ config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
388
+ )
389
+ self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
390
+ self.output_gate = (
391
+ nn.Linear(config.hidden_size, self.num_heads, bias=False)
392
+ if config.attention_output_gate
393
+ else None
394
+ )
395
+ self.output_gate_activation = config.attention_output_gate_activation
396
+ self.rope_theta = config.rope_theta
397
+ self.attention_implementation = config.attention_implementation
398
+ self.qk_norm_position = config.qk_norm_position
399
+ if config.qk_norm == "per_head":
400
+ # One affine scale is shared by all Q heads and one by all K heads;
401
+ # normalization itself is applied independently over each head.
402
+ self.q_norm: RMSNorm | None = RMSNorm(self.head_dim, config.rms_norm_eps)
403
+ self.k_norm: RMSNorm | None = RMSNorm(self.head_dim, config.rms_norm_eps)
404
+ else:
405
+ self.q_norm = None
406
+ self.k_norm = None
407
+
408
+ def forward(
409
+ self,
410
+ hidden_states: Tensor,
411
+ attention_mask: Tensor | None = None,
412
+ position_ids: Tensor | None = None,
413
+ rope_embeddings: tuple[Tensor, Tensor] | None = None,
414
+ first_value_states: Tensor | None = None,
415
+ value_residual_scales: Tensor | None = None,
416
+ ) -> Tensor:
417
+ batch, sequence, _ = hidden_states.shape
418
+ q = self.q_proj(hidden_states).view(batch, sequence, self.num_heads, self.head_dim)
419
+ k = self.k_proj(hidden_states).view(
420
+ batch, sequence, self.num_key_value_heads, self.head_dim
421
+ )
422
+ v = self.v_proj(hidden_states).view(
423
+ batch, sequence, self.num_key_value_heads, self.head_dim
424
+ )
425
+ q = q.transpose(1, 2)
426
+ k = k.transpose(1, 2)
427
+ v = v.transpose(1, 2)
428
+ if first_value_states is not None:
429
+ if value_residual_scales is None:
430
+ raise ValueError("value residual states require value_residual_scales")
431
+ if first_value_states.shape != v.shape:
432
+ raise ValueError("first_value_states must match the current value-state shape")
433
+ v = value_residual_scales[0] * v + value_residual_scales[1] * first_value_states
434
+ if position_ids is None:
435
+ position_ids = torch.arange(sequence, device=hidden_states.device).expand(batch, -1)
436
+ if position_ids.shape != (batch, sequence):
437
+ raise ValueError(
438
+ f"position_ids must have shape [batch, sequence], got {tuple(position_ids.shape)}"
439
+ )
440
+ if rope_embeddings is None:
441
+ table_cos, table_sin = _rope_tables(sequence, self.head_dim, self.rope_theta)
442
+ cos = table_cos[position_ids].unsqueeze(1).to(q.dtype)
443
+ sin = table_sin[position_ids].unsqueeze(1).to(q.dtype)
444
+ else:
445
+ cos, sin = rope_embeddings
446
+ if self.q_norm is not None and self.qk_norm_position == "pre_rope":
447
+ # Normalize in the unrotated head basis. RMS normalization with
448
+ # learned per-coordinate scales does not commute with RoPE; doing
449
+ # it first preserves RoPE's relative-position shift equivariance.
450
+ q = self.q_norm(q)
451
+ assert self.k_norm is not None
452
+ k = self.k_norm(k)
453
+ q, k = _apply_rope(q, k, cos, sin)
454
+ if self.q_norm is not None and self.qk_norm_position == "post_rope":
455
+ q = self.q_norm(q)
456
+ assert self.k_norm is not None
457
+ k = self.k_norm(k)
458
+
459
+ if self.num_heads % self.num_key_value_heads != 0:
460
+ raise ValueError(
461
+ f"num_heads {self.num_heads} must divide num_key_value_heads "
462
+ f"{self.num_key_value_heads}"
463
+ )
464
+ if attention_mask is None:
465
+ visible: Tensor | None = None
466
+ is_causal = True
467
+ else:
468
+ # A 2-D mask uses the conventional HF meaning: one means visible.
469
+ if attention_mask.shape == (batch, sequence):
470
+ causal = torch.tril(
471
+ torch.ones(sequence, sequence, device=q.device, dtype=torch.bool)
472
+ )
473
+ visible = causal.unsqueeze(0).unsqueeze(0) & attention_mask.bool().unsqueeze(
474
+ 1
475
+ ).unsqueeze(2)
476
+ is_causal = False
477
+ elif attention_mask.shape == (batch, sequence, sequence):
478
+ visible = attention_mask.bool().unsqueeze(1)
479
+ is_causal = False
480
+ else:
481
+ raise ValueError(
482
+ "attention_mask must have shape [batch, sequence] or "
483
+ "[batch, sequence, sequence], "
484
+ f"got {tuple(attention_mask.shape)}"
485
+ )
486
+ # GQA: repeat the KV heads so every query head has its own K/V.
487
+ repeat = self.num_heads // self.num_key_value_heads
488
+ if repeat > 1:
489
+ k = k.repeat_interleave(repeat, dim=1)
490
+ v = v.repeat_interleave(repeat, dim=1)
491
+ if self.attention_implementation == "sdpa":
492
+ attended = F.scaled_dot_product_attention(
493
+ q, k, v, attn_mask=visible, dropout_p=0.0, is_causal=is_causal
494
+ )
495
+ else:
496
+ scores = torch.matmul(q, k.transpose(-2, -1)) / float(self.head_dim) ** 0.5
497
+ if is_causal:
498
+ seq_ids = torch.arange(sequence, device=scores.device)
499
+ visible = seq_ids.unsqueeze(0) <= seq_ids.unsqueeze(1)
500
+ visible = visible.expand(batch, self.num_heads, sequence, sequence)
501
+ if visible is not None:
502
+ scores = scores.masked_fill(~visible, float("-inf"))
503
+ probs = torch.softmax(scores, dim=-1)
504
+ attended = torch.matmul(probs, v)
505
+ if self.output_gate is not None:
506
+ gate_logits = self.output_gate(hidden_states)
507
+ gate = (
508
+ torch.sigmoid(gate_logits)
509
+ if self.output_gate_activation == "sigmoid"
510
+ else F.silu(gate_logits)
511
+ )
512
+ gate = gate.transpose(1, 2).unsqueeze(-1)
513
+ attended = attended * gate
514
+ attended = attended.transpose(1, 2).contiguous().view(batch, sequence, -1)
515
+ return self.o_proj(attended)
516
+
517
+
518
+ class LowRankFFNProjection(nn.Module):
519
+ """CoLA-inspired B(activation(A(x))); outer SwiGLU remains in the block."""
520
+
521
+ def __init__(self, in_features: int, out_features: int, rank: int, activation: str):
522
+ super().__init__()
523
+ self.reduce = nn.Linear(in_features, rank, bias=False)
524
+ self.expand = nn.Linear(rank, out_features, bias=False)
525
+ self.activation = nn.SiLU() if activation == "silu" else nn.Identity()
526
+
527
+ def forward(self, hidden_states: Tensor) -> Tensor:
528
+ return self.expand(self.activation(self.reduce(hidden_states)))
529
+
530
+
531
+ class MicroLoopBlock(nn.Module):
532
+ """Pre-norm transformer block with SwiGLU feed-forward network."""
533
+
534
+ def __init__(self, config: MicroLoopConfig, layer_index: int) -> None:
535
+ super().__init__()
536
+ self.attn_norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
537
+ self.attn = GroupedQueryAttention(config)
538
+ self.ffn_norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
539
+ if config.ffn_rank is None:
540
+ self.ffn_gate = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
541
+ self.ffn_up = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
542
+ self.ffn_down = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
543
+ else:
544
+ self.ffn_gate = LowRankFFNProjection(
545
+ config.hidden_size, config.intermediate_size,
546
+ config.ffn_rank, config.ffn_factor_activation,
547
+ )
548
+ self.ffn_up = LowRankFFNProjection(
549
+ config.hidden_size, config.intermediate_size,
550
+ config.ffn_rank, config.ffn_factor_activation,
551
+ )
552
+ self.ffn_down = LowRankFFNProjection(
553
+ config.intermediate_size, config.hidden_size,
554
+ config.ffn_rank, config.ffn_factor_activation,
555
+ )
556
+ self.use_mhc = config.mhc_multiplier > 1
557
+ if self.use_mhc:
558
+ self.attn_mhc = ManifoldHyperConnection(config)
559
+ self.ffn_mhc = ManifoldHyperConnection(config)
560
+ self.use_attn_residuals = config.attn_res_block_size is not None
561
+ self.value_residual_scales = (
562
+ nn.Parameter(torch.tensor([1.0, 0.0]))
563
+ if config.value_residual.get("enabled", False) and layer_index > 0
564
+ else None
565
+ )
566
+ if self.use_attn_residuals:
567
+ self.attn_res_norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
568
+ self.ffn_res_norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
569
+ self.attn_res_proj = nn.Linear(config.hidden_size, 1, bias=False)
570
+ self.ffn_res_proj = nn.Linear(config.hidden_size, 1, bias=False)
571
+ clamp = dict(config.swiglu_clamp)
572
+ self.swiglu_clamp_enabled = bool(clamp.get("enabled", False))
573
+ self.swiglu_linear_min = float(clamp.get("linear_min", -10.0))
574
+ self.swiglu_linear_max = float(clamp.get("linear_max", 10.0))
575
+ self.swiglu_gate_max = float(clamp.get("gate_max", 10.0))
576
+
577
+ def forward(
578
+ self,
579
+ hidden_states: Tensor,
580
+ attention_mask: Tensor | None = None,
581
+ position_ids: Tensor | None = None,
582
+ rope_embeddings: tuple[Tensor, Tensor] | None = None,
583
+ block_residuals: list[Tensor] | None = None,
584
+ first_value_states: Tensor | None = None,
585
+ ) -> Tensor:
586
+ if self.use_mhc:
587
+ attn_post, attn_residual, attn_input = self.attn_mhc(hidden_states)
588
+ attn_output = self.attn(
589
+ self.attn_norm(attn_input),
590
+ attention_mask,
591
+ position_ids,
592
+ rope_embeddings,
593
+ first_value_states=first_value_states,
594
+ value_residual_scales=self.value_residual_scales,
595
+ )
596
+ hidden_states = self.attn_mhc.merge(
597
+ hidden_states, attn_output, attn_post, attn_residual
598
+ )
599
+ ffn_post, ffn_residual, ffn_input = self.ffn_mhc(hidden_states)
600
+ normalized = self.ffn_norm(ffn_input)
601
+ gate_linear = self.ffn_gate(normalized)
602
+ up_linear = self.ffn_up(normalized)
603
+ if self.swiglu_clamp_enabled:
604
+ gate_linear = gate_linear.clamp(self.swiglu_linear_min, self.swiglu_linear_max)
605
+ up_linear = up_linear.clamp(self.swiglu_linear_min, self.swiglu_linear_max)
606
+ gate = F.silu(gate_linear)
607
+ if self.swiglu_clamp_enabled:
608
+ gate = gate.clamp(max=self.swiglu_gate_max)
609
+ ffn_output = self.ffn_down(gate * up_linear)
610
+ return self.ffn_mhc.merge(hidden_states, ffn_output, ffn_post, ffn_residual)
611
+ if self.use_attn_residuals and block_residuals:
612
+ residual_stack = torch.stack(block_residuals, dim=-2)
613
+ scores = torch.cat(
614
+ [self.attn_res_proj(self.attn_res_norm(state)) for state in block_residuals], dim=-1
615
+ )
616
+ hidden_states = hidden_states + (
617
+ torch.softmax(scores, dim=-1).unsqueeze(-1) * residual_stack
618
+ ).sum(dim=-2)
619
+ hidden_states = hidden_states + self.attn(
620
+ self.attn_norm(hidden_states),
621
+ attention_mask,
622
+ position_ids,
623
+ rope_embeddings,
624
+ first_value_states=first_value_states,
625
+ value_residual_scales=self.value_residual_scales,
626
+ )
627
+ if self.use_attn_residuals and block_residuals:
628
+ residual_stack = torch.stack(block_residuals, dim=-2)
629
+ scores = torch.cat(
630
+ [self.ffn_res_proj(self.ffn_res_norm(state)) for state in block_residuals], dim=-1
631
+ )
632
+ hidden_states = hidden_states + (
633
+ torch.softmax(scores, dim=-1).unsqueeze(-1) * residual_stack
634
+ ).sum(dim=-2)
635
+ ffn_input = self.ffn_norm(hidden_states)
636
+ gate_linear = self.ffn_gate(ffn_input)
637
+ up_linear = self.ffn_up(ffn_input)
638
+ if self.swiglu_clamp_enabled:
639
+ gate_linear = gate_linear.clamp(self.swiglu_linear_min, self.swiglu_linear_max)
640
+ up_linear = up_linear.clamp(self.swiglu_linear_min, self.swiglu_linear_max)
641
+ gate = F.silu(gate_linear)
642
+ if self.swiglu_clamp_enabled:
643
+ gate = gate.clamp(max=self.swiglu_gate_max)
644
+ ffn_output = self.ffn_down(gate * up_linear)
645
+ return hidden_states + ffn_output
646
+
647
+
648
+ class MicroLoopPreTrainedModel(PreTrainedModel):
649
+ config_class = MicroLoopConfig
650
+ base_model_prefix = "microloop"
651
+
652
+
653
+ class MicroLoopForDiffusionLM(MicroLoopPreTrainedModel, GenerationMixin):
654
+ """Backbone plus tied output head for causal bootstrap and diffusion training."""
655
+
656
+ _tied_weights_keys = {"lm_head.weight": "embed_tokens.weight"}
657
+
658
+ def __init__(self, config: MicroLoopConfig) -> None:
659
+ config.validate()
660
+ super().__init__(config)
661
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
662
+ self.layers = nn.ModuleList(
663
+ [MicroLoopBlock(config, index) for index in range(config.num_hidden_layers)]
664
+ )
665
+ looping = config.looping
666
+ self.loop_gates = (
667
+ nn.Parameter(
668
+ torch.zeros(
669
+ max(
670
+ 0,
671
+ int(
672
+ looping.get(
673
+ "max_loop_count", looping.get("maximum_serving_loops", 3)
674
+ )
675
+ )
676
+ - 1,
677
+ ),
678
+ config.hidden_size,
679
+ )
680
+ )
681
+ if looping.get("mode", "layer") == "block" and looping.get("gated", False)
682
+ else None
683
+ )
684
+ self.ngram_memory = (
685
+ NGramMemory(config) if config.ngram_memory.get("enabled", False) else None
686
+ )
687
+ self.ngram_memory_layer = (
688
+ int(config.ngram_memory["insertion_layer"])
689
+ if self.ngram_memory is not None
690
+ else None
691
+ )
692
+ digit_settings = config.digit_position_embedding
693
+ self.digit_position_embedding = (
694
+ nn.Embedding(
695
+ int(digit_settings.get("max_positions", 128)), config.hidden_size
696
+ )
697
+ if digit_settings.get("enabled", False)
698
+ else None
699
+ )
700
+ self.digit_token_ids = frozenset(
701
+ int(token_id) for token_id in digit_settings.get("digit_token_ids", [])
702
+ )
703
+ self.register_buffer(
704
+ "digit_token_ids_tensor",
705
+ torch.tensor(sorted(self.digit_token_ids), dtype=torch.long),
706
+ persistent=False,
707
+ )
708
+ self.mhc_head = ManifoldHyperHead(config) if config.mhc_multiplier > 1 else None
709
+ self.norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
710
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
711
+ self.mtp_proj = (
712
+ nn.Linear(config.hidden_size, config.hidden_size, bias=False)
713
+ if config.mtp_enabled
714
+ else None
715
+ )
716
+ rope_cos, rope_sin = _rope_tables(
717
+ config.max_position_embeddings, config.head_dimension, config.rope_theta
718
+ )
719
+ # PERSISTENT buffers on purpose: transformers 5.x ``from_pretrained``
720
+ # re-initializes non-persistent buffers that are missing from the
721
+ # checkpoint (``_initialize_missing_keys`` -> ``initialize_weights``),
722
+ # overwriting the rotary tables with garbage. That made every fresh-
723
+ # process evaluation of saved checkpoints compute with corrupted rope
724
+ # tables (the historical "external collapse" at ~0.03 accuracy was this
725
+ # artifact). Persisting the tables makes the saved checkpoint carry
726
+ # exactly the tables used in training.
727
+ self.register_buffer("rope_cos", rope_cos, persistent=True)
728
+ self.register_buffer("rope_sin", rope_sin, persistent=True)
729
+ if config.tie_word_embeddings:
730
+ self.lm_head.weight = self.embed_tokens.weight
731
+ # Canonical HF pattern: post_init() installs all_tied_weights_keys and
732
+ # dispatches _initialize_weights per module.
733
+ self.post_init()
734
+ if self.digit_position_embedding is not None:
735
+ nn.init.zeros_(self.digit_position_embedding.weight)
736
+ if self.ngram_memory is not None and self.ngram_memory.value_proj is not None:
737
+ nn.init.zeros_(self.ngram_memory.value_proj.weight)
738
+
739
+ def _reset_rope_buffers(self) -> None:
740
+ """Recompute the rotary tables from the config (they are deterministic)."""
741
+
742
+ rope_cos, rope_sin = _rope_tables(
743
+ self.config.max_position_embeddings,
744
+ self.config.head_dimension,
745
+ self.config.rope_theta,
746
+ )
747
+ self.rope_cos.copy_(rope_cos)
748
+ self.rope_sin.copy_(rope_sin)
749
+
750
+ def _initialize_weights(self, module: nn.Module, is_custom_code: bool = False) -> None:
751
+ # The caller controls the RNG through seed_everything; this method performs
752
+ # no hidden reseeding and is therefore reproducible by construction.
753
+ if getattr(module, "_is_hf_initialized", False):
754
+ return
755
+ if module is self:
756
+ # The main module owns the rotary tables. transformers 5.x
757
+ # re-initializes buffers that are missing from a loaded checkpoint
758
+ # ("_initialize_missing_keys"), which zeroes/garbles the tables;
759
+ # restore the deterministic canonical tables here instead.
760
+ self._reset_rope_buffers()
761
+ if isinstance(module, (nn.Linear, nn.Embedding)):
762
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
763
+ if getattr(module, "bias", None) is not None:
764
+ nn.init.zeros_(module.bias)
765
+ elif isinstance(module, ManifoldHyperConnection):
766
+ nn.init.normal_(module.fn, mean=0.0, std=0.02)
767
+ nn.init.zeros_(module.base)
768
+ nn.init.constant_(module.scale, self.config.mhc_init_scale)
769
+ elif isinstance(module, ManifoldHyperHead):
770
+ nn.init.normal_(module.fn, mean=0.0, std=0.02)
771
+ nn.init.zeros_(module.base)
772
+ nn.init.constant_(module.scale, self.config.mhc_init_scale)
773
+ elif isinstance(module, RMSNorm):
774
+ nn.init.ones_(module.weight)
775
+
776
+ def get_input_embeddings(self) -> nn.Embedding:
777
+ return self.embed_tokens
778
+
779
+ def get_output_embeddings(self) -> nn.Linear:
780
+ return self.lm_head
781
+
782
+ def set_input_embeddings(self, value: nn.Embedding) -> None:
783
+ self.embed_tokens = value
784
+ if self.config.tie_word_embeddings:
785
+ self.lm_head.weight = self.embed_tokens.weight
786
+
787
+ def digit_position_ids(
788
+ self,
789
+ input_ids: Tensor,
790
+ document_ids: Tensor | None = None,
791
+ prior_run_length: Tensor | None = None,
792
+ prior_active: Tensor | None = None,
793
+ ) -> tuple[Tensor, Tensor, Tensor]:
794
+ """Return zero-based contiguous digit positions and streaming state.
795
+
796
+ Positions reset after non-digit tokens and document boundaries. The two
797
+ state tensors contain the run length and whether the final token is a
798
+ digit, allowing the cache to continue a number across blocks.
799
+ """
800
+
801
+ batch, sequence = input_ids.shape
802
+ device = input_ids.device
803
+ enabled = self.digit_position_embedding is not None
804
+ if not enabled:
805
+ zeros = torch.zeros((batch, sequence), dtype=torch.long, device=device)
806
+ return zeros, zeros[:, -1], zeros[:, -1].bool()
807
+ is_digit = torch.isin(input_ids, self.digit_token_ids_tensor)
808
+ positions = torch.zeros_like(input_ids, dtype=torch.long)
809
+ run = (
810
+ prior_run_length.to(device=device, dtype=torch.long)
811
+ if prior_run_length is not None
812
+ else torch.zeros(batch, dtype=torch.long, device=device)
813
+ )
814
+ active = (
815
+ prior_active.to(device=device, dtype=torch.bool)
816
+ if prior_active is not None
817
+ else torch.zeros(batch, dtype=torch.bool, device=device)
818
+ )
819
+ previous_digit = F.pad(is_digit[:, :-1], (1, 0), value=False)
820
+ same_document = torch.ones_like(is_digit)
821
+ if document_ids is not None:
822
+ previous_document = F.pad(document_ids[:, :-1], (1, 0), value=-1)
823
+ same_document = document_ids.eq(previous_document)
824
+ same_document[:, 0] = False
825
+ continuation = is_digit & previous_digit & same_document
826
+ if prior_active is not None:
827
+ continuation[:, 0] = is_digit[:, 0] & active
828
+ starts = is_digit & ~continuation
829
+ max_positions = self.digit_position_embedding.num_embeddings
830
+ base = sequence + max_positions + 1
831
+ markers = torch.where(starts, torch.arange(sequence, device=device) + base, 0)
832
+ if prior_active is not None:
833
+ prior_start = base - run
834
+ markers[:, 0] = torch.where(
835
+ is_digit[:, 0] & active, prior_start, markers[:, 0]
836
+ )
837
+ last_start = torch.cummax(markers, dim=1).values - base
838
+ positions = (torch.arange(sequence, device=device) - last_start).clamp_min(0)
839
+ positions = positions.expand(batch, -1).clamp_max(max_positions - 1)
840
+ positions = torch.where(is_digit, positions, torch.zeros_like(positions))
841
+ run = torch.where(is_digit, positions + 1, 0)[:, -1]
842
+ active = is_digit[:, -1]
843
+ return positions, run, active
844
+
845
+ def add_digit_position_embeddings(
846
+ self,
847
+ input_ids: Tensor,
848
+ token_embeddings: Tensor,
849
+ document_ids: Tensor | None = None,
850
+ prior_run_length: Tensor | None = None,
851
+ prior_active: Tensor | None = None,
852
+ ) -> tuple[Tensor, Tensor, Tensor]:
853
+ positions, run, active = self.digit_position_ids(
854
+ input_ids, document_ids=document_ids, prior_run_length=prior_run_length
855
+ , prior_active=prior_active
856
+ )
857
+ if self.digit_position_embedding is not None:
858
+ is_digit = torch.isin(input_ids, self.digit_token_ids_tensor)
859
+ token_embeddings = token_embeddings + self.digit_position_embedding(
860
+ positions
861
+ ) * is_digit.unsqueeze(-1)
862
+ return token_embeddings, run, active
863
+
864
+ def forward(
865
+ self,
866
+ input_ids: Tensor | None = None,
867
+ inputs_embeds: Tensor | None = None,
868
+ attention_mask: Tensor | None = None,
869
+ document_ids: Tensor | None = None,
870
+ prefix_lengths: Tensor | None = None,
871
+ position_ids: Tensor | None = None,
872
+ labels: Tensor | None = None,
873
+ logit_mask: Tensor | None = None,
874
+ mtp_loss_weight: float = 0.0,
875
+ use_cut_cross_entropy: bool = False,
876
+ loop_count: int = 1,
877
+ output_hidden_states: bool = False,
878
+ **_: object,
879
+ ) -> MicroLoopCausalLMOutput:
880
+ if (input_ids is None) == (inputs_embeds is None):
881
+ raise ValueError("exactly one of input_ids or inputs_embeds must be provided")
882
+ if loop_count < 1:
883
+ raise ValueError("loop_count must be at least one")
884
+ if use_cut_cross_entropy and labels is None:
885
+ raise ValueError("use_cut_cross_entropy requires labels")
886
+ if input_ids is not None:
887
+ if input_ids.dim() != 2:
888
+ raise ValueError(
889
+ f"input_ids must have shape [batch, sequence], got {input_ids.dim()}-D"
890
+ )
891
+ batch, sequence = input_ids.shape
892
+ else:
893
+ if inputs_embeds is None or inputs_embeds.dim() != 3:
894
+ raise ValueError(
895
+ "inputs_embeds must have shape [batch, sequence, hidden], got "
896
+ f"{None if inputs_embeds is None else inputs_embeds.dim()}-D"
897
+ )
898
+ batch, sequence, _ = inputs_embeds.shape
899
+ if self.ngram_memory is not None and input_ids is None:
900
+ raise ValueError("ngram memory requires input_ids for deterministic suffix lookup")
901
+ device = (input_ids if input_ids is not None else inputs_embeds).device
902
+ if document_ids is not None:
903
+ if document_ids.shape != (batch, sequence):
904
+ raise ValueError("document_ids must have the same shape as the input")
905
+ if attention_mask is not None and attention_mask.dim() != 2:
906
+ raise ValueError(
907
+ "document_ids cannot be combined with a precomputed attention mask"
908
+ )
909
+ valid = (
910
+ attention_mask.bool()
911
+ if attention_mask is not None
912
+ else torch.ones((batch, sequence), dtype=torch.bool, device=device)
913
+ )
914
+ if prefix_lengths is None:
915
+ causal = torch.tril(torch.ones(sequence, sequence, dtype=torch.bool, device=device))
916
+ attention_mask = (
917
+ causal.unsqueeze(0)
918
+ & document_ids.unsqueeze(2).eq(document_ids.unsqueeze(1))
919
+ & valid.unsqueeze(1)
920
+ & valid.unsqueeze(2)
921
+ )
922
+ else:
923
+ attention_mask = build_prefix_lm_mask(
924
+ prefix_lengths.to(device),
925
+ sequence,
926
+ valid=valid,
927
+ document_ids=document_ids,
928
+ )
929
+ elif prefix_lengths is not None:
930
+ if attention_mask is not None and attention_mask.dim() != 2:
931
+ raise ValueError("prefix_lengths requires a 2-D padding mask")
932
+ valid = (
933
+ attention_mask.bool()
934
+ if attention_mask is not None
935
+ else torch.ones((batch, sequence), dtype=torch.bool, device=device)
936
+ )
937
+ attention_mask = build_prefix_lm_mask(
938
+ prefix_lengths.to(device), sequence, valid=valid
939
+ )
940
+ if position_ids is None:
941
+ position_ids = torch.arange(sequence, device=device).expand(batch, -1)
942
+ rope_dtype = (
943
+ torch.get_autocast_dtype("cuda")
944
+ if device.type == "cuda" and torch.is_autocast_enabled("cuda")
945
+ else self.embed_tokens.weight.dtype
946
+ )
947
+ rope_embeddings = (
948
+ self.rope_cos[position_ids].unsqueeze(1).to(rope_dtype),
949
+ self.rope_sin[position_ids].unsqueeze(1).to(rope_dtype),
950
+ )
951
+ token_embeddings = self.embed_tokens(input_ids) if input_ids is not None else inputs_embeds
952
+ if input_ids is not None:
953
+ token_embeddings, _, _ = self.add_digit_position_embeddings(
954
+ input_ids, token_embeddings, document_ids=document_ids
955
+ )
956
+ hidden_states = token_embeddings
957
+ if self.config.mhc_multiplier > 1:
958
+ hidden_states = hidden_states.unsqueeze(2).expand(
959
+ -1, -1, self.config.mhc_multiplier, -1
960
+ ).contiguous()
961
+ first_value_states = None
962
+ if self.config.value_residual.get("enabled", False):
963
+ first_attention = self.layers[0].attn
964
+ first_values = first_attention.v_proj(self.layers[0].attn_norm(hidden_states))
965
+ first_value_states = first_values.view(
966
+ batch,
967
+ sequence,
968
+ first_attention.num_key_value_heads,
969
+ first_attention.head_dim,
970
+ ).transpose(1, 2)
971
+ loop_layers = list(self.config.looping.get("layers", [4, 5, 6]))
972
+ loop_mode = str(self.config.looping.get("mode", "layer"))
973
+ if (
974
+ loop_mode == "block"
975
+ and self.config.looping.get("gated", False)
976
+ and loop_count
977
+ > int(
978
+ self.config.looping.get(
979
+ "max_loop_count", self.config.looping.get("maximum_serving_loops", 3)
980
+ )
981
+ )
982
+ ):
983
+ raise ValueError("loop_count exceeds configured max_loop_count")
984
+ block_residuals: list[Tensor] = []
985
+ block_size = self.config.attn_res_block_size
986
+ total_applications = 0
987
+ if loop_mode == "block":
988
+ valid_layers = sorted(
989
+ {layer for layer in loop_layers if 1 <= int(layer) <= len(self.layers)}
990
+ )
991
+ if valid_layers:
992
+ loop_set = set(valid_layers)
993
+ layer_order = [
994
+ *range(1, valid_layers[0]),
995
+ *valid_layers * loop_count,
996
+ *range(valid_layers[-1] + 1, len(self.layers) + 1),
997
+ ]
998
+ else:
999
+ loop_set = set()
1000
+ layer_order = list(range(1, len(self.layers) + 1))
1001
+ else:
1002
+ loop_set = {int(layer) for layer in loop_layers}
1003
+ layer_order = [
1004
+ layer_number
1005
+ for layer_number in range(1, len(self.layers) + 1)
1006
+ for _ in range(loop_count if layer_number in loop_set else 1)
1007
+ ]
1008
+ block_start = min(loop_set) if loop_set else None
1009
+ block_end = max(loop_set) if loop_set else None
1010
+ block_size_layers = len(loop_set)
1011
+ block_pass = 0
1012
+ block_input: Tensor | None = None
1013
+ for application_index, layer_number in enumerate(layer_order):
1014
+ layer = self.layers[layer_number - 1]
1015
+ if (
1016
+ loop_mode == "block"
1017
+ and block_start is not None
1018
+ and application_index >= block_start - 1
1019
+ and (application_index - (block_start - 1)) % block_size_layers == 0
1020
+ ):
1021
+ block_input = hidden_states
1022
+ if block_size is not None and (layer_number - 1) % block_size == 0:
1023
+ block_residuals.append(hidden_states)
1024
+ prior_block_residuals = block_residuals[:-1] if block_size is not None else None
1025
+ hidden_states = layer(
1026
+ hidden_states,
1027
+ attention_mask=attention_mask,
1028
+ position_ids=position_ids,
1029
+ rope_embeddings=rope_embeddings,
1030
+ block_residuals=prior_block_residuals,
1031
+ first_value_states=first_value_states if layer_number > 1 else None,
1032
+ )
1033
+ if self.ngram_memory is not None and layer_number == self.ngram_memory_layer:
1034
+ assert input_ids is not None
1035
+ hidden_states = hidden_states + self.ngram_memory(
1036
+ input_ids,
1037
+ hidden_states,
1038
+ token_embeddings=token_embeddings,
1039
+ document_ids=document_ids,
1040
+ )
1041
+ total_applications += 1
1042
+ if (
1043
+ loop_mode == "block"
1044
+ and block_end is not None
1045
+ and layer_number == block_end
1046
+ and block_start is not None
1047
+ and (application_index - (block_start - 1) + 1) % block_size_layers == 0
1048
+ ):
1049
+ block_pass += 1
1050
+ if block_pass < loop_count:
1051
+ assert block_input is not None
1052
+ hidden_states = self._apply_loop_gate(
1053
+ block_input, hidden_states, block_pass - 1
1054
+ )
1055
+ if self.mhc_head is not None:
1056
+ hidden_states = self.mhc_head(hidden_states)
1057
+ hidden_states = self.norm(hidden_states)
1058
+ if use_cut_cross_entropy:
1059
+ if logit_mask is not None:
1060
+ raise ValueError("use_cut_cross_entropy cannot be combined with logit_mask")
1061
+ logits = None
1062
+ elif logit_mask is not None:
1063
+ # Diffusion training: only the masked positions carry loss, so the
1064
+ # output head runs on those rows instead of the full sequence.
1065
+ if labels is not None:
1066
+ raise ValueError("logit_mask cannot be combined with labels")
1067
+ if logit_mask.shape != (batch, sequence):
1068
+ raise ValueError("logit_mask must have the same shape as the input")
1069
+ flat = hidden_states.reshape(-1, self.config.hidden_size)
1070
+ logits = self.lm_head(flat[logit_mask.reshape(-1)])
1071
+ else:
1072
+ logits = self.lm_head(hidden_states)
1073
+ loss = None
1074
+ if labels is not None:
1075
+ if labels.shape != (batch, sequence):
1076
+ raise ValueError("labels must have the same shape as the input")
1077
+ if labels.size(1) < 2:
1078
+ raise ValueError("causal training requires sequences with at least two tokens")
1079
+ # Causal next-token prediction: position t predicts the label at t + 1.
1080
+ if use_cut_cross_entropy:
1081
+ try:
1082
+ from cut_cross_entropy import linear_cross_entropy
1083
+ except ImportError as exc: # pragma: no cover - optional dependency
1084
+ raise RuntimeError(
1085
+ "Cut Cross Entropy is optional; install the fused-loss project extra"
1086
+ ) from exc
1087
+ cce_embeddings = hidden_states[:, :-1, :]
1088
+ if torch.is_autocast_enabled("cuda"):
1089
+ cce_embeddings = cce_embeddings.to(torch.get_autocast_dtype("cuda"))
1090
+ if cce_embeddings.dtype not in (torch.float16, torch.bfloat16):
1091
+ raise ValueError("Cut Cross Entropy requires CUDA fp16 or bf16 autocast")
1092
+ loss = linear_cross_entropy(
1093
+ cce_embeddings,
1094
+ self.lm_head.weight,
1095
+ labels[:, 1:],
1096
+ ignore_index=-100,
1097
+ )
1098
+ else:
1099
+ assert logits is not None
1100
+ loss = F.cross_entropy(
1101
+ logits[:, :-1, :].reshape(-1, logits.size(-1)),
1102
+ labels[:, 1:].reshape(-1),
1103
+ ignore_index=-100,
1104
+ )
1105
+ if mtp_loss_weight:
1106
+ if self.mtp_proj is None:
1107
+ raise ValueError("mtp_loss_weight requires mtp_enabled=true")
1108
+ if mtp_loss_weight < 0:
1109
+ raise ValueError("mtp_loss_weight must be non-negative")
1110
+ mtp_logits = self.lm_head(self.mtp_proj(hidden_states[:, :-2, :]))
1111
+ mtp_loss = F.cross_entropy(
1112
+ mtp_logits.reshape(-1, mtp_logits.size(-1)),
1113
+ labels[:, 2:].reshape(-1),
1114
+ ignore_index=-100,
1115
+ )
1116
+ loss = loss + float(mtp_loss_weight) * mtp_loss
1117
+ return MicroLoopCausalLMOutput(
1118
+ logits=logits,
1119
+ loss=loss,
1120
+ hidden_states=hidden_states if output_hidden_states else None,
1121
+ loop_applications=total_applications,
1122
+ )
1123
+
1124
+ def _apply_loop_gate(
1125
+ self, previous: Tensor, candidate: Tensor, pass_index: int
1126
+ ) -> Tensor:
1127
+ """Blend a repeated shared block into the previous pass."""
1128
+
1129
+ if self.loop_gates is None:
1130
+ return candidate
1131
+ if pass_index < 0 or pass_index >= self.loop_gates.size(0):
1132
+ raise ValueError("loop_count exceeds configured max_loop_count")
1133
+ gate = torch.tanh(self.loop_gates[pass_index]).to(candidate.dtype)
1134
+ return previous + gate.view(1, 1, -1) * (candidate - previous)
1135
+
1136
+ @torch.no_grad()
1137
+ def generate_greedy(
1138
+ self, input_ids: Tensor, max_new_tokens: int, eos_token_id: int | None = None
1139
+ ) -> Tensor:
1140
+ """Small causal smoke decoder; diffusion sampling belongs in ``sampler.py``."""
1141
+
1142
+ return self.generate_causal(
1143
+ input_ids, max_new_tokens=max_new_tokens, eos_token_id=eos_token_id, do_sample=False
1144
+ )
1145
+
1146
+ @torch.no_grad()
1147
+ def generate_causal(
1148
+ self,
1149
+ input_ids: Tensor,
1150
+ *,
1151
+ max_new_tokens: int,
1152
+ eos_token_id: int | None = None,
1153
+ do_sample: bool = False,
1154
+ temperature: float = 1.0,
1155
+ top_k: int | None = None,
1156
+ ) -> Tensor:
1157
+ """Generate a batched causal continuation for M2 validation and serving.
1158
+
1159
+ This deliberately recomputes the context on every step. KV caching is a
1160
+ later optimization; keeping this reference path simple makes M2 output
1161
+ semantics straightforward to test.
1162
+ """
1163
+
1164
+ if max_new_tokens < 0:
1165
+ raise ValueError("max_new_tokens must be non-negative")
1166
+ if temperature <= 0:
1167
+ raise ValueError("temperature must be positive")
1168
+ if top_k is not None and top_k <= 0:
1169
+ raise ValueError("top_k must be positive when supplied")
1170
+ generated = input_ids
1171
+ finished = torch.zeros(input_ids.size(0), dtype=torch.bool, device=input_ids.device)
1172
+ for _ in range(max_new_tokens):
1173
+ next_logits = self(generated).logits[:, -1, :]
1174
+ if do_sample:
1175
+ next_logits = next_logits / temperature
1176
+ if top_k is not None and top_k < next_logits.size(-1):
1177
+ threshold = torch.topk(next_logits, top_k, dim=-1).values[:, -1:]
1178
+ next_logits = next_logits.masked_fill(next_logits < threshold, float("-inf"))
1179
+ next_token = torch.multinomial(torch.softmax(next_logits, dim=-1), 1)
1180
+ else:
1181
+ next_token = next_logits.argmax(dim=-1, keepdim=True)
1182
+ if eos_token_id is not None:
1183
+ next_token = torch.where(
1184
+ finished.unsqueeze(1),
1185
+ torch.full_like(next_token, eos_token_id),
1186
+ next_token,
1187
+ )
1188
+ finished |= next_token.squeeze(1).eq(eos_token_id)
1189
+ generated = torch.cat((generated, next_token), dim=1)
1190
+ if eos_token_id is not None and bool(finished.all()):
1191
+ break
1192
+ return generated
prefix_lm.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Attention masks for response-conditioned PrefixLM training."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import torch
6
+ from torch import Tensor
7
+
8
+
9
+ def build_prefix_lm_mask(
10
+ prefix_lengths: Tensor,
11
+ sequence_length: int,
12
+ *,
13
+ valid: Tensor | None = None,
14
+ document_ids: Tensor | None = None,
15
+ ) -> Tensor:
16
+ """Build visibility for a bidirectional prefix and causal response."""
17
+ if prefix_lengths.dim() != 1:
18
+ raise ValueError("prefix_lengths must have shape [batch]")
19
+ if sequence_length < 1:
20
+ raise ValueError("sequence_length must be positive")
21
+ batch = prefix_lengths.size(0)
22
+ if torch.any(prefix_lengths < 0) or torch.any(prefix_lengths > sequence_length):
23
+ raise ValueError("prefix_lengths must lie in [0, sequence_length]")
24
+ if valid is not None and valid.shape != (batch, sequence_length):
25
+ raise ValueError("valid must have shape [batch, sequence]")
26
+ if document_ids is not None and document_ids.shape != (batch, sequence_length):
27
+ raise ValueError("document_ids must have shape [batch, sequence]")
28
+
29
+ device = prefix_lengths.device
30
+ positions = torch.arange(sequence_length, device=device)
31
+ query = positions.view(1, sequence_length, 1)
32
+ key = positions.view(1, 1, sequence_length)
33
+ prefix = prefix_lengths.view(batch, 1, 1)
34
+ query_in_prefix = query < prefix
35
+ key_in_prefix = key < prefix
36
+ visible = torch.where(query_in_prefix, key_in_prefix, key_in_prefix | (key <= query))
37
+ if valid is not None:
38
+ mask = valid.to(device)
39
+ visible &= mask.view(batch, 1, sequence_length)
40
+ visible &= mask.view(batch, sequence_length, 1)
41
+ if document_ids is not None:
42
+ ids = document_ids.to(device)
43
+ visible &= ids.unsqueeze(1).eq(ids.unsqueeze(2))
44
+ return visible
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<bos>",
4
+ "clean_up_tokenization_spaces": false,
5
+ "eos_token": "<eos>",
6
+ "extra_special_tokens": [
7
+ "<system>",
8
+ "<user>",
9
+ "<assistant>",
10
+ "<turn_end>",
11
+ "<doc_end>"
12
+ ],
13
+ "is_local": true,
14
+ "local_files_only": false,
15
+ "mask_token": "<mask>",
16
+ "model_max_length": 2048,
17
+ "pad_token": "<pad>",
18
+ "padding_side": "right",
19
+ "tokenizer_class": "TokenizersBackend",
20
+ "truncation_side": "right"
21
+ }
training/corpus_contract.yaml ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 3
2
+ project: hummingbird
3
+ purpose: flightmix_10b_balanced_pretraining
4
+ status: building
5
+ snapshot_date: 2026-09-20
6
+ seed: 42
7
+
8
+ target:
9
+ tokenizer: artifacts/runs/e3_tokenizers/tok_4k_digit
10
+ token_storage_dtype: uint16
11
+ train_token_presentations: 10000000000
12
+ unique_train_tokens_min: 10000000000
13
+ optimizer_step_tokens: 320000
14
+ epochs: 1
15
+ padding_tokens_count_toward_budget: false
16
+ validation_tokens_not_trained: 25000000
17
+ held_out_tokens_not_trained: 25000000
18
+ split_policy: document_sha256_mod_1000
19
+ split_modulus: 1000
20
+ split_hash_bytes: first_8_big_endian
21
+ validation_buckets: [0, 1, 2, 3, 4]
22
+ held_out_buckets: [5, 6, 7, 8, 9]
23
+ train_buckets: 10-999
24
+
25
+ source_mix:
26
+ - name: general_web
27
+ role: general_educational_web
28
+ train_tokens: 2050000000
29
+ share: 0.205
30
+ - name: general_web_v2
31
+ role: general_educational_web_dedup_reserve
32
+ train_tokens: 3450000000
33
+ share: 0.345
34
+ - name: cosmopedia_v2
35
+ role: synthetic_textbook_exposition_and_narrative
36
+ train_tokens: 1500000000
37
+ share: 0.15
38
+ - name: worked_mathematics
39
+ role: natural_worked_mathematics
40
+ train_tokens: 1000000000
41
+ share: 0.10
42
+ - name: natural_text
43
+ role: broad_natural_text
44
+ train_tokens: 1000000000
45
+ share: 0.10
46
+ - name: science_exposition
47
+ role: science_exposition
48
+ train_tokens: 400000000
49
+ share: 0.04
50
+ - name: science_pdf_qa
51
+ role: science_pdf_and_grounded_qa
52
+ train_tokens: 200000000
53
+ share: 0.02
54
+ - name: dense_pdf_exposition
55
+ role: dense_educational_pdf_exposition
56
+ train_tokens: 300000000
57
+ share: 0.03
58
+ - name: code
59
+ role: educational_code
60
+ train_tokens: 100000000
61
+ share: 0.01
62
+
63
+ sources:
64
+ - name: general_web
65
+ repo_id: HuggingFaceFW/fineweb-edu
66
+ revision: 87f09149ef4734204d70ed1d046ddc9ca3f2b8f9
67
+ config: sample-100BT
68
+ split: train
69
+ text_field: text
70
+ id_field: id
71
+ license: odc-by-1.0
72
+ selection: int_score >= 4; fresh deterministic shard selection; V2 exact digests excluded
73
+ - name: general_web_v2
74
+ repo_id: HuggingFaceTB/smollm-corpus
75
+ revision: 3ba9d605774198c5868892d7a8deda78031a781f
76
+ config: fineweb-edu-dedup
77
+ split: train
78
+ text_field: text
79
+ id_field: id
80
+ license: odc-by-1.0
81
+ selection: pinned FineWeb-Edu-Dedup reserve; V2 exact digests excluded
82
+ - name: cosmopedia_v2
83
+ repo_id: HuggingFaceTB/smollm-corpus
84
+ revision: 3ba9d605774198c5868892d7a8deda78031a781f
85
+ config: cosmopedia-v2
86
+ split: train
87
+ text_field: text
88
+ license: odc-by-1.0
89
+ selection: fresh deterministic shards; V2 exact digests excluded
90
+ - name: worked_mathematics
91
+ repo_id: HuggingFaceTB/finemath
92
+ revision: e92b25a616738fe95dc186b64dfb19f9c8525594
93
+ config: finemath-4plus
94
+ split: train
95
+ text_field: text
96
+ id_field: url
97
+ license: odc-by-1.0
98
+ selection: intact worked solutions; V2 exact digests excluded
99
+ - name: natural_text
100
+ repo_id: mlfoundations/dclm-baseline-1.0
101
+ revision: a3b142c183aebe5af344955ae20836eb34dcf69b
102
+ config: default
103
+ split: train
104
+ text_field: text
105
+ license: cc-by-4.0
106
+ selection: deterministic source shards; V2 exact digests excluded
107
+ - name: science_exposition
108
+ repo_id: allenai/dolma3_dolmino_mix-100B-1025
109
+ revision: f23942ae8a8114af6e992efe8188ce8c531acd16
110
+ format: jsonl.zst
111
+ text_field: text
112
+ id_field: id
113
+ license: odc-by-1.0
114
+ include_slices: [stem-heavy-crawl/science_math_and_technology]
115
+ - name: science_pdf_qa
116
+ repo_id: allenai/dolma3_dolmino_mix-100B-1025
117
+ revision: f23942ae8a8114af6e992efe8188ce8c531acd16
118
+ format: jsonl.zst
119
+ text_field: text
120
+ id_field: id
121
+ license: odc-by-1.0
122
+ include_slices: [wiki_to_rcqa-part1, wiki_to_rcqa-part2, wiki_to_rcqa-part3]
123
+ selection: grounded general Wikipedia QA; not science-only
124
+ - name: dense_pdf_exposition
125
+ repo_id: HuggingFaceFW/finepdfs-edu
126
+ revision: 9cfabe2127faca99b3d5c4dc6d1fcb397399ebde
127
+ config: eng_Latn
128
+ split: train
129
+ text_field: text
130
+ id_field: id
131
+ license: odc-by-1.0
132
+ selection: full_doc_lid_score >= 0.98; non-truncated; upstream-deduped
133
+ - name: code
134
+ repo_id: allenai/dolma3_dolmino_mix-10B-1025
135
+ revision: 275d00e588098d2658e36be74ffd010dfb54d8a6
136
+ format: jsonl.zst
137
+ text_field: text
138
+ id_field: id
139
+ license: odc-by-1.0
140
+ include_slices: [stack_edu_fim]
141
+ quality:
142
+ min_tokens: 48
143
+ max_tokens: 4096
144
+ language: English
145
+ max_symbol_ratio: 0.30
146
+ max_repeated_line_fraction: 0.15
147
+ reject_secrets: true
148
+ reject_navigation_and_cookie_boilerplate: true
149
+ source_overrides:
150
+ code:
151
+ repeated_line_metric: character_fraction
152
+
153
+ deduplication:
154
+ exact: canonical_document_sha256_over_all_sources_and_splits
155
+ v2_exclusion_index: artifacts/flightmix_5b_v2/materialized/exact_documents.sqlite3
156
+ cross_split: deduplicate_union_before_split_assignment
157
+ near_duplicate:
158
+ full_tier_sources: [general_web, general_web_v2, worked_mathematics, natural_text]
159
+ method: sqlite_minhash_lsh_with_exact_jaccard_confirmation
160
+ permutations: 32
161
+ bands: 8
162
+ band_width: 4
163
+ shingle_width: 5
164
+ threshold: 0.80
165
+ policy: keep_first
166
+ exact_only_sources: [cosmopedia_v2, science_exposition, science_pdf_qa, dense_pdf_exposition, code]
167
+ generated_family_rule: exact_plus_family_cap
168
+
169
+ decontamination:
170
+ protected_tasks: [HellaSwag, ARC-Easy, ARC-Challenge, PIQA, ArithMark-3]
171
+ reject_if: [canonical_exact_match, normalized_13gram_match, five_word_shingle_jaccard_gte_0.50]
172
+ protected_sources:
173
+ - artifacts/m9_protection/open_slm_harness_protected.jsonl
174
+ - artifacts/m9_protection/arithmark_3_protected.jsonl
175
+
176
+ curriculum:
177
+ - phase: constant_mixture
178
+ start_token: 0
179
+ end_token: 10000000000
180
+ source_tokens:
181
+ general_web: 2050000000
182
+ general_web_v2: 3450000000
183
+ cosmopedia_v2: 1500000000
184
+ worked_mathematics: 1000000000
185
+ natural_text: 1000000000
186
+ science_exposition: 400000000
187
+ science_pdf_qa: 200000000
188
+ dense_pdf_exposition: 300000000
189
+ code: 100000000
190
+ document_boundary: true
191
+ policy: constant_proportional_interleave
192
+
193
+ arithmetic_decision: exclude generated arithmetic from the first Balanced candidate
194
+ science_decision: retain 400M science exposition; use pinned 100B STEM slice; full-source yield unverified
195
+ review_exclusions:
196
+ 7b9cffe96d06d371720103c0b7b27c6d87c8d3de710b844e0b3608780d7f5b27:
197
+ source: worked_mathematics
198
+ reason: The document claims stopping a 1000 kg car at 72 km/h requires 400000 J. Independently recomputed kinetic energy is 0.5 * 1000 * (72 / 3.6)^2 = 200000 J.
199
+ record_id: train-00000-of-00064.parquet:27049:https://easyrelocated.com/what-is-the-average-braking-force-of-a-1000-kg-car-moving-at-20m-s/
training/packed_metadata.json ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "audit_drain_documents": 0,
3
+ "contract": "D:\\llm\\hummingbird\\configs\\flightmix_10b_balanced_corpus_contract.yaml",
4
+ "contract_sha256": "73cd71ff4f7849d939606bd77434df4697d590bdfe2202ba1681b267c63f6786",
5
+ "contract_validation": {
6
+ "contract": "D:\\llm\\hummingbird\\configs\\flightmix_10b_balanced_corpus_contract.yaml",
7
+ "curriculum": "constant_mixture",
8
+ "pilot_only": false,
9
+ "source_count": 9,
10
+ "source_share_sum": 1.0,
11
+ "source_tokens": {
12
+ "code": 100000000,
13
+ "cosmopedia_v2": 1500000000,
14
+ "dense_pdf_exposition": 300000000,
15
+ "general_web": 2050000000,
16
+ "general_web_v2": 3450000000,
17
+ "natural_text": 1000000000,
18
+ "science_exposition": 400000000,
19
+ "science_pdf_qa": 200000000,
20
+ "worked_mathematics": 1000000000
21
+ },
22
+ "status": "passed",
23
+ "train_tokens": 10000000000
24
+ },
25
+ "curriculum": [
26
+ {
27
+ "document_boundary": true,
28
+ "end_token": 10000000000,
29
+ "per_source_tokens": {
30
+ "code": 100000000,
31
+ "cosmopedia_v2": 1500000000,
32
+ "dense_pdf_exposition": 300000000,
33
+ "general_web": 2050000000,
34
+ "general_web_v2": 3450000000,
35
+ "natural_text": 1000000000,
36
+ "science_exposition": 400000000,
37
+ "science_pdf_qa": 200000000,
38
+ "worked_mathematics": 1000000000
39
+ },
40
+ "phase": "constant_mixture",
41
+ "start_token": 0,
42
+ "tokens": 10000000000
43
+ }
44
+ ],
45
+ "document_end_id": 8,
46
+ "dtype": "uint16",
47
+ "elapsed_seconds": 1166.1,
48
+ "format_version": 5,
49
+ "mix_policy": "three_phase_exact_token_curriculum",
50
+ "per_source_documents_all_splits": {
51
+ "code": {
52
+ "held_out": 269,
53
+ "train": 110098,
54
+ "validation": 257
55
+ },
56
+ "cosmopedia_v2": {
57
+ "held_out": 3687,
58
+ "train": 1482589,
59
+ "validation": 3700
60
+ },
61
+ "dense_pdf_exposition": {
62
+ "held_out": 516,
63
+ "train": 211198,
64
+ "validation": 508
65
+ },
66
+ "general_web": {
67
+ "held_out": 5209,
68
+ "train": 2085750,
69
+ "validation": 5245
70
+ },
71
+ "general_web_v2": {
72
+ "held_out": 8644,
73
+ "train": 3366937,
74
+ "validation": 8545
75
+ },
76
+ "natural_text": {
77
+ "held_out": 2344,
78
+ "train": 927051,
79
+ "validation": 2356
80
+ },
81
+ "science_exposition": {
82
+ "held_out": 877,
83
+ "train": 338512,
84
+ "validation": 862
85
+ },
86
+ "science_pdf_qa": {
87
+ "held_out": 1732,
88
+ "train": 680086,
89
+ "validation": 1688
90
+ },
91
+ "worked_mathematics": {
92
+ "held_out": 2041,
93
+ "train": 831431,
94
+ "validation": 2117
95
+ }
96
+ },
97
+ "per_source_tokens_all_splits": {
98
+ "code": {
99
+ "held_out": 243511,
100
+ "train": 100000000,
101
+ "validation": 250292
102
+ },
103
+ "cosmopedia_v2": {
104
+ "held_out": 3750173,
105
+ "train": 1500000000,
106
+ "validation": 3750712
107
+ },
108
+ "dense_pdf_exposition": {
109
+ "held_out": 751319,
110
+ "train": 300000000,
111
+ "validation": 750424
112
+ },
113
+ "general_web": {
114
+ "held_out": 5123293,
115
+ "train": 2050000000,
116
+ "validation": 5125099
117
+ },
118
+ "general_web_v2": {
119
+ "held_out": 8626828,
120
+ "train": 3450000000,
121
+ "validation": 8625843
122
+ },
123
+ "natural_text": {
124
+ "held_out": 2500508,
125
+ "train": 1000000000,
126
+ "validation": 2501686
127
+ },
128
+ "science_exposition": {
129
+ "held_out": 1001743,
130
+ "train": 400000000,
131
+ "validation": 995177
132
+ },
133
+ "science_pdf_qa": {
134
+ "held_out": 500686,
135
+ "train": 200000000,
136
+ "validation": 500188
137
+ },
138
+ "worked_mathematics": {
139
+ "held_out": 2501939,
140
+ "train": 1000000000,
141
+ "validation": 2500579
142
+ }
143
+ },
144
+ "per_source_train_tokens": {
145
+ "code": 100000000,
146
+ "cosmopedia_v2": 1500000000,
147
+ "dense_pdf_exposition": 300000000,
148
+ "general_web": 2050000000,
149
+ "general_web_v2": 3450000000,
150
+ "natural_text": 1000000000,
151
+ "science_exposition": 400000000,
152
+ "science_pdf_qa": 200000000,
153
+ "worked_mathematics": 1000000000
154
+ },
155
+ "phase_boundaries": [
156
+ 10000000000
157
+ ],
158
+ "source_files": {
159
+ "code": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\cleaned_code.jsonl",
160
+ "cosmopedia_v2": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\cleaned_cosmopedia_v2.jsonl",
161
+ "dense_pdf_exposition": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\cleaned_dense_pdf_exposition.jsonl",
162
+ "general_web": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\cleaned_general_web.jsonl",
163
+ "general_web_v2": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\cleaned_general_web_v2.jsonl",
164
+ "natural_text": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\cleaned_natural_text.jsonl",
165
+ "science_exposition": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\cleaned_science_exposition.jsonl",
166
+ "science_pdf_qa": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\cleaned_science_pdf_qa.jsonl",
167
+ "worked_mathematics": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\cleaned_worked_mathematics.jsonl"
168
+ },
169
+ "source_order": [
170
+ "general_web",
171
+ "general_web_v2",
172
+ "cosmopedia_v2",
173
+ "worked_mathematics",
174
+ "natural_text",
175
+ "science_exposition",
176
+ "science_pdf_qa",
177
+ "dense_pdf_exposition",
178
+ "code"
179
+ ],
180
+ "source_rows_read": {
181
+ "code": 110629,
182
+ "cosmopedia_v2": 1489976,
183
+ "dense_pdf_exposition": 212222,
184
+ "general_web": 2096207,
185
+ "general_web_v2": 3384126,
186
+ "natural_text": 931751,
187
+ "science_exposition": 340254,
188
+ "science_pdf_qa": 683506,
189
+ "worked_mathematics": 835589
190
+ },
191
+ "split_policy": {
192
+ "hash": "sha256_first_8_bytes_big_endian",
193
+ "held_out_buckets": [
194
+ 5,
195
+ 6,
196
+ 7,
197
+ 8,
198
+ 9
199
+ ],
200
+ "modulus": 1000,
201
+ "validation_buckets": [
202
+ 0,
203
+ 1,
204
+ 2,
205
+ 3,
206
+ 4
207
+ ]
208
+ },
209
+ "splits": {
210
+ "held_out": {
211
+ "document_ends_file": "held_out_document_ends.npy",
212
+ "documents": 25319,
213
+ "quota_tail_fragments": 1,
214
+ "token_file": "held_out_tokens.uint16",
215
+ "tokens": 25000000
216
+ },
217
+ "train": {
218
+ "document_ends_file": "train_document_ends.npy",
219
+ "documents": 10033652,
220
+ "quota_tail_fragments": 9,
221
+ "token_file": "train_tokens.uint16",
222
+ "tokens": 10000000000
223
+ },
224
+ "validation": {
225
+ "document_ends_file": "validation_document_ends.npy",
226
+ "documents": 25278,
227
+ "quota_tail_fragments": 1,
228
+ "token_file": "validation_tokens.uint16",
229
+ "tokens": 25000000
230
+ }
231
+ },
232
+ "tokenized_source_files": {
233
+ "code": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\tokenized_code.uint16",
234
+ "cosmopedia_v2": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\tokenized_cosmopedia_v2.uint16",
235
+ "dense_pdf_exposition": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\tokenized_dense_pdf_exposition.uint16",
236
+ "general_web": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\tokenized_general_web.uint16",
237
+ "general_web_v2": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\tokenized_general_web_v2.uint16",
238
+ "natural_text": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\tokenized_natural_text.uint16",
239
+ "science_exposition": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\tokenized_science_exposition.uint16",
240
+ "science_pdf_qa": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\tokenized_science_pdf_qa.uint16",
241
+ "worked_mathematics": "E:\\hummingbird\\flightmix_10b_balanced\\materialized\\tokenized_worked_mathematics.uint16"
242
+ },
243
+ "tokenizer_path": "D:\\llm\\hummingbird\\artifacts\\runs\\e3_tokenizers\\tok_4k_digit",
244
+ "tokenizer_sha256": "a788340e936445a7c6a463b11e87f8025be1e63c2fd47a072901328d08ef8818"
245
+ }
training/provenance.json ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_checkpoint": null,
3
+ "base_token_presentations": 0,
4
+ "checkpoint_selection": {
5
+ "evaluated_token_checkpoints": [
6
+ 500000000,
7
+ 1000000000,
8
+ 1500000000,
9
+ 2000000000,
10
+ 2500000000,
11
+ 3000000000,
12
+ 3500000000,
13
+ 4000000000,
14
+ 4500000000,
15
+ 5000000000,
16
+ 5500000000,
17
+ 6000000000,
18
+ 6500000000,
19
+ 7000000000,
20
+ 7500000000,
21
+ 8000000000,
22
+ 8500000000,
23
+ 9000000000,
24
+ 9500000000,
25
+ 10000000000
26
+ ],
27
+ "reason": "10B baseline selected after checkpoint and alternative-architecture comparisons; author-run public evaluations influenced the choice",
28
+ "selected_token_checkpoint": 10000000000,
29
+ "used_public_evaluations": true
30
+ },
31
+ "continuation_checkpoint_metrics": {
32
+ "elapsed_seconds": 14313.178094000003,
33
+ "gradient_norm": 0.42358821630477905,
34
+ "learning_rate": 3.0000068175060853e-05,
35
+ "step": 31250,
36
+ "tokens_seen": 10000000000,
37
+ "train_loss": 2.6495230102539065,
38
+ "training_loop_count": 1,
39
+ "validation_loss": 2.6567683436653833
40
+ },
41
+ "continuation_token_presentations": 10000000000,
42
+ "cumulative_token_presentations": 10000000000,
43
+ "format_version": 1,
44
+ "release_name": "Hummingbird-V2",
45
+ "source_checkpoint": "artifacts/runs/flightmix_10b_balanced_10m_muon_lrfix_20260921/checkpoint-tokens-10000000000",
46
+ "training_config": {
47
+ "adam_beta1": 0.9,
48
+ "adam_beta2": 0.95,
49
+ "adam_eps": 1e-08,
50
+ "batched_head_wise_muon": false,
51
+ "choice_data_path": null,
52
+ "choice_loss_weight": 0.0,
53
+ "choice_microbatch_stride": 1,
54
+ "choice_records_per_step": 4,
55
+ "compile": true,
56
+ "context_length": 512,
57
+ "corpus_path": "E:\\hummingbird\\flightmix_10b_balanced\\packed_curriculum",
58
+ "deterministic": false,
59
+ "device": null,
60
+ "gradient_accumulation_steps": 25,
61
+ "head_wise_muon": false,
62
+ "init_from": null,
63
+ "learning_rate": 0.0003,
64
+ "lr_decay_fraction": 0.100032,
65
+ "lr_min_ratio": 0.1,
66
+ "lr_schedule": "wsd",
67
+ "lr_warmup_steps": 200,
68
+ "max_grad_norm": 1.0,
69
+ "micro_batch_size": 25,
70
+ "model_config_path": "D:\\llm\\hummingbird\\configs\\model_4k_14l_sdpa_qk_clamp.yaml",
71
+ "mtp_final_loss_weight": null,
72
+ "mtp_loss_weight": 0.0,
73
+ "num_workers": 0,
74
+ "optimizer": "muon",
75
+ "pin_memory": true,
76
+ "precision": "bf16",
77
+ "prepared_data_dir": "E:\\hummingbird\\flightmix_10b_balanced\\packed_curriculum",
78
+ "prepared_data_start_sequence": 12695625,
79
+ "run_dir": "D:\\llm\\hummingbird\\artifacts\\runs\\flightmix_10b_balanced_10m_muon_lrfix_20260921",
80
+ "save_every_steps": 500,
81
+ "save_every_tokens": 500000000,
82
+ "seed": 42,
83
+ "tokenizer_path": "D:\\llm\\hummingbird\\artifacts\\runs\\e3_tokenizers\\tok_4k_digit",
84
+ "tokens_target": 10000000000,
85
+ "train_ngram_only": false,
86
+ "training_loop_counts": [
87
+ 1
88
+ ],
89
+ "validate_every_steps": 100,
90
+ "validation_tokens": 131072,
91
+ "weight_decay": 0.1
92
+ }
93
+ }