


'''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


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





def __snake_case (				UpperCAmelCase_						:						Optional[Any]		):
 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:
  lowerCamelCase_								=  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
   ):
    lowerCamelCase_								=  ClusterConfig
   else:
    lowerCamelCase_								=  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
   ):
    lowerCamelCase_								=  ClusterConfig
   else:
    lowerCamelCase_								=  SageMakerConfig
   return config_class.from_yaml_file(yaml_file=UpperCAmelCase_		)





@dataclass
class 					snake_case   :





  """simple docstring"""




  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  42






  def   snake_case		(   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(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   snake_case		(   cls      ,  UpperCamelCase=None					):







   """simple docstring"""
   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   snake_case		(   self      ,  UpperCamelCase					):







   """simple docstring"""
   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   snake_case		(   cls      ,  UpperCamelCase=None					):







   """simple docstring"""
   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   snake_case		(   self      ,  UpperCamelCase					):







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







  def   snake_case		(   self					):







   """simple docstring"""
   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 					snake_case   (   lowercase      ):





  """simple docstring"""




  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  0
  _lowerCamelCase		   =  1
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  "static"
  _lowerCamelCase		   =  False
  _lowerCamelCase		   =  "main"

  # args for deepspeed_plugin
  _lowerCamelCase		   =  None
  # args for fsdp
  _lowerCamelCase		   =  None
  # args for megatron_lm
  _lowerCamelCase		   =  None
  # args for ipex
  _lowerCamelCase		   =  None
  # args for TPU
  _lowerCamelCase		   =  False

  # args for TPU pods
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  False
  _lowerCamelCase		   =  False
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None

  # args for dynamo
  _lowerCamelCase		   =  None






  def   snake_case		(   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 					snake_case   (   lowercase      ):





  """simple docstring"""




  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  "us-east-1"
  _lowerCamelCase		   =  1
  _lowerCamelCase		   =  "all"
  _lowerCamelCase		   =  F"accelerate-sagemaker-{num_machines}"
  _lowerCamelCase		   =  SAGEMAKER_PYTORCH_VERSION
  _lowerCamelCase		   =  SAGEMAKER_TRANSFORMERS_VERSION
  _lowerCamelCase		   =  SAGEMAKER_PYTHON_VERSION
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None







'''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


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





def __snake_case (				UpperCAmelCase_						:						Optional[Any]		):
 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:
  lowerCamelCase_								=  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
   ):
    lowerCamelCase_								=  ClusterConfig
   else:
    lowerCamelCase_								=  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
   ):
    lowerCamelCase_								=  ClusterConfig
   else:
    lowerCamelCase_								=  SageMakerConfig
   return config_class.from_yaml_file(yaml_file=UpperCAmelCase_		)





@dataclass
class 					snake_case   :





  """simple docstring"""




  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  42






  def   snake_case		(   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(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   snake_case		(   cls      ,  UpperCamelCase=None					):







   """simple docstring"""
   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   snake_case		(   self      ,  UpperCamelCase					):







   """simple docstring"""
   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   snake_case		(   cls      ,  UpperCamelCase=None					):







   """simple docstring"""
   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   snake_case		(   self      ,  UpperCamelCase					):







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







  def   snake_case		(   self					):







   """simple docstring"""
   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 					snake_case   (   lowercase      ):





  """simple docstring"""




  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  0
  _lowerCamelCase		   =  1
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  "static"
  _lowerCamelCase		   =  False
  _lowerCamelCase		   =  "main"

  # args for deepspeed_plugin
  _lowerCamelCase		   =  None
  # args for fsdp
  _lowerCamelCase		   =  None
  # args for megatron_lm
  _lowerCamelCase		   =  None
  # args for ipex
  _lowerCamelCase		   =  None
  # args for TPU
  _lowerCamelCase		   =  False

  # args for TPU pods
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  False
  _lowerCamelCase		   =  False
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None

  # args for dynamo
  _lowerCamelCase		   =  None






  def   snake_case		(   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 					snake_case   (   lowercase      ):





  """simple docstring"""




  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  42
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  "us-east-1"
  _lowerCamelCase		   =  1
  _lowerCamelCase		   =  "all"
  _lowerCamelCase		   =  F"accelerate-sagemaker-{num_machines}"
  _lowerCamelCase		   =  SAGEMAKER_PYTORCH_VERSION
  _lowerCamelCase		   =  SAGEMAKER_TRANSFORMERS_VERSION
  _lowerCamelCase		   =  SAGEMAKER_PYTHON_VERSION
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None
  _lowerCamelCase		   =  None



