krisha06 commited on
Commit
43ede4d
·
verified ·
1 Parent(s): e4bc1f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -42
app.py CHANGED
@@ -1,57 +1,97 @@
 
1
  import streamlit as st
2
- from transformers import AutoModelForCausalLM, AutoTokenizer
3
- from huggingface_hub import Repository
 
4
  import os
5
 
6
- # Retrieve Hugging Face token from Streamlit secrets
7
- token = st.secrets["HUGGINGFACE_TOKEN"] # Make sure to add your Hugging Face token to Streamlit secrets
 
8
 
9
- # Define model directory and Hugging Face repo name
10
- model_dir = "./tuned_model" # The directory where the fine-tuned model is saved
11
- repo_name = "krisha06/Python_tutor" # Replace with your Hugging Face repo name
12
 
13
- # Streamlit App Title
14
- st.title("AI Coding Mentor")
15
 
16
- # Section to upload the fine-tuned model to Hugging Face Hub
17
- st.header("Upload Your Fine-Tuned Model to Hugging Face Hub")
 
 
 
 
 
18
 
19
- # Option to upload the model
20
- upload_model_button = st.button("Upload Model to Hugging Face Hub")
 
 
 
 
21
 
22
- if upload_model_button:
23
- if os.path.exists(model_dir):
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
- # Section for using the model in the app
32
- st.header("Ask Me Any Coding Question!!")
 
 
 
 
 
 
 
 
33
 
34
- # Load model and tokenizer (either from local directory or Hugging Face Hub)
35
- model_name = repo_name # Use the repo name if the model is on Hugging Face Hub, else use local dir
36
 
37
- if os.path.exists(model_dir):
38
- # Load the model and tokenizer from local directory
39
- model = AutoModelForCausalLM.from_pretrained(model_dir, use_auth_token=token)
40
- tokenizer = AutoTokenizer.from_pretrained(model_dir, use_auth_token=token)
41
- else:
42
- # Load the model from Hugging Face Hub
43
- model = AutoModelForCausalLM.from_pretrained(model_name, use_auth_token=token)
44
- tokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token=token)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
- # User input: Coding question
47
- question = st.text_input("Enter your coding question:")
48
 
49
- if question:
50
- input_text = f"### Question:\n{question}\n### Answer:"
51
- inputs = tokenizer(input_text, return_tensors="pt")
52
 
53
- with st.spinner("Processing..."):
54
- output = model.generate(**inputs, max_length=200, num_return_sequences=1)
55
- answer = tokenizer.decode(output[0], skip_special_tokens=True)
56
 
57
- st.write(answer)
 
 
 
 
 
 
 
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)