|
|
|
from transformers import T5ForConditionalGeneration, T5Tokenizer, Trainer, TrainingArguments
|
|
from datasets import load_dataset
|
|
from huggingface_hub import login
|
|
import pandas as pd
|
|
import os
|
|
import torch
|
|
import matplotlib.pyplot as plt
|
|
|
|
|
|
|
|
hf_token = "YOUR_HUGGING_FACE_TOKEN"
|
|
if not hf_token or hf_token == "YOUR_HUGGING_FACE_TOKEN":
|
|
raise ValueError("Please replace 'YOUR_HUGGING_FACE_TOKEN' in the code with your actual Hugging Face token")
|
|
login(token=hf_token)
|
|
print("Logged in to Hugging Face successfully")
|
|
|
|
|
|
|
|
dataset_name = "dataset.csv"
|
|
dataset_path = dataset_name
|
|
if dataset_name.endswith('.csv'):
|
|
|
|
print(f"Converting {dataset_name} to JSON format...")
|
|
df = pd.read_csv(dataset_path)
|
|
df.to_json('dataset.json', orient='records', lines=True)
|
|
dataset_path = 'dataset.json'
|
|
|
|
|
|
print(f"Loading dataset from {dataset_path}...")
|
|
dataset = load_dataset('json', data_files=dataset_path)
|
|
|
|
|
|
|
|
print("Splitting dataset into training and validation sets...")
|
|
train_test_split = dataset['train'].train_test_split(test_size=0.15, seed=42)
|
|
train_dataset = train_test_split['train']
|
|
eval_dataset = train_test_split['test']
|
|
|
|
|
|
print("Downloading T5-small model and tokenizer...")
|
|
tokenizer = T5Tokenizer.from_pretrained('t5-small')
|
|
model = T5ForConditionalGeneration.from_pretrained('t5-small')
|
|
|
|
model.save_pretrained('./t5_small_weights')
|
|
tokenizer.save_pretrained('./t5_small_weights')
|
|
print("Model and tokenizer saved to './t5_small_weights'")
|
|
|
|
|
|
|
|
def preprocess_data(examples):
|
|
|
|
inputs = ["question: " + q.strip() for q in examples['input']]
|
|
targets = [r.strip() for r in examples['response']]
|
|
|
|
model_inputs = tokenizer(inputs, max_length=128, truncation=True, padding='max_length')
|
|
|
|
labels = tokenizer(targets, max_length=64, truncation=True, padding='max_length')
|
|
|
|
model_inputs['labels'] = [
|
|
[(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels['input_ids']
|
|
]
|
|
return model_inputs
|
|
|
|
|
|
print("Preprocessing datasets...")
|
|
processed_train_dataset = train_dataset.map(preprocess_data, batched=True, remove_columns=['input', 'response'])
|
|
processed_eval_dataset = eval_dataset.map(preprocess_data, batched=True, remove_columns=['input', 'response'])
|
|
|
|
|
|
|
|
training_args = TrainingArguments(
|
|
output_dir='./results',
|
|
num_train_epochs=10,
|
|
per_device_train_batch_size=2,
|
|
gradient_accumulation_steps=2,
|
|
learning_rate=3e-4,
|
|
save_steps=500,
|
|
save_total_limit=2,
|
|
logging_steps=50,
|
|
eval_strategy="steps",
|
|
eval_steps=100,
|
|
load_best_model_at_end=True,
|
|
metric_for_best_model="eval_loss",
|
|
greater_is_better=False,
|
|
gradient_checkpointing=True,
|
|
max_grad_norm=1.0,
|
|
)
|
|
|
|
|
|
|
|
print("Initializing Trainer...")
|
|
trainer = Trainer(
|
|
model=model,
|
|
args=training_args,
|
|
train_dataset=processed_train_dataset,
|
|
eval_dataset=processed_eval_dataset,
|
|
)
|
|
|
|
|
|
print("Starting training...")
|
|
trainer.train()
|
|
print("Training finished.")
|
|
|
|
|
|
|
|
print("Generating training and validation loss plot...")
|
|
logs = trainer.state.log_history
|
|
steps = [log['step'] for log in logs if 'loss' in log or 'eval_loss' in log]
|
|
train_loss = [log['loss'] for log in logs if 'loss' in log]
|
|
eval_loss = [log['eval_loss'] for log in logs if 'eval_loss' in log]
|
|
plt.figure(figsize=(10, 5))
|
|
if train_loss:
|
|
plt.plot(steps[:len(train_loss)], train_loss, label='Training Loss')
|
|
if eval_loss:
|
|
plt.plot(steps[:len(eval_loss)], eval_loss, label='Validation Loss')
|
|
plt.xlabel('Step')
|
|
plt.ylabel('Loss')
|
|
plt.title('Training and Validation Loss Over Time')
|
|
plt.legend()
|
|
plt.grid(True)
|
|
plt.savefig('training_metrics.png')
|
|
plt.show()
|
|
|
|
|
|
final_model_save_path = './finetuned_t5'
|
|
model.save_pretrained(final_model_save_path)
|
|
tokenizer.save_pretrained(final_model_save_path)
|
|
print(f"Model fine-tuned and saved to '{final_model_save_path}'")
|
|
print("Training metrics plot saved as 'training_metrics.png'") |