






"""simple docstring"""
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
			import torch

if is_vision_available():
			from PIL import Image

			from transformers import ViTImageProcessor







class      UpperCamelCase_			(unittest.TestCase	):





	def __init__( self   :					Optional[int]      ,      lowerCAmelCase_   :					Tuple      ,      lowerCAmelCase_   :					List[str]=13      ,      lowerCAmelCase_   :					Union[str, Any]=3      ,      lowerCAmelCase_   :					Union[str, Any]=224      ,      lowerCAmelCase_   :					List[Any]=30      ,      lowerCAmelCase_   :					Any=400      ,      lowerCAmelCase_   :					Any=True      ,      lowerCAmelCase_   :					Dict=None      ,      lowerCAmelCase_   :					int=True      ,      lowerCAmelCase_   :					Any=[0.5, 0.5, 0.5]      ,      lowerCAmelCase_   :					str=[0.5, 0.5, 0.5]      ,      )		->     Dict:
				UpperCAmelCase_	:					int     	=   size if size is not None else {"height": 18, "width": 18}
				UpperCAmelCase_	:					List[Any]     	=   parent
				UpperCAmelCase_	:					int     	=   batch_size
				UpperCAmelCase_	:					Optional[int]     	=   num_channels
				UpperCAmelCase_	:					Dict     	=   image_size
				UpperCAmelCase_	:					Union[str, Any]     	=   min_resolution
				UpperCAmelCase_	:					List[str]     	=   max_resolution
				UpperCAmelCase_	:					Dict     	=   do_resize
				UpperCAmelCase_	:					Optional[int]     	=   size
				UpperCAmelCase_	:					List[str]     	=   do_normalize
				UpperCAmelCase_	:					List[Any]     	=   image_mean
				UpperCAmelCase_	:					Dict     	=   image_std





	def 	_SCREAMING_SNAKE_CASE ( self   :					int		)		->     Union[str, Any]:
				return {
				    "image_mean": self.image_mean,
				    "image_std": self.image_std,
				    "do_normalize": self.do_normalize,
				    "do_resize": self.do_resize,
				    "size": self.size,
				}







@require_torch
@require_vision
class      UpperCamelCase_			(__A							,		unittest.TestCase	):
	__magic_name__       =							ViTImageProcessor if is_vision_available() else None





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[str]		)		->     Optional[Any]:
				UpperCAmelCase_	:					Optional[Any]     	=   EfficientFormerImageProcessorTester(self		)





	@property
	def 	_SCREAMING_SNAKE_CASE ( self   :					Dict		)		->     List[Any]:
				return self.image_proc_tester.prepare_image_processor_dict()





	def 	_SCREAMING_SNAKE_CASE ( self   :					Tuple		)		->     str:
				UpperCAmelCase_	:					Tuple     	=   self.image_processing_class(**self.image_processor_dict		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "image_mean"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "image_std"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "do_normalize"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "do_resize"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "size"		)		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[str]		)		->     List[str]:
				pass





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]		)		->     int:
				# Initialize image_processor
				UpperCAmelCase_	:					str     	=   self.image_processing_class(**self.image_processor_dict		)
				# create random PIL images
				UpperCAmelCase_	:					int     	=   prepare_image_inputs(self.image_proc_tester      ,      equal_resolution=lowerCAmelCase_		)
				for image in image_inputs:
							self.assertIsInstance(lowerCAmelCase_      ,      Image.Image		)

				# Test not batched input
				UpperCAmelCase_	:					Optional[Any]     	=   image_processor(image_inputs[0]      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        1,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )

				# Test batched
				UpperCAmelCase_	:					str     	=   image_processor(lowerCAmelCase_      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        self.image_proc_tester.batch_size,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )





	def 	_SCREAMING_SNAKE_CASE ( self   :					Dict		)		->     List[Any]:
				# Initialize image_processor
				UpperCAmelCase_	:					List[str]     	=   self.image_processing_class(**self.image_processor_dict		)
				# create random numpy tensors
				UpperCAmelCase_	:					List[str]     	=   prepare_image_inputs(self.image_proc_tester      ,      equal_resolution=lowerCAmelCase_      ,      numpify=lowerCAmelCase_		)
				for image in image_inputs:
							self.assertIsInstance(lowerCAmelCase_      ,      np.ndarray		)

				# Test not batched input
				UpperCAmelCase_	:					str     	=   image_processor(image_inputs[0]      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        1,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )

				# Test batched
				UpperCAmelCase_	:					Dict     	=   image_processor(lowerCAmelCase_      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        self.image_proc_tester.batch_size,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]		)		->     List[Any]:
				# Initialize image_processor
				UpperCAmelCase_	:					Optional[Any]     	=   self.image_processing_class(**self.image_processor_dict		)
				# create random PyTorch tensors
				UpperCAmelCase_	:					Dict     	=   prepare_image_inputs(self.image_proc_tester      ,      equal_resolution=lowerCAmelCase_      ,      torchify=lowerCAmelCase_		)
				for image in image_inputs:
							self.assertIsInstance(lowerCAmelCase_      ,      torch.Tensor		)

				# Test not batched input
				UpperCAmelCase_	:					Optional[int]     	=   image_processor(image_inputs[0]      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        1,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )

				# Test batched
				UpperCAmelCase_	:					Optional[int]     	=   image_processor(lowerCAmelCase_      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        self.image_proc_tester.batch_size,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )





'''simple docstring'''

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


 def __init__(    self  : str			,							a__  : Union[str, Any]			,							a__  : Union[str, Any]=13			,							a__  : Union[str, Any]=7			,							a__  : Any=True			,							a__  : str=True			,							a__  : Optional[Any]=True			,							a__  : Any=99			,							a__  : Dict=32			,							a__  : Tuple=5			,							a__  : List[Any]=4			,							a__  : List[Any]=37			,							a__  : List[str]="gelu"			,							a__  : Dict=0.1			,							a__  : str=0.1			,							a__  : str=512			,							a__  : List[str]=16			,							a__  : Dict=2			,							a__  : Union[str, Any]=0.02			,							a__  : Dict=3			,							a__  : List[Any]=4			,							a__  : Optional[int]=None			,							):
  '''simple docstring'''

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


 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Optional[int]     		=	ids_tensor([self.batch_size, self.seq_length]			,							self.vocab_size    )

  lowerCAmelCase__     :   Dict     		=	None
  if self.use_token_type_ids:
   lowerCAmelCase__     :   List[str]     		=	ids_tensor([self.batch_size, self.seq_length]			,							self.type_vocab_size    )

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

  lowerCAmelCase__     :   Any     		=	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			,							)

  lowerCAmelCase__     :   Optional[Any]     		=	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    _A	(    self  : Dict			,							a__  : Any			,							a__  : Any			,							a__  : int			,							a__  : str			,							*a__  : Optional[Any]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   str     		=	OpenAIGPTModel(config=a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Optional[Any]     		=	model(a__			,							token_type_ids=a__			,							head_mask=a__    )
  lowerCAmelCase__     :   Optional[int]     		=	model(a__			,							token_type_ids=a__    )
  lowerCAmelCase__     :   Any     		=	model(a__    )

  self.parent.assertEqual(result.last_hidden_state.shape			,							(self.batch_size, self.seq_length, self.hidden_size)    )


 def    _A	(    self  : Optional[int]			,							a__  : List[Any]			,							a__  : int			,							a__  : Dict			,							a__  : Any			,							*a__  : Any    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Tuple     		=	OpenAIGPTLMHeadModel(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Dict     		=	model(a__			,							token_type_ids=a__			,							labels=a__    )
  self.parent.assertEqual(result.loss.shape			,							()    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.seq_length, self.vocab_size)    )


 def    _A	(    self  : List[str]			,							a__  : str			,							a__  : Dict			,							a__  : Union[str, Any]			,							a__  : int			,							*a__  : Dict    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[str]     		=	OpenAIGPTDoubleHeadsModel(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Optional[Any]     		=	model(a__			,							token_type_ids=a__			,							labels=a__    )
  self.parent.assertEqual(result.loss.shape			,							()    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.seq_length, self.vocab_size)    )


 def    _A	(    self  : Any			,							a__  : Any			,							a__  : Union[str, Any]			,							a__  : Optional[int]			,							a__  : Any			,							*a__  : List[str]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[Any]     		=	self.num_labels
  lowerCAmelCase__     :   Union[str, Any]     		=	OpenAIGPTForSequenceClassification(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   List[str]     		=	ids_tensor([self.batch_size]			,							self.type_sequence_label_size    )
  lowerCAmelCase__     :   Tuple     		=	model(a__			,							token_type_ids=a__			,							labels=a__    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.num_labels)    )


 def    _A	(    self  : Optional[int]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[str]     		=	self.prepare_config_and_inputs()
  (
      (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     
  )     :   Union[str, Any]     		=	config_and_inputs
  lowerCAmelCase__     :   str     		=	{
      "input_ids": input_ids,
      "token_type_ids": token_type_ids,
      "head_mask": head_mask,
  }

  return config, inputs_dict




@require_torch
class    lowerCAmelCase       (     UpperCamelCase_    ,  UpperCamelCase_    ,  UpperCamelCase_    ,  unittest.TestCase  ):
 A_				:				str	=			(
     (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
     if is_torch_available()
     else ()
 )
 A_				:				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    _A	(    self  : List[Any]			,							a__  : Optional[Any]			,							a__  : Optional[int]			,							a__  : Optional[Any]			,							a__  : List[Any]			,							a__  : int    ):
  '''simple docstring'''

  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    _A	(    self  : Dict			,							a__  : Optional[int]			,							a__  : List[Any]			,							a__  : List[Any]=False    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Any     		=	super()._prepare_for_class(a__			,							a__			,							return_labels=a__    )

  if return_labels:
   if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
    lowerCAmelCase__     :   Tuple     		=	torch.zeros(
        (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)			,							dtype=torch.long			,							device=a__			,							)
    lowerCAmelCase__     :   Union[str, Any]     		=	inputs_dict["labels"]
    lowerCAmelCase__     :   int     		=	inputs_dict["labels"]
    lowerCAmelCase__     :   Optional[int]     		=	torch.zeros(
        (self.model_tester.batch_size, self.model_tester.num_choices)			,							dtype=torch.long			,							device=a__			,							)
    lowerCAmelCase__     :   List[str]     		=	torch.zeros(
        self.model_tester.batch_size			,							dtype=torch.long			,							device=a__    )
  return inputs_dict


 def    _A	(    self  : str    ):
  '''simple docstring'''

  lowerCAmelCase__     :   str     		=	OpenAIGPTModelTester(self    )
  lowerCAmelCase__     :   Any     		=	ConfigTester(self			,							config_class=a__			,							n_embd=37    )


 def    _A	(    self  : List[str]    ):
  '''simple docstring'''

  self.config_tester.run_common_tests()


 def    _A	(    self  : Optional[int]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Dict     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_openai_gpt_model(*a__    )


 def    _A	(    self  : Union[str, Any]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Optional[int]     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_lm_head_model(*a__    )


 def    _A	(    self  : int    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Tuple     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_double_lm_head_model(*a__    )


 def    _A	(    self  : str    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Union[str, Any]     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*a__    )


 @slow
 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
   lowerCAmelCase__     :   Any     		=	OpenAIGPTModel.from_pretrained(a__    )
   self.assertIsNotNone(a__    )




@require_torch
class    lowerCAmelCase       (     unittest.TestCase  ):


 @slow
 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  lowerCAmelCase__     :   int     		=	OpenAIGPTLMHeadModel.from_pretrained("openai-gpt"    )
  model.to(a__    )
  lowerCAmelCase__     :   Union[str, Any]     		=	torch.tensor([[481, 4735, 544]]			,							dtype=torch.long			,							device=a__    )  # the president is
  lowerCAmelCase__     :   Optional[int]     		=	[
      481,
      4735,
      544,
      246,
      963,
      870,
      762,
      239,
      244,
      4_0477,
      244,
      249,
      719,
      881,
      487,
      544,
      240,
      244,
      603,
      481,
  ]  # the president is a very good man. " \n " i\'m sure he is, " said the

  lowerCAmelCase__     :   Optional[int]     		=	model.generate(a__			,							do_sample=a__    )
  self.assertListEqual(output_ids[0].tolist()			,							a__    )





