-
Notifications
You must be signed in to change notification settings - Fork 2.3k
[won't merge - v1 codebase] Bert #1543
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Zenglinxiao
wants to merge
32
commits into
OpenNMT:master
Choose a base branch
from
Zenglinxiao:bert
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 18 commits
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
fd8ac2e
Bert init commit
Zenglinxiao 7601a88
support file
Zenglinxiao 1c0498e
activation function
Zenglinxiao de3ca85
bert dataset
Zenglinxiao ede0250
add a new way of using bert
Zenglinxiao 1dfa50a
merge some function
Zenglinxiao c1dd1f9
adapt BERT related module to ONMT habit
Zenglinxiao 8c3436f
add downsteam task support
Zenglinxiao 12a909a
update
Zenglinxiao ea14b13
update
Zenglinxiao 3fae446
fix bug; add new feature
Zenglinxiao 4b511e4
add prediction file
Zenglinxiao 7f6a127
clean up code
Zenglinxiao 892e0a0
tagging bug fix
Zenglinxiao ed0cf4d
clean code
Zenglinxiao dde55e6
Merge branch 'master' of https://github.com/OpenNMT/OpenNMT-py into bert
Zenglinxiao 6c5ec3a
Fix flake8
Zenglinxiao ba8a358
solve PR check
Zenglinxiao 08b1080
minor changes to make code simpler/more explicit
pltrdy b317ecf
Merge pull request #1 from pltrdy/bert
Zenglinxiao 660e459
simplify code
Zenglinxiao e5b0355
fix import; clarify FAQ
Zenglinxiao 1a676b2
fix build
Zenglinxiao 4335a13
fix exception
Zenglinxiao f5aec9f
switch BertLayerNorm to offical LayerNorm, change BertAdam to AdamW w…
Zenglinxiao 4938a93
fix bert valid step, remove unuse part in saver
Zenglinxiao b1658f5
add dynamic batchingwhen inference
Zenglinxiao 9b1abd2
update classifier with confiance option
Zenglinxiao 2e7e8d1
merge recent change on master
Zenglinxiao e352a94
rm tailing space
Zenglinxiao 9d655fd
merge recent update from master
Zenglinxiao 6c8e8e6
fix travis
Zenglinxiao File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| #!/usr/bin/env python | ||
| """ Convert weights of huggingface Bert to onmt Bert""" | ||
| from argparse import ArgumentParser | ||
| import torch | ||
| from onmt.encoders.bert import BertEncoder | ||
| from onmt.models.bert_generators import BertPreTrainingHeads | ||
| from onmt.modules.bert_embeddings import BertEmbeddings | ||
| from collections import OrderedDict | ||
| import re | ||
|
|
||
|
|
||
| def decrement(matched): | ||
| value = int(matched.group(1)) | ||
| if value < 1: | ||
| raise ValueError('Value Error when converting string') | ||
| string = "bert.encoder.layer.{}.output.LayerNorm".format(value-1) | ||
| return string | ||
|
|
||
|
|
||
| def mapping_key(key, max_layers): | ||
| if 'bert.embeddings' in key: | ||
| key = key | ||
|
|
||
| elif 'bert.encoder' in key: | ||
| # convert layer_norm weights | ||
| key = re.sub(r'bert.encoder.0.layer_norm\.(.*)', | ||
| r'bert.embeddings.LayerNorm.\1', key) | ||
| key = re.sub(r'bert.encoder\.(\d+)\.layer_norm', | ||
| decrement, key) | ||
| # convert attention weights | ||
| key = re.sub(r'bert.encoder\.(\d+)\.self_attn.linear_keys\.(.*)', | ||
| r'bert.encoder.layer.\1.attention.self.key.\2', key) | ||
| key = re.sub(r'bert.encoder\.(\d+)\.self_attn.linear_values\.(.*)', | ||
| r'bert.encoder.layer.\1.attention.self.value.\2', key) | ||
| key = re.sub(r'bert.encoder\.(\d+)\.self_attn.linear_query\.(.*)', | ||
| r'bert.encoder.layer.\1.attention.self.query.\2', key) | ||
| key = re.sub(r'bert.encoder\.(\d+)\.self_attn.final_linear\.(.*)', | ||
| r'bert.encoder.layer.\1.attention.output.dense.\2', key) | ||
| # convert feed forward weights | ||
| key = re.sub(r'bert.encoder\.(\d+)\.feed_forward.layer_norm\.(.*)', | ||
| r'bert.encoder.layer.\1.attention.output.LayerNorm.\2', | ||
| key) | ||
| key = re.sub(r'bert.encoder\.(\d+)\.feed_forward.w_1\.(.*)', | ||
| r'bert.encoder.layer.\1.intermediate.dense.\2', key) | ||
| key = re.sub(r'bert.encoder\.(\d+)\.feed_forward.w_2\.(.*)', | ||
| r'bert.encoder.layer.\1.output.dense.\2', key) | ||
|
|
||
| elif 'bert.layer_norm' in key: | ||
| key = re.sub(r'bert.layer_norm', | ||
| r'bert.encoder.layer.' + str(max_layers - 1) + | ||
| '.output.LayerNorm', key) | ||
| elif 'bert.pooler' in key: | ||
| key = key | ||
| elif 'generator.next_sentence' in key: | ||
| key = re.sub(r'generator.next_sentence.linear\.(.*)', | ||
| r'cls.seq_relationship.\1', key) | ||
| elif 'generator.mask_lm' in key: | ||
| key = re.sub(r'generator.mask_lm.bias', | ||
| r'cls.predictions.bias', key) | ||
| key = re.sub(r'generator.mask_lm.decode.weight', | ||
| r'cls.predictions.decoder.weight', key) | ||
| key = re.sub(r'generator.mask_lm.transform.dense\.(.*)', | ||
| r'cls.predictions.transform.dense.\1', key) | ||
| key = re.sub(r'generator.mask_lm.transform.layer_norm\.(.*)', | ||
| r'cls.predictions.transform.LayerNorm.\1', key) | ||
| else: | ||
| raise KeyError("Unexpected keys! Please provide HuggingFace weights") | ||
| return key | ||
|
|
||
|
|
||
| def convert_bert_weights(bert_model, weights, n_layers=12): | ||
| bert_model_keys = bert_model.state_dict().keys() | ||
| bert_weights = OrderedDict() | ||
| generator_weights = OrderedDict() | ||
| model_weights = {"bert": bert_weights, | ||
| "generator": generator_weights} | ||
| hugface_keys = weights.keys() | ||
| try: | ||
| for key in bert_model_keys: | ||
| hugface_key = mapping_key(key, n_layers) | ||
| if hugface_key not in hugface_keys: | ||
| if 'LayerNorm' in hugface_key: | ||
| # Fix LayerNorm of old huggingface ckp | ||
| hugface_key = re.sub(r'LayerNorm.weight', | ||
| r'LayerNorm.gamma', hugface_key) | ||
| hugface_key = re.sub(r'LayerNorm.bias', | ||
| r'LayerNorm.beta', hugface_key) | ||
| if hugface_key in hugface_keys: | ||
| print("[OLD Weights file]gamma/beta is used in " + | ||
| "naming BertLayerNorm. Mapping succeed.") | ||
| else: | ||
| raise KeyError("Key %s not found in weight file" | ||
| % hugface_key) | ||
| else: | ||
| raise KeyError("Key %s not found in weight file" | ||
| % hugface_key) | ||
| if 'generator' not in key: | ||
| onmt_key = re.sub(r'bert\.(.*)', r'\1', key) | ||
| model_weights['bert'][onmt_key] = weights[hugface_key] | ||
| else: | ||
| onmt_key = re.sub(r'generator\.(.*)', r'\1', key) | ||
| model_weights['generator'][onmt_key] = weights[hugface_key] | ||
| except ValueError: | ||
| print("Unsuccessful convert!") | ||
| exit() | ||
| return model_weights | ||
|
|
||
|
|
||
| def main(): | ||
| parser = ArgumentParser() | ||
| parser.add_argument("--layers", type=int, default=None, required=True) | ||
|
|
||
| parser.add_argument("--bert_model_weights_file", "-i", type=str, | ||
| default=None, required=True, help="Path to the " | ||
| "huggingface Bert weights file download from " | ||
| "https://github.com/huggingface/pytorch-transformers") | ||
|
|
||
| parser.add_argument("--output_name", "-o", type=str, | ||
| default=None, required=True, | ||
| help="output onmt version Bert weight file Path") | ||
| args = parser.parse_args() | ||
|
|
||
| print("Model contain {} layers.".format(args.layers)) | ||
|
|
||
| print("Load weights from {}.".format(args.bert_model_weights_file)) | ||
|
|
||
| bert_weights = torch.load(args.bert_model_weights_file) | ||
| embeddings = BertEmbeddings(28996) # vocab don't bother the conversion | ||
| bert_encoder = BertEncoder(embeddings) | ||
| generator = BertPreTrainingHeads(bert_encoder.d_model, | ||
| embeddings.vocab_size) | ||
| bertlm = torch.nn.Sequential(OrderedDict([ | ||
| ('bert', bert_encoder), | ||
| ('generator', generator)])) | ||
| model_weights = convert_bert_weights(bertlm, bert_weights, args.layers) | ||
|
|
||
| ckp = {'model': model_weights['bert'], | ||
| 'generator': model_weights['generator']} | ||
|
|
||
| outfile = args.output_name | ||
| print("Converted weights file in {}".format(outfile)) | ||
| torch.save(ckp, outfile) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.