
import unittest

from transformers import 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
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import (
						    OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
						    OpenAIGPTConfig,
						    OpenAIGPTDoubleHeadsModel,
						    OpenAIGPTForSequenceClassification,
						    OpenAIGPTLMHeadModel,
						    OpenAIGPTModel,
						)
class 					lowercase__:



	"""simple docstring"""




	def __init__(			self    :     Optional[int]			,				SCREAMING_SNAKE_CASE_    :     str			,				SCREAMING_SNAKE_CASE_    :     Tuple=1_3			,				SCREAMING_SNAKE_CASE_    :     Optional[Any]=7			,				SCREAMING_SNAKE_CASE_    :     Dict=True			,				SCREAMING_SNAKE_CASE_    :     str=True			,				SCREAMING_SNAKE_CASE_    :     Union[str, Any]=True			,				SCREAMING_SNAKE_CASE_    :     Union[str, Any]=9_9			,				SCREAMING_SNAKE_CASE_    :     Union[str, Any]=3_2			,				SCREAMING_SNAKE_CASE_    :     Dict=5			,				SCREAMING_SNAKE_CASE_    :     int=4			,				SCREAMING_SNAKE_CASE_    :     Any=3_7			,				SCREAMING_SNAKE_CASE_    :     Any="gelu"			,				SCREAMING_SNAKE_CASE_    :     Tuple=0.1			,				SCREAMING_SNAKE_CASE_    :     Dict=0.1			,				SCREAMING_SNAKE_CASE_    :     Tuple=5_1_2			,				SCREAMING_SNAKE_CASE_    :     List[Any]=1_6			,				SCREAMING_SNAKE_CASE_    :     Dict=2			,				SCREAMING_SNAKE_CASE_    :     int=0.02			,				SCREAMING_SNAKE_CASE_    :     Tuple=3			,				SCREAMING_SNAKE_CASE_    :     str=4			,				SCREAMING_SNAKE_CASE_    :     Tuple=None			,				)			->	List[str]:
					lowercase_	    =   parent
					lowercase_	    =   batch_size
					lowercase_	    =   seq_length
					lowercase_	    =   is_training
					lowercase_	    =   use_token_type_ids
					lowercase_	    =   use_labels
					lowercase_	    =   vocab_size
					lowercase_	    =   hidden_size
					lowercase_	    =   num_hidden_layers
					lowercase_	    =   num_attention_heads
					lowercase_	    =   intermediate_size
					lowercase_	    =   hidden_act
					lowercase_	    =   hidden_dropout_prob
					lowercase_	    =   attention_probs_dropout_prob
					lowercase_	    =   max_position_embeddings
					lowercase_	    =   type_vocab_size
					lowercase_	    =   type_sequence_label_size
					lowercase_	    =   initializer_range
					lowercase_	    =   num_labels
					lowercase_	    =   num_choices
					lowercase_	    =   scope
					lowercase_	    =   self.vocab_size - 1
	def 		_lowercase    (			self    :     str			)			->	List[str]:
					lowercase_	    =   ids_tensor([self.batch_size, self.seq_length]			,				self.vocab_size			)

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

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

					lowercase_	    =   OpenAIGPTConfig(
					    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			,				)

					lowercase_	    =   ids_tensor([self.num_hidden_layers, self.num_attention_heads]			,				2			)

					return (
					    config,
					    input_ids,
					    head_mask,
					    token_type_ids,
					    sequence_labels,
					    token_labels,
					    choice_labels,
					)
	def 		_lowercase    (			self    :     str			,				SCREAMING_SNAKE_CASE_    :     str			,				SCREAMING_SNAKE_CASE_    :     Union[str, Any]			,				SCREAMING_SNAKE_CASE_    :     List[Any]			,				SCREAMING_SNAKE_CASE_    :     int			,				*SCREAMING_SNAKE_CASE_    :     Optional[Any]			)			->	Union[str, Any]:
					lowercase_	    =   OpenAIGPTModel(config=SCREAMING_SNAKE_CASE_			)
					model.to(SCREAMING_SNAKE_CASE_			)
					model.eval()

					lowercase_	    =   model(SCREAMING_SNAKE_CASE_			,				token_type_ids=SCREAMING_SNAKE_CASE_			,				head_mask=SCREAMING_SNAKE_CASE_			)
					lowercase_	    =   model(SCREAMING_SNAKE_CASE_			,				token_type_ids=SCREAMING_SNAKE_CASE_			)
					lowercase_	    =   model(SCREAMING_SNAKE_CASE_			)

					self.parent.assertEqual(result.last_hidden_state.shape			,				(self.batch_size, self.seq_length, self.hidden_size)			)
	def 		_lowercase    (			self    :     int			,				SCREAMING_SNAKE_CASE_    :     Union[str, Any]			,				SCREAMING_SNAKE_CASE_    :     Dict			,				SCREAMING_SNAKE_CASE_    :     Tuple			,				SCREAMING_SNAKE_CASE_    :     str			,				*SCREAMING_SNAKE_CASE_    :     List[Any]			)			->	List[Any]:
					lowercase_	    =   OpenAIGPTLMHeadModel(SCREAMING_SNAKE_CASE_			)
					model.to(SCREAMING_SNAKE_CASE_			)
					model.eval()

					lowercase_	    =   model(SCREAMING_SNAKE_CASE_			,				token_type_ids=SCREAMING_SNAKE_CASE_			,				labels=SCREAMING_SNAKE_CASE_			)
					self.parent.assertEqual(result.loss.shape			,				()			)
					self.parent.assertEqual(result.logits.shape			,				(self.batch_size, self.seq_length, self.vocab_size)			)
	def 		_lowercase    (			self    :     Optional[Any]			,				SCREAMING_SNAKE_CASE_    :     List[str]			,				SCREAMING_SNAKE_CASE_    :     str			,				SCREAMING_SNAKE_CASE_    :     Optional[int]			,				SCREAMING_SNAKE_CASE_    :     Optional[Any]			,				*SCREAMING_SNAKE_CASE_    :     List[Any]			)			->	Optional[int]:
					lowercase_	    =   OpenAIGPTDoubleHeadsModel(SCREAMING_SNAKE_CASE_			)
					model.to(SCREAMING_SNAKE_CASE_			)
					model.eval()

					lowercase_	    =   model(SCREAMING_SNAKE_CASE_			,				token_type_ids=SCREAMING_SNAKE_CASE_			,				labels=SCREAMING_SNAKE_CASE_			)
					self.parent.assertEqual(result.loss.shape			,				()			)
					self.parent.assertEqual(result.logits.shape			,				(self.batch_size, self.seq_length, self.vocab_size)			)
	def 		_lowercase    (			self    :     Any			,				SCREAMING_SNAKE_CASE_    :     Union[str, Any]			,				SCREAMING_SNAKE_CASE_    :     List[Any]			,				SCREAMING_SNAKE_CASE_    :     List[str]			,				SCREAMING_SNAKE_CASE_    :     Optional[int]			,				*SCREAMING_SNAKE_CASE_    :     Tuple			)			->	List[str]:
					lowercase_	    =   self.num_labels
					lowercase_	    =   OpenAIGPTForSequenceClassification(SCREAMING_SNAKE_CASE_			)
					model.to(SCREAMING_SNAKE_CASE_			)
					model.eval()

					lowercase_	    =   ids_tensor([self.batch_size]			,				self.type_sequence_label_size			)
					lowercase_	    =   model(SCREAMING_SNAKE_CASE_			,				token_type_ids=SCREAMING_SNAKE_CASE_			,				labels=SCREAMING_SNAKE_CASE_			)
					self.parent.assertEqual(result.logits.shape			,				(self.batch_size, self.num_labels)			)




	def 		_lowercase    (			self    :     Optional[Any]			)			->	Optional[Any]:
					lowercase_	    =   self.prepare_config_and_inputs()
					(
					    (
					    lowercase_
					)    ,      (
					    lowercase_
					)    ,      (
					    lowercase_
					)    ,      (
					    lowercase_
					)    ,      (
					    lowercase_
					)    ,      (
					    lowercase_
					)    ,      (
					    lowercase_
					)    ,      
					)	    =   config_and_inputs
					lowercase_	    =   {
					    '''input_ids''': input_ids,
					    '''token_type_ids''': token_type_ids,
					    '''head_mask''': head_mask,
					}

					return config, inputs_dict

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



	"""simple docstring"""




	a     :Dict       	=      (
	    (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
	    if is_torch_available()
	    else ()
	)
	a     :Optional[Any]       	=      (
	    (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
	)  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
	a     :int       	=      (
	    {
	        'feature-extraction': OpenAIGPTModel,
	        'text-classification': OpenAIGPTForSequenceClassification,
	        'text-generation': OpenAIGPTLMHeadModel,
	        'zero-shot': OpenAIGPTForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	def 		_lowercase    (			self    :     str			,				SCREAMING_SNAKE_CASE_    :     Union[str, Any]			,				SCREAMING_SNAKE_CASE_    :     int			,				SCREAMING_SNAKE_CASE_    :     Tuple			,				SCREAMING_SNAKE_CASE_    :     List[str]			,				SCREAMING_SNAKE_CASE_    :     Dict			)			->	int:
					if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
									# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
									# `OpenAIGPTConfig` 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 		_lowercase    (			self    :     Optional[int]			,				SCREAMING_SNAKE_CASE_    :     Tuple			,				SCREAMING_SNAKE_CASE_    :     int			,				SCREAMING_SNAKE_CASE_    :     List[Any]=False			)			->	List[str]:
					lowercase_	    =   super()._prepare_for_class(SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_			,				return_labels=SCREAMING_SNAKE_CASE_			)

					if return_labels:
									if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
													lowercase_	    =   torch.zeros(
													    (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)			,				dtype=torch.long			,				device=SCREAMING_SNAKE_CASE_			,				)
													lowercase_	    =   inputs_dict['''labels''']
													lowercase_	    =   inputs_dict['''labels''']
													lowercase_	    =   torch.zeros(
													    (self.model_tester.batch_size, self.model_tester.num_choices)			,				dtype=torch.long			,				device=SCREAMING_SNAKE_CASE_			,				)
													lowercase_	    =   torch.zeros(
													    self.model_tester.batch_size			,				dtype=torch.long			,				device=SCREAMING_SNAKE_CASE_			)
					return inputs_dict
	def 		_lowercase    (			self    :     Optional[Any]			)			->	int:
					lowercase_	    =   OpenAIGPTModelTester(self			)
					lowercase_	    =   ConfigTester(self			,				config_class=SCREAMING_SNAKE_CASE_			,				n_embd=3_7			)
	def 		_lowercase    (			self    :     List[str]			)			->	Any:
					self.config_tester.run_common_tests()
	def 		_lowercase    (			self    :     str			)			->	Dict:
					lowercase_	    =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_openai_gpt_model(*SCREAMING_SNAKE_CASE_			)
	def 		_lowercase    (			self    :     List[str]			)			->	Tuple:
					lowercase_	    =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_lm_head_model(*SCREAMING_SNAKE_CASE_			)
	def 		_lowercase    (			self    :     Optional[int]			)			->	Optional[Any]:
					lowercase_	    =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_double_lm_head_model(*SCREAMING_SNAKE_CASE_			)
	def 		_lowercase    (			self    :     Tuple			)			->	Union[str, Any]:
					lowercase_	    =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*SCREAMING_SNAKE_CASE_			)




	@slow
	def 		_lowercase    (			self    :     Any			)			->	List[Any]:
					for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowercase_	    =   OpenAIGPTModel.from_pretrained(SCREAMING_SNAKE_CASE_			)
									self.assertIsNotNone(SCREAMING_SNAKE_CASE_			)

@require_torch
class 					lowercase__(							unittest.TestCase				):



	"""simple docstring"""




	@slow
	def 		_lowercase    (			self    :     List[Any]			)			->	str:
					lowercase_	    =   OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt'''			)
					model.to(SCREAMING_SNAKE_CASE_			)
					lowercase_	    =   torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]]			,				dtype=torch.long			,				device=SCREAMING_SNAKE_CASE_			)  # the president is
					lowercase_	    =   [
					    4_8_1,
					    4_7_3_5,
					    5_4_4,
					    2_4_6,
					    9_6_3,
					    8_7_0,
					    7_6_2,
					    2_3_9,
					    2_4_4,
					    4_0_4_7_7,
					    2_4_4,
					    2_4_9,
					    7_1_9,
					    8_8_1,
					    4_8_7,
					    5_4_4,
					    2_4_0,
					    2_4_4,
					    6_0_3,
					    4_8_1,
					]  # the president is a very good man. " \n " i\'m sure he is, " said the

					lowercase_	    =   model.generate(SCREAMING_SNAKE_CASE_			,				do_sample=SCREAMING_SNAKE_CASE_			)
					self.assertListEqual(output_ids[0].tolist()			,				SCREAMING_SNAKE_CASE_			)






import argparse
import os

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_task_guides.py
__a         =   'src/transformers'
__a         =   'docs/source/en/tasks'




def 							a		(				snake_case__:   Optional[int]		,  snake_case__:   Union[str, Any]		,  snake_case__:   Any   ):


				'''simple docstring'''
				with open(snake_case__		,  '''r'''		,  encoding='''utf-8'''		,  newline='''\n'''   ) as f:
								lowercase_	    =   f.readlines()
				# Find the start prompt.
				lowercase_	    =   0
				while not lines[start_index].startswith(snake_case__   ):
								start_index += 1
				start_index += 1

				lowercase_	    =   start_index
				while not lines[end_index].startswith(snake_case__   ):
								end_index += 1
				end_index -= 1

				while len(lines[start_index]   ) <= 1:
								start_index += 1
				while len(lines[end_index]   ) <= 1:
								end_index -= 1
				end_index += 1
				return "".join(lines[start_index:end_index]   ), start_index, end_index, lines


# This is to make sure the transformers module imported is the one in the repo.
__a         =   direct_transformers_import(TRANSFORMERS_PATH)

__a         =   {
    'asr.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES,
    'audio_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES,
    'language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,
    'image_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES,
    'masked_language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES,
    'multiple_choice.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES,
    'object_detection.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES,
    'question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES,
    'semantic_segmentation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES,
    'sequence_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES,
    'summarization.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
    'token_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES,
    'translation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
    'video_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES,
    'document_question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES,
    'monocular_depth_estimation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES,
}

# This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any
# `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`).
__a         =   {
    'summarization.md': ('nllb',),
    'translation.md': ('nllb',),
}




def 							a		(				snake_case__:   Tuple   ):


				'''simple docstring'''
				lowercase_	    =   TASK_GUIDE_TO_MODELS[task_guide]
				lowercase_	    =   SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(snake_case__		,  set()   )
				lowercase_	    =   {
				    code: name
				    for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
				    if (code in model_maping_names or code in special_model_types)
				}
				return ", ".join([F'''[{name}](../model_doc/{code})''' for code, name in model_names.items()]   ) + "\n"




def 							a		(				snake_case__:   List[Any]		,  snake_case__:   Optional[int]=False   ):


				'''simple docstring'''
				lowercase_    ,      lowercase_    ,      lowercase_    ,      lowercase_	    =   _find_text_in_file(
				    filename=os.path.join(snake_case__		,  snake_case__   )		,  start_prompt='''<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->'''		,  end_prompt='''<!--End of the generated tip-->'''		,  )

				lowercase_	    =   get_model_list_for_task(snake_case__   )

				if current_list != new_list:
								if overwrite:
												with open(os.path.join(snake_case__		,  snake_case__   )		,  '''w'''		,  encoding='''utf-8'''		,  newline='''\n'''   ) as f:
																f.writelines(lines[:start_index] + [new_list] + lines[end_index:]   )
								else:
												raise ValueError(
												    F'''The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`'''
												    ''' to fix this.'''   )


if __name__ == "__main__":
						__a         =   argparse.ArgumentParser()
						parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
						__a         =   parser.parse_args()

						for task_guide in TASK_GUIDE_TO_MODELS.keys():
												check_model_list_for_task(task_guide, args.fix_and_overwrite)




