1import torch2import torch.nn as nn3from torch.nn import functional as F45# hyperparameters6batch_size = 64 # how many independent sequences will we process in parallel?7block_size = 256 # what is the maximum context length for predictions?8max_iters = 50009eval_interval = 50010learning_rate = 3e-411device = 'cuda' if torch.cuda.is_available() else 'cpu'12eval_iters = 20013n_embd = 38414n_head = 615n_layer = 616dropout = 0.217# ------------1819torch.manual_seed(1337)2021# wget https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt22with open('input.txt', 'r', encoding='utf-8') as f:23 text = f.read()2425# here are all the unique characters that occur in this text26chars = sorted(list(set(text)))27vocab_size = len(chars)28# create a mapping from characters to integers29stoi = { ch:i for i,ch in enumerate(chars) }30itos = { i:ch for i,ch in enumerate(chars) }31encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers32decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string3334# Train and test splits35data = torch.tensor(encode(text), dtype=torch.long)36n = int(0.9*len(data)) # first 90% will be train, rest val37train_data = data[:n]38val_data = data[n:]3940# data loading41def get_batch(split):42 # generate a small batch of data of inputs x and targets y43 data = train_data if split == 'train' else val_data44 ix = torch.randint(len(data) - block_size, (batch_size,))45 x = torch.stack([data[i:i+block_size] for i in ix])46 y = torch.stack([data[i+1:i+block_size+1] for i in ix])47 x, y = x.to(device), y.to(device)48 return x, y4950@torch.no_grad()51def estimate_loss():52 out = {}53 model.eval()54 for split in ['train', 'val']:55 losses = torch.zeros(eval_iters)56 for k in range(eval_iters):57 X, Y = get_batch(split)58 logits, loss = model(X, Y)59 losses[k] = loss.item()60 out[split] = losses.mean()61 model.train()62 return out6364class Head(nn.Module):65 """ one head of self-attention """6667 def __init__(self, head_size):68 super().__init__()69 self.key = nn.Linear(n_embd, head_size, bias=False)70 self.query = nn.Linear(n_embd, head_size, bias=False)71 self.value = nn.Linear(n_embd, head_size, bias=False)72 self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))7374 self.dropout = nn.Dropout(dropout)7576 def forward(self, x):77 # input of size (batch, time-step, channels)78 # output of size (batch, time-step, head size)79 B,T,C = x.shape80 k = self.key(x) # (B,T,hs)81 q = self.query(x) # (B,T,hs)82 # compute attention scores ("affinities")83 wei = q @ k.transpose(-2,-1) * k.shape[-1]**-0.5 # (B, T, hs) @ (B, hs, T) -> (B, T, T)84 wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)85 wei = F.softmax(wei, dim=-1) # (B, T, T)86 wei = self.dropout(wei)87 # perform the weighted aggregation of the values88 v = self.value(x) # (B,T,hs)89 out = wei @ v # (B, T, T) @ (B, T, hs) -> (B, T, hs)90 return out9192class MultiHeadAttention(nn.Module):93 """ multiple heads of self-attention in parallel """9495 def __init__(self, num_heads, head_size):96 super().__init__()97 self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])98 self.proj = nn.Linear(head_size * num_heads, n_embd)99 self.dropout = nn.Dropout(dropout)100101 def forward(self, x):102 out = torch.cat([h(x) for h in self.heads], dim=-1)103 out = self.dropout(self.proj(out))104 return out105106class FeedFoward(nn.Module):107 """ a simple linear layer followed by a non-linearity """108109 def __init__(self, n_embd):110 super().__init__()111 self.net = nn.Sequential(112 nn.Linear(n_embd, 4 * n_embd),113 nn.ReLU(),114 nn.Linear(4 * n_embd, n_embd),115 nn.Dropout(dropout),116 )117118 def forward(self, x):119 return self.net(x)120121class Block(nn.Module):122 """ Transformer block: communication followed by computation """123124 def __init__(self, n_embd, n_head):125 # n_embd: embedding dimension, n_head: the number of heads we'd like126 super().__init__()127 head_size = n_embd // n_head128 self.sa = MultiHeadAttention(n_head, head_size)129 self.ffwd = FeedFoward(n_embd)130 self.ln1 = nn.LayerNorm(n_embd)131 self.ln2 = nn.LayerNorm(n_embd)132133 def forward(self, x):134 x = x + self.sa(self.ln1(x))135 x = x + self.ffwd(self.ln2(x))136 return x137138class GPTLanguageModel(nn.Module):139140 def __init__(self):141 super().__init__()142 # each token directly reads off the logits for the next token from a lookup table143 self.token_embedding_table = nn.Embedding(vocab_size, n_embd)144 self.position_embedding_table = nn.Embedding(block_size, n_embd)145 self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])146 self.ln_f = nn.LayerNorm(n_embd) # final layer norm147 self.lm_head = nn.Linear(n_embd, vocab_size)148149 # better init, not covered in the original GPT video, but important, will cover in followup video150 self.apply(self._init_weights)151152 def _init_weights(self, module):153 if isinstance(module, nn.Linear):154 torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)155 if module.bias is not None:156 torch.nn.init.zeros_(module.bias)157 elif isinstance(module, nn.Embedding):158 torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)159160 def forward(self, idx, targets=None):161 B, T = idx.shape162163 # idx and targets are both (B,T) tensor of integers164 tok_emb = self.token_embedding_table(idx) # (B,T,C)165 pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)166 x = tok_emb + pos_emb # (B,T,C)167 x = self.blocks(x) # (B,T,C)168 x = self.ln_f(x) # (B,T,C)169 logits = self.lm_head(x) # (B,T,vocab_size)170171 if targets is None:172 loss = None173 else:174 B, T, C = logits.shape175 logits = logits.view(B*T, C)176 targets = targets.view(B*T)177 loss = F.cross_entropy(logits, targets)178179 return logits, loss180181 def generate(self, idx, max_new_tokens):182 # idx is (B, T) array of indices in the current context183 for _ in range(max_new_tokens):184 # crop idx to the last block_size tokens185 idx_cond = idx[:, -block_size:]186 # get the predictions187 logits, loss = self(idx_cond)188 # focus only on the last time step189 logits = logits[:, -1, :] # becomes (B, C)190 # apply softmax to get probabilities191 probs = F.softmax(logits, dim=-1) # (B, C)192 # sample from the distribution193 idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)194 # append sampled index to the running sequence195 idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)196 return idx197198model = GPTLanguageModel()199m = model.to(device)200# print the number of parameters in the model201print(sum(p.numel() for p in m.parameters())/1e6, 'M parameters')202203# create a PyTorch optimizer204optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)205206for iter in range(max_iters):207208 # every once in a while evaluate the loss on train and val sets209 if iter % eval_interval == 0 or iter == max_iters - 1:210 losses = estimate_loss()211 print(f"step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")212213 # sample a batch of data214 xb, yb = get_batch('train')215216 # evaluate the loss217 logits, loss = model(xb, yb)218 optimizer.zero_grad(set_to_none=True)219 loss.backward()220 optimizer.step()221222# generate from the model223context = torch.zeros((1, 1), dtype=torch.long, device=device)224print(decode(m.generate(context, max_new_tokens=500)[0].tolist()))225#open('more.txt', 'w').write(decode(m.generate(context, max_new_tokens=10000)[0].tolist()))226Ask about anything
Highlight code and press Explain ✨ — or type a question below.
Ask about anything
Highlight code and press Explain ✨ — or type a question below.