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|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Trackmodel - Fine-Tuning Script
|
| 3 |
+
This script downloads a pre-trained model and fine-tunes it on IMDb dataset
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
from transformers import (
|
| 8 |
+
AutoTokenizer,
|
| 9 |
+
AutoModelForSequenceClassification,
|
| 10 |
+
Trainer,
|
| 11 |
+
TrainingArguments,
|
| 12 |
+
)
|
| 13 |
+
from datasets import load_dataset
|
| 14 |
+
from huggingface_hub import login
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
def setup_training():
|
| 18 |
+
"""Setup and run the fine-tuning process"""
|
| 19 |
+
|
| 20 |
+
print("=" * 60)
|
| 21 |
+
print("π TRACKMODEL - FINE-TUNING STARTED")
|
| 22 |
+
print("=" * 60)
|
| 23 |
+
|
| 24 |
+
# 1. Load Dataset
|
| 25 |
+
print("\nπ Step 1: Loading dataset...")
|
| 26 |
+
dataset = load_dataset("imdb")
|
| 27 |
+
print(f"β
Loaded {len(dataset['train'])} training samples")
|
| 28 |
+
print(f"β
Loaded {len(dataset['test'])} test samples")
|
| 29 |
+
|
| 30 |
+
# Use a subset for faster training (remove .select() for full training)
|
| 31 |
+
print("\nβ‘ Using subset for faster training (500 train, 100 test)")
|
| 32 |
+
train_subset = dataset["train"].select(range(500))
|
| 33 |
+
test_subset = dataset["test"].select(range(100))
|
| 34 |
+
|
| 35 |
+
# 2. Load Model and Tokenizer
|
| 36 |
+
print("\nπ€ Step 2: Loading pre-trained model...")
|
| 37 |
+
model_name = "distilbert-base-uncased"
|
| 38 |
+
print(f"π¦ Model: {model_name}")
|
| 39 |
+
|
| 40 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 41 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 42 |
+
model_name,
|
| 43 |
+
num_labels=2 # Binary classification: positive/negative
|
| 44 |
+
)
|
| 45 |
+
print("β
Model and tokenizer loaded successfully")
|
| 46 |
+
|
| 47 |
+
# 3. Tokenize the dataset
|
| 48 |
+
print("\nβοΈ Step 3: Tokenizing dataset...")
|
| 49 |
+
|
| 50 |
+
def tokenize_function(examples):
|
| 51 |
+
return tokenizer(
|
| 52 |
+
examples["text"],
|
| 53 |
+
padding="max_length",
|
| 54 |
+
truncation=True,
|
| 55 |
+
max_length=256, # Shorter for faster training
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
tokenized_train = train_subset.map(tokenize_function, batched=True)
|
| 59 |
+
tokenized_test = test_subset.map(tokenize_function, batched=True)
|
| 60 |
+
|
| 61 |
+
# Format for PyTorch
|
| 62 |
+
tokenized_train = tokenized_train.remove_columns(["text"])
|
| 63 |
+
tokenized_test = tokenized_test.remove_columns(["text"])
|
| 64 |
+
tokenized_train = tokenized_train.rename_column("label", "labels")
|
| 65 |
+
tokenized_test = tokenized_test.rename_column("label", "labels")
|
| 66 |
+
tokenized_train.set_format("torch")
|
| 67 |
+
tokenized_test.set_format("torch")
|
| 68 |
+
print("β
Tokenization complete")
|
| 69 |
+
|
| 70 |
+
# 4. Training Arguments
|
| 71 |
+
print("\nβοΈ Step 4: Configuring training parameters...")
|
| 72 |
+
|
| 73 |
+
training_args = TrainingArguments(
|
| 74 |
+
output_dir="./results",
|
| 75 |
+
num_train_epochs=2, # 2 epochs for quick demonstration
|
| 76 |
+
per_device_train_batch_size=8,
|
| 77 |
+
per_device_eval_batch_size=8,
|
| 78 |
+
evaluation_strategy="epoch",
|
| 79 |
+
save_strategy="epoch",
|
| 80 |
+
logging_dir="./logs",
|
| 81 |
+
logging_steps=10,
|
| 82 |
+
load_best_model_at_end=True,
|
| 83 |
+
save_total_limit=2,
|
| 84 |
+
report_to=None, # Disable wandb/tensorboard
|
| 85 |
+
push_to_hub=False, # We'll push manually
|
| 86 |
+
)
|
| 87 |
+
print("β
Training arguments configured")
|
| 88 |
+
|
| 89 |
+
# 5. Train the model
|
| 90 |
+
print("\nποΈ Step 5: Training the model...")
|
| 91 |
+
print("β³ This may take a few minutes...")
|
| 92 |
+
|
| 93 |
+
trainer = Trainer(
|
| 94 |
+
model=model,
|
| 95 |
+
args=training_args,
|
| 96 |
+
train_dataset=tokenized_train,
|
| 97 |
+
eval_dataset=tokenized_test,
|
| 98 |
+
tokenizer=tokenizer,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
trainer.train()
|
| 102 |
+
print("β
Training complete!")
|
| 103 |
+
|
| 104 |
+
# 6. Save the model
|
| 105 |
+
print("\nπΎ Step 6: Saving the model...")
|
| 106 |
+
model.save_pretrained("./my_finetuned_model")
|
| 107 |
+
tokenizer.save_pretrained("./my_finetuned_model")
|
| 108 |
+
print("β
Model saved to: ./my_finetuned_model")
|
| 109 |
+
|
| 110 |
+
# 7. Evaluate
|
| 111 |
+
print("\nπ Step 7: Evaluating the model...")
|
| 112 |
+
eval_results = trainer.evaluate()
|
| 113 |
+
print(f"π Accuracy: {eval_results.get('eval_accuracy', 'N/A')}")
|
| 114 |
+
print(f"π Loss: {eval_results.get('eval_loss', 'N/A')}")
|
| 115 |
+
|
| 116 |
+
print("\n" + "=" * 60)
|
| 117 |
+
print("β
FINE-TUNING COMPLETE!")
|
| 118 |
+
print("=" * 60)
|
| 119 |
+
|
| 120 |
+
return "./my_finetuned_model"
|
| 121 |
+
|
| 122 |
+
def push_to_hub():
|
| 123 |
+
"""Push the fine-tuned model to your Hugging Face profile"""
|
| 124 |
+
|
| 125 |
+
print("\nπ€ Pushing model to Hugging Face Hub...")
|
| 126 |
+
|
| 127 |
+
# Check if token exists
|
| 128 |
+
token = os.getenv("HF_TOKEN")
|
| 129 |
+
if token:
|
| 130 |
+
login(token=token)
|
| 131 |
+
else:
|
| 132 |
+
print("β οΈ No HF_TOKEN found in environment variables.")
|
| 133 |
+
print("π Please login manually:")
|
| 134 |
+
login() # Will prompt for token
|
| 135 |
+
|
| 136 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 137 |
+
|
| 138 |
+
model = AutoModelForSequenceClassification.from_pretrained("./my_finetuned_model")
|
| 139 |
+
tokenizer = AutoTokenizer.from_pretrained("./my_finetuned_model")
|
| 140 |
+
|
| 141 |
+
# Change this to your username/model-name
|
| 142 |
+
repo_name = "Surajnitp/sentiment-trackmodel"
|
| 143 |
+
|
| 144 |
+
print(f"π€ Uploading to: https://huggingface.co/{repo_name}")
|
| 145 |
+
model.push_to_hub(repo_name)
|
| 146 |
+
tokenizer.push_to_hub(repo_name)
|
| 147 |
+
|
| 148 |
+
print(f"β
Model pushed successfully!")
|
| 149 |
+
print(f"οΏ½οΏ½οΏ½ https://huggingface.co/{repo_name}")
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
# Train the model
|
| 153 |
+
model_path = setup_training()
|
| 154 |
+
|
| 155 |
+
# Ask if user wants to push to Hub
|
| 156 |
+
print("\n" + "=" * 60)
|
| 157 |
+
choice = input("π Push model to Hugging Face Hub? (y/n): ")
|
| 158 |
+
|
| 159 |
+
if choice.lower() == 'y':
|
| 160 |
+
push_to_hub()
|
| 161 |
+
else:
|
| 162 |
+
print("βοΈ Skipping upload. You can push later.")
|
| 163 |
+
|
| 164 |
+
print("\nβ
All done! Your model is ready.")
|
| 165 |
+
print("π Model location: ./my_finetuned_model")
|