Spaces:
Runtime error
Runtime error
Create huggingface_helper.py
Browse files- huggingface_helper.py +51 -0
huggingface_helper.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
|
| 3 |
+
from datasets import load_dataset
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
class HuggingFaceHelper:
|
| 7 |
+
def __init__(self, model_path="./merged_model", dataset_path=None):
|
| 8 |
+
self.model_path = model_path
|
| 9 |
+
self.dataset_path = dataset_path
|
| 10 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 11 |
+
|
| 12 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 13 |
+
self.model = AutoModelForCausalLM.from_pretrained(model_path).to(self.device)
|
| 14 |
+
|
| 15 |
+
def load_dataset(self):
|
| 16 |
+
if self.dataset_path:
|
| 17 |
+
dataset = load_dataset("json", data_files=self.dataset_path, split="train")
|
| 18 |
+
return dataset.map(self.tokenize_function, batched=True)
|
| 19 |
+
raise ValueError("Dataset path not provided.")
|
| 20 |
+
|
| 21 |
+
def tokenize_function(self, examples):
|
| 22 |
+
return self.tokenizer(examples["messages"], truncation=True, padding="max_length", max_length=512)
|
| 23 |
+
|
| 24 |
+
def fine_tune(self, output_dir="./fine_tuned_model", epochs=3, batch_size=4):
|
| 25 |
+
dataset = self.load_dataset()
|
| 26 |
+
|
| 27 |
+
training_args = TrainingArguments(
|
| 28 |
+
output_dir=output_dir,
|
| 29 |
+
evaluation_strategy="epoch",
|
| 30 |
+
save_strategy="epoch",
|
| 31 |
+
per_device_train_batch_size=batch_size,
|
| 32 |
+
num_train_epochs=epochs,
|
| 33 |
+
weight_decay=0.01,
|
| 34 |
+
push_to_hub=True,
|
| 35 |
+
hub_model_id="Raiff1982/codriao-finetuned"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
trainer = Trainer(
|
| 39 |
+
model=self.model,
|
| 40 |
+
args=training_args,
|
| 41 |
+
train_dataset=dataset,
|
| 42 |
+
tokenizer=self.tokenizer,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
trainer.train()
|
| 46 |
+
self.save_model(output_dir)
|
| 47 |
+
|
| 48 |
+
def save_model(self, output_dir):
|
| 49 |
+
self.model.save_pretrained(output_dir)
|
| 50 |
+
self.tokenizer.save_pretrained(output_dir)
|
| 51 |
+
print(f"Γ’ΒΒ
Model saved to {output_dir} and uploaded to Hugging Face Hub.")
|