edwjin commited on
Commit
f0c8417
·
verified ·
1 Parent(s): d8f350f

Upload PresGPT2.py

Browse files
Files changed (1) hide show
  1. PresGPT2.py +141 -0
PresGPT2.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn import functional as F
4
+
5
+ # parameters for GPT-2
6
+ class GPTConfig:
7
+ def __init__(self, block_size, vocab_size, n_layers, n_heads, n_embd):
8
+ self.block_size = block_size
9
+ self.vocab_size = vocab_size
10
+ self.n_layers = n_layers
11
+ self.n_heads = n_heads
12
+ self.n_embd = n_embd
13
+
14
+ """ one head of self-attention """
15
+ class Head(nn.Module):
16
+ def __init__(self, config):
17
+ super().__init__()
18
+
19
+ head_size = config.n_embd // config.n_heads
20
+
21
+ self.key = nn.Linear(config.n_embd, head_size, bias=False)
22
+ self.query = nn.Linear(config.n_embd, head_size, bias=False)
23
+ self.value = nn.Linear(config.n_embd, head_size, bias=False)
24
+ self.register_buffer('tril', torch.tril(torch.ones(config.block_size, config.block_size)))
25
+
26
+ def forward(self, x):
27
+ _,T,_ = x.shape
28
+
29
+ k = self.key(x)
30
+ q = self.query(x)
31
+
32
+ # transpose last two dimensions
33
+ wei = q @ k.transpose(-2,-1) * (k.shape[-1]**-0.5)
34
+
35
+ # mask out bottom half
36
+ wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf'))
37
+
38
+ # softmax each column
39
+ wei = F.softmax(wei, dim=-1)
40
+
41
+ v = self.value(x)
42
+
43
+ return wei @ v
44
+
45
+ class MultiHeadAttention(nn.Module):
46
+ def __init__(self, config: GPTConfig):
47
+ super().__init__()
48
+ self.heads = nn.ModuleList([Head(config) for _ in range(config.n_heads)])
49
+ self.proj = nn.Linear(config.n_embd,config. n_embd)
50
+ self.proj.STD_SCALE_INIT = 1
51
+
52
+ def forward(self, x):
53
+ out = torch.cat([h(x) for h in self.heads], dim=-1)
54
+ return self.proj(out)
55
+
56
+ class MLP(nn.Module):
57
+ def __init__(self, config):
58
+ super().__init__()
59
+ self.c_fc = nn.Linear(config.n_embd, 4*config.n_embd)
60
+ self.gelu = nn.GELU(approximate='tanh')
61
+ self.c_proj = nn.Linear(4*config.n_embd, config.n_embd)
62
+ self.c_proj.STD_SCALE_INIT = 1
63
+
64
+ def forward(self, x):
65
+ x = self.c_fc(x)
66
+ x = self.gelu(x)
67
+ return self.c_proj(x)
68
+
69
+ class Block(nn.Module):
70
+ def __init__(self, config: GPTConfig):
71
+ super().__init__()
72
+
73
+ self.ln_1 = nn.LayerNorm(config.n_embd)
74
+ self.attn = MultiHeadAttention(config)
75
+ self.ln_2 = nn.LayerNorm(config.n_embd)
76
+ self.mlp = MLP(config)
77
+
78
+ def forward(self, x):
79
+ x = x + self.attn(self.ln_1(x))
80
+ x = x + self.mlp(self.ln_2(x))
81
+ return x
82
+
83
+ class PresGPT2(nn.Module):
84
+ def __init__(self, config: GPTConfig):
85
+ super().__init__()
86
+ self.config = config
87
+
88
+ # stop immediately if not a multiple
89
+ assert config.n_embd % config.n_heads == 0
90
+
91
+ self.transformer = nn.ModuleDict(
92
+ dict(
93
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
94
+ wpe = nn.Embedding(config.block_size, config.n_embd),
95
+ h = nn.ModuleList([Block(config) for _ in range(config.n_layers)]),
96
+ ln_f = nn.LayerNorm(config.n_embd)
97
+ )
98
+ )
99
+
100
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
101
+
102
+ # weight tying intuition: if inputs are encoded similar, outputs should be similar
103
+ self.lm_head.weight = self.transformer.wte.weight
104
+
105
+ self.apply(self.__init_weights)
106
+
107
+ def __init_weights(self, module):
108
+ if isinstance(module, nn.Linear):
109
+ std = 0.02
110
+
111
+ if hasattr(module, 'STD_SCALE_INIT'):
112
+ # 2 times since each Block has two residual sums
113
+ std *= (2*self.config.n_layers)**-0.5
114
+
115
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
116
+ elif isinstance(module, nn.Embedding):
117
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
118
+
119
+ def forward(self, X, y=None):
120
+ B,T = X.shape
121
+
122
+ tok_emb = self.transformer.wte(X) # -> (B, T, config.n_embd)
123
+
124
+ pos = torch.arange(0, T, 1, dtype=torch.long, device=X.device) # put it on the same device as X
125
+
126
+ pos_emb = self.transformer.wpe(pos)
127
+
128
+ x = pos_emb + tok_emb
129
+
130
+ for b in self.transformer.h:
131
+ x = b(x)
132
+
133
+ x = self.transformer.ln_f(x)
134
+
135
+ loss = None
136
+ logits = self.lm_head(x) # B x T x vocab_size
137
+
138
+ if y is not None:
139
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), y.view(-1))
140
+
141
+ return logits, loss