Spaces:
Sleeping
Sleeping
import gradio as gr | |
from transformers import AutoTokenizer, AutoModelForCausalLM | |
import torch | |
# Load your fine-tuned model | |
model_id = "ragunath-ravi/distilgpt2-lmsys-chat" | |
tokenizer = AutoTokenizer.from_pretrained(model_id) | |
model = AutoModelForCausalLM.from_pretrained(model_id) | |
# Set padding token to be the same as EOS token if not set | |
if tokenizer.pad_token is None: | |
tokenizer.pad_token = tokenizer.eos_token | |
# Move model to GPU if available | |
device = "cuda" if torch.cuda.is_available() else "cpu" | |
model = model.to(device) | |
def respond( | |
message, | |
history: list[tuple[str, str]], | |
system_message, | |
max_tokens, | |
temperature, | |
top_p, | |
): | |
# Format the conversation history as expected by the model | |
prompt = system_message + "\n\n" | |
for user_msg, assistant_msg in history: | |
if user_msg: | |
prompt += f"User: {user_msg}\n" | |
if assistant_msg: | |
prompt += f"Assistant: {assistant_msg}\n" | |
# Add the latest user message | |
prompt += f"User: {message}\nAssistant:" | |
# Tokenize the prompt | |
inputs = tokenizer(prompt, return_tensors="pt").to(device) | |
# Generate response | |
with torch.no_grad(): | |
output = model.generate( | |
inputs["input_ids"], | |
max_new_tokens=max_tokens, | |
temperature=temperature, | |
top_p=top_p, | |
do_sample=True, | |
pad_token_id=tokenizer.eos_token_id, | |
attention_mask=inputs["attention_mask"], | |
) | |
# Decode the generated response | |
full_response = tokenizer.decode(output[0], skip_special_tokens=True) | |
# Extract only the assistant's part from the full response | |
assistant_response = full_response[len(prompt):].strip() | |
# Sometimes the model might continue with "User:" - we need to cut that off | |
if "User:" in assistant_response: | |
assistant_response = assistant_response.split("User:")[0].strip() | |
# Stream the response token by token (simulated for this model) | |
response_so_far = "" | |
tokens = assistant_response.split() | |
for token in tokens: | |
response_so_far += token + " " | |
yield response_so_far.strip() | |
# Create the Gradio chat interface | |
demo = gr.ChatInterface( | |
respond, | |
additional_inputs=[ | |
gr.Textbox(value="You are a helpful assistant.", label="System message"), | |
gr.Slider(minimum=1, maximum=512, value=128, step=1, label="Max new tokens"), | |
gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"), | |
gr.Slider( | |
minimum=0.1, | |
maximum=1.0, | |
value=0.9, | |
step=0.05, | |
label="Top-p (nucleus sampling)", | |
), | |
], | |
title="DistilGPT-2 Chat Assistant", | |
description="A simple chatbot powered by a fine-tuned DistilGPT-2 model on the LMSYS Chat 1M dataset.", | |
) | |
if __name__ == "__main__": | |
demo.launch() |