AlmostNobody commited on
Commit
5b3859c
·
verified ·
1 Parent(s): 4882d91

Upload 6 files

Browse files
Files changed (6) hide show
  1. LICENSE +21 -0
  2. README.md +136 -0
  3. Untitled8.ipynb +0 -0
  4. final_model.pt +3 -0
  5. model.py +156 -0
  6. tokenizer.json +0 -0
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AlmostNobody
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 CHANGED
@@ -1,3 +1,139 @@
1
  ---
2
  license: mit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
+ language:
4
+ - en
5
+ pipeline_tag: text-generation
6
+ datasets:
7
+ - AlmostNobody/youtube-commons-clean-40k
8
+ tags:
9
+ - text-generation
10
+ - from-scratch
11
+ - small-language-model
12
+ - llama-style
13
+ - rope
14
+ - swiglu
15
+ - rmsnorm
16
+ - pytorch
17
  ---
18
+
19
+ # Pronghorn-5M-base
20
+
21
+ **Small, quick, and built from scratch.**
22
+
23
+ A 5-million-parameter, Llama-style language model, trained from scratch in under an hour on a free GPU.
24
+
25
+ <!-- Optional: add a logo by uploading logo.png to this repo and uncommenting the next line.
26
+ <p align="center"><img src="logo.png" width="160" alt="Pronghorn logo"></p>
27
+ -->
28
+
29
+ Pronghorn is my third from-scratch model and the biggest so far: 5M parameters. This time I built the
30
+ tokenizer, cleaned the dataset, and wrote the Llama-style architecture (RMSNorm, RoPE, SwiGLU) myself.
31
+ It is the successor to my earlier 1M-parameter models,
32
+ [Tinygpt-python-teacher](https://huggingface.co/AlmostNobody/Tinygpt-python-teacher) and
33
+ [Tinygpt_v2_conversation](https://huggingface.co/AlmostNobody/Tinygpt_v2_conversation).
34
+
35
+ > **This is a base model: a text continuer, not a chat assistant.** Give it the start of a sentence
36
+ > and it keeps going in the style of a spoken video transcript. It does not follow instructions or answer
37
+ > questions, and it frequently makes things up.
38
+
39
+ ## Model details
40
+
41
+ | | |
42
+ |---|---|
43
+ | Parameters | 5,078,208 |
44
+ | Architecture | Decoder-only Transformer, Llama-style, written from scratch in PyTorch |
45
+ | Layers / heads / width | 8 layers, 6 heads (32 dims each), 192 dimensions |
46
+ | Feed-forward | SwiGLU, hidden size 512 |
47
+ | Position encoding | RoPE (rotary), no learned position table |
48
+ | Normalization | RMSNorm (pre-norm), plus a final RMSNorm |
49
+ | Embeddings | Output layer shares weights with the input embedding table |
50
+ | Context length | 256 tokens |
51
+ | Tokenizer | Byte-level BPE, 8,000 tokens, trained on the same data. Special tokens: `<pad>` (id 0), `<eos>` (id 1) |
52
+
53
+ ## Training
54
+
55
+ - **Data:** [AlmostNobody/youtube-commons-clean-40k](https://huggingface.co/datasets/AlmostNobody/youtube-commons-clean-40k),
56
+ a cleaned subset of the [Common Pile Creative Commons YouTube dataset](https://huggingface.co/datasets/common-pile/youtube).
57
+ About 183.9M training tokens and 10.0M validation tokens (split by video, 95% / 5%).
58
+ An `<eos>` token marks the end of each video.
59
+ - **Steps:** 12,000 steps, batch of 64 sequences x 256 tokens (about 197M tokens seen, roughly one pass over the data).
60
+ - **Optimizer:** AdamW (betas 0.9 / 0.95, weight decay 0.1 on weight matrices, none on norms).
61
+ - **Learning rate:** 300 warmup steps up to a peak of 1e-3, then cosine decay down to a final value of 1e-4.
62
+ - **Other:** gradient clipping at 1.0, mixed precision (fp16).
63
+ - **Hardware:** one free Google Colab T4 GPU, about 50 minutes.
64
+ - **Training code:** see `training_notebook.ipynb` in this repo.
65
+
66
+ ## Results
67
+
68
+ | Metric | Value |
69
+ |---|---|
70
+ | Final validation loss | 3.756 |
71
+ | Final training loss | about 3.76 |
72
+ | Perplexity (validation) | about 43 |
73
+
74
+ Training and validation loss stayed close together, so the model was learning general patterns of the
75
+ data and not memorizing it. A model guessing randomly among 8,000 tokens would start at a loss of about 9.0.
76
+
77
+ ### Example output
78
+
79
+ Prompt: `Hi everyone, my name is`
80
+
81
+ > Hi everyone, my name is Jared. As you know me right now, I'm going to get up on our list and I'll be getting
82
+ > you a little over there as well so we've been with the Cavs. Well, I would say that's kind of a nice point...
83
+
84
+ The grammar and rhythm look like real speech, but the content is not meaningful. Names, places, and
85
+ facts it produces are invented, not recalled.
86
+
87
+ ## How to use
88
+
89
+ ```python
90
+ from huggingface_hub import snapshot_download
91
+ from tokenizers import Tokenizer
92
+ import sys
93
+
94
+ path = snapshot_download("AlmostNobody/Pronghorn-5M-base")
95
+ sys.path.insert(0, path)
96
+
97
+ from model import load_model, generate
98
+
99
+ tok = Tokenizer.from_file(f"{path}/tokenizer.json")
100
+ model = load_model(f"{path}/final_model.pt") # add device="cuda" for a GPU
101
+
102
+ print(generate(model, tok, "Welcome back to the channel. Today we are going to"))
103
+ ```
104
+
105
+ Requirements: `torch`, `tokenizers`, `huggingface_hub`.
106
+
107
+ Settings you can change in `generate`: `temperature` (lower is safer, higher is more random), `top_k`,
108
+ and `rep_penalty` (higher means fewer repeated words, but stranger word choice).
109
+
110
+ ## Limitations
111
+
112
+ - **Repetition:** small models tend to loop ("channel channel channel"). The repetition penalty helps but does not fix it.
113
+ - **No knowledge or reasoning:** it learned how spoken English sounds, not what is true.
114
+ - **Drifts off topic** after a sentence or two.
115
+ - **Short memory:** 256-token context.
116
+ - **No safety or alignment training.** It was trained only on raw transcripts, so it can produce biased or
117
+ offensive text that reflects the mix of videos in the data.
118
+ - **The training data comes from automatic transcripts,** which contain recognition errors.
119
+
120
+ ## Intended use
121
+
122
+ Learning, experiments, and a small baseline for tokenizer, architecture, or fine-tuning projects.
123
+ Not suitable for any real-world use where accuracy or safety matters.
124
+
125
+ ## License and attribution
126
+
127
+ The model weights and code are released under the **MIT License** (see `LICENSE`).
128
+
129
+ The training data is derived from the Creative Commons YouTube portion of the Common Pile (videos under
130
+ CC BY 4.0). See the [dataset page](https://huggingface.co/datasets/AlmostNobody/youtube-commons-clean-40k)
131
+ for the full attribution and a description of the changes I made. Please cite the original work:
132
+
133
+ > Kandpal, N., Lester, B., Raffel, C., et al. (2025).
134
+ > *The Common Pile v0.1: An 8TB Dataset of Public Domain and Openly Licensed Text.* arXiv:2506.05209.
135
+
136
+ ## Author
137
+
138
+ Built by [AlmostNobody](https://huggingface.co/AlmostNobody) while learning how language models work.
139
+ Questions and feedback are welcome in the Community tab.
Untitled8.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
final_model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f61e4c88496369d22bad77fa821494b57f3220663144c8b237a36c486d3b5ab6
3
+ size 20340869
model.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pronghorn: a small Llama-style language model (5,078,208 parameters).
3
+
4
+ Architecture: token embedding -> 8 x [RMSNorm -> attention with RoPE -> add back,
5
+ RMSNorm -> SwiGLU -> add back] -> RMSNorm -> output scores over the vocabulary.
6
+ The output layer shares its weights with the embedding table (weight tying).
7
+
8
+ License: MIT (see LICENSE).
9
+
10
+ Usage:
11
+ from tokenizers import Tokenizer
12
+ from model import load_model, generate
13
+
14
+ tok = Tokenizer.from_file("tokenizer.json")
15
+ model = load_model("final_model.pt")
16
+ print(generate(model, tok, "Welcome back to the channel. Today we are going to"))
17
+ """
18
+ import math
19
+ from dataclasses import dataclass
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+
25
+
26
+ @dataclass
27
+ class Config:
28
+ vocab_size: int = 8000
29
+ dim: int = 192
30
+ n_layers: int = 8
31
+ n_heads: int = 6
32
+ hidden: int = 512 # width of the SwiGLU feed-forward layer
33
+ ctx: int = 256 # context length the model was trained with
34
+
35
+
36
+ class RMSNorm(nn.Module):
37
+ def __init__(self, dim, eps=1e-6):
38
+ super().__init__()
39
+ self.eps = eps
40
+ self.scale = nn.Parameter(torch.ones(dim))
41
+
42
+ def forward(self, x):
43
+ rms = torch.sqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
44
+ return (x / rms) * self.scale
45
+
46
+
47
+ def precompute_rope(head_dim, max_len, base=10000.0):
48
+ speeds = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))
49
+ angles = torch.outer(torch.arange(max_len).float(), speeds)
50
+ return torch.cos(angles), torch.sin(angles)
51
+
52
+
53
+ def apply_rope(x, cos, sin):
54
+ # x: (batch, heads, seq_len, head_dim)
55
+ seq_len, half = x.shape[2], x.shape[-1] // 2
56
+ cos = cos[:seq_len][None, None, :, :]
57
+ sin = sin[:seq_len][None, None, :, :]
58
+ x1, x2 = x[..., :half], x[..., half:]
59
+ out = torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)
60
+ return out.type_as(x)
61
+
62
+
63
+ class Attention(nn.Module):
64
+ def __init__(self, cfg):
65
+ super().__init__()
66
+ self.n_heads = cfg.n_heads
67
+ self.head_dim = cfg.dim // cfg.n_heads
68
+ self.wq = nn.Linear(cfg.dim, cfg.dim, bias=False)
69
+ self.wk = nn.Linear(cfg.dim, cfg.dim, bias=False)
70
+ self.wv = nn.Linear(cfg.dim, cfg.dim, bias=False)
71
+ self.wo = nn.Linear(cfg.dim, cfg.dim, bias=False)
72
+
73
+ def forward(self, x, cos, sin):
74
+ B, T, C = x.shape
75
+ q = self.wq(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
76
+ k = self.wk(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
77
+ v = self.wv(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
78
+ q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
79
+ scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
80
+ mask = torch.triu(torch.ones(T, T, dtype=torch.bool, device=x.device), diagonal=1)
81
+ scores = scores.masked_fill(mask, float("-inf"))
82
+ out = F.softmax(scores, dim=-1) @ v
83
+ return self.wo(out.transpose(1, 2).contiguous().view(B, T, C))
84
+
85
+
86
+ class SwiGLU(nn.Module):
87
+ def __init__(self, cfg):
88
+ super().__init__()
89
+ self.w_gate = nn.Linear(cfg.dim, cfg.hidden, bias=False)
90
+ self.w_up = nn.Linear(cfg.dim, cfg.hidden, bias=False)
91
+ self.w_down = nn.Linear(cfg.hidden, cfg.dim, bias=False)
92
+
93
+ def forward(self, x):
94
+ return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))
95
+
96
+
97
+ class Block(nn.Module):
98
+ def __init__(self, cfg):
99
+ super().__init__()
100
+ self.norm1, self.attn = RMSNorm(cfg.dim), Attention(cfg)
101
+ self.norm2, self.ffn = RMSNorm(cfg.dim), SwiGLU(cfg)
102
+
103
+ def forward(self, x, cos, sin):
104
+ x = x + self.attn(self.norm1(x), cos, sin)
105
+ x = x + self.ffn(self.norm2(x))
106
+ return x
107
+
108
+
109
+ class Pronghorn(nn.Module):
110
+ def __init__(self, cfg=None):
111
+ super().__init__()
112
+ cfg = cfg or Config()
113
+ self.cfg = cfg
114
+ self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.dim)
115
+ self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layers)])
116
+ self.norm_f = RMSNorm(cfg.dim)
117
+ self.lm_head = nn.Linear(cfg.dim, cfg.vocab_size, bias=False)
118
+ self.lm_head.weight = self.tok_emb.weight # weight tying
119
+ cos, sin = precompute_rope(cfg.dim // cfg.n_heads, cfg.ctx)
120
+ self.register_buffer("cos", cos, persistent=False)
121
+ self.register_buffer("sin", sin, persistent=False)
122
+
123
+ def forward(self, idx):
124
+ x = self.tok_emb(idx)
125
+ for blk in self.blocks:
126
+ x = blk(x, self.cos, self.sin)
127
+ return self.lm_head(self.norm_f(x))
128
+
129
+
130
+ def load_model(weights_path, device="cpu"):
131
+ """Build the model and load the trained weights."""
132
+ model = Pronghorn(Config())
133
+ state = torch.load(weights_path, map_location="cpu")
134
+ model.load_state_dict(state)
135
+ return model.to(device).eval()
136
+
137
+
138
+ @torch.no_grad()
139
+ def generate(model, tokenizer, prompt, max_new_tokens=80, temperature=0.8,
140
+ top_k=40, rep_penalty=1.2, window=64):
141
+ """Continue a prompt. rep_penalty > 1 discourages repeating recent tokens."""
142
+ device = next(model.parameters()).device
143
+ ctx = model.cfg.ctx
144
+ x = torch.tensor([tokenizer.encode(prompt).ids], device=device)
145
+ for _ in range(max_new_tokens):
146
+ logits = model(x[:, -ctx:])[:, -1, :].float()
147
+ if rep_penalty != 1.0:
148
+ recent = x[0, -window:].unique()
149
+ vals = logits[0, recent]
150
+ logits[0, recent] = torch.where(vals > 0, vals / rep_penalty, vals * rep_penalty)
151
+ logits = logits / temperature
152
+ v, _ = torch.topk(logits, top_k)
153
+ logits[logits < v[:, [-1]]] = -float("inf")
154
+ next_id = torch.multinomial(F.softmax(logits, dim=-1), 1)
155
+ x = torch.cat([x, next_id], dim=1)
156
+ return tokenizer.decode(x[0].tolist())
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff