Skip to content
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

include the output layer in the model using the pretrained weights #18

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions convert_tf_checkpoint_to_pytorch.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,21 @@ def convert():
arrays.append(array)

for name, array in zip(names, arrays):

# include the output_layer in the model
if (name=="bert/embeddings/word_embeddings"):
pointer = model
pointer = getattr(pointer, 'output_layer')
pointer = getattr(pointer, 'weight')
assert pointer.shape == array.shape
pointer.data = torch.from_numpy(array)
elif (name=="cls/predictions/output_bias"):
pointer = model
pointer = getattr(pointer, 'output_layer')
pointer = getattr(pointer, 'bias')
assert pointer.shape == array.shape
pointer.data = torch.from_numpy(array)

if not name.startswith("bert"):
print("Skipping {}".format(name))
continue
Expand Down
6 changes: 5 additions & 1 deletion modeling.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ class BERTEncoder(nn.Module):
def __init__(self, config):
super(BERTEncoder, self).__init__()
layer = BERTLayer(config)
self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config.num_hidden_layers)])
self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config.num_hidden_layers)])

def forward(self, hidden_states, attention_mask):
all_encoder_layers = []
Expand Down Expand Up @@ -330,6 +330,10 @@ def __init__(self, config: BertConfig):
self.encoder = BERTEncoder(config)
self.pooler = BERTPooler(config)

# the output weights are the same as the input embeddings,
# but there is an output-only bias for each token
self.output_layer = nn.Linear(config.hidden_size, config.vocab_size, bias=True)

def forward(self, input_ids, token_type_ids=None, attention_mask=None):
if attention_mask is None:
attention_mask = torch.ones_like(input_ids)
Expand Down