NeuralInternet chansung commited on
Commit
3ac5300
0 Parent(s):

Duplicate from chansung/Alpaca-LoRA-Serve

Browse files

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

.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Alpaca-LoRA-Serve
3
+ emoji: 🦙🚀
4
+ sdk: gradio
5
+ sdk_version: 3.22.0
6
+ app_file: app.py
7
+ pinned: true
8
+ license: gpl-3.0
9
+ colorFrom: yellow
10
+ colorTo: green
11
+ duplicated_from: chansung/Alpaca-LoRA-Serve
12
+ ---
13
+
14
+ # 🦙 🚀 Alpaca-LoRA as a Chatbot Service
15
+
16
+ 🚧 This project is still under development process. While serving the project, I noticed there are some bugs emitted by the model itself such as too many line breaks which causes OOM eventually. You can propose PR, but I will merge any improvement at any time as soon as I spot any problems.
17
+
18
+ 🔗 **Demo link**: [Batch Mode](https://notebooksf.jarvislabs.ai/43j3x9FSS8Tg0sqvMlDgKPo9vsoSTTKRsX4RIdC3tNd6qeQ6ktlA0tyWRAR3fe_l) and [Streaming Mode](https://notebookse.jarvislabs.ai/BuOu_VbEuUHb09VEVHhfnFq4-PMhBRVCcfHBRCOrq7c4O9GI4dIGoidvNf76UsRL/) (both are running on a single A6000 instance)
19
+
20
+ The **easiest way** to run this project is to use Colab. Just open up the [alpaca_lora_in_colab](https://github.com/deep-diver/Alpaca-LoRA-Serve/blob/main/notebooks/alpaca_lora_in_colab.ipynb) notebook in Colab (there is a button `open in colab`), and run every cell sequentially. With the standard GPU instance(___T4___), you can run 7B and 13B models. With the premium GPU instance(___A100 40GB___), you can even run 30B model! Screenshot👇🏼 Just note that the connection could be somewhat unstable, so I recommend you to use Colab for development purpose.
21
+
22
+ ![](https://i.ibb.co/hZ3771L/Screen-Shot-2023-03-22-at-9-36-15-PM.png)
23
+
24
+ This repository demonstrates Alpaca-LoRA as a Chatbot service with [Alpaca-LoRA](https://github.com/tloen/alpaca-lora) and [Gradio](https://gradio.app/). It comes with the following features:
25
+
26
+ ### Mode
27
+
28
+ **1. Batch Generation Mode**: batch generation mode aggregates requests up to `batch_size`, and pass the prompts in the requests to the model. It waits the current requests are fully handled. For instance, with `batch_size=4`, if a user sends a request, that is under processing. While it is under processing, if other users are connected, up to 4 requests from the users are aggregated and processed as soon as the current one is done.
29
+
30
+ **2. Streaming Mode**: streaming mode handles multiple requests in a interleaving way with threads. For instance, if there are two users (A and B) are connected, A's request is handled, and then B's request is handled, and then A's request is handled again.... This is because of the nature of streaming mode which generates and `yield` tokens in one by one manner.
31
+
32
+ ### Context management
33
+
34
+ - Alpaca-LoRA as a Chatbot Service manages context in two ways. First of all, it remembers(stores) every history of the conversations by default as in the following code snippet. `context_string` is set as ___"Below is a history of instructions that describe tasks, paired with an input that provides further context. Write a response that appropriately completes the request by remembering the conversation history."___ by default, but it could be set manually via the `Context` field on top of the screen.
35
+ - additionally, there is a `Summarize` button in the middle (you need to expand the component labeled as ___"Helper Buttons"___). If you click this button, it automatically input ___"summarize our conversations so far in three sentences."___ as a prompt, and the resulting generated text will be inserted into the `Context` field. THen all the conversation history up to this point will be ignored. That means the conversation fresh restarts with the below code snippet except `context_string` will be filled up with the model generated text.
36
+ - _NOTE: the only last 2,000 characters are kept, and this number can be configured in `constants.py`_
37
+
38
+ ```python
39
+ f"""{context_string}
40
+
41
+ ### Input: {input} # Surrounding information to AI
42
+
43
+ ### Instruction: {prompt1} # First instruction/prompt given by user
44
+
45
+ ### Response {response1} # First response on the first prompt by AI
46
+
47
+ ### Instruction: {prompt2} # Second instruction/prompt given by user
48
+
49
+ ### Response: {response2} # Second response on the first prompt by AI
50
+ ....
51
+ """
52
+ ```
53
+
54
+ ### misc.
55
+
56
+ - There is a `continue` button in the middle of screen. What it does is to simply send ___"continue."___ prompt to the model. This is useful if you get incomplete previous response from the model. With the ___"continue."___, the model tries to complete the response. Also, since this is a continuation of the response, the ___"continue."___ prompt will be hidden to make chatting history more natural.
57
+
58
+ ### Currently supported LoRA checkpoints
59
+ - [tloen/alpaca-lora-7b](https://huggingface.co/tloen/alpaca-lora-7b): the original 7B Alpaca-LoRA checkpoint by tloen
60
+ - [chansung/alpaca-lora-13b](https://huggingface.co/chansung/alpaca-lora-13b): the 13B Alpaca-LoRA checkpoint by myself(chansung) with the same script to tune the original 7B model
61
+ - [chansung/koalpaca-lora-13b](https://huggingface.co/chansung/koalpaca-lora-13b): the 13B Alpaca-LoRA checkpoint by myself(chansung) with the Korean dataset created by [KoAlpaca project](https://github.com/Beomi/KoAlpaca) by Beomi. It works for English(user) to Korean(AI) conversations.
62
+ - [chansung/alpaca-lora-30b](https://huggingface.co/chansung/alpaca-lora-30b): the 30B Alpaca-LoRA checkpoint by myself(chansung) with the same script to tune the original 7B model
63
+
64
+ ## Instructions
65
+
66
+ 0. Prerequisites
67
+
68
+ Note that the code only works `Python >= 3.9`
69
+
70
+ ```console
71
+ $ conda create -n alpaca-serve python=3.9
72
+ $ conda activate alpaca-serve
73
+ ```
74
+
75
+ 1. Install dependencies
76
+ ```console
77
+ $ cd Alpaca-LoRA-Serve
78
+ $ pip install -r requirements.txt
79
+ ```
80
+
81
+ 2. Run Gradio application
82
+ ```console
83
+ $ BASE_URL=decapoda-research/llama-7b-hf
84
+ $ FINETUNED_CKPT_URL=tloen/alpaca-lora-7b
85
+
86
+ $ python app.py --base_url $BASE_URL --ft_ckpt_url $FINETUNED_CKPT_URL --port 6006
87
+ ```
88
+
89
+ the following flags are supported
90
+
91
+ ```console
92
+ usage: app.py [-h] [--base_url BASE_URL] [--ft_ckpt_url FT_CKPT_URL] [--port PORT] [--batch_size BATCH_SIZE]
93
+ [--api_open API_OPEN] [--share SHARE] [--gen_config_path GEN_CONFIG_PATH]
94
+
95
+ Gradio Application for Alpaca-LoRA as a chatbot service
96
+
97
+ optional arguments:
98
+ -h, --help show this help message and exit
99
+ --base_url BASE_URL Hugging Face Hub URL
100
+ --ft_ckpt_url FT_CKPT_URL
101
+ Hugging Face Hub URL
102
+ --port PORT port number where the app is served
103
+ --batch_size BATCH_SIZE
104
+ how many requests to handle at the same time
105
+ default is set to 1 which enables streaming mode
106
+ --api_open API_OPEN do you want to open as API
107
+ --share SHARE do you want to share temporarily (useful in Colab env)
108
+ --gen_config_path GEN_CONFIG_PATH
109
+ which config to use for GenerationConfig
110
+ ```
111
+
112
+ ## Design figure
113
+
114
+ <p align="center">
115
+ <img src="https://i.ibb.co/w069GYg/Screenshot-2023-03-20-at-1-25-29-PM.png" />
116
+ </p>
117
+
118
+ ## Acknowledgements
119
+
120
+ I am thankful to [Jarvislabs.ai](https://jarvislabs.ai/) who generously provided free GPU resources to experiment with Alpaca-LoRA deployment and share it to communities to try out.
app.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from strings import TITLE, ABSTRACT, BOTTOM_LINE
2
+ from strings import DEFAULT_EXAMPLES
3
+ from strings import SPECIAL_STRS
4
+ from styles import PARENT_BLOCK_CSS
5
+
6
+ import time
7
+ import gradio as gr
8
+
9
+ from model import load_model
10
+ from gen import get_output_batch, StreamModel
11
+ from utils import generate_prompt, post_processes_batch, post_process_stream, get_generation_config, common_post_process
12
+
13
+ model, tokenizer = load_model(
14
+ base="decapoda-research/llama-13b-hf",
15
+ finetuned="chansung/alpaca-lora-13b"
16
+ )
17
+
18
+ model = StreamModel(model, tokenizer)
19
+
20
+ def chat_stream(
21
+ context,
22
+ instruction,
23
+ state_chatbot,
24
+ ):
25
+ # print(instruction)
26
+
27
+ # user input should be appropriately formatted (don't be confused by the function name)
28
+ instruction_display = common_post_process(instruction)
29
+ instruction_prompt = generate_prompt(instruction, state_chatbot, context)
30
+ bot_response = model(
31
+ instruction_prompt,
32
+ max_tokens=256,
33
+ temperature=1,
34
+ top_p=0.9
35
+ )
36
+
37
+ instruction_display = None if instruction_display == SPECIAL_STRS["continue"] else instruction_display
38
+ state_chatbot = state_chatbot + [(instruction_display, None)]
39
+
40
+ prev_index = 0
41
+ agg_tokens = ""
42
+ cutoff_idx = 0
43
+ for tokens in bot_response:
44
+ tokens = tokens.strip()
45
+ cur_token = tokens[prev_index:]
46
+
47
+ if "#" in cur_token and agg_tokens == "":
48
+ cutoff_idx = tokens.find("#")
49
+ agg_tokens = tokens[cutoff_idx:]
50
+
51
+ if agg_tokens != "":
52
+ if len(agg_tokens) < len("### Instruction:") :
53
+ agg_tokens = agg_tokens + cur_token
54
+ elif len(agg_tokens) >= len("### Instruction:"):
55
+ if tokens.find("### Instruction:") > -1:
56
+ processed_response, _ = post_process_stream(tokens[:tokens.find("### Instruction:")].strip())
57
+
58
+ state_chatbot[-1] = (
59
+ instruction_display,
60
+ processed_response
61
+ )
62
+ yield (state_chatbot, state_chatbot, context)
63
+ break
64
+ else:
65
+ agg_tokens = ""
66
+ cutoff_idx = 0
67
+
68
+ if agg_tokens == "":
69
+ processed_response, to_exit = post_process_stream(tokens)
70
+ state_chatbot[-1] = (instruction_display, processed_response)
71
+ yield (state_chatbot, state_chatbot, context)
72
+
73
+ if to_exit:
74
+ break
75
+
76
+ prev_index = len(tokens)
77
+
78
+ yield (
79
+ state_chatbot,
80
+ state_chatbot,
81
+ gr.Textbox.update(value=tokens) if instruction_display == SPECIAL_STRS["summarize"] else context
82
+ )
83
+
84
+ def chat_batch(
85
+ contexts,
86
+ instructions,
87
+ state_chatbots,
88
+ ):
89
+ state_results = []
90
+ ctx_results = []
91
+
92
+ instruct_prompts = [
93
+ generate_prompt(instruct, histories, ctx)
94
+ for ctx, instruct, histories in zip(contexts, instructions, state_chatbots)
95
+ ]
96
+
97
+ bot_responses = get_output_batch(
98
+ model, tokenizer, instruct_prompts, generation_config
99
+ )
100
+ bot_responses = post_processes_batch(bot_responses)
101
+
102
+ for ctx, instruction, bot_response, state_chatbot in zip(contexts, instructions, bot_responses, state_chatbots):
103
+ new_state_chatbot = state_chatbot + [('' if instruction == SPECIAL_STRS["continue"] else instruction, bot_response)]
104
+ ctx_results.append(gr.Textbox.update(value=bot_response) if instruction == SPECIAL_STRS["summarize"] else ctx)
105
+ state_results.append(new_state_chatbot)
106
+
107
+ return (state_results, state_results, ctx_results)
108
+
109
+ def reset_textbox():
110
+ return gr.Textbox.update(value='')
111
+
112
+ with gr.Blocks(css=PARENT_BLOCK_CSS) as demo:
113
+ state_chatbot = gr.State([])
114
+
115
+ with gr.Column(elem_id='col_container'):
116
+ gr.Markdown(f"## {TITLE}\n\n\n{ABSTRACT}")
117
+
118
+ with gr.Accordion("Context Setting", open=False):
119
+ context_txtbox = gr.Textbox(placeholder="Surrounding information to AI", label="Enter Context")
120
+ hidden_txtbox = gr.Textbox(placeholder="", label="Order", visible=False)
121
+
122
+ chatbot = gr.Chatbot(elem_id='chatbot', label="Alpaca-LoRA")
123
+ instruction_txtbox = gr.Textbox(placeholder="What do you want to say to AI?", label="Instruction")
124
+ send_prompt_btn = gr.Button(value="Send Prompt")
125
+
126
+ with gr.Accordion("Helper Buttons", open=False):
127
+ gr.Markdown(f"`Continue` lets AI to complete the previous incomplete answers. `Summarize` lets AI to summarize the conversations so far.")
128
+ continue_txtbox = gr.Textbox(value=SPECIAL_STRS["continue"], visible=False)
129
+ summrize_txtbox = gr.Textbox(value=SPECIAL_STRS["summarize"], visible=False)
130
+
131
+ continue_btn = gr.Button(value="Continue")
132
+ summarize_btn = gr.Button(value="Summarize")
133
+
134
+ gr.Markdown("#### Examples")
135
+ for idx, examples in enumerate(DEFAULT_EXAMPLES):
136
+ with gr.Accordion(examples["title"], open=False):
137
+ gr.Examples(
138
+ examples=examples["examples"],
139
+ inputs=[
140
+ hidden_txtbox, instruction_txtbox
141
+ ],
142
+ label=None
143
+ )
144
+
145
+ gr.Markdown(f"{BOTTOM_LINE}")
146
+
147
+ send_prompt_btn.click(
148
+ chat_stream,
149
+ [context_txtbox, instruction_txtbox, state_chatbot],
150
+ [state_chatbot, chatbot, context_txtbox],
151
+ )
152
+ send_prompt_btn.click(
153
+ reset_textbox,
154
+ [],
155
+ [instruction_txtbox],
156
+ )
157
+
158
+ continue_btn.click(
159
+ chat_stream,
160
+ [context_txtbox, continue_txtbox, state_chatbot],
161
+ [state_chatbot, chatbot, context_txtbox],
162
+ )
163
+ continue_btn.click(
164
+ reset_textbox,
165
+ [],
166
+ [instruction_txtbox],
167
+ )
168
+
169
+ summarize_btn.click(
170
+ chat_stream,
171
+ [context_txtbox, summrize_txtbox, state_chatbot],
172
+ [state_chatbot, chatbot, context_txtbox],
173
+ )
174
+ summarize_btn.click(
175
+ reset_textbox,
176
+ [],
177
+ [instruction_txtbox],
178
+ )
179
+
180
+ demo.queue(
181
+ concurrency_count=2,
182
+ max_size=100,
183
+ ).launch(
184
+ max_threads=2,
185
+ server_name="0.0.0.0",
186
+ )
constants.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ # constants
4
+ num_of_characters_to_keep = 2000
5
+
6
+ # regex
7
+ html_tag_pattern = re.compile(r"<.*?>")
8
+ multi_line_pattern = re.compile(r"\n+")
9
+ multi_space_pattern = re.compile(r"( )")
10
+ multi_br_tag_pattern = re.compile(re.compile(r'<br>\s*(<br>\s*)*'))
11
+
12
+ # repl is short for replacement
13
+ repl_linebreak = "\n"
14
+ repl_empty_str = ""
15
+ repl_br_tag = "<br>"
16
+ repl_span_tag_multispace = '<span class="chat_wrap_space"> <span>'
gen.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import copy
3
+ from tenacity import RetryError
4
+ from tenacity import retry, stop_after_attempt, wait_fixed
5
+
6
+ import torch
7
+
8
+ from transformers import (
9
+ AutoModelForCausalLM,
10
+ AutoModelForSeq2SeqLM,
11
+ AutoTokenizer,
12
+ LogitsProcessorList,
13
+ MinNewTokensLengthLogitsProcessor,
14
+ TemperatureLogitsWarper,
15
+ TopPLogitsWarper,
16
+ )
17
+
18
+ def get_output_batch(
19
+ model, tokenizer, prompts, generation_config
20
+ ):
21
+ if len(prompts) == 1:
22
+ encoding = tokenizer(prompts, return_tensors="pt")
23
+ input_ids = encoding["input_ids"].cuda()
24
+ generated_id = model.generate(
25
+ input_ids=input_ids,
26
+ generation_config=generation_config,
27
+ max_new_tokens=256
28
+ )
29
+
30
+ decoded = tokenizer.batch_decode(generated_id)
31
+ del input_ids, generated_id
32
+ torch.cuda.empty_cache()
33
+ return decoded
34
+ else:
35
+ encodings = tokenizer(prompts, padding=True, return_tensors="pt").to('cuda')
36
+ generated_ids = model.generate(
37
+ **encodings,
38
+ generation_config=generation_config,
39
+ max_new_tokens=256
40
+ )
41
+
42
+ decoded = tokenizer.batch_decode(generated_ids)
43
+ del encodings, generated_ids
44
+ torch.cuda.empty_cache()
45
+ return decoded
46
+
47
+
48
+ # StreamModel is borrowed from basaran project
49
+ # please find more info about it -> https://github.com/hyperonym/basaran
50
+ class StreamModel:
51
+ """StreamModel wraps around a language model to provide stream decoding."""
52
+
53
+ def __init__(self, model, tokenizer):
54
+ super().__init__()
55
+ self.model = model
56
+ self.tokenizer = tokenizer
57
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
58
+
59
+ def __call__(
60
+ self,
61
+ prompt,
62
+ min_tokens=0,
63
+ max_tokens=16,
64
+ temperature=1.0,
65
+ top_p=1.0,
66
+ n=1,
67
+ logprobs=0,
68
+ ):
69
+ """Create a completion stream for the provided prompt."""
70
+ input_ids = self.tokenize(prompt)
71
+ logprobs = max(logprobs, 0)
72
+
73
+ # bigger than 1
74
+ chunk_size = 2
75
+ chunk_count = 0
76
+
77
+ # Generate completion tokens.
78
+ final_tokens = torch.empty(0).to(self.device)
79
+
80
+ try:
81
+ for tokens in self.generate(
82
+ input_ids[None, :].repeat(n, 1),
83
+ logprobs=logprobs,
84
+ min_new_tokens=min_tokens,
85
+ max_new_tokens=max_tokens,
86
+ temperature=temperature,
87
+ top_p=top_p,
88
+ ):
89
+ if chunk_count < chunk_size:
90
+ chunk_count = chunk_count + 1
91
+
92
+ final_tokens = torch.cat((final_tokens, tokens))
93
+
94
+ if chunk_count == chunk_size-1:
95
+ chunk_count = 0
96
+ yield self.tokenizer.decode(final_tokens, skip_special_tokens=True)
97
+
98
+ if chunk_count > 0:
99
+ yield self.tokenizer.decode(final_tokens, skip_special_tokens=True)
100
+
101
+ except RetryError as e:
102
+ print(e)
103
+ del input_ids
104
+ gc.collect()
105
+
106
+ del final_tokens
107
+ if self.device == "cuda":
108
+ torch.cuda.empty_cache()
109
+
110
+ @retry(stop=stop_after_attempt(5), wait=wait_fixed(1))
111
+ def _infer(self, model_fn, **kwargs):
112
+ """Call a model function in inference mode with auto retrying."""
113
+ # This is a temporary workaround for bitsandbytes #162:
114
+ # https://github.com/TimDettmers/bitsandbytes/issues/162
115
+ with torch.inference_mode():
116
+ return model_fn(**kwargs)
117
+
118
+ def _logits_processor(self, config, input_length):
119
+ """Set up logits processor based on the generation config."""
120
+ processor = LogitsProcessorList()
121
+
122
+ # Add processor for enforcing a min-length of new tokens.
123
+ if (
124
+ config.min_new_tokens is not None
125
+ and config.min_new_tokens > 0
126
+ and config.eos_token_id is not None
127
+ ):
128
+ processor.append(
129
+ MinNewTokensLengthLogitsProcessor(
130
+ prompt_length_to_skip=input_length,
131
+ min_new_tokens=config.min_new_tokens,
132
+ eos_token_id=config.eos_token_id,
133
+ )
134
+ )
135
+
136
+ # Add processor for scaling output probability distribution.
137
+ if (
138
+ config.temperature is not None
139
+ and config.temperature > 0
140
+ and config.temperature != 1.0
141
+ ):
142
+ processor.append(TemperatureLogitsWarper(config.temperature))
143
+
144
+ # Add processor for nucleus sampling.
145
+ if config.top_p is not None and config.top_p > 0 and config.top_p < 1:
146
+ processor.append(TopPLogitsWarper(config.top_p))
147
+
148
+ return processor
149
+
150
+ def tokenize(self, text):
151
+ """Tokenize a string into a tensor of token IDs."""
152
+ batch = self.tokenizer.encode(text, return_tensors="pt")
153
+ return batch[0].to(self.device)
154
+
155
+ def generate(self, input_ids, logprobs=0, **kwargs):
156
+ """Generate a stream of predicted tokens using the language model."""
157
+
158
+ # Store the original batch size and input length.
159
+ batch_size = input_ids.shape[0]
160
+ input_length = input_ids.shape[-1]
161
+
162
+ # Separate model arguments from generation config.
163
+ config = self.model.generation_config
164
+ config = copy.deepcopy(config)
165
+ kwargs = config.update(**kwargs)
166
+ kwargs["output_attentions"] = False
167
+ kwargs["output_hidden_states"] = False
168
+ kwargs["use_cache"] = True # config.use_cache
169
+
170
+ # Collect special token IDs.
171
+ pad_token_id = config.pad_token_id
172
+ bos_token_id = config.bos_token_id
173
+ eos_token_id = config.eos_token_id
174
+ if isinstance(eos_token_id, int):
175
+ eos_token_id = [eos_token_id]
176
+ if pad_token_id is None and eos_token_id is not None:
177
+ pad_token_id = eos_token_id[0]
178
+
179
+ # Generate from eos if no input is specified.
180
+ if input_length == 0:
181
+ input_ids = input_ids.new_ones((batch_size, 1)).long()
182
+ if eos_token_id is not None:
183
+ input_ids = input_ids * eos_token_id[0]
184
+ input_length = 1
185
+
186
+ # Prepare inputs for encoder-decoder models.
187
+ if self.model.config.is_encoder_decoder:
188
+ # Get outputs from the encoder.
189
+ encoder = self.model.get_encoder()
190
+ encoder_kwargs = kwargs.copy()
191
+ encoder_kwargs.pop("use_cache", None)
192
+ encoder_kwargs["input_ids"] = input_ids
193
+ encoder_kwargs["return_dict"] = True
194
+ encoder_outputs = self._infer(encoder, **encoder_kwargs)
195
+ kwargs["encoder_outputs"] = encoder_outputs
196
+
197
+ # Reinitialize inputs for the decoder.
198
+ decoder_start_token_id = config.decoder_start_token_id
199
+ if decoder_start_token_id is None:
200
+ decoder_start_token_id = bos_token_id
201
+ input_ids = input_ids.new_ones((batch_size, 1))
202
+ input_ids = input_ids * decoder_start_token_id
203
+ input_length = 1
204
+
205
+ # Set up logits processor.
206
+ processor = self._logits_processor(config, input_length)
207
+
208
+ # Keep track of which sequences are already finished.
209
+ unfinished = input_ids.new_ones(batch_size)
210
+
211
+ # Start auto-regressive generation.
212
+ while True:
213
+ inputs = self.model.prepare_inputs_for_generation(
214
+ input_ids, **kwargs
215
+ ) # noqa: E501
216
+ outputs = self._infer(
217
+ self.model,
218
+ **inputs,
219
+ return_dict=True,
220
+ output_attentions=False,
221
+ output_hidden_states=False,
222
+ )
223
+
224
+ # Pre-process the probability distribution of the next tokens.
225
+ logits = outputs.logits[:, -1, :]
226
+ with torch.inference_mode():
227
+ logits = processor(input_ids, logits)
228
+ probs = torch.nn.functional.softmax(logits, dim=-1)
229
+
230
+ # Select deterministic or stochastic decoding strategy.
231
+ if (config.top_p is not None and config.top_p <= 0) or (
232
+ config.temperature is not None and config.temperature <= 0
233
+ ):
234
+ tokens = torch.argmax(probs, dim=-1)[:, None]
235
+ else:
236
+ tokens = torch.multinomial(probs, num_samples=1)
237
+
238
+ tokens = tokens.squeeze(1)
239
+
240
+ # Finished sequences should have their next token be a padding.
241
+ if pad_token_id is not None:
242
+ tokens = tokens * unfinished + pad_token_id * (1 - unfinished)
243
+
244
+ # Append selected tokens to the inputs.
245
+ input_ids = torch.cat([input_ids, tokens[:, None]], dim=-1)
246
+
247
+ # Mark sequences with eos tokens as finished.
248
+ if eos_token_id is not None:
249
+ not_eos = sum(tokens != i for i in eos_token_id)
250
+ unfinished = unfinished.mul(not_eos.long())
251
+
252
+ # Set status to -1 if exceeded the max length.
253
+ status = unfinished.clone()
254
+ if input_ids.shape[-1] - input_length >= config.max_new_tokens:
255
+ status = 0 - status
256
+
257
+ # Yield predictions and status.
258
+ yield tokens
259
+
260
+ # Stop when finished or exceeded the max length.
261
+ if status.max() <= 0:
262
+ break
263
+
generation_config_default.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ generation_config:
2
+ temperature: 0.90
3
+ top_p: 0.75
4
+ num_beams: 1
5
+ use_cache: True
6
+ max_length: 1000
7
+ min_length: 0
model.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from peft import PeftModel
2
+ from transformers import LlamaTokenizer, LlamaForCausalLM
3
+
4
+ def load_model(
5
+ base="decapoda-research/llama-7b-hf",
6
+ finetuned="tloen/alpaca-lora-7b",
7
+ ):
8
+ tokenizer = LlamaTokenizer.from_pretrained(base)
9
+ tokenizer.pad_token_id = 0
10
+ tokenizer.padding_side = "left"
11
+
12
+ model = LlamaForCausalLM.from_pretrained(
13
+ base,
14
+ load_in_8bit=True,
15
+ device_map="auto",
16
+ )
17
+
18
+ model = PeftModel.from_pretrained(model, finetuned, device_map={'': 0})
19
+ return model, tokenizer
20
+
notebooks/alpaca_lora_in_colab.ipynb ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "machine_shape": "hm"
8
+ },
9
+ "kernelspec": {
10
+ "name": "python3",
11
+ "display_name": "Python 3"
12
+ },
13
+ "language_info": {
14
+ "name": "python"
15
+ },
16
+ "accelerator": "GPU",
17
+ "gpuClass": "premium"
18
+ },
19
+ "cells": [
20
+ {
21
+ "cell_type": "markdown",
22
+ "source": [
23
+ "# Check GPU's Memory Capacity\n",
24
+ "\n",
25
+ "By running `nvidia-smi` command, you can find out the GPU's memory capacity on the current system. \n",
26
+ "\n",
27
+ "With the standard GPU instance(___T4___) which is free, you can run 7B and 13B models. With the premium GPU instance(___A100 40GB___) which is paid with the compute unit that you own, you can even run 30B model! Choose the instance at the menu `Runtime` -> `Change runtime type` -> `Hardware accelerator (GPU)` -> `GPU class (Standard or Premium)`"
28
+ ],
29
+ "metadata": {
30
+ "id": "xf3pUNyVO3WS"
31
+ }
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "source": [
36
+ "!nvidia-smi"
37
+ ],
38
+ "metadata": {
39
+ "id": "L2MoM27rfaKK",
40
+ "colab": {
41
+ "base_uri": "https://localhost:8080/"
42
+ },
43
+ "outputId": "53175950-3269-4296-9425-3652c81ce9b7"
44
+ },
45
+ "execution_count": 1,
46
+ "outputs": [
47
+ {
48
+ "output_type": "stream",
49
+ "name": "stdout",
50
+ "text": [
51
+ "Wed Mar 22 12:11:41 2023 \n",
52
+ "+-----------------------------------------------------------------------------+\n",
53
+ "| NVIDIA-SMI 525.85.12 Driver Version: 525.85.12 CUDA Version: 12.0 |\n",
54
+ "|-------------------------------+----------------------+----------------------+\n",
55
+ "| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\n",
56
+ "| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\n",
57
+ "| | | MIG M. |\n",
58
+ "|===============================+======================+======================|\n",
59
+ "| 0 Tesla T4 Off | 00000000:00:04.0 Off | 0 |\n",
60
+ "| N/A 41C P0 24W / 70W | 0MiB / 15360MiB | 0% Default |\n",
61
+ "| | | N/A |\n",
62
+ "+-------------------------------+----------------------+----------------------+\n",
63
+ " \n",
64
+ "+-----------------------------------------------------------------------------+\n",
65
+ "| Processes: |\n",
66
+ "| GPU GI CI PID Type Process name GPU Memory |\n",
67
+ "| ID ID Usage |\n",
68
+ "|=============================================================================|\n",
69
+ "| No running processes found |\n",
70
+ "+-----------------------------------------------------------------------------+\n"
71
+ ]
72
+ }
73
+ ]
74
+ },
75
+ {
76
+ "cell_type": "markdown",
77
+ "source": [
78
+ "# Clone the repository"
79
+ ],
80
+ "metadata": {
81
+ "id": "N0MDD9TuPTfJ"
82
+ }
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "source": [
87
+ "!git clone https://github.com/deep-diver/Alpaca-LoRA-Serve.git"
88
+ ],
89
+ "metadata": {
90
+ "id": "a_i5DKBNnzAK"
91
+ },
92
+ "execution_count": null,
93
+ "outputs": []
94
+ },
95
+ {
96
+ "cell_type": "markdown",
97
+ "source": [
98
+ "# Move into the directory of the cloned repository"
99
+ ],
100
+ "metadata": {
101
+ "id": "HUuzxWGuPYLq"
102
+ }
103
+ },
104
+ {
105
+ "cell_type": "code",
106
+ "source": [
107
+ "%cd Alpaca-LoRA-Serve"
108
+ ],
109
+ "metadata": {
110
+ "id": "wR-M8u7gsQqg",
111
+ "colab": {
112
+ "base_uri": "https://localhost:8080/"
113
+ },
114
+ "outputId": "eb7b24ba-10e4-46d5-cf8f-852d9fac8170"
115
+ },
116
+ "execution_count": 3,
117
+ "outputs": [
118
+ {
119
+ "output_type": "stream",
120
+ "name": "stdout",
121
+ "text": [
122
+ "/content/Alpaca-LoRA-Serve\n"
123
+ ]
124
+ }
125
+ ]
126
+ },
127
+ {
128
+ "cell_type": "markdown",
129
+ "source": [
130
+ "# Install dependencies"
131
+ ],
132
+ "metadata": {
133
+ "id": "XG8oy7BBPdMh"
134
+ }
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "source": [
139
+ "!pip install -r requirements.txt"
140
+ ],
141
+ "metadata": {
142
+ "id": "moN-15x_ifHE",
143
+ "colab": {
144
+ "base_uri": "https://localhost:8080/"
145
+ },
146
+ "outputId": "a7ec61ff-28cb-4ac4-a0ca-6a5cba060579"
147
+ },
148
+ "execution_count": 4,
149
+ "outputs": [
150
+ {
151
+ "output_type": "stream",
152
+ "name": "stdout",
153
+ "text": [
154
+ " Building wheel for transformers (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
155
+ " Created wheel for transformers: filename=transformers-4.28.0.dev0-py3-none-any.whl size=6758864 sha256=028619344608e01338ac944ad0d4e6496fe5c743c90a15dd20c2e436e56106a9\n",
156
+ " Stored in directory: /tmp/pip-ephem-wheel-cache-vqcgstta/wheels/f7/92/8c/752ff3bfcd3439805d8bbf641614da38ef3226e127ebea86ee\n",
157
+ " Building wheel for peft (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
158
+ " Created wheel for peft: filename=peft-0.3.0.dev0-py3-none-any.whl size=40669 sha256=bb0afa4164ac44e0a604c781f61767ea3e7255b85b70e2d4cf76a4252119ac27\n",
159
+ " Stored in directory: /tmp/pip-ephem-wheel-cache-vqcgstta/wheels/2d/60/1b/0edd9dc0f0c489738b1166bc1b0b560ee368f7721f89d06e3a\n",
160
+ " Building wheel for ffmpy (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
161
+ " Created wheel for ffmpy: filename=ffmpy-0.3.0-py3-none-any.whl size=4707 sha256=5f7dae7c29ab50f6251f5c864c70d4e485a4338a98c5cc1ee51523ace2758bf1\n",
162
+ " Stored in directory: /root/.cache/pip/wheels/91/e2/96/f676aa08bfd789328c6576cd0f1fde4a3d686703bb0c247697\n",
163
+ "Successfully built transformers peft ffmpy\n",
164
+ "Installing collected packages: tokenizers, sentencepiece, rfc3986, pydub, ffmpy, bitsandbytes, xxhash, websockets, uc-micro-py, python-multipart, pycryptodome, orjson, multidict, mdurl, loralib, h11, frozenlist, dill, async-timeout, aiofiles, yarl, uvicorn, starlette, responses, multiprocess, markdown-it-py, linkify-it-py, huggingface-hub, httpcore, aiosignal, accelerate, transformers, mdit-py-plugins, httpx, fastapi, aiohttp, peft, gradio, datasets\n",
165
+ "Successfully installed accelerate-0.17.1 aiofiles-23.1.0 aiohttp-3.8.4 aiosignal-1.3.1 async-timeout-4.0.2 bitsandbytes-0.37.2 datasets-2.10.1 dill-0.3.6 fastapi-0.95.0 ffmpy-0.3.0 frozenlist-1.3.3 gradio-3.20.0 h11-0.14.0 httpcore-0.16.3 httpx-0.23.3 huggingface-hub-0.13.3 linkify-it-py-2.0.0 loralib-0.1.1 markdown-it-py-2.2.0 mdit-py-plugins-0.3.3 mdurl-0.1.2 multidict-6.0.4 multiprocess-0.70.14 orjson-3.8.8 peft-0.3.0.dev0 pycryptodome-3.17 pydub-0.25.1 python-multipart-0.0.6 responses-0.18.0 rfc3986-1.5.0 sentencepiece-0.1.97 starlette-0.26.1 tokenizers-0.13.2 transformers-4.28.0.dev0 uc-micro-py-1.0.1 uvicorn-0.21.1 websockets-10.4 xxhash-3.2.0 yarl-1.8.2\n"
166
+ ]
167
+ }
168
+ ]
169
+ },
170
+ {
171
+ "cell_type": "markdown",
172
+ "source": [
173
+ "# Run the application"
174
+ ],
175
+ "metadata": {
176
+ "id": "Cr3bQkSePfrG"
177
+ }
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "source": [
182
+ "#@title Choose models\n",
183
+ "\n",
184
+ "base_model = 'decapoda-research/llama-13b-hf' #@param [\"decapoda-research/llama-7b-hf\", \"decapoda-research/llama-13b-hf\", \"decapoda-research/llama-30b-hf\"]\n",
185
+ "finetuned_model = 'chansung/alpaca-lora-13b' #@param [\"tloen/alpaca-lora-7b\", \"chansung/alpaca-lora-13b\", \"chansung/koalpaca-lora-13b\", \"chansung/alpaca-lora-30b\"]\n"
186
+ ],
187
+ "metadata": {
188
+ "id": "4Wg0eqnkPnq-"
189
+ },
190
+ "execution_count": 14,
191
+ "outputs": []
192
+ },
193
+ {
194
+ "cell_type": "markdown",
195
+ "source": [
196
+ "## Run the application\n",
197
+ "\n",
198
+ "It will take some time since LLaMA weights are huge. \n",
199
+ "\n",
200
+ "Click the URL appeared in the `Running on public URL:` field from the log. That will bring you to a new browser tab which opens up the running application."
201
+ ],
202
+ "metadata": {
203
+ "id": "b81jhdtcQyOP"
204
+ }
205
+ },
206
+ {
207
+ "cell_type": "code",
208
+ "source": [
209
+ "!python app.py --base_url $base_model --ft_ckpt_url $finetuned_model --share yes"
210
+ ],
211
+ "metadata": {
212
+ "id": "y3qpzBw2jMHq"
213
+ },
214
+ "execution_count": null,
215
+ "outputs": []
216
+ }
217
+ ]
218
+ }
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ bitsandbytes
2
+ datasets
3
+ loralib
4
+ sentencepiece
5
+ git+https://github.com/huggingface/transformers.git
6
+ git+https://github.com/huggingface/peft.git
7
+ gradio==3.20.0
8
+ tenacity
scripts/hparams_explore.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import itertools
3
+ import wandb
4
+ from transformers import GenerationConfig
5
+
6
+ wandb.login(key="")
7
+
8
+ PROJECT="txt_gen_test_project"
9
+
10
+ generation_configs = {
11
+ "temperature": [0.5, 0.7, 0.8, 0.9, 1.0],
12
+ "top_p": [0.5, 0.75, 0.85, 0.95, 1.0],
13
+ "num_beams": [1, 2, 3, 4]
14
+ }
15
+
16
+ num_gens = 1
17
+
18
+ # token initialization
19
+ # model initialization
20
+
21
+ for comb in itertools.product(generation_configs['temperature'],
22
+ generation_configs['top_p'],
23
+ generation_configs['num_beams']):
24
+ temperature = comb[0]
25
+ top_p = comb[1]
26
+ num_beams = comb[2]
27
+
28
+ generation_config = GenerationConfig(
29
+ temperature=temperature,
30
+ top_p=top_p,
31
+ num_beams=num_beams,
32
+ )
33
+
34
+ first_columns = [f"gen_txt_{num}" for num in range(num_gens)]
35
+ columns = first_columns + ["temperature", "top_p", "num_beams", "time_delta"]
36
+
37
+ avg_time_delta = 0
38
+ txt_gens = []
39
+ for i in range(num_gens):
40
+ start = time.time()
41
+ # text generation
42
+ text = "dummy text"
43
+ txt_gens.append(text)
44
+
45
+ # decode outputs
46
+ end = time.time()
47
+ t_delta = end - start
48
+ avg_time_delta = avg_time_delta + t_delta
49
+
50
+ avg_time_delta = round(avg_time_delta / num_gens, 4)
51
+
52
+ wandb.init(
53
+ project=PROJECT,
54
+ name=f"t@{temperature}-tp@{top_p}-nb@{num_beams}",
55
+ config=generation_config,
56
+ )
57
+
58
+ text_table = wandb.Table(columns=columns)
59
+ text_table.add_data(*txt_gens, temperature, top_p, num_beams, avg_time_delta)
60
+
61
+ wandb.log({
62
+ "avg_t_delta": avg_time_delta,
63
+ "results": text_table
64
+ })
65
+
66
+ wandb.finish()
scripts/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ transformers
2
+ wandb
strings.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ TITLE = "Alpaca-LoRA Playground"
2
+
3
+ ABSTRACT = """
4
+ Thanks to [tolen](https://github.com/tloen/alpaca-lora), this simple application runs Alpaca-LoRA which is instruction fine-tuned version of [LLaMA](https://ai.facebook.com/blog/large-language-model-llama-meta-ai/) from Meta AI. Alpaca-LoRA is *Low-Rank LLaMA Instruct-Tuning* which is inspired by [Stanford Alpaca project](https://github.com/tatsu-lab/stanford_alpaca). This demo application currently runs 13B version on a A10 instance.
5
+ """
6
+
7
+ BOTTOM_LINE = """
8
+
9
+ This demo application runs the open source project, [Alpaca-LoRA-Serve](https://github.com/deep-diver/Alpaca-LoRA-Serve). By default, it runs with streaming mode, but you can also run with dynamic batch generation model. Please visit the repo, find more information, and contribute if you can.
10
+
11
+ Alpaca-LoRA is built on the same concept as Standford Alpaca project, but it lets us train and inference on a smaller GPUs such as RTX4090 for 7B version. Also, we could build very small size of checkpoints on top of base models thanks to [🤗 transformers](https://huggingface.co/docs/transformers/index), [🤗 peft](https://github.com/huggingface/peft), and [bitsandbytes](https://github.com/TimDettmers/bitsandbytes/tree/main) libraries.
12
+ """
13
+
14
+ DEFAULT_EXAMPLES = [
15
+ {
16
+ "title": "1️⃣ List all Canadian provinces in alphabetical order.",
17
+ "examples": [
18
+ ["1", "List all Canadian provinces in alphabetical order."],
19
+ ["2", "Which ones are on the east side?"],
20
+ ["3", "What foods are famous in each province on the east side?"],
21
+ ["4", "What about sightseeing? or landmarks? list one per province"],
22
+ ],
23
+ },
24
+ {
25
+ "title": "2️⃣ Tell me about Alpacas.",
26
+ "examples": [
27
+ ["1", "Tell me about alpacas in two sentences"],
28
+ ["2", "What other animals are living in the same area?"],
29
+ ["3", "Are they the same species?"],
30
+ ["4", "Write a Python program to return those species"],
31
+ ],
32
+ },
33
+ {
34
+ "title": "3️⃣ Tell me about the king of France in 2019.",
35
+ "examples": [
36
+ ["1", "Tell me about the king of France in 2019."],
37
+ ["2", "What about before him?"],
38
+ ]
39
+ },
40
+ {
41
+ "title": "4️⃣ Write a Python program that prints the first 10 Fibonacci numbers.",
42
+ "examples": [
43
+ ["1", "Write a Python program that prints the first 10 Fibonacci numbers."],
44
+ ["2", "Could you explain how the code works?"],
45
+ ["3", "What is recursion?"],
46
+ ]
47
+ }
48
+ ]
49
+
50
+ SPECIAL_STRS = {
51
+ "continue": "continue.",
52
+ "summarize": "summarize our conversations so far in three sentences."
53
+ }
styles.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PARENT_BLOCK_CSS = """
2
+ #col_container {
3
+ width: 95%;
4
+ margin-left: auto;
5
+ margin-right: auto;
6
+ }
7
+
8
+ #chatbot {
9
+ height: 500px;
10
+ overflow: auto;
11
+ }
12
+
13
+ .chat_wrap_space {
14
+ margin-left: 0.5em
15
+ }
16
+ """
utils.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import yaml
3
+
4
+ from transformers import GenerationConfig
5
+
6
+ from strings import SPECIAL_STRS
7
+ from constants import num_of_characters_to_keep
8
+ from constants import html_tag_pattern, multi_line_pattern, multi_space_pattern
9
+ from constants import repl_empty_str, repl_br_tag, repl_span_tag_multispace, repl_linebreak
10
+
11
+ def get_generation_config(path):
12
+ with open(path, 'rb') as f:
13
+ generation_config = yaml.safe_load(f.read())
14
+
15
+ return GenerationConfig(**generation_config["generation_config"])
16
+
17
+ def generate_prompt(prompt, histories, ctx=None):
18
+ convs = f"""Below is a history of instructions that describe tasks, paired with an input that provides further context. Write a response that appropriately completes the request by remembering the conversation history.
19
+
20
+ """
21
+ if ctx is not None:
22
+ convs = f"""{ctx}
23
+
24
+ """
25
+
26
+ start_idx = 0
27
+
28
+ for idx, history in enumerate(histories):
29
+ history_prompt = history[0]
30
+ if history_prompt == SPECIAL_STRS["summarize"]:
31
+ start_idx = idx
32
+
33
+ # drop the previous conversations if user has summarized
34
+ for history in histories[start_idx if start_idx == 0 else start_idx+1:]:
35
+ history_prompt = history[0]
36
+ history_response = history[1]
37
+
38
+ history_response = history_response.replace("<br>", "\n")
39
+ history_response = re.sub(
40
+ html_tag_pattern, repl_empty_str, history_response
41
+ )
42
+
43
+ convs = convs + f"""### Instruction:{history_prompt}
44
+
45
+ ### Response:{history_response}
46
+
47
+ """
48
+
49
+ convs = convs + f"""### Instruction:{prompt}
50
+
51
+ ### Response:"""
52
+
53
+ return convs[-num_of_characters_to_keep:]
54
+
55
+ # applicable to instruction to be displayed as well
56
+ def common_post_process(original_str):
57
+ original_str = re.sub(
58
+ multi_line_pattern, repl_br_tag, original_str
59
+ )
60
+ original_str = re.sub(
61
+ multi_space_pattern, repl_span_tag_multispace, original_str
62
+ )
63
+
64
+ return original_str
65
+
66
+ def post_process_stream(bot_response):
67
+ # sometimes model spits out text containing
68
+ # "### Response:" and "### Instruction: -> in this case, we want to stop generating
69
+ if "### Response:" in bot_response or "### Input:" in bot_response:
70
+ bot_response = bot_response.replace("### Response:", '').replace("### Input:", '').strip()
71
+ return bot_response, True
72
+
73
+ return common_post_process(bot_response), False
74
+
75
+ def post_process_batch(bot_response):
76
+ bot_response = bot_response.split("### Response:")[-1].strip()
77
+ return common_post_process(bot_response)
78
+
79
+ def post_processes_batch(bot_responses):
80
+ return [post_process_batch(r) for r in bot_responses]