

import unittest

import numpy as np
from datasets import load_dataset

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, prepare_image_inputs


if is_torch_available():
  import torch

if is_vision_available():
  from PIL import Image

  from transformers import SegformerImageProcessor







class     a__    (				unittest.TestCase    ):







  """simple docstring"""




  def __init__(     self      :	Tuple			,			UpperCAmelCase__      :	Any			,			UpperCAmelCase__      :	List[Any]=7			,			UpperCAmelCase__      :	Optional[int]=3			,			UpperCAmelCase__      :	Any=3_0			,			UpperCAmelCase__      :	List[str]=4_0_0			,			UpperCAmelCase__      :	List[str]=True			,			UpperCAmelCase__      :	str=None			,			UpperCAmelCase__      :	Optional[int]=True			,			UpperCAmelCase__      :	List[str]=[0.5, 0.5, 0.5]			,			UpperCAmelCase__      :	Dict=[0.5, 0.5, 0.5]			,			UpperCAmelCase__      :	Any=False			,			)   ->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: List[str]					       =				size if size is not None else {"""height""": 3_0, """width""": 3_0}
        SCREAMING_SNAKE_CASE	: List[str]					       =				parent
        SCREAMING_SNAKE_CASE	: int					       =				batch_size
        SCREAMING_SNAKE_CASE	: int					       =				num_channels
        SCREAMING_SNAKE_CASE	: int					       =				min_resolution
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				max_resolution
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				do_resize
        SCREAMING_SNAKE_CASE	: Any					       =				size
        SCREAMING_SNAKE_CASE	: List[str]					       =				do_normalize
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				image_mean
        SCREAMING_SNAKE_CASE	: Dict					       =				image_std
        SCREAMING_SNAKE_CASE	: str					       =				do_reduce_labels




  def 	_lowercase (     self      :	Any						)   ->Any:
        """simple docstring"""







        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_normalize": self.do_normalize,
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_reduce_labels": self.do_reduce_labels,
        }






def    __lowercase (       )       ->  int:
      SCREAMING_SNAKE_CASE	: Optional[Any]					       =				load_dataset("""hf-internal-testing/fixtures_ade20k"""  ,      split="""test"""     )

      SCREAMING_SNAKE_CASE	: str					       =				Image.open(dataset[0]["""file"""]     )
      SCREAMING_SNAKE_CASE	: Optional[int]					       =				Image.open(dataset[1]["""file"""]     )

      return image, map






def    __lowercase (       )       ->  List[Any]:
      SCREAMING_SNAKE_CASE	: int					       =				load_dataset("""hf-internal-testing/fixtures_ade20k"""  ,      split="""test"""     )

      SCREAMING_SNAKE_CASE	: Optional[int]					       =				Image.open(dataset[0]["""file"""]     )
      SCREAMING_SNAKE_CASE	: Dict					       =				Image.open(dataset[1]["""file"""]     )
      SCREAMING_SNAKE_CASE	: int					       =				Image.open(dataset[2]["""file"""]     )
      SCREAMING_SNAKE_CASE	: Optional[Any]					       =				Image.open(dataset[3]["""file"""]     )

      return [imagea, imagea], [mapa, mapa]







@require_torch
@require_vision
class     a__    (				lowercase__		,     unittest.TestCase    ):







  """simple docstring"""




  UpperCAmelCase__ :	Optional[Any]         =SegformerImageProcessor if is_vision_available() else None


  def 	_lowercase (     self      :	str						)   ->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: List[Any]					       =				SegformerImageProcessingTester(self						)


  @property
  def 	_lowercase (     self      :	Optional[int]						)   ->List[str]:
        """simple docstring"""







        return self.image_processor_tester.prepare_image_processor_dict()


  def 	_lowercase (     self      :	Any						)   ->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[int]					       =				self.image_processing_class(**self.image_processor_dict						)
        self.assertTrue(hasattr(lowerCAmelCase__			,			"""do_resize"""						)						)
        self.assertTrue(hasattr(lowerCAmelCase__			,			"""size"""						)						)
        self.assertTrue(hasattr(lowerCAmelCase__			,			"""do_normalize"""						)						)
        self.assertTrue(hasattr(lowerCAmelCase__			,			"""image_mean"""						)						)
        self.assertTrue(hasattr(lowerCAmelCase__			,			"""image_std"""						)						)
        self.assertTrue(hasattr(lowerCAmelCase__			,			"""do_reduce_labels"""						)						)


  def 	_lowercase (     self      :	List[str]						)   ->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Tuple					       =				self.image_processing_class.from_dict(self.image_processor_dict						)
        self.assertEqual(image_processor.size			,			{"""height""": 3_0, """width""": 3_0}						)
        self.assertEqual(image_processor.do_reduce_labels			,			lowerCAmelCase__						)

        SCREAMING_SNAKE_CASE	: List[Any]					       =				self.image_processing_class.from_dict(self.image_processor_dict			,			size=4_2			,			reduce_labels=lowerCAmelCase__						)
        self.assertEqual(image_processor.size			,			{"""height""": 4_2, """width""": 4_2}						)
        self.assertEqual(image_processor.do_reduce_labels			,			lowerCAmelCase__						)


  def 	_lowercase (     self      :	Any						)   ->Optional[Any]:
        """simple docstring"""







        pass


  def 	_lowercase (     self      :	List[str]						)   ->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: str					       =				self.image_processing_class(**self.image_processor_dict						)
        # create random PIL images
        SCREAMING_SNAKE_CASE	: Tuple					       =				prepare_image_inputs(self.image_processor_tester			,			equal_resolution=lowerCAmelCase__						)
        for image in image_inputs:
              self.assertIsInstance(lowerCAmelCase__			,			Image.Image						)

        # Test not batched input
        SCREAMING_SNAKE_CASE	: List[Any]					       =				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.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )			,			)

        # Test batched
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				image_processing(lowerCAmelCase__			,			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.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )			,			)


  def 	_lowercase (     self      :	Tuple						)   ->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: int					       =				self.image_processing_class(**self.image_processor_dict						)
        # create random numpy tensors
        SCREAMING_SNAKE_CASE	: List[str]					       =				prepare_image_inputs(self.image_processor_tester			,			equal_resolution=lowerCAmelCase__			,			numpify=lowerCAmelCase__						)
        for image in image_inputs:
              self.assertIsInstance(lowerCAmelCase__			,			np.ndarray						)

        # Test not batched input
        SCREAMING_SNAKE_CASE	: Tuple					       =				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.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )			,			)

        # Test batched
        SCREAMING_SNAKE_CASE	: List[Any]					       =				image_processing(lowerCAmelCase__			,			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.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )			,			)


  def 	_lowercase (     self      :	Optional[int]						)   ->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Tuple					       =				self.image_processing_class(**self.image_processor_dict						)
        # create random PyTorch tensors
        SCREAMING_SNAKE_CASE	: Dict					       =				prepare_image_inputs(self.image_processor_tester			,			equal_resolution=lowerCAmelCase__			,			torchify=lowerCAmelCase__						)
        for image in image_inputs:
              self.assertIsInstance(lowerCAmelCase__			,			torch.Tensor						)

        # Test not batched input
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				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.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )			,			)

        # Test batched
        SCREAMING_SNAKE_CASE	: List[str]					       =				image_processing(lowerCAmelCase__			,			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.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )			,			)


  def 	_lowercase (     self      :	Optional[Any]						)   ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Any					       =				self.image_processing_class(**self.image_processor_dict						)
        # create random PyTorch tensors
        SCREAMING_SNAKE_CASE	: List[Any]					       =				prepare_image_inputs(self.image_processor_tester			,			equal_resolution=lowerCAmelCase__			,			torchify=lowerCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				[]
        for image in image_inputs:
              self.assertIsInstance(lowerCAmelCase__			,			torch.Tensor						)
              maps.append(torch.zeros(image.shape[-2:]						).long()						)

        # Test not batched input
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				image_processing(image_inputs[0]			,			maps[0]			,			return_tensors="""pt"""						)
        self.assertEqual(
            encoding["""pixel_values"""].shape			,			(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )			,			)
        self.assertEqual(
            encoding["""labels"""].shape			,			(
                1,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )			,			)
        self.assertEqual(encoding["""labels"""].dtype			,			torch.long						)
        self.assertTrue(encoding["""labels"""].min().item() >= 0						)
        self.assertTrue(encoding["""labels"""].max().item() <= 2_5_5						)

        # Test batched
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				image_processing(lowerCAmelCase__			,			lowerCAmelCase__			,			return_tensors="""pt"""						)
        self.assertEqual(
            encoding["""pixel_values"""].shape			,			(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )			,			)
        self.assertEqual(
            encoding["""labels"""].shape			,			(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )			,			)
        self.assertEqual(encoding["""labels"""].dtype			,			torch.long						)
        self.assertTrue(encoding["""labels"""].min().item() >= 0						)
        self.assertTrue(encoding["""labels"""].max().item() <= 2_5_5						)

        # Test not batched input (PIL images)
        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Any					       =				prepare_semantic_single_inputs()

        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				image_processing(lowerCAmelCase__			,			lowerCAmelCase__			,			return_tensors="""pt"""						)
        self.assertEqual(
            encoding["""pixel_values"""].shape			,			(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )			,			)
        self.assertEqual(
            encoding["""labels"""].shape			,			(
                1,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )			,			)
        self.assertEqual(encoding["""labels"""].dtype			,			torch.long						)
        self.assertTrue(encoding["""labels"""].min().item() >= 0						)
        self.assertTrue(encoding["""labels"""].max().item() <= 2_5_5						)

        # Test batched input (PIL images)
        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Optional[Any]					       =				prepare_semantic_batch_inputs()

        SCREAMING_SNAKE_CASE	: str					       =				image_processing(lowerCAmelCase__			,			lowerCAmelCase__			,			return_tensors="""pt"""						)
        self.assertEqual(
            encoding["""pixel_values"""].shape			,			(
                2,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )			,			)
        self.assertEqual(
            encoding["""labels"""].shape			,			(
                2,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )			,			)
        self.assertEqual(encoding["""labels"""].dtype			,			torch.long						)
        self.assertTrue(encoding["""labels"""].min().item() >= 0						)
        self.assertTrue(encoding["""labels"""].max().item() <= 2_5_5						)




  def 	_lowercase (     self      :	Dict						)   ->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				self.image_processing_class(**self.image_processor_dict						)

        # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				prepare_semantic_single_inputs()
        SCREAMING_SNAKE_CASE	: Tuple					       =				image_processing(lowerCAmelCase__			,			lowerCAmelCase__			,			return_tensors="""pt"""						)
        self.assertTrue(encoding["""labels"""].min().item() >= 0						)
        self.assertTrue(encoding["""labels"""].max().item() <= 1_5_0						)

        SCREAMING_SNAKE_CASE	: List[str]					       =				True
        SCREAMING_SNAKE_CASE	: int					       =				image_processing(lowerCAmelCase__			,			lowerCAmelCase__			,			return_tensors="""pt"""						)
        self.assertTrue(encoding["""labels"""].min().item() >= 0						)
        self.assertTrue(encoding["""labels"""].max().item() <= 2_5_5						)







import inspect
import os
import unittest

import torch

import accelerate
from accelerate import debug_launcher
from accelerate.test_utils import (
    execute_subprocess_async,
    require_cpu,
    require_multi_gpu,
    require_single_gpu,
    test_sync,
)
from accelerate.utils import patch_environment







class     a__    (				unittest.TestCase    ):







  """simple docstring"""




  def 	_lowercase (     self      :	Optional[int]						)   ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				inspect.getfile(accelerate.test_utils						)
        SCREAMING_SNAKE_CASE	: int					       =				os.path.sep.join(mod_file.split(os.path.sep						)[:-1] + ["""scripts""", """test_sync.py"""]						)


  @require_cpu
  def 	_lowercase (     self      :	Optional[int]						)   ->str:
        """simple docstring"""







        debug_launcher(test_sync.main			,			num_processes=1						)


  @require_cpu
  def 	_lowercase (     self      :	Optional[int]						)   ->int:
        """simple docstring"""







        debug_launcher(test_sync.main						)


  @require_single_gpu
  def 	_lowercase (     self      :	str						)   ->Any:
        """simple docstring"""







        test_sync.main()




  @require_multi_gpu
  def 	_lowercase (     self      :	Union[str, Any]						)   ->List[Any]:
        """simple docstring"""







        print(f"Found {torch.cuda.device_count()} devices."						)
        SCREAMING_SNAKE_CASE	: List[str]					       =				["""torchrun""", f"--nproc_per_node={torch.cuda.device_count()}", self.test_file_path]
        with patch_environment(omp_num_threads=1						):
              execute_subprocess_async(UpperCAmelCase__			,			env=os.environ.copy()						)




