├── .gitignore
├── DATA_LICENSE
├── LICENSE
├── README.md
├── convert_to_hf.py
├── data
├── code_alpaca_20k.json
├── code_alpaca_2k.json
├── new_codealpaca.json
└── rosetta_alpaca.json
├── ds_config.json
├── generate_instruction.py
├── nolora.py
├── prompt.txt
├── requirements.txt
├── seed_tasks.jsonl
├── train.py
└── utils.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
131 | .DS_Store
132 | .idea
133 |
--------------------------------------------------------------------------------
/DATA_LICENSE:
--------------------------------------------------------------------------------
1 | Attribution-NonCommercial 4.0 International
2 |
3 | =======================================================================
4 |
5 | Creative Commons Corporation ("Creative Commons") is not a law firm and
6 | does not provide legal services or legal advice. Distribution of
7 | Creative Commons public licenses does not create a lawyer-client or
8 | other relationship. Creative Commons makes its licenses and related
9 | information available on an "as-is" basis. Creative Commons gives no
10 | warranties regarding its licenses, any material licensed under their
11 | terms and conditions, or any related information. Creative Commons
12 | disclaims all liability for damages resulting from their use to the
13 | fullest extent possible.
14 |
15 | Using Creative Commons Public Licenses
16 |
17 | Creative Commons public licenses provide a standard set of terms and
18 | conditions that creators and other rights holders may use to share
19 | original works of authorship and other material subject to copyright
20 | and certain other rights specified in the public license below. The
21 | following considerations are for informational purposes only, are not
22 | exhaustive, and do not form part of our licenses.
23 |
24 | Considerations for licensors: Our public licenses are
25 | intended for use by those authorized to give the public
26 | permission to use material in ways otherwise restricted by
27 | copyright and certain other rights. Our licenses are
28 | irrevocable. Licensors should read and understand the terms
29 | and conditions of the license they choose before applying it.
30 | Licensors should also secure all rights necessary before
31 | applying our licenses so that the public can reuse the
32 | material as expected. Licensors should clearly mark any
33 | material not subject to the license. This includes other CC-
34 | licensed material, or material used under an exception or
35 | limitation to copyright. More considerations for licensors:
36 | wiki.creativecommons.org/Considerations_for_licensors
37 |
38 | Considerations for the public: By using one of our public
39 | licenses, a licensor grants the public permission to use the
40 | licensed material under specified terms and conditions. If
41 | the licensor's permission is not necessary for any reason--for
42 | example, because of any applicable exception or limitation to
43 | copyright--then that use is not regulated by the license. Our
44 | licenses grant only permissions under copyright and certain
45 | other rights that a licensor has authority to grant. Use of
46 | the licensed material may still be restricted for other
47 | reasons, including because others have copyright or other
48 | rights in the material. A licensor may make special requests,
49 | such as asking that all changes be marked or described.
50 | Although not required by our licenses, you are encouraged to
51 | respect those requests where reasonable. More considerations
52 | for the public:
53 | wiki.creativecommons.org/Considerations_for_licensees
54 |
55 | =======================================================================
56 |
57 | Creative Commons Attribution-NonCommercial 4.0 International Public
58 | License
59 |
60 | By exercising the Licensed Rights (defined below), You accept and agree
61 | to be bound by the terms and conditions of this Creative Commons
62 | Attribution-NonCommercial 4.0 International Public License ("Public
63 | License"). To the extent this Public License may be interpreted as a
64 | contract, You are granted the Licensed Rights in consideration of Your
65 | acceptance of these terms and conditions, and the Licensor grants You
66 | such rights in consideration of benefits the Licensor receives from
67 | making the Licensed Material available under these terms and
68 | conditions.
69 |
70 |
71 | Section 1 -- Definitions.
72 |
73 | a. Adapted Material means material subject to Copyright and Similar
74 | Rights that is derived from or based upon the Licensed Material
75 | and in which the Licensed Material is translated, altered,
76 | arranged, transformed, or otherwise modified in a manner requiring
77 | permission under the Copyright and Similar Rights held by the
78 | Licensor. For purposes of this Public License, where the Licensed
79 | Material is a musical work, performance, or sound recording,
80 | Adapted Material is always produced where the Licensed Material is
81 | synched in timed relation with a moving image.
82 |
83 | b. Adapter's License means the license You apply to Your Copyright
84 | and Similar Rights in Your contributions to Adapted Material in
85 | accordance with the terms and conditions of this Public License.
86 |
87 | c. Copyright and Similar Rights means copyright and/or similar rights
88 | closely related to copyright including, without limitation,
89 | performance, broadcast, sound recording, and Sui Generis Database
90 | Rights, without regard to how the rights are labeled or
91 | categorized. For purposes of this Public License, the rights
92 | specified in Section 2(b)(1)-(2) are not Copyright and Similar
93 | Rights.
94 | d. Effective Technological Measures means those measures that, in the
95 | absence of proper authority, may not be circumvented under laws
96 | fulfilling obligations under Article 11 of the WIPO Copyright
97 | Treaty adopted on December 20, 1996, and/or similar international
98 | agreements.
99 |
100 | e. Exceptions and Limitations means fair use, fair dealing, and/or
101 | any other exception or limitation to Copyright and Similar Rights
102 | that applies to Your use of the Licensed Material.
103 |
104 | f. Licensed Material means the artistic or literary work, database,
105 | or other material to which the Licensor applied this Public
106 | License.
107 |
108 | g. Licensed Rights means the rights granted to You subject to the
109 | terms and conditions of this Public License, which are limited to
110 | all Copyright and Similar Rights that apply to Your use of the
111 | Licensed Material and that the Licensor has authority to license.
112 |
113 | h. Licensor means the individual(s) or entity(ies) granting rights
114 | under this Public License.
115 |
116 | i. NonCommercial means not primarily intended for or directed towards
117 | commercial advantage or monetary compensation. For purposes of
118 | this Public License, the exchange of the Licensed Material for
119 | other material subject to Copyright and Similar Rights by digital
120 | file-sharing or similar means is NonCommercial provided there is
121 | no payment of monetary compensation in connection with the
122 | exchange.
123 |
124 | j. Share means to provide material to the public by any means or
125 | process that requires permission under the Licensed Rights, such
126 | as reproduction, public display, public performance, distribution,
127 | dissemination, communication, or importation, and to make material
128 | available to the public including in ways that members of the
129 | public may access the material from a place and at a time
130 | individually chosen by them.
131 |
132 | k. Sui Generis Database Rights means rights other than copyright
133 | resulting from Directive 96/9/EC of the European Parliament and of
134 | the Council of 11 March 1996 on the legal protection of databases,
135 | as amended and/or succeeded, as well as other essentially
136 | equivalent rights anywhere in the world.
137 |
138 | l. You means the individual or entity exercising the Licensed Rights
139 | under this Public License. Your has a corresponding meaning.
140 |
141 |
142 | Section 2 -- Scope.
143 |
144 | a. License grant.
145 |
146 | 1. Subject to the terms and conditions of this Public License,
147 | the Licensor hereby grants You a worldwide, royalty-free,
148 | non-sublicensable, non-exclusive, irrevocable license to
149 | exercise the Licensed Rights in the Licensed Material to:
150 |
151 | a. reproduce and Share the Licensed Material, in whole or
152 | in part, for NonCommercial purposes only; and
153 |
154 | b. produce, reproduce, and Share Adapted Material for
155 | NonCommercial purposes only.
156 |
157 | 2. Exceptions and Limitations. For the avoidance of doubt, where
158 | Exceptions and Limitations apply to Your use, this Public
159 | License does not apply, and You do not need to comply with
160 | its terms and conditions.
161 |
162 | 3. Term. The term of this Public License is specified in Section
163 | 6(a).
164 |
165 | 4. Media and formats; technical modifications allowed. The
166 | Licensor authorizes You to exercise the Licensed Rights in
167 | all media and formats whether now known or hereafter created,
168 | and to make technical modifications necessary to do so. The
169 | Licensor waives and/or agrees not to assert any right or
170 | authority to forbid You from making technical modifications
171 | necessary to exercise the Licensed Rights, including
172 | technical modifications necessary to circumvent Effective
173 | Technological Measures. For purposes of this Public License,
174 | simply making modifications authorized by this Section 2(a)
175 | (4) never produces Adapted Material.
176 |
177 | 5. Downstream recipients.
178 |
179 | a. Offer from the Licensor -- Licensed Material. Every
180 | recipient of the Licensed Material automatically
181 | receives an offer from the Licensor to exercise the
182 | Licensed Rights under the terms and conditions of this
183 | Public License.
184 |
185 | b. No downstream restrictions. You may not offer or impose
186 | any additional or different terms or conditions on, or
187 | apply any Effective Technological Measures to, the
188 | Licensed Material if doing so restricts exercise of the
189 | Licensed Rights by any recipient of the Licensed
190 | Material.
191 |
192 | 6. No endorsement. Nothing in this Public License constitutes or
193 | may be construed as permission to assert or imply that You
194 | are, or that Your use of the Licensed Material is, connected
195 | with, or sponsored, endorsed, or granted official status by,
196 | the Licensor or others designated to receive attribution as
197 | provided in Section 3(a)(1)(A)(i).
198 |
199 | b. Other rights.
200 |
201 | 1. Moral rights, such as the right of integrity, are not
202 | licensed under this Public License, nor are publicity,
203 | privacy, and/or other similar personality rights; however, to
204 | the extent possible, the Licensor waives and/or agrees not to
205 | assert any such rights held by the Licensor to the limited
206 | extent necessary to allow You to exercise the Licensed
207 | Rights, but not otherwise.
208 |
209 | 2. Patent and trademark rights are not licensed under this
210 | Public License.
211 |
212 | 3. To the extent possible, the Licensor waives any right to
213 | collect royalties from You for the exercise of the Licensed
214 | Rights, whether directly or through a collecting society
215 | under any voluntary or waivable statutory or compulsory
216 | licensing scheme. In all other cases the Licensor expressly
217 | reserves any right to collect such royalties, including when
218 | the Licensed Material is used other than for NonCommercial
219 | purposes.
220 |
221 |
222 | Section 3 -- License Conditions.
223 |
224 | Your exercise of the Licensed Rights is expressly made subject to the
225 | following conditions.
226 |
227 | a. Attribution.
228 |
229 | 1. If You Share the Licensed Material (including in modified
230 | form), You must:
231 |
232 | a. retain the following if it is supplied by the Licensor
233 | with the Licensed Material:
234 |
235 | i. identification of the creator(s) of the Licensed
236 | Material and any others designated to receive
237 | attribution, in any reasonable manner requested by
238 | the Licensor (including by pseudonym if
239 | designated);
240 |
241 | ii. a copyright notice;
242 |
243 | iii. a notice that refers to this Public License;
244 |
245 | iv. a notice that refers to the disclaimer of
246 | warranties;
247 |
248 | v. a URI or hyperlink to the Licensed Material to the
249 | extent reasonably practicable;
250 |
251 | b. indicate if You modified the Licensed Material and
252 | retain an indication of any previous modifications; and
253 |
254 | c. indicate the Licensed Material is licensed under this
255 | Public License, and include the text of, or the URI or
256 | hyperlink to, this Public License.
257 |
258 | 2. You may satisfy the conditions in Section 3(a)(1) in any
259 | reasonable manner based on the medium, means, and context in
260 | which You Share the Licensed Material. For example, it may be
261 | reasonable to satisfy the conditions by providing a URI or
262 | hyperlink to a resource that includes the required
263 | information.
264 |
265 | 3. If requested by the Licensor, You must remove any of the
266 | information required by Section 3(a)(1)(A) to the extent
267 | reasonably practicable.
268 |
269 | 4. If You Share Adapted Material You produce, the Adapter's
270 | License You apply must not prevent recipients of the Adapted
271 | Material from complying with this Public License.
272 |
273 |
274 | Section 4 -- Sui Generis Database Rights.
275 |
276 | Where the Licensed Rights include Sui Generis Database Rights that
277 | apply to Your use of the Licensed Material:
278 |
279 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right
280 | to extract, reuse, reproduce, and Share all or a substantial
281 | portion of the contents of the database for NonCommercial purposes
282 | only;
283 |
284 | b. if You include all or a substantial portion of the database
285 | contents in a database in which You have Sui Generis Database
286 | Rights, then the database in which You have Sui Generis Database
287 | Rights (but not its individual contents) is Adapted Material; and
288 |
289 | c. You must comply with the conditions in Section 3(a) if You Share
290 | all or a substantial portion of the contents of the database.
291 |
292 | For the avoidance of doubt, this Section 4 supplements and does not
293 | replace Your obligations under this Public License where the Licensed
294 | Rights include other Copyright and Similar Rights.
295 |
296 |
297 | Section 5 -- Disclaimer of Warranties and Limitation of Liability.
298 |
299 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
300 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
301 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
302 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
303 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
304 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
305 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
306 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
307 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
308 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
309 |
310 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
311 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
312 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
313 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
314 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
315 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
316 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
317 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
318 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
319 |
320 | c. The disclaimer of warranties and limitation of liability provided
321 | above shall be interpreted in a manner that, to the extent
322 | possible, most closely approximates an absolute disclaimer and
323 | waiver of all liability.
324 |
325 |
326 | Section 6 -- Term and Termination.
327 |
328 | a. This Public License applies for the term of the Copyright and
329 | Similar Rights licensed here. However, if You fail to comply with
330 | this Public License, then Your rights under this Public License
331 | terminate automatically.
332 |
333 | b. Where Your right to use the Licensed Material has terminated under
334 | Section 6(a), it reinstates:
335 |
336 | 1. automatically as of the date the violation is cured, provided
337 | it is cured within 30 days of Your discovery of the
338 | violation; or
339 |
340 | 2. upon express reinstatement by the Licensor.
341 |
342 | For the avoidance of doubt, this Section 6(b) does not affect any
343 | right the Licensor may have to seek remedies for Your violations
344 | of this Public License.
345 |
346 | c. For the avoidance of doubt, the Licensor may also offer the
347 | Licensed Material under separate terms or conditions or stop
348 | distributing the Licensed Material at any time; however, doing so
349 | will not terminate this Public License.
350 |
351 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
352 | License.
353 |
354 |
355 | Section 7 -- Other Terms and Conditions.
356 |
357 | a. The Licensor shall not be bound by any additional or different
358 | terms or conditions communicated by You unless expressly agreed.
359 |
360 | b. Any arrangements, understandings, or agreements regarding the
361 | Licensed Material not stated herein are separate from and
362 | independent of the terms and conditions of this Public License.
363 |
364 |
365 | Section 8 -- Interpretation.
366 |
367 | a. For the avoidance of doubt, this Public License does not, and
368 | shall not be interpreted to, reduce, limit, restrict, or impose
369 | conditions on any use of the Licensed Material that could lawfully
370 | be made without permission under this Public License.
371 |
372 | b. To the extent possible, if any provision of this Public License is
373 | deemed unenforceable, it shall be automatically reformed to the
374 | minimum extent necessary to make it enforceable. If the provision
375 | cannot be reformed, it shall be severed from this Public License
376 | without affecting the enforceability of the remaining terms and
377 | conditions.
378 |
379 | c. No term or condition of this Public License will be waived and no
380 | failure to comply consented to unless expressly agreed to by the
381 | Licensor.
382 |
383 | d. Nothing in this Public License constitutes or may be interpreted
384 | as a limitation upon, or waiver of, any privileges and immunities
385 | that apply to the Licensor or You, including from the legal
386 | processes of any jurisdiction or authority.
387 |
388 | =======================================================================
389 |
390 | Creative Commons is not a party to its public
391 | licenses. Notwithstanding, Creative Commons may elect to apply one of
392 | its public licenses to material it publishes and in those instances
393 | will be considered the “Licensor.” The text of the Creative Commons
394 | public licenses is dedicated to the public domain under the CC0 Public
395 | Domain Dedication. Except for the limited purpose of indicating that
396 | material is shared under a Creative Commons public license or as
397 | otherwise permitted by the Creative Commons policies published at
398 | creativecommons.org/policies, Creative Commons does not authorize the
399 | use of the trademark "Creative Commons" or any other trademark or logo
400 | of Creative Commons without its prior written consent including,
401 | without limitation, in connection with any unauthorized modifications
402 | to any of its public licenses or any other arrangements,
403 | understandings, or agreements concerning use of licensed material. For
404 | the avoidance of doubt, this paragraph does not form part of the
405 | public licenses.
406 |
407 | Creative Commons may be contacted at creativecommons.org.
408 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
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 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
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.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Code Alpaca: An Instruction-following LLaMA Model trained on code generation instructions
2 | [](https://github.com/tatsu-lab/stanford_alpaca/blob/main/LICENSE)
3 | [](https://www.python.org/downloads/release/python-390/)
4 | [](https://github.com/psf/black)
5 |
6 | This is the repo for the Code Alpaca project, which aims to build and share an instruction-following LLaMA model for code generation. This repo is fully based on [Stanford Alpaca](https://github.com/tatsu-lab/stanford_alpaca) ,and only changes the data used for training. Training approach is the same.
7 |
8 | The repo contains:
9 | - The [20K data](#data-release) used for fine-tuning the model
10 | - The code for [generating the data](#data-generation-process)
11 | - The code for [fine-tuning the model](#fine-tuning)
12 |
13 | Demo for the model can be found [https://code-alpaca-demo.vercel.app/](https://code-alpaca-demo.vercel.app/)
14 |
15 | ## Overview
16 |
17 | The Code Alpaca models are fine-tuned from a 7B and 13B LLaMA model on 20K instruction-following data generated by the techniques in the Self-Instruct [1] paper, with some modifications that we discuss in the next section.
18 | Evals are still a todo.
19 |
20 | The model is not finetuned to be safe and harmless, so be cautious.
21 |
22 | Current release contains the data generation procedure, dataset, and training code. Model weights aren't part of the release for now, to respect OpenAI TOS and LLaMA license.
23 |
24 | [1]: Self-Instruct: Aligning Language Model with Self Generated Instructions. Yizhong Wang, Yeganeh Kordi, Swaroop Mishra, Alisa Liu, Noah A. Smith, Daniel Khashabi, Hannaneh Hajishirzi. https://arxiv.org/abs/2212.10560
25 |
26 |
27 | ## Data Release
28 | [`data/code_alpaca_20k.json`](./data/code_alpaca_20k.json) contains 20K instruction-following data used for fine-tuning the Code Alpaca model.
29 | This JSON file is a list of dictionaries, each dictionary contains the following fields:
30 | - `instruction`: `str`, describes the task the model should perform. Each of the 20K instructions is unique.
31 | - `input`: `str`, optional context or input for the task. For example, when the instruction is "Amend the following SQL query to select distinct elements", the input is the SQL query. Around 40% of the examples have an input.
32 | - `output`: `str`, the answer to the instruction as generated by `text-davinci-003`.
33 |
34 | We used the following prompts for fine-tuning the model:
35 | - for examples with a non-empty input field:
36 | ```
37 | Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
38 |
39 | ### Instruction:
40 | {instruction}
41 |
42 | ### Input:
43 | {input}
44 |
45 | ### Response:
46 | ```
47 | - for examples with an empty input field:
48 | ```
49 | Below is an instruction that describes a task. Write a response that appropriately completes the request.
50 |
51 | ### Instruction:
52 | {instruction}
53 |
54 | ### Response:
55 | ```
56 |
57 | During inference (eg for the web demo), we use the user instruction with an empty input field (second option).
58 |
59 | ## Data Generation Process
60 |
61 |
62 | Running the code
63 |
64 | 1. Set environment variables `OPENAI_API_KEY` to your OpenAI API key.
65 | 2. Install the dependencies with `pip install -r requirements.txt`.
66 | 3. Run `python -m generate_instruction generate_instruction_following_data` to generate the data.
67 |
68 |
69 | Data generation pipeline had minor changes from [Stanford Alpaca](https://github.com/tatsu-lab/stanford_alpaca)
70 | - Modified prompt to focus on code generation/editing/optimization tasks instead of general tasks.
71 | - Modified seed tasks to only be related to code generation.
72 |
73 | This produced an instruction-following dataset with 20K examples obtained at a much lower cost (less than $200). Also including a smaller 2k samples dataset which was used to derisk the approach and quality of the model.
74 |
75 | ## Fine-tuning
76 | Finetuned the models using standard Hugging Face training code and deepspeed with the following hyperparameters:
77 |
78 | | Hyperparameter | Value |
79 | |----------------|-------|
80 | | Learning rate | 2e-5 |
81 | | Epochs | 3 |
82 | | Max length | 512 |
83 | | Weight decay | 0 |
84 |
85 | Given Hugging Face hasn't officially supported the LLaMA models, we fine-tuned LLaMA with Hugging Face's transformers library by installing it from a particular fork (i.e. this [PR](https://github.com/huggingface/transformers/pull/21955) to be merged).
86 | The hash of the specific commit we installed was `68d640f7c368bcaaaecfc678f11908ebbd3d6176`.
87 |
88 | The code runs on a 8xA100 80GB, but can also run on 8xA10040GB or 4xA100 with lower batch size and gradient accumulation steps. To get the GPUs, I suggest using [Lambda Labs](https://cloud.lambdalabs.com/login?redirect_to=/instances?), best pricing for the best hardware.
89 |
90 | To reproduce the fine-tuning runs for LLaMA, first install the requirements
91 | ```bash
92 | pip install -r requirements.txt
93 | ```
94 | Then, install the particular fork of Hugging Face's transformers library.
95 |
96 | Below is a command that fine-tunes LLaMA-7B with our dataset on a machine with 4 A100 80G GPUs using deepspeed.
97 |
98 | Replace `` with a port of your own, `` with the
99 | path to your converted checkpoint and tokenizer (following instructions in the PR), and `` with where you want to store your outputs.
100 |
101 | ```bash
102 | torchrun --nproc_per_node=8 --master_port= train.py \
103 | --model_name_or_path
104 | --data_path ./data/code_alpaca_20k.json \
105 | --fp16 True \
106 | --output_dir \
107 | --num_train_epochs 3 \
108 | --per_device_train_batch_size 8 \
109 | --per_device_eval_batch_size 8 \
110 | --gradient_accumulation_steps 4 \
111 | --evaluation_strategy "no" \
112 | --save_strategy "steps" \
113 | --save_steps 500 \
114 | --save_total_limit 1 \
115 | --learning_rate 2e-5 \
116 | --weight_decay 0. \
117 | --warmup_ratio 0.03 \
118 | --lr_scheduler_type "cosine" \
119 | --logging_steps 1 \
120 | --deepspeed ds_config.json
121 | --tf32 False
122 | ```
123 |
124 | Note the given training script is meant to be simple and easy to use, and is not particularly optimized.
125 |
126 | For convenience I have included the [`convert_to_hf.py`](./convert_to_hf.py) to covnert llama checkpoints to huggingface compatible checkpoints. (This file is taken from the hugginface transformers repo)
127 |
128 | ### Citation
129 |
130 | Cite this repo if you want to, or don't, both are fine.
131 | ```
132 | @misc{codealpaca,
133 | author = {Sahil Chaudhary},
134 | title = {Code Alpaca: An Instruction-following LLaMA model for code generation},
135 | year = {2023},
136 | publisher = {GitHub},
137 | journal = {GitHub repository},
138 | howpublished = {\url{https://github.com/sahil280114/codealpaca}},
139 | }
140 | ```
141 |
142 | Naturally, you should also cite the original LLaMA paper [1] and the Self-Instruct paper [2] and the [Stanford Alpaca repo](https://github.com/tatsu-lab/stanford_alpaca).
143 |
--------------------------------------------------------------------------------
/convert_to_hf.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import json
3 | import math
4 | import os
5 | import shutil
6 |
7 | import torch
8 |
9 |
10 | """
11 | Sample usage:
12 | ```
13 | python co.py --input_dir . --model_size 13B --output_dir output/ d
14 | ```
15 | Thereafter, models can be loaded via:
16 | ```
17 | tokenizer = transformers.LLaMATokenizer.from_pretrained("/output/path/tokenizer/")
18 | model = transformers.LLaMAForCausalLM.from_pretrained("/output/path/llama-7b/")
19 | ```
20 | """
21 |
22 | INTERMEDIATE_SIZE_MAP = {
23 | "7B": 11008,
24 | "13B": 13824,
25 | "30B": 17920,
26 | "65B": 22016,
27 | }
28 | NUM_SHARDS = {
29 | "7B": 1,
30 | "13B": 2,
31 | "30B": 4,
32 | "65B": 8,
33 | }
34 |
35 |
36 | def compute_intermediate_size(n):
37 | return int(math.ceil(n * 8 / 3) + 255) // 256 * 256
38 |
39 |
40 | def read_json(path):
41 | with open(path, "r") as f:
42 | return json.load(f)
43 |
44 |
45 | def write_json(text, path):
46 | with open(path, "w") as f:
47 | json.dump(text, f)
48 |
49 |
50 | def write_model(model_path, input_base_path, model_size):
51 | assert model_size in NUM_SHARDS
52 | os.makedirs(model_path, exist_ok=True)
53 |
54 | params = read_json(os.path.join(input_base_path, "params.json"))
55 | num_shards = NUM_SHARDS[model_size]
56 | n_layers = params["n_layers"]
57 | n_heads = params["n_heads"]
58 | n_heads_per_shard = n_heads // num_shards
59 | dim = params["dim"]
60 | dims_per_head = dim // n_heads
61 | base = 10000.0
62 | inv_freq = 1.0 / (base ** (torch.arange(0, dims_per_head, 2).float() / dims_per_head))
63 |
64 | # permute for sliced rotary
65 | def permute(w):
66 | return w.view(n_heads, dim // n_heads // 2, 2, dim).transpose(1, 2).reshape(dim, dim)
67 |
68 | # Load weights
69 | if model_size == "7B":
70 | # Not shared
71 | # (The sharded implementation would also work, but this is simpler.)
72 | loaded = torch.load(os.path.join(input_base_path, "consolidated.00.pth"), map_location="cpu")
73 | else:
74 | # Sharded
75 | loaded = [
76 | torch.load(os.path.join(input_base_path, f"consolidated.{i:02d}.pth"), map_location="cpu")
77 | for i in range(num_shards)
78 | ]
79 | param_count = 0
80 | index_dict = {"weight_map": {}}
81 | for layer_i in range(n_layers):
82 | filename = "pytorch_model-{:05d}-of-{:05d}.bin".format(
83 | layer_i + 1,
84 | n_layers + 1,
85 | )
86 | if model_size == "7B":
87 | # Unsharded
88 | state_dict = {
89 | f"model.layers.{layer_i}.self_attn.q_proj.weight": permute(
90 | loaded[f"layers.{layer_i}.attention.wq.weight"]
91 | ),
92 | f"model.layers.{layer_i}.self_attn.k_proj.weight": permute(
93 | loaded[f"layers.{layer_i}.attention.wk.weight"]
94 | ),
95 | f"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[f"layers.{layer_i}.attention.wv.weight"],
96 | f"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[f"layers.{layer_i}.attention.wo.weight"],
97 | f"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w1.weight"],
98 | f"model.layers.{layer_i}.mlp.down_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w2.weight"],
99 | f"model.layers.{layer_i}.mlp.up_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w3.weight"],
100 | f"model.layers.{layer_i}.input_layernorm.weight": loaded[f"layers.{layer_i}.attention_norm.weight"],
101 | f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[f"layers.{layer_i}.ffn_norm.weight"],
102 | }
103 | else:
104 | # Sharded
105 | state_dict = {
106 | f"model.layers.{layer_i}.input_layernorm.weight": loaded[0][f"layers.{layer_i}.attention_norm.weight"],
107 | f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][
108 | f"layers.{layer_i}.ffn_norm.weight"
109 | ],
110 | }
111 | state_dict[f"model.layers.{layer_i}.self_attn.q_proj.weight"] = permute(
112 | torch.cat(
113 | [
114 | loaded[i][f"layers.{layer_i}.attention.wq.weight"].view(n_heads_per_shard, dims_per_head, dim)
115 | for i in range(num_shards)
116 | ],
117 | dim=0,
118 | ).reshape(dim, dim)
119 | )
120 | state_dict[f"model.layers.{layer_i}.self_attn.k_proj.weight"] = permute(
121 | torch.cat(
122 | [
123 | loaded[i][f"layers.{layer_i}.attention.wk.weight"].view(n_heads_per_shard, dims_per_head, dim)
124 | for i in range(num_shards)
125 | ],
126 | dim=0,
127 | ).reshape(dim, dim)
128 | )
129 | state_dict[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = torch.cat(
130 | [
131 | loaded[i][f"layers.{layer_i}.attention.wv.weight"].view(n_heads_per_shard, dims_per_head, dim)
132 | for i in range(num_shards)
133 | ],
134 | dim=0,
135 | ).reshape(dim, dim)
136 |
137 | state_dict[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = torch.cat(
138 | [loaded[i][f"layers.{layer_i}.attention.wo.weight"] for i in range(num_shards)], dim=1
139 | )
140 | state_dict[f"model.layers.{layer_i}.mlp.gate_proj.weight"] = torch.cat(
141 | [loaded[i][f"layers.{layer_i}.feed_forward.w1.weight"] for i in range(num_shards)], dim=0
142 | )
143 | state_dict[f"model.layers.{layer_i}.mlp.down_proj.weight"] = torch.cat(
144 | [loaded[i][f"layers.{layer_i}.feed_forward.w2.weight"] for i in range(num_shards)], dim=1
145 | )
146 | state_dict[f"model.layers.{layer_i}.mlp.up_proj.weight"] = torch.cat(
147 | [loaded[i][f"layers.{layer_i}.feed_forward.w3.weight"] for i in range(num_shards)], dim=0
148 | )
149 |
150 | state_dict[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = inv_freq
151 | for k, v in state_dict.items():
152 | index_dict["weight_map"][k] = filename
153 | param_count += v.numel()
154 | torch.save(state_dict, os.path.join(model_path, filename))
155 |
156 | filename = "pytorch_model-{:05d}-of-{:05d}.bin".format(
157 | n_layers + 1,
158 | n_layers + 1,
159 | )
160 | if model_size == "7B":
161 | # Unsharded
162 | state_dict = {
163 | "model.embed_tokens.weight": loaded["tok_embeddings.weight"],
164 | "model.norm.weight": loaded["norm.weight"],
165 | "lm_head.weight": loaded["output.weight"],
166 | }
167 | else:
168 | state_dict = {
169 | "model.norm.weight": loaded[0]["norm.weight"],
170 | "model.embed_tokens.weight": torch.cat(
171 | [loaded[i]["tok_embeddings.weight"] for i in range(num_shards)], dim=1
172 | ),
173 | "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(num_shards)], dim=0),
174 | }
175 |
176 | for k, v in state_dict.items():
177 | index_dict["weight_map"][k] = filename
178 | param_count += v.numel()
179 | torch.save(state_dict, os.path.join(model_path, filename))
180 |
181 | # Write configs
182 | index_dict["metadata"] = {"total_size": param_count * 2}
183 | write_json(index_dict, os.path.join(model_path, "pytorch_model.bin.index.json"))
184 | config_out = {
185 | "architectures": ["LlamaForCausalLM"],
186 | "bos_token_id": 1,
187 | "eos_token_id": 2,
188 | "hidden_act": "silu",
189 | "hidden_size": dim,
190 | "intermediate_size": compute_intermediate_size(dim),
191 | "initializer_range": 0.02,
192 | "max_sequence_length": 2048,
193 | "model_type": "llama",
194 | "num_attention_heads": params["n_heads"],
195 | "num_hidden_layers": params["n_layers"],
196 | "pad_token_id": 0,
197 | "rms_norm_eps": params["norm_eps"],
198 | "torch_dtype": "float16",
199 | "transformers_version": "4.27.0.dev0",
200 | "use_cache": True,
201 | "vocab_size": 32000,
202 | }
203 | write_json(
204 | config_out,
205 | os.path.join(model_path, "config.json"),
206 | )
207 | generation_config = {
208 | "_from_model_config": True,
209 | "bos_token_id": 1,
210 | "eos_token_id": 2,
211 | "pad_token_id": 0,
212 | "transformers_version": "4.27.0.dev0",
213 | }
214 | write_json(
215 | generation_config,
216 | os.path.join(model_path, "generation_config.json"),
217 | )
218 |
219 |
220 | def write_tokenizer(tokenizer_path, input_tokenizer_path):
221 | os.makedirs(tokenizer_path, exist_ok=True)
222 | write_json({}, os.path.join(tokenizer_path, "special_tokens_map.json"))
223 | write_json(
224 | {
225 | "bos_token": "",
226 | "eos_token": "",
227 | "model_max_length": int(1e30),
228 | "tokenizer_class": "LlamaTokenizer",
229 | "unk_token": "",
230 | },
231 | os.path.join(tokenizer_path, "tokenizer_config.json"),
232 | )
233 | shutil.copyfile(input_tokenizer_path, os.path.join(tokenizer_path, "tokenizer.model"))
234 |
235 |
236 | def main():
237 | parser = argparse.ArgumentParser()
238 | parser.add_argument(
239 | "--input_dir",
240 | help="Location of LLaMA weights, which contains tokenizer.model and model folders",
241 | )
242 | parser.add_argument(
243 | "--model_size",
244 | choices=["7B", "13B", "30B", "65B", "tokenizer_only"],
245 | )
246 | parser.add_argument(
247 | "--output_dir",
248 | help="Location to write HF model and tokenizer",
249 | )
250 | args = parser.parse_args()
251 | if args.model_size != "tokenizer_only":
252 | write_model(
253 | model_path=os.path.join(args.output_dir, "llama-{}".format(args.model_size).lower()),
254 | input_base_path=os.path.join(args.input_dir, args.model_size),
255 | model_size=args.model_size,
256 | )
257 | write_tokenizer(
258 | tokenizer_path=os.path.join(args.output_dir, "tokenizer"),
259 | input_tokenizer_path=os.path.join(args.input_dir, "tokenizer.model"),
260 | )
261 |
262 |
263 | if __name__ == "__main__":
264 | main()
--------------------------------------------------------------------------------
/ds_config.json:
--------------------------------------------------------------------------------
1 | {
2 | "zero_optimization": {
3 | "stage": 3,
4 | "contiguous_gradients": true,
5 | "stage3_max_live_parameters": 0,
6 | "stage3_max_reuse_distance": 0,
7 | "stage3_prefetch_bucket_size": 0,
8 | "stage3_param_persistence_threshold": 100,
9 | "reduce_bucket_size": 100,
10 | "sub_group_size": 100000000,
11 | "offload_optimizer": {
12 | "device": "cpu",
13 | "pin_memory": true
14 | },
15 | "offload_param": {
16 | "device": "cpu",
17 | "pin_memory": true
18 | },
19 | "stage3_gather_16bit_weights_on_model_save": true
20 | },
21 | "optimizer": {
22 | "type": "Adam",
23 | "params": {
24 | "lr": 0.00002,
25 | "betas": [
26 | 0.9,
27 | 0.999
28 | ],
29 | "eps": 1e-8,
30 | "weight_decay": 0
31 | }
32 | },
33 | "fp16": {
34 | "enabled": "auto",
35 | "auto_cast": "auto",
36 | "loss_scale": 0,
37 | "initial_scale_power": 32,
38 | "loss_scale_window": 1000,
39 | "hysteresis": 2,
40 | "min_loss_scale": 1
41 | },
42 | "train_batch_size": "auto",
43 | "train_micro_batch_size_per_gpu": "auto",
44 | "wall_clock_breakdown": false
45 | }
46 |
--------------------------------------------------------------------------------
/generate_instruction.py:
--------------------------------------------------------------------------------
1 | """
2 | batch_selfinstruct_generate.py
3 |
4 | run:
5 | python -m generate_instruction generate_instruction_following_data \
6 | --output_dir ./ \
7 | --num_instructions_to_generate 10 \
8 | --model_name="text-davinci-003" \
9 | """
10 | import time
11 | import json
12 | import os
13 | import random
14 | import re
15 | import string
16 | from functools import partial
17 | from multiprocessing import Pool
18 |
19 | import numpy as np
20 | import tqdm
21 | from rouge_score import rouge_scorer
22 | import utils
23 |
24 | import fire
25 |
26 |
27 | def encode_prompt(prompt_instructions):
28 | """Encode multiple prompt instructions into a single string."""
29 | prompt = open("./prompt.txt").read() + "\n"
30 |
31 | for idx, task_dict in enumerate(prompt_instructions):
32 | (instruction, input, output) = task_dict["instruction"], task_dict["input"], task_dict["output"]
33 | instruction = re.sub(r"\s+", " ", instruction).strip().rstrip(":")
34 | input = "" if input.lower() == "" else input
35 | prompt += f"###\n"
36 | prompt += f"{idx + 1}. Instruction: {instruction}\n"
37 | prompt += f"{idx + 1}. Input:\n{input}\n"
38 | prompt += f"{idx + 1}. Output:\n{output}\n"
39 | prompt += f"###\n"
40 | prompt += f"{idx + 2}. Instruction:"
41 | return prompt
42 |
43 |
44 | def post_process_gpt3_response(num_prompt_instructions, response):
45 | if response is None:
46 | return []
47 | raw_instructions = f"{num_prompt_instructions+1}. Instruction:" + response["text"]
48 | raw_instructions = re.split("###", raw_instructions)
49 | instructions = []
50 | for idx, inst in enumerate(raw_instructions):
51 | # if the decoding stops due to length, the last example is likely truncated so we discard it
52 | if idx == len(raw_instructions) - 1 and response["finish_reason"] == "length":
53 | continue
54 | idx += num_prompt_instructions + 1
55 | splitted_data = re.split(f"{idx}\.\s+(Instruction|Input|Output):", inst)
56 | if len(splitted_data) != 7:
57 | continue
58 | else:
59 | inst = splitted_data[2].strip()
60 | input = splitted_data[4].strip()
61 | input = "" if input.lower() == "" else input
62 | output = splitted_data[6].strip()
63 | # filter out too short or too long instructions
64 | if len(inst.split()) <= 3 or len(inst.split()) > 150:
65 | continue
66 | # filter based on keywords that are not suitable for language models.
67 | blacklist = [
68 | "image",
69 | "images",
70 | "graph",
71 | "graphs",
72 | "picture",
73 | "pictures",
74 | "file",
75 | "files",
76 | "map",
77 | "maps",
78 | "draw",
79 | "plot",
80 | "go to",
81 | "video",
82 | "audio",
83 | "music",
84 | "flowchart",
85 | "diagram",
86 | ]
87 | blacklist += []
88 | if any(find_word_in_string(word, inst) for word in blacklist):
89 | continue
90 | # We found that the model tends to add "write a program" to some existing instructions, which lead to a lot of such instructions.
91 | # And it's a bit comfusing whether the model need to write a program or directly output the result.
92 | # Here we filter them out.
93 | # Note this is not a comprehensive filtering for all programming instructions.
94 | if inst.startswith("Write a program"):
95 | continue
96 | # filter those starting with punctuation
97 | if inst[0] in string.punctuation:
98 | continue
99 | # filter those starting with non-english character
100 | if not inst[0].isascii():
101 | continue
102 | instructions.append({"instruction": inst, "input": input, "output": output})
103 | return instructions
104 |
105 |
106 | def find_word_in_string(w, s):
107 | return re.compile(r"\b({0})\b".format(w), flags=re.IGNORECASE).search(s)
108 |
109 |
110 | def generate_instruction_following_data(
111 | output_dir="./",
112 | seed_tasks_path="./seed_tasks.jsonl",
113 | num_instructions_to_generate=20000,
114 | model_name="text-davinci-003",
115 | num_prompt_instructions=3,
116 | request_batch_size=5,
117 | temperature=1.0,
118 | top_p=1.0,
119 | num_cpus=16,
120 | ):
121 | seed_tasks = [json.loads(l) for l in open(seed_tasks_path, "r")]
122 | seed_instruction_data = [
123 | {"instruction": t["instruction"], "input": t["instances"][0]["input"], "output": t["instances"][0]["output"]}
124 | for t in seed_tasks
125 | ]
126 | print(f"Loaded {len(seed_instruction_data)} human-written seed instructions")
127 |
128 | os.makedirs(output_dir, exist_ok=True)
129 | request_idx = 0
130 | # load the LM-generated instructions
131 | machine_instruction_data = []
132 | if os.path.exists(os.path.join(output_dir, "regen.json")):
133 | machine_instruction_data = utils.jload(os.path.join(output_dir, "regen.json"))
134 | print(f"Loaded {len(machine_instruction_data)} machine-generated instructions")
135 |
136 | # similarities = {}
137 | scorer = rouge_scorer.RougeScorer(["rougeL"], use_stemmer=False)
138 |
139 | # now let's generate new instructions!
140 | progress_bar = tqdm.tqdm(total=num_instructions_to_generate)
141 | if machine_instruction_data:
142 | progress_bar.update(len(machine_instruction_data))
143 |
144 | # first we tokenize all the seed instructions and generated machine instructions
145 | all_instructions = [d["instruction"] for d in seed_instruction_data] + [
146 | d["instruction"] for d in machine_instruction_data
147 | ]
148 | all_instruction_tokens = [scorer._tokenizer.tokenize(inst) for inst in all_instructions]
149 |
150 | while len(machine_instruction_data) < num_instructions_to_generate:
151 | request_idx += 1
152 |
153 | batch_inputs = []
154 | for _ in range(request_batch_size):
155 | # only sampling from the seed tasks
156 | prompt_instructions = random.sample(seed_instruction_data, num_prompt_instructions)
157 | prompt = encode_prompt(prompt_instructions)
158 | batch_inputs.append(prompt)
159 | decoding_args = utils.OpenAIDecodingArguments(
160 | temperature=temperature,
161 | n=1,
162 | max_tokens=3072, # hard-code to maximize the length. the requests will be automatically adjusted
163 | top_p=top_p,
164 | stop=["\n20", "20.", "20."],
165 | )
166 | request_start = time.time()
167 | print("Calling openai...")
168 | results = utils.openai_completion(
169 | prompts=batch_inputs,
170 | model_name=model_name,
171 | batch_size=request_batch_size,
172 | decoding_args=decoding_args,
173 | logit_bias={"50256": -100}, # prevent the <|endoftext|> token from being generated
174 | )
175 | request_duration = time.time() - request_start
176 | print(f'request took - {request_duration}')
177 | process_start = time.time()
178 | instruction_data = []
179 | for result in results:
180 | new_instructions = post_process_gpt3_response(num_prompt_instructions, result)
181 | instruction_data += new_instructions
182 |
183 | total = len(instruction_data)
184 | keep = 0
185 | for instruction_data_entry in instruction_data:
186 | # computing similarity with the pre-tokenzied instructions
187 | new_instruction_tokens = scorer._tokenizer.tokenize(instruction_data_entry["instruction"])
188 | with Pool(num_cpus) as p:
189 | rouge_scores = p.map(
190 | partial(rouge_scorer._score_lcs, new_instruction_tokens),
191 | all_instruction_tokens,
192 | )
193 | rouge_scores = [score.fmeasure for score in rouge_scores]
194 | most_similar_instructions = {
195 | all_instructions[i]: rouge_scores[i] for i in np.argsort(rouge_scores)[-10:][::-1]
196 | }
197 | if max(rouge_scores) > 0.7:
198 | continue
199 | else:
200 | keep += 1
201 | instruction_data_entry["most_similar_instructions"] = most_similar_instructions
202 | instruction_data_entry["avg_similarity_score"] = float(np.mean(rouge_scores))
203 | machine_instruction_data.append(instruction_data_entry)
204 | all_instructions.append(instruction_data_entry["instruction"])
205 | all_instruction_tokens.append(new_instruction_tokens)
206 | progress_bar.update(1)
207 | process_duration = time.time() - process_start
208 | print(f"Request {request_idx} took {request_duration:.2f}s, processing took {process_duration:.2f}s")
209 | print(f"Generated {total} instructions, kept {keep} instructions")
210 | utils.jdump(machine_instruction_data, os.path.join(output_dir, "regen.json"))
211 |
212 |
213 | def main(task, **kwargs):
214 | globals()[task](**kwargs)
215 |
216 |
217 | if __name__ == "__main__":
218 | fire.Fire(main)
219 |
--------------------------------------------------------------------------------
/nolora.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | from typing import List
4 |
5 | import fire
6 | import torch
7 | import transformers
8 | from datasets import load_dataset
9 |
10 | """
11 | Unused imports:
12 | import torch.nn as nn
13 | import bitsandbytes as bnb
14 | """
15 |
16 | # from peft import (
17 | # LoraConfig,
18 | # get_peft_model,
19 | # get_peft_model_state_dict,
20 | # prepare_model_for_int8_training,
21 | # set_peft_model_state_dict,
22 | # )
23 | from transformers import AutoModelForCausalLM, AutoTokenizer
24 |
25 | from utils.prompter import Prompter
26 |
27 |
28 | def train(
29 | # model/data params
30 | base_model: str = "", # the only required argument
31 | data_path: str = "yahma/alpaca-cleaned",
32 | output_dir: str = "./lora-alpaca",
33 | # training hyperparams
34 | batch_size: int = 128,
35 | micro_batch_size: int = 8,
36 | num_epochs: int = 1,
37 | learning_rate: float = 3e-4,
38 | cutoff_len: int = 2048,
39 | val_set_size: int = 2000,
40 | # lora hyperparams
41 | lora_r: int = 8,
42 | lora_alpha: int = 16,
43 | lora_dropout: float = 0.05,
44 | lora_target_modules: List[str] = [
45 | "q_proj",
46 | "v_proj",
47 | ],
48 | # llm hyperparams
49 | train_on_inputs: bool = True, # if False, masks out inputs in loss
50 | group_by_length: bool = False, # faster, but produces an odd training loss curve
51 | # wandb params
52 | wandb_project: str = "",
53 | wandb_run_name: str = "",
54 | wandb_watch: str = "", # options: false | gradients | all
55 | wandb_log_model: str = "", # options: false | true
56 | resume_from_checkpoint: str = None, # either training checkpoint or final adapter
57 | prompt_template_name: str = "alpaca", # The prompt template to use, will default to alpaca.
58 | ):
59 | if int(os.environ.get("LOCAL_RANK", 0)) == 0:
60 | print(
61 | f"Training Alpaca-LoRA model with params:\n"
62 | f"base_model: {base_model}\n"
63 | f"data_path: {data_path}\n"
64 | f"output_dir: {output_dir}\n"
65 | f"batch_size: {batch_size}\n"
66 | f"micro_batch_size: {micro_batch_size}\n"
67 | f"num_epochs: {num_epochs}\n"
68 | f"learning_rate: {learning_rate}\n"
69 | f"cutoff_len: {cutoff_len}\n"
70 | f"val_set_size: {val_set_size}\n"
71 | f"lora_r: {lora_r}\n"
72 | f"lora_alpha: {lora_alpha}\n"
73 | f"lora_dropout: {lora_dropout}\n"
74 | f"lora_target_modules: {lora_target_modules}\n"
75 | f"train_on_inputs: {train_on_inputs}\n"
76 | f"group_by_length: {group_by_length}\n"
77 | f"wandb_project: {wandb_project}\n"
78 | f"wandb_run_name: {wandb_run_name}\n"
79 | f"wandb_watch: {wandb_watch}\n"
80 | f"wandb_log_model: {wandb_log_model}\n"
81 | f"resume_from_checkpoint: {resume_from_checkpoint or False}\n"
82 | f"prompt template: {prompt_template_name}\n"
83 | )
84 | assert (
85 | base_model
86 | ), "Please specify a --base_model, e.g. --base_model='huggyllama/llama-7b'"
87 | gradient_accumulation_steps = 16
88 |
89 | prompter = Prompter(prompt_template_name)
90 |
91 | device_map = "auto"
92 | world_size = int(os.environ.get("WORLD_SIZE", 1))
93 | ddp = world_size != 1
94 | if ddp:
95 | device_map = {"": int(os.environ.get("LOCAL_RANK") or 0)}
96 | gradient_accumulation_steps = gradient_accumulation_steps // world_size
97 |
98 | # Check if parameter passed or if set within environ
99 | use_wandb = len(wandb_project) > 0 or (
100 | "WANDB_PROJECT" in os.environ and len(os.environ["WANDB_PROJECT"]) > 0
101 | )
102 | # Only overwrite environ if wandb param passed
103 | if len(wandb_project) > 0:
104 | os.environ["WANDB_PROJECT"] = wandb_project
105 | if len(wandb_watch) > 0:
106 | os.environ["WANDB_WATCH"] = wandb_watch
107 | if len(wandb_log_model) > 0:
108 | os.environ["WANDB_LOG_MODEL"] = wandb_log_model
109 |
110 | model = AutoModelForCausalLM.from_pretrained(
111 | base_model,
112 | load_in_8bit=False,
113 | torch_dtype=torch.float16,
114 | device_map=device_map,
115 | )
116 |
117 | tokenizer = AutoTokenizer.from_pretrained(base_model)
118 |
119 | tokenizer.pad_token_id = (
120 | 0 # unk. we want this to be different from the eos token
121 | )
122 | tokenizer.padding_side = "left" # Allow batched inference
123 |
124 | def tokenize(prompt, add_eos_token=True):
125 | # there's probably a way to do this with the tokenizer settings
126 | # but again, gotta move fast
127 | result = tokenizer(
128 | prompt,
129 | truncation=True,
130 | max_length=cutoff_len,
131 | padding=False,
132 | return_tensors=None,
133 | )
134 | if (
135 | result["input_ids"][-1] != tokenizer.eos_token_id
136 | and len(result["input_ids"]) < cutoff_len
137 | and add_eos_token
138 | ):
139 | result["input_ids"].append(tokenizer.eos_token_id)
140 | result["attention_mask"].append(1)
141 |
142 | result["labels"] = result["input_ids"].copy()
143 |
144 | return result
145 |
146 | def generate_and_tokenize_prompt(data_point):
147 | full_prompt = prompter.generate_prompt(
148 | data_point["instruction"],
149 | data_point["input"],
150 | data_point["output"],
151 | )
152 | tokenized_full_prompt = tokenize(full_prompt)
153 | if not train_on_inputs:
154 | user_prompt = prompter.generate_prompt(
155 | data_point["instruction"], data_point["input"]
156 | )
157 | tokenized_user_prompt = tokenize(user_prompt, add_eos_token=False)
158 | user_prompt_len = len(tokenized_user_prompt["input_ids"])
159 |
160 | tokenized_full_prompt["labels"] = [
161 | -100
162 | ] * user_prompt_len + tokenized_full_prompt["labels"][
163 | user_prompt_len:
164 | ] # could be sped up, probably
165 | return tokenized_full_prompt
166 |
167 | if data_path.endswith(".json") or data_path.endswith(".jsonl"):
168 | data = load_dataset("json", data_files=data_path)
169 | else:
170 | data = load_dataset(data_path)
171 |
172 | if resume_from_checkpoint:
173 | # Check the available weights and load them
174 | checkpoint_name = os.path.join(
175 | resume_from_checkpoint, "pytorch_model.bin"
176 | ) # Full checkpoint
177 | if not os.path.exists(checkpoint_name):
178 | checkpoint_name = os.path.join(
179 | resume_from_checkpoint, "adapter_model.bin"
180 | ) # only LoRA model - LoRA config above has to fit
181 | resume_from_checkpoint = (
182 | False # So the trainer won't try loading its state
183 | )
184 | # The two files above have a different name depending on how they were saved, but are actually the same.
185 | if os.path.exists(checkpoint_name):
186 | print(f"Restarting from {checkpoint_name}")
187 | adapters_weights = torch.load(checkpoint_name)
188 | # model = set_peft_model_state_dict(model, adapters_weights)
189 | else:
190 | print(f"Checkpoint {checkpoint_name} not found")
191 | # Be more transparent about the % of trainable params.
192 |
193 | if val_set_size > 0:
194 | train_val = data["train"].train_test_split(
195 | test_size=val_set_size, shuffle=True, seed=42
196 | )
197 | train_data = (
198 | train_val["train"].shuffle().map(generate_and_tokenize_prompt)
199 | )
200 | val_data = (
201 | train_val["test"].shuffle().map(generate_and_tokenize_prompt)
202 | )
203 | else:
204 | train_data = data["train"].shuffle().map(generate_and_tokenize_prompt)
205 | val_data = None
206 |
207 | if not ddp and torch.cuda.device_count() > 1:
208 | # keeps Trainer from trying its own DataParallelism when more than 1 gpu is available
209 | model.is_parallelizable = True
210 | model.model_parallel = True
211 |
212 | trainer = transformers.Trainer(
213 | model=model,
214 | train_dataset=train_data,
215 | eval_dataset=val_data,
216 | args=transformers.TrainingArguments(
217 | per_device_train_batch_size=batch_size,
218 | gradient_accumulation_steps=gradient_accumulation_steps,
219 | warmup_steps=100,
220 | num_train_epochs=num_epochs,
221 | learning_rate=learning_rate,
222 | fp16=True,
223 | logging_steps=10,
224 | optim="adamw_torch",
225 | evaluation_strategy="steps" if val_set_size > 0 else "no",
226 | save_strategy="steps",
227 | eval_steps=200 if val_set_size > 0 else None,
228 | save_steps=200,
229 | output_dir=output_dir,
230 | save_total_limit=3,
231 | load_best_model_at_end=True if val_set_size > 0 else False,
232 | ddp_find_unused_parameters=False if ddp else None,
233 | report_to="wandb" if use_wandb else None,
234 | run_name=wandb_run_name if use_wandb else None,
235 | ),
236 | data_collator=transformers.DataCollatorForSeq2Seq(
237 | tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True
238 | ),
239 | )
240 | model.config.use_cache = False
241 |
242 | # old_state_dict = model.state_dict
243 | # model.state_dict = (
244 | # lambda self, *_, **__: get_peft_model_state_dict(
245 | # self, old_state_dict()
246 | # )
247 | # ).__get__(model, type(model))
248 |
249 | if torch.__version__ >= "2" and sys.platform != "win32":
250 | model = torch.compile(model)
251 |
252 | trainer.train(resume_from_checkpoint=resume_from_checkpoint)
253 |
254 | model.save_pretrained(output_dir)
255 |
256 | print(
257 | "\n If there's a warning about missing keys above, please disregard :)"
258 | )
259 |
260 |
261 | if __name__ == "__main__":
262 | fire.Fire(train)
263 |
--------------------------------------------------------------------------------
/prompt.txt:
--------------------------------------------------------------------------------
1 | You are asked to come up with a set of 20 diverse code generation task instructions. These task instructions will be given to a GPT model and we will evaluate the GPT model for completing the instructions.
2 |
3 | Here are the requirements:
4 | 1. Try not to repeat the verb for each instruction to maximize diversity.
5 | 2. The language used for the instruction also should be diverse. For example, you should combine questions with imperative instrucitons.
6 | 3. The type of instructions should be diverse. The list should include diverse types of programming tasks like open-ended generation, classification, editing, optimization etc.
7 | 2. A GPT language model should be able to complete the instruction. For example, do not ask the assistant to create any visual or audio output. For another example, do not ask the assistant to wake you up at 5pm or set a reminder because it cannot perform any action.
8 | 3. The instructions should be in English.
9 | 4. The instructions should at least 1 to 2 sentences long. Either an imperative sentence or a question is permitted.
10 | 5. You should generate an appropriate input to the instruction. The input field should contain a specific example provided for the instruction. It should involve realistic data and should not contain simple placeholders. The input should provide substantial content to make the instruction challenging but should ideally not exceed 100 words.
11 | 6. Not all instructions require input. For example, when a instruction asks about some general information, "write a python program to load a file.", it is not necssary to provide a specific context. In this case, we simply put "" in the input field.
12 | 7. The output should be an appropriate response to the instruction and the input.
13 | 8. All tasks should be coding or programming related.
14 |
15 | List of 20 tasks:
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | numpy
2 | rouge_score
3 | fire
4 | openai
5 | transformers>=4.26.1
6 | torch
7 | sentencepiece
8 | tokenizers==0.12.1
9 | wandb
10 |
--------------------------------------------------------------------------------
/seed_tasks.jsonl:
--------------------------------------------------------------------------------
1 | {"id": "seed_task_1", "name": "complete_python_code", "instruction": "Suggest a completion for the following python code.", "instances": [{"input": "import json\n\ndef read_task_from_jsonl(data_file):\n '''This function will read a .jsonl file and return the ``task`` fields in all the lines.'''", "output": "import json\n\ndef read_task_from_jsonl(data_file):\n '''This function will read a .jsonl file and return the ``task`` fields in all the lines.'''\n with open(data_file) as fin:\n return [json.loads(line)['task'] for line in fin]"}], "is_classification": false}
2 | {"id": "seed_task_2", "name": "code_todo", "instruction": "Using the comment as a guide, replace the \"TODO\" comment in the code with the proper code.", "instances": [{"input": "def greet_to(name):\n \"\"\"Print a greeting to the name provided.\"\"\"\n # TODO: assert name is a string\n print(\"Hello, \" + name + \"!\")", "output": "def greet_to(name):\n \"\"\"Print a greeting to the name provided.\"\"\"\n # assert name is a string\n assert isinstance(name, str), \"name must be a string\"\n print(\"Hello, \" + name + \"!\")"}], "is_classification": false}
3 | {"id": "seed_task_3", "name": "python_code_generation", "instruction": "Generate a correct python program to fulfill the following purpose:", "instances": [{"input": "Count the occurrence of an element x in a list y.", "output": "def count_x(x, y):\n count = 0\n for i in range(y):\n if i == x:\n count += 1\n return count"}], "is_classification": false}
4 | {"id": "seed_task_4", "name": "code_for_bitcoin_price", "instruction": "write a code to get the current value of a Bitcoin in US dollars using the bitcoincharts API.", "instances": [{"input": "", "output": "\"\"\"\nGet the current value of a Bitcoin in US dollars using the bitcoincharts api\n\"\"\"\n\nimport requests\nimport json\n\ndef get_bitcoin_price():\n url = 'http://api.bitcoincharts.com/v1/weighted_prices.json'\n response = requests.get(url)\n data = json.loads(response.text)\n return data['USD']['24h']\n \nif __name__ == '__main__':\n print(get_bitcoin_price())"}], "is_classification": false}
5 | {"id": "seed_task_5", "name": "program_for_summation", "instruction": "Write a program to compute the sum of integers from k to n.", "instances": [{"input": "", "output": "def sum(k, n):\n sum = 0\n for i in range(k, n+1):\n sum += i\n return sum"}], "is_classification": false}
6 | {"id": "seed_task_6", "name": "javascript_date_and_time", "instruction": "Write a script in JavaScript for printing the current date and time.", "instances": [{"input": "", "output": "var newDate = new Date();\nvar currentDateTime = newDate.toLocaleString();\nconsole.log(currentDateTime);"}], "is_classification": false}
7 | {"id": "seed_task_7", "name": "python_leetcode", "instruction": "Write Python code to solve this leetcode problem.", "instances": [{"input": "Problem: You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.\n\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.", "output": "class Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n carry = 0\n root = n = ListNode(0)\n while l1 or l2 or carry:\n v1 = v2 = 0\n if l1:\n v1 = l1.val\n l1 = l1.next\n if l2:\n v2 = l2.val\n l2 = l2.next\n carry, val = divmod(v1+v2+carry, 10)\n n.next = ListNode(val)\n n = n.next\n return root.next"}], "is_classification": false}
8 | {"id": "seed_task_8", "name": "pos_tag_for_word", "instruction": "Identify the pos tag of the word in the given sentence.", "instances": [{"input": "Word: excited\nSentence: She felt so excited that her application got approval.", "output": "Adjective, JJ."}], "is_classification": true}
9 | {"id": "seed_task_9", "name": "code_syntax_error", "instruction": "You need to read a code and detect if there is a syntax error or not. Outpus true if there is error, output false if there is not.", "instances": [{"input": "def quick_sort(arr):\n if len(arr) < 2:\n return arr\n else:\n pivot = arr[0]\n less = [i for i in arr[1:] if i <= pivot]\n greater = [i for i in arr[1:] if i > pivot]\n return quick_sort(less) + [pivot] + quick_sort(greater)", "output": "false"}], "is_classification": true}
10 | {"id": "seed_task_10", "name": "find_prime_numbers", "instruction": "Write a Python function to find all prime numbers up to the given number n.", "instances": [{"input": "", "output": "def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef find_prime_numbers(n):\n primes = []\n for i in range(2, n + 1):\n if is_prime(i):\n primes.append(i)\n return primes"}], "is_classification": false}
11 | {"id": "seed_task_11", "name": "csharp_hello_world", "instruction": "Write a simple C# program that prints \"Hello, World!\".", "instances": [{"input": "", "output": "using System;\n\nnamespace HelloWorld\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.WriteLine(\"Hello, World!\");\n }\n }\n}"}], "is_classification": false}
12 | {"id": "seed_task_12", "name": "sql_query", "instruction": "Write an SQL query to select all columns from a table named 'employees' where the age is greater than 30.", "instances": [{"input": "", "output": "SELECT * FROM employees WHERE age > 30;"}], "is_classification": false}
13 | {"id": "seed_task_13", "name": "palindrome_check", "instruction": "Write a Python function to check if a given word is a palindrome or not. A palindrome is a word that reads the same backwards as forwards.", "instances": [{"input": "", "output": "def is_palindrome(word):\n return word == word[::-1]"}], "is_classification": false}
14 | {"id": "seed_task_14", "name": "javascript_alert", "instruction": "Write a JavaScript code snippet to show an alert message with the text \"Welcome to my website!\".", "instances": [{"input": "", "output": "alert('Welcome to my website!');"}], "is_classification": false}
15 | {"id": "seed_task_15", "name": "python_reverse_list", "instruction": "Write a Python function to reverse a given list of integers.", "instances": [{"input": "", "output": "def reverse_list(numbers):\n return numbers[::-1]"}], "is_classification": false}
16 | {"id": "seed_task_16", "name": "html_basic_structure", "instruction": "Write a basic HTML structure with a title \"My First Web Page\".", "instances": [{"input": "", "output": "\n\n\n \n \n My First Web Page\n\n\n\n\n"}], "is_classification": false}
17 | {"id": "seed_task_17", "name": "c_plus_plus_hello_world", "instruction": "Write a simple C++ program that prints \"Hello, World!\".", "instances": [{"input": "", "output": "#include \n\nint main() {\n std::cout << \"Hello, World!\" << std::endl;\n return 0;\n}"}], "is_classification": false}
18 | {"id": "seed_task_18", "name": "python_summation", "instruction": "Write a Python function that takes two numbers as input and returns their sum.", "instances": [{"input": "5, 7", "output": "def add_numbers(a, b):\n return a + b\n\nresult = add_numbers(5, 7)\nprint(result)"}], "is_classification": false}
19 | {"id": "seed_task_19", "name": "java_loop_array", "instruction": "Create a JavaScript function that takes an array of numbers and returns the product of all elements.", "instances": [{"input": "[2, 3, 4]", "output": "function multiplyArrayElements(arr) {\n let product = 1;\n for (const num of arr) {\n product *= num;\n }\n return product;\n}\n\nconst result = multiplyArrayElements([2, 3, 4]);\nconsole.log(result);"}], "is_classification": false}
20 | {"id": "seed_task_20", "name": "shell_total_lines_in_txt_file", "instruction": "Can you provide a shell script that displays the total number of lines in all '*.txt' files in the current directory?", "instances": [{"input": "\"file1.txt:\\nHello\\nWorld\\n\\nfile2.txt:\\nAnother\\nExample\"", "output": "#!/bin/sh\n\ntotal_lines=0\n\nfor file in *.txt; do\n lines=$(wc -l < \"$file\")\n total_lines=$((total_lines + lines))\ndone\n\necho \"Total lines: $total_lines\""}], "is_classification": false}
21 | {"id": "seed_task_21", "name": "java_reverse_string_no_builtin", "instruction": "Implement a Java method to reverse a string without using any built-in functions.", "instances": [{"input": "\"Hello, World!\"", "output": "public class StringReversal {\n public static String reverseString(String input) {\n char[] charArray = input.toCharArray();\n int left = 0;\n int right = charArray.length - 1;\n\n while (left < right) {\n char temp = charArray[left];\n charArray[left] = charArray[right];\n charArray[right] = temp;\n\n left++;\n right--;\n }\n return new String(charArray);\n }\n\n public static void main(String[] args) {\n String str = \"Hello, World!\";\n System.out.println(\"Reversed string: \" + reverseString(str));\n }\n}"}], "is_classification": false}
--------------------------------------------------------------------------------
/train.py:
--------------------------------------------------------------------------------
1 | #
2 | # Licensed under the Apache License, Version 2.0 (the "License");
3 | # you may not use this file except in compliance with the License.
4 | # You may obtain a copy of the License at
5 | #
6 | # http://www.apache.org/licenses/LICENSE-2.0
7 | #
8 | # Unless required by applicable law or agreed to in writing, software
9 | # distributed under the License is distributed on an "AS IS" BASIS,
10 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | # See the License for the specific language governing permissions and
12 | # limitations under the License.
13 |
14 | import copy
15 | import logging
16 | from dataclasses import dataclass, field
17 | from typing import Optional, Dict, Sequence
18 |
19 | import torch
20 | import transformers
21 | from torch.utils.data import Dataset
22 | from transformers import Trainer
23 |
24 | import utils
25 |
26 | IGNORE_INDEX = -100
27 | DEFAULT_PAD_TOKEN = "[PAD]"
28 | DEFAULT_EOS_TOKEN = ""
29 | DEFAULT_BOS_TOKEN = ""
30 | DEFAULT_UNK_TOKEN = ""
31 | PROMPT_DICT = {
32 | "prompt_input": (
33 | "Below is an instruction that describes a task, paired with an input that provides further context. "
34 | "Write a response that appropriately completes the request.\n\n"
35 | "### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:"
36 | ),
37 | "prompt_no_input": (
38 | "Below is an instruction that describes a task. "
39 | "Write a response that appropriately completes the request.\n\n"
40 | "### Instruction:\n{instruction}\n\n### Response:"
41 | ),
42 | }
43 |
44 |
45 | @dataclass
46 | class ModelArguments:
47 | model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
48 |
49 |
50 | @dataclass
51 | class DataArguments:
52 | data_path: str = field(default=None, metadata={"help": "Path to the training data."})
53 |
54 |
55 | @dataclass
56 | class TrainingArguments(transformers.TrainingArguments):
57 | cache_dir: Optional[str] = field(default=None)
58 | optim: str = field(default="adamw_torch")
59 | model_max_length: int = field(
60 | default=512,
61 | metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."},
62 | )
63 |
64 |
65 | def smart_tokenizer_and_embedding_resize(
66 | special_tokens_dict: Dict,
67 | tokenizer: transformers.PreTrainedTokenizer,
68 | model: transformers.PreTrainedModel,
69 | ):
70 | """Resize tokenizer and embedding.
71 |
72 | Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
73 | """
74 | num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
75 | model.resize_token_embeddings(len(tokenizer))
76 |
77 | if num_new_tokens > 0:
78 | input_embeddings = model.get_input_embeddings().weight.data
79 | output_embeddings = model.get_output_embeddings().weight.data
80 |
81 | input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
82 | output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
83 |
84 | input_embeddings[-num_new_tokens:] = input_embeddings_avg
85 | output_embeddings[-num_new_tokens:] = output_embeddings_avg
86 |
87 |
88 | def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
89 | """Tokenize a list of strings."""
90 | tokenized_list = [
91 | tokenizer(
92 | text,
93 | return_tensors="pt",
94 | padding="longest",
95 | max_length=tokenizer.model_max_length,
96 | truncation=True,
97 | )
98 | for text in strings
99 | ]
100 | input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]
101 | input_ids_lens = labels_lens = [
102 | tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list
103 | ]
104 | return dict(
105 | input_ids=input_ids,
106 | labels=labels,
107 | input_ids_lens=input_ids_lens,
108 | labels_lens=labels_lens,
109 | )
110 |
111 |
112 | def preprocess(
113 | sources: Sequence[str],
114 | targets: Sequence[str],
115 | tokenizer: transformers.PreTrainedTokenizer,
116 | ) -> Dict:
117 | """Preprocess the data by tokenizing."""
118 | examples = [s + t for s, t in zip(sources, targets)]
119 | examples_tokenized, sources_tokenized = [_tokenize_fn(strings, tokenizer) for strings in (examples, sources)]
120 | input_ids = examples_tokenized["input_ids"]
121 | labels = copy.deepcopy(input_ids)
122 | for label, source_len in zip(labels, sources_tokenized["input_ids_lens"]):
123 | label[:source_len] = IGNORE_INDEX
124 | return dict(input_ids=input_ids, labels=labels)
125 |
126 |
127 | class SupervisedDataset(Dataset):
128 | """Dataset for supervised fine-tuning."""
129 |
130 | def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer):
131 | super(SupervisedDataset, self).__init__()
132 | logging.warning("Loading data...")
133 | list_data_dict = utils.jload(data_path)
134 |
135 | logging.warning("Formatting inputs...")
136 | prompt_input, prompt_no_input = PROMPT_DICT["prompt_input"], PROMPT_DICT["prompt_no_input"]
137 | sources = [
138 | prompt_input.format_map(example) if example.get("input", "") != "" else prompt_no_input.format_map(example)
139 | for example in list_data_dict
140 | ]
141 | targets = [f"{example['output']}{tokenizer.eos_token}" for example in list_data_dict]
142 |
143 | logging.warning("Tokenizing inputs... This may take some time...")
144 | data_dict = preprocess(sources, targets, tokenizer)
145 |
146 | self.input_ids = data_dict["input_ids"]
147 | self.labels = data_dict["labels"]
148 |
149 | def __len__(self):
150 | return len(self.input_ids)
151 |
152 | def __getitem__(self, i) -> Dict[str, torch.Tensor]:
153 | return dict(input_ids=self.input_ids[i], labels=self.labels[i])
154 |
155 |
156 | @dataclass
157 | class DataCollatorForSupervisedDataset(object):
158 | """Collate examples for supervised fine-tuning."""
159 |
160 | tokenizer: transformers.PreTrainedTokenizer
161 |
162 | def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
163 | input_ids, labels = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels"))
164 | input_ids = torch.nn.utils.rnn.pad_sequence(
165 | input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id
166 | )
167 | labels = torch.nn.utils.rnn.pad_sequence(labels, batch_first=True, padding_value=IGNORE_INDEX)
168 | return dict(
169 | input_ids=input_ids,
170 | labels=labels,
171 | attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
172 | )
173 |
174 |
175 | def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict:
176 | """Make dataset and collator for supervised fine-tuning."""
177 | train_dataset = SupervisedDataset(tokenizer=tokenizer, data_path=data_args.data_path)
178 | data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
179 | return dict(train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator)
180 |
181 |
182 | def train():
183 | parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
184 | model_args, data_args, training_args = parser.parse_args_into_dataclasses()
185 |
186 | model = transformers.AutoModelForCausalLM.from_pretrained(
187 | model_args.model_name_or_path,
188 | cache_dir=training_args.cache_dir,
189 | )
190 |
191 | tokenizer = transformers.AutoTokenizer.from_pretrained(
192 | model_args.model_name_or_path,
193 | cache_dir=training_args.cache_dir,
194 | model_max_length=training_args.model_max_length,
195 | padding_side="right",
196 | use_fast=False,
197 | )
198 | if tokenizer.pad_token is None:
199 | smart_tokenizer_and_embedding_resize(
200 | special_tokens_dict=dict(pad_token=DEFAULT_PAD_TOKEN),
201 | tokenizer=tokenizer,
202 | model=model,
203 | )
204 | if "llama" in model_args.model_name_or_path:
205 | tokenizer.add_special_tokens(
206 | {
207 | "eos_token": DEFAULT_EOS_TOKEN,
208 | "bos_token": DEFAULT_BOS_TOKEN,
209 | "unk_token": DEFAULT_UNK_TOKEN,
210 | }
211 | )
212 |
213 | data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args)
214 | trainer = Trainer(model=model, tokenizer=tokenizer, args=training_args, **data_module)
215 | trainer.train()
216 | trainer.save_model(training_args.output_dir)
217 |
218 |
219 | if __name__ == "__main__":
220 | train()
221 |
--------------------------------------------------------------------------------
/utils.py:
--------------------------------------------------------------------------------
1 | import dataclasses
2 | import logging
3 | import math
4 | import os
5 | import io
6 | import sys
7 | import time
8 | import json
9 | from typing import Optional, Sequence, Union
10 |
11 | import openai
12 | import tqdm
13 | from openai import openai_object
14 | import copy
15 |
16 | StrOrOpenAIObject = Union[str, openai_object.OpenAIObject]
17 |
18 | openai_org = os.getenv("OPENAI_ORG")
19 | if openai_org is not None:
20 | openai.organization = openai_org
21 | logging.warning(f"Switching to organization: {openai_org} for OAI API key.")
22 |
23 |
24 | @dataclasses.dataclass
25 | class OpenAIDecodingArguments(object):
26 | max_tokens: int = 1800
27 | temperature: float = 0.2
28 | top_p: float = 1.0
29 | n: int = 1
30 | stream: bool = False
31 | stop: Optional[Sequence[str]] = None
32 | presence_penalty: float = 0.0
33 | frequency_penalty: float = 0.0
34 | suffix: Optional[str] = None
35 | logprobs: Optional[int] = None
36 | echo: bool = False
37 |
38 |
39 | def openai_completion(
40 | prompts: Union[str, Sequence[str], Sequence[dict[str, str]], dict[str, str]],
41 | decoding_args: OpenAIDecodingArguments,
42 | model_name="text-davinci-003",
43 | sleep_time=2,
44 | batch_size=1,
45 | max_instances=sys.maxsize,
46 | max_batches=sys.maxsize,
47 | return_text=False,
48 | **decoding_kwargs,
49 | ) -> Union[Union[StrOrOpenAIObject], Sequence[StrOrOpenAIObject], Sequence[Sequence[StrOrOpenAIObject]],]:
50 | """Decode with OpenAI API.
51 |
52 | Args:
53 | prompts: A string or a list of strings to complete. If it is a chat model the strings should be formatted
54 | as explained here: https://github.com/openai/openai-python/blob/main/chatml.md. If it is a chat model
55 | it can also be a dictionary (or list thereof) as explained here:
56 | https://github.com/openai/openai-cookbook/blob/main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb
57 | decoding_args: Decoding arguments.
58 | model_name: Model name. Can be either in the format of "org/model" or just "model".
59 | sleep_time: Time to sleep once the rate-limit is hit.
60 | batch_size: Number of prompts to send in a single request. Only for non chat model.
61 | max_instances: Maximum number of prompts to decode.
62 | max_batches: Maximum number of batches to decode. This argument will be deprecated in the future.
63 | return_text: If True, return text instead of full completion object (which contains things like logprob).
64 | decoding_kwargs: Additional decoding arguments. Pass in `best_of` and `logit_bias` if you need them.
65 |
66 | Returns:
67 | A completion or a list of completions.
68 | Depending on return_text, return_openai_object, and decoding_args.n, the completion type can be one of
69 | - a string (if return_text is True)
70 | - an openai_object.OpenAIObject object (if return_text is False)
71 | - a list of objects of the above types (if decoding_args.n > 1)
72 | """
73 | is_single_prompt = isinstance(prompts, (str, dict))
74 | if is_single_prompt:
75 | prompts = [prompts]
76 |
77 | if max_batches < sys.maxsize:
78 | logging.warning(
79 | "`max_batches` will be deprecated in the future, please use `max_instances` instead."
80 | "Setting `max_instances` to `max_batches * batch_size` for now."
81 | )
82 | max_instances = max_batches * batch_size
83 |
84 | prompts = prompts[:max_instances]
85 | num_prompts = len(prompts)
86 | prompt_batches = [
87 | prompts[batch_id * batch_size : (batch_id + 1) * batch_size]
88 | for batch_id in range(int(math.ceil(num_prompts / batch_size)))
89 | ]
90 |
91 | completions = []
92 | for batch_id, prompt_batch in tqdm.tqdm(
93 | enumerate(prompt_batches),
94 | desc="prompt_batches",
95 | total=len(prompt_batches),
96 | ):
97 | batch_decoding_args = copy.deepcopy(decoding_args) # cloning the decoding_args
98 |
99 | while True:
100 | try:
101 | shared_kwargs = dict(
102 | model=model_name,
103 | **batch_decoding_args.__dict__,
104 | **decoding_kwargs,
105 | )
106 | completion_batch = openai.Completion.create(prompt=prompt_batch, **shared_kwargs)
107 | choices = completion_batch.choices
108 |
109 | for choice in choices:
110 | choice["total_tokens"] = completion_batch.usage.total_tokens
111 | completions.extend(choices)
112 | break
113 | except openai.error.OpenAIError as e:
114 | logging.warning(f"OpenAIError: {e}.")
115 | if "Please reduce your prompt" in str(e):
116 | batch_decoding_args.max_tokens = int(batch_decoding_args.max_tokens * 0.8)
117 | logging.warning(f"Reducing target length to {batch_decoding_args.max_tokens}, Retrying...")
118 | else:
119 | logging.warning("Hit request rate limit; retrying...")
120 | time.sleep(sleep_time) # Annoying rate limit on requests.
121 |
122 | if return_text:
123 | completions = [completion.text for completion in completions]
124 | if decoding_args.n > 1:
125 | # make completions a nested list, where each entry is a consecutive decoding_args.n of original entries.
126 | completions = [completions[i : i + decoding_args.n] for i in range(0, len(completions), decoding_args.n)]
127 | if is_single_prompt:
128 | # Return non-tuple if only 1 input and 1 generation.
129 | (completions,) = completions
130 | return completions
131 |
132 |
133 | def _make_w_io_base(f, mode: str):
134 | if not isinstance(f, io.IOBase):
135 | f_dirname = os.path.dirname(f)
136 | if f_dirname != "":
137 | os.makedirs(f_dirname, exist_ok=True)
138 | f = open(f, mode=mode)
139 | return f
140 |
141 |
142 | def _make_r_io_base(f, mode: str):
143 | if not isinstance(f, io.IOBase):
144 | f = open(f, mode=mode)
145 | return f
146 |
147 |
148 | def jdump(obj, f, mode="w", indent=4, default=str):
149 | """Dump a str or dictionary to a file in json format.
150 |
151 | Args:
152 | obj: An object to be written.
153 | f: A string path to the location on disk.
154 | mode: Mode for opening the file.
155 | indent: Indent for storing json dictionaries.
156 | default: A function to handle non-serializable entries; defaults to `str`.
157 | """
158 | f = _make_w_io_base(f, mode)
159 | if isinstance(obj, (dict, list)):
160 | json.dump(obj, f, indent=indent, default=default)
161 | elif isinstance(obj, str):
162 | f.write(obj)
163 | else:
164 | raise ValueError(f"Unexpected type: {type(obj)}")
165 | f.close()
166 |
167 |
168 | def jload(f, mode="r"):
169 | """Load a .json file into a dictionary."""
170 | f = _make_r_io_base(f, mode)
171 | jdict = json.load(f)
172 | f.close()
173 | return jdict
174 |
--------------------------------------------------------------------------------