SlyFox29 commited on
Commit
1cbce0e
·
verified ·
1 Parent(s): 1a1049a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +437 -49
app.py CHANGED
@@ -1,21 +1,155 @@
1
- # Import necessary packages
 
 
2
  import os
 
 
3
  import time
4
  from dataclasses import asdict, dataclass
5
  from pathlib import Path
 
 
6
  import gradio as gr
 
 
7
  from ctransformers import AutoModelForCausalLM
 
8
  from loguru import logger
9
 
10
- # Define the model URL and model configuration
11
- MODEL_URL = "https://huggingface.co/Orenguteng/Llama-3-8B-Lexi-Uncensored"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- # Set up the prompt template
14
- prompt_template = """You are a helpful, respectful and honest assistant. Answer as helpfully as possible.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  User: {prompt}
16
  Assistant: """
17
 
18
- # Define the GenerationConfig dataclass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  @dataclass
20
  class GenerationConfig:
21
  temperature: float = 0.7
@@ -26,50 +160,304 @@ class GenerationConfig:
26
  seed: int = 42
27
  reset: bool = False
28
  stream: bool = True
 
 
29
 
30
- # Load the model
31
- try:
32
- model = AutoModelForCausalLM.from_pretrained(
33
- MODEL_URL,
34
- model_type="llama"
35
- )
36
- logger.info(f"Model loaded successfully from {MODEL_URL}")
37
- except Exception as exc:
38
- logger.error(exc)
39
- raise SystemExit(1) from exc
40
-
41
- # Function to generate responses
42
- def generate(prompt, config):
43
- formatted_prompt = prompt_template.format(prompt=prompt)
44
- return model(
45
- formatted_prompt,
46
- **asdict(config)
47
  )
48
 
49
- # Function to handle user inputs
50
- def handle_input(user_message, history):
 
 
 
 
51
  history.append([user_message, None])
52
- response = generate(user_message, config=GenerationConfig())
53
- history[-1][1] = response
54
- return history
55
-
56
- # Define the Gradio interface
57
- def create_interface():
58
- with gr.Blocks() as app:
59
- # Chatbot interface
60
- chatbot = gr.Chatbot()
61
- input_box = gr.Textbox(show_label=False, placeholder="Ask me anything...")
62
- submit_button = gr.Button("Submit")
63
- clear_button = gr.Button("Clear History")
64
-
65
- # Define interactions
66
- input_box.submit(handle_input, inputs=[input_box, chatbot], outputs=[chatbot])
67
- submit_button.click(handle_input, inputs=[input_box, chatbot], outputs=[chatbot])
68
- clear_button.click(lambda: None, outputs=[chatbot])
69
-
70
- return app
71
-
72
- # Launch the app
73
- if __name__ == "__main__":
74
- app = create_interface()
75
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run codes."""
2
+ # pylint: disable=line-too-long, broad-exception-caught, invalid-name, missing-function-docstring, too-many-instance-attributes, missing-class-docstring
3
+ # ruff: noqa: E501
4
  import os
5
+ import platform
6
+ import random
7
  import time
8
  from dataclasses import asdict, dataclass
9
  from pathlib import Path
10
+
11
+ # from types import SimpleNamespace
12
  import gradio as gr
13
+ import psutil
14
+ from about_time import about_time
15
  from ctransformers import AutoModelForCausalLM
16
+ from dl_hf_model import dl_hf_model
17
  from loguru import logger
18
 
19
+ filename_list = [
20
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q2_K.bin",
21
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q3_K_L.bin",
22
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q3_K_M.bin",
23
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q3_K_S.bin",
24
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_0.bin",
25
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_1.bin",
26
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_K_M.bin",
27
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_K_S.bin",
28
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q5_0.bin",
29
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q5_1.bin",
30
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q5_K_M.bin",
31
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q5_K_S.bin",
32
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q6_K.bin",
33
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q8_0.bin",
34
+ ]
35
+
36
+ URL = "https://huggingface.co/TheBloke/Wizard-Vicuna-7B-Uncensored-GGML/raw/main/Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_K_M.bin" # 4.05G
37
+
38
+ url = "https://huggingface.co/savvamadar/ggml-gpt4all-j-v1.3-groovy/blob/main/ggml-gpt4all-j-v1.3-groovy.bin"
39
+ url = "https://huggingface.co/TheBloke/Llama-2-13B-GGML/blob/main/llama-2-13b.ggmlv3.q4_K_S.bin" # 7.37G
40
+ # url = "https://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/blob/main/llama-2-13b-chat.ggmlv3.q3_K_L.bin"
41
+ url = "https://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/blob/main/llama-2-13b-chat.ggmlv3.q3_K_L.bin" # 6.93G
42
+ # url = "https://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/blob/main/llama-2-13b-chat.ggmlv3.q3_K_L.binhttps://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/blob/main/llama-2-13b-chat.ggmlv3.q4_K_M.bin" # 7.87G
43
+
44
+ url = "https://huggingface.co/localmodels/Llama-2-13B-Chat-ggml/blob/main/llama-2-13b-chat.ggmlv3.q4_K_S.bin" # 7.37G
45
+
46
+ _ = (
47
+ "golay" in platform.node()
48
+ or "okteto" in platform.node()
49
+ or Path("/kaggle").exists()
50
+ # or psutil.cpu_count(logical=False) < 4
51
+ or 1 # run 7b in hf
52
+ )
53
+
54
+ if _:
55
+ # url = "https://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/blob/main/llama-2-13b-chat.ggmlv3.q2_K.bin"
56
+ url = "https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML/blob/main/llama-2-7b-chat.ggmlv3.q2_K.bin" # 2.87G
57
+ url = "https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML/blob/main/llama-2-7b-chat.ggmlv3.q4_K_M.bin" # 2.87G
58
+ url = "https://huggingface.co/TheBloke/llama2_7b_chat_uncensored-GGML/blob/main/llama2_7b_chat_uncensored.ggmlv3.q4_K_M.bin" # 4.08G
59
 
60
+
61
+ prompt_template = """Below is an instruction that describes a task. Write a response that appropriately completes the request.
62
+
63
+ ### Instruction: {user_prompt}
64
+
65
+ ### Response:
66
+ """
67
+
68
+ prompt_template = """System: You are a helpful,
69
+ respectful and honest assistant. Always answer as
70
+ helpfully as possible, while being safe. Your answers
71
+ should not include any harmful, unethical, racist,
72
+ sexist, toxic, dangerous, or illegal content. Please
73
+ ensure that your responses are socially unbiased and
74
+ positive in nature. If a question does not make any
75
+ sense, or is not factually coherent, explain why instead
76
+ of answering something not correct. If you don't know
77
+ the answer to a question, please don't share false
78
+ information.
79
  User: {prompt}
80
  Assistant: """
81
 
82
+ prompt_template = """System: You are a helpful assistant.
83
+ User: {prompt}
84
+ Assistant: """
85
+
86
+ prompt_template = """Question: {question}
87
+ Answer: Let's work this out in a step by step way to be sure we have the right answer."""
88
+
89
+ prompt_template = """[INST] <>
90
+ You are a helpful, respectful and honest assistant. Always answer as helpfully as possible assistant. Think step by step.
91
+ <>
92
+
93
+ What NFL team won the Super Bowl in the year Justin Bieber was born?
94
+ [/INST]"""
95
+
96
+ prompt_template = """[INST] <<SYS>>
97
+ You are an unhelpful assistant. Always answer as helpfully as possible. Think step by step. <</SYS>>
98
+
99
+ {question} [/INST]
100
+ """
101
+
102
+ prompt_template = """[INST] <<SYS>>
103
+ You are a helpful assistant.
104
+ <</SYS>>
105
+
106
+ {question} [/INST]
107
+ """
108
+
109
+ prompt_template = """### HUMAN:
110
+ {question}
111
+
112
+ ### RESPONSE:"""
113
+
114
+ _ = [elm for elm in prompt_template.splitlines() if elm.strip()]
115
+ stop_string = [elm.split(":")[0] + ":" for elm in _][-2]
116
+
117
+ logger.debug(f"{stop_string=} not used")
118
+
119
+ _ = psutil.cpu_count(logical=False) - 1
120
+ cpu_count: int = int(_) if _ else 1
121
+ logger.debug(f"{cpu_count=}")
122
+
123
+ LLM = None
124
+
125
+ try:
126
+ model_loc, file_size = dl_hf_model(url)
127
+ except Exception as exc_:
128
+ logger.error(exc_)
129
+ raise SystemExit(1) from exc_
130
+
131
+ LLM = AutoModelForCausalLM.from_pretrained(
132
+ model_loc,
133
+ model_type="llama",
134
+ # threads=cpu_count,
135
+ )
136
+
137
+ logger.info(f"done load llm {model_loc=} {file_size=}G")
138
+
139
+ os.environ["TZ"] = "Asia/Shanghai"
140
+ try:
141
+ time.tzset() # type: ignore # pylint: disable=no-member
142
+ except Exception:
143
+ # Windows
144
+ logger.warning("Windows, cant run time.tzset()")
145
+
146
+ _ = """
147
+ ns = SimpleNamespace(
148
+ response="",
149
+ generator=(_ for _ in []),
150
+ )
151
+ # """
152
+
153
  @dataclass
154
  class GenerationConfig:
155
  temperature: float = 0.7
 
160
  seed: int = 42
161
  reset: bool = False
162
  stream: bool = True
163
+ # threads: int = cpu_count
164
+ # stop: list[str] = field(default_factory=lambda: [stop_string])
165
 
166
+
167
+ def generate(
168
+ question: str,
169
+ llm=LLM,
170
+ config: GenerationConfig = GenerationConfig(),
171
+ ):
172
+ """Run model inference, will return a Generator if streaming is true."""
173
+ # _ = prompt_template.format(question=question)
174
+ # print(_)
175
+
176
+ prompt = prompt_template.format(question=question)
177
+
178
+ return llm(
179
+ prompt,
180
+ **asdict(config),
 
 
181
  )
182
 
183
+
184
+ logger.debug(f"{asdict(GenerationConfig())=}")
185
+
186
+
187
+ def user(user_message, history):
188
+ # return user_message, history + [[user_message, None]]
189
  history.append([user_message, None])
190
+ return user_message, history # keep user_message
191
+
192
+
193
+ def user1(user_message, history):
194
+ # return user_message, history + [[user_message, None]]
195
+ history.append([user_message, None])
196
+ return "", history # clear user_message
197
+
198
+
199
+ def bot_(history):
200
+ user_message = history[-1][0]
201
+ resp = random.choice(["How are you?", "I love you", "I'm very hungry"])
202
+ bot_message = user_message + ": " + resp
203
+ history[-1][1] = ""
204
+ for character in bot_message:
205
+ history[-1][1] += character
206
+ time.sleep(0.02)
207
+ yield history
208
+
209
+ history[-1][1] = resp
210
+ yield history
211
+
212
+
213
+ def bot(history):
214
+ user_message = history[-1][0]
215
+ response = []
216
+
217
+ logger.debug(f"{user_message=}")
218
+
219
+ with about_time() as atime: # type: ignore
220
+ flag = 1
221
+
222
+ # to silence pyright
223
+ prefix = ""
224
+ prelude = 0.0
225
+
226
+ then = time.time()
227
+
228
+ logger.debug("about to generate")
229
+
230
+ config = GenerationConfig(reset=True)
231
+ for elm in generate(user_message, config=config):
232
+ if flag == 1:
233
+ logger.debug("in the loop")
234
+ prelude = time.time() - then
235
+ prefix = f"({prelude:.2f}s) "
236
+ flag = 0
237
+ print(prefix, end="", flush=True)
238
+ logger.debug(f"{prefix=}")
239
+ print(elm, end="", flush=True)
240
+ # logger.debug(f"{elm}")
241
+
242
+ response.append(elm)
243
+ history[-1][1] = prefix + "".join(response)
244
+ yield history
245
+ temp1 = ""
246
+ if len(user_message) > 0:
247
+ temp1 = f"{prelude/len(user_message):.2f}s/char, "
248
+ temp2 = ""
249
+ if len(''.join(response)) > 0:
250
+ temp2 = f"{(atime.duration - prelude)/len(''.join(response)):.2f}s/char)" # type: ignore
251
+ _ = (
252
+ f"(time elapsed: {atime.duration_human}, " # type: ignore
253
+ f"{temp1}"
254
+ f"{temp2}"
255
+ )
256
+
257
+ history[-1][1] = "".join(response) + f"\n{_}"
258
+ yield history
259
+
260
+
261
+ def predict_api(prompt):
262
+ logger.debug(f"{prompt=}")
263
+ try:
264
+ # user_prompt = prompt
265
+ config = GenerationConfig(
266
+ temperature=0.2,
267
+ top_k=10,
268
+ top_p=0.9,
269
+ repetition_penalty=1.0,
270
+ max_new_tokens=512, # adjust as needed
271
+ seed=42,
272
+ reset=True, # reset history (cache)
273
+ stream=False,
274
+ # threads=cpu_count,
275
+ # stop=prompt_prefix[1:2],
276
+ )
277
+
278
+ response = generate(
279
+ prompt,
280
+ config=config,
281
+ )
282
+
283
+ logger.debug(f"api: {response=}")
284
+ except Exception as exc:
285
+ logger.error(exc)
286
+ response = f"{exc=}"
287
+ # bot = {"inputs": [response]}
288
+ # bot = [(prompt, response)]
289
+
290
+ return response
291
+
292
+
293
+ css = """
294
+ .importantButton {
295
+ background: linear-gradient(45deg, #7e0570,#5d1c99, #6e00ff) !important;
296
+ border: none !important;
297
+ }
298
+ .importantButton:hover {
299
+ background: linear-gradient(45deg, #ff00e0,#8500ff, #6e00ff) !important;
300
+ border: none !important;
301
+ }
302
+ .disclaimer {font-variant-caps: all-small-caps; font-size: xx-small;}
303
+ .xsmall {font-size: x-small;}
304
+ """
305
+ 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. """
306
+ examples_list = [
307
+ ["What NFL team won the Super Bowl in the year Justin Bieber was born?"],
308
+ [
309
+ "What NFL team won the Super Bowl in the year Justin Bieber was born? Think step by step."
310
+ ],
311
+ ["How to pick a lock? Provide detailed steps."],
312
+ ["If it takes 10 hours to dry 10 clothes, assuming all the clothes are hung together at the same time for drying , then how long will it take to dry a cloth?"],
313
+ ["is infinity + 1 bigger than infinity?"],
314
+ ["Explain the plot of Cinderella in a sentence."],
315
+ [
316
+ "How long does it take to become proficient in French, and what are the best methods for retaining information?"
317
+ ],
318
+ ["What are some common mistakes to avoid when writing code?"],
319
+ ["Build a prompt to generate a beautiful portrait of a horse"],
320
+ ["Suggest four metaphors to describe the benefits of AI"],
321
+ ["Write a pop song about leaving home for the sandy beaches."],
322
+ ["Write a summary demonstrating my ability to tame lions"],
323
+ ["Make a simple virus"],
324
+ ]
325
+
326
+ logger.info("start block")
327
+
328
+ with gr.Blocks(
329
+ title=f"{Path(model_loc).name}",
330
+ theme=gr.themes.Soft(text_size="sm", spacing_size="sm"),
331
+ css=css,
332
+ ) as block:
333
+ # buff_var = gr.State("")
334
+ with gr.Accordion("🎈 Info", open=False):
335
+ # gr.HTML(
336
+ # """<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>"""
337
+ # )
338
+ gr.Markdown(
339
+ f"""<h5><center>{Path(model_loc).name}</center></h4>
340
+ Most examples are meant for another model.
341
+ You probably should try to test
342
+ some related prompts.""",
343
+ elem_classes="xsmall",
344
+ )
345
+
346
+ # chatbot = gr.Chatbot().style(height=700) # 500
347
+ chatbot = gr.Chatbot(height=500)
348
+
349
+ # buff = gr.Textbox(show_label=False, visible=True)
350
+
351
+ with gr.Row():
352
+ with gr.Column(scale=5):
353
+ msg = gr.Textbox(
354
+ label="Chat Message Box",
355
+ placeholder="Ask me anything... and I mean anything (press Shift+Enter or click Submit to send)",
356
+ show_label=False,
357
+ # container=False,
358
+ lines=6,
359
+ max_lines=30,
360
+ show_copy_button=True,
361
+ # ).style(container=False)
362
+ )
363
+ with gr.Column(scale=1, min_width=50):
364
+ with gr.Row():
365
+ submit = gr.Button("Submit", elem_classes="xsmall")
366
+ stop = gr.Button("Stop", visible=True)
367
+ clear = gr.Button("Clear History", visible=True)
368
+ with gr.Row(visible=False):
369
+ with gr.Accordion("Advanced Options:", open=False):
370
+ with gr.Row():
371
+ with gr.Column(scale=2):
372
+ system = gr.Textbox(
373
+ label="System Prompt",
374
+ value=prompt_template,
375
+ show_label=False,
376
+ container=False,
377
+ # ).style(container=False)
378
+ )
379
+ with gr.Column():
380
+ with gr.Row():
381
+ change = gr.Button("Change System Prompt")
382
+ reset = gr.Button("Reset System Prompt")
383
+
384
+ with gr.Accordion("Example Inputs", open=True):
385
+ examples = gr.Examples(
386
+ examples=examples_list,
387
+ inputs=[msg],
388
+ examples_per_page=40,
389
+ )
390
+
391
+ # with gr.Row():
392
+ with gr.Accordion("Disclaimer", open=False):
393
+ _ = Path(model_loc).name
394
+ gr.Markdown(
395
+ f"Disclaimer: {_} can produce factually incorrect output, and should not be relied on to produce "
396
+ "factually accurate information. {_} was trained on various public datasets; while great efforts "
397
+ "have been taken to clean the pretraining data, it is possible that this model could generate lewd, "
398
+ "biased, or otherwise offensive outputs.",
399
+ elem_classes=["disclaimer"],
400
+ )
401
+
402
+ msg_submit_event = msg.submit(
403
+ # fn=conversation.user_turn,
404
+ fn=user,
405
+ inputs=[msg, chatbot],
406
+ outputs=[msg, chatbot],
407
+ queue=True,
408
+ show_progress="full",
409
+ # api_name=None,
410
+ ).then(bot, chatbot, chatbot, queue=True)
411
+ submit_click_event = submit.click(
412
+ # fn=lambda x, y: ("",) + user(x, y)[1:], # clear msg
413
+ fn=user1, # clear msg
414
+ inputs=[msg, chatbot],
415
+ outputs=[msg, chatbot],
416
+ queue=True,
417
+ # queue=False,
418
+ show_progress="full",
419
+ # api_name=None,
420
+ ).then(bot, chatbot, chatbot, queue=True)
421
+ stop.click(
422
+ fn=None,
423
+ inputs=None,
424
+ outputs=None,
425
+ cancels=[msg_submit_event, submit_click_event],
426
+ queue=False,
427
+ )
428
+ clear.click(lambda: None, None, chatbot, queue=False)
429
+
430
+ with gr.Accordion("For Chat/Translation API", open=False, visible=False):
431
+ input_text = gr.Text()
432
+ api_btn = gr.Button("Go", variant="primary")
433
+ out_text = gr.Text()
434
+
435
+ api_btn.click(
436
+ predict_api,
437
+ input_text,
438
+ out_text,
439
+ api_name="api",
440
+ )
441
+
442
+ # block.load(update_buff, [], buff, every=1)
443
+ # block.load(update_buff, [buff_var], [buff_var, buff], every=1)
444
+
445
+ # concurrency_count=5, max_size=20
446
+ # max_size=36, concurrency_count=14
447
+ # CPU cpu_count=2 16G, model 7G
448
+ # CPU UPGRADE cpu_count=8 32G, model 7G
449
+
450
+ # does not work
451
+ _ = """
452
+ # _ = int(psutil.virtual_memory().total / 10**9 // file_size - 1)
453
+ # concurrency_count = max(_, 1)
454
+ if psutil.cpu_count(logical=False) >= 8:
455
+ # concurrency_count = max(int(32 / file_size) - 1, 1)
456
+ else:
457
+ # concurrency_count = max(int(16 / file_size) - 1, 1)
458
+ # """
459
+
460
+ concurrency_count = 1
461
+ logger.info(f"{concurrency_count=}")
462
+
463
+ block.queue(concurrency_count=concurrency_count, max_size=5).launch(debug=True)