

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 ChineseCLIPImageProcessor


class 			A						(							unittest.TestCase			):







    """simple docstring"""





    def __init__(				self			:	str,lowercase_			:	List[str],lowercase_			:	Optional[Any]=7,lowercase_			:	Optional[int]=3,lowercase_			:	Dict=1_8,lowercase_			:	Tuple=3_0,lowercase_			:	List[str]=4_0_0,lowercase_			:	Union[str, Any]=True,lowercase_			:	Optional[Any]=None,lowercase_			:	Any=True,lowercase_			:	List[Any]=None,lowercase_			:	Tuple=True,lowercase_			:	str=[0.48_145_466, 0.4_578_275, 0.40_821_073],lowercase_			:	Any=[0.26_862_954, 0.26_130_258, 0.27_577_711],lowercase_			:	List[Any]=True,)->   Optional[Any]:





        '''simple docstring'''







        A__   				=       size if size is not None else {'height': 2_2_4, 'width': 2_2_4}
        A__   				=       crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8}
        A__   				=       parent
        A__   				=       batch_size
        A__   				=       num_channels
        A__   				=       image_size
        A__   				=       min_resolution
        A__   				=       max_resolution
        A__   				=       do_resize
        A__   				=       size
        A__   				=       do_center_crop
        A__   				=       crop_size
        A__   				=       do_normalize
        A__   				=       image_mean
        A__   				=       image_std
        A__   				=       do_convert_rgb


    def 						snake_case__					(				self			:	str		)->   Optional[Any]:





        '''simple docstring'''







        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_center_crop": self.do_center_crop,
            "crop_size": self.crop_size,
            "do_normalize": self.do_normalize,
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_convert_rgb": self.do_convert_rgb,
        }


    def 						snake_case__					(				self			:	Tuple,lowercase_			:	List[Any]=False,lowercase_			:	Union[str, Any]=False,lowercase_			:	List[Any]=False		)->   int:





        '''simple docstring'''







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

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

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

        if torchify:
            A__   				=       [torch.from_numpy(lowercase_		) for x in image_inputs]

        return image_inputs




@require_torch
@require_vision
class 			A						(							_UpperCAmelCase   ,							unittest.TestCase			):







    """simple docstring"""





    lowerCamelCase		     =							ChineseCLIPImageProcessor if is_vision_available() else None


    def 						snake_case__					(				self			:	Dict		)->   Any:





        '''simple docstring'''







        A__   				=       ChineseCLIPImageProcessingTester(self,do_center_crop=lowercase_		)


    @property
    def 						snake_case__					(				self			:	List[Any]		)->   int:





        '''simple docstring'''







        return self.image_processor_tester.prepare_image_processor_dict()


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





        '''simple docstring'''







        A__   				=       self.image_processing_class(**self.image_processor_dict		)
        self.assertTrue(hasattr(lowercase_,'do_resize'		)		)
        self.assertTrue(hasattr(lowercase_,'size'		)		)
        self.assertTrue(hasattr(lowercase_,'do_center_crop'		)		)
        self.assertTrue(hasattr(lowercase_,'center_crop'		)		)
        self.assertTrue(hasattr(lowercase_,'do_normalize'		)		)
        self.assertTrue(hasattr(lowercase_,'image_mean'		)		)
        self.assertTrue(hasattr(lowercase_,'image_std'		)		)
        self.assertTrue(hasattr(lowercase_,'do_convert_rgb'		)		)


    def 						snake_case__					(				self			:	Optional[Any]		)->   int:





        '''simple docstring'''







        A__   				=       self.image_processing_class.from_dict(self.image_processor_dict		)
        self.assertEqual(image_processor.size,{'height': 2_2_4, 'width': 2_2_4}		)
        self.assertEqual(image_processor.crop_size,{'height': 1_8, 'width': 1_8}		)

        A__   				=       self.image_processing_class.from_dict(self.image_processor_dict,size=4_2,crop_size=8_4		)
        self.assertEqual(image_processor.size,{'shortest_edge': 4_2}		)
        self.assertEqual(image_processor.crop_size,{'height': 8_4, 'width': 8_4}		)


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





        '''simple docstring'''







        pass


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





        '''simple docstring'''







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

        # Test not batched input
        A__   				=       image_processing(image_inputs[0],return_tensors='pt'		).pixel_values
        self.assertEqual(
            encoded_images.shape,(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            ),)

        # Test batched
        A__   				=       image_processing(lowercase_,return_tensors='pt'		).pixel_values
        self.assertEqual(
            encoded_images.shape,(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            ),)


    def 						snake_case__					(				self			:	Optional[Any]		)->   str:





        '''simple docstring'''







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

        # Test not batched input
        A__   				=       image_processing(image_inputs[0],return_tensors='pt'		).pixel_values
        self.assertEqual(
            encoded_images.shape,(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            ),)

        # Test batched
        A__   				=       image_processing(lowercase_,return_tensors='pt'		).pixel_values
        self.assertEqual(
            encoded_images.shape,(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            ),)


    def 						snake_case__					(				self			:	int		)->   Any:





        '''simple docstring'''







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

        # Test not batched input
        A__   				=       image_processing(image_inputs[0],return_tensors='pt'		).pixel_values
        self.assertEqual(
            encoded_images.shape,(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            ),)

        # Test batched
        A__   				=       image_processing(lowercase_,return_tensors='pt'		).pixel_values
        self.assertEqual(
            encoded_images.shape,(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            ),)




@require_torch
@require_vision
class 			A						(							_UpperCAmelCase   ,							unittest.TestCase			):







    """simple docstring"""





    lowerCamelCase		     =							ChineseCLIPImageProcessor if is_vision_available() else None


    def 						snake_case__					(				self			:	List[Any]		)->   List[Any]:





        '''simple docstring'''







        A__   				=       ChineseCLIPImageProcessingTester(self,num_channels=4,do_center_crop=lowercase_		)
        A__   				=       3


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





        '''simple docstring'''







        return self.image_processor_tester.prepare_image_processor_dict()


    def 						snake_case__					(				self			:	List[Any]		)->   List[str]:





        '''simple docstring'''







        A__   				=       self.image_processing_class(**self.image_processor_dict		)
        self.assertTrue(hasattr(lowercase_,'do_resize'		)		)
        self.assertTrue(hasattr(lowercase_,'size'		)		)
        self.assertTrue(hasattr(lowercase_,'do_center_crop'		)		)
        self.assertTrue(hasattr(lowercase_,'center_crop'		)		)
        self.assertTrue(hasattr(lowercase_,'do_normalize'		)		)
        self.assertTrue(hasattr(lowercase_,'image_mean'		)		)
        self.assertTrue(hasattr(lowercase_,'image_std'		)		)
        self.assertTrue(hasattr(lowercase_,'do_convert_rgb'		)		)


    def 						snake_case__					(				self			:	List[Any]		)->   List[str]:





        '''simple docstring'''







        pass


    def 						snake_case__					(				self			:	List[Any]		)->   int:





        '''simple docstring'''







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

        # Test not batched input
        A__   				=       image_processing(image_inputs[0],return_tensors='pt'		).pixel_values
        self.assertEqual(
            encoded_images.shape,(
                1,
                self.expected_encoded_image_num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            ),)

        # Test batched
        A__   				=       image_processing(lowercase_,return_tensors='pt'		).pixel_values
        self.assertEqual(
            encoded_images.shape,(
                self.image_processor_tester.batch_size,
                self.expected_encoded_image_num_channels,
                self.image_processor_tester.crop_size['height'],
                self.image_processor_tester.crop_size['width'],
            ),)




import os
import tempfile
import unittest
from pathlib import Path

from transformers import AutoConfig, is_torch_available
from transformers.testing_utils import require_torch, torch_device


if is_torch_available():
     from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments


@require_torch
class 			A						(							unittest.TestCase			):







    """simple docstring"""





    def 						snake_case__					(				self			:	List[Any],lowercase_			:	str		)->   List[Any]:





        '''simple docstring'''







        for model_result in results.values():
            for batch_size, sequence_length in zip(model_result['bs'],model_result['ss']		):
                A__   				=       model_result['result'][batch_size][sequence_length]
                self.assertIsNotNone(lowercase_		)


    def 						snake_case__					(				self			:	Dict		)->   List[str]:





        '''simple docstring'''







        A__   				=       'sshleifer/tiny-gpt2'
        A__   				=       PyTorchBenchmarkArguments(
            models=[MODEL_ID],training=lowercase_,inference=lowercase_,sequence_lengths=[8],batch_sizes=[1],multi_process=lowercase_,)
        A__   				=       PyTorchBenchmark(lowercase_		)
        A__   				=       benchmark.run()
        self.check_results_dict_not_empty(results.time_inference_result		)
        self.check_results_dict_not_empty(results.memory_inference_result		)


    def 						snake_case__					(				self			:	Dict		)->   List[str]:





        '''simple docstring'''







        A__   				=       'sgugger/tiny-distilbert-classification'
        A__   				=       PyTorchBenchmarkArguments(
            models=[MODEL_ID],training=lowercase_,inference=lowercase_,sequence_lengths=[8],batch_sizes=[1],multi_process=lowercase_,only_pretrain_model=lowercase_,)
        A__   				=       PyTorchBenchmark(lowercase_		)
        A__   				=       benchmark.run()
        self.check_results_dict_not_empty(results.time_inference_result		)
        self.check_results_dict_not_empty(results.memory_inference_result		)


    def 						snake_case__					(				self			:	List[Any]		)->   Any:





        '''simple docstring'''







        A__   				=       'sshleifer/tiny-gpt2'
        A__   				=       PyTorchBenchmarkArguments(
            models=[MODEL_ID],training=lowercase_,inference=lowercase_,torchscript=lowercase_,sequence_lengths=[8],batch_sizes=[1],multi_process=lowercase_,)
        A__   				=       PyTorchBenchmark(lowercase_		)
        A__   				=       benchmark.run()
        self.check_results_dict_not_empty(results.time_inference_result		)
        self.check_results_dict_not_empty(results.memory_inference_result		)


    @unittest.skipIf(torch_device == 'cpu','Cant do half precision'		)
    def 						snake_case__					(				self			:	Any		)->   Dict:





        '''simple docstring'''







        A__   				=       'sshleifer/tiny-gpt2'
        A__   				=       PyTorchBenchmarkArguments(
            models=[MODEL_ID],training=lowercase_,inference=lowercase_,fpaa=lowercase_,sequence_lengths=[8],batch_sizes=[1],multi_process=lowercase_,)
        A__   				=       PyTorchBenchmark(lowercase_		)
        A__   				=       benchmark.run()
        self.check_results_dict_not_empty(results.time_inference_result		)
        self.check_results_dict_not_empty(results.memory_inference_result		)


    def 						snake_case__					(				self			:	Any		)->   Optional[Any]:





        '''simple docstring'''







        A__   				=       'sshleifer/tiny-gpt2'
        A__   				=       AutoConfig.from_pretrained(lowercase_		)
        # set architectures equal to `None`
        A__   				=       None
        A__   				=       PyTorchBenchmarkArguments(
            models=[MODEL_ID],training=lowercase_,inference=lowercase_,sequence_lengths=[8],batch_sizes=[1],multi_process=lowercase_,)
        A__   				=       PyTorchBenchmark(lowercase_,configs=[config]		)
        A__   				=       benchmark.run()
        self.check_results_dict_not_empty(results.time_inference_result		)
        self.check_results_dict_not_empty(results.memory_inference_result		)


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





        '''simple docstring'''







        A__   				=       'sshleifer/tiny-gpt2'
        A__   				=       PyTorchBenchmarkArguments(
            models=[MODEL_ID],training=lowercase_,inference=lowercase_,sequence_lengths=[8],batch_sizes=[1],multi_process=lowercase_,)
        A__   				=       PyTorchBenchmark(lowercase_		)
        A__   				=       benchmark.run()
        self.check_results_dict_not_empty(results.time_train_result		)
        self.check_results_dict_not_empty(results.memory_train_result		)


    @unittest.skipIf(torch_device == 'cpu','Can\'t do half precision'		)
    def 						snake_case__					(				self			:	List[Any]		)->   Dict:





        '''simple docstring'''







        A__   				=       'sshleifer/tiny-gpt2'
        A__   				=       PyTorchBenchmarkArguments(
            models=[MODEL_ID],training=lowercase_,inference=lowercase_,sequence_lengths=[8],batch_sizes=[1],fpaa=lowercase_,multi_process=lowercase_,)
        A__   				=       PyTorchBenchmark(lowercase_		)
        A__   				=       benchmark.run()
        self.check_results_dict_not_empty(results.time_train_result		)
        self.check_results_dict_not_empty(results.memory_train_result		)


    def 						snake_case__					(				self			:	int		)->   Optional[int]:





        '''simple docstring'''







        A__   				=       'sshleifer/tiny-gpt2'
        A__   				=       AutoConfig.from_pretrained(lowercase_		)
        A__   				=       PyTorchBenchmarkArguments(
            models=[MODEL_ID],training=lowercase_,inference=lowercase_,sequence_lengths=[8],batch_sizes=[1],multi_process=lowercase_,)
        A__   				=       PyTorchBenchmark(lowercase_,configs=[config]		)
        A__   				=       benchmark.run()
        self.check_results_dict_not_empty(results.time_inference_result		)
        self.check_results_dict_not_empty(results.memory_inference_result		)


    def 						snake_case__					(				self			:	List[Any]		)->   Any:





        '''simple docstring'''







        A__   				=       'sshleifer/tinier_bart'
        A__   				=       AutoConfig.from_pretrained(lowercase_		)
        A__   				=       PyTorchBenchmarkArguments(
            models=[MODEL_ID],training=lowercase_,inference=lowercase_,sequence_lengths=[8],batch_sizes=[1],multi_process=lowercase_,)
        A__   				=       PyTorchBenchmark(lowercase_,configs=[config]		)
        A__   				=       benchmark.run()
        self.check_results_dict_not_empty(results.time_inference_result		)
        self.check_results_dict_not_empty(results.memory_inference_result		)


    def 						snake_case__					(				self			:	List[str]		)->   List[str]:





        '''simple docstring'''







        A__   				=       'sshleifer/tiny-gpt2'
        A__   				=       AutoConfig.from_pretrained(lowercase_		)
        A__   				=       PyTorchBenchmarkArguments(
            models=[MODEL_ID],training=lowercase_,inference=lowercase_,sequence_lengths=[8],batch_sizes=[1],multi_process=lowercase_,)
        A__   				=       PyTorchBenchmark(lowercase_,configs=[config]		)
        A__   				=       benchmark.run()
        self.check_results_dict_not_empty(results.time_train_result		)
        self.check_results_dict_not_empty(results.memory_train_result		)


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





        '''simple docstring'''







        A__   				=       'sshleifer/tinier_bart'
        A__   				=       AutoConfig.from_pretrained(lowercase_		)
        A__   				=       PyTorchBenchmarkArguments(
            models=[MODEL_ID],training=lowercase_,inference=lowercase_,sequence_lengths=[8],batch_sizes=[1],multi_process=lowercase_,)
        A__   				=       PyTorchBenchmark(lowercase_,configs=[config]		)
        A__   				=       benchmark.run()
        self.check_results_dict_not_empty(results.time_train_result		)
        self.check_results_dict_not_empty(results.memory_train_result		)


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





        '''simple docstring'''







        A__   				=       'sshleifer/tiny-gpt2'
        with tempfile.TemporaryDirectory() as tmp_dir:
            A__   				=       PyTorchBenchmarkArguments(
                models=[MODEL_ID],training=lowercase_,inference=lowercase_,save_to_csv=lowercase_,sequence_lengths=[8],batch_sizes=[1],inference_time_csv_file=os.path.join(lowercase_,'inf_time.csv'		),train_memory_csv_file=os.path.join(lowercase_,'train_mem.csv'		),inference_memory_csv_file=os.path.join(lowercase_,'inf_mem.csv'		),train_time_csv_file=os.path.join(lowercase_,'train_time.csv'		),env_info_csv_file=os.path.join(lowercase_,'env.csv'		),multi_process=lowercase_,)
            A__   				=       PyTorchBenchmark(lowercase_		)
            benchmark.run()
            self.assertTrue(Path(os.path.join(lowercase_,'inf_time.csv'		)		).exists()		)
            self.assertTrue(Path(os.path.join(lowercase_,'train_time.csv'		)		).exists()		)
            self.assertTrue(Path(os.path.join(lowercase_,'inf_mem.csv'		)		).exists()		)
            self.assertTrue(Path(os.path.join(lowercase_,'train_mem.csv'		)		).exists()		)
            self.assertTrue(Path(os.path.join(lowercase_,'env.csv'		)		).exists()		)


    def 						snake_case__					(				self			:	Tuple		)->   str:





        '''simple docstring'''







        A__   				=       'sshleifer/tiny-gpt2'

        def _check_summary_is_not_empty(lowercase_			:	Optional[Any]		):
            self.assertTrue(hasattr(lowercase_,'sequential'		)		)
            self.assertTrue(hasattr(lowercase_,'cumulative'		)		)
            self.assertTrue(hasattr(lowercase_,'current'		)		)
            self.assertTrue(hasattr(lowercase_,'total'		)		)

        with tempfile.TemporaryDirectory() as tmp_dir:
            A__   				=       PyTorchBenchmarkArguments(
                models=[MODEL_ID],training=lowercase_,inference=lowercase_,sequence_lengths=[8],batch_sizes=[1],log_filename=os.path.join(lowercase_,'log.txt'		),log_print=lowercase_,trace_memory_line_by_line=lowercase_,multi_process=lowercase_,)
            A__   				=       PyTorchBenchmark(lowercase_		)
            A__   				=       benchmark.run()
            _check_summary_is_not_empty(result.inference_summary		)
            _check_summary_is_not_empty(result.train_summary		)
            self.assertTrue(Path(os.path.join(lowercase_,'log.txt'		)		).exists()		)

