AlmostNobody commited on
Commit
3a9fc0f
Β·
verified Β·
1 Parent(s): e96b27c

Upload 6 files

Browse files
Files changed (6) hide show
  1. README.md +64 -0
  2. config.json +8 -0
  3. generate.py +17 -0
  4. model.py +79 -0
  5. tinygpt_checkpoint.pt +3 -0
  6. vocab.json +112 -0
README.md CHANGED
@@ -1,3 +1,67 @@
1
  ---
2
  license: mit
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
+ library_name: pytorch
4
+ tags:
5
+ - text-generation
6
+ - from-scratch
7
+ - character-level
8
+ - tiny-model
9
+ - educational
10
  ---
11
+
12
+ # TinyGPT: a 1M parameter model trained from scratch
13
+
14
+ A tiny character-level transformer (about 1.04 million parameters), written in
15
+ PyTorch and trained **from scratch** (not fine-tuned from any other model) on a
16
+ small "friendly Python teacher" dataset. It is a learning project and is not
17
+ meant to be useful for real questions.
18
+
19
+ ## Model details
20
+
21
+ | | |
22
+ |---|---|
23
+ | Parameters | ~1.04M |
24
+ | Layers / heads / embedding size | 5 / 4 / 128 |
25
+ | Context length | 128 characters |
26
+ | Tokenizer | character-level (108 characters, see `vocab.json`) |
27
+ | Training data | 3,000 question/answer examples (~1.5M characters) |
28
+ | Final loss | train ~0.16, validation ~0.89 |
29
+
30
+ ## What it can and can't do
31
+
32
+ - It picks up the **style** of the training data: friendly tone, emojis, code blocks.
33
+ - It mostly **memorizes** its training answers. The training set has only about
34
+ 150 distinct questions, so it does not understand new questions, and for
35
+ unseen wording it tends to produce confident-looking but wrong or nonsensical text.
36
+ - Questions worded like the training data work best, for example
37
+ "How does a while loop work?" or "What is recursion?".
38
+
39
+ ## Usage
40
+
41
+ Put `tinygpt.pt` (the weights) in the same folder as the other files, then:
42
+
43
+ ```bash
44
+ pip install torch
45
+ python generate.py "How does a while loop work?"
46
+ ```
47
+
48
+ The model expects this prompt format (`generate.py` adds it for you):
49
+
50
+ ```
51
+ ### Question:
52
+ <your question>
53
+ ### Answer:
54
+ ```
55
+
56
+ ## Files
57
+
58
+ - `tinygpt.pt`: trained weights (PyTorch state dict)
59
+ - `model.py`: the model code (needed to load the weights)
60
+ - `config.json`: model settings
61
+ - `vocab.json`: the character vocabulary, in order
62
+ - `generate.py`: example script
63
+
64
+ ## Training
65
+
66
+ Trained for 3,000 steps with AdamW (lr 2e-3), batch size 64, on 1,529,604
67
+ characters, with 15 held-out questions used for validation.
config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "vocab_size": 108,
3
+ "block_size": 128,
4
+ "n_embd": 128,
5
+ "n_head": 4,
6
+ "n_layer": 5,
7
+ "dropout": 0.1
8
+ }
generate.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ask TinyGPT a question: python generate.py "How does a while loop work?" """
2
+ import sys
3
+ import torch
4
+ from model import load_model
5
+
6
+ weights = "tinygpt.pt" # change if your file has another name
7
+ device = "cuda" if torch.cuda.is_available() else "cpu"
8
+ model, chars = load_model(weights, device)
9
+ stoi = {c: i for i, c in enumerate(chars)}
10
+ itos = {i: c for i, c in enumerate(chars)}
11
+
12
+ question = " ".join(sys.argv[1:]) or "How does a while loop work?"
13
+ prompt = f"### Question:\n{question}\n### Answer:\n"
14
+ idx = torch.tensor([[stoi[c] for c in prompt if c in stoi]], device=device)
15
+ out = model.generate(idx, 400, temperature=0.5)[0].tolist()
16
+ text = "".join(itos[i] for i in out)[len(prompt):]
17
+ print(text.split("<END>")[0])
model.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.nn import functional as F
5
+
6
+
7
+ class Block(nn.Module):
8
+ def __init__(self, cfg):
9
+ super().__init__()
10
+ n_embd = cfg["n_embd"]
11
+ self.n_head = cfg["n_head"]
12
+ self.dropout = cfg["dropout"]
13
+ self.ln1 = nn.LayerNorm(n_embd)
14
+ self.qkv = nn.Linear(n_embd, 3 * n_embd)
15
+ self.proj = nn.Linear(n_embd, n_embd)
16
+ self.ln2 = nn.LayerNorm(n_embd)
17
+ self.mlp = nn.Sequential(
18
+ nn.Linear(n_embd, 4 * n_embd), nn.GELU(),
19
+ nn.Linear(4 * n_embd, n_embd), nn.Dropout(self.dropout))
20
+ self.drop = nn.Dropout(self.dropout)
21
+
22
+ def forward(self, x):
23
+ B, T, C = x.shape
24
+ h = self.n_head
25
+ q, k, v = self.qkv(self.ln1(x)).split(C, dim=2)
26
+ q = q.view(B, T, h, C // h).transpose(1, 2)
27
+ k = k.view(B, T, h, C // h).transpose(1, 2)
28
+ v = v.view(B, T, h, C // h).transpose(1, 2)
29
+ y = F.scaled_dot_product_attention(
30
+ q, k, v, is_causal=True,
31
+ dropout_p=self.dropout if self.training else 0.0)
32
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
33
+ x = x + self.drop(self.proj(y))
34
+ x = x + self.mlp(self.ln2(x))
35
+ return x
36
+
37
+
38
+ class TinyGPT(nn.Module):
39
+ def __init__(self, cfg):
40
+ super().__init__()
41
+ self.cfg = cfg
42
+ self.tok = nn.Embedding(cfg["vocab_size"], cfg["n_embd"])
43
+ self.pos = nn.Embedding(cfg["block_size"], cfg["n_embd"])
44
+ self.blocks = nn.Sequential(*[Block(cfg) for _ in range(cfg["n_layer"])])
45
+ self.ln_f = nn.LayerNorm(cfg["n_embd"])
46
+ self.head = nn.Linear(cfg["n_embd"], cfg["vocab_size"])
47
+
48
+ def forward(self, idx, targets=None):
49
+ B, T = idx.shape
50
+ x = self.tok(idx) + self.pos(torch.arange(T, device=idx.device))
51
+ logits = self.head(self.ln_f(self.blocks(x)))
52
+ loss = None
53
+ if targets is not None:
54
+ loss = F.cross_entropy(
55
+ logits.view(-1, self.cfg["vocab_size"]), targets.view(-1))
56
+ return logits, loss
57
+
58
+ @torch.no_grad()
59
+ def generate(self, idx, max_new_tokens, temperature=0.8):
60
+ for _ in range(max_new_tokens):
61
+ logits, _ = self(idx[:, -self.cfg["block_size"]:])
62
+ probs = F.softmax(logits[:, -1, :] / temperature, dim=-1)
63
+ idx = torch.cat([idx, torch.multinomial(probs, 1)], dim=1)
64
+ return idx
65
+
66
+
67
+ def load_model(weights_path="tinygpt.pt", device="cpu"):
68
+ cfg = json.load(open("config.json"))
69
+ chars = json.load(open("vocab.json"))["chars"]
70
+ model = TinyGPT(cfg).to(device)
71
+ sd = torch.load(weights_path, map_location=device)
72
+ # accept either a plain state_dict or a checkpoint dict that wraps one
73
+ for key in ("model", "model_state_dict", "state_dict"):
74
+ if isinstance(sd, dict) and key in sd:
75
+ sd = sd[key]
76
+ break
77
+ model.load_state_dict(sd)
78
+ model.eval()
79
+ return model, chars
tinygpt_checkpoint.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:321731cbd7328bf9cdbdd39c632f7d07d83dc799c6ddaa4e47d81485b350c8f3
3
+ size 4169077
vocab.json ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "chars": [
3
+ "\n",
4
+ " ",
5
+ "!",
6
+ "\"",
7
+ "#",
8
+ "$",
9
+ "%",
10
+ "&",
11
+ "'",
12
+ "(",
13
+ ")",
14
+ "*",
15
+ "+",
16
+ ",",
17
+ "-",
18
+ ".",
19
+ "/",
20
+ "0",
21
+ "1",
22
+ "2",
23
+ "3",
24
+ "4",
25
+ "5",
26
+ "6",
27
+ "7",
28
+ "8",
29
+ "9",
30
+ ":",
31
+ ";",
32
+ "<",
33
+ "=",
34
+ ">",
35
+ "?",
36
+ "@",
37
+ "A",
38
+ "B",
39
+ "C",
40
+ "D",
41
+ "E",
42
+ "F",
43
+ "G",
44
+ "H",
45
+ "I",
46
+ "J",
47
+ "K",
48
+ "L",
49
+ "M",
50
+ "N",
51
+ "O",
52
+ "P",
53
+ "Q",
54
+ "R",
55
+ "S",
56
+ "T",
57
+ "U",
58
+ "V",
59
+ "W",
60
+ "X",
61
+ "Y",
62
+ "Z",
63
+ "[",
64
+ "\\",
65
+ "]",
66
+ "_",
67
+ "`",
68
+ "a",
69
+ "b",
70
+ "c",
71
+ "d",
72
+ "e",
73
+ "f",
74
+ "g",
75
+ "h",
76
+ "i",
77
+ "j",
78
+ "k",
79
+ "l",
80
+ "m",
81
+ "n",
82
+ "o",
83
+ "p",
84
+ "q",
85
+ "r",
86
+ "s",
87
+ "t",
88
+ "u",
89
+ "v",
90
+ "w",
91
+ "x",
92
+ "y",
93
+ "z",
94
+ "{",
95
+ "|",
96
+ "}",
97
+ "Γ—",
98
+ "β€”",
99
+ "β†’",
100
+ "️",
101
+ "πŸŽ‰",
102
+ "🐍",
103
+ "πŸ’Œ",
104
+ "πŸ’›",
105
+ "πŸ’ͺ",
106
+ "πŸ”",
107
+ "πŸ•΅",
108
+ "πŸ˜„",
109
+ "😊",
110
+ "😒"
111
+ ]
112
+ }