Spaces:
Sleeping
Sleeping
| 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}") | |