-
Notifications
You must be signed in to change notification settings - Fork 301
Port gpt2 transformers checkpoint #1704
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
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
0829d62
port gpt2
cosmo3769 28dd08c
updated test
cosmo3769 4008008
removed unused params
cosmo3769 5fad456
update key prefix
cosmo3769 e342e4f
update sharded files
cosmo3769 91b8b69
update get_prefix logic
cosmo3769 c035ba3
added docsting for get_prefix func
cosmo3769 55af1f6
consistent comment keras style
cosmo3769 1976a23
optimized get_prefixed_key func
cosmo3769 bd096cb
change intermediate_dim config value
cosmo3769 a428fa8
replaced harcoded value
cosmo3769 a024ccf
code formatted
cosmo3769 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
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,186 @@ | ||
# Copyright 2024 The KerasNLP Authors | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
import numpy as np | ||
|
||
from keras_nlp.src.utils.preset_utils import HF_CONFIG_FILE | ||
from keras_nlp.src.utils.preset_utils import get_file | ||
from keras_nlp.src.utils.preset_utils import jax_memory_cleanup | ||
from keras_nlp.src.utils.preset_utils import load_config | ||
from keras_nlp.src.utils.transformers.safetensor_utils import SafetensorLoader | ||
|
||
|
||
def convert_backbone_config(transformers_config): | ||
return { | ||
"vocabulary_size": transformers_config["vocab_size"], | ||
"num_layers": transformers_config["n_layer"], | ||
"num_heads": transformers_config["n_head"], | ||
"hidden_dim": transformers_config["n_embd"], | ||
"intermediate_dim": transformers_config["n_embd"] * 4, | ||
"dropout": transformers_config["resid_pdrop"], | ||
"max_sequence_length": transformers_config["n_positions"], | ||
} | ||
|
||
|
||
def convert_weights(backbone, loader, transformers_config): | ||
# Embeddings | ||
loader.port_weight( | ||
keras_variable=backbone.token_embedding.embeddings, | ||
hf_weight_key="wte.weight", | ||
) | ||
loader.port_weight( | ||
keras_variable=backbone.position_embedding.position_embeddings, | ||
hf_weight_key="wpe.weight", | ||
) | ||
|
||
# Attention blocks | ||
for index in range(backbone.num_layers): | ||
decoder_layer = backbone.transformer_layers[index] | ||
|
||
# Norm layers | ||
loader.port_weight( | ||
keras_variable=decoder_layer._self_attention_layer_norm.gamma, | ||
hf_weight_key=f"h.{index}.ln_1.weight", | ||
) | ||
loader.port_weight( | ||
keras_variable=decoder_layer._self_attention_layer_norm.beta, | ||
hf_weight_key=f"h.{index}.ln_1.bias", | ||
) | ||
loader.port_weight( | ||
keras_variable=decoder_layer._feedforward_layer_norm.gamma, | ||
hf_weight_key=f"h.{index}.ln_2.weight", | ||
) | ||
loader.port_weight( | ||
keras_variable=decoder_layer._feedforward_layer_norm.beta, | ||
hf_weight_key=f"h.{index}.ln_2.bias", | ||
) | ||
|
||
# Attention layers | ||
n_embd = transformers_config["n_embd"] | ||
|
||
# Query | ||
loader.port_weight( | ||
keras_variable=decoder_layer._self_attention_layer.query_dense.kernel, | ||
hf_weight_key=f"h.{index}.attn.c_attn.weight", | ||
hook_fn=lambda hf_tensor, keras_shape: np.reshape( | ||
hf_tensor[:, :n_embd], keras_shape | ||
), | ||
) | ||
loader.port_weight( | ||
keras_variable=decoder_layer._self_attention_layer.query_dense.bias, | ||
hf_weight_key=f"h.{index}.attn.c_attn.bias", | ||
hook_fn=lambda hf_tensor, keras_shape: np.reshape( | ||
hf_tensor[:n_embd], keras_shape | ||
), | ||
) | ||
|
||
# Key | ||
loader.port_weight( | ||
keras_variable=decoder_layer._self_attention_layer.key_dense.kernel, | ||
hf_weight_key=f"h.{index}.attn.c_attn.weight", | ||
hook_fn=lambda hf_tensor, keras_shape: np.reshape( | ||
hf_tensor[:, n_embd : 2 * n_embd], keras_shape | ||
), | ||
) | ||
loader.port_weight( | ||
keras_variable=decoder_layer._self_attention_layer.key_dense.bias, | ||
hf_weight_key=f"h.{index}.attn.c_attn.bias", | ||
hook_fn=lambda hf_tensor, keras_shape: np.reshape( | ||
hf_tensor[n_embd : 2 * n_embd], keras_shape | ||
), | ||
) | ||
|
||
# Value | ||
loader.port_weight( | ||
keras_variable=decoder_layer._self_attention_layer.value_dense.kernel, | ||
hf_weight_key=f"h.{index}.attn.c_attn.weight", | ||
hook_fn=lambda hf_tensor, keras_shape: np.reshape( | ||
hf_tensor[:, 2 * n_embd :], keras_shape | ||
), | ||
) | ||
loader.port_weight( | ||
keras_variable=decoder_layer._self_attention_layer.value_dense.bias, | ||
hf_weight_key=f"h.{index}.attn.c_attn.bias", | ||
hook_fn=lambda hf_tensor, keras_shape: np.reshape( | ||
hf_tensor[2 * n_embd :], keras_shape | ||
), | ||
) | ||
|
||
# Output | ||
loader.port_weight( | ||
keras_variable=decoder_layer._self_attention_layer.output_dense.kernel, | ||
hf_weight_key=f"h.{index}.attn.c_proj.weight", | ||
hook_fn=lambda hf_tensor, keras_shape: np.reshape( | ||
hf_tensor, keras_shape | ||
), | ||
) | ||
loader.port_weight( | ||
keras_variable=decoder_layer._self_attention_layer.output_dense.bias, | ||
hf_weight_key=f"h.{index}.attn.c_proj.bias", | ||
) | ||
|
||
# MLP layers | ||
loader.port_weight( | ||
keras_variable=decoder_layer._feedforward_intermediate_dense.kernel, | ||
hf_weight_key=f"h.{index}.mlp.c_fc.weight", | ||
hook_fn=lambda hf_tensor, keras_shape: np.reshape( | ||
hf_tensor, keras_shape | ||
), | ||
) | ||
loader.port_weight( | ||
keras_variable=decoder_layer._feedforward_intermediate_dense.bias, | ||
hf_weight_key=f"h.{index}.mlp.c_fc.bias", | ||
) | ||
loader.port_weight( | ||
keras_variable=decoder_layer._feedforward_output_dense.kernel, | ||
hf_weight_key=f"h.{index}.mlp.c_proj.weight", | ||
hook_fn=lambda hf_tensor, keras_shape: np.reshape( | ||
hf_tensor, keras_shape | ||
), | ||
) | ||
loader.port_weight( | ||
keras_variable=decoder_layer._feedforward_output_dense.bias, | ||
hf_weight_key=f"h.{index}.mlp.c_proj.bias", | ||
) | ||
|
||
# Normalization | ||
loader.port_weight( | ||
keras_variable=backbone.layer_norm.gamma, | ||
hf_weight_key="ln_f.weight", | ||
) | ||
loader.port_weight( | ||
keras_variable=backbone.layer_norm.beta, | ||
hf_weight_key="ln_f.bias", | ||
) | ||
|
||
return backbone | ||
|
||
|
||
def load_gpt2_backbone(cls, preset, load_weights): | ||
transformers_config = load_config(preset, HF_CONFIG_FILE) | ||
keras_config = convert_backbone_config(transformers_config) | ||
backbone = cls(**keras_config) | ||
if load_weights: | ||
jax_memory_cleanup(backbone) | ||
with SafetensorLoader(preset) as loader: | ||
convert_weights(backbone, loader, transformers_config) | ||
return backbone | ||
|
||
|
||
def load_gpt2_tokenizer(cls, preset): | ||
vocab_file = get_file(preset, "vocab.json") | ||
merges_file = get_file(preset, "merges.txt") | ||
return cls( | ||
vocabulary=vocab_file, | ||
merges=merges_file, | ||
) |
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,27 @@ | ||
# Copyright 2024 The KerasNLP Authors | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
import pytest | ||
|
||
from keras_nlp.src.models.gpt2.gpt2_causal_lm import GPT2CausalLM | ||
from keras_nlp.src.tests.test_case import TestCase | ||
|
||
|
||
class TestTask(TestCase): | ||
@pytest.mark.large | ||
def test_convert_tiny_preset(self): | ||
model = GPT2CausalLM.from_preset("hf://openai-community/gpt2") | ||
prompt = "What is your favorite condiment?" | ||
model.generate([prompt], max_length=15) | ||
|
||
# TODO: compare numerics with huggingface model |
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
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.