




from ...configuration_utils import PretrainedConfig
from ...utils import logging


__UpperCamelCase					:       Optional[int]    					=      logging.get_logger(__name__)

__UpperCamelCase					:       Tuple    					=      {
    "google/switch-base-8": "https://huggingface.co/google/switch-base-8/blob/main/config.json",
}

class 		__lowerCAmelCase	(	__magic_name__ ):
							UpperCamelCase__					     =  """switch_transformers"""
							UpperCamelCase__					     =  ["""past_key_values"""]
							UpperCamelCase__					     =  {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""}
							def __init__(						self						:Optional[int]		,      __magic_name__						:str=3_2128		,      __magic_name__						:List[Any]=768		,      __magic_name__						:Optional[Any]=64		,      __magic_name__						:Tuple=2048		,      __magic_name__						:Dict=64		,      __magic_name__						:Tuple=12		,      __magic_name__						:Optional[int]=3		,      __magic_name__						:int=12		,      __magic_name__						:str=3		,      __magic_name__						:List[Any]=12		,      __magic_name__						:Tuple=8		,      __magic_name__						:Tuple=False		,      __magic_name__						:int=0.01		,      __magic_name__						:Dict="float32"		,      __magic_name__						:int=False		,      __magic_name__						:Tuple=32		,      __magic_name__						:Any=128		,      __magic_name__						:Tuple=0.1		,      __magic_name__						:Optional[int]=1E-6		,      __magic_name__						:List[str]=0.001		,      __magic_name__						:int=0.001		,      __magic_name__						:List[Any]=1.0		,      __magic_name__						:Tuple="relu"		,      __magic_name__						:List[str]=True		,      __magic_name__						:Optional[Any]=False		,      __magic_name__						:int=True		,      __magic_name__						:List[str]=0		,      __magic_name__						:Dict=1		,      **__magic_name__						:Optional[Any]		,      ):







								'''simple docstring'''







								a										=							vocab_size
								a										=							d_model
								a										=							d_kv
								a										=							d_ff

								a										=							num_sparse_encoder_layers

								a										=							num_layers
								a										=							(
								    num_decoder_layers if num_decoder_layers is not None else self.num_layers
								)  # default = symmetry
								a										=							num_sparse_decoder_layers

								# This tells us, each how many encoder layer we'll have to set a sparse layer.
								if self.num_sparse_encoder_layers > 0:
									a										=							self.num_layers // self.num_sparse_encoder_layers
								else:
									a										=							self.num_layers  # HACK: this will create 0 sparse layers

								# This tells us, each how many encoder layer we'll have to set a sparse layer.
								if self.num_sparse_decoder_layers > 0:
									a										=							self.num_decoder_layers // self.num_sparse_decoder_layers
								else:
									a										=							self.num_decoder_layers  # HACK: this will create 0 sparse layers

								a										=							num_heads
								a										=							num_experts
								a										=							expert_capacity
								a										=							router_bias
								a										=							router_jitter_noise
								if router_dtype not in ["float32", "float16", "bfloat16"]:
									raise ValueError(F'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}'				)
								a										=							router_dtype

								a										=							router_ignore_padding_tokens
								a										=							relative_attention_num_buckets
								a										=							relative_attention_max_distance

								a										=							dropout_rate
								a										=							layer_norm_epsilon
								a										=							initializer_factor
								a										=							feed_forward_proj
								a										=							use_cache
								a										=							add_router_probs

								a										=							router_z_loss_coef
								a										=							router_aux_loss_coef

								a										=							self.feed_forward_proj.split("""-"""				)
								a										=							act_info[-1]
								a										=							act_info[0] == 'gated'

								if len(__UpperCAmelCase				) > 1 and act_info[0] != "gated" or len(__UpperCAmelCase				) > 2:
									raise ValueError(
									    F'`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.'
									    """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """
									    """\'gated-gelu\' or \'relu\'"""				)

								# for backwards compatibility
								if feed_forward_proj == "gated-gelu":
									a										=							'gelu_new'

								super().__init__(
								    pad_token_id=__UpperCAmelCase		,      eos_token_id=__UpperCAmelCase		,      is_encoder_decoder=__UpperCAmelCase		,      **__UpperCAmelCase		,      )








"""simple docstring"""





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  __A   (_SCREAMING_SNAKE_CASE			)					->int:





  """simple docstring"""


  return 1.0 / (1.0 + np.exp(-_outputs			))
def  __A   (_SCREAMING_SNAKE_CASE			)					->Tuple:





  """simple docstring"""


  lowerCAmelCase__			:List[str]											=							np.max(_outputs     ,   axis=-1     ,   keepdims=_SCREAMING_SNAKE_CASE			)
  lowerCAmelCase__			:List[Any]											=							np.exp(_outputs - maxes			)
  return shifted_exp / shifted_exp.sum(axis=-1     ,   keepdims=_SCREAMING_SNAKE_CASE			)






class 					_lowerCAmelCase   (     a       ):
       """simple docstring"""




       __magic_name__     :Any		  =					"""sigmoid"""
       __magic_name__     :Optional[Any]		  =					"""softmax"""
       __magic_name__     :Optional[Any]		  =					"""none"""






@add_end_docstrings(
    a  ,   r"""
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `\"default\"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `\"sigmoid\"`: Applies the sigmoid function on the output.
            - `\"softmax\"`: Applies the softmax function on the output.
            - `\"none\"`: Does not apply any function on the output.
    """  ,   )
class 					_lowerCAmelCase   (     a       ):
       """simple docstring"""




       __magic_name__     :Union[str, Any]		  =					False
       __magic_name__     :Dict		  =					ClassificationFunction.NONE






       def __init__(    self    , **__UpperCAmelCase      ):



         '''simple docstring'''

         super().__init__(**__UpperCAmelCase      )

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






       def      snake_case						(    self    , __UpperCAmelCase=None    , __UpperCAmelCase=None    , __UpperCAmelCase=""    , **__UpperCAmelCase      ):



         '''simple docstring'''

         lowerCAmelCase__			:Optional[int]											=							tokenizer_kwargs

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

         if isinstance(__UpperCAmelCase    , __UpperCAmelCase      ) or top_k is None:
           lowerCAmelCase__			:int											=							top_k
           lowerCAmelCase__			:Dict											=							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`.'    , __UpperCAmelCase    , )
           if return_all_scores:
             lowerCAmelCase__			:List[Any]											=							None
           else:
             lowerCAmelCase__			:Union[str, Any]											=							1

         if isinstance(__UpperCAmelCase    , __UpperCAmelCase      ):
           lowerCAmelCase__			:Union[str, Any]											=							ClassificationFunction[function_to_apply.upper()]

         if function_to_apply is not None:
           lowerCAmelCase__			:List[Any]											=							function_to_apply
         return preprocess_params, {}, postprocess_params






       def __call__(    self    , *__UpperCAmelCase    , **__UpperCAmelCase      ):



         '''simple docstring'''

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






       def      snake_case						(    self    , __UpperCAmelCase    , **__UpperCAmelCase      ):



         '''simple docstring'''

         lowerCAmelCase__			:Dict											=							self.framework
         if isinstance(__UpperCAmelCase    , __UpperCAmelCase      ):
           return self.tokenizer(**__UpperCAmelCase    , return_tensors=__UpperCAmelCase    , **__UpperCAmelCase      )
         elif isinstance(__UpperCAmelCase    , __UpperCAmelCase      ) and len(__UpperCAmelCase      ) == 1 and isinstance(inputs[0]    , __UpperCAmelCase      ) 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=__UpperCAmelCase    , **__UpperCAmelCase      )
         elif isinstance(__UpperCAmelCase    , __UpperCAmelCase      ):
           # 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(__UpperCAmelCase    , return_tensors=__UpperCAmelCase    , **__UpperCAmelCase      )






       def      snake_case						(    self    , __UpperCAmelCase      ):



         '''simple docstring'''

         return self.model(**__UpperCAmelCase      )






       def      snake_case						(    self    , __UpperCAmelCase    , __UpperCAmelCase=None    , __UpperCAmelCase=1    , __UpperCAmelCase=True      ):



         '''simple docstring'''

         if function_to_apply is None:
           if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
             lowerCAmelCase__			:str											=							ClassificationFunction.SIGMOID
           elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
             lowerCAmelCase__			:int											=							ClassificationFunction.SOFTMAX
           elif hasattr(self.model.config    , 'function_to_apply'      ) and function_to_apply is None:
             lowerCAmelCase__			:Optional[Any]											=							self.model.config.function_to_apply
           else:
             lowerCAmelCase__			:Dict											=							ClassificationFunction.NONE

         lowerCAmelCase__			:int											=							model_outputs['logits'][0]
         lowerCAmelCase__			:Union[str, Any]											=							outputs.numpy()

         if function_to_apply == ClassificationFunction.SIGMOID:
           lowerCAmelCase__			:Dict											=							sigmoid(__UpperCAmelCase      )
         elif function_to_apply == ClassificationFunction.SOFTMAX:
           lowerCAmelCase__			:int											=							softmax(__UpperCAmelCase      )
         elif function_to_apply == ClassificationFunction.NONE:
           lowerCAmelCase__			:Tuple											=							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()}

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