File size: 1,915 Bytes
f152a90
76084c0
 
 
 
ede2137
76084c0
 
 
 
 
 
b207a62
76084c0
 
 
 
 
 
 
 
 
b207a62
76084c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b207a62
 
c088d8d
b207a62
 
c088d8d
 
b207a62
 
 
 
c088d8d
b207a62
 
f152a90
76084c0
 
f152a90
 
b207a62
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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()