

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							(			lowerCAmelCase:					Optional[Any]					, lowerCAmelCase:					Dict=False	)				->    str:
				try:
								_UpperCAmelCase    :						Optional[int]							=      os.environ[key]
				except KeyError:
								# KEY isn't set, default to `default`.
								_UpperCAmelCase    :						Any							=      default
				else:
								# KEY is set, convert it to True or False.
								try:
												_UpperCAmelCase    :						str							=      strtobool(snake_case_	)
								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


SCREAMING_SNAKE_CASE_        = parse_flag_from_env('RUN_SLOW', default=False)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Tuple	)				->    Optional[int]:
				return unittest.skip("Test was skipped"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[int]	)				->    Dict:
				return unittest.skipUnless(_run_slow_tests					, "test is slow"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[str]	)				->    str:
				return unittest.skipUnless(not torch.cuda.is_available()					, "test requires only a CPU"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Tuple	)				->    Dict:
				return unittest.skipUnless(torch.cuda.is_available()					, "test requires a GPU"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					str	)				->    Union[str, Any]:
				return unittest.skipUnless(is_xpu_available()					, "test requires a XPU"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Tuple	)				->    Optional[Any]:
				return unittest.skipUnless(is_mps_available()					, "test requires a `mps` backend support in `torch`"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Tuple	)				->    Dict:
				return unittest.skipUnless(
				    is_transformers_available() and is_datasets_available()					, "test requires the Hugging Face suite"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[Any]	)				->    Dict:
				return unittest.skipUnless(is_bnb_available()					, "test requires the bitsandbytes library"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Any	)				->    int:
				return unittest.skipUnless(is_tpu_available()					, "test requires TPU"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[str]	)				->    str:
				return unittest.skipUnless(torch.cuda.device_count() == 1					, "test requires a GPU"	)(snake_case_	)

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

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[str]	)				->    Union[str, Any]:
				return unittest.skipUnless(torch.cuda.device_count() > 1					, "test requires multiple GPUs"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[Any]	)				->    List[str]:
				return unittest.skipUnless(torch.xpu.device_count() > 1					, "test requires multiple XPUs"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Dict	)				->    Optional[int]:
				return unittest.skipUnless(is_safetensors_available()					, "test requires safetensors"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[Any]	)				->    Optional[int]:
				return unittest.skipUnless(is_deepspeed_available()					, "test requires DeepSpeed"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[int]	)				->    List[Any]:
				return unittest.skipUnless(is_torch_version(">="					, "1.12.0"	)					, "test requires torch version >= 1.12.0"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Tuple=None					, lowerCAmelCase:					List[str]=None	)				->    Optional[int]:
				if test_case is None:
								return partial(snake_case_					, version=snake_case_	)
				return unittest.skipUnless(is_torch_version(">="					, snake_case_	)					, F'test requires torch version >= {version}'	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Tuple	)				->    Tuple:
				return unittest.skipUnless(is_tensorboard_available()					, "test requires Tensorboard"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Union[str, Any]	)				->    Optional[int]:
				return unittest.skipUnless(is_wandb_available()					, "test requires wandb"	)(snake_case_	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Tuple	)				->    Any:
				return unittest.skipUnless(is_comet_ml_available()					, "test requires comet_ml"	)(snake_case_	)


SCREAMING_SNAKE_CASE_        = (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)

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

class 			a					(		unittest.TestCase			):
						_lowercase        =     True


						@classmethod
						def     _UpperCAmelCase			(    cls		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[Any]							=      tempfile.mkdtemp()


						@classmethod
						def     _UpperCAmelCase			(    cls		):







										'''simple docstring'''


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





						def     _UpperCAmelCase			(    self		):







										'''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(SCREAMING_SNAKE_CASE_		)







class 			a					(		unittest.TestCase			):


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


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







class 			a					(		unittest.TestCase			):


						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


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







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

class 			a					:


						def __init__(    self  ,   A_  ,   A_  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      returncode
										_UpperCAmelCase    :						List[str]							=      stdout
										_UpperCAmelCase    :						Union[str, Any]							=      stderr







async def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Union[str, Any]					, lowerCAmelCase:					List[str]	)				->    Union[str, Any]:
				while True:
								_UpperCAmelCase    :						Any							=      await stream.readline()
								if line:
												callback(snake_case_	)
								else:
												break

async def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[str]					, lowerCAmelCase:					Tuple=None					, lowerCAmelCase:					int=None					, lowerCAmelCase:					str=None					, lowerCAmelCase:					Dict=False					, lowerCAmelCase:					List[str]=False	)				->    Optional[Any]:
				if echo:
								print("\nRunning: "					, " ".join(snake_case_	)	)

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

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

				_UpperCAmelCase    :						List[Any]							=      []
				_UpperCAmelCase    :						List[str]							=      []

				def tee(lowerCAmelCase:					List[Any]					, lowerCAmelCase:					Tuple					, lowerCAmelCase:					int					, lowerCAmelCase:					str=""	):
								_UpperCAmelCase    :						Tuple							=      line.decode("utf-8"	).rstrip()
								sink.append(snake_case_	)
								if not quiet:
												print(snake_case_					, snake_case_					, file=snake_case_	)

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

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[Any]					, lowerCAmelCase:					Optional[Any]=None					, lowerCAmelCase:					Dict=None					, lowerCAmelCase:					Any=180					, lowerCAmelCase:					List[str]=False					, lowerCAmelCase:					Optional[Any]=True	)				->    Optional[Any]:
				_UpperCAmelCase    :						List[str]							=      asyncio.get_event_loop()
				_UpperCAmelCase    :						Dict							=      loop.run_until_complete(
				    _stream_subprocess(snake_case_					, env=snake_case_					, stdin=snake_case_					, timeout=snake_case_					, quiet=snake_case_					, echo=snake_case_	)	)

				_UpperCAmelCase    :						int							=      """ """.join(snake_case_	)
				if result.returncode > 0:
								_UpperCAmelCase    :						List[Any]							=      """\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			):
						pass







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





import inspect
import re

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
SCREAMING_SNAKE_CASE_            = 'src/transformers'


# This is to make sure the transformers module imported is the one in the repo.
SCREAMING_SNAKE_CASE_            = direct_transformers_import(PATH_TO_TRANSFORMERS)

SCREAMING_SNAKE_CASE_            = transformers.models.auto.configuration_auto.CONFIG_MAPPING

# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
SCREAMING_SNAKE_CASE_            = re.compile(R'\[(.+?)\]\((https://huggingface\.co/.+?)\)')


SCREAMING_SNAKE_CASE_            = {
    'DecisionTransformerConfig',
    'EncoderDecoderConfig',
    'MusicgenConfig',
    'RagConfig',
    'SpeechEncoderDecoderConfig',
    'TimmBackboneConfig',
    'VisionEncoderDecoderConfig',
    'VisionTextDualEncoderConfig',
    'LlamaConfig',
}

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Dict	)				->    Union[str, Any]:
				_UpperCAmelCase    :						List[Any]							=      None

				# source code of `config_class`
				_UpperCAmelCase    :						int							=      inspect.getsource(lowerCAmelCase	)
				_UpperCAmelCase    :						Tuple							=      _re_checkpoint.findall(lowerCAmelCase	)

				# Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
				# For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
				for ckpt_name, ckpt_link in checkpoints:
								# allow the link to end with `/`
								if ckpt_link.endswith("/"	):
												_UpperCAmelCase    :						Dict							=      ckpt_link[:-1]

								# verify the checkpoint name corresponds to the checkpoint link
								_UpperCAmelCase    :						Any							=      F'https://huggingface.co/{ckpt_name}'
								if ckpt_link == ckpt_link_from_name:
												_UpperCAmelCase    :						Union[str, Any]							=      ckpt_name
												break

				return checkpoint

def 							__SCREAMING_SNAKE_CASE							(			)				->    Dict:
				_UpperCAmelCase    :						Any							=      []

				for config_class in list(CONFIG_MAPPING.values()	):
								# Skip deprecated models
								if "models.deprecated" in config_class.__module__:
												continue
								_UpperCAmelCase    :						int							=      get_checkpoint_from_config_class(lowerCAmelCase	)

								_UpperCAmelCase    :						Tuple							=      config_class.__name__
								if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
												configs_without_checkpoint.append(lowerCAmelCase	)

				if len(lowerCAmelCase	) > 0:
								_UpperCAmelCase    :						int							=      "\n".join(sorted(lowerCAmelCase	)	)
								raise ValueError(F'The following configurations don\'t contain any valid checkpoint:\n{message}'	)


if __name__ == "__main__":
					check_config_docstrings_have_checkpoints()


