Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -12,7 +12,7 @@ base_model = AutoModelForCausalLM.from_pretrained(
|
|
| 12 |
device_map="auto" if torch.cuda.is_available() else None
|
| 13 |
)
|
| 14 |
|
| 15 |
-
# Load LoRA
|
| 16 |
model = PeftModel.from_pretrained(base_model, "lora_adapter")
|
| 17 |
model.eval()
|
| 18 |
|
|
@@ -23,35 +23,36 @@ st.write("Ask me any **Python programming** question:")
|
|
| 23 |
user_input = st.text_input("Your question")
|
| 24 |
|
| 25 |
if user_input:
|
| 26 |
-
# Prompt
|
| 27 |
-
prompt = f"""
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
If the question is unrelated to Python
|
| 31 |
"Sorry, I can only answer Python-related questions."
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
| 35 |
|
| 36 |
-
|
| 37 |
-
"""
|
| 38 |
|
| 39 |
-
inputs = tokenizer(prompt, return_tensors="pt", return_attention_mask=True).to(model.device)
|
| 40 |
with torch.no_grad():
|
| 41 |
-
|
| 42 |
**inputs,
|
| 43 |
-
max_new_tokens=
|
| 44 |
temperature=0.7,
|
| 45 |
do_sample=True,
|
|
|
|
|
|
|
| 46 |
pad_token_id=tokenizer.eos_token_id
|
| 47 |
)
|
| 48 |
|
| 49 |
-
|
| 50 |
|
| 51 |
-
#
|
| 52 |
-
|
| 53 |
-
|
|
|
|
| 54 |
else:
|
| 55 |
-
final_answer =
|
| 56 |
|
| 57 |
st.markdown(f"**Answer:** {final_answer}")
|
|
|
|
| 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 |
|
|
|
|
| 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}")
|