




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 a :
						"""simple docstring"""

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


													__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     UpperCAmelCase_      ( self :     str				)    ->						Any:
													"""simple docstring"""


													__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     UpperCAmelCase_      ( self :     Dict				,							lowerCamelCase__ :     Union[str, Any]				,							lowerCamelCase__ :     Optional[int]				,							lowerCamelCase__ :     Union[str, Any]				,							lowerCamelCase__ :     str				,							*lowerCamelCase__ :     Tuple				)    ->						int:
													"""simple docstring"""


													__lowercase      =    OpenAIGPTModel(config=lowerCamelCase__				)
													model.to(lowerCamelCase__				)
													model.eval()

													__lowercase      =    model(lowerCamelCase__				,							token_type_ids=lowerCamelCase__				,							head_mask=lowerCamelCase__				)
													__lowercase      =    model(lowerCamelCase__				,							token_type_ids=lowerCamelCase__				)
													__lowercase      =    model(lowerCamelCase__				)

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






						def     UpperCAmelCase_      ( self :     Optional[int]				,							lowerCamelCase__ :     str				,							lowerCamelCase__ :     int				,							lowerCamelCase__ :     List[str]				,							lowerCamelCase__ :     Optional[int]				,							*lowerCamelCase__ :     List[Any]				)    ->						Dict:
													"""simple docstring"""


													__lowercase      =    OpenAIGPTLMHeadModel(lowerCamelCase__				)
													model.to(lowerCamelCase__				)
													model.eval()

													__lowercase      =    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     UpperCAmelCase_      ( self :     Optional[int]				,							lowerCamelCase__ :     str				,							lowerCamelCase__ :     Dict				,							lowerCamelCase__ :     Any				,							lowerCamelCase__ :     Tuple				,							*lowerCamelCase__ :     int				)    ->						List[Any]:
													"""simple docstring"""


													__lowercase      =    OpenAIGPTDoubleHeadsModel(lowerCamelCase__				)
													model.to(lowerCamelCase__				)
													model.eval()

													__lowercase      =    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     UpperCAmelCase_      ( self :     Any				,							lowerCamelCase__ :     Tuple				,							lowerCamelCase__ :     int				,							lowerCamelCase__ :     Optional[Any]				,							lowerCamelCase__ :     Any				,							*lowerCamelCase__ :     List[Any]				)    ->						Dict:
													"""simple docstring"""


													__lowercase      =    self.num_labels
													__lowercase      =    OpenAIGPTForSequenceClassification(lowerCamelCase__				)
													model.to(lowerCamelCase__				)
													model.eval()

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






						def     UpperCAmelCase_      ( self :     List[Any]				)    ->						Tuple:
													"""simple docstring"""


													__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 a (     __SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						unittest.TestCase  ):
						"""simple docstring"""

						UpperCamelCase_	:       Tuple       	=		(
						    (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
						    if is_torch_available()
						    else ()
						)
						UpperCamelCase_	:       Union[str, Any]       	=		(
						    (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
						)  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
						UpperCamelCase_	:       int       	=		(
						    {
						        'feature-extraction': OpenAIGPTModel,
						        'text-classification': OpenAIGPTForSequenceClassification,
						        'text-generation': OpenAIGPTLMHeadModel,
						        'zero-shot': OpenAIGPTForSequenceClassification,
						    }
						    if is_torch_available()
						    else {}
						)






						def     UpperCAmelCase_      ( self :     List[Any]				,							lowerCamelCase__ :     Any				,							lowerCamelCase__ :     Optional[Any]				,							lowerCamelCase__ :     str				,							lowerCamelCase__ :     Union[str, Any]				,							lowerCamelCase__ :     List[Any]				)    ->						Tuple:
													"""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     UpperCAmelCase_      ( self :     Optional[Any]				,							lowerCamelCase__ :     Union[str, Any]				,							lowerCamelCase__ :     Dict				,							lowerCamelCase__ :     List[Any]=False				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    super()._prepare_for_class(lowerCamelCase__				,							lowerCamelCase__				,							return_labels=lowerCamelCase__				)

													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=lowerCamelCase__				,							)
																											__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=lowerCamelCase__				,							)
																											__lowercase      =    torch.zeros(
																											    self.model_tester.batch_size				,							dtype=torch.long				,							device=lowerCamelCase__				)
													return inputs_dict






						def     UpperCAmelCase_      ( self :     Any				)    ->						Dict:
													"""simple docstring"""


													__lowercase      =    OpenAIGPTModelTester(self				)
													__lowercase      =    ConfigTester(self				,							config_class=lowerCamelCase__				,							n_embd=37				)






						def     UpperCAmelCase_      ( self :     Tuple				)    ->						Optional[int]:
													"""simple docstring"""


													self.config_tester.run_common_tests()






						def     UpperCAmelCase_      ( self :     Any				)    ->						Dict:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_openai_gpt_model(*lowerCamelCase__				)






						def     UpperCAmelCase_      ( self :     Union[str, Any]				)    ->						int:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_lm_head_model(*lowerCamelCase__				)






						def     UpperCAmelCase_      ( self :     Tuple				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_double_lm_head_model(*lowerCamelCase__				)






						def     UpperCAmelCase_      ( self :     Any				)    ->						int:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*lowerCamelCase__				)






						@slow
						def     UpperCAmelCase_      ( self :     Optional[int]				)    ->						List[str]:
													"""simple docstring"""


													for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				__lowercase      =    OpenAIGPTModel.from_pretrained(lowerCamelCase__				)
																				self.assertIsNotNone(lowerCamelCase__				)







@require_torch
class a (     unittest.TestCase  ):
						"""simple docstring"""

						@slow
						def     UpperCAmelCase_      ( self :     Optional[int]				)    ->						Union[str, Any]:
													"""simple docstring"""


													__lowercase      =    OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt'''				)
													model.to(lowerCamelCase__				)
													__lowercase      =    torch.tensor([[481, 4_735, 544]]				,							dtype=torch.long				,							device=lowerCamelCase__				)  # the president is
													__lowercase      =    [
													    481,
													    4_735,
													    544,
													    246,
													    963,
													    870,
													    762,
													    239,
													    244,
													    40_477,
													    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

													__lowercase      =    model.generate(lowerCamelCase__				,							do_sample=lowerCamelCase__				)
													self.assertListEqual(output_ids[0].tolist()				,							lowerCamelCase__				)












import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available


if is_vision_available():
			from PIL import Image

			from transformers import AutoProcessor, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast







@require_vision
class a (     unittest.TestCase  ):
						"""simple docstring"""

						def     UpperCAmelCase_      ( self :     List[str]				)    ->						Tuple:
													"""simple docstring"""


													__lowercase      =    tempfile.mkdtemp()

													__lowercase      =    BlipImageProcessor()
													__lowercase      =    GPTaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-GPT2Model'''				)

													__lowercase      =    BlipaProcessor(lowerCamelCase__				,							lowerCamelCase__				)

													processor.save_pretrained(self.tmpdirname				)






						def     UpperCAmelCase_      ( self :     Optional[int]				,							**lowerCamelCase__ :     Any				)    ->						str:
													"""simple docstring"""


													return AutoProcessor.from_pretrained(self.tmpdirname				,							**lowerCamelCase__				).tokenizer






						def     UpperCAmelCase_      ( self :     Dict				,							**lowerCamelCase__ :     List[str]				)    ->						Dict:
													"""simple docstring"""


													return AutoProcessor.from_pretrained(self.tmpdirname				,							**lowerCamelCase__				).image_processor






						def     UpperCAmelCase_      ( self :     List[str]				)    ->						str:
													"""simple docstring"""


													shutil.rmtree(self.tmpdirname				)






						def     UpperCAmelCase_      ( self :     Any				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    [np.random.randint(255				,							size=(3, 30, 400)				,							dtype=np.uinta				)]

													__lowercase      =    [Image.fromarray(np.moveaxis(lowerCamelCase__				,							0				,							-1				)				) for x in image_inputs]

													return image_inputs






						def     UpperCAmelCase_      ( self :     List[Any]				)    ->						List[str]:
													"""simple docstring"""


													__lowercase      =    BlipaProcessor(tokenizer=self.get_tokenizer()				,							image_processor=self.get_image_processor()				)
													processor.save_pretrained(self.tmpdirname				)

													__lowercase      =    self.get_tokenizer(bos_token='''(BOS)'''				,							eos_token='''(EOS)'''				)
													__lowercase      =    self.get_image_processor(do_normalize=lowerCamelCase__				,							padding_value=1.0				)

													__lowercase      =    BlipaProcessor.from_pretrained(
													    self.tmpdirname				,							bos_token='''(BOS)'''				,							eos_token='''(EOS)'''				,							do_normalize=lowerCamelCase__				,							padding_value=1.0				)

													self.assertEqual(processor.tokenizer.get_vocab()				,							tokenizer_add_kwargs.get_vocab()				)
													self.assertIsInstance(processor.tokenizer				,							lowerCamelCase__				)

													self.assertEqual(processor.image_processor.to_json_string()				,							image_processor_add_kwargs.to_json_string()				)
													self.assertIsInstance(processor.image_processor				,							lowerCamelCase__				)






						def     UpperCAmelCase_      ( self :     List[Any]				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    self.get_image_processor()
													__lowercase      =    self.get_tokenizer()

													__lowercase      =    BlipaProcessor(tokenizer=lowerCamelCase__				,							image_processor=lowerCamelCase__				)

													__lowercase      =    self.prepare_image_inputs()

													__lowercase      =    image_processor(lowerCamelCase__				,							return_tensors='''np'''				)
													__lowercase      =    processor(images=lowerCamelCase__				,							return_tensors='''np'''				)

													for key in input_feat_extract.keys():
																				self.assertAlmostEqual(input_feat_extract[key].sum()				,							input_processor[key].sum()				,							delta=1e-2				)






						def     UpperCAmelCase_      ( self :     Tuple				)    ->						Tuple:
													"""simple docstring"""


													__lowercase      =    self.get_image_processor()
													__lowercase      =    self.get_tokenizer()

													__lowercase      =    BlipaProcessor(tokenizer=lowerCamelCase__				,							image_processor=lowerCamelCase__				)

													__lowercase      =    '''lower newer'''

													__lowercase      =    processor(text=lowerCamelCase__				)

													__lowercase      =    tokenizer(lowerCamelCase__				,							return_token_type_ids=lowerCamelCase__				)

													for key in encoded_tok.keys():
																				self.assertListEqual(encoded_tok[key]				,							encoded_processor[key]				)






						def     UpperCAmelCase_      ( self :     Dict				)    ->						Tuple:
													"""simple docstring"""


													__lowercase      =    self.get_image_processor()
													__lowercase      =    self.get_tokenizer()

													__lowercase      =    BlipaProcessor(tokenizer=lowerCamelCase__				,							image_processor=lowerCamelCase__				)

													__lowercase      =    '''lower newer'''
													__lowercase      =    self.prepare_image_inputs()

													__lowercase      =    processor(text=lowerCamelCase__				,							images=lowerCamelCase__				)

													self.assertListEqual(list(inputs.keys()				)				,							['''pixel_values''', '''input_ids''', '''attention_mask''']				)

													# test if it raises when no input is passed
													with pytest.raises(lowerCamelCase__				):
																				processor()






						def     UpperCAmelCase_      ( self :     Optional[Any]				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    self.get_image_processor()
													__lowercase      =    self.get_tokenizer()

													__lowercase      =    BlipaProcessor(tokenizer=lowerCamelCase__				,							image_processor=lowerCamelCase__				)

													__lowercase      =    [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

													__lowercase      =    processor.batch_decode(lowerCamelCase__				)
													__lowercase      =    tokenizer.batch_decode(lowerCamelCase__				)

													self.assertListEqual(lowerCamelCase__				,							lowerCamelCase__				)






						def     UpperCAmelCase_      ( self :     List[str]				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    self.get_image_processor()
													__lowercase      =    self.get_tokenizer()

													__lowercase      =    BlipaProcessor(tokenizer=lowerCamelCase__				,							image_processor=lowerCamelCase__				)

													__lowercase      =    '''lower newer'''
													__lowercase      =    self.prepare_image_inputs()

													__lowercase      =    processor(text=lowerCamelCase__				,							images=lowerCamelCase__				)

													# For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
													self.assertListEqual(list(inputs.keys()				)				,							['''pixel_values''', '''input_ids''', '''attention_mask''']				)






