





import argparse
import collections

import torch
from flax import traverse_util
from tax import checkpoints

from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration
from transformers.utils import logging


logging.set_verbosity_info()







def        __lowerCamelCase (							__a       :Any   ,					__a       :Optional[Any]   ,					__a       :Dict   ,					__a       :Union[str, Any]="attention"   )		->    Optional[int]:






		"""simple docstring"""

		A__  				=       params[F'{prefix}/layers_{i}/{layer_name}/key/kernel']
		A__  				=       params[F'{prefix}/layers_{i}/{layer_name}/out/kernel']
		A__  				=       params[F'{prefix}/layers_{i}/{layer_name}/query/kernel']
		A__  				=       params[F'{prefix}/layers_{i}/{layer_name}/value/kernel']
		return k, o, q, v







def        __lowerCamelCase (							__a       :Tuple   ,					__a       :List[str]   ,					__a       :str   ,					__a       :Optional[Any]=False   )		->    int:






		"""simple docstring"""

		if split_mlp_wi:
				A__  				=       params[F'{prefix}/layers_{i}/mlp/wi_0/kernel']
				A__  				=       params[F'{prefix}/layers_{i}/mlp/wi_1/kernel']
				A__  				=       (wi_a, wi_a)
		else:
				A__  				=       params[F'{prefix}/layers_{i}/mlp/wi/kernel']

		A__  				=       params[F'{prefix}/layers_{i}/mlp/wo/kernel']
		return wi, wo







def        __lowerCamelCase (							__a       :Optional[int]   ,					__a       :Optional[int]   ,					__a       :Dict   ,					__a       :List[Any]   )		->    int:






		"""simple docstring"""

		return params[F'{prefix}/layers_{i}/{layer_name}/scale']







def        __lowerCamelCase (							__a       :dict   ,					*, __a       :int   ,					__a       :bool   )		->    Tuple:






		"""simple docstring"""

		A__  				=       traverse_util.flatten_dict(variables["""target"""]   )
		A__  				=       {"""/""".join(__a   ): v for k, v in old.items()}

		# v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi
		A__  				=       """encoder/layers_0/mlp/wi_0/kernel""" in old
		print("""Split MLP:"""   ,					__a   )

		A__  				=       collections.OrderedDict()

		# Shared embeddings.
		A__  				=       old["""token_embedder/embedding"""]

		# Encoder.
		for i in range(__a   ):
				# Block i, layer 0 (Self Attention).
				A__  				=       tax_layer_norm_lookup(__a   ,					__a   ,					"""encoder"""   ,					"""pre_attention_layer_norm"""   )
				A__				,      A__				,      A__				,      A__  				=       tax_attention_lookup(__a   ,					__a   ,					"""encoder"""   ,					"""attention"""   )
				A__  				=       layer_norm
				A__  				=       k.T
				A__  				=       o.T
				A__  				=       q.T
				A__  				=       v.T

				# Block i, layer 1 (MLP).
				A__  				=       tax_layer_norm_lookup(__a   ,					__a   ,					"""encoder"""   ,					"""pre_mlp_layer_norm"""   )
				A__				,      A__  				=       tax_mlp_lookup(__a   ,					__a   ,					"""encoder"""   ,					__a   )
				A__  				=       layer_norm
				if split_mlp_wi:
						A__  				=       wi[0].T
						A__  				=       wi[1].T
				else:
						A__  				=       wi.T
				A__  				=       wo.T

		A__  				=       old[
		    """encoder/relpos_bias/rel_embedding"""
		].T
		A__  				=       old["""encoder/encoder_norm/scale"""]

		if not is_encoder_only:
				# Decoder.
				for i in range(__a   ):
						# Block i, layer 0 (Self Attention).
						A__  				=       tax_layer_norm_lookup(__a   ,					__a   ,					"""decoder"""   ,					"""pre_self_attention_layer_norm"""   )
						A__				,      A__				,      A__				,      A__  				=       tax_attention_lookup(__a   ,					__a   ,					"""decoder"""   ,					"""self_attention"""   )
						A__  				=       layer_norm
						A__  				=       k.T
						A__  				=       o.T
						A__  				=       q.T
						A__  				=       v.T

						# Block i, layer 1 (Cross Attention).
						A__  				=       tax_layer_norm_lookup(__a   ,					__a   ,					"""decoder"""   ,					"""pre_cross_attention_layer_norm"""   )
						A__				,      A__				,      A__				,      A__  				=       tax_attention_lookup(__a   ,					__a   ,					"""decoder"""   ,					"""encoder_decoder_attention"""   )
						A__  				=       layer_norm
						A__  				=       k.T
						A__  				=       o.T
						A__  				=       q.T
						A__  				=       v.T

						# Block i, layer 2 (MLP).
						A__  				=       tax_layer_norm_lookup(__a   ,					__a   ,					"""decoder"""   ,					"""pre_mlp_layer_norm"""   )
						A__				,      A__  				=       tax_mlp_lookup(__a   ,					__a   ,					"""decoder"""   ,					__a   )
						A__  				=       layer_norm
						if split_mlp_wi:
								A__  				=       wi[0].T
								A__  				=       wi[1].T
						else:
								A__  				=       wi.T
						A__  				=       wo.T

				A__  				=       old["""decoder/decoder_norm/scale"""]
				A__  				=       old[
				    """decoder/relpos_bias/rel_embedding"""
				].T

				# LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead)
				if "decoder/logits_dense/kernel" in old:
						A__  				=       old["""decoder/logits_dense/kernel"""].T

		return new







def        __lowerCamelCase (							__a       :Any   ,					__a       :bool   )		->    int:






		"""simple docstring"""

		A__  				=       collections.OrderedDict([(k, torch.from_numpy(v.copy()   )) for (k, v) in converted_params.items()]   )

		# Add what is missing.
		if "encoder.embed_tokens.weight" not in state_dict:
				A__  				=       state_dict["""shared.weight"""]

		if not is_encoder_only:
				if "decoder.embed_tokens.weight" not in state_dict:
						A__  				=       state_dict["""shared.weight"""]

				if "lm_head.weight" not in state_dict:  # For old 1.0 models.
						print("""Using shared word embeddings as lm_head."""   )
						A__  				=       state_dict["""shared.weight"""]

		return state_dict







def        __lowerCamelCase (							__a       :Any   ,					__a       :int   ,					__a       :Optional[Any]   ,					__a       :List[Any]   )		->    Optional[int]:






		"""simple docstring"""

		A__  				=       checkpoints.load_tax_checkpoint(__a   )
		A__  				=       convert_tax_to_pytorch(__a   ,					num_layers=config.num_layers   ,					is_encoder_only=__a   )
		A__  				=       make_state_dict(__a   ,					__a   )
		model.load_state_dict(__a   ,					strict=__a   )







def        __lowerCamelCase (							__a       :int   ,					__a       :Union[str, Any]   ,					__a       :Optional[Any]   ,					__a       :bool = False   )		->    Optional[int]:






		"""simple docstring"""

		A__  				=       TaConfig.from_json_file(__a   )
		print(F'Building PyTorch model from configuration: {config}'   )
		# Non-v1.1 checkpoints could also use T5Model, but this works for all.
		# The v1.0 checkpoints will simply have an LM head that is the word embeddings.
		if is_encoder_only:
				A__  				=       TaEncoderModel(__a   )
		else:
				A__  				=       TaForConditionalGeneration(__a   )

		# Load weights from tf checkpoint
		load_tax_weights_in_ta(__a   ,					__a   ,					__a   ,					__a   )

		# Save pytorch-model
		print(F'Save PyTorch model to {pytorch_dump_path}'   )
		model.save_pretrained(__a   )

		# Verify that we can load the checkpoint.
		model.from_pretrained(__a   )
		print("""Done"""   )


if __name__ == "__main__":
					A   : Optional[int]			=				argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''')
					# Required parameters
					parser.add_argument(
					    '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.'''
					)
					parser.add_argument(
					    '''--config_file''',
					    default=None,
					    type=str,
					    required=True,
					    help='''The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.''',
					)
					parser.add_argument(
					    '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
					)
					parser.add_argument(
					    '''--is_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False
					)
					A   : List[Any]			=				parser.parse_args()
					convert_tax_checkpoint_to_pytorch(
					    args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only
					)










import os
import re
import shutil
import sys
import tempfile
import unittest

import black


A   : Dict			=				os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_copies  # noqa: E402


# This is the reference code that will be used in the tests.
# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated.
A   : Optional[int]			=				'''    def __init__(self, config):
        super().__init__()
        self.transform = BertPredictionHeadTransform(config)

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

        self.bias = nn.Parameter(torch.zeros(config.vocab_size))

        # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
        self.decoder.bias = self.bias

    def forward(self, hidden_states):
        hidden_states = self.transform(hidden_states)
        hidden_states = self.decoder(hidden_states)
        return hidden_states
'''


class   A      (unittest.TestCase   ):
			'''simple docstring'''




			def        a_	(      self       :   Union[str, Any]       )     ->     List[str]:







					"""simple docstring"""






					A__  				=       tempfile.mkdtemp()
					os.makedirs(os.path.join(self.transformer_dir							,     """models/bert/"""       )       )
					A__  				=       self.transformer_dir
					shutil.copy(
					    os.path.join(__lowerCAmelCase							,     """src/transformers/models/bert/modeling_bert.py"""       )							,     os.path.join(self.transformer_dir							,     """models/bert/modeling_bert.py"""       )							,     )






			def        a_	(      self       :   str       )     ->     Optional[int]:







					"""simple docstring"""






					A__  				=       """src/transformers"""
					shutil.rmtree(self.transformer_dir       )






			def        a_	(      self       :   List[str]							,     __lowerCAmelCase       :   List[Any]							,     __lowerCAmelCase       :   Optional[int]							,     __lowerCAmelCase       :   int							,     __lowerCAmelCase       :   Tuple=None       )     ->     Dict:







					"""simple docstring"""






					A__  				=       comment + f'\nclass {class_name}(nn.Module):\n' + class_code
					if overwrite_result is not None:
							A__  				=       comment + f'\nclass {class_name}(nn.Module):\n' + overwrite_result
					A__  				=       black.Mode(target_versions={black.TargetVersion.PYaa}							,     line_length=1_19       )
					A__  				=       black.format_str(__lowerCAmelCase							,     mode=__lowerCAmelCase       )
					A__  				=       os.path.join(self.transformer_dir							,     """new_code.py"""       )
					with open(__lowerCAmelCase							,     """w"""							,     newline="""\n"""       ) as f:
							f.write(__lowerCAmelCase       )
					if overwrite_result is None:
							self.assertTrue(len(check_copies.is_copy_consistent(__lowerCAmelCase       )       ) == 0       )
					else:
							check_copies.is_copy_consistent(f.name							,     overwrite=__lowerCAmelCase       )
							with open(__lowerCAmelCase							,     """r"""       ) as f:
									self.assertTrue(f.read()							,     __lowerCAmelCase       )






			def        a_	(      self       :   Tuple       )     ->     List[Any]:







					"""simple docstring"""






					A__  				=       check_copies.find_code_in_transformers("""models.bert.modeling_bert.BertLMPredictionHead"""       )
					self.assertEqual(__lowerCAmelCase							,     __lowerCAmelCase       )






			def        a_	(      self       :   Tuple       )     ->     Any:







					"""simple docstring"""






					self.check_copy_consistency(
					    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead"""							,     """BertLMPredictionHead"""							,     REFERENCE_CODE + """\n"""							,     )

					# With no empty line at the end
					self.check_copy_consistency(
					    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead"""							,     """BertLMPredictionHead"""							,     __lowerCAmelCase							,     )

					# Copy consistency with rename
					self.check_copy_consistency(
					    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel"""							,     """TestModelLMPredictionHead"""							,     re.sub("""Bert"""							,     """TestModel"""							,     __lowerCAmelCase       )							,     )

					# Copy consistency with a really long name
					A__  				=       """TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason"""
					self.check_copy_consistency(
					    f'# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}'							,     f'{long_class_name}LMPredictionHead'							,     re.sub("""Bert"""							,     __lowerCAmelCase							,     __lowerCAmelCase       )							,     )

					# Copy consistency with overwrite
					self.check_copy_consistency(
					    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel"""							,     """TestModelLMPredictionHead"""							,     __lowerCAmelCase							,     overwrite_result=re.sub("""Bert"""							,     """TestModel"""							,     __lowerCAmelCase       )							,     )







			def        a_	(      self       :   Optional[int]       )     ->     Optional[int]:







					"""simple docstring"""






					A__  				=       check_copies.LOCALIZED_READMES["""README_zh-hans.md"""]

					A__  				=       (
					    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"""
					    """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"""
					    """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"""
					    """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1."""
					    """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),"""
					    """ released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"""
					    """ lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same"""
					    """ method has been applied to compress GPT2 into"""
					    """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"""
					    """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"""
					    """ Multilingual BERT into"""
					    """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"""
					    """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**"""
					    """ (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders"""
					    """ as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang"""
					    """ Luong, Quoc V. Le, Christopher D. Manning."""
					)
					A__  				=       (
					    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"""
					    """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
					    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
					    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"""
					)
					A__  				=       (
					    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"""
					    """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
					    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
					    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1."""
					    """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文"""
					    """ [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"""
					    """ lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same"""
					    """ method has been applied to compress GPT2 into"""
					    """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"""
					    """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"""
					    """ Multilingual BERT into"""
					    """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"""
					    """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自"""
					    """ Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather"""
					    """ than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,"""
					    """ Christopher D. Manning 发布。\n"""
					)

					A__				,      A__  				=       check_copies.convert_to_localized_md(
					    __lowerCAmelCase							,     __lowerCAmelCase							,     localized_readme["""format_model_list"""]       )

					self.assertFalse(__lowerCAmelCase       )
					self.assertEqual(__lowerCAmelCase							,     __lowerCAmelCase       )

					A__				,      A__  				=       check_copies.convert_to_localized_md(
					    __lowerCAmelCase							,     __lowerCAmelCase							,     localized_readme["""format_model_list"""]       )

					# Check whether the number of models is equal to README.md after conversion.
					self.assertTrue(__lowerCAmelCase       )

					A__  				=       (
					    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"""
					    """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"""
					    """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"""
					    """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut."""
					)
					A__  				=       (
					    """1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and"""
					    """ the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
					    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
					    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"""
					)
					A__  				=       (
					    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"""
					    """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
					    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
					    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"""
					)

					A__				,      A__  				=       check_copies.convert_to_localized_md(
					    __lowerCAmelCase							,     __lowerCAmelCase							,     localized_readme["""format_model_list"""]       )

					# Check if the model link is synchronized.
					self.assertEqual(__lowerCAmelCase							,     __lowerCAmelCase       )



