Brich627 commited on
Commit
50aa7f9
·
verified ·
1 Parent(s): 436c9f7

Upload folder using huggingface_hub

Browse files
Files changed (4) hide show
  1. README.md +24 -43
  2. config.json +2 -2
  3. load_model.py +20 -12
  4. model.safetensors +3 -0
README.md CHANGED
@@ -3,32 +3,23 @@ license: mit
3
  tags:
4
  - educational
5
  - from-scratch
6
- - character-level
7
  - transformer
8
  - pytorch
9
  ---
10
 
11
- # SIL-v01 — Tiny From-Scratch Language Model
12
 
13
  **This is an educational project, not a practical language model.** It is a
14
- from-scratch, char-RNN-scale transformer built to learn the mechanics of
15
- language modeling end-to-end: tokenization embeddings the
16
- language-modeling objective → training loop → self-attention → subword
17
- tokenization. It is not intended for any downstream or production use —
18
  treat it as a worked example, not a tool.
19
 
20
- The published checkpoint here is the **best-performing configuration found
21
- in a controlled scaling sweep**: a 4-layer, 4-head, causal self-attention
22
- transformer with `n_embd=128`, trained on a character-level tokenizer.
23
-
24
  ## Model architecture
25
 
26
- Token + position embeddings 4 stacked pre-norm transformer blocks
27
- (multi-head causal self-attention + feedforward, residual connections)
28
- final LayerNorm → linear head to vocab logits. Same family as a minimal
29
- GPT, at a scale that trains on a CPU in minutes. Full hyperparameters are
30
- in `config.json`; nothing about the architecture is hardcoded in the loader
31
- — see `load_model.py`.
32
 
33
  | | |
34
  |---|---|
@@ -37,21 +28,11 @@ in `config.json`; nothing about the architecture is hardcoded in the loader
37
  | n_head | 4 |
38
  | n_layer | 4 |
39
  | block_size | 32 |
40
- | Tokenizer | character-level, vocab_size=65 |
41
 
42
  ## Training corpus
43
 
44
- Trained on **TinyShakespeare** (~1.1M characters), the classic small corpus
45
- for character-level language modeling. It is fetched directly from Andrej
46
- Karpathy's `char-rnn` GitHub repository
47
- (`raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt`)
48
- — a concatenation of Shakespeare's plays, ultimately public-domain text, but
49
- sourced from that repo directly rather than downloaded from Project
50
- Gutenberg. (This project's data pipeline also includes a Project Gutenberg
51
- boilerplate-stripper for *other* corpora it experiments with — Dostoevsky,
52
- Nietzsche, Suetonius — but that path was not used for this checkpoint.)
53
-
54
- 90/10 train/val split, held fixed across every run below.
55
 
56
  ## Results
57
 
@@ -93,30 +74,30 @@ run here.
93
 
94
  | File | Purpose |
95
  |---|---|
96
- | `model.pt` | `state_dict()` of the trained `BigramLanguageModel` |
97
  | `config.json` | Every hyperparameter needed to reconstruct the architecture and tokenizer |
98
- | `tokenizer_char.json` | The character-level tokenizer's `stoi` vocabulary |
99
- | `bigram.py` | Model architecture source (vendored so this repo is self-sufficient) |
100
- | `tokenizer.py` | Character tokenizer source (vendored, same reason) |
101
  | `load_model.py` | Reconstructs the model + tokenizer from `config.json` and generates a sample |
102
 
103
  ## Usage
104
 
105
  ```bash
106
- pip install torch
107
  python load_model.py
108
  ```
109
 
110
- `load_model.py` reads `config.json` for every architectural parameter
111
- (`vocab_size`, `n_embd`, `n_head`, `n_layer`, `block_size`, `tokenizer_type`)
112
- it does not assume or hardcode them loads `model.pt` into a freshly
113
- constructed model, and samples 400 characters to prove the checkpoint and
114
- its config agree.
115
 
116
  ## Limitations
117
 
118
- This is a ~65-character-vocabulary, 32-token-context toy model trained for
119
- 8,000 steps on 1MB of text. It reproduces surface Shakespeare-ish texture
120
- (names, verse-like line breaks, archaic diction) but not coherent meaning,
121
- plot, or factual content. **Do not use this for anything beyond studying
122
- how these mechanics fit together.**
 
 
3
  tags:
4
  - educational
5
  - from-scratch
6
+ - char-level
7
  - transformer
8
  - pytorch
9
  ---
10
 
11
+ # tinyshakespeare -- char tokenizer, n_embd=128
12
 
13
  **This is an educational project, not a practical language model.** It is a
14
+ from-scratch transformer built to learn the mechanics of language modeling
15
+ end-to-end. It is not intended for any downstream or production use --
 
 
16
  treat it as a worked example, not a tool.
17
 
 
 
 
 
18
  ## Model architecture
19
 
20
+ Token + position embeddings -> n_layer stacked transformer blocks (pre-norm multi-head causal self-attention + feedforward, residual connections) -> final LayerNorm -> linear head to vocab logits. Full hyperparameters are in `config.json`;
21
+ nothing about the architecture is hardcoded in the loader -- see
22
+ `load_model.py`.
 
 
 
23
 
24
  | | |
25
  |---|---|
 
28
  | n_head | 4 |
29
  | n_layer | 4 |
30
  | block_size | 32 |
31
+ | Tokenizer | char-level, vocab_size=65 |
32
 
33
  ## Training corpus
34
 
35
+ Trained on **TinyShakespeare** (~1.1M characters), fetched directly from `https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt`.
 
 
 
 
 
 
 
 
 
 
36
 
37
  ## Results
38
 
 
74
 
75
  | File | Purpose |
76
  |---|---|
77
+ | `model.safetensors` | `state_dict()` of the trained `BigramLanguageModel`, in safetensors format |
78
  | `config.json` | Every hyperparameter needed to reconstruct the architecture and tokenizer |
79
+ | `tokenizer_char.json` | The char-level tokenizer's vocabulary |
80
+ | `bigram.py` | Model architecture source (vendored so this folder is self-sufficient) |
81
+ | `tokenizer.py` | Tokenizer source (vendored, same reason) |
82
  | `load_model.py` | Reconstructs the model + tokenizer from `config.json` and generates a sample |
83
 
84
  ## Usage
85
 
86
  ```bash
87
+ pip install torch safetensors
88
  python load_model.py
89
  ```
90
 
91
+ `load_model.py` reads `config.json` for every architectural parameter --
92
+ it does not assume or hardcode them -- loads `model.safetensors`
93
+ into a freshly constructed model, and samples 400 characters to prove the
94
+ checkpoint and its config agree.
 
95
 
96
  ## Limitations
97
 
98
+ This is a ~65-char-vocabulary,
99
+ 32-token-context toy model trained for
100
+ 8,000 steps. It reproduces surface
101
+ Shakespeare-ish texture but not coherent meaning, plot, or factual
102
+ content. **Do not use this for anything beyond studying how these
103
+ mechanics fit together.**
config.json CHANGED
@@ -8,11 +8,11 @@
8
  "block_size": 32,
9
  "tokenizer_type": "char",
10
  "tokenizer_file": "tokenizer_char.json",
11
- "weights_file": "model.pt",
12
  "training": {
13
  "dataset": "tinyshakespeare.txt",
14
  "batch_size": 32,
15
- "learning_rate": 1e-3,
16
  "max_iters": 8000,
17
  "seed": 1337
18
  },
 
8
  "block_size": 32,
9
  "tokenizer_type": "char",
10
  "tokenizer_file": "tokenizer_char.json",
11
+ "weights_file": "model.safetensors",
12
  "training": {
13
  "dataset": "tinyshakespeare.txt",
14
  "batch_size": 32,
15
+ "learning_rate": 0.001,
16
  "max_iters": 8000,
17
  "seed": 1337
18
  },
load_model.py CHANGED
@@ -1,11 +1,10 @@
1
  """
2
  Self-contained loader for this checkpoint.
3
 
4
- Reconstructs the model architecture and tokenizer entirely from config.json
5
- (no hardcoded hyperparameters here), loads the trained weights, and
6
- generates a sample -- proving the artifact set (config.json + model.pt +
7
- tokenizer_char.json + bigram.py + tokenizer.py) is sufficient on its own,
8
- with no dependency on the original training repo or its train.py.
9
 
10
  Usage:
11
  python load_model.py
@@ -19,19 +18,28 @@ from pathlib import Path
19
  import torch
20
 
21
  from bigram import BigramLanguageModel
22
- from tokenizer import CharTokenizer
23
 
24
  HERE = Path(__file__).resolve().parent
25
 
26
 
 
 
 
 
 
 
 
 
27
  def load_model_and_tokenizer(dir_path: Path = HERE):
28
  config = json.loads((dir_path / "config.json").read_text())
29
 
30
- if config["tokenizer_type"] != "char":
31
- raise ValueError(
32
- f"This loader only wires up 'char'; config says {config['tokenizer_type']!r}"
33
- )
34
- tokenizer = CharTokenizer.load(dir_path / config["tokenizer_file"])
 
 
35
 
36
  model = BigramLanguageModel(
37
  vocab_size=config["vocab_size"],
@@ -40,7 +48,7 @@ def load_model_and_tokenizer(dir_path: Path = HERE):
40
  n_head=config["n_head"],
41
  n_layer=config["n_layer"],
42
  )
43
- state_dict = torch.load(dir_path / config["weights_file"], map_location="cpu")
44
  model.load_state_dict(state_dict)
45
  model.eval()
46
 
 
1
  """
2
  Self-contained loader for this checkpoint.
3
 
4
+ Reconstructs the model architecture and tokenizer entirely from
5
+ config.json (no hardcoded hyperparameters here), loads the trained
6
+ weights, and generates a sample -- proving this folder is sufficient on
7
+ its own, with no dependency on the original training repo.
 
8
 
9
  Usage:
10
  python load_model.py
 
18
  import torch
19
 
20
  from bigram import BigramLanguageModel
 
21
 
22
  HERE = Path(__file__).resolve().parent
23
 
24
 
25
+ def _load_weights(path: Path) -> dict[str, torch.Tensor]:
26
+ if path.suffix == ".safetensors":
27
+ from safetensors.torch import load_file
28
+
29
+ return load_file(path)
30
+ return torch.load(path, map_location="cpu", weights_only=True)
31
+
32
+
33
  def load_model_and_tokenizer(dir_path: Path = HERE):
34
  config = json.loads((dir_path / "config.json").read_text())
35
 
36
+ if config["tokenizer_type"] == "char":
37
+ from tokenizer import CharTokenizer as TokenizerClass
38
+ elif config["tokenizer_type"] == "bpe":
39
+ from bpe_tokenizer import BPETokenizer as TokenizerClass
40
+ else:
41
+ raise ValueError(f"Unknown tokenizer_type: {config['tokenizer_type']!r}")
42
+ tokenizer = TokenizerClass.load(dir_path / config["tokenizer_file"])
43
 
44
  model = BigramLanguageModel(
45
  vocab_size=config["vocab_size"],
 
48
  n_head=config["n_head"],
49
  n_layer=config["n_layer"],
50
  )
51
+ state_dict = _load_weights(dir_path / config["weights_file"])
52
  model.load_state_dict(state_dict)
53
  model.eval()
54
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ce06ec1406abaa871d90b8fcc2ff4d008047fceea39dff3c75c542f617ca75ef
3
+ size 3326268