


import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
     from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
     from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
def 				__lowerCamelCase						( UpperCAmelCase_						:		Union[str, Any]						):




      """simple docstring"""





      return 1.0 / (1.0 + np.exp(-_outputs						))
def 				__lowerCamelCase						( UpperCAmelCase_						:		Tuple						):




      """simple docstring"""





      a						:str 							=       np.max(_outputs ,  axis=-1 ,  keepdims=UpperCAmelCase_						)
      a						:Optional[int] 							=       np.exp(_outputs - maxes						)
      return shifted_exp / shifted_exp.sum(axis=-1 ,  keepdims=UpperCAmelCase_						)







class 		_snake_case  (      _snake_case							):
 SCREAMING_SNAKE_CASE__      =       'sigmoid'
 SCREAMING_SNAKE_CASE__      =       'softmax'
 SCREAMING_SNAKE_CASE__      =       'none'







@add_end_docstrings(
    _snake_case						,    r'\n        return_all_scores (`bool`, *optional*, defaults to `False`):\n            Whether to return all prediction scores or just the one of the predicted class.\n        function_to_apply (`str`, *optional*, defaults to `"default"`):\n            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n              has several labels, will apply the softmax function on the output.\n            - `"sigmoid"`: Applies the sigmoid function on the output.\n            - `"softmax"`: Applies the softmax function on the output.\n            - `"none"`: Does not apply any function on the output.\n    '						,    )
class 		_snake_case  (      _snake_case							):
 SCREAMING_SNAKE_CASE__      =       False
 SCREAMING_SNAKE_CASE__      =       ClassificationFunction.NONE




 def __init__(		self					,  **_lowerCamelCase    ):
       super().__init__(**_lowerCamelCase    )

       self.check_model_type(
           TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
           if self.framework == '''tf'''
           else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING    )




 def        SCREAMING_SNAKE_CASE__				(		self					,  _lowerCamelCase=None					,  _lowerCamelCase=None					,  _lowerCamelCase=""					,  **_lowerCamelCase    ):
       # Using "" as default argument because we're going to use `top_k=None` in user code to declare
       # "No top_k"
       a						:int 							=       tokenizer_kwargs

       a						:Optional[int] 							=       {}
       if hasattr(self.model.config					,  '''return_all_scores'''    ) and return_all_scores is None:
             a						:List[Any] 							=       self.model.config.return_all_scores

       if isinstance(_lowerCamelCase					,  _lowerCamelCase    ) or top_k is None:
             a						:List[str] 							=       top_k
             a						:int 							=       False
       elif return_all_scores is not None:
             warnings.warn(
                 '''`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'''
                 ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'''					,  _lowerCamelCase					,  )
             if return_all_scores:
                   a						:int 							=       None
             else:
                   a						:Optional[Any] 							=       1

       if isinstance(_lowerCamelCase					,  _lowerCamelCase    ):
             a						:Any 							=       ClassificationFunction[function_to_apply.upper()]

       if function_to_apply is not None:
             a						:Dict 							=       function_to_apply
       return preprocess_params, {}, postprocess_params




 def __call__(		self					,  *_lowerCamelCase					,  **_lowerCamelCase    ):
       a						:str 							=       super().__call__(*_lowerCamelCase					,  **_lowerCamelCase    )
       # TODO try and retrieve it in a nicer way from _sanitize_parameters.
       a						:Union[str, Any] 							=       '''top_k''' not in kwargs
       if isinstance(args[0]					,  _lowerCamelCase    ) and _legacy:
             # This pipeline is odd, and return a list when single item is run
             return [result]
       else:
             return result




 def        SCREAMING_SNAKE_CASE__				(		self					,  _lowerCamelCase					,  **_lowerCamelCase    ):
       a						:Optional[Any] 							=       self.framework
       if isinstance(_lowerCamelCase					,  _lowerCamelCase    ):
             return self.tokenizer(**_lowerCamelCase					,  return_tensors=_lowerCamelCase					,  **_lowerCamelCase    )
       elif isinstance(_lowerCamelCase					,  _lowerCamelCase    ) and len(_lowerCamelCase    ) == 1 and isinstance(inputs[0]					,  _lowerCamelCase    ) and len(inputs[0]    ) == 2:
             # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
             return self.tokenizer(
                 text=inputs[0][0]					,  text_pair=inputs[0][1]					,  return_tensors=_lowerCamelCase					,  **_lowerCamelCase    )
       elif isinstance(_lowerCamelCase					,  _lowerCamelCase    ):
             # This is likely an invalid usage of the pipeline attempting to pass text pairs.
             raise ValueError(
                 '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'''
                 ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'''    )
       return self.tokenizer(_lowerCamelCase					,  return_tensors=_lowerCamelCase					,  **_lowerCamelCase    )




 def        SCREAMING_SNAKE_CASE__				(		self					,  _lowerCamelCase    ):
       return self.model(**_lowerCamelCase    )




 def        SCREAMING_SNAKE_CASE__				(		self					,  _lowerCamelCase					,  _lowerCamelCase=None					,  _lowerCamelCase=1					,  _lowerCamelCase=True    ):
       # `_legacy` is used to determine if we're running the naked pipeline and in backward
       # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
       # the more natural result containing the list.
       # Default value before `set_parameters`
       if function_to_apply is None:
             if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
                   a						:Optional[int] 							=       ClassificationFunction.SIGMOID
             elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
                   a						:Tuple 							=       ClassificationFunction.SOFTMAX
             elif hasattr(self.model.config					,  '''function_to_apply'''    ) and function_to_apply is None:
                   a						:List[Any] 							=       self.model.config.function_to_apply
             else:
                   a						:Any 							=       ClassificationFunction.NONE

       a						:List[Any] 							=       model_outputs['''logits'''][0]
       a						:Dict 							=       outputs.numpy()

       if function_to_apply == ClassificationFunction.SIGMOID:
             a						:List[Any] 							=       sigmoid(_lowerCamelCase    )
       elif function_to_apply == ClassificationFunction.SOFTMAX:
             a						:Optional[Any] 							=       softmax(_lowerCamelCase    )
       elif function_to_apply == ClassificationFunction.NONE:
             a						:List[str] 							=       outputs
       else:
             raise ValueError(F'''Unrecognized `function_to_apply` argument: {function_to_apply}'''    )

       if top_k == 1 and _legacy:
             return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

       a						:List[str] 							=       [
           {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(_lowerCamelCase    )
       ]
       if not _legacy:
             dict_scores.sort(key=lambda _lowerCamelCase    : x["score"]					,  reverse=_lowerCamelCase    )
             if top_k is not None:
                   a						:Any 							=       dict_scores[:top_k]
       return dict_scores









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_						:		Union[str, Any] ,  UpperCAmelCase_						:		int ,  UpperCAmelCase_						:		Optional[Any] ,  UpperCAmelCase_						:		Union[str, Any]="attention"						):




      """simple docstring"""





      a						:Optional[int] 							=       params[F'''{prefix}/layers_{i}/{layer_name}/key/kernel''']
      a						:Optional[Any] 							=       params[F'''{prefix}/layers_{i}/{layer_name}/out/kernel''']
      a						:int 							=       params[F'''{prefix}/layers_{i}/{layer_name}/query/kernel''']
      a						:Optional[Any] 							=       params[F'''{prefix}/layers_{i}/{layer_name}/value/kernel''']
      return k, o, q, v
def 				__lowerCamelCase						( UpperCAmelCase_						:		Optional[int] ,  UpperCAmelCase_						:		str ,  UpperCAmelCase_						:		List[str] ,  UpperCAmelCase_						:		int=False						):




      """simple docstring"""





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

      a						:Dict 							=       params[F'''{prefix}/layers_{i}/mlp/wo/kernel''']
      return wi, wo
def 				__lowerCamelCase						( UpperCAmelCase_						:		str ,  UpperCAmelCase_						:		int ,  UpperCAmelCase_						:		List[str] ,  UpperCAmelCase_						:		Optional[int]						):




      """simple docstring"""





      return params[F'''{prefix}/layers_{i}/{layer_name}/scale''']
def 				__lowerCamelCase						( UpperCAmelCase_						:		dict ,  *, UpperCAmelCase_						:		int ,  UpperCAmelCase_						:		bool						):




      """simple docstring"""





      a						:str 							=       traverse_util.flatten_dict(variables['''target''']						)
      a						:Any 							=       {'''/'''.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
      a						:Any 							=       '''encoder/layers_0/mlp/wi_0/kernel''' in old
      print('''Split MLP:''' ,  UpperCAmelCase_						)

      a						:Optional[Any] 							=       collections.OrderedDict()

      # Shared embeddings.
      a						:Union[str, Any] 							=       old['''token_embedder/embedding''']

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

            # Block i, layer 1 (MLP).
            a						:Tuple 							=       tax_layer_norm_lookup(UpperCAmelCase_ ,  UpperCAmelCase_ ,  '''encoder''' ,  '''pre_mlp_layer_norm'''						)
            a							,				a						:List[Any] 							=       tax_mlp_lookup(UpperCAmelCase_ ,  UpperCAmelCase_ ,  '''encoder''' ,  UpperCAmelCase_						)
            a						:Any 							=       layer_norm
            if split_mlp_wi:
                  a						:Any 							=       wi[0].T
                  a						:Tuple 							=       wi[1].T
            else:
                  a						:List[str] 							=       wi.T
            a						:List[Any] 							=       wo.T

      a						:Union[str, Any] 							=       old[
          '''encoder/relpos_bias/rel_embedding'''
      ].T
      a						:Optional[Any] 							=       old['''encoder/encoder_norm/scale''']

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

                  # Block i, layer 1 (Cross Attention).
                  a						:str 							=       tax_layer_norm_lookup(UpperCAmelCase_ ,  UpperCAmelCase_ ,  '''decoder''' ,  '''pre_cross_attention_layer_norm'''						)
                  a							,				a							,				a							,				a						:Any 							=       tax_attention_lookup(UpperCAmelCase_ ,  UpperCAmelCase_ ,  '''decoder''' ,  '''encoder_decoder_attention'''						)
                  a						:str 							=       layer_norm
                  a						:Optional[Any] 							=       k.T
                  a						:Any 							=       o.T
                  a						:Dict 							=       q.T
                  a						:Optional[Any] 							=       v.T

                  # Block i, layer 2 (MLP).
                  a						:Optional[int] 							=       tax_layer_norm_lookup(UpperCAmelCase_ ,  UpperCAmelCase_ ,  '''decoder''' ,  '''pre_mlp_layer_norm'''						)
                  a							,				a						:List[Any] 							=       tax_mlp_lookup(UpperCAmelCase_ ,  UpperCAmelCase_ ,  '''decoder''' ,  UpperCAmelCase_						)
                  a						:Optional[int] 							=       layer_norm
                  if split_mlp_wi:
                        a						:int 							=       wi[0].T
                        a						:Tuple 							=       wi[1].T
                  else:
                        a						:str 							=       wi.T
                  a						:Dict 							=       wo.T

            a						:Any 							=       old['''decoder/decoder_norm/scale''']
            a						:Optional[Any] 							=       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						:Union[str, Any] 							=       old['''decoder/logits_dense/kernel'''].T

      return new
def 				__lowerCamelCase						( UpperCAmelCase_						:		Any ,  UpperCAmelCase_						:		bool						):




      """simple docstring"""





      a						:List[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:
            a						:Optional[Any] 							=       state_dict['''shared.weight''']

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

      return state_dict
def 				__lowerCamelCase						( UpperCAmelCase_						:		Any ,  UpperCAmelCase_						:		Union[str, Any] ,  UpperCAmelCase_						:		Optional[int] ,  UpperCAmelCase_						:		Optional[int]						):




      """simple docstring"""





      a						:Tuple 							=       checkpoints.load_tax_checkpoint(UpperCAmelCase_						)
      a						:Optional[int] 							=       convert_tax_to_pytorch(UpperCAmelCase_ ,  num_layers=config.num_layers ,  is_encoder_only=UpperCAmelCase_						)
      a						:Tuple 							=       make_state_dict(UpperCAmelCase_ ,  UpperCAmelCase_						)
      model.load_state_dict(UpperCAmelCase_ ,  strict=UpperCAmelCase_						)
def 				__lowerCamelCase						( UpperCAmelCase_						:		int ,  UpperCAmelCase_						:		Optional[Any] ,  UpperCAmelCase_						:		str ,  UpperCAmelCase_						:		bool = False						):




      """simple docstring"""





      a						:List[Any] 							=       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:
            a						:Any 							=       TaEncoderModel(UpperCAmelCase_						)
      else:
            a						:List[str] 							=       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__":
     snake_case				:    Any       				=     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
     )
     snake_case				:    Optional[Any]       				=     parser.parse_args()
     convert_tax_checkpoint_to_pytorch(
         args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only
     )





