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
  
  
  snake_case_    						=				os.path.expanduser(
      os.getenv('''HF_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''huggingface'''))
  )
  snake_case_    						=				os.path.join(hf_cache_home, '''accelerate''')
  snake_case_    						=				os.path.join(cache_dir, '''default_config.yaml''')
  snake_case_    						=				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):
         snake_case_    						=				default_yaml_config_file
  else:
         snake_case_    						=				default_json_config_file
  
  def 			snake_case__    (					SCREAMING_SNAKE_CASE_	:					Optional[int]    ):
  
  
  
       '''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:
            lowercase__					:     Tuple   = 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
                 ):
                      lowercase__					:     int   = ClusterConfig
                 else:
                      lowercase__					:     List[str]   = 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
                 ):
                      lowercase__					:     Any   = ClusterConfig
                 else:
                      lowercase__					:     int   = SageMakerConfig
                 return config_class.from_yaml_file(yaml_file=SCREAMING_SNAKE_CASE_    )
  
  
  @dataclass
  class    SCREAMING_SNAKE_CASE__      :
      __lowerCamelCase		: ComputeEnvironment
      __lowerCamelCase		: Union[DistributedType, SageMakerDistributedType]
      __lowerCamelCase		: str
      __lowerCamelCase		: bool
  
  
  
  
  
      def    snake_case_       (   self):
           lowercase__					:     Optional[int]   = 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):
                     lowercase__					:     Any   = value.value
                if isinstance(a		,     a) and not bool(a):
                     lowercase__					:     Optional[Any]   = None
           lowercase__					:     List[Any]   = {k: v for k, v in result.items() if v is not None}
           return result
  
  
  
  
  
      @classmethod
      def    snake_case_       (   cls		,     a=None):
           lowercase__					:     Dict   = default_json_config_file if json_file is None else json_file
           with open(a		,     'r'		,     encoding='utf-8') as f:
                lowercase__					:     Union[str, Any]   = json.load(a)
           if "compute_environment" not in config_dict:
                lowercase__					:     Tuple   = ComputeEnvironment.LOCAL_MACHINE
           if "mixed_precision" not in config_dict:
                lowercase__					:     Dict   = '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.
                lowercase__					:     str   = config_dict.pop('dynamo_backend')
                lowercase__					:     Optional[int]   = {} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
           if "use_cpu" not in config_dict:
                lowercase__					:     Tuple   = False
           return cls(**a)
  
  
  
  
  
      def    snake_case_       (   self		,     a):
           with open(a		,     'w'		,     encoding='utf-8') as f:
                lowercase__					:     int   = json.dumps(self.to_dict()		,     indent=2		,     sort_keys=a) + '\n'
                f.write(a)
  
  
  
  
  
      @classmethod
      def    snake_case_       (   cls		,     a=None):
           lowercase__					:     Optional[Any]   = default_yaml_config_file if yaml_file is None else yaml_file
           with open(a		,     'r'		,     encoding='utf-8') as f:
                lowercase__					:     str   = yaml.safe_load(a)
           if "compute_environment" not in config_dict:
                lowercase__					:     str   = ComputeEnvironment.LOCAL_MACHINE
  
           if "mixed_precision" not in config_dict:
                lowercase__					:     List[str]   = '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"]:
                lowercase__					:     Optional[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.
                lowercase__					:     List[str]   = config_dict.pop('dynamo_backend')
                lowercase__					:     Optional[int]   = {} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
           if "use_cpu" not in config_dict:
                lowercase__					:     Union[str, Any]   = False
           return cls(**a)
  
  
  
  
  
      def    snake_case_       (   self		,     a):
           with open(a		,     'w'		,     encoding='utf-8') as f:
                yaml.safe_dump(self.to_dict()		,     a)
  
  
  
  
  
      def    snake_case_       (   self):
           if isinstance(self.compute_environment		,     a):
                lowercase__					:     Dict   = ComputeEnvironment(self.compute_environment)
           if isinstance(self.distributed_type		,     a):
                if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                     lowercase__					:     str   = SageMakerDistributedType(self.distributed_type)
                else:
                     lowercase__					:     Union[str, Any]   = DistributedType(self.distributed_type)
           if self.dynamo_config is None:
                lowercase__					:     Optional[Any]   = {}
  
  
  
  @dataclass
  class    SCREAMING_SNAKE_CASE__      (__snake_case  ):
      __lowerCamelCase		: int
      __lowerCamelCase		: int														=  0
      __lowerCamelCase		: int														=  1
      __lowerCamelCase		: Optional[str]														=  None
      __lowerCamelCase		: Optional[str]														=  None
      __lowerCamelCase		: Optional[int]														=  None
      __lowerCamelCase		: Optional[str]														=  "static"
      __lowerCamelCase		: Optional[bool]														=  False
      __lowerCamelCase		: str														=  "main"
  
      # args for deepspeed_plugin
      __lowerCamelCase		: dict														=  None
      # args for fsdp
      __lowerCamelCase		: dict														=  None
      # args for megatron_lm
      __lowerCamelCase		: dict														=  None
      # args for ipex
      __lowerCamelCase		: dict														=  None
      # args for TPU
      __lowerCamelCase		: bool														=  False
  
      # args for TPU pods
      __lowerCamelCase		: str														=  None
      __lowerCamelCase		: str														=  None
      __lowerCamelCase		: bool														=  False
      __lowerCamelCase		: bool														=  False
      __lowerCamelCase		: str														=  None
      __lowerCamelCase		: List[str]														=  None
      __lowerCamelCase		: List[str]														=  None
      __lowerCamelCase		: List[str]														=  None
  
      # args for dynamo
      __lowerCamelCase		: dict														=  None
  
  
  
  
  
      def    snake_case_       (   self):
           if self.deepspeed_config is None:
                lowercase__					:     Dict   = {}
           if self.fsdp_config is None:
                lowercase__					:     Tuple   = {}
           if self.megatron_lm_config is None:
                lowercase__					:     Optional[int]   = {}
           if self.ipex_config is None:
                lowercase__					:     Optional[Any]   = {}
           return super().__post_init__()
  
  
  
  @dataclass
  class    SCREAMING_SNAKE_CASE__      (__snake_case  ):
      __lowerCamelCase		: str
      __lowerCamelCase		: str
      __lowerCamelCase		: Optional[str]														=  None
      __lowerCamelCase		: Optional[str]														=  None
      __lowerCamelCase		: str														=  "us-east-1"
      __lowerCamelCase		: int														=  1
      __lowerCamelCase		: str														=  "all"
      __lowerCamelCase		: str														=  f'''accelerate-sagemaker-{num_machines}'''
      __lowerCamelCase		: str														=  SAGEMAKER_PYTORCH_VERSION
      __lowerCamelCase		: str														=  SAGEMAKER_TRANSFORMERS_VERSION
      __lowerCamelCase		: str														=  SAGEMAKER_PYTHON_VERSION
      __lowerCamelCase		: str														=  None
      __lowerCamelCase		: str														=  None
      __lowerCamelCase		: dict														=  None
      __lowerCamelCase		: dict														=  None
  
  
style_context: 
  
  from typing import TYPE_CHECKING
  
  from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
  
  
  snake_case_    						=				{
      '''configuration_donut_swin''': ['''DONUT_SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DonutSwinConfig'''],
      '''processing_donut''': ['''DonutProcessor'''],
  }
  
  try:
         if not is_torch_available():
                raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
         pass
  else:
         snake_case_    						=				[
             '''DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''',
             '''DonutSwinModel''',
             '''DonutSwinPreTrainedModel''',
         ]
  
  try:
         if not is_vision_available():
                raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
         pass
  else:
         snake_case_    						=				['''DonutFeatureExtractor''']
         snake_case_    						=				['''DonutImageProcessor''']
  
  
  if TYPE_CHECKING:
         from .configuration_donut_swin import DONUT_SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, DonutSwinConfig
         from .processing_donut import DonutProcessor
  
         try:
                if not is_torch_available():
                       raise OptionalDependencyNotAvailable()
         except OptionalDependencyNotAvailable:
                pass
         else:
                from .modeling_donut_swin import (
                    DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
                    DonutSwinModel,
                    DonutSwinPreTrainedModel,
                )
  
         try:
                if not is_vision_available():
                       raise OptionalDependencyNotAvailable()
         except OptionalDependencyNotAvailable:
                pass
         else:
                from .feature_extraction_donut import DonutFeatureExtractor
                from .image_processing_donut import DonutImageProcessor
  
  else:
         import sys
  
         snake_case_    						=				_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
  
  