


'''simple docstring'''




import unittest

from transformers import AutoTokenizer, FalconConfig, 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 (
           FalconForCausalLM,
           FalconForQuestionAnswering,
           FalconForSequenceClassification,
           FalconForTokenClassification,
           FalconModel,
       )

class 		UpperCAmelCase_      :





     def __init__( self       :      Union[str, Any]    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      List[Any]=3    ,      UpperCAmelCase__       :      Optional[int]=7    ,      UpperCAmelCase__       :      int=True    ,      UpperCAmelCase__       :      Union[str, Any]=True    ,      UpperCAmelCase__       :      str=False    ,      UpperCAmelCase__       :      List[Any]=True    ,      UpperCAmelCase__       :      List[str]=9_9    ,      UpperCAmelCase__       :      Union[str, Any]=3_2    ,      UpperCAmelCase__       :      Optional[Any]=5    ,      UpperCAmelCase__       :      List[Any]=4    ,      UpperCAmelCase__       :      str=3_7    ,      UpperCAmelCase__       :      Optional[int]="gelu"    ,      UpperCAmelCase__       :      str=0.1    ,      UpperCAmelCase__       :      Optional[int]=0.1    ,      UpperCAmelCase__       :      Dict=5_1_2    ,      UpperCAmelCase__       :      int=1_6    ,      UpperCAmelCase__       :      str=2    ,      UpperCAmelCase__       :      Dict=0.02    ,      UpperCAmelCase__       :      int=3    ,      UpperCAmelCase__       :      int=4    ,      UpperCAmelCase__       :      Any=None    ,      )				->  Dict:
        lowerCAmelCase     =			parent
        lowerCAmelCase     =			batch_size
        lowerCAmelCase     =			seq_length
        lowerCAmelCase     =			is_training
        lowerCAmelCase     =			use_input_mask
        lowerCAmelCase     =			use_token_type_ids
        lowerCAmelCase     =			use_labels
        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





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  Union[str, Any]:
        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

        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()

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





     def 							__UpperCAmelCase      ( self       :      Dict    )				->  str:
        return FalconConfig(
            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    ,      hidden_dropout_prob=self.hidden_dropout_prob    ,      attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,      max_position_embeddings=self.max_position_embeddings    ,      type_vocab_size=self.type_vocab_size    ,      is_decoder=UpperCAmelCase__    ,      initializer_range=self.initializer_range    ,      pad_token_id=1    ,      new_decoder_architecture=UpperCAmelCase__    ,      )





     def 							__UpperCAmelCase      ( self       :      Tuple    ,      UpperCAmelCase__       :      List[Any]    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      int    ,      UpperCAmelCase__       :      Tuple    ,      UpperCAmelCase__       :      Optional[int]    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      Optional[int]    )				->  Dict:
        lowerCAmelCase     =			FalconModel(config=UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    )
        lowerCAmelCase     =			model(UpperCAmelCase__    )
        self.parent.assertEqual(result.last_hidden_state.shape    ,      (self.batch_size, self.seq_length, self.hidden_size)    )





     def 							__UpperCAmelCase      ( self       :      Optional[Any]    ,      UpperCAmelCase__       :      Optional[int]    ,      UpperCAmelCase__       :      Optional[Any]    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      Optional[Any]    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      str    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      Tuple    ,      )				->  Optional[int]:
        lowerCAmelCase     =			True
        lowerCAmelCase     =			FalconModel(UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(
            UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      encoder_hidden_states=UpperCAmelCase__    ,      encoder_attention_mask=UpperCAmelCase__    ,      )
        lowerCAmelCase     =			model(
            UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      encoder_hidden_states=UpperCAmelCase__    ,      )
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    )
        self.parent.assertEqual(result.last_hidden_state.shape    ,      (self.batch_size, self.seq_length, self.hidden_size)    )





     def 							__UpperCAmelCase      ( self       :      Any    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      Any    ,      UpperCAmelCase__       :      List[Any]    ,      UpperCAmelCase__       :      str    ,      UpperCAmelCase__       :      str    ,      UpperCAmelCase__       :      int    ,      UpperCAmelCase__       :      Tuple    ,      UpperCAmelCase__       :      str    ,      UpperCAmelCase__       :      Tuple    ,      )				->  Tuple:
        lowerCAmelCase     =			FalconForCausalLM(config=UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      labels=UpperCAmelCase__    )
        self.parent.assertEqual(result.logits.shape    ,      (self.batch_size, self.seq_length, self.vocab_size)    )





     def 							__UpperCAmelCase      ( self       :      Dict    ,      UpperCAmelCase__       :      List[Any]    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      Optional[Any]    ,      UpperCAmelCase__       :      Any    ,      UpperCAmelCase__       :      Dict    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      Optional[Any]    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      Any    ,      )				->  Optional[int]:
        lowerCAmelCase     =			True
        lowerCAmelCase     =			True
        lowerCAmelCase     =			FalconForCausalLM(config=UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()

        # first forward pass
        lowerCAmelCase     =			model(
            UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      encoder_hidden_states=UpperCAmelCase__    ,      encoder_attention_mask=UpperCAmelCase__    ,      use_cache=UpperCAmelCase__    ,      )
        lowerCAmelCase     =			outputs.past_key_values

        # create hypothetical multiple next token and extent to next_input_ids
        lowerCAmelCase     =			ids_tensor((self.batch_size, 3)    ,      config.vocab_size    )
        lowerCAmelCase     =			ids_tensor((self.batch_size, 3)    ,      vocab_size=2    )

        # append to next input_ids and
        lowerCAmelCase     =			torch.cat([input_ids, next_tokens]    ,      dim=-1    )
        lowerCAmelCase     =			torch.cat([input_mask, next_mask]    ,      dim=-1    )

        lowerCAmelCase     =			model(
            UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      encoder_hidden_states=UpperCAmelCase__    ,      encoder_attention_mask=UpperCAmelCase__    ,      output_hidden_states=UpperCAmelCase__    ,      )['hidden_states'][0]
        lowerCAmelCase     =			model(
            UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      encoder_hidden_states=UpperCAmelCase__    ,      encoder_attention_mask=UpperCAmelCase__    ,      past_key_values=UpperCAmelCase__    ,      output_hidden_states=UpperCAmelCase__    ,      )['hidden_states'][0]

        # select random slice
        lowerCAmelCase     =			ids_tensor((1,)    ,      output_from_past.shape[-1]    ).item()
        lowerCAmelCase     =			output_from_no_past[:, -3:, random_slice_idx].detach()
        lowerCAmelCase     =			output_from_past[:, :, random_slice_idx].detach()

        self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]    )

        # test that outputs are equal for slice
        self.parent.assertTrue(torch.allclose(UpperCAmelCase__    ,      UpperCAmelCase__    ,      atol=1E-3    )    )





     def 							__UpperCAmelCase      ( self       :      Dict    )				->  List[Any]:
        lowerCAmelCase     =			self.prepare_config_and_inputs()
        (
            (
            lowerCAmelCase
        )     ,  (
            lowerCAmelCase
        )     ,  (
            lowerCAmelCase
        )     ,  (
            lowerCAmelCase
        )     ,  (
            lowerCAmelCase
        )     ,  (
            lowerCAmelCase
        )     ,  (
            lowerCAmelCase
        )     ,  
        )     =			config_and_inputs
        lowerCAmelCase     =			{'input_ids': input_ids, 'attention_mask': input_mask}
        return config, inputs_dict




@require_torch
class 		UpperCAmelCase_      (  __lowercase       ,	__lowercase       ,	__lowercase       ,	unittest.TestCase		):
     lowerCamelCase				:	List[Any]		=     (
         (
             FalconModel,
             FalconForCausalLM,
             FalconForSequenceClassification,
             FalconForTokenClassification,
             FalconForQuestionAnswering,
         )
         if is_torch_available()
         else ()
     )
     lowerCamelCase				:	List[Any]		=     (FalconForCausalLM,) if is_torch_available() else ()
     lowerCamelCase				:	Tuple		=     (
         {
             '''feature-extraction''': FalconModel,
             '''text-classification''': FalconForSequenceClassification,
             '''text-generation''': FalconForCausalLM,
             '''question-answering''': FalconForQuestionAnswering,
             '''token-classification''': FalconForTokenClassification,
             '''zero-shot''': FalconForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )
     lowerCamelCase				:	str		=     False
     lowerCamelCase				:	Tuple		=     False





     def 							__UpperCAmelCase      ( self       :      Optional[int]    )				->  Dict:
        lowerCAmelCase     =			FalconModelTester(self    )
        lowerCAmelCase     =			ConfigTester(self    ,      config_class=UpperCAmelCase__    ,      hidden_size=3_7    )





     def 							__UpperCAmelCase      ( self       :      List[str]    )				->  Tuple:
        self.config_tester.run_common_tests()





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  Union[str, Any]:
        lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*UpperCAmelCase__    )





     def 							__UpperCAmelCase      ( self       :      List[Any]    )				->  Any:
        lowerCAmelCase     ,  *lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs()
        for alibi in [True, False]:
           lowerCAmelCase     =			alibi
           self.model_tester.create_and_check_model(UpperCAmelCase__    ,      *UpperCAmelCase__    )





     def 							__UpperCAmelCase      ( self       :      Optional[Any]    )				->  List[str]:
        lowerCAmelCase     ,  lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase     =			3
        lowerCAmelCase     =			input_dict['input_ids']
        lowerCAmelCase     =			input_ids.ne(1    ).to(UpperCAmelCase__    )
        lowerCAmelCase     =			ids_tensor([self.model_tester.batch_size]    ,      self.model_tester.type_sequence_label_size    )
        lowerCAmelCase     =			FalconForSequenceClassification(UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      labels=UpperCAmelCase__    )
        self.assertEqual(result.logits.shape    ,      (self.model_tester.batch_size, self.model_tester.num_labels)    )





     def 							__UpperCAmelCase      ( self       :      List[Any]    )				->  Dict:
        lowerCAmelCase     ,  lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase     =			3
        lowerCAmelCase     =			'single_label_classification'
        lowerCAmelCase     =			input_dict['input_ids']
        lowerCAmelCase     =			input_ids.ne(1    ).to(UpperCAmelCase__    )
        lowerCAmelCase     =			ids_tensor([self.model_tester.batch_size]    ,      self.model_tester.type_sequence_label_size    )
        lowerCAmelCase     =			FalconForSequenceClassification(UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      labels=UpperCAmelCase__    )
        self.assertEqual(result.logits.shape    ,      (self.model_tester.batch_size, self.model_tester.num_labels)    )





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  int:
        lowerCAmelCase     ,  lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase     =			input_dict['input_ids']
        lowerCAmelCase     =			FalconForCausalLM(UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      use_cache=UpperCAmelCase__    )
        lowerCAmelCase     =			input_ids.shape[0]
        lowerCAmelCase     =			model._convert_to_rw_cache(result.past_key_values    )
        lowerCAmelCase     =			model._convert_cache_to_standard_format(UpperCAmelCase__    ,      UpperCAmelCase__    )
        for layer in range(len(UpperCAmelCase__    )    ):
           for tensor_idx in range(2    ):
              self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3    )
              self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4    )
              self.assertTrue(
                  torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx]    )    )





     def 							__UpperCAmelCase      ( self       :      int    )				->  Dict:
        lowerCAmelCase     ,  lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase     =			3
        lowerCAmelCase     =			'multi_label_classification'
        lowerCAmelCase     =			input_dict['input_ids']
        lowerCAmelCase     =			input_ids.ne(1    ).to(UpperCAmelCase__    )
        lowerCAmelCase     =			ids_tensor(
            [self.model_tester.batch_size, config.num_labels]    ,      self.model_tester.type_sequence_label_size    ).to(torch.float    )
        lowerCAmelCase     =			FalconForSequenceClassification(UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      attention_mask=UpperCAmelCase__    ,      labels=UpperCAmelCase__    )
        self.assertEqual(result.logits.shape    ,      (self.model_tester.batch_size, self.model_tester.num_labels)    )





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  Optional[Any]:
        # Falcon can have different numbers of KV-heads than the number of query heads, so we need
        # to override this test to use the right head counts.
        for model_class in self.all_generative_model_classes:
           lowerCAmelCase     ,  lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs_for_common()

           # If it doesn't support cache, pass the test
           if not hasattr(UpperCAmelCase__    ,      'use_cache'    ):
              return

           lowerCAmelCase     =			model_class(UpperCAmelCase__    ).to(UpperCAmelCase__    )
           if "use_cache" not in inputs:
              lowerCAmelCase     =			True
           lowerCAmelCase     =			model(**UpperCAmelCase__    )

           # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
           if "past_key_values" not in outputs:
              return

           lowerCAmelCase     =			(
               getattr(UpperCAmelCase__    ,      'decoder_layers'    ,      UpperCAmelCase__    )
               or getattr(UpperCAmelCase__    ,      'num_decoder_layers'    ,      UpperCAmelCase__    )
               or config.num_hidden_layers
           )
           lowerCAmelCase     =			getattr(UpperCAmelCase__    ,      'num_kv_heads'    ,      config.num_attention_heads    )
           lowerCAmelCase     =			getattr(UpperCAmelCase__    ,      'd_model'    ,      config.hidden_size    )
           lowerCAmelCase     =			embed_dim // num_attention_heads

           lowerCAmelCase     =			outputs['past_key_values']
           self.assertEqual(len(UpperCAmelCase__    )    ,      UpperCAmelCase__    )

           lowerCAmelCase     ,  lowerCAmelCase     =			inputs['input_ids'].shape
           for i in range(UpperCAmelCase__    ):
              if config.new_decoder_architecture:
                 lowerCAmelCase     =			config.num_attention_heads
              elif config.multi_query:
                 lowerCAmelCase     =			1
              self.assertEqual(len(past_kv[0]    )    ,      2    )  # K V for the decoder = 2
              self.assertEqual(
                  past_kv[i][0].shape    ,      (batch_size, num_attention_heads, seq_length, per_head_embed_dim)    )
              self.assertEqual(
                  past_kv[i][1].shape    ,      (batch_size, num_attention_heads, seq_length, per_head_embed_dim)    )




@require_torch
class 		UpperCAmelCase_      (  unittest.TestCase		):





     @slow
     def 							__UpperCAmelCase      ( self       :      Optional[int]    )				->  List[str]:
        lowerCAmelCase     =			AutoTokenizer.from_pretrained('Rocketknight1/falcon-rw-1b'    )
        lowerCAmelCase     =			FalconForCausalLM.from_pretrained('Rocketknight1/falcon-rw-1b'    )
        model.eval()
        model.to(UpperCAmelCase__    )
        lowerCAmelCase     =			tokenizer('My favorite food is'    ,      return_tensors='pt'    ).to(UpperCAmelCase__    )

        lowerCAmelCase     =			(
            'My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.'
        )

        lowerCAmelCase     =			model.generate(**UpperCAmelCase__    ,      do_sample=UpperCAmelCase__    ,      max_new_tokens=1_9    )
        lowerCAmelCase     =			tokenizer.batch_decode(UpperCAmelCase__    )[0]

        self.assertEqual(UpperCAmelCase__    ,      UpperCAmelCase__    )





     @slow
     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  List[Any]:
        # The big models are way too big for the CI, so we use tiny random models that resemble their
        # architectures but with much smaller and fewer layers
        for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
           lowerCAmelCase     =			AutoTokenizer.from_pretrained(UpperCAmelCase__    )
           lowerCAmelCase     =			FalconForCausalLM.from_pretrained(UpperCAmelCase__    )
           model.eval()
           model.to(UpperCAmelCase__    )
           lowerCAmelCase     =			tokenizer('My favorite food is'    ,      return_tensors='pt'    ).to(UpperCAmelCase__    )

           # We just test that these run without errors - the models are randomly initialized
           # and so the actual text outputs will be garbage
           model.generate(**UpperCAmelCase__    ,      do_sample=UpperCAmelCase__    ,      max_new_tokens=4    )
           model.generate(**UpperCAmelCase__    ,      do_sample=UpperCAmelCase__    ,      max_new_tokens=4    )
           model.generate(**UpperCAmelCase__    ,      num_beams=2    ,      max_new_tokens=4    )





     @slow
     def 							__UpperCAmelCase      ( self       :      Dict    )				->  Any:
        # The big models are way too big for the CI, so we use tiny random models that resemble their
        # architectures but with much smaller and fewer layers
        with torch.no_grad():
           for repo in [
               "Rocketknight1/falcon-rw-1b",
               "Rocketknight1/tiny-random-falcon-7b",
               "Rocketknight1/tiny-random-falcon-40b",
           ]:
              lowerCAmelCase     =			AutoTokenizer.from_pretrained(UpperCAmelCase__    )
              lowerCAmelCase     =			FalconForCausalLM.from_pretrained(UpperCAmelCase__    )
              model.eval()
              model.to(device=UpperCAmelCase__    )
              lowerCAmelCase     =			tokenizer('My favorite food is'    ,      return_tensors='pt'    ).to(UpperCAmelCase__    )

              # Test results are the same with and without cache
              lowerCAmelCase     =			model.generate(**UpperCAmelCase__    ,      do_sample=UpperCAmelCase__    ,      max_new_tokens=2_0    ,      use_cache=UpperCAmelCase__    )
              lowerCAmelCase     =			model.generate(**UpperCAmelCase__    ,      do_sample=UpperCAmelCase__    ,      max_new_tokens=2_0    ,      use_cache=UpperCAmelCase__    )
              self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0    )













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

				"""simple docstring"""




				def __init__(     self						:    Optional[Any],  lowerCamelCase						:    Optional[int],  lowerCamelCase						:    str=14,  lowerCamelCase						:    List[str]=7,  lowerCamelCase						:    Dict=True,  lowerCamelCase						:    List[str]=True,  lowerCamelCase						:    Optional[Any]=True,  lowerCamelCase						:    Optional[Any]=True,  lowerCamelCase						:    Any=True,  lowerCamelCase						:    List[str]=99,  lowerCamelCase						:    Optional[Any]=32,  lowerCamelCase						:    Optional[int]=5,  lowerCamelCase						:    List[Any]=4,  lowerCamelCase						:    List[Any]=37,  lowerCamelCase						:    List[str]="gelu",  lowerCamelCase						:    Any=0.1,  lowerCamelCase						:    Optional[Any]=0.1,  lowerCamelCase						:    List[Any]=512,  lowerCamelCase						:    List[str]=16,  lowerCamelCase						:    Dict=2,  lowerCamelCase						:    Union[str, Any]=0.02,  lowerCamelCase						:    Optional[int]=3,  lowerCamelCase						:    Dict=4,  lowerCamelCase						:    List[Any]=None,  ):

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




				def 				lowercase__   (     self						:    Optional[int]  ):

								'''simple docstring'''
								lowercase__    =			ids_tensor([self.batch_size, self.seq_length],  self.vocab_size  )

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

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

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

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

								lowercase__    =			self.get_config()

								lowercase__    =			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 				lowercase__   (     self						:    Optional[int]  ):

								'''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 				lowercase__   (     self						:    Union[str, Any],  lowerCamelCase						:    Any,  lowerCamelCase						:    Tuple,  lowerCamelCase						:    Any,  lowerCamelCase						:    List[Any],  lowerCamelCase						:    Union[str, Any],  *lowerCamelCase						:    Dict  ):

								'''simple docstring'''
								lowercase__    =			CTRLModel(config=lowerCamelCase  )
								model.to(lowerCamelCase  )
								model.eval()

								model(lowerCamelCase,  token_type_ids=lowerCamelCase,  head_mask=lowerCamelCase  )
								model(lowerCamelCase,  token_type_ids=lowerCamelCase  )
								lowercase__    =			model(lowerCamelCase  )
								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 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    Union[str, Any],  lowerCamelCase						:    Tuple,  lowerCamelCase						:    Union[str, Any],  lowerCamelCase						:    Union[str, Any],  lowerCamelCase						:    Optional[int],  *lowerCamelCase						:    Any  ):

								'''simple docstring'''
								lowercase__    =			CTRLLMHeadModel(lowerCamelCase  )
								model.to(lowerCamelCase  )
								model.eval()

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




				def 				lowercase__   (     self						:    Dict  ):

								'''simple docstring'''
								lowercase__    =			self.prepare_config_and_inputs()

								(
								    (
								    lowercase__
								) ,						(
								    lowercase__
								) ,						(
								    lowercase__
								) ,						(
								    lowercase__
								) ,						(
								    lowercase__
								) ,						(
								    lowercase__
								) ,						(
								    lowercase__
								) ,						(
								    lowercase__
								) ,						(
								    lowercase__
								) ,						
								)    =			config_and_inputs

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

								return config, inputs_dict




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    Tuple,  lowerCamelCase						:    Optional[Any],  lowerCamelCase						:    int,  lowerCamelCase						:    Any,  *lowerCamelCase						:    int  ):

								'''simple docstring'''
								lowercase__    =			self.num_labels
								lowercase__    =			CTRLForSequenceClassification(lowerCamelCase  )
								model.to(lowerCamelCase  )
								model.eval()
								lowercase__    =			ids_tensor([self.batch_size],  self.type_sequence_label_size  )
								lowercase__    =			model(lowerCamelCase,  token_type_ids=lowerCamelCase,  labels=lowerCamelCase  )
								self.parent.assertEqual(result.logits.shape,  (self.batch_size, self.num_labels)  )



@require_torch
class       _UpperCAmelCase					(       A__		,A__		,A__		,unittest.TestCase	):

				"""simple docstring"""




				lowercase__											=       (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
				lowercase__											=       (CTRLLMHeadModel,) if is_torch_available() else ()
				lowercase__											=       (
				    {
				        """feature-extraction""": CTRLModel,
				        """text-classification""": CTRLForSequenceClassification,
				        """text-generation""": CTRLLMHeadModel,
				        """zero-shot""": CTRLForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)
				lowercase__											=       True
				lowercase__											=       False
				lowercase__											=       False




				def 				lowercase__   (     self						:    Dict,  lowerCamelCase						:    Optional[int],  lowerCamelCase						:    str,  lowerCamelCase						:    Any,  lowerCamelCase						:    List[str],  lowerCamelCase						:    Optional[Any]  ):

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

								'''simple docstring'''
								lowercase__    =			CTRLModelTester(self  )
								lowercase__    =			ConfigTester(self,  config_class=lowerCamelCase,  n_embd=37  )




				def 				lowercase__   (     self						:    Tuple  ):

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




				def 				lowercase__   (     self						:    int  ):

								'''simple docstring'''
								self.config_tester.run_common_tests()




				def 				lowercase__   (     self						:    str  ):

								'''simple docstring'''
								lowercase__    =			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_ctrl_model(*lowerCamelCase  )




				def 				lowercase__   (     self						:    List[Any]  ):

								'''simple docstring'''
								lowercase__    =			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_lm_head_model(*lowerCamelCase  )




				@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''  )
				def 				lowercase__   (     self						:    Union[str, Any]  ):

								'''simple docstring'''
								pass




				@slow
				def 				lowercase__   (     self						:    Any  ):

								'''simple docstring'''
								for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												lowercase__    =			CTRLModel.from_pretrained(lowerCamelCase  )
												self.assertIsNotNone(lowerCamelCase  )




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

								'''simple docstring'''
								pass



@require_torch
class       _UpperCAmelCase					(       unittest.TestCase	):

				"""simple docstring"""




				def 				lowercase__   (     self						:    Any  ):

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




				@slow
				def 				lowercase__   (     self						:    int  ):

								'''simple docstring'''
								lowercase__    =			CTRLLMHeadModel.from_pretrained('''ctrl'''  )
								model.to(lowerCamelCase  )
								lowercase__    =			torch.tensor(
								    [[11_859, 0, 1_611, 8]],  dtype=torch.long,  device=lowerCamelCase  )  # Legal the president is
								lowercase__    =			[
								    11_859,
								    0,
								    1_611,
								    8,
								    5,
								    150,
								    26_449,
								    2,
								    19,
								    348,
								    469,
								    3,
								    2_595,
								    48,
								    20_740,
								    246_533,
								    246_533,
								    19,
								    30,
								    5,
								]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

								lowercase__    =			model.generate(lowerCamelCase,  do_sample=lowerCamelCase  )
								self.assertListEqual(output_ids[0].tolist(),  lowerCamelCase  )




