


import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List

from ..utils import logging


snake_case							: str      =   logging.get_logger(__name__)






def 							__lowercase     (				__lowerCAmelCase							:       List[Any]=None      ,					__lowerCAmelCase							:       Optional[Any]=None     ):
							return field(default_factory=lambda: default      ,					metadata=__lowerCAmelCase     )







@dataclass
class  snake_case_     :
					UpperCAmelCase__      :					List[str]					   =    list_field(
					    default=[]			,		metadata={
					        '''help''': (
					            '''Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version'''
					            ''' of all available models'''
					        )
					    }			,		)

					UpperCAmelCase__      :					List[int]					   =    list_field(
					    default=[8]			,		metadata={'''help''': '''List of batch sizes for which memory and time performance will be evaluated'''}   )

					UpperCAmelCase__      :					List[int]					   =    list_field(
					    default=[8, 3_2, 1_2_8, 5_1_2]			,		metadata={'''help''': '''List of sequence lengths for which memory and time performance will be evaluated'''}			,		)

					UpperCAmelCase__      :					bool					   =    field(
					    default=lowerCamelCase_			,		metadata={'''help''': '''Whether to benchmark inference of model. Inference can be disabled via --no-inference.'''}			,		)
					UpperCAmelCase__      :					bool					   =    field(
					    default=lowerCamelCase_			,		metadata={'''help''': '''Whether to run on available cuda devices. Cuda can be disabled via --no-cuda.'''}			,		)
					UpperCAmelCase__      :					bool					   =    field(
					    default=lowerCamelCase_			,		metadata={'''help''': '''Whether to run on available tpu devices. TPU can be disabled via --no-tpu.'''}   )
					UpperCAmelCase__      :					bool					   =    field(default=lowerCamelCase_			,		metadata={'''help''': '''Use FP16 to accelerate inference.'''}   )
					UpperCAmelCase__      :					bool					   =    field(default=lowerCamelCase_			,		metadata={'''help''': '''Benchmark training of model'''}   )
					UpperCAmelCase__      :					bool					   =    field(default=lowerCamelCase_			,		metadata={'''help''': '''Verbose memory tracing'''}   )
					UpperCAmelCase__      :					bool					   =    field(
					    default=lowerCamelCase_			,		metadata={'''help''': '''Whether to perform speed measurements. Speed measurements can be disabled via --no-speed.'''}			,		)
					UpperCAmelCase__      :					bool					   =    field(
					    default=lowerCamelCase_			,		metadata={
					        '''help''': '''Whether to perform memory measurements. Memory measurements can be disabled via --no-memory'''
					    }			,		)
					UpperCAmelCase__      :					bool					   =    field(default=lowerCamelCase_			,		metadata={'''help''': '''Trace memory line by line'''}   )
					UpperCAmelCase__      :					bool					   =    field(default=lowerCamelCase_			,		metadata={'''help''': '''Save result to a CSV file'''}   )
					UpperCAmelCase__      :					bool					   =    field(default=lowerCamelCase_			,		metadata={'''help''': '''Save all print statements in a log file'''}   )
					UpperCAmelCase__      :					bool					   =    field(default=lowerCamelCase_			,		metadata={'''help''': '''Whether to print environment information'''}   )
					UpperCAmelCase__      :					bool					   =    field(
					    default=lowerCamelCase_			,		metadata={
					        '''help''': (
					            '''Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use'''
					            ''' multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled'''
					            ''' for debugging / testing and on TPU.'''
					        )
					    }			,		)
					UpperCAmelCase__      :					str					   =    field(
					    default=f'inference_time_{round(time()   )}.csv'			,		metadata={'''help''': '''CSV filename used if saving time results to csv.'''}			,		)
					UpperCAmelCase__      :					str					   =    field(
					    default=f'inference_memory_{round(time()   )}.csv'			,		metadata={'''help''': '''CSV filename used if saving memory results to csv.'''}			,		)
					UpperCAmelCase__      :					str					   =    field(
					    default=f'train_time_{round(time()   )}.csv'			,		metadata={'''help''': '''CSV filename used if saving time results to csv for training.'''}			,		)
					UpperCAmelCase__      :					str					   =    field(
					    default=f'train_memory_{round(time()   )}.csv'			,		metadata={'''help''': '''CSV filename used if saving memory results to csv for training.'''}			,		)
					UpperCAmelCase__      :					str					   =    field(
					    default=f'env_info_{round(time()   )}.csv'			,		metadata={'''help''': '''CSV filename used if saving environment information.'''}			,		)
					UpperCAmelCase__      :					str					   =    field(
					    default=f'log_{round(time()   )}.csv'			,		metadata={'''help''': '''Log filename used if print statements are saved in log.'''}			,		)
					UpperCAmelCase__      :					int					   =    field(default=3			,		metadata={'''help''': '''Times an experiment will be run.'''}   )
					UpperCAmelCase__      :					bool					   =    field(
					    default=lowerCamelCase_			,		metadata={
					        '''help''': (
					            '''Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain'''
					            ''' model weights.'''
					        )
					    }			,		)
					def 				lowerCamelCase__(   self     :List[str]   )      ->					str:
												warnings.warn(
												    F'The class {self.__class__} is deprecated. Hugging Face Benchmarking utils'
												    ' are deprecated in general and it is advised to use external Benchmarking libraries '
												    ' to benchmark Transformer models.'    ,__snake_case    ,)
					def 				lowerCamelCase__(   self     :Dict   )      ->					Dict:
												return json.dumps(dataclasses.asdict(self   )    ,indent=2   )
					@property
					def 				lowerCamelCase__(   self     :List[Any]   )      ->					List[str]:
												if len(self.models   ) <= 0:
																			raise ValueError(
																			    'Please make sure you provide at least one model name / model identifier, *e.g.* `--models'
																			    ' bert-base-cased` or `args.models = [\'bert-base-cased\'].'   )
												return self.models



					@property
					def 				lowerCamelCase__(   self     :Dict   )      ->					Optional[int]:
												if not self.multi_process:
																			return False
												elif self.is_tpu:
																			logger.info('Multiprocessing is currently not possible on TPU.'   )
																			return False
												else:
																			return True








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  snake_case_     :
					def __init__(   self     :Optional[Any]    ,__snake_case     :str    ,__snake_case     :Optional[Any]=14    ,__snake_case     :Dict=7    ,__snake_case     :Optional[int]=True    ,__snake_case     :Optional[int]=True    ,__snake_case     :Dict=True    ,__snake_case     :List[Any]=True    ,__snake_case     :Optional[int]=True    ,__snake_case     :Any=99    ,__snake_case     :List[str]=32    ,__snake_case     :List[str]=5    ,__snake_case     :Tuple=4    ,__snake_case     :Optional[int]=37    ,__snake_case     :Optional[int]="gelu"    ,__snake_case     :Tuple=0.1    ,__snake_case     :Tuple=0.1    ,__snake_case     :Dict=5_12    ,__snake_case     :Union[str, Any]=16    ,__snake_case     :str=2    ,__snake_case     :Optional[Any]=0.02    ,__snake_case     :Dict=3    ,__snake_case     :Optional[Any]=4    ,__snake_case     :Optional[Any]=None    ,)      ->					Tuple:
												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 				lowerCamelCase__(   self     :Optional[int]   )      ->					Union[str, Any]:
												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 				lowerCamelCase__(   self     :Optional[Any]   )      ->					Tuple:
												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     :str    ,__snake_case     :List[str]    ,__snake_case     :Any    ,__snake_case     :Dict    ,__snake_case     :int    ,__snake_case     :Optional[Any]    ,*__snake_case     :List[str]   )      ->					List[Any]:
												a__    =  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   )
												a__    =  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 				lowerCamelCase__(   self     :Optional[int]    ,__snake_case     :List[str]    ,__snake_case     :Union[str, Any]    ,__snake_case     :str    ,__snake_case     :str    ,__snake_case     :Dict    ,*__snake_case     :Dict   )      ->					Dict:
												a__    =  CTRLLMHeadModel(__snake_case   )
												model.to(__snake_case   )
												model.eval()

												a__    =  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 				lowerCamelCase__(   self     :Optional[Any]   )      ->					Optional[Any]:
												a__    =  self.prepare_config_and_inputs()

												(
												    (
												    a__
												)   ,      (
												    a__
												)   ,      (
												    a__
												)   ,      (
												    a__
												)   ,      (
												    a__
												)   ,      (
												    a__
												)   ,      (
												    a__
												)   ,      (
												    a__
												)   ,      (
												    a__
												)   ,      
												)    =  config_and_inputs

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

												return config, inputs_dict



					def 				lowerCamelCase__(   self     :Optional[int]    ,__snake_case     :Tuple    ,__snake_case     :str    ,__snake_case     :str    ,__snake_case     :List[str]    ,*__snake_case     :Optional[int]   )      ->					List[Any]:
												a__    =  self.num_labels
												a__    =  CTRLForSequenceClassification(__snake_case   )
												model.to(__snake_case   )
												model.eval()
												a__    =  ids_tensor([self.batch_size]    ,self.type_sequence_label_size   )
												a__    =  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  snake_case_     (lowerCamelCase_			,		lowerCamelCase_			,		lowerCamelCase_			,		unittest.TestCase   ):
					UpperCAmelCase__      :					Union[str, Any]					   =    (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
					UpperCAmelCase__      :					Any					   =    (CTRLLMHeadModel,) if is_torch_available() else ()
					UpperCAmelCase__      :					Any					   =    (
					    {
					        '''feature-extraction''': CTRLModel,
					        '''text-classification''': CTRLForSequenceClassification,
					        '''text-generation''': CTRLLMHeadModel,
					        '''zero-shot''': CTRLForSequenceClassification,
					    }
					    if is_torch_available()
					    else {}
					)
					UpperCAmelCase__      :					Tuple					   =    True
					UpperCAmelCase__      :					List[Any]					   =    False
					UpperCAmelCase__      :					List[str]					   =    False
					def 				lowerCamelCase__(   self     :Union[str, Any]    ,__snake_case     :Optional[int]    ,__snake_case     :int    ,__snake_case     :Any    ,__snake_case     :List[str]    ,__snake_case     :Dict   )      ->					Union[str, Any]:
												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     :int   )      ->					List[str]:
												a__    =  CTRLModelTester(self   )
												a__    =  ConfigTester(self    ,config_class=__snake_case    ,n_embd=37   )
					def 				lowerCamelCase__(   self     :str   )      ->					str:
												super().tearDown()
												# clean-up as much as possible GPU memory occupied by PyTorch
												gc.collect()
												torch.cuda.empty_cache()
					def 				lowerCamelCase__(   self     :Tuple   )      ->					List[Any]:
												self.config_tester.run_common_tests()
					def 				lowerCamelCase__(   self     :str   )      ->					str:
												a__    =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_ctrl_model(*__snake_case   )
					def 				lowerCamelCase__(   self     :List[Any]   )      ->					Any:
												a__    =  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 				lowerCamelCase__(   self     :Union[str, Any]   )      ->					Tuple:
												pass
					@slow
					def 				lowerCamelCase__(   self     :int   )      ->					List[Any]:
												for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			a__    =  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 				lowerCamelCase__(   self     :Dict   )      ->					List[str]:
												pass







@require_torch
class  snake_case_     (unittest.TestCase   ):
					def 				lowerCamelCase__(   self     :Union[str, Any]   )      ->					str:
												super().tearDown()
												# clean-up as much as possible GPU memory occupied by PyTorch
												gc.collect()
												torch.cuda.empty_cache()



					@slow
					def 				lowerCamelCase__(   self     :Any   )      ->					Dict:
												a__    =  CTRLLMHeadModel.from_pretrained('ctrl'   )
												model.to(__snake_case   )
												a__    =  torch.tensor(
												    [[1_18_59, 0, 16_11, 8]]    ,dtype=torch.long    ,device=__snake_case   )  # Legal the president is
												a__    =  [
												    1_18_59,
												    0,
												    16_11,
												    8,
												    5,
												    1_50,
												    2_64_49,
												    2,
												    19,
												    3_48,
												    4_69,
												    3,
												    25_95,
												    48,
												    2_07_40,
												    24_65_33,
												    24_65_33,
												    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(__snake_case    ,do_sample=__snake_case   )
												self.assertListEqual(output_ids[0].tolist()    ,__snake_case   )




