





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


if is_torch_available():
     import torch

if is_vision_available():
     from PIL import Image

     from transformers import SwinaSRImageProcessor
     from transformers.image_transforms import get_image_size



class 				_UpperCamelCase       (						unittest.TestCase  ):

       def __init__(		self:			List[Any]       , _SCREAMING_SNAKE_CASE:			Tuple       , _SCREAMING_SNAKE_CASE:			Optional[Any]=7       , _SCREAMING_SNAKE_CASE:			Any=3       , _SCREAMING_SNAKE_CASE:			List[Any]=18       , _SCREAMING_SNAKE_CASE:			Tuple=30       , _SCREAMING_SNAKE_CASE:			List[str]=400       , _SCREAMING_SNAKE_CASE:			Tuple=True       , _SCREAMING_SNAKE_CASE:			List[str]=1 / 255       , _SCREAMING_SNAKE_CASE:			List[Any]=True       , _SCREAMING_SNAKE_CASE:			Tuple=8       , )							->			Optional[int]:




              """simple docstring"""


              UpperCamelCase_ 							=	parent
              UpperCamelCase_ 							=	batch_size
              UpperCamelCase_ 							=	num_channels
              UpperCamelCase_ 							=	image_size
              UpperCamelCase_ 							=	min_resolution
              UpperCamelCase_ 							=	max_resolution
              UpperCamelCase_ 							=	do_rescale
              UpperCamelCase_ 							=	rescale_factor
              UpperCamelCase_ 							=	do_pad
              UpperCamelCase_ 							=	pad_size

       def lowercase			(		self:			Tuple		)							->			Optional[Any]:




              """simple docstring"""


              return {
                  "do_rescale": self.do_rescale,
                  "rescale_factor": self.rescale_factor,
                  "do_pad": self.do_pad,
                  "pad_size": self.pad_size,
              }



       def lowercase			(		self:			Tuple       , _SCREAMING_SNAKE_CASE:			List[Any]=False       , _SCREAMING_SNAKE_CASE:			List[str]=False       , _SCREAMING_SNAKE_CASE:			Any=False		)							->			List[str]:




              """simple docstring"""


              assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

              if equal_resolution:
                     UpperCamelCase_ 							=	[]
                     for i in range(self.batch_size		):
                            image_inputs.append(
                                np.random.randint(
                                    255       , size=(self.num_channels, self.max_resolution, self.max_resolution)       , dtype=np.uinta		)		)
              else:
                     UpperCamelCase_ 							=	[]
                     for i in range(self.batch_size		):
                            UpperCamelCase_							,			UpperCamelCase_ 							=	np.random.choice(np.arange(self.min_resolution       , self.max_resolution		)       , 2		)
                            image_inputs.append(np.random.randint(255       , size=(self.num_channels, width, height)       , dtype=np.uinta		)		)

              if not numpify and not torchify:
                     # PIL expects the channel dimension as last dimension
                     UpperCamelCase_ 							=	[Image.fromarray(np.moveaxis(_SCREAMING_SNAKE_CASE       , 0       , -1		)		) for x in image_inputs]

              if torchify:
                     UpperCamelCase_ 							=	[torch.from_numpy(_SCREAMING_SNAKE_CASE		) for x in image_inputs]

              return image_inputs



@require_torch
@require_vision
class 				_UpperCamelCase       (						lowerCAmelCase_	,    unittest.TestCase  ):
       _UpperCamelCase					:       Union[str, Any]       = SwinaSRImageProcessor if is_vision_available() else None

       def lowercase			(		self:			Union[str, Any]		)							->			str:




              """simple docstring"""


              UpperCamelCase_ 							=	SwinaSRImageProcessingTester(self		)

       @property
       def lowercase			(		self:			Optional[int]		)							->			Optional[int]:




              """simple docstring"""


              return self.image_processor_tester.prepare_image_processor_dict()

       def lowercase			(		self:			Tuple		)							->			Optional[Any]:




              """simple docstring"""


              UpperCamelCase_ 							=	self.image_processing_class(**self.image_processor_dict		)
              self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE       , "do_rescale"		)		)
              self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE       , "rescale_factor"		)		)
              self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE       , "do_pad"		)		)
              self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE       , "pad_size"		)		)

       def lowercase			(		self:			List[Any]		)							->			Tuple:




              """simple docstring"""


              pass

       def lowercase			(		self:			int       , _SCREAMING_SNAKE_CASE:			Optional[Any]		)							->			Dict:




              """simple docstring"""


              UpperCamelCase_							,			UpperCamelCase_ 							=	get_image_size(_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_ 							=	self.image_processor_tester.pad_size

              UpperCamelCase_ 							=	(old_height // size + 1) * size - old_height
              UpperCamelCase_ 							=	(old_width // size + 1) * size - old_width
              return old_height + pad_height, old_width + pad_width

       def lowercase			(		self:			Dict		)							->			Any:




              """simple docstring"""


              UpperCamelCase_ 							=	self.image_processing_class(**self.image_processor_dict		)
              # create random PIL images
              UpperCamelCase_ 							=	self.image_processor_tester.prepare_inputs(equal_resolution=_SCREAMING_SNAKE_CASE		)
              for image in image_inputs:
                     self.assertIsInstance(_SCREAMING_SNAKE_CASE       , Image.Image		)

              # Test not batched input
              UpperCamelCase_ 							=	image_processor(image_inputs[0]       , return_tensors="pt"		).pixel_values
              UpperCamelCase_							,			UpperCamelCase_ 							=	self.calculate_expected_size(np.array(image_inputs[0]		)		)
              self.assertEqual(
                  encoded_images.shape       , (
                      1,
                      self.image_processor_tester.num_channels,
                      expected_height,
                      expected_width,
                  )       , )

       def lowercase			(		self:			Any		)							->			Any:




              """simple docstring"""


              UpperCamelCase_ 							=	self.image_processing_class(**self.image_processor_dict		)
              # create random numpy tensors
              UpperCamelCase_ 							=	self.image_processor_tester.prepare_inputs(equal_resolution=_SCREAMING_SNAKE_CASE       , numpify=_SCREAMING_SNAKE_CASE		)
              for image in image_inputs:
                     self.assertIsInstance(_SCREAMING_SNAKE_CASE       , np.ndarray		)

              # Test not batched input
              UpperCamelCase_ 							=	image_processor(image_inputs[0]       , return_tensors="pt"		).pixel_values
              UpperCamelCase_							,			UpperCamelCase_ 							=	self.calculate_expected_size(image_inputs[0]		)
              self.assertEqual(
                  encoded_images.shape       , (
                      1,
                      self.image_processor_tester.num_channels,
                      expected_height,
                      expected_width,
                  )       , )



       def lowercase			(		self:			str		)							->			Optional[int]:




              """simple docstring"""


              UpperCamelCase_ 							=	self.image_processing_class(**self.image_processor_dict		)
              # create random PyTorch tensors
              UpperCamelCase_ 							=	self.image_processor_tester.prepare_inputs(equal_resolution=_SCREAMING_SNAKE_CASE       , torchify=_SCREAMING_SNAKE_CASE		)
              for image in image_inputs:
                     self.assertIsInstance(_SCREAMING_SNAKE_CASE       , torch.Tensor		)

              # Test not batched input
              UpperCamelCase_ 							=	image_processor(image_inputs[0]       , return_tensors="pt"		).pixel_values
              UpperCamelCase_							,			UpperCamelCase_ 							=	self.calculate_expected_size(image_inputs[0]		)
              self.assertEqual(
                  encoded_images.shape       , (
                      1,
                      self.image_processor_tester.num_channels,
                      expected_height,
                      expected_width,
                  )       , )









"""simple docstring"""


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 							_SCREAMING_SNAKE_CASE							(      self					:	int    ):

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

     __A		     =					torch.tensor(
         [[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]],			device=_lowerCamelCase,			dtype=torch.long,			)

     with torch.no_grad():
       __A		     =					model(_lowerCamelCase    ).logits

     __A		     =					torch.Size((1, 9, 5_02_57)    )
     self.assertEqual(output.shape,			_lowerCamelCase    )

     __A		     =					torch.tensor(
         [
             4.94_14,
             -0.29_20,
             -1.21_48,
             -4.02_73,
             -0.51_61,
             -5.21_09,
             -1.24_12,
             -1.83_01,
             -1.77_34,
             -4.71_48,
             -0.23_17,
             -1.08_11,
             -2.17_77,
             0.41_41,
             -3.79_69,
             -4.05_86,
             -2.53_32,
             -3.38_09,
             4.38_67,
         ],			device=_lowerCamelCase,			dtype=torch.half,			)

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




