


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


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






def 						_A					(lowerCAmelCase__	:Any		) ->	List[str]:




     '''simple docstring'''



     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         =				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         =				ClusterConfig
               else:
                    _a         =				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         =				ClusterConfig
               else:
                    _a         =				SageMakerConfig
               return config_class.from_yaml_file(yaml_file=lowerCAmelCase__		)




@dataclass
class 			a  :
 _lowerCAmelCase			       =						42
 _lowerCAmelCase			       =						42
 _lowerCAmelCase			       =						42
 _lowerCAmelCase			       =						42
 def 				__UpperCAmelCase		(			self    )       ->				Dict:
      _a         =				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(__magic_name__   ,					__magic_name__    ):
                _a         =				value.value
           if isinstance(__magic_name__   ,					__magic_name__    ) and not bool(__magic_name__    ):
                _a         =				None
      _a         =				{k: v for k, v in result.items() if v is not None}
      return result
 @classmethod
 def 				__UpperCAmelCase		(			cls   ,					__magic_name__=None    )       ->				Union[str, Any]:
      _a         =				default_json_config_file if json_file is None else json_file
      with open(__magic_name__   ,					'r'   ,					encoding='utf-8'    ) as f:
           _a         =				json.load(__magic_name__    )
      if "compute_environment" not in config_dict:
           _a         =				ComputeEnvironment.LOCAL_MACHINE
      if "mixed_precision" not in config_dict:
           _a         =				'''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         =				config_dict.pop('dynamo_backend'    )
           _a         =				{} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
      if "use_cpu" not in config_dict:
           _a         =				False
      return cls(**__magic_name__    )
 def 				__UpperCAmelCase		(			self   ,					__magic_name__    )       ->				Dict:







      with open(__magic_name__   ,					'w'   ,					encoding='utf-8'    ) as f:
           _a         =				json.dumps(self.to_dict()   ,					indent=2   ,					sort_keys=__magic_name__    ) + '''\n'''
           f.write(__magic_name__    )
 @classmethod
 def 				__UpperCAmelCase		(			cls   ,					__magic_name__=None    )       ->				Optional[int]:
      _a         =				default_yaml_config_file if yaml_file is None else yaml_file
      with open(__magic_name__   ,					'r'   ,					encoding='utf-8'    ) as f:
           _a         =				yaml.safe_load(__magic_name__    )
      if "compute_environment" not in config_dict:
           _a         =				ComputeEnvironment.LOCAL_MACHINE

      if "mixed_precision" not in config_dict:
           _a         =				'''fp16''' if ('''fp16''' in config_dict and config_dict['''fp16''']) else None
      if isinstance(config_dict['mixed_precision']   ,					__magic_name__    ) and not config_dict["mixed_precision"]:
           _a         =				'''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         =				config_dict.pop('dynamo_backend'    )
           _a         =				{} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
      if "use_cpu" not in config_dict:
           _a         =				False
      return cls(**__magic_name__    )
 def 				__UpperCAmelCase		(			self   ,					__magic_name__    )       ->				Optional[Any]:







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




 def 				__UpperCAmelCase		(			self    )       ->				List[str]:







      if isinstance(self.compute_environment   ,					__magic_name__    ):
           _a         =				ComputeEnvironment(self.compute_environment    )
      if isinstance(self.distributed_type   ,					__magic_name__    ):
           if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                _a         =				SageMakerDistributedType(self.distributed_type    )
           else:
                _a         =				DistributedType(self.distributed_type    )
      if self.dynamo_config is None:
           _a         =				{}





@dataclass
class 			a  (  _SCREAMING_SNAKE_CASE							):
 _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 				__UpperCAmelCase		(			self    )       ->				int:







      if self.deepspeed_config is None:
           _a         =				{}
      if self.fsdp_config is None:
           _a         =				{}
      if self.megatron_lm_config is None:
           _a         =				{}
      if self.ipex_config is None:
           _a         =				{}
      return super().__post_init__()





@dataclass
class 			a  (  _SCREAMING_SNAKE_CASE							):
 _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"""





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


UpperCamelCase_						:					Tuple      				=			{"""configuration_detr""": ["""DETR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DetrConfig""", """DetrOnnxConfig"""]}

try:
    if not is_vision_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    UpperCamelCase_						:					Tuple      				=			["""DetrFeatureExtractor"""]
    UpperCamelCase_						:					int      				=			["""DetrImageProcessor"""]

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    UpperCamelCase_						:					Dict      				=			[
        """DETR_PRETRAINED_MODEL_ARCHIVE_LIST""",
        """DetrForObjectDetection""",
        """DetrForSegmentation""",
        """DetrModel""",
        """DetrPreTrainedModel""",
    ]


if TYPE_CHECKING:
    from .configuration_detr import DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, DetrConfig, DetrOnnxConfig

    try:
        if not is_vision_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .feature_extraction_detr import DetrFeatureExtractor
        from .image_processing_detr import DetrImageProcessor

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_detr import (
            DETR_PRETRAINED_MODEL_ARCHIVE_LIST,
            DetrForObjectDetection,
            DetrForSegmentation,
            DetrModel,
            DetrPreTrainedModel,
        )

else:
    import sys

    UpperCamelCase_						:					List[str]      				=			_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)


