



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


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


def   lowercase_	(   lowerCAmelCase__	:  Dict ):

			"""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:
						__UpperCAmelCase   :      List[str]										=     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
									):
												__UpperCAmelCase   :      List[str]										=     ClusterConfig
									else:
												__UpperCAmelCase   :      Tuple										=     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
									):
												__UpperCAmelCase   :      Any										=     ClusterConfig
									else:
												__UpperCAmelCase   :      Tuple										=     SageMakerConfig
									return config_class.from_yaml_file(yaml_file=lowerCAmelCase__ )



@dataclass
class _A  :
		_SCREAMING_SNAKE_CASE					:    ComputeEnvironment
		_SCREAMING_SNAKE_CASE					:    Union[DistributedType, SageMakerDistributedType]
		_SCREAMING_SNAKE_CASE					:    str
		_SCREAMING_SNAKE_CASE					:    bool





		def 							__A       (     self				)       ->     Dict:

					'''simple docstring'''
					__UpperCAmelCase   :      List[str]										=     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				):
											__UpperCAmelCase   :      List[Any]										=     value.value
								if isinstance(__UpperCAmelCase ,       __UpperCAmelCase				) and not bool(__UpperCAmelCase				):
											__UpperCAmelCase   :      Dict										=     None
					__UpperCAmelCase   :      Any										=     {k: v for k, v in result.items() if v is not None}
					return result





		@classmethod
		def 							__A       (     cls ,       __UpperCAmelCase=None				)       ->     Dict:

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





		def 							__A       (     self ,       __UpperCAmelCase				)       ->     str:

					'''simple docstring'''
					with open(__UpperCAmelCase ,       """w""" ,       encoding="""utf-8"""				) as f:
								__UpperCAmelCase   :      int										=     json.dumps(self.to_dict() ,       indent=2 ,       sort_keys=__UpperCAmelCase				) + """\n"""
								f.write(__UpperCAmelCase				)





		@classmethod
		def 							__A       (     cls ,       __UpperCAmelCase=None				)       ->     Optional[int]:

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

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





		def 							__A       (     self ,       __UpperCAmelCase				)       ->     Optional[int]:

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





		def 							__A       (     self				)       ->     str:

					'''simple docstring'''
					if isinstance(self.compute_environment ,       __UpperCAmelCase				):
								__UpperCAmelCase   :      Dict										=     ComputeEnvironment(self.compute_environment				)
					if isinstance(self.distributed_type ,       __UpperCAmelCase				):
								if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
											__UpperCAmelCase   :      Union[str, Any]										=     SageMakerDistributedType(self.distributed_type				)
								else:
											__UpperCAmelCase   :      Tuple										=     DistributedType(self.distributed_type				)
					if self.dynamo_config is None:
								__UpperCAmelCase   :      List[str]										=     {}



@dataclass
class _A  (    __SCREAMING_SNAKE_CASE    ):
		_SCREAMING_SNAKE_CASE					:    int
		_SCREAMING_SNAKE_CASE					:    int						      =			0
		_SCREAMING_SNAKE_CASE					:    int						      =			1
		_SCREAMING_SNAKE_CASE					:    Optional[str]						      =			None
		_SCREAMING_SNAKE_CASE					:    Optional[str]						      =			None
		_SCREAMING_SNAKE_CASE					:    Optional[int]						      =			None
		_SCREAMING_SNAKE_CASE					:    Optional[str]						      =			"static"
		_SCREAMING_SNAKE_CASE					:    Optional[bool]						      =			False
		_SCREAMING_SNAKE_CASE					:    str						      =			"main"

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

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

		# args for dynamo
		_SCREAMING_SNAKE_CASE					:    dict						      =			None





		def 							__A       (     self				)       ->     Union[str, Any]:

					'''simple docstring'''
					if self.deepspeed_config is None:
								__UpperCAmelCase   :      Tuple										=     {}
					if self.fsdp_config is None:
								__UpperCAmelCase   :      List[str]										=     {}
					if self.megatron_lm_config is None:
								__UpperCAmelCase   :      Optional[Any]										=     {}
					if self.ipex_config is None:
								__UpperCAmelCase   :      Tuple										=     {}
					return super().__post_init__()



@dataclass
class _A  (    __SCREAMING_SNAKE_CASE    ):
		_SCREAMING_SNAKE_CASE					:    str
		_SCREAMING_SNAKE_CASE					:    str
		_SCREAMING_SNAKE_CASE					:    Optional[str]						      =			None
		_SCREAMING_SNAKE_CASE					:    Optional[str]						      =			None
		_SCREAMING_SNAKE_CASE					:    str						      =			"us-east-1"
		_SCREAMING_SNAKE_CASE					:    int						      =			1
		_SCREAMING_SNAKE_CASE					:    str						      =			"all"
		_SCREAMING_SNAKE_CASE					:    str						      =			f'''accelerate-sagemaker-{num_machines}'''
		_SCREAMING_SNAKE_CASE					:    str						      =			SAGEMAKER_PYTORCH_VERSION
		_SCREAMING_SNAKE_CASE					:    str						      =			SAGEMAKER_TRANSFORMERS_VERSION
		_SCREAMING_SNAKE_CASE					:    str						      =			SAGEMAKER_PYTHON_VERSION
		_SCREAMING_SNAKE_CASE					:    str						      =			None
		_SCREAMING_SNAKE_CASE					:    str						      =			None
		_SCREAMING_SNAKE_CASE					:    dict						      =			None
		_SCREAMING_SNAKE_CASE					:    dict						      =			None









'''simple docstring'''
from .chunk_utils import chunk_layer
from .data_transforms import make_atomaa_masks
from .feats import atomaa_to_atomaa, frames_and_literature_positions_to_atomaa_pos, torsion_angles_to_frames
from .loss import compute_predicted_aligned_error, compute_tm
from .protein import Protein as OFProtein
from .protein import to_pdb
from .rigid_utils import Rigid, Rotation
from .tensor_utils import dict_multimap, flatten_final_dims, permute_final_dims




