






"""simple docstring"""
import inspect
import os
import unittest

import torch

import accelerate
from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_multi_gpu
from accelerate.utils import patch_environment



class      SCREAMING_SNAKE_CASE  (				unittest.TestCase						):





	"""simple docstring"""




	def    lowerCamelCase(self							):
		A_		:						List[str]	    =   inspect.getfile(accelerate.test_utils							)
		A_		:						Tuple	    =   os.path.sep.join(mod_file.split(os.path.sep							)[:-1] + ["""scripts""", """test_script.py"""]							)
		A_		:						Tuple	    =   os.path.sep.join(
		    mod_file.split(os.path.sep							)[:-1] + ["""scripts""", """test_distributed_data_loop.py"""]							)
		A_		:						str	    =   os.path.sep.join(mod_file.split(os.path.sep							)[:-1] + ["""scripts""", """test_ops.py"""]							)





	@require_multi_gpu
	def    lowerCamelCase(self							):
		print(f"""Found {torch.cuda.device_count()} devices."""							)
		A_		:						List[Any]	    =   ["""torchrun""", f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path]
		with patch_environment(omp_num_threads=1							):
			execute_subprocess_async(lowerCAmelCase_     ,     env=os.environ.copy()							)





	@require_multi_gpu
	def    lowerCamelCase(self							):
		print(f"""Found {torch.cuda.device_count()} devices."""							)
		A_		:						int	    =   ["""torchrun""", f"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path]
		print(f"""Command: {cmd}"""							)
		with patch_environment(omp_num_threads=1							):
			execute_subprocess_async(lowerCAmelCase_     ,     env=os.environ.copy()							)





	@require_multi_gpu
	def    lowerCamelCase(self							):
		A_		:						str	    =   ["""torchrun""", f"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__							)]
		with patch_environment(omp_num_threads=1							):
			execute_subprocess_async(lowerCAmelCase_     ,     env=os.environ.copy()							)





	@require_multi_gpu
	def    lowerCamelCase(self							):
		print(f"""Found {torch.cuda.device_count()} devices, using 2 devices only"""							)
		A_		:						Optional[Any]	    =   ["""torchrun""", f"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path]
		with patch_environment(omp_num_threads=1     ,     cuda_visible_devices="""0,1"""							):
			execute_subprocess_async(lowerCAmelCase_     ,     env=os.environ.copy()							)


if __name__ == "__main__":
							_lowerCAmelCase         =							Accelerator()
							_lowerCAmelCase         =							(accelerator.state.process_index + 2, 10)
							_lowerCAmelCase         =							torch.randint(0, 10, shape).to(accelerator.device)

							_lowerCAmelCase         =							""

							_lowerCAmelCase         =							accelerator.pad_across_processes(tensor)
							if tensora.shape[0] != accelerator.state.num_processes + 1:
														error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
							if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor):
														error_msg += "Tensors have different values."
							if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0):
														error_msg += "Padding was not done with the right value (0)."

							_lowerCAmelCase         =							accelerator.pad_across_processes(tensor, pad_first=True)
							if tensora.shape[0] != accelerator.state.num_processes + 1:
														error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
							_lowerCAmelCase         =							accelerator.state.num_processes - accelerator.state.process_index - 1
							if not torch.equal(tensora[index:], tensor):
														error_msg += "Tensors have different values."
							if not torch.all(tensora[:index] == 0):
														error_msg += "Padding was not done with the right value (0)."

							# Raise error at the end to make sure we don't stop at the first failure.
							if len(error_msg) > 0:
														raise ValueError(error_msg)









"""simple docstring"""
import unittest

from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
							from PIL import Image
else:



							class      SCREAMING_SNAKE_CASE  :





								"""simple docstring"""




								@staticmethod
								def    lowerCamelCase(*lowerCAmelCase_     ,     **lowerCAmelCase_							):
									pass



@is_pipeline_test
@require_torch
@require_vision
class      SCREAMING_SNAKE_CASE  (				unittest.TestCase						):





	"""simple docstring"""




	_A       :				List[Any]    =				MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING





	def    lowerCamelCase(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_							):
		A_		:						Union[str, Any]	    =   pipeline("""visual-question-answering"""     ,     model="""hf-internal-testing/tiny-vilt-random-vqa"""							)
		A_		:						Union[str, Any]	    =   [
		    {
		        """image""": Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							),
		        """question""": """How many cats are there?""",
		    },
		    {
		        """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""",
		        """question""": """How many cats are there?""",
		    },
		]
		return vqa_pipeline, examples





	def    lowerCamelCase(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_							):
		A_		:						str	    =   vqa_pipeline(lowerCAmelCase_     ,     top_k=1							)
		self.assertEqual(
		    lowerCAmelCase_     ,     [
		        [{"""score""": ANY(lowerCAmelCase_							), """answer""": ANY(lowerCAmelCase_							)}],
		        [{"""score""": ANY(lowerCAmelCase_							), """answer""": ANY(lowerCAmelCase_							)}],
		    ]     ,     )





	@require_torch
	def    lowerCamelCase(self							):
		A_		:						Tuple	    =   pipeline("""visual-question-answering"""     ,     model="""hf-internal-testing/tiny-vilt-random-vqa"""							)
		A_		:						Any	    =   """./tests/fixtures/tests_samples/COCO/000000039769.png"""
		A_		:						Any	    =   """How many cats are there?"""

		A_		:						Optional[int]	    =   vqa_pipeline(image=lowerCAmelCase_     ,     question="""How many cats are there?"""     ,     top_k=2							)
		self.assertEqual(
		    lowerCAmelCase_     ,     [{"""score""": ANY(lowerCAmelCase_							), """answer""": ANY(lowerCAmelCase_							)}, {"""score""": ANY(lowerCAmelCase_							), """answer""": ANY(lowerCAmelCase_							)}]							)

		A_		:						Any	    =   vqa_pipeline({"""image""": image, """question""": question}     ,     top_k=2							)
		self.assertEqual(
		    lowerCAmelCase_     ,     [{"""score""": ANY(lowerCAmelCase_							), """answer""": ANY(lowerCAmelCase_							)}, {"""score""": ANY(lowerCAmelCase_							), """answer""": ANY(lowerCAmelCase_							)}]							)





	@slow
	@require_torch
	def    lowerCamelCase(self							):
		A_		:						int	    =   pipeline("""visual-question-answering"""     ,     model="""dandelin/vilt-b32-finetuned-vqa"""							)
		A_		:						Tuple	    =   """./tests/fixtures/tests_samples/COCO/000000039769.png"""
		A_		:						int	    =   """How many cats are there?"""

		A_		:						List[Any]	    =   vqa_pipeline(image=lowerCAmelCase_     ,     question=lowerCAmelCase_     ,     top_k=2							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase_     ,     decimals=4							)     ,     [{"""score""": 0.8799, """answer""": """2"""}, {"""score""": 0.296, """answer""": """1"""}]							)

		A_		:						Any	    =   vqa_pipeline({"""image""": image, """question""": question}     ,     top_k=2							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase_     ,     decimals=4							)     ,     [{"""score""": 0.8799, """answer""": """2"""}, {"""score""": 0.296, """answer""": """1"""}]							)

		A_		:						Tuple	    =   vqa_pipeline(
		    [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]     ,     top_k=2							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase_     ,     decimals=4							)     ,     [[{"""score""": 0.8799, """answer""": """2"""}, {"""score""": 0.296, """answer""": """1"""}]] * 2     ,     )





	@require_tf
	@unittest.skip("""Visual question answering not implemented in TF"""							)
	def    lowerCamelCase(self							):
		pass

