
# 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 		_lowerCamelCase       (   _a  ):
  """simple docstring"""




  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 		__magic_name__				:


  """simple docstring"""





  _UpperCamelCase						 = 42
  _UpperCamelCase						 = 42
  _UpperCamelCase						 = 42
  _UpperCamelCase						 = 42


  def     _UpperCAmelCase  (					self		):
    _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(A__	,		A__		):
        _lowerCamelCase      =						value.value
      if isinstance(A__	,		A__		) and not bool(A__		):
        _lowerCamelCase      =						None
    _lowerCamelCase      =						{k: v for k, v in result.items() if v is not None}
    return result


  @classmethod
  def     _UpperCAmelCase  (					cls	,		a__=None		):
    _lowerCamelCase      =						default_json_config_file if json_file is None else json_file
    with open(A__	,		'''r'''	,		encoding='''utf-8'''		) as f:
      _lowerCamelCase      =						json.load(A__		)
    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(**A__		)


  def     _UpperCAmelCase  (					self	,		a__		):
    with open(A__	,		'''w'''	,		encoding='''utf-8'''		) as f:
      _lowerCamelCase      =						json.dumps(self.to_dict()	,		indent=2	,		sort_keys=A__		) + '''\n'''
      f.write(A__		)


  @classmethod
  def     _UpperCAmelCase  (					cls	,		a__=None		):
    _lowerCamelCase      =						default_yaml_config_file if yaml_file is None else yaml_file
    with open(A__	,		'''r'''	,		encoding='''utf-8'''		) as f:
      _lowerCamelCase      =						yaml.safe_load(A__		)
    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''']	,		A__		) 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(**A__		)


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


  def     _UpperCAmelCase  (					self		):
    if isinstance(self.compute_environment	,		A__		):
      _lowerCamelCase      =						ComputeEnvironment(self.compute_environment		)
    if isinstance(self.distributed_type	,		A__		):
      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 		__magic_name__				( __lowercase					):


  """simple docstring"""





  _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		):
    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 		__magic_name__				( __lowercase					):


  """simple docstring"""





  _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







import warnings

from ...utils import logging
from .image_processing_detr import DetrImageProcessor


__A     						=      logging.get_logger(__name__)



class     lowercase_       (    __lowercase	):



      def __init__(     self :							List[str]     ,   *A__ :							Tuple     ,   **A__ :							int						)       ->	None:
        warnings.warn(
            '''The class DetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'''
            ''' Please use DetrImageProcessor instead.'''     ,   A__     ,   )
        super().__init__(*A__     ,   **A__						)

