


"""simple docstring"""







# 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_     :     Dict    		=						os.path.expanduser(
    os.getenv("""HF_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """huggingface"""))
)
lowerCamelCase_     :     Any    		=						os.path.join(hf_cache_home, """accelerate""")
lowerCamelCase_     :     List[Any]    		=						os.path.join(cache_dir, """default_config.yaml""")
lowerCamelCase_     :     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):
       lowerCamelCase_     :     str    		=						default_yaml_config_file
else:
       lowerCamelCase_     :     Any    		=						default_json_config_file
def _A		(		lowercase	):







    """simple docstring"""
    if config_file is not None:
        if not os.path.isfile(lowercase	):
            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(lowercase ,					'''r''' ,					encoding='''utf-8'''	) as f:
        if config_file.endswith('''.json'''	):
            if (
                json.load(lowercase	).get('''compute_environment''' ,					ComputeEnvironment.LOCAL_MACHINE	)
                == ComputeEnvironment.LOCAL_MACHINE
            ):
                a					=ClusterConfig
            else:
                a					=SageMakerConfig
            return config_class.from_json_file(json_file=lowercase	)
        else:
            if (
                yaml.safe_load(lowercase	).get('''compute_environment''' ,					ComputeEnvironment.LOCAL_MACHINE	)
                == ComputeEnvironment.LOCAL_MACHINE
            ):
                a					=ClusterConfig
            else:
                a					=SageMakerConfig
            return config_class.from_yaml_file(yaml_file=lowercase	)






@dataclass
class    __A       :






 """simple docstring"""




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


 def    SCREAMING_SNAKE_CASE							(	self		)      ->  List[Any]:
     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(__A				,					__A		):
             a					=value.value
         if isinstance(__A				,					__A		) and not bool(__A		):
             a					=None
     a					={k: v for k, v in result.items() if v is not None}
     return result


 @classmethod
 def    SCREAMING_SNAKE_CASE							(	cls				,					__A=None		)      ->  List[Any]:
     a					=default_json_config_file if json_file is None else json_file
     with open(__A				,					'''r'''				,					encoding='''utf-8'''		) as f:
         a					=json.load(__A		)
     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(**__A		)


 def    SCREAMING_SNAKE_CASE							(	self				,					__A		)      ->  int:
     with open(__A				,					'''w'''				,					encoding='''utf-8'''		) as f:
         a					=json.dumps(self.to_dict()				,					indent=2				,					sort_keys=__A		) + '''\n'''
         f.write(__A		)


 @classmethod
 def    SCREAMING_SNAKE_CASE							(	cls				,					__A=None		)      ->  List[str]:
     a					=default_yaml_config_file if yaml_file is None else yaml_file
     with open(__A				,					'''r'''				,					encoding='''utf-8'''		) as f:
         a					=yaml.safe_load(__A		)
     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''']				,					__A		) 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(**__A		)


 def    SCREAMING_SNAKE_CASE							(	self				,					__A		)      ->  Optional[Any]:
     with open(__A				,					'''w'''				,					encoding='''utf-8'''		) as f:
         yaml.safe_dump(self.to_dict()				,					__A		)





 def    SCREAMING_SNAKE_CASE							(	self		)      ->  Dict:
     if isinstance(self.compute_environment				,					__A		):
         a					=ComputeEnvironment(self.compute_environment		)
     if isinstance(self.distributed_type				,					__A		):
         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    ):






 """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		)      ->  Optional[Any]:
     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    ):






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



"""simple docstring"""







from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCamelCase_     :     Any    		=						logging.get_logger(__name__)

lowerCamelCase_     :     Tuple    		=						{
    """apple/mobilevitv2-1.0""": """https://huggingface.co/apple/mobilevitv2-1.0/resolve/main/config.json""",
}






class    __A       ( _SCREAMING_SNAKE_CASE    ):






 """simple docstring"""




 __lowerCAmelCase				      =						"mobilevitv2"


 def __init__(	self				,					__A=3				,					__A=256				,					__A=2				,					__A=2.0				,					__A="swish"				,					__A=3				,					__A=32				,					__A=0.1				,					__A=0.02				,					__A=1E-5				,					__A=512				,					__A=[6, 12, 18]				,					__A=0.1				,					__A=255				,					__A=[2, 4, 3]				,					__A=[128, 192, 256]				,					__A=1.0				,					__A=2				,					__A=0.0				,					__A=0.0				,					**__A				,					)      ->  int:
     super().__init__(**__A		)

     a					=num_channels
     a					=image_size
     a					=patch_size
     a					=expand_ratio
     a					=hidden_act
     a					=conv_kernel_size
     a					=output_stride
     a					=initializer_range
     a					=layer_norm_eps
     a					=n_attn_blocks
     a					=base_attn_unit_dims
     a					=width_multiplier
     a					=ffn_multiplier
     a					=ffn_dropout
     a					=attn_dropout
     a					=classifier_dropout_prob

     # decode head attributes for semantic segmentation
     a					=aspp_out_channels
     a					=atrous_rates
     a					=aspp_dropout_prob
     a					=semantic_loss_ignore_index






class    __A       ( _SCREAMING_SNAKE_CASE    ):






 """simple docstring"""




 __lowerCAmelCase				      =						version.parse("1.11"    )


 @property
 def    SCREAMING_SNAKE_CASE							(	self		)      ->  Mapping[str, Mapping[int, str]]:
     return OrderedDict([('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''})]		)


 @property
 def    SCREAMING_SNAKE_CASE							(	self		)      ->  Mapping[str, Mapping[int, str]]:
     if self.task == "image-classification":
         return OrderedDict([('''logits''', {0: '''batch'''})]		)
     else:
         return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})]		)





 @property
 def    SCREAMING_SNAKE_CASE							(	self		)      ->  float:
     return 1E-4