






# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


_UpperCAmelCase				:	Tuple    						=    os.path.expanduser(
    os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface'))
)
_UpperCAmelCase				:	Optional[Any]    						=    os.path.join(hf_cache_home, 'accelerate')
_UpperCAmelCase				:	Dict    						=    os.path.join(cache_dir, 'default_config.yaml')
_UpperCAmelCase				:	str    						=    os.path.join(cache_dir, 'default_config.yaml')

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
   _UpperCAmelCase				:	int    						=    default_yaml_config_file
else:
   _UpperCAmelCase				:	List[Any]    						=    default_json_config_file






def    UpperCAmelCase__	(						lowerCamelCase  : str						):
   if config_file is not None:
      if not os.path.isfile(lowerCamelCase						):
         raise FileNotFoundError(
             f'The passed configuration file `{config_file}` does not exist. '
             """Please pass an existing file to `accelerate launch`, or use the the default one """
             """created through `accelerate config` and run `accelerate launch` """
             """without the `--config_file` argument."""						)
   else:
      lowerCamelCase											=default_config_file
   with open(lowerCamelCase ,"""r""" ,encoding="""utf-8"""						) as f:
      if config_file.endswith(""".json"""						):
         if (
             json.load(lowerCamelCase						).get("""compute_environment""" ,ComputeEnvironment.LOCAL_MACHINE						)
             == ComputeEnvironment.LOCAL_MACHINE
         ):
            lowerCamelCase											=ClusterConfig
         else:
            lowerCamelCase											=SageMakerConfig
         return config_class.from_json_file(json_file=lowerCamelCase						)
      else:
         if (
             yaml.safe_load(lowerCamelCase						).get("""compute_environment""" ,ComputeEnvironment.LOCAL_MACHINE						)
             == ComputeEnvironment.LOCAL_MACHINE
         ):
            lowerCamelCase											=ClusterConfig
         else:
            lowerCamelCase											=SageMakerConfig
         return config_class.from_yaml_file(yaml_file=lowerCamelCase						)


@dataclass
class 		lowerCAmelCase_							:
     __lowerCamelCase					:						ComputeEnvironment
     __lowerCamelCase					:						Union[DistributedType, SageMakerDistributedType]
     __lowerCamelCase					:						str
     __lowerCamelCase					:						bool





     def 	lowerCamelCase       (  self     )		->							List[Any]:
        lowerCamelCase											=self.__dict__
        # For serialization, it's best to convert Enums to strings (or their underlying value type).
        for key, value in result.items():
           if isinstance(_UpperCAmelCase       ,   _UpperCAmelCase     ):
              lowerCamelCase											=value.value
           if isinstance(_UpperCAmelCase       ,   _UpperCAmelCase     ) and not bool(_UpperCAmelCase     ):
              lowerCamelCase											=None
        lowerCamelCase											={k: v for k, v in result.items() if v is not None}
        return result





     @classmethod
     def 	lowerCamelCase       (  cls       ,   _UpperCAmelCase=None     )		->							Dict:
        lowerCamelCase											=default_json_config_file if json_file is None else json_file
        with open(_UpperCAmelCase       ,   """r"""       ,   encoding="""utf-8"""     ) as f:
           lowerCamelCase											=json.load(_UpperCAmelCase     )
        if "compute_environment" not in config_dict:
           lowerCamelCase											=ComputeEnvironment.LOCAL_MACHINE
        if "mixed_precision" not in config_dict:
           lowerCamelCase											="""fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
        if "fp16" in config_dict:  # Convert the config to the new format.
           del config_dict["fp16"]
        if "dynamo_backend" in config_dict:  # Convert the config to the new format.
           lowerCamelCase											=config_dict.pop("""dynamo_backend"""     )
           lowerCamelCase											={} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
        if "use_cpu" not in config_dict:
           lowerCamelCase											=False
        return cls(**_UpperCAmelCase     )





     def 	lowerCamelCase       (  self       ,   _UpperCAmelCase     )		->							Dict:
        with open(_UpperCAmelCase       ,   """w"""       ,   encoding="""utf-8"""     ) as f:
           lowerCamelCase											=json.dumps(self.to_dict()       ,   indent=2       ,   sort_keys=_UpperCAmelCase     ) + """\n"""
           f.write(_UpperCAmelCase     )





     @classmethod
     def 	lowerCamelCase       (  cls       ,   _UpperCAmelCase=None     )		->							Any:
        lowerCamelCase											=default_yaml_config_file if yaml_file is None else yaml_file
        with open(_UpperCAmelCase       ,   """r"""       ,   encoding="""utf-8"""     ) as f:
           lowerCamelCase											=yaml.safe_load(_UpperCAmelCase     )
        if "compute_environment" not in config_dict:
           lowerCamelCase											=ComputeEnvironment.LOCAL_MACHINE

        if "mixed_precision" not in config_dict:
           lowerCamelCase											="""fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
        if isinstance(config_dict["""mixed_precision"""]       ,   _UpperCAmelCase     ) and not config_dict["mixed_precision"]:
           lowerCamelCase											="""no"""
        if "fp16" in config_dict:  # Convert the config to the new format.
           del config_dict["fp16"]
        if "dynamo_backend" in config_dict:  # Convert the config to the new format.
           lowerCamelCase											=config_dict.pop("""dynamo_backend"""     )
           lowerCamelCase											={} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
        if "use_cpu" not in config_dict:
           lowerCamelCase											=False
        return cls(**_UpperCAmelCase     )





     def 	lowerCamelCase       (  self       ,   _UpperCAmelCase     )		->							int:
        with open(_UpperCAmelCase       ,   """w"""       ,   encoding="""utf-8"""     ) as f:
           yaml.safe_dump(self.to_dict()       ,   _UpperCAmelCase     )





     def 	lowerCamelCase       (  self     )		->							str:
        if isinstance(self.compute_environment       ,   _UpperCAmelCase     ):
           lowerCamelCase											=ComputeEnvironment(self.compute_environment     )
        if isinstance(self.distributed_type       ,   _UpperCAmelCase     ):
           if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
              lowerCamelCase											=SageMakerDistributedType(self.distributed_type     )
           else:
              lowerCamelCase											=DistributedType(self.distributed_type     )
        if self.dynamo_config is None:
           lowerCamelCase											={}




@dataclass
class 		lowerCAmelCase_							(     UpperCamelCase   ):
     __lowerCamelCase					:						int
     __lowerCamelCase					:						int     =    0
     __lowerCamelCase					:						int     =    1
     __lowerCamelCase					:						Optional[str]     =    None
     __lowerCamelCase					:						Optional[str]     =    None
     __lowerCamelCase					:						Optional[int]     =    None
     __lowerCamelCase					:						Optional[str]     =    "static"
     __lowerCamelCase					:						Optional[bool]     =    False
     __lowerCamelCase					:						str     =    "main"

     # args for deepspeed_plugin
     __lowerCamelCase					:						dict     =    None
     # args for fsdp
     __lowerCamelCase					:						dict     =    None
     # args for megatron_lm
     __lowerCamelCase					:						dict     =    None
     # args for ipex
     __lowerCamelCase					:						dict     =    None
     # args for TPU
     __lowerCamelCase					:						bool     =    False

     # args for TPU pods
     __lowerCamelCase					:						str     =    None
     __lowerCamelCase					:						str     =    None
     __lowerCamelCase					:						bool     =    False
     __lowerCamelCase					:						bool     =    False
     __lowerCamelCase					:						str     =    None
     __lowerCamelCase					:						List[str]     =    None
     __lowerCamelCase					:						List[str]     =    None
     __lowerCamelCase					:						List[str]     =    None

     # args for dynamo
     __lowerCamelCase					:						dict     =    None





     def 	lowerCamelCase       (  self     )		->							int:
        if self.deepspeed_config is None:
           lowerCamelCase											={}
        if self.fsdp_config is None:
           lowerCamelCase											={}
        if self.megatron_lm_config is None:
           lowerCamelCase											={}
        if self.ipex_config is None:
           lowerCamelCase											={}
        return super().__post_init__()




@dataclass
class 		lowerCAmelCase_							(     UpperCamelCase   ):
     __lowerCamelCase					:						str
     __lowerCamelCase					:						str
     __lowerCamelCase					:						Optional[str]     =    None
     __lowerCamelCase					:						Optional[str]     =    None
     __lowerCamelCase					:						str     =    "us-east-1"
     __lowerCamelCase					:						int     =    1
     __lowerCamelCase					:						str     =    "all"
     __lowerCamelCase					:						str     =    f'''accelerate-sagemaker-{num_machines}'''
     __lowerCamelCase					:						str     =    SAGEMAKER_PYTORCH_VERSION
     __lowerCamelCase					:						str     =    SAGEMAKER_TRANSFORMERS_VERSION
     __lowerCamelCase					:						str     =    SAGEMAKER_PYTHON_VERSION
     __lowerCamelCase					:						str     =    None
     __lowerCamelCase					:						str     =    None
     __lowerCamelCase					:						dict     =    None
     __lowerCamelCase					:						dict     =    None







import unittest

from transformers import ErnieMTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


_UpperCAmelCase				:	Any    						=    get_tests_dir('fixtures/spiece.model')


@require_sentencepiece
@require_tokenizers
class 		lowerCAmelCase_							(     UpperCamelCase							,    unittest.TestCase   ):
     __lowerCamelCase					:						List[Any]     =    ErnieMTokenizer
     __lowerCamelCase					:						Optional[Any]     =    False
     __lowerCamelCase					:						Optional[int]     =    True
     __lowerCamelCase					:						str     =    False
     __lowerCamelCase					:						Any     =    False





     def 	lowerCamelCase       (  self     )		->							Any:
        super().setUp()

        # We have a SentencePiece fixture for testing
        lowerCamelCase											=ErnieMTokenizer(_UpperCAmelCase       ,   unk_token="""<unk>"""       ,   pad_token="""<pad>"""     )
        tokenizer.save_pretrained(self.tmpdirname     )





     def 	lowerCamelCase       (  self       ,   _UpperCAmelCase     )		->							Union[str, Any]:
        lowerCamelCase											="""this is a test"""
        lowerCamelCase											="""this is a test"""
        return input_text, output_text





     def 	lowerCamelCase       (  self     )		->							List[Any]:
        lowerCamelCase											="""<pad>"""
        lowerCamelCase											=0

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





     def 	lowerCamelCase       (  self     )		->							List[str]:
        lowerCamelCase											=list(self.get_tokenizer().get_vocab().keys()     )

        self.assertEqual(vocab_keys[0]       ,   """<pad>"""     )
        self.assertEqual(vocab_keys[1]       ,   """<unk>"""     )
        self.assertEqual(vocab_keys[-1]       ,   """▁eloquent"""     )
        self.assertEqual(len(_UpperCAmelCase     )       ,   30000     )





     def 	lowerCamelCase       (  self     )		->							Any:
        self.assertEqual(self.get_tokenizer().vocab_size       ,   30000     )





     def 	lowerCamelCase       (  self     )		->							Any:
        if not self.test_rust_tokenizer:
           return

        lowerCamelCase											=self.get_tokenizer()
        lowerCamelCase											=self.get_rust_tokenizer()

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

        lowerCamelCase											=tokenizer.tokenize(_UpperCAmelCase     )
        lowerCamelCase											=rust_tokenizer.tokenize(_UpperCAmelCase     )
        self.assertListEqual(_UpperCAmelCase       ,   _UpperCAmelCase     )

        lowerCamelCase											=tokenizer.encode(_UpperCAmelCase       ,   add_special_tokens=_UpperCAmelCase     )
        lowerCamelCase											=rust_tokenizer.encode(_UpperCAmelCase       ,   add_special_tokens=_UpperCAmelCase     )
        self.assertListEqual(_UpperCAmelCase       ,   _UpperCAmelCase     )

        lowerCamelCase											=self.get_rust_tokenizer()
        lowerCamelCase											=tokenizer.encode(_UpperCAmelCase     )
        lowerCamelCase											=rust_tokenizer.encode(_UpperCAmelCase     )
        self.assertListEqual(_UpperCAmelCase       ,   _UpperCAmelCase     )





     def 	lowerCamelCase       (  self     )		->							Union[str, Any]:
        lowerCamelCase											=ErnieMTokenizer(_UpperCAmelCase       ,   do_lower_case=_UpperCAmelCase       ,   unk_token="""<unk>"""       ,   pad_token="""<pad>"""     )

        lowerCamelCase											=tokenizer.tokenize("""This is a test"""     )
        self.assertListEqual(_UpperCAmelCase       ,   ["""▁this""", """▁is""", """▁a""", """▁test"""]     )

        self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase     )       ,   [48, 25, 21, 1289]     )

        lowerCamelCase											=tokenizer.tokenize("""I was born in 92000, and this is falsé."""     )
        # ErnieMTokenizer(paddlenlp implementation) outputs '9' instead of '_9' so to mimic that '_9' is changed to '9'
        self.assertListEqual(
            _UpperCAmelCase       ,   ["""▁i""", """▁was""", """▁born""", """▁in""", """9""", """2000""", """,""", """▁and""", """▁this""", """▁is""", """▁fal""", """s""", """é""", """."""]     )
        lowerCamelCase											=tokenizer.convert_tokens_to_ids(_UpperCAmelCase     )
        self.assertListEqual(_UpperCAmelCase       ,   [31, 23, 386, 19, 518, 3050, 15, 17, 48, 25, 8256, 18, 1, 9]     )

        lowerCamelCase											=tokenizer.convert_ids_to_tokens(_UpperCAmelCase     )
        self.assertListEqual(
            _UpperCAmelCase       ,   ["""▁i""", """▁was""", """▁born""", """▁in""", """9""", """2000""", """,""", """▁and""", """▁this""", """▁is""", """▁fal""", """s""", """<unk>""", """."""]       ,   )





     def 	lowerCamelCase       (  self     )		->							List[str]:
        lowerCamelCase											=ErnieMTokenizer(_UpperCAmelCase       ,   unk_token="""<unk>"""       ,   pad_token="""<pad>"""     )

        lowerCamelCase											=tokenizer.encode("""sequence builders"""     )
        lowerCamelCase											=tokenizer.encode("""multi-sequence build"""     )

        lowerCamelCase											=tokenizer.build_inputs_with_special_tokens(_UpperCAmelCase     )
        lowerCamelCase											=tokenizer.build_inputs_with_special_tokens(_UpperCAmelCase       ,   _UpperCAmelCase     )

        assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
        assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + [
            tokenizer.sep_token_id
        ] + text_a + [tokenizer.sep_token_id]





     @slow
     def 	lowerCamelCase       (  self     )		->							Dict:
        # fmt: off
        lowerCamelCase											={"""input_ids""": [[0, 11062, 82772, 7, 15, 82772, 538, 51529, 237, 17198, 1290, 206, 9, 215175, 1314, 136, 17198, 1290, 206, 9, 56359, 42, 122009, 9, 16466, 16, 87344, 4537, 9, 4717, 78381, 6, 159958, 7, 15, 24480, 618, 4, 527, 22693, 9, 304, 4, 2777, 24480, 9874, 4, 43523, 594, 4, 803, 18392, 33189, 18, 4, 43523, 24447, 5, 5, 5, 16, 100, 24955, 83658, 9626, 144057, 15, 839, 22335, 16, 136, 24955, 83658, 83479, 15, 39102, 724, 16, 678, 645, 6460, 1328, 4589, 42, 122009, 115774, 23, 3559, 1328, 46876, 7, 136, 53894, 1940, 42227, 41159, 17721, 823, 425, 4, 27512, 98722, 206, 136, 5531, 4970, 919, 17336, 5, 2], [0, 20080, 618, 83, 82775, 47, 479, 9, 1517, 73, 53894, 333, 80581, 110117, 18811, 5256, 1295, 51, 152526, 297, 7986, 390, 124416, 538, 35431, 214, 98, 15044, 25737, 136, 7108, 43701, 23, 756, 135355, 7, 5, 2, 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], [0, 581, 63773, 119455, 6, 147797, 88203, 7, 645, 70, 21, 3285, 10269, 5, 2, 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]]}
        # fmt: on

        self.tokenizer_integration_test_util(
            expected_encoding=_UpperCAmelCase       ,   model_name="""susnato/ernie-m-base_pytorch"""       ,   sequences=[
                """Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides """
                """general-purpose architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet...) for Natural """
                """Language Understanding (NLU) and Natural Language Generation (NLG) with over32+ pretrained """
                """models in100+ languages and deep interoperability between Jax, PyTorch and TensorFlow.""",
                """BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly """
                """conditioning on both left and right context in all layers.""",
                """The quick brown fox jumps over the lazy dog.""",
            ]       ,   )