Spaces:
Paused
Paused
Update train.py
Browse files15 unmodified lines161718192021222324252627282930313233343536373839404142434445464748495051521 unmodified line545556575859606162632 unmodified lines666768697071727374759 unmodified lines85868788899091929394951 unmodified line9798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281292 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416515 unmodified linesdef setup_training():"""Setup and run the fine-tuning process"""print("=" * 60)print("π TRACKMODEL - FINE-TUNING STARTED")print("=" * 60)# 1. Load Datasetprint("\nπ Step 1: Loading dataset...")dataset = load_dataset("imdb")print(f"β Loaded {len(dataset['train'])} training samples")print(f"β Loaded {len(dataset['test'])} test samples")# Use a subset for faster training (remove .select() for full training)print("\nβ‘ Using subset for faster training (500 train, 100 test)")train_subset = dataset["train"].select(range(500))test_subset = dataset["test"].select(range(100))# 2. Load Model and Tokenizerprint("\nπ€ Step 2: Loading pre-trained model...")model_name = "distilbert-base-uncased"print(f"π¦ Model: {model_name}")tokenizer = AutoTokenizer.from_pretrained(model_name)model = AutoModelForSequenceClassification.from_pretrained(model_name,num_labels=2 # Binary classification: positive/negative)print("β Model and tokenizer loaded successfully")# 3. Tokenize the datasetprint("\nβοΈ Step 3: Tokenizing dataset...")def tokenize_function(examples):return tokenizer(examples["text"],1 unmodified linetruncation=True,max_length=256, # Shorter for faster training)tokenized_train = train_subset.map(tokenize_function, batched=True)tokenized_test = test_subset.map(tokenize_function, batched=True)# Format for PyTorchtokenized_train = tokenized_train.remove_columns(["text"])tokenized_test = tokenized_test.remove_columns(["text"])2 unmodified linestokenized_train.set_format("torch")tokenized_test.set_format("torch")print("β Tokenization complete")# 4. Training Argumentsprint("\nβοΈ Step 4: Configuring training parameters...")training_args = TrainingArguments(output_dir="./results",num_train_epochs=2, # 2 epochs for quick demonstration9 unmodified linespush_to_hub=False, # We'll push manually)print("β Training arguments configured")# 5. Train the modelprint("\nποΈ Step 5: Training the model...")print("β³ This may take a few minutes...")trainer = Trainer(model=model,args=training_args,1 unmodified lineeval_dataset=tokenized_test,tokenizer=tokenizer,)trainer.train()print("β Training complete!")# 6. Save the modelprint("\nπΎ Step 6: Saving the model...")model.save_pretrained("./my_finetuned_model")tokenizer.save_pretrained("./my_finetuned_model")print("β Model saved to: ./my_finetuned_model")# 7. Evaluateprint("\nπ Step 7: Evaluating the model...")eval_results = trainer.evaluate()print(f"π Accuracy: {eval_results.get('eval_accuracy', 'N/A')}")print(f"π Loss: {eval_results.get('eval_loss', 'N/A')}")print("\n" + "=" * 60)print("β FINE-TUNING COMPLETE!")print("=" * 60)return "./my_finetuned_model"def push_to_hub():"""Push the fine-tuned model to your Hugging Face profile"""print("\nπ€ Pushing model to Hugging Face Hub...")# Check if token existstoken = os.getenv("HF_TOKEN")if token:2 unmodified linesprint("β οΈ No HF_TOKEN found in environment variables.")print("π Please login manually:")login() # Will prompt for tokenfrom transformers import AutoModelForSequenceClassification, AutoTokenizermodel = AutoModelForSequenceClassification.from_pretrained("./my_finetuned_model")tokenizer = AutoTokenizer.from_pretrained("./my_finetuned_model")# Change this to your username/model-namerepo_name = "Surajnitp/sentiment-trackmodel"print(f"π€ Uploading to: https://huggingface.co/{repo_name}")model.push_to_hub(repo_name)tokenizer.push_to_hub(repo_name)print(f"β Model pushed successfully!")print(f"π https://huggingface.co/{repo_name}")if __name__ == "__main__":# Train the modelmodel_path = setup_training()# Ask if user wants to push to Hubprint("\n" + "=" * 60)choice = input("π Push model to Hugging Face Hub? (y/n): ")if choice.lower() == 'y':push_to_hub()else:print("βοΈ Skipping upload. You can push later.")print("\nβ All done! Your model is ready.")print("π Model location: ./my_finetuned_model")15 unmodified lines161718192021222324252627282930313233343536373839404142434445464748495051521 unmodified line545556575859606162632 unmodified lines666768697071727374759 unmodified lines85868788899091929394951 unmodified line9798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281292 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416515 unmodified linesdef setup_training():"""Setup and run the fine-tuning process"""print("=" * 60)print("π TRACKMODEL - FINE-TUNING STARTED")print("=" * 60)# 1. Load Datasetprint("\nπ Step 1: Loading dataset...")dataset = load_dataset("imdb")print(f"β Loaded {len(dataset['train'])} training samples")print(f"β Loaded {len(dataset['test'])} test samples")# Use a subset for faster training (remove .select() for full training)print("\nβ‘ Using subset for faster training (500 train, 100 test)")train_subset = dataset["train"].select(range(500))test_subset = dataset["test"].select(range(100))# 2. Load Model and Tokenizerprint("\nπ€ Step 2: Loading pre-trained model...")model_name = "distilbert-base-uncased"print(f"π¦ Model: {model_name}")tokenizer = AutoTokenizer.from_pretrained(model_name)model = AutoModelForSequenceClassification.from_pretrained(model_name,num_labels=2 # Binary classification: positive/negative)print("β Model and tokenizer loaded successfully")# 3. Tokenize the datasetprint("\nβοΈ Step 3: Tokenizing dataset...")def tokenize_function(examples):return tokenizer(examples["text"],1 unmodified linetruncation=True,max_length=256, # Shorter for faster training)tokenized_train = train_subset.map(tokenize_function, batched=True)tokenized_test = test_subset.map(tokenize_function, batched=True)# Format for PyTorchtokenized_train = tokenized_train.remove_columns(["text"])tokenized_test = tokenized_test.remove_columns(["text"])2 unmodified linestokenized_train.set_format("torch")tokenized_test.set_format("torch")print("β Tokenization complete")# 4. Training Argumentsprint("\nβοΈ Step 4: Configuring training parameters...")training_args = TrainingArguments(output_dir="./results",num_train_epochs=2, # 2 epochs for quick demonstration9 unmodified linespush_to_hub=False, # We'll push manually)print("β Training arguments configured")# 5. Train the modelprint("\nποΈ Step 5: Training the model...")print("β³ This may take a few minutes...")trainer = Trainer(model=model,args=training_args,1 unmodified lineeval_dataset=tokenized_test,tokenizer=tokenizer,)trainer.train()print("β Training complete!")# 6. Save the modelprint("\nπΎ Step 6: Saving the model...")model.save_pretrained("./my_finetuned_model")tokenizer.save_pretrained("./my_finetuned_model")print("β Model saved to: ./my_finetuned_model")# 7. Evaluateprint("\nπ Step 7: Evaluating the model...")eval_results = trainer.evaluate()print(f"π Accuracy: {eval_results.get('eval_accuracy', 'N/A')}")print(f"π Loss: {eval_results.get('eval_loss', 'N/A')}")print("\n" + "=" * 60)print("β FINE-TUNING COMPLETE!")print("=" * 60)return "./my_finetuned_model"def push_to_hub():"""Push the fine-tuned model to your Hugging Face profile"""print("\nπ€ Pushing model to Hugging Face Hub...")# Check if token existstoken = os.getenv("HF_TOKEN")if token:2 unmodified linesprint("β οΈ No HF_TOKEN found in environment variables.")print("π Please login manually:")login() # Will prompt for tokenfrom transformers import AutoModelForSequenceClassification, AutoTokenizermodel = AutoModelForSequenceClassification.from_pretrained("./my_finetuned_model")tokenizer = AutoTokenizer.from_pretrained("./my_finetuned_model")# Change this to your username/model-namerepo_name = "Surajnitp/sentiment-trackmodel"print(f"π€ Uploading to: https://huggingface.co/{repo_name}")model.push_to_hub(repo_name)tokenizer.push_to_hub(repo_name)print(f"β Model pushed successfully!")print(f"π https://huggingface.co/{repo_name}")if __name__ == "__main__":# Train the modelmodel_path = setup_training()# Ask if user wants to push to Hubprint("\n" + "=" * 60)choice = input("π Push model to Hugging Face Hub? (y/n): ")if choice.lower() == 'y':push_to_hub()else:print("βοΈ Skipping upload. You can push later.")print("\nβ All done! Your model is ready.")print("π Model location: ./my_finetuned_model")
train.py+28-28