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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Solving for residual std scaling issue
|
| 2 |
+
import os
|
| 3 |
+
import math
|
| 4 |
+
import time
|
| 5 |
+
import inspect
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
from torch.nn import functional as F
|
| 10 |
+
import tiktoken
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class CausalSelfAttention(nn.Module):
|
| 14 |
+
|
| 15 |
+
def __init__(self, config):
|
| 16 |
+
super().__init__()
|
| 17 |
+
assert config.n_embd % config.n_head == 0
|
| 18 |
+
# key, query, value projections for all heads, but in a batch
|
| 19 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
|
| 20 |
+
# output projection
|
| 21 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
|
| 22 |
+
self.c_proj.NANGPT_SCALE_INIT = 1
|
| 23 |
+
# regularization
|
| 24 |
+
self.n_head = config.n_head
|
| 25 |
+
self.n_embd = config.n_embd
|
| 26 |
+
self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)).view(1, 1, config.block_size, config.block_size))
|
| 27 |
+
|
| 28 |
+
def forward(self, x):
|
| 29 |
+
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
|
| 30 |
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
| 31 |
+
# nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
|
| 32 |
+
# e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
|
| 33 |
+
qkv = self.c_attn(x)
|
| 34 |
+
q, k, v = qkv.split(self.n_embd, dim=2)
|
| 35 |
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
| 36 |
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
| 37 |
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
| 38 |
+
|
| 39 |
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
| 40 |
+
att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
|
| 41 |
+
att = F.softmax(att, dim=-1)
|
| 42 |
+
y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
|
| 43 |
+
|
| 44 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
|
| 45 |
+
# output projection
|
| 46 |
+
y = self.c_proj(y)
|
| 47 |
+
return y
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class MLP(nn.Module):
|
| 51 |
+
|
| 52 |
+
def __init__(self, config):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
|
| 55 |
+
self.gelu = nn.GELU(approximate='tanh')
|
| 56 |
+
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
|
| 57 |
+
self.c_proj.NANOGPT_SCALE_INIT = 1
|
| 58 |
+
|
| 59 |
+
def forward(self, x):
|
| 60 |
+
x = self.c_fc(x)
|
| 61 |
+
x = self.gelu(x)
|
| 62 |
+
x = self.c_proj(x)
|
| 63 |
+
return x
|
| 64 |
+
|
| 65 |
+
class Block(nn.Module):
|
| 66 |
+
|
| 67 |
+
def __init__(self, config):
|
| 68 |
+
super().__init__()
|
| 69 |
+
self.ln_1 = nn.LayerNorm(config.n_embd)
|
| 70 |
+
self.attn = CausalSelfAttention(config)
|
| 71 |
+
self.ln_2 = nn.LayerNorm(config.n_embd)
|
| 72 |
+
self.mlp = MLP(config)
|
| 73 |
+
|
| 74 |
+
def forward(self, x):
|
| 75 |
+
x = x + self.attn(self.ln_1(x))
|
| 76 |
+
x = x + self.mlp(self.ln_2(x))
|
| 77 |
+
return x
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@dataclass
|
| 81 |
+
class GPTConfig:
|
| 82 |
+
block_size: int = 1024 # max sequence length
|
| 83 |
+
vocab_size: int = 50257 # number of tokens: 50,000 BPE merges + 256 bytes tokens + 1 <|endoftext|> token
|
| 84 |
+
n_layer: int = 12 # number of layers
|
| 85 |
+
n_head: int = 12 # number of heads
|
| 86 |
+
n_embd: int = 768 # embedding dimension
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class GPT(nn.Module):
|
| 90 |
+
|
| 91 |
+
def __init__(self, config):
|
| 92 |
+
super().__init__()
|
| 93 |
+
self.config = config
|
| 94 |
+
|
| 95 |
+
self.transformer = nn.ModuleDict(dict(
|
| 96 |
+
wte = nn.Embedding(config.vocab_size, config.n_embd),
|
| 97 |
+
wpe = nn.Embedding(config.block_size, config.n_embd),
|
| 98 |
+
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
| 99 |
+
ln_f = nn.LayerNorm(config.n_embd),
|
| 100 |
+
))
|
| 101 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 102 |
+
|
| 103 |
+
# weight sharing
|
| 104 |
+
self.transformer.wte.weight = self.lm_head.weight
|
| 105 |
+
|
| 106 |
+
# weight initialization
|
| 107 |
+
self.apply(self._init_weights)
|
| 108 |
+
|
| 109 |
+
def _init_weights(self, module):
|
| 110 |
+
if isinstance(module, nn.Linear):
|
| 111 |
+
std = 0.02
|
| 112 |
+
if hasattr(module, 'NANGPT_SCALE_INIT'):
|
| 113 |
+
std *= (2 * self.config.n_layer) ** -0.5
|
| 114 |
+
torch.nn.init.normal_(module.weight, mean = 0.0, std = std)
|
| 115 |
+
if module.bias is not None:
|
| 116 |
+
torch.nn.init.zeros_(module.bias)
|
| 117 |
+
elif isinstance(module, nn.Embedding):
|
| 118 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std = 0.02)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def forward(self, idx, targets=None):
|
| 123 |
+
|
| 124 |
+
# Handle input shape
|
| 125 |
+
if len(idx.size()) == 1:
|
| 126 |
+
# If flat tensor, reshape to (1, T)
|
| 127 |
+
idx = idx.view(1, -1)
|
| 128 |
+
elif len(idx.size()) == 3:
|
| 129 |
+
# If 3D tensor, take first two dimensions
|
| 130 |
+
idx = idx[:, :, 0]
|
| 131 |
+
|
| 132 |
+
B, T = idx.size()
|
| 133 |
+
|
| 134 |
+
assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
|
| 135 |
+
|
| 136 |
+
# forward the token and position embeddings
|
| 137 |
+
pos = torch.arange(0, T, dtype=torch.long, device=idx.device) # shape (T)
|
| 138 |
+
pos_emb = self.transformer.wpe(pos) # position embeddings of shape (T, n_embd)
|
| 139 |
+
tok_emb = self.transformer.wte(idx) # token embeddings of shape (B, T, n_embd)
|
| 140 |
+
|
| 141 |
+
# Expand pos_emb to match batch dimension
|
| 142 |
+
pos_emb = pos_emb.unsqueeze(0).expand(B, -1, -1) # shape (B, T, n_embd)
|
| 143 |
+
x = tok_emb + pos_emb # Now both tensors are shape (B, T, n_embd)
|
| 144 |
+
|
| 145 |
+
# forward the blocks of the transformer
|
| 146 |
+
for block in self.transformer.h:
|
| 147 |
+
x = block(x)
|
| 148 |
+
|
| 149 |
+
# forward the final layernorm and the classifier
|
| 150 |
+
x = self.transformer.ln_f(x)
|
| 151 |
+
logits = self.lm_head(x) # (B, T, vocab_size)
|
| 152 |
+
|
| 153 |
+
loss = None
|
| 154 |
+
if targets is not None:
|
| 155 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
|
| 156 |
+
return logits, loss
|
| 157 |
+
|
| 158 |
+
@classmethod
|
| 159 |
+
def from_pretrained(cls, model_type):
|
| 160 |
+
"""Loads pretrained GPT-2 model weights from huggingface"""
|
| 161 |
+
assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
|
| 162 |
+
from transformers import GPT2LMHeadModel
|
| 163 |
+
print("loading weights from pretrained gpt: %s" % model_type)
|
| 164 |
+
|
| 165 |
+
# n_layer, n_head and n_embd are determined from model_type
|
| 166 |
+
config_args = {
|
| 167 |
+
'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
|
| 168 |
+
'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
|
| 169 |
+
'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
|
| 170 |
+
'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
|
| 171 |
+
}[model_type]
|
| 172 |
+
config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
|
| 173 |
+
config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
|
| 174 |
+
# create a from-scratch initialized minGPT model
|
| 175 |
+
config = GPTConfig(**config_args)
|
| 176 |
+
model = GPT(config)
|
| 177 |
+
sd = model.state_dict()
|
| 178 |
+
sd_keys = sd.keys()
|
| 179 |
+
sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
|
| 180 |
+
|
| 181 |
+
# init a huggingface/transformers model
|
| 182 |
+
model_hf = GPT2LMHeadModel.from_pretrained(model_type)
|
| 183 |
+
sd_hf = model_hf.state_dict()
|
| 184 |
+
|
| 185 |
+
# copy while ensuring all of the parameters are aligned and match in names and shapes
|
| 186 |
+
sd_keys_hf = sd_hf.keys()
|
| 187 |
+
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
|
| 188 |
+
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
|
| 189 |
+
transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
|
| 190 |
+
# basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
|
| 191 |
+
# this means that we have to transpose these weights when we import them
|
| 192 |
+
assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
|
| 193 |
+
for k in sd_keys_hf:
|
| 194 |
+
if any(k.endswith(w) for w in transposed):
|
| 195 |
+
# special treatment for the Conv1D weights we need to transpose
|
| 196 |
+
assert sd_hf[k].shape[::-1] == sd[k].shape
|
| 197 |
+
with torch.no_grad():
|
| 198 |
+
sd[k].copy_(sd_hf[k].t())
|
| 199 |
+
else:
|
| 200 |
+
# vanilla copy over the other parameters
|
| 201 |
+
assert sd_hf[k].shape == sd[k].shape
|
| 202 |
+
with torch.no_grad():
|
| 203 |
+
sd[k].copy_(sd_hf[k])
|
| 204 |
+
|
| 205 |
+
return model
|