



'''simple docstring'''



import unittest

import requests

from transformers import MODEL_FOR_VISION_2_SEQ_MAPPING, TF_MODEL_FOR_VISION_2_SEQ_MAPPING, is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    is_torch_available,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_torch_available():
				from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
				_lowercase       :						int						=False


if is_vision_available():
				from PIL import Image
else:






				class 			_SCREAMING_SNAKE_CASE				:



							@staticmethod
							def 				lowerCAmelCase (     *__UpperCamelCase		:						Optional[int]    ,			**__UpperCamelCase		:						int			)      ->      Dict:
											"""simple docstring"""





											pass






@is_pipeline_test
@require_vision
class 			_SCREAMING_SNAKE_CASE				(unittest.TestCase      ):
			A__								=  MODEL_FOR_VISION_2_SEQ_MAPPING
			A__								=  TF_MODEL_FOR_VISION_2_SEQ_MAPPING



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





							snake_case__      :   Dict      =    pipeline('''image-to-text'''    ,			model=__UpperCamelCase    ,			tokenizer=__UpperCamelCase    ,			image_processor=__UpperCamelCase			)
							snake_case__      :   Union[str, Any]      =    [
							    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			),
							    '''./tests/fixtures/tests_samples/COCO/000000039769.png''',
							]
							return pipe, examples



			def 				lowerCAmelCase (     self		:						Tuple    ,			__UpperCamelCase		:						Tuple    ,			__UpperCamelCase		:						Optional[Any]			)      ->      List[str]:
							"""simple docstring"""





							snake_case__      :   Any      =    pipe(__UpperCamelCase			)
							self.assertEqual(
							    __UpperCamelCase    ,			[
							        [{'''generated_text''': ANY(__UpperCamelCase			)}],
							        [{'''generated_text''': ANY(__UpperCamelCase			)}],
							    ]    ,			)



			@require_tf
			def 				lowerCAmelCase (     self		:						Dict			)      ->      Optional[Any]:
							"""simple docstring"""





							snake_case__      :   List[str]      =    pipeline('''image-to-text'''    ,			model='''hf-internal-testing/tiny-random-vit-gpt2'''    ,			framework='''tf'''			)
							snake_case__      :   Dict      =    '''./tests/fixtures/tests_samples/COCO/000000039769.png'''

							snake_case__      :   Optional[Any]      =    pipe(__UpperCamelCase			)
							self.assertEqual(
							    __UpperCamelCase    ,			[
							        {
							            '''generated_text''': '''growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'''
							        },
							    ]    ,			)

							snake_case__      :   Tuple      =    pipe([image, image]			)
							self.assertEqual(
							    __UpperCamelCase    ,			[
							        [
							            {
							                '''generated_text''': '''growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'''
							            }
							        ],
							        [
							            {
							                '''generated_text''': '''growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'''
							            }
							        ],
							    ]    ,			)

							snake_case__      :   List[str]      =    pipe(__UpperCamelCase    ,			max_new_tokens=1			)
							self.assertEqual(
							    __UpperCamelCase    ,			[{'''generated_text''': '''growth'''}]    ,			)



			@require_torch
			def 				lowerCAmelCase (     self		:						int			)      ->      Optional[Any]:
							"""simple docstring"""





							snake_case__      :   Union[str, Any]      =    pipeline('''image-to-text'''    ,			model='''hf-internal-testing/tiny-random-vit-gpt2'''			)
							snake_case__      :   str      =    '''./tests/fixtures/tests_samples/COCO/000000039769.png'''

							snake_case__      :   List[Any]      =    pipe(__UpperCamelCase			)
							self.assertEqual(
							    __UpperCamelCase    ,			[
							        {
							            '''generated_text''': '''growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'''
							        },
							    ]    ,			)

							snake_case__      :   Any      =    pipe([image, image]			)
							self.assertEqual(
							    __UpperCamelCase    ,			[
							        [
							            {
							                '''generated_text''': '''growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'''
							            }
							        ],
							        [
							            {
							                '''generated_text''': '''growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'''
							            }
							        ],
							    ]    ,			)



			@require_torch
			def 				lowerCAmelCase (     self		:						Any			)      ->      int:
							"""simple docstring"""





							snake_case__      :   Tuple      =    pipeline('''image-to-text'''    ,			model='''hf-internal-testing/tiny-random-BlipForConditionalGeneration'''			)
							snake_case__      :   Dict      =    '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
							snake_case__      :   List[str]      =    '''a photo of'''

							snake_case__      :   Optional[Any]      =    pipe(__UpperCamelCase    ,			prompt=__UpperCamelCase			)
							self.assertTrue(outputs[0]['''generated_text'''].startswith(__UpperCamelCase			)			)



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





							snake_case__      :   Union[str, Any]      =    pipeline('''image-to-text'''    ,			model='''ydshieh/vit-gpt2-coco-en'''			)
							snake_case__      :   str      =    '''./tests/fixtures/tests_samples/COCO/000000039769.png'''

							snake_case__      :   Optional[int]      =    pipe(__UpperCamelCase			)
							self.assertEqual(__UpperCamelCase    ,			[{'''generated_text''': '''a cat laying on a blanket next to a cat laying on a bed '''}]			)

							snake_case__      :   Union[str, Any]      =    pipe([image, image]			)
							self.assertEqual(
							    __UpperCamelCase    ,			[
							        [{'''generated_text''': '''a cat laying on a blanket next to a cat laying on a bed '''}],
							        [{'''generated_text''': '''a cat laying on a blanket next to a cat laying on a bed '''}],
							    ]    ,			)



			@slow
			@require_torch
			def 				lowerCAmelCase (     self		:						Optional[int]			)      ->      Tuple:
							"""simple docstring"""





							snake_case__      :   Any      =    pipeline('''image-to-text'''    ,			model='''Salesforce/blip-image-captioning-base'''			)
							snake_case__      :   Union[str, Any]      =    '''https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png'''
							snake_case__      :   Optional[int]      =    Image.open(requests.get(__UpperCamelCase    ,			stream=__UpperCamelCase			).raw			)

							snake_case__      :   List[Any]      =    pipe(__UpperCamelCase			)
							self.assertEqual(__UpperCamelCase    ,			[{'''generated_text''': '''a pink pokemon pokemon with a blue shirt and a blue shirt'''}]			)



			@slow
			@require_torch
			def 				lowerCAmelCase (     self		:						List[Any]			)      ->      Tuple:
							"""simple docstring"""





							snake_case__      :   int      =    pipeline('''image-to-text'''    ,			model='''microsoft/git-base-coco'''			)
							snake_case__      :   Any      =    '''https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png'''
							snake_case__      :   Any      =    Image.open(requests.get(__UpperCamelCase    ,			stream=__UpperCamelCase			).raw			)

							snake_case__      :   List[str]      =    pipe(__UpperCamelCase			)
							self.assertEqual(__UpperCamelCase    ,			[{'''generated_text''': '''a cartoon of a purple character.'''}]			)



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





							snake_case__      :   int      =    pipeline('''image-to-text'''    ,			model='''Salesforce/blip-image-captioning-base'''			)
							snake_case__      :   Union[str, Any]      =    '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'''
							snake_case__      :   Dict      =    Image.open(requests.get(__UpperCamelCase    ,			stream=__UpperCamelCase			).raw			)

							snake_case__      :   List[Any]      =    '''a photography of'''

							snake_case__      :   Union[str, Any]      =    pipe(__UpperCamelCase    ,			prompt=__UpperCamelCase			)
							self.assertEqual(__UpperCamelCase    ,			[{'''generated_text''': '''a photography of a volcano'''}]			)

							with self.assertRaises(__UpperCamelCase			):
											snake_case__      :   str      =    pipe([image, image]    ,			prompt=[prompt, prompt]			)



			@slow
			@require_torch
			def 				lowerCAmelCase (     self		:						str			)      ->      Dict:
							"""simple docstring"""





							snake_case__      :   List[Any]      =    pipeline('''image-to-text'''    ,			model='''microsoft/git-base-coco'''			)
							snake_case__      :   Optional[int]      =    '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'''
							snake_case__      :   Any      =    Image.open(requests.get(__UpperCamelCase    ,			stream=__UpperCamelCase			).raw			)

							snake_case__      :   Union[str, Any]      =    '''a photo of a'''

							snake_case__      :   str      =    pipe(__UpperCamelCase    ,			prompt=__UpperCamelCase			)
							self.assertEqual(__UpperCamelCase    ,			[{'''generated_text''': '''a photo of a tent with a tent and a tent in the background.'''}]			)

							with self.assertRaises(__UpperCamelCase			):
											snake_case__      :   Dict      =    pipe([image, image]    ,			prompt=[prompt, prompt]			)



			@unittest.skipIf(
			    not is_torch_greater_or_equal_than_1_11    ,			reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.'''			)
			@slow
			@require_torch
			def 				lowerCAmelCase (     self		:						str			)      ->      Tuple:
							"""simple docstring"""





							snake_case__      :   Tuple      =    pipeline('''image-to-text'''    ,			model='''google/pix2struct-ai2d-base'''			)
							snake_case__      :   Optional[int]      =    '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'''
							snake_case__      :   Any      =    Image.open(requests.get(__UpperCamelCase    ,			stream=__UpperCamelCase			).raw			)

							snake_case__      :   Tuple      =    '''What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud'''

							snake_case__      :   str      =    pipe(__UpperCamelCase    ,			prompt=__UpperCamelCase			)
							self.assertEqual(__UpperCamelCase    ,			[{'''generated_text''': '''ash cloud'''}]			)

							with self.assertRaises(__UpperCamelCase			):
											snake_case__      :   str      =    pipe([image, image]    ,			prompt=[prompt, prompt]			)







			@slow
			@require_tf
			def 				lowerCAmelCase (     self		:						Dict			)      ->      List[str]:
							"""simple docstring"""





							snake_case__      :   List[Any]      =    pipeline('''image-to-text'''    ,			model='''ydshieh/vit-gpt2-coco-en'''    ,			framework='''tf'''			)
							snake_case__      :   Optional[Any]      =    '''./tests/fixtures/tests_samples/COCO/000000039769.png'''

							snake_case__      :   Dict      =    pipe(__UpperCamelCase			)
							self.assertEqual(__UpperCamelCase    ,			[{'''generated_text''': '''a cat laying on a blanket next to a cat laying on a bed '''}]			)

							snake_case__      :   Union[str, Any]      =    pipe([image, image]			)
							self.assertEqual(
							    __UpperCamelCase    ,			[
							        [{'''generated_text''': '''a cat laying on a blanket next to a cat laying on a bed '''}],
							        [{'''generated_text''': '''a cat laying on a blanket next to a cat laying on a bed '''}],
							    ]    ,			)









"""simple docstring"""






import timeit
from typing import Callable, Optional

from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_auto import MODEL_MAPPING, MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_torch_available, logging
from .benchmark_utils import (
    Benchmark,
    Memory,
    MemorySummary,
    measure_peak_memory_cpu,
    start_memory_tracing,
    stop_memory_tracing,
)


if is_torch_available():
		import torch

		from .benchmark_args import PyTorchBenchmarkArguments


if is_pyanvml_available():
		import pyanvml.pyanvml as nvml


_lowercase					:					Optional[Any] 		=		logging.get_logger(__name__)

class 			__SCREAMING_SNAKE_CASE      ( lowerCAmelCase_  ):


					'''simple docstring'''





					_a       =				42
					_a       =				42
					_a       =				"PyTorch"



					@property
					def 						snake_case			(			self				:    Dict	)->   List[str]:
								return torch.__version__



					def 						snake_case			(			self				:    Optional[Any],    lowerCamelCase				:    str,    lowerCamelCase				:    int,    lowerCamelCase				:    int	)->   float:
								lowerCamelCase__						:						List[Any]						      =self._prepare_inference_func(lowerCamelCase,    lowerCamelCase,    lowerCamelCase	)
								return self._measure_speed(_inference	)



					def 						snake_case			(			self				:    List[str],    lowerCamelCase				:    str,    lowerCamelCase				:    int,    lowerCamelCase				:    int	)->   [Memory, Optional[MemorySummary]]:
								lowerCamelCase__						:						List[Any]						      =self._prepare_inference_func(lowerCamelCase,    lowerCamelCase,    lowerCamelCase	)
								return self._measure_memory(_inference	)



					def 						snake_case			(			self				:    Any,    lowerCamelCase				:    str,    lowerCamelCase				:    int,    lowerCamelCase				:    int	)->   float:
								lowerCamelCase__						:						int						      =self._prepare_train_func(lowerCamelCase,    lowerCamelCase,    lowerCamelCase	)
								return self._measure_speed(_train	)



					def 						snake_case			(			self				:    List[str],    lowerCamelCase				:    str,    lowerCamelCase				:    int,    lowerCamelCase				:    int	)->   [Memory, Optional[MemorySummary]]:
								lowerCamelCase__						:						str						      =self._prepare_train_func(lowerCamelCase,    lowerCamelCase,    lowerCamelCase	)
								return self._measure_memory(_train	)



					def 						snake_case			(			self				:    List[str],    lowerCamelCase				:    str,    lowerCamelCase				:    int,    lowerCamelCase				:    int	)->   Callable[[], None]:
								lowerCamelCase__						:						List[str]						      =self.config_dict[model_name]

								if self.args.torchscript:
											lowerCamelCase__						:						int						      =True

								lowerCamelCase__						:						Optional[Any]						      =(
								    hasattr(lowerCamelCase,    '''architectures'''	)
								    and isinstance(config.architectures,    lowerCamelCase	)
								    and len(config.architectures	) > 0
								)
								if not self.args.only_pretrain_model and has_model_class_in_config:
											try:
														lowerCamelCase__						:						int						      =config.architectures[0]
														lowerCamelCase__						:						Dict						      =__import__('''transformers''',    fromlist=[model_class]	)
														lowerCamelCase__						:						str						      =getattr(lowerCamelCase,    lowerCamelCase	)
														lowerCamelCase__						:						Tuple						      =model_cls(lowerCamelCase	)
											except ImportError:
														raise ImportError(
														    F'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
														    ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.'''	)
								else:
											lowerCamelCase__						:						List[str]						      =MODEL_MAPPING[config.__class__](lowerCamelCase	)

								model.eval()
								model.to(self.args.device	)

								# encoder-decoder has vocab size saved differently
								lowerCamelCase__						:						Optional[Any]						      =config.vocab_size if hasattr(lowerCamelCase,    '''vocab_size'''	) else config.encoder.vocab_size
								lowerCamelCase__						:						int						      =torch.randint(lowerCamelCase,    (batch_size, sequence_length),    dtype=torch.long,    device=self.args.device	)

								if self.args.fpaa:
											logger.info('''Running training in Mixed Precision...'''	)
											if not self.args.is_gpu:
														raise ValueError('''Mixed precision is possible only for GPU.'''	)
											# amp seems to have memory leaks so that memory usage
											# is measured using .half() for now https://github.com/NVIDIA/apex/issues/439
											model.half()

								if self.args.torchscript:
											with torch.no_grad():
														lowerCamelCase__						:						Optional[Any]						      =torch.jit.trace(lowerCamelCase,    lowerCamelCase	)
								else:
											lowerCamelCase__						:						Tuple						      =model

								def encoder_decoder_forward():
											with torch.no_grad():
														lowerCamelCase__						:						Optional[Any]						      =inference_model(lowerCamelCase,    decoder_input_ids=lowerCamelCase	)
											return outputs

								def encoder_forward():
											with torch.no_grad():
														lowerCamelCase__						:						Any						      =inference_model(lowerCamelCase	)
											return outputs

								lowerCamelCase__						:						Optional[int]						      =encoder_decoder_forward if config.is_encoder_decoder else encoder_forward
								return _forward



					def 						snake_case			(			self				:    Union[str, Any],    lowerCamelCase				:    str,    lowerCamelCase				:    int,    lowerCamelCase				:    int	)->   Callable[[], None]:
								lowerCamelCase__						:						Any						      =self.config_dict[model_name]

								lowerCamelCase__						:						Tuple						      =(
								    hasattr(lowerCamelCase,    '''architectures'''	)
								    and isinstance(config.architectures,    lowerCamelCase	)
								    and len(config.architectures	) > 0
								)
								if not self.args.only_pretrain_model and has_model_class_in_config:
											try:
														lowerCamelCase__						:						List[Any]						      =config.architectures[0]
														lowerCamelCase__						:						int						      =__import__('''transformers''',    fromlist=[model_class]	)
														lowerCamelCase__						:						int						      =getattr(lowerCamelCase,    lowerCamelCase	)
														lowerCamelCase__						:						Dict						      =model_cls(lowerCamelCase	)
											except ImportError:
														raise ImportError(
														    F'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
														    ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.'''	)
								else:
											lowerCamelCase__						:						List[str]						      =MODEL_WITH_LM_HEAD_MAPPING[config.__class__](lowerCamelCase	)

								if self.args.torchscript:
											raise NotImplementedError('''Training for torchscript is currently not implemented'''	)
								else:
											lowerCamelCase__						:						str						      =model

								model.train()
								model.to(self.args.device	)

								# encoder-decoder has vocab size saved differently
								lowerCamelCase__						:						Dict						      =config.vocab_size if hasattr(lowerCamelCase,    '''vocab_size'''	) else config.encoder.vocab_size
								lowerCamelCase__						:						int						      =torch.randint(lowerCamelCase,    (batch_size, sequence_length),    dtype=torch.long,    device=self.args.device	)

								if self.args.fpaa:
											logger.info('''Running training in Mixed Precision...'''	)
											if not self.args.is_gpu:
														raise ValueError('''Mixed precision is possible only for GPU.'''	)

											# amp seems to have memory leaks so that memory usage
											# is measured using .half() for now https://github.com/NVIDIA/apex/issues/439
											model.half()

								def compute_loss_and_backprob_encoder():
											lowerCamelCase__						:						Optional[int]						      =train_model(lowerCamelCase,    labels=lowerCamelCase	)[0]
											loss.backward()
											return loss

								def compute_loss_and_backprob_encoder_decoder():
											lowerCamelCase__						:						Dict						      =train_model(lowerCamelCase,    decoder_input_ids=lowerCamelCase,    labels=lowerCamelCase	)[0]
											loss.backward()
											return loss

								lowerCamelCase__						:						Optional[Any]						      =(
								    compute_loss_and_backprob_encoder_decoder
								    if config.is_encoder_decoder
								    else compute_loss_and_backprob_encoder
								)
								return _train



					def 						snake_case			(			self				:    Optional[int],    lowerCamelCase				:    Optional[int]	)->   float:
								try:
											if self.args.is_tpu or self.args.torchscript:
														# run additional 10 times to stabilize compilation for tpu and torchscript
														logger.info('''Do inference on TPU or torchscript. Running model 5 times to stabilize compilation'''	)
														timeit.repeat(
														    lowerCamelCase,    repeat=1,    number=5,    )

											# as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
											lowerCamelCase__						:						List[str]						      =timeit.repeat(
											    lowerCamelCase,    repeat=self.args.repeat,    number=10,    )

											if self.args.is_tpu and self.args.torch_xla_tpu_print_metrics:
														import torch_xla.debug.metrics as met

														self.print_fn(met.metrics_report()	)

											return min(lowerCamelCase	) / 10.0
								except RuntimeError as e:
											self.print_fn(F'''Doesn\'t fit on GPU. {e}'''	)
											return "N/A"




					def 						snake_case			(			self				:    Optional[int],    lowerCamelCase				:    Callable[[], None]	)->   [Memory, MemorySummary]:
								try:
											if self.args.trace_memory_line_by_line:
														lowerCamelCase__						:						Optional[int]						      =start_memory_tracing('''transformers'''	)

											if self.args.is_tpu:
														# tpu
														raise NotImplementedError(
														    '''Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking with'''
														    ''' `--no-memory` or `args.memory=False`'''	)
											elif self.args.is_gpu:
														if not is_pyanvml_available():
																	logger.warning(
																	    '''py3nvml not installed, we won\'t log GPU memory usage. '''
																	    '''Install py3nvml (pip install py3nvml) to log information about GPU.'''	)
																	lowerCamelCase__						:						str						      ='''N/A'''
														else:
																	logger.info(
																	    '''Measuring total GPU usage on GPU device. Make sure to not have additional processes running'''
																	    ''' on the same GPU.'''	)
																	# init nvml
																	nvml.nvmlInit()
																	func()
																	lowerCamelCase__						:						int						      =nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx	)
																	lowerCamelCase__						:						Optional[Any]						      =nvml.nvmlDeviceGetMemoryInfo(lowerCamelCase	)
																	lowerCamelCase__						:						str						      =meminfo.used
																	lowerCamelCase__						:						List[str]						      =Memory(lowerCamelCase	)
																	# shutdown nvml
																	nvml.nvmlShutdown()
											else:
														# cpu
														lowerCamelCase__						:						List[Any]						      =measure_peak_memory_cpu(lowerCamelCase	)
														lowerCamelCase__						:						List[Any]						      =Memory(lowerCamelCase	) if isinstance(lowerCamelCase,    lowerCamelCase	) else memory_bytes

											if self.args.trace_memory_line_by_line:
														lowerCamelCase__						:						List[str]						      =stop_memory_tracing(lowerCamelCase	)
											else:
														lowerCamelCase__						:						Optional[int]						      =None

											return memory, summary
								except RuntimeError as e:
											self.print_fn(F'''Doesn\'t fit on GPU. {e}'''	)
											return "N/A", None




