o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
write a finetune script for https://qwenlm.github.io/blog/qwen2-math/
- User
write a finetune script for https://qwenlm.github.io/blog/qwen2-math/
- Assistant
write a finetune script for https://qwenlm.github.io/blog/qwen2-math/
Certainly! Below is a sample fine-tuning script for the Qwen-2 model, specifically tailored for mathematical problems. This script utilizes the Hugging Face Transformers library to fine-tune the model on your custom dataset of math problems and solutions.
Prerequisites:
Install the necessary libraries:
pip install transformers datasets accelerate
Ensure you have access to a GPU with sufficient memory since Qwen-2 is a large model.
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer, TrainingArguments
from datasets import load_dataset, Dataset
from datasets.dataset_dict import DatasetDict
# Check if GPU is available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# Load the tokenizer and model with remote code trust (necessary for custom architectures)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-14B", trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
"Qwen/Qwen-14B",
device_map="auto", # Automatically maps layers to devices
torch_dtype=torch.float16, # Use FP16 for faster computation and reduced memory
trust_remote_code=True
)
# Prepare your custom dataset
# Replace this part with the code to load your dataset
# For illustration, let's create a simple dataset
# Sample data: list of dictionaries with 'prompt' and 'answer'
data = [
{"prompt": "Solve for x: 2x + 3 = 7.", "answer": "x = 2"},
{"prompt": "Integrate the function f(x) = x^2.", "answer": "∫x^2 dx = x^3/3 + C"},
# Add more data here...
]
# Convert the list to a Hugging Face Dataset
dataset = Dataset.from_list(data)
# Define a prompt format (you can customize this)
def format_example(example):
return f"Problem: {example['prompt']}\nAnswer: {example['answer']}"
# Apply the formatting
dataset = dataset.map(lambda x: {"text": format_example(x)})
# Split the dataset into training and validation sets
split_dataset = dataset.train_test_split(test_size=0.1)
train_dataset = split_dataset["train"]
eval_dataset = split_dataset["test"]
# Tokenization function
def tokenize_function(examples):
return tokenizer(
examples["text"],
padding="max_length",
truncation=True,
max_length=512, # Adjust based on your needs and GPU memory
return_tensors="pt"
)
# Tokenize datasets
tokenized_train = train_dataset.map(tokenize_function, batched=True, remove_columns=["prompt", "answer", "text"])
tokenized_eval = eval_dataset.map(tokenize_function, batched=True, remove_columns=["prompt", "answer", "text"])
# Set format for PyTorch tensors
tokenized_train.set_format(type="torch")
tokenized_eval.set_format(type="torch")
# Data collator for language modeling
from transformers import DataCollatorForLanguageModeling
data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
# Define training arguments
training_args = TrainingArguments(
output_dir="./qwen2-math-finetuned",
overwrite_output_dir=True,
num_train_epochs=3,
per_device_train_batch_size=1, # Adjust based on GPU memory
per_device_eval_batch_size=1,
gradient_accumulation_steps=8, # Adjust to simulate larger batch size
evaluation_strategy="steps",
eval_steps=500,
save_steps=500,
logging_steps=50,
learning_rate=5e-5,
warmup_steps=100,
fp16=True, # Enable mixed precision
save_total_limit=2,
dataloader_num_workers=4, # Adjust based on your system
report_to="none", # Disable online logging
)
# Initialize the Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_train,
eval_dataset=tokenized_eval,
data_collator=data_collator,
)
# Start training
trainer.train()
# Save the fine-tuned model
trainer.save_model("./qwen2-math-finetuned")
tokenizer.save_pretrained("./qwen2-math-finetuned")
Explanation:
Data Preparation:
data list with your actual dataset containing math problems and solutions.format_example function formats each example into a prompt-answer pair, which can be customized.Tokenization:
tokenize_function tokenizes the text data, with padding and truncation to a maximum length (e.g., 512 tokens).max_length according to the complexity of your data and GPU memory constraints.Training Arguments:
per_device_train_batch_size and gradient_accumulation_steps are set to manage GPU memory usage.fp16=True for faster training and reduced memory usage.Training:
Trainer class handles the training loop, evaluation, and saving of checkpoints.Saving the Model:
Notes:
GPU Requirements:
max_length.per_device_train_batch_size or increasing gradient_accumulation_steps.Data Quality:
Evaluation Metrics:
Customization:
References:
Disclaimer:
Let me know if you need further assistance or modifications to the script!
Not yet included in a published release.