

# 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     						=      os.path.expanduser(
    os.getenv('''HF_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''huggingface'''))
)
__A     						=      os.path.join(hf_cache_home, '''accelerate''')
__A     						=      os.path.join(cache_dir, '''default_config.yaml''')
__A     						=      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     						=      default_yaml_config_file
else:
 __A     						=      default_json_config_file



def  snake_case_(_UpperCamelCase	)				->      Optional[int]:



  """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:
    _snake_case		=				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
      ):
        _snake_case		=				ClusterConfig
      else:
        _snake_case		=				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
      ):
        _snake_case		=				ClusterConfig
      else:
        _snake_case		=				SageMakerConfig
      return config_class.from_yaml_file(yaml_file=_UpperCamelCase	)



@dataclass
class     lowercase_       :
      UpperCamelCase_     :						ComputeEnvironment
      UpperCamelCase_     :						Union[DistributedType, SageMakerDistributedType]
      UpperCamelCase_     :						str
      UpperCamelCase_     :						bool



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



      @classmethod
      def 		UpperCamelCase_						(     cls :							Tuple     ,   A__ :							List[Any]=None						)       ->	Dict:
        _snake_case		=				default_json_config_file if json_file is None else json_file
        with open(A__     ,   '''r'''     ,   encoding='''utf-8'''						) as f:
          _snake_case		=				json.load(A__						)
        if "compute_environment" not in config_dict:
          _snake_case		=				ComputeEnvironment.LOCAL_MACHINE
        if "mixed_precision" not in config_dict:
          _snake_case		=				'''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.
          _snake_case		=				config_dict.pop('''dynamo_backend'''						)
          _snake_case		=				{} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
        if "use_cpu" not in config_dict:
          _snake_case		=				False
        return cls(**A__						)



      def 		UpperCamelCase_						(     self :							int     ,   A__ :							Optional[Any]						)       ->	Dict:
        with open(A__     ,   '''w'''     ,   encoding='''utf-8'''						) as f:
          _snake_case		=				json.dumps(self.to_dict()     ,   indent=2     ,   sort_keys=A__						) + '''\n'''
          f.write(A__						)



      @classmethod
      def 		UpperCamelCase_						(     cls :							int     ,   A__ :							List[Any]=None						)       ->	List[str]:
        _snake_case		=				default_yaml_config_file if yaml_file is None else yaml_file
        with open(A__     ,   '''r'''     ,   encoding='''utf-8'''						) as f:
          _snake_case		=				yaml.safe_load(A__						)
        if "compute_environment" not in config_dict:
          _snake_case		=				ComputeEnvironment.LOCAL_MACHINE

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



      def 		UpperCamelCase_						(     self :							Dict     ,   A__ :							str						)       ->	Optional[int]:
        with open(A__     ,   '''w'''     ,   encoding='''utf-8'''						) as f:
          yaml.safe_dump(self.to_dict()     ,   A__						)







      def 		UpperCamelCase_						(     self :							List[str]						)       ->	int:
        if isinstance(self.compute_environment     ,   A__						):
          _snake_case		=				ComputeEnvironment(self.compute_environment						)
        if isinstance(self.distributed_type     ,   A__						):
          if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
            _snake_case		=				SageMakerDistributedType(self.distributed_type						)
          else:
            _snake_case		=				DistributedType(self.distributed_type						)
        if self.dynamo_config is None:
          _snake_case		=				{}



@dataclass
class     lowercase_       (    __lowercase	):
      UpperCamelCase_     :						int
      UpperCamelCase_     :						int		 =							0
      UpperCamelCase_     :						int		 =							1
      UpperCamelCase_     :						Optional[str]		 =							None
      UpperCamelCase_     :						Optional[str]		 =							None
      UpperCamelCase_     :						Optional[int]		 =							None
      UpperCamelCase_     :						Optional[str]		 =							"static"
      UpperCamelCase_     :						Optional[bool]		 =							False
      UpperCamelCase_     :						str		 =							"main"

      # args for deepspeed_plugin
      UpperCamelCase_     :						dict		 =							None
      # args for fsdp
      UpperCamelCase_     :						dict		 =							None
      # args for megatron_lm
      UpperCamelCase_     :						dict		 =							None
      # args for ipex
      UpperCamelCase_     :						dict		 =							None
      # args for TPU
      UpperCamelCase_     :						bool		 =							False

      # args for TPU pods
      UpperCamelCase_     :						str		 =							None
      UpperCamelCase_     :						str		 =							None
      UpperCamelCase_     :						bool		 =							False
      UpperCamelCase_     :						bool		 =							False
      UpperCamelCase_     :						str		 =							None
      UpperCamelCase_     :						List[str]		 =							None
      UpperCamelCase_     :						List[str]		 =							None
      UpperCamelCase_     :						List[str]		 =							None

      # args for dynamo
      UpperCamelCase_     :						dict		 =							None



      def 		UpperCamelCase_						(     self :							Optional[Any]						)       ->	List[Any]:
        if self.deepspeed_config is None:
          _snake_case		=				{}
        if self.fsdp_config is None:
          _snake_case		=				{}
        if self.megatron_lm_config is None:
          _snake_case		=				{}
        if self.ipex_config is None:
          _snake_case		=				{}
        return super().__post_init__()



@dataclass
class     lowercase_       (    __lowercase	):
      UpperCamelCase_     :						str
      UpperCamelCase_     :						str
      UpperCamelCase_     :						Optional[str]		 =							None
      UpperCamelCase_     :						Optional[str]		 =							None
      UpperCamelCase_     :						str		 =							"us-east-1"
      UpperCamelCase_     :						int		 =							1
      UpperCamelCase_     :						str		 =							"all"
      UpperCamelCase_     :						str		 =							F'accelerate-sagemaker-{num_machines}'
      UpperCamelCase_     :						str		 =							SAGEMAKER_PYTORCH_VERSION
      UpperCamelCase_     :						str		 =							SAGEMAKER_TRANSFORMERS_VERSION
      UpperCamelCase_     :						str		 =							SAGEMAKER_PYTHON_VERSION
      UpperCamelCase_     :						str		 =							None
      UpperCamelCase_     :						str		 =							None
      UpperCamelCase_     :						dict		 =							None
      UpperCamelCase_     :						dict		 =							None




from __future__ import annotations



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase	)				->      int:



  """simple docstring"""






  assert n > 1 and a > 0 and greatest_common_divisor(_UpperCamelCase					,			_UpperCamelCase	) == 1
  ((_snake_case),	(_snake_case),	(_snake_case))		=				extended_gcd(_UpperCamelCase					,			_UpperCamelCase	)  # Implemented below
  _snake_case		=				(b * s) % n
  return x



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase	)				->      int:



  """simple docstring"""






  ((_snake_case),	(_snake_case))		=				extended_euclid(_UpperCamelCase					,			_UpperCamelCase	)  # Implemented below
  if b < 0:
    _snake_case		=				(b % n + n) % n
  return b



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase	)				->      int:



  """simple docstring"""






  _snake_case		=				invert_modulo(_UpperCamelCase					,			_UpperCamelCase	)
  _snake_case		=				(b * s) % n
  return x



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase	)				->      tuple[int, int, int]:



  """simple docstring"""






  assert a >= 0 and b >= 0

  if b == 0:
    _snake_case,	_snake_case,	_snake_case		=				a, 1, 0
  else:
    ((_snake_case),	(_snake_case),	(_snake_case))		=				extended_gcd(_UpperCamelCase					,			a % b	)
    _snake_case		=				q
    _snake_case		=				p - q * (a // b)

  assert a % d == 0 and b % d == 0
  assert d == a * x + b * y

  return (d, x, y)



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase	)				->      tuple[int, int]:



  """simple docstring"""






  if b == 0:
    return (1, 0)
  ((_snake_case),	(_snake_case))		=				extended_euclid(_UpperCamelCase					,			a % b	)
  _snake_case		=				a // b
  return (y, x - k * y)



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase	)				->      int:



  """simple docstring"""






  if a < b:
    _snake_case,	_snake_case		=				b, a

  while a % b != 0:
    _snake_case,	_snake_case		=				b, a % b

  return b


if __name__ == "__main__":
 from doctest import testmod

 testmod(name='''modular_division''', verbose=True)
 testmod(name='''modular_division2''', verbose=True)
 testmod(name='''invert_modulo''', verbose=True)
 testmod(name='''extended_gcd''', verbose=True)
 testmod(name='''extended_euclid''', verbose=True)
 testmod(name='''greatest_common_divisor''', verbose=True)

