File size: 10,304 Bytes
41b1248
 
 
 
 
3f35dda
41b1248
 
 
 
 
3f35dda
 
 
41b1248
fd490fb
 
 
 
cc9c601
2b7f2f4
 
 
 
 
 
cc9c601
 
d676716
fd490fb
d676716
fd490fb
cc9c601
 
fd490fb
cc9c601
 
fd490fb
 
cc9c601
798bcec
 
 
 
 
 
cc9c601
2b7f2f4
cc9c601
 
 
fd490fb
 
 
d676716
 
fd490fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d676716
fd490fb
 
 
 
 
d676716
fd490fb
 
 
d676716
 
 
 
 
 
 
 
 
 
cc9c601
 
 
d676716
cc9c601
 
 
 
 
 
fd490fb
cc9c601
fd490fb
 
 
cc9c601
 
 
 
 
fd490fb
cc9c601
fd490fb
cc9c601
 
fd490fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d676716
 
 
fd490fb
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
try:
    import flash_attn
except:
    import subprocess

    print("Installing flash-attn...")
    subprocess.run(
        "pip install flash-attn --no-build-isolation",
        env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
        shell=True,
    )
    import flash_attn

    print("flash-attn installed.")

import os
import uuid
import requests

import torch
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    TextIteratorStreamer,
    BitsAndBytesConfig,
)
from threading import Thread

import gradio as gr
from dotenv import load_dotenv

import spaces


load_dotenv()

MODEL_NAME = "hatakeyama-llm-team/Tanuki-8B-Instruct"
PREFERENCE_API_URL = os.getenv("PREFERENCE_API_URL")
assert PREFERENCE_API_URL, "PREFERENCE_API_URL is not set"

quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_use_double_quant=True,
)
model = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME, quantization_config=quantization_config, device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)

print("Compiling model...")
model = torch.compile(model)
print("Model compiled.")


def send_report(
    type: str,
    data: dict,
):
    print(f"Sending report: {data}")
    try:
        res = requests.post(PREFERENCE_API_URL, json={"type": type, **data})
        print(f"Report sent: {res.json()}")
    except Exception as e:
        print(f"Failed to send report: {e}")


def send_reply(
    reply_id: str,
    parent_id: str,
    role: str,
    body: str,
):

    send_report(
        "conversation",
        {
            "reply_id": reply_id,
            "parent_id": parent_id,
            "role": role,
            "body": body,
        },
    )


def send_score(
    reply_id: str,
    score: int,
):
    # print(f"Score: {score}, reply_id: {reply_id}")
    send_report(
        "score",
        {
            "reply_id": reply_id,
            "score": score,
        },
    )


def generate_unique_id():
    return str(uuid.uuid4())


@spaces.GPU(duration=45)
def generate(
    message: str,
    history: list[tuple[str, str]],
    system_message: str,
    max_tokens: int,
    temperature: float,
    top_p: float,
    top_k: int,
):
    if not message or message.strip() == "":
        return "", history

    messages = [{"role": "system", "content": system_message}]

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

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

    tokenized_input = tokenizer.apply_chat_template(
        messages, add_generation_prompt=True, tokenize=True, return_tensors="pt"
    ).to(model.device)

    streamer = TextIteratorStreamer(
        tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True
    )
    generate_kwargs = dict(
        input_ids=tokenized_input,
        streamer=streamer,
        max_new_tokens=int(max_tokens),
        do_sample=True,
        temperature=float(temperature),
        top_k=int(top_k),
        top_p=float(top_p),
        num_beams=1,
    )
    t = Thread(target=model.generate, kwargs=generate_kwargs)
    t.start()

    # 返す値を初期化
    partial_message = ""

    for new_token in streamer:
        partial_message += new_token
        new_history = history + [(message, partial_message)]
        # 入力テキストをクリアする
        yield "", new_history


def respond(
    message: str,
    history: list[tuple[str, str]],
    system_message: str,
    max_tokens: int,
    temperature: float,
    top_p: float,
    top_k: int,
    reply_ids: list[str],
):
    if len(reply_ids) == 0:
        reply_ids = [generate_unique_id()]
    last_reply_id = reply_ids[-1]
    user_reply_id = generate_unique_id()
    assistant_reply_id = generate_unique_id()

    reply_ids.append(user_reply_id)
    reply_ids.append(assistant_reply_id)

    for stream in generate(
        message,
        history,
        system_message,
        max_tokens,
        temperature,
        top_p,
        top_k,
    ):
        yield *stream, reply_ids

    # 記録を取る
    if len(reply_ids) == 3:
        send_reply(reply_ids[0], "", "system", system_message)
    send_reply(user_reply_id, last_reply_id, "user", message)
    send_reply(assistant_reply_id, user_reply_id, "assistant", stream[1][-1][1])


def retry(
    history: list[tuple[str, str]],
    system_message: str,
    max_tokens: int,
    temperature: float,
    top_p: float,
    top_k: int,
    reply_ids: list[str],
):
    # 最後のメッセージを削除
    last_conversation = history[-1]
    user_message = last_conversation[0]
    history = history[:-1]

    user_reply_id = reply_ids[-2]
    reply_ids = reply_ids[:-1]
    assistant_reply_id = generate_unique_id()
    reply_ids.append(assistant_reply_id)

    for stream in generate(
        user_message,
        history,
        system_message,
        max_tokens,
        temperature,
        top_p,
        top_k,
    ):
        yield *stream, reply_ids

    # 記録を取る
    send_reply(assistant_reply_id, user_reply_id, "assistant", stream[1][-1][1])


def like_reponse(like_data: gr.LikeData, reply_ids: list[str]):
    # print(like_data.index, like_data.value, like_data.liked)
    assert isinstance(like_data.index, list)
    # 評価を送信
    send_score(reply_ids[like_data.index[0] + 1], 1 if like_data.liked else -1)


def demo():
    with gr.Blocks() as ui:

        gr.Markdown(
            """\
# Tanuki 8B Instruct デモ
モデル: https://huggingface.co/hatakeyama-llm-team/Tanuki-8B-Instruct

アシスタントの回答が不適切だと思った場合は **低評価ボタンを押して低評価を送信**、同様に、回答が素晴らしいと思った場合は**高評価ボタンを押して高評価を送信**することで、モデルの改善に貢献できます。

## 注意点
**本デモに入力されたデータ・会話は匿名で全て記録されます**。これらのデータは Tanuki の学習に利用する可能性があります。そのため、**機密情報・個人情報を入力しないでください**。
"""
        )

        reply_ids = gr.State(value=[generate_unique_id()])

        chat_history = gr.Chatbot(value=[])

        with gr.Row():
            retry_btn = gr.Button(value="🔄 再生成", scale=1, size="sm")
            clear_btn = gr.ClearButton(
                components=[chat_history], value="🗑️ 削除", scale=1, size="sm"
            )

        with gr.Group():
            with gr.Row():
                input_text = gr.Textbox(
                    value="",
                    placeholder="質問を入力してください...",
                    show_label=False,
                    scale=8,
                )
                start_btn = gr.Button(
                    value="送信",
                    variant="primary",
                    scale=1,
                )
            gr.Markdown(
                value="※ 機密情報を入力しないでください。また、Tanuki は誤った情報を生成する可能性があります。"
            )

        with gr.Accordion(label="詳細設定", open=False):
            system_prompt_text = gr.Textbox(
                label="システムプロンプト",
                value="以下は、タスクを説明する指示と、文脈のある入力の組み合わせです。要求を適切に満たす応答を書きなさい。",
            )
            max_new_tokens_slider = gr.Slider(
                minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"
            )
            temperature_slider = gr.Slider(
                minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"
            )
            top_p_slider = gr.Slider(
                minimum=0.1,
                maximum=1.0,
                value=0.95,
                step=0.05,
                label="Top-p",
            )
            top_k_slider = gr.Slider(
                minimum=1, maximum=2000, value=250, step=10, label="Top-k"
            )

        gr.Examples(
            examples=[
                ["たぬきってなんですか?"],
                ["情けは人の為ならずとはどういう意味ですか?"],
                ["まどマギで一番可愛いのは誰?"],
                ["明晰夢とはなんですか?"],
                [
                    "シュレディンガー方程式とシュレディンガーの猫はどのような関係がありますか?"
                ],
            ],
            inputs=[input_text],
            cache_examples=False,
        )

        start_btn.click(
            respond,
            inputs=[
                input_text,
                chat_history,
                system_prompt_text,
                max_new_tokens_slider,
                temperature_slider,
                top_p_slider,
                top_k_slider,
                reply_ids,
            ],
            outputs=[input_text, chat_history, reply_ids],
        )
        input_text.submit(
            respond,
            inputs=[
                input_text,
                chat_history,
                system_prompt_text,
                max_new_tokens_slider,
                temperature_slider,
                top_p_slider,
                top_k_slider,
                reply_ids,
            ],
            outputs=[input_text, chat_history, reply_ids],
        )
        retry_btn.click(
            retry,
            inputs=[
                chat_history,
                system_prompt_text,
                max_new_tokens_slider,
                temperature_slider,
                top_p_slider,
                top_k_slider,
                reply_ids,
            ],
            outputs=[input_text, chat_history, reply_ids],
        )

        # 評価されたら
        chat_history.like(like_reponse, inputs=[reply_ids], outputs=None)

        clear_btn.click(
            lambda: [generate_unique_id()],  # system_message用のIDを生成
            outputs=[reply_ids],
        )

    ui.launch()


if __name__ == "__main__":
    demo()