Download app.py from Sbnos/rono2: direct link, hf CLI and curl.
- Browser
- Download file 2.47 kB
-
https://huggingface.co/spaces/Sbnos/rono2/resolve/main/app.py
- Command line
-
hf download hf://spaces/Sbnos/rono2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Sbnos/rono2/resolve/main/app.py
2.47 kB
| import gradio as gr | |
| import torch | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| # Load Phi-1.5 model | |
| model_name = "microsoft/phi-1_5" | |
| print(f"Loading {model_name}...") | |
| tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| model_name, | |
| trust_remote_code=True, | |
| torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, | |
| device_map="auto" if torch.cuda.is_available() else None | |
| ) | |
| if not torch.cuda.is_available(): | |
| model = model.to('cpu') | |
| print("Model loaded successfully!") | |
| def respond( | |
| message, | |
| history: list[dict[str, str]], | |
| system_message, | |
| max_tokens, | |
| temperature, | |
| top_p, | |
| ): | |
| # Build conversation from history | |
| conversation = f"System: {system_message}\n\n" | |
| for msg in history: | |
| if msg["role"] == "user": | |
| conversation += f"User: {msg['content']}\n" | |
| elif msg["role"] == "assistant": | |
| conversation += f"Assistant: {msg['content']}\n" | |
| conversation += f"User: {message}\nAssistant:" | |
| # Tokenize | |
| inputs = tokenizer(conversation, return_tensors="pt", truncation=True, max_length=2048) | |
| if torch.cuda.is_available(): | |
| inputs = {k: v.to('cuda') for k, v in inputs.items()} | |
| # Generate | |
| with torch.no_grad(): | |
| outputs = model.generate( | |
| **inputs, | |
| max_new_tokens=max_tokens, | |
| temperature=temperature, | |
| top_p=top_p, | |
| do_sample=True, | |
| pad_token_id=tokenizer.eos_token_id, | |
| ) | |
| # Decode | |
| response = tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| response = response.split("Assistant:")[-1].strip() | |
| if "User:" in response: | |
| response = response.split("User:")[0].strip() | |
| return response | |
| chatbot = gr.ChatInterface( | |
| respond, | |
| type="messages", | |
| additional_inputs=[ | |
| gr.Textbox(value="You are a helpful AI assistant.", label="System message"), | |
| gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), | |
| gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"), | |
| gr.Slider( | |
| minimum=0.1, | |
| maximum=1.0, | |
| value=0.95, | |
| step=0.05, | |
| label="Top-p (nucleus sampling)", | |
| ), | |
| ], | |
| ) | |
| with gr.Blocks() as demo: | |
| chatbot.render() | |
| if __name__ == "__main__": | |
| demo.launch() |