






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



def      _SCREAMING_SNAKE_CASE  (	__lowercase				:     Any      )  -> int:





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







     '''simple docstring'''
     SCREAMING_SNAKE_CASE				  =			42
     SCREAMING_SNAKE_CASE				  =			42
     SCREAMING_SNAKE_CASE				  =			42
     SCREAMING_SNAKE_CASE				  =			42




     def 						lowerCAmelCase_       (			self    :     List[Any]			):


          """simple docstring"""



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




     @classmethod
     def 						lowerCAmelCase_       (			cls    :     Any	,		UpperCamelCase_    :     str=None			):


          """simple docstring"""



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




     def 						lowerCAmelCase_       (			self    :     Any	,		UpperCamelCase_    :     List[str]			):


          """simple docstring"""



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




     @classmethod
     def 						lowerCAmelCase_       (			cls    :     str	,		UpperCamelCase_    :     Dict=None			):


          """simple docstring"""



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




     def 						lowerCAmelCase_       (			self    :     Dict	,		UpperCamelCase_    :     Dict			):


          """simple docstring"""



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





     def 						lowerCAmelCase_       (			self    :     List[str]			):


          """simple docstring"""



          if isinstance(self.compute_environment	,		UpperCamelCase_			):
               __A             =		ComputeEnvironment(self.compute_environment			)
          if isinstance(self.distributed_type	,		UpperCamelCase_			):
               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  __lowercase (		lowercase_					):







     '''simple docstring'''
     SCREAMING_SNAKE_CASE				  =			42
     SCREAMING_SNAKE_CASE				  =			0
     SCREAMING_SNAKE_CASE				  =			1
     SCREAMING_SNAKE_CASE				  =			None
     SCREAMING_SNAKE_CASE				  =			None
     SCREAMING_SNAKE_CASE				  =			None
     SCREAMING_SNAKE_CASE				  =			"static"
     SCREAMING_SNAKE_CASE				  =			False
     SCREAMING_SNAKE_CASE				  =			"main"

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

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

     # args for dynamo
     SCREAMING_SNAKE_CASE				  =			None




     def 						lowerCAmelCase_       (			self    :     str			):


          """simple docstring"""



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







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












def      _SCREAMING_SNAKE_CASE  (	__lowercase				:     list[int]      )  -> list[int]:





    """simple docstring"""

    if len(__lowercase      ) > 1:
        __A             =		len(__lowercase      ) // 2  # Finds the middle of the array
        __A             =		arr[
            :middle_length
        ]  # Creates an array of the elements in the first half.
        __A             =		arr[
            middle_length:
        ]  # Creates an array of the elements in the second half.
        __A             =		len(__lowercase      )
        __A             =		len(__lowercase      )
        merge(__lowercase      )  # Starts sorting the left.
        merge(__lowercase      )  # Starts sorting the right
        __A             =		0  # Left Counter
        __A             =		0  # Right Counter
        __A             =		0  # Position Counter
        while (
            left_index < left_size and right_index < right_size
        ):  # Runs until the lowers size of the left and right are sorted.
            if left_array[left_index] < right_array[right_index]:
                __A             =		left_array[left_index]
                left_index += 1
            else:
                __A             =		right_array[right_index]
                right_index += 1
            index += 1
        while (
            left_index < left_size
        ):  # Adds the left over elements in the left half of the array
            __A             =		left_array[left_index]
            left_index += 1
            index += 1
        while (
            right_index < right_size
        ):  # Adds the left over elements in the right half of the array
            __A             =		right_array[right_index]
            right_index += 1
            index += 1
    return arr


if __name__ == "__main__":
  import doctest

  doctest.testmod()




