├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── __main__.py ├── build_parser ├── build_parser.py └── languages_java_py_cs.so ├── dataset ├── BPE.py ├── GetTypeNode.py ├── ParseTOASTPath.py ├── __init__.py ├── dataset.py ├── utils.py └── vocab.py ├── model ├── __init__.py ├── transformer.py └── treebert.py ├── requirements.txt └── trainer ├── __init__.py ├── optim_schedule.py └── pretrain.py /.gitignore: -------------------------------------------------------------------------------- 1 | data/ 2 | output/ 3 | .vscode/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TreeBERT 2 | 3 | This is an implementation of the model described in: TreeBERT: A Tree-Based Pre-Trained Model for Programming Language. 4 | In this paper, we propose TreeBERT, a tree-based pretrained model for programming language. TreeBERT follows the Transformer encoder-decoder architecture. To enable the Transformer to utilize the tree structure, we represent the AST corresponding to the code snippet as the set of the root node to terminal node paths as input and then introduce node position embedding to obtain the position of the node in the tree. We propose a hybrid objective applicable to AST to learn syntactic and semantic knowledge, i.e., tree masked language modeling (TMLM) and node order prediction (NOP). TreeBERT can be applied to a wide range of PL-oriented generation tasks by means of fine-tuning and without extensive modifications to the task-specific architecture. 5 | ## Requirements 6 | * python3 7 | * numpy 8 | * tree-sitter 9 | * torch 10 | * tqdm 11 | 12 | ## Pre-training Data Ready 13 | The pre-training dataset we use is the Python and Java pre-training corpus published by [CuBERT](https://github.com/google-research/google-research/tree/master/cubert). 14 | By running `dataset\ParseTOASTPath.py` you can transform the code snippet into an AST, extract the path from the root node to the terminal node in the AST, and standardize the format of the target code snippet. 15 | 16 | ## Fine-tuning Data Ready 17 | In method name prediction, we evaluate TreeBERT on two datasets, Python and Java, where the python dataset uses [py150](https://www.sri.inf.ethz.ch/py150) , and the Java dataset uses [java-small](https://s3.amazonaws.com/code2seq/datasets/java-small.tar.gz), [java-med](https://s3.amazonaws.com/code2seq/datasets/java-med.tar.gz), and [java-large](https://s3.amazonaws.com/code2seq/datasets/java-large.tar.gz). 18 | These data sets can be processed into the form required by the code summarization task by running `dataset\Get_FunctionDesc.py`. 19 | ``` 20 | { 21 | "function": Function, its function name is replaced by "__", 22 | "label": Function Name 23 | } 24 | ``` 25 | 26 | In code summarization, we use the Java dataset provided by [DeepCom](https://github.com/xing-hu/DeepCom/blob/master/data.7z) to fine-tune our model. 27 | ## Pre-training 28 | #### 1. Create vocab: 29 | ``` 30 | python dataset/vocab.py -c /home/pretrain_data_AST/ -o data/vocab.large -f 2 -m 32000 31 | ``` 32 | #### 2.Training TCBERT using GPU: 33 | ``` 34 | python __main__.py -td /home/pretrain_data_AST_train/ -vd /home/pretrain_data_AST_test/ -v data/vocab.large -o output/treebert.model --with_cuda True 35 | ``` 36 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from .model import Seq2Seq 2 | -------------------------------------------------------------------------------- /__main__.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import copy 3 | 4 | import torch 5 | from torch.utils.data import DataLoader 6 | 7 | from dataset import BPE, TokenVocab, TreeBERTDataset 8 | from model import Decoder, Encoder, Seq2Seq 9 | from trainer import BERTTrainer 10 | 11 | 12 | def train(): 13 | parser = argparse.ArgumentParser() 14 | parser.add_argument("-td", "--train_dataset", type=str, required=True, help="train set") 15 | parser.add_argument("-vd", "--valid_dataset", type=str, default=None, help="validation set") 16 | parser.add_argument("-v", "--vocab_path", required=True, type=str, help="vocab path") 17 | parser.add_argument("-o", "--output_path", required=True, type=str, help="model save path") 18 | 19 | parser.add_argument("-fs", "--feed_forward_hidden", type=int, default=4096, help="hidden size of feed-forward network") 20 | parser.add_argument("-hs", "--hidden", type=int, default=1024, help="hidden size of transformer model") 21 | parser.add_argument("-l", "--layers", type=int, default=6, help="number of transformer layers") 22 | parser.add_argument("-a", "--attn_heads", type=int, default=8, help="number of attention heads") 23 | parser.add_argument("-p", "--path_num", type=int, default=100, help="a AST's maximum path num") 24 | parser.add_argument("-n", "--node_num", type=int, default=20, help="a path's maximum node num") 25 | parser.add_argument("-c", "--code_len", type=int, default=200, help="maximum code len") 26 | 27 | parser.add_argument("-al", "--alpha", type=int, default=0.75, help="loss weight") 28 | parser.add_argument("-b", "--batch_size", type=int, default=4096, help="number of batch_size") 29 | parser.add_argument("-e", "--epochs", type=int, default=1, help="number of epochs") 30 | parser.add_argument("-w", "--num_workers", type=int, default=0, help="dataloader worker num") 31 | 32 | parser.add_argument("--with_cuda", type=bool, default=False, help="training with CUDA: true, or false") 33 | parser.add_argument("--log_freq", type=int, default=10, help="printing loss every n iter: setting n") 34 | parser.add_argument("--corpus_lines", type=int, default=None, help="total number of lines in corpus") 35 | parser.add_argument("--cuda_devices", type=int, nargs='+', default=None, help="CUDA device ids") 36 | 37 | parser.add_argument("--lr", type=float, default=1e-5, help="learning rate of adam") 38 | parser.add_argument("--adam_weight_decay", type=float, default=0.01, help="weight_decay of adam") 39 | parser.add_argument("--adam_beta1", type=float, default=0.9, help="adam first beta value") 40 | parser.add_argument("--adam_beta2", type=float, default=0.999, help="adam first beta value") 41 | 42 | args = parser.parse_args() 43 | 44 | print("Loading Vocab", args.vocab_path) 45 | vocab = TokenVocab.load_vocab(args.vocab_path) 46 | # source and target corpus share the vocab 47 | print("Vocab Size: ", len(vocab)) 48 | 49 | print("Loading Train Dataset") 50 | train_dataset = TreeBERTDataset(vocab, args.train_dataset, path_num=args.path_num, node_num=args.node_num, 51 | code_len=args.code_len, is_fine_tune=False, corpus_lines=args.corpus_lines) 52 | 53 | print("Loading valid Dataset") 54 | valid_dataset = TreeBERTDataset(vocab, args.valid_dataset, path_num=args.path_num, node_num=args.node_num, 55 | code_len=args.code_len, is_fine_tune=False, corpus_lines=args.corpus_lines) \ 56 | if args.valid_dataset is not None else None 57 | 58 | # Creating Dataloader 59 | train_data_loader = DataLoader(train_dataset, batch_size=args.batch_size, num_workers=args.num_workers) 60 | valid_data_loader = DataLoader(valid_dataset, batch_size=args.batch_size, num_workers=args.num_workers) \ 61 | if valid_dataset is not None else None 62 | 63 | print("Building model") 64 | dropout = 0.1 65 | enc= Encoder(len(vocab), args.node_num, args.hidden, args.layers, args.attn_heads, args.feed_forward_hidden, 66 | dropout, max_length = args.path_num) 67 | dec= Decoder(len(vocab), args.hidden, args.layers, args.attn_heads, args.feed_forward_hidden, 68 | dropout, max_length = args.code_len+2) 69 | 70 | PAD_IDX = vocab.pad_index 71 | transformer = Seq2Seq(enc, dec, args.hidden, PAD_IDX) 72 | 73 | print("Creating Trainer") 74 | trainer = BERTTrainer(transformer, args.alpha, len(vocab), train_dataloader=train_data_loader, test_dataloader=valid_data_loader, 75 | lr=args.lr, betas=(args.adam_beta1, args.adam_beta2), weight_decay=args.adam_weight_decay, 76 | with_cuda=args.with_cuda, cuda_devices=args.cuda_devices, log_freq=args.log_freq) 77 | 78 | print("Training Start") 79 | min_loss = 10 80 | loss = 0 81 | best_model = None 82 | for epoch in range(args.epochs): 83 | trainer.train(epoch) 84 | 85 | if valid_data_loader is not None: 86 | loss = trainer.test(epoch) 87 | 88 | if min_loss>loss: 89 | best_model = copy.deepcopy(trainer.transformer) 90 | 91 | trainer.save(epoch, best_model, args.output_path) 92 | 93 | train() 94 | -------------------------------------------------------------------------------- /build_parser/build_parser.py: -------------------------------------------------------------------------------- 1 | from tree_sitter import Language, Parser 2 | 3 | Language.build_library( 4 | 'build/my-languages.so', 5 | [ 6 | '/root/test_tree-sitter/tree-sitter-c-sharp', 7 | '/root/test_tree-sitter/tree-sitter-java', 8 | '/root/test_tree-sitter/tree-sitter-python' 9 | ] 10 | ) -------------------------------------------------------------------------------- /build_parser/languages_java_py_cs.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/17385/TreeBERT/67b808ab8f0193208af6fe5b907fd1f0abf5c4cd/build_parser/languages_java_py_cs.so -------------------------------------------------------------------------------- /dataset/BPE.py: -------------------------------------------------------------------------------- 1 | import re, collections 2 | 3 | class BPE(object): 4 | def __init__(self, sourceFile, targetFile, num_merges=5): 5 | print('==========') 6 | print("Adopt BPE") 7 | vocab = self.get_vocab(sourceFile, targetFile) 8 | 9 | self.tokens_frequencies, self.vocab_tokenization = self.get_tokens_from_vocab(vocab) 10 | 11 | for i in range(num_merges): 12 | pairs = self.get_stats(vocab) 13 | if not pairs: 14 | break 15 | best = max(pairs, key=pairs.get) 16 | vocab = self.merge_vocab(best, vocab) 17 | if(i % 100 == 0): 18 | print('Iter: {}'.format(i)) 19 | print('Number of tokens: {}'.format(len(self.tokens_frequencies.keys()))) 20 | print('==========') 21 | 22 | self.tokens_frequencies, self.vocab_tokenization = self.get_tokens_from_vocab(vocab) 23 | 24 | sorted_tokens_tuple = sorted(self.tokens_frequencies.items(), key=lambda item: (self.measure_token_length(item[0]), item[1]), reverse=True) 25 | self.sorted_tokens = [token for (token, freq) in sorted_tokens_tuple] 26 | 27 | print('==========') 28 | 29 | 30 | @staticmethod 31 | def encode(vocab_tokenization, tokenize_word, sorted_tokens, texts, max_subtoken_len=3): 32 | encode_output = [] 33 | for word_given in texts: 34 | word_given = word_given.lower() + '' 35 | 36 | if word_given in vocab_tokenization: 37 | tmpWord = vocab_tokenization[word_given] 38 | 39 | else: 40 | if(word_given==""): 41 | tmpWord = [""] 42 | else: 43 | tmpWord = tokenize_word(string=word_given, sorted_tokens=sorted_tokens, unknown_token='') 44 | 45 | tmpWord = tmpWord[:max_subtoken_len] 46 | if (len(tmpWord)" for _ in range(max_subtoken_len-len(tmpWord))] 48 | tmpWord.extend(padding) 49 | encode_output.append(tmpWord) 50 | return encode_output 51 | 52 | @staticmethod 53 | def decode(): 54 | ''' 55 | TODO: concatenate all the tokens together and replace "<\w> with space 56 | ''' 57 | pass 58 | 59 | def get_vocab(self, sourceFile, targetFile): 60 | vocab = collections.Counter() 61 | with open(sourceFile, 'r', encoding='utf-8') as fhand: 62 | for line in fhand: 63 | words = line.replace("\n", "").replace("\t", " ").replace("|", " ").replace("\/?", "").replace("/", " / ").split() 64 | for word in words: 65 | vocab[' '.join(list(word)) + ' '] += 1 66 | with open(targetFile, 'r', encoding='utf-8') as fhand: 67 | for line in fhand: 68 | words = line.replace("\n", "").replace("\t", " ").replace("\/?", "").replace("/", " / ").split() 69 | for word in words: 70 | vocab[' '.join(list(word)) + ' '] += 1 71 | return vocab 72 | 73 | def get_stats(self, vocab): 74 | pairs = collections.Counter() 75 | for word, freq in vocab.items(): 76 | symbols = word.split() 77 | for i in range(len(symbols)-1): 78 | pairs[symbols[i],symbols[i+1]] += freq 79 | return pairs 80 | 81 | def merge_vocab(self, pair, v_in): 82 | v_out = {} 83 | bigram = re.escape(' '.join(pair)) 84 | p = re.compile(r'(?': 102 | return len(token[:-4]) + 1 103 | else: 104 | return len(token) 105 | 106 | def tokenize_word(self, string, sorted_tokens, unknown_token=''): 107 | 108 | if string == '': 109 | return [] 110 | if sorted_tokens == []: 111 | return [unknown_token] 112 | 113 | string_tokens = [] 114 | for i in range(len(sorted_tokens)): 115 | token = sorted_tokens[i] 116 | token_reg = re.escape(token.replace('.', '[.]')) 117 | 118 | matched_positions = [(m.start(0), m.end(0)) for m in re.finditer(token_reg, string)] 119 | if len(matched_positions) == 0: 120 | continue 121 | substring_end_positions = [matched_position[0] for matched_position in matched_positions] 122 | 123 | substring_start_position = 0 124 | for substring_end_position in substring_end_positions: 125 | substring = string[substring_start_position:substring_end_position] 126 | string_tokens += self.tokenize_word(string=substring, sorted_tokens=sorted_tokens[i+1:], unknown_token=unknown_token) 127 | string_tokens += [token] 128 | substring_start_position = substring_end_position + len(token) 129 | remaining_substring = string[substring_start_position:] 130 | string_tokens += self.tokenize_word(string=remaining_substring, sorted_tokens=sorted_tokens[i+1:], unknown_token=unknown_token) 131 | break 132 | return string_tokens -------------------------------------------------------------------------------- /dataset/GetTypeNode.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import sys 4 | 5 | from tqdm import tqdm 6 | from tree_sitter import Language, Parser 7 | 8 | CS_LANGUAGE = Language('build_parser/languages_java_py_cs.so', 'c_sharp') 9 | JA_LANGUAGE = Language('build_parser/languages_java_py_cs.so', 'java') 10 | PY_LANGUAGE = Language('build_parser/languages_java_py_cs.so', 'python') 11 | 12 | lang = { 13 | "py" : PY_LANGUAGE, 14 | "java" : JA_LANGUAGE, 15 | "cs" : CS_LANGUAGE 16 | } 17 | parser = Parser() 18 | 19 | Path = "/home/pretrain_data_code/" 20 | savepath = "data/type_list_" 21 | files= os.listdir(Path) 22 | fail_num = 0 23 | queue = [] 24 | code = [] 25 | pytypeNode = [] 26 | javatypeNode = [] 27 | cstypeNode = [] 28 | 29 | typeNode = { 30 | "py" : pytypeNode, 31 | "java" : javatypeNode, 32 | "cs" : cstypeNode 33 | } 34 | 35 | class TailRecurseException(BaseException): 36 | def __init__(self, args, kwargs): 37 | self.args = args 38 | self.kwargs = kwargs 39 | 40 | def tail_call_optimized(g): 41 | """ 42 | This function decorates a function with tail call 43 | optimization. It does this by throwing an exception 44 | if it is it's own grandparent, and catching such 45 | exceptions to fake the tail call optimization. 46 | 47 | This function fails if the decorated 48 | function recurses in a non-tail context. 49 | """ 50 | def func(*args, **kwargs): 51 | f = sys._getframe() 52 | if f.f_back and f.f_back.f_back \ 53 | and f.f_back.f_back.f_code == f.f_code: 54 | raise TailRecurseException(args, kwargs) 55 | else: 56 | while 1: 57 | try: 58 | return g(*args, **kwargs) 59 | except TailRecurseException as e: 60 | args = e.args 61 | kwargs = e.kwargs 62 | func.__doc__ = g.__doc__ 63 | return func 64 | 65 | 66 | @tail_call_optimized 67 | def getTypeNode(node, code_type): 68 | queue.extend(node.children) 69 | type = node.type 70 | 71 | if type not in typeNode[code_type]: 72 | typeNode[code_type].append(type) 73 | 74 | if(len(queue)==0): 75 | return 76 | return getTypeNode(queue.pop(0), code_type) 77 | 78 | 79 | code_num = {"py":100, "java":100, "cs":100} 80 | for index, file in enumerate(files): 81 | with open(Path + file) as f1: 82 | s = f1.readlines() 83 | for line in tqdm(s, 84 | desc="file %d" % (index), 85 | total=len(s), 86 | bar_format="{l_bar}{r_bar}"): 87 | 88 | line = json.loads(line) 89 | code = line["content"] 90 | 91 | code_type =line['filepath'].split(".")[-1] 92 | 93 | # Set parser language type 94 | parser.set_language(lang[code_type]) 95 | 96 | if (code_type in code_num.keys()): 97 | if code_num[code_type] > 0: 98 | code_num[code_type] -= 1 99 | else: 100 | break 101 | 102 | tree = parser.parse(bytes(code, "utf8")) 103 | 104 | try: 105 | getTypeNode(tree.root_node, code_type) 106 | except: 107 | fail_num += 1 108 | continue 109 | 110 | # open save file 111 | for type in typeNode: 112 | savepath_tmp = savepath + type 113 | with open(savepath_tmp, "w") as f: 114 | f.write(" ".join(typeNode[type])) 115 | -------------------------------------------------------------------------------- /dataset/ParseTOASTPath.py: -------------------------------------------------------------------------------- 1 | # coding=UTF-8 2 | # This Python file uses the following encoding: utf-8 3 | 4 | # for pre-train (python and java) 5 | 6 | import copy 7 | import json 8 | import json as json 9 | import os 10 | import random 11 | import re 12 | import sys 13 | 14 | import numpy as np 15 | from tqdm import tqdm 16 | from tree_sitter import Language, Parser 17 | 18 | 19 | CS_LANGUAGE = Language('build_parser/languages_java_py_cs.so', 'c_sharp') 20 | JA_LANGUAGE = Language('build_parser/languages_java_py_cs.so', 'java') 21 | PY_LANGUAGE = Language('build_parser/languages_java_py_cs.so', 'python') 22 | 23 | lang = { 24 | "py" : PY_LANGUAGE, 25 | "java" : JA_LANGUAGE, 26 | "cs" : CS_LANGUAGE 27 | } 28 | parser = Parser() 29 | 30 | Path = "/home/pretrain_data_code/" 31 | savepath = "/home/pretrain_data_AST_tmp/" 32 | 33 | AST = [] 34 | queue = [] 35 | parentQueue = [] 36 | code = [] 37 | class TailRecurseException(BaseException): 38 | def __init__(self, args, kwargs): 39 | self.args = args 40 | self.kwargs = kwargs 41 | 42 | def tail_call_optimized(g): 43 | """ 44 | This function decorates a function with tail call 45 | optimization. It does this by throwing an exception 46 | if it is it's own grandparent, and catching such 47 | exceptions to fake the tail call optimization. 48 | 49 | This function fails if the decorated 50 | function recurses in a non-tail context. 51 | """ 52 | def func(*args, **kwargs): 53 | f = sys._getframe() 54 | if f.f_back and f.f_back.f_back \ 55 | and f.f_back.f_back.f_code == f.f_code: 56 | raise TailRecurseException(args, kwargs) 57 | else: 58 | while 1: 59 | try: 60 | return g(*args, **kwargs) 61 | except TailRecurseException as e: 62 | args = e.args 63 | kwargs = e.kwargs 64 | func.__doc__ = g.__doc__ 65 | return func 66 | 67 | def getNodeValue(code, start_point, end_point): 68 | if start_point[0]==end_point[0]: 69 | value=code[start_point[0]][start_point[1]:end_point[1]] 70 | else: 71 | value="" 72 | value+=code[start_point[0]][start_point[1]:] 73 | for i in range(start_point[0]+1,end_point[0]): 74 | value+=code[i] 75 | value+=code[end_point[0]][:end_point[1]] 76 | return value 77 | 78 | @tail_call_optimized 79 | def getAST(node, parentIndex=-1): 80 | index = len(AST) 81 | 82 | queue.extend(node.children) 83 | parentQueue.extend([index for _ in range(len(node.children))]) 84 | 85 | json_node = {} 86 | 87 | # If there is no child node, value will be taken 88 | if(len(node.children)==0): 89 | value = getNodeValue(code, node.start_point, node.end_point) 90 | json_node["value"] = value 91 | 92 | json_node["type"] = node.type 93 | json_node["children"] = [] 94 | if(parentIndex!=-1): 95 | AST[parentIndex]["children"].append(index) 96 | 97 | AST.append(json_node) 98 | 99 | if(len(queue)==0): 100 | return 101 | return getAST(queue.pop(0), parentIndex=parentQueue.pop(0)) 102 | 103 | def ProcessCode(code): 104 | """ 105 | Delete blank lines 106 | Processing code blocks, INDENT represents the beginning of the block and DEDENT represents the end of the block. 107 | """ 108 | lines = code.split("\n") 109 | codePathList = [] 110 | indentationNum = 0 111 | recordIndentationNum = [] 112 | for i in range(len(lines)): 113 | line=lines[i].replace("\n", "") 114 | rhs = line.lstrip() 115 | 116 | # The indentation of this line is larger than the previous line, which means that a new block of code is starting, add "INDENT" at the beginning of this line. 117 | num = len(line) - len(rhs) 118 | if(indentationNum < num): 119 | tmp = abs((indentationNum-num)/4) * "INDENT " + rhs 120 | 121 | # The indentation number of this line is smaller than the previous line, which means that the block of code is over, add "DEDENT" at the beginning of the previous line. 122 | elif(indentationNum > num): 123 | codePathList[i-1] = abs((indentationNum-num)/4) * "DEDENT " + codePathList[i-1] 124 | tmp = rhs 125 | else: 126 | tmp = rhs 127 | indentationNum = num 128 | recordIndentationNum.append(indentationNum) 129 | codePathList.append(tmp) 130 | 131 | # End of Code 132 | codePathList[-1] = abs((0 - indentationNum)/4) * "DEDENT " + codePathList[-1] 133 | 134 | targetCode = [] 135 | for i in range(len(codePathList)): 136 | if (codePathList[i] != "") and recordIndentationNum[i] != 0: 137 | targetCode.append("NEWLINE "+codePathList[i]) 138 | if (codePathList[i] != "") and recordIndentationNum[i] == 0: 139 | targetCode.append(codePathList[i]) 140 | 141 | return " ".join(targetCode) 142 | 143 | # Remove comments from the code, taking care before converting to AST. 144 | def DeleteComment(s, code_type): 145 | if(code_type=="py"): 146 | s = re.sub(r'(#.*)', '', s) 147 | s= re.sub(r'(\'\'\')[\s\S]*?(\'\'\')', "", s, re.S) 148 | s= re.sub(r'(\"\"\")[\s\S]*?(\"\"\")', "", s, re.S) 149 | if(code_type=="java") or (code_type=="cs"): 150 | s = re.sub(r'(\/\/.*)', '', s) 151 | s= re.sub(r'(\/\*)[\s\S]*?(\*\/)', "", s, re.S) 152 | return s 153 | 154 | def getPathIndex(AST): 155 | paths = [] 156 | path = [] 157 | 158 | path.append(0) 159 | 160 | GetPath(AST[0], paths, path) 161 | return paths 162 | 163 | def GetPath(node, paths, path): 164 | ''' 165 | Recursively get the root-terminal path from the parsed AST 166 | ''' 167 | if len(node["children"])!=0: 168 | children = node.get('children') 169 | for i in children: 170 | child = AST[i] 171 | path.append(i) 172 | GetPath(child, paths, path) 173 | path.pop() 174 | else: 175 | tempPath = copy.deepcopy(path) 176 | path.pop() 177 | paths.append(tempPath) 178 | 179 | def myreplace(matched): 180 | return " " + matched.group(0) + " " 181 | 182 | def TMLM(AST,pathIndex,code): 183 | decoder_input = [] 184 | decoder_output = [] 185 | AST_mask_nodes = [] 186 | 187 | # mask AST at encoder 188 | for path in pathIndex: 189 | p = len(path) 190 | q = np.array(range(p)) 191 | select_node_pro_dis = np.exp(q-p) / np.sum(np.exp(q-p)) 192 | for index, node in enumerate(path): 193 | if (random.random()") 214 | else: 215 | decoder_input.append(token) 216 | 217 | return AST, decoder_input, decoder_output 218 | 219 | def NOP(AST): 220 | if random.random() > 0.5: 221 | return AST, 1 222 | else: 223 | position = random.sample(range(0,len(AST)),2) 224 | AST[position[0]]['type'], AST[position[1]]['type'] = AST[position[1]]['type'], AST[position[0]]['type'] 225 | if ('value' in AST[position[0]].keys()) and ('value' in AST[position[1]].keys()): 226 | AST[position[0]]['value'], AST[position[1]]['value'] = AST[position[1]]['value'], AST[position[0]]['value'] 227 | return AST, 0 228 | 229 | def getNodePosEmCoeff(AST): 230 | AST[0]['coeff'] = 0.5 231 | for parent in AST: 232 | children = parent.get('children') 233 | if len(children)>0: 234 | children = parent.get('children') 235 | c = len(children) 236 | for i, child in enumerate(children): 237 | coeff = (c-i)/(c+1.0) 238 | AST[child]['coeff'] = coeff 239 | return AST 240 | 241 | def truncatCode(code, max_code_len): 242 | trunc_code = [] 243 | token_num = 0 244 | code = code.split('\n') 245 | for line in code: 246 | tmp_tokens = [] 247 | line = line.split() 248 | for token in line: 249 | tmp_tokens.append(token) 250 | token_num +=1 251 | if token_num>200: 252 | break 253 | str = " ".join(tmp_tokens) 254 | # Determine if it is a blank line 255 | if not len(line): 256 | continue 257 | trunc_code.append(str) 258 | if token_num>200: 259 | break 260 | return trunc_code 261 | 262 | def ParseToASTPath(Path, savepath, max_code_len=200, max_node_num=20, max_path_num=100): 263 | files= os.listdir(Path) 264 | fail_num = 0 265 | 266 | for index, file in enumerate(files): 267 | with open(Path + file) as f1: 268 | 269 | savepath_tmp = savepath + "pretrain_data_%d" % index 270 | f = open(savepath_tmp, "w") 271 | s = f1.readlines() 272 | for line in tqdm(s, 273 | desc="file %d" % (index), 274 | total=len(s), 275 | bar_format="{l_bar}{r_bar}"): 276 | 277 | global code 278 | line = json.loads(line) 279 | try: 280 | code = line["content"] 281 | code_type =line['filepath'].split(".")[-1] 282 | except: 283 | fail_num += 1 284 | continue 285 | parser.set_language(lang[code_type]) 286 | 287 | # Processing Code 288 | code = DeleteComment(code,code_type) 289 | # target_code = ProcessCode(target_code) 290 | code = truncatCode(code, max_code_len) 291 | 292 | # code = "public void RemovePresentationFormat(){MutableSection s = (MutableSection)FirstSection;s.RemoveProperty(PropertyIDMap.PID_PRESFORMAT);}" 293 | tree = parser.parse(bytes("\n".join(code), "utf8")) 294 | target_code = "\n".join(code) 295 | 296 | global AST 297 | AST = [] 298 | try: 299 | getAST(tree.root_node, parentIndex=-1) 300 | except: 301 | fail_num += 1 302 | continue 303 | 304 | # Construct pre-training tasks 305 | pathIndex = getPathIndex(AST) 306 | if len(pathIndex)<2: 307 | fail_num += 1 308 | continue 309 | AST, decoder_input, decoder_output = TMLM(AST,pathIndex,target_code) 310 | AST, is_ast_order = NOP(AST) 311 | 312 | # Get the node position embedding coefficient 313 | getNodePosEmCoeff(AST) 314 | 315 | # Extracting paths from the AST 316 | paths = [] 317 | coeffs = [] 318 | for path in pathIndex: 319 | tmp_path = [] 320 | coeff = [] 321 | for index, node in enumerate(path): 322 | coeff.append(AST[node]['coeff']) 323 | if('value' in AST[node].keys()): 324 | node = AST[node].get('value').replace("\n", "").replace("\t", " ").replace("\/?", "").replace(" ", "_").replace("\\", "") 325 | else: 326 | node = AST[node].get('type') 327 | tmp_path.append(node) 328 | 329 | paths.append(tmp_path[:max_node_num]) 330 | coeffs.append(coeff[:max_node_num]) 331 | 332 | # Save the pre-trained dataset constructed for TMLM and NOP to a file. 333 | output = {"lan_type": code_type, 334 | "encoder_input": paths[:max_path_num], 335 | "decoder_input": decoder_input[:max_code_len], 336 | "decoder_output": decoder_output[:max_code_len], 337 | "is_ast_order": is_ast_order, 338 | "node_pos_em_coeff": coeffs[:max_path_num]} 339 | f.write(json.dumps(output)) 340 | f.write("\n") 341 | f.close() 342 | 343 | 344 | print("fail number:", fail_num) 345 | 346 | 347 | if __name__ == "__main__": 348 | ParseToASTPath(Path,savepath,max_code_len=200, max_node_num=20, max_path_num=100) 349 | -------------------------------------------------------------------------------- /dataset/__init__.py: -------------------------------------------------------------------------------- 1 | from .BPE import BPE 2 | from .dataset import TreeBERTDataset 3 | from .vocab import TokenVocab 4 | -------------------------------------------------------------------------------- /dataset/dataset.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | 4 | import torch 5 | from torch.utils.data import Dataset 6 | 7 | from dataset import BPE 8 | 9 | 10 | class TreeBERTDataset(Dataset): 11 | def __init__(self, vocab, corpus_path, path_num, node_num, code_len, 12 | is_fine_tune=False, 13 | corpus_lines=None, max_subtoken_len=3): 14 | 15 | self.corpus_lines = corpus_lines 16 | self.corpus_path = corpus_path 17 | self.path_num = path_num 18 | self.code_len = code_len 19 | self.node_num = node_num 20 | self.vocab = vocab 21 | self.max_subtoken_len = max_subtoken_len 22 | 23 | self.files = os.listdir(corpus_path) 24 | if self.corpus_lines is None: 25 | self.corpus_lines = 0 26 | for index, tmp_file in enumerate(self.files): 27 | with open(corpus_path+tmp_file, 'r', encoding='utf-8') as f: 28 | for _ in f.readlines(): 29 | self.corpus_lines += 1 30 | 31 | # Start the first file 32 | self.file_index = 0 33 | self.file = open(corpus_path+self.files[self.file_index], 'r', encoding='utf-8') 34 | 35 | def __len__(self): 36 | return self.corpus_lines 37 | 38 | def __getitem__(self, item): 39 | line = self.get_corpus_line() 40 | data = json.loads(line) 41 | lan_type = data['lan_type'] 42 | AST = data['encoder_input'][:self.path_num] 43 | code_mask = data['decoder_input'][:self.code_len] 44 | code = data['decoder_output'][:self.code_len] 45 | coeff = data['node_pos_em_coeff'][:self.path_num] 46 | 47 | padding_token = [self.vocab.pad_index for _ in range(self.max_subtoken_len)] 48 | padding_path = [padding_token for _ in range(self.node_num)] 49 | padding_coeff = [0 for _ in range(self.node_num)] 50 | 51 | for index, path in enumerate(AST): 52 | path = BPE.encode(self.vocab.vocab_tokenization,self.vocab.tokenize_word,self.vocab.sorted_tokens,texts=path[:self.node_num]) 53 | for i, token in enumerate(path): 54 | for j, subtoken in enumerate(token): 55 | path[i][j] = self.vocab.stoi.get(subtoken, self.vocab.unk_index) 56 | 57 | # Padding to the same number of nodes per path 58 | if(len(path)', self.vocab.unk_index) 76 | code_mask[i] = self.vocab.stoi.get(code_mask[i].lower() + '', self.vocab.unk_index) 77 | 78 | # Padding to the same length of code 79 | padding = [self.vocab.pad_index for _ in range(self.code_len - len(code))] 80 | code_mask.extend(padding) 81 | code.extend(padding) 82 | 83 | # add and 84 | if(lan_type=="py"): 85 | sos_token = self.vocab.sos_index_python 86 | elif(lan_type=="java"): 87 | sos_token = self.vocab.sos_index_java 88 | else: 89 | sos_token = self.vocab.unk_index 90 | 91 | code_mask = [sos_token] + code_mask + [self.vocab.cls_index] 92 | code = code + [self.vocab.cls_index] + [self.vocab.eos_index] 93 | 94 | output = {"encoder_input": AST, 95 | "decoder_input": code_mask, 96 | "decoder_output": code, 97 | "is_ast_order": data['is_ast_order'], 98 | "node_pos_em_coeff": coeff} 99 | 100 | return {key: torch.tensor(value) for key, value in output.items()} 101 | 102 | def get_corpus_line(self): 103 | line = self.file.readline() 104 | 105 | # start reading the next file 106 | if line is '': 107 | self.file.close() 108 | self.file_index = (self.file_index + 1) % len(self.files) 109 | self.file = open(self.corpus_path+self.files[self.file_index], "r", encoding='utf-8') 110 | line = self.file.readline() 111 | return line 112 | -------------------------------------------------------------------------------- /dataset/utils.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import json 3 | import os 4 | import random 5 | import socket 6 | import sys 7 | import time 8 | from urllib import request 9 | 10 | import matplotlib.pyplot as plt 11 | import matplotlib.ticker as ticker 12 | # from torchtext.data.metrics import bleu_score 13 | import torch 14 | import torch.nn as nn 15 | import tqdm 16 | 17 | 18 | def getPretrainData(str): 19 | socket.setdefaulttimeout(30) 20 | repos = json.loads(str) 21 | url = repos['url'] 22 | 23 | filename = repos['filepath'].split("/")[-1] 24 | code_type = filename.split(".")[-1] 25 | 26 | ua_headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"} 27 | 28 | 29 | try: 30 | req = request.Request(url, headers=ua_headers) 31 | response = request.urlopen(req) 32 | content = response.read() 33 | content = json.loads(content) 34 | code = base64.b64decode(content["content"]) 35 | code = code.decode('utf-8') 36 | except: 37 | count = 1 38 | while count <= 3: 39 | time.sleep(10) 40 | print("Retrying ", count) 41 | try: 42 | response = request.urlopen(url) 43 | code = response.read() 44 | code = code.decode('utf-8') 45 | break 46 | except: 47 | count += 1 48 | if count > 3: 49 | code = None 50 | print("Crawl code failure") 51 | 52 | return code, code_type 53 | 54 | def SaveToFile(filename, contents): 55 | f = open(filename, 'w') 56 | for index, content in enumerate(contents): 57 | try: 58 | f.write(content) 59 | f.write('\n') 60 | except: 61 | print(index) 62 | print(content) 63 | f.close() 64 | 65 | def is_json(myjson): 66 | try: 67 | json_object = json.loads(myjson) 68 | except ValueError: 69 | return False 70 | return True 71 | 72 | def PrintUsage(): 73 | # Output error message 74 | sys.stderr.write(""" 75 | Usage: 76 | parse_python.py 77 | 78 | """) 79 | exit(1) 80 | 81 | def read_file_to_string(filename): 82 | f = open(filename, 'rt') 83 | s = f.read() 84 | f.close() 85 | return s 86 | 87 | def count_parameters(model): 88 | return sum(p.numel() for p in model.parameters() if p.requires_grad) 89 | 90 | 91 | def initialize_weights(m): 92 | if hasattr(m, 'weight') and m.weight.dim() > 1: 93 | nn.init.xavier_uniform_(m.weight.data) 94 | 95 | 96 | def train(model, iterator, optimizer, criterion, clip): 97 | 98 | model.train() 99 | 100 | epoch_loss = 0 101 | 102 | for i, batch in enumerate(iterator): 103 | 104 | src = batch.src 105 | trg = batch.trg 106 | 107 | optimizer.zero_grad() 108 | 109 | try: 110 | output, _ = model(src, trg[:,:-1]) 111 | except RuntimeError as exception: 112 | if "out of memory" in str(exception): 113 | print("WARNING: out of memory") 114 | if hasattr(torch.cuda, 'empty_cache'): 115 | torch.cuda.empty_cache() 116 | else: 117 | raise exception 118 | 119 | 120 | #output = [batch size, trg len - 1, output dim] 121 | #trg = [batch size, trg len] 122 | 123 | output_dim = output.shape[-1] 124 | 125 | output = output.contiguous().view(-1, output_dim) 126 | trg = trg[:,1:].contiguous().view(-1) 127 | 128 | #output = [batch size * trg len - 1, output dim] 129 | #trg = [batch size * trg len - 1] 130 | 131 | loss = criterion(output, trg) 132 | 133 | loss.backward() 134 | 135 | torch.nn.utils.clip_grad_norm_(model.parameters(), clip) 136 | 137 | optimizer.step() 138 | 139 | epoch_loss += loss.item() 140 | 141 | return epoch_loss / len(iterator) 142 | 143 | def evaluate(model, iterator, criterion): 144 | 145 | model.eval() 146 | 147 | epoch_loss = 0 148 | 149 | with torch.no_grad(): 150 | 151 | for i, batch in enumerate(iterator): 152 | 153 | src = batch.src 154 | trg = batch.trg 155 | 156 | output, _ = model(src, trg[:,:-1]) 157 | 158 | #output = [batch size, trg len - 1, output dim] 159 | #trg = [batch size, trg len] 160 | 161 | output_dim = output.shape[-1] 162 | 163 | output = output.contiguous().view(-1, output_dim) 164 | trg = trg[:,1:].contiguous().view(-1) 165 | 166 | #output = [batch size * trg len - 1, output dim] 167 | #trg = [batch size * trg len - 1] 168 | 169 | loss = criterion(output, trg) 170 | 171 | epoch_loss += loss.item() 172 | 173 | return epoch_loss / len(iterator) 174 | 175 | def epoch_time(start_time, end_time): 176 | elapsed_time = end_time - start_time 177 | elapsed_mins = int(elapsed_time / 60) 178 | elapsed_secs = int(elapsed_time - (elapsed_mins * 60)) 179 | return elapsed_mins, elapsed_secs 180 | 181 | 182 | def generate_target(src, model, vocab, device, max_len = 50): 183 | 184 | model.eval() 185 | 186 | src_tensor = src.unsqueeze(0).to(device) 187 | 188 | src_mask = model.make_src_mask(src_tensor) 189 | 190 | with torch.no_grad(): 191 | enc_src = model.encoder(src.unsqueeze(0), src_mask) 192 | 193 | trg_indexes = [vocab.sos_index] 194 | 195 | for i in range(max_len): 196 | 197 | trg_tensor = torch.LongTensor(trg_indexes).unsqueeze(0).to(device) 198 | 199 | trg_mask = model.make_trg_mask(trg_tensor) 200 | 201 | with torch.no_grad(): 202 | output, attention = model.decoder(trg_tensor, enc_src, trg_mask, src_mask) 203 | 204 | pred_token = output.argmax(2)[:,-1].item() 205 | 206 | trg_indexes.append(pred_token) 207 | 208 | if pred_token == vocab.eos_index: 209 | break 210 | 211 | trg_tokens = [vocab.itos[i] for i in trg_indexes] 212 | trg_tokens = "".join(trg_tokens[1:]) 213 | trg_tokens = trg_tokens.split("") 214 | 215 | return trg_tokens, attention 216 | 217 | def display_attention(sentence, translation, attention, n_heads = 8, n_rows = 4, n_cols = 2): 218 | 219 | assert n_rows * n_cols == n_heads 220 | 221 | fig = plt.figure(figsize=(15,25)) 222 | 223 | for i in range(n_heads): 224 | 225 | ax = fig.add_subplot(n_rows, n_cols, i+1) 226 | 227 | _attention = attention.squeeze(0)[i].cpu().detach().numpy() 228 | 229 | cax = ax.matshow(_attention, cmap='bone') 230 | 231 | ax.tick_params(labelsize=12) 232 | ax.set_xticklabels(['']+['']+[t.lower() for t in sentence]+[''], 233 | rotation=45) 234 | ax.set_yticklabels(['']+translation) 235 | 236 | ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) 237 | ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) 238 | 239 | plt.show() 240 | plt.close() 241 | 242 | 243 | def calculate_bleu(dataset, model, vocab, device, max_len = 50): 244 | dataset = tqdm.tqdm(enumerate(dataset), 245 | desc="inference and calculate BLEU", 246 | total=len(dataset), 247 | bar_format="{l_bar}{r_bar}") 248 | trgs = [] 249 | pred_trgs = [] 250 | for i, data in dataset: 251 | # data will be sent into the device(GPU or cpu) 252 | data = {key: value.to(device) for key, value in data.items()} 253 | 254 | src = data['encoder_input'] 255 | trg_index = data['label'] 256 | trg = [vocab.itos[i] for i in trg_index] 257 | trg = "".join(trg[1:]) 258 | trg = trg.split("") 259 | 260 | 261 | pred_trg, _ = generate_target(src, model, vocab, device, max_len) 262 | 263 | #cut off token 264 | pred_trgs.append(pred_trg[:-1]) 265 | trgs.append(trg[:-1]) 266 | 267 | return bleu_score(pred_trgs, trgs) 268 | -------------------------------------------------------------------------------- /dataset/vocab.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | 3 | import collections 4 | import json 5 | import os 6 | import pickle 7 | import re 8 | 9 | from tqdm import tqdm 10 | 11 | 12 | class BPE(object): 13 | def __init__(self, corpus_path, BPE_path="data/BPEObject.small", except_list=None, num_merges=5): 14 | print("Read in files") 15 | print('==========') 16 | vocab = self.get_vocab(corpus_path, except_list) 17 | # self.tokens_frequencies, self.vocab_tokenization = self.get_tokens_from_vocab(vocab) 18 | print('==========') 19 | print("Adopt BPE") 20 | for i in range(num_merges): 21 | pairs = self.get_stats(vocab) 22 | if not pairs: 23 | break 24 | best = max(pairs, key=pairs.get) 25 | vocab = self.merge_vocab(best, vocab) 26 | if(i % 100 == 0): 27 | print('Iter: {}'.format(i)) 28 | # print('Number of tokens: {}'.format(len(self.tokens_frequencies.keys()))) 29 | print('==========') 30 | 31 | self.tokens_frequencies, self.vocab_tokenization = self.get_tokens_from_vocab(vocab) 32 | 33 | sorted_tokens_tuple = sorted(self.tokens_frequencies.items(), key=lambda item: (self.measure_token_length(item[0]), item[1]), reverse=True) 34 | self.sorted_tokens = [token for (token, freq) in sorted_tokens_tuple] 35 | 36 | print('==========') 37 | 38 | 39 | @staticmethod 40 | def encode(vocab_tokenization, tokenize_word, sorted_tokens, texts): 41 | encode_output = [] 42 | for word_given in texts: 43 | # Tokenization of the known word 44 | word_given = word_given.lower() + '' 45 | if word_given in vocab_tokenization: 46 | tmpWord = vocab_tokenization[word_given] 47 | # Tokenizating of the unknown word 48 | else: 49 | tmpWord = tokenize_word(string=word_given, sorted_tokens=sorted_tokens, unknown_token='') 50 | encode_output = encode_output + tmpWord 51 | return encode_output 52 | 53 | 54 | @staticmethod 55 | def decode(): 56 | pass 57 | @staticmethod 58 | def load_BPE(BPE_path: str): 59 | with open(BPE_path, "rb") as f: 60 | return pickle.load(f) 61 | 62 | def save_BPE(self, BPE_path): 63 | with open(BPE_path, "wb") as f: 64 | pickle.dump(self, f) 65 | 66 | def get_vocab(self, corpus_path, except_list): 67 | vocab = collections.Counter() 68 | files= os.listdir(corpus_path) 69 | 70 | for index, file in enumerate(files): 71 | with open(corpus_path+file, 'r', encoding='utf-8') as f: 72 | s = f.readlines() 73 | for line in tqdm(s, 74 | desc="file %d" % (index), 75 | total=len(s), 76 | bar_format="{l_bar}{r_bar}"): 77 | data = json.loads(line) 78 | AST = data['encoder_input'] 79 | code = data['decoder_output'] 80 | for path in AST: 81 | for node in path: 82 | if (node in except_list): 83 | vocab[node.lower() + ''] += 1 84 | else: 85 | vocab[' '.join(list(node.lower())) + ' '] += 1 86 | for token in code: 87 | vocab[token.lower() + ''] += 1 88 | 89 | return vocab 90 | 91 | def get_stats(self, vocab): 92 | pairs = collections.Counter() 93 | for word, freq in vocab.items(): 94 | symbols = word.split() 95 | for i in range(len(symbols)-1): 96 | pairs[symbols[i],symbols[i+1]] += freq 97 | return pairs 98 | 99 | def merge_vocab(self, pair, v_in): 100 | v_out = {} 101 | bigram = re.escape(' '.join(pair)) 102 | p = re.compile(r'(?': 120 | return len(token[:-4]) + 1 121 | else: 122 | return len(token) 123 | 124 | def tokenize_word(self, string, sorted_tokens, unknown_token=''): 125 | 126 | if string == '': 127 | return [] 128 | if sorted_tokens == []: 129 | return [unknown_token] 130 | 131 | string_tokens = [] 132 | for i in range(len(sorted_tokens)): 133 | token = sorted_tokens[i] 134 | token_reg = re.escape(token.replace('.', '[.]')) 135 | 136 | matched_positions = [(m.start(0), m.end(0)) for m in re.finditer(token_reg, string)] 137 | if len(matched_positions) == 0: 138 | continue 139 | substring_end_positions = [matched_position[0] for matched_position in matched_positions] 140 | 141 | substring_start_position = 0 142 | for substring_end_position in substring_end_positions: 143 | substring = string[substring_start_position:substring_end_position] 144 | string_tokens += self.tokenize_word(string=substring, sorted_tokens=sorted_tokens[i+1:], unknown_token=unknown_token) 145 | string_tokens += [token] 146 | substring_start_position = substring_end_position + len(token) 147 | remaining_substring = string[substring_start_position:] 148 | string_tokens += self.tokenize_word(string=remaining_substring, sorted_tokens=sorted_tokens[i+1:], unknown_token=unknown_token) 149 | break 150 | return string_tokens 151 | 152 | class TorchVocab(object): 153 | """Defines a vocabulary object that will be used to numericalize a field. 154 | Attributes: 155 | freqs: A collections.Counter object holding the frequencies of tokens 156 | in the data used to build the Vocab. 157 | stoi: A collections.defaultdict instance mapping token strings to 158 | numerical identifiers. 159 | itos: A list of token strings indexed by their numerical identifiers. 160 | """ 161 | 162 | def __init__(self, counter, max_size=None, min_freq=1, specials=['', ''], 163 | vectors=None, unk_init=None, vectors_cache=None): 164 | """Create a Vocab object from a collections.Counter. 165 | Arguments: 166 | counter: collections.Counter object holding the frequencies of 167 | each value found in the data. 168 | max_size: The maximum size of the vocabulary, or None for no 169 | maximum. Default: None. 170 | min_freq: The minimum frequency needed to include a token in the 171 | vocabulary. Values less than 1 will be set to 1. Default: 1. 172 | specials: The list of special tokens (e.g., padding or eos) that 173 | will be prepended to the vocabulary in addition to an 174 | token. Default: [''] 175 | vectors: One of either the available pretrained vectors 176 | or custom pretrained vectors (see Vocab.load_vectors); 177 | or a list of aforementioned vectors 178 | unk_init (callback): by default, initialize out-of-vocabulary word vectors 179 | to zero vectors; can be any function that takes in a Tensor and 180 | returns a Tensor of the same size. Default: torch.Tensor.zero_. 181 | vectors_cache: directory for cached vectors. Default: '.vector_cache'. 182 | """ 183 | self.freqs = counter 184 | counter = counter.copy() 185 | min_freq = max(min_freq, 1) 186 | 187 | self.itos = list(specials) 188 | # frequencies of special tokens are not counted when building vocabulary 189 | # in frequency order 190 | for tok in specials: 191 | del counter[tok] 192 | 193 | max_size = None if max_size is None else max_size + len(self.itos) 194 | 195 | # sort by frequency, then alphabetically 196 | words_and_frequencies = sorted(counter.items(), key=lambda tup: tup[0]) 197 | words_and_frequencies.sort(key=lambda tup: tup[1], reverse=True) 198 | 199 | for word, freq in words_and_frequencies: 200 | if freq < min_freq or len(self.itos) == max_size: 201 | break 202 | self.itos.append(word) 203 | 204 | # stoi is simply a reverse dict for itos 205 | self.stoi = {tok: i for i, tok in enumerate(self.itos)} 206 | 207 | self.vectors = None 208 | if vectors is not None: 209 | self.load_vectors(vectors, unk_init=unk_init, cache=vectors_cache) 210 | else: 211 | assert unk_init is None and vectors_cache is None 212 | 213 | def __eq__(self, other): 214 | if self.freqs != other.freqs: 215 | return False 216 | if self.stoi != other.stoi: 217 | return False 218 | if self.itos != other.itos: 219 | return False 220 | if self.vectors != other.vectors: 221 | return False 222 | return True 223 | 224 | def __len__(self): 225 | return len(self.itos) 226 | 227 | def vocab_rerank(self): 228 | self.stoi = {word: i for i, word in enumerate(self.itos)} 229 | 230 | def extend(self, v, sort=False): 231 | words = sorted(v.itos) if sort else v.itos 232 | for w in words: 233 | if w not in self.stoi: 234 | self.itos.append(w) 235 | self.stoi[w] = len(self.itos) - 1 236 | 237 | 238 | class Vocab(TorchVocab): 239 | def __init__(self, counter, max_size=None, min_freq=1): 240 | self.pad_index = 0 241 | self.unk_index = 1 242 | self.sos_index_python = 2 243 | self.sos_index_java = 3 244 | self.eos_index = 4 245 | self.mask_index = 5 246 | self.cls_index = 6 247 | # is automatically included when creating a vocab 248 | super().__init__(counter, specials=["", "", "", "","", ""], 249 | max_size=max_size, min_freq=min_freq) 250 | 251 | def to_seq(self, sentece, seq_len, with_eos=False, with_sos=False) -> list: 252 | pass 253 | 254 | def from_seq(self, seq, join=False, with_pad=False): 255 | pass 256 | 257 | @staticmethod 258 | def load_vocab(vocab_path: str) -> 'Vocab': 259 | with open(vocab_path, "rb") as f: 260 | return pickle.load(f) 261 | 262 | def save_vocab(self, vocab_path): 263 | with open(vocab_path, "wb") as f: 264 | pickle.dump(self, f) 265 | 266 | 267 | class TokenVocab(Vocab): 268 | def __init__(self, BPEObject, max_size=None,min_freq=1): 269 | print("Building Vocab") 270 | 271 | self.sorted_tokens = BPEObject.sorted_tokens 272 | self.tokenize_word = BPEObject.tokenize_word 273 | self.vocab_tokenization = BPEObject.vocab_tokenization 274 | counter = BPEObject.tokens_frequencies 275 | 276 | super().__init__(counter, max_size=max_size, min_freq=min_freq) 277 | 278 | def to_seq(self, sentence, seq_len=None, with_eos=False, with_sos=False, with_len=False): 279 | if isinstance(sentence, str): 280 | sentence = sentence.split() 281 | 282 | seq = [self.stoi.get(word, self.unk_index) for word in sentence] 283 | 284 | if with_eos: 285 | seq += [self.eos_index] 286 | if with_sos: 287 | seq = [self.sos_index] + seq 288 | 289 | origin_seq_len = len(seq) 290 | 291 | if seq_len is None: 292 | pass 293 | elif len(seq) <= seq_len: 294 | seq += [self.pad_index for _ in range(seq_len - len(seq))] 295 | else: 296 | seq = seq[:seq_len] 297 | 298 | return (seq, origin_seq_len) if with_len else seq 299 | 300 | def from_seq(self, seq, join=False, with_pad=False): 301 | words = [self.itos[idx] 302 | if idx < len(self.itos) 303 | else "<%d>" % idx 304 | for idx in seq 305 | if not with_pad or idx != self.pad_index] 306 | 307 | return " ".join(words) if join else words 308 | 309 | @staticmethod 310 | def load_vocab(vocab_path: str) -> 'TokenVocab': 311 | with open(vocab_path, "rb") as f: 312 | return pickle.load(f) 313 | 314 | 315 | def build(): 316 | import argparse 317 | 318 | parser = argparse.ArgumentParser() 319 | parser.add_argument("-c", "--corpus_path", required=True, type=str) 320 | parser.add_argument("-o", "--output_path", required=True, type=str) 321 | parser.add_argument("-s", "--vocab_size", type=int, default=None) 322 | parser.add_argument("-f", "--min_freq", type=int, default=2) 323 | parser.add_argument("-m", "--num_merges", type=int, default=5000) 324 | args = parser.parse_args() 325 | 326 | # load type nodes 327 | type_path = "data/type_list/" 328 | files = os.listdir(type_path) 329 | type_node = [] 330 | for file in files: 331 | with open(type_path+file, "r", encoding='utf-8') as f: 332 | s = f.read() 333 | type_node += s.split() 334 | 335 | except_list = ['False','None', 'True','and','as', 'assert','break', 336 | 'class','continue', 'def','del','elif', 'else','except', 337 | 'finally', 'for', 'from','global','if','import','in','is', 338 | 'lambda', 'nonlocal','not','or','pass','raise', 'return', 339 | 'try','while','with','yield','NEWLINE','INDENT',''] + [ 340 | "abstract", "assert", "boolean", "break", "byte", "case", "catch", 341 | "char", "class", "const", "continue", "default", "do", "double", 342 | "else", "enum", "extends", "final", "finally", "float", "for", "goto", 343 | "if", "implements", "import", "instanceof", "int", "interface", "long", 344 | "native", "new", "package", "private", "protected", "public", "return", 345 | "strictfp", "short", "static", "super", "switch", "synchronized", "this", 346 | "throw", "throws", "transient", "try", "void", "volatile", "while"] 347 | 348 | except_list.extend(type_node) 349 | # except_list include type nodes and key word in code, which do not need to adopt BPE 350 | except_list = list(set(except_list)) 351 | 352 | # Create BPE object 353 | BPE_object = BPE(args.corpus_path,except_list=except_list,num_merges=args.num_merges) 354 | vocab = TokenVocab( BPE_object,max_size=args.vocab_size,min_freq=args.min_freq) 355 | 356 | print("VOCAB SIZE:", len(vocab)) 357 | vocab.save_vocab(args.output_path) 358 | 359 | # build() 360 | -------------------------------------------------------------------------------- /model/__init__.py: -------------------------------------------------------------------------------- 1 | from .transformer import Encoder, Decoder, Seq2Seq 2 | from .TreeBERT import TreeBERT 3 | -------------------------------------------------------------------------------- /model/transformer.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | import numpy as np 4 | import torch 5 | import torch.nn as nn 6 | 7 | SEED = 1234 8 | 9 | random.seed(SEED) 10 | np.random.seed(SEED) 11 | torch.manual_seed(SEED) 12 | torch.cuda.manual_seed(SEED) 13 | torch.backends.cudnn.deterministic = True 14 | 15 | class PathEncoder(nn.Module): 16 | def __init__(self, 17 | input_dim, 18 | node_num, 19 | hid_dim, 20 | dropout): 21 | super().__init__() 22 | 23 | self.tok_embedding = nn.Embedding(input_dim, hid_dim) 24 | 25 | self.W_level = nn.Embedding(node_num, hid_dim) 26 | self.W_parent = nn.Embedding(node_num, hid_dim) 27 | 28 | self.linear = nn.Linear(node_num*hid_dim, hid_dim) 29 | 30 | self.layer_norm = nn.LayerNorm(hid_dim) 31 | 32 | self.dropout = nn.Dropout(dropout) 33 | 34 | def forward(self, src, pos_coeff, src_subtoken_mask): 35 | 36 | # subtoken summation 37 | src = self.tok_embedding(src) 38 | src_subtoken_mask = src_subtoken_mask.unsqueeze(4) 39 | src = src*src_subtoken_mask 40 | src = src.sum(axis=3) 41 | 42 | # add node position embedding 43 | l = torch.arange(0, src.shape[2]).unsqueeze(0).unsqueeze(1).to(src.device) 44 | E_pos = pos_coeff.unsqueeze(3) * self.W_parent(l) + (1 - pos_coeff).unsqueeze(3) * self.W_level(l) 45 | 46 | src = self.linear(torch.reshape(src + E_pos, (src.shape[0], src.shape[1], -1))) 47 | 48 | src = self.dropout(src) 49 | 50 | src = self.layer_norm(src) 51 | 52 | return src 53 | 54 | class Encoder(nn.Module): 55 | def __init__(self, 56 | input_dim, 57 | node_num, 58 | hid_dim, 59 | n_layers, 60 | n_heads, 61 | pf_dim, 62 | dropout, 63 | max_length = 200): 64 | super().__init__() 65 | 66 | self.pathEncode = PathEncoder(input_dim, node_num, hid_dim, dropout) 67 | 68 | self.layers = nn.ModuleList([EncoderLayer(hid_dim, 69 | n_heads, 70 | pf_dim, 71 | dropout) 72 | for _ in range(n_layers)]) 73 | 74 | self.dropout = nn.Dropout(dropout) 75 | 76 | self.scale = torch.sqrt(torch.FloatTensor([hid_dim])) 77 | 78 | def forward(self, src, pos_coeff, src_mask, src_subtoken_mask): 79 | src = self.pathEncode(src, pos_coeff, src_subtoken_mask) 80 | 81 | for layer in self.layers: 82 | src = layer(src, src_mask) 83 | 84 | return src 85 | 86 | class EncoderLayer(nn.Module): 87 | def __init__(self, 88 | hid_dim, 89 | n_heads, 90 | pf_dim, 91 | dropout): 92 | super().__init__() 93 | 94 | self.self_attn_layer_norm = nn.LayerNorm(hid_dim) 95 | self.ff_layer_norm = nn.LayerNorm(hid_dim) 96 | self.self_attention = MultiHeadAttentionLayer(hid_dim, n_heads, dropout) 97 | self.positionwise_feedforward = PositionwiseFeedforwardLayer(hid_dim, 98 | pf_dim, 99 | dropout) 100 | self.dropout = nn.Dropout(dropout) 101 | 102 | def forward(self, src, src_mask): 103 | _src, _ = self.self_attention(src, src, src, src_mask) 104 | 105 | src = self.self_attn_layer_norm(src + self.dropout(_src)) 106 | 107 | _src = self.positionwise_feedforward(src) 108 | 109 | src = self.ff_layer_norm(src + self.dropout(_src)) 110 | 111 | return src 112 | 113 | class MultiHeadAttentionLayer(nn.Module): 114 | def __init__(self, hid_dim, n_heads, dropout): 115 | super().__init__() 116 | 117 | assert hid_dim % n_heads == 0 118 | 119 | self.hid_dim = hid_dim 120 | self.n_heads = n_heads 121 | self.head_dim = hid_dim // n_heads 122 | 123 | self.fc_q = nn.Linear(hid_dim, hid_dim) 124 | self.fc_k = nn.Linear(hid_dim, hid_dim) 125 | self.fc_v = nn.Linear(hid_dim, hid_dim) 126 | 127 | self.fc_o = nn.Linear(hid_dim, hid_dim) 128 | 129 | self.dropout = nn.Dropout(dropout) 130 | 131 | def forward(self, query, key, value, mask = None): 132 | 133 | batch_size = query.shape[0] 134 | 135 | Q = self.fc_q(query) 136 | K = self.fc_k(key) 137 | V = self.fc_v(value) 138 | 139 | Q = Q.view(batch_size, -1, self.n_heads, self.head_dim).permute(0, 2, 1, 3) 140 | K = K.view(batch_size, -1, self.n_heads, self.head_dim).permute(0, 2, 1, 3) 141 | V = V.view(batch_size, -1, self.n_heads, self.head_dim).permute(0, 2, 1, 3) 142 | 143 | energy = torch.matmul(Q, K.permute(0, 1, 3, 2)) / torch.sqrt(torch.FloatTensor([self.head_dim])).to(Q.device) 144 | 145 | if mask is not None: 146 | energy = energy.masked_fill(mask == 0, -1e10) 147 | 148 | attention = torch.softmax(energy, dim = -1) 149 | 150 | x = torch.matmul(self.dropout(attention), V) 151 | 152 | x = x.permute(0, 2, 1, 3).contiguous() 153 | 154 | x = x.view(batch_size, -1, self.hid_dim) 155 | 156 | x = self.fc_o(x) 157 | 158 | return x, attention 159 | 160 | class PositionwiseFeedforwardLayer(nn.Module): 161 | def __init__(self, hid_dim, pf_dim, dropout): 162 | super().__init__() 163 | 164 | self.fc_1 = nn.Linear(hid_dim, pf_dim) 165 | self.fc_2 = nn.Linear(pf_dim, hid_dim) 166 | 167 | self.dropout = nn.Dropout(dropout) 168 | 169 | def forward(self, x): 170 | x = self.dropout(torch.relu(self.fc_1(x))) 171 | 172 | x = self.fc_2(x) 173 | 174 | return x 175 | 176 | class Decoder(nn.Module): 177 | def __init__(self, 178 | output_dim, 179 | hid_dim, 180 | n_layers, 181 | n_heads, 182 | pf_dim, 183 | dropout, 184 | max_length = 210): 185 | super().__init__() 186 | 187 | self.hid_dim = hid_dim 188 | 189 | self.tok_embedding = nn.Embedding(output_dim, hid_dim) 190 | self.pos_embedding = nn.Embedding(max_length, hid_dim) 191 | 192 | self.layers = nn.ModuleList([DecoderLayer(hid_dim, 193 | n_heads, 194 | pf_dim, 195 | dropout) 196 | for _ in range(n_layers)]) 197 | 198 | self.dropout = nn.Dropout(dropout) 199 | 200 | def forward(self, trg, enc_src, trg_mask, src_mask): 201 | batch_size = trg.shape[0] 202 | trg_len = trg.shape[1] 203 | 204 | pos = torch.arange(0, trg_len).unsqueeze(0).to(trg.device) 205 | 206 | trg = self.dropout(self.tok_embedding(trg) * torch.sqrt(torch.FloatTensor([self.hid_dim])).to(trg.device) + self.pos_embedding(pos)) 207 | 208 | for layer in self.layers: 209 | output = layer(trg, enc_src, trg_mask, src_mask) 210 | 211 | return output 212 | 213 | class DecoderLayer(nn.Module): 214 | def __init__(self, 215 | hid_dim, 216 | n_heads, 217 | pf_dim, 218 | dropout): 219 | super().__init__() 220 | 221 | self.self_attn_layer_norm = nn.LayerNorm(hid_dim) 222 | self.enc_attn_layer_norm = nn.LayerNorm(hid_dim) 223 | self.ff_layer_norm = nn.LayerNorm(hid_dim) 224 | self.self_attention = MultiHeadAttentionLayer(hid_dim, n_heads, dropout) 225 | self.encoder_attention = MultiHeadAttentionLayer(hid_dim, n_heads, dropout) 226 | self.positionwise_feedforward = PositionwiseFeedforwardLayer(hid_dim, 227 | pf_dim, 228 | dropout) 229 | self.dropout = nn.Dropout(dropout) 230 | 231 | def forward(self, trg, enc_src, trg_mask, src_mask): 232 | _trg, _ = self.self_attention(trg, trg, trg, trg_mask) 233 | 234 | trg = self.self_attn_layer_norm(trg + self.dropout(_trg)) 235 | 236 | _trg, _ = self.encoder_attention(trg, enc_src, enc_src, src_mask) 237 | 238 | trg = self.enc_attn_layer_norm(trg + self.dropout(_trg)) 239 | 240 | _trg = self.positionwise_feedforward(trg) 241 | 242 | trg = self.ff_layer_norm(trg + self.dropout(_trg)) 243 | 244 | return trg 245 | 246 | class Seq2Seq(nn.Module): 247 | def __init__(self, 248 | encoder, 249 | decoder, 250 | hidden, 251 | pad_idx): 252 | super().__init__() 253 | 254 | self.hidden = hidden 255 | self.encoder = encoder 256 | self.decoder = decoder 257 | self.src_pad_idx = pad_idx 258 | self.trg_pad_idx = pad_idx 259 | 260 | def make_src_mask(self, src): 261 | # Determines if the last dimensional vector is a zero vector and returns the mask matrix (0+0+... +0 = 0) 262 | src_mask = (src.sum(axis=3).sum(axis=2) != self.src_pad_idx).unsqueeze(1).unsqueeze(2) 263 | src_subtoken_mask = (src != self.src_pad_idx) 264 | 265 | return src_mask, src_subtoken_mask 266 | 267 | def make_trg_mask(self, trg): 268 | trg_pad_mask = (trg != self.trg_pad_idx).unsqueeze(1).unsqueeze(2) 269 | trg_len = trg.shape[1] 270 | trg_sub_mask = torch.tril(torch.ones((trg_len, trg_len), device = trg_pad_mask.device)).bool() 271 | 272 | trg_mask = trg_pad_mask & trg_sub_mask 273 | 274 | return trg_mask 275 | 276 | def forward(self, src, pos_coeff, trg): 277 | src_mask, src_subtoken_mask = self.make_src_mask(src) 278 | trg_mask = self.make_trg_mask(trg) 279 | 280 | enc_src = self.encoder(src, pos_coeff, src_mask, src_subtoken_mask) 281 | 282 | output = self.decoder(trg, enc_src, trg_mask, src_mask) 283 | 284 | return output 285 | -------------------------------------------------------------------------------- /model/treebert.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | 3 | class TreeBERT(nn.Module): 4 | def __init__(self, transformer, vocab_size): 5 | super().__init__() 6 | self.transformer = transformer 7 | self.mask_lm = MaskedLanguageModel(self.transformer.hidden, vocab_size) 8 | self.node_order_prediction = NodeOrderPrediction(self.transformer.hidden) 9 | 10 | def forward(self, x, p, y): 11 | output = self.transformer(x,p,y) 12 | return self.node_order_prediction(output[:,-2:-1,:]), self.mask_lm(output) 13 | 14 | class NodeOrderPrediction(nn.Module): 15 | def __init__(self, hidden): 16 | super().__init__() 17 | self.linear = nn.Linear(hidden, 1) 18 | 19 | def forward(self, x): 20 | x = self.linear(x).squeeze(1) 21 | return x 22 | 23 | class MaskedLanguageModel(nn.Module): 24 | def __init__(self, hidden, vocab_size): 25 | super().__init__() 26 | self.fc_out = nn.Linear(hidden, vocab_size) 27 | self.softmax = nn.LogSoftmax(dim=-1) 28 | 29 | def forward(self, x): 30 | x = self.fc_out(x) 31 | return self.softmax(x) 32 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | tqdm 2 | numpy 3 | tree-sitter 4 | torch 5 | -------------------------------------------------------------------------------- /trainer/__init__.py: -------------------------------------------------------------------------------- 1 | from .pretrain import BERTTrainer 2 | from .optim_schedule import ScheduledOptim -------------------------------------------------------------------------------- /trainer/optim_schedule.py: -------------------------------------------------------------------------------- 1 | '''A wrapper class for optimizer ''' 2 | import numpy as np 3 | 4 | 5 | class ScheduledOptim(): 6 | '''A simple wrapper class for learning rate scheduling''' 7 | 8 | def __init__(self, optimizer, d_model, n_warmup_steps): 9 | self._optimizer = optimizer 10 | self.n_warmup_steps = n_warmup_steps 11 | self.n_current_steps = 0 12 | self.init_lr = np.power(d_model, -0.5) 13 | 14 | def step_and_update_lr(self): 15 | "Step with the inner optimizer" 16 | self._update_learning_rate() 17 | self._optimizer.step() 18 | 19 | def zero_grad(self): 20 | "Zero out the gradients by the inner optimizer" 21 | self._optimizer.zero_grad() 22 | 23 | def _get_lr_scale(self): 24 | return np.min([ 25 | np.power(self.n_current_steps, -0.5), 26 | np.power(self.n_warmup_steps, -1.5) * self.n_current_steps]) 27 | 28 | def _update_learning_rate(self): 29 | ''' Learning rate scheduling per step ''' 30 | 31 | self.n_current_steps += 1 32 | lr = self.init_lr * self._get_lr_scale() 33 | 34 | for param_group in self._optimizer.param_groups: 35 | param_group['lr'] = lr 36 | -------------------------------------------------------------------------------- /trainer/pretrain.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | import torch 4 | import torch.nn as nn 5 | from torch.optim import Adam 6 | from torch.utils.data import DataLoader 7 | 8 | from .optim_schedule import ScheduledOptim 9 | 10 | sys.path.append("..") 11 | import tqdm 12 | from model import TreeBERT, transformer 13 | 14 | 15 | class BERTTrainer: 16 | def __init__(self, transformer, alpha, vocab_size: int, 17 | train_dataloader: DataLoader, test_dataloader: DataLoader = None, 18 | lr: float = 1e-4, betas=(0.9, 0.999), weight_decay: float = 0.01, warmup_steps=10000, 19 | with_cuda: bool = True, cuda_devices=None, log_freq: int = 10): 20 | 21 | self.alpha = alpha 22 | cuda_condition = torch.cuda.is_available() and with_cuda 23 | self.device = torch.device("cuda:0" if cuda_condition else "cpu") 24 | 25 | self.transformer = transformer 26 | self.model = TreeBERT(self.transformer, vocab_size).to(self.device) 27 | 28 | # Distributed GPU training if CUDA can detect more than 1 GPU 29 | if with_cuda and torch.cuda.device_count() > 1: 30 | print("Using %d GPUS for TreeBERT" % torch.cuda.device_count()) 31 | self.model = nn.DataParallel(self.model, device_ids=cuda_devices) 32 | 33 | self.train_data = train_dataloader 34 | self.test_data = test_dataloader 35 | 36 | self.optim = Adam(self.model.parameters(), lr=lr, betas=betas, weight_decay=weight_decay) 37 | self.optim_schedule = ScheduledOptim(self.optim, self.transformer.hidden, n_warmup_steps=warmup_steps) 38 | 39 | self.criterionNOP = nn.BCEWithLogitsLoss() 40 | self.criterionTMLM = nn.NLLLoss(ignore_index=-2) 41 | 42 | self.log_freq = log_freq 43 | 44 | print("Total Parameters:", sum([p.nelement() for p in self.model.parameters()])) 45 | 46 | def train(self, epoch): 47 | loss = self.iteration(epoch, self.train_data) 48 | return loss 49 | 50 | def test(self, epoch): 51 | loss = self.iteration(epoch, self.test_data, train=False) 52 | return loss 53 | 54 | def iteration(self, epoch, data_loader, train=True): 55 | str_code = "train" if train else "test" 56 | 57 | data_iter = tqdm.tqdm(enumerate(data_loader), 58 | desc="EP_%s:%d" % (str_code, epoch), 59 | total=len(data_loader), 60 | bar_format="{l_bar}{r_bar}") 61 | 62 | avg_loss = 0.0 63 | total_correct = 0 64 | total_element = 0 65 | 66 | for i, data in data_iter: 67 | data = {key: value.to(self.device) for key, value in data.items()} 68 | 69 | node_order_predic, tree_mask_predic = self.model.forward(data["encoder_input"], data["node_pos_em_coeff"], data["decoder_input"]) 70 | NOP_loss = self.criterionNOP(node_order_predic.squeeze(dim=-1), data["is_ast_order"].float()) 71 | tree_mask_predic = tree_mask_predic.reshape(-1,tree_mask_predic.shape[-1]) 72 | target = data["decoder_output"].reshape(-1) 73 | TMLM_loss = self.criterionTMLM(tree_mask_predic, target) 74 | 75 | loss = (1-self.alpha) * NOP_loss + self.alpha * TMLM_loss 76 | 77 | if train: 78 | self.optim_schedule.zero_grad() 79 | loss.backward() 80 | self.optim_schedule.step_and_update_lr() 81 | 82 | NOP_prediction = (node_order_predic > 0.5).squeeze(-1) 83 | correct = NOP_prediction.eq(data["is_ast_order"]).sum().item() 84 | avg_loss += loss.item() 85 | total_correct += correct 86 | total_element += data["is_ast_order"].nelement() 87 | 88 | print("EP%d_%s, avg_loss=" % (epoch, str_code), avg_loss / len(data_iter), "NOP_total_acc=", 89 | total_correct * 100.0 / total_element) 90 | 91 | return avg_loss / len(data_iter) 92 | 93 | def save(self, epoch, model, file_path="output/bert_trained.model"): 94 | output_path = file_path + ".ep%d" % epoch 95 | torch.save(model, output_path) 96 | model.to(self.device) 97 | print("EP:%d Model Saved on:" % epoch, output_path) 98 | return output_path 99 | --------------------------------------------------------------------------------