Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
3 |
+
import torch
|
4 |
+
from bitsandbytes.nn import Int8Params, Int8Linear
|
5 |
+
from transformers.utils.quantization_config import BitsAndBytesConfig
|
6 |
+
|
7 |
+
# モデルとトークナイザの読み込み
|
8 |
+
model_name = "Qwen/Qwen2.5-7B-Instruct"
|
9 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
10 |
+
|
11 |
+
# 4bit量子化設定
|
12 |
+
quantization_config = BitsAndBytesConfig(
|
13 |
+
load_in_4bit=True,
|
14 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
15 |
+
bnb_4bit_use_double_quant=True,
|
16 |
+
bnb_4bit_quant_type="nf4"
|
17 |
+
)
|
18 |
+
|
19 |
+
# モデルの読み込みと量子化
|
20 |
+
model = AutoModelForCausalLM.from_pretrained(
|
21 |
+
model_name,
|
22 |
+
device_map="auto",
|
23 |
+
torch_dtype=torch.bfloat16,
|
24 |
+
quantization_config=quantization_config
|
25 |
+
)
|
26 |
+
|
27 |
+
def respond(
|
28 |
+
message,
|
29 |
+
history: list[tuple[str, str]],
|
30 |
+
system_message,
|
31 |
+
max_tokens,
|
32 |
+
temperature,
|
33 |
+
top_p,
|
34 |
+
):
|
35 |
+
# メッセージの準備
|
36 |
+
messages = [{"role": "system", "content": system_message}]
|
37 |
+
|
38 |
+
for val in history:
|
39 |
+
if val[0]:
|
40 |
+
messages.append({"role": "user", "content": val[0]})
|
41 |
+
if val[1]:
|
42 |
+
messages.append({"role": "assistant", "content": val[1]})
|
43 |
+
|
44 |
+
messages.append({"role": "user", "content": message})
|
45 |
+
|
46 |
+
# メッセージをトークナイザに通す
|
47 |
+
input_ids = tokenizer([message], return_tensors="pt").input_ids.to(model.device)
|
48 |
+
|
49 |
+
# モデルの推論
|
50 |
+
output_ids = model.generate(
|
51 |
+
input_ids,
|
52 |
+
max_length=max_tokens,
|
53 |
+
temperature=temperature,
|
54 |
+
top_p=top_p,
|
55 |
+
do_sample=True,
|
56 |
+
)
|
57 |
+
|
58 |
+
response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
59 |
+
response = response[len(message):] # 入力メッセージを削除
|
60 |
+
return response
|
61 |
+
|
62 |
+
# インターフェース
|
63 |
+
demo = gr.ChatInterface(
|
64 |
+
respond,
|
65 |
+
additional_inputs=[
|
66 |
+
gr.Textbox(value="ユーザーの応答と依頼に答えてください。ポジティブに", label="システムメッセージ"),
|
67 |
+
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="新規トークン最大"),
|
68 |
+
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="温度"),
|
69 |
+
gr.Slider(
|
70 |
+
minimum=0.1,
|
71 |
+
maximum=1.0,
|
72 |
+
value=0.95,
|
73 |
+
step=0.05,
|
74 |
+
label="Top-p (核 sampling)",
|
75 |
+
),
|
76 |
+
],
|
77 |
+
concurrency_limit=30 # 例: 同時に4つのリクエストを処理
|
78 |
+
)
|
79 |
+
|
80 |
+
if __name__ == "__main__":
|
81 |
+
demo.launch()
|