Final checkpoints of Table 2
Browse filesFiles changed (7)
- LICENSEAdded+202
- README.mdAdded+168
- config.jsonAdded+39
- example.pyAdded+73
- model.safetensorsAdded+3
- modeling_shellelastic.pyAdded+536
- requirements.txtAdded+5
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168---license: apache-2.0language:- endatasets:- mlfoundations/dclm-baseline-1.0- Can111/ShellElastic-pretraining-datalibrary_name: pytorchpipeline_tag: text-generationtags:- shellelastic- elastic-pretraining- supernet---
# ShellElastic, 375M–906M scale (Table 2)
Final weights of the ShellElastic supernet 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. ShellElastic is an elastic transformer that organizes hidden dimensions into a dense core and successive shells, so that every hidden matrix is block lower triangular, and one full-width forward pass contains the exact hidden states of every sub-network (Section 3.1 and Proposition 1). `model.safetensors` holds the supernet with its five sub-networks (Low, Medium, High, Extra, Max); `modeling_shellelastic.py` runs any of them and extracts it as a standalone model (Section 3.3).
## Sub-networks
| Sub-network | Model width | Attention heads | FFN width | Parameters ||---|---|---|---|---|| Low | 1,024 | 8 | 1,024 | 371,852,293 (371.9M) || Medium | 1,280 | 10 | 1,280 | 481,592,581 (481.6M) || High | 1,536 | 12 | 1,536 | 608,110,085 (608.1M) || Extra | 1,792 | 14 | 1,792 | 751,404,805 (751.4M) || Max | 2,048 | 16 | 2,048 | 911,476,741 (911.5M) |
Parameter counts include the five learned readout scalars α_s; rounded to 0.1M, they equal the entries of Table 10 of the paper. `model.num_parameters(tier)` counts the extracted sub-network, whose readout weights already contain α_s, and reports 5 fewer. `model.safetensors` stores the supernet: 1,195,515,392 parameters (4.78 GB in float32).
## Results
| Sub-network | Val. loss, this checkpoint | Val. loss, Table 2 | 5-shot acc. (%), this checkpoint | 5-shot acc. (%), Table 2 ||---|---|---|---|---|| Low | 3.0528 | 3.055 | 40.8 | 40.8 || Medium | 2.9998 | 3.000 | 41.8 | 41.4 || High | 2.9670 | 2.967 | 42.4 | 42.0 || Extra | 2.9432 | 2.943 | 42.7 | 42.6 || Max | 2.9245 | 2.925 | 43.2 | 43.0 || Avg. | 2.9774 | 2.978 | 42.2 | 41.9 |
*This checkpoint*: the final validation loss of each sub-network of these weights (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 ShellElastic row at the 375M–906M scale. *Avg.*: the mean over the five sub-networks. Appendix G of the paper gives the per-task accuracies.
## Architecture
ShellElastic (Section 3.1 of the paper) organizes the hidden dimensions into a dense core followed by successive shells (Figure 1). This supernet has the settings of Section 4.1 and Appendix E.1 (Tables 7 and 8):
| | ||---|---|| Base width, supported set | g = 256, S = {4, 5, 6, 7, 8}, M = 8: a 1,024-dimensional core followed by four 256-dimensional shells || Groups | G_1 (the core) to G_5, of widths (1,024, 256, 256, 256, 256); sub-network s_k contains the first k groups, so Low to Max have widths 1,024 to 2,048 || Projections | every hidden matrix is block lower triangular: the block row W_k, which produces output group G_k, reads only the first s_k·g input dimensions (Equation 2) || Normalization | the two branch norms of every layer are group-local over G_1, …, G_5 (Equation 3); every sub-network has its own terminal norm over all of its s·g dimensions (Equation 6) || Attention | d_head = 128, two heads per base width; sub-network s uses the first s·g/d_head heads (Section 3.1) || FFN | SwiGLU with expansion e = 1 (Equation 5) || Readout | a readout U_s and a learned logit scale α_s per sub-network (Equation 6) || 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) |
`model.safetensors` stores every hidden matrix by block row, without the zero blocks above the diagonal: `core` is W_1, the block row of the core G_1, and `shell.<j>` (j = 1, …, 4) is W_(j+1), the block row of the shell G_(j+1), of shape [|G_(j+1)|, s_(j+1)·g] (for the FFN, e times as many rows in `gate_proj` and `up_proj` and e times as many columns in `down_proj`). With i = 0, …, 31 numbering the layers and `<tier>` one of `low`, `medium`, `high`, `extra`, `max`:
| Tensor | Shape ||---|---|| `embed_tokens.weight` | [50432, 2048]; sub-network s uses the first s·g columns || `layers.<i>.{attn_norm,mlp_norm}.weight`, `layers.<i>.attn.{q,k}_norm.weight` | [2048]; sub-network s uses the first s·g entries || `layers.<i>.attn.{q,k,v,gate,o}_proj.core.weight` | [1024, 1024] || `layers.<i>.attn.{q,k,v,gate,o}_proj.shell.<j>.weight` | [256, 1280], [256, 1536], [256, 1792], [256, 2048] for j = 1, …, 4 || `layers.<i>.mlp.{gate,up}_proj.core.weight` | [1024, 1024] || `layers.<i>.mlp.{gate,up}_proj.shell.<j>.weight` | [256, 1280], [256, 1536], [256, 1792], [256, 2048] || `layers.<i>.mlp.down_proj.core.weight` | [1024, 1024] || `layers.<i>.mlp.down_proj.shell.<j>.weight` | [256, 1280], [256, 1536], [256, 1792], [256, 2048] || `norm.<tier>.weight` | [s·g]: the terminal norm of sub-network s || `lm_head.<tier>.weight` | [50432, s·g]: the readout U_s multiplied by its learned logit scale α_s |
`mlp.down_proj` includes the forward multiplier 1/e of Table 1 (here e = 1), so the model needs no further scalars; query, key and value are separate tensors.
## Training
**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). 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).
**Recipe.** Trained as described in the paper (Sections 3.3 and 4.1, Appendices E.1 and E.2, and Table 9).
**Hyperparameters** (Section 4.1, Appendix E.1 and Table 9):
| Setting | Value ||---|---|| Parameterization | µ-Elastic (Section 3.2, Table 1) with d0 = 128 and m = g/d0 = 2 || Optimizer | AdamW with decoupled weight decay || Base learning rate η0 | 2×10⁻³ || Base initialization σ0 | 3.3×10⁻³, truncated normal at ±3 standard deviations || Base weight decay λ0 | 0.01; none on norm gains and α_s || β1, β2 | 0.95, 0.95 || AdamW ε | 10⁻¹⁴ || Learning-rate schedule | warmup-stable-decay || Learning-rate warmup | linear, first 1,000 steps || Learning-rate decay | linear to 0, from step 40,000 to step 50,000 || Batch size | 256 sequences (524,288 tokens) || Sequence length | 2,048 || Training steps | 50,000 (26.2B tokens) || Gradient clipping | global norm 4 || Step skipping | after step 5,000, a step is skipped if its gradient norm exceeds 20× the clip value || z-loss coefficient λz | 10⁻⁴ (Equation 8); all reported losses are the cross-entropy alone (Appendix E.2) || Loss weights ω_s, Low to Max | (1, 1, 1, 1, 4) (Equation 8) || Precision | bf16 mixed precision with fp32 master weights and fp32 gradient reduction |
## Usage
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-375M-906M", local_dir="ShellElastic-375M-906M")`) and run, from that directory:
```pythonimport torchfrom modeling_shellelastic import ShellElasticForCausalLM
model = ShellElasticForCausalLM.from_pretrained(".") # float32 on the CPU# model = ShellElasticForCausalLM.from_pretrained(".", device="cuda", dtype=torch.bfloat16)ids = torch.tensor([[510, 5347, 273, 6181, 310]]) # GPT-NeoX-20B ids of "The capital of France is"logits = model(ids, tier="medium") # [1, 5, 50432]; tiers: low, medium, high, extra, maxper_tier = model(ids, tiers=model.config.tiers) # all five sub-networks from one trunk passlogits, loss = model(ids[:, :-1], tier="low", labels=ids[:, 1:]) # mean next-token cross-entropyout = model.generate(ids, max_new_tokens=20, tier="max") # greedy decoding (no key/value cache)low = model.extract("low") # the Low sub-network as a standalone modellow.save_pretrained("low_model") # its config.json and model.safetensors```
`extract(tier)` keeps the embedding columns, the core and the shells of that sub-network, the leading entries of every norm gain, and its own terminal norm and readout (Section 3.3); by Proposition 1 its logits equal the supernet's for that sub-network, and `from_pretrained` loads the saved folder. `dense_state_dict(tier)` returns the weights of a sub-network with dense matrices (zeros above the block diagonal), for inspection and porting; running them still requires the group-local norms. `python example.py --tier medium` runs a sub-network on the CPU and checks its extraction (`--save DIR` writes the extracted model).
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.
## Validation
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 every sub-network to within 2×10⁻⁴ nats.
## Files
- `README.md`: this card- `LICENSE`: the Apache License 2.0- `requirements.txt`: `torch` and `safetensors`- `modeling_shellelastic.py`: the reference implementation (PyTorch only)- `example.py`: loads the supernet on the CPU and runs one sub-network and extracts it- `config.json`: the architecture of the supernet- `model.safetensors`: the weights of the supernet (float32)
## Limitations
These are research checkpoints of language models pretrained on DCLM-Baseline, a filtered Common Crawl corpus,for a study of elastic pretraining. They have not been instruction-tuned, aligned or evaluated for safety, arenot intended for deployment, and can produce incorrect, biased or offensive text. Use them for research only.
## License
The weights and the code in this repository are released under the Apache License 2.0 (`LICENSE`).
Third-party terms: the training data, DCLM-Baseline, are distributed under CC-BY-4.0 and derived from Common Crawl;the validation text is from C4, distributed under ODC-BY together with the Common Crawl terms of use. Neither isincluded in this repository; the tokenized data of these runs are in the dataset repository[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 notbundled here.
## Citation
```bibtex@article{jin2026shellelastic, title = {ShellElastic: Scalable Elastic Pretraining with Simultaneous Maximal Updates and Hyperparameter Transfer}, 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}, journal = {arXiv preprint arXiv:XXXX.XXXXX}, year = {2026}}```123456789101112131415161718192021222324252627282930313233343536373839{ "vocab_size": 50432, "num_hidden_layers": 32, "base_width": 256, "widths": [ 4, 5, 6, 7, 8 ], "tiers": [ "low", "medium", "high", "extra", "max" ], "readout_tiers": [ "low", "medium", "high", "extra", "max" ], "head_dim": 128, "mlp_base_width": 256, "rope_theta": 10000.0, "rope_precision": "bfloat16", "rms_norm_eps": 1e-05, "max_position_embeddings": 2048, "tie_word_embeddings": false, "tokenizer": "EleutherAI/gpt-neox-20b", "architectures": [ "ShellElasticForCausalLM" ], "model_type": "shellelastic", "torch_dtype": "float32"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""Load the ShellElastic supernet of this repository on the CPU, run one sub-network and extract it.
Usage, from the downloaded repository:
python example.py # the Low sub-network, float32 python example.py --tier max --dtype bfloat16 python example.py --tier low --save low_model # also write the extracted Low model to ./low_model
Needs only torch and safetensors (see requirements.txt). Nothing is written to disk unless --save is given."""
import argparseimport osimport sys
sys.dont_write_bytecode = True # leave the downloaded folder unchangedHERE = os.path.dirname(os.path.abspath(__file__))sys.path.insert(0, HERE)
import torch # noqa: E402
from modeling_shellelastic import ShellElasticForCausalLM # noqa: E402
# GPT-NeoX-20B token ids of "The capital of France is". Any copy of that tokenizer gives them, for example# tokenizers.Tokenizer.from_pretrained("EleutherAI/gpt-neox-20b").encode("The capital of France is").idsPROMPT_IDS = [510, 5347, 273, 6181, 310]
def main() -> None: parser = argparse.ArgumentParser(description="Run and extract one sub-network of this supernet on the CPU.") parser.add_argument("--tier", default="low", choices=["low", "medium", "high", "extra", "max"], help="sub-network (default: low)") parser.add_argument("--dtype", default="float32", choices=["float32", "bfloat16"], help="compute precision (the released weights are float32)") parser.add_argument("--new-tokens", type=int, default=8, help="greedy tokens to generate") parser.add_argument("--save", metavar="DIR", help="write the extracted sub-network (config.json and " "model.safetensors, loadable with modeling_shellelastic.py) to DIR") args = parser.parse_args()
model = ShellElasticForCausalLM.from_pretrained(HERE, device="cpu", dtype=getattr(torch, args.dtype)) cfg = model.config print(f"supernet: {model.num_parameters():,} stored parameters, {args.dtype}") print(f"{args.tier}: width {cfg.width(args.tier)}, {cfg.width(args.tier) // cfg.head_dim} heads, " f"{model.num_parameters(args.tier):,} parameters")
ids = torch.tensor([PROMPT_IDS]) with torch.no_grad(): logits, loss = model(ids[:, :-1], tier=args.tier, labels=ids[:, 1:]) all_tiers = model(ids, tiers=cfg.tiers) # every sub-network from one full-width trunk pass out = model.generate(ids, max_new_tokens=args.new_tokens, tier=args.tier) assert logits.shape == (1, len(PROMPT_IDS) - 1, cfg.vocab_size) assert torch.isfinite(logits.float()).all() and torch.isfinite(loss) print(f"prompt ids: {PROMPT_IDS}") print(f"mean next-token loss on the prompt: {loss.item():.4f}") print("next-token id after the prompt, per sub-network: " + ", ".join(f"{t} {all_tiers[t][0, -1].argmax().item()}" for t in cfg.tiers)) print(f"greedy continuation ids: {out[0, len(PROMPT_IDS):].tolist()}")
# The sub-network as a standalone model: its embedding columns, the core and the shells it contains, and its own # terminal norm and readout. By Proposition 1 of the paper its logits equal the supernet's for this tier. small = model.extract(args.tier) with torch.no_grad(): diff = (small(ids, tier=args.tier).float() - model(ids, tier=args.tier).float()).abs().max().item() print(f"extracted {args.tier}: {small.num_parameters():,} parameters, max |logit difference| to the " f"supernet {diff:g}") assert diff == 0.0 if args.save: small.save_pretrained(args.save) print(f"wrote {os.path.join(args.save, 'config.json')} and {os.path.join(args.save, 'model.safetensors')}")
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:0252caa3fb50a7431dbd798dd0b088d531cc7a900d8cfa5890d7cfb05e7692e5size 4782219624123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536# Copyright the ShellElastic authors."""Reference PyTorch implementation of the ShellElastic supernet.
This file implements the model of "ShellElastic: Scalable Elastic Pretraining with Simultaneous Maximal Updates andHyperparameter Transfer" (Jin et al.). It depends only on ``torch``; ``safetensors`` is needed to load releasedweights.
Notation follows Section 3.1 of the paper.
* Width. With base width ``g`` and supported set ``S = {s_1 < ... < s_K = M}`` (stored in ``config.widths``, in units of ``g``), the residual stream has ``M * g`` features split into contiguous groups ``G_k = [s_{k-1} g, s_k g)``. ``G_1`` is the dense core, ``G_2 .. G_K`` are the shells. The sub-network of tier ``k`` (Low, Medium, High, Extra, Max) is the core plus the first ``k - 1`` shells, i.e. the first ``s_k g`` features.* Structured projections (Eq. 2). Every hidden matrix is block lower triangular: the block row ``W_k`` that produces group ``G_k`` reads only the first ``s_k g`` input features and has shape ``[|G_k|, s_k g]``. Each matrix is stored by block row: ``<proj>.core.weight`` is ``W_1`` (the rows of the core ``G_1``), and ``<proj>.shell.<j>.weight`` is ``W_{j+1}`` (the rows of the shell ``G_{j+1}``, ``j = 1 .. K-1``), of shape ``[|G_{j+1}|, s_{j+1} g]``. The zero blocks above the diagonal are never stored.* Group-local normalization (Eq. 3). The two pre-norms of every layer are RMSNorms whose statistics are computed separately over the core and over each shell (one gain per feature).* Attention (Eq. 4). Tier ``k`` uses the first ``s_k g / d_head`` heads; heads never straddle a group. Queries and keys get a per-head RMSNorm and rotary position embeddings, and the attention output is multiplied elementwise by ``sigmoid(x W_G^T)`` before the output projection.* FFN (Eq. 5). SwiGLU with hidden width ``e`` times the model width; ``gate_proj`` / ``up_proj`` have block boundaries ``s_k g`` on the input axis and ``e s_k g`` on the output axis, ``down_proj`` the reverse.* Readout (Eq. 6). Every tier has its own terminal RMSNorm over all of its ``s_k g`` features (``norm.<tier>``) and its own readout ``U_s`` (``lm_head.<tier>``). In the released weights the learned logit scale ``alpha_s`` is already multiplied into ``lm_head.<tier>.weight`` and the FFN multiplier ``1/e`` into ``down_proj``, so inference needs no extra scalars.
Because no operation lets the features of a tier depend on the groups outside it, one forward pass at width``M g`` contains the exact hidden states of every smaller tier in its leading features (Proposition 1).``forward(..., tiers=[...])`` uses this to return several tiers' logits from one trunk pass, and ``extract(tier)``returns a standalone smaller model with identical outputs.
Numerics. This file computes the RMSNorm statistics in float32 and casts the result back to the activation dtypebefore the gain is applied. ``config.rope_precision`` selects the rotary tables: ``"bfloat16"`` (the default)rounds the positions, the frequencies, their product and the cosine and sine to bfloat16; ``"float32"`` computesthem in float32. The released weights are float32; run the model in float32, or cast it to bfloat16 with``from_pretrained(..., dtype=torch.bfloat16)``.
Example::
model = ShellElasticForCausalLM.from_pretrained("path/to/checkpoint", device="cuda") logits = model(input_ids, tier="medium") # [batch, seq, vocab] all_logits = model(input_ids, tiers=model.config.tiers) # dict: tier -> logits logits, loss = model(input_ids[:, :-1], tier="low", labels=input_ids[:, 1:]) low = model.extract("low") # standalone Low sub-network"""
from __future__ import annotations
import jsonimport osfrom dataclasses import asdict, dataclass, fieldfrom typing import Dict, List, Optional, Sequence, Union
import torchimport torch.nn as nnimport torch.nn.functional as F
DEFAULT_TIERS = ["low", "medium", "high", "extra", "max"]
# --------------------------------------------------------------------------------------# Configuration# --------------------------------------------------------------------------------------
@dataclassclass ShellElasticConfig: """Hyperparameters of a ShellElastic supernet (or of a sub-network extracted from it).
Attributes: vocab_size: Size of the vocabulary. num_hidden_layers: Number of transformer layers ``L``. base_width: Base width ``g``; every group is a multiple of it. widths: Supported set ``S`` in units of ``g``, strictly increasing. The last entry is ``M`` (the full width is ``M * g``). Group ``G_1`` (the core) has ``widths[0] * g`` features, every later group ``(widths[k] - widths[k-1]) * g``. tiers: One name per supported width (Low, Medium, High, Extra, Max). readout_tiers: Tiers that have their own terminal norm and readout in this checkpoint (default: all tiers; a sub-network returned by ``extract`` keeps only its own). head_dim: Attention head dimension ``d_head`` (must divide ``base_width``). mlp_base_width: FFN hidden features per base width, i.e. ``e * g`` with FFN expansion ``e``. rope_theta: Base of the rotary position embedding. rope_precision: Rotary tables, ``"bfloat16"`` (default: position, frequency and their product rounded to bfloat16, and the cosine and sine rounded to bfloat16, in any compute precision) or ``"float32"`` (computed in float32). rms_norm_eps: Epsilon of every RMSNorm. max_position_embeddings: Context length (the sequence length of 2,048 tokens). tie_word_embeddings: Always false (the embedding and the readouts are separate). tokenizer: Tokenizer the token ids refer to. """
vocab_size: int = 50432 num_hidden_layers: int = 32 base_width: int = 128 widths: List[int] = field(default_factory=lambda: [4, 5, 6, 7, 8]) tiers: List[str] = field(default_factory=lambda: list(DEFAULT_TIERS)) readout_tiers: Optional[List[str]] = None head_dim: int = 128 mlp_base_width: int = 128 rope_theta: float = 10000.0 rope_precision: str = "bfloat16" rms_norm_eps: float = 1e-5 max_position_embeddings: int = 2048 tie_word_embeddings: bool = False tokenizer: str = "EleutherAI/gpt-neox-20b" architectures: List[str] = field(default_factory=lambda: ["ShellElasticForCausalLM"]) model_type: str = "shellelastic"
def __post_init__(self) -> None: self.widths = [int(w) for w in self.widths] self.tiers = [str(t) for t in self.tiers] if self.readout_tiers is None: self.readout_tiers = list(self.tiers) if any(b <= a for a, b in zip([0] + self.widths, self.widths)): raise ValueError(f"widths must be positive and strictly increasing, got {self.widths}") if len(self.tiers) != len(self.widths): raise ValueError("tiers and widths must have the same length") if not self.readout_tiers or any(t not in self.tiers for t in self.readout_tiers): raise ValueError(f"readout_tiers {self.readout_tiers} must be a non-empty subset of tiers {self.tiers}") self.readout_tiers = sorted(set(self.readout_tiers), key=self.tiers.index) if self.base_width % self.head_dim != 0: raise ValueError("head_dim must divide base_width so that heads never straddle a group") if self.rope_precision not in ("bfloat16", "float32"): raise ValueError("rope_precision must be 'bfloat16' or 'float32'") if self.tie_word_embeddings: raise ValueError("ShellElastic models do not tie the embedding and the readouts")
# ---- derived quantities --------------------------------------------------------------
@property def hidden_size(self) -> int: """Full model width ``M * g``.""" return self.widths[-1] * self.base_width
@property def boundaries(self) -> List[int]: """Right edges of the residual groups, ``[s_1 g, ..., s_K g]``.""" return [s * self.base_width for s in self.widths]
@property def mlp_boundaries(self) -> List[int]: """Right edges of the FFN hidden groups, ``[e s_1 g, ..., e s_K g]``.""" return [s * self.mlp_base_width for s in self.widths]
@property def group_sizes(self) -> List[int]: """Sizes of the core and of every shell.""" b = self.boundaries return [b[0]] + [hi - lo for lo, hi in zip(b, b[1:])]
def num_groups(self, tier: str) -> int: """Number of groups (core + shells) used by ``tier``.""" return self.tiers.index(tier) + 1
def width(self, tier: str) -> int: """Model width of ``tier``.""" return self.boundaries[self.tiers.index(tier)]
def for_tier(self, tier: str) -> "ShellElasticConfig": """Configuration of the standalone sub-network ``tier`` (see ``extract``).""" k = self.num_groups(tier) values = asdict(self) values.update(widths=self.widths[:k], tiers=self.tiers[:k], readout_tiers=[tier]) return ShellElasticConfig(**values)
# ---- (de)serialization ---------------------------------------------------------------
def to_dict(self) -> dict: return asdict(self)
@classmethod def from_dict(cls, values: dict) -> "ShellElasticConfig": known = {f for f in cls.__dataclass_fields__} return cls(**{k: v for k, v in values.items() if k in known})
@classmethod def from_json_file(cls, path: str) -> "ShellElasticConfig": with open(path, "r", encoding="utf-8") as f: return cls.from_dict(json.load(f))
# --------------------------------------------------------------------------------------# Building blocks# --------------------------------------------------------------------------------------
def rms_norm(x: torch.Tensor, weight: torch.Tensor, eps: float, group_sizes: Optional[Sequence[int]] = None) -> torch.Tensor: """RMSNorm over the last dimension, with separate statistics per feature group (Eq. 3).
The statistics are computed in float32 and the result is cast back to the input dtype before the gain is applied. ``group_sizes=None`` normalizes over the whole last dimension. """ xf = x.float() chunks = xf.split(list(group_sizes), dim=-1) if group_sizes is not None else (xf,) normed = [c * torch.rsqrt(c.pow(2).mean(dim=-1, keepdim=True) + eps) for c in chunks] return torch.cat(normed, dim=-1).to(x.dtype) * weight
class RMSNorm(nn.Module): """RMSNorm with one gain per feature. ``group_sizes`` selects group-local statistics.
The gain has the full width of the module; a narrower input uses its leading entries. """
def __init__(self, width: int, eps: float) -> None: super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(width))
def forward(self, x: torch.Tensor, group_sizes: Optional[Sequence[int]] = None) -> torch.Tensor: return rms_norm(x, self.weight[: x.shape[-1]], self.eps, group_sizes)
class ShellLinear(nn.Module): """Block-lower-triangular linear map, stored as one weight per output group (block row).
``core.weight`` (the block row of the core ``G_1``) has shape ``[out_bounds[0], in_bounds[0]]``; ``shell[str(j)].weight`` (the block row of the shell ``G_{j+1}``, ``j = 1 .. K-1``) has shape ``[out_bounds[j] - out_bounds[j-1], in_bounds[j]]``: its rows read only the first ``in_bounds[j]`` input features. There is no bias. """
def __init__(self, in_bounds: Sequence[int], out_bounds: Sequence[int]) -> None: super().__init__() self.in_bounds = list(in_bounds) self.out_bounds = list(out_bounds) self.core = nn.Linear(self.in_bounds[0], self.out_bounds[0], bias=False) self.shell = nn.ModuleDict({ str(k): nn.Linear(self.in_bounds[k], self.out_bounds[k] - self.out_bounds[k - 1], bias=False) for k in range(1, len(self.out_bounds)) })
def block_rows(self, num_groups: int) -> List[torch.Tensor]: """Weights of the first ``num_groups`` block rows (core first).""" return [self.core.weight] + [self.shell[str(k)].weight for k in range(1, num_groups)]
def forward(self, x: torch.Tensor, num_groups: int) -> torch.Tensor: # y_{G_k} = x[:, :s_k g] W_k^T (Eq. 2), concatenated over the active groups. return torch.cat([F.linear(x[..., : w.shape[1]], w) for w in self.block_rows(num_groups)], dim=-1)
def dense_weight(self, num_groups: int) -> torch.Tensor: """The equivalent dense ``[out, in]`` matrix of the first ``num_groups`` groups, with the blocks above the diagonal filled with zeros.""" n_in = self.in_bounds[num_groups - 1] return torch.cat([F.pad(w, (0, n_in - w.shape[1])) for w in self.block_rows(num_groups)], dim=0)
def rotary_cos_sin(length: int, head_dim: int, theta: float, precision: str, device: torch.device, dtype: torch.dtype): """Cosine and sine tables of shape ``[length, head_dim]`` for rotate-half RoPE.""" frequency = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim)) # computed on the CPU position = torch.arange(length, dtype=torch.float32) frequency, position = frequency.to(device), position.to(device) if precision == "bfloat16": # Position, frequency, angle (their product, which is exact in float32 before rounding) and the cosine / # sine are each rounded to bfloat16. angles = torch.outer(position.bfloat16().float(), frequency.bfloat16().float()).bfloat16().float() angles = torch.cat([angles, angles], dim=-1) return angles.cos().bfloat16().to(dtype), angles.sin().bfloat16().to(dtype) angles = torch.outer(position, frequency) angles = torch.cat([angles, angles], dim=-1) return angles.cos().to(dtype), angles.sin().to(dtype)
def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: """Rotate-half RoPE for ``x`` of shape ``[batch, seq, heads, head_dim]``.""" x1, x2 = x.chunk(2, dim=-1) rotated = torch.cat([-x2, x1], dim=-1) return x * cos[None, :, None, :] + rotated * sin[None, :, None, :]
class ShellAttention(nn.Module): """Causal self-attention with nested heads, QK-norm, RoPE and an elementwise sigmoid gate."""
def __init__(self, config: ShellElasticConfig) -> None: super().__init__() b, width = config.boundaries, config.hidden_size self.head_dim = config.head_dim self.q_proj = ShellLinear(b, b) self.k_proj = ShellLinear(b, b) self.v_proj = ShellLinear(b, b) self.gate_proj = ShellLinear(b, b) self.o_proj = ShellLinear(b, b) # Per-head RMSNorm of queries and keys, with one gain per feature (head-major order). self.q_norm = RMSNorm(width, config.rms_norm_eps) self.k_norm = RMSNorm(width, config.rms_norm_eps)
def _per_head_norm(self, norm: RMSNorm, x: torch.Tensor) -> torch.Tensor: heads = x.shape[-2] gain = norm.weight[: heads * self.head_dim].view(heads, self.head_dim) return rms_norm(x, gain, norm.eps)
def forward(self, x: torch.Tensor, num_groups: int, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: batch, seq, width = x.shape heads = width // self.head_dim shape = (batch, seq, heads, self.head_dim) q = self.q_proj(x, num_groups).view(shape) k = self.k_proj(x, num_groups).view(shape) v = self.v_proj(x, num_groups).view(shape) q = apply_rotary(self._per_head_norm(self.q_norm, q), cos, sin) k = apply_rotary(self._per_head_norm(self.k_norm, k), cos, sin) out = F.scaled_dot_product_attention( q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, scale=self.head_dim ** -0.5, ).transpose(1, 2) out = out * torch.sigmoid(self.gate_proj(x, num_groups).view(shape)) return self.o_proj(out.reshape(batch, seq, width), num_groups)
class ShellMLP(nn.Module): """SwiGLU feed-forward network with block-lower-triangular projections."""
def __init__(self, config: ShellElasticConfig) -> None: super().__init__() b, h = config.boundaries, config.mlp_boundaries self.gate_proj = ShellLinear(b, h) self.up_proj = ShellLinear(b, h) self.down_proj = ShellLinear(h, b) # the released weights already include the 1/e multiplier
def forward(self, x: torch.Tensor, num_groups: int) -> torch.Tensor: hidden = F.silu(self.gate_proj(x, num_groups)) * self.up_proj(x, num_groups) return self.down_proj(hidden, num_groups)
class ShellElasticLayer(nn.Module): """Pre-norm transformer layer with group-local branch normalization."""
def __init__(self, config: ShellElasticConfig) -> None: super().__init__() self.group_sizes = config.group_sizes self.attn_norm = RMSNorm(config.hidden_size, config.rms_norm_eps) self.attn = ShellAttention(config) self.mlp_norm = RMSNorm(config.hidden_size, config.rms_norm_eps) self.mlp = ShellMLP(config)
def forward(self, x: torch.Tensor, num_groups: int, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: groups = self.group_sizes[:num_groups] x = x + self.attn(self.attn_norm(x, groups), num_groups, cos, sin) x = x + self.mlp(self.mlp_norm(x, groups), num_groups) return x
# --------------------------------------------------------------------------------------# Model# --------------------------------------------------------------------------------------
class ShellElasticForCausalLM(nn.Module): """ShellElastic supernet: a shared trunk plus one terminal norm and readout per tier."""
def __init__(self, config: ShellElasticConfig) -> None: super().__init__() self.config = config self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) self.layers = nn.ModuleList([ShellElasticLayer(config) for _ in range(config.num_hidden_layers)]) self.norm = nn.ModuleDict({t: RMSNorm(config.width(t), config.rms_norm_eps) for t in config.readout_tiers}) self.lm_head = nn.ModuleDict({ t: nn.Linear(config.width(t), config.vocab_size, bias=False) for t in config.readout_tiers })
# ---- loading -------------------------------------------------------------------------
@classmethod def from_pretrained(cls, path: str, device: Union[str, torch.device] = "cpu", dtype: Optional[torch.dtype] = None) -> "ShellElasticForCausalLM": """Load ``config.json`` and ``model.safetensors`` from the directory ``path``; ``dtype`` optionally casts the (float32) weights, e.g. to ``torch.bfloat16``. The weights are read and cast on the CPU and then moved to ``device``, so the device holds only one copy of the model, in ``dtype``.""" from safetensors.torch import load_file
config = ShellElasticConfig.from_json_file(os.path.join(path, "config.json")) with torch.device("meta"): model = cls(config) state = load_file(os.path.join(path, "model.safetensors"), device="cpu") if dtype is not None: for name in list(state): # cast on the CPU, one tensor at a time if state[name].is_floating_point(): state[name] = state[name].to(dtype) model.load_state_dict(state, strict=True, assign=True) return model.to(device).eval()
def save_pretrained(self, path: str) -> None: """Write ``config.json`` and ``model.safetensors`` to the directory ``path`` (for example, a sub-network returned by ``extract``); ``from_pretrained`` reads them back.""" from safetensors.torch import save_file
os.makedirs(path, exist_ok=True) values = self.config.to_dict() values["torch_dtype"] = str(self.embed_tokens.weight.dtype).replace("torch.", "") with open(os.path.join(path, "config.json"), "w", encoding="utf-8") as f: json.dump(values, f, indent=2) f.write("\n") state = {name: t.detach().contiguous() for name, t in self.state_dict().items()} save_file(state, os.path.join(path, "model.safetensors"), metadata={"format": "pt"})
# ---- forward -------------------------------------------------------------------------
def hidden_states(self, input_ids: torch.Tensor, tier: Optional[str] = None) -> torch.Tensor: """Trunk output (before the terminal norm) of width ``config.width(tier)``.
Its first ``config.width(t)`` features are the hidden states of every smaller tier ``t``. """ tier = tier or self.config.tiers[-1] num_groups = self.config.num_groups(tier) width = self.config.width(tier) seq = input_ids.shape[1] if seq > self.config.max_position_embeddings: raise ValueError(f"{seq} tokens exceed the context of {self.config.max_position_embeddings}") x = self.embed_tokens(input_ids)[..., :width] cos, sin = rotary_cos_sin(seq, self.config.head_dim, self.config.rope_theta, self.config.rope_precision, x.device, x.dtype) for layer in self.layers: x = layer(x, num_groups, cos, sin) return x
def logits(self, hidden: torch.Tensor, tier: str) -> torch.Tensor: """Terminal norm and readout of ``tier`` (Eq. 6) applied to a trunk output of width >= its own.""" if tier not in self.lm_head: raise KeyError(f"tier {tier!r} has no readout in this model (available: {self.config.readout_tiers})") h = hidden[..., : self.config.width(tier)] return self.lm_head[tier](self.norm[tier](h))
def forward(self, input_ids: torch.Tensor, tier: Optional[str] = None, tiers: Optional[Sequence[str]] = None, labels: Optional[torch.Tensor] = None): """Next-token logits (in the model's dtype).
Args: input_ids: ``[batch, seq]`` token ids (no padding; causal attention over the sequence). tier: Tier to evaluate (default: the widest tier with a readout). tiers: If given, evaluate all of these tiers with one trunk pass at the widest of them and return a ``{tier: logits}`` dict. labels: Optional ``[batch, seq]`` targets (-100 is ignored). The mean cross-entropy (computed in float32) is returned as well: ``(logits, loss)``, or ``({tier: logits}, {tier: loss})`` with ``tiers``. """ if tiers is None: tier = tier or self.config.readout_tiers[-1] logits = self.logits(self.hidden_states(input_ids, tier), tier) return logits if labels is None else (logits, self.loss(logits, labels)) widest = max(tiers, key=self.config.tiers.index) hidden = self.hidden_states(input_ids, widest) out = {t: self.logits(hidden, t) for t in tiers} return out if labels is None else (out, {t: self.loss(v, labels) for t, v in out.items()})
@staticmethod def loss(logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: """Mean next-token cross-entropy in float32 (label -100 is ignored).""" return F.cross_entropy(logits.float().flatten(0, 1), labels.flatten(), ignore_index=-100)
@torch.no_grad() def generate(self, input_ids: torch.Tensor, max_new_tokens: int, tier: Optional[str] = None, temperature: float = 0.0, top_k: Optional[int] = None) -> torch.Tensor: """Simple sampling loop without a key/value cache (greedy when ``temperature == 0``).""" for _ in range(max_new_tokens): context = input_ids[:, -self.config.max_position_embeddings:] logits = self(context, tier=tier)[:, -1].float() if temperature <= 0: next_ids = logits.argmax(dim=-1, keepdim=True) else: logits = logits / temperature if top_k is not None: kth = torch.topk(logits, top_k, dim=-1).values[:, -1:] logits = logits.masked_fill(logits < kth, float("-inf")) next_ids = torch.multinomial(torch.softmax(logits, dim=-1), num_samples=1) input_ids = torch.cat([input_ids, next_ids], dim=1) return input_ids
# ---- sub-networks --------------------------------------------------------------------
def subnetwork_state_dict(self, tier: str) -> Dict[str, torch.Tensor]: """Weights of the standalone sub-network ``tier``: the embedding columns, the core and the shells it contains, the leading entries of every norm gain, and its own terminal norm and readout. Loads into ``ShellElasticForCausalLM(config.for_tier(tier))``.""" if tier not in self.lm_head: raise KeyError(f"tier {tier!r} has no readout in this model (available: {self.config.readout_tiers})") k, width = self.config.num_groups(tier), self.config.width(tier) out = {} for name, tensor in self.state_dict().items(): if name.startswith(("norm.", "lm_head.")): if name.split(".")[1] == tier: out[name] = tensor elif name == "embed_tokens.weight": out[name] = tensor[:, :width] elif ".shell." in name: if int(name.split(".shell.")[1].split(".")[0]) < k: out[name] = tensor elif name.endswith("norm.weight"): # branch norms and query/key norms out[name] = tensor[:width] else: # core block rows out[name] = tensor return out
def extract(self, tier: str) -> "ShellElasticForCausalLM": """A standalone copy of the sub-network ``tier``; its logits equal ``self(x, tier=tier)``.""" with torch.device("meta"): model = ShellElasticForCausalLM(self.config.for_tier(tier)) state = {n: t.clone() for n, t in self.subnetwork_state_dict(tier).items()} model.load_state_dict(state, strict=True, assign=True) return model.train(self.training)
def dense_state_dict(self, tier: str) -> Dict[str, torch.Tensor]: """Returns the weights of the sub-network ``tier`` as a state dict (nothing is written to disk), with every structured projection as one dense matrix (``...<proj>.weight``, zeros above the block diagonal). The group-local norms are still required to run it; this format is provided for inspection and porting.""" k = self.config.num_groups(tier) out = {} for name, tensor in self.subnetwork_state_dict(tier).items(): if ".core." in name or ".shell." in name: continue out[name] = tensor for name, module in self.named_modules(): if isinstance(module, ShellLinear): out[f"{name}.weight"] = module.dense_weight(k) return out
def num_parameters(self, tier: Optional[str] = None) -> int: """Parameters stored for the whole model, or used by ``tier`` (non-zero weights it reads, its embedding columns, and its own terminal norm and readout).""" tensors = self.state_dict() if tier is None else self.subnetwork_state_dict(tier) return sum(t.numel() for t in tensors.values())
__all__ = [ "ShellElasticConfig", "ShellElasticForCausalLM", "ShellLinear", "RMSNorm", "rms_norm", "rotary_cos_sin",]12345# PyTorch and safetensors. The [torch] extra of safetensors also installs numpy, which safetensors needs to write# files (save_pretrained, save_subnetwork); loading and running the models need only torch and safetensors.# Tested with torch 2.9.1 and safetensors 0.7.0.torch>=2.1safetensors[torch]>=0.4LICENSEAdded+202
README.mdAdded+168
config.jsonAdded+39
example.pyAdded+73
model.safetensorsAdded+3
modeling_shellelastic.pyAdded+536
requirements.txtAdded+5