



import unittest

from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, 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 				_a				:

				@staticmethod
				def      __snake_case       (*SCREAMING_SNAKE_CASE_,   **SCREAMING_SNAKE_CASE_					)       ->   Union[str, Any]:
							pass







@is_pipeline_test
@require_vision
@require_torch
class 				_a				(   unittest.TestCase					):
			A      		=	MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   Any:
						UpperCAmelCase_:		Optional[Any]							      =     pipeline(
						    """zero-shot-object-detection""",   model="""hf-internal-testing/tiny-random-owlvit-object-detection"""					)

						UpperCAmelCase_:		int							      =     [
						    {
						        """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""",
						        """candidate_labels""": ["""cat""", """remote""", """couch"""],
						    }
						]
						return object_detector, examples

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   Tuple:
						UpperCAmelCase_:		List[str]							      =     object_detector(examples[0],   threshold=0.0					)

						UpperCAmelCase_:		Dict							      =     len(SCREAMING_SNAKE_CASE_					)
						self.assertGreater(SCREAMING_SNAKE_CASE_,   0					)
						self.assertEqual(
						    SCREAMING_SNAKE_CASE_,   [
						        {
						            """score""": ANY(SCREAMING_SNAKE_CASE_					),
						            """label""": ANY(SCREAMING_SNAKE_CASE_					),
						            """box""": {"""xmin""": ANY(SCREAMING_SNAKE_CASE_					), """ymin""": ANY(SCREAMING_SNAKE_CASE_					), """xmax""": ANY(SCREAMING_SNAKE_CASE_					), """ymax""": ANY(SCREAMING_SNAKE_CASE_					)},
						        }
						        for i in range(SCREAMING_SNAKE_CASE_					)
						    ],   )

			@require_tf
			@unittest.skip("""Zero Shot Object Detection not implemented in TF"""					)
			def      __snake_case       (self					)       ->   str:
						pass

			@require_torch
			def      __snake_case       (self					)       ->   List[Any]:
						UpperCAmelCase_:		Tuple							      =     pipeline(
						    """zero-shot-object-detection""",   model="""hf-internal-testing/tiny-random-owlvit-object-detection"""					)

						UpperCAmelCase_:		Optional[int]							      =     object_detector(
						    """./tests/fixtures/tests_samples/COCO/000000039769.png""",   candidate_labels=["""cat""", """remote""", """couch"""],   threshold=0.6_4,   )

						self.assertEqual(
						    nested_simplify(SCREAMING_SNAKE_CASE_,   decimals=4					),   [
						        {"""score""": 0.7_2_3_5, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
						        {"""score""": 0.7_2_1_8, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
						        {"""score""": 0.7_1_8_4, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
						        {"""score""": 0.6_7_4_8, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
						        {"""score""": 0.6_6_5_6, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
						        {"""score""": 0.6_6_1_4, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
						        {"""score""": 0.6_4_5_6, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
						        {"""score""": 0.6_4_2, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}},
						        {"""score""": 0.6_4_1_9, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
						    ],   )

						UpperCAmelCase_:		Any							      =     object_detector(
						    [
						        {
						            """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""",
						            """candidate_labels""": ["""cat""", """remote""", """couch"""],
						        }
						    ],   threshold=0.6_4,   )

						self.assertEqual(
						    nested_simplify(SCREAMING_SNAKE_CASE_,   decimals=4					),   [
						        [
						            {"""score""": 0.7_2_3_5, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
						            {"""score""": 0.7_2_1_8, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
						            {"""score""": 0.7_1_8_4, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
						            {"""score""": 0.6_7_4_8, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
						            {"""score""": 0.6_6_5_6, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
						            {"""score""": 0.6_6_1_4, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
						            {"""score""": 0.6_4_5_6, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
						            {"""score""": 0.6_4_2, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}},
						            {"""score""": 0.6_4_1_9, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
						        ]
						    ],   )

			@require_torch
			@slow
			def      __snake_case       (self					)       ->   Union[str, Any]:
						UpperCAmelCase_:		List[str]							      =     pipeline("""zero-shot-object-detection"""					)

						UpperCAmelCase_:		Optional[int]							      =     object_detector(
						    """http://images.cocodataset.org/val2017/000000039769.jpg""",   candidate_labels=["""cat""", """remote""", """couch"""],   )
						self.assertEqual(
						    nested_simplify(SCREAMING_SNAKE_CASE_,   decimals=4					),   [
						        {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
						        {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
						        {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
						        {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}},
						        {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}},
						    ],   )

						UpperCAmelCase_:		Any							      =     object_detector(
						    [
						        {
						            """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""",
						            """candidate_labels""": ["""cat""", """remote""", """couch"""],
						        },
						        {
						            """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""",
						            """candidate_labels""": ["""cat""", """remote""", """couch"""],
						        },
						    ],   )
						self.assertEqual(
						    nested_simplify(SCREAMING_SNAKE_CASE_,   decimals=4					),   [
						        [
						            {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
						            {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
						            {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
						            {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}},
						            {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}},
						        ],
						        [
						            {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
						            {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
						            {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
						            {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}},
						            {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}},
						        ],
						    ],   )

			@require_tf
			@unittest.skip("""Zero Shot Object Detection not implemented in TF"""					)
			def      __snake_case       (self					)       ->   List[str]:
						pass

			@require_torch
			@slow
			def      __snake_case       (self					)       ->   str:
						UpperCAmelCase_:		Optional[int]							      =     0.2
						UpperCAmelCase_:		int							      =     pipeline("""zero-shot-object-detection"""					)

						UpperCAmelCase_:		List[Any]							      =     object_detector(
						    """http://images.cocodataset.org/val2017/000000039769.jpg""",   candidate_labels=["""cat""", """remote""", """couch"""],   threshold=SCREAMING_SNAKE_CASE_,   )
						self.assertEqual(
						    nested_simplify(SCREAMING_SNAKE_CASE_,   decimals=4					),   [
						        {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
						        {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
						        {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
						    ],   )

			@require_torch
			@slow
			def      __snake_case       (self					)       ->   str:
						UpperCAmelCase_:		Any							      =     2
						UpperCAmelCase_:		List[Any]							      =     pipeline("""zero-shot-object-detection"""					)

						UpperCAmelCase_:		List[Any]							      =     object_detector(
						    """http://images.cocodataset.org/val2017/000000039769.jpg""",   candidate_labels=["""cat""", """remote""", """couch"""],   top_k=SCREAMING_SNAKE_CASE_,   )
						self.assertEqual(
						    nested_simplify(SCREAMING_SNAKE_CASE_,   decimals=4					),   [
						        {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
						        {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
						    ],   )











#
# This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or
# many nodes) can talk to each other via nccl and allocate gpu memory.
#
# To run first adjust the number of processes and nodes:
#
# python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
#
# You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port
#
# You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d
#
# use torch.distributed.launch instead of torch.distributed.run for torch < 1.9
#
# If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with:
#
# NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
#
# which should tell you what's going on behind the scenes.
#
#
# This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that
# runs on 2 nodes of 4 gpus per node:
#
# #SBATCH --job-name=test-nodes        # name
# #SBATCH --nodes=2                    # nodes
# #SBATCH --ntasks-per-node=1          # crucial - only 1 task per dist per node!
# #SBATCH --cpus-per-task=10           # number of cores per tasks
# #SBATCH --gres=gpu:4                 # number of gpus
# #SBATCH --time 0:05:00               # maximum execution time (HH:MM:SS)
# #SBATCH --output=%x-%j.out           # output file name
#
# GPUS_PER_NODE=4
# MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1)
# MASTER_PORT=6000
#
# srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \
# --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \
# --master_addr $MASTER_ADDR --master_port $MASTER_PORT \
# torch-distributed-gpu-test.py'
#

import fcntl
import os
import socket

import torch
import torch.distributed as dist







def  lowerCAmelCase_	(*lowerCAmelCase__:		Dict  ):





			"""simple docstring"""


			with open(lowerCAmelCase__		,						"""r"""  ) as fh:
						fcntl.flock(lowerCAmelCase__		,						fcntl.LOCK_EX  )
						try:
									print(*lowerCAmelCase__  )
						finally:
									fcntl.flock(lowerCAmelCase__		,						fcntl.LOCK_UN  )


a      :  Tuple			     =			int(os.environ['LOCAL_RANK'])
torch.cuda.set_device(local_rank)
a      :  Union[str, Any]			     =			torch.device('cuda', local_rank)
a      :  Any			     =			socket.gethostname()

a      :  Optional[Any]			     =			F'''[{hostname}-{local_rank}]'''

try:
	# test distributed
	dist.init_process_group('nccl')
	dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM)
	dist.barrier()

	# test cuda is available and can allocate memory
	torch.cuda.is_available()
	torch.ones(1).cuda(local_rank)

	# global rank
	a      :  Optional[Any]			     =			dist.get_rank()
	a      :  List[Any]			     =			dist.get_world_size()

	printflock(F'''{gpu} is OK (global rank: {rank}/{world_size})''')

	dist.barrier()
	if rank == 0:
		printflock(F'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''')

except Exception:
	printflock(F'''{gpu} is broken''')
	raise






