ToletiSri commited on
Commit
a59382e
1 Parent(s): 3f93b0f

Upload 5 files

Browse files
Files changed (5) hide show
  1. bigram.py +122 -0
  2. config.py +18 -0
  3. gpt.py +138 -0
  4. input.txt +0 -0
  5. saved_model.pth +3 -0
bigram.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn import functional as F
4
+
5
+ # hyperparameters
6
+ batch_size = 32 # how many independent sequences will we process in parallel?
7
+ block_size = 8 # what is the maximum context length for predictions?
8
+ max_iters = 3000
9
+ eval_interval = 300
10
+ learning_rate = 1e-2
11
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
12
+ eval_iters = 200
13
+ # ------------
14
+
15
+ torch.manual_seed(1337)
16
+
17
+ # wget https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt
18
+ with open('input.txt', 'r', encoding='utf-8') as f:
19
+ text = f.read()
20
+
21
+ # here are all the unique characters that occur in this text
22
+ chars = sorted(list(set(text)))
23
+ vocab_size = len(chars)
24
+ # create a mapping from characters to integers
25
+ stoi = { ch:i for i,ch in enumerate(chars) }
26
+ itos = { i:ch for i,ch in enumerate(chars) }
27
+ encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers
28
+ decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string
29
+
30
+ # Train and test splits
31
+ data = torch.tensor(encode(text), dtype=torch.long)
32
+ n = int(0.9*len(data)) # first 90% will be train, rest val
33
+ train_data = data[:n]
34
+ val_data = data[n:]
35
+
36
+ # data loading
37
+ def get_batch(split):
38
+ # generate a small batch of data of inputs x and targets y
39
+ data = train_data if split == 'train' else val_data
40
+ ix = torch.randint(len(data) - block_size, (batch_size,))
41
+ x = torch.stack([data[i:i+block_size] for i in ix])
42
+ y = torch.stack([data[i+1:i+block_size+1] for i in ix])
43
+ x, y = x.to(device), y.to(device)
44
+ return x, y
45
+
46
+ @torch.no_grad()
47
+ def estimate_loss():
48
+ out = {}
49
+ model.eval()
50
+ for split in ['train', 'val']:
51
+ losses = torch.zeros(eval_iters)
52
+ for k in range(eval_iters):
53
+ X, Y = get_batch(split)
54
+ logits, loss = model(X, Y)
55
+ losses[k] = loss.item()
56
+ out[split] = losses.mean()
57
+ model.train()
58
+ return out
59
+
60
+ # super simple bigram model
61
+ class BigramLanguageModel(nn.Module):
62
+
63
+ def __init__(self, vocab_size):
64
+ super().__init__()
65
+ # each token directly reads off the logits for the next token from a lookup table
66
+ self.token_embedding_table = nn.Embedding(vocab_size, vocab_size)
67
+
68
+ def forward(self, idx, targets=None):
69
+
70
+ # idx and targets are both (B,T) tensor of integers
71
+ logits = self.token_embedding_table(idx) # (B,T,C)
72
+
73
+ if targets is None:
74
+ loss = None
75
+ else:
76
+ B, T, C = logits.shape
77
+ logits = logits.view(B*T, C)
78
+ targets = targets.view(B*T)
79
+ loss = F.cross_entropy(logits, targets)
80
+
81
+ return logits, loss
82
+
83
+ def generate(self, idx, max_new_tokens):
84
+ # idx is (B, T) array of indices in the current context
85
+ for _ in range(max_new_tokens):
86
+ # get the predictions
87
+ logits, loss = self(idx)
88
+ # focus only on the last time step
89
+ logits = logits[:, -1, :] # becomes (B, C)
90
+ # apply softmax to get probabilities
91
+ probs = F.softmax(logits, dim=-1) # (B, C)
92
+ # sample from the distribution
93
+ idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
94
+ # append sampled index to the running sequence
95
+ idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
96
+ return idx
97
+
98
+ model = BigramLanguageModel(vocab_size)
99
+ m = model.to(device)
100
+
101
+ # create a PyTorch optimizer
102
+ optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
103
+
104
+ for iter in range(max_iters):
105
+
106
+ # every once in a while evaluate the loss on train and val sets
107
+ if iter % eval_interval == 0:
108
+ losses = estimate_loss()
109
+ print(f"step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
110
+
111
+ # sample a batch of data
112
+ xb, yb = get_batch('train')
113
+
114
+ # evaluate the loss
115
+ logits, loss = model(xb, yb)
116
+ optimizer.zero_grad(set_to_none=True)
117
+ loss.backward()
118
+ optimizer.step()
119
+
120
+ # generate from the model
121
+ context = torch.zeros((1, 1), dtype=torch.long, device=device)
122
+ print(decode(m.generate(context, max_new_tokens=500)[0].tolist()))
config.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ # hyperparameters
4
+ batch_size = 64 # how many independent sequences will we process in parallel?
5
+ block_size = 256 # what is the maximum context length for predictions?
6
+ max_iters = 5000
7
+ eval_interval = 500
8
+ learning_rate = 3e-4
9
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
10
+ eval_iters = 200
11
+ n_embd = 384
12
+ n_head = 6
13
+ n_layer = 6
14
+ dropout = 0.2
15
+ # ------------
16
+
17
+
18
+
gpt.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn import functional as F
4
+ import config as cfg
5
+
6
+ class Head(nn.Module):
7
+ """ one head of self-attention """
8
+
9
+ def __init__(self, head_size):
10
+ super().__init__()
11
+ self.key = nn.Linear(cfg.n_embd, head_size, bias=False)
12
+ self.query = nn.Linear(cfg.n_embd, head_size, bias=False)
13
+ self.value = nn.Linear(cfg.n_embd, head_size, bias=False)
14
+ self.register_buffer('tril', torch.tril(torch.ones(cfg.block_size, cfg.block_size)))
15
+
16
+ self.dropout = nn.Dropout(cfg.dropout)
17
+
18
+ def forward(self, x):
19
+ # input of size (batch, time-step, channels)
20
+ # output of size (batch, time-step, head size)
21
+ B,T,C = x.shape
22
+ k = self.key(x) # (B,T,hs)
23
+ q = self.query(x) # (B,T,hs)
24
+ # compute attention scores ("affinities")
25
+ wei = q @ k.transpose(-2,-1) * k.shape[-1]**-0.5 # (B, T, hs) @ (B, hs, T) -> (B, T, T)
26
+ wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
27
+ wei = F.softmax(wei, dim=-1) # (B, T, T)
28
+ wei = self.dropout(wei)
29
+ # perform the weighted aggregation of the values
30
+ v = self.value(x) # (B,T,hs)
31
+ out = wei @ v # (B, T, T) @ (B, T, hs) -> (B, T, hs)
32
+ return out
33
+
34
+ class MultiHeadAttention(nn.Module):
35
+ """ multiple heads of self-attention in parallel """
36
+
37
+ def __init__(self, num_heads, head_size):
38
+ super().__init__()
39
+ self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
40
+ self.proj = nn.Linear(head_size * num_heads, cfg.n_embd)
41
+ self.dropout = nn.Dropout(cfg.dropout)
42
+
43
+ def forward(self, x):
44
+ out = torch.cat([h(x) for h in self.heads], dim=-1)
45
+ out = self.dropout(self.proj(out))
46
+ return out
47
+
48
+ class FeedFoward(nn.Module):
49
+ """ a simple linear layer followed by a non-linearity """
50
+
51
+ def __init__(self, n_embd):
52
+ super().__init__()
53
+ self.net = nn.Sequential(
54
+ nn.Linear(n_embd, 4 * n_embd),
55
+ nn.ReLU(),
56
+ nn.Linear(4 * n_embd, n_embd),
57
+ nn.Dropout(cfg.dropout),
58
+ )
59
+
60
+ def forward(self, x):
61
+ return self.net(x)
62
+
63
+ class Block(nn.Module):
64
+ """ Transformer block: communication followed by computation """
65
+
66
+ def __init__(self, n_embd, n_head):
67
+ # n_embd: embedding dimension, n_head: the number of heads we'd like
68
+ super().__init__()
69
+ head_size = n_embd // n_head
70
+ self.sa = MultiHeadAttention(n_head, head_size)
71
+ self.ffwd = FeedFoward(n_embd)
72
+ self.ln1 = nn.LayerNorm(n_embd)
73
+ self.ln2 = nn.LayerNorm(n_embd)
74
+
75
+ def forward(self, x):
76
+ x = x + self.sa(self.ln1(x))
77
+ x = x + self.ffwd(self.ln2(x))
78
+ return x
79
+
80
+ class GPTLanguageModel(nn.Module):
81
+
82
+ def __init__(self, vocab_size):
83
+ super().__init__()
84
+ # each token directly reads off the logits for the next token from a lookup table
85
+ self.token_embedding_table = nn.Embedding(vocab_size, cfg.n_embd)
86
+ self.position_embedding_table = nn.Embedding(cfg.block_size, cfg.n_embd)
87
+ self.blocks = nn.Sequential(*[Block(cfg.n_embd, n_head=cfg.n_head) for _ in range(cfg.n_layer)])
88
+ self.ln_f = nn.LayerNorm(cfg.n_embd) # final layer norm
89
+ self.lm_head = nn.Linear(cfg.n_embd, vocab_size)
90
+
91
+ # better init, not covered in the original GPT video, but important, will cover in followup video
92
+ self.apply(self._init_weights)
93
+
94
+ def _init_weights(self, module):
95
+ if isinstance(module, nn.Linear):
96
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
97
+ if module.bias is not None:
98
+ torch.nn.init.zeros_(module.bias)
99
+ elif isinstance(module, nn.Embedding):
100
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
101
+
102
+ def forward(self, idx, targets=None):
103
+ B, T = idx.shape
104
+
105
+ # idx and targets are both (B,T) tensor of integers
106
+ tok_emb = self.token_embedding_table(idx) # (B,T,C)
107
+ pos_emb = self.position_embedding_table(torch.arange(T, device=cfg.device)) # (T,C)
108
+ x = tok_emb + pos_emb # (B,T,C)
109
+ x = self.blocks(x) # (B,T,C)
110
+ x = self.ln_f(x) # (B,T,C)
111
+ logits = self.lm_head(x) # (B,T,vocab_size)
112
+
113
+ if targets is None:
114
+ loss = None
115
+ else:
116
+ B, T, C = logits.shape
117
+ logits = logits.view(B*T, C)
118
+ targets = targets.view(B*T)
119
+ loss = F.cross_entropy(logits, targets)
120
+
121
+ return logits, loss
122
+
123
+ def generate(self, idx, max_new_tokens):
124
+ # idx is (B, T) array of indices in the current context
125
+ for _ in range(max_new_tokens):
126
+ # crop idx to the last block_size tokens
127
+ idx_cond = idx[:, -cfg.block_size:]
128
+ # get the predictions
129
+ logits, loss = self(idx_cond)
130
+ # focus only on the last time step
131
+ logits = logits[:, -1, :] # becomes (B, C)
132
+ # apply softmax to get probabilities
133
+ probs = F.softmax(logits, dim=-1) # (B, C)
134
+ # sample from the distribution
135
+ idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
136
+ # append sampled index to the running sequence
137
+ idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
138
+ return idx
input.txt ADDED
The diff for this file is too large to render. See raw diff
 
saved_model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b4c2d92904deec61a54aea4d8507baa2963b113d8a4a29f2ccb5d5face8b2f03
3
+ size 52672301