


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






def  _UpperCAmelCase						( __lowerCamelCase							)		->List[str]:


 '''simple docstring'''
 if config_file is not None:
  if not os.path.isfile(__lowerCamelCase							):
   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 :			Any							=   default_config_file
 with open(__lowerCamelCase			,  '''r'''			,  encoding='''utf-8'''							) as f:
  if config_file.endswith('''.json'''							):
   if (
       json.load(__lowerCamelCase							).get('''compute_environment'''			,  ComputeEnvironment.LOCAL_MACHINE							)
       == ComputeEnvironment.LOCAL_MACHINE
   ):
    snake_case :			Optional[Any]							=   ClusterConfig
   else:
    snake_case :			Optional[Any]							=   SageMakerConfig
   return config_class.from_json_file(json_file=__lowerCamelCase							)
  else:
   if (
       yaml.safe_load(__lowerCamelCase							).get('''compute_environment'''			,  ComputeEnvironment.LOCAL_MACHINE							)
       == ComputeEnvironment.LOCAL_MACHINE
   ):
    snake_case :			Optional[int]							=   ClusterConfig
   else:
    snake_case :			Any							=   SageMakerConfig
   return config_class.from_yaml_file(yaml_file=__lowerCamelCase							)

@dataclass
class   lowerCamelCase						:
       _UpperCamelCase     		=   42
       _UpperCamelCase     		=   42
       _UpperCamelCase     		=   42
       _UpperCamelCase     		=   42

       def 					UpperCAmelCase					(      self       ):






        '''simple docstring'''






        snake_case :			int							=   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 :			List[str]							=   value.value
         if isinstance(a__						,    a__       ) and not bool(a__       ):
          snake_case :			Optional[Any]							=   None
        snake_case :			Tuple							=   {k: v for k, v in result.items() if v is not None}
        return result

       @classmethod
       def 					UpperCAmelCase					(      cls						,    a__=None       ):






        '''simple docstring'''






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

       def 					UpperCAmelCase					(      self						,    a__       ):






        '''simple docstring'''






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

       @classmethod
       def 					UpperCAmelCase					(      cls						,    a__=None       ):






        '''simple docstring'''






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

        if "mixed_precision" not in config_dict:
         snake_case :			int							=   '''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 :			int							=   '''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 :			Optional[Any]							=   config_dict.pop('''dynamo_backend'''       )
         snake_case :			Tuple							=   {} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
        if "use_cpu" not in config_dict:
         snake_case :			List[str]							=   False
        return cls(**a__       )

       def 					UpperCAmelCase					(      self						,    a__       ):






        '''simple docstring'''






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



       def 					UpperCAmelCase					(      self       ):






        '''simple docstring'''






        if isinstance(self.compute_environment						,    a__       ):
         snake_case :			Dict							=   ComputeEnvironment(self.compute_environment       )
        if isinstance(self.distributed_type						,    a__       ):
         if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
          snake_case :			List[Any]							=   SageMakerDistributedType(self.distributed_type       )
         else:
          snake_case :			Dict							=   DistributedType(self.distributed_type       )
        if self.dynamo_config is None:
         snake_case :			List[str]							=   {}







@dataclass
class   lowerCamelCase						(	SCREAMING_SNAKE_CASE  ):
       _UpperCamelCase     		=   42
       _UpperCamelCase     		=   0
       _UpperCamelCase     		=   1
       _UpperCamelCase     		=   None
       _UpperCamelCase     		=   None
       _UpperCamelCase     		=   None
       _UpperCamelCase     		=   "static"
       _UpperCamelCase     		=   False
       _UpperCamelCase     		=   "main"

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

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

       # args for dynamo
       _UpperCamelCase     		=   None

       def 					UpperCAmelCase					(      self       ):






        '''simple docstring'''






        if self.deepspeed_config is None:
         snake_case :			Tuple							=   {}
        if self.fsdp_config is None:
         snake_case :			Union[str, Any]							=   {}
        if self.megatron_lm_config is None:
         snake_case :			str							=   {}
        if self.ipex_config is None:
         snake_case :			str							=   {}
        return super().__post_init__()







@dataclass
class   lowerCamelCase						(	SCREAMING_SNAKE_CASE  ):
       _UpperCamelCase     		=   42
       _UpperCamelCase     		=   42
       _UpperCamelCase     		=   None
       _UpperCamelCase     		=   None
       _UpperCamelCase     		=   "us-east-1"
       _UpperCamelCase     		=   1
       _UpperCamelCase     		=   "all"
       _UpperCamelCase     		=   F"accelerate-sagemaker-{num_machines}"
       _UpperCamelCase     		=   SAGEMAKER_PYTORCH_VERSION
       _UpperCamelCase     		=   SAGEMAKER_TRANSFORMERS_VERSION
       _UpperCamelCase     		=   SAGEMAKER_PYTHON_VERSION
       _UpperCamelCase     		=   None
       _UpperCamelCase     		=   None
       _UpperCamelCase     		=   None
       _UpperCamelCase     		=   None










from typing import Any

import numpy as np






def  _UpperCAmelCase						( __lowerCamelCase							)		->bool:


 '''simple docstring'''
 assert np.shape(__lowerCamelCase							)[0] == np.shape(__lowerCamelCase							)[1]

 # If matrix not symmetric, exit right away.
 if np.allclose(__lowerCamelCase			,  matrix.T							) is False:
  return False

 # Get eigenvalues and eignevectors for a symmetric matrix.
 snake_case	,       snake_case :			int							=   np.linalg.eigh(__lowerCamelCase							)

 # Check sign of all eigenvalues.
 # np.all returns a value of type np.bool_
 return bool(np.all(eigen_values > 0							)							)






def  _UpperCAmelCase						( __lowerCamelCase							)		->Any:


 '''simple docstring'''
 snake_case :			Dict							=   np.random.randn(__lowerCamelCase			,  __lowerCamelCase							)
 snake_case :			List[Any]							=   np.dot(__lowerCamelCase			,  random_matrix.T							)
 assert _is_matrix_spd(__lowerCamelCase							)
 return spd_matrix






def  _UpperCAmelCase						( __lowerCamelCase			,  __lowerCamelCase			,  __lowerCamelCase = 1000			,  __lowerCamelCase = 1E-8			,  )		->Any:


 '''simple docstring'''
 assert np.shape(__lowerCamelCase							)[0] == np.shape(__lowerCamelCase							)[1]
 assert np.shape(__lowerCamelCase							)[0] == np.shape(__lowerCamelCase							)[0]
 assert _is_matrix_spd(__lowerCamelCase							)

 # Initialize solution guess, residual, search direction.
 snake_case :			Any							=   np.zeros((np.shape(__lowerCamelCase							)[0], 1)							)
 snake_case :			Optional[int]							=   np.copy(__lowerCamelCase							)
 snake_case :			Optional[Any]							=   np.copy(__lowerCamelCase							)

 # Set initial errors in solution guess and residual.
 snake_case :			Optional[Any]							=   1E9
 snake_case :			List[Any]							=   1E9
 snake_case :			List[str]							=   1E9

 # Set iteration counter to threshold number of iterations.
 snake_case :			List[str]							=   0

 while error > tol:
  # Save this value so we only calculate the matrix-vector product once.
  snake_case :			str							=   np.dot(__lowerCamelCase			,  __lowerCamelCase							)

  # The main algorithm.

  # Update search direction magnitude.
  snake_case :			List[str]							=   np.dot(ra.T			,  __lowerCamelCase							) / np.dot(pa.T			,  __lowerCamelCase							)
  # Update solution guess.
  snake_case :			Optional[int]							=   xa + alpha * pa
  # Calculate new residual.
  snake_case :			str							=   ra - alpha * w
  # Calculate new Krylov subspace scale.
  snake_case :			List[str]							=   np.dot(r.T			,  __lowerCamelCase							) / np.dot(ra.T			,  __lowerCamelCase							)
  # Calculate new A conjuage search direction.
  snake_case :			List[Any]							=   r + beta * pa

  # Calculate errors.
  snake_case :			List[Any]							=   np.linalg.norm(r - ra							)
  snake_case :			Any							=   np.linalg.norm(x - xa							)
  snake_case :			str							=   np.maximum(__lowerCamelCase			,  __lowerCamelCase							)

  # Update variables.
  snake_case :			Tuple							=   np.copy(__lowerCamelCase							)
  snake_case :			Tuple							=   np.copy(__lowerCamelCase							)
  snake_case :			List[str]							=   np.copy(__lowerCamelCase							)

  # Update number of iterations.
  iterations += 1
  if iterations > max_iterations:
   break

 return x






def  _UpperCAmelCase						( )		->None:


 '''simple docstring'''
 snake_case :			str							=   3
 snake_case :			Dict							=   _create_spd_matrix(__lowerCamelCase							)
 snake_case :			str							=   np.random.randn(__lowerCamelCase			,  1							)
 snake_case :			str							=   np.dot(__lowerCamelCase			,  __lowerCamelCase							)

 # Numpy solution.
 snake_case :			Any							=   np.linalg.solve(__lowerCamelCase			,  __lowerCamelCase							)

 # Our implementation.
 snake_case :			List[str]							=   conjugate_gradient(__lowerCamelCase			,  __lowerCamelCase							)

 # Ensure both solutions are close to x_true (and therefore one another).
 assert np.linalg.norm(x_numpy - x_true							) <= 1E-6
 assert np.linalg.norm(x_conjugate_gradient - x_true							) <= 1E-6


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  test_conjugate_gradient()






