Views
No views yet
1from datasets import load_dataset
2import tiktoken, numpy as np
3
4# Load dataset
5ds = load_dataset("IsmaelMousa/movies")
6
7# Split into train/val
8ds = ds['train'].train_test_split(test_size=0.1, seed=42)
9
10# Tokenizer (GPT-2)
11enc = tiktoken.get_encoding("gpt2")
12
13def process(example):
14 ids = enc.encode_ordinary(example['Script'])
15 return {'ids': ids, 'len': len(ids)}
16
17# Tokenize
18tokenized = ds.map(process, remove_columns=['Name','Script']).bin files for fast training.block_size) of tokens.X and target Y sequences, where Y is shifted by 1 (next-token labels).1def get_batch(split):
2 data = train_data if split == 'train' else val_data
3 ix = torch.randint(len(data) - block_size, (batch_size,))
4 x = torch.stack([torch.from_numpy(data[i:i+block_size].astype(np.int64)) for i in ix])
5 y = torch.stack([torch.from_numpy(data[i+1:i+block_size+1].astype(np.int64)) for i in ix])
6 return x.to(device), y.to(device)1class LayerNorm(nn.Module):
2 def __init__(self, ndim, bias):
3 super().__init__()
4 self.weight = nn.Parameter(torch.ones(ndim))
5 self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
6 def forward(self, x):
7 return F.layer_norm(x, self.weight.shape, self.weight, self.bias, 1e-5)1class CausalSelfAttention(nn.Module):
2 def __init__(self, config):
3 super().__init__()
4 self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias) # QKV
5 self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
6 self.n_head = config.n_head
7 self.n_embd = config.n_embd
8
9 def forward(self, x):
10 B, T, C = x.size()
11 q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
12 # Reshape into multi-heads
13 k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
14 q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
15 v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
16
17 # Masked self-attention (causal: no peeking forward)
18 att = (q @ k.transpose(-2, -1)) / (C // self.n_head)**0.5
19 mask = torch.tril(torch.ones(T, T, device=x.device))
20 att = att.masked_fill(mask == 0, float('-inf'))
21 att = F.softmax(att, dim=-1)
22 y = att @ v
23
24 # Recombine heads
25 y = y.transpose(1, 2).contiguous().view(B, T, C)
26 return self.c_proj(y)1class MLP(nn.Module):
2 def __init__(self, config):
3 super().__init__()
4 self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
5 self.gelu = nn.GELU()
6 self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
7
8 def forward(self, x):
9 return self.c_proj(self.gelu(self.c_fc(x)))1class Block(nn.Module):
2 def __init__(self, config):
3 super().__init__()
4 self.ln1 = LayerNorm(config.n_embd, config.bias)
5 self.attn = CausalSelfAttention(config)
6 self.ln2 = LayerNorm(config.n_embd, config.bias)
7 self.mlp = MLP(config)
8
9 def forward(self, x):
10 x = x + self.attn(self.ln1(x)) # Residual
11 x = x + self.mlp(self.ln2(x)) # Residual
12 return x[Norm → Attention → Residual → Norm → MLP → Residual].1class GPT(nn.Module):
2 def __init__(self, config):
3 super().__init__()
4 self.transformer = nn.ModuleDict(dict(
5 wte = nn.Embedding(config.vocab_size, config.n_embd), # token embedding
6 wpe = nn.Embedding(config.block_size, config.n_embd), # position embedding
7 h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
8 ln_f = LayerNorm(config.n_embd, config.bias),
9 ))
10 self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
11 self.transformer.wte.weight = self.lm_head.weight # weight tying
12
13 def forward(self, idx, targets=None):
14 b, t = idx.size()
15 tok_emb = self.transformer.wte(idx)
16 pos_emb = self.transformer.wpe(torch.arange(0, t, device=idx.device))
17 x = tok_emb + pos_emb
18 for block in self.transformer.h:
19 x = block(x)
20 x = self.transformer.ln_f(x)
21 logits = self.lm_head(x)
22
23 if targets is None:
24 return logits, None
25 loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
26 return logits, losstargets provided → compute cross-entropy loss.1@torch.no_grad()
2def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
3 for _ in range(max_new_tokens):
4 idx_cond = idx[:, -self.config.block_size:]
5 logits, _ = self(idx_cond)
6 logits = logits[:, -1, :] / temperature
7 if top_k is not None:
8 v, _ = torch.topk(logits, top_k)
9 logits[logits < v[:, [-1]]] = -float('Inf')
10 probs = F.softmax(logits, dim=-1)
11 idx_next = torch.multinomial(probs, num_samples=1)
12 idx = torch.cat((idx, idx_next), dim=1)
13 return idxtemperature (randomness) and top_k (restricts to top-k likely tokens).1plt.plot(train_loss_list, 'g', label='train_loss')
2plt.plot(validation_loss_list, 'r', label='validation_loss')
3plt.xlabel("Steps - Every 100 epochs")
4plt.ylabel("Loss")
5plt.legend()
6plt.show()| Epoch | Train Loss | Val Loss | Perplexity |
|---|---|---|---|
| 500 | 6.0358 | 6.0601 | 430.1 |
| 1000 | 5.0690 | 5.1143 | 166.0 |
| 1500 | 4.3162 | 4.3407 | 76.7 |
| 2000 | 3.5948 | 3.6099 | 36.9 |
| 2500 | 3.0460 | 3.0569 | 21.3 |
| 3000 | 2.7518 | 2.7398 | 15.5 |
| 3500 | 2.5606 | 2.5574 | 12.9 |
| 4000 | 2.4583 | 2.4691 | 11.8 |
| 4500 | 2.3943 | 2.3969 | 11.0 |
| 5000 | 2.3428 | 2.3513 | 10.5 |
| 6000 | 2.2141 | 2.2155 | 9.17 |
| 7000 | 2.1389 | 2.1577 | 8.65 |
| 8000 | 2.0570 | 2.0703 | 7.93 |
| 9000 | 2.0062 | 2.0210 | 7.55 |
| 10000 | 1.9604 | 1.9715 | 7.18 |
| 12000 | 1.8580 | 1.8924 | 6.64 |
| 14000 | 1.7954 | 1.8284 | 6.23 |
| 16000 | 1.7369 | 1.7937 | 5.95 |
| 18000 | 1.6901 | 1.7314 | 5.65 |
| 19500 | 1.6594 | 1.7216 | 5.60 |
1# Load best model
2model = GPT(config)
3model.load_state_dict(torch.load("best_model_params.pt", map_location=device))
4model.eval()
5
6# Prompt
7sentence = "Write a Tarantino-style diner scene with two strangers..."
8context = torch.tensor(enc.encode_ordinary(sentence)).unsqueeze(0).to(device)
9
10# Generate (recommended shorter length)
11y = model.generate(context, max_new_tokens=300, temperature=0.8, top_k=50)
12print(enc.decode(y[0].tolist()))max_new_tokens=5000 was used, which may be excessive.