Delete continue.py
Browse files- continue.py +0 -117
continue.py
DELETED
|
@@ -1,117 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import torch.nn as nn
|
| 3 |
-
import torch.optim as optim
|
| 4 |
-
import pickle
|
| 5 |
-
from torch.utils.data import Dataset, DataLoader
|
| 6 |
-
from safetensors.torch import load_file, save_file
|
| 7 |
-
import logging
|
| 8 |
-
import json
|
| 9 |
-
|
| 10 |
-
# Set up logging
|
| 11 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 12 |
-
|
| 13 |
-
# Hyperparameters
|
| 14 |
-
sequence_length = 16
|
| 15 |
-
batch_size = 32
|
| 16 |
-
num_epochs = 1 # Continue training for 1 more epoch
|
| 17 |
-
learning_rate = 0.00001
|
| 18 |
-
embedding_dim = 256
|
| 19 |
-
hidden_dim = 512
|
| 20 |
-
num_layers = 2
|
| 21 |
-
|
| 22 |
-
# LSTM Model
|
| 23 |
-
class LSTMModel(nn.Module):
|
| 24 |
-
def __init__(self, vocab_size, embedding_dim, hidden_dim, num_layers):
|
| 25 |
-
super(LSTMModel, self).__init__()
|
| 26 |
-
self.embedding = nn.Embedding(vocab_size, embedding_dim)
|
| 27 |
-
self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers, batch_first=True)
|
| 28 |
-
self.fc = nn.Linear(hidden_dim, vocab_size)
|
| 29 |
-
|
| 30 |
-
def forward(self, x):
|
| 31 |
-
embeds = self.embedding(x)
|
| 32 |
-
lstm_out, _ = self.lstm(embeds)
|
| 33 |
-
logits = self.fc(lstm_out[:, -1, :])
|
| 34 |
-
return logits
|
| 35 |
-
|
| 36 |
-
# Load the model and vocabulary
|
| 37 |
-
logging.info('Loading the model and vocabulary...')
|
| 38 |
-
model_state_dict = load_file('lstm_model.safetensors')
|
| 39 |
-
with open('word2idx.pkl', 'rb') as f:
|
| 40 |
-
word2idx = pickle.load(f)
|
| 41 |
-
with open('idx2word.pkl', 'rb') as f:
|
| 42 |
-
idx2word = pickle.load(f)
|
| 43 |
-
|
| 44 |
-
vocab_size = len(word2idx)
|
| 45 |
-
model = LSTMModel(vocab_size, embedding_dim, hidden_dim, num_layers)
|
| 46 |
-
model.load_state_dict(model_state_dict)
|
| 47 |
-
model.train()
|
| 48 |
-
|
| 49 |
-
logging.info('Model and vocabulary loaded successfully.')
|
| 50 |
-
|
| 51 |
-
# Output the total number of parameters
|
| 52 |
-
total_params = sum(p.numel() for p in model.parameters())
|
| 53 |
-
logging.info(f'Total number of parameters: {total_params}')
|
| 54 |
-
|
| 55 |
-
# Read the text file
|
| 56 |
-
logging.info('Reading the text file...')
|
| 57 |
-
with open('text.txt', 'r') as file:
|
| 58 |
-
text = file.read()
|
| 59 |
-
logging.info('Text file read successfully.')
|
| 60 |
-
|
| 61 |
-
# Preprocess the text
|
| 62 |
-
logging.info('Preprocessing the text...')
|
| 63 |
-
words = json.loads(text)
|
| 64 |
-
sequences = []
|
| 65 |
-
for i in range(len(words) - sequence_length):
|
| 66 |
-
seq = words[i:i + sequence_length]
|
| 67 |
-
label = words[i + sequence_length]
|
| 68 |
-
sequences.append((seq, label))
|
| 69 |
-
|
| 70 |
-
logging.info(f'Number of sequences: {len(sequences)}')
|
| 71 |
-
|
| 72 |
-
# Dataset and DataLoader
|
| 73 |
-
class TextDataset(Dataset):
|
| 74 |
-
def __init__(self, sequences, word2idx):
|
| 75 |
-
self.sequences = sequences
|
| 76 |
-
self.word2idx = word2idx
|
| 77 |
-
|
| 78 |
-
def __len__(self):
|
| 79 |
-
return len(self.sequences)
|
| 80 |
-
|
| 81 |
-
def __getitem__(self, idx):
|
| 82 |
-
seq, label = self.sequences[idx]
|
| 83 |
-
seq_idx = [self.word2idx.get(word, self.word2idx['<UNK>']) for word in seq]
|
| 84 |
-
label_idx = self.word2idx.get(label, self.word2idx['<UNK>'])
|
| 85 |
-
return torch.tensor(seq_idx, dtype=torch.long), torch.tensor(label_idx, dtype=torch.long)
|
| 86 |
-
|
| 87 |
-
logging.info('Creating dataset and dataloader...')
|
| 88 |
-
dataset = TextDataset(sequences, word2idx)
|
| 89 |
-
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
|
| 90 |
-
|
| 91 |
-
# Continue training
|
| 92 |
-
criterion = nn.CrossEntropyLoss()
|
| 93 |
-
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
|
| 94 |
-
|
| 95 |
-
logging.info('Starting continued training...')
|
| 96 |
-
for epoch in range(num_epochs):
|
| 97 |
-
for batch_idx, batch in enumerate(dataloader):
|
| 98 |
-
inputs, targets = batch
|
| 99 |
-
outputs = model(inputs)
|
| 100 |
-
loss = criterion(outputs, targets)
|
| 101 |
-
|
| 102 |
-
optimizer.zero_grad()
|
| 103 |
-
loss.backward()
|
| 104 |
-
optimizer.step()
|
| 105 |
-
|
| 106 |
-
if batch_idx % 10 == 0:
|
| 107 |
-
logging.info(f'Epoch [{epoch+1}/{num_epochs}], Batch [{batch_idx}/{len(dataloader)}], Loss: {loss.item():.4f}')
|
| 108 |
-
|
| 109 |
-
# Save the updated model
|
| 110 |
-
logging.info('Saving the updated model...')
|
| 111 |
-
save_file(model.state_dict(), 'lstm_model.safetensors')
|
| 112 |
-
with open('word2idx.pkl', 'wb') as f:
|
| 113 |
-
pickle.dump(word2idx, f)
|
| 114 |
-
with open('idx2word.pkl', 'wb') as f:
|
| 115 |
-
pickle.dump(idx2word, f)
|
| 116 |
-
|
| 117 |
-
logging.info('Updated model and vocabulary saved successfully.')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|