




"""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  lowercase:







 '''simple docstring'''





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




   '''simple docstring'''



   _snake_case							:		int								=  parent
   _snake_case							:		Union[str, Any]								=  batch_size
   _snake_case							:		List[str]								=  seq_length
   _snake_case							:		Optional[int]								=  is_training
   _snake_case							:		int								=  use_token_type_ids
   _snake_case							:		int								=  use_input_mask
   _snake_case							:		Any								=  use_labels
   _snake_case							:		int								=  use_mc_token_ids
   _snake_case							:		Optional[Any]								=  vocab_size
   _snake_case							:		List[str]								=  hidden_size
   _snake_case							:		List[Any]								=  num_hidden_layers
   _snake_case							:		Any								=  num_attention_heads
   _snake_case							:		List[str]								=  intermediate_size
   _snake_case							:		Tuple								=  hidden_act
   _snake_case							:		Tuple								=  hidden_dropout_prob
   _snake_case							:		Tuple								=  attention_probs_dropout_prob
   _snake_case							:		Union[str, Any]								=  max_position_embeddings
   _snake_case							:		Tuple								=  type_vocab_size
   _snake_case							:		Optional[Any]								=  type_sequence_label_size
   _snake_case							:		List[Any]								=  initializer_range
   _snake_case							:		Any								=  num_labels
   _snake_case							:		str								=  num_choices
   _snake_case							:		str								=  scope
   _snake_case							:		List[Any]								=  self.vocab_size - 1


 def 			UpperCamelCase_       (    self:		Dict		):




   '''simple docstring'''



   _snake_case							:		Optional[int]								=  ids_tensor([self.batch_size, self.seq_length],				self.vocab_size		)

   _snake_case							:		int								=  None
   if self.use_input_mask:
     _snake_case							:		Union[str, Any]								=  random_attention_mask([self.batch_size, self.seq_length]		)

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

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

   _snake_case							:		str								=  None
   _snake_case							:		Optional[int]								=  None
   _snake_case							:		Optional[int]								=  None
   if self.use_labels:
     _snake_case							:		str								=  ids_tensor([self.batch_size],				self.type_sequence_label_size		)
     _snake_case							:		int								=  ids_tensor([self.batch_size, self.seq_length],				self.num_labels		)
     _snake_case							:		List[Any]								=  ids_tensor([self.batch_size],				self.num_choices		)

   _snake_case							:		List[Any]								=  self.get_config()

   _snake_case							:		Any								=  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 			UpperCamelCase_       (    self:		str		):




   '''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 			UpperCamelCase_       (    self:		Dict,				a_:		str,				a_:		Dict,				a_:		Any,				a_:		str,				a_:		Dict,				*a_:		Union[str, Any]		):




   '''simple docstring'''



   _snake_case							:		int								=  CTRLModel(config=a_		)
   model.to(a_		)
   model.eval()

   model(a_,				token_type_ids=a_,				head_mask=a_		)
   model(a_,				token_type_ids=a_		)
   _snake_case							:		List[Any]								=  model(a_		)
   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 			UpperCamelCase_       (    self:		List[str],				a_:		Dict,				a_:		Union[str, Any],				a_:		List[str],				a_:		List[str],				a_:		Optional[Any],				*a_:		int		):




   '''simple docstring'''



   _snake_case							:		Any								=  CTRLLMHeadModel(a_		)
   model.to(a_		)
   model.eval()

   _snake_case							:		Union[str, Any]								=  model(a_,				token_type_ids=a_,				labels=a_		)
   self.parent.assertEqual(result.loss.shape,				()		)
   self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.seq_length, self.vocab_size)		)


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




   '''simple docstring'''



   _snake_case							:		Any								=  self.prepare_config_and_inputs()

   (
       _snake_case  
   )							:		List[Any]								=  config_and_inputs

   _snake_case							:		str								=  {"input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask}

   return config, inputs_dict


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




   '''simple docstring'''



   _snake_case							:		Optional[Any]								=  self.num_labels
   _snake_case							:		Any								=  CTRLForSequenceClassification(a_		)
   model.to(a_		)
   model.eval()
   _snake_case							:		int								=  ids_tensor([self.batch_size],				self.type_sequence_label_size		)
   _snake_case							:		str								=  model(a_,				token_type_ids=a_,				labels=a_		)
   self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.num_labels)		)







@require_torch
class  lowercase(					lowerCamelCase__	,      lowerCamelCase__	,      lowerCamelCase__	,      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 			UpperCamelCase_       (    self:		str,				a_:		Optional[int],				a_:		List[str],				a_:		Any,				a_:		Optional[int],				a_:		List[str]		):




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




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  CTRLModelTester(self		)
   _snake_case							:		Union[str, Any]								=  ConfigTester(self,				config_class=a_,				n_embd=37		)


 def 			UpperCamelCase_       (    self:		Optional[Any]		):




   '''simple docstring'''



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


 def 			UpperCamelCase_       (    self:		int		):




   '''simple docstring'''



   self.config_tester.run_common_tests()


 def 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



   _snake_case							:		Optional[Any]								=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_ctrl_model(*a_		)


 def 			UpperCamelCase_       (    self:		Dict		):




   '''simple docstring'''



   _snake_case							:		int								=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_lm_head_model(*a_		)


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




   '''simple docstring'''



   pass


 @slow
 def 			UpperCamelCase_       (    self:		List[str]		):




   '''simple docstring'''



   for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     _snake_case							:		str								=  CTRLModel.from_pretrained(a_		)
     self.assertIsNotNone(a_		)


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




   '''simple docstring'''



   pass







@require_torch
class  lowercase(					unittest.TestCase			):







 '''simple docstring'''





 def 			UpperCamelCase_       (    self:		List[Any]		):




   '''simple docstring'''



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


 @slow
 def 			UpperCamelCase_       (    self:		List[Any]		):




   '''simple docstring'''



   _snake_case							:		Optional[int]								=  CTRLLMHeadModel.from_pretrained("""ctrl"""		)
   model.to(a_		)
   _snake_case							:		List[str]								=  torch.tensor(
       [[11_859, 0, 1_611, 8]],				dtype=torch.long,				device=a_		)  # Legal the president is
   _snake_case							:		Optional[Any]								=  [
       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

   _snake_case							:		str								=  model.generate(a_,				do_sample=a_		)
   self.assertListEqual(output_ids[0].tolist(),				a_		)







"""simple docstring"""


from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


A_      =    {
    '''configuration_maskformer''': ['''MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MaskFormerConfig'''],
    '''configuration_maskformer_swin''': ['''MaskFormerSwinConfig'''],
}

try:
     if not is_vision_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     A_      =    ['''MaskFormerFeatureExtractor''']
     A_      =    ['''MaskFormerImageProcessor''']


try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     A_      =    [
         '''MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
         '''MaskFormerForInstanceSegmentation''',
         '''MaskFormerModel''',
         '''MaskFormerPreTrainedModel''',
     ]
     A_      =    [
         '''MaskFormerSwinBackbone''',
         '''MaskFormerSwinModel''',
         '''MaskFormerSwinPreTrainedModel''',
     ]

if TYPE_CHECKING:
     from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig
     from .configuration_maskformer_swin import MaskFormerSwinConfig

     try:
          if not is_vision_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .feature_extraction_maskformer import MaskFormerFeatureExtractor
          from .image_processing_maskformer import MaskFormerImageProcessor
     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_maskformer import (
              MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
              MaskFormerForInstanceSegmentation,
              MaskFormerModel,
              MaskFormerPreTrainedModel,
          )
          from .modeling_maskformer_swin import (
              MaskFormerSwinBackbone,
              MaskFormerSwinModel,
              MaskFormerSwinPreTrainedModel,
          )


else:
     import sys

     A_      =    _LazyModule(__name__, globals()['''__file__'''], _import_structure)


