




import argparse
import collections

import numpy as np
import torch
from flax import traverse_util
from tax import checkpoints

from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration
from transformers.utils import logging


logging.set_verbosity_info()




def 					__SCREAMING_SNAKE_CASE   (  lowercase_					,     lowercase_					,     lowercase_      )       ->	List[str]:

    """simple docstring"""


    return params[F"{prefix}/{prefix}/relpos_bias/rel_embedding"][:, i, :]




def 					__SCREAMING_SNAKE_CASE   (  lowercase_					,     lowercase_					,     lowercase_					,     lowercase_="attention"      )       ->	Optional[Any]:

    """simple docstring"""


    __UpperCamelCase  		=						__UpperCamelCase  		=						np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/key/kernel"][:, i, :, :]      )
    __UpperCamelCase  		=						k_tmp.reshape(k_tmp.shape[0]					,     k_tmp.shape[1] * k_tmp.shape[2]      )
    __UpperCamelCase  		=						np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/out/kernel"][:, i, :, :]      )
    __UpperCamelCase  		=						o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1]					,     o_tmp.shape[2]      )
    __UpperCamelCase  		=						np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/query/kernel"][:, i, :, :]      )
    __UpperCamelCase  		=						q_tmp.reshape(q_tmp.shape[0]					,     q_tmp.shape[1] * q_tmp.shape[2]      )
    __UpperCamelCase  		=						np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/value/kernel"][:, i, :, :]      )
    __UpperCamelCase  		=						v_tmp.reshape(v_tmp.shape[0]					,     v_tmp.shape[1] * v_tmp.shape[2]      )
    return k, o, q, v




def 					__SCREAMING_SNAKE_CASE   (  lowercase_					,     lowercase_					,     lowercase_					,     lowercase_=False      )       ->	Dict:

    """simple docstring"""


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

    __UpperCamelCase  		=						params[F"{prefix}/{prefix}/mlp/wo/kernel"][:, i, :]
    return wi, wo




def 					__SCREAMING_SNAKE_CASE   (  lowercase_					,     lowercase_					,     lowercase_					,     lowercase_      )       ->	int:

    """simple docstring"""


    return params[F"{prefix}/{prefix}/{layer_name}/scale"][:, i]




def 					__SCREAMING_SNAKE_CASE   (  lowercase_					,     *, lowercase_					,     lowercase_					,     lowercase_ = False      )       ->	Union[str, Any]:

    """simple docstring"""


    __UpperCamelCase  		=						traverse_util.flatten_dict(variables['''target''']      )
    __UpperCamelCase  		=						{'''/'''.join(lowercase_      ): v for k, v in old.items()}

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

    __UpperCamelCase  		=						collections.OrderedDict()

    # Shared embeddings.
    __UpperCamelCase  		=						old['''token_embedder/embedding''']

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

        # Block i, layer 1 (MLP).
        __UpperCamelCase  		=						tax_layer_norm_lookup(lowercase_					,     lowercase_					,     '''encoder'''					,     '''pre_mlp_layer_norm'''      )
        __UpperCamelCase		,      __UpperCamelCase  		=						tax_mlp_lookup(lowercase_					,     lowercase_					,     '''encoder'''					,     lowercase_      )
        __UpperCamelCase  		=						layer_norm
        if split_mlp_wi:
            __UpperCamelCase  		=						wi[0].T
            __UpperCamelCase  		=						wi[1].T
        else:
            __UpperCamelCase  		=						wi.T
        __UpperCamelCase  		=						wo.T
        if scalable_attention:
            # convert the rel_embedding of each layer
            __UpperCamelCase  		=						tax_relpos_bias_lookup(
                lowercase_					,     lowercase_					,     '''encoder'''      ).T

    __UpperCamelCase  		=						old['''encoder/encoder_norm/scale''']

    if not scalable_attention:
        __UpperCamelCase  		=						tax_relpos_bias_lookup(
            lowercase_					,     0					,     '''encoder'''      ).T
        __UpperCamelCase  		=						tax_relpos_bias_lookup(
            lowercase_					,     0					,     '''decoder'''      ).T

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

            # Block i, layer 1 (Cross Attention).
            __UpperCamelCase  		=						tax_layer_norm_lookup(lowercase_					,     lowercase_					,     '''decoder'''					,     '''pre_cross_attention_layer_norm'''      )
            __UpperCamelCase		,      __UpperCamelCase		,      __UpperCamelCase		,      __UpperCamelCase  		=						tax_attention_lookup(lowercase_					,     lowercase_					,     '''decoder'''					,     '''encoder_decoder_attention'''      )
            __UpperCamelCase  		=						layer_norm
            __UpperCamelCase  		=						k.T
            __UpperCamelCase  		=						o.T
            __UpperCamelCase  		=						q.T
            __UpperCamelCase  		=						v.T

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

            if scalable_attention:
                # convert the rel_embedding of each layer
                __UpperCamelCase  		=						tax_relpos_bias_lookup(lowercase_					,     lowercase_					,     '''decoder'''      ).T

        __UpperCamelCase  		=						old['''decoder/decoder_norm/scale''']

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

    return new




def 					__SCREAMING_SNAKE_CASE   (  lowercase_					,     lowercase_      )       ->	str:

    """simple docstring"""


    __UpperCamelCase  		=						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  		=						state_dict['''shared.weight''']

    if not is_encoder_only:
        if "decoder.embed_tokens.weight" not in state_dict:
            __UpperCamelCase  		=						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  		=						state_dict['''shared.weight''']

    return state_dict




def 					__SCREAMING_SNAKE_CASE   (  lowercase_					,     lowercase_					,     lowercase_					,     lowercase_					,     lowercase_      )       ->	Dict:

    """simple docstring"""


    __UpperCamelCase  		=						checkpoints.load_tax_checkpoint(lowercase_      )
    __UpperCamelCase  		=						convert_tax_to_pytorch(
        lowercase_					,     num_layers=config.num_layers					,     is_encoder_only=lowercase_					,     scalable_attention=lowercase_      )
    __UpperCamelCase  		=						make_state_dict(lowercase_					,     lowercase_      )
    model.load_state_dict(lowercase_					,     strict=lowercase_      )




def 					__SCREAMING_SNAKE_CASE   (  lowercase_					,     lowercase_					,     lowercase_					,     lowercase_ = False					,     lowercase_ = False					,     )       ->	List[str]:

    """simple docstring"""


    __UpperCamelCase  		=						MTaConfig.from_json_file(lowercase_      )
    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  		=						UMTaEncoderModel(lowercase_      )
    else:
        __UpperCamelCase  		=						UMTaForConditionalGeneration(lowercase_      )

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

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

    # Verify that we can load the checkpoint.
    model.from_pretrained(lowercase_      )
    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
 )
 parser.add_argument(
     "--scalable_attention",
     action="store_true",
     help="Whether the model uses scaled attention (umt5 model)",
     default=False,
 )
 a_     :   Tuple   		=     parser.parse_args()
 convert_tax_checkpoint_to_pytorch(
     args.tax_checkpoint_path,
     args.config_file,
     args.pytorch_dump_path,
     args.is_encoder_only,
     args.scalable_attention,
 )












import gc
import unittest

from transformers import CTRLConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import (
     CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
     CTRLForSequenceClassification,
     CTRLLMHeadModel,
     CTRLModel,
 )

class  _lowerCamelCase						:

      """simple docstring"""

      def __init__(     self					: str ,       snake_case					: Any ,       snake_case					: str=14 ,       snake_case					: Dict=7 ,       snake_case					: Any=True ,       snake_case					: Any=True ,       snake_case					: str=True ,       snake_case					: List[str]=True ,       snake_case					: int=True ,       snake_case					: List[Any]=99 ,       snake_case					: Optional[int]=32 ,       snake_case					: str=5 ,       snake_case					: int=4 ,       snake_case					: str=37 ,       snake_case					: Union[str, Any]="gelu" ,       snake_case					: List[str]=0.1 ,       snake_case					: Optional[int]=0.1 ,       snake_case					: Tuple=512 ,       snake_case					: int=16 ,       snake_case					: Any=2 ,       snake_case					: List[str]=0.02 ,       snake_case					: List[Any]=3 ,       snake_case					: str=4 ,       snake_case					: Tuple=None ,       ):
          __UpperCamelCase  		=						parent
          __UpperCamelCase  		=						batch_size
          __UpperCamelCase  		=						seq_length
          __UpperCamelCase  		=						is_training
          __UpperCamelCase  		=						use_token_type_ids
          __UpperCamelCase  		=						use_input_mask
          __UpperCamelCase  		=						use_labels
          __UpperCamelCase  		=						use_mc_token_ids
          __UpperCamelCase  		=						vocab_size
          __UpperCamelCase  		=						hidden_size
          __UpperCamelCase  		=						num_hidden_layers
          __UpperCamelCase  		=						num_attention_heads
          __UpperCamelCase  		=						intermediate_size
          __UpperCamelCase  		=						hidden_act
          __UpperCamelCase  		=						hidden_dropout_prob
          __UpperCamelCase  		=						attention_probs_dropout_prob
          __UpperCamelCase  		=						max_position_embeddings
          __UpperCamelCase  		=						type_vocab_size
          __UpperCamelCase  		=						type_sequence_label_size
          __UpperCamelCase  		=						initializer_range
          __UpperCamelCase  		=						num_labels
          __UpperCamelCase  		=						num_choices
          __UpperCamelCase  		=						scope
          __UpperCamelCase  		=						self.vocab_size - 1







      def       snake_case	(     self					: Optional[Any]				):
          __UpperCamelCase  		=						ids_tensor([self.batch_size, self.seq_length] ,       self.vocab_size				)

          __UpperCamelCase  		=						None
          if self.use_input_mask:
              __UpperCamelCase  		=						random_attention_mask([self.batch_size, self.seq_length]				)

          __UpperCamelCase  		=						None
          if self.use_token_type_ids:
              __UpperCamelCase  		=						ids_tensor([self.batch_size, self.seq_length] ,       self.type_vocab_size				)

          __UpperCamelCase  		=						None
          if self.use_mc_token_ids:
              __UpperCamelCase  		=						ids_tensor([self.batch_size, self.num_choices] ,       self.seq_length				)

          __UpperCamelCase  		=						None
          __UpperCamelCase  		=						None
          __UpperCamelCase  		=						None
          if self.use_labels:
              __UpperCamelCase  		=						ids_tensor([self.batch_size] ,       self.type_sequence_label_size				)
              __UpperCamelCase  		=						ids_tensor([self.batch_size, self.seq_length] ,       self.num_labels				)
              __UpperCamelCase  		=						ids_tensor([self.batch_size] ,       self.num_choices				)

          __UpperCamelCase  		=						self.get_config()

          __UpperCamelCase  		=						ids_tensor([self.num_hidden_layers, self.num_attention_heads] ,       2				)

          return (
              config,
              input_ids,
              input_mask,
              head_mask,
              token_type_ids,
              mc_token_ids,
              sequence_labels,
              token_labels,
              choice_labels,
          )







      def       snake_case	(     self					: Optional[int]				):
          return CTRLConfig(
              vocab_size=self.vocab_size ,       n_embd=self.hidden_size ,       n_layer=self.num_hidden_layers ,       n_head=self.num_attention_heads ,       n_positions=self.max_position_embeddings ,       pad_token_id=self.pad_token_id ,       )







      def       snake_case	(     self					: Any ,       snake_case					: Optional[int] ,       snake_case					: Any ,       snake_case					: Union[str, Any] ,       snake_case					: Dict ,       snake_case					: List[Any] ,       *snake_case					: Union[str, Any]				):
          __UpperCamelCase  		=						CTRLModel(config=snake_case				)
          model.to(snake_case				)
          model.eval()

          model(snake_case ,       token_type_ids=snake_case ,       head_mask=snake_case				)
          model(snake_case ,       token_type_ids=snake_case				)
          __UpperCamelCase  		=						model(snake_case				)
          self.parent.assertEqual(result.last_hidden_state.shape ,       (self.batch_size, self.seq_length, self.hidden_size)				)
          self.parent.assertEqual(len(result.past_key_values				) ,       config.n_layer				)







      def       snake_case	(     self					: Any ,       snake_case					: Tuple ,       snake_case					: Tuple ,       snake_case					: Union[str, Any] ,       snake_case					: Dict ,       snake_case					: List[str] ,       *snake_case					: Union[str, Any]				):
          __UpperCamelCase  		=						CTRLLMHeadModel(snake_case				)
          model.to(snake_case				)
          model.eval()

          __UpperCamelCase  		=						model(snake_case ,       token_type_ids=snake_case ,       labels=snake_case				)
          self.parent.assertEqual(result.loss.shape ,       ()				)
          self.parent.assertEqual(result.logits.shape ,       (self.batch_size, self.seq_length, self.vocab_size)				)







      def       snake_case	(     self					: Any				):
          __UpperCamelCase  		=						self.prepare_config_and_inputs()

          (
              (
              __UpperCamelCase
          )		,      (
              __UpperCamelCase
          )		,      (
              __UpperCamelCase
          )		,      (
              __UpperCamelCase
          )		,      (
              __UpperCamelCase
          )		,      (
              __UpperCamelCase
          )		,      (
              __UpperCamelCase
          )		,      (
              __UpperCamelCase
          )		,      (
              __UpperCamelCase
          )		,      
          )  		=						config_and_inputs

          __UpperCamelCase  		=						{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask}

          return config, inputs_dict







      def       snake_case	(     self					: List[Any] ,       snake_case					: int ,       snake_case					: Dict ,       snake_case					: Optional[Any] ,       snake_case					: Any ,       *snake_case					: str				):
          __UpperCamelCase  		=						self.num_labels
          __UpperCamelCase  		=						CTRLForSequenceClassification(snake_case				)
          model.to(snake_case				)
          model.eval()
          __UpperCamelCase  		=						ids_tensor([self.batch_size] ,       self.type_sequence_label_size				)
          __UpperCamelCase  		=						model(snake_case ,       token_type_ids=snake_case ,       labels=snake_case				)
          self.parent.assertEqual(result.logits.shape ,       (self.batch_size, self.num_labels)				)







@require_torch
class  _lowerCamelCase						(			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			_SCREAMING_SNAKE_CASE							,			unittest.TestCase   ):

      """simple docstring"""

      lowerCAmelCase__			: int    =					(CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
      lowerCAmelCase__			: List[str]    =					(CTRLLMHeadModel,) if is_torch_available() else ()
      lowerCAmelCase__			: str    =					(
          {
              "feature-extraction": CTRLModel,
              "text-classification": CTRLForSequenceClassification,
              "text-generation": CTRLLMHeadModel,
              "zero-shot": CTRLForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      lowerCAmelCase__			: Dict    =					True
      lowerCAmelCase__			: List[Any]    =					False
      lowerCAmelCase__			: str    =					False







      def       snake_case	(     self					: str ,       snake_case					: Optional[int] ,       snake_case					: List[str] ,       snake_case					: Tuple ,       snake_case					: Dict ,       snake_case					: List[str]				):
          if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
              # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
              # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
              # config could not be created.
              return True

          return False







      def       snake_case	(     self					: Optional[int]				):
          __UpperCamelCase  		=						CTRLModelTester(self				)
          __UpperCamelCase  		=						ConfigTester(self ,       config_class=snake_case ,       n_embd=37				)







      def       snake_case	(     self					: Union[str, Any]				):
          super().tearDown()
          # clean-up as much as possible GPU memory occupied by PyTorch
          gc.collect()
          torch.cuda.empty_cache()







      def       snake_case	(     self					: Dict				):
          self.config_tester.run_common_tests()







      def       snake_case	(     self					: Optional[int]				):
          __UpperCamelCase  		=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_ctrl_model(*snake_case				)







      def       snake_case	(     self					: Tuple				):
          __UpperCamelCase  		=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_lm_head_model(*snake_case				)







      @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''				)
      def       snake_case	(     self					: List[Any]				):
          pass







      @slow
      def       snake_case	(     self					: Optional[Any]				):
          for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __UpperCamelCase  		=						CTRLModel.from_pretrained(snake_case				)
              self.assertIsNotNone(snake_case				)







      @unittest.skip('''The model doesn\'t support left padding'''				)  # and it's not used enough to be worth fixing :)
      def       snake_case	(     self					: List[Any]				):
          pass







@require_torch
class  _lowerCamelCase						(			unittest.TestCase   ):

      """simple docstring"""

      def       snake_case	(     self					: int				):
          super().tearDown()
          # clean-up as much as possible GPU memory occupied by PyTorch
          gc.collect()
          torch.cuda.empty_cache()







      @slow
      def       snake_case	(     self					: Optional[int]				):
          __UpperCamelCase  		=						CTRLLMHeadModel.from_pretrained('''ctrl'''				)
          model.to(snake_case				)
          __UpperCamelCase  		=						torch.tensor(
              [[11859, 0, 1611, 8]] ,       dtype=torch.long ,       device=snake_case				)  # Legal the president is
          __UpperCamelCase  		=						[
              11859,
              0,
              1611,
              8,
              5,
              150,
              26449,
              2,
              19,
              348,
              469,
              3,
              2595,
              48,
              20740,
              246533,
              246533,
              19,
              30,
              5,
          ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

          __UpperCamelCase  		=						model.generate(snake_case ,       do_sample=snake_case				)
          self.assertListEqual(output_ids[0].tolist() ,       snake_case				)






