

'''simple docstring'''



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 				_snake_case					:

  def __init__(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE=14      , _SCREAMING_SNAKE_CASE=7      , _SCREAMING_SNAKE_CASE=True      , _SCREAMING_SNAKE_CASE=True      , _SCREAMING_SNAKE_CASE=True      , _SCREAMING_SNAKE_CASE=True      , _SCREAMING_SNAKE_CASE=True      , _SCREAMING_SNAKE_CASE=99      , _SCREAMING_SNAKE_CASE=32      , _SCREAMING_SNAKE_CASE=5      , _SCREAMING_SNAKE_CASE=4      , _SCREAMING_SNAKE_CASE=37      , _SCREAMING_SNAKE_CASE="gelu"      , _SCREAMING_SNAKE_CASE=0.1      , _SCREAMING_SNAKE_CASE=0.1      , _SCREAMING_SNAKE_CASE=5_12      , _SCREAMING_SNAKE_CASE=16      , _SCREAMING_SNAKE_CASE=2      , _SCREAMING_SNAKE_CASE=0.02      , _SCREAMING_SNAKE_CASE=3      , _SCREAMING_SNAKE_CASE=4      , _SCREAMING_SNAKE_CASE=None      , ):





      '''simple docstring'''

      lowerCAmelCase 						=							parent
      lowerCAmelCase 						=							batch_size
      lowerCAmelCase 						=							seq_length
      lowerCAmelCase 						=							is_training
      lowerCAmelCase 						=							use_token_type_ids
      lowerCAmelCase 						=							use_input_mask
      lowerCAmelCase 						=							use_labels
      lowerCAmelCase 						=							use_mc_token_ids
      lowerCAmelCase 						=							vocab_size
      lowerCAmelCase 						=							hidden_size
      lowerCAmelCase 						=							num_hidden_layers
      lowerCAmelCase 						=							num_attention_heads
      lowerCAmelCase 						=							intermediate_size
      lowerCAmelCase 						=							hidden_act
      lowerCAmelCase 						=							hidden_dropout_prob
      lowerCAmelCase 						=							attention_probs_dropout_prob
      lowerCAmelCase 						=							max_position_embeddings
      lowerCAmelCase 						=							type_vocab_size
      lowerCAmelCase 						=							type_sequence_label_size
      lowerCAmelCase 						=							initializer_range
      lowerCAmelCase 						=							num_labels
      lowerCAmelCase 						=							num_choices
      lowerCAmelCase 						=							scope
      lowerCAmelCase 						=							self.vocab_size - 1

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

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

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

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

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

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

      lowerCAmelCase 						=							self.get_config()

      lowerCAmelCase 						=							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   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      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   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , *_SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							CTRLModel(config=_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()

      model(_SCREAMING_SNAKE_CASE      , token_type_ids=_SCREAMING_SNAKE_CASE      , head_mask=_SCREAMING_SNAKE_CASE	)
      model(_SCREAMING_SNAKE_CASE      , token_type_ids=_SCREAMING_SNAKE_CASE	)
      lowerCAmelCase 						=							model(_SCREAMING_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   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , *_SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							CTRLLMHeadModel(_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()

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

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.prepare_config_and_inputs()

      (
          (
          lowerCAmelCase
      )						,   (
          lowerCAmelCase
      )						,   (
          lowerCAmelCase
      )						,   (
          lowerCAmelCase
      )						,   (
          lowerCAmelCase
      )						,   (
          lowerCAmelCase
      )						,   (
          lowerCAmelCase
      )						,   (
          lowerCAmelCase
      )						,   (
          lowerCAmelCase
      )						,   
      ) 						=							config_and_inputs

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

      return config, inputs_dict


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





      '''simple docstring'''

      lowerCAmelCase 						=							self.num_labels
      lowerCAmelCase 						=							CTRLForSequenceClassification(_SCREAMING_SNAKE_CASE	)
      model.to(_SCREAMING_SNAKE_CASE	)
      model.eval()
      lowerCAmelCase 						=							ids_tensor([self.batch_size]      , self.type_sequence_label_size	)
      lowerCAmelCase 						=							model(_SCREAMING_SNAKE_CASE      , token_type_ids=_SCREAMING_SNAKE_CASE      , labels=_SCREAMING_SNAKE_CASE	)
      self.parent.assertEqual(result.logits.shape      , (self.batch_size, self.num_labels)	)



@require_torch
class 				_snake_case					(   a_     , a_     , a_     , unittest.TestCase			):
  SCREAMING_SNAKE_CASE			:       Optional[Any]				=     (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE			:       Dict				=     (CTRLLMHeadModel,) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE			:       Union[str, Any]				=     (
      {
          '''feature-extraction''': CTRLModel,
          '''text-classification''': CTRLForSequenceClassification,
          '''text-generation''': CTRLLMHeadModel,
          '''zero-shot''': CTRLForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )
  SCREAMING_SNAKE_CASE			:       str				=     True
  SCREAMING_SNAKE_CASE			:       Any				=     False
  SCREAMING_SNAKE_CASE			:       Dict				=     False

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

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





      '''simple docstring'''

      lowerCAmelCase 						=							CTRLModelTester(self	)
      lowerCAmelCase 						=							ConfigTester(self      , config_class=_SCREAMING_SNAKE_CASE      , n_embd=37	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

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

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      self.config_tester.run_common_tests()

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_ctrl_model(*_SCREAMING_SNAKE_CASE	)

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_lm_head_model(*_SCREAMING_SNAKE_CASE	)

  @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'	)
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      pass

  @slow
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase 						=							CTRLModel.from_pretrained(_SCREAMING_SNAKE_CASE	)
          self.assertIsNotNone(_SCREAMING_SNAKE_CASE	)


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





      '''simple docstring'''

      pass



@require_torch
class 				_snake_case					(   unittest.TestCase			):

  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

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


  @slow
  def   _SCREAMING_SNAKE_CASE				(				self	):





      '''simple docstring'''

      lowerCAmelCase 						=							CTRLLMHeadModel.from_pretrained('ctrl'	)
      model.to(_SCREAMING_SNAKE_CASE	)
      lowerCAmelCase 						=							torch.tensor(
          [[1_18_59, 0, 16_11, 8]]      , dtype=torch.long      , device=_SCREAMING_SNAKE_CASE	)  # Legal the president is
      lowerCAmelCase 						=							[
          1_18_59,
          0,
          16_11,
          8,
          5,
          1_50,
          2_64_49,
          2,
          19,
          3_48,
          4_69,
          3,
          25_95,
          48,
          2_07_40,
          24_65_33,
          24_65_33,
          19,
          30,
          5,
      ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

      lowerCAmelCase 						=							model.generate(_SCREAMING_SNAKE_CASE      , do_sample=_SCREAMING_SNAKE_CASE	)
      self.assertListEqual(output_ids[0].tolist()      , _SCREAMING_SNAKE_CASE	)








'''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





