



# 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 							A     (						__UpperCAmelCase      )			->			Optional[Any]:



						'''simple docstring'''






						if config_file is not None:
												if not os.path.isfile(__UpperCAmelCase      ):
																		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:
												UpperCAmelCase_					=	default_config_file
						with open(__UpperCAmelCase				,   '''r'''				,   encoding='''utf-8'''      ) as f:
												if config_file.endswith('''.json'''      ):
																		if (
																		    json.load(__UpperCAmelCase      ).get('''compute_environment'''				,   ComputeEnvironment.LOCAL_MACHINE      )
																		    == ComputeEnvironment.LOCAL_MACHINE
																		):
																								UpperCAmelCase_					=	ClusterConfig
																		else:
																								UpperCAmelCase_					=	SageMakerConfig
																		return config_class.from_json_file(json_file=__UpperCAmelCase      )
												else:
																		if (
																		    yaml.safe_load(__UpperCAmelCase      ).get('''compute_environment'''				,   ComputeEnvironment.LOCAL_MACHINE      )
																		    == ComputeEnvironment.LOCAL_MACHINE
																		):
																								UpperCAmelCase_					=	ClusterConfig
																		else:
																								UpperCAmelCase_					=	SageMakerConfig
																		return config_class.from_yaml_file(yaml_file=__UpperCAmelCase      )







@dataclass
class 				a_    :
						UpperCamelCase__ :		ComputeEnvironment
						UpperCamelCase__ :		Union[DistributedType, SageMakerDistributedType]
						UpperCamelCase__ :		str
						UpperCamelCase__ :		bool

						def       __a			(       self      :Dict)						->   List[Any]:
												UpperCAmelCase_					=	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(_lowercase  ,		_lowercase):
																								UpperCAmelCase_					=	value.value
																		if isinstance(_lowercase  ,		_lowercase) and not bool(_lowercase):
																								UpperCAmelCase_					=	None
												UpperCAmelCase_					=	{k: v for k, v in result.items() if v is not None}
												return result

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

						def       __a			(       self      :Tuple  ,		_lowercase      :Optional[int])						->   str:
												with open(_lowercase  ,		'''w'''  ,		encoding='''utf-8''') as f:
																		UpperCAmelCase_					=	json.dumps(self.to_dict()  ,		indent=2  ,		sort_keys=_lowercase) + '''\n'''
																		f.write(_lowercase)

						@classmethod
						def       __a			(       cls      :List[Any]  ,		_lowercase      :List[str]=None)						->   Tuple:
												UpperCAmelCase_					=	default_yaml_config_file if yaml_file is None else yaml_file
												with open(_lowercase  ,		'''r'''  ,		encoding='''utf-8''') as f:
																		UpperCAmelCase_					=	yaml.safe_load(_lowercase)
												if "compute_environment" not in config_dict:
																		UpperCAmelCase_					=	ComputeEnvironment.LOCAL_MACHINE

												if "mixed_precision" not in config_dict:
																		UpperCAmelCase_					=	'''fp16''' if ('''fp16''' in config_dict and config_dict['''fp16''']) else None
												if isinstance(config_dict['''mixed_precision''']  ,		_lowercase) and not config_dict["mixed_precision"]:
																		UpperCAmelCase_					=	'''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.
																		UpperCAmelCase_					=	config_dict.pop('''dynamo_backend''')
																		UpperCAmelCase_					=	{} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
												if "use_cpu" not in config_dict:
																		UpperCAmelCase_					=	False
												return cls(**_lowercase)

						def       __a			(       self      :Union[str, Any]  ,		_lowercase      :Optional[int])						->   List[str]:
												with open(_lowercase  ,		'''w'''  ,		encoding='''utf-8''') as f:
																		yaml.safe_dump(self.to_dict()  ,		_lowercase)




						def       __a			(       self      :Optional[int])						->   Optional[Any]:
												if isinstance(self.compute_environment  ,		_lowercase):
																		UpperCAmelCase_					=	ComputeEnvironment(self.compute_environment)
												if isinstance(self.distributed_type  ,		_lowercase):
																		if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																								UpperCAmelCase_					=	SageMakerDistributedType(self.distributed_type)
																		else:
																								UpperCAmelCase_					=	DistributedType(self.distributed_type)
												if self.dynamo_config is None:
																		UpperCAmelCase_					=	{}







@dataclass
class 				a_    (						_snake_case							):
						UpperCamelCase__ :		int
						UpperCamelCase__ :		int										=0
						UpperCamelCase__ :		int										=1
						UpperCamelCase__ :		Optional[str]										=None
						UpperCamelCase__ :		Optional[str]										=None
						UpperCamelCase__ :		Optional[int]										=None
						UpperCamelCase__ :		Optional[str]										="static"
						UpperCamelCase__ :		Optional[bool]										=False
						UpperCamelCase__ :		str										="main"

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

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

						# args for dynamo
						UpperCamelCase__ :		dict										=None

						def       __a			(       self      :List[Any])						->   Optional[int]:
												if self.deepspeed_config is None:
																		UpperCAmelCase_					=	{}
												if self.fsdp_config is None:
																		UpperCAmelCase_					=	{}
												if self.megatron_lm_config is None:
																		UpperCAmelCase_					=	{}
												if self.ipex_config is None:
																		UpperCAmelCase_					=	{}
												return super().__post_init__()







@dataclass
class 				a_    (						_snake_case							):
						UpperCamelCase__ :		str
						UpperCamelCase__ :		str
						UpperCamelCase__ :		Optional[str]										=None
						UpperCamelCase__ :		Optional[str]										=None
						UpperCamelCase__ :		str										="us-east-1"
						UpperCamelCase__ :		int										=1
						UpperCamelCase__ :		str										="all"
						UpperCamelCase__ :		str										=F'''accelerate-sagemaker-{num_machines}'''
						UpperCamelCase__ :		str										=SAGEMAKER_PYTORCH_VERSION
						UpperCamelCase__ :		str										=SAGEMAKER_TRANSFORMERS_VERSION
						UpperCamelCase__ :		str										=SAGEMAKER_PYTHON_VERSION
						UpperCamelCase__ :		str										=None
						UpperCamelCase__ :		str										=None
						UpperCamelCase__ :		dict										=None
						UpperCamelCase__ :		dict										=None










import os
import tempfile
import unittest
from typing import List

from transformers.models.esm.tokenization_esm import VOCAB_FILES_NAMES, EsmTokenizer
from transformers.testing_utils import require_tokenizers
from transformers.tokenization_utils import PreTrainedTokenizer
from transformers.tokenization_utils_base import PreTrainedTokenizerBase







@require_tokenizers
class 				a_    (						unittest.TestCase							):
						UpperCamelCase__ :		Any										=EsmTokenizer

						def       __a			(       self      :Optional[int])						->   Optional[int]:
												super().setUp()
												UpperCAmelCase_					=	tempfile.mkdtemp()
												# fmt: off
												UpperCAmelCase_					=	["<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>"]  # noqa: E501
												# fmt: on
												UpperCAmelCase_					=	os.path.join(self.tmpdirname  ,		VOCAB_FILES_NAMES['''vocab_file'''])
												with open(self.vocab_file  ,		'''w'''  ,		encoding='''utf-8''') as vocab_writer:
																		vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]))

						def       __a			(       self      :List[str]  ,		**_lowercase      :Union[str, Any])						->   List[PreTrainedTokenizerBase]:
												return [self.get_tokenizer(**_lowercase)]

						def       __a			(       self      :Optional[int]  ,		**_lowercase      :List[str])						->   PreTrainedTokenizer:
												return self.tokenizer_class.from_pretrained(self.tmpdirname  ,		**_lowercase)

						def       __a			(       self      :int)						->   Any:
												UpperCAmelCase_					=	self.tokenizer_class(self.vocab_file)

												UpperCAmelCase_					=	tokenizer.tokenize('''LAGVS''')
												self.assertListEqual(_lowercase  ,		['''L''', '''A''', '''G''', '''V''', '''S'''])
												self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowercase)  ,		[4, 5, 6, 7, 8])

						def       __a			(       self      :List[Any])						->   Optional[int]:
												UpperCAmelCase_					=	self.tokenizer_class(self.vocab_file)

												UpperCAmelCase_					=	'''LAGVS'''
												self.assertListEqual(tokenizer.encode(_lowercase)  ,		[0, 4, 5, 6, 7, 8, 2])

						def       __a			(       self      :Tuple)						->   Union[str, Any]:
												UpperCAmelCase_					=	self.tokenizer_class(self.vocab_file)

												UpperCAmelCase_					=	['''LAGVS''', '''WCB''']
												UpperCAmelCase_					=	tokenizer(_lowercase  ,		padding=_lowercase)['''input_ids''']

												self.assertListEqual(_lowercase  ,		[[0, 4, 5, 6, 7, 8, 2], [0, 22, 23, 25, 2]])

						def       __a			(       self      :str)						->   Any:
												UpperCAmelCase_					=	self.tokenizer_class(self.vocab_file)

												UpperCAmelCase_					=	['''LAGVS''', '''WCB''']
												UpperCAmelCase_					=	tokenizer(_lowercase  ,		padding=_lowercase)['''input_ids''']

												self.assertListEqual(_lowercase  ,		[[0, 4, 5, 6, 7, 8, 2], [0, 22, 23, 25, 2, 1, 1]])




						def       __a			(       self      :Dict)						->   Optional[int]:
												UpperCAmelCase_					=	self.get_tokenizers(fast=_lowercase)
												for tokenizer in tokenizers:
																		with self.subTest(f"{tokenizer.__class__.__name__}"):
																								UpperCAmelCase_					=	'''<unk>'''
																								UpperCAmelCase_					=	'''<mask>'''

																								UpperCAmelCase_					=	tokenizer.tokenize(_lowercase)
																								UpperCAmelCase_					=	tokenizer.tokenize(_lowercase)

																								self.assertEqual(len(_lowercase)  ,		1)
																								self.assertEqual(len(_lowercase)  ,		1)
																								self.assertEqual(token_a[0]  ,		_lowercase)
																								self.assertEqual(token_a[0]  ,		_lowercase)





