Spaces:
Paused
Paused
Create helper.py
Browse files
helper.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments, pipeline
|
| 3 |
+
from datasets import load_dataset, Dataset
|
| 4 |
+
import json
|
| 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 |
+
# Load tokenizer and model
|
| 13 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 14 |
+
self.model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True, device_map="auto")
|
| 15 |
+
|
| 16 |
+
def check_model_integrity(self):
|
| 17 |
+
print("π Checking model integrity...")
|
| 18 |
+
for param_tensor in self.model.state_dict():
|
| 19 |
+
print(f"{param_tensor}: {self.model.state_dict()[param_tensor].size()}")
|
| 20 |
+
print("β
Model integrity check completed.")
|
| 21 |
+
|
| 22 |
+
def test_pipeline(self):
|
| 23 |
+
try:
|
| 24 |
+
pipe = pipeline("text-generation", model=self.model, tokenizer=self.tokenizer)
|
| 25 |
+
output = pipe("What is the future of AI?", max_length=100)
|
| 26 |
+
print("β
Model successfully generates text:", output)
|
| 27 |
+
except Exception as e:
|
| 28 |
+
print(f"β Pipeline Error: {e}")
|
| 29 |
+
|
| 30 |
+
def load_dataset(self):
|
| 31 |
+
if self.dataset_path:
|
| 32 |
+
dataset = load_dataset("json", data_files=self.dataset_path, split="train")
|
| 33 |
+
return dataset.map(self.tokenize_function, batched=True)
|
| 34 |
+
else:
|
| 35 |
+
raise ValueError("Dataset path not provided.")
|
| 36 |
+
|
| 37 |
+
def tokenize_function(self, examples):
|
| 38 |
+
return self.tokenizer(examples["messages"], truncation=True, padding="max_length", max_length=512)
|
| 39 |
+
|
| 40 |
+
def fine_tune(self, output_dir="./fine_tuned_model", epochs=3, batch_size=4):
|
| 41 |
+
dataset = self.load_dataset()
|
| 42 |
+
|
| 43 |
+
training_args = TrainingArguments(
|
| 44 |
+
output_dir=output_dir,
|
| 45 |
+
evaluation_strategy="epoch",
|
| 46 |
+
save_strategy="epoch",
|
| 47 |
+
per_device_train_batch_size=batch_size,
|
| 48 |
+
per_device_eval_batch_size=batch_size,
|
| 49 |
+
num_train_epochs=epochs,
|
| 50 |
+
weight_decay=0.01,
|
| 51 |
+
logging_dir=f"{output_dir}/logs",
|
| 52 |
+
push_to_hub=False,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
trainer = Trainer(
|
| 56 |
+
model=self.model,
|
| 57 |
+
args=training_args,
|
| 58 |
+
train_dataset=dataset,
|
| 59 |
+
tokenizer=self.tokenizer,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
trainer.train()
|
| 63 |
+
self.save_model(output_dir)
|
| 64 |
+
|
| 65 |
+
def save_model(self, output_dir):
|
| 66 |
+
self.model.save_pretrained(output_dir)
|
| 67 |
+
self.tokenizer.save_pretrained(output_dir)
|
| 68 |
+
print(f"β
Model saved to {output_dir}")
|
| 69 |
+
|
| 70 |
+
def generate_response(self, prompt, max_length=200):
|
| 71 |
+
inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device)
|
| 72 |
+
output = self.model.generate(**inputs, max_length=max_length)
|
| 73 |
+
return self.tokenizer.decode(output[0], skip_special_tokens=True)
|
| 74 |
+
|
| 75 |
+
# Example usage
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
helper = HuggingFaceHelper(model_path="./merged_model", dataset_path="codette_training_data_finetune_fixed.jsonl")
|
| 78 |
+
helper.check_model_integrity()
|
| 79 |
+
helper.test_pipeline()
|
| 80 |
+
helper.fine_tune(output_dir="./codette_finetuned", epochs=3, batch_size=4)
|
| 81 |
+
print(helper.generate_response("How will AI impact cybersecurity?"))
|