
'''simple docstring'''







from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
					import PIL


lowercase					:							int   =      logging.get_logger(__name__)


class 		__UpperCAmelCase   (      _lowerCamelCase		):
							__lowercase   	= ["""pixel_values"""]


							def __init__( self					,     lowerCAmelCase_ = True					,     lowerCAmelCase_ = None					,     lowerCAmelCase_ = PIL.Image.BICUBIC					,     lowerCAmelCase_ = True					,     lowerCAmelCase_ = None					,     lowerCAmelCase_ = 1 / 2_55					,     lowerCAmelCase_ = True					,     lowerCAmelCase_ = True					,     lowerCAmelCase_ = None					,     lowerCAmelCase_ = None					,     **lowerCAmelCase_					,     ):





								"""simple docstring"""






								super().__init__(**lowerCAmelCase_						)
								_snake_case     		=	size if size is not None else {'height': 2_56, 'width': 2_56}
								_snake_case     		=	get_size_dict(lowerCAmelCase_						)
								_snake_case     		=	crop_size if crop_size is not None else {'height': 2_24, 'width': 2_24}
								_snake_case     		=	get_size_dict(lowerCAmelCase_					,     param_name='crop_size'						)

								_snake_case     		=	do_resize
								_snake_case     		=	size
								_snake_case     		=	resample
								_snake_case     		=	do_center_crop
								_snake_case     		=	crop_size
								_snake_case     		=	do_rescale
								_snake_case     		=	rescale_factor
								_snake_case     		=	do_normalize
								_snake_case     		=	image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
								_snake_case     		=	image_std if image_std is not None else IMAGENET_STANDARD_STD


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_ = PIL.Image.BICUBIC					,     lowerCAmelCase_ = None					,     **lowerCAmelCase_					,     ):





								"""simple docstring"""






								_snake_case     		=	get_size_dict(lowerCAmelCase_						)
								if "height" not in size or "width" not in size:
									raise ValueError(F'The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'						)
								return resize(
								    lowerCAmelCase_					,     size=(size['height'], size['width'])					,     resample=lowerCAmelCase_					,     data_format=lowerCAmelCase_					,     **lowerCAmelCase_						)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_ = None					,     **lowerCAmelCase_					,     ):





								"""simple docstring"""






								_snake_case     		=	get_size_dict(lowerCAmelCase_						)
								if "height" not in size or "width" not in size:
									raise ValueError(F'The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'						)
								return center_crop(lowerCAmelCase_					,     size=(size['height'], size['width'])					,     data_format=lowerCAmelCase_					,     **lowerCAmelCase_						)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_ = None					,     **lowerCAmelCase_					,     ):





								"""simple docstring"""






								return rescale(lowerCAmelCase_					,     scale=lowerCAmelCase_					,     data_format=lowerCAmelCase_					,     **lowerCAmelCase_						)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_ = None					,     **lowerCAmelCase_					,     ):





								"""simple docstring"""






								return normalize(lowerCAmelCase_					,     mean=lowerCAmelCase_					,     std=lowerCAmelCase_					,     data_format=lowerCAmelCase_					,     **lowerCAmelCase_						)




							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_ = None					,     lowerCAmelCase_ = None					,     lowerCAmelCase_=None					,     lowerCAmelCase_ = None					,     lowerCAmelCase_ = None					,     lowerCAmelCase_ = None					,     lowerCAmelCase_ = None					,     lowerCAmelCase_ = None					,     lowerCAmelCase_ = None					,     lowerCAmelCase_ = None					,     lowerCAmelCase_ = None					,     lowerCAmelCase_ = ChannelDimension.FIRST					,     **lowerCAmelCase_					,     ):





								"""simple docstring"""






								_snake_case     		=	do_resize if do_resize is not None else self.do_resize
								_snake_case     		=	resample if resample is not None else self.resample
								_snake_case     		=	do_center_crop if do_center_crop is not None else self.do_center_crop
								_snake_case     		=	do_rescale if do_rescale is not None else self.do_rescale
								_snake_case     		=	rescale_factor if rescale_factor is not None else self.rescale_factor
								_snake_case     		=	do_normalize if do_normalize is not None else self.do_normalize
								_snake_case     		=	image_mean if image_mean is not None else self.image_mean
								_snake_case     		=	image_std if image_std is not None else self.image_std

								_snake_case     		=	size if size is not None else self.size
								_snake_case     		=	get_size_dict(lowerCAmelCase_						)
								_snake_case     		=	crop_size if crop_size is not None else self.crop_size
								_snake_case     		=	get_size_dict(lowerCAmelCase_					,     param_name='crop_size'						)

								_snake_case     		=	make_list_of_images(lowerCAmelCase_						)

								if not valid_images(lowerCAmelCase_						):
									raise ValueError(
									    'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
									    'torch.Tensor, tf.Tensor or jax.ndarray.'						)

								if do_resize and size is None or resample is None:
									raise ValueError('Size and resample must be specified if do_resize is True.'						)

								if do_center_crop and crop_size is None:
									raise ValueError('Crop size must be specified if do_center_crop is True.'						)

								if do_rescale and rescale_factor is None:
									raise ValueError('Rescale factor must be specified if do_rescale is True.'						)

								if do_normalize and (image_mean is None or image_std is None):
									raise ValueError('Image mean and std must be specified if do_normalize is True.'						)

								# All transformations expect numpy arrays.
								_snake_case     		=	[to_numpy_array(lowerCAmelCase_						) for image in images]

								if do_resize:
									_snake_case     		=	[self.resize(image=lowerCAmelCase_					,     size=lowerCAmelCase_					,     resample=lowerCAmelCase_						) for image in images]

								if do_center_crop:
									_snake_case     		=	[self.center_crop(image=lowerCAmelCase_					,     size=lowerCAmelCase_						) for image in images]

								if do_rescale:
									_snake_case     		=	[self.rescale(image=lowerCAmelCase_					,     scale=lowerCAmelCase_						) for image in images]

								if do_normalize:
									_snake_case     		=	[self.normalize(image=lowerCAmelCase_					,     mean=lowerCAmelCase_					,     std=lowerCAmelCase_						) for image in images]

								_snake_case     		=	[to_channel_dimension_format(lowerCAmelCase_					,     lowerCAmelCase_						) for image in images]

								_snake_case     		=	{'pixel_values': images}
								return BatchFeature(data=lowerCAmelCase_					,     tensor_type=lowerCAmelCase_						)



'''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 		__UpperCAmelCase   :


							def __init__( self					,     lowerCAmelCase_					,     lowerCAmelCase_=13					,     lowerCAmelCase_=7					,     lowerCAmelCase_=True					,     lowerCAmelCase_=True					,     lowerCAmelCase_=True					,     lowerCAmelCase_=99					,     lowerCAmelCase_=32					,     lowerCAmelCase_=5					,     lowerCAmelCase_=4					,     lowerCAmelCase_=37					,     lowerCAmelCase_="gelu"					,     lowerCAmelCase_=0.1					,     lowerCAmelCase_=0.1					,     lowerCAmelCase_=5_12					,     lowerCAmelCase_=16					,     lowerCAmelCase_=2					,     lowerCAmelCase_=0.02					,     lowerCAmelCase_=3					,     lowerCAmelCase_=4					,     lowerCAmelCase_=None					,     ):





								"""simple docstring"""






								_snake_case     		=	parent
								_snake_case     		=	batch_size
								_snake_case     		=	seq_length
								_snake_case     		=	is_training
								_snake_case     		=	use_token_type_ids
								_snake_case     		=	use_labels
								_snake_case     		=	vocab_size
								_snake_case     		=	hidden_size
								_snake_case     		=	num_hidden_layers
								_snake_case     		=	num_attention_heads
								_snake_case     		=	intermediate_size
								_snake_case     		=	hidden_act
								_snake_case     		=	hidden_dropout_prob
								_snake_case     		=	attention_probs_dropout_prob
								_snake_case     		=	max_position_embeddings
								_snake_case     		=	type_vocab_size
								_snake_case     		=	type_sequence_label_size
								_snake_case     		=	initializer_range
								_snake_case     		=	num_labels
								_snake_case     		=	num_choices
								_snake_case     		=	scope
								_snake_case     		=	self.vocab_size - 1


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	ids_tensor([self.batch_size, self.seq_length]					,     self.vocab_size						)

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

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

								_snake_case     		=	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					,     )

								_snake_case     		=	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 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTModel(config=lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_					,     head_mask=lowerCAmelCase_						)
								_snake_case     		=	model(lowerCAmelCase_					,     token_type_ids=lowerCAmelCase_						)
								_snake_case     		=	model(lowerCAmelCase_						)

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


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTLMHeadModel(lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

								_snake_case     		=	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					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTDoubleHeadsModel(lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

								_snake_case     		=	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					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     *lowerCAmelCase_						):





								"""simple docstring"""






								_snake_case     		=	self.num_labels
								_snake_case     		=	OpenAIGPTForSequenceClassification(lowerCAmelCase_						)
								model.to(lowerCAmelCase_						)
								model.eval()

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




							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.prepare_config_and_inputs()
								(
								    (
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				(
								    _snake_case
								)		,				
								)     		=	config_and_inputs
								_snake_case     		=	{
								    'input_ids': input_ids,
								    'token_type_ids': token_type_ids,
								    'head_mask': head_mask,
								}

								return config, inputs_dict


@require_torch
class 		__UpperCAmelCase   (      _lowerCamelCase		,     _lowerCamelCase		,     _lowerCamelCase		,     unittest.TestCase		):
							__lowercase   	= (
							    (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
							    if is_torch_available()
							    else ()
							)
							__lowercase   	= (
							    (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
							)  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
							__lowercase   	= (
							    {
							        """feature-extraction""": OpenAIGPTModel,
							        """text-classification""": OpenAIGPTForSequenceClassification,
							        """text-generation""": OpenAIGPTLMHeadModel,
							        """zero-shot""": OpenAIGPTForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)


							def 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_						):





								"""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 				lowerCamelCase       ( self					,     lowerCAmelCase_					,     lowerCAmelCase_					,     lowerCAmelCase_=False						):





								"""simple docstring"""






								_snake_case     		=	super()._prepare_for_class(lowerCAmelCase_					,     lowerCAmelCase_					,     return_labels=lowerCAmelCase_						)

								if return_labels:
									if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
										_snake_case     		=	torch.zeros(
										    (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)					,     dtype=torch.long					,     device=lowerCAmelCase_					,     )
										_snake_case     		=	inputs_dict['labels']
										_snake_case     		=	inputs_dict['labels']
										_snake_case     		=	torch.zeros(
										    (self.model_tester.batch_size, self.model_tester.num_choices)					,     dtype=torch.long					,     device=lowerCAmelCase_					,     )
										_snake_case     		=	torch.zeros(
										    self.model_tester.batch_size					,     dtype=torch.long					,     device=lowerCAmelCase_						)
								return inputs_dict


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTModelTester(self						)
								_snake_case     		=	ConfigTester(self					,     config_class=lowerCAmelCase_					,     n_embd=37						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								self.config_tester.run_common_tests()


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_openai_gpt_model(*lowerCAmelCase_						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_lm_head_model(*lowerCAmelCase_						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_double_lm_head_model(*lowerCAmelCase_						)


							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*lowerCAmelCase_						)




							@slow
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






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


@require_torch
class 		__UpperCAmelCase   (      unittest.TestCase		):


							@slow
							def 				lowerCamelCase       ( self						):





								"""simple docstring"""






								_snake_case     		=	OpenAIGPTLMHeadModel.from_pretrained('openai-gpt'						)
								model.to(lowerCAmelCase_						)
								_snake_case     		=	torch.tensor([[4_81, 47_35, 5_44]]					,     dtype=torch.long					,     device=lowerCAmelCase_						)  # the president is
								_snake_case     		=	[
								    4_81,
								    47_35,
								    5_44,
								    2_46,
								    9_63,
								    8_70,
								    7_62,
								    2_39,
								    2_44,
								    4_04_77,
								    2_44,
								    2_49,
								    7_19,
								    8_81,
								    4_87,
								    5_44,
								    2_40,
								    2_44,
								    6_03,
								    4_81,
								]  # the president is a very good man. " \n " i\'m sure he is, " said the

								_snake_case     		=	model.generate(lowerCAmelCase_					,     do_sample=lowerCAmelCase_						)
								self.assertListEqual(output_ids[0].tolist()					,     lowerCAmelCase_						)

