


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


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


def    _snake_case  (	A			)		->       List[Any]:
							return unittest.skip('''Test was skipped'''			)(A			)


def    _snake_case  (	A			)		->       Tuple:
							return unittest.skipUnless(_run_slow_tests					,       '''test is slow'''			)(A			)


def    _snake_case  (	A			)		->       Any:
							return unittest.skipUnless(not torch.cuda.is_available()					,       '''test requires only a CPU'''			)(A			)


def    _snake_case  (	A			)		->       str:
							return unittest.skipUnless(torch.cuda.is_available()					,       '''test requires a GPU'''			)(A			)


def    _snake_case  (	A			)		->       str:
							return unittest.skipUnless(is_xpu_available()					,       '''test requires a XPU'''			)(A			)


def    _snake_case  (	A			)		->       Dict:
							return unittest.skipUnless(is_mps_available()					,       '''test requires a `mps` backend support in `torch`'''			)(A			)


def    _snake_case  (	A			)		->       Tuple:
							return unittest.skipUnless(
							    is_transformers_available() and is_datasets_available()					,       '''test requires the Hugging Face suite'''			)(A			)


def    _snake_case  (	A			)		->       Dict:
							return unittest.skipUnless(is_bnb_available()					,       '''test requires the bitsandbytes library'''			)(A			)


def    _snake_case  (	A			)		->       Optional[Any]:
							return unittest.skipUnless(is_tpu_available()					,       '''test requires TPU'''			)(A			)


def    _snake_case  (	A			)		->       Optional[int]:
							return unittest.skipUnless(torch.cuda.device_count() == 1					,       '''test requires a GPU'''			)(A			)


def    _snake_case  (	A			)		->       List[str]:
							return unittest.skipUnless(torch.xpu.device_count() == 1					,       '''test requires a XPU'''			)(A			)


def    _snake_case  (	A			)		->       List[Any]:
							return unittest.skipUnless(torch.cuda.device_count() > 1					,       '''test requires multiple GPUs'''			)(A			)


def    _snake_case  (	A			)		->       str:
							return unittest.skipUnless(torch.xpu.device_count() > 1					,       '''test requires multiple XPUs'''			)(A			)


def    _snake_case  (	A			)		->       Any:
							return unittest.skipUnless(is_safetensors_available()					,       '''test requires safetensors'''			)(A			)


def    _snake_case  (	A			)		->       Optional[int]:
							return unittest.skipUnless(is_deepspeed_available()					,       '''test requires DeepSpeed'''			)(A			)


def    _snake_case  (	A			)		->       Union[str, Any]:
							return unittest.skipUnless(is_torch_version('''>='''					,       '''1.12.0'''			)					,       '''test requires torch version >= 1.12.0'''			)(A			)


def    _snake_case  (	A=None					,       A=None			)		->       Union[str, Any]:
							if test_case is None:
														return partial(A					,       version=A			)
							return unittest.skipUnless(is_torch_version('''>='''					,       A			)					,       F"""test requires torch version >= {version}"""			)(A			)


def    _snake_case  (	A			)		->       List[str]:
							return unittest.skipUnless(is_tensorboard_available()					,       '''test requires Tensorboard'''			)(A			)


def    _snake_case  (	A			)		->       Optional[int]:
							return unittest.skipUnless(is_wandb_available()					,       '''test requires wandb'''			)(A			)


def    _snake_case  (	A			)		->       Optional[int]:
							return unittest.skipUnless(is_comet_ml_available()					,       '''test requires comet_ml'''			)(A			)


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


def    _snake_case  (	A			)		->       Optional[int]:
							return unittest.skipUnless(
							    _atleast_one_tracker_available					,       '''test requires at least one tracker to be available and for `comet_ml` to not be installed'''					,       )(A			)




class 						a__							(				unittest.TestCase    ):





							'''simple docstring'''






							lowercase__     :  List[Any]      		= True







							@classmethod
							def     __SCREAMING_SNAKE_CASE				(						cls  )			->				str:
														lowerCAmelCase__			  =      tempfile.mkdtemp()







							@classmethod
							def     __SCREAMING_SNAKE_CASE				(						cls  )			->				str:
														if os.path.exists(cls.tmpdir  ):
																					shutil.rmtree(cls.tmpdir  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				str:
														if self.clear_on_setup:
																					for path in Path(self.tmpdir  ).glob('''**/*'''  ):
																												if path.is_file():
																																			path.unlink()
																												elif path.is_dir():
																																			shutil.rmtree(lowerCamelCase_  )




class 						a__							(				unittest.TestCase    ):





							'''simple docstring'''






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




class 						a__							(				unittest.TestCase    ):





							'''simple docstring'''






							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_  )			->				List[Any]:
														lowerCAmelCase__			  =      mocks if isinstance(lowerCamelCase_   ,       (tuple, list)  ) else [mocks]
														for m in self.mocks:
																					m.start()
																					self.addCleanup(m.stop  )


def    _snake_case  (	A			)		->       int:
							lowerCAmelCase__			  =      AcceleratorState()
							lowerCAmelCase__			  =      tensor[None].clone().to(state.device			)
							lowerCAmelCase__			  =      gather(A			).cpu()
							lowerCAmelCase__			  =      tensor[0].cpu()
							for i in range(tensors.shape[0]			):
														if not torch.equal(tensors[i]					,       A			):
																					return False
							return True




class 						a__							:





							'''simple docstring'''






							def __init__(						self   ,       lowerCamelCase_   ,       lowerCamelCase_   ,       lowerCamelCase_  )			->				Tuple:
														lowerCAmelCase__			  =      returncode
														lowerCAmelCase__			  =      stdout
														lowerCAmelCase__			  =      stderr


async def    _snake_case  (	A					,       A			)		->       Union[str, Any]:
							while True:
														lowerCAmelCase__			  =      await stream.readline()
														if line:
																					callback(A			)
														else:
																					break


async def    _snake_case  (	A					,       A=None					,       A=None					,       A=None					,       A=False					,       A=False			)		->       _RunOutput:
							if echo:
														print('''\nRunning: '''					,       ''' '''.join(A			)			)

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

							# 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__			  =      []
							lowerCAmelCase__			  =      []

							def tee(A					,       A					,       A					,       A=""			):
														lowerCAmelCase__			  =      line.decode('''utf-8'''			).rstrip()
														sink.append(A			)
														if not quiet:
																					print(A					,       A					,       file=A			)

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


def    _snake_case  (	A					,       A=None					,       A=None					,       A=180					,       A=False					,       A=True			)		->       _RunOutput:
							lowerCAmelCase__			  =      asyncio.get_event_loop()
							lowerCAmelCase__			  =      loop.run_until_complete(
							    _stream_subprocess(A					,       env=A					,       stdin=A					,       timeout=A					,       quiet=A					,       echo=A			)			)

							lowerCAmelCase__			  =      ''' '''.join(A			)
							if result.returncode > 0:
														lowerCAmelCase__			  =      '''\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__							(				a__    ):





							'''simple docstring'''






							pass


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




"""simple docstring"""







import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


a_							=    logging.get_logger(__name__)


a_							=    """▁"""

a_							=    {"""vocab_file""": """spiece.model"""}

a_							=    {
    """vocab_file""": {
        """google/reformer-crime-and-punishment""": (
            """https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model"""
        )
    }
}

a_							=    {
    """google/reformer-crime-and-punishment""": 52_42_88,
}







class 					A_(SCREAMING_SNAKE_CASE_      ):







			"""simple docstring"""



			a_       :			Optional[int]												=			VOCAB_FILES_NAMES
			a_       :			int												=			PRETRAINED_VOCAB_FILES_MAP
			a_       :			str												=			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			a_       :			Optional[Any]												=			["""input_ids""", """attention_mask"""]
			def __init__(	self				,   A				,   A="</s>"				,   A="<unk>"				,   A=[]				,   A = None				,   **A				,   ):
						_lowerCamelCase					:					Any	       =    {} if sp_model_kwargs is None else sp_model_kwargs

						super().__init__(
						    eos_token=A				,   unk_token=A				,   additional_special_tokens=A				,   sp_model_kwargs=self.sp_model_kwargs				,   **A				,   )

						_lowerCamelCase					:					Dict	       =    vocab_file
						_lowerCamelCase					:					List[Any]	       =    spm.SentencePieceProcessor(**self.sp_model_kwargs							)
						self.sp_model.Load(A							)
			@property
			def    _lowerCAmelCase		(	self							):
						return self.sp_model.get_piece_size()
			def    _lowerCAmelCase		(	self							):
						_lowerCamelCase					:					int	       =    {self.convert_ids_to_tokens(A							): i for i in range(self.vocab_size							)}
						vocab.update(self.added_tokens_encoder							)
						return vocab
			def __getstate__(	self							):
						_lowerCamelCase					:					Optional[int]	       =    self.__dict__.copy()
						_lowerCamelCase					:					Union[str, Any]	       =    None
						return state
			def __setstate__(	self				,   A							):
						_lowerCamelCase					:					int	       =    d

						# for backward compatibility
						if not hasattr(self				,   'sp_model_kwargs'							):
									_lowerCamelCase					:					Union[str, Any]	       =    {}

						_lowerCamelCase					:					Dict	       =    spm.SentencePieceProcessor(**self.sp_model_kwargs							)
						self.sp_model.Load(self.vocab_file							)
			def    _lowerCAmelCase		(	self				,   A							):
						return self.sp_model.encode(A				,   out_type=A							)
			def    _lowerCAmelCase		(	self				,   A							):
						return self.sp_model.piece_to_id(A							)
			def    _lowerCAmelCase		(	self				,   A							):
						if index < self.sp_model.get_piece_size():
									_lowerCamelCase					:					Dict	       =    self.sp_model.IdToPiece(A							)
						return token
			def    _lowerCAmelCase		(	self				,   A							):
						_lowerCamelCase					:					Tuple	       =    []
						_lowerCamelCase					:					Optional[int]	       =    ''
						for token in tokens:
									# make sure that special tokens are not decoded using sentencepiece model
									if token in self.all_special_tokens:
												out_string += self.sp_model.decode(A							) + token
												_lowerCamelCase					:					Dict	       =    []
									else:
												current_sub_tokens.append(A							)
						out_string += self.sp_model.decode(A							)
						return out_string.strip()

			def    _lowerCAmelCase		(	self				,   A				,   A = None							):
						if not os.path.isdir(A							):
									logger.error(F"Vocabulary path ({save_directory}) should be a directory"							)
									return
						_lowerCamelCase					:					Any	       =    os.path.join(
						    A				,   (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']							)

						if os.path.abspath(self.vocab_file							) != os.path.abspath(A							) and os.path.isfile(self.vocab_file							):
									copyfile(self.vocab_file				,   A							)
						elif not os.path.isfile(self.vocab_file							):
									with open(A				,   'wb'							) as fi:
												_lowerCamelCase					:					List[str]	       =    self.sp_model.serialized_model_proto()
												fi.write(A							)

						return (out_vocab_file,)





