Spaces:
Running
Running
HannahLin271
commited on
Create model.py
Browse files
model.py
ADDED
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Full definition of a GPT Language Model, all of it in this single file.
|
3 |
+
References:
|
4 |
+
1) the official GPT-2 TensorFlow implementation released by OpenAI:
|
5 |
+
https://github.com/openai/gpt-2/blob/master/src/model.py
|
6 |
+
2) huggingface/transformers PyTorch implementation:
|
7 |
+
https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py
|
8 |
+
"""
|
9 |
+
|
10 |
+
import math
|
11 |
+
import inspect
|
12 |
+
from dataclasses import dataclass
|
13 |
+
|
14 |
+
import torch
|
15 |
+
import torch.nn as nn
|
16 |
+
from torch.nn import functional as F
|
17 |
+
|
18 |
+
class LayerNorm(nn.Module):
|
19 |
+
""" LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False """
|
20 |
+
|
21 |
+
def __init__(self, ndim, bias):
|
22 |
+
super().__init__()
|
23 |
+
self.weight = nn.Parameter(torch.ones(ndim))
|
24 |
+
self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
|
25 |
+
|
26 |
+
def forward(self, input):
|
27 |
+
return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5)
|
28 |
+
|
29 |
+
class CausalSelfAttention(nn.Module):
|
30 |
+
|
31 |
+
def __init__(self, config):
|
32 |
+
super().__init__()
|
33 |
+
assert config.n_embd % config.n_head == 0
|
34 |
+
# key, query, value projections for all heads, but in a batch
|
35 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
|
36 |
+
# output projection
|
37 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
|
38 |
+
# regularization
|
39 |
+
self.attn_dropout = nn.Dropout(config.dropout)
|
40 |
+
self.resid_dropout = nn.Dropout(config.dropout)
|
41 |
+
self.n_head = config.n_head
|
42 |
+
self.n_embd = config.n_embd
|
43 |
+
self.dropout = config.dropout
|
44 |
+
# flash attention make GPU go brrrrr but support is only in PyTorch >= 2.0
|
45 |
+
self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
|
46 |
+
if not self.flash:
|
47 |
+
print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
|
48 |
+
# causal mask to ensure that attention is only applied to the left in the input sequence (torch.tril gives the lower triangular part of the matrix)
|
49 |
+
self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
|
50 |
+
.view(1, 1, config.block_size, config.block_size))
|
51 |
+
|
52 |
+
def forward(self, x):
|
53 |
+
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
|
54 |
+
|
55 |
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
56 |
+
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
|
57 |
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
58 |
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
59 |
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
60 |
+
|
61 |
+
# causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
|
62 |
+
if self.flash:
|
63 |
+
# efficient attention using Flash Attention CUDA kernels
|
64 |
+
y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=self.dropout if self.training else 0, is_causal=True)
|
65 |
+
else:
|
66 |
+
# manual implementation of attention
|
67 |
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
68 |
+
att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf')) # fill the upper triangle of the attention matrix with -inf
|
69 |
+
att = F.softmax(att, dim=-1)
|
70 |
+
att = self.attn_dropout(att)
|
71 |
+
y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
|
72 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
|
73 |
+
|
74 |
+
# output projection
|
75 |
+
y = self.resid_dropout(self.c_proj(y))
|
76 |
+
return y
|
77 |
+
|
78 |
+
class MLP(nn.Module):
|
79 |
+
|
80 |
+
def __init__(self, config):
|
81 |
+
super().__init__()
|
82 |
+
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias) # length = 4 * n_embd
|
83 |
+
self.gelu = nn.GELU()
|
84 |
+
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias) # project the length back to n_embd
|
85 |
+
self.dropout = nn.Dropout(config.dropout)
|
86 |
+
|
87 |
+
def forward(self, x):
|
88 |
+
x = self.c_fc(x)
|
89 |
+
x = self.gelu(x)
|
90 |
+
x = self.c_proj(x)
|
91 |
+
x = self.dropout(x)
|
92 |
+
return x
|
93 |
+
|
94 |
+
class Block(nn.Module):
|
95 |
+
|
96 |
+
def __init__(self, config):
|
97 |
+
super().__init__()
|
98 |
+
self.ln_1 = LayerNorm(config.n_embd, bias=config.bias)
|
99 |
+
self.attn = CausalSelfAttention(config)
|
100 |
+
self.ln_2 = LayerNorm(config.n_embd, bias=config.bias)
|
101 |
+
self.mlp = MLP(config)
|
102 |
+
|
103 |
+
def forward(self, x):
|
104 |
+
x = x + self.attn(self.ln_1(x))
|
105 |
+
x = x + self.mlp(self.ln_2(x))
|
106 |
+
return x
|
107 |
+
|
108 |
+
@dataclass
|
109 |
+
class GPTConfig:
|
110 |
+
block_size: int = 1024
|
111 |
+
vocab_size: int = 50304 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
|
112 |
+
n_layer: int = 12
|
113 |
+
n_head: int = 12
|
114 |
+
n_embd: int = 768
|
115 |
+
dropout: float = 0.0
|
116 |
+
bias: bool = False # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
|
117 |
+
pos_embd: str = 'default'
|
118 |
+
"""
|
119 |
+
Improving positional Embeddings
|
120 |
+
1. RoPE
|
121 |
+
2. Relative
|
122 |
+
3. Dynamic
|
123 |
+
"""
|
124 |
+
################################### 1. RoPE ###################################
|
125 |
+
class RotaryPositionalEmbedding(nn.Module):
|
126 |
+
def __init__(self, config):
|
127 |
+
super().__init__()
|
128 |
+
self.dim = config.n_embd
|
129 |
+
self.inv_freq = 1.0 / (10000 ** (torch.arange(0, self.dim, 2).float() / self.dim))
|
130 |
+
|
131 |
+
def forward(self, seq_len, device):
|
132 |
+
pos = torch.arange(seq_len, dtype=torch.float, device=device) # Ensure pos is on the correct device
|
133 |
+
sinusoid_inp = torch.einsum("i,j->ij", pos, self.inv_freq.to(device)) # Move self.inv_freq to the same device
|
134 |
+
emb = torch.cat([torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)], dim=-1)
|
135 |
+
return emb
|
136 |
+
|
137 |
+
@staticmethod
|
138 |
+
def apply_rotary_embedding(x, rope):
|
139 |
+
# Ensure all tensors are on the same device
|
140 |
+
device = x.device
|
141 |
+
rope = rope.to(device)
|
142 |
+
|
143 |
+
# x: shape (batch, seq_len, dim)
|
144 |
+
# rope: shape (seq_len, dim)
|
145 |
+
dim = rope.size(-1)
|
146 |
+
x1, x2 = x[..., :dim // 2], x[..., dim // 2:]
|
147 |
+
rope1, rope2 = rope[..., :dim // 2], rope[..., dim // 2:]
|
148 |
+
return torch.cat([x1 * rope1 - x2 * rope2, x1 * rope2 + x2 * rope1], dim=-1)
|
149 |
+
|
150 |
+
|
151 |
+
# MARK: - GPT Model
|
152 |
+
class GPT(nn.Module):
|
153 |
+
|
154 |
+
def __init__(self, config):
|
155 |
+
super().__init__()
|
156 |
+
assert config.vocab_size is not None
|
157 |
+
assert config.block_size is not None
|
158 |
+
self.config = config
|
159 |
+
|
160 |
+
self.transformer = nn.ModuleDict(dict(
|
161 |
+
wte = nn.Embedding(config.vocab_size, config.n_embd), # token embedding
|
162 |
+
wpe = nn.Embedding(config.block_size, config.n_embd), # positional embedding
|
163 |
+
rope = RotaryPositionalEmbedding(config), # improving PE: 1. RoPE
|
164 |
+
drop = nn.Dropout(config.dropout), # dropout layer
|
165 |
+
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]), # the transformer
|
166 |
+
ln_f = LayerNorm(config.n_embd, bias=config.bias), # layer norm at the output of the model
|
167 |
+
))
|
168 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
169 |
+
# with weight tying when using torch.compile() some warnings get generated:
|
170 |
+
# "UserWarning: functional_call was passed multiple values for tied weights.
|
171 |
+
# This behavior is deprecated and will be an error in future versions"
|
172 |
+
# not 100% sure what this is, so far seems to be harmless. TODO investigate
|
173 |
+
self.transformer.wte.weight = self.lm_head.weight # https://paperswithcode.com/method/weight-tying
|
174 |
+
|
175 |
+
# init all weights
|
176 |
+
self.apply(self._init_weights)
|
177 |
+
# apply special scaled init to the residual projections, per GPT-2 paper
|
178 |
+
for pn, p in self.named_parameters():
|
179 |
+
if pn.endswith('c_proj.weight'):
|
180 |
+
torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layer))
|
181 |
+
|
182 |
+
# report number of parameters
|
183 |
+
print("number of parameters: %.2fM" % (self.get_num_params()/1e6,))
|
184 |
+
|
185 |
+
def get_num_params(self, non_embedding=True):
|
186 |
+
"""
|
187 |
+
Return the number of parameters in the model.
|
188 |
+
For non-embedding count (default), the position embeddings get subtracted.
|
189 |
+
The token embeddings would too, except due to the parameter sharing these
|
190 |
+
params are actually used as weights in the final layer, so we include them.
|
191 |
+
"""
|
192 |
+
n_params = sum(p.numel() for p in self.parameters())
|
193 |
+
if non_embedding:
|
194 |
+
n_params -= self.transformer.wpe.weight.numel()
|
195 |
+
return n_params
|
196 |
+
|
197 |
+
def _init_weights(self, module):
|
198 |
+
if isinstance(module, nn.Linear):
|
199 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
200 |
+
if module.bias is not None:
|
201 |
+
torch.nn.init.zeros_(module.bias)
|
202 |
+
elif isinstance(module, nn.Embedding):
|
203 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
204 |
+
|
205 |
+
def forward(self, idx, targets=None):
|
206 |
+
device = idx.device
|
207 |
+
b, t = idx.size()
|
208 |
+
assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
|
209 |
+
pos = torch.arange(0, t, dtype=torch.long, device=device) # shape (t)
|
210 |
+
|
211 |
+
# forward the GPT model itself
|
212 |
+
tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
|
213 |
+
|
214 |
+
'''POSITIONAL EMBEDDING'''
|
215 |
+
if self.config.pos_embd == 'default':
|
216 |
+
# 0. Default NanoGPT
|
217 |
+
pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)
|
218 |
+
x = self.transformer.drop(tok_emb + pos_emb)
|
219 |
+
elif self.config.pos_embd == 'rope':
|
220 |
+
# 1. RoPE
|
221 |
+
rope = self.transformer.rope.forward(t, device=device) # (t, n_embd)
|
222 |
+
pos_emb = rope.unsqueeze(0).expand(b, -1, -1) # (b, t, n_embd)
|
223 |
+
x = RotaryPositionalEmbedding.apply_rotary_embedding(tok_emb, pos_emb)
|
224 |
+
else:
|
225 |
+
raise ValueError(f"Unknown positional embedding type: {self.config.pos_embedding_type}")
|
226 |
+
|
227 |
+
################################### 0. Default of Nano GPT ###################################
|
228 |
+
# pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)
|
229 |
+
##TODO: the embedding here is simple, just sum them up, could improve with more sophisticated tokenization
|
230 |
+
# x = self.transformer.drop(tok_emb + pos_emb)
|
231 |
+
|
232 |
+
# ################################### 1. RoPE ###################################
|
233 |
+
# rope = self.transformer.rope.forward(t, device=device) # (t, n_embd)
|
234 |
+
# pos_emb = rope.unsqueeze(0).expand(b, -1, -1) # (b, t, n_embd)
|
235 |
+
# x = RotaryPositionalEmbedding.apply_rotary_embedding(tok_emb, pos_emb)
|
236 |
+
|
237 |
+
#########################################################################################################
|
238 |
+
|
239 |
+
for block in self.transformer.h:
|
240 |
+
x = block(x)
|
241 |
+
x = self.transformer.ln_f(x)
|
242 |
+
|
243 |
+
if targets is not None:
|
244 |
+
# if we are given some desired targets also calculate the loss
|
245 |
+
logits = self.lm_head(x) # B, T, C = logits.shape
|
246 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
|
247 |
+
else:
|
248 |
+
# inference-time mini-optimization: only forward the lm_head on the very last position
|
249 |
+
logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
|
250 |
+
loss = None
|
251 |
+
|
252 |
+
return logits, loss
|
253 |
+
|
254 |
+
def crop_block_size(self, block_size):
|
255 |
+
# model surgery to decrease the block size if necessary
|
256 |
+
# e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)
|
257 |
+
# but want to use a smaller block size for some smaller, simpler model
|
258 |
+
assert block_size <= self.config.block_size
|
259 |
+
self.config.block_size = block_size
|
260 |
+
self.transformer.wpe.weight = nn.Parameter(self.transformer.wpe.weight[:block_size])
|
261 |
+
for block in self.transformer.h:
|
262 |
+
if hasattr(block.attn, 'bias'):
|
263 |
+
block.attn.bias = block.attn.bias[:,:,:block_size,:block_size]
|
264 |
+
|
265 |
+
@classmethod
|
266 |
+
def from_pretrained(cls, model_type, override_args=None):
|
267 |
+
assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
|
268 |
+
override_args = override_args or {} # default to empty dict
|
269 |
+
# only dropout can be overridden see more notes below
|
270 |
+
assert all(k == 'dropout' for k in override_args)
|
271 |
+
from transformers import GPT2LMHeadModel
|
272 |
+
print("loading weights from pretrained gpt: %s" % model_type)
|
273 |
+
|
274 |
+
# n_layer, n_head and n_embd are determined from model_type
|
275 |
+
config_args = {
|
276 |
+
'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
|
277 |
+
'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
|
278 |
+
'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
|
279 |
+
'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
|
280 |
+
}[model_type]
|
281 |
+
print("forcing vocab_size=50257, block_size=1024, bias=True")
|
282 |
+
config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
|
283 |
+
config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
|
284 |
+
config_args['bias'] = True # always True for GPT model checkpoints
|
285 |
+
# we can override the dropout rate, if desired
|
286 |
+
if 'dropout' in override_args:
|
287 |
+
print(f"overriding dropout rate to {override_args['dropout']}")
|
288 |
+
config_args['dropout'] = override_args['dropout']
|
289 |
+
# create a from-scratch initialized minGPT model
|
290 |
+
config = GPTConfig(**config_args)
|
291 |
+
model = GPT(config)
|
292 |
+
sd = model.state_dict()
|
293 |
+
sd_keys = sd.keys()
|
294 |
+
sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
|
295 |
+
|
296 |
+
# init a huggingface/transformers model
|
297 |
+
model_hf = GPT2LMHeadModel.from_pretrained(model_type)
|
298 |
+
sd_hf = model_hf.state_dict()
|
299 |
+
|
300 |
+
# copy while ensuring all of the parameters are aligned and match in names and shapes
|
301 |
+
sd_keys_hf = sd_hf.keys()
|
302 |
+
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
|
303 |
+
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
|
304 |
+
transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
|
305 |
+
# basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
|
306 |
+
# this means that we have to transpose these weights when we import them
|
307 |
+
assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
|
308 |
+
for k in sd_keys_hf:
|
309 |
+
if any(k.endswith(w) for w in transposed):
|
310 |
+
# special treatment for the Conv1D weights we need to transpose
|
311 |
+
assert sd_hf[k].shape[::-1] == sd[k].shape
|
312 |
+
with torch.no_grad():
|
313 |
+
sd[k].copy_(sd_hf[k].t())
|
314 |
+
else:
|
315 |
+
# vanilla copy over the other parameters
|
316 |
+
assert sd_hf[k].shape == sd[k].shape
|
317 |
+
with torch.no_grad():
|
318 |
+
sd[k].copy_(sd_hf[k])
|
319 |
+
|
320 |
+
return model
|
321 |
+
|
322 |
+
def configure_optimizers(self, weight_decay, learning_rate, betas, device_type):
|
323 |
+
# start with all of the candidate parameters
|
324 |
+
param_dict = {pn: p for pn, p in self.named_parameters()}
|
325 |
+
# filter out those that do not require grad
|
326 |
+
param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
|
327 |
+
# create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.
|
328 |
+
# i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.
|
329 |
+
decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
|
330 |
+
nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
|
331 |
+
optim_groups = [
|
332 |
+
{'params': decay_params, 'weight_decay': weight_decay},
|
333 |
+
{'params': nodecay_params, 'weight_decay': 0.0}
|
334 |
+
]
|
335 |
+
num_decay_params = sum(p.numel() for p in decay_params)
|
336 |
+
num_nodecay_params = sum(p.numel() for p in nodecay_params)
|
337 |
+
print(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters")
|
338 |
+
print(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters")
|
339 |
+
# Create AdamW optimizer and use the fused version if it is available
|
340 |
+
fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
|
341 |
+
use_fused = fused_available and device_type == 'cuda'
|
342 |
+
extra_args = dict(fused=True) if use_fused else dict()
|
343 |
+
optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **extra_args)
|
344 |
+
print(f"using fused AdamW: {use_fused}")
|
345 |
+
|
346 |
+
return optimizer
|
347 |
+
|
348 |
+
def estimate_mfu(self, fwdbwd_per_iter, dt):
|
349 |
+
""" estimate model flops utilization (MFU) in units of A100 bfloat16 peak FLOPS """
|
350 |
+
# first estimate the number of flops we do per iteration.
|
351 |
+
# see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
|
352 |
+
N = self.get_num_params()
|
353 |
+
cfg = self.config
|
354 |
+
L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd//cfg.n_head, cfg.block_size
|
355 |
+
flops_per_token = 6*N + 12*L*H*Q*T
|
356 |
+
flops_per_fwdbwd = flops_per_token * T
|
357 |
+
flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter
|
358 |
+
# express our flops throughput as ratio of A100 bfloat16 peak flops
|
359 |
+
flops_achieved = flops_per_iter * (1.0/dt) # per second
|
360 |
+
flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
|
361 |
+
mfu = flops_achieved / flops_promised
|
362 |
+
return mfu
|
363 |
+
|
364 |
+
@torch.no_grad()
|
365 |
+
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
|
366 |
+
# idx is (B,T) array of indices in the current context
|
367 |
+
"""
|
368 |
+
Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
|
369 |
+
the sequence max_new_tokens times, feeding the predictions back into the model each time.
|
370 |
+
Most likely you'll want to make sure to be in model.eval() mode of operation for this.
|
371 |
+
"""
|
372 |
+
for _ in range(max_new_tokens):
|
373 |
+
# if the sequence context is growing too long we must crop it at block_size
|
374 |
+
idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
|
375 |
+
# forward the model to get the logits for the index in the sequence
|
376 |
+
logits, _ = self(idx_cond)
|
377 |
+
# pluck the logits at the final step and scale by desired temperature
|
378 |
+
logits = logits[:, -1, :] / temperature
|
379 |
+
# optionally crop the logits to only the top k options
|
380 |
+
if top_k is not None:
|
381 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
382 |
+
logits[logits < v[:, [-1]]] = -float('Inf')
|
383 |
+
# apply softmax to convert logits to (normalized) probabilities
|
384 |
+
probs = F.softmax(logits, dim=-1)
|
385 |
+
# sample from the distribution
|
386 |
+
idx_next = torch.multinomial(probs, num_samples=1)
|
387 |
+
# append sampled index to the running sequence and continue
|
388 |
+
idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
|
389 |
+
|
390 |
+
return idx
|