krisha06 commited on
Commit
98b9a53
Β·
verified Β·
1 Parent(s): 6a9d02e

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -100
app.py DELETED
@@ -1,100 +0,0 @@
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 if missing
17
- if tokenizer.pad_token is None:
18
- tokenizer.add_special_tokens({'pad_token': '[PAD]'})
19
-
20
- # Check if fine-tuned model exists
21
- model_path = "./models"
22
- if os.path.exists(model_path):
23
- st.write("βœ… Loading fine-tuned model...")
24
- model = AutoModelForCausalLM.from_pretrained(model_path)
25
- else:
26
- st.write("⚑ Fine-tuning the model (this will take time)...")
27
-
28
- # Load model on CPU
29
- model = AutoModelForCausalLM.from_pretrained(
30
- model_name,
31
- torch_dtype=torch.float32, # Use float32 for CPU compatibility
32
- device_map={"": "cpu"} # Force CPU usage
33
- )
34
-
35
- # Resize model embeddings
36
- model.resize_token_embeddings(len(tokenizer))
37
-
38
- # Apply LoRA
39
- lora_config = LoraConfig(
40
- r=8,
41
- lora_alpha=32,
42
- target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
43
- lora_dropout=0.05,
44
- bias="none",
45
- task_type="CAUSAL_LM",
46
- )
47
- model = get_peft_model(model, lora_config)
48
-
49
- # Load dataset (Choose any one)
50
- dataset = load_dataset("lvwerra/codeparrot-clean", split="train") # βœ… Free dataset
51
-
52
- # πŸ”₯ Fix: Set `labels` properly
53
- def tokenize_function(examples):
54
- inputs = tokenizer(examples["content"], padding="max_length", truncation=True, max_length=512)
55
- inputs["labels"] = inputs["input_ids"].copy() # βœ… Ensure labels exist
56
- return inputs
57
-
58
- tokenized_dataset = dataset.map(tokenize_function, batched=True)
59
-
60
- # Data collator
61
- data_collator = DataCollatorForSeq2Seq(tokenizer, return_tensors="pt")
62
-
63
- # Training arguments
64
- training_args = TrainingArguments(
65
- per_device_train_batch_size=1,
66
- num_train_epochs=1, # Reduce epochs for quick training
67
- learning_rate=3e-4,
68
- output_dir=model_path,
69
- save_strategy="epoch",
70
- logging_dir="./logs",
71
- logging_steps=10,
72
- save_total_limit=2,
73
- evaluation_strategy="no", # βœ… No eval dataset needed
74
- load_best_model_at_end=False # βœ… Prevents conflicts
75
- )
76
-
77
- # Trainer
78
- trainer = Trainer(
79
- model=model,
80
- args=training_args,
81
- train_dataset=tokenized_dataset,
82
- data_collator=data_collator,
83
- )
84
-
85
- # Train
86
- trainer.train()
87
-
88
- # Save model
89
- model.save_pretrained(model_path)
90
- tokenizer.save_pretrained("./tokenizer")
91
-
92
- st.write("πŸŽ‰ Fine-tuning complete! Model saved.")
93
-
94
- # Chat Interface
95
- user_input = st.text_input("Ask a coding question:")
96
- if user_input:
97
- inputs = tokenizer(user_input, return_tensors="pt").to("cpu")
98
- outputs = model.generate(**inputs, max_length=150)
99
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
100
- st.write("πŸ€– AI Tutor:", response)