├── .DS_Store ├── .gitignore ├── DATA_LICENSE ├── LICENSE ├── README.md ├── __init__.py ├── assets ├── .DS_Store └── logo.png ├── configs └── config.yml ├── data ├── dataset │ ├── __init__.py │ └── capybara.py ├── loaders │ ├── __init__.py │ ├── load_code_alpaca.py │ ├── load_code_capybara.py │ └── load_code_contests.py ├── prompts │ ├── __init__.py │ └── prompt.py └── utils │ ├── __init__.py │ ├── mask.py │ └── pad.py ├── data_generation ├── call.sh ├── data_generation.py └── tokenizer.py ├── deploy └── run_hf.py ├── main ├── __init__.py ├── data │ └── HumanEval.jsonl.gz ├── eval_humaneval.py ├── eval_mbpp.py ├── generate.py ├── train.py └── utils │ ├── evaluation.py │ └── prompter.py ├── requirements.txt └── scripts ├── eval_humaneval.sh ├── eval_mbpp.sh └── train.sh /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FSoft-AI4Code/CodeCapybara/9bc7ab4305444cca625ceed7b1aaca987a193bec/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | output_dir/ 3 | haha/ 4 | checkpoints/ 5 | logs/ 6 | env/ 7 | wandb/ 8 | LLaMA-7B/ 9 | *.jsonl 10 | *.json -------------------------------------------------------------------------------- /DATA_LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. Copyright and Similar Rights means copyright and/or similar rights 88 | closely related to copyright including, without limitation, 89 | performance, broadcast, sound recording, and Sui Generis Database 90 | Rights, without regard to how the rights are labeled or 91 | categorized. For purposes of this Public License, the rights 92 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 93 | Rights. 94 | d. Effective Technological Measures means those measures that, in the 95 | absence of proper authority, may not be circumvented under laws 96 | fulfilling obligations under Article 11 of the WIPO Copyright 97 | Treaty adopted on December 20, 1996, and/or similar international 98 | agreements. 99 | 100 | e. Exceptions and Limitations means fair use, fair dealing, and/or 101 | any other exception or limitation to Copyright and Similar Rights 102 | that applies to Your use of the Licensed Material. 103 | 104 | f. Licensed Material means the artistic or literary work, database, 105 | or other material to which the Licensor applied this Public 106 | License. 107 | 108 | g. Licensed Rights means the rights granted to You subject to the 109 | terms and conditions of this Public License, which are limited to 110 | all Copyright and Similar Rights that apply to Your use of the 111 | Licensed Material and that the Licensor has authority to license. 112 | 113 | h. Licensor means the individual(s) or entity(ies) granting rights 114 | under this Public License. 115 | 116 | i. NonCommercial means not primarily intended for or directed towards 117 | commercial advantage or monetary compensation. For purposes of 118 | this Public License, the exchange of the Licensed Material for 119 | other material subject to Copyright and Similar Rights by digital 120 | file-sharing or similar means is NonCommercial provided there is 121 | no payment of monetary compensation in connection with the 122 | exchange. 123 | 124 | j. Share means to provide material to the public by any means or 125 | process that requires permission under the Licensed Rights, such 126 | as reproduction, public display, public performance, distribution, 127 | dissemination, communication, or importation, and to make material 128 | available to the public including in ways that members of the 129 | public may access the material from a place and at a time 130 | individually chosen by them. 131 | 132 | k. Sui Generis Database Rights means rights other than copyright 133 | resulting from Directive 96/9/EC of the European Parliament and of 134 | the Council of 11 March 1996 on the legal protection of databases, 135 | as amended and/or succeeded, as well as other essentially 136 | equivalent rights anywhere in the world. 137 | 138 | l. You means the individual or entity exercising the Licensed Rights 139 | under this Public License. Your has a corresponding meaning. 140 | 141 | 142 | Section 2 -- Scope. 143 | 144 | a. License grant. 145 | 146 | 1. Subject to the terms and conditions of this Public License, 147 | the Licensor hereby grants You a worldwide, royalty-free, 148 | non-sublicensable, non-exclusive, irrevocable license to 149 | exercise the Licensed Rights in the Licensed Material to: 150 | 151 | a. reproduce and Share the Licensed Material, in whole or 152 | in part, for NonCommercial purposes only; and 153 | 154 | b. produce, reproduce, and Share Adapted Material for 155 | NonCommercial purposes only. 156 | 157 | 2. Exceptions and Limitations. For the avoidance of doubt, where 158 | Exceptions and Limitations apply to Your use, this Public 159 | License does not apply, and You do not need to comply with 160 | its terms and conditions. 161 | 162 | 3. Term. The term of this Public License is specified in Section 163 | 6(a). 164 | 165 | 4. Media and formats; technical modifications allowed. The 166 | Licensor authorizes You to exercise the Licensed Rights in 167 | all media and formats whether now known or hereafter created, 168 | and to make technical modifications necessary to do so. The 169 | Licensor waives and/or agrees not to assert any right or 170 | authority to forbid You from making technical modifications 171 | necessary to exercise the Licensed Rights, including 172 | technical modifications necessary to circumvent Effective 173 | Technological Measures. For purposes of this Public License, 174 | simply making modifications authorized by this Section 2(a) 175 | (4) never produces Adapted Material. 176 | 177 | 5. Downstream recipients. 178 | 179 | a. Offer from the Licensor -- Licensed Material. Every 180 | recipient of the Licensed Material automatically 181 | receives an offer from the Licensor to exercise the 182 | Licensed Rights under the terms and conditions of this 183 | Public License. 184 | 185 | b. No downstream restrictions. You may not offer or impose 186 | any additional or different terms or conditions on, or 187 | apply any Effective Technological Measures to, the 188 | Licensed Material if doing so restricts exercise of the 189 | Licensed Rights by any recipient of the Licensed 190 | Material. 191 | 192 | 6. No endorsement. Nothing in this Public License constitutes or 193 | may be construed as permission to assert or imply that You 194 | are, or that Your use of the Licensed Material is, connected 195 | with, or sponsored, endorsed, or granted official status by, 196 | the Licensor or others designated to receive attribution as 197 | provided in Section 3(a)(1)(A)(i). 198 | 199 | b. Other rights. 200 | 201 | 1. Moral rights, such as the right of integrity, are not 202 | licensed under this Public License, nor are publicity, 203 | privacy, and/or other similar personality rights; however, to 204 | the extent possible, the Licensor waives and/or agrees not to 205 | assert any such rights held by the Licensor to the limited 206 | extent necessary to allow You to exercise the Licensed 207 | Rights, but not otherwise. 208 | 209 | 2. Patent and trademark rights are not licensed under this 210 | Public License. 211 | 212 | 3. To the extent possible, the Licensor waives any right to 213 | collect royalties from You for the exercise of the Licensed 214 | Rights, whether directly or through a collecting society 215 | under any voluntary or waivable statutory or compulsory 216 | licensing scheme. In all other cases the Licensor expressly 217 | reserves any right to collect such royalties, including when 218 | the Licensed Material is used other than for NonCommercial 219 | purposes. 220 | 221 | 222 | Section 3 -- License Conditions. 223 | 224 | Your exercise of the Licensed Rights is expressly made subject to the 225 | following conditions. 226 | 227 | a. Attribution. 228 | 229 | 1. If You Share the Licensed Material (including in modified 230 | form), You must: 231 | 232 | a. retain the following if it is supplied by the Licensor 233 | with the Licensed Material: 234 | 235 | i. identification of the creator(s) of the Licensed 236 | Material and any others designated to receive 237 | attribution, in any reasonable manner requested by 238 | the Licensor (including by pseudonym if 239 | designated); 240 | 241 | ii. a copyright notice; 242 | 243 | iii. a notice that refers to this Public License; 244 | 245 | iv. a notice that refers to the disclaimer of 246 | warranties; 247 | 248 | v. a URI or hyperlink to the Licensed Material to the 249 | extent reasonably practicable; 250 | 251 | b. indicate if You modified the Licensed Material and 252 | retain an indication of any previous modifications; and 253 | 254 | c. indicate the Licensed Material is licensed under this 255 | Public License, and include the text of, or the URI or 256 | hyperlink to, this Public License. 257 | 258 | 2. You may satisfy the conditions in Section 3(a)(1) in any 259 | reasonable manner based on the medium, means, and context in 260 | which You Share the Licensed Material. For example, it may be 261 | reasonable to satisfy the conditions by providing a URI or 262 | hyperlink to a resource that includes the required 263 | information. 264 | 265 | 3. If requested by the Licensor, You must remove any of the 266 | information required by Section 3(a)(1)(A) to the extent 267 | reasonably practicable. 268 | 269 | 4. If You Share Adapted Material You produce, the Adapter's 270 | License You apply must not prevent recipients of the Adapted 271 | Material from complying with this Public License. 272 | 273 | 274 | Section 4 -- Sui Generis Database Rights. 275 | 276 | Where the Licensed Rights include Sui Generis Database Rights that 277 | apply to Your use of the Licensed Material: 278 | 279 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 280 | to extract, reuse, reproduce, and Share all or a substantial 281 | portion of the contents of the database for NonCommercial purposes 282 | only; 283 | 284 | b. if You include all or a substantial portion of the database 285 | contents in a database in which You have Sui Generis Database 286 | Rights, then the database in which You have Sui Generis Database 287 | Rights (but not its individual contents) is Adapted Material; and 288 | 289 | c. You must comply with the conditions in Section 3(a) if You Share 290 | all or a substantial portion of the contents of the database. 291 | 292 | For the avoidance of doubt, this Section 4 supplements and does not 293 | replace Your obligations under this Public License where the Licensed 294 | Rights include other Copyright and Similar Rights. 295 | 296 | 297 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 298 | 299 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 300 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 301 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 302 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 303 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 304 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 305 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 306 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 307 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 308 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 309 | 310 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 311 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 312 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 313 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 314 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 315 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 316 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 317 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 318 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 319 | 320 | c. The disclaimer of warranties and limitation of liability provided 321 | above shall be interpreted in a manner that, to the extent 322 | possible, most closely approximates an absolute disclaimer and 323 | waiver of all liability. 324 | 325 | 326 | Section 6 -- Term and Termination. 327 | 328 | a. This Public License applies for the term of the Copyright and 329 | Similar Rights licensed here. However, if You fail to comply with 330 | this Public License, then Your rights under this Public License 331 | terminate automatically. 332 | 333 | b. Where Your right to use the Licensed Material has terminated under 334 | Section 6(a), it reinstates: 335 | 336 | 1. automatically as of the date the violation is cured, provided 337 | it is cured within 30 days of Your discovery of the 338 | violation; or 339 | 340 | 2. upon express reinstatement by the Licensor. 341 | 342 | For the avoidance of doubt, this Section 6(b) does not affect any 343 | right the Licensor may have to seek remedies for Your violations 344 | of this Public License. 345 | 346 | c. For the avoidance of doubt, the Licensor may also offer the 347 | Licensed Material under separate terms or conditions or stop 348 | distributing the Licensed Material at any time; however, doing so 349 | will not terminate this Public License. 350 | 351 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 352 | License. 353 | 354 | 355 | Section 7 -- Other Terms and Conditions. 356 | 357 | a. The Licensor shall not be bound by any additional or different 358 | terms or conditions communicated by You unless expressly agreed. 359 | 360 | b. Any arrangements, understandings, or agreements regarding the 361 | Licensed Material not stated herein are separate from and 362 | independent of the terms and conditions of this Public License. 363 | 364 | 365 | Section 8 -- Interpretation. 366 | 367 | a. For the avoidance of doubt, this Public License does not, and 368 | shall not be interpreted to, reduce, limit, restrict, or impose 369 | conditions on any use of the Licensed Material that could lawfully 370 | be made without permission under this Public License. 371 | 372 | b. To the extent possible, if any provision of this Public License is 373 | deemed unenforceable, it shall be automatically reformed to the 374 | minimum extent necessary to make it enforceable. If the provision 375 | cannot be reformed, it shall be severed from this Public License 376 | without affecting the enforceability of the remaining terms and 377 | conditions. 378 | 379 | c. No term or condition of this Public License will be waived and no 380 | failure to comply consented to unless expressly agreed to by the 381 | Licensor. 382 | 383 | d. Nothing in this Public License constitutes or may be interpreted 384 | as a limitation upon, or waiver of, any privileges and immunities 385 | that apply to the Licensor or You, including from the legal 386 | processes of any jurisdiction or authority. 387 | 388 | ======================================================================= 389 | 390 | Creative Commons is not a party to its public 391 | licenses. Notwithstanding, Creative Commons may elect to apply one of 392 | its public licenses to material it publishes and in those instances 393 | will be considered the “Licensor.” The text of the Creative Commons 394 | public licenses is dedicated to the public domain under the CC0 Public 395 | Domain Dedication. Except for the limited purpose of indicating that 396 | material is shared under a Creative Commons public license or as 397 | otherwise permitted by the Creative Commons policies published at 398 | creativecommons.org/policies, Creative Commons does not authorize the 399 | use of the trademark "Creative Commons" or any other trademark or logo 400 | of Creative Commons without its prior written consent including, 401 | without limitation, in connection with any unauthorized modifications 402 | to any of its public licenses or any other arrangements, 403 | understandings, or agreements concerning use of licensed material. For 404 | the avoidance of doubt, this paragraph does not form part of the 405 | public licenses. 406 | 407 | Creative Commons may be contacted at creativecommons.org. 408 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | Code-Capybara 3 |

4 | 5 | 6 | # CodeCapybara: Open Source LLaMA Model that Follow Instruction-Tuning for Code Generation. 7 | [![Code License](https://img.shields.io/badge/Code%20License-Apache_2.0-green.svg)](https://github.com/AI4Code-Research/CodeCapybara/blob/main/LICENSE) 8 | [![Data License](https://img.shields.io/badge/Data%20License-CC%20By%20NC%204.0-red.svg)](https://github.com/AI4Code-Research/CodeCapybara/blob/main/DATA_LICENSE) 9 | [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/release/python-390/) 10 | [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) 11 | 12 | We introduce CodeCapybara - A Code specialized Instruction-following Large Language Model. This repo also attempts to evaluate and reproduce performance results of existing LLMs for code, such as Llama, Alpaca and CodeAlpaca for code generation benchmarks (HumanEval and MBPP). 13 | 14 | - ***First attempt to reproduce of LLaMA results*** on widely recognized Code Generation benchmarks 15 | - CodeCapybara is fine-tuned from Llama 7B. Larger models will be available soon. You can find our checkpoints at [this](#instruction-tuning). 16 | - We use ***our own dataset in larger scale and more diverse*** to fine-tune Llama under an instruction-tuning style. 17 | - ***Improved evaluation results on HumanEval*** in comparison to LLaMA, Alpaca and CodeAlpaca. 18 | - Full transparency with open source availability: ***all scripts and models are accessible to the community***. 19 | We encourage you to contribute to CodeCapybara and help advance the field of code generation. 20 | 21 | ## Table of Contents 22 | 23 | - [CodeCapybara: Open Source LLaMA Model that Follow Instruction-Tuning for Code Generation.](#codecapybara-open-source-llama-model-that-follow-instruction-tuning-for-code-generation) 24 | - [Table of Contents](#table-of-contents) 25 | - [Overview](#overview) 26 | - [Data Collection](#data-collection) 27 | - [Only Instruction Generation](#only-instruction-generation) 28 | - [Code Alpaca](#code-alpaca) 29 | - [DeepMind's Code Contests](#deepminds-code-contests) 30 | - [Instruction Tuning](#instruction-tuning) 31 | - [Results](#results) 32 | - [HumanEval Results](#humaneval-results) 33 | - [MBPP Results](#mbpp-results) 34 | - [Data Release](#data-release) 35 | - [Checkpoint Release](#checkpoint-release) 36 | - [Installation](#installation) 37 | - [Usage](#usage) 38 | - [Loading model](#loading-model) 39 | - [Loading CodeCapybara](#loading-codecapybara) 40 | - [Loading CodeCapybara-LoRA](#loading-codecapybara-lora) 41 | - [Generate](#generate) 42 | - [Instruction Tuning](#instruction-tuning-1) 43 | - [Benchmarking](#benchmarking) 44 | - [HumanEval](#humaneval) 45 | - [MBPP](#mbpp) 46 | - [Reproducing LLaMA Results](#reproducing-llama-results) 47 | - [Example Outputs](#example-outputs) 48 | - [Future Plans](#future-plans) 49 | - [Contributing](#contributing) 50 | - [License](#license) 51 | 52 | ## Overview 53 | We follow several recent techniques of instruction tuning to collect data and train an instruction-following model with ability to generate executable code from human language description. 54 | 55 | We can divide our process for training CodeyCapybara into two stages: 56 | 1. **Data Collection**: We collect data generated through OpenAI `gpt-3.5-turbo` as well as code generation supervised dataset. 57 | 2. **Instruction Tuning**: We fine-tune our model from MetaAI's LLaMA checkpoint with parameter-efficient fine-tuning methods. 58 | 59 | ### Data Collection 60 | In this stage, we follow previous works to collect instruction data. To ensure the quality of the code data used in the fine-tuning stage, we make some modifications from data Self-Instruct data generation procedure. 61 | 67 | 68 | #### Only Instruction Generation 69 | To ensure the code quality for later use as targets in the fine-tuning step, we leverage an unsupervised dataset that only contains code snippets crawled from open-sources. We then design a prompt to ask `gpt-3.5-turbo` to generate a corresponding instruction for each code snippet. In other words, to obtain a pair (instruction-output), we ask `gpt-3.5-turbo` to generate the instruction given the output as human written code snippet. 70 | 71 | Our unsupervised dataset contains code functions that covers a wide range of programming problem in 10 programming languages, i.e `Python, Javascript, Java, Golang, Ruby, Rust, PHP, C, C++, C#` 72 | 73 | We obtain our dataset through `gpt-3.5-turbo` OpenAI API. Each instruction-output pair is generated through 2 rounds of API calling. 74 | - In 1st round, we include a code function (i.e output) in the prompt, and ask `gpt-3.5-turbo` to generate a corresponding instruction. 75 | - In 2nd round, since the code function does not guarantee an executable program, we include both 1st round generated instruction and code function to a new prompt and ask the model to generate an executable program with libraries imported and dependencies implementation along with the given code function. 76 | 77 | - Our prompt template can be found [here](./data/prompts/prompt.py). 78 | - Our script for 2 rounds of data generation can be found [here](./data_generation/data_generation.py). 79 | 80 | #### [Code Alpaca](https://github.com/sahil280114/codealpaca) 81 | For the second source of data, our intention is to follow [Self-Instruct](https://arxiv.org/abs/2212.10560) paper to completely generate various code problems in the format of (Instruction-Input-Output) data from a seed dataset. 82 | 83 | We reuse the generated instruction data from [Code Alpaca](https://github.com/sahil280114/codealpaca/blob/master/data/code_alpaca_20k.json) to reduce API calling cost since what they did is similar to our purpose. 84 | 85 | #### [DeepMind's Code Contests](https://github.com/deepmind/code_contests) 86 | We also leverage the supervised code generation dataset. There are various code generation dataset with high quality and quantity, such as APPS (5,000 problems in train split), MBPP (500 problems in train split). 87 | 88 | In this version, we select [DeepMind's Code Contests](https://github.com/deepmind/code_contests) dataset, which contains competitive programming problems with detailed description and test cases. The train split we employ to fine-tune our model contains 13,328 problems which results in 51,766 instruction-output pairs. 89 | 90 | ### Instruction Tuning 91 | We tried 2 approaches to fine-tune LLaMA-7B checkpoint on the collected data, including: 92 | - Full-parameter Fine-tuning 93 | - Parameter-efficient Fine-tuning with HuggingFace's PEFT 94 | 95 | Please refer to [Checkpoint Release](#checkpoint-release) section for accessing to our checkpoints. 96 | 97 | ## Results 98 | 99 | We evaluate our models as well as reproduce other models' results on 2 benchmarks, HumanEval and MBPP. All numbers are reported in zero-shot settings. 100 | 101 | ### HumanEval Results 102 | | Model |Base checkpoint | pass@1 | pass@10 | pass@100 | 103 | | - | - | - | - | - | 104 | | LLaMA | decapoda-research/llama-7b-hf | 10.70| 13.29 | **13.41** | 105 | | LLaMA | huggyllama/llama-7b |9.7 | 12.66| 12.80 | 106 | | Alpaca-LoRA | decapoda-research/llama-7b-hf | 8.00 | 10.00 | 10.37| 107 | | CodeCapybara-LoRA | decapoda-research/llama-7b-hf | 9.61 | 11.62 | 12.02 | 108 | | CodeCapybara | huggyllama/llama-7b | **11.10** | **13.33** | **13.41** | 109 | 110 | ### MBPP Results 111 | 112 | ## Data Release 113 | We release our data as well as other data sources used for training our models 114 | - [Our Instruction Only Generation data](./data/raw-data/generated_data.jsonl) 115 | - [Code Apaca data](https://github.com/sahil280114/codealpaca/blob/master/data/code_alpaca_20k.json) 116 | - [Deepmind's CodeContests](https://huggingface.co/datasets/deepmind/code_contests) hosted on HuggingFace 117 | 118 | 119 | ## Checkpoint Release 120 | We release our checkpoints hosted on HuggingFace 121 | - [CodeCapybara](https://huggingface.co/Fsoft-AIC/CodeCapybara) - Full-parameter Fine-tuning 122 | - [CodeCapypara-LoRA](https://huggingface.co/Fsoft-AIC/CodeCapybara-LoRA) - Parameter-efficient Fine-tuning 123 | 124 | ## Installation 125 | 126 | ```bash 127 | conda create -n codecapybara -y 128 | conda activate codecapybara 129 | conda install pip -y 130 | pip install -r requirements.txt 131 | ``` 132 | 133 | ## Usage 134 | Let's define a function to convert `instruction` and `input` into a single prompt as input to our `model.generate` 135 | ```python 136 | def generate_prompt(instruction, input=None): 137 | # Templates used by Stanford Alpaca: https://github.com/tatsu-lab/stanford_alpaca 138 | if input is not None: 139 | prompt = f"Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.\n\n### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:" 140 | else: 141 | prompt = f"prompt_no_input": "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\n{instruction}\n\n### Response:" 142 | return prompt 143 | ``` 144 | 145 | ### Loading model 146 | You can choose to load full-parameter `CodeCapybara` or `CodeCapybara-LoRA` 147 | #### Loading CodeCapybara 148 | 149 | ```python 150 | import sys 151 | import torch 152 | from transformers import LlamaTokenizer, LlamaForCausalLM 153 | 154 | tokenizer = LlamaTokenizer.from_pretrained("Fsoft-AIC/CodeCapybara") 155 | model = LlamaForCausalLM.from_pretrain("Fsoft-AIC/CodeCapybara", 156 | load_in_8bit=True, 157 | dtype=torch.float16, 158 | device_map="auto") 159 | 160 | model.config.pad_token_id = tokenizer.pad_token_id = 0 161 | model.config.bos_token_id = 1 162 | model.config.eos_token_id = 2 163 | 164 | model.eval() 165 | if torch.__version__ >= "2" and sys.platform != "win32": 166 | model = torch.compile(model) 167 | ``` 168 | 169 | #### Loading CodeCapybara-LoRA 170 | 171 | ```python 172 | import sys 173 | import torch 174 | from transformers import LlamaTokenizer, LlamaForCausalLM 175 | from peft import PeftModel 176 | 177 | tokenizer = LlamaTokenizer.from_pretrained("decapoda-research/llama-7b-hf") 178 | model = LlamaForCausalLM.from_pretrained("decapoda-research/llama-7b-hf", 179 | load_in_8bit=True, 180 | dtype=torch.float16, 181 | device_map="auto") 182 | model = PeftModel.from_pretrained("Fsoft-AIC/CodeCapybara-LoRA", 183 | load_in_8bit=True, 184 | dtype=torch.float16, 185 | device_map="auto") 186 | 187 | model.config.pad_token_id = tokenizer.pad_token_id = 0 188 | model.config.bos_token_id = 1 189 | model.config.eos_token_id = 2 190 | 191 | model.eval() 192 | if torch.__version__ >= "2" and sys.platform != "win32": 193 | model = torch.compile(model) 194 | ``` 195 | ### Generate 196 | After loading model to your device, add the following script to generate prediction 197 | ```python 198 | instruction = "Write a Python program that prints the first 10 Fibonacci numbers" 199 | prompt = generate_prompt(instruction) 200 | 201 | input_ids = tokenizer(prompt)["input_ids"] 202 | 203 | generation_config = GenerationConfig(temperature=0.1, 204 | top_k=40, 205 | top_p=0.75) 206 | with torch.no_grad(): 207 | output_ids = model.generate(inputs, 208 | generation_config=generation_config, 209 | max_new_tokens=128) 210 | output = tokenizer.decode(output_ids, skip_special_tokens=True, ignore_tokenization_space=True) 211 | print(output) 212 | ``` 213 | ## Instruction Tuning 214 | We support 2 settings to fine-tune LLaMA models. In the first setting, we refine all the parameters using Fully Sharded Data Parallel, and for the rest, we currently utilize LoRA to adapt the models to the instruction tuning task. You can easily run such settings by the command 215 | ```bash 216 | bash scripts/train.sh 217 | ``` 218 | 219 | which calls `main/train.py`. We also provide some arguments to customize the training process 220 | - --train-batch-size: batch-size of each gpu for training 221 | - --val-batch-size: batch-size of each gpu for validating 222 | - --num-workers: number of workers in the DataLoader 223 | - --config-path: the path of the configuration file. We provide a template in the folder `configs` 224 | - --model-type: setting's used to fine-tune. There are 2 valid values: `fine-tunning` and `lora`. 225 | - --use-wandb: 0 if you don't use *wandb* for logging; otherwise, wandb is used. 226 | Moreover, you can edit the configuration file `configs/config.yml` which contains some notable fields: 227 | - checkpoint 228 | - dir: the folder contains all the checkpoints 229 | - old_checkpoint: the path of the old checkpoint. If it is null, the model'll train from scratch; otherwise, it continues training from this checkpoint. 230 | - epochs: the number of epochs between 2 consecutive model saves. 231 | - epochs: number of epochs for training 232 | - model: 233 | - hf_model: LLaMA model in HuggingFace format 234 | - lora: settings for LoRA method 235 | - optimizer: specify optimizer 236 | - scheduler: configurate the hypermeters for a warm-up learning-rate schedule 237 | - max-seq-length: maximum length of the instruction and the response. 238 | 239 | ## Benchmarking 240 | To evaluate checkpoints on HumanEval or MBPP benchmark, navigate to `main/` 241 | ```bash 242 | cd main/ 243 | ``` 244 | 245 | We use nucleus sampling for sampling next-token in each prediction step to generate multiple difference code outputs for each problem. Hyperparameter configuration used for our evaluation is specified in the command below. 246 | 247 | ### HumanEval 248 | The first part of the below command generates multiple `.jsonl` files, which will be saved into `path/to/prediction/directory` by inference the model. The command follows after taking predictions as input to calculate pass@k. 249 | ```bash 250 | # model inference 251 | export CUDA_VISIBLE_DEVICES=0,1 252 | N_PROCS=$(echo $CUDA_VISIBLE_DEVICES | tr "," "\n" | wc -l) 253 | NUM_ITERATIONS=10 254 | 255 | for _ in $(seq $NUM_ITERATIONS); 256 | do 257 | python -m torch.distributed.run --nprocs ${N_PROCS} generate.py \ 258 | --output_dir path/to/prediction/directory \ 259 | --dataset_name 'humaneval' \ 260 | --base_model 'Fsoft-AIC/CodeCapybara' \ 261 | --lora_weights '' \ 262 | --batch_size 1 \ 263 | --num_return_sequences 20 \ 264 | --load_8bit True \ 265 | --temperature 0.1 \ 266 | --top_p 0.75 \ 267 | --top_k 40 268 | done 269 | 270 | # Calculating pass@k with k=1,10,100 271 | python eval_humaneval.py --prediction_dir path/to/prediction/directory 272 | ``` 273 | 274 | `n = NUM_ITERATIONS * batch_size * num_return_sequences`, where `n` is used to estimate `pass@k` as in the [Codex](https://arxiv.org/pdf/2107.03374.pdf) paper. 275 | 276 | $${pass@k} = \underset{\text { Problems }}{\mathbb{E}}\left[1-\frac{C^{k}_{n-c}}{C^{k}_{n}}\right]$$ 277 | 278 | Here we choose `n = 200` as employed in the paper, which results in 279 | - `NUM_ITERATIONS=10` 280 | - `batch_size=1` 281 | - `num_return_sequences=20` 282 | 283 | ### MBPP 284 | Replacing the `humaneval` by `mbpp` 285 | ```bash 286 | # model inference 287 | export CUDA_VISIBLE_DEVICES=0,1 288 | N_PROCS=$(echo $CUDA_VISIBLE_DEVICES | tr "," "\n" | wc -l) 289 | NUM_ITERATIONS=10 290 | 291 | for _ in $(seq $NUM_ITERATIONS); 292 | do 293 | python -m torch.distributed.run --nprocs ${N_PROCS} generate.py \ 294 | --output_dir path/to/prediction/directory \ 295 | --dataset_name 'mbpp' \ 296 | --base_model 'Fsoft-AIC/CodeCapybara' \ 297 | --lora_weights '' \ 298 | --batch_size 1 \ 299 | --num_return_sequences 20 \ 300 | --load_8bit True \ 301 | --temperature 0.1 \ 302 | --top_p 0.75 \ 303 | --top_k 40 304 | done 305 | 306 | # Calculating pass@k with k=1,10,80,100 307 | python eval_mbpp.py --prediction_dir path/to/prediction/directory 308 | ``` 309 | 310 | ## Reproducing LLaMA Results 311 | Since MetaAI released their official LLaMA checkpoints, there have been questions and efforts on reproducing their results on HumanEval and MBPP reported in [paper](https://arxiv.org/pdf/2302.13971.pdf). This repo wishes to reproduce LLaMA and other LLMs results on widely recognized Code Generation benchmarks. 312 | 313 | To evaluate a HuggingFace LLaMA checkpoint on HumanEval or MBPP,  please pass the values of `--base_model` and `--dataset_name` the corresponding model and benchmark in the [evaluation script example](#humaneval). 314 | 315 | You can also tweak hyperparameters i.e  `temperature`, `top-p`, `top-k` for trade-off between accuracy and diversity and in prediction. Tuning hyperparameters will lead to change in final results. Community is welcome for seeking optimal hyperparameter values. 316 | 317 | We are in our progress of evaluating LLaMA official checkpoints without HuggingFace format checkpoint conversion. 318 | 319 | ## Example Outputs 320 | 321 | ## Future Plans 322 | 323 | ## Contributing 324 | 325 | ## License 326 | 327 | Feel free to cite us 328 | ```bibtex 329 | @misc{codecapybara, 330 | title = {CodeCapybara: Code Instruction Tuning}, 331 | author = {}, 332 | year = {2023}, 333 | } 334 | ``` 335 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FSoft-AI4Code/CodeCapybara/9bc7ab4305444cca625ceed7b1aaca987a193bec/__init__.py -------------------------------------------------------------------------------- /assets/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FSoft-AI4Code/CodeCapybara/9bc7ab4305444cca625ceed7b1aaca987a193bec/assets/.DS_Store -------------------------------------------------------------------------------- /assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FSoft-AI4Code/CodeCapybara/9bc7ab4305444cca625ceed7b1aaca987a193bec/assets/logo.png -------------------------------------------------------------------------------- /configs/config.yml: -------------------------------------------------------------------------------- 1 | checkpoint: 2 | dir: checkpoints/llama-tuning/ 3 | old_checkpoint: 4 | epochs: 1 5 | clip_gradient: null 6 | datasets: 7 | - code-contest: 8 | - codealpaca: data/raw-data/code_alpaca_20k.json 9 | - codecapybara: data/raw-data/generated_data.jsonl 10 | early_stopping: 11 | patience: 20 12 | epochs: 5 13 | model: 14 | hf_model: huggyllama/llama-7b 15 | lora: 16 | r: 8 17 | alpha: 16 18 | dropout: 0.5 19 | target_modules: 20 | - q_proj 21 | - v_proj 22 | log: 23 | dir: logs 24 | file: log 25 | optimizer: 26 | name: AdamW 27 | params: 28 | lr: 2.0e-5 29 | scheduler: 30 | num_warmup_steps: 1000 31 | num_training_epochs: 5 32 | wandb: 33 | project: LLaMA-all-data 34 | name: fine-tune 35 | max_seq_length: 1000 -------------------------------------------------------------------------------- /data/dataset/__init__.py: -------------------------------------------------------------------------------- 1 | from .capybara import CapybaraDataset -------------------------------------------------------------------------------- /data/dataset/capybara.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import json 3 | import jsonlines 4 | import torch 5 | from torch.utils.data import Dataset 6 | 7 | from data.utils.pad import pad_batch_2D 8 | from data.utils.mask import get_subsequent_mask 9 | from data.prompts import code_contests_prompts, codealpaca_prompts 10 | 11 | import random 12 | 13 | 14 | class CapybaraDataset(Dataset): 15 | def __init__(self, data, tokenizer, max_seq_length = 600): 16 | self.data = data 17 | self.tokenizer = tokenizer 18 | self.max_seq_length = max_seq_length 19 | def __len__(self): 20 | return 16#len(self.data) 21 | def __getitem__(self, index): 22 | item = self.data[index] 23 | dataset_name = item['dataset'] 24 | 25 | if dataset_name == 'code-contest': 26 | lang = item['language'] 27 | instruction = item['description'] 28 | output = item['solution'] 29 | prompt = random.choice(code_contests_prompts) 30 | if prompt.startswith('{'): 31 | full_input = instruction 32 | else: 33 | full_input = prompt.format(language = lang, problem_description = instruction) 34 | full_input = full_input + ' Output: ' 35 | elif dataset_name == 'codealpaca': 36 | instruction = item['instruction'] 37 | input = item['input'] 38 | output = item['output'] 39 | if len(input) > 0: 40 | full_input = codealpaca_prompts['prompt_input'].format(instruction = instruction, input = input) 41 | else: 42 | full_input = codealpaca_prompts['prompt_no_input'].format(instruction = instruction) 43 | elif dataset_name == 'codecapybara': 44 | full_input = item['instruction'] + ' Output: ' 45 | output = item['gen_code'] 46 | elif dataset_name == 'mbpp': 47 | full_input = item['text'] 48 | output = item['code'] 49 | 50 | 51 | prompts = self.tokenizer.encode(full_input) 52 | targets = self.tokenizer.encode(output)[1:self.max_seq_length - len(prompts)] 53 | input_ids = prompts + targets 54 | output_ids = [-100] * (len(prompts) - 1) + targets + [self.tokenizer.eos_token_id] 55 | return input_ids, output_ids 56 | def collate(self, batch): 57 | input_ids, output_ids = list(zip(*batch)) 58 | pad_input_ids = pad_batch_2D(input_ids, value = self.tokenizer.pad_token_id) 59 | pad_output_ids = pad_batch_2D(output_ids, value = -100) 60 | pad_input_ids = torch.tensor(pad_input_ids) 61 | pad_output_ids = torch.tensor(pad_output_ids) 62 | mask = pad_input_ids.ne(self.tokenizer.pad_token_id) 63 | return pad_input_ids, pad_output_ids, mask 64 | -------------------------------------------------------------------------------- /data/loaders/__init__.py: -------------------------------------------------------------------------------- 1 | from .load_code_contests import get_code_contests 2 | from .load_code_capybara import get_code_capybara 3 | from .load_code_alpaca import get_code_alpaca -------------------------------------------------------------------------------- /data/loaders/load_code_alpaca.py: -------------------------------------------------------------------------------- 1 | import json 2 | def get_code_alpaca(path, tokenizer, max_length): 3 | with open(path) as f: 4 | data = json.load(f) 5 | filtered_data = [] 6 | for line in data: 7 | if len(tokenizer.encode(line['instruction'])) > max_length: continue 8 | line['dataset'] = 'codealpaca' 9 | filtered_data.append(line) 10 | return filtered_data 11 | -------------------------------------------------------------------------------- /data/loaders/load_code_capybara.py: -------------------------------------------------------------------------------- 1 | import jsonlines 2 | def get_code_capybara(path, tokenizer, max_length): 3 | data = [] 4 | with jsonlines.open(path) as f: 5 | for line in f: 6 | if 'gen_code' not in line: continue 7 | if len(tokenizer.encode(line['instruction'])) > max_length: continue 8 | line['dataset'] = 'codecapybara' 9 | data.append(line) 10 | return data 11 | -------------------------------------------------------------------------------- /data/loaders/load_code_contests.py: -------------------------------------------------------------------------------- 1 | import datasets 2 | 3 | def get_code_contests(tokenizer, max_seq_length): 4 | language_map = {1: "python2", 2: "C++", 3: "python3", 4: "java"} 5 | dataset_name = "deepmind/code_contests" 6 | dataset = datasets.load_dataset(dataset_name) 7 | train_dataset = dataset["train"] 8 | data = [] 9 | for example in train_dataset: 10 | desc = example['description'] 11 | desc_tokens = tokenizer.tokenize(desc) 12 | if len(desc_tokens) > max_seq_length: continue 13 | solutions = example['solutions'] 14 | languages = set() 15 | for language, solution in zip(solutions["language"], solutions["solution"]): 16 | _example = dict(description=desc) 17 | if language in languages or language == 0: 18 | continue 19 | languages.add(language) 20 | # full_seq = desc + ' Output: ' + solution 21 | # if len(full_seq) > max_seq_length: continue 22 | 23 | _example["language"] = language_map[language] 24 | _example["solution"] = solution 25 | 26 | _example['dataset'] = 'code-contest' 27 | data.append(_example) 28 | return data 29 | -------------------------------------------------------------------------------- /data/prompts/__init__.py: -------------------------------------------------------------------------------- 1 | from .prompt import * -------------------------------------------------------------------------------- /data/prompts/prompt.py: -------------------------------------------------------------------------------- 1 | first_PROMPT = { 2 | "template": """ 3 | I have {num_code_snippets} code snippets. You are a software programming teacher and you want to have assignment problems for your students to implement with the code snippets as solutions, how would you generate such assignment questions given the snippets. 4 | 5 | Here are the requirements: 6 | {requirements} 7 | 8 | List of {num_code_snippets} code snippets: 9 | 10 | """, 11 | "requirements": { 12 | "r1": "The problem statements should clearly state the problem that the code is intended to solve, and the expected behavior of the code.", 13 | "repeat_words": "Try not to repeat the verb for each assignment statement to maximize diversity.", 14 | "diversity": "The language used for the assignment statement also should be diverse. For example, you should combine questions with imperative problem statements.", 15 | "gpt" :"A GPT language model should be able to complete the problem statements. For example, do not ask the assistant to create any visual or audio output. For another example, do not ask the assistant to wake you up at 5pm or set a reminder because it cannot perform any action. ", 16 | "english" :"The problem statements should be in English and not include code. ", 17 | "manner" :"The problem statements should be written in a clear and concise manner, with proper grammar and punctuation.", 18 | "length": "The problem statements should be concise, ideally at least {min_length} words and at most {max_length} words. ", 19 | "natural_language_reflection": "The problem statements must correctly reflect the corresponding code in natural language. ", 20 | "code_related" :"All tasks should be coding or programming related.", 21 | "terminology": "Use the appropriate terminology corresponding to each language in the problem statement. For example, List in Python corresponds to vector in C++, dictionary in python corresponds to hash in Perl. ", 22 | "programming_language": "The problem statements must mention the programming language of the code.", 23 | "input_output": "The problem statements may include input and output descriptions or not. ", 24 | }, 25 | "optional_requirements": ["input_output", "length"] 26 | } 27 | 28 | second_PROMPT = { 29 | "template": """ 30 | I have a pair of a code problem assignments and its solution. However, the solution is not able to run because it lacks libraries that need to be imported as well as other dependency functions appeared within the solution. Write a full script containing all libraries and the dependency implementation that are required to run the solution code. 31 | 32 | Here are the mandatory requirements: 33 | {requirements} 34 | - Problem: 35 | {instruction} 36 | - Solution: 37 | {code} 38 | 39 | Here is the implementation: 40 | """, 41 | "requirements": { 42 | "r1": "The script should not contain the main function and testing code.", 43 | "r2": "Your answer should not include any sample usage and code comment.", 44 | "r3": "Only dependencies necessitated in the solution should be implemented.", 45 | "r4": "Your answer only contains libraries and dependencies implementation.", 46 | "r5": "Your answer should have a unique script.", 47 | "r6": "New functions and code elements in your answer should not be empty.", 48 | "r7": "Your answer do not include any explanation and note.", 49 | # "r1": "The script should not contain the main function.", 50 | # "r2": "Only dependencies appeared in the solution should be implemented.", 51 | # "r3": "Your answer only contains libraries and dependencies implementation, not the solution.", 52 | # "r4": "The solution should not be mentioned in your answer.", 53 | # "r5": "Your answer must only contain the code without any explaination.", 54 | } 55 | } 56 | 57 | code_contests_prompts = [ 58 | '{problem_description}' 59 | 'Give me the {language} code solution for this problem.\n{problem_description}', 60 | 'Solve this problem in {language}.\n{problem_description}', 61 | 'Can you provide a {language} implementation for this algorithmic challenge? \n{problem_description}', 62 | 'Demonstrate a {language} solution for this code problem.\n{problem_description}', 63 | 'I need a {language} program to solve this competitive programming challenge.\n{problem_description}', 64 | 'Plea se write a {language} code to solve this algorithmic problem.\n{problem_description}', 65 | 'Show me how to solve this code challenge in {language}.\n{problem_description}', 66 | 'Python implementation needed for this competitive programming problem.\n{problem_description}', 67 | 'Can you code a solution in {language} for this problem?\n{problem_description}', 68 | 'I require a {language} script to solve this algorithmic task.\n{problem_description}', 69 | 'Please present a {language} solution for this code problem.\n{problem_description}', 70 | 'Python code for this competitive programming challenge please.\n{problem_description}', 71 | 'Could you show me a {language} impl ementation for this programming challenge?\n{problem_description}', 72 | "I'm looking for a {language} program to solve this coding challenge.\n{problem_description}", 73 | 'Can you help me with a {language} solution for this algorithm?\n{problem_description}', 74 | 'Please code a {language} solution for this problem.\n{problem_description}', 75 | 'I need a {language} implementation for this code problem.\n{problem_description}', 76 | 'Provide me with a {language} code for this competitive programming problem.\n{problem_description}', 77 | 'Solve this algorithmic problem using {language}.\n{problem_description}', 78 | "I'm seeking a {language} script to solve this code challeng e.\n{problem_description}", 79 | 'Please write a {language} program to solve this competitive programming challenge.\n{problem_description}', 80 | 'Could you show me a {language} solution for this code problem?\n{problem_description}', 81 | 'I need a {language} implementation for this algorithmic task.\n{problem_description}', 82 | "I'm looking for a {language} code to solve this competitive programming challenge.\n{problem_description}", 83 | 'Can you present a {language} program to solve this algorithmic problem?\n{problem_description}', 84 | 'Python implementation required for this code problem.\n{problem_description}', 85 | 'Solve this programming challenge using py thon.\n{problem_description}', 86 | 'Can you code a {language} solution for this competitive programming challenge?\n{problem_description}', 87 | 'I require a {language} implementation to solve this algorithmic challenge.\n{problem_description}', 88 | 'Provide me with a {language} code to solve this coding problem.\n{problem_description}', 89 | 'Please write a {language} script to solve this programming challenge.\n{problem_description}', 90 | 'Python solution needed for this code problem.\n{problem_description}', 91 | 'Can you help me solve this competitive programming problem with a {language} implementation?\n{problem_description}', 92 | "I'm seeking a {language} program to solve this algorithmic challenge.\n{problem_description}", 93 | 'Solve this code problem using {language} language.\n{problem_description}', 94 | 'Please present a {language} implementation for this programming challenge.\n{problem_description}', 95 | 'Could you show me how to solve this competitive programming challenge in {language}?\n{problem_description}', 96 | 'I need a {language} code to solve this algorithmic task. \n{problem_description}', 97 | 'Python solution required for this code problem.\n{problem_description}', 98 | 'Can you code a {language} implementation for this programming challenge?\n{problem_description}', 99 | "I'm looking for a {language} program t o solve this coding problem.\n{problem_description}", 100 | 'Provide me with a {language} solution for this algorithmic challenge.\n{problem_description}', 101 | 'Please write a {language} code to solve this competitive programming problem.\n{problem_description}', 102 | 'Python implementation needed to solve this code problem.\n{problem_description}', 103 | 'Can you help me solve this programming challenge with a {language} implementation?\n{problem_description}', 104 | 'I require a {language} program to solve this competitive programming challenge.\n{problem_description}', 105 | 'Please show me a {language} solution for this algorithmic task.\n{problem_description}'] 106 | 107 | 108 | codealpaca_prompts = { 109 | "prompt_input": ( 110 | "Below is an instruction that describes a task, paired with an input that provides further context. " 111 | "Write a response that appropriately completes the request.\n\n" 112 | "### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Output:" 113 | ), 114 | "prompt_no_input": ( 115 | "Below is an instruction that describes a task. " 116 | "Write a response that appropriately completes the request.\n\n" 117 | "### Instruction:\n{instruction}\n\n### Output:" 118 | ), 119 | } -------------------------------------------------------------------------------- /data/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FSoft-AI4Code/CodeCapybara/9bc7ab4305444cca625ceed7b1aaca987a193bec/data/utils/__init__.py -------------------------------------------------------------------------------- /data/utils/mask.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | def get_subsequent_mask(max_seq_len): 4 | mask = torch.full((max_seq_len, max_seq_len), float('-inf')) 5 | mask = torch.triu(mask, diagonal = 1) 6 | return mask -------------------------------------------------------------------------------- /data/utils/pad.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def pad_batch_2D(batch, value = 0): 4 | max_batch = max([len(x) for x in batch]) 5 | batch = [n + [value] * (max_batch - len(n)) for n in batch] 6 | batch = np.asarray(batch) 7 | return batch -------------------------------------------------------------------------------- /data_generation/call.sh: -------------------------------------------------------------------------------- 1 | python data_generation.py \ 2 | --seed_data_dir ./seed_data \ 3 | --request_batch_size 500 \ 4 | --num_instructions_to_generate 100 \ 5 | --num_examples_per_language 100 6 | -------------------------------------------------------------------------------- /data_generation/data_generation.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import string 4 | import json 5 | import time 6 | from datetime import datetime 7 | import random 8 | from functools import partial 9 | random.seed(42) 10 | from tqdm import tqdm 11 | from collections import OrderedDict 12 | # import concurrent.futures 13 | import multiprocessing 14 | import logging 15 | from typing import List, Optional, Sequence, Union 16 | from argparse import ArgumentParser 17 | import multiprocessing 18 | import functools 19 | import openai 20 | from openai import openai_object 21 | 22 | from data.prompts.prompt import first_PROMPT, second_PROMPT 23 | from tokenizer import num_tokens_from_messages 24 | 25 | openai_org = os.getenv("OPENAI_ORG") 26 | if openai_org is not None: 27 | openai.organization = openai_org 28 | logging.warning(f"Switching to organization: {openai_org} for OPENAI API key.") 29 | openai.api_key = os.getenv("OPENAI_KEY") 30 | 31 | MIN_INS_LEN = 3 32 | MAX_INS_LEN = 1e6 33 | NUM_PROMPT_CODE_SNIPPETS = 3 34 | CODE_LENGTH_THRESHOLD = 4000 35 | 36 | def encode_prompt(code_snippets, instructions, mode): 37 | assert mode in ["1st", "2nd"] 38 | assert len(instructions) <= len(code_snippets) 39 | if mode == "1st": 40 | num_code_snippets = len(code_snippets) 41 | template = first_PROMPT["template"] 42 | requirement_dict = first_PROMPT["requirements"] 43 | requirement_str = "" 44 | for idx, (k, requirement) in enumerate(requirement_dict.items()): 45 | if k == "input_output": 46 | if random.uniform(0, 1) < 0.5: 47 | continue 48 | elif k == "length": 49 | min_length = random.choice(range(0, 60, 10)) 50 | max_length = min_length + random.choice(range(30, 110, 10)) 51 | requirement = requirement.format(min_length=min_length,max_length=max_length) 52 | requirement_str += f"{idx + 1}. {requirement}\n" 53 | prompt = template.format(requirements=requirement_str.strip(), num_code_snippets=num_code_snippets) 54 | for idx, code_snippet in enumerate(code_snippets): 55 | code_snippet = code_snippet.strip() 56 | prompt += f"Code snippet {idx + 1}:\n" 57 | prompt += code_snippet 58 | prompt += "\n" 59 | prompt += f"\n\n###\nList of {num_code_snippets} corresponding problem statements:\n" 60 | 61 | idx = 0 62 | for idx, instruction in enumerate(instructions): 63 | prompt += f"Problem statement {idx + 1}:\n" 64 | prompt += instruction 65 | prompt += "\n" 66 | else: 67 | prompt += f"Problem statement {idx + 1}:" 68 | else: 69 | assert len(code_snippets) == 1 70 | assert len(instructions) == 1 71 | template = second_PROMPT["template"] 72 | requirement_dict = second_PROMPT["requirements"] 73 | requirement_str = "" 74 | for idx, (k, requirement) in enumerate(requirement_dict.items()): 75 | requirement_str += f"{idx + 1}. {requirement}\n" 76 | code_snippet = code_snippets[0] 77 | instruction = instructions[0] 78 | prompt = template.format(code=code_snippet.strip(), instruction=instruction.strip(), requirements=requirement_str.strip()) 79 | 80 | return prompt 81 | 82 | def load_data(data_dir, num_examples): 83 | languages = ["python", "go", "java", "javascript", "ruby", "php", "c", "cpp", "csharp", "rust"] 84 | data = dict() 85 | progress_bar = tqdm(total=8e6) 86 | idx = 0 87 | for language in languages: 88 | data_path = os.path.join(data_dir, language, "train.jsonl") 89 | if not os.path.exists(data_path): 90 | data_path = os.path.join(data_dir, language, "final", "extract_function_train.jsonl") 91 | with open(data_path, "r") as f: 92 | for j, ex in enumerate(f): 93 | ex = json.loads(ex) 94 | if j == num_examples: 95 | break 96 | example_id = ex.get("id", idx) 97 | data.update({example_id: { 98 | "code": ex["code"], 99 | "instruction": "", 100 | "language": language, 101 | }}) 102 | idx += 1 103 | progress_bar.update(1) 104 | 105 | return data 106 | 107 | def post_process_1st_response(response, example_ids): 108 | if response is None: 109 | return [] 110 | seperator = "Problem statement \d:" 111 | response_text = response["choices"][0]["message"]["content"] 112 | raw_instructions = re.split(seperator, response_text) 113 | raw_instructions.extend([""]*(len(example_ids) - len(raw_instructions))) 114 | result = dict() 115 | for idx, (inst, k) in enumerate(zip(raw_instructions, example_ids)): 116 | if idx == len(raw_instructions) - 1 and response["choices"][0]["finish_reason"] == "length": 117 | result.update({k: {"pass": False, "instruction": inst, "reason": "cutoff"}}) 118 | continue 119 | if len(inst.split()) <= MIN_INS_LEN or len(inst.split()) > MAX_INS_LEN: 120 | result.update({k: {"pass": False, "instruction": inst, "reason": "length"}}) 121 | continue 122 | # filter based on keywords that are not suitable for language models. 123 | blacklist = [ 124 | ] 125 | if any(find_word_in_string(word, inst) for word in blacklist): 126 | result.update({k: {"pass": False, "instruction": inst, "reason": "blacklist"}}) 127 | continue 128 | # filter those starting with punctuation 129 | if inst[0] in string.punctuation: 130 | result.update({k: {"pass": False, "instruction": inst, "reason": "punctuation"}}) 131 | continue 132 | # filter those starting with non-english character 133 | if not inst[0].isascii(): 134 | result.update({k: {"pass": False, "instruction": inst, "reason": "ascii"}}) 135 | continue 136 | result.update({k: {"pass": True, "instruction": inst, "reason": ""}}) 137 | return result 138 | 139 | 140 | def find_word_in_string(w, s): 141 | return re.compile(r"\b({0})\b".format(w), flags=re.IGNORECASE).search(s) 142 | 143 | 144 | def one_call(examples: OrderedDict[dict[str, str]], decoding_kwargs): 145 | sleep_time = 8 146 | num_requests = 0 147 | code_examples = [ex["code"] for ex in examples.values()] 148 | example_ids = [example_id for example_id in examples.keys()] 149 | example_instructions = [] 150 | prompt = encode_prompt(code_examples, example_instructions, mode="1st") 151 | messages = [ 152 | {"role": "system", "content": prompt} 153 | ] 154 | call_1st_responses, call_2nd_responses = [], [] 155 | decoding_kwargs["max_tokens"] = 4096 - 512 - num_tokens_from_messages(messages) 156 | if decoding_kwargs["max_tokens"] < 0: 157 | for ex in examples.values(): 158 | ex["instruction"] = "" 159 | ex["pass_1st"] = False 160 | ex["pass_2nd_reason"] = "exceed_max_tokens" 161 | 162 | ex["gen_code"] = "" 163 | ex["pass_2nd"] = False 164 | ex["pass_2nd_reason"] = "not_pass_1st" 165 | return examples, call_1st_responses, call_2nd_responses, num_requests 166 | # 1st round 167 | while True: 168 | try: 169 | response_1st = openai.ChatCompletion.create(messages=messages, 170 | **decoding_kwargs, 171 | # **shared_kwargs 172 | ) 173 | break 174 | except openai.error.OpenAIError as e: 175 | logging.warning(f"OpenAIError: {e}.") 176 | if "Please reduce your prompt" in str(e): 177 | max_tokens = decoding_kwargs.get("max_tokens", 2048) 178 | decoding_kwargs["max_tokens"]= int(max_tokens * 0.8) 179 | logging.warning(f"Reducing target length to {max_tokens}, Retrying...") 180 | else: 181 | logging.warning("Hit request rate limit; retrying...") 182 | time.sleep(sleep_time) # Annoying rate limit on requests. 183 | 184 | response_1st.update({"data_ids": example_ids}) 185 | call_1st_responses.append(response_1st) 186 | num_requests += 1 187 | 188 | result_1st = post_process_1st_response(response_1st, example_ids) 189 | for ex_id, result in result_1st.items(): 190 | examples[ex_id].update({ 191 | "pass_1st": result["pass"], 192 | "pass_1st_reason": result["reason"], 193 | "instruction": result["instruction"], 194 | }) 195 | 196 | # 2nd round 197 | for ex_id, ex in examples.items(): 198 | if not ex["pass_1st"]: 199 | ex["pass_2nd"] = False 200 | ex["pass_2nd_reason"] = "not_pass_1st" 201 | continue 202 | code = ex["code"] 203 | instruction = ex["instruction"] 204 | prompt = encode_prompt([code], [instruction], mode="2nd") 205 | messages = [ 206 | {"role": "system", "content": prompt} 207 | ] 208 | decoding_kwargs["max_tokens"] = 4096 - 512 - num_tokens_from_messages(messages) 209 | if decoding_kwargs["max_tokens"] < 0: 210 | ex["gen_code"] = "" 211 | ex["pass_2nd"] = False 212 | ex["pass_2nd"] = "exceed_max_tokens" 213 | continue 214 | while True: 215 | try: 216 | response_2nd = openai.ChatCompletion.create(messages=messages, 217 | **decoding_kwargs) 218 | break 219 | except openai.error.OpenAIError as e: 220 | logging.warning(f"OpenAIError: {e}.") 221 | if "Please reduce your prompt" in str(e): 222 | max_tokens = decoding_kwargs.get("max_tokens", 2048) 223 | decoding_kwargs["max_tokens"]= int(max_tokens * 0.8) 224 | logging.warning(f"Reducing target length to {max_tokens}, Retrying...") 225 | else: 226 | logging.warning("Hit request rate limit; retrying...") 227 | time.sleep(sleep_time) # Annoying rate limit on requests. 228 | num_requests += 1 229 | gen_code = response_2nd["choices"][0]["message"]["content"] 230 | response_2nd.update({"data_id": ex_id}) 231 | call_2nd_responses.append(response_2nd) 232 | ex["gen_code"] = gen_code 233 | if response_2nd["choices"][0]["finish_reason"] == "length": 234 | ex["pass_2nd"] = False 235 | ex["pass_2nd_reason"] = "cutoff" 236 | continue 237 | else: 238 | ex["pass_2nd"] = True 239 | ex["pass_2nd_reason"] = "" 240 | 241 | return examples, call_1st_responses, call_2nd_responses, num_requests 242 | 243 | def generate_instruction_following_data( 244 | data, 245 | request_batch_size=500, 246 | num_instructions_to_generate=100, 247 | output_dir="./output_dir", 248 | model_name="gpt-3.5-turbo", 249 | temperature=1.0, 250 | top_p=1.0, 251 | ): 252 | now = datetime.now() 253 | datetime_string = now.strftime("%Y-%m-%d %H:%M:%S") 254 | output_dir = os.path.join(output_dir, now.strftime("%Y-%m-%d_%H:%M:%S")) 255 | print("output_dir = {}".format(output_dir)) 256 | os.makedirs(output_dir, exist_ok=True) 257 | 258 | count_tokens = 0 259 | keep = 0 260 | num_generated_data = 0 261 | num_requests = 0 262 | 263 | passed_ids = [] 264 | if os.path.exists("./output_dir/passed_ids.txt"): 265 | with open("./output_dir/passed_ids.txt", "r") as f: 266 | passed_ids = f.read() 267 | passed_ids = passed_ids.strip().split(",") 268 | passed_ids = [int(i) for i in passed_ids] 269 | for example_id in passed_ids: 270 | if example_id in data: 271 | data.pop(example_id) 272 | 273 | progress_bar = tqdm(total=num_instructions_to_generate) 274 | 275 | decoding_kwargs = dict( 276 | model=model_name, 277 | temperature=temperature, 278 | n=1, 279 | top_p=top_p, 280 | ) 281 | 282 | idx = 0 283 | while keep < num_instructions_to_generate and len(data) > 0: 284 | num_requested_examples = min(request_batch_size * NUM_PROMPT_CODE_SNIPPETS, num_instructions_to_generate - keep) 285 | batch_examples_ids = random.sample(list(data.keys()), k=num_requested_examples) 286 | grouped_examples_ids = [batch_examples_ids[i:i+NUM_PROMPT_CODE_SNIPPETS] for i in range(0, num_requested_examples, NUM_PROMPT_CODE_SNIPPETS)] 287 | grouped_examples = [OrderedDict([(example_id, data[example_id]) for example_id in example_ids]) for example_ids in grouped_examples_ids] 288 | request_start = time.time() 289 | with multiprocessing.Pool() as p: 290 | for result in p.imap(partial(one_call, decoding_kwargs=decoding_kwargs), grouped_examples): 291 | examples, call_1st_responses, call_2nd_responses, _num_requests = result 292 | num_requests += _num_requests 293 | for ex_id, ex in examples.items(): 294 | if ex["pass_1st"] and ex["pass_2nd"]: 295 | keep += 1 296 | passed_ids.append(ex_id) 297 | progress_bar.update(1) 298 | num_generated_data += 1 299 | data.pop(ex_id) 300 | mode = "w" if idx == 0 else "a" 301 | with open(os.path.join(output_dir, "openai_1st_reponses.jsonl"), mode) as f: 302 | for response in call_1st_responses: 303 | json.dump(response, f) 304 | f.write("\n") 305 | with open(os.path.join(output_dir, "openai_2nd_reponses.jsonl"), mode) as f: 306 | for response in call_2nd_responses: 307 | json.dump(response, f) 308 | f.write("\n") 309 | with open(os.path.join(output_dir, "generated_data.jsonl"), mode) as f: 310 | for ex_id, example in examples.items(): 311 | example["id"] = ex_id 312 | json.dump(example, f) 313 | f.write("\n") 314 | idx += 1 315 | for response in call_1st_responses + call_2nd_responses: 316 | count_tokens += response["usage"]["total_tokens"] 317 | request_duration = time.time() - request_start 318 | print(f"Batch request tooks {request_duration:.2f}s") 319 | 320 | print(f"Generated {num_generated_data} instructions, kept {keep} instructions") 321 | with open(os.path.join(output_dir, "count_tokens.jsonl"), "a") as f: 322 | json.dump({"date": datetime_string, "count_tokens": count_tokens, "cost": count_tokens*1e-6}, f) 323 | with open("output_dir/passed_ids.txt", "w") as f: 324 | f.write(",".join([str(i) for i in passed_ids])) 325 | 326 | def parse_args(): 327 | parser = ArgumentParser() 328 | parser.add_argument("--seed_data_dir", type=str, default="./seed_data") 329 | parser.add_argument("--output_dir", type=str, default="./output_dir") 330 | parser.add_argument("--request_batch_size", type=int, default=500) 331 | parser.add_argument("--num_instructions_to_generate", type=int, default=1000) 332 | parser.add_argument("--num_examples_per_language", type=int, default=-1) 333 | 334 | return parser.parse_args() 335 | 336 | def main(): 337 | args = parse_args() 338 | print("Loading data ...") 339 | seed_data = load_data(args.seed_data_dir, args.num_examples_per_language) 340 | print("Finished loading data.") 341 | print("Starting generating data ...") 342 | generate_instruction_following_data(seed_data, 343 | request_batch_size=args.request_batch_size, 344 | num_instructions_to_generate=args.num_instructions_to_generate, 345 | output_dir=args.output_dir, 346 | ) 347 | print("Finished generating data ...") 348 | 349 | if __name__ == "__main__": 350 | main() 351 | -------------------------------------------------------------------------------- /data_generation/tokenizer.py: -------------------------------------------------------------------------------- 1 | import tiktoken 2 | 3 | def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0301"): 4 | """Returns the number of tokens used by a list of messages.""" 5 | try: 6 | encoding = tiktoken.encoding_for_model(model) 7 | except KeyError: 8 | encoding = tiktoken.get_encoding("cl100k_base") 9 | if model == "gpt-3.5-turbo-0301": # note: future models may deviate from this 10 | num_tokens = 0 11 | for message in messages: 12 | num_tokens += 4 # every message follows {role/name}\n{content}\n 13 | for key, value in message.items(): 14 | num_tokens += len(encoding.encode(value)) 15 | if key == "name": # if there's a name, the role is omitted 16 | num_tokens += -1 # role is always required and always 1 token 17 | num_tokens += 2 # every reply is primed with assistant 18 | return num_tokens 19 | else: 20 | raise NotImplementedError(f"""num_tokens_from_messages() is not presently implemented for model {model}. 21 | See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""") 22 | 23 | def main(): 24 | messages = [ 25 | {"role": "system", "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."}, 26 | {"role": "system", "name":"example_user", "content": "New synergies will help drive top-line growth."}, 27 | {"role": "system", "name": "example_assistant", "content": "Things working well together will increase revenue."}, 28 | {"role": "system", "name":"example_user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."}, 29 | {"role": "system", "name": "example_assistant", "content": "Let's talk later when we're less busy about how to do better."}, 30 | {"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."}, 31 | ] 32 | 33 | model = "gpt-3.5-turbo-0301" 34 | 35 | print(f"{num_tokens_from_messages(messages, model)} prompt tokens counted.") 36 | # Should show ~126 total_tokens 37 | -------------------------------------------------------------------------------- /deploy/run_hf.py: -------------------------------------------------------------------------------- 1 | from transformers import GenerationConfig, LlamaForCausalLM, LlamaTokenizer 2 | import gradio as gr 3 | import torch 4 | import fire 5 | 6 | if torch.cuda.is_available(): 7 | device = "cuda" 8 | else: 9 | device = "cpu" 10 | total_queries = 0 11 | def load_model(model_path: str, tokenizer_path: str, load_8bit: bool = False): 12 | tokenizer = LlamaTokenizer.from_pretrained(tokenizer_path) 13 | generator = LlamaForCausalLM.from_pretrained(model_path).to(device).eval() 14 | 15 | 16 | tokenizer.pad_token_id = generator.config.pad_token_id = 0 17 | tokenizer.bos_token_id = generator.config.bos_token_id = 1 18 | tokenizer.eos_token_id = generator.config.eos_token_id = 2 19 | return tokenizer, generator 20 | 21 | def main( 22 | model_path: str, 23 | tokenizer_path: str, 24 | load_8bit: bool = False 25 | ): 26 | global total_queries 27 | tokenizer, generator = load_model(model_path, tokenizer_path, load_8bit = load_8bit) 28 | 29 | def generate(input:str, model_name, temperature: float, top_p: float, top_k: int, max_new_tokens: int): 30 | global total_queries 31 | generation_config = GenerationConfig( 32 | temperature=temperature, 33 | top_p=top_p, 34 | top_k=top_k 35 | ) 36 | #print('input', input) 37 | 38 | input_ids = tokenizer.encode(input, return_tensors = 'pt').to(device) 39 | total_queries += 1 40 | print('NUM QUERY:', total_queries) 41 | #print(input_ids.shape, input_ids) 42 | with torch.inference_mode(): 43 | generation_output = generator.generate( 44 | input_ids = input_ids, 45 | generation_config = generation_config, 46 | max_new_tokens = max_new_tokens, 47 | top_k = top_k, 48 | top_p = top_p 49 | ) 50 | result = generation_output[0].tolist()[1:] 51 | try: 52 | result = result[: result.index(tokenizer.eos_token_id)] 53 | except: pass 54 | yield tokenizer.decode(result) 55 | 56 | 57 | 58 | gr.Interface( 59 | fn = generate, 60 | inputs=[ 61 | gr.components.Textbox( 62 | lines=2, 63 | label="Instruction", 64 | placeholder="Write an instruction...", 65 | ), 66 | gr.Radio(["Fully Fine-tuning"], value = 'Fully Fine-tuning', llabel = 'Model'), 67 | gr.components.Slider( 68 | minimum=0, maximum=1, value=0.1, label="Temperature" 69 | ), 70 | gr.components.Slider( 71 | minimum=0, maximum=1, value=0.75, label="Top p" 72 | ), 73 | gr.components.Slider( 74 | minimum=0, maximum=100, step=1, value=40, label="Top k" 75 | ), 76 | gr.components.Slider( 77 | minimum=1, maximum=512, step=1, value=128, label="Max New Tokens" 78 | ) 79 | ], 80 | outputs=[ 81 | gr.inputs.Textbox( 82 | lines=5, 83 | label="Output", 84 | ) 85 | ], 86 | title= "CodeCapybara", 87 | description="Our demonstration for CodeCapybara. CodeCapybara is fine-tuned from LLaMA on our curated dataset.", # noqa: E501 88 | ).queue().launch(server_name="localhost", share = True) 89 | if __name__ == "__main__": 90 | fire.Fire(main) -------------------------------------------------------------------------------- /main/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FSoft-AI4Code/CodeCapybara/9bc7ab4305444cca625ceed7b1aaca987a193bec/main/__init__.py -------------------------------------------------------------------------------- /main/data/HumanEval.jsonl.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FSoft-AI4Code/CodeCapybara/9bc7ab4305444cca625ceed7b1aaca987a193bec/main/data/HumanEval.jsonl.gz -------------------------------------------------------------------------------- /main/eval_humaneval.py: -------------------------------------------------------------------------------- 1 | import os 2 | import fire 3 | import json 4 | import gzip 5 | import subprocess 6 | from pathlib import Path 7 | from glob import glob 8 | 9 | def eval_humaneval(prediction_dir, 10 | output_dir="./output_dir", 11 | reference_path="./data/HumanEval.jsonl.gz"): 12 | references = [] 13 | if reference_path.endswith(".jsonl.gz"): 14 | with gzip.open(reference_path, "rt") as f: 15 | references = [json.loads(line) for line in f] 16 | 17 | predictions = [] 18 | for prediction_path in glob(f"{prediction_dir}/*.jsonl"): 19 | with open(prediction_path, "r") as f: 20 | predictions.extend([json.loads(line) for line in f]) 21 | 22 | references = {ref["task_id"]: ref for ref in references} 23 | for idx, prediction in enumerate(predictions): 24 | task_id = prediction["task_id"] 25 | code = prediction["completion"] 26 | ref = references[task_id] 27 | prompt = ref["prompt"] 28 | # 1. remove the prefixed prompt 29 | code = code[len(prompt):] 30 | # 2. remove everything after "\n\n" 31 | code = code.split("\n\n")[0] 32 | # 3. remove everything after the "def " 33 | code = code.split("def ")[0] 34 | prediction["completion"] = code 35 | predictions[idx] = prediction 36 | 37 | os.makedirs(output_dir, exist_ok=True) 38 | postprocessed_prediction_path = Path(output_dir, "humaneval_postprocessed_prediction.jsonl") 39 | with open(postprocessed_prediction_path, "w") as f: 40 | for prediction in predictions: 41 | json.dump(prediction, f) 42 | f.write("\n") 43 | cmd = f"evaluate_functional_correctness {postprocessed_prediction_path}" 44 | result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) 45 | for line in result.stdout: 46 | print(line.decode(), end="") 47 | 48 | if __name__ == "__main__": 49 | fire.Fire(eval_humaneval) 50 | -------------------------------------------------------------------------------- /main/eval_mbpp.py: -------------------------------------------------------------------------------- 1 | import os 2 | import fire 3 | import json 4 | import regex 5 | import signal 6 | import tempfile 7 | import threading 8 | import subprocess 9 | import collections 10 | from glob import glob 11 | from tqdm import tqdm 12 | from datetime import datetime 13 | from functools import partial 14 | from multiprocessing import Pool 15 | import numpy as np 16 | from utils.evaluation import estimate_pass_at_k 17 | 18 | class Command(object): 19 | def __init__(self, cmd): 20 | self.cmd = cmd 21 | self.process = None 22 | 23 | def run(self, timeout): 24 | def target(): 25 | self.process = subprocess.Popen(self.cmd, shell=True, preexec_fn=os.setsid) 26 | self.process.communicate() 27 | 28 | thread = threading.Thread(target=target) 29 | thread.start() 30 | 31 | thread.join(timeout) 32 | if thread.is_alive(): 33 | os.killpg(self.process.pid, signal.SIGTERM) 34 | thread.join() 35 | return self.process.returncode 36 | 37 | class MBPPGoogleDataset(object): 38 | def __init__(self, path="dataset/mbpp/mbpp.jsonl", mode="function_name"): 39 | raw_data = sorted( 40 | [json.loads(x) for x in open(path)], key=lambda x: x["task_id"] 41 | ) 42 | for i, data_item in enumerate(raw_data): 43 | assert data_item["task_id"] == i + 1 44 | self.raw_data = collections.defaultdict() 45 | self.mode = mode 46 | # 374 for training, 100 heldout, 500 test 47 | self.raw_data["train"] = raw_data[:10] + raw_data[510:] 48 | self.raw_data["test"] = raw_data[10:510] 49 | # data for codex collector, in input-output-info format 50 | self.data = collections.defaultdict() 51 | for split in self.raw_data: 52 | self.data[split] = self.extract_data(self.raw_data[split], mode) 53 | 54 | @staticmethod 55 | def extract_data(raw_data, mode): 56 | if mode == "function_name": 57 | get_function_name = lambda test_example: regex.match( 58 | "assert [\(]*([^\(]+)\(", test_example 59 | ).group(1) 60 | info = [get_function_name(x["test_list"][0]) for x in raw_data] 61 | elif mode == "assertion": 62 | info = [x["test_list"][0] for x in raw_data] 63 | elif mode == "assertion-full": 64 | info = [x["test_list"] for x in raw_data] 65 | else: 66 | raise Exception(f"Mode {mode} not supported.") 67 | nls = [x["text"] for x in raw_data] 68 | codes = [x["code"] for x in raw_data] 69 | return list(zip(nls, codes, info)) 70 | 71 | def evaluate_one_mbpp(args, tempdir, references, timeout): 72 | i, item = args 73 | task_id = item["task_id"] 74 | ref = references[task_id - 10 - 1] 75 | test_cases = ref["test_list"] 76 | test_setups = ref["test_setup_code"] 77 | code = item["trg_prediction"] 78 | # write code to file 79 | with open(f"{tempdir.name}/code-{i}.py", "w") as fout: 80 | print(code, file=fout) 81 | print(test_setups, file=fout) 82 | for case in test_cases: 83 | print(case, file=fout) 84 | fout.close() 85 | command = Command(f"python {tempdir.name}/code-{i}.py >/dev/null 2>&1") 86 | execution_result = command.run(timeout=timeout) == 0 87 | return (task_id, execution_result) 88 | # return execution_result 89 | 90 | 91 | """ dataset keys: src, trg_prediction, reference (only trg_prediction useful) """ 92 | 93 | 94 | def evaluate_google_mbpp( 95 | dataset, 96 | reference_path, 97 | split="test", 98 | timeout=10, 99 | num_procs=1, 100 | verbose=False, 101 | ): 102 | references = MBPPGoogleDataset(reference_path) 103 | tempdir = tempfile.TemporaryDirectory() 104 | passed_information = list() 105 | passed_information = collections.defaultdict(list) 106 | partial_evalutate_one = partial( 107 | evaluate_one_mbpp, tempdir=tempdir, references=references.raw_data[split], timeout=timeout 108 | ) 109 | 110 | if num_procs > 1: 111 | with Pool(processes=num_procs) as pool: 112 | for result_json in tqdm( 113 | pool.imap( 114 | partial_evalutate_one, list(enumerate(dataset)) 115 | ), 116 | total=len(dataset), 117 | leave=False, 118 | disable=not verbose, 119 | ): 120 | passed_information[result_json[0]].append(result_json[1]) 121 | else: 122 | for args in tqdm( 123 | list(enumerate(dataset)), disable=not verbose 124 | ): 125 | result_json = partial_evalutate_one(args) 126 | passed_information[result_json[0]].append(result_json[1]) 127 | tempdir.cleanup() 128 | results = {task_id: {"num_samples": len(sample_passed_info), "num_correct": sum(sample_passed_info)} for task_id, sample_passed_info in passed_information.items()} 129 | return results 130 | 131 | def postprocess(datapoint): 132 | prediction = datapoint.get("trg_prediction") 133 | prediction = prediction.split("###")[0].strip() 134 | prediction = prediction.split("if __name__")[0].strip() 135 | prediction = prediction.split("assert")[0].strip() 136 | prediction = "def ".join(prediction.split("def ")[:2]).strip() 137 | datapoint["trg_prediction"] = prediction 138 | 139 | return datapoint 140 | 141 | def eval_mbpp( 142 | prediction_dir, 143 | reference_path="data/mbpp.jsonl", 144 | num_procs=8, 145 | ): 146 | dataset = [] 147 | for filepath in glob("{}/*.jsonl".format(prediction_dir)): 148 | with open(filepath) as f: 149 | dataset.extend([json.loads(line) for line in f]) 150 | 151 | dataset = list(map(postprocess, dataset)) 152 | 153 | # statistics 154 | stats = collections.Counter([ex["task_id"] for ex in dataset]) 155 | print(stats) 156 | 157 | results = evaluate_google_mbpp(dataset, 158 | reference_path, 159 | num_procs=num_procs, 160 | verbose=True) 161 | score_dict = collections.defaultdict(float) 162 | num_samples = [r["num_samples"] for r in results.values()] 163 | num_correct = [r["num_correct"] for r in results.values()] 164 | for k in (1, 10, 80, 100): 165 | scores = estimate_pass_at_k(num_samples, num_correct, k) 166 | score_dict[k] = float(np.mean(scores)) 167 | 168 | print("Results:\n") 169 | for k, score in score_dict.items(): 170 | print(f"Pass@{k} = {score*100:.2f}%\n") 171 | 172 | if __name__ == "__main__": 173 | fire.Fire(eval_mbpp) 174 | -------------------------------------------------------------------------------- /main/generate.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import re 4 | from tqdm import tqdm 5 | import json 6 | import math 7 | 8 | import fire 9 | import torch 10 | import torch.distributed as dist 11 | from torch.nn.parallel import DistributedDataParallel as DDP 12 | from peft import PeftModel, get_peft_model, LoraConfig 13 | from transformers import GenerationConfig, LlamaForCausalLM, LlamaTokenizer 14 | 15 | from utils.prompter import Prompter 16 | from utils.evaluation import create_filepath, load_data 17 | 18 | if torch.cuda.is_available(): 19 | device = "cuda" 20 | else: 21 | device = "cpu" 22 | 23 | try: 24 | if torch.backends.mps.is_available(): 25 | device = "mps" 26 | except: 27 | pass 28 | 29 | def main( 30 | output_dir: str = "./output_dir", 31 | dataset_name: str = "mbpp", 32 | load_8bit: bool = False, 33 | base_model: str = "", 34 | tokenizer: str = "", 35 | lora_weights: str = "tloen/alpaca-lora-7b", 36 | prompt_template: str = "", 37 | batch_size: int = 64, 38 | temperature=0.1, 39 | top_p=0.75, 40 | top_k=40, 41 | num_return_sequences: int = 1, 42 | 43 | ): 44 | base_model = base_model or os.environ.get("BASE_MODEL", "") 45 | assert ( 46 | base_model 47 | ), "Please specify a --base_model, e.g. --base_model='huggyllama/llama-7b'" 48 | os.makedirs(output_dir, exist_ok=True) 49 | 50 | world_size = int(os.environ.get("WORLD_SIZE", 1)) 51 | local_rank = int(os.environ.get("LOCAL_RANK", 0)) 52 | ddp = world_size != 1 53 | 54 | if ddp: 55 | # init distributed process group 56 | dist.init_process_group( 57 | backend="nccl", 58 | init_method="env://", 59 | world_size=world_size, 60 | rank=local_rank, 61 | ) 62 | torch.cuda.set_device(local_rank) 63 | device_map = {"": local_rank} 64 | 65 | prompter = Prompter(prompt_template) 66 | if tokenizer is None or tokenizer == "": 67 | tokenizer = LlamaTokenizer.from_pretrained(base_model) 68 | else: 69 | tokenizer = LlamaTokenizer.from_pretrained(tokenizer) 70 | if lora_weights is None or lora_weights == "": 71 | model = LlamaForCausalLM.from_pretrained( 72 | base_model, 73 | load_in_8bit=load_8bit, 74 | torch_dtype=torch.float16, 75 | device_map=device_map, 76 | ) 77 | elif lora_weights.endswith(".bin"): 78 | model = LlamaForCausalLM.from_pretrained( 79 | base_model, 80 | load_in_8bit=True, 81 | torch_dtype=torch.float16, 82 | device_map=device_map, 83 | ) 84 | 85 | config = LoraConfig( 86 | r=8, 87 | lora_alpha=16, 88 | target_modules=["q_proj", "v_proj"], 89 | lora_dropout=0.05, 90 | bias="none", 91 | task_type="CAUSAL_LM", 92 | 93 | ) 94 | model = get_peft_model(model, config) 95 | 96 | state_dict = torch.load(lora_weights, map_location="cuda:0") 97 | pretrained_dict = {k: v for k, v in model.state_dict().items() if k not in state_dict.keys()} 98 | state_dict.update(pretrained_dict) 99 | model.load_state_dict(state_dict) 100 | else: 101 | model = LlamaForCausalLM.from_pretrained( 102 | base_model, 103 | load_in_8bit=load_8bit, 104 | torch_dtype=torch.float16, 105 | device_map=device_map, 106 | ) 107 | model = PeftModel.from_pretrained( 108 | model, 109 | lora_weights, 110 | torch_dtype=torch.float16, 111 | device_map=device_map, 112 | ) 113 | 114 | # unwind broken decapoda-research config 115 | model.config.pad_token_id = tokenizer.pad_token_id = 0 116 | model.config.bos_token_id = 1 117 | model.config.eos_token_id = 2 118 | 119 | tokenizer.padding_size = "left" 120 | 121 | if not load_8bit: 122 | model.haft() 123 | 124 | if ddp: 125 | model = DDP(model, device_ids=[local_rank]) 126 | 127 | model.eval() 128 | if torch.__version__ >= "2" and sys.platform != "win32": 129 | model = torch.compile(model) 130 | 131 | # loading data 132 | task_ids, instructions = load_data(dataset_name) 133 | if dataset_name == "humaneval": 134 | prompts = instructions 135 | else: 136 | prompts = [prompter.generate_prompt(instruction) for instruction in instructions] 137 | 138 | num_samples_this_rank = math.ceil(len(prompts)/world_size) 139 | _start_idx = num_samples_this_rank*local_rank 140 | _end_idx = num_samples_this_rank*(local_rank + 1) 141 | prompts = prompts[_start_idx:_end_idx] 142 | task_ids = task_ids[_start_idx:_end_idx] 143 | print("Rank: {}, task_ids: {}".format(local_rank, task_ids)) 144 | 145 | output_strings = [] 146 | for idx in tqdm(range(0, len(prompts), batch_size), desc="Rank {}".format(local_rank)): 147 | batch_prompts = prompts[batch_size*idx:batch_size*(idx+1)] 148 | # tokenization 149 | inputs = tokenizer(batch_prompts, 150 | truncation=False, 151 | padding=False, 152 | ) 153 | input_ids = inputs["input_ids"] 154 | batch_max_length = max(len(_input_ids) for _input_ids in input_ids) 155 | new_input_ids, attention_mask = [], [] 156 | for _input_ids in input_ids: 157 | padding_size = batch_max_length - len(_input_ids) 158 | new_input_ids.append([tokenizer.pad_token_id]*padding_size + _input_ids) 159 | attention_mask.append([False]*padding_size + [True]*len(_input_ids)) 160 | input_ids = torch.LongTensor(new_input_ids) 161 | input_ids = input_ids.to(device) 162 | attention_mask = torch.BoolTensor(attention_mask) 163 | attention_mask = attention_mask.to(device) 164 | 165 | this_batch_size = input_ids.shape[0] 166 | 167 | try: 168 | generation_config = GenerationConfig( 169 | temperature=temperature, 170 | top_p=top_p, 171 | top_k=top_k, 172 | do_sample=True, 173 | num_return_sequences=num_return_sequences, 174 | ) 175 | 176 | with torch.no_grad(): 177 | output_ids = model.module.generate( 178 | input_ids=input_ids, 179 | attention_mask=attention_mask, 180 | generation_config=generation_config, 181 | return_dict_in_generate=False, 182 | max_new_tokens=128, 183 | ) 184 | except torch.cuda.OutOfMemoryError: 185 | print("Rank {} out of memory ... continue ...".format(local_rank)) 186 | torch.cuda.empty_cache() 187 | output_strings.extend([""]*(this_batch_size*num_return_sequences)) 188 | continue 189 | batch_output_strings = [tokenizer.decode(s, 190 | skip_special_tokens=True, 191 | ignore_tokenization_space=True) 192 | for s in output_ids] 193 | output_strings.extend(batch_output_strings) 194 | 195 | filepath = create_filepath(os.path.join(output_dir, "generation.jsonl")) 196 | with open(filepath, "w") as f: 197 | for j, output_str in enumerate(output_strings): 198 | if output_str == "": 199 | continue 200 | task_id = task_ids[j//num_return_sequences] 201 | if dataset_name == "mbpp": 202 | output_str = prompter.get_response(output_str) 203 | json.dump({"task_id": task_id, "trg_prediction": output_str, "rank": local_rank}, f) 204 | elif dataset_name == "humaneval": 205 | json.dump({"task_id": task_id, "completion": output_str, "rank": local_rank}, f) 206 | f.write("\n") 207 | 208 | print("Rank {} finished. Predictions saved to {}".format(local_rank, filepath)) 209 | 210 | if __name__ == "__main__": 211 | fire.Fire(main) 212 | 213 | -------------------------------------------------------------------------------- /main/train.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.path.append(".") 3 | sys.path.append("..") 4 | 5 | import logging 6 | import random 7 | import numpy as np 8 | import argparse 9 | from types import SimpleNamespace 10 | import yaml 11 | import math 12 | import os 13 | import wandb 14 | from tqdm import tqdm 15 | import torch 16 | import torch.nn as nn 17 | from torch.nn.parallel import DistributedDataParallel as DDP 18 | from torch.distributed import init_process_group, barrier, destroy_process_group 19 | from torch.utils.data.distributed import DistributedSampler 20 | from prettytable import PrettyTable 21 | from peft import PeftModel 22 | from peft import ( 23 | LoraConfig, 24 | get_peft_model, 25 | get_peft_model_state_dict 26 | ) 27 | 28 | import functools 29 | from transformers import LlamaForCausalLM, LlamaTokenizer, get_linear_schedule_with_warmup 30 | from transformers.models.llama.modeling_llama import LlamaDecoderLayer 31 | 32 | from torch.distributed.fsdp import ( 33 | FullyShardedDataParallel, 34 | CPUOffload, 35 | FullStateDictConfig, 36 | StateDictType, 37 | ) 38 | from torch.distributed.fsdp.wrap import ( 39 | transformer_auto_wrap_policy, 40 | enable_wrap, 41 | wrap, 42 | ) 43 | 44 | 45 | from data.dataset import CapybaraDataset 46 | from data.loaders import get_code_contests, get_code_capybara, get_code_alpaca 47 | 48 | def set_seed(seed): 49 | random.seed(seed) 50 | np.random.seed(seed) 51 | torch.manual_seed(seed) 52 | torch.cuda.manual_seed_all(seed) 53 | 54 | def display_params(model): 55 | param_table = PrettyTable(['Name', 'Trainable', 'Shape', '#Params']) 56 | param_table.align["Name"] = "l" 57 | param_table.align["Shape"] = "l" 58 | 59 | for name, w in model.named_parameters(): 60 | size = torch.tensor(w.shape) 61 | param_table.add_row([name, w.requires_grad, size.tolist(), size.prod().item()]) 62 | print(param_table) 63 | 64 | def parse_args(): 65 | ap = argparse.ArgumentParser() 66 | ap.add_argument('-c', '--config-path', default = 'configs/config.yml', type = str, help = 'the path of the config file') 67 | ap.add_argument('--seed', type = int, default = 0, help = 'seed for training process') 68 | ap.add_argument('--train-batch-size', default = 10, type = int) 69 | ap.add_argument('--val-batch-size', default = 10, type = int) 70 | ap.add_argument('--num-workers', default = 0, type = int) 71 | ap.add_argument('--model-type', type = str, choices = ['fine-tuning', 'lora']) 72 | ap.add_argument('--use-wandb', type = int, default = 1) 73 | return ap.parse_args() 74 | 75 | def parse_config(data): 76 | if type(data) is list: 77 | return list(map(parse_config, data)) 78 | elif type(data) is dict: 79 | sns = SimpleNamespace() 80 | for key, value in data.items(): 81 | setattr(sns, key, parse_config(value)) 82 | return sns 83 | else: 84 | return data 85 | 86 | def ddp_setup(): 87 | init_process_group(backend = 'nccl') 88 | def cleanup(): 89 | destroy_process_group() 90 | 91 | 92 | def save_fsdp_checkpoint(base_path, stats, model, optimizer, scheduler = None): 93 | path = os.path.join(base_path, f"cp_{stats['epoch']}.tar") 94 | save_policy = FullStateDictConfig(offload_to_cpu=True, rank0_only=True) 95 | saved_checkpoint_data = { 96 | 'epoch': stats['epoch'], 97 | 'optimizer': optimizer.state_dict(), 98 | 'scheduler': scheduler.state_dict() if scheduler is not None else None 99 | } 100 | with FullyShardedDataParallel.state_dict_type( 101 | model, StateDictType.FULL_STATE_DICT, save_policy 102 | ): 103 | cpu_state = model.state_dict() 104 | saved_checkpoint_data['model'] = cpu_state 105 | 106 | torch.save(saved_checkpoint_data, path) 107 | def save_ddp_checkpoint(base_path, stats, model, optimizer, scheduler = None): 108 | path = os.path.join(base_path, f"cp_{stats['epoch']}.tar") 109 | saved_checkpoint_data = { 110 | 'epoch': stats['epoch'], 111 | 'model': get_peft_model_state_dict(model.module), 112 | 'optimizer': optimizer.state_dict(), 113 | 'scheduler': scheduler.state_dict() if scheduler is not None else None 114 | } 115 | torch.save(saved_checkpoint_data, path) 116 | 117 | def load_checkpoint(path, device): 118 | saved_data = torch.load(path, map_location = device) 119 | return saved_data['epoch'], saved_data['model'], saved_data['optimizer'], saved_data['scheduler'] 120 | 121 | def train_one_epoch(stats, loader, model, optimizer, scheduler = None): 122 | dataset_size = len(loader) 123 | local_rank = stats['rank'] 124 | use_wandb = stats['use_wandb'] 125 | model.train() 126 | acc_loss, acc_perplexity, count = 0, 0, 0 127 | criterion = nn.CrossEntropyLoss() 128 | bar = tqdm(loader, total = dataset_size) if local_rank == 0 else loader 129 | for input_ids, output_ids, mask in bar: 130 | input_ids = input_ids.cuda() 131 | output_ids = output_ids.cuda() 132 | mask = mask.cuda() 133 | optimizer.zero_grad() 134 | outputs = model(input_ids = input_ids, attention_mask = mask) 135 | logits = outputs.logits.transpose(1, 2) 136 | loss = criterion(logits, output_ids) 137 | loss.backward() 138 | optimizer.step() 139 | if scheduler is not None: scheduler.step() 140 | loss_cpu = loss.detach().cpu().item() 141 | acc_loss += loss_cpu 142 | perplexity = math.exp(loss_cpu) 143 | acc_perplexity += perplexity 144 | count += 1 145 | if local_rank == 0: 146 | bar.set_description(f'loss: {loss_cpu: .4f} perplexity: {perplexity: .4f}') 147 | if use_wandb: 148 | wandb.log({ 149 | 'loss': loss_cpu, 150 | 'perplexity': perplexity, 151 | 'lr': optimizer.param_groups[0]['lr'] 152 | }) 153 | 154 | return acc_loss / count, acc_perplexity / count 155 | 156 | 157 | @torch.no_grad() 158 | def validate_one_epoch(stats, loader, model): 159 | dataset_size = len(loader) 160 | local_rank = stats['rank'] 161 | 162 | acc_loss, acc_perplexity, count = 0, 0, 0 163 | criterion = nn.CrossEntropyLoss() 164 | bar = tqdm(loader, total = dataset_size) if local_rank == 0 else loader 165 | for input_ids, output_ids, mask in bar: 166 | input_ids = input_ids.cuda() 167 | output_ids = output_ids.cuda() 168 | mask = mask.cuda() 169 | outputs = model(input_ids = input_ids, attention_mask = mask) 170 | logits = outputs.logits.transpose(1, 2) 171 | loss = criterion(logits, output_ids) 172 | loss_cpu = loss.cpu().item() 173 | acc_loss += loss_cpu 174 | perplexity = math.exp(loss_cpu) 175 | acc_perplexity += perplexity 176 | count += 1 177 | 178 | return acc_loss / count, acc_perplexity / count 179 | 180 | def main(): 181 | args = parse_args() 182 | 183 | ddp_setup() 184 | set_seed(args.seed) 185 | 186 | config = yaml.load(open(args.config_path), Loader = yaml.FullLoader) 187 | config = parse_config(config) 188 | 189 | 190 | start_epoch = -1 191 | local_rank = int(os.environ['LOCAL_RANK']) 192 | torch.cuda.set_device(local_rank) 193 | 194 | 195 | if local_rank == 0: 196 | if not os.path.exists(config.checkpoint.dir): 197 | os.makedirs(config.checkpoint.dir) 198 | if not os.path.exists(config.log.dir): 199 | os.makedirs(config.log.dir) 200 | barrier() 201 | logger = logging.getLogger('Training CodeCapyraba ...\n') 202 | logger.setLevel(logging.INFO) 203 | formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s') 204 | 205 | stdout_handler = logging.StreamHandler(sys.stdout) 206 | stdout_handler.setFormatter(formatter) 207 | logger.addHandler(stdout_handler) 208 | 209 | file_handler = logging.FileHandler(f'{config.log.dir}/{config.log.file}') 210 | file_handler.setFormatter(formatter) 211 | logger.addHandler(file_handler) 212 | 213 | 214 | tokenizer = LlamaTokenizer.from_pretrained(config.model.hf_model) 215 | tokenizer.pad_token_id = 0 216 | if local_rank == 0: 217 | logging.info('HUGGING FACE MODEL:', config.model.hf_model) 218 | model = LlamaForCausalLM.from_pretrained(config.model.hf_model).train() 219 | 220 | model_data, optimizer_data, scheduler_data = [None] * 3 221 | resume_train = os.path.exists(config.checkpoint.old_checkpoint or '') 222 | if resume_train: 223 | if local_rank == 0: 224 | logger.info('Resume training ...') 225 | start_epoch, model_data, optimizer_data, scheduler_data = load_checkpoint(config.checkpoint.old_checkpoint, 'cpu') 226 | elif local_rank == 0: 227 | logger.info('Train from scratch ...') 228 | start_epoch += 1 229 | 230 | 231 | if args.model_type == 'lora': 232 | 233 | lora_config = LoraConfig( 234 | r = config.model.lora.r, 235 | lora_alpha = config.model.lora.alpha, 236 | target_modules = config.model.lora.target_modules, 237 | lora_dropout = config.model.lora.dropout, 238 | bias = "none", 239 | task_type="CAUSAL_LM", 240 | ) 241 | model = get_peft_model(model, lora_config) 242 | if model_data is not None: 243 | model.load_state_dict(model_data, strict = False) 244 | 245 | display_params(model) 246 | model = model.cuda() 247 | model = DDP(model) 248 | save_checkpoint = save_ddp_checkpoint 249 | elif args.model_type == 'fine-tuning': 250 | if local_rank == 0: 251 | logger.info('[MODEL TYPE] fine-tuning') 252 | display_params(model) 253 | if model_data is not None: 254 | model.load_state_dict(model_data) 255 | 256 | llama_auto_wrap_policy = functools.partial( 257 | transformer_auto_wrap_policy, 258 | transformer_layer_cls = { 259 | LlamaDecoderLayer, 260 | }, 261 | ) 262 | 263 | model = FullyShardedDataParallel( 264 | model, 265 | auto_wrap_policy=llama_auto_wrap_policy, 266 | device_id = torch.cuda.current_device() 267 | ) 268 | 269 | save_checkpoint = save_fsdp_checkpoint 270 | else: 271 | raise RuntimeError(f"The model type {args.model_type} isn't supported") 272 | 273 | dataset_names = config.datasets 274 | 275 | train_data, val_data = [], [] 276 | for dataset in dataset_names: 277 | dataset = vars(dataset) 278 | dataset_name, dataset_path = next(iter(dataset.items())) 279 | 280 | if dataset_name == 'code-contest': 281 | data = get_code_contests(tokenizer, config.max_seq_length) 282 | elif dataset_name == 'codealpaca': 283 | data = get_code_alpaca(dataset_path, tokenizer, config.max_seq_length) 284 | elif dataset_name == 'codecapybara': 285 | data = get_code_capybara(dataset_path, tokenizer, config.max_seq_length) 286 | else: 287 | raise RuntimeError(f"This dataset ({dataset_name}) isn't supported") 288 | 289 | train_size = int(len(data) * 0.8) 290 | train_data.extend(data[:train_size]) 291 | val_data.extend(data[train_size:]) 292 | if local_rank == 0: 293 | logger.info(f'LOADED the dataset: {dataset_name}') 294 | 295 | 296 | train_dataset = CapybaraDataset(train_data,tokenizer, max_seq_length = config.max_seq_length) 297 | train_sampler = DistributedSampler(train_dataset) 298 | train_batch_size = args.train_batch_size 299 | train_loader = torch.utils.data.DataLoader( 300 | train_dataset, 301 | batch_size = train_batch_size, 302 | num_workers = args.num_workers, 303 | collate_fn = train_dataset.collate, 304 | sampler = train_sampler 305 | ) 306 | 307 | val_dataset = CapybaraDataset(val_data, tokenizer, max_seq_length = config.max_seq_length) 308 | val_sampler = DistributedSampler(train_dataset) 309 | val_batch_size = args.train_batch_size 310 | val_loader = torch.utils.data.DataLoader( 311 | train_dataset, 312 | batch_size = val_batch_size, 313 | num_workers = args.num_workers, 314 | collate_fn = val_dataset.collate, 315 | sampler = val_sampler 316 | ) 317 | 318 | learnable_weights = [w for w in model.parameters() if w.requires_grad] 319 | optimizer = getattr(torch.optim, config.optimizer.name)(learnable_weights, **vars(config.optimizer.params)) 320 | num_warmup_steps = config.scheduler.num_warmup_steps 321 | num_training_steps = config.scheduler.num_training_epochs * len(train_loader) 322 | scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps) 323 | 324 | if optimizer_data is not None: 325 | optimizer.load_state_dict(optimizer_data) 326 | if scheduler_data is not None: 327 | scheduler.load_state_dict(scheduler_data) 328 | 329 | use_wandb = args.use_wandb 330 | stats = {'epoch': start_epoch, 'rank': local_rank, 'use_wandb': use_wandb} 331 | 332 | 333 | if local_rank == 0 and use_wandb: 334 | wandb.init(project = config.wandb.project, name = config.wandb.name) 335 | for epoch in range(start_epoch, config.epochs): 336 | if local_rank == 0: 337 | logger.info(f'EPOCH: {epoch}') 338 | stats['epoch'] = epoch 339 | train_loader.sampler.set_epoch(epoch) 340 | train_loss, train_perplexity = train_one_epoch(stats, train_loader, model, optimizer, scheduler = scheduler) 341 | logger.info(f'[RANK = {local_rank}] train-loss: {train_loss: .4f} train-perplexity: {train_perplexity: .4f}') 342 | if local_rank == 0: 343 | if epoch % config.checkpoint.epochs == 0: 344 | save_checkpoint(config.checkpoint.dir, stats, model, optimizer, scheduler) 345 | logger.info(f'SAVED CHECKPOINT AT EPOCH: {epoch}') 346 | val_loss, val_perplexity = validate_one_epoch(stats, val_loader, model) 347 | if local_rank == 0 and use_wandb: 348 | wandb.log({ 349 | 'train-loss': train_loss, 350 | 'train-perplexity': train_perplexity, 351 | 'val-loss': val_loss, 352 | 'val-perplexity': val_perplexity 353 | }) 354 | logger.info(f'[RANK = {local_rank}] val-loss: {val_loss: .4f} val-perplexity: {val_perplexity: .4f}') 355 | 356 | 357 | barrier() 358 | cleanup() 359 | if __name__ == "__main__": 360 | os.environ['TORCH_DISTRIBUTED_DEBUG'] = 'DETAIL' 361 | main() 362 | -------------------------------------------------------------------------------- /main/utils/evaluation.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import json 4 | import gzip 5 | import itertools 6 | from typing import Union, List 7 | import numpy as np 8 | 9 | def create_filepath(filepath): 10 | if os.path.exists(filepath): 11 | filename, ext = os.path.splitext(filepath) 12 | file_index = re.search(r"\d+$", filename) 13 | if file_index is None: 14 | filename = "{}1".format(filename) 15 | file_index = 1 16 | else: 17 | file_index = int(file_index.group(0)) 18 | file_index = int(file_index) 19 | while os.path.exists("{}{}".format(filename, ext)): 20 | filename = filename[:-len(str(file_index))] + str(file_index+1) 21 | file_index += 1 22 | filepath = "{}{}".format(filename, ext) 23 | return filepath 24 | 25 | def create_mbpp_instruction(example): 26 | description = example["text"] 27 | test_cases = example["test_list"] 28 | prompt = "You are an expert Python programmer, and here is your task: {description} Your code should pass these tests:\n\n{tests}\n" 29 | instruction = prompt.format(description=description, tests="\n".join(test_cases)) 30 | return instruction 31 | 32 | def load_data(dataset_name): 33 | data_path_mapping = { 34 | "mbpp": "./data/mbpp.jsonl", 35 | "humaneval": "./data/HumanEval.jsonl.gz" 36 | } 37 | data_path = data_path_mapping[dataset_name] 38 | data = [] 39 | if data_path.endswith(".jsonl.gz"): 40 | with gzip.open(data_path, "rt") as f: 41 | data = [json.loads(line) for line in f] 42 | elif data_path.endswith(".json"): 43 | with open(data_path, "r") as f: 44 | data = json.load(f) 45 | else: 46 | with open(data_path, "r") as f: 47 | data = [json.loads(line) for line in f] 48 | 49 | instructions = [] 50 | task_ids = [] 51 | if dataset_name == "mbpp": 52 | data = list(filter(lambda x: x["task_id"] in range(11, 511), data)) 53 | instructions = list(map(create_mbpp_instruction, data)) 54 | task_ids = list(map(lambda x: x["task_id"], data)) 55 | else: 56 | task_ids = [ex["task_id"] for ex in data] 57 | instructions = [ex["prompt"] for ex in data] 58 | 59 | return task_ids, instructions 60 | 61 | 62 | def estimate_pass_at_k( 63 | num_samples: Union[int, List[int], np.ndarray], 64 | num_correct: Union[List[int], np.ndarray], 65 | k: int 66 | ) -> np.ndarray: 67 | """ 68 | Estimates pass@k of each problem and returns them in an array. 69 | """ 70 | 71 | def estimator(n: int, c: int, k: int) -> float: 72 | """ 73 | Calculates 1 - comb(n - c, k) / comb(n, k). 74 | """ 75 | if n - c < k: 76 | return 1.0 77 | return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1)) 78 | 79 | if isinstance(num_samples, int): 80 | num_samples_it = itertools.repeat(num_samples, len(num_correct)) 81 | else: 82 | assert len(num_samples) == len(num_correct) 83 | num_samples_it = iter(num_samples) 84 | 85 | return np.array([estimator(int(n), int(c), k) for n, c in zip(num_samples_it, num_correct)]) 86 | -------------------------------------------------------------------------------- /main/utils/prompter.py: -------------------------------------------------------------------------------- 1 | """ 2 | A dedicated helper to manage templates and prompt building. 3 | """ 4 | 5 | import json 6 | import os.path as osp 7 | from typing import Union 8 | 9 | 10 | class Prompter(object): 11 | __slots__ = ("template", "_verbose") 12 | 13 | def __init__(self, template_name: str = "", verbose: bool = False): 14 | self._verbose = verbose 15 | # if not template_name: 16 | # # Enforce the default here, so the constructor can be called with '' and will not break. 17 | # template_name = "alpaca" 18 | # file_name = osp.join("templates", f"{template_name}.json") 19 | # if not osp.exists(file_name): 20 | # raise ValueError(f"Can't read {file_name}") 21 | # with open(file_name) as fp: 22 | # self.template = json.load(fp) 23 | self.template = { 24 | "description": "Template used by Alpaca-LoRA.", 25 | "prompt_input": "Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.\n\n### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:\n", 26 | "prompt_no_input": "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\n{instruction}\n\n### Response:\n", 27 | "response_split": "### Response:" 28 | } 29 | if self._verbose: 30 | print( 31 | f"Using prompt template {template_name}: {self.template['description']}" 32 | ) 33 | 34 | def generate_prompt( 35 | self, 36 | instruction: str, 37 | input: Union[None, str] = None, 38 | label: Union[None, str] = None, 39 | ) -> str: 40 | # returns the full prompt from instruction and optional input 41 | # if a label (=response, =output) is provided, it's also appended. 42 | if input: 43 | res = self.template["prompt_input"].format( 44 | instruction=instruction, input=input 45 | ) 46 | else: 47 | res = self.template["prompt_no_input"].format( 48 | instruction=instruction 49 | ) 50 | if label: 51 | res = f"{res}{label}" 52 | if self._verbose: 53 | print(res) 54 | return res 55 | 56 | def get_response(self, output: str) -> str: 57 | return output.split(self.template["response_split"])[1].strip() 58 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | accelerate 2 | appdirs 3 | loralib 4 | bitsandbytes 5 | black 6 | black[jupyter] 7 | datasets 8 | fire 9 | git+https://github.com/huggingface/peft.git 10 | git+https://github.com/openai/human-eval.git 11 | transformers>=4.28.0 12 | sentencepiece 13 | gradio 14 | -------------------------------------------------------------------------------- /scripts/eval_humaneval.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | cd main/ 4 | 5 | # model inference 6 | export CUDA_VISIBLE_DEVICES=0,1 7 | N_PROCS=$(echo $CUDA_VISIBLE_DEVICES | tr "," "\n" | wc -l) 8 | NUM_ITERATIONS=10 9 | 10 | for _ in $(seq $NUM_ITERATIONS); 11 | do 12 | python -m torch.distributed.run --nprocs ${N_PROCS} generate.py \ 13 | --output_dir ./generation_output_dir/humaneval \ 14 | --dataset_name 'humaneval' \ 15 | --base_model 'decapoda-research/llama-7b-hf' \ 16 | --lora_weights '' \ 17 | --batch_size 1 \ 18 | --num_return_sequences 20 \ 19 | --load_8bit True 20 | done 21 | 22 | # Calculating pass@k with k=1,10,80,100 23 | python eval_humaneval.py --prediction_dir ./generation_output_dir/humaneval \ 24 | -------------------------------------------------------------------------------- /scripts/eval_mbpp.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | cd main/ 4 | 5 | # model inference 6 | export CUDA_VISIBLE_DEVICES=0,1 7 | N_PROCS=$(echo $CUDA_VISIBLE_DEVICES | tr "," "\n" | wc -l) 8 | NUM_ITERATIONS=10 9 | 10 | for _ in $(seq $NUM_ITERATIONS); 11 | do 12 | python -m torch.distributed.run --nprocs ${N_PROCS} generate.py \ 13 | --output_dir ./generation_output_dir/mbpp \ 14 | --dataset_name 'mbpp' \ 15 | --base_model 'decapoda-research/llama-7b-hf' \ 16 | --lora_weights '' \ 17 | --batch_size 1 \ 18 | --num_return_sequences 20 \ 19 | --load_8bit True 20 | done 21 | 22 | # Calculating pass@k with k=1,10,80,100 23 | python eval_mbpp.py --prediction_dir ./generation_output_dir/mbpp 24 | -------------------------------------------------------------------------------- /scripts/train.sh: -------------------------------------------------------------------------------- 1 | torchrun --master_port=29450 --nnodes=1 --nproc_per_node=gpu main/train.py --train-batch-size 2 --val-batch-size 4 --num-workers 2 --config-path configs/config.yml --model-type lora --use-wandb 1 --------------------------------------------------------------------------------