├── README.md ├── convet_ernie_to_pytorch.py └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | # ERNIE2Torch 2 | a script from ERNIE1.0 or ERNIE2.0 to transfomers' BERT format 3 | 4 | refer:https://github.com/nghuyong/ERNIE-Pytorch 5 | 6 | easy use:https://github.com/trueto/transformers_sklearn -------------------------------------------------------------------------------- /convet_ernie_to_pytorch.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import os 3 | import sys 4 | import argparse 5 | import numpy as np 6 | import paddle.fluid as fluid 7 | import torch 8 | import json 9 | 10 | if not os.path.exists('ERNIE'): 11 | os.system('git clone https://github.com/PaddlePaddle/ERNIE.git') 12 | sys.path = ['./ERNIE/ernie'] + sys.path 13 | try: 14 | from model.ernie import ErnieConfig, ErnieModel 15 | except: 16 | raise Exception('Place clone ERNIE first') 17 | 18 | 19 | def create_model(args, 20 | pyreader_name, 21 | ernie_config, 22 | is_prediction=False, 23 | task_name="", 24 | is_classify=True, 25 | is_regression=False, 26 | ernie_version="2.0"): 27 | 28 | src_ids = fluid.layers.data(name='eval_placeholder_0', shape=[-1, args.max_seq_len, 1], dtype='int64') 29 | sent_ids = fluid.layers.data(name='eval_placeholder_1', shape=[-1, args.max_seq_len, 1], dtype='int64') 30 | pos_ids = fluid.layers.data(name='eval_placeholder_2', shape=[-1, args.max_seq_len, 1], dtype='int64') 31 | input_mask = fluid.layers.data(name='eval_placeholder_3', shape=[-1, args.max_seq_len, 1], dtype='float32') 32 | task_ids = fluid.layers.data(name='eval_placeholder_4', shape=[-1, args.max_seq_len, 1], dtype='int64') 33 | qids = fluid.layers.data(name='eval_placeholder_5', shape=[-1, 1], dtype='int64') 34 | 35 | if is_classify: 36 | labels = fluid.layers.data(name='6', shape=[-1, 1], dtype='int64') 37 | elif is_regression: 38 | labels = fluid.layers.data(name='6', shape=[-1, 1], dtype='float32') 39 | 40 | pyreader = fluid.io.DataLoader.from_generator(feed_list=[src_ids, sent_ids, pos_ids, task_ids, input_mask, labels, qids], 41 | capacity=70, 42 | iterable=False) 43 | 44 | ernie = ErnieModel( 45 | src_ids=src_ids, 46 | position_ids=pos_ids, 47 | sentence_ids=sent_ids, 48 | task_ids=task_ids, 49 | input_mask=input_mask, 50 | config=ernie_config, 51 | use_fp16=args.use_fp16) 52 | 53 | cls_feats = ernie.get_pooled_output() 54 | cls_feats = fluid.layers.dropout( 55 | x=cls_feats, 56 | dropout_prob=0.1, 57 | dropout_implementation="upscale_in_train") 58 | logits = fluid.layers.fc( 59 | input=cls_feats, 60 | size=args.num_labels, 61 | param_attr=fluid.ParamAttr( 62 | name=task_name + "_cls_out_w", 63 | initializer=fluid.initializer.TruncatedNormal(scale=0.02)), 64 | bias_attr=fluid.ParamAttr( 65 | name=task_name + "_cls_out_b", 66 | initializer=fluid.initializer.Constant(0.))) 67 | 68 | assert is_classify != is_regression, 'is_classify or is_regression must be true and only one of them can be true' 69 | if is_prediction: 70 | if is_classify: 71 | probs = fluid.layers.softmax(logits) 72 | else: 73 | probs = logits 74 | feed_targets_name = [ 75 | src_ids.name, sent_ids.name, pos_ids.name, input_mask.name 76 | ] 77 | if ernie_version == "2.0": 78 | feed_targets_name += [task_ids.name] 79 | return pyreader, probs, feed_targets_name 80 | 81 | num_seqs = fluid.layers.create_tensor(dtype='int64') 82 | if is_classify: 83 | ce_loss, probs = fluid.layers.softmax_with_cross_entropy( 84 | logits=logits, label=labels, return_softmax=True) 85 | loss = fluid.layers.mean(x=ce_loss) 86 | accuracy = fluid.layers.accuracy( 87 | input=probs, label=labels, total=num_seqs) 88 | graph_vars = { 89 | "loss": loss, 90 | "probs": probs, 91 | "accuracy": accuracy, 92 | "labels": labels, 93 | "num_seqs": num_seqs, 94 | "qids": qids 95 | } 96 | elif is_regression: 97 | cost = fluid.layers.square_error_cost(input=logits, label=labels) 98 | loss = fluid.layers.mean(x=cost) 99 | graph_vars = { 100 | "loss": loss, 101 | "probs": logits, 102 | "labels": labels, 103 | "num_seqs": num_seqs, 104 | "qids": qids 105 | } 106 | else: 107 | raise ValueError( 108 | 'unsupported fine tune mode. only supported classify/regression') 109 | 110 | return pyreader, graph_vars 111 | 112 | 113 | def if_exist(var): 114 | return os.path.exists(os.path.join(args.init_pretraining_params, var.name)) 115 | 116 | 117 | def build_weight_map(): 118 | weight_map = collections.OrderedDict({ 119 | 'word_embedding': 'bert.embeddings.word_embeddings.weight', 120 | 'pos_embedding': 'bert.embeddings.position_embeddings.weight', 121 | 'sent_embedding': 'bert.embeddings.token_type_embeddings.weight', 122 | 'pre_encoder_layer_norm_scale': 'bert.embeddings.LayerNorm.gamma', 123 | 'pre_encoder_layer_norm_bias': 'bert.embeddings.LayerNorm.beta', 124 | }) 125 | 126 | def add_w_and_b(ernie_pre, pytroch_pre): 127 | weight_map[ernie_pre + ".w_0"] = pytroch_pre + ".weight" 128 | weight_map[ernie_pre + ".b_0"] = pytroch_pre + ".bias" 129 | 130 | def add_one_encoder_layer(layer_number): 131 | # attention 132 | add_w_and_b(f"encoder_layer_{layer_number}_multi_head_att_query_fc", 133 | f"bert.encoder.layer.{layer_number}.attention.self.query") 134 | add_w_and_b(f"encoder_layer_{layer_number}_multi_head_att_key_fc", 135 | f"bert.encoder.layer.{layer_number}.attention.self.key") 136 | add_w_and_b(f"encoder_layer_{layer_number}_multi_head_att_value_fc", 137 | f"bert.encoder.layer.{layer_number}.attention.self.value") 138 | add_w_and_b(f"encoder_layer_{layer_number}_multi_head_att_output_fc", 139 | f"bert.encoder.layer.{layer_number}.attention.output.dense") 140 | weight_map[f"encoder_layer_{layer_number}_post_att_layer_norm_bias"] = \ 141 | f"bert.encoder.layer.{layer_number}.attention.output.LayerNorm.bias" 142 | weight_map[f"encoder_layer_{layer_number}_post_att_layer_norm_scale"] = \ 143 | f"bert.encoder.layer.{layer_number}.attention.output.LayerNorm.weight" 144 | # intermediate 145 | add_w_and_b(f"encoder_layer_{layer_number}_ffn_fc_0", f"bert.encoder.layer.{layer_number}.intermediate.dense") 146 | # output 147 | add_w_and_b(f"encoder_layer_{layer_number}_ffn_fc_1", f"bert.encoder.layer.{layer_number}.output.dense") 148 | weight_map[f"encoder_layer_{layer_number}_post_ffn_layer_norm_bias"] = \ 149 | f"bert.encoder.layer.{layer_number}.output.LayerNorm.bias" 150 | weight_map[f"encoder_layer_{layer_number}_post_ffn_layer_norm_scale"] = \ 151 | f"bert.encoder.layer.{layer_number}.output.LayerNorm.weight" 152 | 153 | for i in range(12): 154 | add_one_encoder_layer(i) 155 | add_w_and_b('pooled_fc', 'bert.pooler.dense') 156 | 157 | # weight_map.update({ 158 | # 'mask_lm_trans_fc.b_0': 'cls.predictions.transform.dense.bias', 159 | # 'mask_lm_trans_fc.w_0': 'cls.predictions.transform.dense.weight', 160 | # 'mask_lm_trans_layer_norm_scale': 'cls.predictions.transform.LayerNorm.weight', 161 | # 'mask_lm_trans_layer_norm_bias': 'cls.predictions.transform.LayerNorm.bias', 162 | # 'mask_lm_out_fc.b_0': 'cls.predictions.bias', 163 | # }) 164 | 165 | return weight_map 166 | 167 | def extract_weights(args): 168 | # add ERNIR to environment 169 | print('extract weights start'.center(60, '=')) 170 | startup_prog = fluid.Program() 171 | test_prog = fluid.Program() 172 | place = fluid.CPUPlace() 173 | exe = fluid.Executor(place) 174 | exe.run(startup_prog) 175 | args.max_seq_len = 512 176 | args.use_fp16 = False 177 | args.num_labels = 2 178 | args.loss_scaling = 1.0 179 | ernie_config = ErnieConfig(args.ernie_config_path) 180 | ernie_config.print_config() 181 | with fluid.program_guard(test_prog, startup_prog): 182 | with fluid.unique_name.guard(): 183 | create_model( 184 | args, 185 | pyreader_name='train', 186 | ernie_config=ernie_config, 187 | ernie_version=args.ernie_version 188 | ) 189 | fluid.io.load_vars(exe, args.init_pretraining_params, main_program=test_prog, predicate=if_exist) 190 | state_dict = collections.OrderedDict() 191 | weight_map = build_weight_map() 192 | for ernie_name, pytorch_name in weight_map.items(): 193 | fluid_tensor = fluid.global_scope().find_var(ernie_name).get_tensor() 194 | fluid_array = np.array(fluid_tensor) 195 | if 'w_0' in ernie_name: 196 | fluid_array = fluid_array.transpose() 197 | state_dict[pytorch_name] = fluid_array 198 | print(f'{ernie_name} -> {pytorch_name} {fluid_array.shape}') 199 | print('extract weights done!'.center(60, '=')) 200 | return state_dict 201 | 202 | def save_model(args,state_dict, dump_path): 203 | print('save model start'.center(60, '=')) 204 | if not os.path.exists(dump_path): 205 | os.makedirs(dump_path) 206 | # save model 207 | for key in state_dict: 208 | state_dict[key] = torch.FloatTensor(state_dict[key]) 209 | torch.save(state_dict, os.path.join(dump_path, "pytorch_model.bin")) 210 | print('finish save model') 211 | # save config 212 | ernie_config = ErnieConfig(args.ernie_config_path)._config_dict 213 | # set layer_norm_eps, more detail see: https://github.com/PaddlePaddle/LARK/issues/75 214 | ernie_config['layer_norm_eps'] = 1e-5 215 | if args.ernie_version == '2.0': 216 | ernie_config["type_vocab_size"] = 4 217 | else: 218 | ernie_config["type_vocab_size"] = 2 219 | with open(os.path.join(dump_path, "config.json"), 'wt', encoding='utf-8') as f: 220 | json.dump(ernie_config, f, indent=4) 221 | print('finish save config') 222 | # save vocab.txt 223 | vocab_f = open(os.path.join(dump_path, "vocab.txt"), "wt", encoding='utf-8') 224 | with open("./ERNIE/config/vocab.txt", "rt", encoding='utf-8') as f: 225 | for line in f: 226 | data = line.strip().split("\t") 227 | vocab_f.writelines(data[0] + "\n") 228 | vocab_f.close() 229 | print('finish save vocab') 230 | print('save model done!'.center(60, '=')) 231 | 232 | if __name__ == "__main__": 233 | parser = argparse.ArgumentParser() 234 | parser.add_argument("--init_pretraining_params", default='./ERNIE_Large_en_stable-2.0.0/params', type=str, help=".") 235 | parser.add_argument("--ernie_config_path", default='./ERNIE_Large_en_stable-2.0.0/ernie_config.json', type=str, help=".") 236 | parser.add_argument("--output_dir", default='./ERNIE_Large_en_stable-2.0.0_pytorch', type=str, help=".") 237 | parser.add_argument("--ernie_version", default='2.0', type=str, help=".") 238 | parser.add_argument("--is_prediction", default=False, type=str, help=".") 239 | parser.add_argument("--is_classify", default=True, type=str, help=".") 240 | parser.add_argument("--is_regression", default=False, type=str, help=".") 241 | args = parser.parse_args() 242 | state_dict = extract_weights(args) 243 | save_model(args,state_dict, args.output_dir) -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------