Canstralian commited on
Commit
a021dd4
·
verified ·
1 Parent(s): d8fe97e

Upload 15 files

Browse files
CODE_LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 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.
DATA_LICENSE ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.
MODEL_WEIGHTS_LICENSE ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BigCode Open RAIL-M v1 License Agreement
2
+ Section I: Preamble
3
+ This OpenRAIL-M License Agreement was created under BigCode, an open and collaborative research project aimed at the responsible development and Use of Large Language Models (“LLMs”) for code generation. This license is generally applicable to any machine-learning Model.
4
+
5
+ This License Agreement strives for both the open and responsible Use of the accompanying Model. Openness here is understood as enabling users of the Model on a royalty free basis to Use it, modify it, and even share commercial versions of it. Use restrictions are included to prevent misuse of the Model.
6
+
7
+ This License Agreement governs the Use of the Model and Modifications of the Model. You and Licensor agree as follows:
8
+
9
+ 1.Definitions
10
+
11
+ a. “Contribution” means any work of authorship, including the original version of the Model and any Modifications of the Model that is intentionally submitted to Licensor for inclusion in the Model by the copyright owner or by an individual or entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, “submitted” means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as “Not a Contribution.”
12
+
13
+ b. “Contributor” means Licensor and any individual or entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model.
14
+
15
+ c. “Data” means a collection of information extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License Agreement.
16
+
17
+ d. “Explanatory Documentation” means model cards, data cards, or any other similar documentation or related information dedicated to inform the public about the characteristics of the model. Explanatory documentation is not licensed under this license.
18
+
19
+ e. “Harm” includes but is not limited to physical, mental, psychological, financial and reputational damage, pain, or loss.
20
+
21
+ f. “License Agreement” means this document.
22
+
23
+ g. “Licensor” means the rights owners or entity authorized by the rights owners that are granting the terms and conditions of this License Agreement.
24
+
25
+ h. “Model” means machine-learning based assemblies (including checkpoints), consisting of learnt weights and parameters (including optimizer states), corresponding to a model architecture as embodied in source code. Source code is not licensed under this License Agreement.
26
+
27
+ i. “Modifications of the Model” means all changes to the Model or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or Output of the Model.
28
+
29
+ j. “Output” means the results of operating the Model.
30
+
31
+ k. “Share” means any transmission, reproduction, publication or other sharing of the Model or Modifications of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means, including - but not limited to - API-based or web access.
32
+
33
+ l. “Third Parties” means individuals or legal entities that are not under common control with Licensor or You.
34
+
35
+ m. “Use” includes - but is not limited to - generating any Output, fine tuning, updating, running, training, evaluating and/or reparametrizing the Model.
36
+
37
+ n. “You” (or “Your”) means an individual or Legal Entity exercising permissions granted by this License Agreement and/or making Use of the Model for whichever purpose and in any field of Use.
38
+
39
+ Section II: INTELLECTUAL PROPERTY RIGHTS
40
+ The Model and Modifications of the Model are subject to additional terms as described in Section III, which shall govern the Use of the Model and Modifications of the Model.
41
+
42
+ Grant of Copyright license. Subject to the terms and conditions of this License Agreement and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, copyright license to reproduce, prepare, publicly display, publicly perform, sublicense under the terms herein, and distribute the Model and Modifications of the Model.
43
+ Grant of Patent license. Subject to the terms and conditions of this License Agreement and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free patent license to make, have made, Use, offer to sell, sell, import, and otherwise transfer the Model, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Model to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model or a Contribution incorporated within the Model constitutes direct or contributory patent infringement, then any rights granted to You under this License Agreement for the Model shall terminate as of the date such litigation is filed.
44
+ Section III: CONDITIONS OF USE
45
+ 4. Use conditions. Compliance with the restrictions in Attachment A is a condition to the grants in this License Agreement. If You Use the Model, You agree not to Use it for the specified restricted uses set forth in Attachment A.
46
+
47
+ 5. Sharing of the Model
48
+
49
+ 5.1. You may Share the Model or Modifications of the Model under any license of your choice that does not contradict the restrictions in Attachment A of this License Agreement and includes:
50
+
51
+ a. Paragraph 4 and the restrictions in Attachment A of this License Agreement, or,
52
+
53
+ b. Use conditions similar to Paragraph 4 that must accomplish the same purpose as the use conditions in Paragraph 4 and a similar set of restrictions to those in Attachment A that must accomplish the same purpose as the restrictions in Attachment A.
54
+
55
+ 5.2. When You Share the Model or Modifications of the Model, You agree to:
56
+
57
+ a. Give any recipients a copy of this License Agreement;
58
+
59
+ b. Retain all Explanatory Documentation; and if sharing Modifications of the Model, add Explanatory Documentation of the same or better quality documenting the changes made to create the Modifications of the Model; and
60
+
61
+ c. Retain all copyright, patent, trademark, and attribution notices.
62
+
63
+ 6. The Output You Generate. Licensor claims no rights in the Output. You agree not to contravene any provision as stated in the License Agreement with your Use of the Output.
64
+
65
+ Section IV: OTHER PROVISIONS
66
+ 7. Updates and Runtime Restrictions. Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License Agreement.
67
+
68
+ 8. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Model by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
69
+
70
+ 9. Trademarks and related. Nothing in this License Agreement permits You to make Use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors.
71
+
72
+ 10. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model (and each Contributor provides its Contributions) on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or sharing the Model and Modifications of the Model, and assume any risks associated with Your exercise of permissions under this License Agreement.
73
+
74
+ 11. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License Agreement or out of the Use or inability to Use the Model (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, model failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
75
+
76
+ 12. Accepting Warranty or Additional Liability. While sharing the Model or Modifications of the Model thereof, You may choose to offer and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License Agreement. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
77
+
78
+ 13. This License Agreement is a license of copyright and patent rights and an agreement in contract between You and the Licensor. If any provision of this License Agreement is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
79
+
80
+ END OF TERMS AND CONDITIONS
81
+
82
+ Attachment A - USE RESTRICTIONS
83
+ You agree not to Use the Model or Modifications of the Model:
84
+
85
+ (a) In any way that violates any applicable national, federal, state, local or international law or regulation;
86
+
87
+ (b) For the purpose of exploiting, Harming or attempting to exploit or harm minors in any way;
88
+
89
+ (c) To generate and/or disseminate malware (including - but not limited to - ransomware) or any other content to be used for the purpose of Harming electronic systems;
90
+
91
+ (d) To generate or disseminate verifiably false information and/or content with the purpose of Harming others;
92
+
93
+ (e) To generate or disseminate personal identifiable information with the purpose of Harming others;
94
+
95
+ (f) To generate or disseminate information (including - but not limited to - images, code, posts, articles), and place the information in any public context (including - but not limited to - bot generating tweets) without expressly and intelligibly disclaiming that the information and/or content is machine generated;
96
+
97
+ (g) To intentionally defame, disparage or otherwise harass others;
98
+
99
+ (h) To impersonate or attempt to impersonate human beings for purposes of deception;
100
+
101
+ (i) For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation without expressly and intelligibly disclaiming that the creation or modification of the obligation is machine generated;
102
+
103
+ (j) For any Use intended to discriminate against or Harm individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;
104
+
105
+ (k) To intentionally exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
106
+
107
+ (l) For any Use intended to discriminate against individuals or groups based on legally protected characteristics or categories;
108
+
109
+ (m) To provide medical advice or medical results interpretation that is intended to be a substitute for professional medical advice, diagnosis, or treatment;
110
+
111
+ (n) For fully automated decision making in administration of justice, law enforcement, immigration or asylum processes.
README.md CHANGED
@@ -1,13 +1,364 @@
1
- ---
2
- title: WizardLM 1.6
3
- emoji: 📊
4
- colorFrom: green
5
- colorTo: red
6
- sdk: streamlit
7
- sdk_version: 1.41.1
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # WizardCoder: Empowering Code Large Language Models with Evol-Instruct
2
+
3
+ [![Code License](https://img.shields.io/badge/Code%20License-Apache_2.0-green.svg)](CODE_LICENSE)
4
+ [![Data License](https://img.shields.io/badge/Data%20License-CC%20By%20NC%204.0-red.svg)](DATA_LICENSE)
5
+ <!-- [![Model Weight License](https://img.shields.io/badge/Model%20Weights%20License-bigscience%20OpenRAIL%20M%20v1-yellow)](MODEL_WEIGHTS_LICENSE) -->
6
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/release/python-390/)
7
+
8
+ To develop our WizardCoder model, we begin by adapting the Evol-Instruct method specifically for coding tasks. This involves tailoring the prompt to the domain of code-related instructions. Subsequently, we fine-tune the Code LLMs, StarCoder or Code LLama, utilizing the newly created instruction-following training set.
9
+
10
+ ## News
11
+
12
+ - 🔥🔥🔥[2023/08/26] We released **WizardCoder-Python-34B-V1.0** , which achieves the **73.2 pass@1** and surpasses **GPT4 (2023/03/15)**, **ChatGPT-3.5**, and **Claude2** on the [HumanEval Benchmarks](https://github.com/openai/human-eval).
13
+ - [2023/06/16] We released **WizardCoder-15B-V1.0** , which achieves the **57.3 pass@1** and surpasses **Claude-Plus (+6.8)**, **Bard (+15.3)** and **InstructCodeT5+ (+22.3)** on the [HumanEval Benchmarks](https://github.com/openai/human-eval).
14
+
15
+ ❗Note: There are two HumanEval results of GPT4 and ChatGPT-3.5. The 67.0 and 48.1 are reported by the official GPT4 Report (2023/03/15) of [OpenAI](https://arxiv.org/abs/2303.08774). The 82.0 and 72.5 are tested by ourselves with the latest API (2023/08/26).
16
+
17
+
18
+ | Model | Checkpoint | Paper | HumanEval | MBPP | Demo | License |
19
+ | ----- |------| ---- |------|-------| ----- | ----- |
20
+ | WizardCoder-Python-34B-V1.0 | 🤗 <a href="https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0" target="_blank">HF Link</a> | 📃 <a href="https://arxiv.org/abs/2306.08568" target="_blank">[WizardCoder]</a> | 73.2 | 61.2 | [Demo](http://47.103.63.15:50085/) | <a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads/" target="_blank">Llama2</a> |
21
+ | WizardCoder-15B-V1.0 | 🤗 <a href="https://huggingface.co/WizardLM/WizardCoder-15B-V1.0" target="_blank">HF Link</a> | 📃 <a href="https://arxiv.org/abs/2306.08568" target="_blank">[WizardCoder]</a> | 59.8 |50.6 | -- | <a href="https://huggingface.co/spaces/bigcode/bigcode-model-license-agreement" target="_blank">OpenRAIL-M</a> |
22
+
23
+ - &#x1F4E3; Please refer to our Twitter account https://twitter.com/WizardLM_AI and HuggingFace Repo https://huggingface.co/WizardLM . We will use them to announce any new release at the 1st time.
24
+
25
+ ## Comparing WizardCoder-Python-34B-V1.0 with Other LLMs.
26
+
27
+ 🔥 The following figure shows that our **WizardCoder-Python-34B-V1.0 attains the second position in this benchmark**, surpassing GPT4 (2023/03/15, 73.2 vs. 67.0), ChatGPT-3.5 (73.2 vs. 72.5) and Claude2 (73.2 vs. 71.2).
28
+
29
+ <p align="center" width="100%">
30
+ <a ><img src="imgs/compare_sota.png" alt="WizardCoder" style="width: 96%; min-width: 300px; display: block; margin: auto;"></a>
31
+ </p>
32
+
33
+ ❗❗❗**Note: This performance is 100% reproducible! If you cannot reproduce it, please follow the steps in [Evaluation](#evaluation).**
34
+
35
+ ❗Note: There are two HumanEval results of GPT4 and ChatGPT-3.5. The 67.0 and 48.1 are reported by the official GPT4 Report (2023/03/15) of [OpenAI](https://arxiv.org/abs/2303.08774). The 82.0 and 72.5 are tested by ourselves with the latest API (2023/08/26).
36
+
37
+ ## Comparing WizardCoder-15B-V1.0 with the Closed-Source Models.
38
+
39
+ 🔥 The following figure shows that our **WizardCoder attains the third position in this benchmark**, surpassing Claude-Plus (59.8 vs. 53.0) and Bard (59.8 vs. 44.5). Notably, our model exhibits a substantially smaller size compared to these models.
40
+
41
+ <p align="center" width="100%">
42
+ <a ><img src="imgs/pass1.png" alt="WizardCoder" style="width: 86%; min-width: 300px; display: block; margin: auto;"></a>
43
+ </p>
44
+
45
+ ❗❗❗**Note: This performance is 100% reproducible! If you cannot reproduce it, please follow the steps in [Evaluation](#evaluation).**
46
+
47
+ ❗**Note: In this study, we copy the scores for HumanEval and HumanEval+ from the [LLM-Humaneval-Benchmarks](https://github.com/my-other-github-account/llm-humaneval-benchmarks). Notably, all the mentioned models generate code solutions for each problem utilizing a **single attempt**, and the resulting pass rate percentage is reported. Our **WizardCoder** generates answers using greedy decoding and tests with the same [code](https://github.com/evalplus/evalplus).**
48
+
49
+ ## Comparing WizardCoder-15B-V1.0 with the Open-Source Models.
50
+
51
+ The following table clearly demonstrates that our **WizardCoder** exhibits a substantial performance advantage over all the open-source models. ❗**If you are confused with the different scores of our model (57.3 and 59.8), please check the Notes.**
52
+
53
+
54
+ | Model | HumanEval Pass@1 | MBPP Pass@1 |
55
+ |------------------|------------------|-------------|
56
+ | CodeGen-16B-Multi| 18.3 |20.9 |
57
+ | CodeGeeX | 22.9 |24.4 |
58
+ | LLaMA-33B | 21.7 |30.2 |
59
+ | LLaMA-65B | 23.7 |37.7 |
60
+ | PaLM-540B | 26.2 |36.8 |
61
+ | PaLM-Coder-540B | 36.0 |47.0 |
62
+ | PaLM 2-S | 37.6 |50.0 |
63
+ | CodeGen-16B-Mono | 29.3 |35.3 |
64
+ | Code-Cushman-001 | 33.5 |45.9 |
65
+ | StarCoder-15B | 33.6 |43.6* |
66
+ | InstructCodeT5+ | 35.0 |-- |
67
+ | WizardLM-30B 1.0| 37.8 |-- |
68
+ | WizardCoder-15B 1.0 | **57.3** |**51.8** |
69
+
70
+ ❗**Note: The reproduced result of StarCoder on MBPP.**
71
+
72
+ ❗**Note: The above table conducts a comprehensive comparison of our **WizardCoder** with other models on the HumanEval and MBPP benchmarks. We adhere to the approach outlined in previous studies by generating **20 samples** for each problem to estimate the pass@1 score and evaluate with the same [code](https://github.com/openai/human-eval/tree/master). The scores of GPT4 and GPT3.5 reported by [OpenAI](https://openai.com/research/gpt-4) are 67.0 and 48.1 (maybe these are the early version GPT4&3.5).**
73
+
74
+ ## Call for Feedbacks
75
+ We welcome everyone to use your professional and difficult instructions to evaluate WizardCoder, and show us examples of poor performance and your suggestions in the [issue discussion](https://github.com/nlpxucan/WizardLM/issues) area. We are focusing on improving the Evol-Instruct now and hope to relieve existing weaknesses and issues in the the next version of WizardCoder. After that, we will open the code and pipeline of up-to-date Evol-Instruct algorithm and work with you together to improve it.
76
+
77
+ ## Unofficial Video Introductions
78
+ Thanks to the enthusiastic friends, their video introductions are more lively and interesting.
79
+ 1. [WizardCoder AI Is The NEW ChatGPT's Coding TWIN!](https://www.youtube.com/watch?v=XjsyHrmd3Xo)
80
+
81
+ ## Contents
82
+
83
+ 1. [Online Demo](#online-demo)
84
+
85
+ 2. [Fine-tuning](#fine-tuning)
86
+
87
+ 3. [Inference](#inference)
88
+
89
+ 4. [Evaluation](#evaluation)
90
+
91
+ 5. [Citation](#citation)
92
+
93
+ 6. [Disclaimer](#disclaimer)
94
+
95
+ ## Online Demo
96
+
97
+ We will provide our latest models for you to try for as long as possible. If you find a link is not working, please try another one. At the same time, please try as many **real-world** and **challenging** code-related problems that you encounter in your work and life as possible. We will continue to evolve our models with your feedbacks.
98
+
99
+ [Demo Link](https://e5eaf7d09cc1521c.gradio.app/) (We adopt the greedy decoding now.)
100
+
101
+ ## Fine-tuning
102
+
103
+ We fine-tune WizardCoder using the modified code `train.py` from [Llama-X](https://github.com/AetherCortex/Llama-X).
104
+ We fine-tune StarCoder-15B with the following hyperparameters:
105
+
106
+ | Hyperparameter | StarCoder-15B |
107
+ |----------------|---------------|
108
+ | Batch size | 512 |
109
+ | Learning rate | 2e-5 |
110
+ | Epochs | 3 |
111
+ | Max length | 2048 |
112
+ | Warmup step | 30 |
113
+ | LR scheduler | cosine |
114
+
115
+ To reproduce our fine-tuning of WizardCoder, please follow the following steps:
116
+ 1. According to the instructions of [Llama-X](https://github.com/AetherCortex/Llama-X), install the environment, download the training code, and deploy. (Note: `deepspeed==0.9.2` and `transformers==4.29.2`)
117
+ 2. Replace the `train.py` with the `train_wizardcoder.py` in our repo (`src/train_wizardcoder.py`)
118
+ 3. Login Huggingface:
119
+ ```bash
120
+ huggingface-cli login
121
+ ```
122
+ 4. Execute the following training command:
123
+ ```bash
124
+ deepspeed train_wizardcoder.py \
125
+ --model_name_or_path "bigcode/starcoder" \
126
+ --data_path "/your/path/to/code_instruction_data.json" \
127
+ --output_dir "/your/path/to/ckpt" \
128
+ --num_train_epochs 3 \
129
+ --model_max_length 2048 \
130
+ --per_device_train_batch_size 16 \
131
+ --per_device_eval_batch_size 1 \
132
+ --gradient_accumulation_steps 4 \
133
+ --evaluation_strategy "no" \
134
+ --save_strategy "steps" \
135
+ --save_steps 50 \
136
+ --save_total_limit 2 \
137
+ --learning_rate 2e-5 \
138
+ --warmup_steps 30 \
139
+ --logging_steps 2 \
140
+ --lr_scheduler_type "cosine" \
141
+ --report_to "tensorboard" \
142
+ --gradient_checkpointing True \
143
+ --deepspeed configs/deepspeed_config.json \
144
+ --fp16 True
145
+ ```
146
+
147
+ ## Inference
148
+
149
+ We provide the decoding script for WizardCoder, which reads a input file and generates corresponding responses for each sample, and finally consolidates them into an output file.
150
+
151
+ You can specify `base_model`, `input_data_path` and `output_data_path` in `src\inference_wizardcoder.py` to set the decoding model, path of input file and path of output file.
152
+
153
+ ```bash
154
+ pip install jsonlines
155
+ ```
156
+
157
+ The decoding command is:
158
+ ```
159
+ python src\inference_wizardcoder.py \
160
+ --base_model "/your/path/to/ckpt" \
161
+ --input_data_path "/your/path/to/input/data.jsonl" \
162
+ --output_data_path "/your/path/to/output/result.jsonl"
163
+ ```
164
+
165
+ The format of `data.jsonl` should be:
166
+ ```
167
+ {"idx": 11, "Instruction": "Write a Python code to count 1 to 10."}
168
+ {"idx": 12, "Instruction": "Write a Java code to sum 1 to 10."}
169
+ ```
170
+
171
+ The prompt for our WizardCoder in `src\inference_wizardcoder.py` is:
172
+ ```
173
+ Below is an instruction that describes a task. Write a response that appropriately completes the request.
174
+
175
+ ### Instruction:
176
+ {instruction}
177
+
178
+ ### Response:
179
+ ```
180
+
181
+ ## Evaluation
182
+
183
+ ### HumanEval
184
+
185
+ 1. According to the instructions of [HumanEval](https://github.com/openai/human-eval), install the environment.
186
+ 2. Run the following scripts to generate the answer.
187
+
188
+ - (1) For WizardCoder-15B-V1.0 (base on StarCoder)
189
+ ```bash
190
+ model="/path/to/your/model"
191
+ temp=0.2
192
+ max_len=2048
193
+ pred_num=200
194
+ num_seqs_per_iter=2
195
+
196
+ output_path=preds/T${temp}_N${pred_num}
197
+
198
+ mkdir -p ${output_path}
199
+ echo 'Output path: '$output_path
200
+ echo 'Model to eval: '$model
201
+
202
+ # 164 problems, 21 per GPU if GPU=8
203
+ index=0
204
+ gpu_num=8
205
+ for ((i = 0; i < $gpu_num; i++)); do
206
+ start_index=$((i * 21))
207
+ end_index=$(((i + 1) * 21))
208
+
209
+ gpu=$((i))
210
+ echo 'Running process #' ${i} 'from' $start_index 'to' $end_index 'on GPU' ${gpu}
211
+ ((index++))
212
+ (
213
+ CUDA_VISIBLE_DEVICES=$gpu python humaneval_gen.py --model ${model} \
214
+ --start_index ${start_index} --end_index ${end_index} --temperature ${temp} \
215
+ --num_seqs_per_iter ${num_seqs_per_iter} --N ${pred_num} --max_len ${max_len} --output_path ${output_path}
216
+ ) &
217
+ if (($index % $gpu_num == 0)); then wait; fi
218
+ done
219
+ ```
220
+
221
+ - (2) For WizardCoder-Python-34B-V1.0 (base on CodeLLama)
222
+
223
+ ```bash
224
+ pip install vllm # This can acclerate the inference process a lot.
225
+ pip install transformers==4.31.0
226
+
227
+ model="/path/to/your/model"
228
+ temp=0.2
229
+ max_len=2048
230
+ pred_num=200
231
+ num_seqs_per_iter=2
232
+
233
+ output_path=preds/T${temp}_N${pred_num}
234
+
235
+ mkdir -p ${output_path}
236
+ echo 'Output path: '$output_path
237
+ echo 'Model to eval: '$model
238
+
239
+ CUDA_VISIBLE_DEVICES=0,1,2,3 python humaneval_gen_vllm.py --model ${model} \
240
+ --start_index 0 --end_index 164 --temperature ${temp} \
241
+ --num_seqs_per_iter ${num_seqs_per_iter} --N ${pred_num} --max_len ${max_len} --output_path ${output_path} --num_gpus 4
242
+ ```
243
+
244
+ 3. Run the post processing code `src/process_humaneval.py` to collect the code completions from all answer files.
245
+ ```bash
246
+ output_path=preds/T${temp}_N${pred_num}
247
+
248
+ echo 'Output path: '$output_path
249
+ python process_humaneval.py --path ${output_path} --out_path ${output_path}.jsonl --add_prompt
250
+
251
+ evaluate_functional_correctness ${output_path}.jsonl
252
+ ```
253
+
254
+ ### How to Reproduce the 59.8 Pass@1 on HumanEval with Greedy Decoding?
255
+
256
+ ❗❗❗**This performance is 100% reproducible!**
257
+
258
+ Run the following script to generate the answer with greedy decoding. Then follow the above steps 2 and 3 to get the evaluation result.
259
+
260
+ ❗We also provide the generated codes in `data/humaneval.59.8.gen.zip`
261
+
262
+ ```bash
263
+ model="WizardLM/WizardCoder-15B-V1.0"
264
+ temp=0.0
265
+ max_len=2048
266
+ pred_num=1
267
+ num_seqs_per_iter=1
268
+
269
+ output_path=preds/T${temp}_N${pred_num}_WizardCoder_Greedy_Decode
270
+
271
+ mkdir -p ${output_path}
272
+ echo 'Output path: '$output_path
273
+ echo 'Model to eval: '$model
274
+
275
+ # 164 problems, 21 per GPU if GPU=8
276
+ index=0
277
+ gpu_num=8
278
+ for ((i = 0; i < $gpu_num; i++)); do
279
+ start_index=$((i * 21))
280
+ end_index=$(((i + 1) * 21))
281
+
282
+ gpu=$((i))
283
+ echo 'Running process #' ${i} 'from' $start_index 'to' $end_index 'on GPU' ${gpu}
284
+ ((index++))
285
+ (
286
+ CUDA_VISIBLE_DEVICES=$gpu python humaneval_gen.py --model ${model} \
287
+ --start_index ${start_index} --end_index ${end_index} --temperature ${temp} \
288
+ --num_seqs_per_iter ${num_seqs_per_iter} --N ${pred_num} --max_len ${max_len} --output_path ${output_path} --greedy_decode
289
+ ) &
290
+ if (($index % $gpu_num == 0)); then wait; fi
291
+ done
292
+ ```
293
+
294
+ ### MBPP
295
+
296
+ 1. Run the following script to generate the answer.
297
+ ```bash
298
+ model="/path/to/your/model"
299
+ temp=0.2
300
+ max_len=2048
301
+ pred_num=200
302
+ num_seqs_per_iter=2
303
+
304
+ output_path=preds/MBPP_T${temp}_N${pred_num}
305
+ mbpp_path=data/mbpp.test.jsonl # we provide this file in data/mbpp.test.zip
306
+
307
+ mkdir -p ${output_path}
308
+ echo 'Output path: '$output_path
309
+ echo 'Model to eval: '$model
310
+
311
+ # 500 problems, 63 per GPU if GPU=8
312
+ index=0
313
+ gpu_num=8
314
+ for ((i = 0; i < $gpu_num; i++)); do
315
+ start_index=$((i * 50))
316
+ end_index=$(((i + 1) * 50))
317
+
318
+ gpu=$((i))
319
+ echo 'Running process #' ${i} 'from' $start_index 'to' $end_index 'on GPU' ${gpu}
320
+ ((index++))
321
+ (
322
+ CUDA_VISIBLE_DEVICES=$gpu python mbpp_gen.py --model ${model} \
323
+ --start_index ${start_index} --end_index ${end_index} --temperature ${temp} \
324
+ --num_seqs_per_iter ${num_seqs_per_iter} --N ${pred_num} --max_len ${max_len} --output_path ${output_path} --mbpp_path ${mbpp_path}
325
+ ) &
326
+ if (($index % $gpu_num == 0)); then wait; fi
327
+ done
328
+ ```
329
+
330
+ 3. Run the post processing code `src/process_mbpp.py` to collect the code completions from all answer files.
331
+ ```bash
332
+ output_path=preds/MBPP_T${temp}_N${pred_num}
333
+ mbpp_path=data/mbpp.test.jsonl # we provide this file in data/mbpp.test.zip
334
+
335
+ echo 'Output path: '$output_path
336
+ python process_mbpp.py --path ${output_path} --out_path ${output_path}.jsonl --mbpp_path ${mbpp_path} --add_prompt
337
+ ```
338
+
339
+ 4. Evaluate the `MBPP_T${temp}_N${pred_num}.jsonl` with [bigcode-evaluation-harness](https://github.com/bigcode-project/bigcode-evaluation-harness).
340
+
341
+ Acknowledgement: The evaluation code `humaneval_gen.py`, `mbpp_gen.py` and bash scripts are modified from the great works of [CodeT5](https://github.com/salesforce/CodeT5).
342
+
343
+ ## Citation
344
+
345
+ Please cite the repo if you use the data or code in this repo.
346
+
347
+ ```
348
+ @misc{luo2023wizardcoder,
349
+ title={WizardCoder: Empowering Code Large Language Models with Evol-Instruct},
350
+ author={Ziyang Luo and Can Xu and Pu Zhao and Qingfeng Sun and Xiubo Geng and Wenxiang Hu and Chongyang Tao and Jing Ma and Qingwei Lin and Daxin Jiang},
351
+ year={2023},
352
+ eprint={2306.08568},
353
+ archivePrefix={arXiv},
354
+ primaryClass={cs.CL}
355
+ }
356
+ ```
357
+ ## Disclaimer
358
+
359
+ WizardCoder model follows the same license as StarCoder. The content produced by any version of WizardCoder is influenced by uncontrollable variables such as randomness, and therefore, the accuracy of the output cannot be guaranteed by this project. This project does not accept any legal liability for the content of the model output, nor does it assume responsibility for any losses incurred due to the use of associated resources and output results.
360
+
361
+ ## Star History
362
+
363
+ [![Star History Chart](https://api.star-history.com/svg?repos=nlpxucan/WizardLM&type=Timeline)](https://star-history.com/#nlpxucan/WizardLM&Timeline)
364
+
data/humaneval.59.8.gen.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab30d7146c08712d975316fd2daaf34c2f187d8967e2b80d181798d99e352010
3
+ size 75828
data/mbpp.test.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9251948d46cd5bc684e378feb45e6edde32829da967f6556a6f66447777ca9d8
3
+ size 69264
imgs/compare_sota.png ADDED
imgs/pass1.png ADDED
src/humaneval_gen.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import pprint
3
+ import sys
4
+ import os
5
+ import re
6
+ from tqdm import tqdm
7
+ import torch
8
+ from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
9
+ from human_eval.data import write_jsonl, read_problems, stream_jsonl
10
+
11
+ if torch.cuda.is_available():
12
+ device = "cuda"
13
+ else:
14
+ device = "cpu"
15
+
16
+ try:
17
+ if torch.backends.mps.is_available():
18
+ device = "mps"
19
+ except:
20
+ pass
21
+
22
+ def generate_prompt(input):
23
+ INSTRUCTION = f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
24
+
25
+
26
+ ### Instruction:
27
+ Create a Python script for this problem:
28
+ {input}
29
+
30
+ ### Response:"""
31
+ return INSTRUCTION
32
+
33
+ def get_model(
34
+ load_8bit: bool = False,
35
+ base_model: str = "bigcode/starcoder",
36
+ ):
37
+ assert base_model, (
38
+ "Please specify a --base_model, e.g. --base_model='bigcode/starcoder'"
39
+ )
40
+
41
+ tokenizer = AutoTokenizer.from_pretrained(base_model)
42
+ if device == "cuda":
43
+ model = AutoModelForCausalLM.from_pretrained(
44
+ base_model,
45
+ load_in_8bit=load_8bit,
46
+ torch_dtype=torch.float16,
47
+ device_map="auto",
48
+ )
49
+ elif device == "mps":
50
+ model = AutoModelForCausalLM.from_pretrained(
51
+ base_model,
52
+ device_map={"": device},
53
+ torch_dtype=torch.float16,
54
+ )
55
+ model.config.pad_token_id = tokenizer.pad_token_id
56
+
57
+ if not load_8bit:
58
+ model.half() # seems to fix bugs for some users.
59
+
60
+ model.eval()
61
+ if torch.__version__ >= "2" and sys.platform != "win32":
62
+ model = torch.compile(model)
63
+
64
+ return tokenizer, model
65
+
66
+
67
+ def main():
68
+ parser = argparse.ArgumentParser()
69
+
70
+ parser.add_argument('--model', type=str, default='bigcode/starcoder', help="")
71
+ parser.add_argument('--output_path', type=str, help="")
72
+ parser.add_argument('--start_index', type=int, default=0, help="")
73
+ parser.add_argument('--end_index', type=int, default=164, help="")
74
+ parser.add_argument('--temperature', type=float, default=0.8, help="")
75
+ parser.add_argument('--N', type=int, default=200, help="")
76
+ parser.add_argument('--max_len', type=int, default=512, help="")
77
+ parser.add_argument('--decoding_style', type=str, default='sampling', help="")
78
+ parser.add_argument('--num_seqs_per_iter', type=int, default=50, help='')
79
+ parser.add_argument('--greedy_decode', action='store_true', help='')
80
+ parser.add_argument('--overwrite', action='store_true', help='')
81
+
82
+ args = parser.parse_args()
83
+
84
+ argsdict = vars(args)
85
+ print(pprint.pformat(argsdict))
86
+
87
+ problems = read_problems()
88
+
89
+ task_ids = sorted(problems.keys())[args.start_index: args.end_index]
90
+ prompts = [problems[task_id]['prompt'] for task_id in task_ids]
91
+ num_samples = len(prompts)
92
+ print("Number of samples: {}".format(num_samples))
93
+
94
+ tokenizer, model = get_model(base_model=args.model)
95
+ generation_config = GenerationConfig(
96
+ pad_token_id=tokenizer.pad_token_id,
97
+ do_sample=False if args.greedy_decode else True,
98
+ temperature=args.temperature,
99
+ max_length=args.max_len,
100
+ num_return_sequences=args.num_seqs_per_iter,
101
+ eos_token_id=tokenizer.eos_token_id,
102
+ top_p=0.95
103
+ )
104
+
105
+ print(f"Loaded {args.model}.")
106
+ for i in tqdm(range(num_samples), ncols=0, total=num_samples):
107
+ output_file = args.output_path + '/{}.jsonl'.format(args.start_index + i)
108
+
109
+ if os.path.exists(output_file) and not args.overwrite:
110
+ print(f'Skip {output_file} as it already exists')
111
+ continue
112
+
113
+ prompt = prompts[i].replace(' ', '\t')
114
+ prompt_batch = [generate_prompt(prompt)]
115
+
116
+ ids_batch = [task_ids[i]]
117
+
118
+ completion_seqs = []
119
+
120
+ encoding = tokenizer(prompt_batch, return_tensors="pt", truncation=True, max_length=args.max_len).to(device)
121
+
122
+ if args.decoding_style == 'sampling':
123
+ loops = int(args.N / args.num_seqs_per_iter)
124
+ else:
125
+ loops = 1
126
+
127
+ for _ in tqdm(range(loops), total=loops, leave=False, ncols=0):
128
+
129
+ with torch.no_grad():
130
+ gen_tokens = model.generate(
131
+ **encoding,
132
+ generation_config=generation_config
133
+ )
134
+
135
+ if gen_tokens is not None:
136
+ gen_seqs = tokenizer.batch_decode(gen_tokens, skip_special_tokens=True)
137
+ else:
138
+ gen_seqs = None
139
+
140
+ if gen_seqs is not None:
141
+ assert len(ids_batch) == 1
142
+ task_id = ids_batch[0]
143
+
144
+ for seq_idx, gen_seq in enumerate(gen_seqs):
145
+ completion_seq = gen_seq.split("### Response:")[1]
146
+ completion_seq = completion_seq.replace('\t', ' ')
147
+ all_code = gen_seq.replace('\t', ' ')
148
+
149
+ completion_seqs.append(
150
+ {'task_id': task_id,
151
+ 'completion': completion_seq,
152
+ 'all_code': all_code,
153
+ }
154
+ )
155
+
156
+ print("Saving results to {}".format(output_file))
157
+ write_jsonl(output_file, completion_seqs)
158
+
159
+
160
+ if __name__ == '__main__':
161
+ main()
src/humaneval_gen_vllm.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import pprint
3
+ import sys
4
+ import os
5
+ import re
6
+ from tqdm import tqdm
7
+ import torch
8
+ from transformers import LlamaTokenizer, AutoModelForCausalLM, GenerationConfig, BitsAndBytesConfig
9
+ from human_eval.data import write_jsonl, read_problems, stream_jsonl
10
+
11
+ from vllm import LLM
12
+ from vllm import SamplingParams
13
+
14
+ if torch.cuda.is_available():
15
+ device = "cuda"
16
+ else:
17
+ device = "cpu"
18
+
19
+ try:
20
+ if torch.backends.mps.is_available():
21
+ device = "mps"
22
+ except:
23
+ pass
24
+
25
+ def generate_prompt(input):
26
+ INSTRUCTION = f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
27
+
28
+
29
+ ### Instruction:
30
+ Create a Python script for this problem:
31
+ {input}
32
+
33
+ ### Response:"""
34
+ return INSTRUCTION
35
+
36
+
37
+ def main():
38
+ parser = argparse.ArgumentParser()
39
+
40
+ parser.add_argument('--model', type=str, default='bigcode/starcoder', help="")
41
+ parser.add_argument('--lora', type=str, default='bigcode/starcoder', help="")
42
+ parser.add_argument('--output_path', type=str, help="")
43
+ parser.add_argument('--start_index', type=int, default=0, help="")
44
+ parser.add_argument('--end_index', type=int, default=164, help="")
45
+ parser.add_argument('--temperature', type=float, default=0.8, help="")
46
+ parser.add_argument('--N', type=int, default=200, help="")
47
+ parser.add_argument('--max_len', type=int, default=512, help="")
48
+ parser.add_argument('--num_gpus', type=int, default=4, help="")
49
+ parser.add_argument('--decoding_style', type=str, default='sampling', help="")
50
+ parser.add_argument('--num_seqs_per_iter', type=int, default=50, help='')
51
+ parser.add_argument('--overwrite', action='store_true', help='')
52
+
53
+ args = parser.parse_args()
54
+
55
+ argsdict = vars(args)
56
+ print(pprint.pformat(argsdict))
57
+
58
+ problems = read_problems()
59
+
60
+ task_ids = sorted(problems.keys())[args.start_index: args.end_index]
61
+ prompts = [problems[task_id]['prompt'] for task_id in task_ids]
62
+ num_samples = len(prompts)
63
+ print("Number of samples: {}".format(num_samples))
64
+
65
+ llm = LLM(base_model, tensor_parallel_size=args.num_gpus)
66
+ sampling_params = SamplingParams(temperature=args.temperature, top_p=1, max_tokens=args.max_len)
67
+
68
+ print(f"Loaded {args.model}.")
69
+ for i in tqdm(range(num_samples), ncols=0, total=num_samples):
70
+ output_file = args.output_path + '/{}.jsonl'.format(args.start_index + i)
71
+
72
+ if os.path.exists(output_file) and not args.overwrite:
73
+ print(f'Skip {output_file} as it already exists')
74
+ continue
75
+
76
+ prompt = prompts[i].replace(' ', '\t')
77
+ prompt_batch = [generate_prompt(prompt)]
78
+
79
+ ids_batch = [task_ids[i]]
80
+ completion_seqs = []
81
+
82
+ if args.decoding_style == 'sampling':
83
+ loops = int(args.N / args.num_seqs_per_iter)
84
+ else:
85
+ loops = 1
86
+
87
+ for _ in tqdm(range(loops), total=loops, leave=False, ncols=0):
88
+
89
+ with torch.no_grad():
90
+ completions = llm.generate(prompt_batch, sampling_params)
91
+ gen_seqs = [completions[0].outputs[0].text]
92
+
93
+ if gen_seqs is not None:
94
+ assert len(ids_batch) == 1
95
+ task_id = ids_batch[0]
96
+
97
+ for seq_idx, gen_seq in enumerate(gen_seqs):
98
+ completion_seq = gen_seq.split("### Response:")[-1]
99
+ completion_seq = completion_seq.replace('\t', ' ')
100
+ all_code = gen_seq.replace('\t', ' ')
101
+
102
+ completion_seqs.append(
103
+ {'task_id': task_id,
104
+ 'completion': completion_seq,
105
+ 'all_code': all_code,
106
+ }
107
+ )
108
+
109
+ print("Saving results to {}".format(output_file))
110
+ write_jsonl(output_file, completion_seqs)
111
+
112
+
113
+ if __name__ == '__main__':
114
+ main()
src/inference_wizardcoder.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import fire
4
+ import torch
5
+ import transformers
6
+ import json
7
+ import jsonlines
8
+
9
+ from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
10
+
11
+ if torch.cuda.is_available():
12
+ device = "cuda"
13
+ else:
14
+ device = "cpu"
15
+
16
+ try:
17
+ if torch.backends.mps.is_available():
18
+ device = "mps"
19
+ except:
20
+ pass
21
+
22
+ def evaluate(
23
+ batch_data,
24
+ tokenizer,
25
+ model,
26
+ input=None,
27
+ temperature=1,
28
+ top_p=0.9,
29
+ top_k=40,
30
+ num_beams=1,
31
+ max_new_tokens=2048,
32
+ **kwargs,
33
+ ):
34
+ prompts = generate_prompt(batch_data, input)
35
+ inputs = tokenizer(prompts, return_tensors="pt", max_length=256, truncation=True, padding=True)
36
+ input_ids = inputs["input_ids"].to(device)
37
+ generation_config = GenerationConfig(
38
+ temperature=temperature,
39
+ top_p=top_p,
40
+ top_k=top_k,
41
+ num_beams=num_beams,
42
+ eos_token_id=tokenizer.eos_token_id,
43
+ pad_token_id=tokenizer.pad_token_id,
44
+ **kwargs,
45
+ )
46
+ with torch.no_grad():
47
+ generation_output = model.generate(
48
+ input_ids=input_ids,
49
+ generation_config=generation_config,
50
+ return_dict_in_generate=True,
51
+ output_scores=True,
52
+ max_new_tokens=max_new_tokens,
53
+ )
54
+ s = generation_output.sequences
55
+ output = tokenizer.batch_decode(s, skip_special_tokens=True)
56
+ return output
57
+
58
+
59
+ def generate_prompt(instruction, input=None):
60
+ return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
61
+
62
+ ### Instruction:
63
+ {instruction}
64
+
65
+ ### Response:"""
66
+
67
+
68
+ def main(
69
+ load_8bit: bool = False,
70
+ base_model: str = "Model_Path",
71
+ input_data_path = "Input.jsonl",
72
+ output_data_path = "Output.jsonl",
73
+ ):
74
+ assert base_model, (
75
+ "Please specify a --base_model, e.g. --base_model='bigcode/starcoder'"
76
+ )
77
+
78
+ tokenizer = AutoTokenizer.from_pretrained(base_model)
79
+ if device == "cuda":
80
+ model = AutoModelForCausalLM.from_pretrained(
81
+ base_model,
82
+ load_in_8bit=load_8bit,
83
+ torch_dtype=torch.float16,
84
+ device_map="auto",
85
+ )
86
+ elif device == "mps":
87
+ model = AutoModelForCausalLM.from_pretrained(
88
+ base_model,
89
+ device_map={"": device},
90
+ torch_dtype=torch.float16,
91
+ )
92
+
93
+ model.config.pad_token_id = tokenizer.pad_token_id
94
+
95
+ if not load_8bit:
96
+ model.half()
97
+
98
+ model.eval()
99
+ if torch.__version__ >= "2" and sys.platform != "win32":
100
+ model = torch.compile(model)
101
+
102
+ input_data = jsonlines.open(input_data_path, mode='r')
103
+ output_data = jsonlines.open(output_data_path, mode='w')
104
+
105
+ for num, line in enumerate(input_data):
106
+ one_data = line
107
+ id = one_data["idx"]
108
+ instruction = one_data["Instruction"]
109
+ print(instruction)
110
+ _output = evaluate(instruction, tokenizer, model)
111
+ final_output = _output[0].split("### Response:")[1].strip()
112
+ new_data = {
113
+ "id": id,
114
+ "instruction": instruction,
115
+ "wizardcoder": final_output
116
+ }
117
+ output_data.write(new_data)
118
+
119
+
120
+ if __name__ == "__main__":
121
+ fire.Fire(main)
src/mbpp_gen.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import jsonlines
2
+ import argparse
3
+ import pprint
4
+ import sys
5
+ import os
6
+ import re
7
+ from tqdm import tqdm
8
+ import torch
9
+ from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
10
+ from human_eval.data import write_jsonl, read_problems, stream_jsonl
11
+
12
+ if torch.cuda.is_available():
13
+ device = "cuda"
14
+ else:
15
+ device = "cpu"
16
+
17
+ try:
18
+ if torch.backends.mps.is_available():
19
+ device = "mps"
20
+ except:
21
+ pass
22
+
23
+ def read_mbpp(path):
24
+ mbpp_problems = {}
25
+ with jsonlines.open(path, "r") as fin:
26
+ for obj in fin:
27
+ mbpp_problems[obj["task_id"]] = obj
28
+ return mbpp_problems
29
+
30
+ def extract_text(prompt, remove_lines=True):
31
+ token = '\"\"\"'
32
+ start = token
33
+ end = '>>>'
34
+
35
+ start_idx = prompt.find(start) + len(start)
36
+ end_idx = prompt.find(end)
37
+
38
+ output = prompt[start_idx: end_idx]
39
+ if remove_lines:
40
+ output = output.replace('\n', ' ')
41
+ output = re.sub(r"\s+", " ", output).strip()
42
+
43
+ return output
44
+
45
+ def generate_prompt(input):
46
+ INSTRUCTION = f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
47
+
48
+ ### Instruction:
49
+ Create a Python script for this problem:
50
+ {input}
51
+
52
+ ### Response:"""
53
+ return INSTRUCTION
54
+
55
+ def get_model(
56
+ load_8bit: bool = False,
57
+ base_model: str = "bigcode/starcoder",
58
+ ):
59
+ assert base_model, (
60
+ "Please specify a --base_model, e.g. --base_model='bigcode/starcoder'"
61
+ )
62
+
63
+ tokenizer = AutoTokenizer.from_pretrained(base_model)
64
+ if device == "cuda":
65
+ model = AutoModelForCausalLM.from_pretrained(
66
+ base_model,
67
+ load_in_8bit=load_8bit,
68
+ torch_dtype=torch.float16,
69
+ device_map="auto",
70
+ )
71
+ elif device == "mps":
72
+ model = AutoModelForCausalLM.from_pretrained(
73
+ base_model,
74
+ device_map={"": device},
75
+ torch_dtype=torch.float16,
76
+ )
77
+ model.config.pad_token_id = tokenizer.pad_token_id
78
+
79
+ if not load_8bit:
80
+ model.half() # seems to fix bugs for some users.
81
+
82
+ model.eval()
83
+ if torch.__version__ >= "2" and sys.platform != "win32":
84
+ model = torch.compile(model)
85
+
86
+ return tokenizer, model
87
+
88
+
89
+ def main():
90
+ parser = argparse.ArgumentParser()
91
+
92
+ parser.add_argument('--model', type=str, default='bigcode/starcoder', help="")
93
+ parser.add_argument('--output_path', type=str, help="")
94
+ parser.add_argument('--start_index', type=int, default=0, help="")
95
+ parser.add_argument('--end_index', type=int, default=164, help="")
96
+ parser.add_argument('--temperature', type=float, default=0.8, help="")
97
+ parser.add_argument('--N', type=int, default=200, help="")
98
+ parser.add_argument('--max_len', type=int, default=512, help="")
99
+ parser.add_argument('--decoding_style', type=str, default='sampling', help="")
100
+ parser.add_argument('--num_seqs_per_iter', type=int, default=50, help='')
101
+ parser.add_argument('--overwrite', action='store_true', help='')
102
+ parser.add_argument('--mbpp_path', type=str, help="")
103
+
104
+ args = parser.parse_args()
105
+
106
+ argsdict = vars(args)
107
+ print(pprint.pformat(argsdict))
108
+
109
+ STOP_SEQS = ['\nclass', '\ndef', '\n#', '\nif', '\nprint']
110
+
111
+ problems = read_mbpp(args.mbpp_path)
112
+
113
+ task_ids = sorted(problems.keys())[args.start_index: args.end_index]
114
+ prompts = []
115
+ for task_id in task_ids:
116
+ prompt = f"\n{problems[task_id]['text']}\nTest examples:"
117
+ if task_id == 493:
118
+ # The test examples are too long. We choose to only include the function name.
119
+ test_example = problems[task_id]['test_list'][0]
120
+ prompt += f"\ncalculate_polygons(startx, starty, endx, endy, radius)"
121
+ else:
122
+ for test_example in problems[task_id]['test_list']:
123
+ prompt += f"\n{test_example}"
124
+ prompts.append(prompt)
125
+
126
+ num_samples = len(prompts)
127
+ print("Number of samples: {}".format(num_samples))
128
+
129
+ tokenizer, model = get_model(base_model=args.model)
130
+ generation_config = GenerationConfig(
131
+ pad_token_id=tokenizer.pad_token_id,
132
+ do_sample=True,
133
+ temperature=args.temperature,
134
+ max_length=args.max_len,
135
+ num_return_sequences=args.num_seqs_per_iter,
136
+ eos_token_id=tokenizer.eos_token_id,
137
+ top_p=0.95
138
+ )
139
+
140
+ print(f"Loaded {args.model}.")
141
+ for i in tqdm(range(num_samples), ncols=0, total=num_samples):
142
+ output_file = args.output_path + '/{}.jsonl'.format(args.start_index + i)
143
+
144
+ if os.path.exists(output_file) and not args.overwrite:
145
+ print(f'Skip {output_file} as it already exists')
146
+ continue
147
+
148
+ prompt = prompts[i].replace(' ', '\t')
149
+ prompt_batch = [generate_prompt(prompt)]
150
+
151
+ ids_batch = [task_ids[i]]
152
+
153
+ completion_seqs = []
154
+
155
+ encoding = tokenizer(prompt_batch, return_tensors="pt", truncation=True, max_length=args.max_len).to(device)
156
+
157
+ if args.decoding_style == 'sampling':
158
+ loops = int(args.N / args.num_seqs_per_iter)
159
+ else:
160
+ loops = 1
161
+
162
+ for _ in tqdm(range(loops), total=loops, leave=False, ncols=0):
163
+
164
+ with torch.no_grad():
165
+ if args.decoding_style == 'sampling':
166
+ gen_tokens = model.generate(
167
+ **encoding,
168
+ generation_config=generation_config
169
+ )
170
+
171
+ if gen_tokens is not None:
172
+ gen_seqs = tokenizer.batch_decode(gen_tokens, skip_special_tokens=True)
173
+ else:
174
+ gen_seqs = None
175
+
176
+ if gen_seqs is not None:
177
+ assert len(ids_batch) == 1
178
+ task_id = ids_batch[0]
179
+
180
+ for seq_idx, gen_seq in enumerate(gen_seqs):
181
+ completion_seq = gen_seq.split("### Response:")[-1]
182
+ completion_seq = completion_seq.replace('\t', ' ')
183
+ all_code = gen_seq.replace('\t', ' ')
184
+
185
+ completion_seqs.append(
186
+ {'task_id': task_id,
187
+ 'completion': completion_seq,
188
+ 'all_code': all_code,
189
+ }
190
+ )
191
+
192
+ print("Saving results to {}".format(output_file))
193
+ write_jsonl(output_file, completion_seqs)
194
+
195
+
196
+ if __name__ == '__main__':
197
+ main()
src/process_humaneval.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from human_eval.data import read_problems, write_jsonl, stream_jsonl
2
+ import glob
3
+ from tqdm import tqdm
4
+ import argparse
5
+
6
+ parser = argparse.ArgumentParser()
7
+
8
+ # Inputs
9
+ parser.add_argument(
10
+ '--path',
11
+ type=str,
12
+ help="")
13
+ parser.add_argument(
14
+ '--out_path',
15
+ type=str,
16
+ help="")
17
+ parser.add_argument(
18
+ '--add_prompt',
19
+ action='store_true',
20
+ help='')
21
+
22
+ args = parser.parse_args()
23
+
24
+
25
+ files = sorted(glob.glob(args.path + '/*.jsonl'))
26
+ print("{} files in {}".format(len(files), args.path))
27
+
28
+ problems = read_problems()
29
+
30
+ output = []
31
+ a = 0
32
+ for code_file in tqdm(files, total=len(files)):
33
+ codes = [c for c in stream_jsonl(code_file)]
34
+ if args.add_prompt:
35
+ for code in codes:
36
+ task_id = code['task_id']
37
+ prompt = problems[task_id]['prompt']
38
+ completion = code['completion']
39
+ completion = completion.replace("\r", "")
40
+ if '```python' in completion:
41
+ def_line = completion.index('```python')
42
+ completion = completion[def_line:].strip()
43
+ completion = completion.replace('```python', '')
44
+ # print(completion)
45
+ try:
46
+ next_line = completion.index('```')
47
+ completion = completion[:next_line].strip()
48
+ except:
49
+ a += 1
50
+ print(completion)
51
+ print("================\n")
52
+ # print(completion)
53
+ if "__name__ == \"__main__\"" in completion:
54
+ next_line = completion.index('if __name__ == "__main__":')
55
+ completion = completion[:next_line].strip()
56
+ # print(completion)
57
+
58
+ if "# Example usage" in completion:
59
+ # print(completion)
60
+ next_line = completion.index('# Example usage')
61
+ completion = completion[:next_line].strip()
62
+
63
+ code['completion'] = completion
64
+
65
+ output += codes
66
+
67
+ print("save to {}".format(args.out_path))
68
+ write_jsonl(args.out_path, output)
69
+ print(a)
src/process_mbpp.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from human_eval.data import stream_jsonl
2
+ import glob
3
+ from tqdm import tqdm
4
+ import argparse
5
+ import jsonlines
6
+ import json
7
+
8
+ def read_mbpp(path):
9
+ mbpp_problems = {}
10
+ with jsonlines.open(path, "r") as fin:
11
+ for obj in fin:
12
+ mbpp_problems[obj["task_id"]] = obj
13
+ return mbpp_problems
14
+
15
+ parser = argparse.ArgumentParser()
16
+
17
+ # Inputs
18
+ parser.add_argument(
19
+ '--path',
20
+ type=str,
21
+ help="")
22
+ parser.add_argument(
23
+ '--out_path',
24
+ type=str,
25
+ help="")
26
+ parser.add_argument(
27
+ '--add_prompt',
28
+ action='store_true',
29
+ help='')
30
+ parser.add_argument('--mbpp_path', type=str, help="")
31
+
32
+ args = parser.parse_args()
33
+
34
+
35
+ files = sorted(glob.glob(args.path + '/*.jsonl'))
36
+ print("{} files in {}".format(len(files), args.path))
37
+
38
+ problems = read_mbpp(args.mbpp_path)
39
+ output = [[] for _ in range(len(problems))]
40
+ a = 0
41
+ for code_file in tqdm(files, total=len(files)):
42
+ codes = [c for c in stream_jsonl(code_file)]
43
+ if args.add_prompt:
44
+ for code in codes:
45
+ task_id = code['task_id']
46
+ completion = code['completion']
47
+ if '```python' in completion:
48
+ def_line = completion.index('```python')
49
+ completion = completion[def_line:].strip()
50
+ completion = completion.replace('```python', '')
51
+ try:
52
+ next_line = completion.index('\n```')
53
+ completion = completion[:next_line].strip()
54
+ except:
55
+ a += 1
56
+ if "__name__ == \"__main__\"" in completion:
57
+ next_line = completion.index('if __name__ == "__main__":')
58
+ completion = completion[:next_line].strip()
59
+
60
+ if "# Example usage" in completion:
61
+ next_line = completion.index('# Example usage')
62
+ completion = completion[:next_line].strip()
63
+
64
+ if "# Test examples" in completion:
65
+ next_line = completion.index('# Test examples')
66
+ completion = completion[:next_line].strip()
67
+
68
+ output[task_id-11].append(completion)
69
+
70
+ print("save to {}".format(args.out_path))
71
+ print(a)
72
+ with open(args.out_path, "w", encoding="utf-8") as fout:
73
+ json.dump(output, fout)
src/train_wizardcoder.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import copy
16
+ import logging
17
+ import random
18
+ from dataclasses import dataclass, field
19
+ from typing import Optional, Dict, Sequence
20
+
21
+ import torch
22
+ import torch.distributed
23
+ import transformers
24
+ from torch.utils.data import Dataset
25
+ from transformers import Trainer
26
+ from datasets import load_dataset
27
+ import utils
28
+
29
+ IGNORE_INDEX = -100
30
+ DEFAULT_PAD_TOKEN = "[PAD]"
31
+ DEFAULT_EOS_TOKEN = "<|endoftext|>"
32
+ DEFAULT_BOS_TOKEN = "<|endoftext|>"
33
+ DEFAULT_UNK_TOKEN = "<|endoftext|>"
34
+ PROMPT_DICT = {
35
+ "prompt_input": (
36
+ "Below is an instruction that describes a task, paired with an input that provides further context. "
37
+ "Write a response that appropriately completes the request.\n\n"
38
+ "### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:"
39
+ ),
40
+ "prompt_no_input": (
41
+ "Below is an instruction that describes a task. "
42
+ "Write a response that appropriately completes the request.\n\n"
43
+ "### Instruction:\n{instruction}\n\n### Response:"
44
+ ),
45
+ }
46
+
47
+
48
+ @dataclass
49
+ class ModelArguments:
50
+ model_name_or_path: Optional[str] = field(default="bigcode/starcoder")
51
+
52
+
53
+ @dataclass
54
+ class DataArguments:
55
+ data_path: str = field(default=None, metadata={"help": "Path to the training data."})
56
+
57
+
58
+ @dataclass
59
+ class TrainingArguments(transformers.TrainingArguments):
60
+ cache_dir: Optional[str] = field(default=None)
61
+ optim: str = field(default="adamw_torch")
62
+ model_max_length: int = field(
63
+ default=512,
64
+ metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."},
65
+ )
66
+
67
+
68
+ def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str):
69
+ """Collects the state dict and dump to disk."""
70
+ state_dict = trainer.model.state_dict()
71
+ if trainer.args.should_save:
72
+ cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()}
73
+ del state_dict
74
+ trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
75
+
76
+
77
+ def smart_tokenizer_and_embedding_resize(
78
+ special_tokens_dict: Dict,
79
+ tokenizer: transformers.PreTrainedTokenizer,
80
+ model: transformers.PreTrainedModel,
81
+ ):
82
+ """Resize tokenizer and embedding.
83
+
84
+ Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
85
+ """
86
+ num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
87
+ model.resize_token_embeddings(len(tokenizer))
88
+
89
+ if num_new_tokens > 0:
90
+ input_embeddings = model.get_input_embeddings().weight.data
91
+ output_embeddings = model.get_output_embeddings().weight.data
92
+
93
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
94
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
95
+
96
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
97
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
98
+
99
+
100
+ def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
101
+ """Tokenize a list of strings."""
102
+ tokenized_list = [
103
+ tokenizer(
104
+ text,
105
+ return_tensors="pt",
106
+ padding="longest",
107
+ max_length=tokenizer.model_max_length,
108
+ truncation=True,
109
+ )
110
+ for text in strings
111
+ ]
112
+ input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]
113
+ input_ids_lens = labels_lens = [
114
+ tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list
115
+ ]
116
+ return dict(
117
+ input_ids=input_ids,
118
+ labels=labels,
119
+ input_ids_lens=input_ids_lens,
120
+ labels_lens=labels_lens,
121
+ )
122
+
123
+
124
+ def preprocess(
125
+ sources: Sequence[str],
126
+ targets: Sequence[str],
127
+ tokenizer: transformers.PreTrainedTokenizer,
128
+ ) -> Dict:
129
+ """Preprocess the data by tokenizing."""
130
+ examples = [s + t for s, t in zip(sources, targets)]
131
+ examples_tokenized, sources_tokenized = [_tokenize_fn(strings, tokenizer) for strings in (examples, sources)]
132
+ input_ids = examples_tokenized["input_ids"]
133
+ labels = copy.deepcopy(input_ids)
134
+ for label, source_len in zip(labels, sources_tokenized["input_ids_lens"]):
135
+ label[:source_len] = IGNORE_INDEX
136
+ return dict(input_ids=input_ids, labels=labels)
137
+
138
+
139
+ @dataclass
140
+ class DataCollatorForSupervisedDataset(object):
141
+ """Collate examples for supervised fine-tuning."""
142
+
143
+ tokenizer: transformers.PreTrainedTokenizer
144
+
145
+ def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
146
+ input_ids, labels = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels"))
147
+ input_ids = [torch.tensor(x) for x in input_ids]
148
+ input_ids = torch.nn.utils.rnn.pad_sequence(
149
+ input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id
150
+ )
151
+ labels = [torch.tensor(x) for x in labels]
152
+ labels = torch.nn.utils.rnn.pad_sequence(labels, batch_first=True, padding_value=IGNORE_INDEX)
153
+ return dict(
154
+ input_ids=input_ids,
155
+ labels=labels,
156
+ attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
157
+ )
158
+
159
+ def train_tokenize_function(examples, tokenizer):
160
+ prompt_input, prompt_no_input = PROMPT_DICT["prompt_input"], PROMPT_DICT["prompt_no_input"]
161
+ if 'input' in examples:
162
+ sources = [
163
+ prompt_input.format_map(dict(instruction=instruction, input=input)) if input != "" \
164
+ else prompt_no_input.format_map(dict(instruction=instruction)) \
165
+ for instruction, input in zip(examples['instruction'], examples['input'])
166
+ ]
167
+ else:
168
+ sources = [
169
+ prompt_no_input.format_map(dict(instruction=instruction)) \
170
+ for instruction in examples['instruction']
171
+ ]
172
+ targets = [f"{output}{tokenizer.eos_token}" for output in examples['output']]
173
+ data_dict = preprocess(sources, targets, tokenizer)
174
+ return data_dict
175
+
176
+
177
+ def train():
178
+ parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
179
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
180
+
181
+ model = transformers.AutoModelForCausalLM.from_pretrained(
182
+ model_args.model_name_or_path,
183
+ cache_dir=training_args.cache_dir,
184
+ )
185
+
186
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
187
+ model_args.model_name_or_path,
188
+ cache_dir=training_args.cache_dir,
189
+ model_max_length=training_args.model_max_length,
190
+ padding_side="right",
191
+ use_fast=True,
192
+ )
193
+ if tokenizer.pad_token is None:
194
+ smart_tokenizer_and_embedding_resize(
195
+ special_tokens_dict=dict(pad_token=DEFAULT_PAD_TOKEN),
196
+ tokenizer=tokenizer,
197
+ model=model,
198
+ )
199
+ if "starcoder" in model_args.model_name_or_path:
200
+ tokenizer.add_special_tokens(
201
+ {
202
+ "eos_token": DEFAULT_EOS_TOKEN,
203
+ "bos_token": DEFAULT_BOS_TOKEN,
204
+ "unk_token": DEFAULT_UNK_TOKEN,
205
+ "pad_token": DEFAULT_PAD_TOKEN,
206
+ }
207
+ )
208
+
209
+ raw_train_datasets = load_dataset('json', data_files=data_args.data_path, split="train", cache_dir=training_args.cache_dir)
210
+ if training_args.local_rank > 0:
211
+ torch.distributed.barrier()
212
+
213
+ train_dataset = raw_train_datasets.map(
214
+ train_tokenize_function,
215
+ batched=True,
216
+ batch_size=3000,
217
+ num_proc=32,
218
+ remove_columns=raw_train_datasets.column_names,
219
+ load_from_cache_file=True, # not args.overwrite_cache
220
+ desc="Running tokenizer on train dataset",
221
+ fn_kwargs={"tokenizer": tokenizer}
222
+ )
223
+
224
+ if training_args.local_rank == 0:
225
+ torch.distributed.barrier()
226
+
227
+ if training_args.local_rank == 0:
228
+ print(len(train_dataset))
229
+ for index in random.sample(range(len(train_dataset)), 3):
230
+ print(f"Sample {index} of the training set: {train_dataset[index]}.")
231
+
232
+ data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
233
+ data_module = dict(train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator)
234
+
235
+ #Tell Trainer not to attempt DataParallel
236
+ model.is_parallelizable = True
237
+ model.model_parallel = True
238
+
239
+ trainer = Trainer(model=model, tokenizer=tokenizer, args=training_args, **data_module)
240
+ model.config.use_cache = False
241
+
242
+ trainer.train()
243
+ trainer.save_state()
244
+ safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir)
245
+
246
+
247
+ if __name__ == "__main__":
248
+ train()