Add model code (CharGPT).

#1
by Compactbot - opened
Files changed (1) hide show
  1. model.py +114 -0
model.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ class CausalSelfAttention(nn.Module):
7
+ def __init__(self, n_embd, n_head):
8
+ super().__init__()
9
+ assert n_embd % n_head == 0
10
+ self.n_head = n_head
11
+ self.head_dim = n_embd // n_head
12
+ self.c_attn = nn.Linear(n_embd, 3 * n_embd, bias=False)
13
+ self.c_proj = nn.Linear(n_embd, n_embd, bias=False)
14
+
15
+ def forward(self, x):
16
+ B, T, C = x.size()
17
+ q, k, v = self.c_attn(x).split(self.head_dim * self.n_head, dim=2)
18
+ q = q.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
19
+ k = k.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
20
+ v = v.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
21
+ att = F.scaled_dot_product_attention(q, k, v, is_causal=True)
22
+ att = att.transpose(1, 2).contiguous().view(B, T, C)
23
+ return self.c_proj(att)
24
+
25
+
26
+ class MLP(nn.Module):
27
+ def __init__(self, n_embd, n_inner):
28
+ super().__init__()
29
+ self.c_fc = nn.Linear(n_embd, n_inner, bias=False)
30
+ self.c_proj = nn.Linear(n_inner, n_embd, bias=False)
31
+
32
+ def forward(self, x):
33
+ return self.c_proj(F.gelu(self.c_fc(x)))
34
+
35
+
36
+ class Block(nn.Module):
37
+ def __init__(self, n_embd, n_head):
38
+ super().__init__()
39
+ self.ln_1 = nn.LayerNorm(n_embd)
40
+ self.attn = CausalSelfAttention(n_embd, n_head)
41
+ self.ln_2 = nn.LayerNorm(n_embd)
42
+ self.mlp = MLP(n_embd, 4 * n_embd)
43
+
44
+ def forward(self, x):
45
+ x = x + self.attn(self.ln_1(x))
46
+ x = x + self.mlp(self.ln_2(x))
47
+ return x
48
+
49
+
50
+ class CharGPT(nn.Module):
51
+ """Character-level causal transformer (nanoGPT-style). No bias in
52
+ attention / FFN / lm_head; LayerNorm carries the affine bias."""
53
+
54
+ def __init__(self, vocab_size, block_size, n_layer, n_head, n_embd):
55
+ super().__init__()
56
+ self.block_size = block_size
57
+ self.transformer = nn.ModuleDict({
58
+ "wte": nn.Embedding(vocab_size, n_embd),
59
+ "wpe": nn.Embedding(block_size, n_embd),
60
+ "drop": nn.Dropout(0.0),
61
+ "h": nn.ModuleList([Block(n_embd, n_head) for _ in range(n_layer)]),
62
+ "ln_f": nn.LayerNorm(n_embd),
63
+ })
64
+ self.lm_head = nn.Linear(n_embd, vocab_size, bias=False)
65
+
66
+ def forward(self, idx, targets=None):
67
+ B, T = idx.size()
68
+ assert T <= self.block_size, f"block size {self.block_size} < {T}"
69
+ pos = torch.arange(0, T, device=idx.device)
70
+ x = self.transformer["drop"](
71
+ self.transformer["wte"](idx) + self.transformer["wpe"](pos))
72
+ for block in self.transformer["h"]:
73
+ x = block(x)
74
+ x = self.transformer["ln_f"](x)
75
+ logits = self.lm_head(x)
76
+ loss = None
77
+ if targets is not None:
78
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)),
79
+ targets.view(-1))
80
+ return logits, loss
81
+
82
+ @torch.no_grad()
83
+ def generate(self, idx, max_new_tokens, temperature=0.8, top_k=40):
84
+ for _ in range(max_new_tokens):
85
+ idx_cond = idx[:, -self.block_size:]
86
+ logits, _ = self(idx_cond)
87
+ logits = logits[:, -1, :] / temperature
88
+ if top_k:
89
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
90
+ logits[logits < v[:, [-1]]] = float("-inf")
91
+ probs = F.softmax(logits, dim=-1)
92
+ idx = torch.cat((idx, torch.multinomial(probs, num_samples=1)), dim=1)
93
+ return idx
94
+
95
+
96
+ def from_config(config):
97
+ return CharGPT(
98
+ vocab_size=config["vocab_size"],
99
+ block_size=config["block_size"],
100
+ n_layer=config["n_layer"],
101
+ n_head=config["n_head"],
102
+ n_embd=config["n_embd"],
103
+ )
104
+
105
+
106
+ if __name__ == "__main__":
107
+ import json
108
+ cfg = json.load(open("config.json"))
109
+ m = from_config(cfg)
110
+ print("params:", sum(p.numel() for p in m.parameters()))
111
+ # tiny smoke test
112
+ x = torch.randint(0, cfg["vocab_size"], (1, 32))
113
+ logits, loss = m(x, x)
114
+ print("smoke loss:", loss.item())