


import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)






def 			UpperCamelCase (     __magic_name__					:							Optional[Any]   ,   __magic_name__					:							int=False					)       ->  Any:
		"""simple docstring"""




		try:
				lowercase__					      =		os.environ[key]
		except KeyError:
				# KEY isn't set, default to `default`.
				lowercase__					      =		default
		else:
				# KEY is set, convert it to True or False.
				try:
						lowercase__					      =		strtobool(__magic_name__					)
				except ValueError:
						# More values are supported, but let's keep the message simple.
						raise ValueError(f'''If set, {key} must be yes or no.'''					)
		return _value


A	:		List[str]    =       parse_flag_from_env('RUN_SLOW', default=False)






def 			UpperCamelCase (     __magic_name__					:							str					)       ->  List[Any]:
		"""simple docstring"""




		return unittest.skip("""Test was skipped"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							List[str]					)       ->  Union[str, Any]:
		"""simple docstring"""




		return unittest.skipUnless(_run_slow_tests   ,   """test is slow"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							List[Any]					)       ->  Any:
		"""simple docstring"""




		return unittest.skipUnless(not torch.cuda.is_available()   ,   """test requires only a CPU"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							Union[str, Any]					)       ->  int:
		"""simple docstring"""




		return unittest.skipUnless(torch.cuda.is_available()   ,   """test requires a GPU"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							str					)       ->  Dict:
		"""simple docstring"""




		return unittest.skipUnless(is_xpu_available()   ,   """test requires a XPU"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							List[Any]					)       ->  int:
		"""simple docstring"""




		return unittest.skipUnless(is_mps_available()   ,   """test requires a `mps` backend support in `torch`"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							Any					)       ->  Union[str, Any]:
		"""simple docstring"""




		return unittest.skipUnless(
		    is_transformers_available() and is_datasets_available()   ,   """test requires the Hugging Face suite"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							Union[str, Any]					)       ->  Dict:
		"""simple docstring"""




		return unittest.skipUnless(is_bnb_available()   ,   """test requires the bitsandbytes library"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							int					)       ->  Dict:
		"""simple docstring"""




		return unittest.skipUnless(is_tpu_available()   ,   """test requires TPU"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							Optional[Any]					)       ->  Optional[Any]:
		"""simple docstring"""




		return unittest.skipUnless(torch.cuda.device_count() == 1   ,   """test requires a GPU"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							Union[str, Any]					)       ->  List[Any]:
		"""simple docstring"""




		return unittest.skipUnless(torch.xpu.device_count() == 1   ,   """test requires a XPU"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							Any					)       ->  int:
		"""simple docstring"""




		return unittest.skipUnless(torch.cuda.device_count() > 1   ,   """test requires multiple GPUs"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							Dict					)       ->  Tuple:
		"""simple docstring"""




		return unittest.skipUnless(torch.xpu.device_count() > 1   ,   """test requires multiple XPUs"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							int					)       ->  List[str]:
		"""simple docstring"""




		return unittest.skipUnless(is_safetensors_available()   ,   """test requires safetensors"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							List[Any]					)       ->  int:
		"""simple docstring"""




		return unittest.skipUnless(is_deepspeed_available()   ,   """test requires DeepSpeed"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							Any					)       ->  Dict:
		"""simple docstring"""




		return unittest.skipUnless(is_torch_version(""">="""   ,   """1.12.0"""					)   ,   """test requires torch version >= 1.12.0"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							Optional[Any]=None   ,   __magic_name__					:							Union[str, Any]=None					)       ->  str:
		"""simple docstring"""




		if test_case is None:
				return partial(__magic_name__   ,   version=__magic_name__					)
		return unittest.skipUnless(is_torch_version(""">="""   ,   __magic_name__					)   ,   f'''test requires torch version >= {version}'''					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							Optional[int]					)       ->  Optional[int]:
		"""simple docstring"""




		return unittest.skipUnless(is_tensorboard_available()   ,   """test requires Tensorboard"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							Union[str, Any]					)       ->  Any:
		"""simple docstring"""




		return unittest.skipUnless(is_wandb_available()   ,   """test requires wandb"""					)(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							Optional[Any]					)       ->  Optional[Any]:
		"""simple docstring"""




		return unittest.skipUnless(is_comet_ml_available()   ,   """test requires comet_ml"""					)(__magic_name__					)


A	:		List[Any]    =       (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)






def 			UpperCamelCase (     __magic_name__					:							Optional[int]					)       ->  List[Any]:
		"""simple docstring"""




		return unittest.skipUnless(
		    _atleast_one_tracker_available   ,   """test requires at least one tracker to be available and for `comet_ml` to not be installed"""   ,   )(__magic_name__					)



class 							A   (	unittest.TestCase							):
					'''simple docstring'''






					A__      =			True

					@classmethod
					def   lowerCamelCase__					(cls   :						int		)						->       Union[str, Any]:




							"""simple docstring"""


							lowercase__					      =		tempfile.mkdtemp()

					@classmethod
					def   lowerCamelCase__					(cls   :						Tuple		)						->       Any:




							"""simple docstring"""


							if os.path.exists(cls.tmpdir		):
									shutil.rmtree(cls.tmpdir		)


					def   lowerCamelCase__					(self   :						Dict		)						->       List[str]:




							"""simple docstring"""


							if self.clear_on_setup:
									for path in Path(self.tmpdir		).glob("""**/*"""		):
											if path.is_file():
													path.unlink()
											elif path.is_dir():
													shutil.rmtree(_UpperCAmelCase		)






class 							A   (	unittest.TestCase							):
					'''simple docstring'''






					def   lowerCamelCase__					(self   :						Union[str, Any]		)						->       List[str]:




							"""simple docstring"""


							super().tearDown()
							# Reset the state of the AcceleratorState singleton.
							AcceleratorState._reset_state()
							PartialState._reset_state()






class 							A   (	unittest.TestCase							):
					'''simple docstring'''






					def   lowerCamelCase__					(self   :						int				, _UpperCAmelCase   :						Union[mock.Mock, List[mock.Mock]]		)						->       Union[str, Any]:




							"""simple docstring"""


							lowercase__					      =		mocks if isinstance(_UpperCAmelCase				, (tuple, list)		) else [mocks]
							for m in self.mocks:
									m.start()
									self.addCleanup(m.stop		)






def 			UpperCamelCase (     __magic_name__					:							Dict					)       ->  List[str]:
		"""simple docstring"""




		lowercase__					      =		AcceleratorState()
		lowercase__					      =		tensor[None].clone().to(state.device					)
		lowercase__					      =		gather(__magic_name__					).cpu()
		lowercase__					      =		tensor[0].cpu()
		for i in range(tensors.shape[0]					):
				if not torch.equal(tensors[i]   ,   __magic_name__					):
						return False
		return True



class 							A   :
					'''simple docstring'''






					def __init__(self   :						Any				, _UpperCAmelCase   :						Dict				, _UpperCAmelCase   :						List[Any]				, _UpperCAmelCase   :						Optional[Any]		)						->       Tuple:




							"""simple docstring"""


							lowercase__					      =		returncode
							lowercase__					      =		stdout
							lowercase__					      =		stderr






async def 			UpperCamelCase (     __magic_name__					:							Optional[Any]   ,   __magic_name__					:							Optional[int]					)       ->  Optional[int]:
		"""simple docstring"""




		while True:
				lowercase__					      =		await stream.readline()
				if line:
						callback(__magic_name__					)
				else:
						break






async def 			UpperCamelCase (     __magic_name__					:							List[str]   ,   __magic_name__					:							Dict=None   ,   __magic_name__					:							Union[str, Any]=None   ,   __magic_name__					:							Optional[int]=None   ,   __magic_name__					:							List[str]=False   ,   __magic_name__					:							List[Any]=False					)       ->  _RunOutput:
		"""simple docstring"""




		if echo:
				print("""\nRunning: """   ,   """ """.join(__magic_name__					)					)

		lowercase__					      =		await asyncio.create_subprocess_exec(
		    cmd[0]   ,   *cmd[1:]   ,   stdin=__magic_name__   ,   stdout=asyncio.subprocess.PIPE   ,   stderr=asyncio.subprocess.PIPE   ,   env=__magic_name__   ,   )

		# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
		# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
		#
		# If it starts hanging, will need to switch to the following code. The problem is that no data
		# will be seen until it's done and if it hangs for example there will be no debug info.
		# out, err = await p.communicate()
		# return _RunOutput(p.returncode, out, err)

		lowercase__					      =		[]
		lowercase__					      =		[]

		def tee(__magic_name__					:							Tuple   ,   __magic_name__					:							Union[str, Any]   ,   __magic_name__					:							Optional[Any]   ,   __magic_name__					:							str=""					):
				lowercase__					      =		line.decode("""utf-8"""					).rstrip()
				sink.append(__magic_name__					)
				if not quiet:
						print(__magic_name__   ,   __magic_name__   ,   file=__magic_name__					)

    # XXX: the timeout doesn't seem to make any difference here
		await asyncio.wait(
		    [
		        asyncio.create_task(_read_stream(p.stdout   ,   lambda __magic_name__					: tee(__magic_name__   ,   __magic_name__   ,   sys.stdout   ,   label="""stdout:"""					)					)					),
		        asyncio.create_task(_read_stream(p.stderr   ,   lambda __magic_name__					: tee(__magic_name__   ,   __magic_name__   ,   sys.stderr   ,   label="""stderr:"""					)					)					),
		    ]   ,   timeout=__magic_name__   ,   )
		return _RunOutput(await p.wait()   ,   __magic_name__   ,   __magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							Union[str, Any]   ,   __magic_name__					:							List[str]=None   ,   __magic_name__					:							Union[str, Any]=None   ,   __magic_name__					:							Union[str, Any]=180   ,   __magic_name__					:							Union[str, Any]=False   ,   __magic_name__					:							Tuple=True					)       ->  _RunOutput:
		"""simple docstring"""




		lowercase__					      =		asyncio.get_event_loop()
		lowercase__					      =		loop.run_until_complete(
		    _stream_subprocess(__magic_name__   ,   env=__magic_name__   ,   stdin=__magic_name__   ,   timeout=__magic_name__   ,   quiet=__magic_name__   ,   echo=__magic_name__					)					)

		lowercase__					      =		""" """.join(__magic_name__					)
		if result.returncode > 0:
				lowercase__					      =		"""\n""".join(result.stderr					)
				raise RuntimeError(
				    f'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
				    f'''The combined stderr from workers follows:\n{stderr}'''					)

		return result



class 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






					pass






def 			UpperCamelCase (     __magic_name__					:							List[str]   ,   __magic_name__					:							int=False					)       ->  List[str]:
		"""simple docstring"""




		try:
				lowercase__					      =		subprocess.check_output(__magic_name__   ,   stderr=subprocess.STDOUT					)
				if return_stdout:
						if hasattr(__magic_name__   ,   """decode"""					):
								lowercase__					      =		output.decode("""utf-8"""					)
						return output
		except subprocess.CalledProcessError as e:
				raise SubprocessCallException(
				    f'''Command `{" ".join(__magic_name__					)}` failed with the following error:\n\n{e.output.decode()}'''					) from e





import warnings
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


A	:		List[str]    =       logging.get_logger(__name__)

A	:		List[Any]    =       {
    'nvidia/segformer-b0-finetuned-ade-512-512': (
        'https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json'
    ),
    # See all SegFormer models at https://huggingface.co/models?filter=segformer
}



class 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






					A__      =			'''segformer'''

					def __init__(self   :						Dict				, _UpperCAmelCase   :						Optional[int]=3				, _UpperCAmelCase   :						Dict=4				, _UpperCAmelCase   :						Union[str, Any]=[2, 2, 2, 2]				, _UpperCAmelCase   :						List[str]=[8, 4, 2, 1]				, _UpperCAmelCase   :						str=[32, 64, 160, 256]				, _UpperCAmelCase   :						Optional[int]=[7, 3, 3, 3]				, _UpperCAmelCase   :						int=[4, 2, 2, 2]				, _UpperCAmelCase   :						str=[1, 2, 5, 8]				, _UpperCAmelCase   :						Optional[int]=[4, 4, 4, 4]				, _UpperCAmelCase   :						List[Any]="gelu"				, _UpperCAmelCase   :						Optional[Any]=0.0				, _UpperCAmelCase   :						Dict=0.0				, _UpperCAmelCase   :						Dict=0.1				, _UpperCAmelCase   :						List[str]=0.02				, _UpperCAmelCase   :						str=0.1				, _UpperCAmelCase   :						Optional[Any]=1E-6				, _UpperCAmelCase   :						Optional[Any]=256				, _UpperCAmelCase   :						Any=255				, **_UpperCAmelCase   :						str				, )						->       Tuple:




							"""simple docstring"""


							super().__init__(**_UpperCAmelCase		)

							if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
									warnings.warn(
									    """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be"""
									    """ removed, as the behaviour will default to that of reshape_last_stage = True."""				, _UpperCAmelCase				, )

							lowercase__					      =		num_channels
							lowercase__					      =		num_encoder_blocks
							lowercase__					      =		depths
							lowercase__					      =		sr_ratios
							lowercase__					      =		hidden_sizes
							lowercase__					      =		patch_sizes
							lowercase__					      =		strides
							lowercase__					      =		mlp_ratios
							lowercase__					      =		num_attention_heads
							lowercase__					      =		hidden_act
							lowercase__					      =		hidden_dropout_prob
							lowercase__					      =		attention_probs_dropout_prob
							lowercase__					      =		classifier_dropout_prob
							lowercase__					      =		initializer_range
							lowercase__					      =		drop_path_rate
							lowercase__					      =		layer_norm_eps
							lowercase__					      =		decoder_hidden_size
							lowercase__					      =		kwargs.get("""reshape_last_stage"""				, _UpperCAmelCase		)
							lowercase__					      =		semantic_loss_ignore_index






class 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






					A__      =			version.parse('''1.11'''							)

					@property
					def   lowerCamelCase__					(self   :						Optional[int]		)						->       Mapping[str, Mapping[int, str]]:




							"""simple docstring"""


							return OrderedDict(
							    [
							        ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
							    ]		)

					@property
					def   lowerCamelCase__					(self   :						Optional[int]		)						->       float:




							"""simple docstring"""


							return 1E-4


					@property
					def   lowerCamelCase__					(self   :						Optional[Any]		)						->       int:




							"""simple docstring"""


							return 12

