



"""simple docstring"""







import unittest
from functools import partial

import torch

from accelerate import Accelerator, debug_launcher
from accelerate.state import AcceleratorState, GradientState
from accelerate.test_utils import require_cpu, require_huggingface_suite
from accelerate.utils import GradientAccumulationPlugin


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase=2   ,				__UpperCAmelCase=True   ,				__UpperCAmelCase=False      ):
		_lowercase				: Dict     =   Accelerator(step_scheduler_with_optimizer=__UpperCAmelCase   ,				split_batches=__UpperCAmelCase      )
		_lowercase				: Union[str, Any]     =   torch.nn.Linear(2   ,				4      )
		_lowercase				: Any     =   torch.optim.AdamW(model.parameters()   ,				lr=1.0      )
		_lowercase				: Optional[int]     =   torch.optim.lr_scheduler.OneCycleLR(__UpperCAmelCase   ,				max_lr=0.0_1   ,				steps_per_epoch=2   ,				epochs=1      )
		_lowercase     ,  _lowercase     ,  _lowercase				: Any     =   accelerator.prepare(__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      )

		# Optimizer has stepped
		scheduler.step()
		if step_scheduler_with_optimizer or (num_processes == 1):
				assert (
				    scheduler.scheduler.last_epoch == num_processes
				), F"""Last Epoch ({scheduler.scheduler.last_epoch}) != Num Processes ({num_processes})"""
		else:
				assert (
				    scheduler.scheduler.last_epoch != num_processes
				), F"""Last Epoch ({scheduler.scheduler.last_epoch}) == Num Processes ({num_processes})"""


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase=2   ,				__UpperCAmelCase=True   ,				__UpperCAmelCase=False      ):
		_lowercase				: str     =   Accelerator(step_scheduler_with_optimizer=__UpperCAmelCase   ,				split_batches=__UpperCAmelCase      )
		_lowercase				: int     =   torch.nn.Linear(2   ,				4      )
		_lowercase				: int     =   torch.optim.AdamW(model.parameters()   ,				lr=1.0      )
		_lowercase				: int     =   torch.optim.lr_scheduler.LambdaLR(__UpperCAmelCase   ,				lr_lambda=lambda __UpperCAmelCase      : 1 - n / 10      )
		_lowercase     ,  _lowercase     ,  _lowercase				: List[Any]     =   accelerator.prepare(__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      )

		# Optimizer has stepped
		_lowercase				: List[Any]     =   False
		scheduler.step()
		_lowercase				: List[str]     =   1 - (num_processes if (step_scheduler_with_optimizer and not split_batches) else 1) / 10
		assert (
		    scheduler.get_last_lr()[0] == expected_lr
		), F"""Wrong lr found at first step, expected {expected_lr}, got {scheduler.get_last_lr()[0]}"""

		# Optimizer has not stepped
		_lowercase				: Optional[Any]     =   True
		scheduler.step()
		if not step_scheduler_with_optimizer:
				_lowercase				: Tuple     =   1 - 2 / 10
		assert (
		    scheduler.get_last_lr()[0] == expected_lr
		), F"""Wrong lr found at second step, expected {expected_lr}, got {scheduler.get_last_lr()[0]}"""


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase = 2      ):
		from transformers import get_linear_schedule_with_warmup

		_lowercase				: Tuple     =   [1, 2, 4]
		for num_steps in steps:
				_lowercase				: Any     =   GradientAccumulationPlugin(num_steps=__UpperCAmelCase   ,				adjust_scheduler=num_steps > 1      )
				_lowercase				: int     =   Accelerator(gradient_accumulation_plugin=__UpperCAmelCase      )
				_lowercase				: int     =   torch.nn.Linear(2   ,				4      )
				_lowercase				: int     =   torch.optim.AdamW(model.parameters()   ,				lr=1_0.0      )
				_lowercase				: Dict     =   get_linear_schedule_with_warmup(optimizer=__UpperCAmelCase   ,				num_warmup_steps=0   ,				num_training_steps=20      )

				_lowercase     ,  _lowercase     ,  _lowercase				: List[str]     =   accelerator.prepare(__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      )

				for i in range(10 * num_steps      ):
						with accelerator.accumulate(__UpperCAmelCase      ):
								optimizer.step()
								scheduler.step()

						if i == (10 * num_steps - 2):
								assert (
								    scheduler.get_last_lr()[0] != 0
								), F"""Wrong lr found at second-to-last step, expected non-zero, got {scheduler.get_last_lr()[0]}. num_steps: {num_steps}"""
				assert (
				    scheduler.get_last_lr()[0] == 0
				), F"""Wrong lr found at last step, expected 0, got {scheduler.get_last_lr()[0]}"""
				GradientState._reset_state()





@require_cpu
class   UpperCamelCase	(     unittest.TestCase       ):




	"""simple docstring"""






	def    lowerCamelCase__					(     self   ):
			debug_launcher(partial(UpperCAmelCase_				,num_processes=1   )				,num_processes=1   )
			debug_launcher(partial(UpperCAmelCase_				,num_processes=1				,split_batches=UpperCAmelCase_   )				,num_processes=1   )






	def    lowerCamelCase__					(     self   ):
			debug_launcher(partial(UpperCAmelCase_				,num_processes=1   )				,num_processes=1   )
			debug_launcher(partial(UpperCAmelCase_				,num_processes=1				,split_batches=UpperCAmelCase_   )				,num_processes=1   )






	def    lowerCamelCase__					(     self   ):
			debug_launcher(partial(UpperCAmelCase_				,num_processes=1				,step_scheduler_with_optimizer=UpperCAmelCase_   )				,num_processes=1   )






	def    lowerCamelCase__					(     self   ):
			debug_launcher(partial(UpperCAmelCase_				,num_processes=1				,step_scheduler_with_optimizer=UpperCAmelCase_   )				,num_processes=1   )






	def    lowerCamelCase__					(     self   ):
			AcceleratorState._reset_state(UpperCAmelCase_   )
			debug_launcher(UpperCAmelCase_   )
			debug_launcher(partial(UpperCAmelCase_				,num_processes=1				,split_batches=UpperCAmelCase_   )				,num_processes=1   )






	def    lowerCamelCase__					(     self   ):
			AcceleratorState._reset_state(UpperCAmelCase_   )
			debug_launcher(UpperCAmelCase_   )
			debug_launcher(partial(UpperCAmelCase_				,num_processes=1				,split_batches=UpperCAmelCase_   )				,num_processes=1   )






	def    lowerCamelCase__					(     self   ):
			AcceleratorState._reset_state(UpperCAmelCase_   )
			debug_launcher(partial(UpperCAmelCase_				,step_scheduler_with_optimizer=UpperCAmelCase_   )   )






	def    lowerCamelCase__					(     self   ):
			AcceleratorState._reset_state(UpperCAmelCase_   )
			debug_launcher(partial(UpperCAmelCase_				,step_scheduler_with_optimizer=UpperCAmelCase_   )   )






	@require_huggingface_suite
	def    lowerCamelCase__					(     self   ):
			AcceleratorState._reset_state(UpperCAmelCase_   )
			debug_launcher(partial(UpperCAmelCase_				,num_processes=1   )   )
			debug_launcher(UpperCAmelCase_   )








# 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 			UpperCAmelCase__     (     lowercase__ )			->   int:
						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:
												__lowercase											=					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
																		):
																								__lowercase											=					ClusterConfig
																		else:
																								__lowercase											=					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
																		):
																								__lowercase											=					ClusterConfig
																		else:
																								__lowercase											=					SageMakerConfig
																		return config_class.from_yaml_file(yaml_file=lowercase__ )
@dataclass
class       _lowerCAmelCase :






			"""simple docstring"""





			lowercase__   :	ComputeEnvironment
			lowercase__   :	Union[DistributedType, SageMakerDistributedType]
			lowercase__   :	str
			lowercase__   :	bool





			def 		snake_case__      (					self						:							Union[str, Any] )    ->       List[Any]:
									"""simple docstring"""







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





			@classmethod
			def 		snake_case__      (					cls						:							List[str]      ,  lowercase						:							List[str]=None )    ->       Union[str, Any]:
									"""simple docstring"""







									__lowercase											=					default_json_config_file if json_file is None else json_file
									with open(lowercase      ,  """r"""      ,  encoding="""utf-8""" ) as f:
															__lowercase											=					json.load(lowercase )
									if "compute_environment" not in config_dict:
															__lowercase											=					ComputeEnvironment.LOCAL_MACHINE
									if "mixed_precision" not in config_dict:
															__lowercase											=					"""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.
															__lowercase											=					config_dict.pop("""dynamo_backend""" )
															__lowercase											=					{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
									if "use_cpu" not in config_dict:
															__lowercase											=					False
									return cls(**lowercase )





			def 		snake_case__      (					self						:							Tuple      ,  lowercase						:							str )    ->       Any:
									"""simple docstring"""







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





			@classmethod
			def 		snake_case__      (					cls						:							List[str]      ,  lowercase						:							Optional[Any]=None )    ->       Union[str, Any]:
									"""simple docstring"""







									__lowercase											=					default_yaml_config_file if yaml_file is None else yaml_file
									with open(lowercase      ,  """r"""      ,  encoding="""utf-8""" ) as f:
															__lowercase											=					yaml.safe_load(lowercase )
									if "compute_environment" not in config_dict:
															__lowercase											=					ComputeEnvironment.LOCAL_MACHINE

									if "mixed_precision" not in config_dict:
															__lowercase											=					"""fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
									if isinstance(config_dict["""mixed_precision"""]      ,  lowercase ) and not config_dict["mixed_precision"]:
															__lowercase											=					"""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.
															__lowercase											=					config_dict.pop("""dynamo_backend""" )
															__lowercase											=					{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
									if "use_cpu" not in config_dict:
															__lowercase											=					False
									return cls(**lowercase )





			def 		snake_case__      (					self						:							Union[str, Any]      ,  lowercase						:							Any )    ->       Tuple:
									"""simple docstring"""







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







			def 		snake_case__      (					self						:							int )    ->       Optional[int]:
									"""simple docstring"""







									if isinstance(self.compute_environment      ,  lowercase ):
															__lowercase											=					ComputeEnvironment(self.compute_environment )
									if isinstance(self.distributed_type      ,  lowercase ):
															if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																					__lowercase											=					SageMakerDistributedType(self.distributed_type )
															else:
																					__lowercase											=					DistributedType(self.distributed_type )
									if self.dynamo_config is None:
															__lowercase											=					{}





@dataclass
class       _lowerCAmelCase (			_UpperCAmelCase      ):






			"""simple docstring"""





			lowercase__   :	int
			lowercase__   :	int  			=      0
			lowercase__   :	int  			=      1
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[int]  			=      None
			lowercase__   :	Optional[str]  			=      "static"
			lowercase__   :	Optional[bool]  			=      False
			lowercase__   :	str  			=      "main"

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

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

			# args for dynamo
			lowercase__   :	dict  			=      None





			def 		snake_case__      (					self						:							List[Any] )    ->       int:
									"""simple docstring"""







									if self.deepspeed_config is None:
															__lowercase											=					{}
									if self.fsdp_config is None:
															__lowercase											=					{}
									if self.megatron_lm_config is None:
															__lowercase											=					{}
									if self.ipex_config is None:
															__lowercase											=					{}
									return super().__post_init__()





@dataclass
class       _lowerCAmelCase (			_UpperCAmelCase      ):






			"""simple docstring"""





			lowercase__   :	str
			lowercase__   :	str
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	str  			=      "us-east-1"
			lowercase__   :	int  			=      1
			lowercase__   :	str  			=      "all"
			lowercase__   :	str  			=      F'''accelerate-sagemaker-{num_machines}'''
			lowercase__   :	str  			=      SAGEMAKER_PYTORCH_VERSION
			lowercase__   :	str  			=      SAGEMAKER_TRANSFORMERS_VERSION
			lowercase__   :	str  			=      SAGEMAKER_PYTHON_VERSION
			lowercase__   :	str  			=      None
			lowercase__   :	str  			=      None
			lowercase__   :	dict  			=      None
			lowercase__   :	dict  			=      None





