





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


lowerCAmelCase       		=      parse_flag_from_env("""RUN_SLOW""", default=False)






def      __A						(							a_						:  int	):
		return unittest.skip("Test was skipped"	)(a_	)






def      __A						(							a_						:  List[str]	):
		return unittest.skipUnless(_run_slow_tests      ,"test is slow"	)(a_	)






def      __A						(							a_						:  Tuple	):
		return unittest.skipUnless(not torch.cuda.is_available()      ,"test requires only a CPU"	)(a_	)






def      __A						(							a_						:  List[str]	):
		return unittest.skipUnless(torch.cuda.is_available()      ,"test requires a GPU"	)(a_	)






def      __A						(							a_						:  Union[str, Any]	):
		return unittest.skipUnless(is_xpu_available()      ,"test requires a XPU"	)(a_	)






def      __A						(							a_						:  Dict	):
		return unittest.skipUnless(is_mps_available()      ,"test requires a `mps` backend support in `torch`"	)(a_	)






def      __A						(							a_						:  Any	):
		return unittest.skipUnless(
		    is_transformers_available() and is_datasets_available()      ,"test requires the Hugging Face suite"	)(a_	)






def      __A						(							a_						:  List[Any]	):
		return unittest.skipUnless(is_bnb_available()      ,"test requires the bitsandbytes library"	)(a_	)






def      __A						(							a_						:  Tuple	):
		return unittest.skipUnless(is_tpu_available()      ,"test requires TPU"	)(a_	)






def      __A						(							a_						:  Dict	):
		return unittest.skipUnless(torch.cuda.device_count() == 1      ,"test requires a GPU"	)(a_	)






def      __A						(							a_						:  Tuple	):
		return unittest.skipUnless(torch.xpu.device_count() == 1      ,"test requires a XPU"	)(a_	)






def      __A						(							a_						:  Optional[int]	):
		return unittest.skipUnless(torch.cuda.device_count() > 1      ,"test requires multiple GPUs"	)(a_	)






def      __A						(							a_						:  str	):
		return unittest.skipUnless(torch.xpu.device_count() > 1      ,"test requires multiple XPUs"	)(a_	)






def      __A						(							a_						:  Any	):
		return unittest.skipUnless(is_safetensors_available()      ,"test requires safetensors"	)(a_	)






def      __A						(							a_						:  List[str]	):
		return unittest.skipUnless(is_deepspeed_available()      ,"test requires DeepSpeed"	)(a_	)






def      __A						(							a_						:  Optional[int]	):
		return unittest.skipUnless(is_torch_version(">="      ,"1.12.0"	)      ,"test requires torch version >= 1.12.0"	)(a_	)






def      __A						(							a_						:  int=None      ,a_						:  Dict=None	):
		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      __A						(							a_						:  Optional[int]	):
		return unittest.skipUnless(is_tensorboard_available()      ,"test requires Tensorboard"	)(a_	)






def      __A						(							a_						:  Optional[int]	):
		return unittest.skipUnless(is_wandb_available()      ,"test requires wandb"	)(a_	)






def      __A						(							a_						:  Optional[int]	):
		return unittest.skipUnless(is_comet_ml_available()      ,"test requires comet_ml"	)(a_	)


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






def      __A						(							a_						:  Optional[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"      ,)(a_	)
class 		lowerCamelCase  (      unittest.TestCase       ):
	snake_case_      =   True



	@classmethod
	def   _lowerCamelCase    (   cls	):
			lowerCAmelCase     :    Tuple						=   tempfile.mkdtemp()



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





	def   _lowerCamelCase    (   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(a_	)






class 		lowerCamelCase  (      unittest.TestCase       ):



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






class 		lowerCamelCase  (      unittest.TestCase       ):



	def   _lowerCamelCase    (   self		,      a_	):
			lowerCAmelCase     :    List[str]						=   mocks if isinstance(a_		,      (tuple, list)	) else [mocks]
			for m in self.mocks:
					m.start()
					self.addCleanup(m.stop	)






def      __A						(							a_						:  int	):
		lowerCAmelCase     :    Optional[Any]						=   AcceleratorState()
		lowerCAmelCase     :    List[str]						=   tensor[None].clone().to(state.device	)
		lowerCAmelCase     :    Optional[Any]						=   gather(a_	).cpu()
		lowerCAmelCase     :    List[Any]						=   tensor[0].cpu()
		for i in range(tensors.shape[0]	):
				if not torch.equal(tensors[i]      ,a_	):
						return False
		return True
class 		lowerCamelCase  :



	def __init__(   self		,      a_		,      a_		,      a_	):
			lowerCAmelCase     :    List[Any]						=   returncode
			lowerCAmelCase     :    int						=   stdout
			lowerCAmelCase     :    Any						=   stderr






async def      __A						(							a_						:  Union[str, Any]      ,a_						:  Union[str, Any]	):
		while True:
				lowerCAmelCase     :    Tuple						=   await stream.readline()
				if line:
						callback(a_	)
				else:
						break






async def      __A						(							a_						:  List[Any]      ,a_						:  Dict=None      ,a_						:  Optional[int]=None      ,a_						:  Optional[Any]=None      ,a_						:  str=False      ,a_						:  List[Any]=False	):
		if echo:
				print("\nRunning: "      ," ".join(a_	)	)

		lowerCAmelCase     :    Union[str, Any]						=   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     :    Tuple						=   []
		lowerCAmelCase     :    Union[str, Any]						=   []

		def tee(a_						:  Any      ,a_						:  List[str]      ,a_						:  Tuple      ,a_						:  Tuple=""	):
				lowerCAmelCase     :    Any						=   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      __A						(							a_						:  List[str]      ,a_						:  Dict=None      ,a_						:  Tuple=None      ,a_						:  Union[str, Any]=1_8_0      ,a_						:  Optional[int]=False      ,a_						:  Union[str, Any]=True	):
		lowerCAmelCase     :    Optional[int]						=   asyncio.get_event_loop()
		lowerCAmelCase     :    int						=   loop.run_until_complete(
		    _stream_subprocess(a_      ,env=a_      ,stdin=a_      ,timeout=a_      ,quiet=a_      ,echo=a_	)	)

		lowerCAmelCase     :    int						=   " ".join(a_	)
		if result.returncode > 0:
				lowerCAmelCase     :    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 		lowerCamelCase  (      _A       ):
	pass






def      __A						(							a_						:  List[str]      ,a_						:  Tuple=False	):
		try:
				lowerCAmelCase     :    str						=   subprocess.check_output(a_      ,stderr=subprocess.STDOUT	)
				if return_stdout:
						if hasattr(a_      ,"decode"	):
								lowerCAmelCase     :    Tuple						=   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 AddedToken, PreTrainedTokenizer
from ...utils import logging


lowerCAmelCase       		=      logging.get_logger(__name__)

lowerCAmelCase       		=      """▁"""

lowerCAmelCase       		=      {"""vocab_file""": """sentencepiece.bpe.model"""}

lowerCAmelCase       		=      {
    """vocab_file""": {
        """xlm-roberta-base""": """https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model""",
        """xlm-roberta-large""": """https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model""",
        """xlm-roberta-large-finetuned-conll02-dutch""": (
            """https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model"""
        ),
        """xlm-roberta-large-finetuned-conll02-spanish""": (
            """https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model"""
        ),
        """xlm-roberta-large-finetuned-conll03-english""": (
            """https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model"""
        ),
        """xlm-roberta-large-finetuned-conll03-german""": (
            """https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model"""
        ),
    }
}

lowerCAmelCase       		=      {
    """xlm-roberta-base""": 5_12,
    """xlm-roberta-large""": 5_12,
    """xlm-roberta-large-finetuned-conll02-dutch""": 5_12,
    """xlm-roberta-large-finetuned-conll02-spanish""": 5_12,
    """xlm-roberta-large-finetuned-conll03-english""": 5_12,
    """xlm-roberta-large-finetuned-conll03-german""": 5_12,
}
class 		lowerCamelCase  (      _A       ):
	snake_case_      =   VOCAB_FILES_NAMES
	snake_case_      =   PRETRAINED_VOCAB_FILES_MAP
	snake_case_      =   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	snake_case_      =   ["input_ids", "attention_mask"]



	def __init__(   self		,      a_		,      a_="<s>"		,      a_="</s>"		,      a_="</s>"		,      a_="<s>"		,      a_="<unk>"		,      a_="<pad>"		,      a_="<mask>"		,      a_ = None		,      **a_		,      ):
			# Mask token behave like a normal word, i.e. include the space before it
			lowerCAmelCase     :    str						=   AddedToken(a_		,      lstrip=a_		,      rstrip=a_	) if isinstance(a_		,      a_	) else mask_token

			lowerCAmelCase     :    Tuple						=   {} if sp_model_kwargs is None else sp_model_kwargs

			super().__init__(
			    bos_token=a_		,      eos_token=a_		,      unk_token=a_		,      sep_token=a_		,      cls_token=a_		,      pad_token=a_		,      mask_token=a_		,      sp_model_kwargs=self.sp_model_kwargs		,      **a_		,      )

			lowerCAmelCase     :    Optional[int]						=   spm.SentencePieceProcessor(**self.sp_model_kwargs	)
			self.sp_model.Load(str(a_	)	)
			lowerCAmelCase     :    int						=   vocab_file

			# Original fairseq vocab and spm vocab must be "aligned":
			# Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
			# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
			# fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
			# spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

			# Mimic fairseq token-to-id alignment for the first 4 token
			lowerCAmelCase     :    Any						=   {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}

			# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
			lowerCAmelCase     :    Dict						=   1

			lowerCAmelCase     :    Optional[Any]						=   len(self.sp_model	) + self.fairseq_offset
			lowerCAmelCase     :    List[Any]						=   {v: k for k, v in self.fairseq_tokens_to_ids.items()}



	def __getstate__(   self	):
			lowerCAmelCase     :    Any						=   self.__dict__.copy()
			lowerCAmelCase     :    Optional[int]						=   None
			lowerCAmelCase     :    List[str]						=   self.sp_model.serialized_model_proto()
			return state



	def __setstate__(   self		,      a_	):
			lowerCAmelCase     :    Any						=   d

			# for backward compatibility
			if not hasattr(self		,      "sp_model_kwargs"	):
					lowerCAmelCase     :    Any						=   {}

			lowerCAmelCase     :    Optional[Any]						=   spm.SentencePieceProcessor(**self.sp_model_kwargs	)
			self.sp_model.LoadFromSerializedProto(self.sp_model_proto	)



	def   _lowerCamelCase    (   self		,      a_		,      a_ = None	):

			if token_ids_a is None:
					return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
			lowerCAmelCase     :    Optional[Any]						=   [self.cls_token_id]
			lowerCAmelCase     :    List[Any]						=   [self.sep_token_id]
			return cls + token_ids_a + sep + sep + token_ids_a + sep



	def   _lowerCamelCase    (   self		,      a_		,      a_ = None		,      a_ = False	):

			if already_has_special_tokens:
					return super().get_special_tokens_mask(
					    token_ids_a=a_		,      token_ids_a=a_		,      already_has_special_tokens=a_	)

			if token_ids_a is None:
					return [1] + ([0] * len(a_	)) + [1]
			return [1] + ([0] * len(a_	)) + [1, 1] + ([0] * len(a_	)) + [1]



	def   _lowerCamelCase    (   self		,      a_		,      a_ = None	):
			lowerCAmelCase     :    Dict						=   [self.sep_token_id]
			lowerCAmelCase     :    List[Any]						=   [self.cls_token_id]

			if token_ids_a is None:
					return len(cls + token_ids_a + sep	) * [0]
			return len(cls + token_ids_a + sep + sep + token_ids_a + sep	) * [0]



	@property
	def   _lowerCamelCase    (   self	):
			return len(self.sp_model	) + self.fairseq_offset + 1  # Add the <mask> token



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    Dict						=   {self.convert_ids_to_tokens(a_	): i for i in range(self.vocab_size	)}
			vocab.update(self.added_tokens_encoder	)
			return vocab



	def   _lowerCamelCase    (   self		,      a_	):
			return self.sp_model.encode(a_		,      out_type=a_	)



	def   _lowerCamelCase    (   self		,      a_	):
			if token in self.fairseq_tokens_to_ids:
					return self.fairseq_tokens_to_ids[token]
			lowerCAmelCase     :    int						=   self.sp_model.PieceToId(a_	)

			# Need to return unknown token if the SP model returned 0
			return spm_id + self.fairseq_offset if spm_id else self.unk_token_id



	def   _lowerCamelCase    (   self		,      a_	):
			if index in self.fairseq_ids_to_tokens:
					return self.fairseq_ids_to_tokens[index]
			return self.sp_model.IdToPiece(index - self.fairseq_offset	)



	def   _lowerCamelCase    (   self		,      a_	):
			lowerCAmelCase     :    Dict						=   "".join(a_	).replace(a_		,      " "	).strip()
			return out_string





	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     :    int						=   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     :    Dict						=   self.sp_model.serialized_model_proto()
							fi.write(a_	)

			return (out_vocab_file,)



