
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				,       UpperCamelCase__				,       UpperCamelCase__=14				,       UpperCamelCase__=7				,       UpperCamelCase__=True				,       UpperCamelCase__=True				,       UpperCamelCase__=True				,       UpperCamelCase__=True				,       UpperCamelCase__=True				,       UpperCamelCase__=99				,       UpperCamelCase__=32				,       UpperCamelCase__=5				,       UpperCamelCase__=4				,       UpperCamelCase__=37				,       UpperCamelCase__="gelu"				,       UpperCamelCase__=0.1				,       UpperCamelCase__=0.1				,       UpperCamelCase__=512				,       UpperCamelCase__=16				,       UpperCamelCase__=2				,       UpperCamelCase__=0.0_2				,       UpperCamelCase__=3				,       UpperCamelCase__=4				,       UpperCamelCase__=None				,       ):
					A__         =							parent
					A__         =							batch_size
					A__         =							seq_length
					A__         =							is_training
					A__         =							use_token_type_ids
					A__         =							use_input_mask
					A__         =							use_labels
					A__         =							use_mc_token_ids
					A__         =							vocab_size
					A__         =							hidden_size
					A__         =							num_hidden_layers
					A__         =							num_attention_heads
					A__         =							intermediate_size
					A__         =							hidden_act
					A__         =							hidden_dropout_prob
					A__         =							attention_probs_dropout_prob
					A__         =							max_position_embeddings
					A__         =							type_vocab_size
					A__         =							type_sequence_label_size
					A__         =							initializer_range
					A__         =							num_labels
					A__         =							num_choices
					A__         =							scope
					A__         =							self.vocab_size - 1





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

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

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

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

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

					A__         =							self.get_config()

					A__         =							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   __snake_case				(			self		):
					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   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       *UpperCamelCase__		):
					A__         =							CTRLModel(config=__lowerCamelCase		)
					model.to(__lowerCamelCase		)
					model.eval()

					model(__lowerCamelCase				,       token_type_ids=__lowerCamelCase				,       head_mask=__lowerCamelCase		)
					model(__lowerCamelCase				,       token_type_ids=__lowerCamelCase		)
					A__         =							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   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       *UpperCamelCase__		):
					A__         =							CTRLLMHeadModel(__lowerCamelCase		)
					model.to(__lowerCamelCase		)
					model.eval()

					A__         =							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   __snake_case				(			self		):
					A__         =							self.prepare_config_and_inputs()

					(
					    A__     
					)         =							config_and_inputs

					A__         =							{"input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask}

					return config, inputs_dict





	def   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       *UpperCamelCase__		):
					A__         =							self.num_labels
					A__         =							CTRLForSequenceClassification(__lowerCamelCase		)
					model.to(__lowerCamelCase		)
					model.eval()
					A__         =							ids_tensor([self.batch_size]				,       self.type_sequence_label_size		)
					A__         =							model(__lowerCamelCase				,       token_type_ids=__lowerCamelCase				,       labels=__lowerCamelCase		)
					self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.num_labels)		)







@require_torch
class  UpperCamelCase__		(    lowercase__,			lowercase__,			lowercase__,			unittest.TestCase   ):







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





	def   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__		):



					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   __snake_case				(			self		):
					A__         =							CTRLModelTester(self		)
					A__         =							ConfigTester(self				,       config_class=__lowerCamelCase				,       n_embd=37		)





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





	def   __snake_case				(			self		):
					self.config_tester.run_common_tests()





	def   __snake_case				(			self		):
					A__         =							self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_ctrl_model(*__lowerCamelCase		)





	def   __snake_case				(			self		):
					A__         =							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   __snake_case				(			self		):
					pass





	@slow
	def   __snake_case				(			self		):



					for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									A__         =							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   __snake_case				(			self		):
					pass







@require_torch
class  UpperCamelCase__		(    unittest.TestCase   ):







	'''simple docstring'''





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





	@slow
	def   __snake_case				(			self		):
					A__         =							CTRLLMHeadModel.from_pretrained('''ctrl'''		)
					model.to(__lowerCamelCase		)
					A__         =							torch.tensor(
					    [[1_1859, 0, 1611, 8]]				,       dtype=torch.long				,       device=__lowerCamelCase		)  # Legal the president is
					A__         =							[
					    1_1859,
					    0,
					    1611,
					    8,
					    5,
					    150,
					    2_6449,
					    2,
					    19,
					    348,
					    469,
					    3,
					    2595,
					    48,
					    2_0740,
					    24_6533,
					    24_6533,
					    19,
					    30,
					    5,
					]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

					A__         =							model.generate(__lowerCamelCase				,       do_sample=__lowerCamelCase		)
					self.assertListEqual(output_ids[0].tolist()				,       __lowerCamelCase		)

from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tensorflow_text_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


_SCREAMING_SNAKE_CASE    :      int          =			{
    'configuration_bert': ['BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BertConfig', 'BertOnnxConfig'],
    'tokenization_bert': ['BasicTokenizer', 'BertTokenizer', 'WordpieceTokenizer'],
}

try:
					if not is_tokenizers_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					_SCREAMING_SNAKE_CASE    :      Optional[Any]          =			['BertTokenizerFast']

try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					_SCREAMING_SNAKE_CASE    :      Union[str, Any]          =			[
					    'BERT_PRETRAINED_MODEL_ARCHIVE_LIST',
					    'BertForMaskedLM',
					    'BertForMultipleChoice',
					    'BertForNextSentencePrediction',
					    'BertForPreTraining',
					    'BertForQuestionAnswering',
					    'BertForSequenceClassification',
					    'BertForTokenClassification',
					    'BertLayer',
					    'BertLMHeadModel',
					    'BertModel',
					    'BertPreTrainedModel',
					    'load_tf_weights_in_bert',
					]

try:
					if not is_tf_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					_SCREAMING_SNAKE_CASE    :      Tuple          =			[
					    'TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST',
					    'TFBertEmbeddings',
					    'TFBertForMaskedLM',
					    'TFBertForMultipleChoice',
					    'TFBertForNextSentencePrediction',
					    'TFBertForPreTraining',
					    'TFBertForQuestionAnswering',
					    'TFBertForSequenceClassification',
					    'TFBertForTokenClassification',
					    'TFBertLMHeadModel',
					    'TFBertMainLayer',
					    'TFBertModel',
					    'TFBertPreTrainedModel',
					]
try:
					if not is_tensorflow_text_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					_SCREAMING_SNAKE_CASE    :      Dict          =			['TFBertTokenizer']

try:
					if not is_flax_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					_SCREAMING_SNAKE_CASE    :      Optional[int]          =			[
					    'FlaxBertForCausalLM',
					    'FlaxBertForMaskedLM',
					    'FlaxBertForMultipleChoice',
					    'FlaxBertForNextSentencePrediction',
					    'FlaxBertForPreTraining',
					    'FlaxBertForQuestionAnswering',
					    'FlaxBertForSequenceClassification',
					    'FlaxBertForTokenClassification',
					    'FlaxBertModel',
					    'FlaxBertPreTrainedModel',
					]

if TYPE_CHECKING:
					from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig
					from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer

					try:
										if not is_tokenizers_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .tokenization_bert_fast import BertTokenizerFast

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_bert import (
										    BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
										    BertForMaskedLM,
										    BertForMultipleChoice,
										    BertForNextSentencePrediction,
										    BertForPreTraining,
										    BertForQuestionAnswering,
										    BertForSequenceClassification,
										    BertForTokenClassification,
										    BertLayer,
										    BertLMHeadModel,
										    BertModel,
										    BertPreTrainedModel,
										    load_tf_weights_in_bert,
										)

					try:
										if not is_tf_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_tf_bert import (
										    TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
										    TFBertEmbeddings,
										    TFBertForMaskedLM,
										    TFBertForMultipleChoice,
										    TFBertForNextSentencePrediction,
										    TFBertForPreTraining,
										    TFBertForQuestionAnswering,
										    TFBertForSequenceClassification,
										    TFBertForTokenClassification,
										    TFBertLMHeadModel,
										    TFBertMainLayer,
										    TFBertModel,
										    TFBertPreTrainedModel,
										)

					try:
										if not is_tensorflow_text_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .tokenization_bert_tf import TFBertTokenizer

					try:
										if not is_flax_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_flax_bert import (
										    FlaxBertForCausalLM,
										    FlaxBertForMaskedLM,
										    FlaxBertForMultipleChoice,
										    FlaxBertForNextSentencePrediction,
										    FlaxBertForPreTraining,
										    FlaxBertForQuestionAnswering,
										    FlaxBertForSequenceClassification,
										    FlaxBertForTokenClassification,
										    FlaxBertModel,
										    FlaxBertPreTrainedModel,
										)

else:
					import sys

					_SCREAMING_SNAKE_CASE    :      Union[str, Any]          =			_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)