Spaces:
Running
Running
import gradio as gr | |
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline | |
import torch | |
# Load the model and tokenizer | |
model_name = "meta-llama/Llama-3.2-1B" | |
tokenizer = AutoTokenizer.from_pretrained(model_name) | |
model = AutoModelForCausalLM.from_pretrained( | |
model_name, | |
device_map="auto", | |
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, | |
) | |
# Initialize the pipeline | |
generator = pipeline( | |
"text-generation", | |
model=model, | |
tokenizer=tokenizer, | |
device_map="auto", | |
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, | |
max_new_tokens=512, | |
) | |
def respond(message, history, system_message, max_tokens, temperature, top_p): | |
prompt = f"{system_message}\n" | |
for user_msg, assistant_msg in history: | |
prompt += f"User: {user_msg}\nAssistant: {assistant_msg}\n" | |
prompt += f"User: {message}\nAssistant:" | |
response = generator( | |
prompt, | |
max_new_tokens=max_tokens, | |
temperature=temperature, | |
top_p=top_p, | |
do_sample=True, | |
)[0]['generated_text'] | |
assistant_response = response.replace(prompt, "").strip() | |
history.append((message, assistant_response)) | |
return assistant_response, history | |
demo = gr.ChatInterface( | |
fn=respond, | |
additional_inputs=[ | |
gr.Textbox(value="You are a friendly Chatbot.", label="System message"), | |
gr.Slider(minimum=1, maximum=1024, value=512, step=1, label="Max new tokens"), | |
gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.01, label="Temperature"), | |
gr.Slider( | |
minimum=0.1, | |
maximum=1.0, | |
value=0.95, | |
step=0.01, | |
label="Top-p (nucleus sampling)", | |
), | |
], | |
title="Chat with LLaMA 2", | |
description="A chat interface using LLaMA 2 model locally via Transformers.", | |
) | |
if __name__ == "__main__": | |
demo.launch() | |