






# 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 							UpperCAmelCase   ( _lowercase   ):


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

@dataclass
class        snake_case_				:







   """simple docstring"""



   __lowerCAmelCase  =    42
   __lowerCAmelCase  =    42
   __lowerCAmelCase  =    42
   __lowerCAmelCase  =    42

   def       SCREAMING_SNAKE_CASE__					(     self:						int						)	->		str:


       """simple docstring"""



       _lowercase     			=						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						):
               _lowercase     			=						value.value
           if isinstance(__lowerCAmelCase ,							__lowerCAmelCase						) and not bool(__lowerCAmelCase						):
               _lowercase     			=						None
       _lowercase     			=						{k: v for k, v in result.items() if v is not None}
       return result

   @classmethod
   def       SCREAMING_SNAKE_CASE__					(     cls:						Optional[int] ,							snake_case__:						Tuple=None						)	->		Union[str, Any]:


       """simple docstring"""



       _lowercase     			=						default_json_config_file if json_file is None else json_file
       with open(__lowerCAmelCase ,							'r' ,							encoding='utf-8'						) as f:
           _lowercase     			=						json.load(__lowerCAmelCase						)
       if "compute_environment" not in config_dict:
           _lowercase     			=						ComputeEnvironment.LOCAL_MACHINE
       if "mixed_precision" not in config_dict:
           _lowercase     			=						'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     			=						config_dict.pop('dynamo_backend'						)
           _lowercase     			=						{} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
       if "use_cpu" not in config_dict:
           _lowercase     			=						False
       return cls(**__lowerCAmelCase						)

   def       SCREAMING_SNAKE_CASE__					(     self:						Optional[int] ,							snake_case__:						List[str]						)	->		Any:


       """simple docstring"""



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

   @classmethod
   def       SCREAMING_SNAKE_CASE__					(     cls:						Optional[int] ,							snake_case__:						List[str]=None						)	->		Optional[int]:


       """simple docstring"""



       _lowercase     			=						default_yaml_config_file if yaml_file is None else yaml_file
       with open(__lowerCAmelCase ,							'r' ,							encoding='utf-8'						) as f:
           _lowercase     			=						yaml.safe_load(__lowerCAmelCase						)
       if "compute_environment" not in config_dict:
           _lowercase     			=						ComputeEnvironment.LOCAL_MACHINE

       if "mixed_precision" not in config_dict:
           _lowercase     			=						'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"]:
           _lowercase     			=						'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     			=						config_dict.pop('dynamo_backend'						)
           _lowercase     			=						{} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
       if "use_cpu" not in config_dict:
           _lowercase     			=						False
       return cls(**__lowerCAmelCase						)

   def       SCREAMING_SNAKE_CASE__					(     self:						int ,							snake_case__:						List[str]						)	->		Optional[int]:


       """simple docstring"""



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

   def       SCREAMING_SNAKE_CASE__					(     self:						int						)	->		int:


       """simple docstring"""



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






@dataclass
class        snake_case_				(							UpperCAmelCase__   ):







   """simple docstring"""



   __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       SCREAMING_SNAKE_CASE__					(     self:						Dict						)	->		Optional[int]:


       """simple docstring"""



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






@dataclass
class        snake_case_				(							UpperCAmelCase__   ):







   """simple docstring"""



   __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





from typing import TYPE_CHECKING

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


A_		:  Any										=  {
    '''configuration_videomae''': ['''VIDEOMAE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''VideoMAEConfig'''],
}

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     A_		:  List[Any]										=  [
         '''VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST''',
         '''VideoMAEForPreTraining''',
         '''VideoMAEModel''',
         '''VideoMAEPreTrainedModel''',
         '''VideoMAEForVideoClassification''',
     ]

try:
     if not is_vision_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     A_		:  str										=  ['''VideoMAEFeatureExtractor''']
     A_		:  Union[str, Any]										=  ['''VideoMAEImageProcessor''']

if TYPE_CHECKING:
     from .configuration_videomae import VIDEOMAE_PRETRAINED_CONFIG_ARCHIVE_MAP, VideoMAEConfig

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_videomae import (
              VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST,
              VideoMAEForPreTraining,
              VideoMAEForVideoClassification,
              VideoMAEModel,
              VideoMAEPreTrainedModel,
          )

     try:
          if not is_vision_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .feature_extraction_videomae import VideoMAEFeatureExtractor
          from .image_processing_videomae import VideoMAEImageProcessor

else:
     import sys

     A_		:  Dict										=  _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)

