






'''simple docstring'''







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 				SCREAMING_SNAKE_CASE_ (UpperCamelCase       ,    UpperCamelCase=False   )   -> Tuple:
							try:
														lowerCamelCase__      :			Dict 						= os.environ[key]
							except KeyError:
														# KEY isn't set, default to `default`.
														lowerCamelCase__      :			Union[str, Any] 						= default
							else:
														# KEY is set, convert it to True or False.
														try:
																					lowerCamelCase__      :			Optional[Any] 						= strtobool(UpperCamelCase   )
														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			:    Dict					  =parse_flag_from_env('''RUN_SLOW''', default=False)





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> Tuple:
							return unittest.skip("""Test was skipped"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> str:
							return unittest.skipUnless(_run_slow_tests       ,    """test is slow"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> Optional[Any]:
							return unittest.skipUnless(not torch.cuda.is_available()       ,    """test requires only a CPU"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> Optional[Any]:
							return unittest.skipUnless(torch.cuda.is_available()       ,    """test requires a GPU"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> Dict:
							return unittest.skipUnless(is_xpu_available()       ,    """test requires a XPU"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> Dict:
							return unittest.skipUnless(is_mps_available()       ,    """test requires a `mps` backend support in `torch`"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> Tuple:
							return unittest.skipUnless(
							    is_transformers_available() and is_datasets_available()       ,    """test requires the Hugging Face suite"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> Optional[int]:
							return unittest.skipUnless(is_bnb_available()       ,    """test requires the bitsandbytes library"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> List[str]:
							return unittest.skipUnless(is_tpu_available()       ,    """test requires TPU"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> Union[str, Any]:
							return unittest.skipUnless(torch.cuda.device_count() == 1       ,    """test requires a GPU"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> str:
							return unittest.skipUnless(torch.xpu.device_count() == 1       ,    """test requires a XPU"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> List[Any]:
							return unittest.skipUnless(torch.cuda.device_count() > 1       ,    """test requires multiple GPUs"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> Union[str, Any]:
							return unittest.skipUnless(torch.xpu.device_count() > 1       ,    """test requires multiple XPUs"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> Union[str, Any]:
							return unittest.skipUnless(is_safetensors_available()       ,    """test requires safetensors"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> Optional[Any]:
							return unittest.skipUnless(is_deepspeed_available()       ,    """test requires DeepSpeed"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> int:
							return unittest.skipUnless(is_torch_version(""">="""       ,    """1.12.0"""   )       ,    """test requires torch version >= 1.12.0"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase=None       ,    UpperCamelCase=None   )   -> List[Any]:
							if test_case is None:
														return partial(UpperCamelCase       ,    version=UpperCamelCase   )
							return unittest.skipUnless(is_torch_version(""">="""       ,    UpperCamelCase   )       ,    f'''test requires torch version >= {version}'''   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> List[Any]:
							return unittest.skipUnless(is_tensorboard_available()       ,    """test requires Tensorboard"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> List[str]:
							return unittest.skipUnless(is_wandb_available()       ,    """test requires wandb"""   )(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> List[Any]:
							return unittest.skipUnless(is_comet_ml_available()       ,    """test requires comet_ml"""   )(UpperCamelCase   )


_A			:    Union[str, Any]					  =(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> Any:
							return unittest.skipUnless(
							    _atleast_one_tracker_available       ,    """test requires at least one tracker to be available and for `comet_ml` to not be installed"""       ,    )(UpperCamelCase   )

class _lowercase			(       unittest.TestCase	):
							a          = True




							@classmethod
							def 	lowerCamelCase_       (							cls:       Dict  ):
														lowerCamelCase__      :			str 						= tempfile.mkdtemp()




							@classmethod
							def 	lowerCamelCase_       (							cls:       Optional[int]  ):
														if os.path.exists(cls.tmpdir  ):
																					shutil.rmtree(cls.tmpdir  )




							def 	lowerCamelCase_       (							self:       int  ):
														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 _lowercase			(       unittest.TestCase	):




							def 	lowerCamelCase_       (							self:       Optional[int]  ):
														super().tearDown()
														# Reset the state of the AcceleratorState singleton.
														AcceleratorState._reset_state()
														PartialState._reset_state()



class _lowercase			(       unittest.TestCase	):




							def 	lowerCamelCase_       (							self:       Dict    ,							UpperCamelCase__:       Union[mock.Mock, List[mock.Mock]]  ):
														lowerCamelCase__      :			List[str] 						= mocks if isinstance(UpperCamelCase__    ,							(tuple, list)  ) else [mocks]
														for m in self.mocks:
																					m.start()
																					self.addCleanup(m.stop  )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> List[str]:
							lowerCamelCase__      :			Tuple 						= AcceleratorState()
							lowerCamelCase__      :			List[str] 						= tensor[None].clone().to(state.device   )
							lowerCamelCase__      :			Optional[Any] 						= gather(UpperCamelCase   ).cpu()
							lowerCamelCase__      :			Optional[Any] 						= tensor[0].cpu()
							for i in range(tensors.shape[0]   ):
														if not torch.equal(tensors[i]       ,    UpperCamelCase   ):
																					return False
							return True

class _lowercase			:




							def __init__(							self:       Dict    ,							UpperCamelCase__:       List[Any]    ,							UpperCamelCase__:       List[str]    ,							UpperCamelCase__:       Union[str, Any]  ):
														lowerCamelCase__      :			Any 						= returncode
														lowerCamelCase__      :			Tuple 						= stdout
														lowerCamelCase__      :			Union[str, Any] 						= stderr





async def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase       ,    UpperCamelCase   )   -> Any:
							while True:
														lowerCamelCase__      :			str 						= await stream.readline()
														if line:
																					callback(UpperCamelCase   )
														else:
																					break





async def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase       ,    UpperCamelCase=None       ,    UpperCamelCase=None       ,    UpperCamelCase=None       ,    UpperCamelCase=False       ,    UpperCamelCase=False   )   -> _RunOutput:
							if echo:
														print("""\nRunning: """       ,    """ """.join(UpperCamelCase   )   )

							lowerCamelCase__      :			Optional[Any] 						= await asyncio.create_subprocess_exec(
							    cmd[0]       ,    *cmd[1:]       ,    stdin=UpperCamelCase       ,    stdout=asyncio.subprocess.PIPE       ,    stderr=asyncio.subprocess.PIPE       ,    env=UpperCamelCase       ,    )

							# 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)

							lowerCamelCase__      :			Any 						= []
							lowerCamelCase__      :			Union[str, Any] 						= []

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

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





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase       ,    UpperCamelCase=None       ,    UpperCamelCase=None       ,    UpperCamelCase=180       ,    UpperCamelCase=False       ,    UpperCamelCase=True   )   -> _RunOutput:
							lowerCamelCase__      :			Dict 						= asyncio.get_event_loop()
							lowerCamelCase__      :			int 						= loop.run_until_complete(
							    _stream_subprocess(UpperCamelCase       ,    env=UpperCamelCase       ,    stdin=UpperCamelCase       ,    timeout=UpperCamelCase       ,    quiet=UpperCamelCase       ,    echo=UpperCamelCase   )   )

							lowerCamelCase__      :			str 						= """ """.join(UpperCamelCase   )
							if result.returncode > 0:
														lowerCamelCase__      :			int 						= """\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 _lowercase			(       _lowercase	):
							pass





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase       ,    UpperCamelCase=False   )   -> Dict:
							try:
														lowerCamelCase__      :			Union[str, Any] 						= subprocess.check_output(UpperCamelCase       ,    stderr=subprocess.STDOUT   )
														if return_stdout:
																					if hasattr(UpperCamelCase       ,    """decode"""   ):
																												lowerCamelCase__      :			List[str] 						= output.decode("""utf-8"""   )
																					return output
							except subprocess.CalledProcessError as e:
														raise SubprocessCallException(
														    f'''Command `{' '.join(UpperCamelCase   )}` failed with the following error:\n\n{e.output.decode()}'''   ) from e









'''simple docstring'''







from ...configuration_utils import PretrainedConfig
from ...utils import logging


_A			:    Union[str, Any]					  =logging.get_logger(__name__)

_A			:    List[str]					  ={
    '''MIT/ast-finetuned-audioset-10-10-0.4593''': (
        '''https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json'''
    ),
}

class _lowercase			(       _lowercase	):
							a          = """audio-spectrogram-transformer"""




							def __init__(							self:       str    ,							UpperCamelCase__:       Any=768    ,							UpperCamelCase__:       Union[str, Any]=12    ,							UpperCamelCase__:       List[Any]=12    ,							UpperCamelCase__:       int=3_072    ,							UpperCamelCase__:       Optional[Any]="gelu"    ,							UpperCamelCase__:       Optional[int]=0.0    ,							UpperCamelCase__:       Tuple=0.0    ,							UpperCamelCase__:       Union[str, Any]=0.02    ,							UpperCamelCase__:       Dict=1e-12    ,							UpperCamelCase__:       List[str]=16    ,							UpperCamelCase__:       List[str]=True    ,							UpperCamelCase__:       Any=10    ,							UpperCamelCase__:       List[str]=10    ,							UpperCamelCase__:       Any=1_024    ,							UpperCamelCase__:       Optional[Any]=128    ,							**UpperCamelCase__:       Union[str, Any]    ,							):
														super().__init__(**UpperCamelCase__  )

														lowerCamelCase__      :			List[Any] 						= hidden_size
														lowerCamelCase__      :			int 						= num_hidden_layers
														lowerCamelCase__      :			List[str] 						= num_attention_heads
														lowerCamelCase__      :			Optional[int] 						= intermediate_size
														lowerCamelCase__      :			List[Any] 						= hidden_act
														lowerCamelCase__      :			List[Any] 						= hidden_dropout_prob
														lowerCamelCase__      :			str 						= attention_probs_dropout_prob
														lowerCamelCase__      :			Dict 						= initializer_range
														lowerCamelCase__      :			List[str] 						= layer_norm_eps
														lowerCamelCase__      :			List[Any] 						= patch_size
														lowerCamelCase__      :			List[str] 						= qkv_bias
														lowerCamelCase__      :			Dict 						= frequency_stride
														lowerCamelCase__      :			List[Any] 						= time_stride
														lowerCamelCase__      :			str 						= max_length
														lowerCamelCase__      :			Dict 						= num_mel_bins

