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







							def __init__(				self     :    Dict	,					__snake_case     :    int	,					__snake_case     :    Optional[int]=14	,					__snake_case     :    Dict=7	,					__snake_case     :    str=True	,					__snake_case     :    int=True	,					__snake_case     :    Optional[int]=True	,					__snake_case     :    Optional[int]=True	,					__snake_case     :    List[Any]=True	,					__snake_case     :    Union[str, Any]=99	,					__snake_case     :    Dict=32	,					__snake_case     :    List[Any]=5	,					__snake_case     :    Tuple=4	,					__snake_case     :    List[str]=37	,					__snake_case     :    str="gelu"	,					__snake_case     :    List[Any]=0.1	,					__snake_case     :    int=0.1	,					__snake_case     :    List[Any]=512	,					__snake_case     :    Any=16	,					__snake_case     :    int=2	,					__snake_case     :    Union[str, Any]=0.0_2	,					__snake_case     :    Optional[int]=3	,					__snake_case     :    Any=4	,					__snake_case     :    str=None	,					):
										lowerCamelCase						:Any						  =     parent
										lowerCamelCase						:List[str]						  =     batch_size
										lowerCamelCase						:Union[str, Any]						  =     seq_length
										lowerCamelCase						:int						  =     is_training
										lowerCamelCase						:Optional[int]						  =     use_token_type_ids
										lowerCamelCase						:Optional[int]						  =     use_input_mask
										lowerCamelCase						:Dict						  =     use_labels
										lowerCamelCase						:Any						  =     use_mc_token_ids
										lowerCamelCase						:str						  =     vocab_size
										lowerCamelCase						:Optional[int]						  =     hidden_size
										lowerCamelCase						:str						  =     num_hidden_layers
										lowerCamelCase						:Union[str, Any]						  =     num_attention_heads
										lowerCamelCase						:Optional[Any]						  =     intermediate_size
										lowerCamelCase						:Dict						  =     hidden_act
										lowerCamelCase						:List[str]						  =     hidden_dropout_prob
										lowerCamelCase						:Optional[Any]						  =     attention_probs_dropout_prob
										lowerCamelCase						:Optional[int]						  =     max_position_embeddings
										lowerCamelCase						:Tuple						  =     type_vocab_size
										lowerCamelCase						:int						  =     type_sequence_label_size
										lowerCamelCase						:Any						  =     initializer_range
										lowerCamelCase						:List[str]						  =     num_labels
										lowerCamelCase						:Any						  =     num_choices
										lowerCamelCase						:Union[str, Any]						  =     scope
										lowerCamelCase						:int						  =     self.vocab_size - 1







							def 				snake_case  (				self     :    int		):
										lowerCamelCase						:Any						  =     ids_tensor([self.batch_size, self.seq_length]	,					self.vocab_size		)

										lowerCamelCase						:str						  =     None
										if self.use_input_mask:
													lowerCamelCase						:List[Any]						  =     random_attention_mask([self.batch_size, self.seq_length]		)

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

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

										lowerCamelCase						:List[str]						  =     None
										lowerCamelCase						:Any						  =     None
										lowerCamelCase						:List[Any]						  =     None
										if self.use_labels:
													lowerCamelCase						:Any						  =     ids_tensor([self.batch_size]	,					self.type_sequence_label_size		)
													lowerCamelCase						:Union[str, Any]						  =     ids_tensor([self.batch_size, self.seq_length]	,					self.num_labels		)
													lowerCamelCase						:Dict						  =     ids_tensor([self.batch_size]	,					self.num_choices		)

										lowerCamelCase						:Tuple						  =     self.get_config()

										lowerCamelCase						:List[str]						  =     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     :    Any		):
										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     :    str	,					__snake_case     :    List[str]	,					__snake_case     :    int	,					__snake_case     :    Any	,					__snake_case     :    List[str]	,					__snake_case     :    Dict	,					*__snake_case     :    List[str]		):
										lowerCamelCase						:Dict						  =     CTRLModel(config=__snake_case		)
										model.to(__snake_case		)
										model.eval()

										model(__snake_case	,					token_type_ids=__snake_case	,					head_mask=__snake_case		)
										model(__snake_case	,					token_type_ids=__snake_case		)
										lowerCamelCase						:Dict						  =     model(__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 				snake_case  (				self     :    str	,					__snake_case     :    Dict	,					__snake_case     :    Dict	,					__snake_case     :    Optional[int]	,					__snake_case     :    Tuple	,					__snake_case     :    Dict	,					*__snake_case     :    str		):
										lowerCamelCase						:List[str]						  =     CTRLLMHeadModel(__snake_case		)
										model.to(__snake_case		)
										model.eval()

										lowerCamelCase						:Optional[Any]						  =     model(__snake_case	,					token_type_ids=__snake_case	,					labels=__snake_case		)
										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     :    List[Any]		):
										lowerCamelCase						:List[str]						  =     self.prepare_config_and_inputs()

										(
										    (
										    lowerCamelCase
										)  ,    (
										    lowerCamelCase
										)  ,    (
										    lowerCamelCase
										)  ,    (
										    lowerCamelCase
										)  ,    (
										    lowerCamelCase
										)  ,    (
										    lowerCamelCase
										)  ,    (
										    lowerCamelCase
										)  ,    (
										    lowerCamelCase
										)  ,    (
										    lowerCamelCase
										)  ,    
										)						:Optional[int]						  =     config_and_inputs

										lowerCamelCase						:str						  =     {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask}

										return config, inputs_dict







							def 				snake_case  (				self     :    int	,					__snake_case     :    Optional[int]	,					__snake_case     :    List[Any]	,					__snake_case     :    int	,					__snake_case     :    List[Any]	,					*__snake_case     :    str		):
										lowerCamelCase						:Tuple						  =     self.num_labels
										lowerCamelCase						:Optional[int]						  =     CTRLForSequenceClassification(__snake_case		)
										model.to(__snake_case		)
										model.eval()
										lowerCamelCase						:Any						  =     ids_tensor([self.batch_size]	,					self.type_sequence_label_size		)
										lowerCamelCase						:List[str]						  =     model(__snake_case	,					token_type_ids=__snake_case	,					labels=__snake_case		)
										self.parent.assertEqual(result.logits.shape	,					(self.batch_size, self.num_labels)		)


@require_torch
class   _lowerCAmelCase		(     __SCREAMING_SNAKE_CASE      ,   __SCREAMING_SNAKE_CASE      ,   __SCREAMING_SNAKE_CASE      ,   unittest.TestCase				):
							_UpperCAmelCase						    =     (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
							_UpperCAmelCase						    =     (CTRLLMHeadModel,) if is_torch_available() else ()
							_UpperCAmelCase						    =     (
							    {
							        'feature-extraction': CTRLModel,
							        'text-classification': CTRLForSequenceClassification,
							        'text-generation': CTRLLMHeadModel,
							        'zero-shot': CTRLForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							_UpperCAmelCase						    =     True
							_UpperCAmelCase						    =     False
							_UpperCAmelCase						    =     False







							def 				snake_case  (				self     :    str	,					__snake_case     :    int	,					__snake_case     :    int	,					__snake_case     :    str	,					__snake_case     :    List[str]	,					__snake_case     :    Optional[int]		):
										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     :    str		):
										lowerCamelCase						:List[str]						  =     CTRLModelTester(self		)
										lowerCamelCase						:Tuple						  =     ConfigTester(self	,					config_class=__snake_case	,					n_embd=37		)







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







							def 				snake_case  (				self     :    List[Any]		):
										self.config_tester.run_common_tests()







							def 				snake_case  (				self     :    List[str]		):
										lowerCamelCase						:int						  =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_ctrl_model(*__snake_case		)







							def 				snake_case  (				self     :    Union[str, Any]		):
										lowerCamelCase						:str						  =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_lm_head_model(*__snake_case		)







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







							@slow
							def 				snake_case  (				self     :    Union[str, Any]		):
										for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													lowerCamelCase						:Dict						  =     CTRLModel.from_pretrained(__snake_case		)
													self.assertIsNotNone(__snake_case		)







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


@require_torch
class   _lowerCAmelCase		(     unittest.TestCase				):







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







							@slow
							def 				snake_case  (				self     :    Union[str, Any]		):
										lowerCamelCase						:Tuple						  =     CTRLLMHeadModel.from_pretrained('''ctrl'''		)
										model.to(__snake_case		)
										lowerCamelCase						:Any						  =     torch.tensor(
										    [[11859, 0, 1611, 8]]	,					dtype=torch.long	,					device=__snake_case		)  # Legal the president is
										lowerCamelCase						:List[str]						  =     [
										    11859,
										    0,
										    1611,
										    8,
										    5,
										    150,
										    26449,
										    2,
										    19,
										    348,
										    469,
										    3,
										    2595,
										    48,
										    20740,
										    246533,
										    246533,
										    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						:int						  =     model.generate(__snake_case	,					do_sample=__snake_case		)
										self.assertListEqual(output_ids[0].tolist()	,					__snake_case		)




from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


A__           =							{
    """configuration_nllb_moe""": [
        """NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """NllbMoeConfig""",
    ]
}

try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A__           =							[
			    """NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST""",
			    """NllbMoeForConditionalGeneration""",
			    """NllbMoeModel""",
			    """NllbMoePreTrainedModel""",
			    """NllbMoeTop2Router""",
			    """NllbMoeSparseMLP""",
			]


if TYPE_CHECKING:
			from .configuration_nllb_moe import (
			    NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP,
			    NllbMoeConfig,
			)

			try:
						if not is_torch_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_nllb_moe import (
						    NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST,
						    NllbMoeForConditionalGeneration,
						    NllbMoeModel,
						    NllbMoePreTrainedModel,
						    NllbMoeSparseMLP,
						    NllbMoeTopaRouter,
						)


else:
			import sys

			A__           =							_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



