Spaces:
Sleeping
Sleeping
File size: 1,801 Bytes
75b206c a2519bb 5b56a67 b389ec2 5b56a67 b389ec2 5b56a67 b389ec2 75b206c b389ec2 75b206c 5b56a67 b389ec2 5b56a67 b389ec2 5b56a67 b389ec2 5b56a67 75b206c b389ec2 75b206c b389ec2 5b56a67 b389ec2 75b206c 5b56a67 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
import streamlit as st
# Load tokenizer and base model
base_model_path = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
tokenizer = AutoTokenizer.from_pretrained(base_model_path)
base_model = AutoModelForCausalLM.from_pretrained(
base_model_path,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
device_map="auto" if torch.cuda.is_available() else None
)
# Load LoRA Adapter
model = PeftModel.from_pretrained(base_model, "lora_adapter")
model.eval()
# Streamlit UI
st.title("🧠 TinyLLaMA Python Tutor (LoRA)")
st.write("Ask me any **Python programming** question:")
user_input = st.text_input("Your question")
if user_input:
# Better Prompt Template
prompt = f"""You are a helpful Python programming tutor.
You will ONLY answer questions related to Python programming.
If the question is unrelated to Python, reply:
"Sorry, I can only answer Python-related questions."
Question: {user_input}
Answer:"""
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=300,
temperature=0.7,
do_sample=True,
top_p=0.95,
eos_token_id=tokenizer.eos_token_id,
pad_token_id=tokenizer.eos_token_id
)
decoded_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Extract answer after 'Answer:' line
answer_start = decoded_output.find("Answer:")
if answer_start != -1:
final_answer = decoded_output[answer_start + len("Answer:"):].strip()
else:
final_answer = decoded_output.strip()
st.markdown(f"**Answer:** {final_answer}")
|