Slayer139 1.02: weights (safetensors), config, tokenizer, model code, card
Browse files- README.md +148 -0
- config.json +19 -0
- model.safetensors +3 -0
- modeling_slayer139.py +174 -0
- tokenizer.json +0 -0
README.md
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language: [en]
|
| 3 |
+
license: apache-2.0
|
| 4 |
+
library_name: pytorch
|
| 5 |
+
tags: [slayer, small-language-model, glint-tiny-ml, fabryka-ai]
|
| 6 |
+
datasets: [SlayerLab/gollem-v5-arcmix-9b, SlayerLab/minimal-en-corpus-5b, HuggingFaceFW/fineweb-edu, mlfoundations/dclm-baseline-1.0-parquet, allenai/ai2_arc, Salesforce/wikitext]
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
# Slayer139 1.02
|
| 10 |
+
|
| 11 |
+
A small decoder-only English language model (139.3M parameters) by Fabryka AI, built for the Glint Tiny-ML leaderboard (≤150M parameters). It is Slayer139 1.01's pretrained base, given a short continued pretraining and a new ARC fine-tune.
|
| 12 |
+
|
| 13 |
+
**Author:** Arkadiusz Słota (Fabryka AI / SlayerLab). Training, evaluation and safety gates were run by the Fabryka AI agent team under his direction.
|
| 14 |
+
|
| 15 |
+
**Identity:** Slayer139 1.02 is the training checkpoint with sha256 `50f07cab0e1eedb4b3c1e65119a53fb6105f9c6e1fe7984b2b604c77c0c5ec7c` (internal run name POL4-CEP s1491). No other checkpoint is published under this name.
|
| 16 |
+
|
| 17 |
+
## Result
|
| 18 |
+
|
| 19 |
+
lm-evaluation-harness 0.4.13, 0-shot, board protocol (C2) — the same protocol and setup as the Slayer139 1.01 row.
|
| 20 |
+
|
| 21 |
+
| measure | Slayer139 1.02 | Slayer139 1.01 | Δ |
|
| 22 |
+
|---|---|---|---|
|
| 23 |
+
| BLiMP (67 tasks) | 79.22 | 79.13 | +0.09 |
|
| 24 |
+
| ARC-Easy (test, 2,376, acc) | 65.91 | 63.09 | +2.82 |
|
| 25 |
+
| WikiText-2 byte perplexity | 1.8620 | 1.8782 | −0.0162 |
|
| 26 |
+
| WikiText-2 score | 99.98 | 99.83 | +0.15 |
|
| 27 |
+
| **Overall** | **81.70** | **80.68** | **+1.02** |
|
| 28 |
+
|
| 29 |
+
Overall is the mean of BLiMP, ARC-Easy and the WikiText-2 score. Board size multiplier 1.003100 (efficiency score 81.96).
|
| 30 |
+
|
| 31 |
+
Provenance (sha256 prefix of the lm-eval `results.json`): `8b21f803`.
|
| 32 |
+
|
| 33 |
+
Numbers are our measurements with the board's protocol, not official scores until the leaderboard lists them.
|
| 34 |
+
|
| 35 |
+
### How this checkpoint was selected (read this before comparing)
|
| 36 |
+
|
| 37 |
+
- 15 fine-tune variants were compared on ARC-Easy **validation** (one half, 285 questions) plus 500 ARC-Easy **train** questions held out from all fine-tuning. The other validation half was read twice in the series (once per test candidate), only to forecast the test score.
|
| 38 |
+
- The test split was read only after a selection rule written in advance was met. For this model the test set was read **once**. Across the whole series the test set was read **twice**: an earlier candidate scored Overall 81.14 and was **not** published.
|
| 39 |
+
- Within the chosen variant the last epoch was taken (fixed in advance, not selected).
|
| 40 |
+
- Our Slayer149-ARC model scores Overall 81.50 with the same protocol, so the lead of this model over it is **only +0.20 Overall, within about one standard error**; treat the two as tied. This checkpoint has not yet been re-benchmarked by the leaderboard maintainers.
|
| 41 |
+
|
| 42 |
+
## Model
|
| 43 |
+
|
| 44 |
+
- Architecture: 17 layers × 768, 12 heads (12 KV heads), SwiGLU, decoder-only; vocabulary 24,576 (BPE), context 1,024. Identical to Slayer139 1.01.
|
| 45 |
+
- Parameters: 139,279,760 unique parameters (input and output embeddings tied: one shared tensor, counted once; counting the shared tensor twice gives 158,154,128).
|
| 46 |
+
- Checkpoint lineage: pretrained base (step 90,310, sha256 `ba223162…`, the base of Slayer139 1.01) → continued pretraining (1,145 steps, sha256 `05815bf3…`) → ARC fine-tune → **this model** (sha256 `50f07cab…`).
|
| 47 |
+
|
| 48 |
+
## Training
|
| 49 |
+
|
| 50 |
+
- **Pretraining:** identical to Slayer139 1.01 (~23.67B tokens, no repeated epoch; see the Slayer139 1.01 card for the optimiser, schedule and hardware).
|
| 51 |
+
- **Continued pretraining:** 1,145 steps, ~303M tokens: 85% the same data mix as pretraining, 15% WikiText-103 train.
|
| 52 |
+
- **ARC fine-tune** (after continued pretraining): listwise cross-entropy over the summed log-probabilities of the answer tokens, prompt `Question: {q}\nAnswer:` / ` {a}` (the lm-evaluation-harness format). Data: ARC-Easy train and ARC-Challenge train, after removing questions that overlap the ARC-Easy test set; 500 ARC-Easy train questions held out for selection. ARC-Challenge questions were used in epochs 1–2 only. AdamW, constant LR 2e-5, betas (0.9, 0.95), weight decay 0.01, 8 questions per step, 5 epochs (last epoch taken), seed 1491. Replay: the loss is 0.15 × answer-choice loss + 0.85 × next-token loss on pretraining text windows, to limit forgetting.
|
| 53 |
+
|
| 54 |
+
## Training data
|
| 55 |
+
|
| 56 |
+
Aggregate corpus; each source keeps its upstream terms.
|
| 57 |
+
|
| 58 |
+
- **ARC-MIX pool** (`SlayerLab/gollem-v5-arcmix-9b`, 9.39B tokens before retokenization): the 15-source base `SlayerLab/minimal-en-corpus-5b` (FineWeb-Edu, DCLM-baseline, open-web-math, FineMath, StarCoderData, StackExchange, LoC public-domain books, Wikipedia, Project Gutenberg, scientific papers, UltraChat, WildChat, CC-News, tiny-textbooks, OpenSubtitles) + a FineWeb-Edu expansion + OpenStax textbooks (×4) + extra copies of FineWeb-Edu documents scored as related to ARC science topics (+2 copies for the highest score, +1 for the next). Removed before training: 4,362 documents by the WikiText-2 / ARC validation+test scan and 1,175 documents marked CC BY-NC-SA.
|
| 59 |
+
- **Top-up** (11.4M documents, 57.45 GB of text, build manifest `b73f45f5…`): FineWeb-Edu expansion (37.1%, ODC-By 1.0, plus the same dose of ARC-related copies as the pool), FineWeb-Edu (14.9%, ODC-By 1.0), DCLM-baseline (10.9%, CC BY 4.0), StackExchange via RedPajama (6.1%, CC BY-SA content), LoC public-domain books (5.4%, CC0), StarCoderData (5.1%, The Stack terms), Wikipedia 20231101.en (4.6%, CC BY-SA 3.0 / GFDL), Project Gutenberg (2.9%, US public domain), PMC Open Access commercial-use subset (2.8%, CC0 / CC BY / CC BY-SA per article; ND and NC excluded), open-web-math (2.7%, ODC-By), FineMath (2.6%, ODC-By), WildChat-1M (2.0%, ODC-By; English, non-toxic), CC-News (1.4%, licence unknown), UltraChat 200k (0.7%, MIT), tiny-textbooks (0.7%, Apache 2.0). The top-up scan removed 25,808 documents (0.23%), each together with its ARC-related copies.
|
| 60 |
+
- Licences upstream include ODC-By, CC BY 4.0, CC BY-SA (Wikipedia, StackExchange, some PMC articles), CC0 / public domain, and sources with unknown or restrictive terms. Commercial use: review upstream terms, in particular CC-News, scientific papers, StarCoderData and model-generated chat data (UltraChat, WildChat, tiny-textbooks).
|
| 61 |
+
- OpenStax textbooks (55 titles) are used under CC BY 4.0; attribution: OpenStax, Rice University (see [OpenStax attribution](#openstax-attribution) below).
|
| 62 |
+
- **Continued-pretraining data:** 85% the same mix as the pretraining above, 15% WikiText-103 train (Merity et al., 2016, Salesforce; `Salesforce/wikitext`, CC BY-SA 3.0 — text from English Wikipedia). WikiText-103 train shares its source (Wikipedia Good/Featured articles) with the WikiText-2 benchmark but not its test articles; see Limitations.
|
| 63 |
+
- **Fine-tune data:** ARC-Easy train and ARC-Challenge train from `allenai/ai2_arc` (Clark et al., 2018, Allen Institute for AI), CC BY-SA 4.0. Questions overlapping the ARC-Easy test set were removed from both. ARC-Easy validation and 500 held-out ARC-Easy train questions (never trained on) were used only for selection; the test split was not used for training or selection.
|
| 64 |
+
|
| 65 |
+
## Limitations
|
| 66 |
+
|
| 67 |
+
- English only; small model; one seed.
|
| 68 |
+
- The pretraining mix deliberately upweights web documents related to ARC science topics (decontaminated against the ARC test set); ARC-Easy is therefore an in-domain benchmark for this model, and it was fine-tuned on ARC-Easy and ARC-Challenge **train**.
|
| 69 |
+
- Continued pretraining includes WikiText-103 train, which comes from the same Wikipedia article pool as the WikiText-2 benchmark (different articles); the WikiText-2 score (99.98 vs 99.83) should be read with that in mind.
|
| 70 |
+
- The improvement over Slayer139 1.01 was measured with one test read after selection on validation and held-out train questions; the margin over our Slayer149-ARC (+0.20 Overall) is within noise.
|
| 71 |
+
|
| 72 |
+
## OpenStax attribution
|
| 73 |
+
|
| 74 |
+
The training data of this model includes text extracted from the following OpenStax textbooks, each licensed under the Creative Commons Attribution 4.0 International License (CC BY 4.0), © Rice University. Download for free at https://openstax.org. The texts were obtained from the Hugging Face dataset crumb/openstax-text (revision 8f502ca45f9f05cb5673eae445b7a97a4e8c4349). Modified: text extracted, chunked and filtered (chunks matching benchmark test/validation sets were removed).
|
| 75 |
+
|
| 76 |
+
| Title (from source file name) | © year |
|
| 77 |
+
|---|---|
|
| 78 |
+
| APBiology | 2018 |
|
| 79 |
+
| APCollege Physics | 2017 |
|
| 80 |
+
| APMacroeconomics 2e | 2017 |
|
| 81 |
+
| APMicroeconomics 2e | 2017 |
|
| 82 |
+
| Algebra and Trigonometry 2e | 2021 |
|
| 83 |
+
| American Government 3e | 2021 |
|
| 84 |
+
| Anatomy and Physiology 2e | 2022 |
|
| 85 |
+
| Anatomyand Physiology | 2017 |
|
| 86 |
+
| Astronomy 2e | 2022 |
|
| 87 |
+
| Astronomy | 2018 |
|
| 88 |
+
| Biology 2e | 2020 |
|
| 89 |
+
| Business Ethics | 2018 |
|
| 90 |
+
| Chemistry 2e | 2019 |
|
| 91 |
+
| Chemistry Atoms First 2e | 2019 |
|
| 92 |
+
| College Algebra 2e | 2021 |
|
| 93 |
+
| College Algebra Corequisite Support 2e | 2021 |
|
| 94 |
+
| College Physics | 2020 |
|
| 95 |
+
| College Physics 2e | 2022 |
|
| 96 |
+
| College Physics for AP Courses 2e | 2022 |
|
| 97 |
+
| College Success | 2020 |
|
| 98 |
+
| College Success | 2023 |
|
| 99 |
+
| Concepts Biology | 2017 |
|
| 100 |
+
| Contemporary Mathematics | 2023 |
|
| 101 |
+
| Economics 2e | 2018 |
|
| 102 |
+
| Economics 3e | 2022 |
|
| 103 |
+
| Elementary Algebra 2e | 2020 |
|
| 104 |
+
| Entrepreneurship | 2020 |
|
| 105 |
+
| Intermediate Algebra 2e | 2020 |
|
| 106 |
+
| Introduction to Intellectual Property | n/a |
|
| 107 |
+
| Introduction to Philosophy | 2022 |
|
| 108 |
+
| Introduction to Political Science | 2022 |
|
| 109 |
+
| Introductionto Anthropology | 2022 |
|
| 110 |
+
| Introductionto Sociology 3e | 2021 |
|
| 111 |
+
| Introductory Business Statistics | 2018 |
|
| 112 |
+
| Introductory Statistics | 2018 |
|
| 113 |
+
| Macroeconomics 2e | 2018 |
|
| 114 |
+
| Macroeconomics 3e | 2022 |
|
| 115 |
+
| Microbiology | 2021 |
|
| 116 |
+
| Microeconomics 2e | 2018 |
|
| 117 |
+
| Microeconomics 3e | 2022 |
|
| 118 |
+
| Physics | n/a |
|
| 119 |
+
| Prealgebra 2e | 2020 |
|
| 120 |
+
| Precalculus 2e | 2021 |
|
| 121 |
+
| Preparing for College Success | 2023 |
|
| 122 |
+
| Principles Marketing | 2023 |
|
| 123 |
+
| Principlesof Finance | 2022 |
|
| 124 |
+
| Psychology 2e | 2020 |
|
| 125 |
+
| Statistics | n/a |
|
| 126 |
+
| USHistory | 2021 |
|
| 127 |
+
| University Physics Vol 1 | 2021 |
|
| 128 |
+
| University Physics Volume 2 | 2021 |
|
| 129 |
+
| University Physics Volume 3 | 2021 |
|
| 130 |
+
| World History Volume 1 | 2023 |
|
| 131 |
+
| World History Volume 2 | 2022 |
|
| 132 |
+
| Writing Guide | 2021 |
|
| 133 |
+
|
| 134 |
+
Titles licensed CC BY-NC-SA 4.0, non-English titles, and three CC BY 4.0 titles whose text contains elements marked ‘CC BY-NC-SA’ (Introduction to Business, Organizational Behavior, Principles of Management) were not used.
|
| 135 |
+
|
| 136 |
+
## How to load
|
| 137 |
+
|
| 138 |
+
```python
|
| 139 |
+
from modeling_slayer139 import load_slayer139, generate
|
| 140 |
+
model, tok = load_slayer139(".") # directory with config.json, model.safetensors, tokenizer.json
|
| 141 |
+
print(generate(model, tok, "The capital of France is", max_new_tokens=40))
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
Requirements: torch, safetensors, tokenizers. The output head is tied to the token embedding (stored once in `model.safetensors`, re-tied on load).
|
| 145 |
+
|
| 146 |
+
## Reproduce
|
| 147 |
+
|
| 148 |
+
Evaluation: lm-evaluation-harness 0.4.13, tasks `blimp`, `arc_easy`, `wikitext` (board protocol C2), 0-shot. Method and full run history: paper „Same recipe, 4.4× faster on 8× RTX 5090” (Fabryka AI, in preparation).
|
config.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"block": 1024,
|
| 3 |
+
"ffn": "swiglu",
|
| 4 |
+
"ffn_mult": 2.667,
|
| 5 |
+
"logit_cap": 0.0,
|
| 6 |
+
"n_embd": 768,
|
| 7 |
+
"n_head": 12,
|
| 8 |
+
"n_layer": 17,
|
| 9 |
+
"norm": "rmsnorm",
|
| 10 |
+
"norm_eps": 1e-06,
|
| 11 |
+
"pos": "rope",
|
| 12 |
+
"qk_norm": true,
|
| 13 |
+
"rope_theta": 100000.0,
|
| 14 |
+
"tied_weights": {
|
| 15 |
+
"tok.weight": "head.weight"
|
| 16 |
+
},
|
| 17 |
+
"value_residual": true,
|
| 18 |
+
"vocab": 24576
|
| 19 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4560ad52648e38e567a60bcd1d64dd268e4a8cedf142accf2e3a5ebb0b9fdbe3
|
| 3 |
+
size 557137920
|
modeling_slayer139.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Slayer139 1.02 model code (inference only), extracted from the training script used for this run.
|
| 2 |
+
|
| 3 |
+
The module definitions are those of the training script; only the weight initialisation and the training loss were
|
| 4 |
+
removed and comments translated. Weights load with strict=True. Requirements: torch, safetensors, tokenizers.
|
| 5 |
+
|
| 6 |
+
from modeling_slayer139 import load_slayer139, generate
|
| 7 |
+
model, tok = load_slayer139(".") # directory with config.json, model.safetensors, tokenizer.json
|
| 8 |
+
print(generate(model, tok, "The capital of France is", max_new_tokens=40))
|
| 9 |
+
|
| 10 |
+
Notes: RoPE uses the interleaved convention (pairs of adjacent channels), not rotate_half; the output head is tied to
|
| 11 |
+
the token embedding; context length is 1,024 tokens.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import types
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class RMSNorm(nn.Module):
|
| 25 |
+
"""RMSNorm with fp32 compute for stability."""
|
| 26 |
+
def __init__(self, d, eps=1e-6):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.weight = nn.Parameter(torch.ones(d))
|
| 29 |
+
self.eps = eps
|
| 30 |
+
|
| 31 |
+
def forward(self, x):
|
| 32 |
+
return x * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps).to(x.dtype) * self.weight
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def make_norm(d, cfg):
|
| 36 |
+
return RMSNorm(d, cfg.norm_eps) if cfg.norm == "rmsnorm" else nn.LayerNorm(d)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def apply_rope(x, base=100000.0):
|
| 40 |
+
"""Parameter-free RoPE on [B, H, T, D], interleaved convention (even/odd channel pairs)."""
|
| 41 |
+
_, _, T, dim = x.shape
|
| 42 |
+
pos = torch.arange(T, device=x.device, dtype=torch.float32)
|
| 43 |
+
freq = 1.0 / (base ** (torch.arange(0, dim, 2, device=x.device, dtype=torch.float32) / dim))
|
| 44 |
+
ang = torch.outer(pos, freq)
|
| 45 |
+
cos, sin = ang.cos().to(x.dtype)[None, None], ang.sin().to(x.dtype)[None, None]
|
| 46 |
+
even, odd = x[..., ::2], x[..., 1::2]
|
| 47 |
+
return torch.stack((even * cos - odd * sin, even * sin + odd * cos), dim=-1).flatten(-2)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class SwiGLU(nn.Module):
|
| 51 |
+
"""Gated MLP: down(silu(gate(x)) * up(x))."""
|
| 52 |
+
def __init__(self, d, hidden):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.gate = nn.Linear(d, hidden, bias=False)
|
| 55 |
+
self.up = nn.Linear(d, hidden, bias=False)
|
| 56 |
+
self.down = nn.Linear(hidden, d, bias=False)
|
| 57 |
+
|
| 58 |
+
def forward(self, x):
|
| 59 |
+
return self.down(F.silu(self.gate(x)) * self.up(x))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class Block(nn.Module):
|
| 63 |
+
def __init__(self, d, nh, block, cfg, is_first=False):
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.ln1 = make_norm(d, cfg)
|
| 66 |
+
self.ln2 = make_norm(d, cfg)
|
| 67 |
+
self.qkv = nn.Linear(d, 3 * d)
|
| 68 |
+
self.proj = nn.Linear(d, d)
|
| 69 |
+
if cfg.ffn == "swiglu":
|
| 70 |
+
self.mlp = SwiGLU(d, int(round(cfg.ffn_mult * d)))
|
| 71 |
+
else:
|
| 72 |
+
self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
|
| 73 |
+
self.nh = nh
|
| 74 |
+
self.d = d
|
| 75 |
+
self.cfg = cfg
|
| 76 |
+
self.is_first = is_first
|
| 77 |
+
if cfg.value_residual and not is_first:
|
| 78 |
+
self.vr_lambda = nn.Parameter(torch.zeros(1))
|
| 79 |
+
if cfg.qk_norm:
|
| 80 |
+
hd = d // nh
|
| 81 |
+
self.q_norm = RMSNorm(hd, cfg.norm_eps)
|
| 82 |
+
self.k_norm = RMSNorm(hd, cfg.norm_eps)
|
| 83 |
+
|
| 84 |
+
def forward(self, x, v0=None):
|
| 85 |
+
B, T, D = x.size()
|
| 86 |
+
h = self.ln1(x)
|
| 87 |
+
q, k, v = self.qkv(h).split(self.d, dim=2)
|
| 88 |
+
hd = D // self.nh
|
| 89 |
+
q = q.view(B, T, self.nh, hd).transpose(1, 2)
|
| 90 |
+
k = k.view(B, T, self.nh, hd).transpose(1, 2)
|
| 91 |
+
v = v.view(B, T, self.nh, hd).transpose(1, 2)
|
| 92 |
+
if self.cfg.qk_norm:
|
| 93 |
+
q = self.q_norm(q)
|
| 94 |
+
k = self.k_norm(k)
|
| 95 |
+
if self.cfg.pos == "rope":
|
| 96 |
+
q = apply_rope(q, self.cfg.rope_theta)
|
| 97 |
+
k = apply_rope(k, self.cfg.rope_theta)
|
| 98 |
+
if self.cfg.value_residual:
|
| 99 |
+
if self.is_first:
|
| 100 |
+
v0 = v
|
| 101 |
+
else:
|
| 102 |
+
v = v + self.vr_lambda * v0
|
| 103 |
+
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
|
| 104 |
+
y = y.transpose(1, 2).contiguous().view(B, T, D)
|
| 105 |
+
x = x + self.proj(y)
|
| 106 |
+
x = x + self.mlp(self.ln2(x))
|
| 107 |
+
return x, v0
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class GPT(nn.Module):
|
| 111 |
+
def __init__(self, vocab, n_layer, n_embd, n_head, block, cfg):
|
| 112 |
+
super().__init__()
|
| 113 |
+
self.cfg = cfg
|
| 114 |
+
self.tok = nn.Embedding(vocab, n_embd)
|
| 115 |
+
self.use_rope = cfg.pos == "rope"
|
| 116 |
+
if not self.use_rope:
|
| 117 |
+
self.pos = nn.Embedding(block, n_embd)
|
| 118 |
+
self.blocks = nn.ModuleList([Block(n_embd, n_head, block, cfg, is_first=(i == 0)) for i in range(n_layer)])
|
| 119 |
+
self.lnf = make_norm(n_embd, cfg)
|
| 120 |
+
self.head = nn.Linear(n_embd, vocab, bias=False)
|
| 121 |
+
self.head.weight = self.tok.weight # tied
|
| 122 |
+
self.block = block
|
| 123 |
+
|
| 124 |
+
def forward(self, idx):
|
| 125 |
+
B, T = idx.size()
|
| 126 |
+
x = self.tok(idx)
|
| 127 |
+
if not self.use_rope:
|
| 128 |
+
pos = torch.arange(T, device=idx.device)
|
| 129 |
+
x = x + self.pos(pos)[None]
|
| 130 |
+
v0 = None
|
| 131 |
+
for b in self.blocks:
|
| 132 |
+
x, v0 = b(x, v0)
|
| 133 |
+
logits = self.head(self.lnf(x))
|
| 134 |
+
cap = getattr(self.cfg, "logit_cap", 0.0)
|
| 135 |
+
if cap and cap > 0:
|
| 136 |
+
logits = cap * torch.tanh(logits / cap)
|
| 137 |
+
return logits
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def load_slayer139(path, device="cpu"):
|
| 141 |
+
"""Model (eval mode) and tokenizer from a directory with config.json, model.safetensors and tokenizer.json."""
|
| 142 |
+
from safetensors.torch import load_file
|
| 143 |
+
from tokenizers import Tokenizer
|
| 144 |
+
|
| 145 |
+
with open(os.path.join(path, "config.json"), encoding="utf-8") as f:
|
| 146 |
+
cfg = types.SimpleNamespace(**json.load(f))
|
| 147 |
+
model = GPT(cfg.vocab, cfg.n_layer, cfg.n_embd, cfg.n_head, cfg.block, cfg)
|
| 148 |
+
state = load_file(os.path.join(path, "model.safetensors"))
|
| 149 |
+
# the output head is tied to the token embedding and stored once (tok.weight); restore the tied key for strict loading
|
| 150 |
+
if "head.weight" in state:
|
| 151 |
+
raise ValueError("model.safetensors must not contain head.weight (tied to tok.weight, stored once)")
|
| 152 |
+
state["head.weight"] = state["tok.weight"]
|
| 153 |
+
model.load_state_dict(state, strict=True)
|
| 154 |
+
return model.to(device).eval(), Tokenizer.from_file(os.path.join(path, "tokenizer.json"))
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
@torch.no_grad()
|
| 158 |
+
def generate(model, tok, prompt, max_new_tokens=64, temperature=0.0, top_k=None, seed=None):
|
| 159 |
+
"""Continue `prompt`. temperature 0 = greedy; otherwise sampling, optionally top-k."""
|
| 160 |
+
g = torch.Generator().manual_seed(seed) if seed is not None else None
|
| 161 |
+
dev = next(model.parameters()).device
|
| 162 |
+
x = torch.tensor([tok.encode(prompt).ids], device=dev)
|
| 163 |
+
for _ in range(max_new_tokens):
|
| 164 |
+
logits = model(x[:, -model.block:])[:, -1].float().cpu()
|
| 165 |
+
if temperature <= 0:
|
| 166 |
+
nxt = logits.argmax(-1, keepdim=True)
|
| 167 |
+
else:
|
| 168 |
+
logits = logits / temperature
|
| 169 |
+
if top_k:
|
| 170 |
+
kth = torch.topk(logits, top_k).values[:, -1:]
|
| 171 |
+
logits = logits.masked_fill(logits < kth, float("-inf"))
|
| 172 |
+
nxt = torch.multinomial(torch.softmax(logits, -1), 1, generator=g)
|
| 173 |
+
x = torch.cat([x, nxt.to(dev)], dim=1)
|
| 174 |
+
return tok.decode(x[0].tolist())
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|