write a code fine tune the gpt-2 model with very small custom data
- User
write a code fine tune the gpt-2 model with very small custom data
- Assistant
write a code fine tune the gpt-2 model with very small custom data
Certainly! Fine-tuning GPT-2 on a small custom dataset is entirely feasible using the Hugging Face Transformers library. Below is a step-by-step guide to help you accomplish this. We'll cover:
First, ensure you have the required libraries installed. You can install them using pip:
pip install transformers datasets torch
Assuming you have a small custom dataset, it's best to structure it as a plain text file. For this example, let's say your data is in train.txt.
Example train.txt:
Once upon a time in a land far, far away, there was a kingdom where...
The sun set over the mountains, casting a golden hue across the valley...
In the bustling city, the streets were alive with the sounds of chatter and music...
Note: Ensure your text data is cleaned and well-formatted. Each example can be a paragraph or sentence separated by newlines.
Below is a Python script that demonstrates how to fine-tune GPT-2 using the Transformers library.
import os
from transformers import GPT2LMHeadModel, GPT2Tokenizer, TextDataset, DataCollatorForLanguageModeling, Trainer, TrainingArguments
# Define the paths to your data
train_file_path = "train.txt" # Path to your training data
# Load the pre-trained GPT-2 tokenizer and model
model_name = 'gpt2' # You can choose 'gpt2-medium', 'gpt2-large', etc., depending on resources
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
model = GPT2LMHeadModel.from_pretrained(model_name)
# Ensure the tokenizer has a padding token
if tokenizer.pad_token is None:
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
model.resize_token_embeddings(len(tokenizer))
# Create a dataset
def load_dataset(file_path, tokenizer, block_size=128):
return TextDataset(
tokenizer=tokenizer,
file_path=file_path,
block_size=block_size
)
train_dataset = load_dataset(train_file_path, tokenizer)
# Create a data collator
data_collator = DataCollatorForLanguageModeling(
tokenizer=tokenizer,
mlm=False, # GPT-2 is not trained with masked language modeling
)
# Define training arguments
training_args = TrainingArguments(
output_dir="./gpt2-finetuned",
overwrite_output_dir=True,
num_train_epochs=3, # Since the dataset is small, you might need more epochs
per_device_train_batch_size=2,
save_steps=500,
save_total_limit=2,
prediction_loss_only=True,
logging_steps=100,
)
# Initialize the Trainer
trainer = Trainer(
model=model,
args=training_args,
data_collator=data_collator,
train_dataset=train_dataset,
)
# Fine-tune the model
trainer.train()
# Save the fine-tuned model and tokenizer
trainer.save_model("./gpt2-finetuned")
tokenizer.save_pretrained("./gpt2-finetuned")
Explanation of the Script:
Loading the Model and Tokenizer:
Preparing the Dataset:
TextDataset utility reads the text file and tokenizes it, breaking it into blocks of block_size tokens.Data Collator:
mlm=False.Training Arguments:
output_dir: Directory to save the fine-tuned model.num_train_epochs: Number of training epochs. With smaller datasets, more epochs can help, but watch for overfitting.per_device_train_batch_size: Batch size per device (GPU/CPU).save_steps and save_total_limit: Control how often and how many checkpoints to save.logging_steps: How often to log training metrics.Trainer:
Trainer handles the training loop, evaluation, and more.Training and Saving:
trainer.train() starts the fine-tuning process.After fine-tuning, you can test your model to see how well it performs on generating text based on your custom data.
from transformers import GPT2LMHeadModel, GPT2Tokenizer
# Load the fine-tuned model and tokenizer
model = GPT2LMHeadModel.from_pretrained("./gpt2-finetuned")
tokenizer = GPT2Tokenizer.from_pretrained("./gpt2-finetuned")
# Function to generate text
def generate_text(prompt, max_length=100):
inputs = tokenizer.encode(prompt, return_tensors='pt')
outputs = model.generate(
inputs,
max_length=max_length,
num_return_sequences=1,
no_repeat_ngram_size=2,
early_stopping=True
)
text = tokenizer.decode(outputs[0], skip_special_tokens=True)
return text
# Example prompt
prompt = "Once upon a time"
generated_text = generate_text(prompt)
print(generated_text)
Output:
Once upon a time in a land far, far away, there was a kingdom where...
Tips for Better Fine-Tuning with Small Datasets:
Data Quality Over Quantity:
Avoid Overfitting:
Use Validation Sets:
Adjust Learning Rates:
Experiment with Epochs and Batch Sizes:
datasets Library for More FlexibilityIf your dataset requires more preprocessing or is in a different format (like CSV, JSON, etc.), you can utilize the Hugging Face datasets library for greater flexibility.
from datasets import load_dataset
from transformers import DataCollatorForLanguageModeling
# Suppose your data is in a CSV with a 'text' column
dataset = load_dataset('csv', data_files={'train': 'train.csv'}, split='train')
# Tokenize the data
def tokenize_function(examples):
return tokenizer(examples['text'], padding='max_length', truncation=True, max_length=128)
tokenized_datasets = dataset.map(tokenize_function, batched=True)
# Set the format for PyTorch
tokenized_datasets.set_format('torch', columns=['input_ids', 'attention_mask'])
# Update Trainer with the new dataset
trainer = Trainer(
model=model,
args=training_args,
data_collator=DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False),
train_dataset=tokenized_datasets,
)
# Train
trainer.train()
This approach provides more control, especially when dealing with diverse data formats or needing advanced preprocessing.
Fine-tuning GPT-2 on a small custom dataset is straightforward with the Hugging Face Transformers library. By following the steps above, you can adapt GPT-2 to better suit your specific needs, whether it's generating specialized text, following certain styles, or understanding domain-specific language. Always remember to monitor for overfitting and adjust your training parameters accordingly to achieve the best results.
Not yet included in a published release.