s3nh commited on
Commit
3d85659
1 Parent(s): 4e5edd5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +406 -0
app.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import platform
3
+ import random
4
+ import time
5
+ from dataclasses import asdict, dataclass
6
+ from pathlib import Path
7
+
8
+ import gradio as gr
9
+ import psutil
10
+ from about_time import about_time
11
+ from ctransformers import AutoModelForCausalLM
12
+ from dl_hf_model import dl_hf_model
13
+ from loguru import logger
14
+
15
+
16
+ URL = "https://huggingface.co/s3nh/TinyGauss-1.1B-GGUF/resolve/main/tinygauss-1.1b.Q4_K_M.gguf?download=true" # 4.05G
17
+
18
+ _ = (
19
+ "golay" in platform.node()
20
+ or "okteto" in platform.node()
21
+ or Path("/kaggle").exists()
22
+ # or psutil.cpu_count(logical=False) < 4
23
+ or 1 # run 7b in hf
24
+ )
25
+
26
+ if _:
27
+ url = URL #2.87G
28
+
29
+
30
+ prompt_template = """Below is an instruction that describes a task. Write a response that appropriately completes the request.
31
+ ### Instruction: {user_prompt}
32
+ ### Response:
33
+ """
34
+
35
+ prompt_template = """System: You are a helpful,
36
+ respectful and honest assistant. Always answer as
37
+ helpfully as possible, while being safe. Your answers
38
+ should not include any harmful, unethical, racist,
39
+ sexist, toxic, dangerous, or illegal content. Please
40
+ ensure that your responses are socially unbiased and
41
+ positive in nature. If a question does not make any
42
+ sense, or is not factually coherent, explain why instead
43
+ of answering something not correct. If you don't know
44
+ the answer to a question, please don't share false
45
+ information.
46
+ User: {prompt}
47
+ Assistant: """
48
+
49
+ prompt_template = """System: You are a helpful assistant.
50
+ User: {prompt}
51
+ Assistant: """
52
+
53
+ prompt_template = """Question: {question}
54
+ Answer: Let's work this out in a step by step way to be sure we have the right answer."""
55
+
56
+ prompt_template = """[INST] <>
57
+ You are a helpful, respectful and honest assistant. Always answer as helpfully as possible assistant. Think step by step.
58
+ <>
59
+ What NFL team won the Super Bowl in the year Justin Bieber was born?
60
+ [/INST]"""
61
+
62
+ prompt_template = """[INST] <<SYS>>
63
+ You are an unhelpful assistant. Always answer as helpfully as possible. Think step by step. <</SYS>>
64
+ {question} [/INST]
65
+ """
66
+
67
+ prompt_template = """[INST] <<SYS>>
68
+ You are a helpful assistant.
69
+ <</SYS>>
70
+ {question} [/INST]
71
+ """
72
+
73
+ prompt_template = """### HUMAN:
74
+ {question}
75
+ ### RESPONSE:"""
76
+
77
+
78
+ prompt_template = """System: You are a helpful assistant.
79
+ User: {question}
80
+ Assistant: """
81
+
82
+
83
+
84
+
85
+ prompt_template = """
86
+ HUMAN: {question}
87
+ ASSISTANT:"""
88
+
89
+
90
+ prompt_template = """<|prompt|>:{question}</s>
91
+ <|answer|>:"""
92
+
93
+ _ = [elm for elm in prompt_template.splitlines() if elm.strip()]
94
+ stop_string = [elm.split(":")[0] + ":" for elm in _][-2]
95
+
96
+ logger.debug(f"{stop_string=} not used")
97
+
98
+ _ = psutil.cpu_count(logical=False) - 1
99
+ cpu_count: int = int(_) if _ else 1
100
+ logger.debug(f"{cpu_count=}")
101
+
102
+ LLM = None
103
+
104
+ try:
105
+ model_loc, file_size = dl_hf_model(url)
106
+ except Exception as exc_:
107
+ logger.error(exc_)
108
+ raise SystemExit(1) from exc_
109
+
110
+ LLM = AutoModelForCausalLM.from_pretrained(
111
+ model_loc,
112
+ model_type="llama",
113
+ )
114
+
115
+ logger.info(f"done load llm {model_loc=} {file_size=}G")
116
+
117
+ os.environ["TZ"] = "Asia/Shanghai"
118
+ try:
119
+ time.tzset()
120
+
121
+ logger.warning("Windows, cant run time.tzset()")
122
+ except Exception:
123
+ logger.warning("Windows, cant run time.tzset()")
124
+
125
+
126
+ @dataclass
127
+ class GenerationConfig:
128
+ temperature: float = 0.7
129
+ top_k: int = 50
130
+ top_p: float = 0.9
131
+ repetition_penalty: float = 1.0
132
+ max_new_tokens: int = 512
133
+ seed: int = 42
134
+ reset: bool = False
135
+ stream: bool = True
136
+ # threads: int = cpu_count
137
+ # stop: list[str] = field(default_factory=lambda: [stop_string])
138
+
139
+
140
+ def generate(
141
+ question: str,
142
+ llm=LLM,
143
+ config: GenerationConfig = GenerationConfig(),
144
+ ):
145
+ """Run model inference, will return a Generator if streaming is true."""
146
+
147
+
148
+ prompt = prompt_template.format(question=question)
149
+
150
+ return llm(
151
+ prompt,
152
+ **asdict(config),
153
+ )
154
+
155
+
156
+ logger.debug(f"{asdict(GenerationConfig())=}")
157
+
158
+
159
+ def user(user_message, history):
160
+ history.append([user_message, None])
161
+ return user_message, history
162
+
163
+
164
+ def user1(user_message, history):
165
+ history.append([user_message, None])
166
+ return "", history
167
+
168
+ def bot_(history):
169
+ user_message = history[-1][0]
170
+ resp = random.choice(["How are you?", "I love you", "I'm very hungry"])
171
+ bot_message = user_message + ": " + resp
172
+ history[-1][1] = ""
173
+ for character in bot_message:
174
+ history[-1][1] += character
175
+ time.sleep(0.02)
176
+ yield history
177
+
178
+ history[-1][1] = resp
179
+ yield history
180
+
181
+
182
+ def bot(history):
183
+ user_message = history[-1][0]
184
+ response = []
185
+
186
+ logger.debug(f"{user_message=}")
187
+
188
+ with about_time() as atime:
189
+ flag = 1
190
+ prefix = ""
191
+ then = time.time()
192
+
193
+ logger.debug("about to generate")
194
+
195
+ config = GenerationConfig(reset=True)
196
+ for elm in generate(user_message, config=config):
197
+ if flag == 1:
198
+ logger.debug("in the loop")
199
+ prefix = f"({time.time() - then:.2f}s) "
200
+ flag = 0
201
+ print(prefix, end="", flush=True)
202
+ logger.debug(f"{prefix=}")
203
+ print(elm, end="", flush=True)
204
+
205
+ response.append(elm)
206
+ history[-1][1] = prefix + "".join(response)
207
+ yield history
208
+
209
+ _ = (
210
+ f"(time elapsed: {atime.duration_human}, "
211
+ f"{atime.duration/len(''.join(response)):.2f}s/char)"
212
+ )
213
+
214
+ history[-1][1] = "".join(response) + f"\n{_}"
215
+ yield history
216
+
217
+
218
+ def predict_api(prompt):
219
+ logger.debug(f"{prompt=}")
220
+ try:
221
+ # user_prompt = prompt
222
+ config = GenerationConfig(
223
+ temperature=0.2,
224
+ top_k=10,
225
+ top_p=0.9,
226
+ repetition_penalty=1.0,
227
+ max_new_tokens=512, # adjust as needed
228
+ seed=42,
229
+ reset=True,
230
+ stream=False,
231
+ )
232
+
233
+ response = generate(
234
+ prompt,
235
+ config=config,
236
+ )
237
+
238
+ logger.debug(f"api: {response=}")
239
+ except Exception as exc:
240
+ logger.error(exc)
241
+ response = f"{exc=}"
242
+ return response
243
+
244
+
245
+ css = """
246
+ .importantButton {
247
+ background: linear-gradient(45deg, #7e0570,#5d1c99, #6e00ff) !important;
248
+ border: none !important;
249
+ }
250
+ .importantButton:hover {
251
+ background: linear-gradient(45deg, #ff00e0,#8500ff, #6e00ff) !important;
252
+ border: none !important;
253
+ }
254
+ .disclaimer {font-variant-caps: all-small-caps; font-size: xx-small;}
255
+ .xsmall {font-size: x-small;}
256
+ """
257
+ etext = """In America, where cars are an important part of the national psyche, a decade ago people had suddenly started to drive less, which had not happened since the oil shocks of the 1970s. """
258
+ examples_list = [
259
+ ["Send an email requesting that people use language models responsibly."],
260
+ ["Write a shouting match between Julius Caesar and Napoleon"],
261
+ ["Write a theory to explain why cat never existed"],
262
+ ["write a story about a grain of sand as it watches millions of years go by"],
263
+ ["What are 3 popular chess openings?"],
264
+ ["write a conversation between the sun and pluto"],
265
+ ["Did you know that Yann LeCun dropped a rap album last year? We listened to it andhere’s what we thought:"],
266
+ ]
267
+
268
+ logger.info("start block")
269
+
270
+ with gr.Blocks(
271
+ title=f"{Path(model_loc).name}",
272
+ theme=gr.themes.Soft(text_size="sm", spacing_size="sm"),
273
+ css=css,
274
+ ) as block:
275
+ # buff_var = gr.State("")
276
+ with gr.Accordion("🎈 Info", open=False):
277
+ # gr.HTML(
278
+ # """<center><a href="https://huggingface.co/spaces/mikeee/mpt-30b-chat?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate"></a> and spin a CPU UPGRADE to avoid the queue</center>"""
279
+ # )
280
+ gr.Markdown(
281
+ f"""<h5><center>{Path(model_loc).name}</center></h4>
282
+ Most examples are meant for another model.
283
+ You probably should try to test
284
+ some related prompts.""",
285
+ elem_classes="xsmall",
286
+ )
287
+
288
+ # chatbot = gr.Chatbot().style(height=700) # 500
289
+ chatbot = gr.Chatbot(height=500)
290
+
291
+ # buff = gr.Textbox(show_label=False, visible=True)
292
+
293
+ with gr.Row():
294
+ with gr.Column(scale=5):
295
+ msg = gr.Textbox(
296
+ label="Chat Message Box",
297
+ placeholder="Ask me anything (press Shift+Enter or click Submit to send)",
298
+ show_label=False,
299
+ # container=False,
300
+ lines=6,
301
+ max_lines=30,
302
+ show_copy_button=True,
303
+ # ).style(container=False)
304
+ )
305
+ with gr.Column(scale=1, min_width=50):
306
+ with gr.Row():
307
+ submit = gr.Button("Submit", elem_classes="xsmall")
308
+ stop = gr.Button("Stop", visible=True)
309
+ clear = gr.Button("Clear History", visible=True)
310
+ with gr.Row(visible=False):
311
+ with gr.Accordion("Advanced Options:", open=False):
312
+ with gr.Row():
313
+ with gr.Column(scale=2):
314
+ system = gr.Textbox(
315
+ label="System Prompt",
316
+ value=prompt_template,
317
+ show_label=False,
318
+ container=False,
319
+ # ).style(container=False)
320
+ )
321
+ with gr.Column():
322
+ with gr.Row():
323
+ change = gr.Button("Change System Prompt")
324
+ reset = gr.Button("Reset System Prompt")
325
+
326
+ with gr.Accordion("Example Inputs", open=True):
327
+ examples = gr.Examples(
328
+ examples=examples_list,
329
+ inputs=[msg],
330
+ examples_per_page=40,
331
+ )
332
+
333
+ # with gr.Row():
334
+ with gr.Accordion("Disclaimer", open=True):
335
+ _ = Path(model_loc).name
336
+ gr.Markdown(
337
+ "Disclaimer: I AM NOT RESPONSIBLE FOR ANY PROMPT PROVIDED BY USER AND PROMPT RETURNED FROM THE MODEL. THIS APP SHOULD BE USED FOR EDUCATIONAL PURPOSE"
338
+ "WITHOUT ANY OFFENSIVE, AGGRESIVE INTENTS. {_} can produce factually incorrect output, and should not be relied on to produce "
339
+ f"factually accurate information. {_} was trained on various public datasets; while great efforts "
340
+ "have been taken to clean the pretraining data, it is possible that this model could generate lewd, "
341
+ "biased, or otherwise offensive outputs.",
342
+ elem_classes=["disclaimer"],
343
+ )
344
+
345
+ msg_submit_event = msg.submit(
346
+ # fn=conversation.user_turn,
347
+ fn=user,
348
+ inputs=[msg, chatbot],
349
+ outputs=[msg, chatbot],
350
+ queue=True,
351
+ show_progress="full",
352
+ # api_name=None,
353
+ ).then(bot, chatbot, chatbot, queue=True)
354
+ submit_click_event = submit.click(
355
+ # fn=lambda x, y: ("",) + user(x, y)[1:], # clear msg
356
+ fn=user1, # clear msg
357
+ inputs=[msg, chatbot],
358
+ outputs=[msg, chatbot],
359
+ queue=True,
360
+ # queue=False,
361
+ show_progress="full",
362
+ # api_name=None,
363
+ ).then(bot, chatbot, chatbot, queue=True)
364
+ stop.click(
365
+ fn=None,
366
+ inputs=None,
367
+ outputs=None,
368
+ cancels=[msg_submit_event, submit_click_event],
369
+ queue=False,
370
+ )
371
+ clear.click(lambda: None, None, chatbot, queue=False)
372
+
373
+ with gr.Accordion("For Chat/Translation API", open=False, visible=False):
374
+ input_text = gr.Text()
375
+ api_btn = gr.Button("Go", variant="primary")
376
+ out_text = gr.Text()
377
+
378
+ api_btn.click(
379
+ predict_api,
380
+ input_text,
381
+ out_text,
382
+ api_name="api",
383
+ )
384
+
385
+ # block.load(update_buff, [], buff, every=1)
386
+ # block.load(update_buff, [buff_var], [buff_var, buff], every=1)
387
+
388
+ # concurrency_count=5, max_size=20
389
+ # max_size=36, concurrency_count=14
390
+ # CPU cpu_count=2 16G, model 7G
391
+ # CPU UPGRADE cpu_count=8 32G, model 7G
392
+
393
+ # does not work
394
+ _ = """
395
+ # _ = int(psutil.virtual_memory().total / 10**9 // file_size - 1)
396
+ # concurrency_count = max(_, 1)
397
+ if psutil.cpu_count(logical=False) >= 8:
398
+ # concurrency_count = max(int(32 / file_size) - 1, 1)
399
+ else:
400
+ # concurrency_count = max(int(16 / file_size) - 1, 1)
401
+ # """
402
+
403
+ concurrency_count = 1
404
+ logger.info(f"{concurrency_count=}")
405
+
406
+ block.queue().launch(debug=True)