krisha06 commited on
Commit
83e427a
·
verified ·
1 Parent(s): b389ec2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -44
app.py CHANGED
@@ -1,58 +1,59 @@
1
  import torch
2
- from transformers import AutoTokenizer, AutoModelForCausalLM
3
  from peft import PeftModel
4
  import streamlit as st
5
 
6
  # Load tokenizer and base model
7
- base_model_path = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
8
- tokenizer = AutoTokenizer.from_pretrained(base_model_path)
9
- base_model = AutoModelForCausalLM.from_pretrained(
10
- base_model_path,
11
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
12
- device_map="auto" if torch.cuda.is_available() else None
13
- )
14
-
15
- # Load LoRA Adapter
16
- model = PeftModel.from_pretrained(base_model, "lora_adapter")
 
 
 
17
  model.eval()
18
 
19
  # Streamlit UI
 
20
  st.title("🧠 TinyLLaMA Python Tutor (LoRA)")
21
  st.write("Ask me any **Python programming** question:")
22
 
23
- user_input = st.text_input("Your question")
24
 
25
  if user_input:
26
- # Better Prompt Template
27
- prompt = f"""You are a helpful Python programming tutor.
28
-
29
- You will ONLY answer questions related to Python programming.
30
- If the question is unrelated to Python, reply:
31
- "Sorry, I can only answer Python-related questions."
32
-
33
- Question: {user_input}
34
- Answer:"""
35
-
36
- inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
37
-
38
- with torch.no_grad():
39
- outputs = model.generate(
40
- **inputs,
41
- max_new_tokens=300,
42
- temperature=0.7,
43
- do_sample=True,
44
- top_p=0.95,
45
- eos_token_id=tokenizer.eos_token_id,
46
- pad_token_id=tokenizer.eos_token_id
47
- )
48
-
49
- decoded_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
50
-
51
- # Extract answer after 'Answer:' line
52
- answer_start = decoded_output.find("Answer:")
53
- if answer_start != -1:
54
- final_answer = decoded_output[answer_start + len("Answer:"):].strip()
55
  else:
56
- final_answer = decoded_output.strip()
57
-
58
- st.markdown(f"**Answer:** {final_answer}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import torch
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
3
  from peft import PeftModel
4
  import streamlit as st
5
 
6
  # Load tokenizer and base model
7
+ base_model = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
8
+ lora_path = "./lora_adapter" # make sure your LoRA adapter folder is named like this
9
+
10
+ bnb_config = BitsAndBytesConfig(load_in_4bit=True,
11
+ bnb_4bit_compute_dtype=torch.bfloat16)
12
+
13
+ tokenizer = AutoTokenizer.from_pretrained(base_model)
14
+ model = AutoModelForCausalLM.from_pretrained(base_model,
15
+ quantization_config=bnb_config,
16
+ torch_dtype=torch.bfloat16,
17
+ device_map="auto")
18
+
19
+ model = PeftModel.from_pretrained(model, lora_path)
20
  model.eval()
21
 
22
  # Streamlit UI
23
+ st.set_page_config(page_title="🧠 TinyLLaMA Python Tutor (LoRA)")
24
  st.title("🧠 TinyLLaMA Python Tutor (LoRA)")
25
  st.write("Ask me any **Python programming** question:")
26
 
27
+ user_input = st.text_input("Your question", placeholder="e.g. What is a lambda function in Python?")
28
 
29
  if user_input:
30
+ # Filtering logic: Only answer Python-related queries
31
+ if "python" not in user_input.lower() and "py" not in user_input.lower():
32
+ st.warning("❌ Sorry, I can only answer Python programming questions.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  else:
34
+ # System prompt for tutor behavior
35
+ system_prompt = (
36
+ "You are a helpful and knowledgeable Python tutor. "
37
+ "Answer the user's Python programming questions clearly and concisely. "
38
+ "If the question is unclear, ask for clarification."
39
+ )
40
+ prompt = f"<|system|>\n{system_prompt}</s>\n<|user|>\n{user_input}</s>\n<|assistant|>"
41
+
42
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
43
+
44
+ with torch.no_grad():
45
+ with st.spinner("Thinking..."):
46
+ outputs = model.generate(
47
+ **inputs,
48
+ max_new_tokens=150,
49
+ temperature=0.7,
50
+ top_p=0.95,
51
+ do_sample=True,
52
+ eos_token_id=tokenizer.eos_token_id,
53
+ pad_token_id=tokenizer.eos_token_id
54
+ )
55
+ decoded_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
56
+
57
+ # Extract answer only (remove prompt)
58
+ answer = decoded_output.split("<|assistant|>")[-1].strip()
59
+ st.success(f"💬 Answer:\n\n{answer}")