



# 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__			=    os.path.expanduser(
    os.getenv("HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
)
UpperCamelCase__			=    os.path.join(hf_cache_home, "accelerate")
UpperCamelCase__			=    os.path.join(cache_dir, "default_config.yaml")
UpperCamelCase__			=    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__			=    default_yaml_config_file
else:
			UpperCamelCase__			=    default_json_config_file






def 			UpperCAmelCase__     (     lowercase__ )			->   Optional[Any]:
						if config_file is not None:
												if not os.path.isfile(lowercase__ ):
																		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:
												__lowercase											=					default_config_file
						with open(lowercase__    ,							"""r"""    ,							encoding="""utf-8""" ) as f:
												if config_file.endswith(""".json""" ):
																		if (
																		    json.load(lowercase__ ).get("""compute_environment"""    ,							ComputeEnvironment.LOCAL_MACHINE )
																		    == ComputeEnvironment.LOCAL_MACHINE
																		):
																								__lowercase											=					ClusterConfig
																		else:
																								__lowercase											=					SageMakerConfig
																		return config_class.from_json_file(json_file=lowercase__ )
												else:
																		if (
																		    yaml.safe_load(lowercase__ ).get("""compute_environment"""    ,							ComputeEnvironment.LOCAL_MACHINE )
																		    == ComputeEnvironment.LOCAL_MACHINE
																		):
																								__lowercase											=					ClusterConfig
																		else:
																								__lowercase											=					SageMakerConfig
																		return config_class.from_yaml_file(yaml_file=lowercase__ )
@dataclass
class       _lowerCAmelCase :






			"""simple docstring"""





			lowercase__   :	ComputeEnvironment
			lowercase__   :	Union[DistributedType, SageMakerDistributedType]
			lowercase__   :	str
			lowercase__   :	bool





			def 		snake_case__      (					self						:							Optional[Any] )    ->       Any:
									"""simple docstring"""







									__lowercase											=					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 ):
																					__lowercase											=					value.value
															if isinstance(_UpperCAmelCase      ,  _UpperCAmelCase ) and not bool(_UpperCAmelCase ):
																					__lowercase											=					None
									__lowercase											=					{k: v for k, v in result.items() if v is not None}
									return result





			@classmethod
			def 		snake_case__      (					cls						:							int      ,  lowercase						:							Optional[Any]=None )    ->       Optional[int]:
									"""simple docstring"""







									__lowercase											=					default_json_config_file if json_file is None else json_file
									with open(_UpperCAmelCase      ,  """r"""      ,  encoding="""utf-8""" ) as f:
															__lowercase											=					json.load(_UpperCAmelCase )
									if "compute_environment" not in config_dict:
															__lowercase											=					ComputeEnvironment.LOCAL_MACHINE
									if "mixed_precision" not in config_dict:
															__lowercase											=					"""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.
															__lowercase											=					config_dict.pop("""dynamo_backend""" )
															__lowercase											=					{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
									if "use_cpu" not in config_dict:
															__lowercase											=					False
									return cls(**_UpperCAmelCase )





			def 		snake_case__      (					self						:							Tuple      ,  lowercase						:							List[Any] )    ->       Optional[Any]:
									"""simple docstring"""







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





			@classmethod
			def 		snake_case__      (					cls						:							Optional[int]      ,  lowercase						:							Any=None )    ->       str:
									"""simple docstring"""







									__lowercase											=					default_yaml_config_file if yaml_file is None else yaml_file
									with open(_UpperCAmelCase      ,  """r"""      ,  encoding="""utf-8""" ) as f:
															__lowercase											=					yaml.safe_load(_UpperCAmelCase )
									if "compute_environment" not in config_dict:
															__lowercase											=					ComputeEnvironment.LOCAL_MACHINE

									if "mixed_precision" not in config_dict:
															__lowercase											=					"""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"]:
															__lowercase											=					"""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.
															__lowercase											=					config_dict.pop("""dynamo_backend""" )
															__lowercase											=					{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
									if "use_cpu" not in config_dict:
															__lowercase											=					False
									return cls(**_UpperCAmelCase )





			def 		snake_case__      (					self						:							int      ,  lowercase						:							List[str] )    ->       Any:
									"""simple docstring"""







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







			def 		snake_case__      (					self						:							Dict )    ->       Dict:
									"""simple docstring"""







									if isinstance(self.compute_environment      ,  _UpperCAmelCase ):
															__lowercase											=					ComputeEnvironment(self.compute_environment )
									if isinstance(self.distributed_type      ,  _UpperCAmelCase ):
															if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																					__lowercase											=					SageMakerDistributedType(self.distributed_type )
															else:
																					__lowercase											=					DistributedType(self.distributed_type )
									if self.dynamo_config is None:
															__lowercase											=					{}





@dataclass
class       _lowerCAmelCase (			_UpperCAmelCase      ):






			"""simple docstring"""





			lowercase__   :	int
			lowercase__   :	int  			=      0
			lowercase__   :	int  			=      1
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[int]  			=      None
			lowercase__   :	Optional[str]  			=      "static"
			lowercase__   :	Optional[bool]  			=      False
			lowercase__   :	str  			=      "main"

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

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

			# args for dynamo
			lowercase__   :	dict  			=      None





			def 		snake_case__      (					self						:							Optional[Any] )    ->       Tuple:
									"""simple docstring"""







									if self.deepspeed_config is None:
															__lowercase											=					{}
									if self.fsdp_config is None:
															__lowercase											=					{}
									if self.megatron_lm_config is None:
															__lowercase											=					{}
									if self.ipex_config is None:
															__lowercase											=					{}
									return super().__post_init__()





@dataclass
class       _lowerCAmelCase (			_UpperCAmelCase      ):






			"""simple docstring"""





			lowercase__   :	str
			lowercase__   :	str
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	str  			=      "us-east-1"
			lowercase__   :	int  			=      1
			lowercase__   :	str  			=      "all"
			lowercase__   :	str  			=      F'''accelerate-sagemaker-{num_machines}'''
			lowercase__   :	str  			=      SAGEMAKER_PYTORCH_VERSION
			lowercase__   :	str  			=      SAGEMAKER_TRANSFORMERS_VERSION
			lowercase__   :	str  			=      SAGEMAKER_PYTHON_VERSION
			lowercase__   :	str  			=      None
			lowercase__   :	str  			=      None
			lowercase__   :	dict  			=      None
			lowercase__   :	dict  			=      None













import json
import os
import unittest

from transformers import HerbertTokenizer, HerbertTokenizerFast
from transformers.models.herbert.tokenization_herbert import VOCAB_FILES_NAMES
from transformers.testing_utils import get_tests_dir, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


@require_tokenizers
class 		lowerCAmelCase_				(  UpperCamelCase				,     unittest.TestCase ):
     __lowerCamelCase       :    List[str] 	=     HerbertTokenizer
     __lowerCamelCase       :    Union[str, Any] 	=     HerbertTokenizerFast
     __lowerCamelCase       :    Union[str, Any] 	=     True





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

        # Use a simpler test file without japanese/chinese characters
        with open(F'''{get_tests_dir()}/fixtures/sample_text_no_unicode.txt'''							, encoding="""utf-8"""  ) as f_data:
           lowerCamelCase									=f_data.read().replace("""\n\n"""							, """\n"""  ).strip()

        lowerCamelCase									=[
            """<s>""",
            """</s>""",
            """l""",
            """o""",
            """w""",
            """e""",
            """r""",
            """s""",
            """t""",
            """i""",
            """d""",
            """n""",
            """w</w>""",
            """r</w>""",
            """t</w>""",
            """lo""",
            """low""",
            """er</w>""",
            """low</w>""",
            """lowest</w>""",
            """newer</w>""",
            """wider</w>""",
            """,</w>""",
            """<unk>""",
        ]
        lowerCamelCase									=dict(zip(_UpperCAmelCase							, range(len(_UpperCAmelCase  )  )  )  )
        lowerCamelCase									=["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""]

        lowerCamelCase									=os.path.join(self.tmpdirname							, VOCAB_FILES_NAMES["""vocab_file"""]  )
        lowerCamelCase									=os.path.join(self.tmpdirname							, VOCAB_FILES_NAMES["""merges_file"""]  )
        with open(self.vocab_file							, """w"""  ) as fp:
           fp.write(json.dumps(_UpperCAmelCase  )  )
        with open(self.merges_file							, """w"""  ) as fp:
           fp.write("""\n""".join(_UpperCAmelCase  )  )





     def 						lowerCamelCase							(	self							, _UpperCAmelCase  )		->				Optional[Any]:
        lowerCamelCase									="""lower newer"""
        lowerCamelCase									="""lower newer"""
        return input_text, output_text





     def 						lowerCamelCase							(	self  )		->				Any:
        lowerCamelCase									=self.tokenizer_class(vocab_file=self.vocab_file							, merges_file=self.merges_file  )

        lowerCamelCase									="""lower"""
        lowerCamelCase									=["""low""", """er</w>"""]
        lowerCamelCase									=tokenizer.tokenize(_UpperCAmelCase  )
        self.assertListEqual(_UpperCAmelCase							, _UpperCAmelCase  )

        lowerCamelCase									=tokens + ["""<unk>"""]
        lowerCamelCase									=[16, 17, 23]
        self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase  )							, _UpperCAmelCase  )





     def 						lowerCamelCase							(	self  )		->				Union[str, Any]:
        if not self.test_rust_tokenizer:
           return

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

        lowerCamelCase									="""lower,newer"""

        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  )





     @slow
     def 						lowerCamelCase							(	self  )		->				Any:
        lowerCamelCase									=self.tokenizer_class.from_pretrained("""allegro/herbert-base-cased"""  )

        lowerCamelCase									=tokenizer.encode("""konstruowanie sekwencji"""							, add_special_tokens=_UpperCAmelCase  )
        lowerCamelCase									=tokenizer.encode("""konstruowanie wielu sekwencji"""							, add_special_tokens=_UpperCAmelCase  )

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

        assert encoded_sentence == [0] + text + [2]
        assert encoded_pair == [0] + text + [2] + text_a + [2]