Release Alloy 312M 2K v0.1.0
Browse files- DATA_LICENSE.md +11 -0
- LICENSE +21 -0
- README.md +61 -0
- config.json +25 -0
- model.safetensors +3 -0
- requirements.txt +4 -0
- tiny_english/__init__.py +1 -0
- tiny_english/artifacts.py +7 -0
- tiny_english/generate.py +113 -0
- tiny_english/model.py +107 -0
- tokenizer.json +0 -0
- training_summary.json +35 -0
DATA_LICENSE.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
| 10 |
+
|
| 11 |
+
The **separate private data-transfer repository**, [helloboy91/tiny-english-pilot-5m-data](https://huggingface.co/datasets/helloboy91/tiny-english-pilot-5m-data), now preserves the prepared corpus under CDLA-Sharing-1.0, with the unmodified license, upstream card, and modification/attribution notice. It is not part of the MIT model release. Private access control does not add restrictions on the rights granted to authorized recipients under CDLA. See [dataset card source](DATASET_CARD.md).
|
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,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
+
license: mit
|
| 5 |
+
pipeline_tag: text-generation
|
| 6 |
+
tags:
|
| 7 |
+
- base-model
|
| 8 |
+
- causal-lm
|
| 9 |
+
- experimental
|
| 10 |
+
- english
|
| 11 |
+
- from-scratch
|
| 12 |
+
- 312m
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# Alloy 312M 2K
|
| 16 |
+
|
| 17 |
+
Alloy is an experimental 311.9M-parameter English causal language model with a 2,048-token context window. It is a base model, not an instruction-following assistant. This release packages the best checkpoint after **5.0003B training tokens** in an inference-only format; optimizer state, raw training data, and private machine paths are not included.
|
| 18 |
+
|
| 19 |
+
## Why this model exists
|
| 20 |
+
|
| 21 |
+
This is a transparent small-model training project. Rather than treating data as a fixed black box, we trained in stages, evaluated each stage, inspected failure modes such as repetition and corrupted/non-English text, and revised the next corpus accordingly.
|
| 22 |
+
|
| 23 |
+
1. **Bronze, Silver, Gold**: three 1B-token stages established a shared 32,768-token byte-level BPE tokenizer and a 2K-context decoder-only model.
|
| 24 |
+
2. **Lead / Alloy**: a 2B-token continuation used a pinned public-source mix: FineWeb-Edu (`CC-MAIN-2025-26`), English Wikipedia (`20231101.en`), and TinyStories. FineWeb-Edu documents had upstream quality score >= 3; all sources then passed English-probability, Unicode/corruption, boilerplate, URL/fragment, and repeated-text filters. Source-shard holdouts separated training from validation and test. Line breaks were deliberately preserved.
|
| 25 |
+
3. The completed Alloy checkpoint was selected by its independent matching validation split, then evaluated zero-shot without prompt tuning.
|
| 26 |
+
|
| 27 |
+
The source revisions, filters, tokenizer hash, model configuration, and data manifest hash are recorded in `training_summary.json` and `config.json`. These are quality controls, not a guarantee of factual accuracy, decontamination, or absence of duplicates.
|
| 28 |
+
|
| 29 |
+
## Evaluation
|
| 30 |
+
|
| 31 |
+
Full zero-shot evaluation used `lm-evaluation-harness` 0.4.13, batch size 1, no bootstrap resampling, and the native checkpoint. `standard-eval.json` contains the complete protocol and raw result.
|
| 32 |
+
|
| 33 |
+
| Task | Raw accuracy |
|
| 34 |
+
| --- | ---: |
|
| 35 |
+
| ARC-Easy | 49.92% |
|
| 36 |
+
| ARC-Challenge | 21.42% |
|
| 37 |
+
| HellaSwag | 29.87% |
|
| 38 |
+
| PIQA | 62.95% |
|
| 39 |
+
| SciQ | 71.90% |
|
| 40 |
+
| WinoGrande | 50.67% |
|
| 41 |
+
|
| 42 |
+
These scores show clear progress over the project’s earlier checkpoints, but they do not make Alloy competitive with mature, heavily trained public models of a similar parameter count. Benchmark contamination and harness-version differences remain possible; do not compare scores across protocols as exact leaderboard rankings.
|
| 43 |
+
|
| 44 |
+
## Use
|
| 45 |
+
|
| 46 |
+
This repository is a native safetensors export rather than a Transformers `AutoModel` package. It includes the minimal `tiny_english` inference module.
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
pip install -r requirements.txt
|
| 50 |
+
python -m tiny_english.generate --model-dir . --prompt "The invention of the printing press changed" --max-new-tokens 128 --temperature 0.7 --top-k 40 --seed 42
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
Generation can repeat phrases, make factual errors, or produce incoherent continuations. Do not use it for high-stakes decisions or as an assistant without additional evaluation and alignment work.
|
| 54 |
+
|
| 55 |
+
## Continue the work
|
| 56 |
+
|
| 57 |
+
Contributions and continuation experiments are welcome. Please retain the tokenizer and 2K context contract, report the exact data mixture and token count, keep independent validation/test data, and publish the same zero-shot evaluation protocol alongside qualitative samples. The next planned direction is supervised fine-tuning (SFT) on carefully curated instruction data, so the base model can become more specifically usable while preserving a transparent base-model checkpoint for comparison.
|
| 58 |
+
|
| 59 |
+
## Data, license, and limitations
|
| 60 |
+
|
| 61 |
+
Model weights, tokenizer, and bundled inference code are released under MIT. The training sources remain subject to their own terms: FineWeb-Edu, [Wikimedia Wikipedia](https://huggingface.co/datasets/wikimedia/wikipedia), and [TinyStories](https://huggingface.co/datasets/roneneldan/TinyStories). No raw source documents or prepared token datasets are included here. Review the upstream dataset licenses and documentation before redistributing data or training derivatives.
|
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": 32768,
|
| 8 |
+
"context_length": 2048,
|
| 9 |
+
"layers": 22,
|
| 10 |
+
"hidden_size": 1024,
|
| 11 |
+
"heads": 16,
|
| 12 |
+
"intermediate_size": 2752
|
| 13 |
+
},
|
| 14 |
+
"dtype": "float32",
|
| 15 |
+
"parameter_count": 311866368,
|
| 16 |
+
"checkpoint_step": 15259,
|
| 17 |
+
"stage_tokens": 2000027648,
|
| 18 |
+
"previous_tokens": 3000238080,
|
| 19 |
+
"training_tokens": 5000265728,
|
| 20 |
+
"tokenizer_sha256": "40d36acc35e5364d90fdcdae773143b7571b5ec3b7ace2030d12d4bd5a3a1025",
|
| 21 |
+
"weights_sha256": "1255d10b05add1834ebe0ee05cd65f0173b57448b26b2b0ff203c29a761e9a50",
|
| 22 |
+
"data_manifest_sha256": "cf6ca78377e03aef753b073d25f710d665de31f0a91d285032955feecc565934",
|
| 23 |
+
"eos_token_id": 1,
|
| 24 |
+
"unk_token_id": 0
|
| 25 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1255d10b05add1834ebe0ee05cd65f0173b57448b26b2b0ff203c29a761e9a50
|
| 3 |
+
size 1247481064
|
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,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import asdict, dataclass
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
from torch.nn import functional as functional
|
| 6 |
+
from torch.utils.checkpoint import checkpoint
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@dataclass
|
| 10 |
+
class ModelConfig:
|
| 11 |
+
vocab_size: int = 8192
|
| 12 |
+
context_length: int = 1024
|
| 13 |
+
layers: int = 8
|
| 14 |
+
hidden_size: int = 512
|
| 15 |
+
heads: int = 8
|
| 16 |
+
intermediate_size: int = 1408
|
| 17 |
+
|
| 18 |
+
def __post_init__(self):
|
| 19 |
+
if any(value <= 0 for value in asdict(self).values()):
|
| 20 |
+
raise ValueError("All model dimensions must be positive")
|
| 21 |
+
if self.hidden_size % self.heads or (self.hidden_size // self.heads) % 2:
|
| 22 |
+
raise ValueError("Head dimension must be an even integer")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Attention(nn.Module):
|
| 26 |
+
def __init__(self, config):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.heads = config.heads
|
| 29 |
+
self.head_size = config.hidden_size // config.heads
|
| 30 |
+
self.qkv = nn.Linear(config.hidden_size, 3 * config.hidden_size, bias=False)
|
| 31 |
+
self.output = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
| 32 |
+
frequencies = 1.0 / (10000 ** (torch.arange(0, self.head_size, 2).float() / self.head_size))
|
| 33 |
+
angles = torch.outer(torch.arange(config.context_length).float(), frequencies)
|
| 34 |
+
self.register_buffer("cosines", angles.cos(), persistent=False)
|
| 35 |
+
self.register_buffer("sines", angles.sin(), persistent=False)
|
| 36 |
+
|
| 37 |
+
def rotate(self, tensor):
|
| 38 |
+
length = tensor.size(-2)
|
| 39 |
+
cosines = self.cosines[:length].to(tensor.dtype)
|
| 40 |
+
sines = self.sines[:length].to(tensor.dtype)
|
| 41 |
+
even, odd = tensor[..., 0::2], tensor[..., 1::2]
|
| 42 |
+
return torch.stack((even * cosines - odd * sines, even * sines + odd * cosines), dim=-1).flatten(-2)
|
| 43 |
+
|
| 44 |
+
def forward(self, hidden):
|
| 45 |
+
batch_size, length, width = hidden.shape
|
| 46 |
+
query, key, value = self.qkv(hidden).reshape(batch_size, length, 3, self.heads, self.head_size).unbind(2)
|
| 47 |
+
attended = functional.scaled_dot_product_attention(
|
| 48 |
+
self.rotate(query.transpose(1, 2)),
|
| 49 |
+
self.rotate(key.transpose(1, 2)),
|
| 50 |
+
value.transpose(1, 2),
|
| 51 |
+
is_causal=True,
|
| 52 |
+
)
|
| 53 |
+
return self.output(attended.transpose(1, 2).contiguous().view(batch_size, length, width))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class Block(nn.Module):
|
| 57 |
+
def __init__(self, config):
|
| 58 |
+
super().__init__()
|
| 59 |
+
self.attention_norm = nn.RMSNorm(config.hidden_size, eps=1e-5)
|
| 60 |
+
self.attention = Attention(config)
|
| 61 |
+
self.ffn_norm = nn.RMSNorm(config.hidden_size, eps=1e-5)
|
| 62 |
+
self.gate = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 63 |
+
self.up = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 64 |
+
self.down = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 65 |
+
|
| 66 |
+
def forward(self, hidden):
|
| 67 |
+
hidden = hidden + self.attention(self.attention_norm(hidden))
|
| 68 |
+
normalized = self.ffn_norm(hidden)
|
| 69 |
+
return hidden + self.down(functional.silu(self.gate(normalized)) * self.up(normalized))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class LanguageModel(nn.Module):
|
| 73 |
+
def __init__(self, config):
|
| 74 |
+
super().__init__()
|
| 75 |
+
self.config = config
|
| 76 |
+
self.embedding = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 77 |
+
self.blocks = nn.ModuleList([Block(config) for _ in range(config.layers)])
|
| 78 |
+
self.norm = nn.RMSNorm(config.hidden_size, eps=1e-5)
|
| 79 |
+
self.gradient_checkpointing = False
|
| 80 |
+
self.apply(self.initialize)
|
| 81 |
+
|
| 82 |
+
def set_gradient_checkpointing(self, enabled):
|
| 83 |
+
self.gradient_checkpointing = enabled
|
| 84 |
+
|
| 85 |
+
@staticmethod
|
| 86 |
+
def initialize(module):
|
| 87 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
| 88 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 89 |
+
|
| 90 |
+
def forward(self, tokens, targets=None, return_logits=False, logit_positions=None):
|
| 91 |
+
if tokens.size(1) > self.config.context_length:
|
| 92 |
+
raise ValueError("Input exceeds context length")
|
| 93 |
+
hidden = self.embedding(tokens)
|
| 94 |
+
for block in self.blocks:
|
| 95 |
+
if self.gradient_checkpointing and self.training and torch.is_grad_enabled():
|
| 96 |
+
hidden = checkpoint(block, hidden, use_reentrant=False)
|
| 97 |
+
else:
|
| 98 |
+
hidden = block(hidden)
|
| 99 |
+
hidden = self.norm(hidden)
|
| 100 |
+
if logit_positions is not None:
|
| 101 |
+
hidden = hidden[:, logit_positions, :]
|
| 102 |
+
if targets is None and not return_logits:
|
| 103 |
+
return functional.linear(hidden[:, -1:, :], self.embedding.weight)
|
| 104 |
+
logits = functional.linear(hidden, self.embedding.weight)
|
| 105 |
+
if targets is None:
|
| 106 |
+
return logits
|
| 107 |
+
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,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"dataset": null,
|
| 3 |
+
"revision": null,
|
| 4 |
+
"source_split": null,
|
| 5 |
+
"source_records_scanned": null,
|
| 6 |
+
"counts": null,
|
| 7 |
+
"corpus_tokens": {
|
| 8 |
+
"train": {
|
| 9 |
+
"fineweb_edu": 1400000000,
|
| 10 |
+
"english_wikipedia": 500000000,
|
| 11 |
+
"narrative": 100000000
|
| 12 |
+
},
|
| 13 |
+
"validation": {
|
| 14 |
+
"fineweb_edu": 700000,
|
| 15 |
+
"english_wikipedia": 250000,
|
| 16 |
+
"narrative": 50000
|
| 17 |
+
},
|
| 18 |
+
"test": {
|
| 19 |
+
"fineweb_edu": 700000,
|
| 20 |
+
"english_wikipedia": 250000,
|
| 21 |
+
"narrative": 50000
|
| 22 |
+
}
|
| 23 |
+
},
|
| 24 |
+
"split_policy": "Canonical source-document SHA256 buckets: test 0-9, validation 10-19, train 20-999; global passage dedup across splits and Bronze, Silver, and Gold-1",
|
| 25 |
+
"filter_version": null,
|
| 26 |
+
"source_checkpoint_sha256": "928865f44252b3ff38a23f7ced73f4986e3e3951673be035b824ec15e5ee1306",
|
| 27 |
+
"data_manifest_sha256": "cf6ca78377e03aef753b073d25f710d665de31f0a91d285032955feecc565934",
|
| 28 |
+
"checkpoint_step": 15259,
|
| 29 |
+
"stage_tokens": 2000027648,
|
| 30 |
+
"previous_tokens": 3000238080,
|
| 31 |
+
"training_tokens": 5000265728,
|
| 32 |
+
"sampled_validation_loss": 2.609314309898764,
|
| 33 |
+
"export_dtype": "float32",
|
| 34 |
+
"optimizer_state_included": false
|
| 35 |
+
}
|