

"""simple docstring"""




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    (       __UpperCamelCase				,     __UpperCamelCase				,     __UpperCamelCase				,     __UpperCamelCase="attention"   ):
 '''simple docstring'''





 UpperCAmelCase__       :	Any        =       params[F"{prefix}/layers_{i}/{layer_name}/key/kernel"]
 UpperCAmelCase__       :	Union[str, Any]        =       params[F"{prefix}/layers_{i}/{layer_name}/out/kernel"]
 UpperCAmelCase__       :	Any        =       params[F"{prefix}/layers_{i}/{layer_name}/query/kernel"]
 UpperCAmelCase__       :	List[str]        =       params[F"{prefix}/layers_{i}/{layer_name}/value/kernel"]
 return k, o, q, v
def 	lowerCAmelCase    (       __UpperCamelCase				,     __UpperCamelCase				,     __UpperCamelCase				,     __UpperCamelCase=False   ):
 '''simple docstring'''





 if split_mlp_wi:
  UpperCAmelCase__       :	str        =       params[F"{prefix}/layers_{i}/mlp/wi_0/kernel"]
  UpperCAmelCase__       :	Any        =       params[F"{prefix}/layers_{i}/mlp/wi_1/kernel"]
  UpperCAmelCase__       :	Tuple        =       (wi_a, wi_a)
 else:
  UpperCAmelCase__       :	Optional[Any]        =       params[F"{prefix}/layers_{i}/mlp/wi/kernel"]

 UpperCAmelCase__       :	Union[str, Any]        =       params[F"{prefix}/layers_{i}/mlp/wo/kernel"]
 return wi, wo
def 	lowerCAmelCase    (       __UpperCamelCase				,     __UpperCamelCase				,     __UpperCamelCase				,     __UpperCamelCase   ):
 '''simple docstring'''





 return params[F"{prefix}/layers_{i}/{layer_name}/scale"]
def 	lowerCAmelCase    (       __UpperCamelCase				,     *, __UpperCamelCase				,     __UpperCamelCase   ):
 '''simple docstring'''





 UpperCAmelCase__       :	List[str]        =       traverse_util.flatten_dict(variables["""target"""]   )
 UpperCAmelCase__       :	Dict        =       {"""/""".join(__UpperCamelCase   ): v for k, v in old.items()}

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

 UpperCAmelCase__       :	Union[str, Any]        =       collections.OrderedDict()

 # Shared embeddings.
 UpperCAmelCase__       :	Optional[Any]        =       old["""token_embedder/embedding"""]

 # Encoder.
 for i in range(__UpperCamelCase   ):
  # Block i, layer 0 (Self Attention).
  UpperCAmelCase__       :	int        =       tax_layer_norm_lookup(__UpperCamelCase				,     __UpperCamelCase				,     """encoder"""				,     """pre_attention_layer_norm"""   )
  UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__       :	List[Any]        =       tax_attention_lookup(__UpperCamelCase				,     __UpperCamelCase				,     """encoder"""				,     """attention"""   )
  UpperCAmelCase__       :	Tuple        =       layer_norm
  UpperCAmelCase__       :	int        =       k.T
  UpperCAmelCase__       :	Optional[int]        =       o.T
  UpperCAmelCase__       :	str        =       q.T
  UpperCAmelCase__       :	Optional[int]        =       v.T

  # Block i, layer 1 (MLP).
  UpperCAmelCase__       :	List[str]        =       tax_layer_norm_lookup(__UpperCamelCase				,     __UpperCamelCase				,     """encoder"""				,     """pre_mlp_layer_norm"""   )
  UpperCAmelCase__ ,   UpperCAmelCase__       :	List[Any]        =       tax_mlp_lookup(__UpperCamelCase				,     __UpperCamelCase				,     """encoder"""				,     __UpperCamelCase   )
  UpperCAmelCase__       :	Dict        =       layer_norm
  if split_mlp_wi:
   UpperCAmelCase__       :	Optional[int]        =       wi[0].T
   UpperCAmelCase__       :	List[str]        =       wi[1].T
  else:
   UpperCAmelCase__       :	Any        =       wi.T
  UpperCAmelCase__       :	List[Any]        =       wo.T

 UpperCAmelCase__       :	Optional[int]        =       old[
     """encoder/relpos_bias/rel_embedding"""
 ].T
 UpperCAmelCase__       :	List[str]        =       old["""encoder/encoder_norm/scale"""]

 if not is_encoder_only:
  # Decoder.
  for i in range(__UpperCamelCase   ):
   # Block i, layer 0 (Self Attention).
   UpperCAmelCase__       :	Tuple        =       tax_layer_norm_lookup(__UpperCamelCase				,     __UpperCamelCase				,     """decoder"""				,     """pre_self_attention_layer_norm"""   )
   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__       :	Any        =       tax_attention_lookup(__UpperCamelCase				,     __UpperCamelCase				,     """decoder"""				,     """self_attention"""   )
   UpperCAmelCase__       :	str        =       layer_norm
   UpperCAmelCase__       :	Union[str, Any]        =       k.T
   UpperCAmelCase__       :	List[str]        =       o.T
   UpperCAmelCase__       :	int        =       q.T
   UpperCAmelCase__       :	Dict        =       v.T

   # Block i, layer 1 (Cross Attention).
   UpperCAmelCase__       :	Optional[Any]        =       tax_layer_norm_lookup(__UpperCamelCase				,     __UpperCamelCase				,     """decoder"""				,     """pre_cross_attention_layer_norm"""   )
   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__       :	List[str]        =       tax_attention_lookup(__UpperCamelCase				,     __UpperCamelCase				,     """decoder"""				,     """encoder_decoder_attention"""   )
   UpperCAmelCase__       :	List[Any]        =       layer_norm
   UpperCAmelCase__       :	str        =       k.T
   UpperCAmelCase__       :	Optional[Any]        =       o.T
   UpperCAmelCase__       :	Any        =       q.T
   UpperCAmelCase__       :	Union[str, Any]        =       v.T

   # Block i, layer 2 (MLP).
   UpperCAmelCase__       :	int        =       tax_layer_norm_lookup(__UpperCamelCase				,     __UpperCamelCase				,     """decoder"""				,     """pre_mlp_layer_norm"""   )
   UpperCAmelCase__ ,   UpperCAmelCase__       :	Tuple        =       tax_mlp_lookup(__UpperCamelCase				,     __UpperCamelCase				,     """decoder"""				,     __UpperCamelCase   )
   UpperCAmelCase__       :	Tuple        =       layer_norm
   if split_mlp_wi:
    UpperCAmelCase__       :	Any        =       wi[0].T
    UpperCAmelCase__       :	Optional[Any]        =       wi[1].T
   else:
    UpperCAmelCase__       :	Tuple        =       wi.T
   UpperCAmelCase__       :	int        =       wo.T

  UpperCAmelCase__       :	int        =       old["""decoder/decoder_norm/scale"""]
  UpperCAmelCase__       :	Dict        =       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:
   UpperCAmelCase__       :	int        =       old["""decoder/logits_dense/kernel"""].T

 return new
def 	lowerCAmelCase    (       __UpperCamelCase				,     __UpperCamelCase   ):
 '''simple docstring'''





 UpperCAmelCase__       :	Optional[Any]        =       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:
  UpperCAmelCase__       :	Tuple        =       state_dict["""shared.weight"""]

 if not is_encoder_only:
  if "decoder.embed_tokens.weight" not in state_dict:
   UpperCAmelCase__       :	List[Any]        =       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."""   )
   UpperCAmelCase__       :	List[Any]        =       state_dict["""shared.weight"""]

 return state_dict
def 	lowerCAmelCase    (       __UpperCamelCase				,     __UpperCamelCase				,     __UpperCamelCase				,     __UpperCamelCase   ):
 '''simple docstring'''





 UpperCAmelCase__       :	List[str]        =       checkpoints.load_tax_checkpoint(__UpperCamelCase   )
 UpperCAmelCase__       :	str        =       convert_tax_to_pytorch(__UpperCamelCase				,     num_layers=config.num_layers				,     is_encoder_only=__UpperCamelCase   )
 UpperCAmelCase__       :	int        =       make_state_dict(__UpperCamelCase				,     __UpperCamelCase   )
 model.load_state_dict(__UpperCamelCase				,     strict=__UpperCamelCase   )
def 	lowerCAmelCase    (       __UpperCamelCase				,     __UpperCamelCase				,     __UpperCamelCase				,     __UpperCamelCase = False   ):
 '''simple docstring'''





 UpperCAmelCase__       :	List[str]        =       TaConfig.from_json_file(__UpperCamelCase   )
 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:
  UpperCAmelCase__       :	int        =       TaEncoderModel(__UpperCamelCase   )
 else:
  UpperCAmelCase__       :	List[Any]        =       TaForConditionalGeneration(__UpperCamelCase   )

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

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

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


if __name__ == "__main__":
      __UpperCAmelCase			=					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
      )
      __UpperCAmelCase			=					parser.parse_args()
      convert_tax_checkpoint_to_pytorch(
          args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only
      )










"""simple docstring"""







def     UpperCAmelCase_					(				__a   :			int						):




			'''simple docstring'''



			_lowerCamelCase					:					Optional[Any]	       =    int(__a						)
			if decimal in (0, 1):  # Exit cases for the recursion
						return str(__a						)
			_lowerCamelCase       ,							_lowerCamelCase					:					Union[str, Any]	       =    divmod(__a      ,							2						)
			return binary_recursive(__a						) + str(__a						)

def     UpperCAmelCase_					(				__a   :			str						):




			'''simple docstring'''



			_lowerCamelCase					:					int	       =    str(__a						).strip()
			if not number:
						raise ValueError('No input value was provided'						)
			_lowerCamelCase					:					Tuple	       =    '-' if number.startswith('-'						) else ''
			_lowerCamelCase					:					List[Any]	       =    number.lstrip('-'						)
			if not number.isnumeric():
						raise ValueError('Input value is not an integer'						)
			return f"{negative}0b{binary_recursive(int(__a						)						)}"


if __name__ == "__main__":
	from doctest import testmod

	testmod()





