Pradeep Kumar commited on
Commit
a173dbb
·
verified ·
1 Parent(s): 1b88228

Delete tf2_albert_encoder_checkpoint_converter.py

Browse files
tf2_albert_encoder_checkpoint_converter.py DELETED
@@ -1,170 +0,0 @@
1
- # Copyright 2024 The TensorFlow Authors. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- """A converter from a tf1 ALBERT encoder checkpoint to a tf2 encoder checkpoint.
16
-
17
- The conversion will yield an object-oriented checkpoint that can be used
18
- to restore an AlbertEncoder object.
19
- """
20
- import os
21
-
22
- from absl import app
23
- from absl import flags
24
-
25
- import tensorflow as tf, tf_keras
26
- from official.legacy.albert import configs
27
- from official.modeling import tf_utils
28
- from official.nlp.modeling import models
29
- from official.nlp.modeling import networks
30
- from official.nlp.tools import tf1_bert_checkpoint_converter_lib
31
-
32
- FLAGS = flags.FLAGS
33
-
34
- flags.DEFINE_string("albert_config_file", None,
35
- "Albert configuration file to define core bert layers.")
36
- flags.DEFINE_string(
37
- "checkpoint_to_convert", None,
38
- "Initial checkpoint from a pretrained BERT model core (that is, only the "
39
- "BertModel, with no task heads.)")
40
- flags.DEFINE_string("converted_checkpoint_path", None,
41
- "Name for the created object-based V2 checkpoint.")
42
- flags.DEFINE_string("checkpoint_model_name", "encoder",
43
- "The name of the model when saving the checkpoint, i.e., "
44
- "the checkpoint will be saved using: "
45
- "tf.train.Checkpoint(FLAGS.checkpoint_model_name=model).")
46
- flags.DEFINE_enum(
47
- "converted_model", "encoder", ["encoder", "pretrainer"],
48
- "Whether to convert the checkpoint to a `AlbertEncoder` model or a "
49
- "`BertPretrainerV2` model (with mlm but without classification heads).")
50
-
51
-
52
- ALBERT_NAME_REPLACEMENTS = (
53
- ("bert/encoder/", ""),
54
- ("bert/", ""),
55
- ("embeddings/word_embeddings", "word_embeddings/embeddings"),
56
- ("embeddings/position_embeddings", "position_embedding/embeddings"),
57
- ("embeddings/token_type_embeddings", "type_embeddings/embeddings"),
58
- ("embeddings/LayerNorm", "embeddings/layer_norm"),
59
- ("embedding_hidden_mapping_in", "embedding_projection"),
60
- ("group_0/inner_group_0/", ""),
61
- ("attention_1/self", "self_attention"),
62
- ("attention_1/output/dense", "self_attention/attention_output"),
63
- ("transformer/LayerNorm/", "transformer/self_attention_layer_norm/"),
64
- ("ffn_1/intermediate/dense", "intermediate"),
65
- ("ffn_1/intermediate/output/dense", "output"),
66
- ("transformer/LayerNorm_1/", "transformer/output_layer_norm/"),
67
- ("pooler/dense", "pooler_transform"),
68
- ("cls/predictions", "bert/cls/predictions"),
69
- ("cls/predictions/output_bias", "cls/predictions/output_bias/bias"),
70
- ("cls/seq_relationship/output_bias", "predictions/transform/logits/bias"),
71
- ("cls/seq_relationship/output_weights",
72
- "predictions/transform/logits/kernel"),
73
- )
74
-
75
-
76
- def _create_albert_model(cfg):
77
- """Creates an ALBERT keras core model from BERT configuration.
78
-
79
- Args:
80
- cfg: A `AlbertConfig` to create the core model.
81
-
82
- Returns:
83
- A keras model.
84
- """
85
- albert_encoder = networks.AlbertEncoder(
86
- vocab_size=cfg.vocab_size,
87
- hidden_size=cfg.hidden_size,
88
- embedding_width=cfg.embedding_size,
89
- num_layers=cfg.num_hidden_layers,
90
- num_attention_heads=cfg.num_attention_heads,
91
- intermediate_size=cfg.intermediate_size,
92
- activation=tf_utils.get_activation(cfg.hidden_act),
93
- dropout_rate=cfg.hidden_dropout_prob,
94
- attention_dropout_rate=cfg.attention_probs_dropout_prob,
95
- max_sequence_length=cfg.max_position_embeddings,
96
- type_vocab_size=cfg.type_vocab_size,
97
- initializer=tf_keras.initializers.TruncatedNormal(
98
- stddev=cfg.initializer_range))
99
- return albert_encoder
100
-
101
-
102
- def _create_pretrainer_model(cfg):
103
- """Creates a pretrainer with AlbertEncoder from ALBERT configuration.
104
-
105
- Args:
106
- cfg: A `BertConfig` to create the core model.
107
-
108
- Returns:
109
- A BertPretrainerV2 model.
110
- """
111
- albert_encoder = _create_albert_model(cfg)
112
- pretrainer = models.BertPretrainerV2(
113
- encoder_network=albert_encoder,
114
- mlm_activation=tf_utils.get_activation(cfg.hidden_act),
115
- mlm_initializer=tf_keras.initializers.TruncatedNormal(
116
- stddev=cfg.initializer_range))
117
- # Makes sure masked_lm layer's variables in pretrainer are created.
118
- _ = pretrainer(pretrainer.inputs)
119
- return pretrainer
120
-
121
-
122
- def convert_checkpoint(bert_config, output_path, v1_checkpoint,
123
- checkpoint_model_name,
124
- converted_model="encoder"):
125
- """Converts a V1 checkpoint into an OO V2 checkpoint."""
126
- output_dir, _ = os.path.split(output_path)
127
-
128
- # Create a temporary V1 name-converted checkpoint in the output directory.
129
- temporary_checkpoint_dir = os.path.join(output_dir, "temp_v1")
130
- temporary_checkpoint = os.path.join(temporary_checkpoint_dir, "ckpt")
131
- tf1_bert_checkpoint_converter_lib.convert(
132
- checkpoint_from_path=v1_checkpoint,
133
- checkpoint_to_path=temporary_checkpoint,
134
- num_heads=bert_config.num_attention_heads,
135
- name_replacements=ALBERT_NAME_REPLACEMENTS,
136
- permutations=tf1_bert_checkpoint_converter_lib.BERT_V2_PERMUTATIONS,
137
- exclude_patterns=["adam", "Adam"])
138
-
139
- # Create a V2 checkpoint from the temporary checkpoint.
140
- if converted_model == "encoder":
141
- model = _create_albert_model(bert_config)
142
- elif converted_model == "pretrainer":
143
- model = _create_pretrainer_model(bert_config)
144
- else:
145
- raise ValueError("Unsupported converted_model: %s" % converted_model)
146
-
147
- tf1_bert_checkpoint_converter_lib.create_v2_checkpoint(
148
- model, temporary_checkpoint, output_path, checkpoint_model_name)
149
-
150
- # Clean up the temporary checkpoint, if it exists.
151
- try:
152
- tf.io.gfile.rmtree(temporary_checkpoint_dir)
153
- except tf.errors.OpError:
154
- # If it doesn't exist, we don't need to clean it up; continue.
155
- pass
156
-
157
-
158
- def main(_):
159
- output_path = FLAGS.converted_checkpoint_path
160
- v1_checkpoint = FLAGS.checkpoint_to_convert
161
- checkpoint_model_name = FLAGS.checkpoint_model_name
162
- converted_model = FLAGS.converted_model
163
- albert_config = configs.AlbertConfig.from_json_file(FLAGS.albert_config_file)
164
- convert_checkpoint(albert_config, output_path, v1_checkpoint,
165
- checkpoint_model_name,
166
- converted_model=converted_model)
167
-
168
-
169
- if __name__ == "__main__":
170
- app.run(main)