


"""simple docstring"""
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				:   Union[str, Any]		,							UpperCAmelCase_				:   Optional[Any]		,							UpperCAmelCase_				:   int=7		,							UpperCAmelCase_				:   Optional[Any]=3		,							UpperCAmelCase_				:   List[str]=30		,							UpperCAmelCase_				:   Optional[int]=400		,							UpperCAmelCase_				:   List[str]=True		,							UpperCAmelCase_				:   Dict=None		,							UpperCAmelCase_				:   Any=True		,							UpperCAmelCase_				:   Optional[int]=[0.5, 0.5, 0.5]		,							UpperCAmelCase_				:   Any=[0.5, 0.5, 0.5]		,							UpperCAmelCase_				:   Tuple=False		,							)       ->int:



														"""simple docstring"""



														snake_case_     							=		size if size is not None else {"""height""": 30, """width""": 30}
														snake_case_     							=		parent
														snake_case_     							=		batch_size
														snake_case_     							=		num_channels
														snake_case_     							=		min_resolution
														snake_case_     							=		max_resolution
														snake_case_     							=		do_resize
														snake_case_     							=		size
														snake_case_     							=		do_normalize
														snake_case_     							=		image_mean
														snake_case_     							=		image_std
														snake_case_     							=		do_reduce_labels



							def 		lowerCAmelCase							(					self				:   Tuple							)       ->Optional[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     _a					(   )     ->					int:
							snake_case_     							=		load_dataset("""hf-internal-testing/fixtures_ade20k"""					,			split="""test"""					)

							snake_case_     							=		Image.open(dataset[0]["""file"""]					)
							snake_case_     							=		Image.open(dataset[1]["""file"""]					)

							return image, map







def     _a					(   )     ->					Union[str, Any]:
							snake_case_     							=		load_dataset("""hf-internal-testing/fixtures_ade20k"""					,			split="""test"""					)

							snake_case_     							=		Image.open(dataset[0]["""file"""]					)
							snake_case_     							=		Image.open(dataset[1]["""file"""]					)
							snake_case_     							=		Image.open(dataset[2]["""file"""]					)
							snake_case_     							=		Image.open(dataset[3]["""file"""]					)

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





@require_torch
@require_vision
class   __A  (snake_case__    ,		unittest.TestCase):





							'''simple docstring'''

							__lowercase:		List[str]				   =     SegformerImageProcessor if is_vision_available() else None



							def 		lowerCAmelCase							(					self				:   str							)       ->int:



														"""simple docstring"""



														snake_case_     							=		SegformerImageProcessingTester(self							)



							@property
							def 		lowerCAmelCase							(					self				:   int							)       ->int:



														"""simple docstring"""



														return self.image_processor_tester.prepare_image_processor_dict()



							def 		lowerCAmelCase							(					self				:   str							)       ->Any:



														"""simple docstring"""



														snake_case_     							=		self.image_processing_class(**self.image_processor_dict							)
														self.assertTrue(hasattr(UpperCAmelCase_		,							"""do_resize"""							)							)
														self.assertTrue(hasattr(UpperCAmelCase_		,							"""size"""							)							)
														self.assertTrue(hasattr(UpperCAmelCase_		,							"""do_normalize"""							)							)
														self.assertTrue(hasattr(UpperCAmelCase_		,							"""image_mean"""							)							)
														self.assertTrue(hasattr(UpperCAmelCase_		,							"""image_std"""							)							)
														self.assertTrue(hasattr(UpperCAmelCase_		,							"""do_reduce_labels"""							)							)



							def 		lowerCAmelCase							(					self				:   int							)       ->int:



														"""simple docstring"""



														snake_case_     							=		self.image_processing_class.from_dict(self.image_processor_dict							)
														self.assertEqual(image_processor.size		,							{"""height""": 30, """width""": 30}							)
														self.assertEqual(image_processor.do_reduce_labels		,							UpperCAmelCase_							)

														snake_case_     							=		self.image_processing_class.from_dict(self.image_processor_dict		,							size=42		,							reduce_labels=UpperCAmelCase_							)
														self.assertEqual(image_processor.size		,							{"""height""": 42, """width""": 42}							)
														self.assertEqual(image_processor.do_reduce_labels		,							UpperCAmelCase_							)



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



														"""simple docstring"""



														pass



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



														"""simple docstring"""



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

														# Test not batched input
														snake_case_     							=		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
														snake_case_     							=		image_processing(UpperCAmelCase_		,							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 		lowerCAmelCase							(					self				:   Tuple							)       ->Any:



														"""simple docstring"""



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

														# Test not batched input
														snake_case_     							=		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
														snake_case_     							=		image_processing(UpperCAmelCase_		,							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 		lowerCAmelCase							(					self				:   Any							)       ->Dict:



														"""simple docstring"""



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

														# Test not batched input
														snake_case_     							=		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
														snake_case_     							=		image_processing(UpperCAmelCase_		,							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 		lowerCAmelCase							(					self				:   Any							)       ->Tuple:



														"""simple docstring"""



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

														# Test not batched input
														snake_case_     							=		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() <= 255							)

														# Test batched
														snake_case_     							=		image_processing(UpperCAmelCase_		,							UpperCAmelCase_		,							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() <= 255							)

														# Test not batched input (PIL images)
														snake_case_							,    snake_case_     							=		prepare_semantic_single_inputs()

														snake_case_     							=		image_processing(UpperCAmelCase_		,							UpperCAmelCase_		,							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() <= 255							)

														# Test batched input (PIL images)
														snake_case_							,    snake_case_     							=		prepare_semantic_batch_inputs()

														snake_case_     							=		image_processing(UpperCAmelCase_		,							UpperCAmelCase_		,							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() <= 255							)



							def 		lowerCAmelCase							(					self				:   int							)       ->str:



														"""simple docstring"""



														snake_case_     							=		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
														snake_case_							,    snake_case_     							=		prepare_semantic_single_inputs()
														snake_case_     							=		image_processing(UpperCAmelCase_		,							UpperCAmelCase_		,							return_tensors="""pt"""							)
														self.assertTrue(encoding["""labels"""].min().item() >= 0							)
														self.assertTrue(encoding["""labels"""].max().item() <= 150							)

														snake_case_     							=		True
														snake_case_     							=		image_processing(UpperCAmelCase_		,							UpperCAmelCase_		,							return_tensors="""pt"""							)
														self.assertTrue(encoding["""labels"""].min().item() >= 0							)
														self.assertTrue(encoding["""labels"""].max().item() <= 255							)







"""simple docstring"""
import importlib
import importlib.metadata
import os
import warnings
from distutils.util import strtobool
from functools import lru_cache

import torch
from packaging import version
from packaging.version import parse

from .environment import parse_flag_from_env
from .versions import compare_versions, is_torch_version


try:
				import torch_xla.core.xla_model as xm  # noqa: F401

				__SCREAMING_SNAKE_CASE				:     List[Any]		=     True
except ImportError:
				__SCREAMING_SNAKE_CASE				:     Dict		=     False


# Cache this result has it's a C FFI call which can be pretty time-consuming
__SCREAMING_SNAKE_CASE				:     Optional[Any]		=     torch.distributed.is_available()







def     _a					(   _SCREAMING_SNAKE_CASE					)     ->					int:
							# Check we're not importing a "pkg_name" directory somewhere but the actual library by trying to grab the version
							snake_case_     							=		importlib.util.find_spec(_SCREAMING_SNAKE_CASE					) is not None
							if package_exists:
														try:
																					snake_case_     							=		importlib.metadata.metadata(_SCREAMING_SNAKE_CASE					)
																					return True
														except importlib.metadata.PackageNotFoundError:
																					return False







def     _a					(   )     ->					bool:
							return _torch_distributed_available







def     _a					(   )     ->					Union[str, Any]:
							try:
														pass
							except ImportError:
														print(
														    """Intel(R) oneCCL Bindings for PyTorch* is required to run DDP on Intel(R) GPUs, but it is not"""
														    """ detected. If you see \"ValueError: Invalid backend: 'ccl'\" error, please install Intel(R) oneCCL"""
														    """ Bindings for PyTorch*."""					)
							return (
							    importlib.util.find_spec("""torch_ccl"""					) is not None
							    or importlib.util.find_spec("""oneccl_bindings_for_pytorch"""					) is not None
							)







def     _a					(   )     ->					Optional[Any]:
							return importlib.metadata.version("""oneccl_bind_pt"""					)







def     _a					(   )     ->					Optional[Any]:
							return _is_package_available("""transformer_engine"""					)







@lru_cache
def     _a					(   _SCREAMING_SNAKE_CASE=True					)     ->					int:
							# Due to bugs on the amp series GPUs, we disable torch-xla on them
							if torch.cuda.is_available():
														return False
							if _tpu_available and check_device:
														try:
																					# Will raise a RuntimeError if no XLA configuration is found
																					snake_case_     							=		xm.xla_device()
																					return True
														except RuntimeError:
																					return False
							return _tpu_available







def     _a					(   )     ->					List[str]:
							return _is_package_available("""deepspeed"""					)







def     _a					(   _SCREAMING_SNAKE_CASE=False					)     ->					Optional[int]:
							if is_tpu_available():
														return not ignore_tpu
							if torch.cuda.is_available():
														return torch.cuda.is_bfaa_supported()
							if is_npu_available():
														return False
							return True







def     _a					(   )     ->					Any:
							snake_case_     							=		_is_package_available("""bitsandbytes"""					)
							if package_exists:
														snake_case_     							=		version.parse(importlib.metadata.version("""bitsandbytes"""					)					)
														return compare_versions(_SCREAMING_SNAKE_CASE					,			""">="""					,			"""0.39.0"""					)
							return False







def     _a					(   )     ->					List[Any]:
							snake_case_     							=		_is_package_available("""bitsandbytes"""					)
							if package_exists:
														snake_case_     							=		version.parse(importlib.metadata.version("""bitsandbytes"""					)					)
														return compare_versions(_SCREAMING_SNAKE_CASE					,			""">="""					,			"""0.37.2"""					)
							return False







def     _a					(   )     ->					Union[str, Any]:
							return _is_package_available("""bitsandbytes"""					)







def     _a					(   )     ->					Optional[int]:
							if strtobool(os.environ.get("""ACCELERATE_USE_MEGATRON_LM"""					,			"""False"""					)					) == 1:
														snake_case_     							=		importlib.util.find_spec("""megatron"""					) is not None
														if package_exists:
																					try:
																												snake_case_     							=		parse(importlib.metadata.version("""megatron-lm"""					)					)
																												return compare_versions(_SCREAMING_SNAKE_CASE					,			""">="""					,			"""2.2.0"""					)
																					except Exception as e:
																												warnings.warn(f"""Parse Megatron version failed. Exception:{e}"""					)
																												return False







def     _a					(   )     ->					str:
							return _is_package_available("""safetensors"""					)







def     _a					(   )     ->					str:
							return _is_package_available("""transformers"""					)







def     _a					(   )     ->					Union[str, Any]:
							return _is_package_available("""datasets"""					)







def     _a					(   )     ->					List[str]:
							return _is_package_available("""aim"""					)







def     _a					(   )     ->					List[str]:
							return _is_package_available("""tensorboard"""					) or _is_package_available("""tensorboardX"""					)







def     _a					(   )     ->					int:
							return _is_package_available("""wandb"""					)







def     _a					(   )     ->					List[Any]:
							return _is_package_available("""comet_ml"""					)







def     _a					(   )     ->					Union[str, Any]:
							return _is_package_available("""boto3"""					)







def     _a					(   )     ->					Optional[Any]:
							if _is_package_available("""rich"""					):
														if "ACCELERATE_DISABLE_RICH" in os.environ:
																					warnings.warn(
																					    """`ACCELERATE_DISABLE_RICH` is deprecated and will be removed in v0.22.0 and deactivated by default. Please use `ACCELERATE_ENABLE_RICH` if you wish to use `rich`."""					)
																					return not parse_flag_from_env("""ACCELERATE_DISABLE_RICH"""					,			_SCREAMING_SNAKE_CASE					)
														return parse_flag_from_env("""ACCELERATE_ENABLE_RICH"""					,			_SCREAMING_SNAKE_CASE					)
							return False







def     _a					(   )     ->					List[Any]:
							return _is_package_available("""sagemaker"""					)







def     _a					(   )     ->					int:
							return _is_package_available("""tqdm"""					)







def     _a					(   )     ->					List[Any]:
							return _is_package_available("""mlflow"""					)







def     _a					(   )     ->					int:
							return is_torch_version(""">="""					,			"""1.12"""					) and torch.backends.mps.is_available() and torch.backends.mps.is_built()







def     _a					(   )     ->					Any:
							def get_major_and_minor_from_version(_SCREAMING_SNAKE_CASE					):
														return str(version.parse(_SCREAMING_SNAKE_CASE					).major					) + "." + str(version.parse(_SCREAMING_SNAKE_CASE					).minor					)

							snake_case_     							=		importlib.metadata.version("""torch"""					)
							if importlib.util.find_spec("""intel_extension_for_pytorch"""					) is None:
														return False
							snake_case_     							=		"""N/A"""
							try:
														snake_case_     							=		importlib.metadata.version("""intel_extension_for_pytorch"""					)
							except importlib.metadata.PackageNotFoundError:
														return False
							snake_case_     							=		get_major_and_minor_from_version(_torch_version					)
							snake_case_     							=		get_major_and_minor_from_version(_ipex_version					)
							if torch_major_and_minor != ipex_major_and_minor:
														warnings.warn(
														    f"""Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*,"""
														    f""" but PyTorch {_torch_version} is found. Please switch to the matching version and run again."""					)
														return False
							return True







@lru_cache
def     _a					(   _SCREAMING_SNAKE_CASE=False					)     ->					List[str]:
							if importlib.util.find_spec("""torch"""					) is None or importlib.util.find_spec("""torch_npu"""					) is None:
														return False

							import torch
							import torch_npu  # noqa: F401

							if check_device:
														try:
																					# Will raise a RuntimeError if no NPU is found
																					snake_case_     							=		torch.npu.device_count()
																					return torch.npu.is_available()
														except RuntimeError:
																					return False
							return hasattr(_SCREAMING_SNAKE_CASE					,			"""npu"""					) and torch.npu.is_available()







@lru_cache
def     _a					(   _SCREAMING_SNAKE_CASE=False					)     ->					int:
							if not parse_flag_from_env("""ACCELERATE_USE_XPU"""					,			default=_SCREAMING_SNAKE_CASE					):
														return False
							if is_ipex_available():
														import torch

														if is_torch_version("""<="""					,			"""1.12"""					):
																					return False
							else:
														return False

							import intel_extension_for_pytorch  # noqa: F401

							if check_device:
														try:
																					# Will raise a RuntimeError if no XPU  is found
																					snake_case_     							=		torch.xpu.device_count()
																					return torch.xpu.is_available()
														except RuntimeError:
																					return False
							return hasattr(_SCREAMING_SNAKE_CASE					,			"""xpu"""					) and torch.xpu.is_available()



