helloboy91 commited on
Commit
5f3e605
·
verified ·
1 Parent(s): 3fa0d9d

Release v0.1.0: verified 30M FP32 weights, tokenizer, inference code, MIT license

Browse files
DATA_LICENSE.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Data provenance and license notice
2
+
3
+ The release weights, trained tokenizer, bundled inference code, and project code are offered under the MIT license, to the extent of the author’s rights. This grant does not relicense third-party datasets or dependencies.
4
+
5
+ Training source: [TinyStories](https://huggingface.co/datasets/roneneldan/TinyStories), by Ronen Eldan and Yuanzhi Li; [paper](https://arxiv.org/abs/2305.07759). The dataset card describes synthetic short stories generated using GPT-3.5 and GPT-4.
6
+
7
+ The dataset card at revision `f54c09fd23315a6f9c86f9dc80f725de7d8f9c64` specifies **CDLA-Sharing-1.0**. See the [official license text](https://cdla.dev/sharing-1-0/). Section 3.5 states that the agreement imposes no obligations or restrictions on use or publication of Results. The release contains trained computational artifacts, not the original or cleaned story corpus.
8
+
9
+ If redistributing source or modified dataset files separately, review and comply with CDLA-Sharing-1.0, including its attribution and sharing requirements. No dataset files are uploaded in this release. Dataset licensing does not guarantee that generated text is free of third-party rights or suitable for any particular purpose. Dependencies retain their respective licenses.
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ybj91 / helloboy91
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ license: mit
5
+ library_name: pytorch
6
+ pipeline_tag: text-generation
7
+ datasets:
8
+ - roneneldan/TinyStories
9
+ tags:
10
+ - tiny-english
11
+ - from-scratch
12
+ - story-completion
13
+ - safetensors
14
+ inference: false
15
+ ---
16
+
17
+ # Tiny English 30M — v0.1.0
18
+
19
+ An experimental **29,893,120-parameter decoder-only language model**, trained from random initialization on a subset of TinyStories. It completes simple English story openings. It is **not** an instruction-tuned assistant, tool-use model, factual reference, or production agent.
20
+
21
+ ## Release contents
22
+
23
+ - `model.safetensors`: FP32 inference weights, **119,578,064 bytes** (about 120 MB / 114 MiB).
24
+ - `config.json` and `tokenizer.json`: architecture, checkpoint metadata, checksums, and trained byte-level BPE vocabulary.
25
+ - `tiny_english/`: minimal, inspectable Python inference package.
26
+ - `training_summary.json`, `evaluation.json`, `SHA256SUMS`: provenance, validation results, and release checksums.
27
+ - `LICENSE` and `DATA_LICENSE.md`: MIT license and third-party dataset attribution.
28
+
29
+ Optimizer/RNG state, raw/cleaned story data, private filesystem paths, user prompts, and training logs are **not** included. Original checkpoints remain private. Full project source is maintained at [ybj91/tiny-english-30m](https://github.com/ybj91/tiny-english-30m), a private repository; public users do not need access because inference code is bundled here.
30
+
31
+ ## Download and run
32
+
33
+ Use Python 3.11 or 3.12. Install CPU PyTorch or a CUDA-enabled build appropriate for your machine before installing the other dependencies.
34
+
35
+ ```bash
36
+ python -m pip install huggingface-hub
37
+ python -c "from huggingface_hub import snapshot_download; snapshot_download('helloboy91/tiny-english-30m', revision='v0.1.0', local_dir='tiny-english-30m')"
38
+ cd tiny-english-30m
39
+ python -m pip install -r requirements.txt
40
+ python -m tiny_english.generate --model-dir . --prompt "Once upon a time, a little rabbit found a blue hat." --max-new-tokens 100 --temperature 0.7 --seed 42
41
+ ```
42
+
43
+ For CUDA inference, install CUDA-enabled PyTorch and add `--device cuda`. CPU FP32 inference and export round trips are tested; no GPU was available for verification. The model runs locally; prompts/results are not uploaded.
44
+
45
+ This is a **custom PyTorch format**, not a Transformers `AutoModelForCausalLM.from_pretrained` export. No `trust_remote_code` or Hub inference widget is required. Review the bundled Python code before running it. The CLI works without access to the private GitHub repository.
46
+
47
+ Python usage, from the downloaded directory:
48
+
49
+ ```python
50
+ import torch
51
+ from tiny_english.generate import complete, load_export
52
+
53
+ torch.set_num_threads(4)
54
+ model, tokenizer, step = load_export(".")
55
+ result = complete(model, tokenizer, "A little cat found a red box.",
56
+ max_new_tokens=100, temperature=0.7, top_k=40, seed=42)
57
+ print(result["text"])
58
+ ```
59
+
60
+ The generator recomputes attention without a KV cache, uses a sliding window for long continuations, and stops at EOS or the output limit. Seeded results may differ across devices/software.
61
+
62
+ ## Architecture
63
+
64
+ | Setting | Value |
65
+ | --- | --- |
66
+ | Blocks / hidden width | 8 / 512 |
67
+ | Attention | 8 causal heads, head size 64 |
68
+ | Feed-forward | SwiGLU, intermediate width 1,408 |
69
+ | Positions / normalization | RoPE / RMSNorm, epsilon 1e-5 |
70
+ | Vocabulary | 8,192 byte-level BPE tokens |
71
+ | Context | 1,024 tokens |
72
+ | Embeddings | Tied input/output weights |
73
+ | Training/export precision | FP32 |
74
+ | Bias / dropout | None |
75
+
76
+ ## Training data
77
+
78
+ Source: [roneneldan/TinyStories](https://huggingface.co/datasets/roneneldan/TinyStories), revision `f54c09fd23315a6f9c86f9dc80f725de7d8f9c64`, by Ronen Eldan and Yuanzhi Li; [paper](https://arxiv.org/abs/2305.07759). Its card describes synthetic stories generated with GPT-3.5 and GPT-4. The dataset license is **CDLA-Sharing-1.0**, separate from this release’s MIT license. See `DATA_LICENSE.md` for attribution and the official license link.
79
+
80
+ The first 100,000 source training records were scanned. Unicode/whitespace normalization and length, letter, URL/markup filters removed 1,303 records; normalized-text hashes removed 999 duplicates. Whole-story hashes assigned approximately 99% train / 0.5% validation / 0.5% test:
81
+
82
+ | Split | Stories | Packed tokens |
83
+ | --- | ---: | ---: |
84
+ | Train | 96,704 | 20,097,225 |
85
+ | Validation | 498 | 105,076 |
86
+ | Test | 496 | 102,851 |
87
+
88
+ The tokenizer was trained only on training text. EOS separates stories; attention is not reset at those boundaries. Windows are sampled with replacement, so processed tokens are not unique coverage or exact epochs. The official dataset validation split was not used. Deduplication does not detect semantic paraphrases, and the letter heuristic is not a language detector.
89
+
90
+ ## Selected checkpoint
91
+
92
+ **This release has 44,699,648 processed training tokens.** The experiment finished at 45,006,848, but validation selected an earlier checkpoint in the final stage.
93
+
94
+ | Stage contribution | Tokens in this checkpoint |
95
+ | --- | ---: |
96
+ | Initial pilot | 5,001,216 |
97
+ | Additional 10M stage | 10,002,432 |
98
+ | Final stage, selected update 7,250 | 29,696,000 |
99
+ | Total | 44,699,648 |
100
+
101
+ Each stage loads selected prior weights and resets AdamW with a fresh 2% warmup/cosine schedule. Peak learning rates: 0.001, 0.0003, 0.0003; each decays to 10% of peak. Batch: 4,096 tokens/update (microbatch 1, context 1,024, accumulation 4); seeds 42, 43, 44. Weight decay 0.1 for matrices, zero for norms; betas (0.9, 0.95); gradient clipping 1.0. Training used an 8-core / 16-thread EPYC 7763 Windows environment with 8 PyTorch threads.
102
+
103
+ ## Evaluation
104
+
105
+ Full validation was rerun on exported FP32 weights using token-weighted next-token cross-entropy and sequential nonoverlapping target blocks; context resets between blocks.
106
+
107
+ | Metric | Result |
108
+ | --- | ---: |
109
+ | Predicted validation tokens | 105,075 |
110
+ | Cross-entropy loss (natural log) | 2.000095448690229 |
111
+ | Perplexity | 7.389761408317215 |
112
+ | Selected-stage sampled validation loss | 2.072966253757477 |
113
+
114
+ Sampled evaluation uses different windows. The held-out test split has **not** been evaluated. These scores are not directly comparable with published TinyStories benchmarks using different tokenizers/splits. Exported tensors and fixed-input logits matched the source checkpoint exactly.
115
+
116
+ ## Limitations
117
+
118
+ - Intended for education, small-model research, and simple English completion experiments.
119
+ - Output can repeat, change characters/objects, lose context, or become implausible. Low loss is not proof of useful reasoning.
120
+ - No instruction tuning, tool-use SFT, preference optimization, or RL has been performed.
121
+ - Do not rely on output for factual or consequential decisions. No multilingual or specialized-domain capability is claimed.
122
+ - Data contamination, memorization, and comprehensive content-quality audits have not been performed. Review generated output before use.
123
+
124
+ ## Continuing training
125
+
126
+ This release contains weights, **not** an optimizer-resumable checkpoint or dataset. Owners of the private project can use its `--init-from` option with this export directory for a new CPU/CUDA stage. Transfer the exact `data/pilot-5m` directory separately so tokenizer/data hashes match. No raw stories are distributed here. Use `--resume` only with a full checkpoint from an unfinished stage with matching schedule.
127
+
128
+ ## License
129
+
130
+ MIT for the weights, trained tokenizer, bundled inference code, and release documentation, to the extent of the author’s rights. Third-party datasets and dependencies retain their licenses. See `LICENSE` and `DATA_LICENSE.md`.
SHA256SUMS ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ae62cedfff3832585ac34367c6d808747b3b3844a07fd381be7622066093c007 DATA_LICENSE.md
2
+ fd8cf1707527ad62c0c56cb6a68c09477d76b4bf8c790ad642fae2951cc9b966 LICENSE
3
+ b0684c0389e523f9371c5ce70b947be261c4eafb284e223cd7823c55205ce1e3 README.md
4
+ 354bcf17c4b19261c304bfdf7eb132e95f9bbc28e6a29a76ecd47b140f7c4fba config.json
5
+ a1f339ffd3fb847b7313f1d98b8279848ca458037560c188d7778ea1b6e39a76 evaluation.json
6
+ 5433d30fb4100f6a221452ce3d3e7c2dcf42bbf32e1e028a5ab9f300a3b91a79 model.safetensors
7
+ 8c69762e727a7f04485f43eecb9113006e1310e4daf3aab26ac289756af1e4d5 requirements.txt
8
+ b3de87b2280eebe60633f9182e46e29dad33dd22aa32c6e44c0667ee8ce2788f tiny_english/__init__.py
9
+ f2bb78e67e66bffd843bf7a44fca2a0c3085185b83a75b32d1c0ba6b7d3a2f25 tiny_english/artifacts.py
10
+ e1a94fe3d44c59980f1a260d51afc0f55fff71f3025dbfd3a9a047e0ab1f1618 tiny_english/generate.py
11
+ ee8839343ebd52348e7ac30f38b234b75f712c953f42cf784d720c9d20ace2cc tiny_english/model.py
12
+ f404d4aed5aa3a00c1c6c45e3a39df810eae24e59cef02182343ab6cb1434fcd tokenizer.json
13
+ 93b0c192cb1970d41bd7fee199f11466f8a2cfdddea91f1fba3de20dd22862ad training_summary.json
config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format": "tiny-english-safetensors-v1",
3
+ "architectures": [
4
+ "LanguageModel"
5
+ ],
6
+ "model_config": {
7
+ "vocab_size": 8192,
8
+ "context_length": 1024,
9
+ "layers": 8,
10
+ "hidden_size": 512,
11
+ "heads": 8,
12
+ "intermediate_size": 1408
13
+ },
14
+ "dtype": "float32",
15
+ "parameter_count": 29893120,
16
+ "checkpoint_step": 7250,
17
+ "stage_tokens": 29696000,
18
+ "previous_tokens": 15003648,
19
+ "training_tokens": 44699648,
20
+ "tokenizer_sha256": "f404d4aed5aa3a00c1c6c45e3a39df810eae24e59cef02182343ab6cb1434fcd",
21
+ "weights_sha256": "5433d30fb4100f6a221452ce3d3e7c2dcf42bbf32e1e028a5ab9f300a3b91a79",
22
+ "data_manifest_sha256": "8a7366d25a937781de35b19d0a9ab4b63981a8e401102b414ce40a71665a4ef5",
23
+ "eos_token_id": 1,
24
+ "unk_token_id": 0
25
+ }
evaluation.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "checkpoint_step": 7250,
3
+ "training_tokens": 44699648,
4
+ "split": "validation",
5
+ "predicted_tokens": 105075,
6
+ "loss": 2.000095448690229,
7
+ "perplexity": 7.389761408317215,
8
+ "method": "Token-weighted next-token cross-entropy; sequential nonoverlapping targets; context resets between blocks",
9
+ "context_length": 1024,
10
+ "precision": "float32",
11
+ "test_split_evaluated": false,
12
+ "export_tensors_and_probe_logits_match_source_exactly": true
13
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5433d30fb4100f6a221452ce3d3e7c2dcf42bbf32e1e028a5ab9f300a3b91a79
3
+ size 119578064
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ torch>=2.5,<3
2
+ tokenizers>=0.21,<1
3
+ safetensors>=0.5,<1
4
+ huggingface-hub>=0.28,<2
tiny_english/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Tiny English model training, evaluation, and local inference."""
tiny_english/artifacts.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ from pathlib import Path
3
+
4
+
5
+ def digest_file(path):
6
+ with Path(path).open("rb") as handle:
7
+ return hashlib.file_digest(handle, "sha256").hexdigest()
tiny_english/generate.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import math
4
+ import time
5
+ from pathlib import Path
6
+
7
+ import torch
8
+ from tokenizers import Tokenizer
9
+
10
+ from .model import LanguageModel, ModelConfig
11
+ from .artifacts import digest_file
12
+
13
+
14
+ def load_model(checkpoint_path, tokenizer_path, device="cpu"):
15
+ checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=True)
16
+ if digest_file(tokenizer_path) != checkpoint["tokenizer_sha256"]:
17
+ raise ValueError("Tokenizer does not match checkpoint")
18
+ tokenizer = Tokenizer.from_file(str(tokenizer_path))
19
+ model = LanguageModel(ModelConfig(**checkpoint["config"]))
20
+ if tokenizer.get_vocab_size() != model.config.vocab_size:
21
+ raise ValueError("Tokenizer vocabulary does not match model")
22
+ model.load_state_dict(checkpoint["model"])
23
+ step = checkpoint["step"]
24
+ del checkpoint
25
+ return model.to(device).eval(), tokenizer, step
26
+
27
+
28
+ def load_export(directory, device="cpu"):
29
+ from safetensors.torch import load_file
30
+ directory = Path(directory)
31
+ metadata = json.loads((directory / "config.json").read_text(encoding="utf-8"))
32
+ if metadata.get("format") != "tiny-english-safetensors-v1":
33
+ raise ValueError("Unsupported exported model format")
34
+ tokenizer_path = directory / "tokenizer.json"
35
+ weights_path = directory / "model.safetensors"
36
+ if digest_file(tokenizer_path) != metadata["tokenizer_sha256"]:
37
+ raise ValueError("Export tokenizer checksum does not match")
38
+ if digest_file(weights_path) != metadata["weights_sha256"]:
39
+ raise ValueError("Export weights checksum does not match")
40
+ tokenizer = Tokenizer.from_file(str(tokenizer_path))
41
+ model = LanguageModel(ModelConfig(**metadata["model_config"]))
42
+ if tokenizer.get_vocab_size() != model.config.vocab_size:
43
+ raise ValueError("Export tokenizer vocabulary does not match model")
44
+ model.load_state_dict(load_file(str(weights_path), device="cpu"), strict=True)
45
+ return model.to(device).eval(), tokenizer, metadata["checkpoint_step"]
46
+
47
+
48
+ def complete(model, tokenizer, prompt, max_new_tokens=150, temperature=0.8, top_k=40, seed=42, deadline=None, strict_context=False):
49
+ if not isinstance(prompt, str) or not prompt.strip():
50
+ raise ValueError("Prompt must not be empty")
51
+ if not math.isfinite(temperature) or temperature <= 0 or top_k < 1 or max_new_tokens < 1:
52
+ raise ValueError("Generation numeric options must be positive and finite")
53
+ tokens = tokenizer.encode(prompt).ids
54
+ prompt_tokens = len(tokens)
55
+ if not tokens:
56
+ raise ValueError("Prompt must contain tokens")
57
+ if strict_context and prompt_tokens > model.config.context_length:
58
+ raise ValueError(f"Prompt has {prompt_tokens} tokens; the maximum is {model.config.context_length}. Shorten the prompt.")
59
+ device = model.embedding.weight.device
60
+ generator = torch.Generator(device=device).manual_seed(seed)
61
+ finish_reason = "length"
62
+ with torch.inference_mode():
63
+ for _ in range(max_new_tokens):
64
+ if deadline is not None and time.monotonic() >= deadline:
65
+ raise TimeoutError("Generation exceeded its time limit. Try fewer tokens or a shorter prompt.")
66
+ inputs = torch.tensor([tokens[-model.config.context_length:]], device=device)
67
+ logits = model(inputs)[0, -1].float() / temperature
68
+ values, indices = logits.topk(min(top_k, logits.numel()))
69
+ next_token = indices[torch.multinomial(values.softmax(-1), 1, generator=generator)].item()
70
+ if next_token == tokenizer.token_to_id("<eos>"):
71
+ finish_reason = "eos"
72
+ break
73
+ tokens.append(next_token)
74
+ return {
75
+ "text": tokenizer.decode(tokens),
76
+ "completion": tokenizer.decode(tokens[prompt_tokens:]),
77
+ "prompt_tokens": prompt_tokens, "generated_tokens": len(tokens) - prompt_tokens,
78
+ "context_length": model.config.context_length, "finish_reason": finish_reason,
79
+ "sliding_context": len(tokens) > model.config.context_length,
80
+ }
81
+
82
+
83
+ def main():
84
+ parser = argparse.ArgumentParser(description="Continue a simple English prompt")
85
+ source = parser.add_mutually_exclusive_group(required=True)
86
+ source.add_argument("--checkpoint", help="Local training checkpoint")
87
+ source.add_argument("--model-dir", type=Path, help="Downloaded/exported safetensors model directory")
88
+ parser.add_argument("--tokenizer", help="Required with --checkpoint; inferred for --model-dir")
89
+ parser.add_argument("--prompt", default="Once upon a time, a little rabbit found a blue hat.")
90
+ parser.add_argument("--max-new-tokens", type=int, default=150)
91
+ parser.add_argument("--temperature", type=float, default=0.8)
92
+ parser.add_argument("--top-k", type=int, default=40)
93
+ parser.add_argument("--device", choices=["cpu", "cuda"], default="cpu")
94
+ parser.add_argument("--threads", type=int, default=8)
95
+ parser.add_argument("--seed", type=int, default=42)
96
+ args = parser.parse_args()
97
+ if args.checkpoint and not args.tokenizer:
98
+ parser.error("--tokenizer is required with --checkpoint")
99
+ if args.model_dir and args.tokenizer:
100
+ parser.error("--model-dir uses its own tokenizer.json; omit --tokenizer")
101
+ if not math.isfinite(args.temperature) or args.temperature <= 0 or args.top_k < 1 or args.max_new_tokens < 1 or args.threads < 1:
102
+ parser.error("Generation numeric options must be positive")
103
+ torch.set_num_threads(args.threads)
104
+ model, tokenizer, _ = load_export(args.model_dir, args.device) if args.model_dir else load_model(args.checkpoint, args.tokenizer, args.device)
105
+ try:
106
+ result = complete(model, tokenizer, args.prompt, args.max_new_tokens, args.temperature, args.top_k, args.seed)
107
+ except ValueError as error:
108
+ parser.error(str(error))
109
+ print(result["text"])
110
+
111
+
112
+ if __name__ == "__main__":
113
+ main()
tiny_english/model.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import asdict, dataclass
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as functional
6
+
7
+
8
+ @dataclass
9
+ class ModelConfig:
10
+ vocab_size: int = 8192
11
+ context_length: int = 1024
12
+ layers: int = 8
13
+ hidden_size: int = 512
14
+ heads: int = 8
15
+ intermediate_size: int = 1408
16
+
17
+ def __post_init__(self):
18
+ if any(value <= 0 for value in asdict(self).values()):
19
+ raise ValueError("All model dimensions must be positive")
20
+ if self.hidden_size % self.heads or (self.hidden_size // self.heads) % 2:
21
+ raise ValueError("Head dimension must be an even integer")
22
+
23
+
24
+ class Attention(nn.Module):
25
+ def __init__(self, config):
26
+ super().__init__()
27
+ self.heads = config.heads
28
+ self.head_size = config.hidden_size // config.heads
29
+ self.qkv = nn.Linear(config.hidden_size, 3 * config.hidden_size, bias=False)
30
+ self.output = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
31
+ frequencies = 1.0 / (10000 ** (torch.arange(0, self.head_size, 2).float() / self.head_size))
32
+ angles = torch.outer(torch.arange(config.context_length).float(), frequencies)
33
+ self.register_buffer("cosines", angles.cos(), persistent=False)
34
+ self.register_buffer("sines", angles.sin(), persistent=False)
35
+
36
+ def rotate(self, tensor):
37
+ length = tensor.size(-2)
38
+ cosines = self.cosines[:length].to(tensor.dtype)
39
+ sines = self.sines[:length].to(tensor.dtype)
40
+ even, odd = tensor[..., 0::2], tensor[..., 1::2]
41
+ return torch.stack((even * cosines - odd * sines, even * sines + odd * cosines), dim=-1).flatten(-2)
42
+
43
+ def forward(self, hidden):
44
+ batch_size, length, width = hidden.shape
45
+ query, key, value = self.qkv(hidden).reshape(batch_size, length, 3, self.heads, self.head_size).unbind(2)
46
+ attended = functional.scaled_dot_product_attention(
47
+ self.rotate(query.transpose(1, 2)),
48
+ self.rotate(key.transpose(1, 2)),
49
+ value.transpose(1, 2),
50
+ is_causal=True,
51
+ )
52
+ return self.output(attended.transpose(1, 2).contiguous().view(batch_size, length, width))
53
+
54
+
55
+ class Block(nn.Module):
56
+ def __init__(self, config):
57
+ super().__init__()
58
+ self.attention_norm = nn.RMSNorm(config.hidden_size, eps=1e-5)
59
+ self.attention = Attention(config)
60
+ self.ffn_norm = nn.RMSNorm(config.hidden_size, eps=1e-5)
61
+ self.gate = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
62
+ self.up = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
63
+ self.down = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
64
+
65
+ def forward(self, hidden):
66
+ hidden = hidden + self.attention(self.attention_norm(hidden))
67
+ normalized = self.ffn_norm(hidden)
68
+ return hidden + self.down(functional.silu(self.gate(normalized)) * self.up(normalized))
69
+
70
+
71
+ class LanguageModel(nn.Module):
72
+ def __init__(self, config):
73
+ super().__init__()
74
+ self.config = config
75
+ self.embedding = nn.Embedding(config.vocab_size, config.hidden_size)
76
+ self.blocks = nn.ModuleList([Block(config) for _ in range(config.layers)])
77
+ self.norm = nn.RMSNorm(config.hidden_size, eps=1e-5)
78
+ self.apply(self.initialize)
79
+
80
+ @staticmethod
81
+ def initialize(module):
82
+ if isinstance(module, (nn.Linear, nn.Embedding)):
83
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
84
+
85
+ def forward(self, tokens, targets=None):
86
+ if tokens.size(1) > self.config.context_length:
87
+ raise ValueError("Input exceeds context length")
88
+ hidden = self.embedding(tokens)
89
+ for block in self.blocks:
90
+ hidden = block(hidden)
91
+ hidden = self.norm(hidden)
92
+ if targets is None:
93
+ return functional.linear(hidden[:, -1:, :], self.embedding.weight)
94
+ logits = functional.linear(hidden, self.embedding.weight)
95
+ return functional.cross_entropy(logits.reshape(-1, self.config.vocab_size), targets.reshape(-1))
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
training_summary.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "roneneldan/TinyStories",
3
+ "revision": "f54c09fd23315a6f9c86f9dc80f725de7d8f9c64",
4
+ "source_split": "train",
5
+ "source_records_scanned": 100000,
6
+ "counts": {
7
+ "scanned": 100000,
8
+ "train": 96704,
9
+ "filtered": 1303,
10
+ "validation": 498,
11
+ "test": 496,
12
+ "duplicates": 999
13
+ },
14
+ "corpus_tokens": {
15
+ "train": 20097225,
16
+ "validation": 105076,
17
+ "test": 102851
18
+ },
19
+ "split_policy": "normalized-text SHA256 modulo 1000: test 0-4, validation 5-9, train 10-999",
20
+ "filter_version": 1,
21
+ "source_checkpoint_sha256": "9de2516e9f97cb7de9e041da63b898f11ca9ebb62a75cde8b20aa9d8285059aa",
22
+ "data_manifest_sha256": "8a7366d25a937781de35b19d0a9ab4b63981a8e401102b414ce40a71665a4ef5",
23
+ "checkpoint_step": 7250,
24
+ "stage_tokens": 29696000,
25
+ "previous_tokens": 15003648,
26
+ "training_tokens": 44699648,
27
+ "sampled_validation_loss": 2.072966253757477,
28
+ "export_dtype": "float32",
29
+ "optimizer_state_included": false
30
+ }