Spaces:
Runtime error
Runtime error
Download app.py from Chuxia-sys/chatbot-lora: direct link, hf CLI and curl.
- Browser
- Download file 2.1 kB
-
https://huggingface.co/spaces/Chuxia-sys/chatbot-lora/resolve/main/app.py
- Command line
-
hf download hf://spaces/Chuxia-sys/chatbot-lora/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Chuxia-sys/chatbot-lora/resolve/main/app.py
2.1 kB
| import torch | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| from peft import PeftModel | |
| # 👇 Replace with your actual model IDs | |
| base_model_id = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" | |
| adapter_id = "Chuxia-sys/finetuned_rag_model_lora" | |
| # Load tokenizer | |
| tokenizer = AutoTokenizer.from_pretrained(base_model_id) | |
| tokenizer.pad_token = tokenizer.eos_token # Important for generation | |
| # Load base model | |
| model = AutoModelForCausalLM.from_pretrained( | |
| base_model_id, | |
| device_map="auto", | |
| torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32 | |
| ) | |
| # Load LoRA adapter | |
| model = PeftModel.from_pretrained(model, adapter_id) | |
| # Optional: Enable half precision if on GPU | |
| if torch.cuda.is_available(): | |
| model = model.to(torch.bfloat16) | |
| # Define chat function | |
| def respond(message, history): | |
| # Format conversation | |
| prompt = f"User: {message}\nAssistant: " | |
| inputs = tokenizer(prompt, return_tensors="pt").to(model.device) | |
| # Generate response | |
| outputs = model.generate( | |
| **inputs, | |
| max_new_tokens=128, | |
| temperature=0.8, # ↑ randomness (was 0.7) | |
| top_p=0.92, # ↑ diversity | |
| top_k=50, # limit to top 50 tokens | |
| repetition_penalty=1.15, # ⬅️ CRITICAL: penalize repeated phrases | |
| do_sample=True, | |
| pad_token_id=tokenizer.eos_token_id, | |
| eos_token_id=tokenizer.eos_token_id | |
| ) | |
| response = tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| # Extract only the assistant's reply | |
| assistant_reply = response.split("Assistant:")[-1].strip() | |
| return assistant_reply | |
| # Build Gradio interface | |
| import gradio as gr | |
| demo = gr.ChatInterface( | |
| fn=respond, | |
| title="💬 Travel Assistant Bot (Fine-tuned TinyLlama)", | |
| description="Ask me anything about travel!", | |
| examples=[ | |
| "What are the best places to visit in Japan?", | |
| "Can you suggest a 3-day itinerary for Paris?", | |
| "What should I pack for a trip to Bali?" | |
| ], | |
| theme="soft" | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |