code: # 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
  
  
  lowerCamelCase__           =				os.path.expanduser(
      os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface'))
  )
  lowerCamelCase__           =				os.path.join(hf_cache_home, 'accelerate')
  lowerCamelCase__           =				os.path.join(cache_dir, 'default_config.yaml')
  lowerCamelCase__           =				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):
  		lowerCamelCase__           =				default_yaml_config_file
  else:
  		lowerCamelCase__           =				default_json_config_file
  
  
  
  def 							_lowerCamelCase(				__snake_case	)  ->   Union[str, Any]:
  		if config_file is not None:
  				if not os.path.isfile(__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:
  				__snake_case		       =     default_config_file
  		with open(__snake_case						,						"r"						,						encoding="utf-8"	) as f:
  				if config_file.endswith(".json"	):
  						if (
  						    json.load(__snake_case	).get("compute_environment"						,						ComputeEnvironment.LOCAL_MACHINE	)
  						    == ComputeEnvironment.LOCAL_MACHINE
  						):
  								__snake_case		       =     ClusterConfig
  						else:
  								__snake_case		       =     SageMakerConfig
  						return config_class.from_json_file(json_file=__snake_case	)
  				else:
  						if (
  						    yaml.safe_load(__snake_case	).get("compute_environment"						,						ComputeEnvironment.LOCAL_MACHINE	)
  						    == ComputeEnvironment.LOCAL_MACHINE
  						):
  								__snake_case		       =     ClusterConfig
  						else:
  								__snake_case		       =     SageMakerConfig
  						return config_class.from_yaml_file(yaml_file=__snake_case	)
  
  
  
  
  @dataclass
  class 					UpperCamelCase	:
  					__UpperCamelCase						=   42
  					__UpperCamelCase						=   42
  					__UpperCamelCase						=   42
  					__UpperCamelCase						=   42
  
  
  
  
  					def 							UpperCamelCase_						( self :					Union[str, Any]						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     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						):
  											__snake_case		       =     value.value
  									if isinstance(_lowerCAmelCase      ,_lowerCAmelCase						) and not bool(_lowerCAmelCase						):
  											__snake_case		       =     None
  							__snake_case		       =     {k: v for k, v in result.items() if v is not None}
  							return result
  
  
  
  
  					@classmethod
  					def 							UpperCamelCase_						( cls :					Dict      ,_lowerCAmelCase :					Union[str, Any]=None						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     default_json_config_file if json_file is None else json_file
  							with open(_lowerCAmelCase      ,"r"      ,encoding="utf-8"						) as f:
  									__snake_case		       =     json.load(_lowerCAmelCase						)
  							if "compute_environment" not in config_dict:
  									__snake_case		       =     ComputeEnvironment.LOCAL_MACHINE
  							if "mixed_precision" not in config_dict:
  									__snake_case		       =     "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.
  									__snake_case		       =     config_dict.pop("dynamo_backend"						)
  									__snake_case		       =     {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
  							if "use_cpu" not in config_dict:
  									__snake_case		       =     False
  							return cls(**_lowerCAmelCase						)
  
  
  
  
  					def 							UpperCamelCase_						( self :					int      ,_lowerCAmelCase :					Optional[Any]						):
  
  
  							"""simple docstring"""
  
  
  
  
  							with open(_lowerCAmelCase      ,"w"      ,encoding="utf-8"						) as f:
  									__snake_case		       =     json.dumps(self.to_dict()      ,indent=2      ,sort_keys=_lowerCAmelCase						) + "\n"
  									f.write(_lowerCAmelCase						)
  
  
  
  
  					@classmethod
  					def 							UpperCamelCase_						( cls :					str      ,_lowerCAmelCase :					List[str]=None						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     default_yaml_config_file if yaml_file is None else yaml_file
  							with open(_lowerCAmelCase      ,"r"      ,encoding="utf-8"						) as f:
  									__snake_case		       =     yaml.safe_load(_lowerCAmelCase						)
  							if "compute_environment" not in config_dict:
  									__snake_case		       =     ComputeEnvironment.LOCAL_MACHINE
  
  							if "mixed_precision" not in config_dict:
  									__snake_case		       =     "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"]:
  									__snake_case		       =     "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.
  									__snake_case		       =     config_dict.pop("dynamo_backend"						)
  									__snake_case		       =     {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
  							if "use_cpu" not in config_dict:
  									__snake_case		       =     False
  							return cls(**_lowerCAmelCase						)
  
  
  
  
  					def 							UpperCamelCase_						( self :					Tuple      ,_lowerCAmelCase :					Any						):
  
  
  							"""simple docstring"""
  
  
  
  
  							with open(_lowerCAmelCase      ,"w"      ,encoding="utf-8"						) as f:
  									yaml.safe_dump(self.to_dict()      ,_lowerCAmelCase						)
  
  
  
  
  
  
  
  					def 							UpperCamelCase_						( self :					Optional[Any]						):
  
  
  							"""simple docstring"""
  
  
  
  
  							if isinstance(self.compute_environment      ,_lowerCAmelCase						):
  									__snake_case		       =     ComputeEnvironment(self.compute_environment						)
  							if isinstance(self.distributed_type      ,_lowerCAmelCase						):
  									if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
  											__snake_case		       =     SageMakerDistributedType(self.distributed_type						)
  									else:
  											__snake_case		       =     DistributedType(self.distributed_type						)
  							if self.dynamo_config is None:
  									__snake_case		       =     {}
  
  
  
  
  @dataclass
  class 					UpperCamelCase	(     snake_case__      ):
  					__UpperCamelCase						=   42
  					__UpperCamelCase						=   0
  					__UpperCamelCase						=   1
  					__UpperCamelCase						=   None
  					__UpperCamelCase						=   None
  					__UpperCamelCase						=   None
  					__UpperCamelCase						=   "static"
  					__UpperCamelCase						=   False
  					__UpperCamelCase						=   "main"
  
  					# args for deepspeed_plugin
  					__UpperCamelCase						=   None
  					# args for fsdp
  					__UpperCamelCase						=   None
  					# args for megatron_lm
  					__UpperCamelCase						=   None
  					# args for ipex
  					__UpperCamelCase						=   None
  					# args for TPU
  					__UpperCamelCase						=   False
  
  					# args for TPU pods
  					__UpperCamelCase						=   None
  					__UpperCamelCase						=   None
  					__UpperCamelCase						=   False
  					__UpperCamelCase						=   False
  					__UpperCamelCase						=   None
  					__UpperCamelCase						=   None
  					__UpperCamelCase						=   None
  					__UpperCamelCase						=   None
  
  					# args for dynamo
  					__UpperCamelCase						=   None
  
  
  
  
  					def 							UpperCamelCase_						( self :					List[str]						):
  
  
  							"""simple docstring"""
  
  
  
  
  							if self.deepspeed_config is None:
  									__snake_case		       =     {}
  							if self.fsdp_config is None:
  									__snake_case		       =     {}
  							if self.megatron_lm_config is None:
  									__snake_case		       =     {}
  							if self.ipex_config is None:
  									__snake_case		       =     {}
  							return super().__post_init__()
  
  
  
  
  @dataclass
  class 					UpperCamelCase	(     snake_case__      ):
  					__UpperCamelCase						=   42
  					__UpperCamelCase						=   42
  					__UpperCamelCase						=   None
  					__UpperCamelCase						=   None
  					__UpperCamelCase						=   "us-east-1"
  					__UpperCamelCase						=   1
  					__UpperCamelCase						=   "all"
  					__UpperCamelCase						=   f'''accelerate-sagemaker-{num_machines}'''
  					__UpperCamelCase						=   SAGEMAKER_PYTORCH_VERSION
  					__UpperCamelCase						=   SAGEMAKER_TRANSFORMERS_VERSION
  					__UpperCamelCase						=   SAGEMAKER_PYTHON_VERSION
  					__UpperCamelCase						=   None
  					__UpperCamelCase						=   None
  					__UpperCamelCase						=   None
  					__UpperCamelCase						=   None
  
  
  
  
  
  
style_context: import posixpath
  from pathlib import Path
  from unittest.mock import patch
  
  import pytest
  from fsspec.implementations.local import AbstractFileSystem, LocalFileSystem, stringify_path
  from fsspec.registry import _registry as _fsspec_registry
  
  
  
  
  class 					UpperCamelCase	(     snake_case__      ):
  					__UpperCamelCase						=   """mock"""
  
  
  
  
  					def __init__( self :					List[Any]      ,*_lowerCAmelCase :					Optional[int]      ,_lowerCAmelCase :					Union[str, Any]      ,**_lowerCAmelCase :					Union[str, Any]						):
  
  
  							"""simple docstring"""
  
  
  
  
  							super().__init__()
  							__snake_case		       =     LocalFileSystem(*_lowerCAmelCase      ,**_lowerCAmelCase						)
  							__snake_case		       =     Path(_lowerCAmelCase						).resolve().as_posix() + "/"
  
  
  
  
  					def 							UpperCamelCase_						( self :					List[Any]      ,_lowerCAmelCase :					Optional[Any]      ,*_lowerCAmelCase :					Union[str, Any]      ,**_lowerCAmelCase :					Dict						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     posixpath.join(self.local_root_dir      ,self._strip_protocol(_lowerCAmelCase						)						)
  							return self._fs.mkdir(_lowerCAmelCase      ,*_lowerCAmelCase      ,**_lowerCAmelCase						)
  
  
  
  
  					def 							UpperCamelCase_						( self :					int      ,_lowerCAmelCase :					Tuple      ,*_lowerCAmelCase :					Optional[Any]      ,**_lowerCAmelCase :					Optional[Any]						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     posixpath.join(self.local_root_dir      ,self._strip_protocol(_lowerCAmelCase						)						)
  							return self._fs.makedirs(_lowerCAmelCase      ,*_lowerCAmelCase      ,**_lowerCAmelCase						)
  
  
  
  
  					def 							UpperCamelCase_						( self :					Tuple      ,_lowerCAmelCase :					Any						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     posixpath.join(self.local_root_dir      ,self._strip_protocol(_lowerCAmelCase						)						)
  							return self._fs.rmdir(_lowerCAmelCase						)
  
  
  
  
  					def 							UpperCamelCase_						( self :					List[Any]      ,_lowerCAmelCase :					List[Any]      ,_lowerCAmelCase :					str=True      ,*_lowerCAmelCase :					int      ,**_lowerCAmelCase :					List[str]						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     posixpath.join(self.local_root_dir      ,self._strip_protocol(_lowerCAmelCase						)						)
  							__snake_case		       =     self._fs.ls(_lowerCAmelCase      ,detail=_lowerCAmelCase      ,*_lowerCAmelCase      ,**_lowerCAmelCase						)
  							if detail:
  									return [{**info, "name": info["name"][len(self.local_root_dir						) :]} for info in out]
  							else:
  									return [name[len(self.local_root_dir						) :] for name in out]
  
  
  
  
  					def 							UpperCamelCase_						( self :					List[str]      ,_lowerCAmelCase :					Any      ,*_lowerCAmelCase :					Any      ,**_lowerCAmelCase :					str						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     posixpath.join(self.local_root_dir      ,self._strip_protocol(_lowerCAmelCase						)						)
  							__snake_case		       =     dict(self._fs.info(_lowerCAmelCase      ,*_lowerCAmelCase      ,**_lowerCAmelCase						)						)
  							__snake_case		       =     out["name"][len(self.local_root_dir						) :]
  							return out
  
  
  
  
  					def 							UpperCamelCase_						( self :					Tuple      ,_lowerCAmelCase :					Optional[int]      ,_lowerCAmelCase :					Optional[Any]      ,*_lowerCAmelCase :					int      ,**_lowerCAmelCase :					Optional[int]						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     posixpath.join(self.local_root_dir      ,self._strip_protocol(_lowerCAmelCase						)						)
  							__snake_case		       =     posixpath.join(self.local_root_dir      ,self._strip_protocol(_lowerCAmelCase						)						)
  							return self._fs.cp_file(_lowerCAmelCase      ,_lowerCAmelCase      ,*_lowerCAmelCase      ,**_lowerCAmelCase						)
  
  
  
  
  					def 							UpperCamelCase_						( self :					Union[str, Any]      ,_lowerCAmelCase :					int      ,*_lowerCAmelCase :					List[Any]      ,**_lowerCAmelCase :					int						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     posixpath.join(self.local_root_dir      ,self._strip_protocol(_lowerCAmelCase						)						)
  							return self._fs.rm_file(_lowerCAmelCase      ,*_lowerCAmelCase      ,**_lowerCAmelCase						)
  
  
  
  
  					def 							UpperCamelCase_						( self :					Optional[Any]      ,_lowerCAmelCase :					str      ,*_lowerCAmelCase :					Optional[int]      ,**_lowerCAmelCase :					int						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     posixpath.join(self.local_root_dir      ,self._strip_protocol(_lowerCAmelCase						)						)
  							return self._fs.rm(_lowerCAmelCase      ,*_lowerCAmelCase      ,**_lowerCAmelCase						)
  
  
  
  
  					def 							UpperCamelCase_						( self :					int      ,_lowerCAmelCase :					Optional[int]      ,*_lowerCAmelCase :					str      ,**_lowerCAmelCase :					Optional[Any]						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     posixpath.join(self.local_root_dir      ,self._strip_protocol(_lowerCAmelCase						)						)
  							return self._fs._open(_lowerCAmelCase      ,*_lowerCAmelCase      ,**_lowerCAmelCase						)
  
  
  
  
  					def 							UpperCamelCase_						( self :					Union[str, Any]      ,_lowerCAmelCase :					Tuple						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     posixpath.join(self.local_root_dir      ,self._strip_protocol(_lowerCAmelCase						)						)
  							return self._fs.created(_lowerCAmelCase						)
  
  
  
  
  					def 							UpperCamelCase_						( self :					Union[str, Any]      ,_lowerCAmelCase :					int						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     posixpath.join(self.local_root_dir      ,self._strip_protocol(_lowerCAmelCase						)						)
  							return self._fs.modified(_lowerCAmelCase						)
  
  
  
  
  
  
  
  					@classmethod
  					def 							UpperCamelCase_						( cls :					Dict      ,_lowerCAmelCase :					Dict						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     stringify_path(_lowerCAmelCase						)
  							if path.startswith("mock://"						):
  									__snake_case		       =     path[7:]
  							return path
  
  
  
  
  class 					UpperCamelCase	(     snake_case__      ):
  					__UpperCamelCase						=   """tmp"""
  					__UpperCamelCase						=   None
  
  
  
  
  					def __init__( self :					int      ,*_lowerCAmelCase :					Tuple      ,**_lowerCAmelCase :					Union[str, Any]						):
  
  
  							"""simple docstring"""
  
  
  
  
  							assert self.tmp_dir is not None, "TmpDirFileSystem.tmp_dir is not set"
  							super().__init__(*_lowerCAmelCase      ,**_lowerCAmelCase      ,local_root_dir=self.tmp_dir      ,auto_mkdir=_lowerCAmelCase						)
  
  
  
  
  
  
  
  					@classmethod
  					def 							UpperCamelCase_						( cls :					int      ,_lowerCAmelCase :					str						):
  
  
  							"""simple docstring"""
  
  
  
  
  							__snake_case		       =     stringify_path(_lowerCAmelCase						)
  							if path.startswith("tmp://"						):
  									__snake_case		       =     path[6:]
  							return path
  
  
  
  
  @pytest.fixture
  def 							_lowerCamelCase(				)  ->   str:
  		__snake_case		       =     MockFileSystem
  		__snake_case		       =     TmpDirFileSystem
  		yield
  		del _fsspec_registry["mock"]
  		del _fsspec_registry["tmp"]
  
  
  
  @pytest.fixture
  def 							_lowerCamelCase(				__snake_case						,						__snake_case	)  ->   Dict:
  		__snake_case		       =     tmp_path_factory.mktemp("mockfs"	)
  		return MockFileSystem(local_root_dir=__snake_case						,						auto_mkdir=__snake_case	)
  
  
  
  
  
  @pytest.fixture
  def 							_lowerCamelCase(				__snake_case						,						__snake_case	)  ->   List[Any]:
  		__snake_case		       =     tmp_path_factory.mktemp("tmpfs"	)
  		with patch.object(__snake_case						,						"tmp_dir"						,						__snake_case	):
  				yield TmpDirFileSystem()
  
  
  
  
  
  