-
Notifications
You must be signed in to change notification settings - Fork 18
/
GPT_1.py
executable file
·161 lines (135 loc) · 5.02 KB
/
GPT_1.py
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
from time import time
import torch
import torch.nn as nn
class SelfAttention(nn.Module):
def __init__(self, input_dims, heads):
super(SelfAttention, self).__init__()
self.heads = heads
self.head_dims = int(input_dims/heads)
self.input_dims = input_dims
self.query = nn.Linear(self.head_dims, self.head_dims)
self.key = nn.Linear(self.head_dims, self.head_dims)
self.value = nn.Linear(self.head_dims, self.head_dims)
self.fc = nn.Linear(self.head_dims*heads, self.input_dims)
def forward(self, query, key, value, mask):
Batch, Seq_len, embed = query.shape
query_len, key_len, value_len = query.shape[1], key.shape[1], value.shape[1]
query = query.reshape(Batch, query_len, self.heads, self.head_dims)
key = key.reshape(Batch, key_len, self.heads, self.head_dims)
value = value.reshape(Batch, value_len, self.heads, self.head_dims)
query = self.query(query)
key = self.key(key)
value = self.value(value)
score = torch.einsum('bqhd,bkhd->bhqk', [query, key])
if mask is not None:
score = score.masked_fill(mask == 0, float('-1e20'))
attention_score = nn.Softmax(dim=-1)(score/((self.head_dims)**(1/2)))
out = torch.einsum('bhqv,bvhd->bqhd', [attention_score, value]).reshape(Batch, query_len, self.head_dims*self.heads)
out = self.fc(out)
return out
class GPTBlock(nn.Module):
def __init__(
self,
heads,
embedding_dims,
dropout,
forward_expansion,
layer_norm_eps
):
super(GPTBlock, self).__init__()
self.embedding_dims = embedding_dims
self.attention = SelfAttention(embedding_dims, heads)
self.layer_norm1 = nn.LayerNorm(embedding_dims, eps=layer_norm_eps)
self.layer_norm2 = nn.LayerNorm(embedding_dims, eps=layer_norm_eps)
self.feed_forward = nn.Sequential(
*[
nn.Linear(embedding_dims, embedding_dims*forward_expansion),
nn.GELU(),
nn.Linear(embedding_dims*forward_expansion, embedding_dims)
]
)
self.dropout = nn.Dropout(dropout)
def forward(self, x, mask):
attention_block = self.attention(x, x, x, mask)
add = self.dropout(self.layer_norm1(attention_block + x))
feed_forward = self.feed_forward(add)
out = self.dropout(self.layer_norm2(feed_forward + add))
return out
class GPT(nn.Module):
def __init__(
self,
vocab_size,
embedding_dims,
dropout,
heads,
num_of_layers,
forward_expansion,
max_len,
layer_norm_eps = 1e-5
):
super(GPT, self).__init__()
self.embedding_dims = embedding_dims
self.word_embeddings = nn.Embedding(vocab_size, embedding_dims)
self.positional_embeddings = nn.Parameter(torch.zeros(1, max_len, embedding_dims))
self.dropout = nn.Dropout(dropout)
self.gpt_blocks = nn.ModuleList(
[
GPTBlock(
heads,
embedding_dims,
dropout,
forward_expansion,
layer_norm_eps
)
for _ in range(num_of_layers)
]
)
self.layer_norm = nn.LayerNorm(embedding_dims, eps=layer_norm_eps)
self.fc = nn.Linear(embedding_dims, vocab_size)
self.apply(self._init_weights)
#From @HuggingFace
def _init_weights(self, module):
if isinstance(module, (nn.Linear, nn.Embedding)):
module.weight.data.normal_(mean=0.0, std=0.02)
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
if isinstance(module, nn.Linear) and module.bias is not None:
module.bias.data.zero_()
def casual_mask(self, x):
mask = torch.tril(torch.ones((x.shape[0], x.shape[-1], x.shape[-1]))).unsqueeze(1)
return mask
def forward(self, x):
casual_mask = self.casual_mask(x)
seq_len = x.shape[-1]
word_embeddings = self.word_embeddings(x)
x = self.dropout(word_embeddings + self.positional_embeddings[:, :seq_len, :])
for block in self.gpt_blocks:
x = block(x, casual_mask)
x = self.layer_norm(x)
out = self.fc(x)
return x
if __name__ == '__main__':
#DEFAULT GPT PARAMETERS :-
vocab_size = 40478
embedding_dims = 768
dropout = 0.1
heads = 12
num_of_layers = 12
forward_expansion = 4
max_len = 512
a = torch.randint(1, 100, (1, 300))
model = GPT(
vocab_size,
embedding_dims,
dropout,
heads,
num_of_layers,
forward_expansion,
max_len,
)
start = time()
y = model(a)
print(f'INFERENCE TIME = {time() - start}sec')
x = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f'NUMBER OF PARAMETERS ARE = {x}')