tranquilkd commited on
Commit
292f256
·
1 Parent(s): 18d0753

First Commit

Browse files
Files changed (7) hide show
  1. .gitattributes +0 -0
  2. .gitignore +136 -0
  3. GPT-Shakespeare.pth +3 -0
  4. README.md +0 -0
  5. app.py +105 -0
  6. requirements.txt +3 -0
  7. transformer.py +323 -0
.gitattributes CHANGED
File without changes
.gitignore ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ *.egg-info/
24
+ .installed.cfg
25
+ *.egg
26
+
27
+ # PyInstaller
28
+ # Usually these files are written by a python script from a template
29
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
30
+ *.manifest
31
+ *.spec
32
+
33
+ # Installer logs
34
+ pip-log.txt
35
+ pip-delete-this-directory.txt
36
+
37
+ # Unit test / coverage reports
38
+ htmlcov/
39
+ .tox/
40
+ .nox/
41
+ .coverage
42
+ .coverage.*
43
+ .cache
44
+ nosetests.xml
45
+ coverage.xml
46
+ *.cover
47
+ *.py,cover
48
+ .hypothesis/
49
+ .pytest_cache/
50
+
51
+ # Translations
52
+ *.mo
53
+ *.pot
54
+
55
+ # Django stuff:
56
+ *.log
57
+ local_settings.py
58
+ db.sqlite3
59
+
60
+ # Flask stuff:
61
+ instance/
62
+ .webassets-cache
63
+
64
+ # Scrapy stuff:
65
+ .scrapy
66
+
67
+ # Sphinx documentation
68
+ docs/_build/
69
+
70
+ # PyBuilder
71
+ target/
72
+
73
+ # Jupyter Notebook
74
+ .ipynb_checkpoints
75
+
76
+ # IPython
77
+ profile_default/
78
+ ipython_config.py
79
+
80
+ # pyenv
81
+ .python-version
82
+
83
+ # Celery stuff
84
+ celerybeat-schedule
85
+ celerybeat.pid
86
+
87
+ # SageMath parsed files
88
+ *.sage.py
89
+
90
+ # Environments
91
+ .env
92
+ .venv
93
+ env/
94
+ venv/
95
+ ENV/
96
+ env.bak/
97
+ venv.bak/
98
+
99
+ # Spyder project settings
100
+ .spyderproject
101
+ .spyproject
102
+
103
+ # Rope project settings
104
+ .ropeproject
105
+
106
+ # mkdocs documentation
107
+ /site
108
+
109
+ # mypy
110
+ .mypy_cache/
111
+ .dmypy.json
112
+ dmypy.json
113
+
114
+ # Pyre type checker
115
+ .pyre/
116
+
117
+ # PyTorch Lightning
118
+ lightning_logs/
119
+
120
+ # VS Code
121
+ .vscode/
122
+
123
+ # MacOS
124
+ .DS_Store
125
+
126
+ # Thumbnails
127
+ ._*
128
+
129
+ # Temporary files
130
+ *.tmp
131
+ *.temp
132
+ *.swp
133
+ *.swo
134
+
135
+ # extras
136
+ *.xlsx
GPT-Shakespeare.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1d3090cfad6aa084fd0ab066772d0e4b2cd2d3169f0f043fc6a2e85b64502cf
3
+ size 548147736
README.md CHANGED
File without changes
app.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import traceback
4
+ import tiktoken
5
+ import gradio as gr
6
+ import torch.nn.functional as F
7
+ from transformer import GPTConfig, GPT
8
+
9
+
10
+ def load_model(model_path):
11
+ # model
12
+ config = GPTConfig()
13
+ model = GPT(config)
14
+
15
+ ckpt = torch.load(os.path.join(model_path), map_location="cpu")
16
+ model.load_state_dict(ckpt["model_state_dict"])
17
+ model.to(device)
18
+ model.eval()
19
+
20
+ return model
21
+
22
+
23
+ def generate_text(text, max_length=64, num_return_sequences=2):
24
+
25
+ tokenizer = tiktoken.get_encoding('gpt2')
26
+ x = tokenizer.encode(text)
27
+ x = torch.tensor(x, dtype=torch.long)
28
+ x = x.unsqueeze(0)
29
+ x = x.repeat(num_return_sequences, 1)
30
+ x = x.to(device)
31
+
32
+ for _ in range(max_length):
33
+
34
+ with torch.no_grad():
35
+ logits, _ = model(x)
36
+ # take the logits at the last position
37
+ logits = logits[:, -1, :] # (B, vocab_size)
38
+ # get the probabilities
39
+ probs = F.softmax(logits, dim=-1)
40
+ # do top-k sampling of 50 (huggingface pipeline default)
41
+ # topk_probs here becomes (5, 50), topk_indices is (5, 50)
42
+ topk_probs, topk_indices = torch.topk(probs, 50, dim=-1)
43
+ # select a token from the top-k probabilities
44
+ # note: multinomial does not demand the input to sum to 1
45
+ ix = torch.multinomial(topk_probs, 1) # (B, 1)
46
+ # gather the corresponding indices
47
+ xcol = torch.gather(topk_indices, -1, ix) # (B, 1)
48
+ # append to the sequence
49
+ x = torch.cat((x, xcol), dim=1)
50
+
51
+ generated_text = []
52
+ for i in range(num_return_sequences):
53
+ tokens = x[i, :max_length].tolist()
54
+ decoded = tokenizer.decode(tokens)
55
+ generated_text.append("\n>>>\n" + decoded + "\n\n")
56
+
57
+ return "".join(generated_text)
58
+
59
+
60
+ device = "cuda" if torch.cuda.is_available() else "cpu"
61
+ model = load_model(R"GPT-Shakespeare.pth")
62
+
63
+ # Define the Gradio interface
64
+ demo = gr.Interface(
65
+ fn=generate_text,
66
+ inputs= [
67
+ gr.Textbox(
68
+ label="Input Text",
69
+ placeholder="Enter the text in style of Coriolanus",
70
+ lines=5
71
+ ),
72
+ gr.Slider(minimum=1,
73
+ maximum=128,
74
+ step=1,
75
+ value=20,
76
+ label="Max Sequence Length"),
77
+ gr.Slider(minimum=1,
78
+ maximum=5,
79
+ step=1,
80
+ value=2,
81
+ label="Number of Sequences to Return")
82
+ ],
83
+ outputs=gr.Textbox(lines=5,
84
+ placeholder="Generated text will be shown here",
85
+ label="Generated Text"),
86
+ title= """<h1 style='text-align: center;'> Text Generation using GPT \
87
+ <a href='https://github.com/KD1994/session-12-Transformer-from-scratch-pt2' target='_blank'> \
88
+ <i class='fab fa-github' style='font-size: 24px;'></i></a> \
89
+ </h1> \
90
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">""",
91
+ description = "<p style='text-align: center'> Decoder only transformer trained on \"Coriolanus\" by William Shakespeare </p>",
92
+ examples = [
93
+ ["My noble Coriolanus, temper thy rage. These men hold"],
94
+ ["Wisdom, say’st thou? Counsel, and truth? Nay, Menenius, they are"],
95
+ ["What speaks this man of war and violence?"],
96
+ ["Enough, Coriolanus! Thy words grow wild. What wouldst thou have?"]
97
+ ]
98
+ )
99
+
100
+ # Add error handling to launch
101
+ try:
102
+ demo.launch()
103
+ except Exception as e:
104
+ print(f"Error launching interface: {str(e)}")
105
+ print(traceback.format_exc())
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio
2
+ torch
3
+ tiktoken
transformer.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from dataclasses import dataclass
6
+
7
+
8
+ class CausalSelfAttention(nn.Module):
9
+
10
+ def __init__(self, config):
11
+ super().__init__()
12
+ assert config.n_embd % config.n_head == 0
13
+ # key, query, value projections for all heads, but in a batch
14
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
15
+ # output projection
16
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
17
+ self.c_proj.NANGPT_SCALE_INIT = 1
18
+ # regularization
19
+ self.n_head = config.n_head
20
+ self.n_embd = config.n_embd
21
+ self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)).view(1, 1, config.block_size, config.block_size))
22
+
23
+ def forward(self, x):
24
+ B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
25
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
26
+ # nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
27
+ # e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
28
+ qkv = self.c_attn(x)
29
+ q, k, v = qkv.split(self.n_embd, dim=2)
30
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
31
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
32
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
33
+
34
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
35
+ att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
36
+ att = F.softmax(att, dim=-1)
37
+ y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
38
+
39
+ y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
40
+ # output projection
41
+ y = self.c_proj(y)
42
+ return y
43
+
44
+
45
+ class MLP(nn.Module):
46
+
47
+ def __init__(self, config):
48
+ super().__init__()
49
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
50
+ self.gelu = nn.GELU(approximate='tanh')
51
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
52
+ self.c_proj.NANOGPT_SCALE_INIT = 1
53
+
54
+ def forward(self, x):
55
+ x = self.c_fc(x)
56
+ x = self.gelu(x)
57
+ x = self.c_proj(x)
58
+ return x
59
+
60
+ class Block(nn.Module):
61
+
62
+ def __init__(self, config):
63
+ super().__init__()
64
+ self.ln_1 = nn.LayerNorm(config.n_embd)
65
+ self.attn = CausalSelfAttention(config)
66
+ self.ln_2 = nn.LayerNorm(config.n_embd)
67
+ self.mlp = MLP(config)
68
+
69
+ def forward(self, x):
70
+ x = x + self.attn(self.ln_1(x))
71
+ x = x + self.mlp(self.ln_2(x))
72
+ return x
73
+
74
+
75
+ @dataclass
76
+ class GPTConfig:
77
+ block_size: int = 1024 # max sequence length
78
+ vocab_size: int = 50257 # number of tokens: 50,000 BPE merges + 256 bytes tokens + 1 <|endoftext|> token
79
+ n_layer: int = 12 # number of layers
80
+ n_head: int = 12 # number of heads
81
+ n_embd: int = 768 # embedding dimension
82
+
83
+
84
+ class GPT(nn.Module):
85
+
86
+ def __init__(self, config):
87
+ super().__init__()
88
+ self.config = config
89
+
90
+ self.transformer = nn.ModuleDict(dict(
91
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
92
+ wpe = nn.Embedding(config.block_size, config.n_embd),
93
+ h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
94
+ ln_f = nn.LayerNorm(config.n_embd),
95
+ ))
96
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
97
+
98
+ # weight sharing
99
+ self.transformer.wte.weight = self.lm_head.weight
100
+
101
+ # weight initialization
102
+ self.apply(self._init_weights)
103
+
104
+ def _init_weights(self, module):
105
+ if isinstance(module, nn.Linear):
106
+ std = 0.02
107
+ if hasattr(module, 'NANGPT_SCALE_INIT'):
108
+ std *= (2 * self.config.n_layer) ** -0.5
109
+ torch.nn.init.normal_(module.weight, mean = 0.0, std = std)
110
+ if module.bias is not None:
111
+ torch.nn.init.zeros_(module.bias)
112
+ elif isinstance(module, nn.Embedding):
113
+ torch.nn.init.normal_(module.weight, mean=0.0, std = 0.02)
114
+
115
+
116
+
117
+ def forward(self, idx, targets=None):
118
+ # idx is of shape (B, T)
119
+ B, T = idx.size()
120
+ assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
121
+ # forward the token and posisition embeddings
122
+ pos = torch.arange(0, T, dtype=torch.long, device=idx.device) # shape (T)
123
+ pos_emb = self.transformer.wpe(pos) # position embeddings of shape (T, n_embd)
124
+ tok_emb = self.transformer.wte(idx) # token embeddings of shape (B, T, n_embd)
125
+ x = tok_emb + pos_emb
126
+ # forward the blocks of the transformer
127
+ for block in self.transformer.h:
128
+ x = block(x)
129
+ # forward the final layernorm and the classifier
130
+ x = self.transformer.ln_f(x)
131
+ logits = self.lm_head(x) # (B, T, vocab_size)
132
+ loss = None
133
+ if targets is not None:
134
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
135
+ return logits, loss
136
+
137
+ @classmethod
138
+ def from_pretrained(cls, model_type):
139
+ """Loads pretrained GPT-2 model weights from huggingface"""
140
+ assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
141
+ from transformers import GPT2LMHeadModel
142
+ print("loading weights from pretrained gpt: %s" % model_type)
143
+
144
+ # n_layer, n_head and n_embd are determined from model_type
145
+ config_args = {
146
+ 'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
147
+ 'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
148
+ 'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
149
+ 'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
150
+ }[model_type]
151
+ config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
152
+ config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
153
+ # create a from-scratch initialized minGPT model
154
+ config = GPTConfig(**config_args)
155
+ model = GPT(config)
156
+ sd = model.state_dict()
157
+ sd_keys = sd.keys()
158
+ sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
159
+
160
+ # init a huggingface/transformers model
161
+ model_hf = GPT2LMHeadModel.from_pretrained(model_type)
162
+ sd_hf = model_hf.state_dict()
163
+
164
+ # copy while ensuring all of the parameters are aligned and match in names and shapes
165
+ sd_keys_hf = sd_hf.keys()
166
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
167
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
168
+ transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
169
+ # basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
170
+ # this means that we have to transpose these weights when we import them
171
+ assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
172
+ for k in sd_keys_hf:
173
+ if any(k.endswith(w) for w in transposed):
174
+ # special treatment for the Conv1D weights we need to transpose
175
+ assert sd_hf[k].shape[::-1] == sd[k].shape
176
+ with torch.no_grad():
177
+ sd[k].copy_(sd_hf[k].t())
178
+ else:
179
+ # vanilla copy over the other parameters
180
+ assert sd_hf[k].shape == sd[k].shape
181
+ with torch.no_grad():
182
+ sd[k].copy_(sd_hf[k])
183
+
184
+ return model
185
+
186
+
187
+ @dataclass
188
+ class Config:
189
+ vocab_size: int = 50257
190
+ max_seq_len: int = 2048
191
+ dim: int = 768
192
+ num_layers: int = 12
193
+ num_heads: int = 12
194
+ dropout: float = 0.1
195
+
196
+ class MultiHeadAttention(nn.Module):
197
+ def __init__(self, config):
198
+ super().__init__()
199
+ self.config = config
200
+ self.n_head = config.num_heads
201
+ self.n_embd = config.dim
202
+
203
+ # Linear projections for Q, K, V
204
+ self.c_attn = nn.Linear(config.dim, 3 * config.dim) # [n_embd, 3 * n_embd]
205
+ self.c_proj = nn.Linear(config.dim, config.dim) # [n_embd, n_embd]
206
+
207
+ self.attn_dropout = nn.Dropout(config.dropout)
208
+ self.resid_dropout = nn.Dropout(config.dropout)
209
+
210
+ def forward(self, x):
211
+ B, T, C = x.size() # [B, T, n_embd]
212
+
213
+ # Linear projection and split into Q, K, V
214
+ q, k, v = self.c_attn(x).split(self.n_embd, dim=2) # [B, T, n_embd] each
215
+
216
+ # Reshape for multi-head attention
217
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # [B, n_head, T, n_embd/n_head]
218
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # [B, n_head, T, n_embd/n_head]
219
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # [B, n_head, T, n_embd/n_head]
220
+
221
+ # Attention scores
222
+ att = (q @ k.transpose(-2, -1)) * (1.0 / (k.size(-1) ** 0.5)) # [B, n_head, T, T]
223
+ att = F.softmax(att, dim=-1) # [B, n_head, T, T]
224
+ att = self.attn_dropout(att) # [B, n_head, T, T]
225
+
226
+ # Weighted sum of values
227
+ y = att @ v # [B, n_head, T, n_embd/n_head]
228
+
229
+ # Reshape and project
230
+ y = y.transpose(1, 2).contiguous().view(B, T, C) # [B, T, n_embd]
231
+ y = self.c_proj(y) # [B, T, n_embd]
232
+ y = self.resid_dropout(y) # [B, T, n_embd]
233
+
234
+ return y
235
+
236
+ class FeedForward(nn.Module):
237
+ def __init__(self, config):
238
+ super().__init__()
239
+ self.c_fc = nn.Linear(config.dim, 4 * config.dim) # [n_embd, 4 * n_embd]
240
+ self.c_proj = nn.Linear(4 * config.dim, config.dim) # [4 * n_embd, n_embd]
241
+ self.dropout = nn.Dropout(config.dropout)
242
+
243
+ def forward(self, x):
244
+ x = self.c_fc(x) # [B, T, 4 * n_embd]
245
+ x = F.gelu(x) # [B, T, 4 * n_embd]
246
+ x = self.c_proj(x) # [B, T, n_embd]
247
+ x = self.dropout(x) # [B, T, n_embd]
248
+ return x
249
+
250
+ class TransformerBlock(nn.Module):
251
+ def __init__(self, config):
252
+ super().__init__()
253
+ self.ln_1 = nn.LayerNorm(config.dim) # [n_embd]
254
+ self.attn = MultiHeadAttention(config)
255
+ self.ln_2 = nn.LayerNorm(config.dim) # [n_embd]
256
+ self.mlp = FeedForward(config)
257
+
258
+ def forward(self, x):
259
+ x = x + self.attn(self.ln_1(x)) # [B, T, n_embd]
260
+ x = x + self.mlp(self.ln_2(x)) # [B, T, n_embd]
261
+ return x
262
+
263
+ class DecoderOnlyTransformer(nn.Module):
264
+ def __init__(self, config):
265
+ super().__init__()
266
+ self.config = config
267
+ self.wte = nn.Embedding(config.vocab_size, config.dim) # [vocab_size, n_embd]
268
+ self.wpe = nn.Embedding(config.max_seq_len, config.dim) # [max_seq_len, n_embd]
269
+ self.drop = nn.Dropout(config.dropout)
270
+ self.blocks = nn.ModuleList([TransformerBlock(config) for _ in range(config.num_layers)])
271
+ self.ln_f = nn.LayerNorm(config.dim) # [n_embd]
272
+ self.lm_head = nn.Linear(config.dim, config.vocab_size, bias=False) # [n_embd, vocab_size]
273
+
274
+ self.apply(self._init_weights)
275
+
276
+ def _init_weights(self, module):
277
+ if isinstance(module, (nn.Linear, nn.Embedding)):
278
+ module.weight.data.normal_(mean=0.0, std=0.02)
279
+ if isinstance(module, nn.Linear) and module.bias is not None:
280
+ module.bias.data.zero_()
281
+ elif isinstance(module, nn.LayerNorm):
282
+ module.bias.data.zero_()
283
+ module.weight.data.fill_(1.0)
284
+
285
+ def forward(self, idx):
286
+ B, T = idx.size() # [B, T]
287
+
288
+ # Positional embeddings
289
+ pos = torch.arange(0, T, dtype=torch.long, device=idx.device).unsqueeze(0) # [1, T]
290
+
291
+ # Token and position embeddings
292
+ tok_emb = self.wte(idx) # [B, T, n_embd]
293
+ pos_emb = self.wpe(pos) # [1, T, n_embd]
294
+
295
+ # Combine embeddings and apply dropout
296
+ x = self.drop(tok_emb + pos_emb) # [B, T, n_embd]
297
+
298
+ # Transformer blocks
299
+ for block in self.blocks:
300
+ x = block(x) # [B, T, n_embd]
301
+
302
+ # Final layer norm and linear projection
303
+ x = self.ln_f(x) # [B, T, n_embd]
304
+ logits = self.lm_head(x) # [B, T, vocab_size]
305
+
306
+ return logits
307
+
308
+ # if __name__ == '__main__':
309
+ # config = Config()
310
+ # model = DecoderOnlyTransformer(config)
311
+
312
+ # # Example usage
313
+ # batch_size = 4
314
+ # seq_len = 128
315
+
316
+ # # Generate random input
317
+ # input_ids = torch.randint(0, config.vocab_size, (batch_size, seq_len))
318
+
319
+ # # Forward pass
320
+ # logits = model(input_ids)
321
+
322
+ # print("Input shape:", input_ids.shape)
323
+ # print("Output shape:", logits.shape)