MakiAi commited on
Commit
13d80e4
1 Parent(s): 2a73da1

🤖 feat: Phi 3.5 Mini Chatbot 実装

Browse files

- Phi-3.5-mini-instruct モデルを使用した、会話型 AI チャットボットを実装しました。
- システムプロンプト、温度、最大トークン数、トップP、トップK、反復ペナルティなどのパラメータ調整機能を追加しました。
- チャット履歴を維持し、チャットのコンテキストを保持できるようにしました。
- グラディオを使用して、ユーザーインターフェースを作成しました。
- デモで使える例をいくつか追加しました。

Files changed (1) hide show
  1. app.py +165 -0
app.py CHANGED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import spaces
4
+ import torch
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, BitsAndBytesConfig
6
+ import gradio as gr
7
+ from threading import Thread
8
+
9
+ MODEL = "microsoft/Phi-3.5-mini-instruct"
10
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
11
+
12
+ TITLE = "<h1><center>Phi 3.5 Mini</center></h1>"
13
+
14
+ PLACEHOLDER = """
15
+ <center>
16
+ <p>Hi, I'm Phi. Ask me anything.</p>
17
+ </center>
18
+ """
19
+
20
+
21
+ CSS = """
22
+ .duplicate-button {
23
+ margin: auto !important;
24
+ color: white !important;
25
+ background: black !important;
26
+ border-radius: 100vh !important;
27
+ }
28
+ h3 {
29
+ text-align: center;
30
+ }
31
+ """
32
+
33
+ device = "cuda" # for GPU usage or "cpu" for CPU usage
34
+
35
+ quantization_config = BitsAndBytesConfig(
36
+ load_in_4bit=True,
37
+ bnb_4bit_compute_dtype=torch.bfloat16,
38
+ bnb_4bit_use_double_quant=True,
39
+ bnb_4bit_quant_type= "nf4")
40
+
41
+ tokenizer = AutoTokenizer.from_pretrained(MODEL)
42
+ model = AutoModelForCausalLM.from_pretrained(
43
+ MODEL,
44
+ torch_dtype=torch.bfloat16,
45
+ device_map="auto",
46
+ quantization_config=quantization_config)
47
+
48
+ @spaces.GPU()
49
+ def stream_chat(
50
+ message: str,
51
+ history: list,
52
+ system_prompt: str,
53
+ temperature: float = 0.8,
54
+ max_new_tokens: int = 1024,
55
+ top_p: float = 1.0,
56
+ top_k: int = 20,
57
+ penalty: float = 1.2,
58
+ ):
59
+ print(f'message: {message}')
60
+ print(f'history: {history}')
61
+
62
+ conversation = [
63
+ {"role": "system", "content": system_prompt}
64
+ ]
65
+ for prompt, answer in history:
66
+ conversation.extend([
67
+ {"role": "user", "content": prompt},
68
+ {"role": "assistant", "content": answer},
69
+ ])
70
+
71
+ conversation.append({"role": "user", "content": message})
72
+
73
+ input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt").to(model.device)
74
+
75
+ streamer = TextIteratorStreamer(tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
76
+
77
+ generate_kwargs = dict(
78
+ input_ids=input_ids,
79
+ max_new_tokens = max_new_tokens,
80
+ do_sample = False if temperature == 0 else True,
81
+ top_p = top_p,
82
+ top_k = top_k,
83
+ temperature = temperature,
84
+ eos_token_id=[128001,128008,128009],
85
+ streamer=streamer,
86
+ )
87
+
88
+ with torch.no_grad():
89
+ thread = Thread(target=model.generate, kwargs=generate_kwargs)
90
+ thread.start()
91
+
92
+ buffer = ""
93
+ for new_text in streamer:
94
+ buffer += new_text
95
+ yield buffer
96
+
97
+
98
+ chatbot = gr.Chatbot(height=600, placeholder=PLACEHOLDER)
99
+
100
+ with gr.Blocks(css=CSS, theme="Nymbo/Nymbo_Theme") as demo:
101
+ gr.HTML(TITLE)
102
+ gr.ChatInterface(
103
+ fn=stream_chat,
104
+ chatbot=chatbot,
105
+ fill_height=True,
106
+ additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
107
+ additional_inputs=[
108
+ gr.Textbox(
109
+ value="You are a helpful assistant",
110
+ label="System Prompt",
111
+ render=False,
112
+ ),
113
+ gr.Slider(
114
+ minimum=0,
115
+ maximum=1,
116
+ step=0.1,
117
+ value=0.8,
118
+ label="Temperature",
119
+ render=False,
120
+ ),
121
+ gr.Slider(
122
+ minimum=128,
123
+ maximum=8192,
124
+ step=1,
125
+ value=1024,
126
+ label="Max new tokens",
127
+ render=False,
128
+ ),
129
+ gr.Slider(
130
+ minimum=0.0,
131
+ maximum=1.0,
132
+ step=0.1,
133
+ value=1.0,
134
+ label="top_p",
135
+ render=False,
136
+ ),
137
+ gr.Slider(
138
+ minimum=1,
139
+ maximum=20,
140
+ step=1,
141
+ value=20,
142
+ label="top_k",
143
+ render=False,
144
+ ),
145
+ gr.Slider(
146
+ minimum=0.0,
147
+ maximum=2.0,
148
+ step=0.1,
149
+ value=1.2,
150
+ label="Repetition penalty",
151
+ render=False,
152
+ ),
153
+ ],
154
+ examples=[
155
+ ["Help me study vocabulary: write a sentence for me to fill in the blank, and I'll try to pick the correct option."],
156
+ ["What are 5 creative things I could do with my kids' art? I don't want to throw them away, but it's also so much clutter."],
157
+ ["Tell me a random fun fact about the Roman Empire."],
158
+ ["Show me a code snippet of a website's sticky header in CSS and JavaScript."],
159
+ ],
160
+ cache_examples=False,
161
+ )
162
+
163
+
164
+ if __name__ == "__main__":
165
+ demo.launch()