




'''simple docstring'''
import concurrent.futures
import json
import os
import shutil
import tempfile
import unittest

from transformers import AutoTokenizer, PreTrainedTokenizerFast
from transformers.testing_utils import require_tokenizers

from ..test_tokenization_common import TokenizerTesterMixin






@require_tokenizers
class 	SCREAMING_SNAKE_CASE(    A__       ,				unittest.TestCase					):
							snake_case_			:					Optional[int]   = PreTrainedTokenizerFast
							snake_case_			:					Optional[Any]   = False
							snake_case_			:					List[str]   = True
							snake_case_			:					str   = """tokenizer_file"""

							def    snake_case__      (   self					)   -> int:

											"""simple docstring"""



											__lowercase          =						False  # because we don't have pretrained_vocab_files_map
											super().setUp()
											__lowercase          =						True

											__lowercase          =						['''robot-test/dummy-tokenizer-fast''', '''robot-test/dummy-tokenizer-wordlevel''']
											__lowercase          =						'''SaulLu/dummy-tokenizer-bytelevel-bpe'''

											# Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment)
											__lowercase          =						[(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths]

											__lowercase          =						PreTrainedTokenizerFast.from_pretrained(model_paths[0]					)
											tokenizer.save_pretrained(self.tmpdirname					)

							def    snake_case__      (   self					)   -> List[Any]:

											"""simple docstring"""



											pass

							def    snake_case__      (   self					)   -> Tuple:

											"""simple docstring"""



											pass

							def    snake_case__      (   self					)   -> str:

											"""simple docstring"""



											pass

							def    snake_case__      (   self					)   -> Dict:

											"""simple docstring"""



											pass

							def    snake_case__      (   self					)   -> Tuple:

											"""simple docstring"""



											__lowercase          =						self.tmpdirname
											# Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
											for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
															with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'					):
																			try:
																							__lowercase          =						tempfile.mkdtemp()
																							__lowercase          =						self.rust_tokenizer_class.from_pretrained(__snake_case ,		**__snake_case					)

																							tokenizer.save_pretrained(self.tmpdirname					)
																							super().test_training_new_tokenizer()
																			finally:
																							# Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
																							# is restored
																							shutil.rmtree(self.tmpdirname					)
																							__lowercase          =						tmpdirname_orig

							def    snake_case__      (   self					)   -> List[Any]:

											"""simple docstring"""



											__lowercase          =						self.tmpdirname
											# Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
											for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
															with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'					):
																			try:
																							__lowercase          =						tempfile.mkdtemp()
																							__lowercase          =						self.rust_tokenizer_class.from_pretrained(__snake_case ,		**__snake_case					)

																							tokenizer.save_pretrained(self.tmpdirname					)
																							super().test_training_new_tokenizer_with_special_tokens_change()
																			finally:
																							# Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
																							# is restored
																							shutil.rmtree(self.tmpdirname					)
																							__lowercase          =						tmpdirname_orig




							def    snake_case__      (   self					)   -> Union[str, Any]:

											"""simple docstring"""



											__lowercase          =						self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name					)

											__lowercase          =						('''a''' for _ in range(1000					))
											__lowercase          =						tokenizer.train_new_from_iterator(text_iterator=__snake_case ,		length=1000 ,		vocab_size=50					)

											__lowercase          =						new_tokenizer.encode("""a🤗"""					)
											self.assertEqual(__snake_case ,		[64, 172, 253, 97, 245]					)






@require_tokenizers
class 	SCREAMING_SNAKE_CASE(    unittest.TestCase					):

							def    snake_case__      (   self					)   -> int:

											"""simple docstring"""



											__lowercase          =						AutoTokenizer.from_pretrained("""bert-base-cased"""					)
											__lowercase          =						json.loads(tokenizer._tokenizer.to_str()					)
											__lowercase          =						len(__snake_case					)

											with tempfile.TemporaryDirectory() as tmp_dir:
															# Hack to save this in the tokenizer_config.json
															__lowercase          =						['''tokenizer.4.0.0.json''']
															tokenizer.save_pretrained(__snake_case					)
															json.dump(__snake_case ,		open(os.path.join(__snake_case ,		"""tokenizer.4.0.0.json"""					) ,		"""w"""					)					)

															# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
															__lowercase          =						AutoTokenizer.from_pretrained(__snake_case					)
															self.assertEqual(len(__snake_case					) ,		len(__snake_case					) + 1					)
															__lowercase          =						json.loads(new_tokenizer._tokenizer.to_str()					)
															self.assertIn("""huggingface""" ,		json_tokenizer["""model"""]["""vocab"""]					)

															# Will need to be adjusted if we reach v42 and this test is still here.
															# Should pick the old tokenizer file as the version of Transformers is < 4.0.0
															shutil.move(os.path.join(__snake_case ,		"""tokenizer.4.0.0.json"""					) ,		os.path.join(__snake_case ,		"""tokenizer.42.0.0.json"""					)					)
															__lowercase          =						['''tokenizer.42.0.0.json''']
															tokenizer.save_pretrained(__snake_case					)
															__lowercase          =						AutoTokenizer.from_pretrained(__snake_case					)
															self.assertEqual(len(__snake_case					) ,		len(__snake_case					)					)
															__lowercase          =						json.loads(new_tokenizer._tokenizer.to_str()					)
															self.assertNotIn("""huggingface""" ,		json_tokenizer["""model"""]["""vocab"""]					)




							def    snake_case__      (   self					)   -> Tuple:

											"""simple docstring"""



											__lowercase          =						'''hf-internal-testing/test-two-tokenizers'''

											# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
											__lowercase          =						AutoTokenizer.from_pretrained(__snake_case					)
											self.assertEqual(len(__snake_case					) ,		2_8997					)
											__lowercase          =						json.loads(tokenizer._tokenizer.to_str()					)
											self.assertIn("""huggingface""" ,		json_tokenizer["""model"""]["""vocab"""]					)

											# Testing an older version by monkey-patching the version in the module it's used.
											import transformers as old_transformers

											__lowercase          =						'''3.0.0'''
											__lowercase          =						old_transformers.models.auto.AutoTokenizer.from_pretrained(__snake_case					)
											self.assertEqual(len(__snake_case					) ,		2_8996					)
											__lowercase          =						json.loads(old_tokenizer._tokenizer.to_str()					)
											self.assertNotIn("""huggingface""" ,		json_tokenizer["""model"""]["""vocab"""]					)






@require_tokenizers
class 	SCREAMING_SNAKE_CASE(    unittest.TestCase					):

							def    snake_case__      (   self					)   -> List[Any]:

											"""simple docstring"""



											__lowercase          =						PreTrainedTokenizerFast.from_pretrained("""robot-test/dummy-tokenizer-wordlevel"""					)
											__lowercase          =						'''The Matrix is a 1999 science fiction action film.'''

											with concurrent.futures.ThreadPoolExecutor() as executor:
															__lowercase          =						[executor.submit(self.fetch ,		__snake_case ,		__snake_case					) for i in range(10					)]
															__lowercase          =						[future.result() for future in futures]
															self.assertEqual(__snake_case ,		[[1, 10, 0, 8, 0, 18, 0, 0, 0, 2] for i in range(10					)]					)




							def    snake_case__      (   self ,		lowerCamelCase__ ,		lowerCamelCase__					)   -> Optional[int]:

											"""simple docstring"""



											return tokenizer.encode(__snake_case ,		truncation="""longest_first""" ,		padding="""longest"""					)










'''simple docstring'''
import random
from typing import List, Optional, Union

import numpy as np
import torch

from ..state import AcceleratorState
from .constants import CUDA_DISTRIBUTED_TYPES
from .dataclasses import DistributedType, RNGType
from .imports import is_npu_available, is_tpu_available, is_xpu_available


if is_tpu_available(check_device=False):
  import torch_xla.core.xla_model as xm
def     snake_case_  (       a__		:     int   ,a__		:     bool = False      ):



    """simple docstring"""




    if device_specific:
        seed += AcceleratorState().process_index
    random.seed(a__      )
    np.random.seed(a__      )
    torch.manual_seed(a__      )
    if is_xpu_available():
        torch.xpu.manual_seed_all(a__      )
    elif is_npu_available():
        torch.npu.manual_seed_all(a__      )
    else:
        torch.cuda.manual_seed_all(a__      )
    # ^^ safe to call this function even if cuda is not available
    if is_tpu_available():
        xm.set_rng_state(a__      )
def     snake_case_  (       a__		:     Optional[RNGType] = None   ,a__		:     Optional[torch.Generator] = None      ):



    """simple docstring"""




    if rng_type == RNGType.TORCH:
        __lowercase          =						torch.get_rng_state()
    elif rng_type == RNGType.CUDA:
        __lowercase          =						torch.cuda.get_rng_state()
    elif rng_type == RNGType.XLA:
        assert is_tpu_available(), "Can't synchronize XLA seeds on an environment without TPUs."
        __lowercase          =						torch.tensor(xm.get_rng_state()      )
    elif rng_type == RNGType.NPU:
        assert is_npu_available(), "Can't synchronize NPU seeds on an environment without NPUs."
        __lowercase          =						torch.npu.get_rng_state()
    elif rng_type == RNGType.XPU:
        assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs."
        __lowercase          =						torch.xpu.get_rng_state()
    elif rng_type == RNGType.GENERATOR:
        assert generator is not None, "Need a generator to synchronize its seed."
        __lowercase          =						generator.get_state()

    # Broadcast the rng state from device 0 to other devices
    __lowercase          =						AcceleratorState()
    if state.distributed_type == DistributedType.TPU:
        __lowercase          =						rng_state.to(xm.xla_device()      )
        xm.collective_broadcast([rng_state]      )
        xm.mark_step()
        __lowercase          =						rng_state.cpu()
    elif (
        state.distributed_type in CUDA_DISTRIBUTED_TYPES
        or state.distributed_type == DistributedType.MULTI_NPU
        or state.distributed_type == DistributedType.MULTI_XPU
    ):
        __lowercase          =						rng_state.to(state.device      )
        torch.distributed.broadcast(a__   ,0      )
        __lowercase          =						rng_state.cpu()
    elif state.distributed_type == DistributedType.MULTI_CPU:
        torch.distributed.broadcast(a__   ,0      )

    # Set the broadcast rng state
    if rng_type == RNGType.TORCH:
        torch.set_rng_state(a__      )
    elif rng_type == RNGType.CUDA:
        torch.cuda.set_rng_state(a__      )
    elif rng_type == RNGType.NPU:
        torch.npu.set_rng_state(a__      )
    elif rng_type == RNGType.XPU:
        torch.xpu.set_rng_state(a__      )
    elif rng_type == RNGType.XLA:
        xm.set_rng_state(rng_state.item()      )
    elif rng_type == RNGType.GENERATOR:
        generator.set_state(a__      )



def     snake_case_  (       a__		:     List[Union[str, RNGType]]   ,a__		:     Optional[torch.Generator] = None      ):



    """simple docstring"""




    for rng_type in rng_types:
        synchronize_rng_state(RNGType(a__      )   ,generator=a__      )




