Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,57 +1,97 @@
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
-
from
|
|
|
|
| 4 |
import os
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
|
|
|
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
# Initialize the Hugging Face Repository and push model to the Hub
|
| 25 |
-
repo = Repository(local_dir=model_dir, clone_from=repo_name)
|
| 26 |
-
repo.push_to_hub(token=token) # Use the token for authentication
|
| 27 |
-
st.success("Model uploaded to Hugging Face Hub successfully!")
|
| 28 |
-
else:
|
| 29 |
-
st.error("Model directory does not exist. Please make sure the model is fine-tuned first.")
|
| 30 |
|
| 31 |
-
#
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
# Load
|
| 35 |
-
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
#
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
#
|
| 47 |
-
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
|
| 53 |
-
|
| 54 |
-
output = model.generate(**inputs, max_length=200, num_return_sequences=1)
|
| 55 |
-
answer = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 56 |
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
import streamlit as st
|
| 3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer, DataCollatorForSeq2Seq
|
| 4 |
+
from datasets import load_dataset
|
| 5 |
+
from peft import LoraConfig, get_peft_model
|
| 6 |
import os
|
| 7 |
|
| 8 |
+
# UI
|
| 9 |
+
st.title("AI Tutor (Fine-tuned LLM)")
|
| 10 |
+
st.write("This AI tutor is fine-tuned on Python-related questions.")
|
| 11 |
|
| 12 |
+
# Load base model and tokenizer
|
| 13 |
+
model_name = "microsoft/phi-2"
|
| 14 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 15 |
|
| 16 |
+
# 🔥 Fix: Add padding token
|
| 17 |
+
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
|
| 18 |
|
| 19 |
+
# Check if fine-tuned model exists
|
| 20 |
+
model_path = "./models"
|
| 21 |
+
if os.path.exists(model_path):
|
| 22 |
+
st.write("✅ Loading fine-tuned model...")
|
| 23 |
+
model = AutoModelForCausalLM.from_pretrained(model_path)
|
| 24 |
+
else:
|
| 25 |
+
st.write("⚡ Fine-tuning the model (this will take time)...")
|
| 26 |
|
| 27 |
+
# Load model on CPU
|
| 28 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 29 |
+
model_name,
|
| 30 |
+
torch_dtype=torch.bfloat16,
|
| 31 |
+
device_map={"": "cpu"} # Force CPU usage
|
| 32 |
+
)
|
| 33 |
|
| 34 |
+
# Resize model embeddings
|
| 35 |
+
model.resize_token_embeddings(len(tokenizer))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
# Apply LoRA
|
| 38 |
+
lora_config = LoraConfig(
|
| 39 |
+
r=8,
|
| 40 |
+
lora_alpha=32,
|
| 41 |
+
target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
|
| 42 |
+
lora_dropout=0.05,
|
| 43 |
+
bias="none",
|
| 44 |
+
task_type="CAUSAL_LM",
|
| 45 |
+
)
|
| 46 |
+
model = get_peft_model(model, lora_config)
|
| 47 |
|
| 48 |
+
# Load dataset and tokenize
|
| 49 |
+
dataset = load_dataset("mbpp", split="train")
|
| 50 |
|
| 51 |
+
def tokenize_function(examples):
|
| 52 |
+
return tokenizer(examples["text"], padding="max_length", truncation=True, max_length=512)
|
| 53 |
+
|
| 54 |
+
tokenized_dataset = dataset.map(tokenize_function, batched=True)
|
| 55 |
+
|
| 56 |
+
# Data collator
|
| 57 |
+
data_collator = DataCollatorForSeq2Seq(tokenizer, return_tensors="pt")
|
| 58 |
+
|
| 59 |
+
# Training arguments
|
| 60 |
+
training_args = TrainingArguments(
|
| 61 |
+
per_device_train_batch_size=1,
|
| 62 |
+
per_device_eval_batch_size=1,
|
| 63 |
+
num_train_epochs=1, # Reduce epochs for quick training
|
| 64 |
+
learning_rate=3e-4,
|
| 65 |
+
output_dir=model_path,
|
| 66 |
+
save_strategy="epoch",
|
| 67 |
+
logging_dir="./logs",
|
| 68 |
+
logging_steps=10,
|
| 69 |
+
evaluation_strategy="epoch",
|
| 70 |
+
save_total_limit=2,
|
| 71 |
+
load_best_model_at_end=True
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# Trainer
|
| 75 |
+
trainer = Trainer(
|
| 76 |
+
model=model,
|
| 77 |
+
args=training_args,
|
| 78 |
+
train_dataset=tokenized_dataset,
|
| 79 |
+
data_collator=data_collator,
|
| 80 |
+
)
|
| 81 |
|
| 82 |
+
# Train
|
| 83 |
+
trainer.train()
|
| 84 |
|
| 85 |
+
# Save model
|
| 86 |
+
model.save_pretrained(model_path)
|
| 87 |
+
tokenizer.save_pretrained("./tokenizer")
|
| 88 |
|
| 89 |
+
st.write("🎉 Fine-tuning complete! Model saved.")
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
# Chat Interface
|
| 92 |
+
user_input = st.text_input("Ask a coding question:")
|
| 93 |
+
if user_input:
|
| 94 |
+
inputs = tokenizer(user_input, return_tensors="pt").to("cpu")
|
| 95 |
+
outputs = model.generate(**inputs, max_length=150)
|
| 96 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 97 |
+
st.write("🤖 AI Tutor:", response)
|