






# 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












# Copyright 2022 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 os
from typing import List



def      _SCREAMING_SNAKE_CASE  (	__lowercase				:     List[str]     ,			__lowercase				:     str      )  -> Optional[int]:





    """simple docstring"""

    if name != "training_function" and name != "main":
        raise ValueError(f"Incorrect function name passed: {name}, choose either 'main' or 'training_function'"      )
    __A      ,		__A             =		[], False
    for line in lines:
        if not found_start and f"def {name}" in line:
            __A             =		True
            good_lines.append(__lowercase      )
            continue
        if found_start:
            if name == "training_function" and "def main" in line:
                return good_lines
            if name == "main" and "if __name__" in line:
                return good_lines
            good_lines.append(__lowercase      )



def      _SCREAMING_SNAKE_CASE  (	__lowercase				:     List[str]      )  -> Optional[int]:





    """simple docstring"""

    return [line for line in lines if not line.lstrip().startswith("""#"""      ) and line != "\n"]






def      _SCREAMING_SNAKE_CASE  (	__lowercase				:     str     ,			__lowercase				:     str     ,			__lowercase				:     bool     ,			__lowercase				:     str = None      )  -> List[Any]:





    """simple docstring"""

    with open(__lowercase     ,			"""r"""      ) as f:
        __A             =		f.readlines()
    with open(os.path.abspath(os.path.join("""examples"""     ,			"""nlp_example.py"""      )      )     ,			"""r"""      ) as f:
        __A             =		f.readlines()
    with open(__lowercase     ,			"""r"""      ) as f:
        __A             =		f.readlines()
    if secondary_filename is not None:
        with open(__lowercase     ,			"""r"""      ) as f:
            __A             =		f.readlines()

    # This is our base, we remove all the code from here in our `full_filename` and `feature_filename` to find the new content
    if parser_only:
        __A             =		clean_lines(get_function_contents_by_name(__lowercase     ,			"""main"""      )      )
        __A             =		clean_lines(get_function_contents_by_name(__lowercase     ,			"""main"""      )      )
        __A             =		clean_lines(get_function_contents_by_name(__lowercase     ,			"""main"""      )      )
        if secondary_filename is not None:
            __A             =		clean_lines(get_function_contents_by_name(__lowercase     ,			"""main"""      )      )
    else:
        __A             =		clean_lines(get_function_contents_by_name(__lowercase     ,			"""training_function"""      )      )
        __A             =		clean_lines(get_function_contents_by_name(__lowercase     ,			"""training_function"""      )      )
        __A             =		clean_lines(get_function_contents_by_name(__lowercase     ,			"""training_function"""      )      )
        if secondary_filename is not None:
            __A             =		clean_lines(
                get_function_contents_by_name(__lowercase     ,			"""training_function"""      )      )

    __A             =		"""train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)\n"""

    # Specific code in our script that differs from the full version, aka what is new
    __A             =		[]
    __A             =		[]  # We keep track of the idxs just in case it's a repeated statement
    __A             =		iter(__lowercase      )
    for i in range(len(__lowercase      ) - 1      ):
        if i not in passed_idxs:
            __A             =		next(__lowercase      )
            if (line not in full_file_func) and (line.lstrip() != _dl_line):
                if "TESTING_MOCKED_DATALOADERS" not in line:
                    new_feature_code.append(__lowercase      )
                    passed_idxs.append(__lowercase      )
                else:
                    # Skip over the `config['num_epochs'] = 2` statement
                    __A             =		next(__lowercase      )

    # Extract out just the new parts from the full_file_training_func
    __A             =		[]
    __A             =		[]  # We keep track of the idxs just in case it's a repeated statement
    for i, line in enumerate(__lowercase      ):
        if i not in passed_idxs:
            if (line not in full_file_func) and (line.lstrip() != _dl_line):
                if "TESTING_MOCKED_DATALOADERS" not in line:
                    new_full_example_parts.append(__lowercase      )
                    passed_idxs.append(__lowercase      )

    # Finally, get the overall diff
    __A             =		[line for line in new_feature_code if line not in new_full_example_parts]
    if secondary_filename is not None:
        __A             =		[line for line in full_file_contents if line not in secondary_file_func]
        __A             =		[line for line in diff_from_example if line not in diff_from_two]

    return diff_from_example




