Can111 commited on
Commit
a45f954
·
verified ·
1 Parent(s): c1b6530

Final checkpoints of Table 2

Browse files
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ datasets:
6
+ - mlfoundations/dclm-baseline-1.0
7
+ - Can111/ShellElastic-pretraining-data
8
+ library_name: pytorch
9
+ pipeline_tag: text-generation
10
+ tags:
11
+ - shellelastic
12
+ - elastic-pretraining
13
+ - baseline
14
+ - standalone
15
+ ---
16
+
17
+ # Standalone baseline, 375M–906M scale (ShellElastic paper, Table 2)
18
+
19
+ Final weights of the Standalone baseline in Table 2 of *ShellElastic: Scalable Elastic Pretraining with Simultaneous Maximal Updates and Hyperparameter Transfer* (Jin et al.; Rutgers University and Adobe Research), at the 375M–906M scale. These weights are a baseline trained for this paper. Standalone trains five separate models, each on the full budget, and thus takes 5× the steps of one elastic run (Section 4.1; † in Table 2). Each folder of this repository holds one of the five models (Low, Medium, High, Extra, Max).
20
+
21
+ ## Models
22
+
23
+ | Model | Folder | Model width | Attention heads | FFN width | Parameters |
24
+ |---|---|---|---|---|---|
25
+ | Low | `low/` | 832 | 13 | 2,288 | 377,529,152 (377.5M) |
26
+ | Medium | `medium/` | 960 | 15 | 2,640 | 487,711,680 (487.7M) |
27
+ | High | `high/` | 1,088 | 17 | 2,992 | 611,787,840 (611.8M) |
28
+ | Extra | `extra/` | 1,216 | 19 | 3,344 | 749,757,632 (749.8M) |
29
+ | Max | `max/` | 1,344 | 21 | 3,696 | 901,621,056 (901.6M) |
30
+
31
+ Parameter counts include every weight of the model; rounded to 0.1M, they equal the entries of Table 10 of the paper. Each folder holds one model: `config.json` and `model.safetensors` (float32).
32
+
33
+ ## Results
34
+
35
+ | Model | Val. loss, this checkpoint | Val. loss, Table 2 | 5-shot acc. (%), this checkpoint | 5-shot acc. (%), Table 2 |
36
+ |---|---|---|---|---|
37
+ | Low | 3.0062 | 3.007 | 40.3 | 40.4 |
38
+ | Medium | 2.9636 | 2.963 | 41.4 | 41.8 |
39
+ | High | 2.9260 | 2.926 | 43.4 | 42.5 |
40
+ | Extra | 2.8975 | 2.897 | 43.8 | 43.2 |
41
+ | Max | 2.8693 | 2.870 | 43.1 | 43.1 |
42
+ | Avg. | 2.9325 | 2.933 | 42.4 | 42.2 |
43
+
44
+ *This checkpoint*: the final validation loss of each model (per-token cross-entropy in nats on held-out C4 text, at step 50,000) and its mean 5-shot accuracy over the 13 downstream tasks of Appendix F. *Table 2*: the paper's entries in the Standalone row at the 375M–906M scale. *Avg.*: the mean over the five models. Appendix G of the paper gives the per-task accuracies.
45
+
46
+ ## Architecture
47
+
48
+ Each folder holds one dense decoder-only transformer, one of the five Standalone architectures of the 375M–906M scale (Appendix E.1, Tables 7 and 8): width 832 to 1,344, FFN expansion 2.75 and d_head = 64.
49
+
50
+ | | |
51
+ |---|---|
52
+ | Attention | heads of size d_head = 64 (13 to 21 heads, Models table); separate query, key and value projections |
53
+ | FFN | SwiGLU with expansion e = 2.75 |
54
+ | Normalization | RMSNorm over the model width |
55
+ | Shared settings | 32 pre-norm layers with residual-branch multiplier 1; RMSNorm with learnable gains and ε_N = 10⁻⁵; query–key RMSNorm per head; rotary embeddings with base 10,000 (the code uses the rotate-half form); attention logit scale d_head^−1/2 and an elementwise sigmoid gate on the attention output, sigmoid(x W_G^⊤) (Equation 4); SwiGLU FFN; no biases; untied embeddings over the 50,432-token GPT-NeoX vocabulary; sequence length 2,048 (Table 8 and Section 4.1) |
56
+
57
+ The stored weights already include the constant forward multipliers of the model (the FFN output multiplier 1/e in `down_proj`), so every folder runs as an ordinary dense transformer of this architecture. Tensors of a model of width d and FFN width f, with i = 0, …, 31 numbering the layers:
58
+
59
+ | Tensor | Shape |
60
+ |---|---|
61
+ | `embed_tokens.weight` | [50432, d] |
62
+ | `layers.<i>.{attn_norm,mlp_norm}.weight`, `layers.<i>.attn.{q,k}_norm.weight`, `norm.weight` | [d] |
63
+ | `layers.<i>.attn.{q,k,v,gate,o}_proj.weight` | [d, d] |
64
+ | `layers.<i>.mlp.{gate,up}_proj.weight` | [f, d] |
65
+ | `layers.<i>.mlp.down_proj.weight` | [d, f] |
66
+ | `lm_head.weight` | [50432, d] |
67
+
68
+ ## Training
69
+
70
+ **Data.** [DCLM-Baseline](https://huggingface.co/datasets/mlfoundations/dclm-baseline-1.0) (Li et al., 2024), a filtered Common Crawl corpus, with the [GPT-NeoX-20B tokenizer](https://huggingface.co/EleutherAI/gpt-neox-20b) (Black et al., 2022) and a sequence length of 2,048 (Section 4.1). A run at this scale takes 50,000 steps of 256 sequences, 26.2B tokens (Appendix E.1). Each of the five models was trained separately for the full number of steps (Section 4.1 and Appendix G). The tokenized training and validation data of these runs are in the dataset repository [Can111/ShellElastic-pretraining-data](https://huggingface.co/datasets/Can111/ShellElastic-pretraining-data).
71
+
72
+ **Recipe.** Trained as described in the paper (Section 4.1, Appendices E.1 and E.2, and Table 9).
73
+
74
+ **Hyperparameters** (Section 4.1, Appendix E.1 and Table 9):
75
+
76
+ | Setting | Value |
77
+ |---|---|
78
+ | Parameterization | µP with d0 = 128 and m = width/128 (Table 8) |
79
+ | Optimizer | AdamW with decoupled weight decay |
80
+ | Base learning rate η0 | 2×10⁻³ |
81
+ | Base initialization σ0 | 3.3×10⁻³, truncated normal at ±3 standard deviations |
82
+ | Base weight decay λ0 | 0.01; none on norm gains |
83
+ | β1, β2 | 0.95, 0.95 |
84
+ | AdamW ε | 10⁻¹⁴ |
85
+ | Learning-rate schedule | warmup-stable-decay |
86
+ | Learning-rate warmup | linear, first 1,000 steps |
87
+ | Learning-rate decay | linear to 0, from step 40,000 to step 50,000 |
88
+ | Batch size | 256 sequences (524,288 tokens) |
89
+ | Sequence length | 2,048 |
90
+ | Training steps | 50,000 (26.2B tokens) |
91
+ | Gradient clipping | global norm 4 |
92
+ | Step skipping | after step 5,000, a step is skipped if its gradient norm exceeds 20× the clip value |
93
+ | z-loss coefficient λz | 10⁻⁴ (Equation 8); all reported losses are the cross-entropy alone (Appendix E.2) |
94
+ | Precision | bf16 mixed precision with fp32 master weights and fp32 gradient reduction |
95
+
96
+ ## Usage
97
+
98
+ The repository is self-contained: the reference implementation needs only PyTorch, plus `safetensors` to read the weights (`pip install -r requirements.txt`), and runs on CPU and GPU. Download the repository (for example with `huggingface_hub.snapshot_download("Can111/ShellElastic-baseline-Standalone-375M-906M", local_dir="ShellElastic-baseline-Standalone-375M-906M")`) and run, from that directory:
99
+
100
+ ```python
101
+ import torch
102
+ from modeling_dense import DenseDecoder
103
+
104
+ model = DenseDecoder.from_pretrained("low") # float32 on the CPU; folders: low, medium, high, extra, max
105
+ # model = DenseDecoder.from_pretrained("max", device="cuda", dtype=torch.bfloat16)
106
+ ids = torch.tensor([[510, 5347, 273, 6181, 310]]) # GPT-NeoX-20B ids of "The capital of France is"
107
+ logits = model(ids) # [1, 5, 50432], float32
108
+ logits, loss = model(ids[:, :-1], labels=ids[:, 1:]) # mean next-token cross-entropy
109
+ out = model.generate(ids, max_new_tokens=20) # greedy decoding (no key/value cache)
110
+ ```
111
+
112
+ `python example.py --tier max` runs one model on the CPU (`--dtype bfloat16` runs it in bfloat16).
113
+
114
+ Inputs are token ids of the [GPT-NeoX-20B tokenizer](https://huggingface.co/EleutherAI/gpt-neox-20b), for example from `tokenizers.Tokenizer.from_pretrained("EleutherAI/gpt-neox-20b")`; the tokenizer is not bundled here. The vocabulary has 50,432 entries (Table 7), of which the tokenizer uses the first 50,277.
115
+
116
+ ## Validation
117
+
118
+ Loaded in bfloat16 (the paper uses bf16 mixed precision, Table 9), the weights and code in this repository reproduce the final validation loss in the *this checkpoint* column of Results for the Max model to within 2×10⁻⁴ nats.
119
+
120
+ ## Files
121
+
122
+ - `README.md`: this card
123
+ - `LICENSE`: the Apache License 2.0
124
+ - `requirements.txt`: `torch` and `safetensors`
125
+ - `modeling_dense.py`: the reference implementation (PyTorch only)
126
+ - `example.py`: loads one model on the CPU and runs it
127
+ - `low/`, `medium/`, `high/`, `extra/`, `max/`: `config.json` and `model.safetensors` (float32) of each model
128
+
129
+ ## Limitations
130
+
131
+ These are research checkpoints of language models pretrained on DCLM-Baseline, a filtered Common Crawl corpus,
132
+ for a study of elastic pretraining. They have not been instruction-tuned, aligned or evaluated for safety, are
133
+ not intended for deployment, and can produce incorrect, biased or offensive text. Use them for research only.
134
+
135
+ ## License
136
+
137
+ The weights and the code in this repository are released under the Apache License 2.0 (`LICENSE`).
138
+
139
+ Third-party terms: the training data, DCLM-Baseline, are distributed under CC-BY-4.0 and derived from Common Crawl;
140
+ the validation text is from C4, distributed under ODC-BY together with the Common Crawl terms of use. Neither is
141
+ included in this repository; the tokenized data of these runs are in the dataset repository
142
+ [Can111/ShellElastic-pretraining-data](https://huggingface.co/datasets/Can111/ShellElastic-pretraining-data), under the licenses of their sources. The GPT-NeoX-20B tokenizer (Apache-2.0) is not
143
+ bundled here.
144
+
145
+ ## Citation
146
+
147
+ ```bibtex
148
+ @article{jin2026shellelastic,
149
+ title = {ShellElastic: Scalable Elastic Pretraining with Simultaneous Maximal Updates and Hyperparameter Transfer},
150
+ author = {Jin, Can and Kang, Yan and Gong, Yifan and Ge, Chongjian and Xu, Mingze and Xiong, Yuanjun and Metaxas, Dimitris N. and Peng, Hongwu},
151
+ journal = {arXiv preprint arXiv:XXXX.XXXXX},
152
+ year = {2026}
153
+ }
154
+ ```
example.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load one model of this repository on the CPU and run it.
2
+
3
+ Usage, from the downloaded repository:
4
+
5
+ python example.py # the Low model, float32
6
+ python example.py --tier max --dtype bfloat16
7
+
8
+ Needs only torch and safetensors (see requirements.txt). Nothing is written to disk.
9
+ """
10
+
11
+ import argparse
12
+ import os
13
+ import sys
14
+
15
+ sys.dont_write_bytecode = True # leave the downloaded folder unchanged
16
+ HERE = os.path.dirname(os.path.abspath(__file__))
17
+ sys.path.insert(0, HERE)
18
+
19
+ import torch # noqa: E402
20
+
21
+ from modeling_dense import DenseDecoder # noqa: E402
22
+
23
+ TIERS = ["low", "medium", "high", "extra", "max"]
24
+ # GPT-NeoX-20B token ids of "The capital of France is". Any copy of that tokenizer gives them, for example
25
+ # tokenizers.Tokenizer.from_pretrained("EleutherAI/gpt-neox-20b").encode("The capital of France is").ids
26
+ PROMPT_IDS = [510, 5347, 273, 6181, 310]
27
+
28
+
29
+ def main() -> None:
30
+ parser = argparse.ArgumentParser(description="Run one model of this repository on the CPU.")
31
+ parser.add_argument("--tier", default="low", choices=TIERS, help="model folder to load (default: low)")
32
+ parser.add_argument("--dtype", default="float32", choices=["float32", "bfloat16"],
33
+ help="compute precision (the released weights are float32)")
34
+ parser.add_argument("--new-tokens", type=int, default=8, help="greedy tokens to generate")
35
+ args = parser.parse_args()
36
+
37
+ model = DenseDecoder.from_pretrained(os.path.join(HERE, args.tier), device="cpu",
38
+ dtype=getattr(torch, args.dtype))
39
+ cfg = model.config
40
+ n_params = sum(p.numel() for p in model.parameters())
41
+ print(f"{args.tier}: width {cfg.hidden_size}, {cfg.num_attention_heads} heads, FFN width "
42
+ f"{cfg.intermediate_size}, {n_params:,} parameters, {args.dtype}")
43
+
44
+ ids = torch.tensor([PROMPT_IDS])
45
+ with torch.no_grad():
46
+ logits, loss = model(ids[:, :-1], labels=ids[:, 1:])
47
+ out = model.generate(ids, max_new_tokens=args.new_tokens)
48
+ assert logits.shape == (1, len(PROMPT_IDS) - 1, cfg.vocab_size)
49
+ assert torch.isfinite(logits).all() and torch.isfinite(loss)
50
+ print(f"prompt ids: {PROMPT_IDS}")
51
+ print(f"mean next-token loss on the prompt: {loss.item():.4f}")
52
+ print(f"greedy continuation ids: {out[0, len(PROMPT_IDS):].tolist()}")
53
+
54
+
55
+ if __name__ == "__main__":
56
+ main()
extra/config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DenseDecoder"
4
+ ],
5
+ "vocab_size": 50432,
6
+ "hidden_size": 1216,
7
+ "intermediate_size": 3344,
8
+ "num_hidden_layers": 32,
9
+ "num_attention_heads": 19,
10
+ "head_dim": 64,
11
+ "max_position_embeddings": 2048,
12
+ "rope_theta": 10000.0,
13
+ "rope_precision": "bfloat16",
14
+ "rms_norm_eps": 1e-05,
15
+ "hidden_act": "silu",
16
+ "attention_output_gate": "sigmoid",
17
+ "qk_norm": "rmsnorm_per_head",
18
+ "tie_word_embeddings": false,
19
+ "torch_dtype": "float32",
20
+ "tokenizer": "EleutherAI/gpt-neox-20b",
21
+ "method": "Standalone",
22
+ "scale": "375M–906M",
23
+ "tier": "Extra"
24
+ }
extra/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ffd400dad1e2589e53da47cbf14b8c21f6ca368098b5a3f69ebc434c385b5b69
3
+ size 2999070608
high/config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DenseDecoder"
4
+ ],
5
+ "vocab_size": 50432,
6
+ "hidden_size": 1088,
7
+ "intermediate_size": 2992,
8
+ "num_hidden_layers": 32,
9
+ "num_attention_heads": 17,
10
+ "head_dim": 64,
11
+ "max_position_embeddings": 2048,
12
+ "rope_theta": 10000.0,
13
+ "rope_precision": "bfloat16",
14
+ "rms_norm_eps": 1e-05,
15
+ "hidden_act": "silu",
16
+ "attention_output_gate": "sigmoid",
17
+ "qk_norm": "rmsnorm_per_head",
18
+ "tie_word_embeddings": false,
19
+ "torch_dtype": "float32",
20
+ "tokenizer": "EleutherAI/gpt-neox-20b",
21
+ "method": "Standalone",
22
+ "scale": "375M–906M",
23
+ "tier": "High"
24
+ }
high/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:355bcdcd0a48ed9158cd075ecf8cd395facca530c645fcfb87fc50392a6c1d6c
3
+ size 2447191368
low/config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DenseDecoder"
4
+ ],
5
+ "vocab_size": 50432,
6
+ "hidden_size": 832,
7
+ "intermediate_size": 2288,
8
+ "num_hidden_layers": 32,
9
+ "num_attention_heads": 13,
10
+ "head_dim": 64,
11
+ "max_position_embeddings": 2048,
12
+ "rope_theta": 10000.0,
13
+ "rope_precision": "bfloat16",
14
+ "rms_norm_eps": 1e-05,
15
+ "hidden_act": "silu",
16
+ "attention_output_gate": "sigmoid",
17
+ "qk_norm": "rmsnorm_per_head",
18
+ "tie_word_embeddings": false,
19
+ "torch_dtype": "float32",
20
+ "tokenizer": "EleutherAI/gpt-neox-20b",
21
+ "method": "Standalone",
22
+ "scale": "375M–906M",
23
+ "tier": "Low"
24
+ }
low/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71e54f8d2da5af695490072c3a6bc0f4ff6b9fce54f7ffc464453293f9f7b206
3
+ size 1510155832
max/config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DenseDecoder"
4
+ ],
5
+ "vocab_size": 50432,
6
+ "hidden_size": 1344,
7
+ "intermediate_size": 3696,
8
+ "num_hidden_layers": 32,
9
+ "num_attention_heads": 21,
10
+ "head_dim": 64,
11
+ "max_position_embeddings": 2048,
12
+ "rope_theta": 10000.0,
13
+ "rope_precision": "bfloat16",
14
+ "rms_norm_eps": 1e-05,
15
+ "hidden_act": "silu",
16
+ "attention_output_gate": "sigmoid",
17
+ "qk_norm": "rmsnorm_per_head",
18
+ "tie_word_embeddings": false,
19
+ "torch_dtype": "float32",
20
+ "tokenizer": "EleutherAI/gpt-neox-20b",
21
+ "method": "Standalone",
22
+ "scale": "375M–906M",
23
+ "tier": "Max"
24
+ }
max/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c04dfe6b120af42a568bb5b9d747ba2a83224ac39f03716a2e5f8ff73e314e3
3
+ size 3606524352
medium/config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DenseDecoder"
4
+ ],
5
+ "vocab_size": 50432,
6
+ "hidden_size": 960,
7
+ "intermediate_size": 2640,
8
+ "num_hidden_layers": 32,
9
+ "num_attention_heads": 15,
10
+ "head_dim": 64,
11
+ "max_position_embeddings": 2048,
12
+ "rope_theta": 10000.0,
13
+ "rope_precision": "bfloat16",
14
+ "rms_norm_eps": 1e-05,
15
+ "hidden_act": "silu",
16
+ "attention_output_gate": "sigmoid",
17
+ "qk_norm": "rmsnorm_per_head",
18
+ "tie_word_embeddings": false,
19
+ "torch_dtype": "float32",
20
+ "tokenizer": "EleutherAI/gpt-neox-20b",
21
+ "method": "Standalone",
22
+ "scale": "375M–906M",
23
+ "tier": "Medium"
24
+ }
medium/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7609f5e692e9c2691c1efae0b62e2f90b60f607fa3bf6e678d00fca0259cd30f
3
+ size 1950886088
modeling_dense.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reference implementation of the dense decoder-only transformer behind the Standalone and Sampled standalone
2
+ models of "ShellElastic: Scalable Elastic Pretraining with Simultaneous Maximal Updates and Hyperparameter
3
+ Transfer".
4
+
5
+ Each released model is an ordinary dense decoder. The released weights already include the constant forward
6
+ multipliers of the model (for these models, the FFN output multiplier 1/e, where e is the FFN expansion), so this
7
+ file contains no scaling constants.
8
+
9
+ Architecture (one layer, pre-norm):
10
+
11
+ h = x + Attention(RMSNorm(x))
12
+ out = h + SwiGLU(RMSNorm(h))
13
+
14
+ * RMSNorm with eps 1e-5; this file computes the statistics in float32 and casts the result back to the input dtype
15
+ before the learned gain is applied.
16
+ * Attention: separate query/key/value projections without biases; queries and keys are RMS-normalized within
17
+ each head (the gains are stored at full width, one per channel); rotary position embeddings in the
18
+ rotate-half form with base 10,000; causal softmax attention with scale 1/sqrt(head_dim); the attention output
19
+ is multiplied elementwise by sigmoid(x W_gate^T) before the output projection.
20
+ * SwiGLU feed-forward network: down_proj(silu(gate_proj(x)) * up_proj(x)).
21
+ * Untied input embedding and output head, no biases anywhere, context length 2,048, and the 50,432-token GPT-NeoX
22
+ vocabulary (Table 8 of the paper; token ids of the GPT-NeoX-20B tokenizer, Section 4.1).
23
+
24
+ Rotary tables: ``rope_precision`` is ``"bfloat16"`` (the default) or ``"float32"``. ``"bfloat16"`` rounds the
25
+ positions and inverse frequencies to bfloat16, their product to bfloat16, and cos/sin of those angles to bfloat16,
26
+ in every compute precision; ``"float32"`` computes the tables in float32.
27
+
28
+ Dependencies: torch, and safetensors for loading the weights.
29
+
30
+ Example:
31
+
32
+ import torch
33
+ from modeling_dense import DenseDecoder
34
+
35
+ model = DenseDecoder.from_pretrained("path/to/model_dir", device="cuda", dtype=torch.bfloat16)
36
+ input_ids = torch.tensor([[...]], device="cuda") # GPT-NeoX-20B token ids
37
+ logits = model(input_ids) # [batch, tokens, 50432], float32
38
+ logits, loss = model(input_ids[:, :-1], labels=input_ids[:, 1:])
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import json
44
+ import os
45
+ from dataclasses import asdict, dataclass, fields
46
+
47
+ import torch
48
+ import torch.nn.functional as F
49
+ from torch import nn
50
+
51
+ __all__ = ["DenseConfig", "DenseDecoder"]
52
+
53
+
54
+ @dataclass
55
+ class DenseConfig:
56
+ vocab_size: int = 50432
57
+ hidden_size: int = 384
58
+ intermediate_size: int = 1536
59
+ num_hidden_layers: int = 32
60
+ num_attention_heads: int = 6
61
+ head_dim: int = 64
62
+ max_position_embeddings: int = 2048
63
+ rope_theta: float = 10000.0
64
+ rope_precision: str = "bfloat16"
65
+ rms_norm_eps: float = 1e-5
66
+
67
+ @classmethod
68
+ def from_dict(cls, values: dict) -> "DenseConfig":
69
+ """Build a config from a dict, ignoring keys that only describe the release (method, tier, ...)."""
70
+ known = {f.name for f in fields(cls)}
71
+ return cls(**{k: v for k, v in values.items() if k in known})
72
+
73
+ @classmethod
74
+ def from_json_file(cls, path: str) -> "DenseConfig":
75
+ with open(path) as f:
76
+ return cls.from_dict(json.load(f))
77
+
78
+ def to_dict(self) -> dict:
79
+ return asdict(self)
80
+
81
+
82
+ class RMSNorm(nn.Module):
83
+ """RMSNorm over the last dimension, or within consecutive groups of ``group_size`` channels.
84
+
85
+ The normalization runs in float32; the result is cast back to the input dtype and then multiplied by the
86
+ per-channel gain (one gain per channel, also in grouped mode).
87
+ """
88
+
89
+ def __init__(self, dim: int, eps: float, group_size: int | None = None) -> None:
90
+ super().__init__()
91
+ self.eps = eps
92
+ self.group_size = group_size
93
+ self.weight = nn.Parameter(torch.ones(dim))
94
+
95
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
96
+ h = x.float()
97
+ if self.group_size is not None:
98
+ h = h.unflatten(-1, (-1, self.group_size))
99
+ h = h * torch.rsqrt(h.pow(2).mean(-1, keepdim=True) + self.eps)
100
+ if self.group_size is not None:
101
+ h = h.flatten(-2)
102
+ return h.to(x.dtype) * self.weight
103
+
104
+
105
+ def rotary_cos_sin(config: DenseConfig, num_positions: int, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:
106
+ """Rotary tables of shape [num_positions, head_dim] in float32 (rotate-half layout)."""
107
+ dim = config.head_dim
108
+ frequencies = 1.0 / (config.rope_theta ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)) # on CPU
109
+ frequencies = frequencies.to(device)
110
+ positions = torch.arange(num_positions, device=device, dtype=torch.float32)
111
+ if config.rope_precision == "bfloat16":
112
+ # Every step rounded to bfloat16 (the product of two bfloat16 numbers is exact in float32, so rounding it
113
+ # once gives the bfloat16 product).
114
+ def bf16(t: torch.Tensor) -> torch.Tensor:
115
+ return t.to(torch.bfloat16).float()
116
+
117
+ angles = bf16(torch.outer(bf16(positions), bf16(frequencies)))
118
+ angles = torch.cat((angles, angles), dim=-1)
119
+ return bf16(angles.cos()), bf16(angles.sin())
120
+ if config.rope_precision != "float32":
121
+ raise ValueError(f"rope_precision must be 'bfloat16' or 'float32', got {config.rope_precision!r}")
122
+ angles = torch.outer(positions, frequencies)
123
+ angles = torch.cat((angles, angles), dim=-1)
124
+ return angles.cos(), angles.sin()
125
+
126
+
127
+ def rotate_half(x: torch.Tensor) -> torch.Tensor:
128
+ """(a, b) -> (-b, a) over the two halves of the last dimension."""
129
+ half = x.shape[-1] // 2
130
+ return torch.cat((-x[..., half:], x[..., :half]), dim=-1)
131
+
132
+
133
+ def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
134
+ """x: [batch, tokens, heads, head_dim]; cos, sin: [tokens, head_dim], already in x's dtype."""
135
+ cos = cos[None, :, None, :]
136
+ sin = sin[None, :, None, :]
137
+ return x * cos + rotate_half(x) * sin
138
+
139
+
140
+ class Attention(nn.Module):
141
+ def __init__(self, config: DenseConfig) -> None:
142
+ super().__init__()
143
+ self.num_heads = config.num_attention_heads
144
+ self.head_dim = config.head_dim
145
+ width = config.num_attention_heads * config.head_dim
146
+ self.q_proj = nn.Linear(config.hidden_size, width, bias=False)
147
+ self.k_proj = nn.Linear(config.hidden_size, width, bias=False)
148
+ self.v_proj = nn.Linear(config.hidden_size, width, bias=False)
149
+ self.gate_proj = nn.Linear(config.hidden_size, width, bias=False) # sigmoid output gate
150
+ self.o_proj = nn.Linear(width, config.hidden_size, bias=False)
151
+ self.q_norm = RMSNorm(width, config.rms_norm_eps, group_size=config.head_dim)
152
+ self.k_norm = RMSNorm(width, config.rms_norm_eps, group_size=config.head_dim)
153
+
154
+ def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
155
+ batch, length, _ = x.shape
156
+ heads = (batch, length, self.num_heads, self.head_dim)
157
+ q = self.q_norm(self.q_proj(x)).view(heads)
158
+ k = self.k_norm(self.k_proj(x)).view(heads)
159
+ v = self.v_proj(x).view(heads)
160
+ q = apply_rotary(q, cos, sin)
161
+ k = apply_rotary(k, cos, sin)
162
+ out = F.scaled_dot_product_attention(
163
+ q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, scale=self.head_dim**-0.5
164
+ )
165
+ out = out.transpose(1, 2).reshape(batch, length, self.num_heads * self.head_dim)
166
+ out = out * torch.sigmoid(self.gate_proj(x))
167
+ return self.o_proj(out)
168
+
169
+
170
+ class MLP(nn.Module):
171
+ def __init__(self, config: DenseConfig) -> None:
172
+ super().__init__()
173
+ self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
174
+ self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
175
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
176
+
177
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
178
+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
179
+
180
+
181
+ class DecoderLayer(nn.Module):
182
+ def __init__(self, config: DenseConfig) -> None:
183
+ super().__init__()
184
+ self.attn_norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
185
+ self.attn = Attention(config)
186
+ self.mlp_norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
187
+ self.mlp = MLP(config)
188
+
189
+ def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
190
+ h = x + self.attn(self.attn_norm(x), cos, sin)
191
+ return h + self.mlp(self.mlp_norm(h))
192
+
193
+
194
+ class DenseDecoder(nn.Module):
195
+ """Decoder-only language model. ``forward`` returns float32 logits (and the mean cross-entropy loss when
196
+ ``labels`` is given; label -100 is ignored)."""
197
+
198
+ def __init__(self, config: DenseConfig) -> None:
199
+ super().__init__()
200
+ self.config = config
201
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
202
+ self.layers = nn.ModuleList(DecoderLayer(config) for _ in range(config.num_hidden_layers))
203
+ self.norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
204
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
205
+
206
+ def hidden_states(self, input_ids: torch.Tensor) -> torch.Tensor:
207
+ """Final hidden states after the last norm, [batch, tokens, hidden_size], in the model's dtype."""
208
+ length = input_ids.shape[1]
209
+ if length > self.config.max_position_embeddings:
210
+ raise ValueError(f"{length} tokens exceed the context of {self.config.max_position_embeddings}")
211
+ x = self.embed_tokens(input_ids)
212
+ cos, sin = rotary_cos_sin(self.config, length, input_ids.device)
213
+ cos, sin = cos.to(x.dtype), sin.to(x.dtype)
214
+ for layer in self.layers:
215
+ x = layer(x, cos, sin)
216
+ return self.norm(x)
217
+
218
+ def forward(self, input_ids: torch.Tensor, labels: torch.Tensor | None = None):
219
+ logits = self.lm_head(self.hidden_states(input_ids)).float()
220
+ if labels is None:
221
+ return logits
222
+ loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100)
223
+ return logits, loss
224
+
225
+ @torch.no_grad()
226
+ def generate(self, input_ids: torch.Tensor, max_new_tokens: int, temperature: float = 0.0) -> torch.Tensor:
227
+ """Simple sampling without a key/value cache (greedy when temperature is 0)."""
228
+ for _ in range(max_new_tokens):
229
+ context = input_ids[:, -self.config.max_position_embeddings:]
230
+ next_logits = self(context)[:, -1]
231
+ if temperature > 0:
232
+ probs = torch.softmax(next_logits / temperature, dim=-1)
233
+ next_ids = torch.multinomial(probs, num_samples=1)
234
+ else:
235
+ next_ids = next_logits.argmax(dim=-1, keepdim=True)
236
+ input_ids = torch.cat([input_ids, next_ids], dim=1)
237
+ return input_ids
238
+
239
+ @classmethod
240
+ def from_pretrained(cls, directory: str, device="cpu", dtype: torch.dtype = torch.float32) -> "DenseDecoder":
241
+ """Load ``config.json`` and ``model.safetensors`` from a released model directory.
242
+
243
+ The weights are read and cast to ``dtype`` on the CPU and then moved to ``device``, so the device holds only
244
+ one copy of the model, in ``dtype``."""
245
+ from safetensors.torch import load_file
246
+
247
+ config = DenseConfig.from_json_file(os.path.join(directory, "config.json"))
248
+ state = load_file(os.path.join(directory, "model.safetensors"), device="cpu")
249
+ if dtype is not None:
250
+ for name in list(state): # cast on the CPU, one tensor at a time
251
+ if state[name].is_floating_point():
252
+ state[name] = state[name].to(dtype)
253
+ with torch.device("meta"):
254
+ model = cls(config)
255
+ model.load_state_dict(state, strict=True, assign=True)
256
+ return model.to(device).eval()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # PyTorch and safetensors. The [torch] extra of safetensors also installs numpy, which safetensors needs to write
2
+ # files (save_pretrained, save_subnetwork); loading and running the models need only torch and safetensors.
3
+ # Tested with torch 2.9.1 and safetensors 0.7.0.
4
+ torch>=2.1
5
+ safetensors[torch]>=0.4