Spaces:
Sleeping
Sleeping
Upload gpt.py
Browse files
gpt.py
ADDED
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
|
5 |
+
import tiktoken
|
6 |
+
enc = tiktoken.get_encoding("gpt2")
|
7 |
+
|
8 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
9 |
+
|
10 |
+
class MultiHeadAttention(nn.Module):
|
11 |
+
def __init__(self, d_model, n_heads):
|
12 |
+
super().__init__()
|
13 |
+
self.d_model = d_model
|
14 |
+
self.n_heads = n_heads
|
15 |
+
assert d_model % n_heads == 0, "d_model must be divisible by n_heads"
|
16 |
+
self.d_key = self.d_model // self.n_heads
|
17 |
+
|
18 |
+
self.wq = nn.Linear(d_model, d_model)
|
19 |
+
self.wk = nn.Linear(d_model, d_model)
|
20 |
+
self.wv = nn.Linear(d_model, d_model)
|
21 |
+
|
22 |
+
self.wo = nn.Linear(d_model, d_model)
|
23 |
+
def forward(self, ins, mask=None):
|
24 |
+
batch_size, seq_len, d_model = ins.size()
|
25 |
+
Q = self.wq(ins).view(batch_size, seq_len, self.n_heads, self.d_key).transpose(1, 2)
|
26 |
+
K = self.wk(ins).view(batch_size, seq_len, self.n_heads, self.d_key).transpose(1, 2)
|
27 |
+
V = self.wv(ins).view(batch_size, seq_len, self.n_heads, self.d_key).transpose(1, 2)
|
28 |
+
|
29 |
+
#scaled_dot_product = (Q @ K.transpose(2, 3)) / (self.d_model ** 0.5)
|
30 |
+
|
31 |
+
#if mask is not None:
|
32 |
+
#scaled_dot_product += mask
|
33 |
+
|
34 |
+
attn_scores = F.scaled_dot_product_attention(Q, K, V, is_causal=True, attn_mask=mask)
|
35 |
+
#F.softmax(scaled_dot_product, dim=-1) @ V
|
36 |
+
attn_scores = attn_scores.transpose(1, 2).contiguous().view(batch_size, seq_len, d_model)
|
37 |
+
return self.wo(attn_scores)
|
38 |
+
|
39 |
+
class MLP(nn.Module):
|
40 |
+
def __init__(self, in_size, hidden_size, out_size):
|
41 |
+
super().__init__()
|
42 |
+
self.l1 = nn.Linear(in_size, hidden_size)
|
43 |
+
self.l2 = nn.Linear(hidden_size, out_size)
|
44 |
+
self.gelu = nn.GELU()
|
45 |
+
def forward(self, ins):
|
46 |
+
acts = self.gelu(self.l1(ins))
|
47 |
+
return self.l2(acts)
|
48 |
+
|
49 |
+
class DecoderBlock(nn.Module):
|
50 |
+
def __init__(self, vocab_size, d_model, n_heads, dropout=0.1):
|
51 |
+
super().__init__()
|
52 |
+
self.d_model = d_model
|
53 |
+
self.n_heads = n_heads
|
54 |
+
self.dropout = nn.Dropout(dropout)
|
55 |
+
self.MHA = MultiHeadAttention(d_model, n_heads)
|
56 |
+
self.MLP = MLP(d_model, 4*d_model, d_model)
|
57 |
+
self.layernorm1 = nn.LayerNorm(d_model)
|
58 |
+
self.layernorm2 = nn.LayerNorm(d_model)
|
59 |
+
def forward(self, ins, mask=None):
|
60 |
+
ins = ins + self.MHA(self.layernorm1(ins), mask=mask)
|
61 |
+
ins = ins + self.MLP(self.layernorm2(ins))
|
62 |
+
return self.dropout(ins)
|
63 |
+
|
64 |
+
class GPT(nn.Module):
|
65 |
+
def __init__(self, vocab_size, block_size, n_layers=2, n_heads=4, d_model=64, dropout=0.1):
|
66 |
+
super().__init__()
|
67 |
+
self.vocab_size = vocab_size
|
68 |
+
self.block_size = block_size
|
69 |
+
self.n_layers = n_layers
|
70 |
+
self.n_heads = n_heads
|
71 |
+
self.d_model = d_model
|
72 |
+
self.dropout = dropout
|
73 |
+
|
74 |
+
self.token_embedding = nn.Embedding(vocab_size, d_model)
|
75 |
+
self.position_embedding = nn.Embedding(block_size, d_model)
|
76 |
+
self.decoder_stack = nn.ModuleList([
|
77 |
+
DecoderBlock(vocab_size, d_model, n_heads, dropout=dropout) for _ in range(n_layers)
|
78 |
+
])
|
79 |
+
self.final_ln = nn.LayerNorm(d_model)
|
80 |
+
self.output_proj = nn.Linear(d_model, vocab_size, bias=False)
|
81 |
+
#self.token_embedding.weight = self.output_proj.weight
|
82 |
+
def forward(self, ins, targets=None):
|
83 |
+
B, T = ins.size()
|
84 |
+
|
85 |
+
x = self.token_embedding(ins.to(device))
|
86 |
+
input_indices = torch.arange(T).to(device)
|
87 |
+
x += self.position_embedding(input_indices)
|
88 |
+
|
89 |
+
#look_ahead_mask = torch.triu(
|
90 |
+
#torch.ones((T, T)), diagonal=1
|
91 |
+
#)
|
92 |
+
#look_ahead_mask.masked_fill_(look_ahead_mask == 1, float("-inf"))
|
93 |
+
#look_ahead_mask = look_ahead_mask.to(device)
|
94 |
+
|
95 |
+
for decoder in self.decoder_stack:
|
96 |
+
x = decoder(x) #mask=look_ahead_mask
|
97 |
+
x = self.final_ln(x)
|
98 |
+
logits = self.output_proj(x)
|
99 |
+
loss = None
|
100 |
+
if targets is not None:
|
101 |
+
targets = targets.to(device)
|
102 |
+
loss = F.cross_entropy(logits.view(-1, self.vocab_size), targets.view(-1))
|
103 |
+
return logits, loss
|
104 |
+
|
105 |
+
|
106 |
+
block_size = 512
|
107 |
+
n_layers = 12
|
108 |
+
n_heads = 12
|
109 |
+
d_model = 768
|
110 |
+
|
111 |
+
torch.set_float32_matmul_precision('high')
|
112 |
+
|
113 |
+
my_GPT = GPT(enc.n_vocab, block_size, n_layers, n_heads, d_model, dropout=0.1) #enc.n_vocab
|
114 |
+
my_GPT = my_GPT.to(device)
|
115 |
+
my_GPT = torch.compile(my_GPT)
|
116 |
+
my_GPT.load_state_dict(torch.load('latest_model_finetune.pth'))
|
117 |
+
my_GPT.eval()
|
118 |
+
|
119 |
+
eot = enc._special_tokens['<|endoftext|>']
|
120 |
+
|
121 |
+
def get_response(in_text):
|
122 |
+
prompt = "USER: " + in_text + "\nASSISTANT: "
|
123 |
+
input_tokens = enc.encode(prompt)
|
124 |
+
output_tokens = enc.encode(prompt)
|
125 |
+
top_k = 50
|
126 |
+
top_p = 0
|
127 |
+
for x in range(block_size):
|
128 |
+
if len(input_tokens) > block_size:
|
129 |
+
input_tokens = input_tokens[1:]
|
130 |
+
context_tensor = torch.tensor(input_tokens).view(1, -1).to(device)
|
131 |
+
|
132 |
+
logits, loss = my_GPT(context_tensor)
|
133 |
+
logits = logits[:, -1, :]
|
134 |
+
if top_k > 0:
|
135 |
+
# Remove all tokens with a probability less than the last token of the top-k
|
136 |
+
indices_to_remove = logits < torch.topk(logits, top_k, dim=1)[0][..., -1, None]
|
137 |
+
logits[indices_to_remove] = float("-inf")
|
138 |
+
if top_p > 0.0:
|
139 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
140 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
141 |
+
|
142 |
+
# Remove tokens with cumulative probability above the threshold
|
143 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
144 |
+
# Shift the indices to the right to keep also the first token above the threshold
|
145 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
146 |
+
sorted_indices_to_remove[..., 0] = 0
|
147 |
+
|
148 |
+
indices_to_remove = sorted_indices[sorted_indices_to_remove]
|
149 |
+
logits[indices_to_remove] = float("-inf")
|
150 |
+
probs = F.softmax(logits, dim=-1)
|
151 |
+
result = torch.multinomial(probs, num_samples=1).item()
|
152 |
+
if result == eot:
|
153 |
+
break
|
154 |
+
input_tokens.append(result)
|
155 |
+
output_tokens.append(result)
|
156 |
+
|
157 |
+
return enc.decode(output_tokens)
|