Update model.py
Browse files
model.py
CHANGED
|
@@ -1,57 +1,61 @@
|
|
| 1 |
-
|
| 2 |
import torch
|
| 3 |
import torch.nn as nn
|
| 4 |
from torch.nn import functional as F
|
| 5 |
import json
|
| 6 |
import os
|
| 7 |
|
| 8 |
-
# --- Hyperparameters
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
n_layer = 4
|
| 19 |
-
dropout = 0.0
|
| 20 |
-
|
| 21 |
-
# --- Data Preparation
|
|
|
|
| 22 |
file_path = 'dataset.jsonl'
|
| 23 |
corpus = ""
|
| 24 |
try:
|
| 25 |
with open(file_path, 'r') as f:
|
| 26 |
for line in f:
|
| 27 |
data_point = json.loads(line)
|
|
|
|
| 28 |
corpus += data_point['header'] + '\n' + data_point['formal_statement'] + '\n'
|
| 29 |
except FileNotFoundError:
|
| 30 |
-
print(f"Error: The file '{file_path}' was not found.")
|
| 31 |
-
exit()
|
| 32 |
-
except json.JSONDecodeError:
|
| 33 |
-
print(f"Error: There was a problem parsing a line in '{file_path}'.")
|
| 34 |
exit()
|
| 35 |
-
except KeyError:
|
| 36 |
-
print(f"Error:
|
| 37 |
exit()
|
| 38 |
|
| 39 |
if not corpus:
|
| 40 |
-
print("Error: The corpus is empty.")
|
| 41 |
exit()
|
| 42 |
|
|
|
|
| 43 |
chars = sorted(list(set(corpus)))
|
| 44 |
vocab_size = len(chars)
|
| 45 |
stoi = {ch: i for i, ch in enumerate(chars)}
|
| 46 |
itos = {i: ch for i, ch in enumerate(chars)}
|
| 47 |
-
# Corrected the encode function
|
| 48 |
encode = lambda s: [stoi[c] for c in s]
|
| 49 |
decode = lambda l: ''.join([itos[i] for i in l])
|
|
|
|
|
|
|
| 50 |
data = torch.tensor(encode(corpus), dtype=torch.long)
|
|
|
|
|
|
|
| 51 |
n = int(0.9 * len(data))
|
| 52 |
train_data = data[:n]
|
| 53 |
val_data = data[n:]
|
| 54 |
|
|
|
|
|
|
|
| 55 |
def get_batch(split):
|
| 56 |
data = train_data if split == 'train' else val_data
|
| 57 |
ix = torch.randint(len(data) - block_size, (batch_size,))
|
|
@@ -60,10 +64,11 @@ def get_batch(split):
|
|
| 60 |
x, y = x.to(device), y.to(device)
|
| 61 |
return x, y
|
| 62 |
|
|
|
|
| 63 |
@torch.no_grad()
|
| 64 |
def estimate_loss():
|
| 65 |
out = {}
|
| 66 |
-
model.eval()
|
| 67 |
for split in ['train', 'val']:
|
| 68 |
losses = torch.zeros(eval_iters)
|
| 69 |
for k in range(eval_iters):
|
|
@@ -71,119 +76,89 @@ def estimate_loss():
|
|
| 71 |
logits, loss = model(X, Y)
|
| 72 |
losses[k] = loss.item()
|
| 73 |
out[split] = losses.mean()
|
| 74 |
-
model.train()
|
| 75 |
return out
|
| 76 |
|
| 77 |
-
# ---
|
| 78 |
-
class Head(nn.Module):
|
| 79 |
-
def __init__(self, head_size):
|
| 80 |
-
super().__init__()
|
| 81 |
-
self.key = nn.Linear(n_embd, head_size, bias=False)
|
| 82 |
-
self.query = nn.Linear(n_embd, head_size, bias=False)
|
| 83 |
-
self.value = nn.Linear(n_embd, head_size, bias=False)
|
| 84 |
-
self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
|
| 85 |
-
self.dropout = nn.Dropout(dropout)
|
| 86 |
-
def forward(self, x):
|
| 87 |
-
B, T, C = x.shape
|
| 88 |
-
k = self.key(x)
|
| 89 |
-
q = self.query(x)
|
| 90 |
-
wei = q @ k.transpose(-2, -1) * C**-0.5
|
| 91 |
-
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf'))
|
| 92 |
-
wei = F.softmax(wei, dim=-1)
|
| 93 |
-
self.dropout(wei)
|
| 94 |
-
v = self.value(x)
|
| 95 |
-
out = wei @ v
|
| 96 |
-
return out
|
| 97 |
-
|
| 98 |
-
class MultiHeadAttention(nn.Module):
|
| 99 |
-
def __init__(self, num_heads, head_size):
|
| 100 |
-
super().__init__()
|
| 101 |
-
self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
|
| 102 |
-
self.proj = nn.Linear(num_heads * head_size, n_embd)
|
| 103 |
-
self.dropout = nn.Dropout(dropout)
|
| 104 |
-
def forward(self, x):
|
| 105 |
-
out = torch.cat([h(x) for h in self.heads], dim=-1)
|
| 106 |
-
out = self.dropout(self.proj(out))
|
| 107 |
-
return out
|
| 108 |
-
|
| 109 |
-
class FeedFoward(nn.Module):
|
| 110 |
-
def __init__(self, n_embd):
|
| 111 |
-
super().__init__()
|
| 112 |
-
self.net = nn.Sequential(
|
| 113 |
-
nn.Linear(n_embd, 4 * n_embd),
|
| 114 |
-
nn.ReLU(),
|
| 115 |
-
nn.Linear(4 * n_embd, n_embd),
|
| 116 |
-
nn.Dropout(dropout),
|
| 117 |
-
)
|
| 118 |
-
def forward(self, x):
|
| 119 |
-
return self.net(x)
|
| 120 |
-
|
| 121 |
-
class TransformerBlock(nn.Module):
|
| 122 |
-
def __init__(self, n_embd, n_head):
|
| 123 |
-
super().__init__()
|
| 124 |
-
head_size = n_embd // n_head
|
| 125 |
-
self.sa = MultiHeadAttention(n_head, head_size)
|
| 126 |
-
self.ffwd = FeedFoward(n_embd)
|
| 127 |
-
self.ln1 = nn.LayerNorm(n_embd)
|
| 128 |
-
self.ln2 = nn.LayerNorm(n_embd)
|
| 129 |
-
def forward(self, x):
|
| 130 |
-
x = x + self.sa(self.ln1(x))
|
| 131 |
-
x = x + self.ffwd(self.ln2(x))
|
| 132 |
-
return x
|
| 133 |
-
|
| 134 |
class LanguageModel(nn.Module):
|
| 135 |
-
def __init__(self
|
| 136 |
super().__init__()
|
|
|
|
| 137 |
self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
|
| 138 |
-
|
| 139 |
-
self.
|
| 140 |
-
|
| 141 |
self.lm_head = nn.Linear(n_embd, vocab_size)
|
| 142 |
-
self.block_size = block_size
|
| 143 |
-
self.vocab_size = vocab_size
|
| 144 |
|
| 145 |
def forward(self, idx, targets=None):
|
| 146 |
-
|
| 147 |
-
tok_emb = self.token_embedding_table(idx)
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
loss = None
|
| 154 |
if targets is not None:
|
|
|
|
| 155 |
B, T, C = logits.shape
|
| 156 |
logits = logits.view(B * T, C)
|
| 157 |
targets = targets.view(B * T)
|
| 158 |
loss = F.cross_entropy(logits, targets)
|
|
|
|
| 159 |
return logits, loss
|
| 160 |
|
| 161 |
def generate(self, idx, max_new_tokens):
|
|
|
|
|
|
|
| 162 |
for _ in range(max_new_tokens):
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
probs = F.softmax(logits, dim=-1)
|
|
|
|
| 167 |
idx_next = torch.multinomial(probs, num_samples=1)
|
|
|
|
| 168 |
idx = torch.cat((idx, idx_next), dim=1)
|
| 169 |
return idx
|
| 170 |
|
| 171 |
-
|
| 172 |
# --- Training and Generation ---
|
| 173 |
-
model = LanguageModel(
|
| 174 |
m = model.to(device)
|
|
|
|
|
|
|
| 175 |
optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
|
| 176 |
|
|
|
|
| 177 |
for iter in range(max_iters):
|
|
|
|
| 178 |
if iter % eval_interval == 0:
|
| 179 |
losses = estimate_loss()
|
| 180 |
print(f"step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
|
|
|
|
|
|
|
| 181 |
xb, yb = get_batch('train')
|
|
|
|
|
|
|
| 182 |
logits, loss = model(xb, yb)
|
|
|
|
| 183 |
optimizer.zero_grad(set_to_none=True)
|
| 184 |
loss.backward()
|
|
|
|
| 185 |
optimizer.step()
|
| 186 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
# Save the model's state dictionary after training
|
| 188 |
torch.save(m.state_dict(), 'model.pt')
|
| 189 |
-
print("Model saved to model.pt")
|
|
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
import torch.nn as nn
|
| 3 |
from torch.nn import functional as F
|
| 4 |
import json
|
| 5 |
import os
|
| 6 |
|
| 7 |
+
# --- Hyperparameters ---
|
| 8 |
+
# These are the settings for our model. You can experiment with these values.
|
| 9 |
+
batch_size = 64 # Increased from 32 to process more sequences in parallel
|
| 10 |
+
block_size = 32 # Increased from 8. This is the maximum context length for predictions. A larger value helps the model see more of the text, leading to better coherence.
|
| 11 |
+
max_iters = 15000 # Increased from 3000 to give the model more training time to learn complex patterns.
|
| 12 |
+
eval_interval = 500 # How often to evaluate the model
|
| 13 |
+
learning_rate = 3e-4 # A slightly lower learning rate is often better for more complex models.
|
| 14 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu' # Use GPU if available
|
| 15 |
+
eval_iters = 200 # Number of iterations for evaluation
|
| 16 |
+
n_embd = 64 # Increased from 32. The dimension of the token embeddings. A larger embedding size allows the model to store more information about each character.
|
| 17 |
+
n_layer = 4 # Increased from 2. The number of LSTM layers. More layers can capture more abstract patterns.
|
| 18 |
+
dropout = 0.0 # Dropout rate for regularization
|
| 19 |
+
|
| 20 |
+
# --- Data Preparation ---
|
| 21 |
+
# This code now expects a 'dataset.jsonl' file to be present in the same directory.
|
| 22 |
file_path = 'dataset.jsonl'
|
| 23 |
corpus = ""
|
| 24 |
try:
|
| 25 |
with open(file_path, 'r') as f:
|
| 26 |
for line in f:
|
| 27 |
data_point = json.loads(line)
|
| 28 |
+
# The corrected line now uses 'header' and 'formal_statement'
|
| 29 |
corpus += data_point['header'] + '\n' + data_point['formal_statement'] + '\n'
|
| 30 |
except FileNotFoundError:
|
| 31 |
+
print(f"Error: The file '{file_path}' was not found. Please create it and run again.")
|
|
|
|
|
|
|
|
|
|
| 32 |
exit()
|
| 33 |
+
except (json.JSONDecodeError, KeyError) as e:
|
| 34 |
+
print(f"Error: There was a problem parsing a line in '{file_path}'. Details: {e}")
|
| 35 |
exit()
|
| 36 |
|
| 37 |
if not corpus:
|
| 38 |
+
print("Error: The corpus is empty. The dataset file might be empty or incorrectly formatted.")
|
| 39 |
exit()
|
| 40 |
|
| 41 |
+
# Create a simple character-level tokenizer.
|
| 42 |
chars = sorted(list(set(corpus)))
|
| 43 |
vocab_size = len(chars)
|
| 44 |
stoi = {ch: i for i, ch in enumerate(chars)}
|
| 45 |
itos = {i: ch for i, ch in enumerate(chars)}
|
|
|
|
| 46 |
encode = lambda s: [stoi[c] for c in s]
|
| 47 |
decode = lambda l: ''.join([itos[i] for i in l])
|
| 48 |
+
|
| 49 |
+
# Convert the entire text into a PyTorch tensor.
|
| 50 |
data = torch.tensor(encode(corpus), dtype=torch.long)
|
| 51 |
+
|
| 52 |
+
# Create a simple train/validation split.
|
| 53 |
n = int(0.9 * len(data))
|
| 54 |
train_data = data[:n]
|
| 55 |
val_data = data[n:]
|
| 56 |
|
| 57 |
+
# --- Helper Functions ---
|
| 58 |
+
# This function gets a random batch of data from either the training or validation set.
|
| 59 |
def get_batch(split):
|
| 60 |
data = train_data if split == 'train' else val_data
|
| 61 |
ix = torch.randint(len(data) - block_size, (batch_size,))
|
|
|
|
| 64 |
x, y = x.to(device), y.to(device)
|
| 65 |
return x, y
|
| 66 |
|
| 67 |
+
# This function is used to estimate the model's loss.
|
| 68 |
@torch.no_grad()
|
| 69 |
def estimate_loss():
|
| 70 |
out = {}
|
| 71 |
+
model.eval() # Set the model to evaluation mode.
|
| 72 |
for split in ['train', 'val']:
|
| 73 |
losses = torch.zeros(eval_iters)
|
| 74 |
for k in range(eval_iters):
|
|
|
|
| 76 |
logits, loss = model(X, Y)
|
| 77 |
losses[k] = loss.item()
|
| 78 |
out[split] = losses.mean()
|
| 79 |
+
model.train() # Set the model back to training mode.
|
| 80 |
return out
|
| 81 |
|
| 82 |
+
# --- The Main LSTM Language Model ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
class LanguageModel(nn.Module):
|
| 84 |
+
def __init__(self):
|
| 85 |
super().__init__()
|
| 86 |
+
# An embedding table to convert tokens to dense vectors.
|
| 87 |
self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
|
| 88 |
+
# An LSTM layer to process the sequence.
|
| 89 |
+
self.lstm = nn.LSTM(n_embd, n_embd, num_layers=n_layer, batch_first=True)
|
| 90 |
+
# A final linear layer to project the LSTM's output to the vocabulary size.
|
| 91 |
self.lm_head = nn.Linear(n_embd, vocab_size)
|
|
|
|
|
|
|
| 92 |
|
| 93 |
def forward(self, idx, targets=None):
|
| 94 |
+
# Get the token embeddings.
|
| 95 |
+
tok_emb = self.token_embedding_table(idx) # (B, T, n_embd)
|
| 96 |
+
# Pass the embeddings through the LSTM layer.
|
| 97 |
+
lstm_out, _ = self.lstm(tok_emb) # lstm_out shape: (B, T, n_embd)
|
| 98 |
+
# Project the LSTM's output to the vocabulary size to get logits.
|
| 99 |
+
logits = self.lm_head(lstm_out) # (B, T, vocab_size)
|
| 100 |
+
|
| 101 |
loss = None
|
| 102 |
if targets is not None:
|
| 103 |
+
# Reshape for cross-entropy loss calculation.
|
| 104 |
B, T, C = logits.shape
|
| 105 |
logits = logits.view(B * T, C)
|
| 106 |
targets = targets.view(B * T)
|
| 107 |
loss = F.cross_entropy(logits, targets)
|
| 108 |
+
|
| 109 |
return logits, loss
|
| 110 |
|
| 111 |
def generate(self, idx, max_new_tokens):
|
| 112 |
+
# The `generate` method for LSTMs needs to handle hidden and cell states.
|
| 113 |
+
h_and_c = None # Start with no hidden state.
|
| 114 |
for _ in range(max_new_tokens):
|
| 115 |
+
# We only need the last token to predict the next one.
|
| 116 |
+
idx_cond = idx[:, -1].unsqueeze(1) # (B, 1)
|
| 117 |
+
tok_emb = self.token_embedding_table(idx_cond) # (B, 1, n_embd)
|
| 118 |
+
# Pass the single token through the LSTM, along with the previous hidden state.
|
| 119 |
+
lstm_out, h_and_c = self.lstm(tok_emb, h_and_c)
|
| 120 |
+
# Focus on the output of the last time step.
|
| 121 |
+
logits = self.lm_head(lstm_out[:, -1, :]) # (B, vocab_size)
|
| 122 |
+
# Apply softmax to get probabilities.
|
| 123 |
probs = F.softmax(logits, dim=-1)
|
| 124 |
+
# Sample from the distribution.
|
| 125 |
idx_next = torch.multinomial(probs, num_samples=1)
|
| 126 |
+
# Append the new token to the sequence.
|
| 127 |
idx = torch.cat((idx, idx_next), dim=1)
|
| 128 |
return idx
|
| 129 |
|
|
|
|
| 130 |
# --- Training and Generation ---
|
| 131 |
+
model = LanguageModel()
|
| 132 |
m = model.to(device)
|
| 133 |
+
|
| 134 |
+
# Create a PyTorch optimizer.
|
| 135 |
optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
|
| 136 |
|
| 137 |
+
# Main training loop.
|
| 138 |
for iter in range(max_iters):
|
| 139 |
+
# Every few iterations, evaluate the loss on both splits.
|
| 140 |
if iter % eval_interval == 0:
|
| 141 |
losses = estimate_loss()
|
| 142 |
print(f"step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
|
| 143 |
+
|
| 144 |
+
# Sample a batch of data.
|
| 145 |
xb, yb = get_batch('train')
|
| 146 |
+
|
| 147 |
+
# Forward pass: compute loss.
|
| 148 |
logits, loss = model(xb, yb)
|
| 149 |
+
# Backward pass: compute gradients.
|
| 150 |
optimizer.zero_grad(set_to_none=True)
|
| 151 |
loss.backward()
|
| 152 |
+
# Update the model parameters.
|
| 153 |
optimizer.step()
|
| 154 |
|
| 155 |
+
# --- Generate new text from the trained model ---
|
| 156 |
+
context = torch.zeros((1, 1), dtype=torch.long, device=device)
|
| 157 |
+
generated_text_indices = m.generate(context, max_new_tokens=20)
|
| 158 |
+
print("\nGenerated text:")
|
| 159 |
+
print(decode(generated_text_indices[0].tolist()))
|
| 160 |
+
|
| 161 |
# Save the model's state dictionary after training
|
| 162 |
torch.save(m.state_dict(), 'model.pt')
|
| 163 |
+
print("Model saved to model.pt")
|
| 164 |
+
|