
import os
import unittest

from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer

from ...test_tokenization_common import TokenizerTesterMixin







class  UpperCamelCase__		(    SCREAMING_SNAKE_CASE_,			unittest.TestCase   ):







	'''simple docstring'''
	_lowerCAmelCase							       =				TransfoXLTokenizer
	_lowerCAmelCase							       =				False
	_lowerCAmelCase							       =				False





	def   __snake_case				(			self		):
					super().setUp()

					A__  :	List[Any]         =							[
					    '''<unk>''',
					    '''[CLS]''',
					    '''[SEP]''',
					    '''want''',
					    '''unwanted''',
					    '''wa''',
					    '''un''',
					    '''running''',
					    ''',''',
					    '''low''',
					    '''l''',
					]
					A__  :	Optional[int]         =							os.path.join(self.tmpdirname				,       VOCAB_FILES_NAMES['''vocab_file''']		)
					with open(self.vocab_file				,       '''w'''				,       encoding='''utf-8'''		) as vocab_writer:
									vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]		)		)





	def   __snake_case				(			self				,       **UpperCamelCase__		):
					A__  :	List[Any]         =							True
					return TransfoXLTokenizer.from_pretrained(self.tmpdirname				,       **UpperCamelCase__		)





	def   __snake_case				(			self				,       UpperCamelCase__		):
					A__  :	Optional[int]         =							'''<unk> UNwanted , running'''
					A__  :	Optional[Any]         =							'''<unk> unwanted, running'''
					return input_text, output_text





	def   __snake_case				(			self		):
					A__  :	Optional[Any]         =							TransfoXLTokenizer(vocab_file=self.vocab_file				,       lower_case=UpperCamelCase__		)

					A__  :	Union[str, Any]         =							tokenizer.tokenize('''<unk> UNwanted , running'''		)
					self.assertListEqual(UpperCamelCase__				,       ['''<unk>''', '''unwanted''', ''',''', '''running''']		)

					self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__		)				,       [0, 4, 8, 7]		)





	def   __snake_case				(			self		):
					A__  :	int         =							TransfoXLTokenizer(lower_case=UpperCamelCase__		)

					self.assertListEqual(
					    tokenizer.tokenize(''' \tHeLLo ! how  \n Are yoU ?  '''		)				,       ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?''']		)





	def   __snake_case				(			self		):
					A__  :	List[Any]         =							TransfoXLTokenizer(lower_case=UpperCamelCase__		)

					self.assertListEqual(
					    tokenizer.tokenize(''' \tHeLLo ! how  \n Are yoU ?  '''		)				,       ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']		)





	def   __snake_case				(			self		):
					A__  :	Tuple         =							TransfoXLTokenizer(lower_case=UpperCamelCase__		)
					A__  :	List[str]         =							'''Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?'''
					A__  :	str         =							[
					    '''Hello''',
					    '''(''',
					    '''bracket''',
					    ''')''',
					    '''and''',
					    '''side''',
					    '''@-@''',
					    '''scrolled''',
					    '''[''',
					    '''and''',
					    ''']''',
					    '''Henry''',
					    '''\'s''',
					    '''$''',
					    '''5''',
					    '''@,@''',
					    '''000''',
					    '''with''',
					    '''3''',
					    '''@.@''',
					    '''34''',
					    '''m''',
					    '''.''',
					    '''What''',
					    '''\'s''',
					    '''up''',
					    '''!''',
					    '''?''',
					]

					self.assertListEqual(tokenizer.tokenize(UpperCamelCase__		)				,       UpperCamelCase__		)

					self.assertEqual(tokenizer.convert_tokens_to_string(UpperCamelCase__		)				,       UpperCamelCase__		)





	def   __snake_case				(			self		):
					A__  :	str         =							self.get_tokenizer()
					A__  :	int         =							len(UpperCamelCase__		)

					tokenizer.add_tokens(['''new1''', '''new2''']		)
					tokenizer.move_added_token('''new1'''				,       1		)

					# Check that moved token is not copied (duplicate)
					self.assertEqual(len(UpperCamelCase__		)				,       original_len + 2		)
					# Check that token is moved to specified id
					self.assertEqual(tokenizer.encode('''new1'''		)				,       [1]		)
					self.assertEqual(tokenizer.decode([1]		)				,       '''new1'''		)

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 :						Optional[Any]							,						__UpperCamelCase :						int=False       ) ->       Tuple:

				"""simple docstring"""







				try:
								A__  :	Dict         =							os.environ[key]
				except KeyError:
								# KEY isn't set, default to `default`.
								A__  :	Tuple         =							default
				else:
								# KEY is set, convert it to True or False.
								try:
												A__  :	Union[str, 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


_SCREAMING_SNAKE_CASE    :      Union[str, Any]          =			parse_flag_from_env('RUN_SLOW', default=False)

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Optional[Any]       ) ->       Any:

				"""simple docstring"""







				return unittest.skip('''Test was skipped'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Tuple       ) ->       Union[str, Any]:

				"""simple docstring"""







				return unittest.skipUnless(_run_slow_tests							,						'''test is slow'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						str       ) ->       int:

				"""simple docstring"""







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

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Optional[Any]       ) ->       Tuple:

				"""simple docstring"""







				return unittest.skipUnless(torch.cuda.is_available()							,						'''test requires a GPU'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Dict       ) ->       List[str]:

				"""simple docstring"""







				return unittest.skipUnless(is_xpu_available()							,						'''test requires a XPU'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Dict       ) ->       Any:

				"""simple docstring"""







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

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						int       ) ->       Optional[Any]:

				"""simple docstring"""







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

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Tuple       ) ->       Tuple:

				"""simple docstring"""







				return unittest.skipUnless(is_bnb_available()							,						'''test requires the bitsandbytes library'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						List[Any]       ) ->       List[Any]:

				"""simple docstring"""







				return unittest.skipUnless(is_tpu_available()							,						'''test requires TPU'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						int       ) ->       Tuple:

				"""simple docstring"""







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

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						int       ) ->       Dict:

				"""simple docstring"""







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

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Any       ) ->       str:

				"""simple docstring"""







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

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						int       ) ->       Any:

				"""simple docstring"""







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

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						List[Any]       ) ->       int:

				"""simple docstring"""







				return unittest.skipUnless(is_safetensors_available()							,						'''test requires safetensors'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						List[Any]       ) ->       Optional[Any]:

				"""simple docstring"""







				return unittest.skipUnless(is_deepspeed_available()							,						'''test requires DeepSpeed'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Any       ) ->       List[Any]:

				"""simple docstring"""







				return unittest.skipUnless(is_torch_version('''>='''							,						'''1.12.0'''       )							,						'''test requires torch version >= 1.12.0'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Optional[int]=None							,						__UpperCamelCase :						List[Any]=None       ) ->       Optional[Any]:

				"""simple docstring"""







				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 :						Optional[Any]       ) ->       Optional[int]:

				"""simple docstring"""







				return unittest.skipUnless(is_tensorboard_available()							,						'''test requires Tensorboard'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Any       ) ->       Tuple:

				"""simple docstring"""







				return unittest.skipUnless(is_wandb_available()							,						'''test requires wandb'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Tuple       ) ->       Any:

				"""simple docstring"""







				return unittest.skipUnless(is_comet_ml_available()							,						'''test requires comet_ml'''       )(__UpperCamelCase       )


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

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Optional[int]       ) ->       Optional[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'''							,						)(__UpperCamelCase       )







class  UpperCamelCase__		(    unittest.TestCase   ):







	'''simple docstring'''
	_lowerCAmelCase							       =				True





	@classmethod
	def   __snake_case				(			cls		):
					A__  :	Tuple         =							tempfile.mkdtemp()





	@classmethod
	def   __snake_case				(			cls		):
					if os.path.exists(cls.tmpdir		):
									shutil.rmtree(cls.tmpdir		)





	def   __snake_case				(			self		):
					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  UpperCamelCase__		(    unittest.TestCase   ):







	'''simple docstring'''





	def   __snake_case				(			self		):
					super().tearDown()
					# Reset the state of the AcceleratorState singleton.
					AcceleratorState._reset_state()
					PartialState._reset_state()







class  UpperCamelCase__		(    unittest.TestCase   ):







	'''simple docstring'''





	def   __snake_case				(			self				,       UpperCamelCase__		):
					A__  :	Tuple         =							mocks if isinstance(UpperCamelCase__				,       (tuple, list)		) else [mocks]
					for m in self.mocks:
									m.start()
									self.addCleanup(m.stop		)




def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						str       ) ->       Any:

				"""simple docstring"""







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







class  UpperCamelCase__		:







	'''simple docstring'''





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




async def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						str							,						__UpperCamelCase :						Optional[Any]       ) ->       Any:

				"""simple docstring"""







				while True:
								A__  :	Tuple         =							await stream.readline()
								if line:
												callback(__UpperCamelCase       )
								else:
												break

async def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Optional[Any]							,						__UpperCamelCase :						Optional[Any]=None							,						__UpperCamelCase :						List[Any]=None							,						__UpperCamelCase :						Tuple=None							,						__UpperCamelCase :						Tuple=False							,						__UpperCamelCase :						List[Any]=False       ) ->       _RunOutput:

				"""simple docstring"""







				if echo:
								print('''\nRunning: '''							,						''' '''.join(__UpperCamelCase       )       )

				A__  :	int         =							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)

				A__  :	List[Any]         =							[]
				A__  :	str         =							[]

				def tee(__UpperCamelCase :						Optional[Any]							,						__UpperCamelCase :						Union[str, Any]							,						__UpperCamelCase :						Dict							,						__UpperCamelCase :						List[Any]=""       ):
								A__  :	Optional[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 :						List[Any]							,						__UpperCamelCase :						Any=None							,						__UpperCamelCase :						List[Any]=None							,						__UpperCamelCase :						List[str]=1_80							,						__UpperCamelCase :						List[str]=False							,						__UpperCamelCase :						Dict=True       ) ->       _RunOutput:

				"""simple docstring"""







				A__  :	Dict         =							asyncio.get_event_loop()
				A__  :	Optional[Any]         =							loop.run_until_complete(
				    _stream_subprocess(__UpperCamelCase							,						env=__UpperCamelCase							,						stdin=__UpperCamelCase							,						timeout=__UpperCamelCase							,						quiet=__UpperCamelCase							,						echo=__UpperCamelCase       )       )

				A__  :	Union[str, Any]         =							''' '''.join(__UpperCamelCase       )
				if result.returncode > 0:
								A__  :	Optional[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  UpperCamelCase__		(    SCREAMING_SNAKE_CASE_   ):







	'''simple docstring'''
	pass




def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						List[str]							,						__UpperCamelCase :						List[Any]=False       ) ->       Dict:

				"""simple docstring"""







				try:
								A__  :	List[Any]         =							subprocess.check_output(__UpperCamelCase							,						stderr=subprocess.STDOUT       )
								if return_stdout:
												if hasattr(__UpperCamelCase							,						'''decode'''       ):
																A__  :	Any         =							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