
import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError

from transformers import (
    AlbertTokenizer,
    AutoTokenizer,
    BertTokenizer,
    BertTokenizerFast,
    GPTaTokenizerFast,
    is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie


sys.path.append(str(Path(__file__).parent.parent / "utils"))

from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
 from test_module.custom_tokenization_fast import CustomTokenizerFast


class 						__lowerCAmelCase	(	unittest.TestCase      ):



      """simple docstring"""







      def 		snake_case_			(      self		:       Optional[Any]				):
          # A mock response for an HTTP head request to emulate server down
          __lowercase		:			Optional[Any]	    =       mock.Mock()
          __lowercase		:			List[str]	    =       500
          __lowercase		:			Dict	    =       {}
          __lowercase		:			List[str]	    =       HTTPError
          __lowercase		:			List[Any]	    =       {}

          # Download this model to make sure it's in the cache.
          __lowercase		:			List[Any]	    =       BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert'''				)

          # Under the mock environment we get a 500 error when trying to reach the tokenizer.
          with mock.patch('''requests.Session.request'''				,       return_value=_snake_case				) as mock_head:
              __lowercase		:			List[Any]	    =       BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert'''				)
              # This check we did call the fake head request
              mock_head.assert_called()




      @require_tokenizers
      def 		snake_case_			(      self		:       int				):
          # A mock response for an HTTP head request to emulate server down
          __lowercase		:			int	    =       mock.Mock()
          __lowercase		:			int	    =       500
          __lowercase		:			List[Any]	    =       {}
          __lowercase		:			str	    =       HTTPError
          __lowercase		:			Tuple	    =       {}

          # Download this model to make sure it's in the cache.
          __lowercase		:			Optional[int]	    =       GPTaTokenizerFast.from_pretrained('''gpt2'''				)

          # Under the mock environment we get a 500 error when trying to reach the tokenizer.
          with mock.patch('''requests.Session.request'''				,       return_value=_snake_case				) as mock_head:
              __lowercase		:			List[str]	    =       GPTaTokenizerFast.from_pretrained('''gpt2'''				)
              # This check we did call the fake head request
              mock_head.assert_called()




      def 		snake_case_			(      self		:       Optional[Any]				):
          # This test is for deprecated behavior and can be removed in v5
          try:
              __lowercase		:			str	    =       tempfile.mktemp()
              with open(_snake_case				,       '''wb'''				) as f:
                  http_get('''https://huggingface.co/albert-base-v1/resolve/main/spiece.model'''				,       _snake_case				)

              __lowercase		:			List[Any]	    =       AlbertTokenizer.from_pretrained(_snake_case				)
          finally:
              os.remove(_snake_case				)

          # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
          # the current folder and have the right name.
          if os.path.isfile('''tokenizer.json'''				):
              # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
              return
          try:
              with open('''tokenizer.json'''				,       '''wb'''				) as f:
                  http_get('''https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json'''				,       _snake_case				)
              __lowercase		:			Tuple	    =       AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''				)
              # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
              self.assertEqual(tokenizer.vocab_size				,       1000				)
              # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.

          finally:
              os.remove('''tokenizer.json'''				)




      def 		snake_case_			(      self		:       Optional[Any]				):
          # This test is for deprecated behavior and can be removed in v5
          __lowercase		:			Dict	    =       AlbertTokenizer.from_pretrained('''https://huggingface.co/albert-base-v1/resolve/main/spiece.model'''				)






@is_staging_test
class 						__lowerCAmelCase	(	unittest.TestCase      ):



      """simple docstring"""







      A__	:			Optional[Any]        =    ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou''']




      @classmethod
      def 		snake_case_			(      cls		:       Union[str, Any]				):
          __lowercase		:			int	    =       TOKEN
          HfFolder.save_token(_snake_case				)




      @classmethod
      def 		snake_case_			(      cls		:       Optional[int]				):
          try:
              delete_repo(token=cls._token				,       repo_id='''test-tokenizer'''				)
          except HTTPError:
              pass

          try:
              delete_repo(token=cls._token				,       repo_id='''valid_org/test-tokenizer-org'''				)
          except HTTPError:
              pass

          try:
              delete_repo(token=cls._token				,       repo_id='''test-dynamic-tokenizer'''				)
          except HTTPError:
              pass




      def 		snake_case_			(      self		:       Any				):
          with tempfile.TemporaryDirectory() as tmp_dir:
              __lowercase		:			Dict	    =       os.path.join(_snake_case				,       '''vocab.txt'''				)
              with open(_snake_case				,       '''w'''				,       encoding='''utf-8'''				) as vocab_writer:
                  vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens]				)				)
              __lowercase		:			Tuple	    =       BertTokenizer(_snake_case				)

          tokenizer.push_to_hub('''test-tokenizer'''				,       use_auth_token=self._token				)
          __lowercase		:			Tuple	    =       BertTokenizer.from_pretrained(F'{USER}/test-tokenizer'				)
          self.assertDictEqual(new_tokenizer.vocab				,       tokenizer.vocab				)

          # Reset repo
          delete_repo(token=self._token				,       repo_id='''test-tokenizer'''				)

          # Push to hub via save_pretrained
          with tempfile.TemporaryDirectory() as tmp_dir:
              tokenizer.save_pretrained(_snake_case				,       repo_id='''test-tokenizer'''				,       push_to_hub=_snake_case				,       use_auth_token=self._token				)

          __lowercase		:			str	    =       BertTokenizer.from_pretrained(F'{USER}/test-tokenizer'				)
          self.assertDictEqual(new_tokenizer.vocab				,       tokenizer.vocab				)




      def 		snake_case_			(      self		:       Tuple				):
          with tempfile.TemporaryDirectory() as tmp_dir:
              __lowercase		:			List[Any]	    =       os.path.join(_snake_case				,       '''vocab.txt'''				)
              with open(_snake_case				,       '''w'''				,       encoding='''utf-8'''				) as vocab_writer:
                  vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens]				)				)
              __lowercase		:			List[str]	    =       BertTokenizer(_snake_case				)

          tokenizer.push_to_hub('''valid_org/test-tokenizer-org'''				,       use_auth_token=self._token				)
          __lowercase		:			Optional[int]	    =       BertTokenizer.from_pretrained('''valid_org/test-tokenizer-org'''				)
          self.assertDictEqual(new_tokenizer.vocab				,       tokenizer.vocab				)

          # Reset repo
          delete_repo(token=self._token				,       repo_id='''valid_org/test-tokenizer-org'''				)

          # Push to hub via save_pretrained
          with tempfile.TemporaryDirectory() as tmp_dir:
              tokenizer.save_pretrained(
                  _snake_case				,       repo_id='''valid_org/test-tokenizer-org'''				,       push_to_hub=_snake_case				,       use_auth_token=self._token				)

          __lowercase		:			Tuple	    =       BertTokenizer.from_pretrained('''valid_org/test-tokenizer-org'''				)
          self.assertDictEqual(new_tokenizer.vocab				,       tokenizer.vocab				)




      @require_tokenizers
      def 		snake_case_			(      self		:       Any				):
          CustomTokenizer.register_for_auto_class()
          with tempfile.TemporaryDirectory() as tmp_dir:
              __lowercase		:			Union[str, Any]	    =       os.path.join(_snake_case				,       '''vocab.txt'''				)
              with open(_snake_case				,       '''w'''				,       encoding='''utf-8'''				) as vocab_writer:
                  vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens]				)				)
              __lowercase		:			List[Any]	    =       CustomTokenizer(_snake_case				)

          # No fast custom tokenizer
          tokenizer.push_to_hub('''test-dynamic-tokenizer'''				,       use_auth_token=self._token				)

          __lowercase		:			Dict	    =       AutoTokenizer.from_pretrained(F'{USER}/test-dynamic-tokenizer'				,       trust_remote_code=_snake_case				)
          # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
          self.assertEqual(tokenizer.__class__.__name__				,       '''CustomTokenizer'''				)

          # Fast and slow custom tokenizer
          CustomTokenizerFast.register_for_auto_class()
          with tempfile.TemporaryDirectory() as tmp_dir:
              __lowercase		:			Dict	    =       os.path.join(_snake_case				,       '''vocab.txt'''				)
              with open(_snake_case				,       '''w'''				,       encoding='''utf-8'''				) as vocab_writer:
                  vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens]				)				)

              __lowercase		:			str	    =       BertTokenizerFast.from_pretrained(_snake_case				)
              bert_tokenizer.save_pretrained(_snake_case				)
              __lowercase		:			Union[str, Any]	    =       CustomTokenizerFast.from_pretrained(_snake_case				)

          tokenizer.push_to_hub('''test-dynamic-tokenizer'''				,       use_auth_token=self._token				)

          __lowercase		:			Optional[int]	    =       AutoTokenizer.from_pretrained(F'{USER}/test-dynamic-tokenizer'				,       trust_remote_code=_snake_case				)
          # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
          self.assertEqual(tokenizer.__class__.__name__				,       '''CustomTokenizerFast'''				)
          __lowercase		:			List[str]	    =       AutoTokenizer.from_pretrained(
              F'{USER}/test-dynamic-tokenizer'				,       use_fast=_snake_case				,       trust_remote_code=_snake_case				)
          # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
          self.assertEqual(tokenizer.__class__.__name__				,       '''CustomTokenizer'''				)






class 						__lowerCAmelCase	(	unittest.TestCase      ):



      """simple docstring"""







      def 		snake_case_			(      self		:       Tuple				):
          __lowercase		:			List[Any]	    =       Trie()
          trie.add('''Hello 友達'''				)
          self.assertEqual(trie.data				,       {'''H''': {'''e''': {'''l''': {'''l''': {'''o''': {''' ''': {'''友''': {'''達''': {'''''': 1}}}}}}}}}				)
          trie.add('''Hello'''				)
          trie.data
          self.assertEqual(trie.data				,       {'''H''': {'''e''': {'''l''': {'''l''': {'''o''': {'''''': 1, ''' ''': {'''友''': {'''達''': {'''''': 1}}}}}}}}}				)




      def 		snake_case_			(      self		:       Optional[Any]				):
          __lowercase		:			List[Any]	    =       Trie()
          self.assertEqual(trie.split('''[CLS] This is a extra_id_100'''				)				,       ['''[CLS] This is a extra_id_100''']				)
          trie.add('''[CLS]'''				)
          trie.add('''extra_id_1'''				)
          trie.add('''extra_id_100'''				)
          self.assertEqual(trie.split('''[CLS] This is a extra_id_100'''				)				,       ['''[CLS]''', ''' This is a ''', '''extra_id_100''']				)




      def 		snake_case_			(      self		:       List[str]				):
          __lowercase		:			Optional[Any]	    =       Trie()
          trie.add('''A'''				)
          self.assertEqual(trie.split('''ABC'''				)				,       ['''A''', '''BC''']				)
          self.assertEqual(trie.split('''BCA'''				)				,       ['''BC''', '''A''']				)




      def 		snake_case_			(      self		:       Union[str, Any]				):
          __lowercase		:			Tuple	    =       Trie()
          trie.add('''TOKEN]'''				)
          trie.add('''[SPECIAL_TOKEN]'''				)
          self.assertEqual(trie.split('''This is something [SPECIAL_TOKEN]'''				)				,       ['''This is something ''', '''[SPECIAL_TOKEN]''']				)




      def 		snake_case_			(      self		:       Tuple				):
          __lowercase		:			int	    =       Trie()
          trie.add('''A'''				)
          trie.add('''P'''				)
          trie.add('''[SPECIAL_TOKEN]'''				)
          self.assertEqual(trie.split('''This is something [SPECIAL_TOKEN]'''				)				,       ['''This is something ''', '''[SPECIAL_TOKEN]''']				)




      def 		snake_case_			(      self		:       List[str]				):
          __lowercase		:			Optional[int]	    =       Trie()
          trie.add('''AB'''				)
          trie.add('''B'''				)
          trie.add('''C'''				)
          self.assertEqual(trie.split('''ABC'''				)				,       ['''AB''', '''C''']				)




      def 		snake_case_			(      self		:       Tuple				):
          __lowercase		:			Dict	    =       Trie()
          trie.add('''ABC'''				)
          trie.add('''B'''				)
          trie.add('''CD'''				)
          self.assertEqual(trie.split('''ABCD'''				)				,       ['''ABC''', '''D''']				)




      def 		snake_case_			(      self		:       Optional[Any]				):
          # Even if the offsets are wrong, we necessarily output correct string
          # parts.
          __lowercase		:			Dict	    =       Trie()
          __lowercase		:			Any	    =       trie.cut_text('''ABC'''				,       [0, 0, 2, 1, 2, 3]				)
          self.assertEqual(_snake_case				,       ['''AB''', '''C''']				)




from .constants import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SAFE_WEIGHTS_INDEX_NAME,
    SAFE_WEIGHTS_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    TORCH_LAUNCH_PARAMS,
    WEIGHTS_INDEX_NAME,
    WEIGHTS_NAME,
)
from .dataclasses import (
    BnbQuantizationConfig,
    ComputeEnvironment,
    CustomDtype,
    DeepSpeedPlugin,
    DistributedDataParallelKwargs,
    DistributedType,
    DynamoBackend,
    FPaRecipeKwargs,
    FullyShardedDataParallelPlugin,
    GradientAccumulationPlugin,
    GradScalerKwargs,
    InitProcessGroupKwargs,
    KwargsHandler,
    LoggerType,
    MegatronLMPlugin,
    PrecisionType,
    ProjectConfiguration,
    RNGType,
    SageMakerDistributedType,
    TensorInformation,
    TorchDynamoPlugin,
)
from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env
from .imports import (
    get_ccl_version,
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_aim_available,
    is_bfaa_available,
    is_bnb_available,
    is_botoa_available,
    is_ccl_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_fpa_available,
    is_ipex_available,
    is_megatron_lm_available,
    is_mlflow_available,
    is_mps_available,
    is_npu_available,
    is_rich_available,
    is_safetensors_available,
    is_sagemaker_available,
    is_tensorboard_available,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)
from .modeling import (
    check_device_map,
    check_tied_parameters_in_config,
    check_tied_parameters_on_same_device,
    compute_module_sizes,
    convert_file_size_to_int,
    dtype_byte_size,
    find_tied_parameters,
    get_balanced_memory,
    get_max_layer_size,
    get_max_memory,
    get_mixed_precision_context_manager,
    id_tensor_storage,
    infer_auto_device_map,
    load_checkpoint_in_model,
    load_offloaded_weights,
    load_state_dict,
    named_module_tensors,
    retie_parameters,
    set_module_tensor_to_device,
    shard_checkpoint,
)
from .offload import (
    OffloadedWeightsLoader,
    PrefixedDataset,
    extract_submodules_state_dict,
    load_offloaded_weight,
    offload_state_dict,
    offload_weight,
    save_offload_index,
)
from .operations import (
    broadcast,
    broadcast_object_list,
    concatenate,
    convert_outputs_to_fpaa,
    convert_to_fpaa,
    find_batch_size,
    find_device,
    gather,
    gather_object,
    get_data_structure,
    honor_type,
    initialize_tensors,
    is_namedtuple,
    is_tensor_information,
    is_torch_tensor,
    listify,
    pad_across_processes,
    recursively_apply,
    reduce,
    send_to_device,
    slice_tensors,
)
from .versions import compare_versions, is_torch_version


if is_deepspeed_available():
 from .deepspeed import (
     DeepSpeedEngineWrapper,
     DeepSpeedOptimizerWrapper,
     DeepSpeedSchedulerWrapper,
     DummyOptim,
     DummyScheduler,
     HfDeepSpeedConfig,
 )

from .bnb import has_abit_bnb_layers, load_and_quantize_model
from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer
from .launch import (
    PrepareForLaunch,
    _filter_args,
    prepare_deepspeed_cmd_env,
    prepare_multi_gpu_env,
    prepare_sagemager_args_inputs,
    prepare_simple_launcher_cmd_env,
    prepare_tpu,
)
from .megatron_lm import (
    AbstractTrainStep,
    BertTrainStep,
    GPTTrainStep,
    MegatronEngine,
    MegatronLMDummyDataLoader,
    MegatronLMDummyScheduler,
    MegatronLMOptimizerWrapper,
    MegatronLMSchedulerWrapper,
    TaTrainStep,
    avg_losses_across_data_parallel_group,
    gather_across_data_parallel_groups,
)
from .megatron_lm import initialize as megatron_lm_initialize
from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader
from .megatron_lm import prepare_model as megatron_lm_prepare_model
from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer
from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler
from .memory import find_executable_batch_size, release_memory
from .other import (
    extract_model_from_parallel,
    get_pretty_name,
    is_port_in_use,
    merge_dicts,
    patch_environment,
    save,
    wait_for_everyone,
    write_basic_config,
)
from .random import set_seed, synchronize_rng_state, synchronize_rng_states
from .torch_xla import install_xla
from .tqdm import tqdm
from .transformer_engine import convert_model, has_transformer_engine_layers


