File size: 8,730 Bytes
b4915c6
 
 
 
2c7920e
b4915c6
 
 
 
 
75266a7
b4915c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c6abca
 
b4915c6
 
 
 
 
 
902c2bc
 
 
b4915c6
 
902c2bc
 
 
 
 
 
 
 
 
 
 
 
 
b4915c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c6abca
b4915c6
902c2bc
d14a9b0
b4915c6
902c2bc
b4915c6
 
 
2c7920e
b4915c6
 
 
 
 
 
 
2c7920e
b4915c6
 
 
 
2c7920e
75266a7
6540e42
75266a7
 
 
 
 
 
 
 
6540e42
 
 
 
 
 
 
 
75266a7
 
 
 
a6e6568
 
 
 
 
 
 
 
 
 
 
d14a9b0
a6e6568
 
 
 
 
 
 
d14a9b0
a6e6568
 
 
 
 
 
 
3291e63
a6e6568
 
 
 
 
 
 
 
 
 
 
 
05e7a0f
3291e63
05e7a0f
a6e6568
 
 
d14a9b0
a6e6568
 
 
05e7a0f
3291e63
05e7a0f
a6e6568
 
6540e42
a6e6568
d14a9b0
a6e6568
 
75266a7
 
 
6540e42
75266a7
a6e6568
 
 
75266a7
3291e63
75266a7
6540e42
75266a7
 
6540e42
 
 
a6e6568
2c7920e
 
75266a7
2c7920e
 
b4915c6
 
 
 
 
 
 
 
2c7920e
b4915c6
 
 
 
 
 
 
2c7920e
 
b4915c6
2c7920e
b4915c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c7920e
b4915c6
 
 
 
 
2c7920e
 
 
 
b4915c6
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import os
from collections.abc import Iterator
from threading import Thread

import gradio as gr
import spaces
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer

import logging
import time

logger = logging.getLogger("gradio_chat_001")
logger.setLevel(logging.INFO)
logging.debug("Starting logging for gradio_chat_001.")
categories = [
    "Legal", "Specification", "Facts and Figures",
    "Publication", "Payment Scheme",
    "Alternative Payment Systems", "Crypto Payments",
    "Card Payments", "Banking", "Regulations", "Account Payments"
]
logging.debug("Categories to classify: " + repr(categories))

# DESCRIPTION = """\
# # Llama 3.2 3B Instruct
# Llama 3.2 3B is Meta's latest iteration of open LLMs.
# This is a demo of [`meta-llama/Llama-3.2-3B-Instruct`](https://huggingface.co/meta-llama/Llama-3.2-3B-Instruct), fine-tuned for instruction following.
# For more details, please check [our post](https://huggingface.co/blog/llama32).
# """

MAX_MAX_NEW_TOKENS = 2048
DEFAULT_MAX_NEW_TOKENS = 1024
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))

USE_CUDA = torch.cuda.is_available()
if USE_CUDA:
    logger.warn("Wants to use CUDA, stop it!")
    USE_CUDA = False
device = torch.device("cuda:0" if USE_CUDA else "cpu")


# model_id = "meta-llama/Llama-3.2-3B-Instruct"
model_id = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    device_map="auto",
    torch_dtype=torch.bfloat16,
)
logger.info("Created model: " + model_id)
logger.info("Model repr: " + repr(model))
logger.info("Tokenizer repr: " + repr(tokenizer))
model.eval()

# Example:
# from transformers import AutoTokenizer, DeepseekV3ForCausalLM

# model = DeepseekV3ForCausalLM.from_pretrained("meta-deepseek_v3/DeepseekV3-2-7b-hf")
# tokenizer = AutoTokenizer.from_pretrained("meta-deepseek_v3/DeepseekV3-2-7b-hf")

# prompt = "Hey, are you conscious? Can you talk to me?"
# inputs = tokenizer(prompt, return_tensors="pt")

# # Generate
# generate_ids = model.generate(inputs.input_ids, max_length=30)
# tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]


# @spaces.GPU(duration=90)
def generate(
    message: str,
    chat_history: list[dict],
    max_new_tokens: int = 1024,
    temperature: float = 0.6,
    top_p: float = 0.9,
    top_k: int = 50,
    repetition_penalty: float = 1.2,
) -> Iterator[str]:
    conversation = [*chat_history, {"role": "user", "content": message}]

    input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
    if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
        input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
        gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
        logger.warn(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
    input_ids = input_ids.to(model.device)
    attention_mask = torch.ones_like(input_ids)
    streamer = TextIteratorStreamer(tokenizer, timeout=30.0, skip_prompt=True, skip_special_tokens=True)
    generate_kwargs = dict(
        {"input_ids": input_ids, "attention_mask": attention_mask},
        streamer=streamer,
        max_new_tokens=max_new_tokens,
        do_sample=True,
        top_p=top_p,
        top_k=top_k,
        temperature=temperature,
        num_beams=1,
        repetition_penalty=repetition_penalty,
    )
    t = Thread(target=model.generate, kwargs=generate_kwargs)
    t.start()

    outputs = []
    for text in streamer:
        outputs.append(text)
        yield "".join(outputs)


def analyse_time_array(arr, extended=False):
    length = len(arr)
    if length == 0:
        return "Empty"
    if length == 1:
        return "Start"
    start = arr[0]
    end = arr[-1]
    diff = end - start
    msg = f"{length-1} Tokens in {diff}s | {diff/length} Tokens/s"
    if extended:
        diffs = sorted([arr[i+1]-arr[i] for i in range(0, length-1)])
        # msg += "\nDiffs between tokens:"
        msg += "\nBest/shortest: " + ", ".join(f"{x:.02f}s" for x in diffs[:5])
        msg += "\nWorst/longest: " + ", ".join(f"{x:.02f}s" for x in diffs[-5:])
    return msg
        


SPACER = "\n\n" + "-"*80 + "\n\n"

def try_generate(
    message: str,
    chat_history: list[dict],
    max_new_tokens: int = 1024,
    temperature: float = 0.6,
    top_p: float = 0.9,
    top_k: int = 50,
    repetition_penalty: float = 1.2,
):
    try:
        logger.info("Create input")
        yield "<Create Input>"
        conversation = [*chat_history, {"role": "user", "content": message}]
    
        input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
        if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
            input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
            gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
            logger.warn(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
        yield f"<input_ids>{repr(input_ids)}</input_ids>"
        input_ids = input_ids.to(model.device)
        attention_mask = torch.ones_like(input_ids)
    except Exception as e:
        logger.warn("Failed to create input parameters: " + repr(e))
        yield "Failed to create input parameters: " + repr(e)
        return
    try:
        streamer = TextIteratorStreamer(tokenizer, timeout=120.0, skip_prompt=True, skip_special_tokens=True)
        generate_kwargs = dict(
            {"input_ids": input_ids, "attention_mask": attention_mask},
            streamer=streamer,
            max_new_tokens=max_new_tokens,
            do_sample=True,
            top_p=top_p,
            top_k=top_k,
            temperature=temperature,
            num_beams=1,
            repetition_penalty=repetition_penalty,
        )
    except Exception as e:
        msg ="Failed to create streamer: " + repr(e)
        logger.warning(msg)
        yield msg
        return

    try:
        yield "<start thread>"
        t = Thread(target=model.generate, kwargs=generate_kwargs)
        t.start()
    except Exception as e:
        msg = "Failed to create thread: " + repr(e)
        logger.warning(msg)
        yield msg
        return
    outputs = []
    times = [time.time()]
    try:
        yield "<start text>"
        for text in streamer:
            outputs.append(text)
            times.append(time.time())
            # yield "".join(outputs)
            msg = "".join(outputs)
            info = analyse_time_array(times, True)
            yield msg+SPACER+info
    except Exception as e:
        n = len(outputs)
        exp = repr(e)
        error = f"Failed creating output @ position {n}: {exp}"
        logger.warning(error)
        msg = "".join(outputs)
        info = analyse_time_array(times, True)
        yield msg+SPACER+info+SPACER+error
        # yield f"{output}\n--------------------\n{msg}"
    msg = "".join(outputs)
    info = analyse_time_array(times, True)
    yield msg+SPACER+info+"\n--- DONE ---"


demo = gr.ChatInterface(
    fn=try_generate,
    additional_inputs=[
        gr.Slider(
            label="Max new tokens",
            minimum=1,
            maximum=MAX_MAX_NEW_TOKENS,
            step=1,
            value=DEFAULT_MAX_NEW_TOKENS,
        ),
        gr.Slider(
            label="Temperature",
            minimum=0.1,
            maximum=4.0,
            step=0.1,
            value=0.6,
        ),
        gr.Slider(
            label="Top-p (nucleus sampling)",
            minimum=0.05,
            maximum=1.0,
            step=0.05,
            value=0.9,
        ),
        gr.Slider(
            label="Top-k",
            minimum=1,
            maximum=1000,
            step=1,
            value=50,
        ),
        gr.Slider(
            label="Repetition penalty",
            minimum=1.0,
            maximum=2.0,
            step=0.05,
            value=1.2,
        ),
    ],
    stop_btn=None,
    examples=[
        ["Hello there! How are you doing?"],
        ["Can you explain briefly to me what is the Python programming language?"],
        ["Explain the plot of Cinderella in a sentence."],
        ["How many hours does it take a man to eat a Helicopter?"],
        ["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
    ],
    cache_examples=False,
    type="messages",
    # description=DESCRIPTION,
    # css_paths="style.css",
    fill_height=True,
)


if __name__ == "__main__":
    demo.queue(max_size=20).launch()