




'''simple docstring'''

import unittest

from transformers import SqueezeBertConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

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 (
						    SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
						    SqueezeBertForMaskedLM,
						    SqueezeBertForMultipleChoice,
						    SqueezeBertForQuestionAnswering,
						    SqueezeBertForSequenceClassification,
						    SqueezeBertForTokenClassification,
						    SqueezeBertModel,
						)



class 		SCREAMING_SNAKE_CASE__  (			_UpperCamelCase	):





			def __init__(      self						:    Optional[Any]      ,		a_						:    List[Any]      ,		a_						:    Tuple=13      ,		a_						:    Optional[Any]=7      ,		a_						:    List[Any]=True      ,		a_						:    List[str]=True      ,		a_						:    List[str]=False      ,		a_						:    List[str]=True      ,		a_						:    Union[str, Any]=99      ,		a_						:    List[Any]=32      ,		a_						:    Optional[Any]=5      ,		a_						:    Union[str, Any]=4      ,		a_						:    Optional[int]=64      ,		a_						:    Any="gelu"      ,		a_						:    Optional[int]=0.1      ,		a_						:    List[str]=0.1      ,		a_						:    str=512      ,		a_						:    int=16      ,		a_						:    Optional[int]=2      ,		a_						:    Dict=0.02      ,		a_						:    List[Any]=3      ,		a_						:    Any=4      ,		a_						:    Tuple=None      ,		a_						:    Optional[int]=2      ,		a_						:    int=2      ,		a_						:    Union[str, Any]=2      ,		a_						:    Union[str, Any]=2      ,		a_						:    List[Any]=4      ,		a_						:    List[Any]=1      ,		):



						"""simple docstring"""




						__snake_case			=		parent
						__snake_case			=		batch_size
						__snake_case			=		seq_length
						__snake_case			=		is_training
						__snake_case			=		use_input_mask
						__snake_case			=		use_token_type_ids
						__snake_case			=		use_labels
						__snake_case			=		vocab_size
						__snake_case			=		hidden_size
						__snake_case			=		num_hidden_layers
						__snake_case			=		num_attention_heads
						__snake_case			=		intermediate_size
						__snake_case			=		hidden_act
						__snake_case			=		hidden_dropout_prob
						__snake_case			=		attention_probs_dropout_prob
						__snake_case			=		max_position_embeddings
						__snake_case			=		type_vocab_size
						__snake_case			=		type_sequence_label_size
						__snake_case			=		initializer_range
						__snake_case			=		num_labels
						__snake_case			=		num_choices
						__snake_case			=		scope
						__snake_case			=		q_groups
						__snake_case			=		k_groups
						__snake_case			=		v_groups
						__snake_case			=		post_attention_groups
						__snake_case			=		intermediate_groups
						__snake_case			=		output_groups





			def 							A (      self						:    Dict							):



						"""simple docstring"""




						__snake_case			=		ids_tensor([self.batch_size, self.seq_length]      ,		self.vocab_size							)

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

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

						__snake_case			=		self.get_config()

						return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels





			def 							A (      self						:    str							):



						"""simple docstring"""




						return SqueezeBertConfig(
						    embedding_size=self.hidden_size      ,		vocab_size=self.vocab_size      ,		hidden_size=self.hidden_size      ,		num_hidden_layers=self.num_hidden_layers      ,		num_attention_heads=self.num_attention_heads      ,		intermediate_size=self.intermediate_size      ,		hidden_act=self.hidden_act      ,		attention_probs_dropout_prob=self.hidden_dropout_prob      ,		attention_dropout=self.attention_probs_dropout_prob      ,		max_position_embeddings=self.max_position_embeddings      ,		initializer_range=self.initializer_range      ,		q_groups=self.q_groups      ,		k_groups=self.k_groups      ,		v_groups=self.v_groups      ,		post_attention_groups=self.post_attention_groups      ,		intermediate_groups=self.intermediate_groups      ,		output_groups=self.output_groups      ,		)





			def 							A (      self						:    Dict      ,		a_						:    Optional[Any]      ,		a_						:    List[Any]      ,		a_						:    List[str]      ,		a_						:    List[Any]      ,		a_						:    Dict      ,		a_						:    Dict							):



						"""simple docstring"""




						__snake_case			=		SqueezeBertModel(config=a_							)
						model.to(a_							)
						model.eval()
						__snake_case			=		model(a_      ,		a_							)
						__snake_case			=		model(a_							)
						self.parent.assertEqual(result.last_hidden_state.shape      ,		(self.batch_size, self.seq_length, self.hidden_size)							)





			def 							A (      self						:    Dict      ,		a_						:    Optional[Any]      ,		a_						:    int      ,		a_						:    Any      ,		a_						:    int      ,		a_						:    Tuple      ,		a_						:    Dict							):



						"""simple docstring"""




						__snake_case			=		SqueezeBertForMaskedLM(config=a_							)
						model.to(a_							)
						model.eval()
						__snake_case			=		model(a_      ,		attention_mask=a_      ,		labels=a_							)
						self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.seq_length, self.vocab_size)							)





			def 							A (      self						:    Any      ,		a_						:    List[Any]      ,		a_						:    str      ,		a_						:    Any      ,		a_						:    List[str]      ,		a_						:    Tuple      ,		a_						:    str							):



						"""simple docstring"""




						__snake_case			=		SqueezeBertForQuestionAnswering(config=a_							)
						model.to(a_							)
						model.eval()
						__snake_case			=		model(
						    a_      ,		attention_mask=a_      ,		start_positions=a_      ,		end_positions=a_							)
						self.parent.assertEqual(result.start_logits.shape      ,		(self.batch_size, self.seq_length)							)
						self.parent.assertEqual(result.end_logits.shape      ,		(self.batch_size, self.seq_length)							)





			def 							A (      self						:    Optional[Any]      ,		a_						:    Tuple      ,		a_						:    Tuple      ,		a_						:    Dict      ,		a_						:    List[Any]      ,		a_						:    Dict      ,		a_						:    List[Any]							):



						"""simple docstring"""




						__snake_case			=		self.num_labels
						__snake_case			=		SqueezeBertForSequenceClassification(a_							)
						model.to(a_							)
						model.eval()
						__snake_case			=		model(a_      ,		attention_mask=a_      ,		labels=a_							)
						self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.num_labels)							)





			def 							A (      self						:    Tuple      ,		a_						:    List[str]      ,		a_						:    Optional[Any]      ,		a_						:    Optional[Any]      ,		a_						:    Optional[int]      ,		a_						:    List[Any]      ,		a_						:    Optional[int]							):



						"""simple docstring"""




						__snake_case			=		self.num_labels
						__snake_case			=		SqueezeBertForTokenClassification(config=a_							)
						model.to(a_							)
						model.eval()

						__snake_case			=		model(a_      ,		attention_mask=a_      ,		labels=a_							)
						self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.seq_length, self.num_labels)							)





			def 							A (      self						:    int      ,		a_						:    str      ,		a_						:    int      ,		a_						:    Union[str, Any]      ,		a_						:    Optional[int]      ,		a_						:    Dict      ,		a_						:    Dict							):



						"""simple docstring"""




						__snake_case			=		self.num_choices
						__snake_case			=		SqueezeBertForMultipleChoice(config=a_							)
						model.to(a_							)
						model.eval()
						__snake_case			=		input_ids.unsqueeze(1							).expand(-1      ,		self.num_choices      ,		-1							).contiguous()
						__snake_case			=		input_mask.unsqueeze(1							).expand(-1      ,		self.num_choices      ,		-1							).contiguous()
						__snake_case			=		model(
						    a_      ,		attention_mask=a_      ,		labels=a_      ,		)
						self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.num_choices)							)






			def 							A (      self						:    int							):



						"""simple docstring"""




						__snake_case			=		self.prepare_config_and_inputs()
						((__snake_case)		,     (__snake_case)		,     (__snake_case)		,     (__snake_case)		,     (__snake_case)		,     (__snake_case))			=		config_and_inputs
						__snake_case			=		{"input_ids": input_ids, "attention_mask": input_mask}
						return config, inputs_dict







@require_torch
class 		SCREAMING_SNAKE_CASE__  (			_UpperCamelCase				,     _UpperCamelCase				,     unittest.TestCase	):
			__SCREAMING_SNAKE_CASE    =			(
			    (
			        SqueezeBertModel,
			        SqueezeBertForMaskedLM,
			        SqueezeBertForMultipleChoice,
			        SqueezeBertForQuestionAnswering,
			        SqueezeBertForSequenceClassification,
			        SqueezeBertForTokenClassification,
			    )
			    if is_torch_available()
			    else None
			)
			__SCREAMING_SNAKE_CASE    =			(
			    {
			        """feature-extraction""": SqueezeBertModel,
			        """fill-mask""": SqueezeBertForMaskedLM,
			        """question-answering""": SqueezeBertForQuestionAnswering,
			        """text-classification""": SqueezeBertForSequenceClassification,
			        """token-classification""": SqueezeBertForTokenClassification,
			        """zero-shot""": SqueezeBertForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			__SCREAMING_SNAKE_CASE    =			False
			__SCREAMING_SNAKE_CASE    =			True
			__SCREAMING_SNAKE_CASE    =			False





			def 							A (      self						:    Union[str, Any]							):



						"""simple docstring"""




						__snake_case			=		SqueezeBertModelTester(self							)
						__snake_case			=		ConfigTester(self      ,		config_class=a_      ,		dim=37							)





			def 							A (      self						:    Dict							):



						"""simple docstring"""




						self.config_tester.run_common_tests()





			def 							A (      self						:    Dict							):



						"""simple docstring"""




						__snake_case			=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_squeezebert_model(*a_							)





			def 							A (      self						:    Tuple							):



						"""simple docstring"""




						__snake_case			=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_squeezebert_for_masked_lm(*a_							)





			def 							A (      self						:    str							):



						"""simple docstring"""




						__snake_case			=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_squeezebert_for_question_answering(*a_							)





			def 							A (      self						:    int							):



						"""simple docstring"""




						__snake_case			=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_squeezebert_for_sequence_classification(*a_							)





			def 							A (      self						:    List[Any]							):



						"""simple docstring"""




						__snake_case			=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_squeezebert_for_token_classification(*a_							)





			def 							A (      self						:    int							):



						"""simple docstring"""




						__snake_case			=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_squeezebert_for_multiple_choice(*a_							)






			@slow
			def 							A (      self						:    Optional[int]							):



						"""simple docstring"""




						for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									__snake_case			=		SqueezeBertModel.from_pretrained(a_							)
									self.assertIsNotNone(a_							)







@require_sentencepiece
@require_tokenizers
@require_torch
class 		SCREAMING_SNAKE_CASE__  (			unittest.TestCase	):





			@slow
			def 							A (      self						:    Any							):



						"""simple docstring"""




						__snake_case			=		SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli"							)

						__snake_case			=		torch.tensor([[1, 29_414, 232, 328, 740, 1_140, 12_695, 69, 13, 1_588, 2]]							)
						__snake_case			=		model(a_							)[0]
						__snake_case			=		torch.Size((1, 3)							)
						self.assertEqual(output.shape      ,		a_							)
						__snake_case			=		torch.tensor([[0.6401, -0.0349, -0.6041]]							)
						self.assertTrue(torch.allclose(a_      ,		a_      ,		atol=1e-4							)							)








'''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       snake_case   (	snake_case      : Any			) ->  Any:


    """simple docstring"""


    return 1.0 / (1.0 + np.exp(-_outputs			))


def       snake_case   (	snake_case      : Dict			) ->  str:


    """simple docstring"""


    lowerCAmelCase 						=							np.max(_outputs					,		axis=-1					,		keepdims=snake_case			)
    lowerCAmelCase 						=							np.exp(_outputs - maxes			)
    return shifted_exp / shifted_exp.sum(axis=-1					,		keepdims=snake_case			)



class 				_snake_case					(   a_			):
  SCREAMING_SNAKE_CASE			:       List[str]				=     '''sigmoid'''
  SCREAMING_SNAKE_CASE			:       List[Any]				=     '''softmax'''
  SCREAMING_SNAKE_CASE			:       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 				_snake_case					(   a_			):
  SCREAMING_SNAKE_CASE			:       Union[str, Any]				=     False
  SCREAMING_SNAKE_CASE			:       Dict				=     ClassificationFunction.NONE

  def __init__(				self      , **_SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      super().__init__(**_SCREAMING_SNAKE_CASE	)

      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      , _SCREAMING_SNAKE_CASE=None      , _SCREAMING_SNAKE_CASE=None      , _SCREAMING_SNAKE_CASE=""      , **_SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							tokenizer_kwargs

      lowerCAmelCase 						=							{}
      if hasattr(self.model.config      , 'return_all_scores'	) and return_all_scores is None:
          lowerCAmelCase 						=							self.model.config.return_all_scores

      if isinstance(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	) or top_k is None:
          lowerCAmelCase 						=							top_k
          lowerCAmelCase 						=							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`.'      , _SCREAMING_SNAKE_CASE      , )
          if return_all_scores:
              lowerCAmelCase 						=							None
          else:
              lowerCAmelCase 						=							1

      if isinstance(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):
          lowerCAmelCase 						=							ClassificationFunction[function_to_apply.upper()]

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

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





      '''simple docstring'''

      lowerCAmelCase 						=							super().__call__(*_SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	)
      # TODO try and retrieve it in a nicer way from _sanitize_parameters.
      lowerCAmelCase 						=							'top_k' not in kwargs
      if isinstance(args[0]      , _SCREAMING_SNAKE_CASE	) 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      , _SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

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

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      return self.model(**_SCREAMING_SNAKE_CASE	)


  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE=None      , _SCREAMING_SNAKE_CASE=1      , _SCREAMING_SNAKE_CASE=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 						=							ClassificationFunction.SIGMOID
          elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
              lowerCAmelCase 						=							ClassificationFunction.SOFTMAX
          elif hasattr(self.model.config      , 'function_to_apply'	) and function_to_apply is None:
              lowerCAmelCase 						=							self.model.config.function_to_apply
          else:
              lowerCAmelCase 						=							ClassificationFunction.NONE

      lowerCAmelCase 						=							model_outputs['logits'][0]
      lowerCAmelCase 						=							outputs.numpy()

      if function_to_apply == ClassificationFunction.SIGMOID:
          lowerCAmelCase 						=							sigmoid(_SCREAMING_SNAKE_CASE	)
      elif function_to_apply == ClassificationFunction.SOFTMAX:
          lowerCAmelCase 						=							softmax(_SCREAMING_SNAKE_CASE	)
      elif function_to_apply == ClassificationFunction.NONE:
          lowerCAmelCase 						=							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 						=							[
          {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(_SCREAMING_SNAKE_CASE	)
      ]
      if not _legacy:
          dict_scores.sort(key=lambda _SCREAMING_SNAKE_CASE	: x["score"]      , reverse=_SCREAMING_SNAKE_CASE	)
          if top_k is not None:
              lowerCAmelCase 						=							dict_scores[:top_k]
      return dict_scores





