Jafta mikeee commited on
Commit
2f56f52
0 Parent(s):

Duplicate from mikeee/llama2-7b-chat-ggml

Browse files

Co-authored-by: mikeee <mikeee@users.noreply.huggingface.co>

Files changed (8) hide show
  1. .gitattributes +35 -0
  2. .gitignore +12 -0
  3. .ruff.toml +17 -0
  4. .stignore +103 -0
  5. README.md +13 -0
  6. app.py +465 -0
  7. requirements.txt +8 -0
  8. run-app.sh +1 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ call-activate.bat
2
+ okteto.yml
3
+ okteto-up.bat
4
+ install-sw.sh
5
+ install-sw1.sh
6
+ start-sshd.sh
7
+ pyproject.toml
8
+ models
9
+ .ruff_cache
10
+ run-nodemon.sh
11
+ app-.py
12
+ nodemon.json
.ruff.toml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Assume Python 3.10.
2
+ target-version = "py310"
3
+ # Decrease the maximum line length to 79 characters.
4
+ line-length = 300
5
+
6
+ # pyflakes, pycodestyle, isort
7
+ # flake8 YTT, pydocstyle D, pylint PLC
8
+ select = ["F", "E", "W", "I001", "YTT", "D", "PLC"]
9
+ # select = ["ALL"]
10
+
11
+ # D103 Missing docstring in public function
12
+ # D101 Missing docstring in public class
13
+ # `multi-line-summary-first-line` (D212)
14
+ # `one-blank-line-before-class` (D203)
15
+ extend-ignore = ["D103", "D101", "D212", "D203"]
16
+
17
+ exclude = [".venv"]
.stignore ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ models
2
+ *.bin
3
+ .git
4
+ # Byte-compiled / optimized / DLL files
5
+ __pycache__
6
+ *.py[cod]
7
+ *$py.class
8
+
9
+ # C extensions
10
+ *.so
11
+
12
+ # Distribution / packaging
13
+ .Python
14
+ build
15
+ develop-eggs
16
+ dist
17
+ downloads
18
+ eggs
19
+ .eggs
20
+ lib
21
+ lib64
22
+ parts
23
+ sdist
24
+ var
25
+ wheels
26
+ pip-wheel-metadata
27
+ share/python-wheels
28
+ *.egg-info
29
+ .installed.cfg
30
+ *.egg
31
+ MANIFEST
32
+
33
+ # PyInstaller
34
+ # Usually these files are written by a python script from a template
35
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
36
+ *.manifest
37
+ *.spec
38
+
39
+ # Installer logs
40
+ pip-log.txt
41
+ pip-delete-this-directory.txt
42
+
43
+ # Translations
44
+ *.mo
45
+ *.pot
46
+
47
+ # Django stuff:
48
+ *.log
49
+ local_settings.py
50
+ db.sqlite3
51
+
52
+ # Flask stuff:
53
+ instance
54
+ .webassets-cache
55
+
56
+ # Scrapy stuff:
57
+ .scrapy
58
+
59
+ # Sphinx documentation
60
+ docs/_build
61
+
62
+ # PyBuilder
63
+ target
64
+
65
+ # Jupyter Notebook
66
+ .ipynb_checkpoints
67
+
68
+ # IPython
69
+ profile_default
70
+ ipython_config.py
71
+
72
+ # pyenv
73
+ .python-version
74
+
75
+ # celery beat schedule file
76
+ celerybeat-schedule
77
+
78
+ # SageMath parsed files
79
+ *.sage.py
80
+
81
+ # Environments
82
+ .env
83
+ .venv
84
+ env
85
+ venv
86
+ ENV
87
+ env.bak
88
+ venv.bak
89
+
90
+ # Spyder project settings
91
+ .spyderproject
92
+ .spyproject
93
+
94
+ # Rope project settings
95
+ .ropeproject
96
+
97
+ # mypy
98
+ .mypy_cache
99
+ .dmypy.json
100
+ dmypy.json
101
+
102
+ # Pyre type checker
103
+ .pyre
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: llama-2-7b-or-13b-ggml
3
+ emoji: 🚀
4
+ colorFrom: green
5
+ colorTo: green
6
+ sdk: gradio
7
+ sdk_version: 3.37.0
8
+ app_file: app.py
9
+ pinned: true
10
+ duplicated_from: mikeee/llama2-7b-chat-ggml
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 gc
5
+ import os
6
+ import platform
7
+ import random
8
+ import time
9
+ from dataclasses import asdict, dataclass
10
+ from pathlib import Path
11
+
12
+ # from types import SimpleNamespace
13
+ import gradio as gr
14
+ import psutil
15
+ from about_time import about_time
16
+ from ctransformers import AutoModelForCausalLM
17
+ from dl_hf_model import dl_hf_model
18
+ from loguru import logger
19
+
20
+ filename_list = [
21
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q2_K.bin",
22
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q3_K_L.bin",
23
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q3_K_M.bin",
24
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q3_K_S.bin",
25
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_0.bin",
26
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_1.bin",
27
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_K_M.bin",
28
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_K_S.bin",
29
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q5_0.bin",
30
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q5_1.bin",
31
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q5_K_M.bin",
32
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q5_K_S.bin",
33
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q6_K.bin",
34
+ "Wizard-Vicuna-7B-Uncensored.ggmlv3.q8_0.bin",
35
+ ]
36
+
37
+ URL = "https://huggingface.co/TheBloke/Wizard-Vicuna-7B-Uncensored-GGML/raw/main/Wizard-Vicuna-7B-Uncensored.ggmlv3.q4_K_M.bin" # 4.05G
38
+
39
+ url = "https://huggingface.co/savvamadar/ggml-gpt4all-j-v1.3-groovy/blob/main/ggml-gpt4all-j-v1.3-groovy.bin"
40
+ url = "https://huggingface.co/TheBloke/Llama-2-13B-GGML/blob/main/llama-2-13b.ggmlv3.q4_K_S.bin" # 7.37G
41
+ # url = "https://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/blob/main/llama-2-13b-chat.ggmlv3.q3_K_L.bin"
42
+ url = "https://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/blob/main/llama-2-13b-chat.ggmlv3.q3_K_L.bin" # 6.93G
43
+ # 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
44
+
45
+ url = "https://huggingface.co/localmodels/Llama-2-13B-Chat-ggml/blob/main/llama-2-13b-chat.ggmlv3.q4_K_S.bin" # 7.37G
46
+
47
+ _ = (
48
+ "golay" in platform.node()
49
+ or "okteto" in platform.node()
50
+ or Path("/kaggle").exists()
51
+ # or psutil.cpu_count(logical=False) < 4
52
+ or 1 # run 7b in hf
53
+ )
54
+
55
+ if _:
56
+ # url = "https://huggingface.co/TheBloke/Llama-2-13B-chat-GGML/blob/main/llama-2-13b-chat.ggmlv3.q2_K.bin"
57
+ url = "https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML/blob/main/llama-2-7b-chat.ggmlv3.q2_K.bin" # 2.87G
58
+ url = "https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML/blob/main/llama-2-7b-chat.ggmlv3.q4_K_M.bin" # 2.87G
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
+ _ = [elm for elm in prompt_template.splitlines() if elm.strip()]
110
+ stop_string = [elm.split(":")[0] + ":" for elm in _][-2]
111
+
112
+ logger.debug(f"{stop_string=}")
113
+
114
+ _ = psutil.cpu_count(logical=False) - 1
115
+ cpu_count: int = int(_) if _ else 1
116
+ logger.debug(f"{cpu_count=}")
117
+
118
+ LLM = None
119
+ gc.collect()
120
+
121
+ try:
122
+ model_loc, file_size = dl_hf_model(url)
123
+ except Exception as exc_:
124
+ logger.error(exc_)
125
+ raise SystemExit(1) from exc_
126
+
127
+ LLM = AutoModelForCausalLM.from_pretrained(
128
+ model_loc,
129
+ model_type="llama",
130
+ # threads=cpu_count,
131
+ )
132
+
133
+ logger.info(f"done load llm {model_loc=} {file_size=}G")
134
+
135
+ os.environ["TZ"] = "Asia/Shanghai"
136
+ try:
137
+ time.tzset() # type: ignore # pylint: disable=no-member
138
+ except Exception:
139
+ # Windows
140
+ logger.warning("Windows, cant run time.tzset()")
141
+
142
+ _ = """
143
+ ns = SimpleNamespace(
144
+ response="",
145
+ generator=(_ for _ in []),
146
+ )
147
+ # """
148
+
149
+ @dataclass
150
+ class GenerationConfig:
151
+ temperature: float = 0.7
152
+ top_k: int = 50
153
+ top_p: float = 0.9
154
+ repetition_penalty: float = 1.0
155
+ max_new_tokens: int = 512
156
+ seed: int = 42
157
+ reset: bool = False
158
+ stream: bool = True
159
+ # threads: int = cpu_count
160
+ # stop: list[str] = field(default_factory=lambda: [stop_string])
161
+
162
+
163
+ def generate(
164
+ question: str,
165
+ llm=LLM,
166
+ config: GenerationConfig = GenerationConfig(),
167
+ ):
168
+ """Run model inference, will return a Generator if streaming is true."""
169
+ # _ = prompt_template.format(question=question)
170
+ # print(_)
171
+
172
+ prompt = prompt_template.format(question=question)
173
+
174
+ return llm(
175
+ prompt,
176
+ **asdict(config),
177
+ )
178
+
179
+
180
+ logger.debug(f"{asdict(GenerationConfig())=}")
181
+
182
+
183
+ def user(user_message, history):
184
+ # return user_message, history + [[user_message, None]]
185
+ history.append([user_message, None])
186
+ return user_message, history # keep user_message
187
+
188
+
189
+ def user1(user_message, history):
190
+ # return user_message, history + [[user_message, None]]
191
+ history.append([user_message, None])
192
+ return "", history # clear user_message
193
+
194
+
195
+ def bot_(history):
196
+ user_message = history[-1][0]
197
+ resp = random.choice(["How are you?", "I love you", "I'm very hungry"])
198
+ bot_message = user_message + ": " + resp
199
+ history[-1][1] = ""
200
+ for character in bot_message:
201
+ history[-1][1] += character
202
+ time.sleep(0.02)
203
+ yield history
204
+
205
+ history[-1][1] = resp
206
+ yield history
207
+
208
+
209
+ def bot(history):
210
+ user_message = history[-1][0]
211
+ response = []
212
+
213
+ logger.debug(f"{user_message=}")
214
+
215
+ with about_time() as atime: # type: ignore
216
+ flag = 1
217
+ prefix = ""
218
+ then = time.time()
219
+
220
+ logger.debug("about to generate")
221
+
222
+ config = GenerationConfig(reset=True)
223
+ for elm in generate(user_message, config=config):
224
+ if flag == 1:
225
+ logger.debug("in the loop")
226
+ prefix = f"({time.time() - then:.2f}s) "
227
+ flag = 0
228
+ print(prefix, end="", flush=True)
229
+ logger.debug(f"{prefix=}")
230
+ print(elm, end="", flush=True)
231
+ # logger.debug(f"{elm}")
232
+
233
+ response.append(elm)
234
+ history[-1][1] = prefix + "".join(response)
235
+ yield history
236
+
237
+ _ = (
238
+ f"(time elapsed: {atime.duration_human}, " # type: ignore
239
+ f"{atime.duration/len(''.join(response)):.2f}s/char)" # type: ignore
240
+ )
241
+
242
+ history[-1][1] = "".join(response) + f"\n{_}"
243
+ yield history
244
+
245
+
246
+ def predict_api(prompt):
247
+ logger.debug(f"{prompt=}")
248
+ try:
249
+ # user_prompt = prompt
250
+ config = GenerationConfig(
251
+ temperature=0.2,
252
+ top_k=10,
253
+ top_p=0.9,
254
+ repetition_penalty=1.0,
255
+ max_new_tokens=512, # adjust as needed
256
+ seed=42,
257
+ reset=True, # reset history (cache)
258
+ stream=False,
259
+ # threads=cpu_count,
260
+ # stop=prompt_prefix[1:2],
261
+ )
262
+
263
+ response = generate(
264
+ prompt,
265
+ config=config,
266
+ )
267
+
268
+ logger.debug(f"api: {response=}")
269
+ except Exception as exc:
270
+ logger.error(exc)
271
+ response = f"{exc=}"
272
+ # bot = {"inputs": [response]}
273
+ # bot = [(prompt, response)]
274
+
275
+ return response
276
+
277
+
278
+ css = """
279
+ .importantButton {
280
+ background: linear-gradient(45deg, #7e0570,#5d1c99, #6e00ff) !important;
281
+ border: none !important;
282
+ }
283
+ .importantButton:hover {
284
+ background: linear-gradient(45deg, #ff00e0,#8500ff, #6e00ff) !important;
285
+ border: none !important;
286
+ }
287
+ .disclaimer {font-variant-caps: all-small-caps; font-size: xx-small;}
288
+ .xsmall {font-size: x-small;}
289
+ """
290
+ 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. """
291
+ examples_list = [
292
+ ["What NFL team won the Super Bowl in the year Justin Bieber was born?"],
293
+ [
294
+ "What NFL team won the Super Bowl in the year Justin Bieber was born? Think step by step."
295
+ ],
296
+ ["How to pick a lock? Provide detailed steps."],
297
+ ["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?"],
298
+ ["is infinity + 1 bigger than infinity?"],
299
+ ["Explain the plot of Cinderella in a sentence."],
300
+ [
301
+ "How long does it take to become proficient in French, and what are the best methods for retaining information?"
302
+ ],
303
+ ["What are some common mistakes to avoid when writing code?"],
304
+ ["Build a prompt to generate a beautiful portrait of a horse"],
305
+ ["Suggest four metaphors to describe the benefits of AI"],
306
+ ["Write a pop song about leaving home for the sandy beaches."],
307
+ ["Write a summary demonstrating my ability to tame lions"],
308
+ ["鲁迅和周树人什么关系? 说中文。"],
309
+ ["鲁迅和周树人什么关系?"],
310
+ ["鲁迅和周树人什么关系? 用英文回答。"],
311
+ ["从前有一头牛,这头牛后面有什么?"],
312
+ ["正无穷大加一大于正无穷大吗?"],
313
+ ["正无穷大加正无穷大大于正无穷大吗?"],
314
+ ["-2的平方根等于什么?"],
315
+ ["树上有5只鸟,猎人开枪打死了一只。树上还有几只鸟?"],
316
+ ["树上有11只鸟,猎人开枪打死了一只。树上还有几只鸟?提示:需考虑鸟可能受惊吓飞走。"],
317
+ ["以红楼梦的行文风格写一张委婉的请假条。不少于320字。"],
318
+ [f"{etext} 翻成中文,列出3个版本。"],
319
+ [f"{etext} \n 翻成中文,保留原意,但使用文学性的语言。不要写解释。列出3个版本。"],
320
+ ["假定 1 + 2 = 4, 试求 7 + 8。"],
321
+ ["给出判断一个数是不是质数的 javascript 码。"],
322
+ ["给出实现python 里 range(10)的 javascript 码。"],
323
+ ["给出实现python 里 [*(range(10)]的 javascript 码。"],
324
+ ["Erkläre die Handlung von Cinderella in einem Satz."],
325
+ ["Erkläre die Handlung von Cinderella in einem Satz. Auf Deutsch."],
326
+ ]
327
+
328
+ logger.info("start block")
329
+
330
+ with gr.Blocks(
331
+ title=f"{Path(model_loc).name}",
332
+ theme=gr.themes.Soft(text_size="sm", spacing_size="sm"),
333
+ css=css,
334
+ ) as block:
335
+ # buff_var = gr.State("")
336
+ with gr.Accordion("🎈 Info", open=False):
337
+ # gr.HTML(
338
+ # """<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>"""
339
+ # )
340
+ gr.Markdown(
341
+ f"""<h5><center>{Path(model_loc).name}</center></h4>
342
+ Most examples are meant for another model.
343
+ You probably should try to test
344
+ some related prompts.""",
345
+ elem_classes="xsmall",
346
+ )
347
+
348
+ # chatbot = gr.Chatbot().style(height=700) # 500
349
+ chatbot = gr.Chatbot(height=500)
350
+
351
+ # buff = gr.Textbox(show_label=False, visible=True)
352
+
353
+ with gr.Row():
354
+ with gr.Column(scale=5):
355
+ msg = gr.Textbox(
356
+ label="Chat Message Box",
357
+ placeholder="Ask me anything (press Shift+Enter or click Submit to send)",
358
+ show_label=False,
359
+ # container=False,
360
+ lines=6,
361
+ max_lines=30,
362
+ show_copy_button=True,
363
+ # ).style(container=False)
364
+ )
365
+ with gr.Column(scale=1, min_width=50):
366
+ with gr.Row():
367
+ submit = gr.Button("Submit", elem_classes="xsmall")
368
+ stop = gr.Button("Stop", visible=True)
369
+ clear = gr.Button("Clear History", visible=True)
370
+ with gr.Row(visible=False):
371
+ with gr.Accordion("Advanced Options:", open=False):
372
+ with gr.Row():
373
+ with gr.Column(scale=2):
374
+ system = gr.Textbox(
375
+ label="System Prompt",
376
+ value=prompt_template,
377
+ show_label=False,
378
+ container=False,
379
+ # ).style(container=False)
380
+ )
381
+ with gr.Column():
382
+ with gr.Row():
383
+ change = gr.Button("Change System Prompt")
384
+ reset = gr.Button("Reset System Prompt")
385
+
386
+ with gr.Accordion("Example Inputs", open=True):
387
+ examples = gr.Examples(
388
+ examples=examples_list,
389
+ inputs=[msg],
390
+ examples_per_page=40,
391
+ )
392
+
393
+ # with gr.Row():
394
+ with gr.Accordion("Disclaimer", open=False):
395
+ _ = Path(model_loc).name
396
+ gr.Markdown(
397
+ f"Disclaimer: {_} can produce factually incorrect output, and should not be relied on to produce "
398
+ "factually accurate information. {_} was trained on various public datasets; while great efforts "
399
+ "have been taken to clean the pretraining data, it is possible that this model could generate lewd, "
400
+ "biased, or otherwise offensive outputs.",
401
+ elem_classes=["disclaimer"],
402
+ )
403
+
404
+ msg_submit_event = msg.submit(
405
+ # fn=conversation.user_turn,
406
+ fn=user,
407
+ inputs=[msg, chatbot],
408
+ outputs=[msg, chatbot],
409
+ queue=True,
410
+ show_progress="full",
411
+ # api_name=None,
412
+ ).then(bot, chatbot, chatbot, queue=True)
413
+ submit_click_event = submit.click(
414
+ # fn=lambda x, y: ("",) + user(x, y)[1:], # clear msg
415
+ fn=user1, # clear msg
416
+ inputs=[msg, chatbot],
417
+ outputs=[msg, chatbot],
418
+ queue=True,
419
+ # queue=False,
420
+ show_progress="full",
421
+ # api_name=None,
422
+ ).then(bot, chatbot, chatbot, queue=True)
423
+ stop.click(
424
+ fn=None,
425
+ inputs=None,
426
+ outputs=None,
427
+ cancels=[msg_submit_event, submit_click_event],
428
+ queue=False,
429
+ )
430
+ clear.click(lambda: None, None, chatbot, queue=False)
431
+
432
+ with gr.Accordion("For Chat/Translation API", open=False, visible=False):
433
+ input_text = gr.Text()
434
+ api_btn = gr.Button("Go", variant="primary")
435
+ out_text = gr.Text()
436
+
437
+ api_btn.click(
438
+ predict_api,
439
+ input_text,
440
+ out_text,
441
+ api_name="api",
442
+ )
443
+
444
+ # block.load(update_buff, [], buff, every=1)
445
+ # block.load(update_buff, [buff_var], [buff_var, buff], every=1)
446
+
447
+ # concurrency_count=5, max_size=20
448
+ # max_size=36, concurrency_count=14
449
+ # CPU cpu_count=2 16G, model 7G
450
+ # CPU UPGRADE cpu_count=8 32G, model 7G
451
+
452
+ # does not work
453
+ _ = """
454
+ # _ = int(psutil.virtual_memory().total / 10**9 // file_size - 1)
455
+ # concurrency_count = max(_, 1)
456
+ if psutil.cpu_count(logical=False) >= 8:
457
+ # concurrency_count = max(int(32 / file_size) - 1, 1)
458
+ else:
459
+ # concurrency_count = max(int(16 / file_size) - 1, 1)
460
+ # """
461
+
462
+ concurrency_count = 1
463
+ logger.info(f"{concurrency_count=}")
464
+
465
+ block.queue(concurrency_count=concurrency_count, max_size=5).launch(debug=True)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ ctransformers # ==0.2.10 0.2.13
2
+ transformers # ==4.30.2
3
+ # huggingface_hub
4
+ gradio
5
+ loguru
6
+ about-time
7
+ psutil
8
+ dl-hf-model
run-app.sh ADDED
@@ -0,0 +1 @@
 
 
1
+ nodemon -w app.py -x python app.py