├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── code2seq ├── code2seq_model.py ├── dataset.py ├── generate_data.py └── generate_vocab.py ├── dataset.py ├── demo.py ├── generate_new_trees.py ├── generate_vocab.py ├── model.py ├── models ├── code2seq │ ├── dataset.py │ ├── generate_data.py │ └── generate_vocab.py ├── path_trans │ ├── dataset.py │ └── generate_data.py ├── path_trans_variation │ ├── dataset.py │ └── generate_data.py ├── seq │ ├── astunparser.py │ ├── dataset.py │ └── generate_data.py └── trav_trans │ ├── dataset.py │ ├── generate_ast_ids.py │ └── generate_data.py ├── train.py └── utils.py /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to make participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies within all project spaces, and it also applies when 49 | an individual is representing the project or its community in public spaces. 50 | Examples of representing a project or community include using an official 51 | project e-mail address, posting via an official social media account, or acting 52 | as an appointed representative at an online or offline event. Representation of 53 | a project may be further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at . All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | **Please note that we are not actively maintaining the repo at this time.** 2 | 3 | ----- 4 | 5 | 6 | 7 | # Contributing to code-prediction-transformer 8 | We want to make contributing to this project as easy and transparent as 9 | possible. 10 | 11 | ## Pull Requests 12 | We actively welcome your pull requests. 13 | 14 | 1. Fork the repo and create your branch from `master`. 15 | 2. If you've added code that should be tested, add tests. 16 | 3. If you've changed APIs, update the documentation. 17 | 4. Ensure the test suite passes. 18 | 5. Make sure your code lints. 19 | 6. If you haven't already, complete the Contributor License Agreement ("CLA"). 20 | 21 | ## Contributor License Agreement ("CLA") 22 | In order to accept your pull request, we need you to submit a CLA. You only need 23 | to do this once to work on any of Facebook's open source projects. 24 | 25 | Complete your CLA here: 26 | 27 | ## Issues 28 | We use GitHub issues to track public bugs. Please ensure your description is 29 | clear and has sufficient instructions to be able to reproduce the issue. 30 | 31 | Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe 32 | disclosure of security bugs. In those cases, please go through the process 33 | outlined on that page and do not file a public issue. 34 | 35 | ## License 36 | By contributing to code-prediction-transformer, you agree that your contributions will be licensed 37 | under the LICENSE file in the root directory of this source tree. 38 | -------------------------------------------------------------------------------- /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 | Section 1 -- Definitions. 71 | 72 | a. Adapted Material means material subject to Copyright and Similar 73 | Rights that is derived from or based upon the Licensed Material 74 | and in which the Licensed Material is translated, altered, 75 | arranged, transformed, or otherwise modified in a manner requiring 76 | permission under the Copyright and Similar Rights held by the 77 | Licensor. For purposes of this Public License, where the Licensed 78 | Material is a musical work, performance, or sound recording, 79 | Adapted Material is always produced where the Licensed Material is 80 | synched in timed relation with a moving image. 81 | 82 | b. Adapter's License means the license You apply to Your Copyright 83 | and Similar Rights in Your contributions to Adapted Material in 84 | accordance with the terms and conditions of this Public License. 85 | 86 | c. Copyright and Similar Rights means copyright and/or similar rights 87 | closely related to copyright including, without limitation, 88 | performance, broadcast, sound recording, and Sui Generis Database 89 | Rights, without regard to how the rights are labeled or 90 | categorized. For purposes of this Public License, the rights 91 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 92 | Rights. 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. NonCommercial means not primarily intended for or directed towards 116 | commercial advantage or monetary compensation. For purposes of 117 | this Public License, the exchange of the Licensed Material for 118 | other material subject to Copyright and Similar Rights by digital 119 | file-sharing or similar means is NonCommercial provided there is 120 | no payment of monetary compensation in connection with the 121 | exchange. 122 | 123 | j. Share means to provide material to the public by any means or 124 | process that requires permission under the Licensed Rights, such 125 | as reproduction, public display, public performance, distribution, 126 | dissemination, communication, or importation, and to make material 127 | available to the public including in ways that members of the 128 | public may access the material from a place and at a time 129 | individually chosen by them. 130 | 131 | k. Sui Generis Database Rights means rights other than copyright 132 | resulting from Directive 96/9/EC of the European Parliament and of 133 | the Council of 11 March 1996 on the legal protection of databases, 134 | as amended and/or succeeded, as well as other essentially 135 | equivalent rights anywhere in the world. 136 | 137 | l. You means the individual or entity exercising the Licensed Rights 138 | under this Public License. Your has a corresponding meaning. 139 | 140 | Section 2 -- Scope. 141 | 142 | a. License grant. 143 | 144 | 1. Subject to the terms and conditions of this Public License, 145 | the Licensor hereby grants You a worldwide, royalty-free, 146 | non-sublicensable, non-exclusive, irrevocable license to 147 | exercise the Licensed Rights in the Licensed Material to: 148 | 149 | a. reproduce and Share the Licensed Material, in whole or 150 | in part, for NonCommercial purposes only; and 151 | 152 | b. produce, reproduce, and Share Adapted Material for 153 | NonCommercial purposes only. 154 | 155 | 2. Exceptions and Limitations. For the avoidance of doubt, where 156 | Exceptions and Limitations apply to Your use, this Public 157 | License does not apply, and You do not need to comply with 158 | its terms and conditions. 159 | 160 | 3. Term. The term of this Public License is specified in Section 161 | 6(a). 162 | 163 | 4. Media and formats; technical modifications allowed. The 164 | Licensor authorizes You to exercise the Licensed Rights in 165 | all media and formats whether now known or hereafter created, 166 | and to make technical modifications necessary to do so. The 167 | Licensor waives and/or agrees not to assert any right or 168 | authority to forbid You from making technical modifications 169 | necessary to exercise the Licensed Rights, including 170 | technical modifications necessary to circumvent Effective 171 | Technological Measures. For purposes of this Public License, 172 | simply making modifications authorized by this Section 2(a) 173 | (4) never produces Adapted Material. 174 | 175 | 5. Downstream recipients. 176 | 177 | a. Offer from the Licensor -- Licensed Material. Every 178 | recipient of the Licensed Material automatically 179 | receives an offer from the Licensor to exercise the 180 | Licensed Rights under the terms and conditions of this 181 | Public License. 182 | 183 | b. No downstream restrictions. You may not offer or impose 184 | any additional or different terms or conditions on, or 185 | apply any Effective Technological Measures to, the 186 | Licensed Material if doing so restricts exercise of the 187 | Licensed Rights by any recipient of the Licensed 188 | Material. 189 | 190 | 6. No endorsement. Nothing in this Public License constitutes or 191 | may be construed as permission to assert or imply that You 192 | are, or that Your use of the Licensed Material is, connected 193 | with, or sponsored, endorsed, or granted official status by, 194 | the Licensor or others designated to receive attribution as 195 | provided in Section 3(a)(1)(A)(i). 196 | 197 | b. Other rights. 198 | 199 | 1. Moral rights, such as the right of integrity, are not 200 | licensed under this Public License, nor are publicity, 201 | privacy, and/or other similar personality rights; however, to 202 | the extent possible, the Licensor waives and/or agrees not to 203 | assert any such rights held by the Licensor to the limited 204 | extent necessary to allow You to exercise the Licensed 205 | Rights, but not otherwise. 206 | 207 | 2. Patent and trademark rights are not licensed under this 208 | Public License. 209 | 210 | 3. To the extent possible, the Licensor waives any right to 211 | collect royalties from You for the exercise of the Licensed 212 | Rights, whether directly or through a collecting society 213 | under any voluntary or waivable statutory or compulsory 214 | licensing scheme. In all other cases the Licensor expressly 215 | reserves any right to collect such royalties, including when 216 | the Licensed Material is used other than for NonCommercial 217 | purposes. 218 | 219 | Section 3 -- License Conditions. 220 | 221 | Your exercise of the Licensed Rights is expressly made subject to the 222 | following conditions. 223 | 224 | a. Attribution. 225 | 226 | 1. If You Share the Licensed Material (including in modified 227 | form), You must: 228 | 229 | a. retain the following if it is supplied by the Licensor 230 | with the Licensed Material: 231 | 232 | i. identification of the creator(s) of the Licensed 233 | Material and any others designated to receive 234 | attribution, in any reasonable manner requested by 235 | the Licensor (including by pseudonym if 236 | designated); 237 | 238 | ii. a copyright notice; 239 | 240 | iii. a notice that refers to this Public License; 241 | 242 | iv. a notice that refers to the disclaimer of 243 | warranties; 244 | 245 | v. a URI or hyperlink to the Licensed Material to the 246 | extent reasonably practicable; 247 | 248 | b. indicate if You modified the Licensed Material and 249 | retain an indication of any previous modifications; and 250 | 251 | c. indicate the Licensed Material is licensed under this 252 | Public License, and include the text of, or the URI or 253 | hyperlink to, this Public License. 254 | 255 | 2. You may satisfy the conditions in Section 3(a)(1) in any 256 | reasonable manner based on the medium, means, and context in 257 | which You Share the Licensed Material. For example, it may be 258 | reasonable to satisfy the conditions by providing a URI or 259 | hyperlink to a resource that includes the required 260 | information. 261 | 262 | 3. If requested by the Licensor, You must remove any of the 263 | information required by Section 3(a)(1)(A) to the extent 264 | reasonably practicable. 265 | 266 | 4. If You Share Adapted Material You produce, the Adapter's 267 | License You apply must not prevent recipients of the Adapted 268 | Material from complying with this Public License. 269 | 270 | Section 4 -- Sui Generis Database Rights. 271 | 272 | Where the Licensed Rights include Sui Generis Database Rights that 273 | apply to Your use of the Licensed Material: 274 | 275 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 276 | to extract, reuse, reproduce, and Share all or a substantial 277 | portion of the contents of the database for NonCommercial purposes 278 | only; 279 | 280 | b. if You include all or a substantial portion of the database 281 | contents in a database in which You have Sui Generis Database 282 | Rights, then the database in which You have Sui Generis Database 283 | Rights (but not its individual contents) is Adapted Material; and 284 | 285 | c. You must comply with the conditions in Section 3(a) if You Share 286 | all or a substantial portion of the contents of the database. 287 | 288 | For the avoidance of doubt, this Section 4 supplements and does not 289 | replace Your obligations under this Public License where the Licensed 290 | Rights include other Copyright and Similar Rights. 291 | 292 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 293 | 294 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 295 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 296 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 297 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 298 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 299 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 300 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 301 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 302 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 303 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 304 | 305 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 306 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 307 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 308 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 309 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 310 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 311 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 312 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 313 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 314 | 315 | c. The disclaimer of warranties and limitation of liability provided 316 | above shall be interpreted in a manner that, to the extent 317 | possible, most closely approximates an absolute disclaimer and 318 | waiver of all liability. 319 | 320 | Section 6 -- Term and Termination. 321 | 322 | a. This Public License applies for the term of the Copyright and 323 | Similar Rights licensed here. However, if You fail to comply with 324 | this Public License, then Your rights under this Public License 325 | terminate automatically. 326 | 327 | b. Where Your right to use the Licensed Material has terminated under 328 | Section 6(a), it reinstates: 329 | 330 | 1. automatically as of the date the violation is cured, provided 331 | it is cured within 30 days of Your discovery of the 332 | violation; or 333 | 334 | 2. upon express reinstatement by the Licensor. 335 | 336 | For the avoidance of doubt, this Section 6(b) does not affect any 337 | right the Licensor may have to seek remedies for Your violations 338 | of this Public License. 339 | 340 | c. For the avoidance of doubt, the Licensor may also offer the 341 | Licensed Material under separate terms or conditions or stop 342 | distributing the Licensed Material at any time; however, doing so 343 | will not terminate this Public License. 344 | 345 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 346 | License. 347 | 348 | Section 7 -- Other Terms and Conditions. 349 | 350 | a. The Licensor shall not be bound by any additional or different 351 | terms or conditions communicated by You unless expressly agreed. 352 | 353 | b. Any arrangements, understandings, or agreements regarding the 354 | Licensed Material not stated herein are separate from and 355 | independent of the terms and conditions of this Public License. 356 | 357 | Section 8 -- Interpretation. 358 | 359 | a. For the avoidance of doubt, this Public License does not, and 360 | shall not be interpreted to, reduce, limit, restrict, or impose 361 | conditions on any use of the Licensed Material that could lawfully 362 | be made without permission under this Public License. 363 | 364 | b. To the extent possible, if any provision of this Public License is 365 | deemed unenforceable, it shall be automatically reformed to the 366 | minimum extent necessary to make it enforceable. If the provision 367 | cannot be reformed, it shall be severed from this Public License 368 | without affecting the enforceability of the remaining terms and 369 | conditions. 370 | 371 | c. No term or condition of this Public License will be waived and no 372 | failure to comply consented to unless expressly agreed to by the 373 | Licensor. 374 | 375 | d. Nothing in this Public License constitutes or may be interpreted 376 | as a limitation upon, or waiver of, any privileges and immunities 377 | that apply to the Licensor or You, including from the legal 378 | processes of any jurisdiction or authority. 379 | 380 | ======================================================================= 381 | 382 | Creative Commons is not a party to its public 383 | licenses. Notwithstanding, Creative Commons may elect to apply one of 384 | its public licenses to material it publishes and in those instances 385 | will be considered the “Licensor.” The text of the Creative Commons 386 | public licenses is dedicated to the public domain under the CC0 Public 387 | Domain Dedication. Except for the limited purpose of indicating that 388 | material is shared under a Creative Commons public license or as 389 | otherwise permitted by the Creative Commons policies published at 390 | creativecommons.org/policies, Creative Commons does not authorize the 391 | use of the trademark "Creative Commons" or any other trademark or logo 392 | of Creative Commons without its prior written consent including, 393 | without limitation, in connection with any unauthorized modifications 394 | to any of its public licenses or any other arrangements, 395 | understandings, or agreements concerning use of licensed material. For 396 | the avoidance of doubt, this paragraph does not form part of the 397 | public licenses. 398 | 399 | Creative Commons may be contacted at creativecommons.org. 400 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This repository contains the code for the paper: Code Completion by Feeding Trees to Transformers. 2 | 3 | **This repo is _not_ actively maintained.** 4 | 5 | If you use our code/implementation, please cite our paper: https://arxiv.org/abs/2003.13848 6 | 7 | 8 | # Dataset 9 | 10 | **generate_new_trees.py**: a preprocessing script that converts the ASTs in py150 dataset (https://www.sri.inf.ethz.ch/phog) to modified ASTs, explained further below in **Modifying the AST**. 11 | 12 | **generate_vocab.py**: a script that creates the vocab corpus. In our models, we took the top 100k common vocab to be in the corpus; all other vocab is replaced by . 13 | 14 | **models\/\\/generate_data.py**: the scripts to generate datasets can be found in the models directory, for all the different models (TravTrans, PathTrans, SeqTrans, SeqRNN). Note that the inputs for SeqTrans and SeqRNN are the same. This script will handle separating out the long trees into subtrees using a sliding window, as explained below in **Splitting Large Trees**. In our implementation, n_context = 1000. 15 | 16 | **models\/trav_trans\/generate_ast_ids.py**: a script to generate index locations for certain predictions in the dataset for the AST-based models (TravTrans). Can get indices for: 17 | - specific values (Table 9): predicting indices for attribute access, name (varialbe, module), numeric constant, function parameter name. 18 | - specific types (Table 10): predicting indices for function call, assign, return, list, dictionary, raise. 19 | - All values / types (Table 6): predicting indices for all values (leaf nodes) and all types (internal nodes). 20 | 21 | **models\/seq\/generate_data.py**: a script that is also used to generate index locations for certain predictions in the dataset for the source code-based models (SeqTrans, SeqRNN). Can get indices for: 22 | - specific values (Table 9): same definition as above 23 | - All values (Table 6): predicting indices for all equivalent leaf nodes of the AST (equivalent to All values, as explained above). 24 | 25 | **dataset.py**: contains class objects (BaseSetup, BaseVocab, BaseDataset) for setting up the dataset and vocab for the model. Each model inherits from these class objects to fit the model's specific setup requirements. The BaseDataset object also contains the collate function for processing batches. 26 | 27 | **train.py**: contains code to carry out the training and report intermittent metrics. The entry point into this code is the train(...) function which should be called from a run script. 28 | 29 | # Model 30 | **model.py** contains the models used in this paper. SeqRNN uses **LSTMModel**, and the other models 31 | except Code2seq use **TransformerModel**. We used the following hyperparameters for our implementation: 32 | - n_layer = 6 33 | - n_embd = 300 34 | - n_head = 6 35 | - layer_norm_epsilon = 1e-6, 36 | - lr = 1e-3 37 | 38 | **code2seq/code2seq_model.py** contains the code2seq PyTorch adaption. We used the same hyperparameters as the one 39 | from the original work, except changing the number of vocab to 100k to stay consistent with the other 40 | models used in the paper. 41 | 42 | # Data processing Information 43 | 44 | ## Modifying the AST 45 | For the AST, we want the internal AST nodes to only have type information, and the leaf nodes to have value information. This way, our model can predict one information given a node (instead of both type and value). However, in the py150 dataset, there are internal and leaf nodes with both type and value information. To accomodate for this, we slightly modify the trees to fit our definition of ASTs. For nodes with both type and value information, we take the value information, and create a new node (now a leaf node) as the node's first child. Figure below illustrates an example of the modification. This increases the average number of nodes in a tree from 623.4 to 951.9. 46 | 47 | Before: 48 | 49 | 50 | Type:AttributeLoad 51 | 0 52 | / \ 53 | / \ 54 | Type: NameLoad Type: Attr 55 | Value: logging Value: getLogger 56 | 1 2 57 | 58 | 59 | After: 60 | 61 | 62 | Type:AttributeLoad 63 | 0 64 | / \ 65 | / \ 66 | Type: NameLoad Type: Attr 67 | 1 3 68 | | | 69 | | | 70 | Value: logging Value: getLogger 71 | 2 4 72 | 73 | 74 | ## Splitting Large Trees 75 | For neural network models, we need to set a maximum number of nodes in the tree that the model can take as input. Ideally, we would want to set the maximum to be high enough to take in any tree of any length; however, in practice, this is infeasible due to memory constraints (and the number of nodes could be infinitely large hypothetically.) We choose the maximum number of context (number of nodes) to be 1000, inspired by the maximum number of context set by GPT2 models and as this covers > 70% of the training data. For trees with number of nodes greater than 1000, we deploy a technique adopted by [1]. Given a large tree, we slice it into shorter segments with a sliding window (in our implementation, we used 500, which is half the context). For example, if a tree has 1700 nodes, we would have 3 new shorter trees: from nodes 0-999, nodes 500-1499, and 699-1699. For the last two trees, we would take loss and evaluate only on the nodes that the model has not seen before (1000-1499 and 1500-1699, respectively). In this way, we provide each subsequent shorter segment with some previous context, while increasing the number of training and testing datapoints at a reasonable amount (in our datasets, it doubled the number). An improvement to this sliding window technique would be to maintain the hidden states at each segment to pass along more context information, as explained in [2]. 76 | 77 | 78 | [1] [Character-Level Language Modeling with Deeper Self-Attention](https://arxiv.org/abs/1808.04444): Rami Al-Rfou, Dokook Choe, Noah Constant, Mandy Guo, Llion Jones. 79 | 80 | [2] [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://arxiv.org/abs/1901.02860): Zihang Dai, Zhilin Yang, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov 81 | 82 | 83 | # License 84 | Code-Prediction-Transformer is CC-BY-NC 4.0 (Attr Non-Commercial Inter.) (e.g., FAIR) licensed, as found in the LICENSE file. 85 | -------------------------------------------------------------------------------- /code2seq/code2seq_model.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) 2019 Technion 3 | # Copyright (c) Facebook, Inc. and its affiliates. 4 | # ---------------------------------------------------------------------------- 5 | # MIT License 6 | 7 | # Permission is hereby granted, free of charge, to any person obtaining a copy 8 | # of this software and associated documentation files (the "Software"), to deal 9 | # in the Software without restriction, including without limitation the rights 10 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | # copies of the Software, and to permit persons to whom the Software is 12 | # furnished to do so, subject to the following conditions: 13 | 14 | # The above copyright notice and this permission notice shall be included in all 15 | # copies or substantial portions of the Software. 16 | 17 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 | # SOFTWARE. 24 | # ---------------------------------------------------------------------------- 25 | """ 26 | Code2seq model is adapted from: https://github.com/tech-srl/code2seq 27 | """ 28 | 29 | import torch 30 | import torch.nn as nn 31 | import torch.nn.functional as F 32 | 33 | 34 | 35 | class EmbeddingAttentionLayer(nn.Module): 36 | def __init__(self, dim: int) -> None: 37 | super().__init__() 38 | self.dim = dim 39 | self.attention = torch.randn(1, dim) 40 | self.attention = nn.Parameter(self.attention) 41 | 42 | def compute_weights(self, embedded: torch.Tensor) -> torch.Tensor: 43 | unnormalized_weights = embedded.matmul(self.attention.t()) 44 | attention_weights = F.softmax(unnormalized_weights, dim=1) 45 | return attention_weights 46 | 47 | def forward(self, embedded: torch.Tensor) -> torch.Tensor: 48 | attention_weights = self.compute_weights(embedded) 49 | weighted = torch.bmm(attention_weights.transpose(1, 2), embedded) 50 | return weighted 51 | 52 | 53 | class Code2SeqModel(nn.Module): 54 | def __init__( 55 | self, 56 | token_vocab_size: int, 57 | subtoken_vocab_size: int, 58 | output_vocab_size: int, 59 | token_pad_idx: int, 60 | subtoken_pad_idx: int, 61 | loss_fn: nn.Module, 62 | n_embd: int = 128, 63 | rnn_dropout: float = 0.5, 64 | embed_dropout: float = 0.25, 65 | ): 66 | super().__init__() 67 | self.subtoken_embedding = nn.Embedding( 68 | subtoken_vocab_size, n_embd, padding_idx=subtoken_pad_idx 69 | ) 70 | self.node_embedding = nn.Embedding( 71 | token_vocab_size, n_embd, padding_idx=token_pad_idx 72 | ) 73 | self.path_lstm = nn.LSTM( 74 | n_embd, n_embd, bidirectional=True, dropout=rnn_dropout, batch_first=True 75 | ) 76 | self.combined_layer = nn.Linear(n_embd * 4, n_embd) 77 | self.dropout = nn.Dropout(embed_dropout) 78 | self.attn_layer = EmbeddingAttentionLayer(n_embd) 79 | self.out_layer = nn.Linear(n_embd, output_vocab_size) 80 | 81 | self.loss_fn = loss_fn 82 | 83 | def reset_parameters(self): 84 | for p in self.parameters(): 85 | if p.dim() > 1: 86 | nn.init.xavier_uniform_(p) 87 | 88 | def embed_paths(self, paths): 89 | path_tokens_embedded = self.node_embedding(paths) 90 | batch_size, bag_size, path_len, _ = path_tokens_embedded.shape 91 | path_tokens_embedded = path_tokens_embedded.view( 92 | (batch_size * bag_size, path_len, -1) 93 | ) 94 | out, (h, c) = self.path_lstm(path_tokens_embedded) 95 | paths_embedded = h.permute((1, 0, 2)).reshape(batch_size, bag_size, -1) 96 | return paths_embedded 97 | 98 | def embed_subtokens(self, subtokens): 99 | tokens_embedded = self.subtoken_embedding(subtokens) 100 | return tokens_embedded.sum(2) 101 | 102 | def forward(self, starts, paths, ends, targets, return_loss=False): 103 | # embed individual parts 104 | starts_embedded = self.embed_subtokens(starts) 105 | paths_embedded = self.embed_paths(paths) 106 | ends_embedded = self.embed_subtokens(ends) 107 | 108 | # combine by concacenating 109 | combined_embedded = torch.cat( 110 | (starts_embedded, paths_embedded, ends_embedded), dim=2 111 | ) 112 | combined_embedded = self.dropout(combined_embedded) 113 | combined_embedded = torch.tanh(self.combined_layer(combined_embedded)) 114 | 115 | # combine paths by simple attention 116 | code_embedded = self.attn_layer(combined_embedded).squeeze() 117 | y_pred = self.out_layer(code_embedded) 118 | 119 | if not return_loss: 120 | return y_pred 121 | return self.loss_fn(y_pred, targets) 122 | -------------------------------------------------------------------------------- /code2seq/dataset.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import json 9 | import logging 10 | 11 | import torch 12 | import utils 13 | 14 | 15 | logging.basicConfig(level=logging.INFO) 16 | 17 | 18 | UNK = "" 19 | PAD = "" 20 | PLACEHOLDER = "" 21 | 22 | 23 | class Dataset(torch.utils.data.Dataset): 24 | def __init__(self, fp): 25 | super().__init__() 26 | self.fp = fp 27 | self._line_pos_dp = list(utils.line_positions(fp)) 28 | 29 | def __len__(self): 30 | return len(self._line_pos_dp) 31 | 32 | def __getitem__(self, idx): 33 | line_pos = self._line_pos_dp[idx] 34 | with open(self.fp) as f: 35 | f.seek(line_pos) 36 | dp_line = json.loads(f.readline().strip()) 37 | return dp_line 38 | 39 | @staticmethod 40 | def collate(batch, token_pad_idx, subtoken_pad_idx): 41 | def combine(seqs, max_len, max_path_len, pad_idx): 42 | if not seqs: 43 | return torch.ones((max_len, max_path_len)).long() * pad_idx 44 | paths = [] 45 | for path in seqs: 46 | paths.append(path + [pad_idx] * (max_path_len - len(path))) 47 | len_pad = torch.ones((max_len - len(paths), max_path_len)).long() 48 | return torch.cat((torch.tensor(paths), len_pad)) 49 | 50 | max_len = max(len(i[1]) for i in batch) 51 | max_start_len = max( 52 | max([len(start) for start in seq[1]], default=0) for seq in batch 53 | ) 54 | max_path_len = max( 55 | max([len(path) for path in seq[2]], default=0) for seq in batch 56 | ) 57 | max_end_len = max( 58 | max([len(start) for start in seq[3]], default=0) for seq in batch 59 | ) 60 | all_targets = [] 61 | all_starts = [] 62 | all_paths = [] 63 | all_ends = [] 64 | 65 | for (target, starts, paths, ends) in batch: 66 | all_targets.append(target) 67 | starts = combine(starts, max_len, max_start_len, subtoken_pad_idx) 68 | paths = combine(paths, max_len, max_path_len, token_pad_idx) 69 | ends = combine(ends, max_len, max_end_len, subtoken_pad_idx) 70 | 71 | all_starts.append(starts) 72 | all_ends.append(ends) 73 | all_paths.append(paths) 74 | 75 | results = { 76 | "targets": torch.tensor(all_targets), 77 | "starts": torch.stack(all_starts), 78 | "paths": torch.stack(all_paths), 79 | "ends": torch.stack(all_ends), 80 | } 81 | return results 82 | -------------------------------------------------------------------------------- /code2seq/generate_data.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import json 3 | import os 4 | import pickle 5 | import random 6 | import re 7 | from collections import defaultdict 8 | from itertools import chain, combinations, product 9 | 10 | from utils import get_ancestors, get_terminal_nodes, parallelize, tokenize 11 | from tqdm import tqdm 12 | 13 | 14 | PLACEHOLDER = "" 15 | UNK = "" 16 | 17 | 18 | def get_leaf_nodes(ast, id_type): 19 | # get ids for special leaf types: attr, num, name, param 20 | if id_type == "attr": 21 | types_ = {"attr"} 22 | elif id_type == "num": 23 | types_ = {"Num"} 24 | elif id_type == "name": 25 | types_ = {"NameLoad", "NameStore"} 26 | elif id_type == "param": 27 | types_ = {"NameParam"} 28 | 29 | nodes = [] 30 | for i, node in enumerate(ast): 31 | if "type" in node and node["type"] in types_: 32 | nodes.append(i + 1) 33 | return nodes 34 | 35 | 36 | def get_value(d): 37 | return d["value"] if "value" in d else d["type"] 38 | 39 | 40 | def extract_paths(ast, max_length): 41 | def dfs(i): 42 | node = ast[i] 43 | if "children" not in node: 44 | full_paths = [] 45 | half_paths = [[i]] 46 | else: 47 | children = node["children"] 48 | child_to_full_paths, child_to_half_paths = zip( 49 | *(dfs(child_id) for child_id in children) 50 | ) 51 | full_paths = list(chain.from_iterable(child_to_full_paths)) 52 | for i_child in range(len(children) - 1): 53 | for j_child in range(i_child + 1, len(children)): 54 | i_child_half_paths = child_to_half_paths[i_child] 55 | j_child_half_paths = child_to_half_paths[j_child] 56 | for i_half_path, j_half_path in product( 57 | i_child_half_paths, j_child_half_paths 58 | ): 59 | path_len = len(i_half_path) + len(j_half_path) + 1 60 | if path_len > max_length: 61 | continue 62 | path = list(chain(i_half_path, [i], reversed(j_half_path))) 63 | full_paths.append(path) 64 | half_paths = [ 65 | half_path + [i] 66 | for half_path in chain.from_iterable(child_to_half_paths) 67 | if len(half_path) + 1 < max_length 68 | ] 69 | return full_paths, half_paths 70 | 71 | return dfs(0)[0] 72 | 73 | 74 | def get_all_paths(ast, id_type, max_path_len, max_num_paths): 75 | if id_type == "leaves": 76 | nodes = get_terminal_nodes(ast) 77 | else: 78 | nodes = get_leaf_nodes(ast, id_type) 79 | if not nodes: 80 | return [] 81 | 82 | all_paths = extract_paths(ast, max_path_len) 83 | ast_values = [get_value(i) for i in ast] 84 | terminal_words = [get_value(ast[i]) for i in get_terminal_nodes(ast)] 85 | tokenized_words = {word: tokenize(word) for word in terminal_words} 86 | node_to_path_idx = {i: [] for i in range(len(ast))} 87 | for i, path in enumerate(all_paths): 88 | node_to_path_idx[path[-1]].append(i) 89 | 90 | dps = [] 91 | paths_to_choose_from = [] 92 | prev_node = 0 93 | for node in nodes: 94 | for j in range(prev_node, node): 95 | paths_to_choose_from += [ 96 | all_paths[path_i] for path_i in node_to_path_idx[j] 97 | ] 98 | prev_node = node 99 | 100 | paths_to_here = [all_paths[path_i] for path_i in node_to_path_idx[node]] 101 | if len(paths_to_choose_from) + len(paths_to_here) <= max_num_paths: 102 | paths = paths_to_choose_from.copy() + paths_to_here 103 | else: 104 | if len(paths_to_here) > max_num_paths: 105 | paths = random.sample(paths_to_here, max_num_paths) 106 | else: 107 | paths = paths_to_here + random.sample( 108 | paths_to_choose_from, max_num_paths - len(paths_to_here) 109 | ) 110 | 111 | # convert to vocab 112 | target = ast_values[node] 113 | paths = [ 114 | [ast_values[i] if i != node else PLACEHOLDER for i in p] for p in paths 115 | ] 116 | lefts = [tokenized_words[p[0]] for p in paths] 117 | rights = [ 118 | tokenized_words[p[-1]] if p[-1] != PLACEHOLDER else [PLACEHOLDER] 119 | for p in paths 120 | ] 121 | dps.append([target, lefts, paths, rights]) 122 | return dps 123 | 124 | 125 | def get_word2idx(out_fp): 126 | with open(out_fp, "rb") as fin: 127 | vocab = pickle.load(fin) 128 | word2idx = {word: i for i, word in enumerate(vocab)} 129 | word2idx = defaultdict(lambda: word2idx[UNK], word2idx) 130 | print("Read vocab from: {}".format(out_fp)) 131 | return word2idx 132 | 133 | 134 | def main(): 135 | parser = argparse.ArgumentParser( 136 | description="Generate terminal to terminal paths from AST" 137 | ) 138 | parser.add_argument("--ast_fp", "-a", help="Filepath with the ASTs to be parsed") 139 | parser.add_argument( 140 | "--out_fp", "-o", default="/tmp/dps.txt", help="Filepath for the output dps" 141 | ) 142 | parser.add_argument("--max_path_len", type=int, default=9, help="Max path len.") 143 | parser.add_argument("--max_num_paths", type=int, default=200) 144 | parser.add_argument("--base_dir", "-b", type=str) 145 | parser.add_argument( 146 | "id_type", 147 | choices=["attr", "num", "name", "param", "leaves"], 148 | default="attr", 149 | help="Which ids to generate. Default = attr", 150 | ) 151 | args = parser.parse_args() 152 | print("Max path len: {}".format(args.max_path_len)) 153 | print("Max num paths: {}".format(args.max_num_paths)) 154 | print("Writing to {}".format(args.out_fp)) 155 | 156 | # read the vocabs 157 | base_dir = args.base_dir 158 | token_vocab = get_word2idx(os.path.join(base_dir, "token_vocab.pkl")) 159 | subtoken_vocab = get_word2idx(os.path.join(base_dir, "subtoken_vocab.pkl")) 160 | output_vocab = get_word2idx(os.path.join(base_dir, "output_vocab.pkl")) 161 | 162 | data = [] 163 | i = 0 164 | c = 0 165 | with open(args.ast_fp, "r") as f, open(args.out_fp, "w") as fout: 166 | for _ in range(20): 167 | i += 1 168 | print("Starting {} / 50".format(i)) 169 | for _ in range(5000): 170 | dp = json.loads(f.readline().strip()) 171 | if len(dp) <= 1: 172 | continue 173 | data.append(dp) 174 | print(" > Finished reading: {}".format(len(data))) 175 | for ast in tqdm(data): 176 | dp = get_all_paths(ast, args.id_type, args.max_path_len, args.max_num_paths) 177 | for target, lefts, paths, rights in dp: 178 | target = output_vocab[target] 179 | lefts = [[subtoken_vocab[t] for t in lst] for lst in lefts] 180 | paths = [[token_vocab[t] for t in lst] for lst in paths] 181 | rights = [[subtoken_vocab[t] for t in lst] for lst in rights] 182 | 183 | json.dump([target, lefts, paths, rights], fout) 184 | fout.write("\n") 185 | c += 1 186 | data = [] 187 | print(" > Finished writing to file") 188 | print("Wrote {} datapoints to {}".format(c, args.out_fp)) 189 | 190 | 191 | if __name__ == "__main__": 192 | main() 193 | -------------------------------------------------------------------------------- /code2seq/generate_vocab.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import argparse 9 | import json 10 | import logging 11 | import pickle 12 | import re 13 | from collections import Counter 14 | 15 | from utils import get_terminal_nodes, file_tqdm, tokenize 16 | 17 | 18 | logging.basicConfig(level=logging.INFO) 19 | 20 | 21 | UNK = "" 22 | PAD = "" 23 | PLACEHOLDER = "" 24 | 25 | 26 | def get_value(line, vocab_type): 27 | if vocab_type == "token": 28 | return get_dfs(line) 29 | elif vocab_type == "subtoken": 30 | lst = [] 31 | for node in get_terminal_nodes(line): 32 | lst += tokenize(node) 33 | return lst 34 | elif vocab_type == "output": 35 | return get_terminal_nodes(line) 36 | 37 | 38 | def main(): 39 | parser = argparse.ArgumentParser( 40 | description="Create vocab for code2seq model for py150 dataset" 41 | ) 42 | parser.add_argument("--n_vocab", "-n", type=int, default=100000) 43 | parser.add_argument("--input_fp", "-i") 44 | parser.add_argument("--out_fp", "-o", default="/tmp/vocab.pkl") 45 | parser.add_argument( 46 | "--vocab_type", 47 | "-v", 48 | choices=["token", "subtoken", "output"], 49 | help="What type of vocab to get", 50 | ) 51 | args = parser.parse_args() 52 | 53 | logging.info("Reading from: {}".format(args.input_fp)) 54 | logging.info("Vocab type: {}".format(args.vocab_type)) 55 | vocab = Counter() 56 | with open(args.input_fp, "r") as f: 57 | for line in file_tqdm(f): 58 | vocab.update(get_value(json.loads(line.strip()), args.vocab_type)) 59 | vocab_to_keep = [i[0] for i in vocab.most_common(args.n_vocab)] 60 | top_total = sum(i[1] for i in vocab.most_common(args.n_vocab)) 61 | total = sum(vocab.values()) 62 | 63 | logging.info("Total # of vocab: {}".format(len(vocab))) 64 | logging.info( 65 | "Using {} top vocab covers: {:.2f}% of the entire dataset".format( 66 | args.n_vocab, 100 * top_total / total 67 | ) 68 | ) 69 | logging.info("Top 10 most common vocab:") 70 | for v, i in vocab.most_common(10): 71 | print(v, i) 72 | 73 | # add unk and pad tokens 74 | vocab_to_keep.append(UNK) 75 | vocab_to_keep.append(PAD) 76 | vocab_to_keep.append(PLACEHOLDER) 77 | logging.info("Added {} and {} and {}".format(UNK, PAD, PLACEHOLDER)) 78 | 79 | # dump vocab to file 80 | with open(args.out_fp, "wb") as fout: 81 | pickle.dump(vocab_to_keep, fout) 82 | logging.info("Wrote {} vocab to: {}".format(len(vocab_to_keep), args.out_fp)) 83 | 84 | 85 | if __name__ == "__main__": 86 | main() -------------------------------------------------------------------------------- /dataset.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import json 9 | import logging 10 | import os 11 | import pickle 12 | 13 | import torch 14 | import utils 15 | 16 | 17 | logging.basicConfig(level=logging.INFO) 18 | 19 | 20 | UNK = "" 21 | PAD = "" 22 | 23 | 24 | class BaseSetup(object): 25 | def __init__( 26 | self, base_dir, fp, ids_fp, max_vocab=100000, mode="train" 27 | ): 28 | super().__init__() 29 | if mode not in {"train", "test"}: 30 | raise Exception("Mode must be either train or test") 31 | self.mode = mode 32 | self.fp = fp 33 | self.max_vocab = max_vocab 34 | 35 | # get all the relevant filepaths 36 | self.filepaths = { 37 | "vocab": os.path.join(base_dir, "vocab.pkl"), 38 | "metrics": os.path.join(base_dir, "{}_metrics.txt".format(mode)), 39 | "conv": os.path.join(base_dir, "{}_converted.txt".format(mode)), 40 | } 41 | self._add_extra_filepaths(base_dir) 42 | 43 | logging.info("Writing metrics to: {}".format(self.filepaths["metrics"])) 44 | 45 | # filter dataset 46 | filtered_fp = self._filter_dataset() 47 | 48 | # set up vocab 49 | self.vocab = self._create_vocab() 50 | 51 | # convert 52 | if not os.path.exists(self.filepaths["conv"]): 53 | with open(filtered_fp, "r") as fin, open( 54 | self.filepaths["conv"], "w" 55 | ) as fout: 56 | for line in utils.file_tqdm(fin): 57 | line = json.loads(line.strip()) 58 | print(json.dumps(self.vocab.convert(line)), file=fout) 59 | logging.info( 60 | "Converted dataset to idx and saved to: {}".format( 61 | self.filepaths["conv"] 62 | ) 63 | ) 64 | 65 | # return dataset 66 | self.dataset = self._create_dataset(self.filepaths["conv"], ids_fp) 67 | logging.info("Loaded dataset from {}".format(self.filepaths["conv"])) 68 | 69 | def return_data(self): 70 | return self.vocab, self.dataset, self.filepaths["metrics"] 71 | 72 | def _add_extra_filepaths(self, base_dir): 73 | return 74 | 75 | def _filter_dataset(self): 76 | return self.fp 77 | 78 | def _create_vocab(self): 79 | raise NotImplementedError("method must be implemented by a subclass.") 80 | 81 | def _create_dataset(self, fp, ids_fp): 82 | raise NotImplementedError("method must be implemented by a subclass.") 83 | 84 | 85 | class BaseVocab(object): 86 | def __init__(self, vocab_fp): 87 | super().__init__() 88 | self.unk_token = UNK 89 | self.pad_token = PAD 90 | self.pad_idx = None 91 | self.unk_idx = None 92 | 93 | if not os.path.exists(vocab_fp): 94 | raise Exception("Get the vocab from generate_vocab.py") 95 | 96 | with open(vocab_fp, "rb") as fin: 97 | self.idx2vocab = pickle.load(fin) 98 | logging.info("Loaded vocab from: {}".format(vocab_fp)) 99 | self.vocab2idx = {token: i for i, token in enumerate(self.idx2vocab)} 100 | self.unk_idx = self.vocab2idx[self.unk_token] 101 | self.pad_idx = self.vocab2idx[self.pad_token] 102 | logging.info("Vocab size: {}".format(len(self.idx2vocab))) 103 | 104 | def __len__(self): 105 | return len(self.idx2vocab) 106 | 107 | def convert(self, line): 108 | raise NotImplementedError("method must be implemented by a subclass.") 109 | 110 | 111 | class BaseDataset(torch.utils.data.Dataset): 112 | def __init__(self, fp, ids_fp): 113 | super().__init__() 114 | self.fp = fp 115 | self.ids_fp = ids_fp 116 | self._line_pos_dp = list(utils.line_positions(fp)) 117 | self._line_pos_ids = list(utils.line_positions(ids_fp)) 118 | assert (len(self._line_pos_dp) == len(self._line_pos_ids)) 119 | 120 | def __len__(self): 121 | return len(self._line_pos_dp) 122 | 123 | def __getitem__(self, idx): 124 | line_pos = self._line_pos_dp[idx] 125 | with open(self.fp) as f: 126 | f.seek(line_pos) 127 | dp_line = f.readline().strip() 128 | 129 | line_pos = self._line_pos_ids[idx] 130 | with open(self.ids_fp) as f: 131 | f.seek(line_pos) 132 | ids_line = f.readline().strip() 133 | return (json.loads(dp_line), json.loads(ids_line)) 134 | 135 | @staticmethod 136 | def collate(seqs, pad_idx=None): 137 | raise NotImplementedError("method must be implemented by a subclass.") 138 | -------------------------------------------------------------------------------- /demo.py: -------------------------------------------------------------------------------- 1 | 2 | #!/usr/bin/env python3 3 | 4 | # Copyright (c) Facebook, Inc. and its affiliates. 5 | # All rights reserved. 6 | # 7 | # This source code is licensed under the license found in the 8 | # LICENSE file in the root directory of this source tree. 9 | 10 | 11 | import LSTMModel 12 | import Dataset, Vocab 13 | 14 | import json 15 | import os 16 | import torch 17 | import argparse 18 | import logging 19 | 20 | def predict_with_seq(seq, converted=False, ): 21 | rel = None 22 | if not converted: 23 | seq = vocab.convert([seq, 0]) # [data, ext] is the format expected 24 | seqs = [[seq, {}]] # the {} is a mapping of attr/leaf locations, not needed here 25 | batch = Dataset.collate(seqs, pad_idx) 26 | x = batch["input_seq"] 27 | y = batch["target_seq"] 28 | ext = batch["extended"] 29 | y_pred = model(x, y, ext, rel=rel, return_loss=False) 30 | return y_pred.squeeze() 31 | 32 | def get_top_pred(pred, k=10, print_results=True): 33 | softmax = torch.nn.Softmax() 34 | top_perc, top_idx = torch.topk(softmax(pred), k) 35 | top_perc = top_perc.tolist() 36 | top_tokens = [vocab.idx2vocab[i] for i in top_idx] 37 | 38 | if print_results: 39 | print('Top {} predictions:'.format(k)) 40 | for i, (perc, token) in enumerate(zip(top_perc, top_tokens)): 41 | print('{}) {:<12} ({:.2f}%)'.format(i + 1, token, 100 * perc)) 42 | return top_perc, top_tokens 43 | 44 | def predict_next(input_seq, k=10, print_results=False): 45 | y_pred = predict_with_seq(input_seq + ['']) 46 | top_perc, top_tokens = get_top_pred(y_pred[-1], k, print_results) 47 | return top_perc, top_tokens 48 | 49 | 50 | def demo_sequence(input_seq): 51 | print(' '.join(input_seq)) 52 | top_perc, top_tokens = predict_next(input_seq, print_results=True) 53 | 54 | def demo_datapoint(data, dp_raw, idxs, converted=False, print_results=True): 55 | k = 10 56 | # predict for the whole sequence in one shot 57 | y_pred = predict_with_seq(data, converted) 58 | for i in idxs: 59 | context = dp_raw[max(0, i-5): i] 60 | target = dp_raw[i] 61 | print('Context: {}'.format('...' + ' '.join(context))) 62 | print('Target : {}'.format(target)) 63 | top_perc, top_tokens = get_top_pred(y_pred[i-1], k, print_results) 64 | rank = top_tokens.index(target) if target in top_tokens else -2 65 | print('Rank : {}'.format(rank + 1)) 66 | print() 67 | 68 | def parse_args(): 69 | parser = argparse.ArgumentParser(description="Demo for a trained model") 70 | parser.add_argument("--base_dir", "-b", default="/tmp/gpt2") 71 | parser.add_argument("--model_fp", "-m", default="rnn.pth", help="Relative fp to best_model") 72 | parser.add_argument("--vocab_fp", "-v", default="vocab.pkl", help="Relative fp to vocab pkl") 73 | parser.add_argument("--dps_fp", help="Test filepath with raw data points") 74 | parser.add_argument("--conv_fp", help="Test filepath with converted data points") 75 | parser.add_argument( 76 | "--ids_fp", help="Filepath with the ids that describe locations of various attrs/leaf/etc" 77 | ) 78 | args = parser.parse_args() 79 | logging.info("Base dir: {}".format(args.base_dir)) 80 | return args 81 | 82 | def main(): 83 | 84 | global vocab 85 | global model 86 | global pad_idx 87 | 88 | args = parse_args() 89 | base_dir = args.base_dir 90 | model_fp = os.path.join(base_dir, args.model_fp) 91 | vocab = Vocab(os.path.join(base_dir, args.vocab_fp)) 92 | pad_idx = vocab.pad_idx 93 | loss_fn = torch.nn.CrossEntropyLoss(ignore_index=vocab.pad_idx) 94 | n_ctx=100 95 | 96 | model = LSTMModel( 97 | vocab_size=len(vocab), 98 | n_embd=300, 99 | loss_fn=loss_fn, 100 | n_ctx=n_ctx, 101 | ) 102 | print('Created {} model!'.format(model_fp)) 103 | 104 | # load model 105 | new_checkpoint = {} 106 | checkpoint = torch.load(model_fp, map_location=torch.device('cpu')) 107 | for name, weights in checkpoint.items(): 108 | name = name.replace('module.', '') 109 | new_checkpoint[name] = weights 110 | del checkpoint 111 | 112 | model.load_state_dict(new_checkpoint) 113 | model.eval() 114 | 115 | print('Loaded model from:', model_fp) 116 | 117 | 118 | # 1. Try prediction with some made up sequence 119 | input_seq = ['with', 'open', '(', 'raw_fp', ',', '"r"', ')', 'as', 'fin', ':', 'data_raw', '=', '[', 'json', '.', ] 120 | demo_sequence(input_seq) 121 | demo_sequence(input_seq + ['loads']) 122 | 123 | # 2. Prediction on a sample from our dataset 124 | 125 | # read dataset 126 | if (args.dps_fp is not None): 127 | raw_fp = os.path.join(base_dir, args.dps_fp) 128 | with open(raw_fp, 'r') as fin: 129 | data_raw = [json.loads(line) for line in fin.readlines()] 130 | print('Read {} datapoints!'.format(len(data_raw))) 131 | # TODO make these random 132 | dp_i = 231 133 | idx = 50 134 | print('Raw data point [data, ext] = ', data_raw[dp_i]) 135 | dp_raw = data_raw[dp_i][0] # data_raw[dp_i][1] is an ext, we don't need it 136 | demo_datapoint(dp_raw, dp_raw, {idx}, converted=False) 137 | else: 138 | return 139 | 140 | # we can also predict from pred-converted data points 141 | if (args.conv_fp is not None): 142 | conv_fp = os.path.join(base_dir, args.conv_fp) 143 | with open(conv_fp, 'r') as fin: 144 | data_conv = [json.loads(line) for line in fin.readlines()] 145 | print('Converted data point [data, ext] = ', data_conv[dp_i]) 146 | demo_datapoint(data_conv[dp_i], dp_raw, {idx}, converted=True) 147 | 148 | # let's focus on the attrs in this data point 149 | if (args.ids_fp is not None): 150 | ids_fp = os.path.join(base_dir, args.ids_fp) 151 | with open(ids_fp, 'r') as fin: 152 | data_ids = [json.loads(line) for line in fin.readlines()] 153 | print('Datapoint:\n{} .... '.format(' '.join(dp_raw[:100]))) 154 | print('# of value predictions:') 155 | for name, lst in data_ids[dp_i].items(): 156 | print('{}: {}'.format(name, len(lst))) 157 | attrs = data_ids[dp_i]["attr_ids"] 158 | demo_datapoint(dp_raw, dp_raw, attrs, converted=False, print_results=False) 159 | 160 | 161 | if __name__ == "__main__": 162 | main() 163 | -------------------------------------------------------------------------------- /generate_new_trees.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import argparse 9 | import json 10 | import logging 11 | import os 12 | 13 | from utils import file_tqdm 14 | 15 | 16 | logging.basicConfig(level=logging.INFO) 17 | 18 | 19 | def convert(ast): 20 | increase_by = {} # count of how many idx to increase the new idx by: 21 | # each time there is a value node 22 | cur = 0 23 | for i, node in enumerate(ast): 24 | increase_by[i] = cur 25 | if "value" in node: 26 | cur += 1 27 | 28 | new_dp = [] 29 | for i, node in enumerate(ast): 30 | inc = increase_by[i] 31 | if "value" in node: 32 | child = [i + inc + 1] 33 | if "children" in node: 34 | child += [n + increase_by[n] for n in node["children"]] 35 | new_dp.append({"type": node["type"], "children": child}) 36 | new_dp.append({"value": node["value"]}) 37 | else: 38 | if "children" in node: 39 | node["children"] = [n + increase_by[n] for n in node["children"]] 40 | new_dp.append(node) 41 | 42 | # sanity check 43 | children = [] 44 | for node in new_dp: 45 | if "children" in node: 46 | children += node["children"] 47 | assert len(children) == len(set(children)) 48 | return new_dp 49 | 50 | 51 | def main(): 52 | parser = argparse.ArgumentParser(description="Generate datapoints from AST") 53 | parser.add_argument("--input_fp", "-i", help="Filepath with the ASTs to be parsed") 54 | parser.add_argument( 55 | "--out_fp", 56 | "-o", 57 | default="/tmp/new_trees.json", 58 | help="Filepath with the output dps", 59 | ) 60 | 61 | args = parser.parse_args() 62 | if os.path.exists(args.out_fp): 63 | os.remove(args.out_fp) 64 | 65 | logging.info("Loading asts from: {}".format(args.input_fp)) 66 | with open(args.input_fp, "r") as f, open(args.out_fp, "w") as fout: 67 | for line in file_tqdm(f): 68 | dp = json.loads(line.strip()) 69 | print(json.dumps(convert(dp)), file=fout) 70 | logging.info("Wrote dps to: {}".format(args.out_fp)) 71 | 72 | 73 | if __name__ == "__main__": 74 | main() 75 | -------------------------------------------------------------------------------- /generate_vocab.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import argparse 9 | import json 10 | import logging 11 | import pickle 12 | from collections import Counter 13 | 14 | from utils import file_tqdm, get_dfs 15 | 16 | 17 | logging.basicConfig(level=logging.INFO) 18 | 19 | 20 | UNK = "" 21 | PAD = "" 22 | 23 | 24 | def get_value(line, input_type): 25 | if input_type == "ast": 26 | return get_dfs(line) 27 | elif input_type == "leaf": 28 | return get_dfs(line, only_leaf=True) 29 | elif input_type == "source_code": 30 | return line[0] 31 | 32 | 33 | def main(): 34 | parser = argparse.ArgumentParser(description="Create vocab for py150 dataset") 35 | parser.add_argument("--n_vocab", "-n", type=int, default=100000) 36 | parser.add_argument("--input_fp", "-i") 37 | parser.add_argument("--out_fp", "-o", default="/tmp/vocab.pkl") 38 | parser.add_argument( 39 | "--input_type", 40 | "-t", 41 | choices=["ast", "leaf", "source_code"], 42 | help="Where to get the input from (all AST nodes, leaf nodes, or source code", 43 | ) 44 | args = parser.parse_args() 45 | 46 | logging.info("Reading from: {}".format(args.input_fp)) 47 | logging.info("Input type: {}".format(args.input_type)) 48 | vocab = Counter() 49 | with open(args.input_fp, "r") as f: 50 | for line in file_tqdm(f): 51 | vocab.update(get_value(json.loads(line.strip()), args.input_type)) 52 | vocab_to_keep = [i[0] for i in vocab.most_common(args.n_vocab)] 53 | top_total = sum(i[1] for i in vocab.most_common(args.n_vocab)) 54 | total = sum(vocab.values()) 55 | 56 | logging.info("Total # of vocab: {}".format(len(vocab))) 57 | logging.info( 58 | "Using {} top vocab covers: {:.2f}% of the entire dataset".format( 59 | args.n_vocab, 100 * top_total / total 60 | ) 61 | ) 62 | logging.info("Top 10 most common vocab:") 63 | for v, i in vocab.most_common(10): 64 | print(v, i) 65 | 66 | # add unk and pad tokens 67 | vocab_to_keep.append(UNK) 68 | vocab_to_keep.append(PAD) 69 | logging.info("Added {} and {}".format(UNK, PAD)) 70 | 71 | # dump vocab to file 72 | with open(args.out_fp, "wb") as fout: 73 | pickle.dump(vocab_to_keep, fout) 74 | logging.info("Wrote {} vocab to: {}".format(len(vocab_to_keep), args.out_fp)) 75 | 76 | 77 | if __name__ == "__main__": 78 | main() 79 | -------------------------------------------------------------------------------- /model.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) 2019 OpenAI, HugginFace Inc. team. and TaeHwan Jung 3 | # Copyright (c) Facebook, Inc. and its affiliates. 4 | # ---------------------------------------------------------------------------- 5 | # MIT LICENSE 6 | # 7 | # Permission is hereby granted, free of charge, to any person obtaining a copy 8 | # of this software and associated documentation files (the "Software"), to deal 9 | # in the Software without restriction, including without limitation the rights 10 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | # copies of the Software, and to permit persons to whom the Software is 12 | # furnished to do so, subject to the following conditions: 13 | 14 | # The above copyright notice and this permission notice shall be included in all 15 | # copies or substantial portions of the Software. 16 | 17 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 | # SOFTWARE. 24 | # ---------------------------------------------------------------------------- 25 | """ 26 | Transformer model is adapted from: https://github.com/graykode/gpt-2-Pytorch 27 | (Commit: 46ae886391a94c6683be438269252c4afd5ba762) 28 | Original Paper and repository here: https://github.com/openai/gpt-2 29 | 30 | RNN implementation is adapted from: https://github.com/pytorch/examples/tree/master/word_language_model 31 | """ 32 | 33 | import copy 34 | import math 35 | 36 | import torch 37 | import torch.nn as nn 38 | 39 | 40 | def gelu(x): 41 | return ( 42 | 0.5 43 | * x 44 | * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) 45 | ) 46 | 47 | 48 | class PathLSTM(nn.Module): 49 | def __init__(self, vocab_size, n_embd): 50 | super(PathLSTM, self).__init__() 51 | self.embedding = nn.Embedding(vocab_size, n_embd) 52 | self.LSTM = nn.LSTM(n_embd, n_embd, batch_first=True) 53 | 54 | def forward(self, paths): 55 | embed = self.embedding(paths) # bs, max_len, max_path_len, n_embd 56 | batch_size, bag_size, path_len, n_embd = embed.shape 57 | _, (h_n, _) = self.LSTM(embed.view(batch_size * bag_size, path_len, n_embd)) 58 | return h_n.permute((1, 0, 2)).view((batch_size, bag_size, -1)) 59 | 60 | 61 | class LayerNorm(nn.Module): 62 | def __init__(self, hidden_size, std_eps=1e-6): 63 | """Construct a layernorm module in the TF style. 64 | """ 65 | super(LayerNorm, self).__init__() 66 | self.weight = nn.Parameter(torch.ones(hidden_size)) 67 | self.bias = nn.Parameter(torch.zeros(hidden_size)) 68 | self.std_eps = std_eps 69 | 70 | def forward(self, x): 71 | u = x.mean(-1, keepdim=True) 72 | s = (x - u).std(-1, keepdim=True) 73 | x = (x - u) / (s + self.std_eps) 74 | return self.weight * x + self.bias 75 | 76 | 77 | class Attention(nn.Module): 78 | def __init__( 79 | self, nx, n_ctx, n_head, scale=False 80 | ): 81 | super(Attention, self).__init__() 82 | n_state = nx 83 | # [switch nx => n_state from Block to Attention to keep identical to TF implem] 84 | assert n_state % n_head == 0 85 | self.register_buffer( 86 | "bias", torch.tril(torch.ones(n_ctx, n_ctx)).view(1, 1, n_ctx, n_ctx) 87 | ) 88 | self.n_head = n_head 89 | self.split_size = n_state 90 | self.scale = scale 91 | self.c_attn = nn.Linear(nx, n_state * 3) 92 | self.c_proj = nn.Linear(nx, n_state) 93 | 94 | def _attn(self, q, k, v): 95 | w = torch.matmul(q, k) 96 | if self.scale: 97 | w = w / math.sqrt(v.size(-1)) 98 | nd, ns = w.size(-2), w.size(-1) 99 | b = self.bias[:, :, ns - nd : ns, :ns] 100 | w = w * b - 1e10 * (1 - b) 101 | 102 | w = nn.Softmax(dim=-1)(w) 103 | return torch.matmul(w, v) 104 | 105 | def merge_heads(self, x): 106 | x = x.permute(0, 2, 1, 3).contiguous() 107 | new_x_shape = x.size()[:-2] + (x.size(-2) * x.size(-1),) 108 | return x.view(*new_x_shape) # in Tensorflow implem: fct merge_states 109 | 110 | def split_heads(self, x, k=False): 111 | new_x_shape = x.size()[:-1] + (self.n_head, x.size(-1) // self.n_head) 112 | x = x.view(*new_x_shape) # in Tensorflow implem: fct split_states 113 | if k: 114 | return x.permute(0, 2, 3, 1) # (batch, head, head_features, seq_length) 115 | else: 116 | return x.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features) 117 | 118 | def forward(self, x): 119 | x = self.c_attn(x) 120 | query, key, value = x.split(self.split_size, dim=2) 121 | query = self.split_heads(query) 122 | key = self.split_heads(key, k=True) 123 | value = self.split_heads(value) 124 | 125 | # self attention component 126 | a = self._attn(query, key, value) 127 | a = self.merge_heads(a) 128 | a = self.c_proj(a) 129 | return a 130 | 131 | 132 | class MLP(nn.Module): 133 | def __init__(self, n_state, n_embd): 134 | super(MLP, self).__init__() 135 | self.c_fc = nn.Linear(n_embd, n_state) 136 | self.c_proj = nn.Linear(n_state, n_embd) 137 | self.act = gelu 138 | 139 | def forward(self, x): 140 | h = self.act(self.c_fc(x)) 141 | h2 = self.c_proj(h) 142 | return h2 143 | 144 | 145 | class Block(nn.Module): 146 | def __init__( 147 | self, 148 | n_ctx, 149 | n_head, 150 | n_embd, 151 | layer_norm_epsilon, 152 | scale=False, 153 | ): 154 | super(Block, self).__init__() 155 | self.ln_1 = LayerNorm(n_embd, std_eps=layer_norm_epsilon) 156 | self.attn = Attention( 157 | n_embd, n_ctx, n_head, scale 158 | ) 159 | self.ln_2 = LayerNorm(n_embd, std_eps=layer_norm_epsilon) 160 | self.mlp = MLP(4 * n_embd, n_embd) 161 | 162 | def forward(self, x): 163 | a = self.attn(self.ln_1(x)) 164 | x = x + a 165 | m = self.mlp(self.ln_2(x)) 166 | x = x + m 167 | return x 168 | 169 | 170 | class GPT2Model(nn.Module): 171 | def __init__( 172 | self, 173 | vocab_size, 174 | n_layer, 175 | n_embd, 176 | n_ctx, 177 | n_head, 178 | layer_norm_epsilon, 179 | root_paths, 180 | ): 181 | super(GPT2Model, self).__init__() 182 | self.n_layer = n_layer 183 | self.n_embd = n_embd 184 | self.n_vocab = vocab_size 185 | self.wte = nn.Embedding(vocab_size, n_embd) 186 | if root_paths: 187 | self.path_lstm = PathLSTM(vocab_size, n_embd) 188 | block = Block( 189 | n_ctx, 190 | n_head, 191 | n_embd, 192 | layer_norm_epsilon, 193 | scale=True, 194 | ) 195 | self.h = nn.ModuleList([copy.deepcopy(block) for _ in range(n_layer)]) 196 | self.ln_f = LayerNorm(n_embd, std_eps=layer_norm_epsilon) 197 | 198 | def forward(self, input_ids, paths=None): 199 | input_shape = input_ids.size() 200 | input_ids = input_ids.view(-1, input_ids.size(-1)) 201 | inputs_embeds = self.wte(input_ids) 202 | path_embeds = self.path_lstm(paths) if paths is not None else 0 203 | hidden_states = inputs_embeds + path_embeds 204 | 205 | for block in self.h: 206 | hidden_states = block(hidden_states) 207 | hidden_states = self.ln_f(hidden_states) 208 | output_shape = input_shape + (hidden_states.size(-1),) 209 | return hidden_states.view(*output_shape) 210 | 211 | 212 | class GPT2LMHead(nn.Module): 213 | def __init__(self, model_embeddings_weights, n_embd): 214 | super(GPT2LMHead, self).__init__() 215 | self.n_embd = n_embd 216 | self.set_embeddings_weights(model_embeddings_weights) 217 | 218 | def set_embeddings_weights(self, model_embeddings_weights): 219 | embed_shape = model_embeddings_weights.shape 220 | self.decoder = nn.Linear(embed_shape[1], embed_shape[0], bias=False) 221 | self.decoder.weight = model_embeddings_weights # Tied weights 222 | 223 | def forward(self, hidden_state): 224 | lm_logits = self.decoder(hidden_state) 225 | return lm_logits 226 | 227 | 228 | class TransformerModel(nn.Module): 229 | def __init__( 230 | self, 231 | vocab_size, 232 | loss_fn, 233 | n_layer, 234 | n_embd, 235 | n_ctx, 236 | n_head, 237 | layer_norm_epsilon, 238 | root_paths=False, 239 | ): 240 | super(TransformerModel, self).__init__() 241 | self.transformer = GPT2Model( 242 | vocab_size, 243 | n_layer, 244 | n_embd, 245 | n_ctx, 246 | n_head, 247 | layer_norm_epsilon, 248 | root_paths, 249 | ) 250 | self.lm_head = GPT2LMHead(self.transformer.wte.weight, n_embd) 251 | self.loss_fn = loss_fn 252 | 253 | def reset_parameters(self): 254 | for p in self.parameters(): 255 | if p.dim() > 1: 256 | nn.init.xavier_uniform_(p) 257 | 258 | def forward( 259 | self, x, y, ext=None, paths=None, return_loss=False 260 | ): 261 | hidden_states = self.transformer(x, paths) 262 | y_pred = self.lm_head(hidden_states) 263 | if not return_loss: 264 | return y_pred 265 | 266 | # ext contains a list of idx of where to take the loss from 267 | # we linearize it first 268 | ids = [] 269 | max_len = y.size(-1) 270 | for i, ext_i in enumerate(ext): 271 | ids += [i * max_len + j for j in range(ext_i, max_len)] 272 | loss = self.loss_fn(y_pred.view(-1, y_pred.size(-1))[ids], y.view(-1)[ids]) 273 | return loss 274 | 275 | 276 | # base RNN model 277 | class LSTMModel(torch.nn.Module): 278 | def __init__(self, vocab_size, n_embd, loss_fn, n_ctx): 279 | super(LSTMModel, self).__init__() 280 | self.embedding = nn.Embedding(vocab_size, n_embd) 281 | self.lstm = nn.LSTM(n_embd, n_embd, num_layers=1, dropout=0.5, batch_first=True) 282 | self.decoder = nn.Linear(n_embd, vocab_size) 283 | 284 | self.loss_fn = loss_fn 285 | self.half_ctx = int(n_ctx / 2) 286 | 287 | def reset_parameters(self): 288 | for p in self.parameters(): 289 | if p.dim() > 1: 290 | nn.init.xavier_uniform_(p) 291 | 292 | def forward( 293 | self, x, y, ext=None, paths=None, return_loss=False 294 | ): 295 | embed = self.embedding(x) # bs, max_len, n_embd 296 | self.lstm.flatten_parameters() 297 | lstm_out, _ = self.lstm(embed) # bs, max_len, n_embd 298 | y_pred = self.decoder(lstm_out) # bs, max_len, vocab_size 299 | if not return_loss: 300 | return y_pred 301 | 302 | # ext contains a list of idx of where to take the loss from 303 | # we linearize it first 304 | ids = [] 305 | max_len = y.size(-1) 306 | for i, ext_i in enumerate(ext): 307 | ids += [i * max_len + j for j in range(ext_i, max_len)] 308 | loss = self.loss_fn(y_pred.view(-1, y_pred.size(-1))[ids], y.view(-1)[ids]) 309 | return loss 310 | -------------------------------------------------------------------------------- /models/code2seq/dataset.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import json 9 | import logging 10 | 11 | import torch 12 | import utils 13 | 14 | 15 | logging.basicConfig(level=logging.INFO) 16 | 17 | 18 | UNK = "" 19 | PAD = "" 20 | PLACEHOLDER = "" 21 | 22 | 23 | class Dataset(torch.utils.data.Dataset): 24 | def __init__(self, fp): 25 | super().__init__() 26 | self.fp = fp 27 | self._line_pos_dp = list(utils.line_positions(fp)) 28 | 29 | def __len__(self): 30 | return len(self._line_pos_dp) 31 | 32 | def __getitem__(self, idx): 33 | line_pos = self._line_pos_dp[idx] 34 | with open(self.fp) as f: 35 | f.seek(line_pos) 36 | dp_line = json.loads(f.readline().strip()) 37 | return dp_line 38 | 39 | @staticmethod 40 | def collate(batch, token_pad_idx, subtoken_pad_idx): 41 | def combine(seqs, max_len, max_path_len, pad_idx): 42 | if not seqs: 43 | return torch.ones((max_len, max_path_len)).long() * pad_idx 44 | paths = [] 45 | for path in seqs: 46 | paths.append(path + [pad_idx] * (max_path_len - len(path))) 47 | len_pad = torch.ones((max_len - len(paths), max_path_len)).long() 48 | return torch.cat((torch.tensor(paths), len_pad)) 49 | 50 | max_len = max(len(i[1]) for i in batch) 51 | max_start_len = max( 52 | max([len(start) for start in seq[1]], default=0) for seq in batch 53 | ) 54 | max_path_len = max( 55 | max([len(path) for path in seq[2]], default=0) for seq in batch 56 | ) 57 | max_end_len = max( 58 | max([len(start) for start in seq[3]], default=0) for seq in batch 59 | ) 60 | all_targets = [] 61 | all_starts = [] 62 | all_paths = [] 63 | all_ends = [] 64 | 65 | for (target, starts, paths, ends) in batch: 66 | all_targets.append(target) 67 | starts = combine(starts, max_len, max_start_len, subtoken_pad_idx) 68 | paths = combine(paths, max_len, max_path_len, token_pad_idx) 69 | ends = combine(ends, max_len, max_end_len, subtoken_pad_idx) 70 | 71 | all_starts.append(starts) 72 | all_ends.append(ends) 73 | all_paths.append(paths) 74 | 75 | results = { 76 | "targets": torch.tensor(all_targets), 77 | "starts": torch.stack(all_starts), 78 | "paths": torch.stack(all_paths), 79 | "ends": torch.stack(all_ends), 80 | } 81 | return results 82 | -------------------------------------------------------------------------------- /models/code2seq/generate_data.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import json 3 | import os 4 | import pickle 5 | import random 6 | import re 7 | from collections import defaultdict 8 | from itertools import chain, combinations, product 9 | 10 | from utils import get_ancestors, get_terminal_nodes, parallelize, tokenize 11 | from tqdm import tqdm 12 | 13 | 14 | PLACEHOLDER = "" 15 | UNK = "" 16 | 17 | 18 | def get_leaf_nodes(ast, id_type): 19 | # get ids for special leaf types: attr, num, name, param 20 | if id_type == "attr": 21 | types_ = {"attr"}: 22 | elif id_type == "num": 23 | types_ = {"Num"} 24 | elif id_type == "name": 25 | types_ = {"NameLoad", "NameStore"} 26 | elif id_type == "param": 27 | types_ = {"NameParam"} 28 | 29 | nodes = [] 30 | for i, node in enumerate(ast): 31 | if "type" in node and node["type"] in types_: 32 | nodes.append(i + 1) 33 | return nodes 34 | 35 | 36 | def get_value(d): 37 | return d["value"] if "value" in d else d["type"] 38 | 39 | 40 | def extract_paths(ast, max_length): 41 | def dfs(i): 42 | node = ast[i] 43 | if "children" not in node: 44 | full_paths = [] 45 | half_paths = [[i]] 46 | else: 47 | children = node["children"] 48 | child_to_full_paths, child_to_half_paths = zip( 49 | *(dfs(child_id) for child_id in children) 50 | ) 51 | full_paths = list(chain.from_iterable(child_to_full_paths)) 52 | for i_child in range(len(children) - 1): 53 | for j_child in range(i_child + 1, len(children)): 54 | i_child_half_paths = child_to_half_paths[i_child] 55 | j_child_half_paths = child_to_half_paths[j_child] 56 | for i_half_path, j_half_path in product( 57 | i_child_half_paths, j_child_half_paths 58 | ): 59 | path_len = len(i_half_path) + len(j_half_path) + 1 60 | if path_len > max_length: 61 | continue 62 | path = list(chain(i_half_path, [i], reversed(j_half_path))) 63 | full_paths.append(path) 64 | half_paths = [ 65 | half_path + [i] 66 | for half_path in chain.from_iterable(child_to_half_paths) 67 | if len(half_path) + 1 < max_length 68 | ] 69 | return full_paths, half_paths 70 | 71 | return dfs(0)[0] 72 | 73 | 74 | def get_all_paths(ast, id_type, max_path_len, max_num_paths): 75 | if id_type == "leaves": 76 | nodes = get_terminal_nodes(ast) 77 | else: 78 | nodes = get_leaf_nodes(ast, id_type) 79 | if not nodes: 80 | return [] 81 | 82 | all_paths = extract_paths(ast, max_path_len) 83 | ast_values = [get_value(i) for i in ast] 84 | terminal_words = [get_value(ast[i]) for i in get_terminal_nodes(ast)] 85 | tokenized_words = {word: tokenize(word) for word in terminal_words} 86 | node_to_path_idx = {i: [] for i in range(len(ast))} 87 | for i, path in enumerate(all_paths): 88 | node_to_path_idx[path[-1]].append(i) 89 | 90 | dps = [] 91 | paths_to_choose_from = [] 92 | prev_node = 0 93 | for node in nodes: 94 | for j in range(prev_node, node): 95 | paths_to_choose_from += [ 96 | all_paths[path_i] for path_i in node_to_path_idx[j] 97 | ] 98 | prev_node = node 99 | 100 | paths_to_here = [all_paths[path_i] for path_i in node_to_path_idx[node]] 101 | if len(paths_to_choose_from) + len(paths_to_here) <= max_num_paths: 102 | paths = paths_to_choose_from.copy() + paths_to_here 103 | else: 104 | if len(paths_to_here) > max_num_paths: 105 | paths = random.sample(paths_to_here, max_num_paths) 106 | else: 107 | paths = paths_to_here + random.sample( 108 | paths_to_choose_from, max_num_paths - len(paths_to_here) 109 | ) 110 | 111 | # convert to vocab 112 | target = ast_values[node] 113 | paths = [ 114 | [ast_values[i] if i != node else PLACEHOLDER for i in p] for p in paths 115 | ] 116 | lefts = [tokenized_words[p[0]] for p in paths] 117 | rights = [ 118 | tokenized_words[p[-1]] if p[-1] != PLACEHOLDER else [PLACEHOLDER] 119 | for p in paths 120 | ] 121 | dps.append([target, lefts, paths, rights]) 122 | return dps 123 | 124 | 125 | def get_word2idx(out_fp): 126 | with open(out_fp, "rb") as fin: 127 | vocab = pickle.load(fin) 128 | word2idx = {word: i for i, word in enumerate(vocab)} 129 | word2idx = defaultdict(lambda: word2idx[UNK], word2idx) 130 | print("Read vocab from: {}".format(out_fp)) 131 | return word2idx 132 | 133 | 134 | def main(): 135 | parser = argparse.ArgumentParser( 136 | description="Generate terminal to terminal paths from AST" 137 | ) 138 | parser.add_argument("--ast_fp", "-a", help="Filepath with the ASTs to be parsed") 139 | parser.add_argument( 140 | "--out_fp", "-o", default="/tmp/dps.txt", help="Filepath for the output dps" 141 | ) 142 | parser.add_argument("--max_path_len", type=int, default=9, help="Max path len.") 143 | parser.add_argument("--max_num_paths", type=int, default=200) 144 | parser.add_argument("--base_dir", "-b", type=str) 145 | parser.add_argument( 146 | "id_type", 147 | choices=["attr", "num", "name", "param", "leaves"], 148 | default="attr", 149 | help="Which ids to generate. Default = attr", 150 | ) 151 | args = parser.parse_args() 152 | print("Max path len: {}".format(args.max_path_len)) 153 | print("Max num paths: {}".format(args.max_num_paths)) 154 | print("Writing to {}".format(args.out_fp)) 155 | 156 | # read the vocabs 157 | base_dir = args.base_dir 158 | token_vocab = get_word2idx(os.path.join(base_dir, "token_vocab.pkl")) 159 | subtoken_vocab = get_word2idx(os.path.join(base_dir, "subtoken_vocab.pkl")) 160 | output_vocab = get_word2idx(os.path.join(base_dir, "output_vocab.pkl")) 161 | 162 | data = [] 163 | i = 0 164 | c = 0 165 | with open(args.ast_fp, "r") as f, open(args.out_fp, "w") as fout: 166 | for _ in range(20): 167 | i += 1 168 | print("Starting {} / 50".format(i)) 169 | for _ in range(5000): 170 | dp = json.loads(f.readline().strip()) 171 | if len(dp) <= 1: 172 | continue 173 | data.append(dp) 174 | print(" > Finished reading: {}".format(len(data))) 175 | for ast in tqdm(data): 176 | dp = get_all_paths(ast, args.id_type, args.max_path_len, args.max_num_paths) 177 | for target, lefts, paths, rights in dp: 178 | target = output_vocab[target] 179 | lefts = [[subtoken_vocab[t] for t in lst] for lst in lefts] 180 | paths = [[token_vocab[t] for t in lst] for lst in paths] 181 | rights = [[subtoken_vocab[t] for t in lst] for lst in rights] 182 | 183 | json.dump([target, lefts, paths, rights], fout) 184 | fout.write("\n") 185 | c += 1 186 | data = [] 187 | print(" > Finished writing to file") 188 | print("Wrote {} datapoints to {}".format(c, args.out_fp)) 189 | 190 | 191 | if __name__ == "__main__": 192 | main() 193 | -------------------------------------------------------------------------------- /models/code2seq/generate_vocab.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import argparse 9 | import json 10 | import logging 11 | import pickle 12 | import re 13 | from collections import Counter 14 | 15 | from utils import get_terminal_nodes, file_tqdm, tokenize 16 | 17 | 18 | logging.basicConfig(level=logging.INFO) 19 | 20 | 21 | UNK = "" 22 | PAD = "" 23 | PLACEHOLDER = "" 24 | 25 | 26 | def get_value(line, vocab_type): 27 | if vocab_type == "token": 28 | return get_dfs(line) 29 | elif vocab_type == "subtoken": 30 | lst = [] 31 | for node in get_terminal_nodes(line): 32 | lst += tokenize(node) 33 | return lst 34 | elif vocab_type == "output": 35 | return get_terminal_nodes(line) 36 | 37 | 38 | def main(): 39 | parser = argparse.ArgumentParser( 40 | description="Create vocab for code2seq model for py150 dataset" 41 | ) 42 | parser.add_argument("--n_vocab", "-n", type=int, default=100000) 43 | parser.add_argument("--input_fp", "-i") 44 | parser.add_argument("--out_fp", "-o", default="/tmp/vocab.pkl") 45 | parser.add_argument( 46 | "--vocab_type", 47 | "-v", 48 | choices=["token", "subtoken", "output"], 49 | help="What type of vocab to get", 50 | ) 51 | args = parser.parse_args() 52 | 53 | logging.info("Reading from: {}".format(args.input_fp)) 54 | logging.info("Vocab type: {}".format(args.vocab_type)) 55 | vocab = Counter() 56 | with open(args.input_fp, "r") as f: 57 | for line in file_tqdm(f): 58 | vocab.update(get_value(json.loads(line.strip()), args.vocab_type)) 59 | vocab_to_keep = [i[0] for i in vocab.most_common(args.n_vocab)] 60 | top_total = sum(i[1] for i in vocab.most_common(args.n_vocab)) 61 | total = sum(vocab.values()) 62 | 63 | logging.info("Total # of vocab: {}".format(len(vocab))) 64 | logging.info( 65 | "Using {} top vocab covers: {:.2f}% of the entire dataset".format( 66 | args.n_vocab, 100 * top_total / total 67 | ) 68 | ) 69 | logging.info("Top 10 most common vocab:") 70 | for v, i in vocab.most_common(10): 71 | print(v, i) 72 | 73 | # add unk and pad tokens 74 | vocab_to_keep.append(UNK) 75 | vocab_to_keep.append(PAD) 76 | vocab_to_keep.append(PLACEHOLDER) 77 | logging.info("Added {} and {} and {}".format(UNK, PAD, PLACEHOLDER)) 78 | 79 | # dump vocab to file 80 | with open(args.out_fp, "wb") as fout: 81 | pickle.dump(vocab_to_keep, fout) 82 | logging.info("Wrote {} vocab to: {}".format(len(vocab_to_keep), args.out_fp)) 83 | 84 | 85 | if __name__ == "__main__": 86 | main() -------------------------------------------------------------------------------- /models/path_trans/dataset.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import torch 9 | from dataset.dataset import BaseDataset, BaseSetup, BaseVocab 10 | 11 | 12 | class Setup(BaseSetup): 13 | def _create_vocab(self): 14 | return Vocab(self.filepaths["vocab"]) 15 | 16 | def _create_dataset(self, fp, ids_fp): 17 | return Dataset(fp, ids_fp) 18 | 19 | 20 | class Vocab(BaseVocab): 21 | def convert(self, line): 22 | dp, ext, root_paths = line 23 | dp_conv = [ 24 | self.vocab2idx[token] if token in self.vocab2idx else self.unk_idx 25 | for token in dp 26 | ] 27 | root_paths_conv = [ 28 | [ 29 | self.vocab2idx[token] if token in self.vocab2idx else self.unk_idx 30 | for token in path 31 | ] 32 | for path in root_paths 33 | ] 34 | return [dp_conv, ext, root_paths_conv] 35 | 36 | 37 | class Dataset(BaseDataset): 38 | @staticmethod 39 | def collate(seqs, pad_idx, bos_idx=None): 40 | def combine_root_paths(root_paths, max_len, max_path_len): 41 | paths = [] 42 | for path in root_paths: 43 | paths.append(path + [pad_idx] * (max_path_len - len(path))) 44 | len_pad = torch.ones((max_len - len(paths), max_path_len)).long() 45 | return torch.cat((torch.tensor(paths), len_pad)) 46 | 47 | max_len = max(len(seq[0][0]) for seq in seqs) 48 | max_len = max(2, max_len) 49 | max_path_len = max(max(len(path) for path in seq[0][2]) for seq in seqs) 50 | max_path_len - max(2, max_path_len) 51 | input_seqs = [] 52 | target_seqs = [] 53 | extended = [] 54 | root_path_seqs = [] 55 | ids = {name: [] for name in seqs[0][1].keys()} 56 | 57 | for i, ((seq, ext, root_paths), ids_lst) in enumerate(seqs): 58 | padding = [pad_idx] * (max_len - len(seq)) 59 | input_seqs.append(seq[:-1] + padding) 60 | target_seqs.append(seq[1:] + padding) 61 | extended.append(ext) 62 | root_path_seqs.append(combine_root_paths(root_paths, max_len, max_path_len)) 63 | for name, lst in ids_lst.items(): 64 | ids[name] += [j - 1 + (max_len - 1) * i for j in lst] 65 | 66 | return { 67 | "input_seq": torch.tensor(input_seqs), 68 | "target_seq": torch.tensor(target_seqs), 69 | "extended": torch.tensor(extended), 70 | "root_paths": torch.stack(root_path_seqs)[:, 1:, :], 71 | "ids": ids, 72 | } 73 | -------------------------------------------------------------------------------- /models/path_trans/generate_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import argparse 9 | import json 10 | import logging 11 | import os 12 | 13 | from utils import file_tqdm 14 | 15 | 16 | logging.basicConfig(level=logging.INFO) 17 | 18 | 19 | def get_leaf_info(ast): 20 | leaf_tokens = [] 21 | leaf_ids = [] 22 | for i, node in enumerate(ast): 23 | if "value" in node: 24 | leaf_ids.append(i) 25 | leaf_tokens.append(node["value"]) 26 | return leaf_tokens, leaf_ids 27 | 28 | 29 | def get_ancestors(ast): 30 | ancestors = {0: []} 31 | node2parent = {0: 0} 32 | for i, node in enumerate(ast): 33 | if "children" in node: 34 | for child in node["children"]: 35 | node2parent[child] = i 36 | token = node["value"] if "value" in node else node["type"] 37 | ancestors[i] = [token] + ancestors[node2parent[i]] 38 | return ancestors 39 | 40 | 41 | def get_root_paths(ancestors, leaf_ids, max_path_len): 42 | return [ancestors[i][1 :max_path_len + 1] for i in leaf_ids] 43 | 44 | 45 | def get_dps(ast, max_len, max_path_len): 46 | leaf_tokens, leaf_ids = get_leaf_info(ast) 47 | ancestors = get_ancestors(ast) 48 | if len(leaf_tokens) <= max_len: 49 | return [[leaf_tokens, 0, get_root_paths(ancestors, leaf_ids, max_path_len)]] 50 | 51 | half_len = int(max_len / 2) 52 | aug_dps = [ 53 | [ 54 | leaf_tokens[:max_len], 55 | 0, 56 | get_root_paths(ancestors, leaf_ids[:max_len], max_path_len), 57 | ] 58 | ] 59 | i = half_len 60 | while i < len(leaf_tokens) - max_len: 61 | aug_dps.append( 62 | [ 63 | leaf_tokens[i : i + max_len], 64 | half_len, 65 | get_root_paths(ancestors, leaf_ids[i : i + max_len], max_path_len), 66 | ] 67 | ) 68 | i += half_len 69 | idx = max_len - (len(leaf_tokens) - (i + half_len)) 70 | aug_dps.append( 71 | [ 72 | leaf_tokens[-max_len:], 73 | idx, 74 | get_root_paths(ancestors, leaf_ids[-max_len:], max_path_len), 75 | ] 76 | ) 77 | return aug_dps 78 | 79 | 80 | def main(): 81 | parser = argparse.ArgumentParser(description="Generate datapoints from AST") 82 | parser.add_argument("--ast_fp", "-a", help="Filepath with the ASTs to be parsed") 83 | parser.add_argument( 84 | "--out_fp", "-o", default="/tmp/dps.txt", help="Filepath with the output dps" 85 | ) 86 | parser.add_argument( 87 | "--n_ctx", "-c", type=int, default=1000, help="Number of contexts for each dp" 88 | ) 89 | parser.add_argument( 90 | "--max_path_len", 91 | "-p", 92 | type=int, 93 | default=13, 94 | help="Max length of rootpath route", 95 | ) 96 | 97 | args = parser.parse_args() 98 | if os.path.exists(args.out_fp): 99 | os.remove(args.out_fp) 100 | logging.info("Writing dps to: {}".format(args.out_fp)) 101 | 102 | num_dps = 0 103 | with open(args.ast_fp, "r") as f, open(args.out_fp, "w") as fout: 104 | for line in file_tqdm(f): 105 | dp = json.loads(line.strip()) 106 | for dp in get_dps(dp, args.n_ctx, args.max_path_len): 107 | if len(dp[0]) > 1: 108 | json.dump(dp, fout) 109 | fout.write("\n") 110 | num_dps += 1 111 | 112 | logging.info("Wrote {} datapoints to {}".format(num_dps, args.out_fp)) 113 | 114 | 115 | if __name__ == "__main__": 116 | main() 117 | -------------------------------------------------------------------------------- /models/path_trans_variation/dataset.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import torch 9 | from dataset.dataset import BaseDataset, BaseSetup, BaseVocab 10 | 11 | 12 | class Setup(BaseSetup): 13 | def _create_vocab(self): 14 | return Vocab(self.filepaths["vocab"]) 15 | 16 | def _create_dataset(self, fp, ids_fp): 17 | return Dataset(fp, ids_fp) 18 | 19 | 20 | class Vocab(BaseVocab): 21 | def convert(self, line): 22 | dp, ext = line 23 | dp_conv = [ 24 | self.vocab2idx[token] if token in self.vocab2idx else self.unk_idx 25 | for token in dp 26 | ] 27 | return [dp_conv, ext] 28 | 29 | 30 | class Dataset(BaseDataset): 31 | @staticmethod 32 | def collate(seqs, pad_idx): 33 | max_len = max(len(seq[0][0]) for seq in seqs) 34 | max_len = max(max_len, 2) 35 | input_seqs = [] 36 | target_seqs = [] 37 | extended = [] 38 | ids = {name: [] for name in seqs[0][1].keys()} 39 | 40 | for i, ((seq, ext), ids_lst) in enumerate(seqs): 41 | padding = [pad_idx] * (max_len - len(seq)) 42 | input_seqs.append(seq[:-1] + padding) 43 | target_seqs.append(seq[1:] + padding) 44 | extended.append(ext) 45 | for name, lst in ids_lst.items(): 46 | ids[name] += [j - 1 + (max_len - 1) * i for j in lst] 47 | 48 | return { 49 | "input_seq": torch.tensor(input_seqs), 50 | "target_seq": torch.tensor(target_seqs), 51 | "extended": torch.tensor(extended), 52 | "ids": ids, 53 | } 54 | -------------------------------------------------------------------------------- /models/path_trans_variation/generate_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import argparse 9 | import json 10 | import logging 11 | import os 12 | 13 | from utils import file_tqdm, get_dfs, separate_dps 14 | 15 | 16 | logging.basicConfig(level=logging.INFO) 17 | 18 | 19 | def get_leaf_info(ast): 20 | leaf_tokens = [] 21 | leaf_ids = [] 22 | for i, node in enumerate(ast): 23 | if "value" in node: 24 | leaf_ids.append(i) 25 | leaf_tokens.append(node["value"]) 26 | return leaf_tokens, leaf_ids 27 | 28 | 29 | def get_dps(ast, max_len): 30 | leaf_tokens, leaf_ids = get_leaf_info(ast) 31 | if len(leaf_tokens) <= max_len: 32 | return [[leaf_tokens, 0]], [leaf_ids] 33 | 34 | half_len = int(max_len / 2) 35 | aug_tokens = [[leaf_tokens[:max_len], 0]] 36 | aug_leaf_ids = [leaf_ids[:max_len]] 37 | i = half_len 38 | while i < len(leaf_tokens) - max_len: 39 | aug_tokens.append([leaf_tokens[i : i + max_len], half_len]) 40 | aug_leaf_ids.append(leaf_ids[i : i + max_len]) 41 | i += half_len 42 | idx = max_len - (len(leaf_tokens) - (i + half_len)) 43 | aug_tokens.append([leaf_tokens[-max_len:], idx]) 44 | aug_leaf_ids.append(leaf_ids[-max_len:]) 45 | return aug_tokens, aug_leaf_ids 46 | 47 | 48 | def main(): 49 | parser = argparse.ArgumentParser(description="Generate datapoints from AST") 50 | parser.add_argument("--ast_fp", "-a", help="Filepath with the ASTs to be parsed") 51 | parser.add_argument( 52 | "--n_ctx", "-c", type=int, default=1000, help="Number of contexts for each dp" 53 | ) 54 | parser.add_argument( 55 | "--out_fp", "-o", default="/tmp/dps.txt", help="Filepath with the output dps" 56 | ) 57 | 58 | args = parser.parse_args() 59 | if os.path.exists(args.out_fp): 60 | os.remove(args.out_fp) 61 | logging.info("Writing dps to: {}".format(args.out_fp)) 62 | 63 | num_dps = 0 64 | with open(args.ast_fp, "r") as f, open(args.out_fp, "w") as fout: 65 | for line in file_tqdm(f): 66 | dp = json.loads(line.strip()) 67 | aug_tokens, aug_leaf_ids = get_dps(dp, args.n_ctx) 68 | for (tokens, ext), leaf in zip(aug_tokens, aug_leaf_ids): 69 | if len(tokens) > 1: 70 | json.dump([tokens, ext], fp=fout) 71 | fout.write("\n") 72 | num_dps += 1 73 | 74 | logging.info("Wrote {} datapoints to {}".format(num_dps, args.out_fp)) 75 | 76 | 77 | if __name__ == "__main__": 78 | main() 79 | -------------------------------------------------------------------------------- /models/seq/astunparser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import ast 9 | import sys 10 | 11 | import six 12 | from six import StringIO 13 | 14 | 15 | # Large float and imaginary literals get turned into infinities in the AST. 16 | # We unparse those infinities to INFSTR. 17 | INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1) 18 | 19 | 20 | def interleave(inter, f, seq): 21 | """Call f on each item in seq, calling inter() in between. 22 | """ 23 | seq = iter(seq) 24 | try: 25 | f(next(seq)) 26 | except StopIteration: 27 | pass 28 | else: 29 | for x in seq: 30 | inter() 31 | f(x) 32 | 33 | 34 | class Unparser: 35 | """Methods in this class recursively traverse an AST and 36 | output source code for the abstract syntax; original formatting 37 | is disregarded. """ 38 | 39 | def __init__(self, tree, file=sys.stdout): 40 | """Unparser(tree, file=sys.stdout) -> None. 41 | Print the source for tree to file.""" 42 | self.f = file 43 | self.future_imports = [] 44 | self._indent = 0 45 | self.dispatch(tree) 46 | self.f.write("\n") 47 | # print("", file=self.f) 48 | self.f.flush() 49 | 50 | def fill(self, text=""): 51 | "Indent a piece of text, according to the current indentation level" 52 | self.f.write("\n" + " " * self._indent + text) 53 | 54 | def write(self, text, type=None): 55 | "Append a piece of text to the current line." 56 | self.f.write(six.text_type(text), type) 57 | 58 | def enter(self): 59 | "Print ':', and increase the indentation." 60 | self.write(":") 61 | self._indent += 1 62 | 63 | def leave(self): 64 | "Decrease the indentation level." 65 | self._indent -= 1 66 | 67 | def dispatch(self, tree): 68 | "Dispatcher function, dispatching tree type T to method _T." 69 | if isinstance(tree, list): 70 | for t in tree: 71 | self.dispatch(t) 72 | return 73 | meth = getattr(self, "_" + tree.__class__.__name__) 74 | meth(tree) 75 | 76 | ############### Unparsing methods ###################### 77 | # There should be one method per concrete grammar type # 78 | # Constructors should be grouped by sum type. Ideally, # 79 | # this would follow the order in the grammar, but # 80 | # currently doesn't. # 81 | ######################################################## 82 | 83 | def _Module(self, tree): 84 | for stmt in tree.body: 85 | self.dispatch(stmt) 86 | 87 | def _Interactive(self, tree): 88 | for stmt in tree.body: 89 | self.dispatch(stmt) 90 | 91 | def _Expression(self, tree): 92 | self.dispatch(tree.body) 93 | 94 | # stmt 95 | def _Expr(self, tree): 96 | self.fill() 97 | self.dispatch(tree.value) 98 | 99 | def _NamedExpr(self, tree): 100 | self.write("(") 101 | self.dispatch(tree.target) 102 | self.write(" := ") 103 | self.dispatch(tree.value) 104 | self.write(")") 105 | 106 | def _Import(self, t): 107 | self.fill("import ") 108 | interleave(lambda: self.write(", "), self.dispatch, t.names) 109 | 110 | def _ImportFrom(self, t): 111 | # A from __future__ import may affect unparsing, so record it. 112 | if t.module and t.module == "__future__": 113 | self.future_imports.extend(n.name for n in t.names) 114 | 115 | self.fill("from ") 116 | self.write("." * t.level) 117 | # NOTE: `level` is not stored as values in py150 trees. 118 | # This will make `from ..package.name import sth` appear the same as 119 | # `from .package.name import sth` or `from package.name import sth`. 120 | if t.module: 121 | # NOTE: Reason: Use class name. `parse_python.py:L66-69`. 122 | self.write(t.module, type="ImportFrom") 123 | self.write(" import ") 124 | interleave(lambda: self.write(", "), self.dispatch, t.names) 125 | 126 | def _Assign(self, t): 127 | self.fill() 128 | for target in t.targets: 129 | self.dispatch(target) 130 | self.write(" = ") 131 | self.dispatch(t.value) 132 | 133 | def _AugAssign(self, t): 134 | self.fill() 135 | self.dispatch(t.target) 136 | self.write(" ") 137 | self.write(self.binop[t.op.__class__.__name__]) 138 | self.write("= ") 139 | self.dispatch(t.value) 140 | 141 | def _AnnAssign(self, t): 142 | self.fill() 143 | if not t.simple and isinstance(t.target, ast.Name): 144 | self.write("(") 145 | self.dispatch(t.target) 146 | if not t.simple and isinstance(t.target, ast.Name): 147 | self.write(")") 148 | self.write(": ") 149 | self.dispatch(t.annotation) 150 | if t.value: 151 | self.write(" = ") 152 | self.dispatch(t.value) 153 | 154 | def _Return(self, t): 155 | self.fill("return") 156 | if t.value: 157 | self.write(" ") 158 | self.dispatch(t.value) 159 | 160 | def _Pass(self, t): 161 | self.fill("pass") 162 | 163 | def _Break(self, t): 164 | self.fill("break") 165 | 166 | def _Continue(self, t): 167 | self.fill("continue") 168 | 169 | def _Delete(self, t): 170 | self.fill("del ") 171 | interleave(lambda: self.write(", "), self.dispatch, t.targets) 172 | 173 | def _Assert(self, t): 174 | self.fill("assert ") 175 | self.dispatch(t.test) 176 | if t.msg: 177 | self.write(", ") 178 | self.dispatch(t.msg) 179 | 180 | def _Exec(self, t): 181 | self.fill("exec ") 182 | self.dispatch(t.body) 183 | if t.globals: 184 | self.write(" in ") 185 | self.dispatch(t.globals) 186 | if t.locals: 187 | self.write(", ") 188 | self.dispatch(t.locals) 189 | 190 | def _Print(self, t): 191 | self.fill("print ") 192 | do_comma = False 193 | if t.dest: 194 | self.write(">>") 195 | self.dispatch(t.dest) 196 | do_comma = True 197 | for e in t.values: 198 | if do_comma: 199 | self.write(", ") 200 | else: 201 | do_comma = True 202 | self.dispatch(e) 203 | if not t.nl: 204 | self.write(",") 205 | 206 | def _Global(self, t): 207 | self.fill("global ") 208 | # NOTE: Reason: Use "identifier". `parse_python.py:L71`. 209 | interleave(lambda: self.write(", "), lambda x: self.write(x, type="identifier"), t.names) 210 | 211 | def _Nonlocal(self, t): 212 | # NOTE: This is not part of PY2. 213 | # NOTE: Reason: Use "identifier". Similar to the case of "Global". 214 | self.fill("nonlocal ") 215 | interleave(lambda: self.write(", "), lambda x: self.write(x, type="identifier"), t.names) 216 | 217 | def _Await(self, t): 218 | self.write("(") 219 | self.write("await") 220 | if t.value: 221 | self.write(" ") 222 | self.dispatch(t.value) 223 | self.write(")") 224 | 225 | def _Yield(self, t): 226 | self.write("(") 227 | self.write("yield") 228 | if t.value: 229 | self.write(" ") 230 | self.dispatch(t.value) 231 | self.write(")") 232 | 233 | def _YieldFrom(self, t): 234 | self.write("(") 235 | self.write("yield from") 236 | if t.value: 237 | self.write(" ") 238 | self.dispatch(t.value) 239 | self.write(")") 240 | 241 | def _Raise(self, t): 242 | self.fill("raise") 243 | if six.PY3: 244 | if not t.exc: 245 | assert not t.cause 246 | return 247 | self.write(" ") 248 | self.dispatch(t.exc) 249 | if t.cause: 250 | self.write(" from ") 251 | self.dispatch(t.cause) 252 | else: 253 | self.write(" ") 254 | if t.type: 255 | self.dispatch(t.type) 256 | if t.inst: 257 | self.write(", ") 258 | self.dispatch(t.inst) 259 | if t.tback: 260 | self.write(", ") 261 | self.dispatch(t.tback) 262 | 263 | def _Try(self, t): 264 | self.fill("try") 265 | self.enter() 266 | self.dispatch(t.body) 267 | self.leave() 268 | for ex in t.handlers: 269 | self.dispatch(ex) 270 | if t.orelse: 271 | self.fill("else") 272 | self.enter() 273 | self.dispatch(t.orelse) 274 | self.leave() 275 | if t.finalbody: 276 | self.fill("finally") 277 | self.enter() 278 | self.dispatch(t.finalbody) 279 | self.leave() 280 | 281 | def _TryExcept(self, t): 282 | self.fill("try") 283 | self.enter() 284 | self.dispatch(t.body) 285 | self.leave() 286 | 287 | for ex in t.handlers: 288 | self.dispatch(ex) 289 | if t.orelse: 290 | self.fill("else") 291 | self.enter() 292 | self.dispatch(t.orelse) 293 | self.leave() 294 | 295 | def _TryFinally(self, t): 296 | if len(t.body) == 1 and isinstance(t.body[0], ast.TryExcept): 297 | # try-except-finally 298 | self.dispatch(t.body) 299 | else: 300 | self.fill("try") 301 | self.enter() 302 | self.dispatch(t.body) 303 | self.leave() 304 | 305 | self.fill("finally") 306 | self.enter() 307 | self.dispatch(t.finalbody) 308 | self.leave() 309 | 310 | def _ExceptHandler(self, t): 311 | self.fill("except") 312 | if t.type: 313 | self.write(" ") 314 | self.dispatch(t.type) 315 | if t.name: 316 | self.write(" as ") 317 | if six.PY3: 318 | # NOTE: This is not part of PY2. 319 | # NOTE: Reason: Use "identifier". Similar to the case of "Global". 320 | self.write(t.name, type="identifier") 321 | else: 322 | self.dispatch(t.name) 323 | self.enter() 324 | self.dispatch(t.body) 325 | self.leave() 326 | 327 | def _ClassDef(self, t): 328 | self.write("\n") 329 | for deco in t.decorator_list: 330 | self.fill("@") 331 | self.dispatch(deco) 332 | self.fill("class ") 333 | # NOTE: Reason: Use class name. `parse_python.py:L64-65`. 334 | self.write(t.name, type="ClassDef") 335 | if six.PY3: 336 | self.write("(") 337 | comma = False 338 | for e in t.bases: 339 | if comma: 340 | self.write(", ") 341 | else: 342 | comma = True 343 | self.dispatch(e) 344 | for e in t.keywords: 345 | if comma: 346 | self.write(", ") 347 | else: 348 | comma = True 349 | self.dispatch(e) 350 | if sys.version_info[:2] < (3, 5): 351 | if t.starargs: 352 | if comma: 353 | self.write(", ") 354 | else: 355 | comma = True 356 | self.write("*") 357 | self.dispatch(t.starargs) 358 | if t.kwargs: 359 | if comma: 360 | self.write(", ") 361 | else: 362 | comma = True 363 | self.write("**") 364 | self.dispatch(t.kwargs) 365 | self.write(")") 366 | elif t.bases: 367 | self.write("(") 368 | for a in t.bases: 369 | self.dispatch(a) 370 | self.write(", ") 371 | self.write(")") 372 | self.enter() 373 | self.dispatch(t.body) 374 | self.leave() 375 | 376 | def _FunctionDef(self, t): 377 | self.__FunctionDef_helper(t, "def") 378 | 379 | def _AsyncFunctionDef(self, t): 380 | self.__FunctionDef_helper(t, "async def") 381 | 382 | def __FunctionDef_helper(self, t, fill_suffix): 383 | self.write("\n") 384 | for deco in t.decorator_list: 385 | self.fill("@") 386 | self.dispatch(deco) 387 | self.fill(fill_suffix) 388 | self.write(" ") 389 | # NOTE: Reason: Use class name. `parse_python.py:L62-63` 390 | self.write(t.name, type="FunctionDef") 391 | self.write("(") 392 | self.dispatch(t.args) 393 | self.write(")") 394 | if getattr(t, "returns", False): 395 | self.write(" -> ") 396 | self.dispatch(t.returns) 397 | self.enter() 398 | self.dispatch(t.body) 399 | self.leave() 400 | 401 | def _For(self, t): 402 | self.__For_helper("for ", t) 403 | 404 | def _AsyncFor(self, t): 405 | self.__For_helper("async for ", t) 406 | 407 | def __For_helper(self, fill, t): 408 | self.fill(fill) 409 | self.dispatch(t.target) 410 | self.write(" in ") 411 | self.dispatch(t.iter) 412 | self.enter() 413 | self.dispatch(t.body) 414 | self.leave() 415 | if t.orelse: 416 | self.fill("else") 417 | self.enter() 418 | self.dispatch(t.orelse) 419 | self.leave() 420 | 421 | def _If(self, t): 422 | self.fill("if ") 423 | self.dispatch(t.test) 424 | self.enter() 425 | self.dispatch(t.body) 426 | self.leave() 427 | # collapse nested ifs into equivalent elifs. 428 | while t.orelse and len(t.orelse) == 1 and isinstance(t.orelse[0], ast.If): 429 | t = t.orelse[0] 430 | self.fill("elif ") 431 | self.dispatch(t.test) 432 | self.enter() 433 | self.dispatch(t.body) 434 | self.leave() 435 | # final else 436 | if t.orelse: 437 | self.fill("else") 438 | self.enter() 439 | self.dispatch(t.orelse) 440 | self.leave() 441 | 442 | def _While(self, t): 443 | self.fill("while ") 444 | self.dispatch(t.test) 445 | self.enter() 446 | self.dispatch(t.body) 447 | self.leave() 448 | if t.orelse: 449 | self.fill("else") 450 | self.enter() 451 | self.dispatch(t.orelse) 452 | self.leave() 453 | 454 | def _generic_With(self, t, async_=False): 455 | self.fill("async with " if async_ else "with ") 456 | if hasattr(t, "items"): 457 | interleave(lambda: self.write(", "), self.dispatch, t.items) 458 | else: 459 | self.dispatch(t.context_expr) 460 | if t.optional_vars: 461 | self.write(" as ") 462 | self.dispatch(t.optional_vars) 463 | self.enter() 464 | self.dispatch(t.body) 465 | self.leave() 466 | 467 | def _With(self, t): 468 | self._generic_With(t) 469 | 470 | def _AsyncWith(self, t): 471 | self._generic_With(t, async_=True) 472 | 473 | # expr 474 | def _Bytes(self, t): 475 | # NOTE: This is not part of PY2 and will be removed in PY3.8+. 476 | # NOTE: Reason: Use class name. Similar to the case of "Str". 477 | self.write(repr(t.s), type="Bytes") 478 | 479 | def _Str(self, tree): 480 | # NOTE: This will be removed in PY3.8+. 481 | # NOTE: Reason: Use class name. `parse_python.py:L56-57`. 482 | if six.PY3: 483 | self.write(repr(tree.s), type="Str") 484 | else: 485 | # NOTE: py150 nodes will keep string in value form, not repr form. 486 | # We keep this part as it is to preserve consistency after training. 487 | # ----- 488 | # if from __future__ import unicode_literals is in effect, 489 | # then we want to output string literals using a 'b' prefix 490 | # and unicode literals with no prefix. 491 | if "unicode_literals" not in self.future_imports: 492 | self.write(repr(tree.s), type="Str") 493 | elif isinstance(tree.s, str): 494 | self.write("b" + repr(tree.s), type="Str") 495 | elif isinstance(tree.s, unicode): 496 | self.write(repr(tree.s).lstrip("u"), type="Str") 497 | else: 498 | assert False, "shouldn't get here" 499 | 500 | def _JoinedStr(self, t): 501 | # NOTE: This is not part of PY2. 502 | # JoinedStr(expr* values) 503 | self.write("f") 504 | string = StringIO() 505 | self._fstring_JoinedStr(t, string.write) 506 | # Deviation from `unparse.py`: Try to find an unused quote. 507 | # This change is made to handle _very_ complex f-strings. 508 | v = string.getvalue() 509 | if "\n" in v or "\r" in v: 510 | quote_types = ["'''", '"""'] 511 | else: 512 | quote_types = ["'", '"', '"""', "'''"] 513 | for quote_type in quote_types: 514 | if quote_type not in v: 515 | v = "{quote_type}{v}{quote_type}".format(quote_type=quote_type, v=v) 516 | break 517 | else: 518 | v = repr(v) 519 | # NOTE: Reason: Use class name. Similar to the case of "Str". 520 | self.write(v, type="JoinedStr") 521 | 522 | def _FormattedValue(self, t): 523 | # NOTE: This is not part of PY2. 524 | # FormattedValue(expr value, int? conversion, expr? format_spec) 525 | self.write("f") 526 | string = StringIO() 527 | self._fstring_JoinedStr(t, string.write) 528 | # NOTE: Reason: Use class name. Similar to the case of "Str". 529 | self.write(repr(string.getvalue()), type="FormattedValue") 530 | 531 | def _fstring_JoinedStr(self, t, write): 532 | for value in t.values: 533 | meth = getattr(self, "_fstring_" + type(value).__name__) 534 | meth(value, write) 535 | 536 | def _fstring_Str(self, t, write): 537 | value = t.s.replace("{", "{{").replace("}", "}}") 538 | write(value) 539 | 540 | def _fstring_Constant(self, t, write): 541 | assert isinstance(t.value, str) 542 | value = t.value.replace("{", "{{").replace("}", "}}") 543 | write(value) 544 | 545 | def _fstring_FormattedValue(self, t, write): 546 | write("{") 547 | expr = StringIO() 548 | Unparser(t.value, expr) 549 | expr = expr.getvalue().rstrip("\n") 550 | if expr.startswith("{"): 551 | write(" ") # Separate pair of opening brackets as "{ {" 552 | write(expr) 553 | if t.conversion != -1: 554 | conversion = chr(t.conversion) 555 | assert conversion in "sra" 556 | write("!{conversion}".format(conversion=conversion)) 557 | if t.format_spec: 558 | write(":") 559 | meth = getattr(self, "_fstring_" + type(t.format_spec).__name__) 560 | meth(t.format_spec, write) 561 | write("}") 562 | 563 | def _Name(self, t): 564 | # NOTE: PY2, PY3 grammar: Name(identifier id, expr_context ctx) 565 | # NOTE: Reason: Use class name + context name. `parse_python.py:L125-127`. 566 | # ETH parser merges the value of `expr_context` into its parent node. 567 | # From [PY2 grammar](https://docs.python.org/2/library/ast.html#abstract-grammar): 568 | # ``` 569 | # expr_context = Load | Store | Del | AugLoad | AugStore | Param 570 | # ``` 571 | self.write(t.id, type="Name" + t.ctx.__class__.__name__) 572 | 573 | def _NameConstant(self, t): 574 | # NOTE: This is not part of PY2 and will be removed PY3.8+. 575 | # NOTE: Use class name. Similar to the case of "str". 576 | self.write(repr(t.value), type="NameConstant") 577 | 578 | def _Repr(self, t): 579 | self.write("`") 580 | self.dispatch(t.value) 581 | self.write("`") 582 | 583 | def _write_constant(self, value): 584 | # NOTE: Reason: Use class name. Similar to the case of "Str". 585 | if isinstance(value, (float, complex)): 586 | # Substitute overflowing decimal literal for AST infinities. 587 | self.write(repr(value).replace("inf", INFSTR), type="Constant") 588 | else: 589 | self.write(repr(value), type="Constant") 590 | 591 | def _Constant(self, t): 592 | # NOTE: This is not part of PY2 and will be removed PY3.8+. 593 | value = t.value 594 | if isinstance(value, tuple): 595 | self.write("(") 596 | if len(value) == 1: 597 | self._write_constant(value[0]) 598 | self.write(",") 599 | else: 600 | interleave(lambda: self.write(", "), self._write_constant, value) 601 | self.write(")") 602 | elif value is Ellipsis: # instead of `...` for Py2 compatibility 603 | self.write("...") 604 | else: 605 | if t.kind == "u": 606 | self.write("u") 607 | self._write_constant(t.value) 608 | 609 | def _Num(self, t): 610 | # NOTE: Reason: Use class name. `parse_python.py:L54-55`. 611 | # NOTE: Here we use `repr()` while `parse_python.py` uses `unicode()`. 612 | # This causes disparity such as: 613 | # | value | repr() | str() | unicode() | notes | 614 | # | ----- | ------ | ----- | --------- | ----- | 615 | # | 1L | '1L' | '1' | u'1' | long int | 616 | # | 3e13 | '30000000000000.0' | '3e+13' | u'3e+13' | exponent notation | 617 | # | 1254213006.517507 | '1254213006.517507' | '1254213006.52' | u'1254213006.52' | floating point precision | 618 | # Here we keep the part as it is to preserve consistency. 619 | repr_n = repr(t.n) 620 | if six.PY3: 621 | self.write(repr_n.replace("inf", INFSTR), type="Num") 622 | else: 623 | # Parenthesize negative numbers, to avoid turning (-1)**2 into -1**2. 624 | if repr_n.startswith("-"): 625 | self.write("(") 626 | if "inf" in repr_n and repr_n.endswith("*j"): 627 | repr_n = repr_n.replace("*j", "j") 628 | # Substitute overflowing decimal literal for AST infinities. 629 | self.write(repr_n.replace("inf", INFSTR), type="Num") 630 | if repr_n.startswith("-"): 631 | self.write(")") 632 | 633 | def _List(self, t): 634 | self.write("[") 635 | interleave(lambda: self.write(", "), self.dispatch, t.elts) 636 | self.write("]") 637 | 638 | def _ListComp(self, t): 639 | self.write("[") 640 | self.dispatch(t.elt) 641 | for gen in t.generators: 642 | self.dispatch(gen) 643 | self.write("]") 644 | 645 | def _GeneratorExp(self, t): 646 | self.write("(") 647 | self.dispatch(t.elt) 648 | for gen in t.generators: 649 | self.dispatch(gen) 650 | self.write(")") 651 | 652 | def _SetComp(self, t): 653 | self.write("{") 654 | self.dispatch(t.elt) 655 | for gen in t.generators: 656 | self.dispatch(gen) 657 | self.write("}") 658 | 659 | def _DictComp(self, t): 660 | self.write("{") 661 | self.dispatch(t.key) 662 | self.write(": ") 663 | self.dispatch(t.value) 664 | for gen in t.generators: 665 | self.dispatch(gen) 666 | self.write("}") 667 | 668 | def _comprehension(self, t): 669 | if getattr(t, "is_async", False): 670 | self.write(" async for ") 671 | else: 672 | self.write(" for ") 673 | self.dispatch(t.target) 674 | self.write(" in ") 675 | self.dispatch(t.iter) 676 | for if_clause in t.ifs: 677 | self.write(" if ") 678 | self.dispatch(if_clause) 679 | 680 | def _IfExp(self, t): 681 | self.write("(") 682 | self.dispatch(t.body) 683 | self.write(" if ") 684 | self.dispatch(t.test) 685 | self.write(" else ") 686 | self.dispatch(t.orelse) 687 | self.write(")") 688 | 689 | def _Set(self, t): 690 | assert t.elts # should be at least one element 691 | self.write("{") 692 | interleave(lambda: self.write(", "), self.dispatch, t.elts) 693 | self.write("}") 694 | 695 | def _Dict(self, t): 696 | self.write("{") 697 | 698 | def write_key_value_pair(k, v): 699 | self.dispatch(k) 700 | self.write(": ") 701 | self.dispatch(v) 702 | 703 | def write_item(item): 704 | k, v = item 705 | if k is None: 706 | # for dictionary unpacking operator in dicts {**{'y': 2}} 707 | # see PEP 448 for details 708 | self.write("**") 709 | self.dispatch(v) 710 | else: 711 | write_key_value_pair(k, v) 712 | 713 | interleave(lambda: self.write(", "), write_item, zip(t.keys, t.values)) 714 | self.write("}") 715 | 716 | def _Tuple(self, t): 717 | self.write("(") 718 | if len(t.elts) == 1: 719 | elt = t.elts[0] 720 | self.dispatch(elt) 721 | self.write(",") 722 | else: 723 | interleave(lambda: self.write(", "), self.dispatch, t.elts) 724 | self.write(")") 725 | 726 | unop = {"Invert": "~", "Not": "not", "UAdd": "+", "USub": "-"} 727 | 728 | def _UnaryOp(self, t): 729 | self.write("(") 730 | self.write(self.unop[t.op.__class__.__name__]) 731 | self.write(" ") 732 | if six.PY2 and isinstance(t.op, ast.USub) and isinstance(t.operand, ast.Num): 733 | # If we're applying unary minus to a number, parenthesize the number. 734 | # This is necessary: -2147483648 is different from -(2147483648) on 735 | # a 32-bit machine (the first is an int, the second a long), and 736 | # -7j is different from -(7j). (The first has real part 0.0, the second 737 | # has real part -0.0.) 738 | self.write("(") 739 | self.dispatch(t.operand) 740 | self.write(")") 741 | else: 742 | self.dispatch(t.operand) 743 | self.write(")") 744 | 745 | binop = { 746 | "Add": "+", 747 | "Sub": "-", 748 | "Mult": "*", 749 | "MatMult": "@", 750 | "Div": "/", 751 | "Mod": "%", 752 | "LShift": "<<", 753 | "RShift": ">>", 754 | "BitOr": "|", 755 | "BitXor": "^", 756 | "BitAnd": "&", 757 | "FloorDiv": "//", 758 | "Pow": "**", 759 | } 760 | 761 | def _BinOp(self, t): 762 | self.write("(") 763 | self.dispatch(t.left) 764 | self.write(" ") 765 | self.write(self.binop[t.op.__class__.__name__]) 766 | self.write(" ") 767 | self.dispatch(t.right) 768 | self.write(")") 769 | 770 | cmpops = { 771 | "Eq": "==", 772 | "NotEq": "!=", 773 | "Lt": "<", 774 | "LtE": "<=", 775 | "Gt": ">", 776 | "GtE": ">=", 777 | "Is": "is", 778 | "IsNot": "is not", 779 | "In": "in", 780 | "NotIn": "not in", 781 | } 782 | 783 | def _Compare(self, t): 784 | self.write("(") 785 | self.dispatch(t.left) 786 | for o, e in zip(t.ops, t.comparators): 787 | self.write(" ") 788 | self.write(self.cmpops[o.__class__.__name__]) 789 | self.write(" ") 790 | self.dispatch(e) 791 | self.write(")") 792 | 793 | boolops = {ast.And: "and", ast.Or: "or"} 794 | 795 | def _BoolOp(self, t): 796 | self.write("(") 797 | s = " %s " % self.boolops[t.op.__class__] 798 | interleave(lambda: self.write(s), self.dispatch, t.values) 799 | self.write(")") 800 | 801 | def _Attribute(self, t): 802 | self.dispatch(t.value) 803 | # Special case: 3.__abs__() is a syntax error, so if t.value 804 | # is an integer literal then we need to either parenthesize 805 | # it or add an extra space to get 3 .__abs__(). 806 | if isinstance( 807 | t.value, getattr(ast, "Constant", getattr(ast, "Num", None)) 808 | ) and isinstance(t.value.n, int): 809 | self.write(" ") 810 | self.write(".") 811 | # NOTE: Reason: Special case. `parse_python.py:L131-132`. 812 | self.write(t.attr, type="attr") 813 | 814 | def _Call(self, t): 815 | self.dispatch(t.func) 816 | self.write("(") 817 | comma = False 818 | for e in t.args: 819 | if comma: 820 | self.write(", ") 821 | else: 822 | comma = True 823 | self.dispatch(e) 824 | for e in t.keywords: 825 | if comma: 826 | self.write(", ") 827 | else: 828 | comma = True 829 | self.dispatch(e) 830 | if sys.version_info[:2] < (3, 5): 831 | if t.starargs: 832 | if comma: 833 | self.write(", ") 834 | else: 835 | comma = True 836 | self.write("*") 837 | self.dispatch(t.starargs) 838 | if t.kwargs: 839 | if comma: 840 | self.write(", ") 841 | else: 842 | comma = True 843 | self.write("**") 844 | self.dispatch(t.kwargs) 845 | self.write(")") 846 | 847 | def _Subscript(self, t): 848 | self.dispatch(t.value) 849 | self.write("[") 850 | self.dispatch(t.slice) 851 | self.write("]") 852 | 853 | def _Starred(self, t): 854 | self.write("*") 855 | self.dispatch(t.value) 856 | 857 | # slice 858 | def _Ellipsis(self, t): 859 | self.write("...") 860 | 861 | def _Index(self, t): 862 | self.dispatch(t.value) 863 | 864 | def _Slice(self, t): 865 | if t.lower: 866 | self.dispatch(t.lower) 867 | self.write(":") 868 | if t.upper: 869 | self.dispatch(t.upper) 870 | if t.step: 871 | self.write(":") 872 | self.dispatch(t.step) 873 | 874 | def _ExtSlice(self, t): 875 | interleave(lambda: self.write(", "), self.dispatch, t.dims) 876 | 877 | # argument 878 | def _arg(self, t): 879 | # NOTE: This is not part of PY2. 880 | # NOTE: Reason: Use class name. Default behaviour of `parse_python.py`. 881 | self.write(t.arg, type="arg") 882 | if t.annotation: 883 | self.write(": ") 884 | self.dispatch(t.annotation) 885 | 886 | # others 887 | def _arguments(self, t): 888 | # NOTE: PY2 grammar: arguments = ( 889 | # expr* args, identifier? vararg, 890 | # identifier? kwarg, expr* defaults) 891 | # NOTE: PY3.7 grammar: arguments = ( 892 | # arg* args, arg? vararg, arg* kwonlyargs, 893 | # expr* kw_defaults, arg? kwarg, expr* defaults) 894 | # NOTE: PY3.8 grammar: arguments = ( 895 | # arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs, 896 | # expr* kw_defaults, arg? kwarg, expr* defaults) 897 | first = True 898 | # normal arguments 899 | # NOTE: `posonlyargs` is not part of PY2 and appears only starting PY3.8. 900 | all_args = getattr(t, "posonlyargs", []) + t.args 901 | defaults = [None] * (len(all_args) - len(t.defaults)) + t.defaults 902 | for index, elements in enumerate(zip(all_args, defaults), 1): 903 | a, d = elements 904 | if first: 905 | first = False 906 | else: 907 | self.write(", ") 908 | self.dispatch(a) 909 | if d: 910 | self.write("=") 911 | self.dispatch(d) 912 | if index == len(getattr(t, "posonlyargs", ())): 913 | self.write(", ") 914 | self.write("/") 915 | 916 | # varargs, or bare '*' if no varargs but keyword-only arguments present 917 | # NOTE: `kwonlyargs` is not part of PY2. 918 | if t.vararg or getattr(t, "kwonlyargs", False): 919 | if first: 920 | first = False 921 | else: 922 | self.write(", ") 923 | self.write("*") 924 | if t.vararg: 925 | if hasattr(t.vararg, "arg"): 926 | # NOTE: This is not part of PY2. 927 | # NOTE: Reason: Special case. Following the case of "vararg". 928 | self.write(t.vararg.arg, type="vararg") 929 | if t.vararg.annotation: 930 | self.write(": ") 931 | self.dispatch(t.vararg.annotation) 932 | else: 933 | # NOTE: Reason: Special case. `parse_python.py:L105`. 934 | self.write(t.vararg, type="vararg") 935 | if getattr(t, "varargannotation", None): 936 | self.write(": ") 937 | self.dispatch(t.varargannotation) 938 | 939 | # keyword-only arguments 940 | if getattr(t, "kwonlyargs", False): 941 | for a, d in zip(t.kwonlyargs, t.kw_defaults): 942 | if first: 943 | first = False 944 | else: 945 | self.write(", ") 946 | self.dispatch(a), 947 | if d: 948 | self.write("=") 949 | self.dispatch(d) 950 | 951 | # kwargs 952 | if t.kwarg: 953 | if first: 954 | first = False 955 | else: 956 | self.write(", ") 957 | if hasattr(t.kwarg, "arg"): 958 | # NOTE: This is not part of PY2. 959 | self.write("**") 960 | # NOTE: Reason: Special case. Following the case of "kwarg". 961 | self.write(t.kwarg.arg, type="kwarg") 962 | if t.kwarg.annotation: 963 | self.write(": ") 964 | self.dispatch(t.kwarg.annotation) 965 | else: 966 | self.write("**") 967 | # NOTE: Reason: Special case. `parse_python.py:L107`. 968 | self.write(t.kwarg, type="kwarg") 969 | if getattr(t, "kwargannotation", None): 970 | self.write(": ") 971 | self.dispatch(t.kwargannotation) 972 | 973 | def _keyword(self, t): 974 | if t.arg is None: 975 | # starting from Python 3.5 this denotes a kwargs part of the invocation 976 | self.write("**") 977 | else: 978 | # NOTE: Reason: Use class name. `parse_python.py:L72-73`. 979 | self.write(t.arg, type="keyword") 980 | self.write("=") 981 | self.dispatch(t.value) 982 | 983 | def _Lambda(self, t): 984 | self.write("(") 985 | self.write("lambda ") 986 | self.dispatch(t.args) 987 | self.write(": ") 988 | self.dispatch(t.body) 989 | self.write(")") 990 | 991 | def _alias(self, t): 992 | # NOTE: Reason: Use class name. `parse_python.py:L59`. 993 | self.write(t.name, type="alias") 994 | if t.asname: 995 | self.write(" as ") 996 | # NOTE: Use "identifier". `parse_python.py:L61`. 997 | self.write(t.asname, type="identifier") 998 | 999 | def _withitem(self, t): 1000 | self.dispatch(t.context_expr) 1001 | if t.optional_vars: 1002 | self.write(" as ") 1003 | self.dispatch(t.optional_vars) 1004 | -------------------------------------------------------------------------------- /models/seq/dataset.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import torch 9 | from dataset.dataset import BaseDataset, BaseSetup, BaseVocab 10 | 11 | 12 | class Setup(BaseSetup): 13 | def _create_vocab(self): 14 | return Vocab(self.filepaths["vocab"]) 15 | 16 | def _create_dataset(self, fp, ids_fp): 17 | return Dataset(fp, ids_fp) 18 | 19 | 20 | class Vocab(BaseVocab): 21 | def convert(self, line): 22 | dp, ext = line 23 | dp_conv = [ 24 | self.vocab2idx[token] if token in self.vocab2idx else self.unk_idx 25 | for token in dp 26 | ] 27 | return [dp_conv, ext] 28 | 29 | 30 | class Dataset(BaseDataset): 31 | @staticmethod 32 | def collate(seqs, pad_idx): 33 | max_len = max(len(seq[0][0]) for seq in seqs) 34 | max_len = max(max_len, 2) 35 | input_seqs = [] 36 | target_seqs = [] 37 | extended = [] 38 | ids = {name: [] for name in seqs[0][1].keys()} 39 | 40 | for i, ((seq, ext), ids_lst) in enumerate(seqs): 41 | padding = [pad_idx] * (max_len - len(seq)) 42 | input_seqs.append(seq[:-1] + padding) 43 | target_seqs.append(seq[1:] + padding) 44 | extended.append(ext) 45 | for name, lst in ids_lst.items(): 46 | ids[name] += [j - 1 + (max_len - 1) * i for j in lst] 47 | 48 | return { 49 | "input_seq": torch.tensor(input_seqs), 50 | "target_seq": torch.tensor(target_seqs), 51 | "extended": torch.tensor(extended), 52 | "ids": ids, 53 | } 54 | -------------------------------------------------------------------------------- /models/seq/generate_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import argparse 9 | import ast 10 | import json 11 | import logging 12 | import os 13 | from collections import namedtuple 14 | 15 | import six 16 | from utils import file_tqdm, separate_dps 17 | from models.source_code.astunparser import Unparser 18 | 19 | 20 | SrcASTToken = namedtuple("SrcASTToken", "text type") 21 | logging.basicConfig(level=logging.INFO) 22 | 23 | 24 | def get_leaf_ids(types_): 25 | ids = {"leaf_ids": []} 26 | for i, v in enumerate(types_): 27 | if v is not None: 28 | ids["leaf_ids"].append(i) 29 | return ids 30 | 31 | 32 | def get_value_ids(types_): 33 | ids = {"attr_ids": [], "num_ids": [], "name_ids": [], "param_ids": []} 34 | for i, v in enumerate(types_): 35 | if v == "attr": 36 | ids["attr_ids"].append(i) 37 | elif v == "Num": 38 | ids["num_ids"].append(i) 39 | elif v in {"NameStore", "NameLoad"}: 40 | ids["name_ids"].append(i) 41 | elif v == "NameParam": 42 | ids["param_ids"].append(i) 43 | return ids 44 | 45 | 46 | class MyListFile(list): 47 | def write(self, text, type=None): 48 | text = text.strip() 49 | if len(text) > 0: 50 | self.append(SrcASTToken(text, type)) 51 | 52 | def flush(self): 53 | pass 54 | 55 | def transpose(self, max_len): 56 | tokens = [tt.text for tt in self] 57 | types_ = [tt.type for tt in self] 58 | return separate_dps(tokens, max_len), separate_dps(types_, max_len) 59 | 60 | 61 | def my_tokenize(code_str, n_ctx): 62 | t = ast.parse(code_str) 63 | lst = MyListFile() 64 | Unparser(t, lst) 65 | return lst.transpose(n_ctx) 66 | 67 | 68 | def main(): 69 | parser = argparse.ArgumentParser(description="Generate datapoints from source code") 70 | parser.add_argument( 71 | "--files_fp", "-f", help="Filepath with the filenames to be parsed" 72 | ) 73 | parser.add_argument( 74 | "--out_fp", "-o", default="/tmp/dps.txt", help="Filepath with the output dps" 75 | ) 76 | parser.add_argument("--base_dir", "-b", help="Base dir to append for the fps") 77 | parser.add_argument( 78 | "--n_ctx", "-c", type=int, default=1000, help="Number of contexts for each dp" 79 | ) 80 | parser.add_argument( 81 | "id_type", 82 | choices=["leaf", "value", "token", "all"], 83 | default="", 84 | help="Which ids to generate. Default = get the tokens", 85 | ) 86 | args = parser.parse_args() 87 | if os.path.exists(args.out_fp): 88 | os.remove(args.out_fp) 89 | logging.info("Number of context: {}".format(args.n_ctx)) 90 | 91 | num_dps = 0 92 | logging.info("Loading files from: {}".format(args.base_dir)) 93 | with open(args.files_fp, "r") as f, open(args.out_fp, "w") as fout: 94 | for line in file_tqdm(f): 95 | fp = os.path.join(args.base_dir, line.strip()) 96 | try: 97 | aug_tokens, aug_types = my_tokenize(open(fp).read(), args.n_ctx) 98 | for (tokens, ext), (types_, _) in zip(aug_tokens, aug_types): 99 | if len(tokens) > 1: 100 | if args.id_type == "leaf": 101 | json.dump(get_leaf_ids(types_), fp=fout) 102 | elif args.id_type == "value": 103 | json.dump(get_value_ids(types_), fp=fout) 104 | elif args.id_type == "all": 105 | ids = get_leaf_ids(types_) 106 | ids.update(get_value_ids(types_)) 107 | json.dump(ids, fp=fout) 108 | else: 109 | json.dump([tokens, ext], fp=fout) 110 | fout.write("\n") 111 | num_dps += 1 112 | except: 113 | continue 114 | logging.info("Wrote {} datapoints to {}".format(num_dps, args.out_fp)) 115 | 116 | 117 | if __name__ == "__main__": 118 | main() 119 | -------------------------------------------------------------------------------- /models/trav_trans/dataset.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import torch 9 | from dataset.dataset import BaseDataset, BaseSetup, BaseVocab 10 | 11 | 12 | class Setup(BaseSetup): 13 | def _create_vocab(self): 14 | return Vocab(self.filepaths["vocab"]) 15 | 16 | def _create_dataset(self, fp, ids_fp): 17 | return Dataset(fp, ids_fp) 18 | 19 | 20 | class Vocab(BaseVocab): 21 | def convert(self, line): 22 | dp, ext = line 23 | dp_conv = [ 24 | self.vocab2idx[token] if token in self.vocab2idx else self.unk_idx 25 | for token in dp 26 | ] 27 | return [dp_conv, ext] 28 | 29 | 30 | class Dataset(BaseDataset): 31 | @staticmethod 32 | def collate(seqs, pad_idx): 33 | max_len = max(len(seq[0][0]) for seq in seqs) 34 | max_len = max(max_len, 2) 35 | input_seqs = [] 36 | target_seqs = [] 37 | extended = [] 38 | ids = {name: [] for name in seqs[0][1].keys()} 39 | 40 | for i, ((seq, ext), ids_lst) in enumerate(seqs): 41 | padding = [pad_idx] * (max_len - len(seq)) 42 | input_seqs.append(seq[:-1] + padding) 43 | target_seqs.append(seq[1:] + padding) 44 | extended.append(ext) 45 | for name, lst in ids_lst.items(): 46 | ids[name] += [j - 1 + (max_len - 1) * i for j in lst] 47 | 48 | return { 49 | "input_seq": torch.tensor(input_seqs), 50 | "target_seq": torch.tensor(target_seqs), 51 | "extended": torch.tensor(extended), 52 | "ids": ids, 53 | } 54 | -------------------------------------------------------------------------------- /models/trav_trans/generate_ast_ids.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import argparse 9 | import json 10 | import logging 11 | import os 12 | 13 | from utils import file_tqdm, separate_dps 14 | 15 | 16 | logging.basicConfig(level=logging.INFO) 17 | 18 | 19 | def get_leaf_ids(ast): 20 | ids = {"leaf_ids": [], "internal_ids": []} 21 | for i, node in enumerate(ast): 22 | if "value" in node: 23 | ids["leaf_ids"].append(i) 24 | else: 25 | ids["internal_ids"].append(i) 26 | return ids 27 | 28 | 29 | def get_value_ids(ast): 30 | ids = {"attr_ids": [], "num_ids": [], "name_ids": [], "param_ids": []} 31 | for i, node in enumerate(ast): 32 | if "type" in node: 33 | if node["type"] == "attr": 34 | ids["attr_ids"].append( 35 | i + 1 36 | ) # + 1 since i is the type, and we want the value 37 | elif node["type"] == "Num": 38 | ids["num_ids"].append(i + 1) 39 | elif node["type"] in {"NameLoad", "NameStore"}: 40 | ids["name_ids"].append(i + 1) 41 | elif node["type"] == "NameParam": 42 | ids["param_ids"].append(i + 1) 43 | return ids 44 | 45 | 46 | def get_type_ids(ast): 47 | ids = { 48 | "call_ids": [], 49 | "assign_ids": [], 50 | "return_ids": [], 51 | "list_ids": [], 52 | "dict_ids": [], 53 | "raise_ids": [], 54 | } 55 | for i, node in enumerate(ast): 56 | if "type" in node: 57 | type_ = node["type"] 58 | if type_ == "Call": 59 | ids["call_ids"].append(i) 60 | elif type_ == "Assign": 61 | ids["assign_ids"].append(i) 62 | elif type_ == "Return": 63 | ids["return_ids"].append(i) 64 | elif type_ in {"ListComp", "ListLoad", "ListStore"}: 65 | ids["list_ids"].append(i) 66 | elif type_ in {"DictComp", "DictLoad", "DictStore"}: 67 | ids["dict_ids"].append(i) 68 | elif type_ == "Raise": 69 | ids["raise_ids"].append(i) 70 | return ids 71 | 72 | 73 | def main(): 74 | parser = argparse.ArgumentParser( 75 | description="Generate ids (leaf, values, types) from AST" 76 | ) 77 | parser.add_argument( 78 | "--ast_fp", "-a", help="Filepath with the new ASTs to be parsed" 79 | ) 80 | parser.add_argument( 81 | "--out_fp", "-o", default="/tmp/ids.txt", help="Filepath for the output ids" 82 | ) 83 | parser.add_argument( 84 | "--n_ctx", "-c", type=int, default=1000, help="Number of contexts for each dp" 85 | ) 86 | parser.add_argument( 87 | "id_type", 88 | choices=["leaf", "value", "type", "all"], 89 | default="leaf", 90 | help="Which ids to generate. Default = leaf", 91 | ) 92 | 93 | args = parser.parse_args() 94 | if os.path.exists(args.out_fp): 95 | os.remove(args.out_fp) 96 | logging.info("Type of id to get: {}".format(args.id_type)) 97 | 98 | logging.info("Loading dps from: {}".format(args.ast_fp)) 99 | with open(args.ast_fp, "r") as f, open(args.out_fp, "w") as fout: 100 | for line in file_tqdm(f): 101 | dp = json.loads(line.strip()) 102 | asts = separate_dps(dp, args.n_ctx) 103 | for ast, _ in asts: 104 | ids = {} 105 | if len(ast) > 1: 106 | if args.id_type in {"leaf", "all"}: 107 | ids.update(get_leaf_ids(ast)) 108 | if args.id_type in {"value", "all"}: 109 | ids.update(get_value_ids(ast)) 110 | if args.id_type in {"type", "all"}: 111 | ids.update(get_type_ids(ast)) 112 | 113 | json.dump(ids, fp=fout) 114 | fout.write("\n") 115 | logging.info("Wrote to: {}".format(args.out_fp)) 116 | 117 | 118 | if __name__ == "__main__": 119 | main() 120 | -------------------------------------------------------------------------------- /models/trav_trans/generate_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import argparse 9 | import json 10 | import logging 11 | import os 12 | 13 | from utils import file_tqdm, get_dfs, separate_dps 14 | 15 | 16 | logging.basicConfig(level=logging.INFO) 17 | 18 | 19 | def main(): 20 | parser = argparse.ArgumentParser(description="Generate datapoints from AST") 21 | parser.add_argument("--ast_fp", "-a", help="Filepath with the ASTs to be parsed") 22 | parser.add_argument( 23 | "--out_fp", "-o", default="/tmp/dps.txt", help="Filepath for the output dps" 24 | ) 25 | parser.add_argument( 26 | "--n_ctx", "-c", type=int, default=1000, help="Number of contexts for each dp" 27 | ) 28 | args = parser.parse_args() 29 | if os.path.exists(args.out_fp): 30 | os.remove(args.out_fp) 31 | logging.info("Number of context: {}".format(args.n_ctx)) 32 | 33 | num_dps = 0 34 | logging.info("Loading asts from: {}".format(args.ast_fp)) 35 | with open(args.ast_fp, "r") as f, open(args.out_fp, "w") as fout: 36 | for line in file_tqdm(f): 37 | dp = json.loads(line.strip()) 38 | asts = separate_dps(dp, args.n_ctx) 39 | for ast, extended in asts: 40 | if len(ast) > 1: 41 | json.dump([get_dfs(ast), extended], fp=fout) 42 | fout.write("\n") 43 | num_dps += 1 44 | 45 | logging.info("Wrote {} datapoints to {}".format(num_dps, args.out_fp)) 46 | 47 | 48 | if __name__ == "__main__": 49 | main() 50 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Copyright (c) Facebook, Inc. and its affiliates. 4 | # All rights reserved. 5 | # 6 | # This source code is licensed under the license found in the 7 | # LICENSE file in the root directory of this source tree. 8 | 9 | import json 10 | import logging 11 | from functools import partial 12 | from typing import Set 13 | 14 | import torch 15 | 16 | 17 | torch.manual_seed(0) 18 | logging.getLogger().setLevel(logging.INFO) 19 | 20 | 21 | def prepare_data(batch, device): 22 | x = batch["input_seq"].to(device) 23 | y = batch["target_seq"].to(device) 24 | ext = batch["extended"] 25 | rel = batch["rel_mask"].to(device) if "rel_mask" in batch else None 26 | child = batch["child_mask"].to(device) if "child_mask" in batch else None 27 | paths = batch["root_paths"].to(device) if "root_paths" in batch else None 28 | return x, y, ext, rel, child, paths 29 | 30 | 31 | def build_dataloader(dataset, batch_size, collate_fn, train_split=0.90): 32 | train_len = int(train_split * len(dataset)) 33 | train_dataset, val_dataset = torch.utils.data.random_split( 34 | dataset, lengths=([train_len, len(dataset) - train_len]) 35 | ) 36 | logging.info("Batch size: {}".format(batch_size)) 37 | logging.info( 38 | "Train / val split ({}%): {} / {}".format( 39 | 100 * train_split, len(train_dataset), len(val_dataset) 40 | ) 41 | ) 42 | train_dataloader = torch.utils.data.DataLoader( 43 | train_dataset, 44 | batch_size=batch_size, 45 | collate_fn=collate_fn, 46 | num_workers=16, 47 | shuffle=True, 48 | drop_last=True, 49 | pin_memory=False, 50 | ) 51 | logging.info("len(train_dataloader) = {}".format(len(train_dataloader))) 52 | val_dataloader = torch.utils.data.DataLoader( 53 | val_dataset, 54 | batch_size=int(batch_size / 4), 55 | collate_fn=collate_fn, 56 | num_workers=16, 57 | shuffle=True, 58 | drop_last=True, 59 | pin_memory=False, 60 | ) 61 | logging.info("len(val_dataloader) = {}".format(len(val_dataloader))) 62 | return train_dataloader, val_dataloader 63 | 64 | 65 | def build_test_dataloader(test_dataset, batch_size, collate_fn): 66 | test_dataloader = torch.utils.data.DataLoader( 67 | test_dataset, 68 | batch_size=batch_size, 69 | collate_fn=collate_fn, 70 | num_workers=16, 71 | shuffle=False, 72 | drop_last=True, 73 | pin_memory=True, 74 | ) 75 | logging.info("len(test_dataloader) = {}".format(len(test_dataloader))) 76 | return test_dataloader 77 | 78 | 79 | def build_metrics(loss_fn, unk_idx_set: Set[int], pad_idx, ids_str): 80 | from ignite.metrics import Loss, TopKCategoricalAccuracy 81 | 82 | def strip(out, id_str="all"): 83 | if id_str != "all": 84 | ids = out[id_str] 85 | y_pred = out["y_pred"][ids] 86 | y = out["y"][ids] 87 | else: 88 | y_pred = out["y_pred"] 89 | y = out["y"] 90 | idx = y != pad_idx 91 | return y_pred[idx], y[idx] 92 | 93 | def topk_trans(id_str): 94 | def wrapped(out): 95 | y_pred, y = strip(out, id_str) 96 | for idx in unk_idx_set: # non-existing tokens 97 | y[y == idx] = -2 98 | return y_pred, y 99 | 100 | return wrapped 101 | 102 | def topk_ex_unk_trans(id_str): 103 | def wrapped(out): 104 | y_pred, y = strip(out, id_str) 105 | idx_tensor = torch.ones(y.shape, dtype=torch.bool) 106 | for idx in unk_idx_set: 107 | idx_tensor[y == idx] = False 108 | return y_pred[idx_tensor], y[idx_tensor] 109 | 110 | return wrapped 111 | 112 | def loss_trans(): 113 | def wrapped(out): 114 | return strip(out) 115 | 116 | return wrapped 117 | 118 | metrics = {"_loss": Loss(loss_fn, loss_trans())} 119 | for id_str in ["attr_ids", "leaf_ids"] + ["all"]: 120 | # reporting metrics for attr and leaf only 121 | metrics["{}_acc".format(id_str)] = TopKCategoricalAccuracy( 122 | 1, topk_trans(id_str) 123 | ) 124 | 125 | return metrics 126 | 127 | 128 | def build_evaluator(model, metrics, metrics_fp, device, pad_idx): 129 | from ignite.contrib.handlers import ProgressBar 130 | from ignite.engine import Engine, Events 131 | 132 | @Engine 133 | @torch.no_grad() 134 | def evaluator(engine, batch): 135 | model.eval() 136 | x, y, ext, rel, child, paths = prepare_data(batch, device) 137 | y_pred = model(x, y, ext, rel, child, paths) 138 | # here we pad out the indices that have been evaluated before 139 | for i, ext_i in enumerate(ext): 140 | y[i][:ext_i] = pad_idx 141 | res = {"y_pred": y_pred.view(-1, y_pred.size(-1)), "y": y.view(-1)} 142 | res.update(batch["ids"]) 143 | return res 144 | 145 | for name, metric in metrics.items(): 146 | metric.attach(evaluator, name) 147 | ProgressBar(bar_format="").attach(evaluator, metric_names=[]) 148 | 149 | @evaluator.on(Events.COMPLETED) 150 | def log_val_metrics(engine): 151 | metrics = engine.state.metrics 152 | metrics = {name: "{:.4f}".format(num) for name, num in metrics.items()} 153 | # mrr 154 | metrics_str = json.dumps(metrics, indent=2, sort_keys=True) 155 | logging.info("val metrics: {}".format(metrics_str)) 156 | with open(metrics_fp, "a") as fout: 157 | fout.write(metrics_str) 158 | fout.write("\n") 159 | 160 | return evaluator 161 | 162 | 163 | def build_trainer( 164 | model, 165 | loss_fn, 166 | optimizer, 167 | train_dataloader, 168 | val_dataloader, 169 | run_dir, 170 | validator, 171 | device, 172 | score_fn=lambda engine: engine.state.metrics["all_acc"], 173 | ): 174 | from ignite.contrib.handlers import ProgressBar 175 | from ignite.engine import Engine, Events 176 | from ignite.handlers import EarlyStopping, ModelCheckpoint, TerminateOnNan 177 | from ignite.metrics import RunningAverage 178 | 179 | @Engine 180 | def trainer(engine, batch): 181 | model.train() 182 | x, y, ext, rel, child, paths = prepare_data(batch, device) 183 | loss = model(x, y, ext, rel, child, paths, return_loss=True) 184 | loss = loss.sum() 185 | optimizer.zero_grad() 186 | loss.backward() 187 | optimizer.step() 188 | return {"batchloss": loss.item()} 189 | 190 | # # validation first 191 | # @trainer.on(Events.STARTED) 192 | # def validate(engine): 193 | # validator.run(val_dataloader) 194 | 195 | RunningAverage(output_transform=lambda out: out["batchloss"]).attach( 196 | trainer, "batchloss" 197 | ) 198 | ProgressBar(bar_format="").attach(trainer, metric_names=["batchloss"]) 199 | 200 | # store the model before validation 201 | pre_model_handler = ModelCheckpoint( 202 | dirname=run_dir, 203 | filename_prefix="pre", 204 | n_saved=100, # save all bests 205 | save_interval=1, 206 | require_empty=False, 207 | ) 208 | trainer.add_event_handler( 209 | Events.EPOCH_COMPLETED, pre_model_handler, {"model": model} 210 | ) 211 | 212 | # validation 213 | @trainer.on(Events.EPOCH_COMPLETED) 214 | def validate(engine): 215 | validator.run(val_dataloader) 216 | 217 | # terminate on NaN 218 | trainer.add_event_handler(Events.ITERATION_COMPLETED, TerminateOnNan()) 219 | 220 | # store the best model 221 | best_model_handler = ModelCheckpoint( 222 | dirname=run_dir, 223 | filename_prefix="best", 224 | n_saved=100, # save all bests 225 | score_name="val_acc", 226 | score_function=score_fn, 227 | require_empty=False, 228 | ) 229 | validator.add_event_handler(Events.COMPLETED, best_model_handler, {"model": model}) 230 | 231 | # Early stopping 232 | es_handler = EarlyStopping(patience=5, score_function=score_fn, trainer=trainer) 233 | validator.add_event_handler(Events.COMPLETED, es_handler) 234 | 235 | return trainer 236 | 237 | 238 | def train( 239 | model, 240 | vocab, 241 | dataset, 242 | metrics_fp, 243 | loss_fn, 244 | lr, 245 | run_dir, 246 | batch_size, 247 | max_epochs, 248 | device, 249 | ids_str, 250 | ): 251 | collate_fn = partial(dataset.collate, pad_idx=vocab.pad_idx) 252 | train_dataloader, val_dataloader = build_dataloader( 253 | dataset, batch_size=batch_size, collate_fn=collate_fn 254 | ) 255 | metrics = build_metrics(loss_fn, vocab.unk_idx_set, vocab.pad_idx, ids_str) 256 | 257 | # run the trainer and validator 258 | validator = build_evaluator( 259 | model=model, 260 | metrics=metrics, 261 | metrics_fp=metrics_fp, 262 | device=device, 263 | pad_idx=vocab.pad_idx, 264 | ) 265 | trainer = build_trainer( 266 | model=model, 267 | loss_fn=loss_fn, 268 | optimizer=torch.optim.Adam(model.parameters(), lr=lr), 269 | train_dataloader=train_dataloader, 270 | val_dataloader=val_dataloader, 271 | run_dir=run_dir, 272 | validator=validator, 273 | device=device, 274 | ) 275 | trainer.run(train_dataloader, max_epochs=max_epochs) 276 | 277 | 278 | def eval_model( 279 | model, vocab, test_dataset, metrics_fp, loss_fn, batch_size, device, ids_str 280 | ): 281 | collate_fn = partial(test_dataset.collate, pad_idx=vocab.pad_idx) 282 | test_dataloader = build_test_dataloader( 283 | test_dataset, batch_size=batch_size, collate_fn=collate_fn 284 | ) 285 | metrics = build_metrics(loss_fn, vocab.unk_idx_set, vocab.pad_idx, ids_str) 286 | 287 | # run the evaluator 288 | evaluator = build_evaluator( 289 | model=model, 290 | metrics=metrics, 291 | metrics_fp=metrics_fp, 292 | device=device, 293 | pad_idx=vocab.pad_idx, 294 | ) 295 | evaluator.run(test_dataloader) 296 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | import math 9 | import multiprocessing as mp 10 | 11 | from tqdm import tqdm 12 | 13 | 14 | def line_positions(file_path): 15 | with open(file_path) as f: 16 | while True: 17 | pos = f.tell() 18 | if f.readline(): 19 | yield pos 20 | else: 21 | break 22 | 23 | 24 | def get_number_of_lines(fobj): 25 | nol = sum(1 for _ in fobj) 26 | fobj.seek(0) 27 | return nol 28 | 29 | 30 | def file_tqdm(f): 31 | return tqdm(f, total=get_number_of_lines(f)) 32 | 33 | 34 | def parallelize(iterable, f, f_args=(), worker_init=None, n_cores=None): 35 | if n_cores == 1: 36 | return _mp_iterate_over(f, iterable, f_args) 37 | if n_cores is None: 38 | n_cores = int(mp.cpu_count()) 39 | lst = list(iterable) 40 | chunksize = math.ceil(len(lst) / n_cores) 41 | with mp.Pool(processes=n_cores, initializer=worker_init) as pool: 42 | jobs = [ 43 | pool.apply_async( 44 | _mp_iterate_over, (f, lst[i * chunksize : (i + 1) * chunksize], f_args) 45 | ) 46 | for i in range(n_cores) 47 | ] 48 | multiple_results = [job.get() for job in jobs] 49 | results = flatten(multiple_results) 50 | return results 51 | 52 | 53 | def _mp_iterate_over(f, lst, f_args): 54 | return [f(x, *f_args) for x in lst] 55 | 56 | 57 | def flatten(list_of_lists): 58 | return [x for xs in list_of_lists for x in xs] 59 | 60 | 61 | ######################################################################## 62 | # generating dataset utils 63 | 64 | 65 | def get_dfs(ast, only_leaf=False): 66 | dp = [] 67 | for node in ast: 68 | if "value" in node: 69 | dp.append(node["value"]) 70 | else: 71 | if not only_leaf: 72 | dp.append(node["type"]) 73 | return dp 74 | 75 | 76 | def separate_dps(ast, max_len): 77 | """ 78 | Handles training / evaluation on long ASTs by splitting 79 | them into smaller ASTs of length max_len, with a sliding 80 | window of max_len / 2. 81 | 82 | Example: for an AST ast with length 1700, and max_len = 1000, 83 | the output will be: 84 | [[ast[0:1000], 0], [ast[500:1500], 1000], [ast[700:1700], 1500]] 85 | 86 | Input: 87 | ast : List[Dictionary] 88 | List of nodes in pre-order traversal. 89 | max_len : int 90 | 91 | Output: 92 | aug_asts : List[List[List, int]] 93 | List of (ast, beginning idx of unseen nodes) 94 | """ 95 | half_len = int(max_len / 2) 96 | if len(ast) <= max_len: 97 | return [[ast, 0]] 98 | 99 | aug_asts = [[ast[:max_len], 0]] 100 | i = half_len 101 | while i < len(ast) - max_len: 102 | aug_asts.append([ast[i : i + max_len], half_len]) 103 | i += half_len 104 | idx = max_len - (len(ast) - (i + half_len)) 105 | aug_asts.append([ast[-max_len:], idx]) 106 | return aug_asts 107 | 108 | 109 | def get_ancestors(ast): 110 | ancestors = {0: []} 111 | node2parent = {0: 0} 112 | for i, node in enumerate(ast): 113 | if "children" in node: 114 | for child in node["children"]: 115 | node2parent[child] = i 116 | ancestors[i] = [i] + ancestors[node2parent[i]] 117 | return ancestors 118 | 119 | 120 | def get_terminal_nodes(ast): 121 | terminal_nodes = [i for i, node in enumerate(ast) if "children" not in node] 122 | return terminal_nodes 123 | 124 | 125 | def tokenize(s): 126 | pattern = re.compile(r"(?