1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
| import torch from torch import nn import math from dataclasses import dataclass import torch.nn.functional as F from pathlib import Path
@dataclass class GPTConfig: block_size: int = 256 vocab_size: int = 73 n_layer: int = 4 n_head: int = 4 n_embd: int = 256 dropout: float = 0.1
TINY_GPT_DIR = Path(__file__).parent SRC_DIR = TINY_GPT_DIR.parent ROOT_DIR = SRC_DIR.parent
FILE_PATH = ROOT_DIR / "data" / "processed" / "alice.txt" OUT_PATH = ROOT_DIR / "tokenizer.json"
device = "cpu" if torch.cuda.is_available(): device = "cuda"
class CausalMaskedAttention(nn.Module): def __init__(self, config): super().__init__()
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
self.attn_dropout = nn.Dropout(config.dropout) self.out_dropout = nn.Dropout(config.dropout)
self.n_embd = config.n_embd self.n_head = config.n_head
def forward(self, x): B, T, C = x.size()
qkv = self.c_attn(x) q, k, v = qkv.split(self.n_embd, dim=-1)
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
scores = torch.matmul(q, k.transpose(-1, -2)) / math.sqrt( C // self.n_head )
mask = torch.tril(torch.ones(T, T, device=x.device)).view(1, 1, T, T) scores = scores.masked_fill(mask == 0, float("-inf"))
weights = torch.softmax(scores, dim=-1) weights = self.attn_dropout(weights)
output = torch.matmul(weights, v)
output = output.transpose(1, 2).contiguous().view(B, T, C)
y = self.c_proj(output) y = self.out_dropout(y) return y
class MLP(nn.Module): def __init__(self, config): super().__init__()
self.network = nn.Sequential( nn.Linear(config.n_embd, 4 * config.n_embd), nn.GELU(approximate="tanh"), nn.Linear(4 * config.n_embd, config.n_embd), nn.Dropout(config.dropout), )
def forward(self, x): return self.network(x)
class Block(nn.Module): def __init__(self, config): super().__init__()
self.ln_1 = nn.LayerNorm(config.n_embd) self.attn = CausalMaskedAttention(config) self.ln_2 = nn.LayerNorm(config.n_embd) self.mlp = MLP(config)
def forward(self, x): x = x + self.attn(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x
class Tiny_GPT(nn.Module): def __init__(self, config): super().__init__()
self.transformer = nn.ModuleDict( dict( wte=nn.Embedding(config.vocab_size, config.n_embd), wpe=nn.Embedding(config.block_size, config.n_embd), h=nn.ModuleList( [Block(config) for _ in range(config.n_layer)] ), ln_f=nn.LayerNorm(config.n_embd), ) ) self.lm_head = nn.Linear(config.n_embd, config.vocab_size)
def forward(self, x, target=None): B, T = x.size()
token_embd = self.transformer.wte(x)
pos = torch.arange(0, T, dtype=torch.long, device=x.device) pos_embd = self.transformer.wpe(pos)
x = token_embd + pos_embd
for layer in self.transformer.h: x = layer(x)
x = self.transformer.ln_f(x)
logits = self.lm_head(x)
loss = None if target is not None: loss = F.cross_entropy( logits.reshape(-1, logits.size(-1)), target.reshape(-1), )
return logits, loss
|