Text Generation
Transformers
Safetensors
English
wildai
nanochat
scaling-laws
ai-generated-text
pretraining-data
Instructions to use pangram/WildAI-models with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use pangram/WildAI-models with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="pangram/WildAI-models")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("pangram/WildAI-models", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use pangram/WildAI-models with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "pangram/WildAI-models" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "pangram/WildAI-models", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/pangram/WildAI-models
- SGLang
How to use pangram/WildAI-models with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "pangram/WildAI-models" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "pangram/WildAI-models", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "pangram/WildAI-models" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "pangram/WildAI-models", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use pangram/WildAI-models with Docker Model Runner:
docker model run hf.co/pangram/WildAI-models
Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- 268m-g073-ai-r0.05/config.jsonAdded+46
- 268m-g073-ai-r0.05/tokenizer_config.jsonAdded+11
- 268m-g073-human-r0.025/model.safetensorsAdded+3
- 268m-g074-control/LICENSEAdded+438
- 268m-g074-control/README.mdAdded+105
- 268m-g074-control/config.jsonAdded+46
- 268m-g074-control/configuration_wildai.pyAdded+96
- 268m-g074-control/generation_config.jsonAdded+10
- 268m-g074-control/modeling_wildai.pyAdded+340
- 268m-g074-control/tokenizer.jsonAdded
- 268m-g074-control/tokenizer_config.jsonAdded+11
- 268m-g074-human-r0.025/model.safetensorsAdded+3
- 268m-g074-human-r0.05/model.safetensorsAdded+3
- 268m-g075-ai-r0.1/model.safetensorsAdded+3
- 268m-g076-ai-r0.5/model.safetensorsAdded+3
- 268m-g076-control/model.safetensorsAdded+3
- 268m-g077-ai-r0.25/LICENSEAdded+438
- 268m-g077-ai-r0.25/README.mdAdded+105
- 268m-g077-ai-r0.25/config.jsonAdded+46
- 268m-g077-ai-r0.25/configuration_wildai.pyAdded+96
- 268m-g077-ai-r0.25/generation_config.jsonAdded+10
- 268m-g077-ai-r0.25/modeling_wildai.pyAdded+340
- 268m-g077-ai-r0.25/tokenizer.jsonAdded
- 268m-g077-ai-r0.25/tokenizer_config.jsonAdded+11
- 268m-g078-human-r0.025/model.safetensorsAdded+3
- 268m-g079-ai-r0.05/model.safetensorsAdded+3
- 268m-g079-control/configuration_wildai.pyAdded+96
- 268m-g079-control/modeling_wildai.pyAdded+340
- 268m-g079-human-r0.025/LICENSEAdded+438
- 268m-g079-human-r0.025/README.mdAdded+105
- 268m-g079-human-r0.025/config.jsonAdded+46
- 268m-g079-human-r0.025/configuration_wildai.pyAdded+96
- 268m-g079-human-r0.025/generation_config.jsonAdded+10
- 268m-g079-human-r0.025/modeling_wildai.pyAdded+340
- 268m-g079-human-r0.025/tokenizer.jsonAdded
- 268m-g079-human-r0.025/tokenizer_config.jsonAdded+11
- 268m-g079-human-r0.05/model.safetensorsAdded+3
- 268m-g081-ai-r0.025/LICENSEAdded+438
- 268m-g081-ai-r0.025/README.mdAdded+105
- 268m-g081-ai-r0.025/config.jsonAdded+46
- 268m-g081-ai-r0.025/configuration_wildai.pyAdded+96
- 268m-g081-ai-r0.025/generation_config.jsonAdded+10
- 268m-g081-ai-r0.025/modeling_wildai.pyAdded+340
- 268m-g081-ai-r0.025/tokenizer_config.jsonAdded+11
- 268m-g081-ai-r0.25/LICENSEAdded+438
- 268m-g081-ai-r0.25/README.mdAdded+105
- 268m-g081-ai-r0.25/config.jsonAdded+46
- 268m-g081-ai-r0.25/configuration_wildai.pyAdded+96
- 268m-g081-ai-r0.25/generation_config.jsonAdded+10
- 268m-g081-ai-r0.25/modeling_wildai.pyAdded+340
12345678910111213141516171819202122232425262728293031323334353637383940414243444546{ "architectures": [ "WildAIForCausalLM" ], "auto_map": { "AutoConfig": "configuration_wildai.WildAIConfig", "AutoModelForCausalLM": "modeling_wildai.WildAIForCausalLM" }, "bos_token_id": 32759, "dtype": "bfloat16", "eos_token_id": 32759, "hidden_size": 1024, "logit_softcap": 15.0, "max_position_embeddings": 2048, "model_type": "wildai", "num_attention_heads": 8, "num_hidden_layers": 16, "num_key_value_heads": 8, "pad_token_id": 32759, "qk_scale": 1.2, "release": { "added_ratio": 0.05, "ai_ratio": 0.05057465216816127, "ai_tokens": 59362642, "arm": "ai", "depth": 16, "group": "g073", "human_tokens": 1173762734, "n_params": 268436282, "name": "268m-g073-ai-r0.05", "seed": 271828, "size": "268m", "split": "fit", "steps": 2352, "total_tokens": 1233125376 }, "rotary_base": 100000.0, "smear_channels": 24, "tie_word_embeddings": false, "transformers_version": "5.17.0", "use_cache": true, "value_embed_gate_channels": 12, "value_embed_gate_range": 3.0, "vocab_size": 32768, "window_pattern": "SSSL"}1234567891011{ "tokenizer_class": "PreTrainedTokenizerFast", "bos_token": "<|bos|>", "eos_token": "<|bos|>", "model_max_length": 2048, "model_input_names": [ "input_ids", "attention_mask" ], "clean_up_tokenization_spaces": false}123version https://git-lfs.github.com/spec/v1oid sha256:e9c4ba5c4ac8a0463f04ce9ef5a37fd00461c74bb40c4e48acb1238a9cf80b71size 1073757052123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438Attribution-NonCommercial-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm anddoes not provide legal services or legal advice. Distribution ofCreative Commons public licenses does not create a lawyer-client orother relationship. Creative Commons makes its licenses and relatedinformation available on an "as-is" basis. Creative Commons gives nowarranties regarding its licenses, any material licensed under theirterms and conditions, or any related information. Creative Commonsdisclaims all liability for damages resulting from their use to thefullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms andconditions that creators and other rights holders may use to shareoriginal works of authorship and other material subject to copyrightand certain other rights specified in the public license below. Thefollowing considerations are for informational purposes only, are notexhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public: wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 InternationalPublic License
By exercising the Licensed Rights (defined below), You accept and agreeto be bound by the terms and conditions of this Creative CommonsAttribution-NonCommercial-ShareAlike 4.0 International Public License("Public License"). To the extent this Public License may beinterpreted as a contract, You are granted the Licensed Rights inconsideration of Your acceptance of these terms and conditions, and theLicensor grants You such rights in consideration of benefits theLicensor receives from making the Licensed Material available underthese terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
k. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
l. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
m. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
b. Additional offer from the Licensor -- Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to thefollowing conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
a. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights thatapply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does notreplace Your obligations under this Public License where the LicensedRights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its publiclicenses. Notwithstanding, Creative Commons may elect to apply one ofits public licenses to material it publishes and in those instanceswill be considered the “Licensor.” The text of the Creative Commonspublic licenses is dedicated to the public domain under the CC0 PublicDomain Dedication. Except for the limited purpose of indicating thatmaterial is shared under a Creative Commons public license or asotherwise permitted by the Creative Commons policies published atcreativecommons.org/policies, Creative Commons does not authorize theuse of the trademark "Creative Commons" or any other trademark or logoof Creative Commons without its prior written consent including,without limitation, in connection with any unauthorized modificationsto any of its public licenses or any other arrangements,understandings, or agreements concerning use of licensed material. Forthe avoidance of doubt, this paragraph does not form part of thepublic licenses.
Creative Commons may be contacted at creativecommons.org.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105---license: cc-by-nc-sa-4.0library_name: transformerspipeline_tag: text-generationlanguage:- endatasets:- pangram/WildAItags:- wildai- nanochat- scaling-laws- ai-generated-text- pretraining-data---
# 268m-g074-control
> **License: [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/).** The WildAI code, models and dataset are released under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license: you may use and adapt them for non-commercial purposes, with attribution, and must share adaptations under the same license.
A 268M decoder-only language model trained from scratch for [*How Much Is an AI Token Worth? Scaling Laws for Wild AI-Generated Web Text*](https://arxiv.org/abs/2609.40295), one of the paper's models measuring how wild AI-generated web text in pretraining data changes a model's loss. It is a research artifact for studying scaling laws, not an assistant: it has had no instruction tuning or safety training.
## Training data
The human-only control of group g074: 1.17B tokens of human-written web documents. The other models of the group add AI or fresh human text to exactly these documents, so their loss minus this model's isolates the effect of the addition.
| | ||---|---|| Parameters (N, input embedding included, value embeddings excluded) | 268.4M || Layers / width | 16 / 1024 || Training tokens | 1.17B (2,240 optimizer steps) || Human / AI tokens | 1.17B / 0.0M || Group / arm / seed | g074 / control / 314159 || Used in the paper for | fitting the scaling laws (726 models, 19.9M to 268M) |
## Held-out loss
| Set | Bits per byte | Text ||---|---|---|| C4 | 0.9968 | C4 validation text (human-written, pre-2022) || FW22 | 0.9812 | held-out FineWeb documents crawled before 2022 || Paloma | 1.3736 | macro average over 16 Paloma sources || FW26 | 0.8698 | held-out 2026 FineWeb-style crawl (22.3% AI tokens) || FW26-H | 0.9140 | the human-labeled documents of FW26 || FW26-AI | 0.7071 | the AI-labeled documents of FW26 || Cosmo | 0.7093 | Cosmopedia (AI-generated textbooks and stories) |
<details><summary>Paloma sources</summary>
| Source | Bits per byte ||---|---|| 4chan | 1.4427 || c4 | 1.0157 || c4_100_domains | 0.9980 || dolma | 1.2662 || falcon_refinedweb | 1.1113 || gab | 1.8966 || m2d2_s2orc | 1.1811 || m2d2_wikipedia | 1.0882 || manosphere | 1.4005 || mc4_en | 1.1042 || programming | 1.9760 || ptb | 1.2302 || reddit_100 | 1.2525 || redpajama | 1.4346 || twitteraae | 2.4947 || wikitext_103 | 1.0845 |
</details>
## Usage
```pythonimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("pangram/WildAI-models", subfolder="268m-g074-control", trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained("pangram/WildAI-models", subfolder="268m-g074-control", trust_remote_code=True, dtype=torch.bfloat16)
inputs = tokenizer("The history of the printing press", return_tensors="pt")output = model.generate(**inputs, max_new_tokens=40, do_sample=False)print(tokenizer.decode(output[0], skip_special_tokens=True))```
The tokenizer prepends `<|bos|>` to every text, as in training; pass `add_special_tokens=False` to skip it. The model predicts `<|bos|>` where a document ends, and generation stops there. Weights are stored in bfloat16, the precision the paper's losses were computed in; `dtype=torch.float32` computes in float32 instead.
## Architecture
The nanochat GPT recipe: rotary embeddings, RMSNorm without weights (also on queries and keys), squared-ReLU MLP, attention windows in a repeating short-short-short-long pattern (512 tokens, then the full 2,048-token context; the last layer always full), gated value embeddings on alternating layers, a previous-token smear, per-layer residual scalars, a mid-network backout, untied input and output embeddings and logits soft-capped at 15. Vocabulary 32,768 tokens, context 2,048. The code ships with the weights (`trust_remote_code=True`) and matches the training code's forward pass.
## License
**License: [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/).** The WildAI code, models and dataset are released under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license: you may use and adapt them for non-commercial purposes, with attribution, and must share adaptations under the same license. The full text is in `LICENSE`.
## Citation
```bibtex@article{russell2026wildai, title = {How Much Is an AI Token Worth? Scaling Laws for Wild AI-Generated Web Text}, author = {Russell, Jenna and Glickenhaus, Ben and Thai, Katherine and Wieting, John and Iyyer, Mohit and Spero, Max and Emi, Bradley}, journal = {arXiv preprint arXiv:2609.40295}, year = {2026}, url = {https://arxiv.org/abs/2609.40295}}```12345678910111213141516171819202122232425262728293031323334353637383940414243444546{ "architectures": [ "WildAIForCausalLM" ], "auto_map": { "AutoConfig": "configuration_wildai.WildAIConfig", "AutoModelForCausalLM": "modeling_wildai.WildAIForCausalLM" }, "bos_token_id": 32759, "dtype": "bfloat16", "eos_token_id": 32759, "hidden_size": 1024, "logit_softcap": 15.0, "max_position_embeddings": 2048, "model_type": "wildai", "num_attention_heads": 8, "num_hidden_layers": 16, "num_key_value_heads": 8, "pad_token_id": 32759, "qk_scale": 1.2, "release": { "added_ratio": 0.0, "ai_ratio": 0.0, "ai_tokens": 0, "arm": "control", "depth": 16, "group": "g074", "human_tokens": 1174405120, "n_params": 268436282, "name": "268m-g074-control", "seed": 314159, "size": "268m", "split": "fit", "steps": 2240, "total_tokens": 1174405120 }, "rotary_base": 100000.0, "smear_channels": 24, "tie_word_embeddings": false, "transformers_version": "5.17.0", "use_cache": true, "value_embed_gate_channels": 12, "value_embed_gate_range": 3.0, "vocab_size": 32768, "window_pattern": "SSSL"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Configuration of the WildAI language models (a nanochat GPT variant) for Hugging Face ``transformers``.
This file is copied verbatim into every released model repository and loaded with ``trust_remote_code=True``.It depends only on ``transformers``."""
from __future__ import annotations
from typing import ClassVar
from transformers import PretrainedConfig
class WildAIConfig(PretrainedConfig): """Architecture of a WildAI model. Only width and depth vary across the released models.
Every layer uses causal attention limited to a left window: a query attends to itself and the ``window`` tokens before it. ``window_pattern`` is tiled over the layers ("S" = a quarter of the context rounded up to a multiple of 128 tokens, "L" = the full context) and the last layer always uses "L".
``release`` holds the model's entry in the release catalog (name, token counts, AI ratio, ...); it does not affect the forward pass. """
model_type = "wildai" keys_to_ignore_at_inference: ClassVar[list[str]] = ["past_key_values"]
def __init__( self, vocab_size: int = 32768, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 6, num_key_value_heads: int = 6, max_position_embeddings: int = 2048, window_pattern: str = "SSSL", rotary_base: float = 100000.0, qk_scale: float = 1.2, logit_softcap: float = 15.0, value_embed_gate_channels: int = 12, value_embed_gate_range: float = 3.0, smear_channels: int = 24, bos_token_id: int = 32759, eos_token_id: int = 32759, use_cache: bool = True, release: dict[str, str | int | float | None] | None = None, **kwargs: object, ) -> None: if hidden_size % num_attention_heads != 0 or num_attention_heads % num_key_value_heads != 0: raise ValueError("hidden_size must divide into num_attention_heads, and those into num_key_value_heads") if not window_pattern or set(window_pattern.upper()) - {"S", "L"}: raise ValueError(f"window_pattern must be a non-empty string of S and L, got {window_pattern!r}") self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.max_position_embeddings = max_position_embeddings self.window_pattern = window_pattern.upper() self.rotary_base = rotary_base self.qk_scale = qk_scale self.logit_softcap = logit_softcap self.value_embed_gate_channels = value_embed_gate_channels self.value_embed_gate_range = value_embed_gate_range self.smear_channels = smear_channels self.use_cache = use_cache self.release = release kwargs.setdefault("tie_word_embeddings", False) super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
@property def head_dim(self) -> int: return self.hidden_size // self.num_attention_heads
@property def intermediate_size(self) -> int: return 4 * self.hidden_size
@property def window_sizes(self) -> list[int]: """Left attention window of each layer, in tokens.""" long_window = self.max_position_embeddings short_window = -(-long_window // 4 // 128) * 128 # a quarter of the context, rounded up to a multiple of 128 (2048 -> 512) pattern = self.window_pattern sizes = [short_window if pattern[i % len(pattern)] == "S" else long_window for i in range(self.num_hidden_layers)] sizes[-1] = long_window return sizes
def has_value_embedding(self, layer_idx: int) -> bool: """Value embeddings sit on alternating layers, always including the last one.""" return layer_idx % 2 == (self.num_hidden_layers - 1) % 2
@property def backout_layer(self) -> int: """The residual stream after this layer is partly subtracted before the final norm.""" return self.num_hidden_layers // 212345678910{ "_from_model_config": true, "bos_token_id": 32759, "eos_token_id": 32759, "output_attentions": false, "output_hidden_states": false, "pad_token_id": 32759, "transformers_version": "5.17.0", "use_cache": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340"""The WildAI language models (a nanochat GPT variant) for Hugging Face ``transformers``.
This file is copied verbatim into every released model repository and loaded with ``trust_remote_code=True``.It depends only on ``torch`` and ``transformers`` and reproduces the training code's forward pass operation byoperation, so a model loaded in bfloat16 computes the same function the paper evaluated:
- token embedding followed by a parameter-free RMSNorm, then a learned "smear" that mixes each position's embedding with the previous token's;- per-layer scalars that rescale the residual stream and blend the initial embedding back in before every block;- attention with rotary embeddings applied before a per-head RMSNorm of queries and keys (both scaled by 1.2), a left sliding window per layer, and gated value embeddings added to the values on alternating layers;- a squared-ReLU MLP, parameter-free pre-norms, no biases;- "backout": part of the residual stream after the middle layer is subtracted before the final norm;- untied output head with logits soft-capped by ``15 * tanh(logits / 15)``.
Attention uses PyTorch's scaled_dot_product_attention with explicit window masks, so no FlashAttention install isneeded. Generation uses the standard ``DynamicCache``."""
from __future__ import annotations
from dataclasses import dataclassfrom typing import ClassVar
import torchimport torch.nn.functional as Ffrom torch import nnfrom transformers import GenerationMixin, PreTrainedModelfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from .configuration_wildai import WildAIConfig
def rms_norm(x: torch.Tensor) -> torch.Tensor: """Parameter-free RMSNorm over the last dimension with PyTorch's default epsilon, as in training.""" return F.rms_norm(x, (x.size(-1),))
def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: """Rotate channel pairs (i, i + d/2) of ``x`` (batch, time, heads, head_dim), with the training code's sign convention.""" d = x.shape[-1] // 2 x1, x2 = x[..., :d], x[..., d:] return torch.cat([x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos], dim=-1)
@dataclass(frozen=True)class WindowMask: """Arguments for scaled_dot_product_attention that implement one attention window."""
mask: torch.Tensor | None is_causal: bool
def window_masks( window_sizes: list[int], query_len: int, past_len: int, padding_mask: torch.Tensor | None, device: torch.device) -> dict[int, WindowMask]: """Masks for each distinct left window. Query i (absolute index past_len + i) sees keys j with i - window <= j <= i.
``padding_mask`` is the (batch, past_len + query_len) attention mask when it contains padding, else None. A padding query is always allowed to see itself so that its (unused) output stays finite. """ total = past_len + query_len q_idx = torch.arange(past_len, total, device=device)[:, None] k_idx = torch.arange(total, device=device)[None, :] masks: dict[int, WindowMask] = {} for window in sorted(set(window_sizes)): if padding_mask is None and window >= total - 1: if query_len == 1: masks[window] = WindowMask(mask=None, is_causal=False) continue if past_len == 0: masks[window] = WindowMask(mask=None, is_causal=True) continue allowed = (k_idx <= q_idx) & (q_idx - k_idx <= window) if padding_mask is not None: allowed = (allowed & padding_mask[:, None, None, :].bool()) | (k_idx == q_idx) masks[window] = WindowMask(mask=allowed, is_causal=False) return masks
class WildAIAttention(nn.Module): def __init__(self, config: WildAIConfig, layer_idx: int) -> None: super().__init__() self.layer_idx = layer_idx self.num_heads = config.num_attention_heads self.num_kv_heads = config.num_key_value_heads self.head_dim = config.head_dim self.qk_scale = config.qk_scale self.window = config.window_sizes[layer_idx] hidden, kv_dim = config.hidden_size, config.num_key_value_heads * config.head_dim self.q_proj = nn.Linear(hidden, config.num_attention_heads * config.head_dim, bias=False) self.k_proj = nn.Linear(hidden, kv_dim, bias=False) self.v_proj = nn.Linear(hidden, kv_dim, bias=False) self.o_proj = nn.Linear(hidden, hidden, bias=False) self.value_embed: nn.Embedding | None = None self.value_embed_gate: nn.Linear | None = None if config.has_value_embedding(layer_idx): self.value_embed = nn.Embedding(config.vocab_size, kv_dim) self.value_embed_gate = nn.Linear(config.value_embed_gate_channels, config.num_key_value_heads, bias=False) self.gate_channels = config.value_embed_gate_channels self.gate_range = config.value_embed_gate_range
def forward( self, x: torch.Tensor, input_ids: torch.LongTensor, rotary: tuple[torch.Tensor, torch.Tensor], mask: WindowMask, past_key_values: Cache | None, ) -> torch.Tensor: batch, time, _ = x.shape q = self.q_proj(x).view(batch, time, self.num_heads, self.head_dim) k = self.k_proj(x).view(batch, time, self.num_kv_heads, self.head_dim) v = self.v_proj(x).view(batch, time, self.num_kv_heads, self.head_dim) if self.value_embed is not None: ve = self.value_embed(input_ids).to(x.dtype).view(batch, time, self.num_kv_heads, self.head_dim) gate = self.gate_range * torch.sigmoid(self.value_embed_gate(x[..., : self.gate_channels])) v = v + gate.unsqueeze(-1) * ve cos, sin = rotary q, k = apply_rotary(q, cos, sin), apply_rotary(k, cos, sin) q, k = rms_norm(q) * self.qk_scale, rms_norm(k) * self.qk_scale q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) if past_key_values is not None: k, v = past_key_values.update(k, v, self.layer_idx) y = F.scaled_dot_product_attention( q, k, v, attn_mask=mask.mask, is_causal=mask.is_causal, enable_gqa=self.num_kv_heads != self.num_heads ) return self.o_proj(y.transpose(1, 2).reshape(batch, time, -1))
class WildAIMLP(nn.Module): def __init__(self, config: WildAIConfig) -> None: super().__init__() self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.down_proj(F.relu(self.up_proj(x)).square())
class WildAIDecoderLayer(nn.Module): def __init__(self, config: WildAIConfig, layer_idx: int) -> None: super().__init__() self.self_attn = WildAIAttention(config, layer_idx) self.mlp = WildAIMLP(config)
def forward( self, x: torch.Tensor, input_ids: torch.LongTensor, rotary: tuple[torch.Tensor, torch.Tensor], mask: WindowMask, past_key_values: Cache | None, ) -> torch.Tensor: x = x + self.self_attn(rms_norm(x), input_ids, rotary, mask, past_key_values) return x + self.mlp(rms_norm(x))
class WildAIPreTrainedModel(PreTrainedModel): config_class = WildAIConfig base_model_prefix = "model" main_input_name = "input_ids" _no_split_modules: ClassVar[list[str]] = ["WildAIDecoderLayer"] _supports_sdpa = True
def _init_weights(self, module: nn.Module) -> None: # Released models are always loaded from trained weights; this only gives from_config() models sane values. if isinstance(module, (nn.Linear, nn.Embedding)): nn.init.normal_(module.weight, mean=0.0, std=0.02) elif isinstance(module, WildAIModel): with torch.no_grad(): module.resid_lambdas.fill_(1.0) module.x0_lambdas.zero_() module.smear_lambda.zero_() module.backout_lambda.zero_()
class WildAIModel(WildAIPreTrainedModel): """The transformer trunk; returns the final normalised hidden states."""
def __init__(self, config: WildAIConfig) -> None: super().__init__(config) n_layer = config.num_hidden_layers self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) self.layers = nn.ModuleList([WildAIDecoderLayer(config, i) for i in range(n_layer)]) self.resid_lambdas = nn.Parameter(torch.ones(n_layer)) self.x0_lambdas = nn.Parameter(torch.zeros(n_layer)) self.smear_gate = nn.Linear(config.smear_channels, 1, bias=False) self.smear_lambda = nn.Parameter(torch.zeros(1)) self.backout_lambda = nn.Parameter(torch.zeros(1)) self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.embed_tokens
def set_input_embeddings(self, value: nn.Embedding) -> None: self.embed_tokens = value
def rotary(self, position_ids: torch.LongTensor, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]: """cos/sin tables of shape (batch, time, 1, head_dim / 2), computed in float32 and cast like in training.""" head_dim = self.config.head_dim channels = torch.arange(0, head_dim, 2, dtype=torch.float32, device=position_ids.device) inv_freq = 1.0 / (self.config.rotary_base ** (channels / head_dim)) freqs = position_ids.to(torch.float32)[..., None] * inv_freq return freqs.cos().to(dtype)[:, :, None, :], freqs.sin().to(dtype)[:, :, None, :]
def smear(self, x: torch.Tensor, previous: torch.Tensor | None, padding_mask: torch.Tensor | None) -> torch.Tensor: """Add a gated copy of the previous position's embedding to every position that has one.
``previous`` is the normalised embedding of the token just before this chunk (None at the start of a sequence); with left padding, the first real token has a padding token before it and gets nothing. """ channels = self.config.smear_channels lam = self.smear_lambda.to(x.dtype) first = x[:, :1] if previous is not None: first = first + lam * torch.sigmoid(self.smear_gate(first[..., :channels])) * previous if x.size(1) == 1: return first gate = lam * torch.sigmoid(self.smear_gate(x[:, 1:, :channels])) if padding_mask is not None: gate = gate * padding_mask[:, -x.size(1) : -1, None].to(gate.dtype) return torch.cat([first, x[:, 1:] + gate * x[:, :-1]], dim=1)
def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, use_cache: bool | None = None, previous_token_ids: torch.LongTensor | None = None, output_hidden_states: bool | None = None, **kwargs: object, ) -> BaseModelOutputWithPast: """``previous_token_ids`` (batch, 1): the token before ``input_ids[:, 0]``; required when continuing from a cache.""" if input_ids is None: raise ValueError("input_ids are required: the value embeddings are looked up by token id") batch, time = input_ids.shape use_cache = self.config.use_cache if use_cache is None else use_cache if use_cache and past_key_values is None: past_key_values = DynamicCache() past_len = past_key_values.get_seq_length() if past_key_values is not None else 0 if past_len > 0 and previous_token_ids is None: raise ValueError("previous_token_ids is required when continuing from past_key_values (the smear needs it)") padding_mask = None if attention_mask is not None: if attention_mask.shape != (batch, past_len + time): raise ValueError(f"attention_mask must have shape {(batch, past_len + time)}, got {tuple(attention_mask.shape)}") if not bool(attention_mask.all()): padding_mask = attention_mask if position_ids is None: position_ids = torch.arange(past_len, past_len + time, device=input_ids.device).expand(batch, -1)
x = rms_norm(self.embed_tokens(input_ids)) previous = rms_norm(self.embed_tokens(previous_token_ids)) if previous_token_ids is not None else None x = self.smear(x, previous, padding_mask) rotary = self.rotary(position_ids, x.dtype) masks = window_masks(self.config.window_sizes, time, past_len, padding_mask, input_ids.device)
x0 = x backout = None hidden_states: tuple[torch.Tensor, ...] = (x,) for i, layer in enumerate(self.layers): x = self.resid_lambdas[i] * x + self.x0_lambdas[i] * x0 x = layer(x, input_ids, rotary, masks[layer.self_attn.window], past_key_values) if i == self.config.backout_layer: backout = x hidden_states += (x,) x = rms_norm(x - self.backout_lambda.to(x.dtype) * backout) return BaseModelOutputWithPast( last_hidden_state=x, past_key_values=past_key_values if use_cache else None, hidden_states=hidden_states if output_hidden_states else None, )
class WildAIForCausalLM(WildAIPreTrainedModel, GenerationMixin): def __init__(self, config: WildAIConfig) -> None: super().__init__(config) self.model = WildAIModel(config) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.model.embed_tokens
def set_input_embeddings(self, value: nn.Embedding) -> None: self.model.embed_tokens = value
def get_output_embeddings(self) -> nn.Linear: return self.lm_head
def set_output_embeddings(self, value: nn.Linear) -> None: self.lm_head = value
def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, previous_token_ids: torch.LongTensor | None = None, output_hidden_states: bool | None = None, logits_to_keep: int = 0, return_dict: bool | None = None, **kwargs: object, ) -> CausalLMOutputWithPast | tuple[torch.Tensor, ...]: """Float32 logits after the soft cap. ``labels`` are shifted inside (standard causal-LM loss, -100 ignored).""" outputs = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, previous_token_ids=previous_token_ids, output_hidden_states=output_hidden_states, ) hidden = outputs.last_hidden_state[:, -logits_to_keep:] if logits_to_keep else outputs.last_hidden_state logits = self.lm_head(hidden).float() cap = self.config.logit_softcap logits = cap * torch.tanh(logits / cap) loss = None if labels is not None: loss = F.cross_entropy(logits[:, :-1].flatten(0, 1), labels[:, 1:].flatten().to(logits.device), ignore_index=-100) result = CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states ) return result.to_tuple() if return_dict is False else result
def prepare_inputs_for_generation(self, input_ids: torch.LongTensor, **kwargs: object) -> dict[str, object]: # The smear mixes in the embedding of the token before the first new one; take it from the full sequence. model_inputs = super().prepare_inputs_for_generation(input_ids, **kwargs) new_len = model_inputs["input_ids"].shape[1] if input_ids.shape[1] > new_len: model_inputs["previous_token_ids"] = input_ids[:, -new_len - 1 : -new_len] return model_inputs1234567891011{ "tokenizer_class": "PreTrainedTokenizerFast", "bos_token": "<|bos|>", "eos_token": "<|bos|>", "model_max_length": 2048, "model_input_names": [ "input_ids", "attention_mask" ], "clean_up_tokenization_spaces": false}123version https://git-lfs.github.com/spec/v1oid sha256:afa46771f41d29cb626c885a56253c38cdee3efa2f92500613c4f7bb6dcb2099size 1073757052123version https://git-lfs.github.com/spec/v1oid sha256:68c1c67e629ea68e163ef6728cc8ef97f010dc1286d9e1381ffd4ac9dd3b4022size 1073757052123version https://git-lfs.github.com/spec/v1oid sha256:c01d86cca56022df459ea69b2108506d751b6253ae03882e989e06573ea8ad1bsize 1073757052123version https://git-lfs.github.com/spec/v1oid sha256:9733b19380d65f7617c69d9dcac92638e53a9960be0fa37be01fa881434bf154size 1073757052123version https://git-lfs.github.com/spec/v1oid sha256:408c5a2a929ff138758487f3818bba4f67e96fb3a259aad100b5397b7c70b1a0size 1073757052123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438Attribution-NonCommercial-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm anddoes not provide legal services or legal advice. Distribution ofCreative Commons public licenses does not create a lawyer-client orother relationship. Creative Commons makes its licenses and relatedinformation available on an "as-is" basis. Creative Commons gives nowarranties regarding its licenses, any material licensed under theirterms and conditions, or any related information. Creative Commonsdisclaims all liability for damages resulting from their use to thefullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms andconditions that creators and other rights holders may use to shareoriginal works of authorship and other material subject to copyrightand certain other rights specified in the public license below. Thefollowing considerations are for informational purposes only, are notexhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public: wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 InternationalPublic License
By exercising the Licensed Rights (defined below), You accept and agreeto be bound by the terms and conditions of this Creative CommonsAttribution-NonCommercial-ShareAlike 4.0 International Public License("Public License"). To the extent this Public License may beinterpreted as a contract, You are granted the Licensed Rights inconsideration of Your acceptance of these terms and conditions, and theLicensor grants You such rights in consideration of benefits theLicensor receives from making the Licensed Material available underthese terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
k. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
l. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
m. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
b. Additional offer from the Licensor -- Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to thefollowing conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
a. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights thatapply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does notreplace Your obligations under this Public License where the LicensedRights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its publiclicenses. Notwithstanding, Creative Commons may elect to apply one ofits public licenses to material it publishes and in those instanceswill be considered the “Licensor.” The text of the Creative Commonspublic licenses is dedicated to the public domain under the CC0 PublicDomain Dedication. Except for the limited purpose of indicating thatmaterial is shared under a Creative Commons public license or asotherwise permitted by the Creative Commons policies published atcreativecommons.org/policies, Creative Commons does not authorize theuse of the trademark "Creative Commons" or any other trademark or logoof Creative Commons without its prior written consent including,without limitation, in connection with any unauthorized modificationsto any of its public licenses or any other arrangements,understandings, or agreements concerning use of licensed material. Forthe avoidance of doubt, this paragraph does not form part of thepublic licenses.
Creative Commons may be contacted at creativecommons.org.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105---license: cc-by-nc-sa-4.0library_name: transformerspipeline_tag: text-generationlanguage:- endatasets:- pangram/WildAItags:- wildai- nanochat- scaling-laws- ai-generated-text- pretraining-data---
# 268m-g077-ai-r0.25
> **License: [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/).** The WildAI code, models and dataset are released under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license: you may use and adapt them for non-commercial purposes, with attribution, and must share adaptations under the same license.
A 268M decoder-only language model trained from scratch for [*How Much Is an AI Token Worth? Scaling Laws for Wild AI-Generated Web Text*](https://arxiv.org/abs/2609.40295), one of the paper's models measuring how wild AI-generated web text in pretraining data changes a model's loss. It is a research artifact for studying scaling laws, not an assistant: it has had no instruction tuning or safety training.
## Training data
The human documents of `268m-g077-control` plus wild AI-generated web documents: 4.69B human and 1.18B AI tokens trained on, an AI-to-human token ratio r = 0.251 (design 0.25), so 20.1% of the training tokens are AI-generated.
| | ||---|---|| Parameters (N, input embedding included, value embeddings excluded) | 268.4M || Layers / width | 16 / 1024 || Training tokens | 5.87B (11,200 optimizer steps) || Human / AI tokens | 4.69B / 1.18B || Group / arm / seed | g077 / ai / 7331 || Used in the paper for | fitting the scaling laws (726 models, 19.9M to 268M) |
## Held-out loss
| Set | Bits per byte | Text ||---|---|---|| C4 | 0.9394 | C4 validation text (human-written, pre-2022) || FW22 | 0.9202 | held-out FineWeb documents crawled before 2022 || Paloma | 1.3078 | macro average over 16 Paloma sources || FW26 | 0.7907 | held-out 2026 FineWeb-style crawl (22.3% AI tokens) || FW26-H | 0.8518 | the human-labeled documents of FW26 || FW26-AI | 0.5646 | the AI-labeled documents of FW26 || Cosmo | 0.5714 | Cosmopedia (AI-generated textbooks and stories) |
<details><summary>Paloma sources</summary>
| Source | Bits per byte ||---|---|| 4chan | 1.3440 || c4 | 0.9585 || c4_100_domains | 0.9362 || dolma | 1.2000 || falcon_refinedweb | 1.0523 || gab | 1.8194 || m2d2_s2orc | 1.1229 || m2d2_wikipedia | 1.0231 || manosphere | 1.3344 || mc4_en | 1.0409 || programming | 1.9015 || ptb | 1.1796 || reddit_100 | 1.1947 || redpajama | 1.3655 || twitteraae | 2.4362 || wikitext_103 | 1.0159 |
</details>
## Usage
```pythonimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("pangram/WildAI-models", subfolder="268m-g077-ai-r0.25", trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained("pangram/WildAI-models", subfolder="268m-g077-ai-r0.25", trust_remote_code=True, dtype=torch.bfloat16)
inputs = tokenizer("The history of the printing press", return_tensors="pt")output = model.generate(**inputs, max_new_tokens=40, do_sample=False)print(tokenizer.decode(output[0], skip_special_tokens=True))```
The tokenizer prepends `<|bos|>` to every text, as in training; pass `add_special_tokens=False` to skip it. The model predicts `<|bos|>` where a document ends, and generation stops there. Weights are stored in bfloat16, the precision the paper's losses were computed in; `dtype=torch.float32` computes in float32 instead.
## Architecture
The nanochat GPT recipe: rotary embeddings, RMSNorm without weights (also on queries and keys), squared-ReLU MLP, attention windows in a repeating short-short-short-long pattern (512 tokens, then the full 2,048-token context; the last layer always full), gated value embeddings on alternating layers, a previous-token smear, per-layer residual scalars, a mid-network backout, untied input and output embeddings and logits soft-capped at 15. Vocabulary 32,768 tokens, context 2,048. The code ships with the weights (`trust_remote_code=True`) and matches the training code's forward pass.
## License
**License: [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/).** The WildAI code, models and dataset are released under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license: you may use and adapt them for non-commercial purposes, with attribution, and must share adaptations under the same license. The full text is in `LICENSE`.
## Citation
```bibtex@article{russell2026wildai, title = {How Much Is an AI Token Worth? Scaling Laws for Wild AI-Generated Web Text}, author = {Russell, Jenna and Glickenhaus, Ben and Thai, Katherine and Wieting, John and Iyyer, Mohit and Spero, Max and Emi, Bradley}, journal = {arXiv preprint arXiv:2609.40295}, year = {2026}, url = {https://arxiv.org/abs/2609.40295}}```12345678910111213141516171819202122232425262728293031323334353637383940414243444546{ "architectures": [ "WildAIForCausalLM" ], "auto_map": { "AutoConfig": "configuration_wildai.WildAIConfig", "AutoModelForCausalLM": "modeling_wildai.WildAIForCausalLM" }, "bos_token_id": 32759, "dtype": "bfloat16", "eos_token_id": 32759, "hidden_size": 1024, "logit_softcap": 15.0, "max_position_embeddings": 2048, "model_type": "wildai", "num_attention_heads": 8, "num_hidden_layers": 16, "num_key_value_heads": 8, "pad_token_id": 32759, "qk_scale": 1.2, "release": { "added_ratio": 0.25, "ai_ratio": 0.25149247953048315, "ai_tokens": 1180007313, "arm": "ai", "depth": 16, "group": "g077", "human_tokens": 4692018287, "n_params": 268436282, "name": "268m-g077-ai-r0.25", "seed": 7331, "size": "268m", "split": "fit", "steps": 11200, "total_tokens": 5872025600 }, "rotary_base": 100000.0, "smear_channels": 24, "tie_word_embeddings": false, "transformers_version": "5.17.0", "use_cache": true, "value_embed_gate_channels": 12, "value_embed_gate_range": 3.0, "vocab_size": 32768, "window_pattern": "SSSL"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Configuration of the WildAI language models (a nanochat GPT variant) for Hugging Face ``transformers``.
This file is copied verbatim into every released model repository and loaded with ``trust_remote_code=True``.It depends only on ``transformers``."""
from __future__ import annotations
from typing import ClassVar
from transformers import PretrainedConfig
class WildAIConfig(PretrainedConfig): """Architecture of a WildAI model. Only width and depth vary across the released models.
Every layer uses causal attention limited to a left window: a query attends to itself and the ``window`` tokens before it. ``window_pattern`` is tiled over the layers ("S" = a quarter of the context rounded up to a multiple of 128 tokens, "L" = the full context) and the last layer always uses "L".
``release`` holds the model's entry in the release catalog (name, token counts, AI ratio, ...); it does not affect the forward pass. """
model_type = "wildai" keys_to_ignore_at_inference: ClassVar[list[str]] = ["past_key_values"]
def __init__( self, vocab_size: int = 32768, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 6, num_key_value_heads: int = 6, max_position_embeddings: int = 2048, window_pattern: str = "SSSL", rotary_base: float = 100000.0, qk_scale: float = 1.2, logit_softcap: float = 15.0, value_embed_gate_channels: int = 12, value_embed_gate_range: float = 3.0, smear_channels: int = 24, bos_token_id: int = 32759, eos_token_id: int = 32759, use_cache: bool = True, release: dict[str, str | int | float | None] | None = None, **kwargs: object, ) -> None: if hidden_size % num_attention_heads != 0 or num_attention_heads % num_key_value_heads != 0: raise ValueError("hidden_size must divide into num_attention_heads, and those into num_key_value_heads") if not window_pattern or set(window_pattern.upper()) - {"S", "L"}: raise ValueError(f"window_pattern must be a non-empty string of S and L, got {window_pattern!r}") self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.max_position_embeddings = max_position_embeddings self.window_pattern = window_pattern.upper() self.rotary_base = rotary_base self.qk_scale = qk_scale self.logit_softcap = logit_softcap self.value_embed_gate_channels = value_embed_gate_channels self.value_embed_gate_range = value_embed_gate_range self.smear_channels = smear_channels self.use_cache = use_cache self.release = release kwargs.setdefault("tie_word_embeddings", False) super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
@property def head_dim(self) -> int: return self.hidden_size // self.num_attention_heads
@property def intermediate_size(self) -> int: return 4 * self.hidden_size
@property def window_sizes(self) -> list[int]: """Left attention window of each layer, in tokens.""" long_window = self.max_position_embeddings short_window = -(-long_window // 4 // 128) * 128 # a quarter of the context, rounded up to a multiple of 128 (2048 -> 512) pattern = self.window_pattern sizes = [short_window if pattern[i % len(pattern)] == "S" else long_window for i in range(self.num_hidden_layers)] sizes[-1] = long_window return sizes
def has_value_embedding(self, layer_idx: int) -> bool: """Value embeddings sit on alternating layers, always including the last one.""" return layer_idx % 2 == (self.num_hidden_layers - 1) % 2
@property def backout_layer(self) -> int: """The residual stream after this layer is partly subtracted before the final norm.""" return self.num_hidden_layers // 212345678910{ "_from_model_config": true, "bos_token_id": 32759, "eos_token_id": 32759, "output_attentions": false, "output_hidden_states": false, "pad_token_id": 32759, "transformers_version": "5.17.0", "use_cache": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340"""The WildAI language models (a nanochat GPT variant) for Hugging Face ``transformers``.
This file is copied verbatim into every released model repository and loaded with ``trust_remote_code=True``.It depends only on ``torch`` and ``transformers`` and reproduces the training code's forward pass operation byoperation, so a model loaded in bfloat16 computes the same function the paper evaluated:
- token embedding followed by a parameter-free RMSNorm, then a learned "smear" that mixes each position's embedding with the previous token's;- per-layer scalars that rescale the residual stream and blend the initial embedding back in before every block;- attention with rotary embeddings applied before a per-head RMSNorm of queries and keys (both scaled by 1.2), a left sliding window per layer, and gated value embeddings added to the values on alternating layers;- a squared-ReLU MLP, parameter-free pre-norms, no biases;- "backout": part of the residual stream after the middle layer is subtracted before the final norm;- untied output head with logits soft-capped by ``15 * tanh(logits / 15)``.
Attention uses PyTorch's scaled_dot_product_attention with explicit window masks, so no FlashAttention install isneeded. Generation uses the standard ``DynamicCache``."""
from __future__ import annotations
from dataclasses import dataclassfrom typing import ClassVar
import torchimport torch.nn.functional as Ffrom torch import nnfrom transformers import GenerationMixin, PreTrainedModelfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from .configuration_wildai import WildAIConfig
def rms_norm(x: torch.Tensor) -> torch.Tensor: """Parameter-free RMSNorm over the last dimension with PyTorch's default epsilon, as in training.""" return F.rms_norm(x, (x.size(-1),))
def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: """Rotate channel pairs (i, i + d/2) of ``x`` (batch, time, heads, head_dim), with the training code's sign convention.""" d = x.shape[-1] // 2 x1, x2 = x[..., :d], x[..., d:] return torch.cat([x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos], dim=-1)
@dataclass(frozen=True)class WindowMask: """Arguments for scaled_dot_product_attention that implement one attention window."""
mask: torch.Tensor | None is_causal: bool
def window_masks( window_sizes: list[int], query_len: int, past_len: int, padding_mask: torch.Tensor | None, device: torch.device) -> dict[int, WindowMask]: """Masks for each distinct left window. Query i (absolute index past_len + i) sees keys j with i - window <= j <= i.
``padding_mask`` is the (batch, past_len + query_len) attention mask when it contains padding, else None. A padding query is always allowed to see itself so that its (unused) output stays finite. """ total = past_len + query_len q_idx = torch.arange(past_len, total, device=device)[:, None] k_idx = torch.arange(total, device=device)[None, :] masks: dict[int, WindowMask] = {} for window in sorted(set(window_sizes)): if padding_mask is None and window >= total - 1: if query_len == 1: masks[window] = WindowMask(mask=None, is_causal=False) continue if past_len == 0: masks[window] = WindowMask(mask=None, is_causal=True) continue allowed = (k_idx <= q_idx) & (q_idx - k_idx <= window) if padding_mask is not None: allowed = (allowed & padding_mask[:, None, None, :].bool()) | (k_idx == q_idx) masks[window] = WindowMask(mask=allowed, is_causal=False) return masks
class WildAIAttention(nn.Module): def __init__(self, config: WildAIConfig, layer_idx: int) -> None: super().__init__() self.layer_idx = layer_idx self.num_heads = config.num_attention_heads self.num_kv_heads = config.num_key_value_heads self.head_dim = config.head_dim self.qk_scale = config.qk_scale self.window = config.window_sizes[layer_idx] hidden, kv_dim = config.hidden_size, config.num_key_value_heads * config.head_dim self.q_proj = nn.Linear(hidden, config.num_attention_heads * config.head_dim, bias=False) self.k_proj = nn.Linear(hidden, kv_dim, bias=False) self.v_proj = nn.Linear(hidden, kv_dim, bias=False) self.o_proj = nn.Linear(hidden, hidden, bias=False) self.value_embed: nn.Embedding | None = None self.value_embed_gate: nn.Linear | None = None if config.has_value_embedding(layer_idx): self.value_embed = nn.Embedding(config.vocab_size, kv_dim) self.value_embed_gate = nn.Linear(config.value_embed_gate_channels, config.num_key_value_heads, bias=False) self.gate_channels = config.value_embed_gate_channels self.gate_range = config.value_embed_gate_range
def forward( self, x: torch.Tensor, input_ids: torch.LongTensor, rotary: tuple[torch.Tensor, torch.Tensor], mask: WindowMask, past_key_values: Cache | None, ) -> torch.Tensor: batch, time, _ = x.shape q = self.q_proj(x).view(batch, time, self.num_heads, self.head_dim) k = self.k_proj(x).view(batch, time, self.num_kv_heads, self.head_dim) v = self.v_proj(x).view(batch, time, self.num_kv_heads, self.head_dim) if self.value_embed is not None: ve = self.value_embed(input_ids).to(x.dtype).view(batch, time, self.num_kv_heads, self.head_dim) gate = self.gate_range * torch.sigmoid(self.value_embed_gate(x[..., : self.gate_channels])) v = v + gate.unsqueeze(-1) * ve cos, sin = rotary q, k = apply_rotary(q, cos, sin), apply_rotary(k, cos, sin) q, k = rms_norm(q) * self.qk_scale, rms_norm(k) * self.qk_scale q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) if past_key_values is not None: k, v = past_key_values.update(k, v, self.layer_idx) y = F.scaled_dot_product_attention( q, k, v, attn_mask=mask.mask, is_causal=mask.is_causal, enable_gqa=self.num_kv_heads != self.num_heads ) return self.o_proj(y.transpose(1, 2).reshape(batch, time, -1))
class WildAIMLP(nn.Module): def __init__(self, config: WildAIConfig) -> None: super().__init__() self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.down_proj(F.relu(self.up_proj(x)).square())
class WildAIDecoderLayer(nn.Module): def __init__(self, config: WildAIConfig, layer_idx: int) -> None: super().__init__() self.self_attn = WildAIAttention(config, layer_idx) self.mlp = WildAIMLP(config)
def forward( self, x: torch.Tensor, input_ids: torch.LongTensor, rotary: tuple[torch.Tensor, torch.Tensor], mask: WindowMask, past_key_values: Cache | None, ) -> torch.Tensor: x = x + self.self_attn(rms_norm(x), input_ids, rotary, mask, past_key_values) return x + self.mlp(rms_norm(x))
class WildAIPreTrainedModel(PreTrainedModel): config_class = WildAIConfig base_model_prefix = "model" main_input_name = "input_ids" _no_split_modules: ClassVar[list[str]] = ["WildAIDecoderLayer"] _supports_sdpa = True
def _init_weights(self, module: nn.Module) -> None: # Released models are always loaded from trained weights; this only gives from_config() models sane values. if isinstance(module, (nn.Linear, nn.Embedding)): nn.init.normal_(module.weight, mean=0.0, std=0.02) elif isinstance(module, WildAIModel): with torch.no_grad(): module.resid_lambdas.fill_(1.0) module.x0_lambdas.zero_() module.smear_lambda.zero_() module.backout_lambda.zero_()
class WildAIModel(WildAIPreTrainedModel): """The transformer trunk; returns the final normalised hidden states."""
def __init__(self, config: WildAIConfig) -> None: super().__init__(config) n_layer = config.num_hidden_layers self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) self.layers = nn.ModuleList([WildAIDecoderLayer(config, i) for i in range(n_layer)]) self.resid_lambdas = nn.Parameter(torch.ones(n_layer)) self.x0_lambdas = nn.Parameter(torch.zeros(n_layer)) self.smear_gate = nn.Linear(config.smear_channels, 1, bias=False) self.smear_lambda = nn.Parameter(torch.zeros(1)) self.backout_lambda = nn.Parameter(torch.zeros(1)) self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.embed_tokens
def set_input_embeddings(self, value: nn.Embedding) -> None: self.embed_tokens = value
def rotary(self, position_ids: torch.LongTensor, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]: """cos/sin tables of shape (batch, time, 1, head_dim / 2), computed in float32 and cast like in training.""" head_dim = self.config.head_dim channels = torch.arange(0, head_dim, 2, dtype=torch.float32, device=position_ids.device) inv_freq = 1.0 / (self.config.rotary_base ** (channels / head_dim)) freqs = position_ids.to(torch.float32)[..., None] * inv_freq return freqs.cos().to(dtype)[:, :, None, :], freqs.sin().to(dtype)[:, :, None, :]
def smear(self, x: torch.Tensor, previous: torch.Tensor | None, padding_mask: torch.Tensor | None) -> torch.Tensor: """Add a gated copy of the previous position's embedding to every position that has one.
``previous`` is the normalised embedding of the token just before this chunk (None at the start of a sequence); with left padding, the first real token has a padding token before it and gets nothing. """ channels = self.config.smear_channels lam = self.smear_lambda.to(x.dtype) first = x[:, :1] if previous is not None: first = first + lam * torch.sigmoid(self.smear_gate(first[..., :channels])) * previous if x.size(1) == 1: return first gate = lam * torch.sigmoid(self.smear_gate(x[:, 1:, :channels])) if padding_mask is not None: gate = gate * padding_mask[:, -x.size(1) : -1, None].to(gate.dtype) return torch.cat([first, x[:, 1:] + gate * x[:, :-1]], dim=1)
def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, use_cache: bool | None = None, previous_token_ids: torch.LongTensor | None = None, output_hidden_states: bool | None = None, **kwargs: object, ) -> BaseModelOutputWithPast: """``previous_token_ids`` (batch, 1): the token before ``input_ids[:, 0]``; required when continuing from a cache.""" if input_ids is None: raise ValueError("input_ids are required: the value embeddings are looked up by token id") batch, time = input_ids.shape use_cache = self.config.use_cache if use_cache is None else use_cache if use_cache and past_key_values is None: past_key_values = DynamicCache() past_len = past_key_values.get_seq_length() if past_key_values is not None else 0 if past_len > 0 and previous_token_ids is None: raise ValueError("previous_token_ids is required when continuing from past_key_values (the smear needs it)") padding_mask = None if attention_mask is not None: if attention_mask.shape != (batch, past_len + time): raise ValueError(f"attention_mask must have shape {(batch, past_len + time)}, got {tuple(attention_mask.shape)}") if not bool(attention_mask.all()): padding_mask = attention_mask if position_ids is None: position_ids = torch.arange(past_len, past_len + time, device=input_ids.device).expand(batch, -1)
x = rms_norm(self.embed_tokens(input_ids)) previous = rms_norm(self.embed_tokens(previous_token_ids)) if previous_token_ids is not None else None x = self.smear(x, previous, padding_mask) rotary = self.rotary(position_ids, x.dtype) masks = window_masks(self.config.window_sizes, time, past_len, padding_mask, input_ids.device)
x0 = x backout = None hidden_states: tuple[torch.Tensor, ...] = (x,) for i, layer in enumerate(self.layers): x = self.resid_lambdas[i] * x + self.x0_lambdas[i] * x0 x = layer(x, input_ids, rotary, masks[layer.self_attn.window], past_key_values) if i == self.config.backout_layer: backout = x hidden_states += (x,) x = rms_norm(x - self.backout_lambda.to(x.dtype) * backout) return BaseModelOutputWithPast( last_hidden_state=x, past_key_values=past_key_values if use_cache else None, hidden_states=hidden_states if output_hidden_states else None, )
class WildAIForCausalLM(WildAIPreTrainedModel, GenerationMixin): def __init__(self, config: WildAIConfig) -> None: super().__init__(config) self.model = WildAIModel(config) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.model.embed_tokens
def set_input_embeddings(self, value: nn.Embedding) -> None: self.model.embed_tokens = value
def get_output_embeddings(self) -> nn.Linear: return self.lm_head
def set_output_embeddings(self, value: nn.Linear) -> None: self.lm_head = value
def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, previous_token_ids: torch.LongTensor | None = None, output_hidden_states: bool | None = None, logits_to_keep: int = 0, return_dict: bool | None = None, **kwargs: object, ) -> CausalLMOutputWithPast | tuple[torch.Tensor, ...]: """Float32 logits after the soft cap. ``labels`` are shifted inside (standard causal-LM loss, -100 ignored).""" outputs = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, previous_token_ids=previous_token_ids, output_hidden_states=output_hidden_states, ) hidden = outputs.last_hidden_state[:, -logits_to_keep:] if logits_to_keep else outputs.last_hidden_state logits = self.lm_head(hidden).float() cap = self.config.logit_softcap logits = cap * torch.tanh(logits / cap) loss = None if labels is not None: loss = F.cross_entropy(logits[:, :-1].flatten(0, 1), labels[:, 1:].flatten().to(logits.device), ignore_index=-100) result = CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states ) return result.to_tuple() if return_dict is False else result
def prepare_inputs_for_generation(self, input_ids: torch.LongTensor, **kwargs: object) -> dict[str, object]: # The smear mixes in the embedding of the token before the first new one; take it from the full sequence. model_inputs = super().prepare_inputs_for_generation(input_ids, **kwargs) new_len = model_inputs["input_ids"].shape[1] if input_ids.shape[1] > new_len: model_inputs["previous_token_ids"] = input_ids[:, -new_len - 1 : -new_len] return model_inputs1234567891011{ "tokenizer_class": "PreTrainedTokenizerFast", "bos_token": "<|bos|>", "eos_token": "<|bos|>", "model_max_length": 2048, "model_input_names": [ "input_ids", "attention_mask" ], "clean_up_tokenization_spaces": false}123version https://git-lfs.github.com/spec/v1oid sha256:ba426963eeaa4d844fd530a2aa3920286ba51a374b213be145fa10d2c890424asize 1073757052123version https://git-lfs.github.com/spec/v1oid sha256:a94a800f331da93267fec32d17facfbd2075a885358c44d4e5b52b919a05b639size 1073757052123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Configuration of the WildAI language models (a nanochat GPT variant) for Hugging Face ``transformers``.
This file is copied verbatim into every released model repository and loaded with ``trust_remote_code=True``.It depends only on ``transformers``."""
from __future__ import annotations
from typing import ClassVar
from transformers import PretrainedConfig
class WildAIConfig(PretrainedConfig): """Architecture of a WildAI model. Only width and depth vary across the released models.
Every layer uses causal attention limited to a left window: a query attends to itself and the ``window`` tokens before it. ``window_pattern`` is tiled over the layers ("S" = a quarter of the context rounded up to a multiple of 128 tokens, "L" = the full context) and the last layer always uses "L".
``release`` holds the model's entry in the release catalog (name, token counts, AI ratio, ...); it does not affect the forward pass. """
model_type = "wildai" keys_to_ignore_at_inference: ClassVar[list[str]] = ["past_key_values"]
def __init__( self, vocab_size: int = 32768, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 6, num_key_value_heads: int = 6, max_position_embeddings: int = 2048, window_pattern: str = "SSSL", rotary_base: float = 100000.0, qk_scale: float = 1.2, logit_softcap: float = 15.0, value_embed_gate_channels: int = 12, value_embed_gate_range: float = 3.0, smear_channels: int = 24, bos_token_id: int = 32759, eos_token_id: int = 32759, use_cache: bool = True, release: dict[str, str | int | float | None] | None = None, **kwargs: object, ) -> None: if hidden_size % num_attention_heads != 0 or num_attention_heads % num_key_value_heads != 0: raise ValueError("hidden_size must divide into num_attention_heads, and those into num_key_value_heads") if not window_pattern or set(window_pattern.upper()) - {"S", "L"}: raise ValueError(f"window_pattern must be a non-empty string of S and L, got {window_pattern!r}") self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.max_position_embeddings = max_position_embeddings self.window_pattern = window_pattern.upper() self.rotary_base = rotary_base self.qk_scale = qk_scale self.logit_softcap = logit_softcap self.value_embed_gate_channels = value_embed_gate_channels self.value_embed_gate_range = value_embed_gate_range self.smear_channels = smear_channels self.use_cache = use_cache self.release = release kwargs.setdefault("tie_word_embeddings", False) super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
@property def head_dim(self) -> int: return self.hidden_size // self.num_attention_heads
@property def intermediate_size(self) -> int: return 4 * self.hidden_size
@property def window_sizes(self) -> list[int]: """Left attention window of each layer, in tokens.""" long_window = self.max_position_embeddings short_window = -(-long_window // 4 // 128) * 128 # a quarter of the context, rounded up to a multiple of 128 (2048 -> 512) pattern = self.window_pattern sizes = [short_window if pattern[i % len(pattern)] == "S" else long_window for i in range(self.num_hidden_layers)] sizes[-1] = long_window return sizes
def has_value_embedding(self, layer_idx: int) -> bool: """Value embeddings sit on alternating layers, always including the last one.""" return layer_idx % 2 == (self.num_hidden_layers - 1) % 2
@property def backout_layer(self) -> int: """The residual stream after this layer is partly subtracted before the final norm.""" return self.num_hidden_layers // 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340"""The WildAI language models (a nanochat GPT variant) for Hugging Face ``transformers``.
This file is copied verbatim into every released model repository and loaded with ``trust_remote_code=True``.It depends only on ``torch`` and ``transformers`` and reproduces the training code's forward pass operation byoperation, so a model loaded in bfloat16 computes the same function the paper evaluated:
- token embedding followed by a parameter-free RMSNorm, then a learned "smear" that mixes each position's embedding with the previous token's;- per-layer scalars that rescale the residual stream and blend the initial embedding back in before every block;- attention with rotary embeddings applied before a per-head RMSNorm of queries and keys (both scaled by 1.2), a left sliding window per layer, and gated value embeddings added to the values on alternating layers;- a squared-ReLU MLP, parameter-free pre-norms, no biases;- "backout": part of the residual stream after the middle layer is subtracted before the final norm;- untied output head with logits soft-capped by ``15 * tanh(logits / 15)``.
Attention uses PyTorch's scaled_dot_product_attention with explicit window masks, so no FlashAttention install isneeded. Generation uses the standard ``DynamicCache``."""
from __future__ import annotations
from dataclasses import dataclassfrom typing import ClassVar
import torchimport torch.nn.functional as Ffrom torch import nnfrom transformers import GenerationMixin, PreTrainedModelfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from .configuration_wildai import WildAIConfig
def rms_norm(x: torch.Tensor) -> torch.Tensor: """Parameter-free RMSNorm over the last dimension with PyTorch's default epsilon, as in training.""" return F.rms_norm(x, (x.size(-1),))
def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: """Rotate channel pairs (i, i + d/2) of ``x`` (batch, time, heads, head_dim), with the training code's sign convention.""" d = x.shape[-1] // 2 x1, x2 = x[..., :d], x[..., d:] return torch.cat([x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos], dim=-1)
@dataclass(frozen=True)class WindowMask: """Arguments for scaled_dot_product_attention that implement one attention window."""
mask: torch.Tensor | None is_causal: bool
def window_masks( window_sizes: list[int], query_len: int, past_len: int, padding_mask: torch.Tensor | None, device: torch.device) -> dict[int, WindowMask]: """Masks for each distinct left window. Query i (absolute index past_len + i) sees keys j with i - window <= j <= i.
``padding_mask`` is the (batch, past_len + query_len) attention mask when it contains padding, else None. A padding query is always allowed to see itself so that its (unused) output stays finite. """ total = past_len + query_len q_idx = torch.arange(past_len, total, device=device)[:, None] k_idx = torch.arange(total, device=device)[None, :] masks: dict[int, WindowMask] = {} for window in sorted(set(window_sizes)): if padding_mask is None and window >= total - 1: if query_len == 1: masks[window] = WindowMask(mask=None, is_causal=False) continue if past_len == 0: masks[window] = WindowMask(mask=None, is_causal=True) continue allowed = (k_idx <= q_idx) & (q_idx - k_idx <= window) if padding_mask is not None: allowed = (allowed & padding_mask[:, None, None, :].bool()) | (k_idx == q_idx) masks[window] = WindowMask(mask=allowed, is_causal=False) return masks
class WildAIAttention(nn.Module): def __init__(self, config: WildAIConfig, layer_idx: int) -> None: super().__init__() self.layer_idx = layer_idx self.num_heads = config.num_attention_heads self.num_kv_heads = config.num_key_value_heads self.head_dim = config.head_dim self.qk_scale = config.qk_scale self.window = config.window_sizes[layer_idx] hidden, kv_dim = config.hidden_size, config.num_key_value_heads * config.head_dim self.q_proj = nn.Linear(hidden, config.num_attention_heads * config.head_dim, bias=False) self.k_proj = nn.Linear(hidden, kv_dim, bias=False) self.v_proj = nn.Linear(hidden, kv_dim, bias=False) self.o_proj = nn.Linear(hidden, hidden, bias=False) self.value_embed: nn.Embedding | None = None self.value_embed_gate: nn.Linear | None = None if config.has_value_embedding(layer_idx): self.value_embed = nn.Embedding(config.vocab_size, kv_dim) self.value_embed_gate = nn.Linear(config.value_embed_gate_channels, config.num_key_value_heads, bias=False) self.gate_channels = config.value_embed_gate_channels self.gate_range = config.value_embed_gate_range
def forward( self, x: torch.Tensor, input_ids: torch.LongTensor, rotary: tuple[torch.Tensor, torch.Tensor], mask: WindowMask, past_key_values: Cache | None, ) -> torch.Tensor: batch, time, _ = x.shape q = self.q_proj(x).view(batch, time, self.num_heads, self.head_dim) k = self.k_proj(x).view(batch, time, self.num_kv_heads, self.head_dim) v = self.v_proj(x).view(batch, time, self.num_kv_heads, self.head_dim) if self.value_embed is not None: ve = self.value_embed(input_ids).to(x.dtype).view(batch, time, self.num_kv_heads, self.head_dim) gate = self.gate_range * torch.sigmoid(self.value_embed_gate(x[..., : self.gate_channels])) v = v + gate.unsqueeze(-1) * ve cos, sin = rotary q, k = apply_rotary(q, cos, sin), apply_rotary(k, cos, sin) q, k = rms_norm(q) * self.qk_scale, rms_norm(k) * self.qk_scale q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) if past_key_values is not None: k, v = past_key_values.update(k, v, self.layer_idx) y = F.scaled_dot_product_attention( q, k, v, attn_mask=mask.mask, is_causal=mask.is_causal, enable_gqa=self.num_kv_heads != self.num_heads ) return self.o_proj(y.transpose(1, 2).reshape(batch, time, -1))
class WildAIMLP(nn.Module): def __init__(self, config: WildAIConfig) -> None: super().__init__() self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.down_proj(F.relu(self.up_proj(x)).square())
class WildAIDecoderLayer(nn.Module): def __init__(self, config: WildAIConfig, layer_idx: int) -> None: super().__init__() self.self_attn = WildAIAttention(config, layer_idx) self.mlp = WildAIMLP(config)
def forward( self, x: torch.Tensor, input_ids: torch.LongTensor, rotary: tuple[torch.Tensor, torch.Tensor], mask: WindowMask, past_key_values: Cache | None, ) -> torch.Tensor: x = x + self.self_attn(rms_norm(x), input_ids, rotary, mask, past_key_values) return x + self.mlp(rms_norm(x))
class WildAIPreTrainedModel(PreTrainedModel): config_class = WildAIConfig base_model_prefix = "model" main_input_name = "input_ids" _no_split_modules: ClassVar[list[str]] = ["WildAIDecoderLayer"] _supports_sdpa = True
def _init_weights(self, module: nn.Module) -> None: # Released models are always loaded from trained weights; this only gives from_config() models sane values. if isinstance(module, (nn.Linear, nn.Embedding)): nn.init.normal_(module.weight, mean=0.0, std=0.02) elif isinstance(module, WildAIModel): with torch.no_grad(): module.resid_lambdas.fill_(1.0) module.x0_lambdas.zero_() module.smear_lambda.zero_() module.backout_lambda.zero_()
class WildAIModel(WildAIPreTrainedModel): """The transformer trunk; returns the final normalised hidden states."""
def __init__(self, config: WildAIConfig) -> None: super().__init__(config) n_layer = config.num_hidden_layers self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) self.layers = nn.ModuleList([WildAIDecoderLayer(config, i) for i in range(n_layer)]) self.resid_lambdas = nn.Parameter(torch.ones(n_layer)) self.x0_lambdas = nn.Parameter(torch.zeros(n_layer)) self.smear_gate = nn.Linear(config.smear_channels, 1, bias=False) self.smear_lambda = nn.Parameter(torch.zeros(1)) self.backout_lambda = nn.Parameter(torch.zeros(1)) self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.embed_tokens
def set_input_embeddings(self, value: nn.Embedding) -> None: self.embed_tokens = value
def rotary(self, position_ids: torch.LongTensor, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]: """cos/sin tables of shape (batch, time, 1, head_dim / 2), computed in float32 and cast like in training.""" head_dim = self.config.head_dim channels = torch.arange(0, head_dim, 2, dtype=torch.float32, device=position_ids.device) inv_freq = 1.0 / (self.config.rotary_base ** (channels / head_dim)) freqs = position_ids.to(torch.float32)[..., None] * inv_freq return freqs.cos().to(dtype)[:, :, None, :], freqs.sin().to(dtype)[:, :, None, :]
def smear(self, x: torch.Tensor, previous: torch.Tensor | None, padding_mask: torch.Tensor | None) -> torch.Tensor: """Add a gated copy of the previous position's embedding to every position that has one.
``previous`` is the normalised embedding of the token just before this chunk (None at the start of a sequence); with left padding, the first real token has a padding token before it and gets nothing. """ channels = self.config.smear_channels lam = self.smear_lambda.to(x.dtype) first = x[:, :1] if previous is not None: first = first + lam * torch.sigmoid(self.smear_gate(first[..., :channels])) * previous if x.size(1) == 1: return first gate = lam * torch.sigmoid(self.smear_gate(x[:, 1:, :channels])) if padding_mask is not None: gate = gate * padding_mask[:, -x.size(1) : -1, None].to(gate.dtype) return torch.cat([first, x[:, 1:] + gate * x[:, :-1]], dim=1)
def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, use_cache: bool | None = None, previous_token_ids: torch.LongTensor | None = None, output_hidden_states: bool | None = None, **kwargs: object, ) -> BaseModelOutputWithPast: """``previous_token_ids`` (batch, 1): the token before ``input_ids[:, 0]``; required when continuing from a cache.""" if input_ids is None: raise ValueError("input_ids are required: the value embeddings are looked up by token id") batch, time = input_ids.shape use_cache = self.config.use_cache if use_cache is None else use_cache if use_cache and past_key_values is None: past_key_values = DynamicCache() past_len = past_key_values.get_seq_length() if past_key_values is not None else 0 if past_len > 0 and previous_token_ids is None: raise ValueError("previous_token_ids is required when continuing from past_key_values (the smear needs it)") padding_mask = None if attention_mask is not None: if attention_mask.shape != (batch, past_len + time): raise ValueError(f"attention_mask must have shape {(batch, past_len + time)}, got {tuple(attention_mask.shape)}") if not bool(attention_mask.all()): padding_mask = attention_mask if position_ids is None: position_ids = torch.arange(past_len, past_len + time, device=input_ids.device).expand(batch, -1)
x = rms_norm(self.embed_tokens(input_ids)) previous = rms_norm(self.embed_tokens(previous_token_ids)) if previous_token_ids is not None else None x = self.smear(x, previous, padding_mask) rotary = self.rotary(position_ids, x.dtype) masks = window_masks(self.config.window_sizes, time, past_len, padding_mask, input_ids.device)
x0 = x backout = None hidden_states: tuple[torch.Tensor, ...] = (x,) for i, layer in enumerate(self.layers): x = self.resid_lambdas[i] * x + self.x0_lambdas[i] * x0 x = layer(x, input_ids, rotary, masks[layer.self_attn.window], past_key_values) if i == self.config.backout_layer: backout = x hidden_states += (x,) x = rms_norm(x - self.backout_lambda.to(x.dtype) * backout) return BaseModelOutputWithPast( last_hidden_state=x, past_key_values=past_key_values if use_cache else None, hidden_states=hidden_states if output_hidden_states else None, )
class WildAIForCausalLM(WildAIPreTrainedModel, GenerationMixin): def __init__(self, config: WildAIConfig) -> None: super().__init__(config) self.model = WildAIModel(config) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.model.embed_tokens
def set_input_embeddings(self, value: nn.Embedding) -> None: self.model.embed_tokens = value
def get_output_embeddings(self) -> nn.Linear: return self.lm_head
def set_output_embeddings(self, value: nn.Linear) -> None: self.lm_head = value
def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, previous_token_ids: torch.LongTensor | None = None, output_hidden_states: bool | None = None, logits_to_keep: int = 0, return_dict: bool | None = None, **kwargs: object, ) -> CausalLMOutputWithPast | tuple[torch.Tensor, ...]: """Float32 logits after the soft cap. ``labels`` are shifted inside (standard causal-LM loss, -100 ignored).""" outputs = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, previous_token_ids=previous_token_ids, output_hidden_states=output_hidden_states, ) hidden = outputs.last_hidden_state[:, -logits_to_keep:] if logits_to_keep else outputs.last_hidden_state logits = self.lm_head(hidden).float() cap = self.config.logit_softcap logits = cap * torch.tanh(logits / cap) loss = None if labels is not None: loss = F.cross_entropy(logits[:, :-1].flatten(0, 1), labels[:, 1:].flatten().to(logits.device), ignore_index=-100) result = CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states ) return result.to_tuple() if return_dict is False else result
def prepare_inputs_for_generation(self, input_ids: torch.LongTensor, **kwargs: object) -> dict[str, object]: # The smear mixes in the embedding of the token before the first new one; take it from the full sequence. model_inputs = super().prepare_inputs_for_generation(input_ids, **kwargs) new_len = model_inputs["input_ids"].shape[1] if input_ids.shape[1] > new_len: model_inputs["previous_token_ids"] = input_ids[:, -new_len - 1 : -new_len] return model_inputs123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438Attribution-NonCommercial-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm anddoes not provide legal services or legal advice. Distribution ofCreative Commons public licenses does not create a lawyer-client orother relationship. Creative Commons makes its licenses and relatedinformation available on an "as-is" basis. Creative Commons gives nowarranties regarding its licenses, any material licensed under theirterms and conditions, or any related information. Creative Commonsdisclaims all liability for damages resulting from their use to thefullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms andconditions that creators and other rights holders may use to shareoriginal works of authorship and other material subject to copyrightand certain other rights specified in the public license below. Thefollowing considerations are for informational purposes only, are notexhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public: wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 InternationalPublic License
By exercising the Licensed Rights (defined below), You accept and agreeto be bound by the terms and conditions of this Creative CommonsAttribution-NonCommercial-ShareAlike 4.0 International Public License("Public License"). To the extent this Public License may beinterpreted as a contract, You are granted the Licensed Rights inconsideration of Your acceptance of these terms and conditions, and theLicensor grants You such rights in consideration of benefits theLicensor receives from making the Licensed Material available underthese terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
k. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
l. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
m. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
b. Additional offer from the Licensor -- Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to thefollowing conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
a. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights thatapply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does notreplace Your obligations under this Public License where the LicensedRights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its publiclicenses. Notwithstanding, Creative Commons may elect to apply one ofits public licenses to material it publishes and in those instanceswill be considered the “Licensor.” The text of the Creative Commonspublic licenses is dedicated to the public domain under the CC0 PublicDomain Dedication. Except for the limited purpose of indicating thatmaterial is shared under a Creative Commons public license or asotherwise permitted by the Creative Commons policies published atcreativecommons.org/policies, Creative Commons does not authorize theuse of the trademark "Creative Commons" or any other trademark or logoof Creative Commons without its prior written consent including,without limitation, in connection with any unauthorized modificationsto any of its public licenses or any other arrangements,understandings, or agreements concerning use of licensed material. Forthe avoidance of doubt, this paragraph does not form part of thepublic licenses.
Creative Commons may be contacted at creativecommons.org.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105---license: cc-by-nc-sa-4.0library_name: transformerspipeline_tag: text-generationlanguage:- endatasets:- pangram/WildAItags:- wildai- nanochat- scaling-laws- ai-generated-text- pretraining-data---
# 268m-g079-human-r0.025
> **License: [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/).** The WildAI code, models and dataset are released under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license: you may use and adapt them for non-commercial purposes, with attribution, and must share adaptations under the same license.
A 268M decoder-only language model trained from scratch for [*How Much Is an AI Token Worth? Scaling Laws for Wild AI-Generated Web Text*](https://arxiv.org/abs/2609.40295), one of the paper's models measuring how wild AI-generated web text in pretraining data changes a model's loss. It is a research artifact for studying scaling laws, not an assistant: it has had no instruction tuning or safety training.
## Training data
The human documents of `268m-g079-control` plus fresh human-written web documents (0.025 times the control's tokens): 4.82B human tokens, the human-text counterpart of adding AI text. No AI text.
| | ||---|---|| Parameters (N, input embedding included, value embeddings excluded) | 268.4M || Layers / width | 16 / 1024 || Training tokens | 4.82B (9,184 optimizer steps) || Human / AI tokens | 4.82B / 0.0M || Group / arm / seed | g079 / human / 314159 || Used in the paper for | fitting the scaling laws (726 models, 19.9M to 268M) |
## Held-out loss
| Set | Bits per byte | Text ||---|---|---|| C4 | 0.9393 | C4 validation text (human-written, pre-2022) || FW22 | 0.9206 | held-out FineWeb documents crawled before 2022 || Paloma | 1.3112 | macro average over 16 Paloma sources || FW26 | 0.8082 | held-out 2026 FineWeb-style crawl (22.3% AI tokens) || FW26-H | 0.8528 | the human-labeled documents of FW26 || FW26-AI | 0.6437 | the AI-labeled documents of FW26 || Cosmo | 0.6380 | Cosmopedia (AI-generated textbooks and stories) |
<details><summary>Paloma sources</summary>
| Source | Bits per byte ||---|---|| 4chan | 1.3404 || c4 | 0.9582 || c4_100_domains | 0.9346 || dolma | 1.2056 || falcon_refinedweb | 1.0538 || gab | 1.8039 || m2d2_s2orc | 1.1209 || m2d2_wikipedia | 1.0253 || manosphere | 1.3476 || mc4_en | 1.0449 || programming | 1.9894 || ptb | 1.1664 || reddit_100 | 1.1888 || redpajama | 1.3654 || twitteraae | 2.4218 || wikitext_103 | 1.0116 |
</details>
## Usage
```pythonimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("pangram/WildAI-models", subfolder="268m-g079-human-r0.025", trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained("pangram/WildAI-models", subfolder="268m-g079-human-r0.025", trust_remote_code=True, dtype=torch.bfloat16)
inputs = tokenizer("The history of the printing press", return_tensors="pt")output = model.generate(**inputs, max_new_tokens=40, do_sample=False)print(tokenizer.decode(output[0], skip_special_tokens=True))```
The tokenizer prepends `<|bos|>` to every text, as in training; pass `add_special_tokens=False` to skip it. The model predicts `<|bos|>` where a document ends, and generation stops there. Weights are stored in bfloat16, the precision the paper's losses were computed in; `dtype=torch.float32` computes in float32 instead.
## Architecture
The nanochat GPT recipe: rotary embeddings, RMSNorm without weights (also on queries and keys), squared-ReLU MLP, attention windows in a repeating short-short-short-long pattern (512 tokens, then the full 2,048-token context; the last layer always full), gated value embeddings on alternating layers, a previous-token smear, per-layer residual scalars, a mid-network backout, untied input and output embeddings and logits soft-capped at 15. Vocabulary 32,768 tokens, context 2,048. The code ships with the weights (`trust_remote_code=True`) and matches the training code's forward pass.
## License
**License: [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/).** The WildAI code, models and dataset are released under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license: you may use and adapt them for non-commercial purposes, with attribution, and must share adaptations under the same license. The full text is in `LICENSE`.
## Citation
```bibtex@article{russell2026wildai, title = {How Much Is an AI Token Worth? Scaling Laws for Wild AI-Generated Web Text}, author = {Russell, Jenna and Glickenhaus, Ben and Thai, Katherine and Wieting, John and Iyyer, Mohit and Spero, Max and Emi, Bradley}, journal = {arXiv preprint arXiv:2609.40295}, year = {2026}, url = {https://arxiv.org/abs/2609.40295}}```12345678910111213141516171819202122232425262728293031323334353637383940414243444546{ "architectures": [ "WildAIForCausalLM" ], "auto_map": { "AutoConfig": "configuration_wildai.WildAIConfig", "AutoModelForCausalLM": "modeling_wildai.WildAIForCausalLM" }, "bos_token_id": 32759, "dtype": "bfloat16", "eos_token_id": 32759, "hidden_size": 1024, "logit_softcap": 15.0, "max_position_embeddings": 2048, "model_type": "wildai", "num_attention_heads": 8, "num_hidden_layers": 16, "num_key_value_heads": 8, "pad_token_id": 32759, "qk_scale": 1.2, "release": { "added_ratio": 0.025, "ai_ratio": 0.0, "ai_tokens": 0, "arm": "human", "depth": 16, "group": "g079", "human_tokens": 4815060992, "n_params": 268436282, "name": "268m-g079-human-r0.025", "seed": 314159, "size": "268m", "split": "fit", "steps": 9184, "total_tokens": 4815060992 }, "rotary_base": 100000.0, "smear_channels": 24, "tie_word_embeddings": false, "transformers_version": "5.17.0", "use_cache": true, "value_embed_gate_channels": 12, "value_embed_gate_range": 3.0, "vocab_size": 32768, "window_pattern": "SSSL"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Configuration of the WildAI language models (a nanochat GPT variant) for Hugging Face ``transformers``.
This file is copied verbatim into every released model repository and loaded with ``trust_remote_code=True``.It depends only on ``transformers``."""
from __future__ import annotations
from typing import ClassVar
from transformers import PretrainedConfig
class WildAIConfig(PretrainedConfig): """Architecture of a WildAI model. Only width and depth vary across the released models.
Every layer uses causal attention limited to a left window: a query attends to itself and the ``window`` tokens before it. ``window_pattern`` is tiled over the layers ("S" = a quarter of the context rounded up to a multiple of 128 tokens, "L" = the full context) and the last layer always uses "L".
``release`` holds the model's entry in the release catalog (name, token counts, AI ratio, ...); it does not affect the forward pass. """
model_type = "wildai" keys_to_ignore_at_inference: ClassVar[list[str]] = ["past_key_values"]
def __init__( self, vocab_size: int = 32768, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 6, num_key_value_heads: int = 6, max_position_embeddings: int = 2048, window_pattern: str = "SSSL", rotary_base: float = 100000.0, qk_scale: float = 1.2, logit_softcap: float = 15.0, value_embed_gate_channels: int = 12, value_embed_gate_range: float = 3.0, smear_channels: int = 24, bos_token_id: int = 32759, eos_token_id: int = 32759, use_cache: bool = True, release: dict[str, str | int | float | None] | None = None, **kwargs: object, ) -> None: if hidden_size % num_attention_heads != 0 or num_attention_heads % num_key_value_heads != 0: raise ValueError("hidden_size must divide into num_attention_heads, and those into num_key_value_heads") if not window_pattern or set(window_pattern.upper()) - {"S", "L"}: raise ValueError(f"window_pattern must be a non-empty string of S and L, got {window_pattern!r}") self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.max_position_embeddings = max_position_embeddings self.window_pattern = window_pattern.upper() self.rotary_base = rotary_base self.qk_scale = qk_scale self.logit_softcap = logit_softcap self.value_embed_gate_channels = value_embed_gate_channels self.value_embed_gate_range = value_embed_gate_range self.smear_channels = smear_channels self.use_cache = use_cache self.release = release kwargs.setdefault("tie_word_embeddings", False) super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
@property def head_dim(self) -> int: return self.hidden_size // self.num_attention_heads
@property def intermediate_size(self) -> int: return 4 * self.hidden_size
@property def window_sizes(self) -> list[int]: """Left attention window of each layer, in tokens.""" long_window = self.max_position_embeddings short_window = -(-long_window // 4 // 128) * 128 # a quarter of the context, rounded up to a multiple of 128 (2048 -> 512) pattern = self.window_pattern sizes = [short_window if pattern[i % len(pattern)] == "S" else long_window for i in range(self.num_hidden_layers)] sizes[-1] = long_window return sizes
def has_value_embedding(self, layer_idx: int) -> bool: """Value embeddings sit on alternating layers, always including the last one.""" return layer_idx % 2 == (self.num_hidden_layers - 1) % 2
@property def backout_layer(self) -> int: """The residual stream after this layer is partly subtracted before the final norm.""" return self.num_hidden_layers // 212345678910{ "_from_model_config": true, "bos_token_id": 32759, "eos_token_id": 32759, "output_attentions": false, "output_hidden_states": false, "pad_token_id": 32759, "transformers_version": "5.17.0", "use_cache": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340"""The WildAI language models (a nanochat GPT variant) for Hugging Face ``transformers``.
This file is copied verbatim into every released model repository and loaded with ``trust_remote_code=True``.It depends only on ``torch`` and ``transformers`` and reproduces the training code's forward pass operation byoperation, so a model loaded in bfloat16 computes the same function the paper evaluated:
- token embedding followed by a parameter-free RMSNorm, then a learned "smear" that mixes each position's embedding with the previous token's;- per-layer scalars that rescale the residual stream and blend the initial embedding back in before every block;- attention with rotary embeddings applied before a per-head RMSNorm of queries and keys (both scaled by 1.2), a left sliding window per layer, and gated value embeddings added to the values on alternating layers;- a squared-ReLU MLP, parameter-free pre-norms, no biases;- "backout": part of the residual stream after the middle layer is subtracted before the final norm;- untied output head with logits soft-capped by ``15 * tanh(logits / 15)``.
Attention uses PyTorch's scaled_dot_product_attention with explicit window masks, so no FlashAttention install isneeded. Generation uses the standard ``DynamicCache``."""
from __future__ import annotations
from dataclasses import dataclassfrom typing import ClassVar
import torchimport torch.nn.functional as Ffrom torch import nnfrom transformers import GenerationMixin, PreTrainedModelfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from .configuration_wildai import WildAIConfig
def rms_norm(x: torch.Tensor) -> torch.Tensor: """Parameter-free RMSNorm over the last dimension with PyTorch's default epsilon, as in training.""" return F.rms_norm(x, (x.size(-1),))
def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: """Rotate channel pairs (i, i + d/2) of ``x`` (batch, time, heads, head_dim), with the training code's sign convention.""" d = x.shape[-1] // 2 x1, x2 = x[..., :d], x[..., d:] return torch.cat([x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos], dim=-1)
@dataclass(frozen=True)class WindowMask: """Arguments for scaled_dot_product_attention that implement one attention window."""
mask: torch.Tensor | None is_causal: bool
def window_masks( window_sizes: list[int], query_len: int, past_len: int, padding_mask: torch.Tensor | None, device: torch.device) -> dict[int, WindowMask]: """Masks for each distinct left window. Query i (absolute index past_len + i) sees keys j with i - window <= j <= i.
``padding_mask`` is the (batch, past_len + query_len) attention mask when it contains padding, else None. A padding query is always allowed to see itself so that its (unused) output stays finite. """ total = past_len + query_len q_idx = torch.arange(past_len, total, device=device)[:, None] k_idx = torch.arange(total, device=device)[None, :] masks: dict[int, WindowMask] = {} for window in sorted(set(window_sizes)): if padding_mask is None and window >= total - 1: if query_len == 1: masks[window] = WindowMask(mask=None, is_causal=False) continue if past_len == 0: masks[window] = WindowMask(mask=None, is_causal=True) continue allowed = (k_idx <= q_idx) & (q_idx - k_idx <= window) if padding_mask is not None: allowed = (allowed & padding_mask[:, None, None, :].bool()) | (k_idx == q_idx) masks[window] = WindowMask(mask=allowed, is_causal=False) return masks
class WildAIAttention(nn.Module): def __init__(self, config: WildAIConfig, layer_idx: int) -> None: super().__init__() self.layer_idx = layer_idx self.num_heads = config.num_attention_heads self.num_kv_heads = config.num_key_value_heads self.head_dim = config.head_dim self.qk_scale = config.qk_scale self.window = config.window_sizes[layer_idx] hidden, kv_dim = config.hidden_size, config.num_key_value_heads * config.head_dim self.q_proj = nn.Linear(hidden, config.num_attention_heads * config.head_dim, bias=False) self.k_proj = nn.Linear(hidden, kv_dim, bias=False) self.v_proj = nn.Linear(hidden, kv_dim, bias=False) self.o_proj = nn.Linear(hidden, hidden, bias=False) self.value_embed: nn.Embedding | None = None self.value_embed_gate: nn.Linear | None = None if config.has_value_embedding(layer_idx): self.value_embed = nn.Embedding(config.vocab_size, kv_dim) self.value_embed_gate = nn.Linear(config.value_embed_gate_channels, config.num_key_value_heads, bias=False) self.gate_channels = config.value_embed_gate_channels self.gate_range = config.value_embed_gate_range
def forward( self, x: torch.Tensor, input_ids: torch.LongTensor, rotary: tuple[torch.Tensor, torch.Tensor], mask: WindowMask, past_key_values: Cache | None, ) -> torch.Tensor: batch, time, _ = x.shape q = self.q_proj(x).view(batch, time, self.num_heads, self.head_dim) k = self.k_proj(x).view(batch, time, self.num_kv_heads, self.head_dim) v = self.v_proj(x).view(batch, time, self.num_kv_heads, self.head_dim) if self.value_embed is not None: ve = self.value_embed(input_ids).to(x.dtype).view(batch, time, self.num_kv_heads, self.head_dim) gate = self.gate_range * torch.sigmoid(self.value_embed_gate(x[..., : self.gate_channels])) v = v + gate.unsqueeze(-1) * ve cos, sin = rotary q, k = apply_rotary(q, cos, sin), apply_rotary(k, cos, sin) q, k = rms_norm(q) * self.qk_scale, rms_norm(k) * self.qk_scale q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) if past_key_values is not None: k, v = past_key_values.update(k, v, self.layer_idx) y = F.scaled_dot_product_attention( q, k, v, attn_mask=mask.mask, is_causal=mask.is_causal, enable_gqa=self.num_kv_heads != self.num_heads ) return self.o_proj(y.transpose(1, 2).reshape(batch, time, -1))
class WildAIMLP(nn.Module): def __init__(self, config: WildAIConfig) -> None: super().__init__() self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.down_proj(F.relu(self.up_proj(x)).square())
class WildAIDecoderLayer(nn.Module): def __init__(self, config: WildAIConfig, layer_idx: int) -> None: super().__init__() self.self_attn = WildAIAttention(config, layer_idx) self.mlp = WildAIMLP(config)
def forward( self, x: torch.Tensor, input_ids: torch.LongTensor, rotary: tuple[torch.Tensor, torch.Tensor], mask: WindowMask, past_key_values: Cache | None, ) -> torch.Tensor: x = x + self.self_attn(rms_norm(x), input_ids, rotary, mask, past_key_values) return x + self.mlp(rms_norm(x))
class WildAIPreTrainedModel(PreTrainedModel): config_class = WildAIConfig base_model_prefix = "model" main_input_name = "input_ids" _no_split_modules: ClassVar[list[str]] = ["WildAIDecoderLayer"] _supports_sdpa = True
def _init_weights(self, module: nn.Module) -> None: # Released models are always loaded from trained weights; this only gives from_config() models sane values. if isinstance(module, (nn.Linear, nn.Embedding)): nn.init.normal_(module.weight, mean=0.0, std=0.02) elif isinstance(module, WildAIModel): with torch.no_grad(): module.resid_lambdas.fill_(1.0) module.x0_lambdas.zero_() module.smear_lambda.zero_() module.backout_lambda.zero_()
class WildAIModel(WildAIPreTrainedModel): """The transformer trunk; returns the final normalised hidden states."""
def __init__(self, config: WildAIConfig) -> None: super().__init__(config) n_layer = config.num_hidden_layers self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) self.layers = nn.ModuleList([WildAIDecoderLayer(config, i) for i in range(n_layer)]) self.resid_lambdas = nn.Parameter(torch.ones(n_layer)) self.x0_lambdas = nn.Parameter(torch.zeros(n_layer)) self.smear_gate = nn.Linear(config.smear_channels, 1, bias=False) self.smear_lambda = nn.Parameter(torch.zeros(1)) self.backout_lambda = nn.Parameter(torch.zeros(1)) self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.embed_tokens
def set_input_embeddings(self, value: nn.Embedding) -> None: self.embed_tokens = value
def rotary(self, position_ids: torch.LongTensor, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]: """cos/sin tables of shape (batch, time, 1, head_dim / 2), computed in float32 and cast like in training.""" head_dim = self.config.head_dim channels = torch.arange(0, head_dim, 2, dtype=torch.float32, device=position_ids.device) inv_freq = 1.0 / (self.config.rotary_base ** (channels / head_dim)) freqs = position_ids.to(torch.float32)[..., None] * inv_freq return freqs.cos().to(dtype)[:, :, None, :], freqs.sin().to(dtype)[:, :, None, :]
def smear(self, x: torch.Tensor, previous: torch.Tensor | None, padding_mask: torch.Tensor | None) -> torch.Tensor: """Add a gated copy of the previous position's embedding to every position that has one.
``previous`` is the normalised embedding of the token just before this chunk (None at the start of a sequence); with left padding, the first real token has a padding token before it and gets nothing. """ channels = self.config.smear_channels lam = self.smear_lambda.to(x.dtype) first = x[:, :1] if previous is not None: first = first + lam * torch.sigmoid(self.smear_gate(first[..., :channels])) * previous if x.size(1) == 1: return first gate = lam * torch.sigmoid(self.smear_gate(x[:, 1:, :channels])) if padding_mask is not None: gate = gate * padding_mask[:, -x.size(1) : -1, None].to(gate.dtype) return torch.cat([first, x[:, 1:] + gate * x[:, :-1]], dim=1)
def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, use_cache: bool | None = None, previous_token_ids: torch.LongTensor | None = None, output_hidden_states: bool | None = None, **kwargs: object, ) -> BaseModelOutputWithPast: """``previous_token_ids`` (batch, 1): the token before ``input_ids[:, 0]``; required when continuing from a cache.""" if input_ids is None: raise ValueError("input_ids are required: the value embeddings are looked up by token id") batch, time = input_ids.shape use_cache = self.config.use_cache if use_cache is None else use_cache if use_cache and past_key_values is None: past_key_values = DynamicCache() past_len = past_key_values.get_seq_length() if past_key_values is not None else 0 if past_len > 0 and previous_token_ids is None: raise ValueError("previous_token_ids is required when continuing from past_key_values (the smear needs it)") padding_mask = None if attention_mask is not None: if attention_mask.shape != (batch, past_len + time): raise ValueError(f"attention_mask must have shape {(batch, past_len + time)}, got {tuple(attention_mask.shape)}") if not bool(attention_mask.all()): padding_mask = attention_mask if position_ids is None: position_ids = torch.arange(past_len, past_len + time, device=input_ids.device).expand(batch, -1)
x = rms_norm(self.embed_tokens(input_ids)) previous = rms_norm(self.embed_tokens(previous_token_ids)) if previous_token_ids is not None else None x = self.smear(x, previous, padding_mask) rotary = self.rotary(position_ids, x.dtype) masks = window_masks(self.config.window_sizes, time, past_len, padding_mask, input_ids.device)
x0 = x backout = None hidden_states: tuple[torch.Tensor, ...] = (x,) for i, layer in enumerate(self.layers): x = self.resid_lambdas[i] * x + self.x0_lambdas[i] * x0 x = layer(x, input_ids, rotary, masks[layer.self_attn.window], past_key_values) if i == self.config.backout_layer: backout = x hidden_states += (x,) x = rms_norm(x - self.backout_lambda.to(x.dtype) * backout) return BaseModelOutputWithPast( last_hidden_state=x, past_key_values=past_key_values if use_cache else None, hidden_states=hidden_states if output_hidden_states else None, )
class WildAIForCausalLM(WildAIPreTrainedModel, GenerationMixin): def __init__(self, config: WildAIConfig) -> None: super().__init__(config) self.model = WildAIModel(config) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.model.embed_tokens
def set_input_embeddings(self, value: nn.Embedding) -> None: self.model.embed_tokens = value
def get_output_embeddings(self) -> nn.Linear: return self.lm_head
def set_output_embeddings(self, value: nn.Linear) -> None: self.lm_head = value
def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, previous_token_ids: torch.LongTensor | None = None, output_hidden_states: bool | None = None, logits_to_keep: int = 0, return_dict: bool | None = None, **kwargs: object, ) -> CausalLMOutputWithPast | tuple[torch.Tensor, ...]: """Float32 logits after the soft cap. ``labels`` are shifted inside (standard causal-LM loss, -100 ignored).""" outputs = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, previous_token_ids=previous_token_ids, output_hidden_states=output_hidden_states, ) hidden = outputs.last_hidden_state[:, -logits_to_keep:] if logits_to_keep else outputs.last_hidden_state logits = self.lm_head(hidden).float() cap = self.config.logit_softcap logits = cap * torch.tanh(logits / cap) loss = None if labels is not None: loss = F.cross_entropy(logits[:, :-1].flatten(0, 1), labels[:, 1:].flatten().to(logits.device), ignore_index=-100) result = CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states ) return result.to_tuple() if return_dict is False else result
def prepare_inputs_for_generation(self, input_ids: torch.LongTensor, **kwargs: object) -> dict[str, object]: # The smear mixes in the embedding of the token before the first new one; take it from the full sequence. model_inputs = super().prepare_inputs_for_generation(input_ids, **kwargs) new_len = model_inputs["input_ids"].shape[1] if input_ids.shape[1] > new_len: model_inputs["previous_token_ids"] = input_ids[:, -new_len - 1 : -new_len] return model_inputs1234567891011{ "tokenizer_class": "PreTrainedTokenizerFast", "bos_token": "<|bos|>", "eos_token": "<|bos|>", "model_max_length": 2048, "model_input_names": [ "input_ids", "attention_mask" ], "clean_up_tokenization_spaces": false}123version https://git-lfs.github.com/spec/v1oid sha256:a7ef07962e39d932da04148b6dee110688eca2a9b94e927be7eba2423d24dc8dsize 1073757052123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438Attribution-NonCommercial-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm anddoes not provide legal services or legal advice. Distribution ofCreative Commons public licenses does not create a lawyer-client orother relationship. Creative Commons makes its licenses and relatedinformation available on an "as-is" basis. Creative Commons gives nowarranties regarding its licenses, any material licensed under theirterms and conditions, or any related information. Creative Commonsdisclaims all liability for damages resulting from their use to thefullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms andconditions that creators and other rights holders may use to shareoriginal works of authorship and other material subject to copyrightand certain other rights specified in the public license below. Thefollowing considerations are for informational purposes only, are notexhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public: wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 InternationalPublic License
By exercising the Licensed Rights (defined below), You accept and agreeto be bound by the terms and conditions of this Creative CommonsAttribution-NonCommercial-ShareAlike 4.0 International Public License("Public License"). To the extent this Public License may beinterpreted as a contract, You are granted the Licensed Rights inconsideration of Your acceptance of these terms and conditions, and theLicensor grants You such rights in consideration of benefits theLicensor receives from making the Licensed Material available underthese terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
k. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
l. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
m. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
b. Additional offer from the Licensor -- Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to thefollowing conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
a. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights thatapply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does notreplace Your obligations under this Public License where the LicensedRights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its publiclicenses. Notwithstanding, Creative Commons may elect to apply one ofits public licenses to material it publishes and in those instanceswill be considered the “Licensor.” The text of the Creative Commonspublic licenses is dedicated to the public domain under the CC0 PublicDomain Dedication. Except for the limited purpose of indicating thatmaterial is shared under a Creative Commons public license or asotherwise permitted by the Creative Commons policies published atcreativecommons.org/policies, Creative Commons does not authorize theuse of the trademark "Creative Commons" or any other trademark or logoof Creative Commons without its prior written consent including,without limitation, in connection with any unauthorized modificationsto any of its public licenses or any other arrangements,understandings, or agreements concerning use of licensed material. Forthe avoidance of doubt, this paragraph does not form part of thepublic licenses.
Creative Commons may be contacted at creativecommons.org.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105---license: cc-by-nc-sa-4.0library_name: transformerspipeline_tag: text-generationlanguage:- endatasets:- pangram/WildAItags:- wildai- nanochat- scaling-laws- ai-generated-text- pretraining-data---
# 268m-g081-ai-r0.025
> **License: [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/).** The WildAI code, models and dataset are released under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license: you may use and adapt them for non-commercial purposes, with attribution, and must share adaptations under the same license.
A 268M decoder-only language model trained from scratch for [*How Much Is an AI Token Worth? Scaling Laws for Wild AI-Generated Web Text*](https://arxiv.org/abs/2609.40295), one of the paper's models measuring how wild AI-generated web text in pretraining data changes a model's loss. It is a research artifact for studying scaling laws, not an assistant: it has had no instruction tuning or safety training.
## Training data
The human documents of `268m-g081-control` plus wild AI-generated web documents: 5.07B human and 126.7M AI tokens trained on, an AI-to-human token ratio r = 0.025 (design 0.025), so 2.4% of the training tokens are AI-generated.
| | ||---|---|| Parameters (N, input embedding included, value embeddings excluded) | 268.4M || Layers / width | 16 / 1024 || Training tokens | 5.19B (9,908 optimizer steps) || Human / AI tokens | 5.07B / 126.7M || Group / arm / seed | g081 / ai / 1337 || Used in the paper for | fitting the scaling laws (726 models, 19.9M to 268M) |
## Held-out loss
| Set | Bits per byte | Text ||---|---|---|| C4 | 0.9375 | C4 validation text (human-written, pre-2022) || FW22 | 0.9181 | held-out FineWeb documents crawled before 2022 || Paloma | 1.3000 | macro average over 16 Paloma sources || FW26 | 0.7999 | held-out 2026 FineWeb-style crawl (22.3% AI tokens) || FW26-H | 0.8501 | the human-labeled documents of FW26 || FW26-AI | 0.6142 | the AI-labeled documents of FW26 || Cosmo | 0.6126 | Cosmopedia (AI-generated textbooks and stories) |
<details><summary>Paloma sources</summary>
| Source | Bits per byte ||---|---|| 4chan | 1.3203 || c4 | 0.9564 || c4_100_domains | 0.9325 || dolma | 1.1909 || falcon_refinedweb | 1.0549 || gab | 1.8093 || m2d2_s2orc | 1.1164 || m2d2_wikipedia | 1.0203 || manosphere | 1.3363 || mc4_en | 1.0373 || programming | 1.8801 || ptb | 1.1674 || reddit_100 | 1.1850 || redpajama | 1.3585 || twitteraae | 2.4313 || wikitext_103 | 1.0031 |
</details>
## Usage
```pythonimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("pangram/WildAI-models", subfolder="268m-g081-ai-r0.025", trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained("pangram/WildAI-models", subfolder="268m-g081-ai-r0.025", trust_remote_code=True, dtype=torch.bfloat16)
inputs = tokenizer("The history of the printing press", return_tensors="pt")output = model.generate(**inputs, max_new_tokens=40, do_sample=False)print(tokenizer.decode(output[0], skip_special_tokens=True))```
The tokenizer prepends `<|bos|>` to every text, as in training; pass `add_special_tokens=False` to skip it. The model predicts `<|bos|>` where a document ends, and generation stops there. Weights are stored in bfloat16, the precision the paper's losses were computed in; `dtype=torch.float32` computes in float32 instead.
## Architecture
The nanochat GPT recipe: rotary embeddings, RMSNorm without weights (also on queries and keys), squared-ReLU MLP, attention windows in a repeating short-short-short-long pattern (512 tokens, then the full 2,048-token context; the last layer always full), gated value embeddings on alternating layers, a previous-token smear, per-layer residual scalars, a mid-network backout, untied input and output embeddings and logits soft-capped at 15. Vocabulary 32,768 tokens, context 2,048. The code ships with the weights (`trust_remote_code=True`) and matches the training code's forward pass.
## License
**License: [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/).** The WildAI code, models and dataset are released under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license: you may use and adapt them for non-commercial purposes, with attribution, and must share adaptations under the same license. The full text is in `LICENSE`.
## Citation
```bibtex@article{russell2026wildai, title = {How Much Is an AI Token Worth? Scaling Laws for Wild AI-Generated Web Text}, author = {Russell, Jenna and Glickenhaus, Ben and Thai, Katherine and Wieting, John and Iyyer, Mohit and Spero, Max and Emi, Bradley}, journal = {arXiv preprint arXiv:2609.40295}, year = {2026}, url = {https://arxiv.org/abs/2609.40295}}```12345678910111213141516171819202122232425262728293031323334353637383940414243444546{ "architectures": [ "WildAIForCausalLM" ], "auto_map": { "AutoConfig": "configuration_wildai.WildAIConfig", "AutoModelForCausalLM": "modeling_wildai.WildAIForCausalLM" }, "bos_token_id": 32759, "dtype": "bfloat16", "eos_token_id": 32759, "hidden_size": 1024, "logit_softcap": 15.0, "max_position_embeddings": 2048, "model_type": "wildai", "num_attention_heads": 8, "num_hidden_layers": 16, "num_key_value_heads": 8, "pad_token_id": 32759, "qk_scale": 1.2, "release": { "added_ratio": 0.025, "ai_ratio": 0.024998866618210925, "ai_tokens": 126693067, "arm": "ai", "depth": 16, "group": "g081", "human_tokens": 5067952437, "n_params": 268436282, "name": "268m-g081-ai-r0.025", "seed": 1337, "size": "268m", "split": "fit", "steps": 9908, "total_tokens": 5194645504 }, "rotary_base": 100000.0, "smear_channels": 24, "tie_word_embeddings": false, "transformers_version": "5.17.0", "use_cache": true, "value_embed_gate_channels": 12, "value_embed_gate_range": 3.0, "vocab_size": 32768, "window_pattern": "SSSL"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Configuration of the WildAI language models (a nanochat GPT variant) for Hugging Face ``transformers``.
This file is copied verbatim into every released model repository and loaded with ``trust_remote_code=True``.It depends only on ``transformers``."""
from __future__ import annotations
from typing import ClassVar
from transformers import PretrainedConfig
class WildAIConfig(PretrainedConfig): """Architecture of a WildAI model. Only width and depth vary across the released models.
Every layer uses causal attention limited to a left window: a query attends to itself and the ``window`` tokens before it. ``window_pattern`` is tiled over the layers ("S" = a quarter of the context rounded up to a multiple of 128 tokens, "L" = the full context) and the last layer always uses "L".
``release`` holds the model's entry in the release catalog (name, token counts, AI ratio, ...); it does not affect the forward pass. """
model_type = "wildai" keys_to_ignore_at_inference: ClassVar[list[str]] = ["past_key_values"]
def __init__( self, vocab_size: int = 32768, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 6, num_key_value_heads: int = 6, max_position_embeddings: int = 2048, window_pattern: str = "SSSL", rotary_base: float = 100000.0, qk_scale: float = 1.2, logit_softcap: float = 15.0, value_embed_gate_channels: int = 12, value_embed_gate_range: float = 3.0, smear_channels: int = 24, bos_token_id: int = 32759, eos_token_id: int = 32759, use_cache: bool = True, release: dict[str, str | int | float | None] | None = None, **kwargs: object, ) -> None: if hidden_size % num_attention_heads != 0 or num_attention_heads % num_key_value_heads != 0: raise ValueError("hidden_size must divide into num_attention_heads, and those into num_key_value_heads") if not window_pattern or set(window_pattern.upper()) - {"S", "L"}: raise ValueError(f"window_pattern must be a non-empty string of S and L, got {window_pattern!r}") self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.max_position_embeddings = max_position_embeddings self.window_pattern = window_pattern.upper() self.rotary_base = rotary_base self.qk_scale = qk_scale self.logit_softcap = logit_softcap self.value_embed_gate_channels = value_embed_gate_channels self.value_embed_gate_range = value_embed_gate_range self.smear_channels = smear_channels self.use_cache = use_cache self.release = release kwargs.setdefault("tie_word_embeddings", False) super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
@property def head_dim(self) -> int: return self.hidden_size // self.num_attention_heads
@property def intermediate_size(self) -> int: return 4 * self.hidden_size
@property def window_sizes(self) -> list[int]: """Left attention window of each layer, in tokens.""" long_window = self.max_position_embeddings short_window = -(-long_window // 4 // 128) * 128 # a quarter of the context, rounded up to a multiple of 128 (2048 -> 512) pattern = self.window_pattern sizes = [short_window if pattern[i % len(pattern)] == "S" else long_window for i in range(self.num_hidden_layers)] sizes[-1] = long_window return sizes
def has_value_embedding(self, layer_idx: int) -> bool: """Value embeddings sit on alternating layers, always including the last one.""" return layer_idx % 2 == (self.num_hidden_layers - 1) % 2
@property def backout_layer(self) -> int: """The residual stream after this layer is partly subtracted before the final norm.""" return self.num_hidden_layers // 212345678910{ "_from_model_config": true, "bos_token_id": 32759, "eos_token_id": 32759, "output_attentions": false, "output_hidden_states": false, "pad_token_id": 32759, "transformers_version": "5.17.0", "use_cache": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340"""The WildAI language models (a nanochat GPT variant) for Hugging Face ``transformers``.
This file is copied verbatim into every released model repository and loaded with ``trust_remote_code=True``.It depends only on ``torch`` and ``transformers`` and reproduces the training code's forward pass operation byoperation, so a model loaded in bfloat16 computes the same function the paper evaluated:
- token embedding followed by a parameter-free RMSNorm, then a learned "smear" that mixes each position's embedding with the previous token's;- per-layer scalars that rescale the residual stream and blend the initial embedding back in before every block;- attention with rotary embeddings applied before a per-head RMSNorm of queries and keys (both scaled by 1.2), a left sliding window per layer, and gated value embeddings added to the values on alternating layers;- a squared-ReLU MLP, parameter-free pre-norms, no biases;- "backout": part of the residual stream after the middle layer is subtracted before the final norm;- untied output head with logits soft-capped by ``15 * tanh(logits / 15)``.
Attention uses PyTorch's scaled_dot_product_attention with explicit window masks, so no FlashAttention install isneeded. Generation uses the standard ``DynamicCache``."""
from __future__ import annotations
from dataclasses import dataclassfrom typing import ClassVar
import torchimport torch.nn.functional as Ffrom torch import nnfrom transformers import GenerationMixin, PreTrainedModelfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from .configuration_wildai import WildAIConfig
def rms_norm(x: torch.Tensor) -> torch.Tensor: """Parameter-free RMSNorm over the last dimension with PyTorch's default epsilon, as in training.""" return F.rms_norm(x, (x.size(-1),))
def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: """Rotate channel pairs (i, i + d/2) of ``x`` (batch, time, heads, head_dim), with the training code's sign convention.""" d = x.shape[-1] // 2 x1, x2 = x[..., :d], x[..., d:] return torch.cat([x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos], dim=-1)
@dataclass(frozen=True)class WindowMask: """Arguments for scaled_dot_product_attention that implement one attention window."""
mask: torch.Tensor | None is_causal: bool
def window_masks( window_sizes: list[int], query_len: int, past_len: int, padding_mask: torch.Tensor | None, device: torch.device) -> dict[int, WindowMask]: """Masks for each distinct left window. Query i (absolute index past_len + i) sees keys j with i - window <= j <= i.
``padding_mask`` is the (batch, past_len + query_len) attention mask when it contains padding, else None. A padding query is always allowed to see itself so that its (unused) output stays finite. """ total = past_len + query_len q_idx = torch.arange(past_len, total, device=device)[:, None] k_idx = torch.arange(total, device=device)[None, :] masks: dict[int, WindowMask] = {} for window in sorted(set(window_sizes)): if padding_mask is None and window >= total - 1: if query_len == 1: masks[window] = WindowMask(mask=None, is_causal=False) continue if past_len == 0: masks[window] = WindowMask(mask=None, is_causal=True) continue allowed = (k_idx <= q_idx) & (q_idx - k_idx <= window) if padding_mask is not None: allowed = (allowed & padding_mask[:, None, None, :].bool()) | (k_idx == q_idx) masks[window] = WindowMask(mask=allowed, is_causal=False) return masks
class WildAIAttention(nn.Module): def __init__(self, config: WildAIConfig, layer_idx: int) -> None: super().__init__() self.layer_idx = layer_idx self.num_heads = config.num_attention_heads self.num_kv_heads = config.num_key_value_heads self.head_dim = config.head_dim self.qk_scale = config.qk_scale self.window = config.window_sizes[layer_idx] hidden, kv_dim = config.hidden_size, config.num_key_value_heads * config.head_dim self.q_proj = nn.Linear(hidden, config.num_attention_heads * config.head_dim, bias=False) self.k_proj = nn.Linear(hidden, kv_dim, bias=False) self.v_proj = nn.Linear(hidden, kv_dim, bias=False) self.o_proj = nn.Linear(hidden, hidden, bias=False) self.value_embed: nn.Embedding | None = None self.value_embed_gate: nn.Linear | None = None if config.has_value_embedding(layer_idx): self.value_embed = nn.Embedding(config.vocab_size, kv_dim) self.value_embed_gate = nn.Linear(config.value_embed_gate_channels, config.num_key_value_heads, bias=False) self.gate_channels = config.value_embed_gate_channels self.gate_range = config.value_embed_gate_range
def forward( self, x: torch.Tensor, input_ids: torch.LongTensor, rotary: tuple[torch.Tensor, torch.Tensor], mask: WindowMask, past_key_values: Cache | None, ) -> torch.Tensor: batch, time, _ = x.shape q = self.q_proj(x).view(batch, time, self.num_heads, self.head_dim) k = self.k_proj(x).view(batch, time, self.num_kv_heads, self.head_dim) v = self.v_proj(x).view(batch, time, self.num_kv_heads, self.head_dim) if self.value_embed is not None: ve = self.value_embed(input_ids).to(x.dtype).view(batch, time, self.num_kv_heads, self.head_dim) gate = self.gate_range * torch.sigmoid(self.value_embed_gate(x[..., : self.gate_channels])) v = v + gate.unsqueeze(-1) * ve cos, sin = rotary q, k = apply_rotary(q, cos, sin), apply_rotary(k, cos, sin) q, k = rms_norm(q) * self.qk_scale, rms_norm(k) * self.qk_scale q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) if past_key_values is not None: k, v = past_key_values.update(k, v, self.layer_idx) y = F.scaled_dot_product_attention( q, k, v, attn_mask=mask.mask, is_causal=mask.is_causal, enable_gqa=self.num_kv_heads != self.num_heads ) return self.o_proj(y.transpose(1, 2).reshape(batch, time, -1))
class WildAIMLP(nn.Module): def __init__(self, config: WildAIConfig) -> None: super().__init__() self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.down_proj(F.relu(self.up_proj(x)).square())
class WildAIDecoderLayer(nn.Module): def __init__(self, config: WildAIConfig, layer_idx: int) -> None: super().__init__() self.self_attn = WildAIAttention(config, layer_idx) self.mlp = WildAIMLP(config)
def forward( self, x: torch.Tensor, input_ids: torch.LongTensor, rotary: tuple[torch.Tensor, torch.Tensor], mask: WindowMask, past_key_values: Cache | None, ) -> torch.Tensor: x = x + self.self_attn(rms_norm(x), input_ids, rotary, mask, past_key_values) return x + self.mlp(rms_norm(x))
class WildAIPreTrainedModel(PreTrainedModel): config_class = WildAIConfig base_model_prefix = "model" main_input_name = "input_ids" _no_split_modules: ClassVar[list[str]] = ["WildAIDecoderLayer"] _supports_sdpa = True
def _init_weights(self, module: nn.Module) -> None: # Released models are always loaded from trained weights; this only gives from_config() models sane values. if isinstance(module, (nn.Linear, nn.Embedding)): nn.init.normal_(module.weight, mean=0.0, std=0.02) elif isinstance(module, WildAIModel): with torch.no_grad(): module.resid_lambdas.fill_(1.0) module.x0_lambdas.zero_() module.smear_lambda.zero_() module.backout_lambda.zero_()
class WildAIModel(WildAIPreTrainedModel): """The transformer trunk; returns the final normalised hidden states."""
def __init__(self, config: WildAIConfig) -> None: super().__init__(config) n_layer = config.num_hidden_layers self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) self.layers = nn.ModuleList([WildAIDecoderLayer(config, i) for i in range(n_layer)]) self.resid_lambdas = nn.Parameter(torch.ones(n_layer)) self.x0_lambdas = nn.Parameter(torch.zeros(n_layer)) self.smear_gate = nn.Linear(config.smear_channels, 1, bias=False) self.smear_lambda = nn.Parameter(torch.zeros(1)) self.backout_lambda = nn.Parameter(torch.zeros(1)) self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.embed_tokens
def set_input_embeddings(self, value: nn.Embedding) -> None: self.embed_tokens = value
def rotary(self, position_ids: torch.LongTensor, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]: """cos/sin tables of shape (batch, time, 1, head_dim / 2), computed in float32 and cast like in training.""" head_dim = self.config.head_dim channels = torch.arange(0, head_dim, 2, dtype=torch.float32, device=position_ids.device) inv_freq = 1.0 / (self.config.rotary_base ** (channels / head_dim)) freqs = position_ids.to(torch.float32)[..., None] * inv_freq return freqs.cos().to(dtype)[:, :, None, :], freqs.sin().to(dtype)[:, :, None, :]
def smear(self, x: torch.Tensor, previous: torch.Tensor | None, padding_mask: torch.Tensor | None) -> torch.Tensor: """Add a gated copy of the previous position's embedding to every position that has one.
``previous`` is the normalised embedding of the token just before this chunk (None at the start of a sequence); with left padding, the first real token has a padding token before it and gets nothing. """ channels = self.config.smear_channels lam = self.smear_lambda.to(x.dtype) first = x[:, :1] if previous is not None: first = first + lam * torch.sigmoid(self.smear_gate(first[..., :channels])) * previous if x.size(1) == 1: return first gate = lam * torch.sigmoid(self.smear_gate(x[:, 1:, :channels])) if padding_mask is not None: gate = gate * padding_mask[:, -x.size(1) : -1, None].to(gate.dtype) return torch.cat([first, x[:, 1:] + gate * x[:, :-1]], dim=1)
def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, use_cache: bool | None = None, previous_token_ids: torch.LongTensor | None = None, output_hidden_states: bool | None = None, **kwargs: object, ) -> BaseModelOutputWithPast: """``previous_token_ids`` (batch, 1): the token before ``input_ids[:, 0]``; required when continuing from a cache.""" if input_ids is None: raise ValueError("input_ids are required: the value embeddings are looked up by token id") batch, time = input_ids.shape use_cache = self.config.use_cache if use_cache is None else use_cache if use_cache and past_key_values is None: past_key_values = DynamicCache() past_len = past_key_values.get_seq_length() if past_key_values is not None else 0 if past_len > 0 and previous_token_ids is None: raise ValueError("previous_token_ids is required when continuing from past_key_values (the smear needs it)") padding_mask = None if attention_mask is not None: if attention_mask.shape != (batch, past_len + time): raise ValueError(f"attention_mask must have shape {(batch, past_len + time)}, got {tuple(attention_mask.shape)}") if not bool(attention_mask.all()): padding_mask = attention_mask if position_ids is None: position_ids = torch.arange(past_len, past_len + time, device=input_ids.device).expand(batch, -1)
x = rms_norm(self.embed_tokens(input_ids)) previous = rms_norm(self.embed_tokens(previous_token_ids)) if previous_token_ids is not None else None x = self.smear(x, previous, padding_mask) rotary = self.rotary(position_ids, x.dtype) masks = window_masks(self.config.window_sizes, time, past_len, padding_mask, input_ids.device)
x0 = x backout = None hidden_states: tuple[torch.Tensor, ...] = (x,) for i, layer in enumerate(self.layers): x = self.resid_lambdas[i] * x + self.x0_lambdas[i] * x0 x = layer(x, input_ids, rotary, masks[layer.self_attn.window], past_key_values) if i == self.config.backout_layer: backout = x hidden_states += (x,) x = rms_norm(x - self.backout_lambda.to(x.dtype) * backout) return BaseModelOutputWithPast( last_hidden_state=x, past_key_values=past_key_values if use_cache else None, hidden_states=hidden_states if output_hidden_states else None, )
class WildAIForCausalLM(WildAIPreTrainedModel, GenerationMixin): def __init__(self, config: WildAIConfig) -> None: super().__init__(config) self.model = WildAIModel(config) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.model.embed_tokens
def set_input_embeddings(self, value: nn.Embedding) -> None: self.model.embed_tokens = value
def get_output_embeddings(self) -> nn.Linear: return self.lm_head
def set_output_embeddings(self, value: nn.Linear) -> None: self.lm_head = value
def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, previous_token_ids: torch.LongTensor | None = None, output_hidden_states: bool | None = None, logits_to_keep: int = 0, return_dict: bool | None = None, **kwargs: object, ) -> CausalLMOutputWithPast | tuple[torch.Tensor, ...]: """Float32 logits after the soft cap. ``labels`` are shifted inside (standard causal-LM loss, -100 ignored).""" outputs = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, previous_token_ids=previous_token_ids, output_hidden_states=output_hidden_states, ) hidden = outputs.last_hidden_state[:, -logits_to_keep:] if logits_to_keep else outputs.last_hidden_state logits = self.lm_head(hidden).float() cap = self.config.logit_softcap logits = cap * torch.tanh(logits / cap) loss = None if labels is not None: loss = F.cross_entropy(logits[:, :-1].flatten(0, 1), labels[:, 1:].flatten().to(logits.device), ignore_index=-100) result = CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states ) return result.to_tuple() if return_dict is False else result
def prepare_inputs_for_generation(self, input_ids: torch.LongTensor, **kwargs: object) -> dict[str, object]: # The smear mixes in the embedding of the token before the first new one; take it from the full sequence. model_inputs = super().prepare_inputs_for_generation(input_ids, **kwargs) new_len = model_inputs["input_ids"].shape[1] if input_ids.shape[1] > new_len: model_inputs["previous_token_ids"] = input_ids[:, -new_len - 1 : -new_len] return model_inputs1234567891011{ "tokenizer_class": "PreTrainedTokenizerFast", "bos_token": "<|bos|>", "eos_token": "<|bos|>", "model_max_length": 2048, "model_input_names": [ "input_ids", "attention_mask" ], "clean_up_tokenization_spaces": false}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438Attribution-NonCommercial-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm anddoes not provide legal services or legal advice. Distribution ofCreative Commons public licenses does not create a lawyer-client orother relationship. Creative Commons makes its licenses and relatedinformation available on an "as-is" basis. Creative Commons gives nowarranties regarding its licenses, any material licensed under theirterms and conditions, or any related information. Creative Commonsdisclaims all liability for damages resulting from their use to thefullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms andconditions that creators and other rights holders may use to shareoriginal works of authorship and other material subject to copyrightand certain other rights specified in the public license below. Thefollowing considerations are for informational purposes only, are notexhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public: wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 InternationalPublic License
By exercising the Licensed Rights (defined below), You accept and agreeto be bound by the terms and conditions of this Creative CommonsAttribution-NonCommercial-ShareAlike 4.0 International Public License("Public License"). To the extent this Public License may beinterpreted as a contract, You are granted the Licensed Rights inconsideration of Your acceptance of these terms and conditions, and theLicensor grants You such rights in consideration of benefits theLicensor receives from making the Licensed Material available underthese terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
k. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
l. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
m. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
b. Additional offer from the Licensor -- Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to thefollowing conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
a. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights thatapply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does notreplace Your obligations under this Public License where the LicensedRights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its publiclicenses. Notwithstanding, Creative Commons may elect to apply one ofits public licenses to material it publishes and in those instanceswill be considered the “Licensor.” The text of the Creative Commonspublic licenses is dedicated to the public domain under the CC0 PublicDomain Dedication. Except for the limited purpose of indicating thatmaterial is shared under a Creative Commons public license or asotherwise permitted by the Creative Commons policies published atcreativecommons.org/policies, Creative Commons does not authorize theuse of the trademark "Creative Commons" or any other trademark or logoof Creative Commons without its prior written consent including,without limitation, in connection with any unauthorized modificationsto any of its public licenses or any other arrangements,understandings, or agreements concerning use of licensed material. Forthe avoidance of doubt, this paragraph does not form part of thepublic licenses.
Creative Commons may be contacted at creativecommons.org.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105---license: cc-by-nc-sa-4.0library_name: transformerspipeline_tag: text-generationlanguage:- endatasets:- pangram/WildAItags:- wildai- nanochat- scaling-laws- ai-generated-text- pretraining-data---
# 268m-g081-ai-r0.25
> **License: [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/).** The WildAI code, models and dataset are released under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license: you may use and adapt them for non-commercial purposes, with attribution, and must share adaptations under the same license.
A 268M decoder-only language model trained from scratch for [*How Much Is an AI Token Worth? Scaling Laws for Wild AI-Generated Web Text*](https://arxiv.org/abs/2609.40295), one of the paper's models measuring how wild AI-generated web text in pretraining data changes a model's loss. It is a research artifact for studying scaling laws, not an assistant: it has had no instruction tuning or safety training.
## Training data
The human documents of `268m-g081-control` plus wild AI-generated web documents: 5.07B human and 1.27B AI tokens trained on, an AI-to-human token ratio r = 0.251 (design 0.25), so 20.1% of the training tokens are AI-generated.
| | ||---|---|| Parameters (N, input embedding included, value embeddings excluded) | 268.4M || Layers / width | 16 / 1024 || Training tokens | 6.34B (12,097 optimizer steps) || Human / AI tokens | 5.07B / 1.27B || Group / arm / seed | g081 / ai / 1337 || Used in the paper for | fitting the scaling laws (726 models, 19.9M to 268M) |
## Held-out loss
| Set | Bits per byte | Text ||---|---|---|| C4 | 0.9374 | C4 validation text (human-written, pre-2022) || FW22 | 0.9180 | held-out FineWeb documents crawled before 2022 || Paloma | 1.3140 | macro average over 16 Paloma sources || FW26 | 0.7886 | held-out 2026 FineWeb-style crawl (22.3% AI tokens) || FW26-H | 0.8497 | the human-labeled documents of FW26 || FW26-AI | 0.5629 | the AI-labeled documents of FW26 || Cosmo | 0.5769 | Cosmopedia (AI-generated textbooks and stories) |
<details><summary>Paloma sources</summary>
| Source | Bits per byte ||---|---|| 4chan | 1.4589 || c4 | 0.9559 || c4_100_domains | 0.9331 || dolma | 1.1981 || falcon_refinedweb | 1.0509 || gab | 1.8262 || m2d2_s2orc | 1.1135 || m2d2_wikipedia | 1.0168 || manosphere | 1.3458 || mc4_en | 1.0365 || programming | 1.9210 || ptb | 1.1606 || reddit_100 | 1.1943 || redpajama | 1.3708 || twitteraae | 2.4428 || wikitext_103 | 0.9988 |
</details>
## Usage
```pythonimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("pangram/WildAI-models", subfolder="268m-g081-ai-r0.25", trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained("pangram/WildAI-models", subfolder="268m-g081-ai-r0.25", trust_remote_code=True, dtype=torch.bfloat16)
inputs = tokenizer("The history of the printing press", return_tensors="pt")output = model.generate(**inputs, max_new_tokens=40, do_sample=False)print(tokenizer.decode(output[0], skip_special_tokens=True))```
The tokenizer prepends `<|bos|>` to every text, as in training; pass `add_special_tokens=False` to skip it. The model predicts `<|bos|>` where a document ends, and generation stops there. Weights are stored in bfloat16, the precision the paper's losses were computed in; `dtype=torch.float32` computes in float32 instead.
## Architecture
The nanochat GPT recipe: rotary embeddings, RMSNorm without weights (also on queries and keys), squared-ReLU MLP, attention windows in a repeating short-short-short-long pattern (512 tokens, then the full 2,048-token context; the last layer always full), gated value embeddings on alternating layers, a previous-token smear, per-layer residual scalars, a mid-network backout, untied input and output embeddings and logits soft-capped at 15. Vocabulary 32,768 tokens, context 2,048. The code ships with the weights (`trust_remote_code=True`) and matches the training code's forward pass.
## License
**License: [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/).** The WildAI code, models and dataset are released under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license: you may use and adapt them for non-commercial purposes, with attribution, and must share adaptations under the same license. The full text is in `LICENSE`.
## Citation
```bibtex@article{russell2026wildai, title = {How Much Is an AI Token Worth? Scaling Laws for Wild AI-Generated Web Text}, author = {Russell, Jenna and Glickenhaus, Ben and Thai, Katherine and Wieting, John and Iyyer, Mohit and Spero, Max and Emi, Bradley}, journal = {arXiv preprint arXiv:2609.40295}, year = {2026}, url = {https://arxiv.org/abs/2609.40295}}```12345678910111213141516171819202122232425262728293031323334353637383940414243444546{ "architectures": [ "WildAIForCausalLM" ], "auto_map": { "AutoConfig": "configuration_wildai.WildAIConfig", "AutoModelForCausalLM": "modeling_wildai.WildAIForCausalLM" }, "bos_token_id": 32759, "dtype": "bfloat16", "eos_token_id": 32759, "hidden_size": 1024, "logit_softcap": 15.0, "max_position_embeddings": 2048, "model_type": "wildai", "num_attention_heads": 8, "num_hidden_layers": 16, "num_key_value_heads": 8, "pad_token_id": 32759, "qk_scale": 1.2, "release": { "added_ratio": 0.25, "ai_ratio": 0.25145614169844904, "ai_tokens": 1274366105, "arm": "ai", "depth": 16, "group": "g081", "human_tokens": 5067945831, "n_params": 268436282, "name": "268m-g081-ai-r0.25", "seed": 1337, "size": "268m", "split": "fit", "steps": 12097, "total_tokens": 6342311936 }, "rotary_base": 100000.0, "smear_channels": 24, "tie_word_embeddings": false, "transformers_version": "5.17.0", "use_cache": true, "value_embed_gate_channels": 12, "value_embed_gate_range": 3.0, "vocab_size": 32768, "window_pattern": "SSSL"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Configuration of the WildAI language models (a nanochat GPT variant) for Hugging Face ``transformers``.
This file is copied verbatim into every released model repository and loaded with ``trust_remote_code=True``.It depends only on ``transformers``."""
from __future__ import annotations
from typing import ClassVar
from transformers import PretrainedConfig
class WildAIConfig(PretrainedConfig): """Architecture of a WildAI model. Only width and depth vary across the released models.
Every layer uses causal attention limited to a left window: a query attends to itself and the ``window`` tokens before it. ``window_pattern`` is tiled over the layers ("S" = a quarter of the context rounded up to a multiple of 128 tokens, "L" = the full context) and the last layer always uses "L".
``release`` holds the model's entry in the release catalog (name, token counts, AI ratio, ...); it does not affect the forward pass. """
model_type = "wildai" keys_to_ignore_at_inference: ClassVar[list[str]] = ["past_key_values"]
def __init__( self, vocab_size: int = 32768, hidden_size: int = 768, num_hidden_layers: int = 12, num_attention_heads: int = 6, num_key_value_heads: int = 6, max_position_embeddings: int = 2048, window_pattern: str = "SSSL", rotary_base: float = 100000.0, qk_scale: float = 1.2, logit_softcap: float = 15.0, value_embed_gate_channels: int = 12, value_embed_gate_range: float = 3.0, smear_channels: int = 24, bos_token_id: int = 32759, eos_token_id: int = 32759, use_cache: bool = True, release: dict[str, str | int | float | None] | None = None, **kwargs: object, ) -> None: if hidden_size % num_attention_heads != 0 or num_attention_heads % num_key_value_heads != 0: raise ValueError("hidden_size must divide into num_attention_heads, and those into num_key_value_heads") if not window_pattern or set(window_pattern.upper()) - {"S", "L"}: raise ValueError(f"window_pattern must be a non-empty string of S and L, got {window_pattern!r}") self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.max_position_embeddings = max_position_embeddings self.window_pattern = window_pattern.upper() self.rotary_base = rotary_base self.qk_scale = qk_scale self.logit_softcap = logit_softcap self.value_embed_gate_channels = value_embed_gate_channels self.value_embed_gate_range = value_embed_gate_range self.smear_channels = smear_channels self.use_cache = use_cache self.release = release kwargs.setdefault("tie_word_embeddings", False) super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
@property def head_dim(self) -> int: return self.hidden_size // self.num_attention_heads
@property def intermediate_size(self) -> int: return 4 * self.hidden_size
@property def window_sizes(self) -> list[int]: """Left attention window of each layer, in tokens.""" long_window = self.max_position_embeddings short_window = -(-long_window // 4 // 128) * 128 # a quarter of the context, rounded up to a multiple of 128 (2048 -> 512) pattern = self.window_pattern sizes = [short_window if pattern[i % len(pattern)] == "S" else long_window for i in range(self.num_hidden_layers)] sizes[-1] = long_window return sizes
def has_value_embedding(self, layer_idx: int) -> bool: """Value embeddings sit on alternating layers, always including the last one.""" return layer_idx % 2 == (self.num_hidden_layers - 1) % 2
@property def backout_layer(self) -> int: """The residual stream after this layer is partly subtracted before the final norm.""" return self.num_hidden_layers // 212345678910{ "_from_model_config": true, "bos_token_id": 32759, "eos_token_id": 32759, "output_attentions": false, "output_hidden_states": false, "pad_token_id": 32759, "transformers_version": "5.17.0", "use_cache": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340"""The WildAI language models (a nanochat GPT variant) for Hugging Face ``transformers``.
This file is copied verbatim into every released model repository and loaded with ``trust_remote_code=True``.It depends only on ``torch`` and ``transformers`` and reproduces the training code's forward pass operation byoperation, so a model loaded in bfloat16 computes the same function the paper evaluated:
- token embedding followed by a parameter-free RMSNorm, then a learned "smear" that mixes each position's embedding with the previous token's;- per-layer scalars that rescale the residual stream and blend the initial embedding back in before every block;- attention with rotary embeddings applied before a per-head RMSNorm of queries and keys (both scaled by 1.2), a left sliding window per layer, and gated value embeddings added to the values on alternating layers;- a squared-ReLU MLP, parameter-free pre-norms, no biases;- "backout": part of the residual stream after the middle layer is subtracted before the final norm;- untied output head with logits soft-capped by ``15 * tanh(logits / 15)``.
Attention uses PyTorch's scaled_dot_product_attention with explicit window masks, so no FlashAttention install isneeded. Generation uses the standard ``DynamicCache``."""
from __future__ import annotations
from dataclasses import dataclassfrom typing import ClassVar
import torchimport torch.nn.functional as Ffrom torch import nnfrom transformers import GenerationMixin, PreTrainedModelfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from .configuration_wildai import WildAIConfig
def rms_norm(x: torch.Tensor) -> torch.Tensor: """Parameter-free RMSNorm over the last dimension with PyTorch's default epsilon, as in training.""" return F.rms_norm(x, (x.size(-1),))
def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: """Rotate channel pairs (i, i + d/2) of ``x`` (batch, time, heads, head_dim), with the training code's sign convention.""" d = x.shape[-1] // 2 x1, x2 = x[..., :d], x[..., d:] return torch.cat([x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos], dim=-1)
@dataclass(frozen=True)class WindowMask: """Arguments for scaled_dot_product_attention that implement one attention window."""
mask: torch.Tensor | None is_causal: bool
def window_masks( window_sizes: list[int], query_len: int, past_len: int, padding_mask: torch.Tensor | None, device: torch.device) -> dict[int, WindowMask]: """Masks for each distinct left window. Query i (absolute index past_len + i) sees keys j with i - window <= j <= i.
``padding_mask`` is the (batch, past_len + query_len) attention mask when it contains padding, else None. A padding query is always allowed to see itself so that its (unused) output stays finite. """ total = past_len + query_len q_idx = torch.arange(past_len, total, device=device)[:, None] k_idx = torch.arange(total, device=device)[None, :] masks: dict[int, WindowMask] = {} for window in sorted(set(window_sizes)): if padding_mask is None and window >= total - 1: if query_len == 1: masks[window] = WindowMask(mask=None, is_causal=False) continue if past_len == 0: masks[window] = WindowMask(mask=None, is_causal=True) continue allowed = (k_idx <= q_idx) & (q_idx - k_idx <= window) if padding_mask is not None: allowed = (allowed & padding_mask[:, None, None, :].bool()) | (k_idx == q_idx) masks[window] = WindowMask(mask=allowed, is_causal=False) return masks
class WildAIAttention(nn.Module): def __init__(self, config: WildAIConfig, layer_idx: int) -> None: super().__init__() self.layer_idx = layer_idx self.num_heads = config.num_attention_heads self.num_kv_heads = config.num_key_value_heads self.head_dim = config.head_dim self.qk_scale = config.qk_scale self.window = config.window_sizes[layer_idx] hidden, kv_dim = config.hidden_size, config.num_key_value_heads * config.head_dim self.q_proj = nn.Linear(hidden, config.num_attention_heads * config.head_dim, bias=False) self.k_proj = nn.Linear(hidden, kv_dim, bias=False) self.v_proj = nn.Linear(hidden, kv_dim, bias=False) self.o_proj = nn.Linear(hidden, hidden, bias=False) self.value_embed: nn.Embedding | None = None self.value_embed_gate: nn.Linear | None = None if config.has_value_embedding(layer_idx): self.value_embed = nn.Embedding(config.vocab_size, kv_dim) self.value_embed_gate = nn.Linear(config.value_embed_gate_channels, config.num_key_value_heads, bias=False) self.gate_channels = config.value_embed_gate_channels self.gate_range = config.value_embed_gate_range
def forward( self, x: torch.Tensor, input_ids: torch.LongTensor, rotary: tuple[torch.Tensor, torch.Tensor], mask: WindowMask, past_key_values: Cache | None, ) -> torch.Tensor: batch, time, _ = x.shape q = self.q_proj(x).view(batch, time, self.num_heads, self.head_dim) k = self.k_proj(x).view(batch, time, self.num_kv_heads, self.head_dim) v = self.v_proj(x).view(batch, time, self.num_kv_heads, self.head_dim) if self.value_embed is not None: ve = self.value_embed(input_ids).to(x.dtype).view(batch, time, self.num_kv_heads, self.head_dim) gate = self.gate_range * torch.sigmoid(self.value_embed_gate(x[..., : self.gate_channels])) v = v + gate.unsqueeze(-1) * ve cos, sin = rotary q, k = apply_rotary(q, cos, sin), apply_rotary(k, cos, sin) q, k = rms_norm(q) * self.qk_scale, rms_norm(k) * self.qk_scale q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) if past_key_values is not None: k, v = past_key_values.update(k, v, self.layer_idx) y = F.scaled_dot_product_attention( q, k, v, attn_mask=mask.mask, is_causal=mask.is_causal, enable_gqa=self.num_kv_heads != self.num_heads ) return self.o_proj(y.transpose(1, 2).reshape(batch, time, -1))
class WildAIMLP(nn.Module): def __init__(self, config: WildAIConfig) -> None: super().__init__() self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.down_proj(F.relu(self.up_proj(x)).square())
class WildAIDecoderLayer(nn.Module): def __init__(self, config: WildAIConfig, layer_idx: int) -> None: super().__init__() self.self_attn = WildAIAttention(config, layer_idx) self.mlp = WildAIMLP(config)
def forward( self, x: torch.Tensor, input_ids: torch.LongTensor, rotary: tuple[torch.Tensor, torch.Tensor], mask: WindowMask, past_key_values: Cache | None, ) -> torch.Tensor: x = x + self.self_attn(rms_norm(x), input_ids, rotary, mask, past_key_values) return x + self.mlp(rms_norm(x))
class WildAIPreTrainedModel(PreTrainedModel): config_class = WildAIConfig base_model_prefix = "model" main_input_name = "input_ids" _no_split_modules: ClassVar[list[str]] = ["WildAIDecoderLayer"] _supports_sdpa = True
def _init_weights(self, module: nn.Module) -> None: # Released models are always loaded from trained weights; this only gives from_config() models sane values. if isinstance(module, (nn.Linear, nn.Embedding)): nn.init.normal_(module.weight, mean=0.0, std=0.02) elif isinstance(module, WildAIModel): with torch.no_grad(): module.resid_lambdas.fill_(1.0) module.x0_lambdas.zero_() module.smear_lambda.zero_() module.backout_lambda.zero_()
class WildAIModel(WildAIPreTrainedModel): """The transformer trunk; returns the final normalised hidden states."""
def __init__(self, config: WildAIConfig) -> None: super().__init__(config) n_layer = config.num_hidden_layers self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) self.layers = nn.ModuleList([WildAIDecoderLayer(config, i) for i in range(n_layer)]) self.resid_lambdas = nn.Parameter(torch.ones(n_layer)) self.x0_lambdas = nn.Parameter(torch.zeros(n_layer)) self.smear_gate = nn.Linear(config.smear_channels, 1, bias=False) self.smear_lambda = nn.Parameter(torch.zeros(1)) self.backout_lambda = nn.Parameter(torch.zeros(1)) self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.embed_tokens
def set_input_embeddings(self, value: nn.Embedding) -> None: self.embed_tokens = value
def rotary(self, position_ids: torch.LongTensor, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]: """cos/sin tables of shape (batch, time, 1, head_dim / 2), computed in float32 and cast like in training.""" head_dim = self.config.head_dim channels = torch.arange(0, head_dim, 2, dtype=torch.float32, device=position_ids.device) inv_freq = 1.0 / (self.config.rotary_base ** (channels / head_dim)) freqs = position_ids.to(torch.float32)[..., None] * inv_freq return freqs.cos().to(dtype)[:, :, None, :], freqs.sin().to(dtype)[:, :, None, :]
def smear(self, x: torch.Tensor, previous: torch.Tensor | None, padding_mask: torch.Tensor | None) -> torch.Tensor: """Add a gated copy of the previous position's embedding to every position that has one.
``previous`` is the normalised embedding of the token just before this chunk (None at the start of a sequence); with left padding, the first real token has a padding token before it and gets nothing. """ channels = self.config.smear_channels lam = self.smear_lambda.to(x.dtype) first = x[:, :1] if previous is not None: first = first + lam * torch.sigmoid(self.smear_gate(first[..., :channels])) * previous if x.size(1) == 1: return first gate = lam * torch.sigmoid(self.smear_gate(x[:, 1:, :channels])) if padding_mask is not None: gate = gate * padding_mask[:, -x.size(1) : -1, None].to(gate.dtype) return torch.cat([first, x[:, 1:] + gate * x[:, :-1]], dim=1)
def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, use_cache: bool | None = None, previous_token_ids: torch.LongTensor | None = None, output_hidden_states: bool | None = None, **kwargs: object, ) -> BaseModelOutputWithPast: """``previous_token_ids`` (batch, 1): the token before ``input_ids[:, 0]``; required when continuing from a cache.""" if input_ids is None: raise ValueError("input_ids are required: the value embeddings are looked up by token id") batch, time = input_ids.shape use_cache = self.config.use_cache if use_cache is None else use_cache if use_cache and past_key_values is None: past_key_values = DynamicCache() past_len = past_key_values.get_seq_length() if past_key_values is not None else 0 if past_len > 0 and previous_token_ids is None: raise ValueError("previous_token_ids is required when continuing from past_key_values (the smear needs it)") padding_mask = None if attention_mask is not None: if attention_mask.shape != (batch, past_len + time): raise ValueError(f"attention_mask must have shape {(batch, past_len + time)}, got {tuple(attention_mask.shape)}") if not bool(attention_mask.all()): padding_mask = attention_mask if position_ids is None: position_ids = torch.arange(past_len, past_len + time, device=input_ids.device).expand(batch, -1)
x = rms_norm(self.embed_tokens(input_ids)) previous = rms_norm(self.embed_tokens(previous_token_ids)) if previous_token_ids is not None else None x = self.smear(x, previous, padding_mask) rotary = self.rotary(position_ids, x.dtype) masks = window_masks(self.config.window_sizes, time, past_len, padding_mask, input_ids.device)
x0 = x backout = None hidden_states: tuple[torch.Tensor, ...] = (x,) for i, layer in enumerate(self.layers): x = self.resid_lambdas[i] * x + self.x0_lambdas[i] * x0 x = layer(x, input_ids, rotary, masks[layer.self_attn.window], past_key_values) if i == self.config.backout_layer: backout = x hidden_states += (x,) x = rms_norm(x - self.backout_lambda.to(x.dtype) * backout) return BaseModelOutputWithPast( last_hidden_state=x, past_key_values=past_key_values if use_cache else None, hidden_states=hidden_states if output_hidden_states else None, )
class WildAIForCausalLM(WildAIPreTrainedModel, GenerationMixin): def __init__(self, config: WildAIConfig) -> None: super().__init__(config) self.model = WildAIModel(config) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.model.embed_tokens
def set_input_embeddings(self, value: nn.Embedding) -> None: self.model.embed_tokens = value
def get_output_embeddings(self) -> nn.Linear: return self.lm_head
def set_output_embeddings(self, value: nn.Linear) -> None: self.lm_head = value
def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, previous_token_ids: torch.LongTensor | None = None, output_hidden_states: bool | None = None, logits_to_keep: int = 0, return_dict: bool | None = None, **kwargs: object, ) -> CausalLMOutputWithPast | tuple[torch.Tensor, ...]: """Float32 logits after the soft cap. ``labels`` are shifted inside (standard causal-LM loss, -100 ignored).""" outputs = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, previous_token_ids=previous_token_ids, output_hidden_states=output_hidden_states, ) hidden = outputs.last_hidden_state[:, -logits_to_keep:] if logits_to_keep else outputs.last_hidden_state logits = self.lm_head(hidden).float() cap = self.config.logit_softcap logits = cap * torch.tanh(logits / cap) loss = None if labels is not None: loss = F.cross_entropy(logits[:, :-1].flatten(0, 1), labels[:, 1:].flatten().to(logits.device), ignore_index=-100) result = CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states ) return result.to_tuple() if return_dict is False else result
def prepare_inputs_for_generation(self, input_ids: torch.LongTensor, **kwargs: object) -> dict[str, object]: # The smear mixes in the embedding of the token before the first new one; take it from the full sequence. model_inputs = super().prepare_inputs_for_generation(input_ids, **kwargs) new_len = model_inputs["input_ids"].shape[1] if input_ids.shape[1] > new_len: model_inputs["previous_token_ids"] = input_ids[:, -new_len - 1 : -new_len] return model_inputs268m-g073-ai-r0.05/config.jsonAdded+46
268m-g073-ai-r0.05/tokenizer_config.jsonAdded+11
268m-g073-human-r0.025/model.safetensorsAdded+3
268m-g074-control/LICENSEAdded+438
268m-g074-control/README.mdAdded+105
268m-g074-control/config.jsonAdded+46
268m-g074-control/configuration_wildai.pyAdded+96
268m-g074-control/generation_config.jsonAdded+10
268m-g074-control/modeling_wildai.pyAdded+340
268m-g074-control/tokenizer.jsonAdded
268m-g074-control/tokenizer_config.jsonAdded+11
268m-g074-human-r0.025/model.safetensorsAdded+3
268m-g074-human-r0.05/model.safetensorsAdded+3
268m-g075-ai-r0.1/model.safetensorsAdded+3
268m-g076-ai-r0.5/model.safetensorsAdded+3
268m-g076-control/model.safetensorsAdded+3
268m-g077-ai-r0.25/LICENSEAdded+438
268m-g077-ai-r0.25/README.mdAdded+105
268m-g077-ai-r0.25/config.jsonAdded+46
268m-g077-ai-r0.25/configuration_wildai.pyAdded+96
268m-g077-ai-r0.25/generation_config.jsonAdded+10
268m-g077-ai-r0.25/modeling_wildai.pyAdded+340
268m-g077-ai-r0.25/tokenizer.jsonAdded
268m-g077-ai-r0.25/tokenizer_config.jsonAdded+11
268m-g078-human-r0.025/model.safetensorsAdded+3
268m-g079-ai-r0.05/model.safetensorsAdded+3
268m-g079-control/configuration_wildai.pyAdded+96
268m-g079-control/modeling_wildai.pyAdded+340
268m-g079-human-r0.025/LICENSEAdded+438
268m-g079-human-r0.025/README.mdAdded+105
268m-g079-human-r0.025/config.jsonAdded+46
268m-g079-human-r0.025/configuration_wildai.pyAdded+96
268m-g079-human-r0.025/generation_config.jsonAdded+10
268m-g079-human-r0.025/modeling_wildai.pyAdded+340
268m-g079-human-r0.025/tokenizer.jsonAdded
268m-g079-human-r0.025/tokenizer_config.jsonAdded+11
268m-g079-human-r0.05/model.safetensorsAdded+3
268m-g081-ai-r0.025/LICENSEAdded+438
268m-g081-ai-r0.025/README.mdAdded+105
268m-g081-ai-r0.025/config.jsonAdded+46
268m-g081-ai-r0.025/configuration_wildai.pyAdded+96
268m-g081-ai-r0.025/generation_config.jsonAdded+10
268m-g081-ai-r0.025/modeling_wildai.pyAdded+340
268m-g081-ai-r0.025/tokenizer_config.jsonAdded+11
268m-g081-ai-r0.25/LICENSEAdded+438
268m-g081-ai-r0.25/README.mdAdded+105
268m-g081-ai-r0.25/config.jsonAdded+46
268m-g081-ai-r0.25/configuration_wildai.pyAdded+96
268m-g081-ai-r0.25/generation_config.jsonAdded+10
268m-g081-ai-r0.25/modeling_wildai.pyAdded+340