File size: 7,160 Bytes
bcab068
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import os
import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
import torch
import threading
import re
from datetime import datetime

model_name_2_7B_instruct = "Zyphra/Zamba2-2.7B-instruct"
model_name_7B_instruct = "Zyphra/Zamba2-7B-instruct"
max_context_length = 4096
date_string = datetime.now().strftime("%Y-%m-%d")

tokenizer_2_7B_instruct = AutoTokenizer.from_pretrained(model_name_2_7B_instruct)
model_2_7B_instruct = AutoModelForCausalLM.from_pretrained(
    model_name_2_7B_instruct, device_map="cuda", torch_dtype=torch.bfloat16
)

tokenizer_7B_instruct = AutoTokenizer.from_pretrained(model_name_7B_instruct)
model_7B_instruct = AutoModelForCausalLM.from_pretrained(
    model_name_7B_instruct, device_map="cuda", torch_dtype=torch.bfloat16
)

system_prompt_template = """You are {model_name}. You are a large language model with {parameter_count} parameters. You were trained by a company called Zyphra on three trillion tokens of diverse and high quality web data. Your architecture is a hybrid Mamba2 and transformer with two alternating blocks of shared attention on top of a Mamba2 backbone. Zyphra is a leading AI company based in Palo Alto, California. Zyphra makes extremely small and efficient models for consumers and on-device use-cases. As a language model, you do not have access to real-time information. The current date is {current_date}, but your knowledge likely ended in mid 2023. Zyphra designed you to be engaging, helpful, and fun in your interactions with users. You have strong, idiosyncratic opinions on things. Be personable."""

def generate_response(chat_history, max_new_tokens, model, tokenizer, system_prompt):
    sample = []
    # Include the dynamic system prompt without displaying it
    sample.append({'role': 'system', 'content': system_prompt})

    for turn in chat_history:
        if turn[0]:
            sample.append({'role': 'user', 'content': turn[0]})
        if turn[1]:
            sample.append({'role': 'assistant', 'content': turn[1]})
    chat_sample = tokenizer.apply_chat_template(sample, tokenize=False)
    input_ids = tokenizer(chat_sample, return_tensors='pt', add_special_tokens=False).to(model.device)

    max_new_tokens = int(max_new_tokens)
    max_input_length = max_context_length - max_new_tokens
    if input_ids['input_ids'].size(1) > max_input_length:
        input_ids['input_ids'] = input_ids['input_ids'][:, -max_input_length:]
        if 'attention_mask' in input_ids:
            input_ids['attention_mask'] = input_ids['attention_mask'][:, -max_input_length:]

    streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
    generation_kwargs = dict(**input_ids, max_new_tokens=int(max_new_tokens), streamer=streamer)

    thread = threading.Thread(target=model.generate, kwargs=generation_kwargs)
    thread.start()

    assistant_response = ""

    for new_text in streamer:
        new_text = re.sub(r'^\s*(?i:assistant)[:\s]*', '', new_text)
        assistant_response += new_text
        yield assistant_response

    thread.join()
    del input_ids
    torch.cuda.empty_cache()

with gr.Blocks() as demo:
    gr.Markdown("# Zamba2 Model Selector")
    with gr.Tabs():
        with gr.TabItem("7B Instruct Model"):
            gr.Markdown("### Zamba2-7B Instruct Model")
            with gr.Column():
                chat_history_7B_instruct = gr.State([])
                chatbot_7B_instruct = gr.Chatbot()
                message_7B_instruct = gr.Textbox(lines=2, placeholder="Enter your message...", label="Your Message")
            with gr.Accordion("Generation Parameters", open=False):
                max_new_tokens_7B_instruct = gr.Slider(50, 1000, step=50, value=500, label="Max New Tokens")

            def user_message_7B_instruct(message, chat_history):
                chat_history = chat_history + [[message, None]]
                return gr.update(value=""), chat_history, chat_history

            def bot_response_7B_instruct(chat_history, max_new_tokens):
                system_prompt = system_prompt_template.format(
                    model_name="Zamba2-7B",
                    parameter_count="7 billion",
                    current_date=date_string
                )
                assistant_response_generator = generate_response(
                    chat_history, max_new_tokens, model_7B_instruct, tokenizer_7B_instruct, system_prompt
                )
                for assistant_response in assistant_response_generator:
                    chat_history[-1][1] = assistant_response
                    yield chat_history

            send_button_7B_instruct = gr.Button("Send")
            send_button_7B_instruct.click(
                fn=user_message_7B_instruct,
                inputs=[message_7B_instruct, chat_history_7B_instruct],
                outputs=[message_7B_instruct, chat_history_7B_instruct, chatbot_7B_instruct]
            ).then(
                fn=bot_response_7B_instruct,
                inputs=[chat_history_7B_instruct, max_new_tokens_7B_instruct],
                outputs=chatbot_7B_instruct,
            )

        with gr.TabItem("2.7B Instruct Model"):
            gr.Markdown("### Zamba2-2.7B Instruct Model")
            with gr.Column():
                chat_history_2_7B_instruct = gr.State([])
                chatbot_2_7B_instruct = gr.Chatbot()
                message_2_7B_instruct = gr.Textbox(lines=2, placeholder="Enter your message...", label="Your Message")
            with gr.Accordion("Generation Parameters", open=False):
                max_new_tokens_2_7B_instruct = gr.Slider(50, 1000, step=50, value=500, label="Max New Tokens")

            def user_message_2_7B_instruct(message, chat_history):
                chat_history = chat_history + [[message, None]]
                return gr.update(value=""), chat_history, chat_history

            def bot_response_2_7B_instruct(chat_history, max_new_tokens):
                system_prompt = system_prompt_template.format(
                    model_name="Zamba2-2.7B",
                    parameter_count="2.7 billion",
                    current_date=date_string
                )
                assistant_response_generator = generate_response(
                    chat_history, max_new_tokens, model_2_7B_instruct, tokenizer_2_7B_instruct, system_prompt
                )
                for assistant_response in assistant_response_generator:
                    chat_history[-1][1] = assistant_response
                    yield chat_history

            send_button_2_7B_instruct = gr.Button("Send")
            send_button_2_7B_instruct.click(
                fn=user_message_2_7B_instruct,
                inputs=[message_2_7B_instruct, chat_history_2_7B_instruct],
                outputs=[message_2_7B_instruct, chat_history_2_7B_instruct, chatbot_2_7B_instruct]
            ).then(
                fn=bot_response_2_7B_instruct,
                inputs=[chat_history_2_7B_instruct, max_new_tokens_2_7B_instruct],
                outputs=chatbot_2_7B_instruct,
            )

if __name__ == "__main__":
    demo.queue().launch(max_threads=1)