Spaces:
Runtime error
Runtime error
File size: 2,309 Bytes
f371534 2a8d198 f371534 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# Import libraries
import os
os.system('pip install transformers torch datasets')
from transformers import GPT2LMHeadModel, GPT2Tokenizer, AdamW
from torch.utils.data import Dataset, DataLoader
from datasets import load_dataset
from torch.nn.utils.rnn import pad_sequence
import torch
dataset = load_dataset("text", data_files={"train": "BotDataset.txt"})
# Tokenization
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
class MyDataset(Dataset):
def __init__(self, texts, max_length=512):
self.texts = texts
self.max_length = max_length
def __len__(self):
return len(self.texts)
def __getitem__(self, idx):
# Tokenize the text without squeezing the tensor and convert to Long tensor
input_ids = tokenizer.encode(self.texts[idx], return_tensors='pt').long()
# Optionally truncate or pad the sequence to a maximum length
input_ids = input_ids[:, :self.max_length]
# If needed, pad the sequence to the max_length using torch.nn.functional.pad
input_ids = torch.nn.functional.pad(input_ids, (0, self.max_length - input_ids.size(1)), 'constant', 0)
return {'input_ids': input_ids}
# Create DataLoader without collate_fn
my_dataset = MyDataset(dataset['train']['text'])
dataloader = DataLoader(my_dataset, batch_size=4, shuffle=True)
# Load pre-trained model
model = GPT2LMHeadModel.from_pretrained("gpt2")
# Move model to GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
# Define optimizer
optimizer = AdamW(model.parameters(), lr=5e-5)
# Fine-tuning Loop
for epoch in range(4):
total_loss = 0.0
for i, batch in enumerate(dataloader):
batch = {k: v.to(device) for k, v in batch.items()}
outputs = model(**batch, labels=batch['input_ids'])
loss = outputs.loss
loss.backward()
optimizer.step()
optimizer.zero_grad()
total_loss += loss.item()
if (i + 1) % 100 == 0: # Print loss every 100 batches
average_loss = total_loss / 100
print(f"Epoch: {epoch + 1}, Batch: {i + 1}, Average Loss: {average_loss:.4f}")
total_loss = 0.0
print("Training complete!")
model.save_pretrained('/gpt2_better')
tokenizer.save_pretrained('/gpt2_better/tokenizer') |