AliMuhammad73 commited on
Commit
3880c6e
·
verified ·
1 Parent(s): 88efd43

Upload model and tokenizer

Browse files
Files changed (2) hide show
  1. modeling_gpt.py +200 -0
  2. tokenizer_config.json +1 -1
modeling_gpt.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model/model.py
2
+ import torch
3
+ import torch.nn as nn
4
+ import inspect
5
+ from huggingface_hub import PyTorchModelHubMixin
6
+
7
+ # Define hyperparameters and constants
8
+ BATCH_SIZE = 16
9
+ BLOCK_SIZE = 1024
10
+ MAX_ITERS = 5
11
+ EVAL_INTERVAL = 500
12
+ LEARNING_RATE = 6e-4
13
+ DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
14
+ EVAL_ITERS = 200
15
+ N_EMBD = 768
16
+ N_HEAD = 12
17
+ N_LAYER = 12
18
+ DROPOUT = 0.2
19
+ MODEL_PATH = "Naive_gpt\model_weights_llama" # Where to save weights
20
+
21
+ class CausalSelfAttention(nn.Module):
22
+
23
+ def __init__(self):
24
+ super().__init__()
25
+ assert N_EMBD % N_HEAD == 0
26
+ # key, query, value projections for all heads, but in a batch
27
+ self.c_attn = nn.Linear(N_EMBD, 3 * N_EMBD)
28
+ # output projection
29
+ self.c_proj = nn.Linear(N_EMBD, N_EMBD)
30
+ self.c_proj.NANOGPT_SCALE_INIT = 1
31
+ # regularization
32
+ self.n_head = N_HEAD
33
+ self.n_embd = N_EMBD
34
+
35
+ def forward(self, x):
36
+ B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
37
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
38
+ # nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
39
+ # e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
40
+ qkv = self.c_attn(x)
41
+ q, k, v = qkv.split(self.n_embd, dim=2)
42
+ k = k.view(B, T, self.n_head, C //
43
+ self.n_head).transpose(1, 2) # (B, nh, T, hs)
44
+ q = q.view(B, T, self.n_head, C //
45
+ self.n_head).transpose(1, 2) # (B, nh, T, hs)
46
+ v = v.view(B, T, self.n_head, C //
47
+ self.n_head).transpose(1, 2) # (B, nh, T, hs)
48
+ y = nn.functional.scaled_dot_product_attention(
49
+ q, k, v, is_causal=True) # flash attention
50
+ # re-assemble all head outputs side by side
51
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
52
+ # output projection
53
+ y = self.c_proj(y)
54
+ return y
55
+
56
+
57
+ class FeedFoward(nn.Module): #yeh MLP hai karpathy wala -> Feed forward hai sebastian wala
58
+ def __init__(self):
59
+ super().__init__()
60
+ self.c_fc = nn.Linear(N_EMBD, 4 * N_EMBD)
61
+ self.gelu = nn.GELU(approximate='tanh')
62
+ self.c_proj = nn.Linear(4 * N_EMBD, N_EMBD)
63
+ self.c_proj.NANOGPT_SCALE_INIT = 1
64
+
65
+ def forward(self, x):
66
+ x = self.c_fc(x)
67
+ x = self.gelu(x)
68
+ x = self.c_proj(x)
69
+ return x
70
+ """ a simple linear layer followed by a non-linearity """
71
+
72
+ class Block(nn.Module):
73
+ """ Transformer block: communication followed by computation """
74
+
75
+ def __init__(self, n_embd, n_head):
76
+ super().__init__()
77
+ head_size = N_EMBD // n_head
78
+ self.sa = CausalSelfAttention()
79
+ self.ffwd = FeedFoward()
80
+ self.ln1 = nn.LayerNorm(N_EMBD)
81
+ self.ln2 = nn.LayerNorm(N_EMBD)
82
+
83
+ def forward(self, x):
84
+ x = x + self.sa(self.ln1(x))
85
+ x = x + self.ffwd(self.ln2(x))
86
+ return x
87
+
88
+ class GPTLanguageModel(nn.Module, PyTorchModelHubMixin):
89
+
90
+ def __init__(self, vocab_size=20000, block_size=1024, n_embd=768, n_head=12, n_layer=12):
91
+ super().__init__()
92
+ print("This is vocab size:", vocab_size)
93
+ self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
94
+ self.position_embedding_table = nn.Embedding(block_size, n_embd)
95
+ self.blocks = nn.Sequential(
96
+ *[Block(n_embd, n_head=n_head) for _ in range(n_layer)]
97
+ )
98
+ self.ln_f = nn.LayerNorm(n_embd)
99
+ self.lm_head = nn.Linear(n_embd, vocab_size)
100
+
101
+ self.token_embedding_table.weight = self.lm_head.weight
102
+
103
+ self.apply(self._init_weights)
104
+ self.config = {"BLOCK_SIZE": block_size, "N_EMBD": n_embd, "N_HEAD":n_head, "N_LAYER": n_layer}
105
+
106
+
107
+ def _init_weights(self, module):
108
+ if isinstance(module, nn.Linear):
109
+ std = 0.02
110
+ if hasattr(module, 'NANOGPT_SCALE_INIT'):
111
+ std *= (2 * N_LAYER) ** -0.5
112
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
113
+ if module.bias is not None:
114
+ torch.nn.init.zeros_(module.bias)
115
+ elif isinstance(module, nn.Embedding):
116
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
117
+
118
+ def forward(self, idx, targets=None):
119
+ B, T = idx.shape
120
+ assert T <= BLOCK_SIZE, f"Cannot forward sequence of length {T}, block size is only {BLOCK_SIZE}"
121
+
122
+
123
+ tok_emb = self.token_embedding_table(idx)
124
+ pos_emb = self.position_embedding_table(torch.arange(0, T, dtype=torch.long, device=idx.device))
125
+ x = tok_emb + pos_emb
126
+ x = self.blocks(x)
127
+ x = self.ln_f(x)
128
+ logits = self.lm_head(x)
129
+
130
+ if targets is None:
131
+ loss = None
132
+ else:
133
+ loss = nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
134
+
135
+ return logits, loss
136
+
137
+ def generate(self, idx, max_new_tokens, temperature=1.0):
138
+ """
139
+ Generate tokens using the language model.
140
+ Args:
141
+ idx: Input token indices
142
+ max_new_tokens: Number of tokens to generate
143
+ temperature: Controls randomness in generation
144
+ - temperature > 1.0 increases randomness
145
+ - temperature < 1.0 decreases randomness
146
+ - temperature = 0 makes it deterministic (always picks highest probability)
147
+ """
148
+ for _ in range(max_new_tokens):
149
+ # Truncate the sequence to the last BLOCK_SIZE tokens
150
+ idx_cond = idx[:, -BLOCK_SIZE:]
151
+ # Get logits from the model
152
+ logits, _ = self(idx_cond)
153
+ # Focus only on the last time step
154
+ logits = logits[:, -1, :]
155
+
156
+ if temperature == 0.0:
157
+ # For temperature = 0, simply take the argmax
158
+ idx_next = torch.argmax(logits, dim=-1, keepdim=True)
159
+ else:
160
+ # Apply temperature scaling
161
+ logits = logits / temperature
162
+ # Convert to probabilities
163
+ probs = torch.softmax(logits, dim=-1)
164
+ # Sample from the distribution
165
+ idx_next = torch.multinomial(probs, num_samples=1)
166
+
167
+ # Append the new token to the sequence
168
+ idx = torch.cat((idx, idx_next), dim=1)
169
+ return idx
170
+
171
+ def save(self, path=MODEL_PATH):
172
+ torch.save(self.state_dict(), path)
173
+
174
+ def load(self, path=MODEL_PATH):
175
+ # Load the state dict
176
+ state_dict = torch.load(path)["model"]
177
+
178
+ new_state_dict = {}
179
+ for key, value in state_dict.items():
180
+ new_key = key.replace('_orig_mod.', '') # Remove 'orig_mod.' prefix
181
+ new_state_dict[new_key] = value
182
+
183
+ self.load_state_dict(new_state_dict)
184
+
185
+
186
+ def configure_optimizers(self, weight_decay=0.1, learning_rate=LEARNING_RATE, device=DEVICE):
187
+ param_dict = {pn: p for pn, p in self.named_parameters()}
188
+ param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
189
+
190
+ decay_parameters = [p for n, p in param_dict.items() if p.dim() >= 2]
191
+ nodecay_parameters = [p for n, p in param_dict.items() if p.dim() < 2]
192
+ optim_groups = [
193
+ {"params": decay_parameters, "weight_decay": weight_decay},
194
+ {"params": nodecay_parameters, "weight_decay": 0.0},
195
+ ]
196
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
197
+ use_fused = fused_available and device == "cuda"
198
+ optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=(0.9, 0.95), eps=1e-8, fused = use_fused)
199
+ return optimizer
200
+ MODEL_PATH = "Naive_gpt\model_weights_llama" # Where to save weights
tokenizer_config.json CHANGED
@@ -1,4 +1,4 @@
1
  {
2
  "type": "llama",
3
- "vocab_size": 0
4
  }
 
1
  {
2
  "type": "llama",
3
+ "vocab_size": 20000
4
  }