hysts HF staff commited on
Commit
c86c2f3
1 Parent(s): 5ced0c7
Files changed (10) hide show
  1. .pre-commit-config.yaml +36 -0
  2. .style.yapf +5 -0
  3. .vscode/settings.json +18 -0
  4. LICENSE +21 -0
  5. README.md +2 -1
  6. app.py +222 -0
  7. model.py +59 -0
  8. requirements.txt +8 -0
  9. settings.py +8 -0
  10. style.css +16 -0
.pre-commit-config.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v4.2.0
4
+ hooks:
5
+ - id: check-executables-have-shebangs
6
+ - id: check-json
7
+ - id: check-merge-conflict
8
+ - id: check-shebang-scripts-are-executable
9
+ - id: check-toml
10
+ - id: check-yaml
11
+ - id: double-quote-string-fixer
12
+ - id: end-of-file-fixer
13
+ - id: mixed-line-ending
14
+ args: ['--fix=lf']
15
+ - id: requirements-txt-fixer
16
+ - id: trailing-whitespace
17
+ - repo: https://github.com/myint/docformatter
18
+ rev: v1.4
19
+ hooks:
20
+ - id: docformatter
21
+ args: ['--in-place']
22
+ - repo: https://github.com/pycqa/isort
23
+ rev: 5.12.0
24
+ hooks:
25
+ - id: isort
26
+ - repo: https://github.com/pre-commit/mirrors-mypy
27
+ rev: v0.991
28
+ hooks:
29
+ - id: mypy
30
+ args: ['--ignore-missing-imports']
31
+ additional_dependencies: ['types-python-slugify']
32
+ - repo: https://github.com/google/yapf
33
+ rev: v0.32.0
34
+ hooks:
35
+ - id: yapf
36
+ args: ['--parallel', '--in-place']
.style.yapf ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [style]
2
+ based_on_style = pep8
3
+ blank_line_before_nested_class_or_def = false
4
+ spaces_before_comment = 2
5
+ split_before_logical_operator = true
.vscode/settings.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "python.linting.enabled": true,
3
+ "python.linting.flake8Enabled": true,
4
+ "python.linting.pylintEnabled": false,
5
+ "python.linting.lintOnSave": true,
6
+ "python.formatting.provider": "yapf",
7
+ "python.formatting.yapfArgs": [
8
+ "--style={based_on_style: pep8, indent_width: 4, blank_line_before_nested_class_or_def: false, spaces_before_comment: 2, split_before_logical_operator: true}"
9
+ ],
10
+ "[python]": {
11
+ "editor.formatOnType": true,
12
+ "editor.codeActionsOnSave": {
13
+ "source.organizeImports": true
14
+ }
15
+ },
16
+ "editor.formatOnSave": true,
17
+ "files.insertFinalNewline": true
18
+ }
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 hysts
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Llama 2 7b Chat
3
  emoji: 🏆
4
  colorFrom: purple
5
  colorTo: gray
@@ -7,6 +7,7 @@ sdk: gradio
7
  sdk_version: 3.37.0
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Llama 2 7B Chat
3
  emoji: 🏆
4
  colorFrom: purple
5
  colorTo: gray
 
7
  sdk_version: 3.37.0
8
  app_file: app.py
9
  pinned: false
10
+ suggested_hardware: t4-small
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+ from typing import Iterator
5
+
6
+ import gradio as gr
7
+ import torch
8
+
9
+ from model import run
10
+ from settings import (ALLOW_CHANGING_SYSTEM_PROMPT, DEFAULT_MAX_NEW_TOKENS,
11
+ DEFAULT_SYSTEM_PROMPT, MAX_MAX_NEW_TOKENS)
12
+
13
+ DESCRIPTION = '# Llama-2 7B chat'
14
+ if not torch.cuda.is_available():
15
+ DESCRIPTION += '\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>'
16
+
17
+
18
+ def clear_and_save_textbox(message: str) -> tuple[str, str]:
19
+ return '', message
20
+
21
+
22
+ def display_input(message: str,
23
+ history: list[tuple[str, str]]) -> list[tuple[str, str]]:
24
+ history.append((message, ''))
25
+ return history
26
+
27
+
28
+ def delete_prev_fn(
29
+ history: list[tuple[str, str]]) -> tuple[list[tuple[str, str]], str]:
30
+ try:
31
+ message, _ = history.pop()
32
+ except IndexError:
33
+ message = ''
34
+ return history, message or ''
35
+
36
+
37
+ def fn(
38
+ message: str,
39
+ history_with_input: list[tuple[str, str]],
40
+ system_prompt: str,
41
+ max_new_tokens: int,
42
+ top_p: float,
43
+ temperature: float,
44
+ top_k: int,
45
+ ) -> Iterator[list[tuple[str, str]]]:
46
+ if max_new_tokens > MAX_MAX_NEW_TOKENS:
47
+ raise ValueError
48
+
49
+ history = history_with_input[:-1]
50
+ generator = run(message, history, system_prompt, max_new_tokens,
51
+ temperature, top_p, top_k)
52
+ try:
53
+ first_response = next(generator)
54
+ yield history + [(message, first_response)]
55
+ except StopIteration:
56
+ yield history + [(message, '')]
57
+ for response in generator:
58
+ yield history + [(message, response)]
59
+
60
+
61
+ with gr.Blocks(css='style.css') as demo:
62
+ gr.Markdown(DESCRIPTION)
63
+ gr.DuplicateButton(value='Duplicate Space for private use',
64
+ elem_id='duplicate-button',
65
+ visible=os.getenv('SHOW_DUPLICATE_BUTTON') == '1')
66
+
67
+ with gr.Group():
68
+ chatbot = gr.Chatbot(label='Chatbot')
69
+ with gr.Row():
70
+ textbox = gr.Textbox(
71
+ container=False,
72
+ show_label=False,
73
+ placeholder='Type a message...',
74
+ scale=10,
75
+ )
76
+ submit_button = gr.Button('Submit',
77
+ variant='primary',
78
+ scale=1,
79
+ min_width=0)
80
+ with gr.Row():
81
+ retry_button = gr.Button('🔄 Retry', variant='secondary')
82
+ undo_button = gr.Button('↩️ Undo', variant='secondary')
83
+ clear_button = gr.Button('🗑️ Clear', variant='secondary')
84
+
85
+ saved_input = gr.State()
86
+
87
+ with gr.Accordion(label='Advanced options', open=False):
88
+ system_prompt = gr.Textbox(label='System prompt',
89
+ value=DEFAULT_SYSTEM_PROMPT,
90
+ lines=6,
91
+ interactive=ALLOW_CHANGING_SYSTEM_PROMPT)
92
+ max_new_tokens = gr.Slider(
93
+ label='Max new tokens',
94
+ minimum=1,
95
+ maximum=MAX_MAX_NEW_TOKENS,
96
+ step=1,
97
+ value=DEFAULT_MAX_NEW_TOKENS,
98
+ )
99
+ temperature = gr.Slider(
100
+ label='Temperature',
101
+ minimum=0.1,
102
+ maximum=5.0,
103
+ step=0.1,
104
+ value=0.8,
105
+ )
106
+ top_p = gr.Slider(
107
+ label='Top-p (nucleus sampling)',
108
+ minimum=0.05,
109
+ maximum=1.0,
110
+ step=0.05,
111
+ value=0.95,
112
+ )
113
+ top_k = gr.Slider(
114
+ label='Top-k',
115
+ minimum=1,
116
+ maximum=50,
117
+ step=1,
118
+ value=50,
119
+ )
120
+
121
+ textbox.submit(
122
+ fn=clear_and_save_textbox,
123
+ inputs=textbox,
124
+ outputs=[textbox, saved_input],
125
+ api_name=False,
126
+ queue=False,
127
+ ).then(
128
+ fn=display_input,
129
+ inputs=[saved_input, chatbot],
130
+ outputs=chatbot,
131
+ api_name=False,
132
+ queue=False,
133
+ ).then(
134
+ fn=fn,
135
+ inputs=[
136
+ saved_input,
137
+ chatbot,
138
+ system_prompt,
139
+ max_new_tokens,
140
+ temperature,
141
+ top_p,
142
+ top_k,
143
+ ],
144
+ outputs=chatbot,
145
+ api_name=False,
146
+ )
147
+
148
+ button_event_preprocess = submit_button.click(
149
+ fn=clear_and_save_textbox,
150
+ inputs=textbox,
151
+ outputs=[textbox, saved_input],
152
+ api_name=False,
153
+ queue=False,
154
+ ).then(
155
+ fn=display_input,
156
+ inputs=[saved_input, chatbot],
157
+ outputs=chatbot,
158
+ api_name=False,
159
+ queue=False,
160
+ ).then(
161
+ fn=fn,
162
+ inputs=[
163
+ saved_input,
164
+ chatbot,
165
+ system_prompt,
166
+ max_new_tokens,
167
+ temperature,
168
+ top_p,
169
+ top_k,
170
+ ],
171
+ outputs=chatbot,
172
+ api_name=False,
173
+ )
174
+
175
+ retry_button.click(
176
+ fn=delete_prev_fn,
177
+ inputs=chatbot,
178
+ outputs=[chatbot, saved_input],
179
+ api_name=False,
180
+ queue=False,
181
+ ).then(
182
+ fn=display_input,
183
+ inputs=[saved_input, chatbot],
184
+ outputs=chatbot,
185
+ api_name=False,
186
+ queue=False,
187
+ ).then(
188
+ fn=fn,
189
+ inputs=[
190
+ saved_input,
191
+ chatbot,
192
+ max_new_tokens,
193
+ temperature,
194
+ top_p,
195
+ top_k,
196
+ ],
197
+ outputs=chatbot,
198
+ api_name=False,
199
+ )
200
+
201
+ undo_button.click(
202
+ fn=delete_prev_fn,
203
+ inputs=chatbot,
204
+ outputs=[chatbot, saved_input],
205
+ api_name=False,
206
+ queue=False,
207
+ ).then(
208
+ fn=lambda x: x,
209
+ inputs=[saved_input],
210
+ outputs=textbox,
211
+ api_name=False,
212
+ queue=False,
213
+ )
214
+
215
+ clear_button.click(
216
+ fn=lambda: ([], ''),
217
+ outputs=[chatbot, saved_input],
218
+ queue=False,
219
+ api_name=False,
220
+ )
221
+
222
+ demo.queue(max_size=20).launch()
model.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from threading import Thread
2
+ from typing import Iterator
3
+
4
+ import torch
5
+ from transformers import (AutoModelForCausalLM, AutoTokenizer,
6
+ TextIteratorStreamer)
7
+
8
+ model_id = 'meta-llama/Llama-2-7b-chat-hf'
9
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
10
+
11
+ if device.type == 'cuda':
12
+ model = AutoModelForCausalLM.from_pretrained(model_id,
13
+ load_in_8bit=True,
14
+ device_map='auto')
15
+ else:
16
+ model = None
17
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
18
+
19
+
20
+ def get_prompt(message: str, chat_history: list[tuple[str, str]],
21
+ system_prompt: str) -> str:
22
+ texts = [f'[INST] <<SYS>>\n{system_prompt}\n<</SYS>>\n\n']
23
+ for user_input, response in chat_history:
24
+ texts.append(f'{user_input} [/INST] {response} [INST] ')
25
+ texts.append(f'{message.strip()} [/INST]')
26
+ return ''.join(texts)
27
+
28
+
29
+ def run(message: str,
30
+ chat_history: list[tuple[str, str]],
31
+ system_prompt: str,
32
+ max_new_tokens: int = 1024,
33
+ temperature: float = 0.8,
34
+ top_p: float = 0.95,
35
+ top_k: int = 50) -> Iterator[str]:
36
+ prompt = get_prompt(message, chat_history, system_prompt)
37
+ inputs = tokenizer([prompt], return_tensors='pt').to(device)
38
+
39
+ streamer = TextIteratorStreamer(tokenizer,
40
+ timeout=10.,
41
+ skip_prompt=True,
42
+ skip_special_tokens=True)
43
+ generate_kwargs = dict(
44
+ inputs,
45
+ streamer=streamer,
46
+ max_new_tokens=max_new_tokens,
47
+ do_sample=True,
48
+ top_p=top_p,
49
+ top_k=top_k,
50
+ temperature=temperature,
51
+ num_beams=1,
52
+ )
53
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
54
+ t.start()
55
+
56
+ outputs = []
57
+ for text in streamer:
58
+ outputs.append(text)
59
+ yield ''.join(outputs)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.21.0
2
+ bitsandbytes==0.40.2
3
+ gradio==3.37.0
4
+ protobuf==3.20.3
5
+ scipy==1.11.1
6
+ sentencepiece==0.1.99
7
+ torch==2.0.1
8
+ transformers==4.31.0
settings.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ DEFAULT_SYSTEM_PROMPT = "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."
4
+ ALLOW_CHANGING_SYSTEM_PROMPT = os.getenv('ALLOW_CHANGING_SYSTEM_PROMPT',
5
+ '0') == '1'
6
+
7
+ MAX_MAX_NEW_TOKENS = int(os.getenv('MAX_MAX_NEW_TOKENS', '1024'))
8
+ DEFAULT_MAX_NEW_TOKENS = int(os.getenv('DEFAULT_MAX_NEW_TOKENS', '256'))
style.css ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ h1 {
2
+ text-align: center;
3
+ }
4
+
5
+ #duplicate-button {
6
+ margin: auto;
7
+ color: white;
8
+ background: #1565c0;
9
+ border-radius: 100vh;
10
+ }
11
+
12
+ #component-0 {
13
+ max-width: 900px;
14
+ margin: auto;
15
+ padding-top: 1.5rem;
16
+ }