





import pickle
import shutil
import tempfile
import unittest

from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin


_UpperCAmelCase        =				get_tests_dir('fixtures/test_sentencepiece.model')



@require_sentencepiece
@require_tokenizers
class 							_UpperCamelCase					(	lowerCAmelCase_  ,						unittest.TestCase     ):
       _UpperCamelCase				:					str         =   XGLMTokenizer
       _UpperCamelCase				:					Tuple         =   XGLMTokenizerFast
       _UpperCamelCase				:					Tuple         =   True
       _UpperCamelCase				:					Optional[int]         =   True

       def lowercase (		self: List[Any]		)       -> Dict:




              """simple docstring"""


              super().setUp()

              # We have a SentencePiece fixture for testing
              UpperCamelCase_          =  XGLMTokenizer(_SCREAMING_SNAKE_CASE					,   keep_accents=_SCREAMING_SNAKE_CASE		)
              tokenizer.save_pretrained(self.tmpdirname		)

       def lowercase (		self: Dict		)       -> Tuple:




              """simple docstring"""


              UpperCamelCase_          =  "<pad>"
              UpperCamelCase_          =  1

              self.assertEqual(self.get_tokenizer()._convert_token_to_id(_SCREAMING_SNAKE_CASE		)					,   _SCREAMING_SNAKE_CASE		)
              self.assertEqual(self.get_tokenizer()._convert_id_to_token(_SCREAMING_SNAKE_CASE		)					,   _SCREAMING_SNAKE_CASE		)

       def lowercase (		self: str		)       -> str:




              """simple docstring"""


              UpperCamelCase_          =  list(self.get_tokenizer().get_vocab().keys()		)

              self.assertEqual(vocab_keys[0]					,   "<s>"		)
              self.assertEqual(vocab_keys[1]					,   "<pad>"		)
              self.assertEqual(len(_SCREAMING_SNAKE_CASE		)					,   1008		)

       def lowercase (		self: Tuple		)       -> Optional[int]:




              """simple docstring"""


              self.assertEqual(self.get_tokenizer().vocab_size					,   1008		)

       def lowercase (		self: List[Any]		)       -> Dict:




              """simple docstring"""


              UpperCamelCase_          =  XGLMTokenizer(_SCREAMING_SNAKE_CASE					,   keep_accents=_SCREAMING_SNAKE_CASE		)

              UpperCamelCase_          =  tokenizer.tokenize("This is a test"		)
              self.assertListEqual(_SCREAMING_SNAKE_CASE					,   ["▁This", "▁is", "▁a", "▁t", "est"]		)

              self.assertListEqual(
                  tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE		)					,   [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]]					,   )

              UpperCamelCase_          =  tokenizer.tokenize("I was born in 92000, and this is falsé."		)
              self.assertListEqual(
                  _SCREAMING_SNAKE_CASE					,   [
                      SPIECE_UNDERLINE + "I",
                      SPIECE_UNDERLINE + "was",
                      SPIECE_UNDERLINE + "b",
                      "or",
                      "n",
                      SPIECE_UNDERLINE + "in",
                      SPIECE_UNDERLINE + "",
                      "9",
                      "2",
                      "0",
                      "0",
                      "0",
                      ",",
                      SPIECE_UNDERLINE + "and",
                      SPIECE_UNDERLINE + "this",
                      SPIECE_UNDERLINE + "is",
                      SPIECE_UNDERLINE + "f",
                      "al",
                      "s",
                      "é",
                      ".",
                  ]					,   )
              UpperCamelCase_          =  tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE		)
              self.assertListEqual(
                  _SCREAMING_SNAKE_CASE					,   [
                      value + tokenizer.fairseq_offset
                      for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
                  ]					,   )

              UpperCamelCase_          =  tokenizer.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE		)
              self.assertListEqual(
                  _SCREAMING_SNAKE_CASE					,   [
                      SPIECE_UNDERLINE + "I",
                      SPIECE_UNDERLINE + "was",
                      SPIECE_UNDERLINE + "b",
                      "or",
                      "n",
                      SPIECE_UNDERLINE + "in",
                      SPIECE_UNDERLINE + "",
                      "<unk>",
                      "2",
                      "0",
                      "0",
                      "0",
                      ",",
                      SPIECE_UNDERLINE + "and",
                      SPIECE_UNDERLINE + "this",
                      SPIECE_UNDERLINE + "is",
                      SPIECE_UNDERLINE + "f",
                      "al",
                      "s",
                      "<unk>",
                      ".",
                  ]					,   )

       @cached_property
       def lowercase (		self: List[Any]		)       -> List[str]:




              """simple docstring"""


              return XGLMTokenizer.from_pretrained("facebook/xglm-564M"		)

       def lowercase (		self: List[Any]		)       -> Optional[int]:




              """simple docstring"""


              with tempfile.NamedTemporaryFile() as f:
                     shutil.copyfile(_SCREAMING_SNAKE_CASE					,   f.name		)
                     UpperCamelCase_          =  XGLMTokenizer(f.name					,   keep_accents=_SCREAMING_SNAKE_CASE		)
                     UpperCamelCase_          =  pickle.dumps(_SCREAMING_SNAKE_CASE		)
              pickle.loads(_SCREAMING_SNAKE_CASE		)

       def lowercase (		self: List[str]		)       -> Optional[int]:




              """simple docstring"""


              if not self.test_rust_tokenizer:
                     return

              UpperCamelCase_          =  self.get_tokenizer()
              UpperCamelCase_          =  self.get_rust_tokenizer()

              UpperCamelCase_          =  "I was born in 92000, and this is falsé."

              UpperCamelCase_          =  tokenizer.tokenize(_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  rust_tokenizer.tokenize(_SCREAMING_SNAKE_CASE		)
              self.assertListEqual(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		)

              UpperCamelCase_          =  tokenizer.encode(_SCREAMING_SNAKE_CASE					,   add_special_tokens=_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  rust_tokenizer.encode(_SCREAMING_SNAKE_CASE					,   add_special_tokens=_SCREAMING_SNAKE_CASE		)
              self.assertListEqual(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		)

              UpperCamelCase_          =  self.get_rust_tokenizer()
              UpperCamelCase_          =  tokenizer.encode(_SCREAMING_SNAKE_CASE		)
              UpperCamelCase_          =  rust_tokenizer.encode(_SCREAMING_SNAKE_CASE		)
              self.assertListEqual(_SCREAMING_SNAKE_CASE					,   _SCREAMING_SNAKE_CASE		)

       @slow
       def lowercase (		self: Any		)       -> str:




              """simple docstring"""


              UpperCamelCase_          =  "Hello World!"
              UpperCamelCase_          =  [2, 31227, 4447, 35]

              self.assertListEqual(_SCREAMING_SNAKE_CASE					,   self.big_tokenizer.encode(_SCREAMING_SNAKE_CASE		)		)

       @slow
       def lowercase (		self: Tuple		)       -> Optional[int]:




              """simple docstring"""


              UpperCamelCase_          =  (
                  "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will"
                  " add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth"
              )
              # fmt: off
              UpperCamelCase_          =  [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735]
              # fmt: on

              self.assertListEqual(_SCREAMING_SNAKE_CASE					,   self.big_tokenizer.encode(_SCREAMING_SNAKE_CASE		)		)



       @slow
       def lowercase (		self: Optional[Any]		)       -> List[str]:




              """simple docstring"""


              UpperCamelCase_          =  {
                  "input_ids": [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]],
                  "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
              }  # noqa: E501
              # fmt: on

              self.tokenizer_integration_test_util(
                  expected_encoding=_SCREAMING_SNAKE_CASE					,   model_name="facebook/xglm-564M"					,   padding=_SCREAMING_SNAKE_CASE					,   )








import os
import sys
import tempfile

import torch

from .state import AcceleratorState
from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment




def  lowerCAmelCase_ (							UpperCamelCase_					,		UpperCamelCase_=()					,		UpperCamelCase_=None					,		UpperCamelCase_="no"					,		UpperCamelCase_="29500"  )     ->		Optional[Any]:
       UpperCamelCase_          =  False
       UpperCamelCase_          =  False
       if any(key.startswith("KAGGLE"  ) for key in os.environ.keys()  ):
              UpperCamelCase_          =  True
       elif "IPython" in sys.modules:
              UpperCamelCase_          =  "google.colab" in str(sys.modules["IPython"].get_ipython()  )

       try:
              UpperCamelCase_          =  PrecisionType(mixed_precision.lower()  )
       except ValueError:
              raise ValueError(
                  F'''Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.'''  )

       if (in_colab or in_kaggle) and (os.environ.get("TPU_NAME"					,		UpperCamelCase_  ) is not None):
              # TPU launch
              import torch_xla.distributed.xla_multiprocessing as xmp

              if len(AcceleratorState._shared_state  ) > 0:
                     raise ValueError(
                         "To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside "
                         "your training function. Restart your notebook and make sure no cells initializes an "
                         "`Accelerator`."  )
              if num_processes is None:
                     UpperCamelCase_          =  8

              UpperCamelCase_          =  PrepareForLaunch(UpperCamelCase_					,		distributed_type="TPU"  )
              print(F'''Launching a training on {num_processes} TPU cores.'''  )
              xmp.spawn(UpperCamelCase_					,		args=UpperCamelCase_					,		nprocs=UpperCamelCase_					,		start_method="fork"  )
       elif in_colab:
              # No need for a distributed launch otherwise as it's either CPU or one GPU.
              if torch.cuda.is_available():
                     print("Launching training on one GPU."  )
              else:
                     print("Launching training on one CPU."  )
              function(*UpperCamelCase_  )
       else:
              if num_processes is None:
                     raise ValueError(
                         "You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call."  )

              if num_processes > 1:
                     # Multi-GPU launch
                     from torch.multiprocessing import start_processes
                     from torch.multiprocessing.spawn import ProcessRaisedException

                     if len(AcceleratorState._shared_state  ) > 0:
                            raise ValueError(
                                "To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized "
                                "inside your training function. Restart your notebook and make sure no cells initializes an "
                                "`Accelerator`."  )

                     if torch.cuda.is_initialized():
                            raise ValueError(
                                "To launch a multi-GPU training from your notebook, you need to avoid running any instruction "
                                "using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA "
                                "function."  )

                     # torch.distributed will expect a few environment variable to be here. We set the ones common to each
                     # process here (the other ones will be set be the launcher).
                     with patch_environment(
                         world_size=UpperCamelCase_					,		master_addr="127.0.01"					,		master_port=UpperCamelCase_					,		mixed_precision=UpperCamelCase_  ):
                            UpperCamelCase_          =  PrepareForLaunch(UpperCamelCase_					,		distributed_type="MULTI_GPU"  )
                            print(F'''Launching training on {num_processes} GPUs.'''  )
                            try:
                                   start_processes(UpperCamelCase_					,		args=UpperCamelCase_					,		nprocs=UpperCamelCase_					,		start_method="fork"  )
                            except ProcessRaisedException as e:
                                   if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
                                          raise RuntimeError(
                                              "CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. "
                                              "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. "
                                              "Please review your imports and test them when running the `notebook_launcher()` to identify "
                                              "which one is problematic."  ) from e

              else:
                     # No need for a distributed launch otherwise as it's either CPU, GPU or MPS.
                     if is_mps_available():
                            UpperCamelCase_          =  "1"
                            print("Launching training on MPS."  )
                     elif torch.cuda.is_available():
                            print("Launching training on one GPU."  )
                     else:
                            print("Launching training on CPU."  )
                     function(*UpperCamelCase_  )







def  lowerCAmelCase_ (							UpperCamelCase_					,		UpperCamelCase_=()					,		UpperCamelCase_=2  )     ->		Optional[Any]:
       from torch.multiprocessing import start_processes

       with tempfile.NamedTemporaryFile() as tmp_file:
              # torch.distributed will expect a few environment variable to be here. We set the ones common to each
              # process here (the other ones will be set be the launcher).
              with patch_environment(
                  world_size=UpperCamelCase_					,		master_addr="127.0.01"					,		master_port="29500"					,		accelerate_mixed_precision="no"					,		accelerate_debug_rdv_file=tmp_file.name					,		accelerate_use_cpu="yes"					,		):
                     UpperCamelCase_          =  PrepareForLaunch(UpperCamelCase_					,		debug=UpperCamelCase_  )
                     start_processes(UpperCamelCase_					,		args=UpperCamelCase_					,		nprocs=UpperCamelCase_					,		start_method="fork"  )

