


# 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


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






def 				UpperCamelCase      (			__magic_name__  :							Union[str, Any]  )     ->						Tuple:
		"""simple docstring"""




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



@dataclass
class 							A					:
					'''simple docstring'''






					A__    =				42
					A__    =				42
					A__    =				42
					A__    =				42

					def 						lowerCamelCase__  (self					:		List[str]	)		->     Any:




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

					@classmethod
					def 						lowerCamelCase__  (cls					:		int   ,      _UpperCAmelCase					:		Union[str, Any]=None	)		->     Optional[int]:




							"""simple docstring"""


							lowercase__      =	default_json_config_file if json_file is None else json_file
							with open(_UpperCAmelCase   ,      """r"""   ,      encoding="""utf-8"""	) as f:
									lowercase__      =	json.load(_UpperCAmelCase	)
							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(**_UpperCAmelCase	)

					def 						lowerCamelCase__  (self					:		int   ,      _UpperCAmelCase					:		List[str]	)		->     Tuple:




							"""simple docstring"""


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

					@classmethod
					def 						lowerCamelCase__  (cls					:		Optional[int]   ,      _UpperCAmelCase					:		Optional[Any]=None	)		->     Optional[int]:




							"""simple docstring"""


							lowercase__      =	default_yaml_config_file if yaml_file is None else yaml_file
							with open(_UpperCAmelCase   ,      """r"""   ,      encoding="""utf-8"""	) as f:
									lowercase__      =	yaml.safe_load(_UpperCAmelCase	)
							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"""]   ,      _UpperCAmelCase	) 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(**_UpperCAmelCase	)

					def 						lowerCamelCase__  (self					:		Optional[int]   ,      _UpperCAmelCase					:		int	)		->     List[Any]:




							"""simple docstring"""


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


					def 						lowerCamelCase__  (self					:		Dict	)		->     List[Any]:




							"""simple docstring"""


							if isinstance(self.compute_environment   ,      _UpperCAmelCase	):
									lowercase__      =	ComputeEnvironment(self.compute_environment	)
							if isinstance(self.distributed_type   ,      _UpperCAmelCase	):
									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 							A					( UpperCAmelCase__							):
					'''simple docstring'''






					A__    =				42
					A__    =				0
					A__    =				1
					A__    =				None
					A__    =				None
					A__    =				None
					A__    =				'''static'''
					A__    =				False
					A__    =				'''main'''

					# args for deepspeed_plugin
					A__    =				None
					# args for fsdp
					A__    =				None
					# args for megatron_lm
					A__    =				None
					# args for ipex
					A__    =				None
					# args for TPU
					A__    =				False

					# args for TPU pods
					A__    =				None
					A__    =				None
					A__    =				False
					A__    =				False
					A__    =				None
					A__    =				None
					A__    =				None
					A__    =				None

					# args for dynamo
					A__    =				None

					def 						lowerCamelCase__  (self					:		Tuple	)		->     List[str]:




							"""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 							A					( UpperCAmelCase__							):
					'''simple docstring'''






					A__    =				42
					A__    =				42
					A__    =				None
					A__    =				None
					A__    =				'''us-east-1'''
					A__    =				1
					A__    =				'''all'''
					A__    =				F"""accelerate-sagemaker-{num_machines}"""
					A__    =				SAGEMAKER_PYTORCH_VERSION
					A__    =				SAGEMAKER_TRANSFORMERS_VERSION
					A__    =				SAGEMAKER_PYTHON_VERSION
					A__    =				None
					A__    =				None
					A__    =				None
					A__    =				None





import warnings

from ...utils import logging
from .image_processing_mobilenet_va import MobileNetVaImageProcessor


A :	Optional[Any]												=     logging.get_logger(__name__)



class 							A					( UpperCAmelCase__							):
					'''simple docstring'''






					def __init__(self					:		Optional[int]   ,      *_UpperCAmelCase					:		Union[str, Any]   ,      **_UpperCAmelCase					:		Any	)		->     None:




							"""simple docstring"""


							warnings.warn(
							    """The class MobileNetV1FeatureExtractor is deprecated and will be removed in version 5 of Transformers."""
							    """ Please use MobileNetV1ImageProcessor instead."""   ,      _UpperCAmelCase   ,      )
							super().__init__(*_UpperCAmelCase   ,      **_UpperCAmelCase	)

