
"""simple docstring"""







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


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




def 			A_			(					lowercase      )     ->							List[Any]:


     """simple docstring"""







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



@dataclass
class 		UpperCAmelCase_	:
 """simple docstring"""




 UpperCamelCase_						:     Optional[int]				   =    42
 UpperCamelCase_						:     Tuple				   =    42
 UpperCamelCase_						:     List[str]				   =    42
 UpperCamelCase_						:     int				   =    42




 def   a      ( self       : Optional[Any] )->					Optional[int]:



      """simple docstring"""

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




 @classmethod
 def   a      ( cls       : str     ,   a_       : Optional[Any]=None )->					Optional[Any]:



      """simple docstring"""

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




 def   a      ( self       : Optional[Any]     ,   a_       : Union[str, Any] )->					Optional[Any]:



      """simple docstring"""

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




 @classmethod
 def   a      ( cls       : str     ,   a_       : Union[str, Any]=None )->					str:



      """simple docstring"""

      UpperCAmelCase_						:    List[Any]    					=  default_yaml_config_file if yaml_file is None else yaml_file
      with open(__a     ,   """r"""     ,   encoding="""utf-8""" ) as f:
           UpperCAmelCase_						:    Union[str, Any]    					=  yaml.safe_load(__a )
      if "compute_environment" not in config_dict:
           UpperCAmelCase_						:    int    					=  ComputeEnvironment.LOCAL_MACHINE

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




 def   a      ( self       : List[str]     ,   a_       : Optional[int] )->					int:



      """simple docstring"""

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






 def   a      ( self       : Optional[int] )->					List[Any]:



      """simple docstring"""

      if isinstance(self.compute_environment     ,   __a ):
           UpperCAmelCase_						:    str    					=  ComputeEnvironment(self.compute_environment )
      if isinstance(self.distributed_type     ,   __a ):
           if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                UpperCAmelCase_						:    Union[str, Any]    					=  SageMakerDistributedType(self.distributed_type )
           else:
                UpperCAmelCase_						:    int    					=  DistributedType(self.distributed_type )
      if self.dynamo_config is None:
           UpperCAmelCase_						:    Any    					=  {}



@dataclass
class 		UpperCAmelCase_	(lowerCAmelCase_						):
 """simple docstring"""




 UpperCamelCase_						:     List[str]				   =    42
 UpperCamelCase_						:     Union[str, Any]				   =    0
 UpperCamelCase_						:     Optional[int]				   =    1
 UpperCamelCase_						:     Tuple				   =    None
 UpperCamelCase_						:     int				   =    None
 UpperCamelCase_						:     Union[str, Any]				   =    None
 UpperCamelCase_						:     Dict				   =    """static"""
 UpperCamelCase_						:     Optional[int]				   =    False
 UpperCamelCase_						:     List[Any]				   =    """main"""

 # args for deepspeed_plugin
 UpperCamelCase_						:     Optional[int]				   =    None
 # args for fsdp
 UpperCamelCase_						:     Any				   =    None
 # args for megatron_lm
 UpperCamelCase_						:     Any				   =    None
 # args for ipex
 UpperCamelCase_						:     Tuple				   =    None
 # args for TPU
 UpperCamelCase_						:     Union[str, Any]				   =    False

 # args for TPU pods
 UpperCamelCase_						:     Union[str, Any]				   =    None
 UpperCamelCase_						:     Optional[Any]				   =    None
 UpperCamelCase_						:     str				   =    False
 UpperCamelCase_						:     Any				   =    False
 UpperCamelCase_						:     Dict				   =    None
 UpperCamelCase_						:     Optional[Any]				   =    None
 UpperCamelCase_						:     Optional[int]				   =    None
 UpperCamelCase_						:     str				   =    None

 # args for dynamo
 UpperCamelCase_						:     List[Any]				   =    None




 def   a      ( self       : str )->					Any:



      """simple docstring"""

      if self.deepspeed_config is None:
           UpperCAmelCase_						:    Dict    					=  {}
      if self.fsdp_config is None:
           UpperCAmelCase_						:    List[Any]    					=  {}
      if self.megatron_lm_config is None:
           UpperCAmelCase_						:    Union[str, Any]    					=  {}
      if self.ipex_config is None:
           UpperCAmelCase_						:    Optional[Any]    					=  {}
      return super().__post_init__()



@dataclass
class 		UpperCAmelCase_	(lowerCAmelCase_						):
 """simple docstring"""




 UpperCamelCase_						:     str				   =    42
 UpperCamelCase_						:     List[str]				   =    42
 UpperCamelCase_						:     List[str]				   =    None
 UpperCamelCase_						:     Optional[int]				   =    None
 UpperCamelCase_						:     int				   =    """us-east-1"""
 UpperCamelCase_						:     Dict				   =    1
 UpperCamelCase_						:     Dict				   =    """all"""
 UpperCamelCase_						:     int				   =    f'''accelerate-sagemaker-{num_machines}'''
 UpperCamelCase_						:     Optional[int]				   =    SAGEMAKER_PYTORCH_VERSION
 UpperCamelCase_						:     int				   =    SAGEMAKER_TRANSFORMERS_VERSION
 UpperCamelCase_						:     Optional[Any]				   =    SAGEMAKER_PYTHON_VERSION
 UpperCamelCase_						:     Tuple				   =    None
 UpperCamelCase_						:     Union[str, Any]				   =    None
 UpperCamelCase_						:     Tuple				   =    None
 UpperCamelCase_						:     Tuple				   =    None



"""simple docstring"""







import warnings

from .generation import FlaxGenerationMixin



class 		UpperCAmelCase_	(lowerCamelCase_						):
 """simple docstring"""




 warnings.warn(
     """Importing `FlaxGenerationMixin` from `src/transformers/generation_flax_utils.py` is deprecated and will """
     """be removed in Transformers v5. Import as `from transformers import FlaxGenerationMixin` instead."""  , lowerCamelCase_  , )

