Jailautner Luigi commited on
Commit
7f5cabe
·
0 Parent(s):

Duplicate from Luigi/Taiwan-LLaMa-13b-v1.0-chat.ggmlv3

Browse files

Co-authored-by: Luigi LIU <[email protected]>

Files changed (9) hide show
  1. .gitattributes +35 -0
  2. LICENSE.txt +126 -0
  3. README.md +22 -0
  4. USE_POLICY.md +50 -0
  5. app.py +270 -0
  6. conversation.py +274 -0
  7. model.py +72 -0
  8. requirements.txt +9 -0
  9. style.css +16 -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
LICENSE.txt ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LLAMA 2 COMMUNITY LICENSE AGREEMENT
2
+ Llama 2 Version Release Date: July 18, 2023
3
+
4
+ "Agreement" means the terms and conditions for use, reproduction, distribution and
5
+ modification of the Llama Materials set forth herein.
6
+
7
+ "Documentation" means the specifications, manuals and documentation
8
+ accompanying Llama 2 distributed by Meta at ai.meta.com/resources/models-and-
9
+ libraries/llama-downloads/.
10
+
11
+ "Licensee" or "you" means you, or your employer or any other person or entity (if
12
+ you are entering into this Agreement on such person or entity's behalf), of the age
13
+ required under applicable laws, rules or regulations to provide legal consent and that
14
+ has legal authority to bind your employer or such other person or entity if you are
15
+ entering in this Agreement on their behalf.
16
+
17
+ "Llama 2" means the foundational large language models and software and
18
+ algorithms, including machine-learning model code, trained model weights,
19
+ inference-enabling code, training-enabling code, fine-tuning enabling code and other
20
+ elements of the foregoing distributed by Meta at ai.meta.com/resources/models-and-
21
+ libraries/llama-downloads/.
22
+
23
+ "Llama Materials" means, collectively, Meta's proprietary Llama 2 and
24
+ Documentation (and any portion thereof) made available under this Agreement.
25
+
26
+ "Meta" or "we" means Meta Platforms Ireland Limited (if you are located in or, if you
27
+ are an entity, your principal place of business is in the EEA or Switzerland) and Meta
28
+ Platforms, Inc. (if you are located outside of the EEA or Switzerland).
29
+
30
+ By clicking "I Accept" below or by using or distributing any portion or element of the
31
+ Llama Materials, you agree to be bound by this Agreement.
32
+
33
+ 1. License Rights and Redistribution.
34
+
35
+ a. Grant of Rights. You are granted a non-exclusive, worldwide, non-
36
+ transferable and royalty-free limited license under Meta's intellectual property or
37
+ other rights owned by Meta embodied in the Llama Materials to use, reproduce,
38
+ distribute, copy, create derivative works of, and make modifications to the Llama
39
+ Materials.
40
+
41
+ b. Redistribution and Use.
42
+
43
+ i. If you distribute or make the Llama Materials, or any derivative works
44
+ thereof, available to a third party, you shall provide a copy of this Agreement to such
45
+ third party.
46
+ ii. If you receive Llama Materials, or any derivative works thereof, from
47
+ a Licensee as part of an integrated end user product, then Section 2 of this
48
+ Agreement will not apply to you.
49
+
50
+ iii. You must retain in all copies of the Llama Materials that you
51
+ distribute the following attribution notice within a "Notice" text file distributed as a
52
+ part of such copies: "Llama 2 is licensed under the LLAMA 2 Community License,
53
+ Copyright (c) Meta Platforms, Inc. All Rights Reserved."
54
+
55
+ iv. Your use of the Llama Materials must comply with applicable laws
56
+ and regulations (including trade compliance laws and regulations) and adhere to the
57
+ Acceptable Use Policy for the Llama Materials (available at
58
+ https://ai.meta.com/llama/use-policy), which is hereby incorporated by reference into
59
+ this Agreement.
60
+
61
+ v. You will not use the Llama Materials or any output or results of the
62
+ Llama Materials to improve any other large language model (excluding Llama 2 or
63
+ derivative works thereof).
64
+
65
+ 2. Additional Commercial Terms. If, on the Llama 2 version release date, the
66
+ monthly active users of the products or services made available by or for Licensee,
67
+ or Licensee's affiliates, is greater than 700 million monthly active users in the
68
+ preceding calendar month, you must request a license from Meta, which Meta may
69
+ grant to you in its sole discretion, and you are not authorized to exercise any of the
70
+ rights under this Agreement unless or until Meta otherwise expressly grants you
71
+ such rights.
72
+
73
+ 3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE
74
+ LLAMA MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE
75
+ PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
76
+ EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY
77
+ WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR
78
+ FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE
79
+ FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING
80
+ THE LLAMA MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR
81
+ USE OF THE LLAMA MATERIALS AND ANY OUTPUT AND RESULTS.
82
+
83
+ 4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE
84
+ LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT,
85
+ NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS
86
+ AGREEMENT, FOR ANY LOST PROFITS OR ANY INDIRECT, SPECIAL,
87
+ CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN
88
+ IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF
89
+ ANY OF THE FOREGOING.
90
+
91
+ 5. Intellectual Property.
92
+
93
+ a. No trademark licenses are granted under this Agreement, and in
94
+ connection with the Llama Materials, neither Meta nor Licensee may use any name
95
+ or mark owned by or associated with the other or any of its affiliates, except as
96
+ required for reasonable and customary use in describing and redistributing the
97
+ Llama Materials.
98
+
99
+ b. Subject to Meta's ownership of Llama Materials and derivatives made by or
100
+ for Meta, with respect to any derivative works and modifications of the Llama
101
+ Materials that are made by you, as between you and Meta, you are and will be the
102
+ owner of such derivative works and modifications.
103
+
104
+ c. If you institute litigation or other proceedings against Meta or any entity
105
+ (including a cross-claim or counterclaim in a lawsuit) alleging that the Llama
106
+ Materials or Llama 2 outputs or results, or any portion of any of the foregoing,
107
+ constitutes infringement of intellectual property or other rights owned or licensable
108
+ by you, then any licenses granted to you under this Agreement shall terminate as of
109
+ the date such litigation or claim is filed or instituted. You will indemnify and hold
110
+ harmless Meta from and against any claim by any third party arising out of or related
111
+ to your use or distribution of the Llama Materials.
112
+
113
+ 6. Term and Termination. The term of this Agreement will commence upon your
114
+ acceptance of this Agreement or access to the Llama Materials and will continue in
115
+ full force and effect until terminated in accordance with the terms and conditions
116
+ herein. Meta may terminate this Agreement if you are in breach of any term or
117
+ condition of this Agreement. Upon termination of this Agreement, you shall delete
118
+ and cease use of the Llama Materials. Sections 3, 4 and 7 shall survive the
119
+ termination of this Agreement.
120
+
121
+ 7. Governing Law and Jurisdiction. This Agreement will be governed and
122
+ construed under the laws of the State of California without regard to choice of law
123
+ principles, and the UN Convention on Contracts for the International Sale of Goods
124
+ does not apply to this Agreement. The courts of California shall have exclusive
125
+ jurisdiction of any dispute arising out of this Agreement.
126
+
README.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: llama-2-13b-chat.ggmlv3.q4_K_S
3
+ emoji: 🏆
4
+ colorFrom: purple
5
+ colorTo: gray
6
+ sdk: gradio
7
+ sdk_version: 3.37.0
8
+ app_file: app.py
9
+ pinned: false
10
+ suggested_hardware: a10g-small
11
+ duplicated_from: Luigi/Taiwan-LLaMa-13b-v1.0-chat.ggmlv3
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
15
+
16
+ # LLAMA v2 Models
17
+
18
+ Llama v2 was introduced in [this paper](https://arxiv.org/abs/2307.09288).
19
+
20
+ This Space demonstrates [Llama-2-7b-chat-hf](https://huggingface.co/spaces/huggingface-projects/llama-2-13b-chat/blob/main/meta-llama/Llama-2-7b-chat-hf) from Meta. Please, check the original model card for details.
21
+
22
+
USE_POLICY.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Llama 2 Acceptable Use Policy
2
+
3
+ Meta is committed to promoting safe and fair use of its tools and features, including Llama 2. If you access or use Llama 2, you agree to this Acceptable Use Policy (“Policy”). The most recent copy of this policy can be found at [ai.meta.com/llama/use-policy](http://ai.meta.com/llama/use-policy).
4
+
5
+ ## Prohibited Uses
6
+ We want everyone to use Llama 2 safely and responsibly. You agree you will not use, or allow others to use, Llama 2 to:
7
+
8
+ 1. Violate the law or others’ rights, including to:
9
+ 1. Engage in, promote, generate, contribute to, encourage, plan, incite, or further illegal or unlawful activity or content, such as:
10
+ 1. Violence or terrorism
11
+ 2. Exploitation or harm to children, including the solicitation, creation, acquisition, or dissemination of child exploitative content or failure to report Child Sexual Abuse Material
12
+ 3. Human trafficking, exploitation, and sexual violence
13
+ 4. The illegal distribution of information or materials to minors, including obscene materials, or failure to employ legally required age-gating in connection with such information or materials.
14
+ 5. Sexual solicitation
15
+ 6. Any other criminal activity
16
+ 2. Engage in, promote, incite, or facilitate the harassment, abuse, threatening, or bullying of individuals or groups of individuals
17
+ 3. Engage in, promote, incite, or facilitate discrimination or other unlawful or harmful conduct in the provision of employment, employment benefits, credit, housing, other economic benefits, or other essential goods and services
18
+ 4. Engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or related professional practices
19
+ 5. Collect, process, disclose, generate, or infer health, demographic, or other sensitive personal or private information about individuals without rights and consents required by applicable laws
20
+ 6. Engage in or facilitate any action or generate any content that infringes, misappropriates, or otherwise violates any third-party rights, including the outputs or results of any products or services using the Llama 2 Materials
21
+ 7. Create, generate, or facilitate the creation of malicious code, malware, computer viruses or do anything else that could disable, overburden, interfere with or impair the proper working, integrity, operation or appearance of a website or computer system
22
+
23
+
24
+
25
+ 2. Engage in, promote, incite, facilitate, or assist in the planning or development of activities that present a risk of death or bodily harm to individuals, including use of Llama 2 related to the following:
26
+ 1. Military, warfare, nuclear industries or applications, espionage, use for materials or activities that are subject to the International Traffic Arms Regulations (ITAR) maintained by the United States Department of State
27
+ 2. Guns and illegal weapons (including weapon development)
28
+ 3. Illegal drugs and regulated/controlled substances
29
+ 4. Operation of critical infrastructure, transportation technologies, or heavy machinery
30
+ 5. Self-harm or harm to others, including suicide, cutting, and eating disorders
31
+ 6. Any content intended to incite or promote violence, abuse, or any infliction of bodily harm to an individual
32
+
33
+
34
+
35
+ 3. Intentionally deceive or mislead others, including use of Llama 2 related to the following:
36
+ 1. Generating, promoting, or furthering fraud or the creation or promotion of disinformation
37
+ 2. Generating, promoting, or furthering defamatory content, including the creation of defamatory statements, images, or other content
38
+ 3. Generating, promoting, or further distributing spam
39
+ 4. Impersonating another individual without consent, authorization, or legal right
40
+ 5. Representing that the use of Llama 2 or outputs are human-generated
41
+ 6. Generating or facilitating false online engagement, including fake reviews and other means of fake online engagement
42
+ 4. Fail to appropriately disclose to end users any known dangers of your AI system
43
+
44
+ Please report any violation of this Policy, software “bug,” or other problems that could lead to a violation of this Policy through one of the following means:
45
+
46
+ * Reporting issues with the model: [github.com/facebookresearch/llama](http://github.com/facebookresearch/llama)
47
+ * Reporting risky content generated by the model: [developers.facebook.com/llama_output_feedback](http://developers.facebook.com/llama_output_feedback)
48
+ * Reporting bugs and security concerns: [facebook.com/whitehat/info](http://facebook.com/whitehat/info)
49
+ * Reporting violations of the Acceptable Use Policy or unlicensed uses of Llama: [[email protected]](mailto:[email protected])
50
+
app.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Iterator
2
+
3
+ import gradio as gr
4
+ import torch
5
+
6
+ from model import get_input_token_length, run
7
+
8
+ DEFAULT_SYSTEM_PROMPT = """A chat between a curious user and a AI telephone assistant. The assistant gives helpful answers in less than 30 tokens to the user's questions. You are built by NTU Miulab by Yen-Ting Lin for research purpose."""
9
+ MAX_MAX_NEW_TOKENS = 2048
10
+ DEFAULT_MAX_NEW_TOKENS = 1024
11
+ MAX_INPUT_TOKEN_LENGTH = 4000
12
+
13
+ DESCRIPTION = """
14
+ # Taiwan-LLaMa-13b-1.0.ggmlv3
15
+ """
16
+
17
+ LICENSE = """
18
+ <p/>
19
+
20
+ ---
21
+ [Llama-2-13b-chat](https://huggingface.co/meta-llama/Llama-2-13b-chat) by Meta).
22
+ """
23
+
24
+ if not torch.cuda.is_available():
25
+ DESCRIPTION += '\n<p>Running on CPU 🥶 This demo does not work on GPU.</p>'
26
+
27
+ def clear_and_save_textbox(message: str) -> tuple[str, str]:
28
+ return '', message
29
+
30
+
31
+ def display_input(message: str,
32
+ history: list[tuple[str, str]]) -> list[tuple[str, str]]:
33
+ history.append((message, ''))
34
+ return history
35
+
36
+
37
+ def delete_prev_fn(
38
+ history: list[tuple[str, str]]) -> tuple[list[tuple[str, str]], str]:
39
+ try:
40
+ message, _ = history.pop()
41
+ except IndexError:
42
+ message = ''
43
+ return history, message or ''
44
+
45
+
46
+ def generate(
47
+ message: str,
48
+ history_with_input: list[tuple[str, str]],
49
+ system_prompt: str,
50
+ max_new_tokens: int,
51
+ temperature: float,
52
+ top_p: float,
53
+ top_k: int,
54
+ ) -> Iterator[list[tuple[str, str]]]:
55
+ if max_new_tokens > MAX_MAX_NEW_TOKENS:
56
+ raise ValueError
57
+
58
+ history = history_with_input[:-1]
59
+ generator = run(message, history, system_prompt, max_new_tokens, temperature, top_p, top_k)
60
+ try:
61
+ first_response = next(generator)
62
+ yield history + [(message, first_response)]
63
+ except StopIteration:
64
+ yield history + [(message, '')]
65
+ for response in generator:
66
+ yield history + [(message, response)]
67
+
68
+
69
+ def process_example(message: str) -> tuple[str, list[tuple[str, str]]]:
70
+ generator = generate(message, [], DEFAULT_SYSTEM_PROMPT, 1024, 1, 0.95, 50)
71
+ for x in generator:
72
+ pass
73
+ return '', x
74
+
75
+
76
+ def check_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> None:
77
+ input_token_length = get_input_token_length(message, chat_history, system_prompt)
78
+ if input_token_length > MAX_INPUT_TOKEN_LENGTH:
79
+ raise gr.Error(f'The accumulated input is too long ({input_token_length} > {MAX_INPUT_TOKEN_LENGTH}). Clear your chat history and try again.')
80
+
81
+
82
+ with gr.Blocks(css='style.css') as demo:
83
+ gr.Markdown(DESCRIPTION)
84
+ gr.DuplicateButton(value='Duplicate Space for private use',
85
+ elem_id='duplicate-button')
86
+
87
+ with gr.Group():
88
+ chatbot = gr.Chatbot(label='Chatbot')
89
+ with gr.Row():
90
+ textbox = gr.Textbox(
91
+ container=False,
92
+ show_label=False,
93
+ placeholder='Type a message...',
94
+ scale=10,
95
+ )
96
+ submit_button = gr.Button('Submit',
97
+ variant='primary',
98
+ scale=1,
99
+ min_width=0)
100
+ with gr.Row():
101
+ retry_button = gr.Button('🔄 Retry', variant='secondary')
102
+ undo_button = gr.Button('↩️ Undo', variant='secondary')
103
+ clear_button = gr.Button('🗑️ Clear', variant='secondary')
104
+
105
+ saved_input = gr.State()
106
+
107
+ with gr.Accordion(label='Advanced options', open=False):
108
+ system_prompt = gr.Textbox(label='System prompt',
109
+ value=DEFAULT_SYSTEM_PROMPT,
110
+ lines=6)
111
+ max_new_tokens = gr.Slider(
112
+ label='Max new tokens',
113
+ minimum=1,
114
+ maximum=MAX_MAX_NEW_TOKENS,
115
+ step=1,
116
+ value=DEFAULT_MAX_NEW_TOKENS,
117
+ )
118
+ temperature = gr.Slider(
119
+ label='Temperature',
120
+ minimum=0.1,
121
+ maximum=4.0,
122
+ step=0.1,
123
+ value=0.1,
124
+ )
125
+ top_p = gr.Slider(
126
+ label='Top-p (nucleus sampling)',
127
+ minimum=0.05,
128
+ maximum=1.0,
129
+ step=0.05,
130
+ value=0.9,
131
+ )
132
+ top_k = gr.Slider(
133
+ label='Top-k',
134
+ minimum=1,
135
+ maximum=1000,
136
+ step=1,
137
+ value=50,
138
+ )
139
+
140
+ gr.Examples(
141
+ examples=[
142
+ '以惡地景觀著名的是高雄哪一個景點?',
143
+ '唐鳳是誰?',
144
+ 'NTU 在哪?',
145
+ '甚麼是22K?',
146
+ '肉圓要不要加香菜?',
147
+ ],
148
+ inputs=textbox,
149
+ outputs=[textbox, chatbot],
150
+ fn=process_example,
151
+ cache_examples=True,
152
+ )
153
+
154
+ gr.Markdown(LICENSE)
155
+
156
+ textbox.submit(
157
+ fn=clear_and_save_textbox,
158
+ inputs=textbox,
159
+ outputs=[textbox, saved_input],
160
+ api_name=False,
161
+ queue=False,
162
+ ).then(
163
+ fn=display_input,
164
+ inputs=[saved_input, chatbot],
165
+ outputs=chatbot,
166
+ api_name=False,
167
+ queue=False,
168
+ ).then(
169
+ fn=check_input_token_length,
170
+ inputs=[saved_input, chatbot, system_prompt],
171
+ api_name=False,
172
+ queue=False,
173
+ ).success(
174
+ fn=generate,
175
+ inputs=[
176
+ saved_input,
177
+ chatbot,
178
+ system_prompt,
179
+ max_new_tokens,
180
+ temperature,
181
+ top_p,
182
+ top_k,
183
+ ],
184
+ outputs=chatbot,
185
+ api_name=False,
186
+ )
187
+
188
+ button_event_preprocess = submit_button.click(
189
+ fn=clear_and_save_textbox,
190
+ inputs=textbox,
191
+ outputs=[textbox, saved_input],
192
+ api_name="submit",
193
+ # api_name=False,
194
+ queue=False,
195
+ ).then(
196
+ fn=display_input,
197
+ inputs=[saved_input, chatbot],
198
+ outputs=chatbot,
199
+ api_name=False,
200
+ queue=False,
201
+ ).then(
202
+ fn=check_input_token_length,
203
+ inputs=[saved_input, chatbot, system_prompt],
204
+ api_name=False,
205
+ queue=False,
206
+ ).success(
207
+ fn=generate,
208
+ inputs=[
209
+ saved_input,
210
+ chatbot,
211
+ system_prompt,
212
+ max_new_tokens,
213
+ temperature,
214
+ top_p,
215
+ top_k,
216
+ ],
217
+ outputs=chatbot,
218
+ api_name=False,
219
+ )
220
+
221
+ retry_button.click(
222
+ fn=delete_prev_fn,
223
+ inputs=chatbot,
224
+ outputs=[chatbot, saved_input],
225
+ api_name=False,
226
+ queue=False,
227
+ ).then(
228
+ fn=display_input,
229
+ inputs=[saved_input, chatbot],
230
+ outputs=chatbot,
231
+ api_name=False,
232
+ queue=False,
233
+ ).then(
234
+ fn=generate,
235
+ inputs=[
236
+ saved_input,
237
+ chatbot,
238
+ system_prompt,
239
+ max_new_tokens,
240
+ temperature,
241
+ top_p,
242
+ top_k,
243
+ ],
244
+ outputs=chatbot,
245
+ api_name=False,
246
+ )
247
+
248
+ undo_button.click(
249
+
250
+ fn=delete_prev_fn,
251
+ inputs=chatbot,
252
+ outputs=[chatbot, saved_input],
253
+ api_name=False,
254
+ queue=False,
255
+ ).then(
256
+ fn=lambda x: x,
257
+ inputs=[saved_input],
258
+ outputs=textbox,
259
+ api_name=False,
260
+ queue=False,
261
+ )
262
+
263
+ clear_button.click(
264
+ fn=lambda: ([], ''),
265
+ outputs=[chatbot, saved_input],
266
+ queue=False,
267
+ api_name=False,
268
+ )
269
+
270
+ demo.queue(max_size=20).launch()
conversation.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Cloned from
2
+ # https://huggingface.co/spaces/yentinglin/Taiwan-LLaMa2/raw/main/conversation.py
3
+
4
+ """
5
+ Conversation prompt template.
6
+ Now we support
7
+ - Vicuna
8
+ - Koala
9
+ - OpenAssistant/oasst-sft-1-pythia-12b
10
+ - StabilityAI/stablelm-tuned-alpha-7b
11
+ - databricks/dolly-v2-12b
12
+ - THUDM/chatglm-6b
13
+ - Alpaca/LLaMa
14
+ """
15
+
16
+ import dataclasses
17
+ from enum import auto, Enum
18
+ from typing import List, Tuple, Any
19
+
20
+
21
+ class SeparatorStyle(Enum):
22
+ """Different separator style."""
23
+
24
+ SINGLE = auto()
25
+ TWO = auto()
26
+ DOLLY = auto()
27
+ OASST_PYTHIA = auto()
28
+
29
+
30
+ @dataclasses.dataclass
31
+ class Conversation:
32
+ """A class that keeps all conversation history."""
33
+
34
+ system: str
35
+ roles: List[str]
36
+ messages: List[List[str]]
37
+ offset: int
38
+ sep_style: SeparatorStyle = SeparatorStyle.SINGLE
39
+ sep: str = "###"
40
+ sep2: str = None
41
+
42
+ # Used for gradio server
43
+ skip_next: bool = False
44
+ conv_id: Any = None
45
+
46
+ def get_prompt(self):
47
+ if self.sep_style == SeparatorStyle.SINGLE:
48
+ ret = self.system
49
+ for role, message in self.messages:
50
+ if message:
51
+ ret += self.sep + " " + role + ": " + message
52
+ else:
53
+ ret += self.sep + " " + role + ":"
54
+ return ret
55
+ elif self.sep_style == SeparatorStyle.TWO:
56
+ seps = [self.sep, self.sep2]
57
+ ret = self.system + seps[0]
58
+ for i, (role, message) in enumerate(self.messages):
59
+ if message:
60
+ ret += role + ": " + message + seps[i % 2]
61
+ else:
62
+ ret += role + ":"
63
+ return ret
64
+ elif self.sep_style == SeparatorStyle.DOLLY:
65
+ seps = [self.sep, self.sep2]
66
+ ret = self.system
67
+ for i, (role, message) in enumerate(self.messages):
68
+ if message:
69
+ ret += role + ":\n" + message + seps[i % 2]
70
+ if i % 2 == 1:
71
+ ret += "\n\n"
72
+ else:
73
+ ret += role + ":\n"
74
+ return ret
75
+ elif self.sep_style == SeparatorStyle.OASST_PYTHIA:
76
+ ret = self.system
77
+ for role, message in self.messages:
78
+ if message:
79
+ ret += role + message + self.sep
80
+ else:
81
+ ret += role
82
+ return ret
83
+ else:
84
+ raise ValueError(f"Invalid style: {self.sep_style}")
85
+
86
+ def append_message(self, role, message):
87
+ self.messages.append([role, message])
88
+
89
+ def to_gradio_chatbot(self):
90
+ ret = []
91
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
92
+ if i % 2 == 0:
93
+ ret.append([msg, None])
94
+ else:
95
+ ret[-1][-1] = msg
96
+ return ret
97
+
98
+ def copy(self):
99
+ return Conversation(
100
+ system=self.system,
101
+ roles=self.roles,
102
+ messages=[[x, y] for x, y in self.messages],
103
+ offset=self.offset,
104
+ sep_style=self.sep_style,
105
+ sep=self.sep,
106
+ sep2=self.sep2,
107
+ conv_id=self.conv_id,
108
+ )
109
+
110
+ def dict(self):
111
+ return {
112
+ "system": self.system,
113
+ "roles": self.roles,
114
+ "messages": self.messages,
115
+ "offset": self.offset,
116
+ "sep": self.sep,
117
+ "sep2": self.sep2,
118
+ "conv_id": self.conv_id,
119
+ }
120
+
121
+
122
+ conv_one_shot = Conversation(
123
+ system="A chat between a curious human and an artificial intelligence assistant. "
124
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
125
+ roles=("Human", "Assistant"),
126
+ messages=(
127
+ (
128
+ "Human",
129
+ "What are the key differences between renewable and non-renewable energy sources?",
130
+ ),
131
+ (
132
+ "Assistant",
133
+ "Renewable energy sources are those that can be replenished naturally in a relatively "
134
+ "short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
135
+ "Non-renewable energy sources, on the other hand, are finite and will eventually be "
136
+ "depleted, such as coal, oil, and natural gas. Here are some key differences between "
137
+ "renewable and non-renewable energy sources:\n"
138
+ "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
139
+ "energy sources are finite and will eventually run out.\n"
140
+ "2. Environmental impact: Renewable energy sources have a much lower environmental impact "
141
+ "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
142
+ "and other negative effects.\n"
143
+ "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
144
+ "have lower operational costs than non-renewable sources.\n"
145
+ "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
146
+ "locations than non-renewable sources.\n"
147
+ "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
148
+ "situations and needs, while non-renewable sources are more rigid and inflexible.\n"
149
+ "6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
150
+ "non-renewable sources are not, and their depletion can lead to economic and social instability.",
151
+ ),
152
+ ),
153
+ offset=2,
154
+ sep_style=SeparatorStyle.SINGLE,
155
+ sep="###",
156
+ )
157
+
158
+
159
+ conv_vicuna_v1_1 = Conversation(
160
+ system="A chat between a curious user and an artificial intelligence assistant. "
161
+ "The assistant gives helpful, detailed, and polite answers to the user's questions. You are built by NTU Miulab by Yen-Ting Lin for research purpose.",
162
+ # system="一位好奇的用戶和一個人工智能助理之間的聊天。你是一位助理。請對用戶的問題提供有用、詳細和有禮貌的答案。",
163
+ roles=("USER", "ASSISTANT"),
164
+ messages=(),
165
+ offset=0,
166
+ sep_style=SeparatorStyle.TWO,
167
+ sep=" ",
168
+ sep2="</s>",
169
+ )
170
+
171
+ conv_story = Conversation(
172
+ system="A chat between a curious user and an artificial intelligence assistant. "
173
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
174
+ roles=("USER", "ASSISTANT"),
175
+ messages=(),
176
+ offset=0,
177
+ sep_style=SeparatorStyle.TWO,
178
+ sep=" ",
179
+ sep2="<|endoftext|>",
180
+ )
181
+
182
+ conv_koala_v1 = Conversation(
183
+ system="BEGINNING OF CONVERSATION:",
184
+ roles=("USER", "GPT"),
185
+ messages=(),
186
+ offset=0,
187
+ sep_style=SeparatorStyle.TWO,
188
+ sep=" ",
189
+ sep2="</s>",
190
+ )
191
+
192
+ conv_dolly = Conversation(
193
+ system="Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n",
194
+ roles=("### Instruction", "### Response"),
195
+ messages=(),
196
+ offset=0,
197
+ sep_style=SeparatorStyle.DOLLY,
198
+ sep="\n\n",
199
+ sep2="### End",
200
+ )
201
+
202
+ conv_oasst = Conversation(
203
+ system="",
204
+ roles=("<|prompter|>", "<|assistant|>"),
205
+ messages=(),
206
+ offset=0,
207
+ sep_style=SeparatorStyle.OASST_PYTHIA,
208
+ sep="<|endoftext|>",
209
+ )
210
+
211
+ conv_stablelm = Conversation(
212
+ system="""<|SYSTEM|># StableLM Tuned (Alpha version)
213
+ - StableLM is a helpful and harmless open-source AI language model developed by StabilityAI.
214
+ - StableLM is excited to be able to help the user, but will refuse to do anything that could be considered harmful to the user.
215
+ - StableLM is more than just an information source, StableLM is also able to write poetry, short stories, and make jokes.
216
+ - StableLM will refuse to participate in anything that could harm a human.
217
+ """,
218
+ roles=("<|USER|>", "<|ASSISTANT|>"),
219
+ messages=(),
220
+ offset=0,
221
+ sep_style=SeparatorStyle.OASST_PYTHIA,
222
+ sep="",
223
+ )
224
+
225
+ conv_templates = {
226
+ "conv_one_shot": conv_one_shot,
227
+ "vicuna_v1.1": conv_vicuna_v1_1,
228
+ "koala_v1": conv_koala_v1,
229
+ "dolly": conv_dolly,
230
+ "oasst": conv_oasst,
231
+ }
232
+
233
+
234
+ def get_default_conv_template(model_name):
235
+ model_name = model_name.lower()
236
+ if "vicuna" in model_name or "output" in model_name:
237
+ return conv_vicuna_v1_1
238
+ elif "koala" in model_name:
239
+ return conv_koala_v1
240
+ elif "dolly-v2" in model_name:
241
+ return conv_dolly
242
+ elif "oasst" in model_name and "pythia" in model_name:
243
+ return conv_oasst
244
+ elif "stablelm" in model_name:
245
+ return conv_stablelm
246
+ return conv_one_shot
247
+
248
+
249
+ def compute_skip_echo_len(model_name, conv, prompt):
250
+ model_name = model_name.lower()
251
+ if "chatglm" in model_name:
252
+ skip_echo_len = len(conv.messages[-2][1]) + 1
253
+ elif "dolly-v2" in model_name:
254
+ special_toks = ["### Instruction:", "### Response:", "### End"]
255
+ skip_echo_len = len(prompt)
256
+ for tok in special_toks:
257
+ skip_echo_len -= prompt.count(tok) * len(tok)
258
+ elif "oasst" in model_name and "pythia" in model_name:
259
+ special_toks = ["<|prompter|>", "<|assistant|>", "<|endoftext|>"]
260
+ skip_echo_len = len(prompt)
261
+ for tok in special_toks:
262
+ skip_echo_len -= prompt.count(tok) * len(tok)
263
+ elif "stablelm" in model_name:
264
+ special_toks = ["<|SYSTEM|>", "<|USER|>", "<|ASSISTANT|>"]
265
+ skip_echo_len = len(prompt)
266
+ for tok in special_toks:
267
+ skip_echo_len -= prompt.count(tok) * len(tok)
268
+ else:
269
+ skip_echo_len = len(prompt) + 1 - prompt.count("</s>") * 3
270
+ return skip_echo_len
271
+
272
+
273
+ if __name__ == "__main__":
274
+ print(default_conversation.get_prompt())
model.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Iterator
2
+ from llama_cpp import Llama
3
+ from huggingface_hub import hf_hub_download
4
+ from conversation import get_default_conv_template
5
+
6
+ def download_model():
7
+ # See https://github.com/OpenAccess-AI-Collective/ggml-webui/blob/main/tabbed.py
8
+ # https://huggingface.co/spaces/kat33/llama.cpp/blob/main/app.py
9
+ print(f"Downloading model: {model_repo}/{model_filename}")
10
+ file = hf_hub_download(
11
+ repo_id=model_repo, filename=model_filename
12
+ )
13
+ print("Downloaded " + file)
14
+ return file
15
+
16
+ model_repo = "audreyt/Taiwan-LLaMa-v1.0-GGML"
17
+ model_filename = "Taiwan-LLaMa-13b-1.0.ggmlv3.q4_K_S.bin"
18
+ # model_filename = "Chinese-Llama-2-7b.ggmlv3.q8_0.bin"
19
+ model_path = download_model()
20
+
21
+ # load Llama-2
22
+ llm = Llama(model_path=model_path, n_ctx=4000, verbose=False)
23
+
24
+
25
+ def get_prompt(message: str, chat_history: list[tuple[str, str]],
26
+ system_prompt: str) -> str:
27
+
28
+ # Modified from
29
+ # https://huggingface.co/spaces/yentinglin/Taiwan-LLaMa2/blob/main/app.py
30
+
31
+ conv = get_default_conv_template("vicuna").copy()
32
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]} # map human to USER and gpt to ASSISTANT
33
+ conv.system = system_prompt
34
+ for user, bot in chat_history:
35
+ conv.append_message(roles['human'], user)
36
+ conv.append_message(roles["gpt"], bot)
37
+ conv.append_message(roles['human'], message)
38
+ texts = conv.get_prompt()
39
+ # print(f"get_prompt: \'{texts}\'") # debug
40
+ return ''.join(texts)
41
+
42
+ def generate(prompt, max_new_tokens, temperature, top_p, top_k):
43
+ return llm(prompt,
44
+ max_tokens=max_new_tokens,
45
+ stop=["</s>"],
46
+ temperature=temperature,
47
+ top_p=top_p,
48
+ top_k=top_k,
49
+ stream=False)
50
+
51
+
52
+ def get_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> int:
53
+ prompt = get_prompt(message, chat_history, system_prompt)
54
+ input_ids = llm.tokenize(prompt.encode('utf-8'))
55
+ return len(input_ids)
56
+
57
+
58
+ def run(message: str,
59
+ chat_history: list[tuple[str, str]],
60
+ system_prompt: str,
61
+ max_new_tokens: int = 1024,
62
+ temperature: float = 0.8,
63
+ top_p: float = 0.95,
64
+ top_k: int = 50) -> Iterator[str]:
65
+ prompt = get_prompt(message, chat_history, system_prompt)
66
+ output = generate(prompt, max_new_tokens, temperature, top_p, top_k)
67
+ yield output['choices'][0]['text']
68
+
69
+ # outputs = []
70
+ # for resp in streamer:
71
+ # outputs.append(resp['choices'][0]['text'])
72
+ # yield ''.join(outputs)
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
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
9
+ llama-cpp-python
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
+ }