Spaces:
Runtime error
Runtime error
Duplicate from chansung/Alpaca-LoRA-Serve
Browse filesCo-authored-by: chansung park <chansung@users.noreply.huggingface.co>
- .gitattributes +34 -0
- LICENSE +201 -0
- README.md +119 -0
- app.py +186 -0
- constants.py +16 -0
- gen.py +207 -0
- generation_config_default.yaml +7 -0
- model.py +20 -0
- notebooks/alpaca_lora_in_colab.ipynb +218 -0
- requirements.txt +8 -0
- scripts/hparams_explore.py +66 -0
- scripts/requirements.txt +2 -0
- strings.py +53 -0
- styles.py +16 -0
- utils.py +80 -0
.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,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: Alpaca-LoRA-Serve
|
3 |
+
emoji: π¦π
|
4 |
+
sdk: gradio
|
5 |
+
app_file: app.py
|
6 |
+
pinned: true
|
7 |
+
license: gpl-3.0
|
8 |
+
colorFrom: yellow
|
9 |
+
colorTo: green
|
10 |
+
duplicated_from: chansung/Alpaca-LoRA-Serve
|
11 |
+
---
|
12 |
+
|
13 |
+
# π¦ π Alpaca-LoRA as a Chatbot Service
|
14 |
+
|
15 |
+
π§ 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.
|
16 |
+
|
17 |
+
π **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)
|
18 |
+
|
19 |
+
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.
|
20 |
+
|
21 |
+
![](https://i.ibb.co/hZ3771L/Screen-Shot-2023-03-22-at-9-36-15-PM.png)
|
22 |
+
|
23 |
+
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:
|
24 |
+
|
25 |
+
### Mode
|
26 |
+
|
27 |
+
**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.
|
28 |
+
|
29 |
+
**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.
|
30 |
+
|
31 |
+
### Context management
|
32 |
+
|
33 |
+
- 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.
|
34 |
+
- 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.
|
35 |
+
- _NOTE: the only last 2,000 characters are kept, and this number can be configured in `constants.py`_
|
36 |
+
|
37 |
+
```python
|
38 |
+
f"""{context_string}
|
39 |
+
|
40 |
+
### Input: {input} # Surrounding information to AI
|
41 |
+
|
42 |
+
### Instruction: {prompt1} # First instruction/prompt given by user
|
43 |
+
|
44 |
+
### Response {response1} # First response on the first prompt by AI
|
45 |
+
|
46 |
+
### Instruction: {prompt2} # Second instruction/prompt given by user
|
47 |
+
|
48 |
+
### Response: {response2} # Second response on the first prompt by AI
|
49 |
+
....
|
50 |
+
"""
|
51 |
+
```
|
52 |
+
|
53 |
+
### misc.
|
54 |
+
|
55 |
+
- 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.
|
56 |
+
|
57 |
+
### Currently supported LoRA checkpoints
|
58 |
+
- [tloen/alpaca-lora-7b](https://huggingface.co/tloen/alpaca-lora-7b): the original 7B Alpaca-LoRA checkpoint by tloen
|
59 |
+
- [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
|
60 |
+
- [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.
|
61 |
+
- [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
|
62 |
+
|
63 |
+
## Instructions
|
64 |
+
|
65 |
+
0. Prerequisites
|
66 |
+
|
67 |
+
Note that the code only works `Python >= 3.9`
|
68 |
+
|
69 |
+
```console
|
70 |
+
$ conda create -n alpaca-serve python=3.9
|
71 |
+
$ conda activate alpaca-serve
|
72 |
+
```
|
73 |
+
|
74 |
+
1. Install dependencies
|
75 |
+
```console
|
76 |
+
$ cd Alpaca-LoRA-Serve
|
77 |
+
$ pip install -r requirements.txt
|
78 |
+
```
|
79 |
+
|
80 |
+
2. Run Gradio application
|
81 |
+
```console
|
82 |
+
$ BASE_URL=decapoda-research/llama-7b-hf
|
83 |
+
$ FINETUNED_CKPT_URL=tloen/alpaca-lora-7b
|
84 |
+
|
85 |
+
$ python app.py --base_url $BASE_URL --ft_ckpt_url $FINETUNED_CKPT_URL --port 6006
|
86 |
+
```
|
87 |
+
|
88 |
+
the following flags are supported
|
89 |
+
|
90 |
+
```console
|
91 |
+
usage: app.py [-h] [--base_url BASE_URL] [--ft_ckpt_url FT_CKPT_URL] [--port PORT] [--batch_size BATCH_SIZE]
|
92 |
+
[--api_open API_OPEN] [--share SHARE] [--gen_config_path GEN_CONFIG_PATH]
|
93 |
+
|
94 |
+
Gradio Application for Alpaca-LoRA as a chatbot service
|
95 |
+
|
96 |
+
optional arguments:
|
97 |
+
-h, --help show this help message and exit
|
98 |
+
--base_url BASE_URL Hugging Face Hub URL
|
99 |
+
--ft_ckpt_url FT_CKPT_URL
|
100 |
+
Hugging Face Hub URL
|
101 |
+
--port PORT port number where the app is served
|
102 |
+
--batch_size BATCH_SIZE
|
103 |
+
how many requests to handle at the same time
|
104 |
+
default is set to 1 which enables streaming mode
|
105 |
+
--api_open API_OPEN do you want to open as API
|
106 |
+
--share SHARE do you want to share temporarily (useful in Colab env)
|
107 |
+
--gen_config_path GEN_CONFIG_PATH
|
108 |
+
which config to use for GenerationConfig
|
109 |
+
```
|
110 |
+
|
111 |
+
## Design figure
|
112 |
+
|
113 |
+
<p align="center">
|
114 |
+
<img src="https://i.ibb.co/w069GYg/Screenshot-2023-03-20-at-1-25-29-PM.png" />
|
115 |
+
</p>
|
116 |
+
|
117 |
+
## Acknowledgements
|
118 |
+
|
119 |
+
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=128,
|
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=1,
|
182 |
+
max_size=100,
|
183 |
+
).launch(
|
184 |
+
max_threads=5,
|
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,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gc
|
2 |
+
import copy
|
3 |
+
import time
|
4 |
+
from tenacity import RetryError
|
5 |
+
from tenacity import retry, stop_after_attempt, wait_fixed
|
6 |
+
|
7 |
+
import torch
|
8 |
+
|
9 |
+
from transformers import (
|
10 |
+
AutoModelForCausalLM,
|
11 |
+
AutoModelForSeq2SeqLM,
|
12 |
+
AutoTokenizer,
|
13 |
+
LogitsProcessorList,
|
14 |
+
MinNewTokensLengthLogitsProcessor,
|
15 |
+
TemperatureLogitsWarper,
|
16 |
+
TopPLogitsWarper,
|
17 |
+
MinLengthLogitsProcessor
|
18 |
+
)
|
19 |
+
|
20 |
+
def get_output_batch(
|
21 |
+
model, tokenizer, prompts, generation_config
|
22 |
+
):
|
23 |
+
if len(prompts) == 1:
|
24 |
+
encoding = tokenizer(prompts, return_tensors="pt")
|
25 |
+
input_ids = encoding["input_ids"].cuda()
|
26 |
+
generated_id = model.generate(
|
27 |
+
input_ids=input_ids,
|
28 |
+
generation_config=generation_config,
|
29 |
+
max_new_tokens=256
|
30 |
+
)
|
31 |
+
|
32 |
+
decoded = tokenizer.batch_decode(generated_id)
|
33 |
+
del input_ids, generated_id
|
34 |
+
torch.cuda.empty_cache()
|
35 |
+
return decoded
|
36 |
+
else:
|
37 |
+
encodings = tokenizer(prompts, padding=True, return_tensors="pt").to('cuda')
|
38 |
+
generated_ids = model.generate(
|
39 |
+
**encodings,
|
40 |
+
generation_config=generation_config,
|
41 |
+
max_new_tokens=256
|
42 |
+
)
|
43 |
+
|
44 |
+
decoded = tokenizer.batch_decode(generated_ids)
|
45 |
+
del encodings, generated_ids
|
46 |
+
torch.cuda.empty_cache()
|
47 |
+
return decoded
|
48 |
+
|
49 |
+
|
50 |
+
# StreamModel is borrowed from basaran project
|
51 |
+
# please find more info about it -> https://github.com/hyperonym/basaran
|
52 |
+
class StreamModel:
|
53 |
+
"""StreamModel wraps around a language model to provide stream decoding."""
|
54 |
+
|
55 |
+
def __init__(self, model, tokenizer):
|
56 |
+
super().__init__()
|
57 |
+
self.model = model
|
58 |
+
self.tokenizer = tokenizer
|
59 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
60 |
+
|
61 |
+
self.processor = LogitsProcessorList()
|
62 |
+
self.processor.append(TemperatureLogitsWarper(0.9))
|
63 |
+
self.processor.append(TopPLogitsWarper(0.75))
|
64 |
+
|
65 |
+
|
66 |
+
def __call__(
|
67 |
+
self,
|
68 |
+
prompt,
|
69 |
+
min_tokens=0,
|
70 |
+
max_tokens=16,
|
71 |
+
temperature=1.0,
|
72 |
+
top_p=1.0,
|
73 |
+
n=1,
|
74 |
+
logprobs=0,
|
75 |
+
):
|
76 |
+
"""Create a completion stream for the provided prompt."""
|
77 |
+
input_ids = self.tokenize(prompt)
|
78 |
+
logprobs = max(logprobs, 0)
|
79 |
+
|
80 |
+
# bigger than 1
|
81 |
+
chunk_size = 2
|
82 |
+
chunk_count = 0
|
83 |
+
|
84 |
+
# Generate completion tokens.
|
85 |
+
final_tokens = torch.empty(0)
|
86 |
+
|
87 |
+
for tokens in self.generate(
|
88 |
+
input_ids[None, :].repeat(n, 1),
|
89 |
+
logprobs=logprobs,
|
90 |
+
min_new_tokens=min_tokens,
|
91 |
+
max_new_tokens=max_tokens,
|
92 |
+
temperature=temperature,
|
93 |
+
top_p=top_p,
|
94 |
+
):
|
95 |
+
if chunk_count < chunk_size:
|
96 |
+
chunk_count = chunk_count + 1
|
97 |
+
|
98 |
+
final_tokens = torch.cat((final_tokens, tokens.to("cpu")))
|
99 |
+
|
100 |
+
if chunk_count == chunk_size-1:
|
101 |
+
chunk_count = 0
|
102 |
+
yield self.tokenizer.decode(final_tokens, skip_special_tokens=True)
|
103 |
+
|
104 |
+
if chunk_count > 0:
|
105 |
+
yield self.tokenizer.decode(final_tokens, skip_special_tokens=True)
|
106 |
+
|
107 |
+
del final_tokens, input_ids
|
108 |
+
if self.device == "cuda":
|
109 |
+
torch.cuda.empty_cache()
|
110 |
+
|
111 |
+
def _infer(self, model_fn, **kwargs):
|
112 |
+
with torch.inference_mode():
|
113 |
+
return model_fn(**kwargs)
|
114 |
+
|
115 |
+
def tokenize(self, text):
|
116 |
+
"""Tokenize a string into a tensor of token IDs."""
|
117 |
+
batch = self.tokenizer.encode(text, return_tensors="pt")
|
118 |
+
return batch[0].to(self.device)
|
119 |
+
|
120 |
+
def generate(self, input_ids, logprobs=0, **kwargs):
|
121 |
+
"""Generate a stream of predicted tokens using the language model."""
|
122 |
+
|
123 |
+
# Store the original batch size and input length.
|
124 |
+
batch_size = input_ids.shape[0]
|
125 |
+
input_length = input_ids.shape[-1]
|
126 |
+
|
127 |
+
# Separate model arguments from generation config.
|
128 |
+
config = self.model.generation_config
|
129 |
+
config = copy.deepcopy(config)
|
130 |
+
kwargs = config.update(**kwargs)
|
131 |
+
kwargs["output_attentions"] = False
|
132 |
+
kwargs["output_hidden_states"] = False
|
133 |
+
kwargs["use_cache"] = True
|
134 |
+
|
135 |
+
# Collect special token IDs.
|
136 |
+
pad_token_id = config.pad_token_id
|
137 |
+
bos_token_id = config.bos_token_id
|
138 |
+
eos_token_id = config.eos_token_id
|
139 |
+
if isinstance(eos_token_id, int):
|
140 |
+
eos_token_id = [eos_token_id]
|
141 |
+
if pad_token_id is None and eos_token_id is not None:
|
142 |
+
pad_token_id = eos_token_id[0]
|
143 |
+
|
144 |
+
# Generate from eos if no input is specified.
|
145 |
+
if input_length == 0:
|
146 |
+
input_ids = input_ids.new_ones((batch_size, 1)).long()
|
147 |
+
if eos_token_id is not None:
|
148 |
+
input_ids = input_ids * eos_token_id[0]
|
149 |
+
input_length = 1
|
150 |
+
|
151 |
+
# Keep track of which sequences are already finished.
|
152 |
+
unfinished = input_ids.new_ones(batch_size)
|
153 |
+
|
154 |
+
# Start auto-regressive generation.
|
155 |
+
while True:
|
156 |
+
inputs = self.model.prepare_inputs_for_generation(
|
157 |
+
input_ids, **kwargs
|
158 |
+
) # noqa: E501
|
159 |
+
|
160 |
+
outputs = self._infer(
|
161 |
+
self.model,
|
162 |
+
**inputs,
|
163 |
+
# return_dict=True,
|
164 |
+
output_attentions=False,
|
165 |
+
output_hidden_states=False,
|
166 |
+
)
|
167 |
+
|
168 |
+
# Pre-process the probability distribution of the next tokens.
|
169 |
+
logits = outputs.logits[:, -1, :]
|
170 |
+
with torch.inference_mode():
|
171 |
+
logits = self.processor(input_ids, logits)
|
172 |
+
probs = torch.nn.functional.softmax(logits, dim=-1)
|
173 |
+
|
174 |
+
# Select deterministic or stochastic decoding strategy.
|
175 |
+
if (config.top_p is not None and config.top_p <= 0) or (
|
176 |
+
config.temperature is not None and config.temperature <= 0
|
177 |
+
):
|
178 |
+
tokens = torch.argmax(probs, dim=-1)[:, None]
|
179 |
+
else:
|
180 |
+
tokens = torch.multinomial(probs, num_samples=1)
|
181 |
+
|
182 |
+
tokens = tokens.squeeze(1)
|
183 |
+
|
184 |
+
# Finished sequences should have their next token be a padding.
|
185 |
+
if pad_token_id is not None:
|
186 |
+
tokens = tokens * unfinished + pad_token_id * (1 - unfinished)
|
187 |
+
|
188 |
+
# Append selected tokens to the inputs.
|
189 |
+
input_ids = torch.cat([input_ids, tokens[:, None]], dim=-1)
|
190 |
+
|
191 |
+
# Mark sequences with eos tokens as finished.
|
192 |
+
if eos_token_id is not None:
|
193 |
+
not_eos = sum(tokens != i for i in eos_token_id)
|
194 |
+
unfinished = unfinished.mul(not_eos.long())
|
195 |
+
|
196 |
+
# Set status to -1 if exceeded the max length.
|
197 |
+
status = unfinished.clone()
|
198 |
+
if input_ids.shape[-1] - input_length >= config.max_new_tokens:
|
199 |
+
status = 0 - status
|
200 |
+
|
201 |
+
# Yield predictions and status.
|
202 |
+
yield tokens
|
203 |
+
|
204 |
+
# Stop when finished or exceeded the max length.
|
205 |
+
if status.max() <= 0:
|
206 |
+
break
|
207 |
+
|
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]
|