File size: 14,275 Bytes
df97cfa
 
 
 
f732d7c
df97cfa
6bde6cb
f732d7c
 
c040907
f732d7c
6bde6cb
5877cdc
 
7a42c18
6bde6cb
 
df97cfa
0d4eedd
d91928f
6bde6cb
0d4eedd
d91928f
c693f6c
 
6bde6cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0edcab
 
 
 
da3b30c
f4d4880
b0edcab
6bde6cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f732d7c
df97cfa
 
df7df20
b555022
df97cfa
 
 
b555022
f732d7c
6bde6cb
df97cfa
dc15b84
c040907
df97cfa
6bde6cb
 
df97cfa
 
dc15b84
df97cfa
 
 
 
 
 
 
 
 
 
 
 
 
 
f732d7c
 
 
 
 
6bde6cb
 
 
 
 
 
9a2c48b
6bde6cb
0d4eedd
 
6bde6cb
 
 
f732d7c
6bde6cb
 
 
f732d7c
6bde6cb
 
 
 
f732d7c
 
df97cfa
 
0b790fb
df97cfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f732d7c
df97cfa
 
6bde6cb
160c75c
f732d7c
c040907
6bde6cb
 
c040907
 
 
 
 
 
 
6bde6cb
c040907
 
 
 
 
 
 
 
 
 
6bde6cb
c040907
 
 
6bde6cb
7a42c18
6bde6cb
 
 
 
 
 
 
5877cdc
 
6bde6cb
 
 
 
 
5877cdc
6bde6cb
 
5877cdc
6bde6cb
 
5877cdc
6bde6cb
df7df20
 
 
 
 
 
 
 
c040907
df7df20
 
 
44af809
df7df20
 
 
 
c040907
 
 
 
 
 
 
d43f5e1
c040907
 
 
 
 
 
6bde6cb
8d4c909
 
 
 
160c75c
c040907
160c75c
 
 
df97cfa
 
 
 
 
 
 
 
 
 
 
 
 
f2582eb
 
 
 
 
 
 
5b34bc3
df97cfa
 
 
 
 
 
 
 
 
6a7e083
df97cfa
 
 
 
 
 
dc15b84
df97cfa
 
dc15b84
df97cfa
 
 
6a7e083
df97cfa
6a7e083
6fbdb04
df97cfa
ecf7aeb
 
6a7e083
 
df97cfa
 
7935419
df97cfa
160c75c
6a7e083
160c75c
6a7e083
b2a0a00
160c75c
 
 
df97cfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e89200e
 
df97cfa
f2582eb
df97cfa
f2582eb
ac7b6c5
f2582eb
ac7b6c5
df97cfa
f2582eb
e89200e
 
df97cfa
f732d7c
df97cfa
 
 
 
 
 
 
6bde6cb
 
 
 
 
 
df97cfa
 
 
6bde6cb
44af809
df97cfa
6bde6cb
df97cfa
 
c040907
df97cfa
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
370
371
372
373
374
375
import datetime
import json
import os
import shutil
from typing import Optional
from typing import Tuple
from typing import Union

import gradio as gr
import requests
import torch
from fastchat.conversation import Conversation
from fastchat.conversation import SeparatorStyle
from fastchat.conversation import compute_skip_echo_len
from fastchat.conversation import get_default_conv_template
from fastchat.serve.cli import SimpleChatIO
from fastchat.serve.inference import generate_stream
from huggingface_hub import Repository
from huggingface_hub import snapshot_download
from peft import LoraConfig
from peft import PeftModel
from peft import get_peft_model
from peft import set_peft_model_state_dict
from transformers import LlamaForCausalLM
from transformers import LlamaTokenizer
from transformers import PreTrainedModel
from transformers import PreTrainedTokenizerBase


def load_lora_model(
    model_path: str,
    lora_weight: str,
    device: str,
    num_gpus: int,
    max_gpu_memory: Optional[str] = None,
    load_8bit: bool = False,
    debug: bool = False,
) -> Tuple[Union[PreTrainedModel, PeftModel], PreTrainedTokenizerBase]:
    model: Union[PreTrainedModel, PeftModel]
    tokenizer: PreTrainedTokenizerBase
    tokenizer = LlamaTokenizer.from_pretrained(model_path)
    model = LlamaForCausalLM.from_pretrained(
        model_path,
        load_in_8bit=load_8bit,
        device_map="auto" if device == "cuda" else {"": device},
        max_memory={i: max_gpu_memory for i in range(num_gpus)},
        torch_dtype=torch.float16,
    )
    if lora_weight is not None:
        # model = PeftModelForCausalLM.from_pretrained(model, model_path, **kwargs)
        config = LoraConfig.from_pretrained(lora_weight)
        model = get_peft_model(model, config)

        # Check the available weights and load them
        checkpoint_name = os.path.join(
            lora_weight, "pytorch_model.bin"
        )  # Full checkpoint
        if not os.path.exists(checkpoint_name):
            checkpoint_name = os.path.join(
                lora_weight, "adapter_model.bin"
            )  # only LoRA model - LoRA config above has to fit
        # The two files above have a different name depending on how they were saved,
        # but are actually the same.
        if os.path.exists(checkpoint_name):
            adapters_weights = torch.load(checkpoint_name)
            set_peft_model_state_dict(model, adapters_weights)
        else:
            raise IOError(f"Checkpoint {checkpoint_name} not found")

    if debug:
        print(model)

    return model, tokenizer


print(datetime.datetime.now())

NUM_THREADS = 1

print(NUM_THREADS)

print("starting server ...")

BASE_MODEL = "decapoda-research/llama-13b-hf"
LORA_WEIGHTS_HF = "izumi-lab/llama-13b-japanese-lora-v0-1ep"
HF_TOKEN = os.environ.get("HF_TOKEN", None)
DATASET_REPOSITORY = os.environ.get("DATASET_REPOSITORY", None)
SLACK_WEBHOOK = os.environ.get("SLACK_WEBHOOK", None)

LORA_WEIGHTS = snapshot_download(LORA_WEIGHTS_HF)

repo = None
LOCAL_DIR = "/home/user/data/"

if HF_TOKEN and DATASET_REPOSITORY:
    try:
        shutil.rmtree(LOCAL_DIR)
    except Exception:
        pass

    repo = Repository(
        local_dir=LOCAL_DIR,
        clone_from=DATASET_REPOSITORY,
        use_auth_token=HF_TOKEN,
        repo_type="dataset",
    )
    repo.git_pull()

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

model, tokenizer = load_lora_model(
    model_path=BASE_MODEL,
    lora_weight=LORA_WEIGHTS,
    device=device,
    num_gpus=1,
    max_gpu_memory="16GiB",
    load_8bit=True,
    debug=False,
)

Conversation._get_prompt = Conversation.get_prompt
Conversation._append_message = Conversation.append_message


def conversation_append_message(cls, role: str, message: str):
    cls.offset = -2
    return cls._append_message(role, message)


def conversation_get_prompt_overrider(cls: Conversation) -> str:
    cls.messages = cls.messages[-2:]
    return cls._get_prompt()


def save_inputs_and_outputs(now, inputs, outputs, generate_kwargs):
    current_hour = now.strftime("%Y-%m-%d_%H")
    file_name = f"prompts_{LORA_WEIGHTS_HF.split('/')[-1]}_{current_hour}.jsonl"

    if repo is not None:
        repo.git_pull(rebase=True)
        with open(os.path.join(LOCAL_DIR, file_name), "a", encoding="utf-8") as f:
            json.dump(
                {
                    "inputs": inputs,
                    "outputs": outputs,
                    "generate_kwargs": generate_kwargs,
                },
                f,
                ensure_ascii=False,
            )
            f.write("\n")
        repo.push_to_hub()


# we cant add typing now
# https://github.com/gradio-app/gradio/issues/3514
def evaluate(
    instruction,
    temperature=0.7,
    max_tokens=256,
    repetition_penalty=1.0,
):
    try:
        inputs = tokenizer(instruction, return_tensors="pt")
        if len(inputs["input_ids"][0]) > max_tokens - 40:
            if HF_TOKEN and DATASET_REPOSITORY:
                try:
                    now = datetime.datetime.now()
                    current_time = now.strftime("%Y-%m-%d %H:%M:%S")
                    print(f"[{current_time}] Pushing prompt and completion to the Hub")
                    save_inputs_and_outputs(
                        now,
                        instruction,
                        "",
                        {
                            "temperature": temperature,
                            "max_tokens": max_tokens,
                            "repetition_penalty": repetition_penalty,
                        },
                    )
                except Exception as e:
                    print(e)
            return (
                f"please reduce the input length. Currently, {len(inputs['input_ids'][0])} ( > {max_tokens - 40}) tokens are used.",
                gr.update(interactive=True),
                gr.update(interactive=True),
            )

        conv = get_default_conv_template(BASE_MODEL).copy()

        conv.append_message(conv.roles[0], instruction)
        conv.append_message(conv.roles[1], None)

        generate_stream_func = generate_stream
        prompt = conv.get_prompt()

        skip_echo_len = compute_skip_echo_len(BASE_MODEL, conv, prompt)

        gen_params = {
            "model": BASE_MODEL,
            "prompt": prompt,
            "temperature": temperature,
            "max_new_tokens": max_tokens - len(inputs["input_ids"][0]) - 30,
            "stop": conv.sep if conv.sep_style == SeparatorStyle.SINGLE else None,
        }
        chatio = SimpleChatIO()

        chatio.prompt_for_output(conv.roles[1])
        output_stream = generate_stream_func(model, tokenizer, gen_params, device)
        output = chatio.stream_output(output_stream, skip_echo_len)

        if HF_TOKEN and DATASET_REPOSITORY:
            try:
                now = datetime.datetime.now()
                current_time = now.strftime("%Y-%m-%d %H:%M:%S")
                print(f"[{current_time}] Pushing prompt and completion to the Hub")
                save_inputs_and_outputs(
                    now,
                    prompt,
                    output,
                    {
                        "temperature": temperature,
                        "max_tokens": max_tokens,
                        "repetition_penalty": repetition_penalty,
                    },
                )
            except Exception as e:
                print(e)
        return output, gr.update(interactive=True), gr.update(interactive=True)
    except Exception as e:
        print(e)
        import traceback

        if SLACK_WEBHOOK:
            payload_dic = {
                "text": f"BASE_MODEL: {BASE_MODEL}\n LORA_WEIGHTS: {LORA_WEIGHTS_HF}\n"
                + f"instruction: {instruction}\ninput: {input}\ntemperature: {temperature}\n"
                + f"max_tokens: {max_tokens}\nrepetition_penalty: {repetition_penalty}\n\n"
                + str(traceback.format_exc()),
                "username": "Hugging Face Space",
                "channel": "#monitor",
            }

            try:
                requests.post(SLACK_WEBHOOK, data=json.dumps(payload_dic))
            except Exception:
                pass
        return (
            "Error happend. Please return later.",
            gr.update(interactive=True),
            gr.update(interactive=True),
        )


def reset_textbox():
    return gr.update(value=""), gr.update(value=""), gr.update(value="")


def no_interactive() -> Tuple[gr.Request, gr.Request]:
    return gr.update(interactive=False), gr.update(interactive=False)


title = """<h1 align="center">LLaMA-13B Japanese LoRA</h1>"""

theme = gr.themes.Default(primary_hue="green")
description = (
    "The official demo for **[izumi-lab/llama-13b-japanese-lora-v0-1ep](https://huggingface.co/izumi-lab/llama-13b-japanese-lora-v0-1ep)**.  "
    "It is a 13B-parameter LLaMA model finetuned to follow instructions.  "
    "It is trained on the [izumi-lab/llm-japanese-dataset](https://huggingface.co/datasets/izumi-lab/llm-japanese-dataset) dataset.  "
    "For more information, please visit [the project's website](https://llm.msuzuki.me).  "
    "It takes about **1 minute** to output. When access is concentrated, the operation may become slow."
)
with gr.Blocks(
    css="""#col_container { margin-left: auto; margin-right: auto;}""",
    theme=theme,
) as demo:
    gr.HTML(title)
    gr.Markdown(description)
    with gr.Column(elem_id="col_container", visible=False) as main_block:
        with gr.Row():
            with gr.Column():
                instruction = gr.Textbox(
                    lines=3, label="Instruction", placeholder="ใ“ใ‚“ใซใกใฏ"
                )
                with gr.Row():
                    with gr.Column(scale=3):
                        clear_button = gr.Button("Clear").style(full_width=True)
                    with gr.Column(scale=5):
                        submit_button = gr.Button("Submit").style(full_width=True)
            outputs = gr.Textbox(lines=4, label="Output")

        # inputs, top_p, temperature, top_k, repetition_penalty
        with gr.Accordion("Parameters", open=True):
            temperature = gr.Slider(
                minimum=0,
                maximum=1.0,
                value=0.0,
                step=0.05,
                interactive=True,
                label="Temperature",
            )
            max_tokens = gr.Slider(
                minimum=20,
                maximum=256,
                value=128,
                step=1,
                interactive=True,
                label="Max length (Pre-prompt + instruction + input + output)",
            )
            repetition_penalty = gr.Slider(
                minimum=0.0,
                maximum=5.0,
                value=1.0,
                step=0.1,
                interactive=True,
                label="Repetition penalty",
            )

    with gr.Column(elem_id="user_consent_container") as user_consent_block:
        # Get user consent
        gr.Markdown(
            """
            ## User Consent for Data Collection, Use, and Sharing:
            By using our app, you acknowledge and agree to the following terms regarding the data you provide:

            - **Collection**: We may collect inputs you type into our app.
            - **Use**: We may use the collected data for research purposes, to improve our services, and to develop new products or services, including commercial applications.
            - **Sharing and Publication**: Your input data may be published, shared with third parties, or used for analysis and reporting purposes.
            - **Data Retention**: We may retain your input data for as long as necessary.

            By continuing to use our app, you provide your explicit consent to the collection, use, and potential sharing of your data as described above. If you do not agree with our data collection, use, and sharing practices, please do not use our app.

            Please note that this space utilizes [decapoda-research/llama-13b-hf](https://huggingface.co/decapoda-research/llama-13b-hf) and its special license is applied.

            ## ใƒ‡ใƒผใ‚ฟๅŽ้›†ใ€ๅˆฉ็”จใ€ๅ…ฑๆœ‰ใซ้–ขใ™ใ‚‹ใƒฆใƒผใ‚ถใƒผใฎๅŒๆ„๏ผš
            ๆœฌใ‚ขใƒ—ใƒชใ‚’ไฝฟ็”จใ™ใ‚‹ใ“ใจใซใ‚ˆใ‚Šใ€ๆไพ›ใ™ใ‚‹ใƒ‡ใƒผใ‚ฟใซ้–ขใ™ใ‚‹ไปฅไธ‹ใฎๆกไปถใซๅŒๆ„ใ™ใ‚‹ใ‚‚ใฎใจใ—ใพใ™๏ผš

            - **ๅŽ้›†**: ๆœฌใ‚ขใƒ—ใƒชใซๅ…ฅๅŠ›ใ•ใ‚Œใ‚‹ใƒ†ใ‚ญใ‚นใƒˆใƒ‡ใƒผใ‚ฟใฏๅŽ้›†ใ•ใ‚Œใ‚‹ๅ ดๅˆใŒใ‚ใ‚Šใพใ™ใ€‚
            - **ๅˆฉ็”จ**: ๅŽ้›†ใ•ใ‚ŒใŸใƒ‡ใƒผใ‚ฟใฏ็ ”็ฉถใ‚„ใ€ๅ•†็”จใ‚ขใƒ—ใƒชใ‚ฑใƒผใ‚ทใƒงใƒณใ‚’ๅซใ‚€ใ‚ตใƒผใƒ“ใ‚นใฎ้–‹็™บใซไฝฟ็”จใ•ใ‚Œใ‚‹ๅ ดๅˆใŒใ‚ใ‚Šใพใ™ใ€‚
            - **ๅ…ฑๆœ‰ใŠใ‚ˆใณๅ…ฌ้–‹**: ๅ…ฅๅŠ›ใƒ‡ใƒผใ‚ฟใฏ็ฌฌไธ‰่€…ใจๅ…ฑๆœ‰ใ•ใ‚ŒใŸใ‚Šใ€ๅˆ†ๆžใ‚„ๅ…ฌ้–‹ใฎ็›ฎ็š„ใงไฝฟ็”จใ•ใ‚Œใ‚‹ๅ ดๅˆใŒใ‚ใ‚Šใพใ™ใ€‚
            - **ใƒ‡ใƒผใ‚ฟไฟๆŒ**: ๅ…ฅๅŠ›ใƒ‡ใƒผใ‚ฟใฏๅฟ…่ฆใช้™ใ‚ŠไฟๆŒใ•ใ‚Œใพใ™ใ€‚

            ๆœฌใ‚ขใƒ—ใƒชใ‚’ๅผ•ใ็ถšใไฝฟ็”จใ™ใ‚‹ใ“ใจใซใ‚ˆใ‚Šใ€ไธŠ่จ˜ใฎใ‚ˆใ†ใซใƒ‡ใƒผใ‚ฟใฎๅŽ้›†ใƒปๅˆฉ็”จใƒปๅ…ฑๆœ‰ใซใคใ„ใฆๅŒๆ„ใ—ใพใ™ใ€‚ใƒ‡ใƒผใ‚ฟใฎๅˆฉ็”จๆ–นๆณ•ใซๅŒๆ„ใ—ใชใ„ๅ ดๅˆใฏใ€ๆœฌใ‚ขใƒ—ใƒชใ‚’ไฝฟ็”จใ—ใชใ„ใงใใ ใ•ใ„ใ€‚

            ใชใŠใ€ใ“ใฎใ‚นใƒšใƒผใ‚นใฏ [decapoda-research/llama-13b-hf](https://huggingface.co/decapoda-research/llama-13b-hf) ใ‚’ๅˆฉ็”จใ—ใฆใŠใ‚Šใ€ใใฎใƒฉใ‚คใ‚ปใƒณใ‚นใŒ้ฉ็”จใ•ใ‚Œใพใ™ใ€‚
            """
        )
        accept_button = gr.Button("I Agree")

        def enable_inputs():
            return user_consent_block.update(visible=False), main_block.update(
                visible=True
            )

        accept_button.click(
            fn=enable_inputs,
            inputs=[],
            outputs=[user_consent_block, main_block],
            queue=False,
        )
    submit_button.click(no_interactive, [], [submit_button, clear_button])
    submit_button.click(
        evaluate,
        [instruction, temperature, max_tokens, repetition_penalty],
        [outputs, submit_button, clear_button],
    )
    clear_button.click(reset_textbox, [], [instruction, outputs], queue=False)

    demo.queue(max_size=20, concurrency_count=NUM_THREADS, api_open=False).launch(
        server_name="0.0.0.0", server_port=7860
    )