






"""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 (
    get_resize_output_image_size,
    normalize,
    pad,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging
from ...utils.import_utils import is_vision_available


A_     =				logging.get_logger(__name__)


if is_vision_available():
						import PIL






class 				__SCREAMING_SNAKE_CASE    (					_a		):
							snake_case_  =				['pixel_values']


							def __init__(      self   :    Optional[int]      ,     snake_case   :    bool = True      ,     snake_case   :    Dict[str, int] = None      ,     snake_case   :    PILImageResampling = PILImageResampling.BILINEAR      ,     snake_case   :    bool = True      ,     snake_case   :    bool = False      ,     snake_case   :    bool = True      ,     snake_case   :    bool = True      ,     snake_case   :    Union[int, float] = 1 / 255      ,     snake_case   :    bool = True      ,     snake_case   :    Optional[Union[float, List[float]]] = None      ,     snake_case   :    Optional[Union[float, List[float]]] = None      ,     **snake_case   :    Dict      ,     ):
													'''simple docstring'''





													super().__init__(**snake_case				)

													A__    :	List[str]			=	size if size is not None else {"""height""": 2560, """width""": 1920}
													if isinstance(snake_case      ,     (tuple, list)				):
																			# The previous feature extractor size parameter was in (width, height) format
																			A__    :	Any			=	size[::-1]
													A__    :	List[Any]			=	get_size_dict(snake_case				)

													A__    :	str			=	do_resize
													A__    :	Optional[int]			=	size
													A__    :	List[Any]			=	resample
													A__    :	int			=	do_thumbnail
													A__    :	List[Any]			=	do_align_long_axis
													A__    :	Tuple			=	do_pad
													A__    :	int			=	do_rescale
													A__    :	str			=	rescale_factor
													A__    :	List[str]			=	do_normalize
													A__    :	Union[str, Any]			=	image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
													A__    :	Optional[int]			=	image_std if image_std is not None else IMAGENET_STANDARD_STD


							def     _UpperCamelCase							(      self   :    str      ,     snake_case   :    np.ndarray      ,     snake_case   :    Dict[str, int]      ,     snake_case   :    Optional[Union[str, ChannelDimension]] = None				):
													'''simple docstring'''





													A__	,	A__    :	Tuple			=	get_image_size(snake_case				)
													A__	,	A__    :	Optional[Any]			=	size["""height"""], size["""width"""]

													if (output_width < output_height and input_width > input_height) or (
													    output_width > output_height and input_width < input_height
													):
																			A__    :	Union[str, Any]			=	np.rotaa(snake_case      ,     3				)

													if data_format is not None:
																			A__    :	List[str]			=	to_channel_dimension_format(snake_case      ,     snake_case				)

													return image


							def     _UpperCamelCase							(      self   :    Union[str, Any]      ,     snake_case   :    np.ndarray      ,     snake_case   :    Dict[str, int]      ,     snake_case   :    bool = False      ,     snake_case   :    Optional[Union[str, ChannelDimension]] = None      ,     ):
													'''simple docstring'''





													A__	,	A__    :	int			=	size["""height"""], size["""width"""]
													A__	,	A__    :	Union[str, Any]			=	get_image_size(snake_case				)

													A__    :	Optional[Any]			=	output_width - input_width
													A__    :	List[str]			=	output_height - input_height

													if random_padding:
																			A__    :	List[str]			=	np.random.randint(low=0      ,     high=delta_height + 1				)
																			A__    :	List[Any]			=	np.random.randint(low=0      ,     high=delta_width + 1				)
													else:
																			A__    :	Union[str, Any]			=	delta_height // 2
																			A__    :	Union[str, Any]			=	delta_width // 2

													A__    :	List[Any]			=	delta_height - pad_top
													A__    :	Union[str, Any]			=	delta_width - pad_left

													A__    :	Tuple			=	((pad_top, pad_bottom), (pad_left, pad_right))
													return pad(snake_case      ,     snake_case      ,     data_format=snake_case				)


							def     _UpperCamelCase							(      self   :    Any      ,     *snake_case   :    Dict      ,     **snake_case   :    Optional[Any]				):
													'''simple docstring'''





													logger.info("""pad is deprecated and will be removed in version 4.27. Please use pad_image instead."""				)
													return self.pad_image(*snake_case      ,     **snake_case				)


							def     _UpperCamelCase							(      self   :    Union[str, Any]      ,     snake_case   :    np.ndarray      ,     snake_case   :    Dict[str, int]      ,     snake_case   :    PILImageResampling = PILImageResampling.BICUBIC      ,     snake_case   :    Optional[Union[str, ChannelDimension]] = None      ,     **snake_case   :    Any      ,     ):
													'''simple docstring'''





													A__	,	A__    :	Optional[Any]			=	get_image_size(snake_case				)
													A__	,	A__    :	List[str]			=	size["""height"""], size["""width"""]

													# We always resize to the smallest of either the input or output size.
													A__    :	List[Any]			=	min(snake_case      ,     snake_case				)
													A__    :	int			=	min(snake_case      ,     snake_case				)

													if height == input_height and width == input_width:
																			return image

													if input_height > input_width:
																			A__    :	Dict			=	int(input_width * height / input_height				)
													elif input_width > input_height:
																			A__    :	Optional[Any]			=	int(input_height * width / input_width				)

													return resize(
													    snake_case      ,     size=(height, width)      ,     resample=snake_case      ,     reducing_gap=2.0      ,     data_format=snake_case      ,     **snake_case				)


							def     _UpperCamelCase							(      self   :    Optional[int]      ,     snake_case   :    np.ndarray      ,     snake_case   :    Dict[str, int]      ,     snake_case   :    PILImageResampling = PILImageResampling.BICUBIC      ,     snake_case   :    Optional[Union[str, ChannelDimension]] = None      ,     **snake_case   :    int      ,     ):
													'''simple docstring'''





													A__    :	List[Any]			=	get_size_dict(snake_case				)
													A__    :	List[str]			=	min(size["""height"""]      ,     size["""width"""]				)
													A__    :	Optional[Any]			=	get_resize_output_image_size(snake_case      ,     size=snake_case      ,     default_to_square=snake_case				)
													A__    :	int			=	resize(snake_case      ,     size=snake_case      ,     resample=snake_case      ,     data_format=snake_case      ,     **snake_case				)
													return resized_image


							def     _UpperCamelCase							(      self   :    Optional[int]      ,     snake_case   :    np.ndarray      ,     snake_case   :    Union[int, float]      ,     snake_case   :    Optional[Union[str, ChannelDimension]] = None      ,     **snake_case   :    Optional[Any]      ,     ):
													'''simple docstring'''





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


							def     _UpperCamelCase							(      self   :    Dict      ,     snake_case   :    np.ndarray      ,     snake_case   :    Union[float, List[float]]      ,     snake_case   :    Union[float, List[float]]      ,     snake_case   :    Optional[Union[str, ChannelDimension]] = None      ,     **snake_case   :    Optional[int]      ,     ):
													'''simple docstring'''





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


							def     _UpperCamelCase							(      self   :    Dict      ,     snake_case   :    ImageInput      ,     snake_case   :    bool = None      ,     snake_case   :    Dict[str, int] = None      ,     snake_case   :    PILImageResampling = None      ,     snake_case   :    bool = None      ,     snake_case   :    bool = None      ,     snake_case   :    bool = None      ,     snake_case   :    bool = False      ,     snake_case   :    bool = None      ,     snake_case   :    float = None      ,     snake_case   :    bool = None      ,     snake_case   :    Optional[Union[float, List[float]]] = None      ,     snake_case   :    Optional[Union[float, List[float]]] = None      ,     snake_case   :    Optional[Union[str, TensorType]] = None      ,     snake_case   :    Optional[ChannelDimension] = ChannelDimension.FIRST      ,     **snake_case   :    Dict      ,     ):
													'''simple docstring'''





													A__    :	Tuple			=	do_resize if do_resize is not None else self.do_resize
													A__    :	List[str]			=	size if size is not None else self.size
													if isinstance(snake_case      ,     (tuple, list)				):
																			# Previous feature extractor had size in (width, height) format
																			A__    :	Dict			=	size[::-1]
													A__    :	str			=	get_size_dict(snake_case				)
													A__    :	Dict			=	resample if resample is not None else self.resample
													A__    :	Optional[int]			=	do_thumbnail if do_thumbnail is not None else self.do_thumbnail
													A__    :	Union[str, Any]			=	do_align_long_axis if do_align_long_axis is not None else self.do_align_long_axis
													A__    :	str			=	do_pad if do_pad is not None else self.do_pad
													A__    :	Optional[int]			=	do_rescale if do_rescale is not None else self.do_rescale
													A__    :	Optional[int]			=	rescale_factor if rescale_factor is not None else self.rescale_factor
													A__    :	str			=	do_normalize if do_normalize is not None else self.do_normalize
													A__    :	int			=	image_mean if image_mean is not None else self.image_mean
													A__    :	Union[str, Any]			=	image_std if image_std is not None else self.image_std

													A__    :	Tuple			=	make_list_of_images(snake_case				)

													if not valid_images(snake_case				):
																			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:
																			raise ValueError("""Size must be specified if do_resize is True."""				)

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

													if do_pad and size is None:
																			raise ValueError("""Size must be specified if do_pad 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.
													A__    :	Union[str, Any]			=	[to_numpy_array(snake_case				) for image in images]

													if do_align_long_axis:
																			A__    :	List[str]			=	[self.align_long_axis(snake_case      ,     size=snake_case				) for image in images]

													if do_resize:
																			A__    :	Any			=	[self.resize(image=snake_case      ,     size=snake_case      ,     resample=snake_case				) for image in images]

													if do_thumbnail:
																			A__    :	int			=	[self.thumbnail(image=snake_case      ,     size=snake_case				) for image in images]

													if do_pad:
																			A__    :	int			=	[self.pad_image(image=snake_case      ,     size=snake_case      ,     random_padding=snake_case				) for image in images]

													if do_rescale:
																			A__    :	List[str]			=	[self.rescale(image=snake_case      ,     scale=snake_case				) for image in images]

													if do_normalize:
																			A__    :	Any			=	[self.normalize(image=snake_case      ,     mean=snake_case      ,     std=snake_case				) for image in images]

													A__    :	Union[str, Any]			=	[to_channel_dimension_format(snake_case      ,     snake_case				) for image in images]

													A__    :	int			=	{"""pixel_values""": images}
													return BatchFeature(data=snake_case      ,     tensor_type=snake_case				)













import os
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device


if is_torch_available():
      import torch

      from transformers import GPTaLMHeadModel

@require_torch
@require_sentencepiece
@require_tokenizers
class 	__snake_case					(      unittest.TestCase ):






    '''simple docstring'''





    @slow
    @unittest.skip('''Model is not available.'''				)
    def 						A		( self    :		str				):

      """simple docstring"""





      __lowerCAmelCase								=					'''nvidia/megatron-gpt2-345m/'''
      if "MYDIR" in os.environ:
        __lowerCAmelCase								=					os.path.join(os.environ['''MYDIR''']      ,    snake_case				)
      __lowerCAmelCase								=					GPTaLMHeadModel.from_pretrained(snake_case				)
      model.to(snake_case				)
      model.half()

      __lowerCAmelCase								=					torch.tensor(
          [[101, 7_110, 1_005, 1_056, 2_023, 11_333, 17_413, 1_029, 102]]      ,    device=snake_case      ,    dtype=torch.long      ,    )

      with torch.no_grad():
        __lowerCAmelCase								=					model(snake_case				).logits

      __lowerCAmelCase								=					torch.Size((1, 9, 50_257)				)
      self.assertEqual(output.shape      ,    snake_case				)

      __lowerCAmelCase								=					torch.tensor(
          [
              4.9414,
              -0.2920,
              -1.2148,
              -4.0273,
              -0.5161,
              -5.2109,
              -1.2412,
              -1.8301,
              -1.7734,
              -4.7148,
              -0.2317,
              -1.0811,
              -2.1777,
              0.4141,
              -3.7969,
              -4.0586,
              -2.5332,
              -3.3809,
              4.3867,
          ]      ,    device=snake_case      ,    dtype=torch.half      ,    )

      for i in range(19				):
        __lowerCAmelCase						,    __lowerCAmelCase								=					8 * i // 17, 2_792 * i  # along the diagonal
        __lowerCAmelCase						,    __lowerCAmelCase								=					output[0, r, c], expected_diag[i]
        __lowerCAmelCase								=					f'''row={r} col={c} computed={computed} expected={expected}'''
        self.assertAlmostEqual(snake_case      ,    snake_case      ,    delta=1e-4      ,    msg=snake_case				)
