File size: 2,331 Bytes
1a3530a
 
 
 
 
58bdce3
 
acd4286
 
 
 
 
 
 
 
 
 
1a3530a
 
58bdce3
1a3530a
 
104faa8
1a3530a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8166990
 
 
1a3530a
 
 
 
 
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
import os
from huggingface_hub import login
import spaces
import gradio as gr

import subprocess

# Ensure the required libraries are installed
def install(package):
    subprocess.check_call([os.sys.executable, "-m", "pip", "install", package])

# Install transformers, huggingface_hub
install("transformers")
install("huggingface_hub")

token = os.environ.get("HF_TOKEN_READ_LLAMA")
login(token)

model_name = 'meta-llama/Meta-Llama-3.1-8B-Instruct'
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype = torch.bfloat16)
tokenizer = AutoTokenizer.from_pretrained(model_name)

if torch.cuda.is_available():
    device = torch.device('cuda')
else:
    device = torch.device('cpu')

model = model.to(device)

@spaces.GPU
def response(message, history, system_message, max_tokens, temperature, top_p):
    messages = [{"role": "system", "content": system_message}]

    for value in history:
        if value[0]:
            messages.append({"role": "user", "content": value[0]})
        if value[1]:
            messages.append({"role": "assistant", "content": value[1]})

    messages.append({"role": "user", "content": message})

    input_ids = tokenizer.apply_chat_template(
        messages,
        add_generation_prompt=True,
        return_tensors='pt'
    ).to(model.device)

    terminators = [
    tokenizer.eos_token_id,
    tokenizer.convert_tokens_to_ids("<|eot_id|>")
    ]

    outputs = model.generate(
        input_ids,
        max_new_tokens=max_tokens,
        eos_token_id=terminators,
        do_sample=True,
        temperature=temperature,
        top_p=top_p
    )

    response = ''

    for message in tokenizer.decode(
        outputs[0][input_ids.shape[-1]:],
        skip_special_tokens=True
    ):
        response += message
        yield response


demo = gr.ChatInterface(
    response,
    additional_inputs = [
        gr.Textbox(value="You are a friendly 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, value=0.7, step=0.1, label="Temperature"),   
        gr.Slider(minimum=0.1, maximum=1, value=0.9, step=0.05, label="Top_p"),    
    ]
)

if __name__ == "__main__":
    demo.launch()