lemonteaa commited on
Commit
a0570ed
1 Parent(s): 8336bb2

Create src/infer1.py

Browse files
Files changed (1) hide show
  1. src/infer1.py +213 -0
src/infer1.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Coded by llama3 405b with some manual changes added
2
+ # Quick and dirty test, not cleaned up
3
+
4
+ import torch
5
+ import torch.nn.functional as F
6
+ from dataclasses import dataclass
7
+
8
+ import tiktoken
9
+
10
+ tokenizer = tiktoken.get_encoding("gpt2")
11
+
12
+ # Define the GPTConfig dataclass
13
+ @dataclass
14
+ class GPTConfig:
15
+ vocab_size : int = 50304
16
+ n_layer : int = 12
17
+ n_head : int = 6 # head dim 128 suggested by @Grad62304977
18
+ n_embd : int = 768
19
+
20
+ # Define the Rotary class
21
+ class Rotary(torch.nn.Module):
22
+
23
+ def __init__(self, dim, base=10000):
24
+ super().__init__()
25
+ self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
26
+ self.seq_len_cached = None
27
+ self.cos_cached = None
28
+ self.sin_cached = None
29
+
30
+ def forward(self, x):
31
+ seq_len = x.shape[1]
32
+ if seq_len!= self.seq_len_cached:
33
+ self.seq_len_cached = seq_len
34
+ t = torch.arange(seq_len, device=x.device).type_as(self.inv_freq)
35
+ freqs = torch.outer(t, self.inv_freq).to(x.device)
36
+ self.cos_cached = freqs.cos().bfloat16()
37
+ self.sin_cached = freqs.sin().bfloat16()
38
+ return self.cos_cached[None, :, None, :], self.sin_cached[None, :, None, :]
39
+
40
+ def apply_rotary_emb(x, cos, sin):
41
+ assert x.ndim == 4 # multihead attention
42
+ d = x.shape[3]//2
43
+ x1 = x[..., :d]
44
+ x2 = x[..., d:]
45
+ y1 = x1 * cos + x2 * sin
46
+ y2 = x1 * (-sin) + x2 * cos
47
+ return torch.cat([y1, y2], 3).type_as(x)
48
+
49
+ # Define the CausalSelfAttention class
50
+ class CausalSelfAttention(torch.nn.Module):
51
+
52
+ def __init__(self, config):
53
+ super().__init__()
54
+ self.n_head = config.n_head
55
+ self.n_embd = config.n_embd
56
+ self.head_dim = self.n_embd // self.n_head
57
+ assert self.n_embd % self.n_head == 0
58
+ self.c_q = torch.nn.Linear(self.n_embd, self.n_embd, bias=False)
59
+ self.c_k = torch.nn.Linear(self.n_embd, self.n_embd, bias=False)
60
+ self.c_v = torch.nn.Linear(self.n_embd, self.n_embd, bias=False)
61
+ # output projection
62
+ self.c_proj = torch.nn.Linear(self.n_embd, self.n_embd, bias=False)
63
+ self.c_proj.weight.data.zero_() # zero init suggested by @Grad62304977
64
+ self.rotary = Rotary(self.head_dim)
65
+ self.lamb = torch.nn.Parameter(torch.tensor(0.5)) # @Grad62304977
66
+
67
+ def forward(self, x, v1=None):
68
+ B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
69
+ q = self.c_q(x).view(B, T, self.n_head, self.head_dim)
70
+ k = self.c_k(x).view(B, T, self.n_head, self.head_dim)
71
+ v = self.c_v(x).view(B, T, self.n_head, self.head_dim)
72
+ if v1 is None:
73
+ v1 = v # This happens if we are in the first block. v needs to be accessed by subsequent blocks
74
+ v = (1 - self.lamb) * v + self.lamb * v1.view_as(v) # @Grad62304977
75
+ cos, sin = self.rotary(q)
76
+ q, k = F.rms_norm(q, (q.size(-1),)), F.rms_norm(k, (k.size(-1),)) # QK norm suggested by @Grad62304977
77
+ q, k = apply_rotary_emb(q, cos, sin), apply_rotary_emb(k, cos, sin)
78
+ y = F.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True)
79
+ y = y.transpose(1, 2).contiguous().view_as(x) # re-assemble all head outputs side by side
80
+ y = self.c_proj(y)
81
+ return y, v1
82
+
83
+ # Define the MLP class
84
+ class MLP(torch.nn.Module):
85
+
86
+ def __init__(self, config):
87
+ super().__init__()
88
+ self.c_fc = torch.nn.Linear(config.n_embd, 4 * config.n_embd, bias=False)
89
+ self.c_proj = torch.nn.Linear(4 * config.n_embd, config.n_embd, bias=False)
90
+ self.c_proj.weight.data.zero_() # zero init suggested by @Grad62304977
91
+
92
+ def forward(self, x):
93
+ x = self.c_fc(x)
94
+ x = F.relu(x).square() # https://arxiv.org/abs/2109.08668v2; ~1-2% better than GELU; suggested by @SKYLINEZ007 and @Grad62304977
95
+ x = self.c_proj(x)
96
+ return x
97
+
98
+ # Define the Block class
99
+ class Block(torch.nn.Module):
100
+
101
+ def __init__(self, config):
102
+ super().__init__()
103
+ self.attn = CausalSelfAttention(config)
104
+ self.mlp = MLP(config)
105
+ self.lambdas = torch.nn.Parameter(torch.tensor([1., 0.]))
106
+
107
+ def forward(self, x, v1, x0):
108
+ x = self.lambdas[0] * x + self.lambdas[1] * x0
109
+ x1, v1 = self.attn(F.rms_norm(x, (x.size(-1),)), v1)
110
+ x = x + x1
111
+ x = x + self.mlp(F.rms_norm(x, (x.size(-1),)))
112
+ return x, v1
113
+
114
+ # Define the GPT class
115
+ class GPT(torch.nn.Module):
116
+
117
+ def __init__(self, config):
118
+ super().__init__()
119
+ self.config = config
120
+
121
+ self.transformer = torch.nn.ModuleDict(dict(
122
+ wte = torch.nn.Embedding(config.vocab_size, config.n_embd),
123
+ h = torch.nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
124
+ ))
125
+ self.lm_head = torch.nn.Linear(config.n_embd, config.vocab_size, bias=False)
126
+ self.lm_head.weight.data.zero_() # @Grad62304977
127
+
128
+ def forward(self, idx, targets=None, return_logits=True):
129
+
130
+ # forward the GPT model itself
131
+ x = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
132
+ x = F.rms_norm(x, (x.size(-1),)) # @Grad62304977
133
+ x0 = x
134
+ v1 = None
135
+ for block in self.transformer.h:
136
+ x, v1 = block(x, v1, x0)
137
+ x = F.rms_norm(x, (x.size(-1),))
138
+
139
+ if targets is not None:
140
+ # if we are given some desired targets also calculate the loss
141
+ logits = self.lm_head(x)
142
+ logits = 30 * torch.tanh(logits / 30) # @Grad62304977
143
+ logits = logits.float() # use tf32/fp32 for logits
144
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
145
+ else:
146
+ # inference-time mini-optimization: only forward the lm_head on the very last position
147
+ logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
148
+ logits = 30 * torch.tanh(logits / 30) # @Grad62304977
149
+ logits = logits.float() # use tf32/fp32 for logits
150
+ loss = None
151
+
152
+ # there are performance reasons why not returning logits is prudent, if not needed
153
+ if not return_logits:
154
+ logits = None
155
+
156
+ return logits, loss
157
+
158
+ # From https://github.com/karpathy/llm.c/blob/master/train_gpt2.py
159
+ def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
160
+ """
161
+ Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
162
+ the sequence max_new_tokens times, feeding the predictions back into the model each time.
163
+ Most likely you'll want to make sure to be in model.eval() mode of operation for this.
164
+ """
165
+ for _ in range(max_new_tokens):
166
+ # if the sequence context is growing too long we must crop it at block_size
167
+ #idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
168
+ # forward the model to get the logits for the index in the sequence
169
+ logits, _ = self(idx)
170
+ # pluck the logits at the final step and scale by desired temperature
171
+ logits = logits[:, -1, :] / temperature
172
+ # optionally crop the logits to only the top k options
173
+ if top_k is not None:
174
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
175
+ logits[logits < v[:, [-1]]] = -float('Inf')
176
+ # apply softmax to convert logits to (normalized) probabilities
177
+ probs = F.softmax(logits, dim=-1)
178
+ # sample from the distribution
179
+ idx_next = torch.multinomial(probs, num_samples=1)
180
+ # append sampled index to the running sequence and continue
181
+ idx = torch.cat((idx, idx_next), dim=1)
182
+
183
+ return idx
184
+
185
+ # Load the trained parameters
186
+ def load_checkpoint(model, checkpoint_path):
187
+ checkpoint = torch.load(checkpoint_path, map_location=torch.device('cpu'))
188
+ model.load_state_dict(dict([(n.removeprefix("_orig_mod."), p) for n, p in checkpoint['model'].items()])) # Due to loading from training checkpoint
189
+
190
+ # Run LLM inference
191
+ def run_inference(model, input_ids):
192
+ input_ids = torch.tensor(input_ids).unsqueeze(0)
193
+ return model.generate(input_ids, 50)
194
+
195
+ # Main function
196
+ def main():
197
+ config = GPTConfig()
198
+ model = GPT(config)
199
+ checkpoint_path = 'state_step003200.pt' # replace with your checkpoint path
200
+ load_checkpoint(model, checkpoint_path)
201
+ model.eval()
202
+
203
+ prompt = "Once upon a time, in a magical kingdom, "
204
+ input_ids = tokenizer.encode_ordinary(prompt)
205
+ output_ids = run_inference(model, input_ids)
206
+ #print(output_ids)
207
+ tmp = output_ids.squeeze().tolist()
208
+ #print(tmp)
209
+ print(tokenizer.decode(tmp))
210
+
211
+
212
+ if __name__ == '__main__':
213
+ main()