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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Training script for ML Pipeline on Kaggle with HF Spaces storage.
|
| 3 |
+
|
| 4 |
+
This script:
|
| 5 |
+
1. Downloads training data from Hugging Face Datasets
|
| 6 |
+
2. Trains a model using GPU acceleration
|
| 7 |
+
3. Pushes the trained model to Hugging Face Model Hub
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
from config import MODEL_REPO_ID, DATASET_REPO_ID, validate_config
|
| 12 |
+
|
| 13 |
+
# Validate configuration before proceeding
|
| 14 |
+
validate_config()
|
| 15 |
+
|
| 16 |
+
from datasets import load_dataset
|
| 17 |
+
from transformers import (
|
| 18 |
+
AutoTokenizer,
|
| 19 |
+
AutoModelForSequenceClassification,
|
| 20 |
+
TrainingArguments,
|
| 21 |
+
Trainer,
|
| 22 |
+
)
|
| 23 |
+
from sklearn.metrics import accuracy_score, f1_score
|
| 24 |
+
import torch
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def load_training_data():
|
| 28 |
+
"""Load dataset from Hugging Face."""
|
| 29 |
+
print(f"Loading dataset...")
|
| 30 |
+
|
| 31 |
+
# Option 1: Load from HF Datasets Hub (public datasets)
|
| 32 |
+
# Using Spotify Songs dataset: https://huggingface.co/datasets/gem1925/spotify_songs
|
| 33 |
+
try:
|
| 34 |
+
print("Loading Spotify songs dataset...")
|
| 35 |
+
dataset = load_dataset("gem1925/spotify_songs", split="train")
|
| 36 |
+
print(f"β Loaded Spotify dataset: {len(dataset)} samples")
|
| 37 |
+
|
| 38 |
+
# Convert to text classification format
|
| 39 |
+
from datasets import Dataset
|
| 40 |
+
# Use song name + artist as text, energy level as label
|
| 41 |
+
texts = [f"{row['song_name']} by {row['artist']}" for row in dataset]
|
| 42 |
+
labels = [1 if row['energy'] > 0.5 else 0 for row in dataset]
|
| 43 |
+
|
| 44 |
+
# Create new dataset with text/label format
|
| 45 |
+
new_dataset = Dataset.from_dict({"text": texts, "label": labels})
|
| 46 |
+
new_dataset = new_dataset.train_test_split(test_size=0.2)
|
| 47 |
+
return new_dataset
|
| 48 |
+
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print(f"Could not load Spotify dataset: {e}")
|
| 51 |
+
print("Falling back to IMDB reviews dataset...")
|
| 52 |
+
|
| 53 |
+
# Fallback to IMDB
|
| 54 |
+
try:
|
| 55 |
+
dataset = load_dataset("imdb")
|
| 56 |
+
print(f"β Loaded IMDB dataset")
|
| 57 |
+
return dataset
|
| 58 |
+
except Exception as e2:
|
| 59 |
+
print(f"Could not load IMDB: {e2}")
|
| 60 |
+
print("Using sample dataset for demonstration...")
|
| 61 |
+
from datasets import Dataset
|
| 62 |
+
sample_data = {
|
| 63 |
+
"text": [
|
| 64 |
+
"I love this product! It works great.",
|
| 65 |
+
"Terrible experience, would not recommend.",
|
| 66 |
+
"Amazing quality and fast shipping.",
|
| 67 |
+
"Waste of money, broke after one day.",
|
| 68 |
+
] * 100,
|
| 69 |
+
"label": [1, 0, 1, 0] * 100,
|
| 70 |
+
}
|
| 71 |
+
dataset = Dataset.from_dict(sample_data).train_test_split(test_size=0.2)
|
| 72 |
+
return dataset
|
| 73 |
+
|
| 74 |
+
return dataset
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def compute_metrics(eval_pred):
|
| 78 |
+
"""Compute evaluation metrics."""
|
| 79 |
+
predictions, labels = eval_pred
|
| 80 |
+
predictions = predictions.argmax(axis=1)
|
| 81 |
+
return {
|
| 82 |
+
"accuracy": accuracy_score(labels, predictions),
|
| 83 |
+
"f1": f1_score(labels, predictions),
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def main():
|
| 88 |
+
"""Main training function."""
|
| 89 |
+
print("=" * 50)
|
| 90 |
+
print("π ML Training Pipeline - Starting")
|
| 91 |
+
print("=" * 50)
|
| 92 |
+
|
| 93 |
+
# Check GPU availability
|
| 94 |
+
if torch.cuda.is_available():
|
| 95 |
+
print(f"β GPU Available: {torch.cuda.get_device_name(0)}")
|
| 96 |
+
else:
|
| 97 |
+
print("β No GPU detected, training on CPU")
|
| 98 |
+
|
| 99 |
+
# Load data
|
| 100 |
+
print("\nπ Loading training data...")
|
| 101 |
+
dataset = load_training_data()
|
| 102 |
+
print(f"β Dataset loaded: {len(dataset['train'])} training samples")
|
| 103 |
+
|
| 104 |
+
# Load tokenizer and model
|
| 105 |
+
print("\nπ€ Loading model and tokenizer...")
|
| 106 |
+
model_name = "distilbert-base-uncased"
|
| 107 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 108 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 109 |
+
model_name,
|
| 110 |
+
num_labels=2
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# Tokenize data
|
| 114 |
+
print("\nπ Tokenizing data...")
|
| 115 |
+
|
| 116 |
+
def tokenize(batch):
|
| 117 |
+
return tokenizer(
|
| 118 |
+
batch["text"],
|
| 119 |
+
padding="max_length",
|
| 120 |
+
truncation=True,
|
| 121 |
+
max_length=128
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
tokenized_dataset = dataset.map(tokenize, batched=True)
|
| 125 |
+
tokenized_dataset = tokenized_dataset.rename_column("label", "labels")
|
| 126 |
+
tokenized_dataset.set_format(
|
| 127 |
+
type="torch",
|
| 128 |
+
columns=["input_ids", "attention_mask", "labels"]
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Training arguments
|
| 132 |
+
training_args = TrainingArguments(
|
| 133 |
+
output_dir="./results",
|
| 134 |
+
num_train_epochs=3,
|
| 135 |
+
per_device_train_batch_size=16,
|
| 136 |
+
per_device_eval_batch_size=32,
|
| 137 |
+
warmup_steps=500,
|
| 138 |
+
weight_decay=0.01,
|
| 139 |
+
logging_dir="./logs",
|
| 140 |
+
logging_steps=100,
|
| 141 |
+
eval_strategy="epoch",
|
| 142 |
+
save_strategy="epoch",
|
| 143 |
+
load_best_model_at_end=True,
|
| 144 |
+
push_to_hub=True,
|
| 145 |
+
hub_model_id=MODEL_REPO_ID,
|
| 146 |
+
hub_token=os.getenv("HF_TOKEN"),
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# Initialize trainer
|
| 150 |
+
trainer = Trainer(
|
| 151 |
+
model=model,
|
| 152 |
+
args=training_args,
|
| 153 |
+
train_dataset=tokenized_dataset["train"],
|
| 154 |
+
eval_dataset=tokenized_dataset["test"],
|
| 155 |
+
compute_metrics=compute_metrics,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
# Train
|
| 159 |
+
print("\nπ₯ Starting training...")
|
| 160 |
+
trainer.train()
|
| 161 |
+
|
| 162 |
+
# Evaluate
|
| 163 |
+
print("\nπ Evaluating model...")
|
| 164 |
+
results = trainer.evaluate()
|
| 165 |
+
print(f"β Evaluation results: {results}")
|
| 166 |
+
|
| 167 |
+
# Push to HF Hub
|
| 168 |
+
print(f"\nπΎ Pushing model to Hugging Face: {MODEL_REPO_ID}")
|
| 169 |
+
trainer.push_to_hub()
|
| 170 |
+
print(f"β Model successfully pushed to: https://huggingface.co/{MODEL_REPO_ID}")
|
| 171 |
+
|
| 172 |
+
print("\n" + "=" * 50)
|
| 173 |
+
print("β
Training Complete!")
|
| 174 |
+
print("=" * 50)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
if __name__ == "__main__":
|
| 178 |
+
main()
|