# 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							(		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:
          a	:     Tuple						      =    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
               ):
                    a	:     List[str]						      =    ClusterConfig
               else:
                    a	:     Any						      =    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
               ):
                    a	:     int						      =    ClusterConfig
               else:
                    a	:     Dict						      =    SageMakerConfig
               return config_class.from_yaml_file(yaml_file=lowerCAmelCase_							)






@dataclass
class 				_SCREAMING_SNAKE_CASE:
   UpperCamelCase_					:    ComputeEnvironment
   UpperCamelCase_					:    Union[DistributedType, SageMakerDistributedType]
   UpperCamelCase_					:    str
   UpperCamelCase_					:    bool
   def _lowercase(     self     )						->List[str]:
        a	:     List[Any]						      =    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(lowerCAmelCase_				,  lowerCAmelCase_     ):
                  a	:     Optional[Any]						      =    value.value
             if isinstance(lowerCAmelCase_				,  lowerCAmelCase_     ) and not bool(lowerCAmelCase_     ):
                  a	:     Tuple						      =    None
        a	:     str						      =    {k: v for k, v in result.items() if v is not None}
        return result
   @classmethod
   def _lowercase(     cls				,  lowerCAmelCase_=None     )						->Union[str, Any]:
        a	:     Optional[int]						      =    default_json_config_file if json_file is None else json_file
        with open(lowerCAmelCase_				,  '''r'''				,  encoding='''utf-8'''     ) as f:
             a	:     Dict						      =    json.load(lowerCAmelCase_     )
        if "compute_environment" not in config_dict:
             a	:     Optional[int]						      =    ComputeEnvironment.LOCAL_MACHINE
        if "mixed_precision" not in config_dict:
             a	:     Optional[Any]						      =    '''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.
             a	:     List[str]						      =    config_dict.pop('''dynamo_backend'''     )
             a	:     Optional[Any]						      =    {} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
        if "use_cpu" not in config_dict:
             a	:     Dict						      =    False
        return cls(**lowerCAmelCase_     )
   def _lowercase(     self				,  lowerCAmelCase_     )						->Tuple:
        with open(lowerCAmelCase_				,  '''w'''				,  encoding='''utf-8'''     ) as f:
             a	:     str						      =    json.dumps(self.to_dict()				,  indent=2				,  sort_keys=lowerCAmelCase_     ) + '''\n'''
             f.write(lowerCAmelCase_     )
   @classmethod
   def _lowercase(     cls				,  lowerCAmelCase_=None     )						->Union[str, Any]:
        a	:     Optional[Any]						      =    default_yaml_config_file if yaml_file is None else yaml_file
        with open(lowerCAmelCase_				,  '''r'''				,  encoding='''utf-8'''     ) as f:
             a	:     str						      =    yaml.safe_load(lowerCAmelCase_     )
        if "compute_environment" not in config_dict:
             a	:     Any						      =    ComputeEnvironment.LOCAL_MACHINE

        if "mixed_precision" not in config_dict:
             a	:     Dict						      =    '''fp16''' if ('''fp16''' in config_dict and config_dict['''fp16''']) else None
        if isinstance(config_dict['''mixed_precision''']				,  lowerCAmelCase_     ) and not config_dict["mixed_precision"]:
             a	:     Dict						      =    '''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.
             a	:     List[str]						      =    config_dict.pop('''dynamo_backend'''     )
             a	:     Optional[int]						      =    {} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
        if "use_cpu" not in config_dict:
             a	:     List[str]						      =    False
        return cls(**lowerCAmelCase_     )
   def _lowercase(     self				,  lowerCAmelCase_     )						->List[Any]:
        with open(lowerCAmelCase_				,  '''w'''				,  encoding='''utf-8'''     ) as f:
             yaml.safe_dump(self.to_dict()				,  lowerCAmelCase_     )


   def _lowercase(     self     )						->Any:
        if isinstance(self.compute_environment				,  lowerCAmelCase_     ):
             a	:     Union[str, Any]						      =    ComputeEnvironment(self.compute_environment     )
        if isinstance(self.distributed_type				,  lowerCAmelCase_     ):
             if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                  a	:     List[Any]						      =    SageMakerDistributedType(self.distributed_type     )
             else:
                  a	:     Dict						      =    DistributedType(self.distributed_type     )
        if self.dynamo_config is None:
             a	:     List[Any]						      =    {}






@dataclass
class 				_SCREAMING_SNAKE_CASE( 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 _lowercase(     self     )						->int:
        if self.deepspeed_config is None:
             a	:     List[Any]						      =    {}
        if self.fsdp_config is None:
             a	:     Optional[Any]						      =    {}
        if self.megatron_lm_config is None:
             a	:     Any						      =    {}
        if self.ipex_config is None:
             a	:     Optional[Any]						      =    {}
        return super().__post_init__()






@dataclass
class 				_SCREAMING_SNAKE_CASE( 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
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
)


UpperCAmelCase				 =   {
    """configuration_gptsan_japanese""": ["""GPTSAN_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTSanJapaneseConfig"""],
    """tokenization_gptsan_japanese""": ["""GPTSanJapaneseTokenizer"""],
}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  UpperCAmelCase				 =   [
      """GPTSAN_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """GPTSanJapaneseForConditionalGeneration""",
      """GPTSanJapaneseModel""",
      """GPTSanJapanesePreTrainedModel""",
  ]
  UpperCAmelCase				 =   [
      """GPTSanJapaneseTokenizer""",
  ]


if TYPE_CHECKING:
  from .configuration_gptsan_japanese import GPTSAN_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTSanJapaneseConfig
  from .tokenization_gptsan_japanese import GPTSanJapaneseTokenizer

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_gptsan_japanese import (
        GPTSAN_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST,
        GPTSanJapaneseForConditionalGeneration,
        GPTSanJapaneseModel,
        GPTSanJapanesePreTrainedModel,
    )
    from .tokenization_gptsan_japanese import GPTSanJapaneseTokenizer


else:
  import sys

  UpperCAmelCase				 =   _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)