




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



	"""simple docstring"""


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







						"""simple docstring"""







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






	def 					lowerCamelCase__     (					self		:						Union[str, Any]	)	->       Any:







						"""simple docstring"""







						__UpperCamelCase					:	Any             =      ids_tensor([self.batch_size, self.seq_length]					,     self.vocab_size	)

						__UpperCamelCase					:	int             =      None
						if self.use_input_mask:
											__UpperCamelCase					:	Dict             =      random_attention_mask([self.batch_size, self.seq_length]	)

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

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

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

						__UpperCamelCase					:	str             =      self.get_config()

						__UpperCamelCase					:	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 					lowerCamelCase__     (					self		:						Optional[Any]	)	->       List[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 					lowerCamelCase__     (					self		:						Optional[int]					,     lowerCAmelCase		:						Tuple					,     lowerCAmelCase		:						Union[str, Any]					,     lowerCAmelCase		:						Any					,     lowerCAmelCase		:						Dict					,     lowerCAmelCase		:						Optional[int]					,     *lowerCAmelCase		:						Tuple	)	->       Optional[int]:







						"""simple docstring"""







						__UpperCamelCase					:	int             =      CTRLModel(config=lowerCAmelCase	)
						model.to(lowerCAmelCase	)
						model.eval()

						model(lowerCAmelCase					,     token_type_ids=lowerCAmelCase					,     head_mask=lowerCAmelCase	)
						model(lowerCAmelCase					,     token_type_ids=lowerCAmelCase	)
						__UpperCamelCase					:	str             =      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 					lowerCamelCase__     (					self		:						Optional[int]					,     lowerCAmelCase		:						List[str]					,     lowerCAmelCase		:						Optional[Any]					,     lowerCAmelCase		:						Tuple					,     lowerCAmelCase		:						Dict					,     lowerCAmelCase		:						Optional[int]					,     *lowerCAmelCase		:						Dict	)	->       Dict:







						"""simple docstring"""







						__UpperCamelCase					:	str             =      CTRLLMHeadModel(lowerCAmelCase	)
						model.to(lowerCAmelCase	)
						model.eval()

						__UpperCamelCase					:	Tuple             =      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 					lowerCamelCase__     (					self		:						Any	)	->       Optional[int]:







						"""simple docstring"""







						__UpperCamelCase					:	Any             =      self.prepare_config_and_inputs()

						(
						    (
						    __UpperCamelCase
						)      ,			(
						    __UpperCamelCase
						)      ,			(
						    __UpperCamelCase
						)      ,			(
						    __UpperCamelCase
						)      ,			(
						    __UpperCamelCase
						)      ,			(
						    __UpperCamelCase
						)      ,			(
						    __UpperCamelCase
						)      ,			(
						    __UpperCamelCase
						)      ,			(
						    __UpperCamelCase
						)      ,			
						)					:	int             =      config_and_inputs

						__UpperCamelCase					:	List[str]             =      {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask}

						return config, inputs_dict






	def 					lowerCamelCase__     (					self		:						Dict					,     lowerCAmelCase		:						int					,     lowerCAmelCase		:						Union[str, Any]					,     lowerCAmelCase		:						int					,     lowerCAmelCase		:						str					,     *lowerCAmelCase		:						str	)	->       Union[str, Any]:







						"""simple docstring"""







						__UpperCamelCase					:	Tuple             =      self.num_labels
						__UpperCamelCase					:	Union[str, Any]             =      CTRLForSequenceClassification(lowerCAmelCase	)
						model.to(lowerCAmelCase	)
						model.eval()
						__UpperCamelCase					:	int             =      ids_tensor([self.batch_size]					,     self.type_sequence_label_size	)
						__UpperCamelCase					:	str             =      model(lowerCAmelCase					,     token_type_ids=lowerCAmelCase					,     labels=lowerCAmelCase	)
						self.parent.assertEqual(result.logits.shape					,     (self.batch_size, self.num_labels)	)






@require_torch
class    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase	,  _UpperCamelCase	,  _UpperCamelCase	,  unittest.TestCase   ):



	"""simple docstring"""


	__magic_name__   :       Dict      	=		(CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
	__magic_name__   :       Optional[int]      	=		(CTRLLMHeadModel,) if is_torch_available() else ()
	__magic_name__   :       Union[str, Any]      	=		(
	    {
	        'feature-extraction': CTRLModel,
	        'text-classification': CTRLForSequenceClassification,
	        'text-generation': CTRLLMHeadModel,
	        'zero-shot': CTRLForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	__magic_name__   :       List[Any]      	=		True
	__magic_name__   :       Optional[int]      	=		False
	__magic_name__   :       Tuple      	=		False






	def 					lowerCamelCase__     (					self		:						List[Any]					,     lowerCAmelCase		:						Optional[Any]					,     lowerCAmelCase		:						Any					,     lowerCAmelCase		:						Optional[int]					,     lowerCAmelCase		:						Any					,     lowerCAmelCase		:						List[str]	)	->       int:







						"""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 					lowerCamelCase__     (					self		:						List[str]	)	->       int:







						"""simple docstring"""







						__UpperCamelCase					:	Any             =      CTRLModelTester(self	)
						__UpperCamelCase					:	List[Any]             =      ConfigTester(self					,     config_class=lowerCAmelCase					,     n_embd=37	)






	def 					lowerCamelCase__     (					self		:						List[Any]	)	->       List[Any]:







						"""simple docstring"""







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






	def 					lowerCamelCase__     (					self		:						Tuple	)	->       Union[str, Any]:







						"""simple docstring"""







						self.config_tester.run_common_tests()






	def 					lowerCamelCase__     (					self		:						int	)	->       Tuple:







						"""simple docstring"""







						__UpperCamelCase					:	Optional[int]             =      self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_ctrl_model(*lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						Optional[int]	)	->       Dict:







						"""simple docstring"""







						__UpperCamelCase					:	str             =      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 					lowerCamelCase__     (					self		:						Optional[Any]	)	->       Union[str, Any]:







						"""simple docstring"""







						pass






	@slow
	def 					lowerCamelCase__     (					self		:						str	)	->       Union[str, Any]:







						"""simple docstring"""







						for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__UpperCamelCase					:	List[Any]             =      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 					lowerCamelCase__     (					self		:						Tuple	)	->       Union[str, Any]:







						"""simple docstring"""







						pass






@require_torch
class    SCREAMING_SNAKE_CASE_				(       unittest.TestCase   ):



	"""simple docstring"""


	def 					lowerCamelCase__     (					self		:						Optional[Any]	)	->       Union[str, Any]:







						"""simple docstring"""







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






	@slow
	def 					lowerCamelCase__     (					self		:						List[Any]	)	->       int:







						"""simple docstring"""







						__UpperCamelCase					:	Optional[int]             =      CTRLLMHeadModel.from_pretrained("""ctrl"""	)
						model.to(lowerCAmelCase	)
						__UpperCamelCase					:	Optional[int]             =      torch.tensor(
						    [[11859, 0, 1611, 8]]					,     dtype=torch.long					,     device=lowerCAmelCase	)  # Legal the president is
						__UpperCamelCase					:	int             =      [
						    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

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












# flake8: noqa
# Lint as: python3

from typing import Dict, List, Optional, Type

from .. import config
from ..utils import logging
from .formatting import (
    ArrowFormatter,
    CustomFormatter,
    Formatter,
    PandasFormatter,
    PythonFormatter,
    TensorFormatter,
    format_table,
    query_table,
)
from .np_formatter import NumpyFormatter


a__		     =     logging.get_logger(__name__)

a__		     =     {}
a__		     =     {}
a__		     =     {}





def 				A__ (snake_case   :		type		,	snake_case   :		Optional[str]		,	snake_case   :		Optional[List[str]] = None		,	)     ->						str:
					__UpperCamelCase					:	int             =      aliases if aliases is not None else []
					if format_type in _FORMAT_TYPES:
										logger.warning(
										    F'''Overwriting format type \'{format_type}\' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})'''				)
					__UpperCamelCase					:	Optional[Any]             =      formatter_cls
					for alias in set(aliases + [format_type]				):
										if alias in _FORMAT_TYPES_ALIASES:
															logger.warning(
															    F'''Overwriting format type alias \'{alias}\' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})'''				)
										__UpperCamelCase					:	Optional[int]             =      format_type





def 				A__ (snake_case   :		Exception		,	snake_case   :		Optional[str]		,	snake_case   :		Optional[List[str]] = None				)     ->						Tuple:
					__UpperCamelCase					:	List[Any]             =      aliases if aliases is not None else []
					for alias in set(aliases + [format_type]				):
										__UpperCamelCase					:	Optional[int]             =      unavailable_error


# Here we define all the available formatting functions that can be used by `Dataset.set_format`
_register_formatter(PythonFormatter, None, aliases=['''python'''])
_register_formatter(ArrowFormatter, '''arrow''', aliases=['''pa''', '''pyarrow'''])
_register_formatter(NumpyFormatter, '''numpy''', aliases=['''np'''])
_register_formatter(PandasFormatter, '''pandas''', aliases=['''pd'''])
_register_formatter(CustomFormatter, '''custom''')

if config.TORCH_AVAILABLE:
	from .torch_formatter import TorchFormatter

	_register_formatter(TorchFormatter, '''torch''', aliases=['''pt''', '''pytorch'''])
else:
	a__		     =     ValueError('''PyTorch needs to be installed to be able to return PyTorch tensors.''')
	_register_unavailable_formatter(_torch_error, '''torch''', aliases=['''pt''', '''pytorch'''])

if config.TF_AVAILABLE:
	from .tf_formatter import TFFormatter

	_register_formatter(TFFormatter, '''tensorflow''', aliases=['''tf'''])
else:
	a__		     =     ValueError('''Tensorflow needs to be installed to be able to return Tensorflow tensors.''')
	_register_unavailable_formatter(_tf_error, '''tensorflow''', aliases=['''tf'''])

if config.JAX_AVAILABLE:
	from .jax_formatter import JaxFormatter

	_register_formatter(JaxFormatter, '''jax''', aliases=[])
else:
	a__		     =     ValueError('''JAX needs to be installed to be able to return JAX arrays.''')
	_register_unavailable_formatter(_jax_error, '''jax''', aliases=[])





def 				A__ (snake_case   :		Optional[str]				)     ->						Optional[str]:
					if format_type in _FORMAT_TYPES_ALIASES:
										return _FORMAT_TYPES_ALIASES[format_type]
					else:
										return format_type







def 				A__ (snake_case   :		Optional[str]		,	**snake_case   :		List[str]				)     ->						Formatter:
					__UpperCamelCase					:	int             =      get_format_type_from_alias(snake_case				)
					if format_type in _FORMAT_TYPES:
										return _FORMAT_TYPES[format_type](**snake_case				)
					if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE:
										raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type]
					else:
										raise ValueError(
										    F'''Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None				)}, but got \'{format_type}\''''				)






