"""simple docstring"""







# 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


_SCREAMING_SNAKE_CASE	:		Tuple   =   os.path.expanduser(
    os.getenv('''HF_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''huggingface'''))
)
_SCREAMING_SNAKE_CASE	:		Optional[Any]   =   os.path.join(hf_cache_home, '''accelerate''')
_SCREAMING_SNAKE_CASE	:		Optional[int]   =   os.path.join(cache_dir, '''default_config.yaml''')
_SCREAMING_SNAKE_CASE	:		Any   =   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):
     _SCREAMING_SNAKE_CASE	:		List[str]   =   default_yaml_config_file
else:
     _SCREAMING_SNAKE_CASE	:		Optional[int]   =   default_json_config_file



def       A__    (	lowercase_     :	Any						)  ->							Union[str, 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:
      __lowerCamelCase    		=					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
         ):
            __lowerCamelCase    		=					ClusterConfig
         else:
            __lowerCamelCase    		=					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
         ):
            __lowerCamelCase    		=					ClusterConfig
         else:
            __lowerCamelCase    		=					SageMakerConfig
         return config_class.from_yaml_file(yaml_file=lowercase_						)






@dataclass
class      _SCREAMING_SNAKE_CASE							:



   '''simple docstring'''



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







   def    _A				(	self	):


      '''simple docstring'''

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







   @classmethod
   def    _A				(	cls ,				_SCREAMING_SNAKE_CASE=None	):


      '''simple docstring'''

      __lowerCamelCase    		=					default_json_config_file if json_file is None else json_file
      with open(_SCREAMING_SNAKE_CASE ,				'r' ,				encoding='utf-8'	) as f:
         __lowerCamelCase    		=					json.load(_SCREAMING_SNAKE_CASE	)
      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(**_SCREAMING_SNAKE_CASE	)







   def    _A				(	self ,				_SCREAMING_SNAKE_CASE	):


      '''simple docstring'''

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







   @classmethod
   def    _A				(	cls ,				_SCREAMING_SNAKE_CASE=None	):


      '''simple docstring'''

      __lowerCamelCase    		=					default_yaml_config_file if yaml_file is None else yaml_file
      with open(_SCREAMING_SNAKE_CASE ,				'r' ,				encoding='utf-8'	) as f:
         __lowerCamelCase    		=					yaml.safe_load(_SCREAMING_SNAKE_CASE	)
      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'] ,				_SCREAMING_SNAKE_CASE	) 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(**_SCREAMING_SNAKE_CASE	)







   def    _A				(	self ,				_SCREAMING_SNAKE_CASE	):


      '''simple docstring'''

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







   def    _A				(	self	):


      '''simple docstring'''

      if isinstance(self.compute_environment ,				_SCREAMING_SNAKE_CASE	):
         __lowerCamelCase    		=					ComputeEnvironment(self.compute_environment	)
      if isinstance(self.distributed_type ,				_SCREAMING_SNAKE_CASE	):
         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      _SCREAMING_SNAKE_CASE							(			UpperCAmelCase				):



   '''simple docstring'''



   __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	):


      '''simple docstring'''

      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      _SCREAMING_SNAKE_CASE							(			UpperCAmelCase				):



   '''simple docstring'''



   __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







"""simple docstring"""







from transformers.models.cpm.tokenization_cpm import CpmTokenizer
from transformers.testing_utils import custom_tokenizers

from ..xlnet.test_modeling_xlnet import XLNetModelTest






@custom_tokenizers
class      _SCREAMING_SNAKE_CASE							(			UpperCAmelCase				):



   '''simple docstring'''



   def    _A				(	self ,				_SCREAMING_SNAKE_CASE ,				_SCREAMING_SNAKE_CASE ,				_SCREAMING_SNAKE_CASE ,				_SCREAMING_SNAKE_CASE ,				_SCREAMING_SNAKE_CASE	):


      '''simple docstring'''

      return True







   def    _A				(	self	):


      '''simple docstring'''

      __lowerCamelCase    		=					CpmTokenizer.from_pretrained('TsinghuaAI/CPM-Generate'	)
      __lowerCamelCase    		=					'Hugging Face大法好，谁用谁知道。'
      __lowerCamelCase    		=					'Hugging Face大法好,谁用谁知道。<unk>'
      __lowerCamelCase    		=					'▁Hu gg ing ▁ ▂ ▁F ace ▁大法 ▁好 ▁ , ▁谁 ▁用 ▁谁 ▁知 道 ▁ 。'.split()

      __lowerCamelCase    		=					tokenizer.tokenize(_SCREAMING_SNAKE_CASE	)
      self.assertListEqual(_SCREAMING_SNAKE_CASE ,				_SCREAMING_SNAKE_CASE	)

      __lowerCamelCase    		=					tokens + [tokenizer.unk_token]

      __lowerCamelCase    		=					[13789, 13283, 1421, 8, 10, 1164, 13608, 16528, 63, 8, 9, 440, 108, 440, 121, 90, 8, 12, 0]
      self.assertListEqual(tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE	) ,				_SCREAMING_SNAKE_CASE	)

      __lowerCamelCase    		=					tokenizer.decode(_SCREAMING_SNAKE_CASE	)
      self.assertEqual(_SCREAMING_SNAKE_CASE ,				_SCREAMING_SNAKE_CASE	)






