
"""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 ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES
from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType
from ...utils.imports import is_botoa_available
from .config_args import SageMakerConfig
from .config_utils import (
    DYNAMO_BACKENDS,
    _ask_field,
    _ask_options,
    _convert_dynamo_backend,
    _convert_mixed_precision,
    _convert_sagemaker_distributed_mode,
    _convert_yes_no_to_bool,
)


if is_botoa_available():
			import botoa  # noqa: F401

def  lowercase     (_lowerCAmelCase						):
						__lowerCAmelCase     =  botoa.client("""iam"""						)

						__lowerCAmelCase     =  {
						    """Version""": """2012-10-17""",
						    """Statement""": [
						        {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""}
						    ],
						}
						try:
												# create the role, associated with the chosen trust policy
												iam_client.create_role(
												    RoleName=_lowerCAmelCase ,    AssumeRolePolicyDocument=json.dumps(_lowerCAmelCase ,    indent=2						)						)
												__lowerCAmelCase     =  {
												    """Version""": """2012-10-17""",
												    """Statement""": [
												        {
												            """Effect""": """Allow""",
												            """Action""": [
												                """sagemaker:*""",
												                """ecr:GetDownloadUrlForLayer""",
												                """ecr:BatchGetImage""",
												                """ecr:BatchCheckLayerAvailability""",
												                """ecr:GetAuthorizationToken""",
												                """cloudwatch:PutMetricData""",
												                """cloudwatch:GetMetricData""",
												                """cloudwatch:GetMetricStatistics""",
												                """cloudwatch:ListMetrics""",
												                """logs:CreateLogGroup""",
												                """logs:CreateLogStream""",
												                """logs:DescribeLogStreams""",
												                """logs:PutLogEvents""",
												                """logs:GetLogEvents""",
												                """s3:CreateBucket""",
												                """s3:ListBucket""",
												                """s3:GetBucketLocation""",
												                """s3:GetObject""",
												                """s3:PutObject""",
												            ],
												            """Resource""": """*""",
												        }
												    ],
												}
												# attach policy to role
												iam_client.put_role_policy(
												    RoleName=_lowerCAmelCase ,    PolicyName=f"""{role_name}_policy_permission""" ,    PolicyDocument=json.dumps(_lowerCAmelCase ,    indent=2						) ,    )
						except iam_client.exceptions.EntityAlreadyExistsException:
												print(f"""role {role_name} already exists. Using existing one"""						)

def  lowercase     (_lowerCAmelCase						):
						__lowerCAmelCase     =  botoa.client("""iam"""						)
						return iam_client.get_role(RoleName=_lowerCAmelCase						)["Role"]["Arn"]



def  lowercase     ():
						__lowerCAmelCase     =  _ask_options(
						    """How do you want to authorize?""" ,    ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """] ,    _lowerCAmelCase ,    )
						__lowerCAmelCase     =  None
						if credentials_configuration == 0:
												__lowerCAmelCase     =  _ask_field("""Enter your AWS Profile name: [default] """ ,    default="""default"""						)
												__lowerCAmelCase     =  aws_profile
						else:
												print(
												    """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,"""
												    """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`"""						)
												__lowerCAmelCase     =  _ask_field("""AWS Access Key ID: """						)
												__lowerCAmelCase     =  aws_access_key_id

												__lowerCAmelCase     =  _ask_field("""AWS Secret Access Key: """						)
												__lowerCAmelCase     =  aws_secret_access_key

						__lowerCAmelCase     =  _ask_field("""Enter your AWS Region: [us-east-1]""" ,    default="""us-east-1"""						)
						__lowerCAmelCase     =  aws_region

						__lowerCAmelCase     =  _ask_options(
						    """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""" ,    ["""Provide IAM Role name""", """Create new IAM role using credentials"""] ,    _lowerCAmelCase ,    )
						if role_management == 0:
												__lowerCAmelCase     =  _ask_field("""Enter your IAM role name: """						)
						else:
												__lowerCAmelCase     =  """accelerate_sagemaker_execution_role"""
												print(f"""Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials"""						)
												_create_iam_role_for_sagemaker(_lowerCAmelCase						)

						__lowerCAmelCase     =  _ask_field(
						    """Do you want to use custom Docker image? [yes/NO]: """ ,    _convert_yes_no_to_bool ,    default=_lowerCAmelCase ,    error_message="""Please enter yes or no.""" ,    )
						__lowerCAmelCase     =  None
						if is_custom_docker_image:
												__lowerCAmelCase     =  _ask_field("""Enter your Docker image: """ ,    lambda _lowerCAmelCase						: str(_lowerCAmelCase						).lower()						)

						__lowerCAmelCase     =  _ask_field(
						    """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """ ,    _convert_yes_no_to_bool ,    default=_lowerCAmelCase ,    error_message="""Please enter yes or no.""" ,    )
						__lowerCAmelCase     =  None
						if is_sagemaker_inputs_enabled:
												__lowerCAmelCase     =  _ask_field(
												    """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """ ,    lambda _lowerCAmelCase						: str(_lowerCAmelCase						).lower() ,    )

						__lowerCAmelCase     =  _ask_field(
						    """Do you want to enable SageMaker metrics? [yes/NO]: """ ,    _convert_yes_no_to_bool ,    default=_lowerCAmelCase ,    error_message="""Please enter yes or no.""" ,    )
						__lowerCAmelCase     =  None
						if is_sagemaker_metrics_enabled:
												__lowerCAmelCase     =  _ask_field(
												    """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """ ,    lambda _lowerCAmelCase						: str(_lowerCAmelCase						).lower() ,    )

						__lowerCAmelCase     =  _ask_options(
						    """What is the distributed mode?""" ,    ["""No distributed training""", """Data parallelism"""] ,    _convert_sagemaker_distributed_mode ,    )
						__lowerCAmelCase     =  {}
						__lowerCAmelCase     =  _ask_field(
						    """Do you wish to optimize your script with torch dynamo?[yes/NO]:""" ,    _convert_yes_no_to_bool ,    default=_lowerCAmelCase ,    error_message="""Please enter yes or no.""" ,    )
						if use_dynamo:
												__lowerCAmelCase     =  """dynamo_"""
												__lowerCAmelCase     =  _ask_options(
												    """Which dynamo backend would you like to use?""" ,    [x.lower() for x in DYNAMO_BACKENDS] ,    _convert_dynamo_backend ,    default=2 ,    )
												__lowerCAmelCase     =  _ask_field(
												    """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """ ,    _convert_yes_no_to_bool ,    default=_lowerCAmelCase ,    error_message="""Please enter yes or no.""" ,    )

												if use_custom_options:
																		__lowerCAmelCase     =  _ask_options(
																		    """Which mode do you want to use?""" ,    _lowerCAmelCase ,    lambda _lowerCAmelCase						: TORCH_DYNAMO_MODES[int(_lowerCAmelCase						)] ,    default="""default""" ,    )
																		__lowerCAmelCase     =  _ask_field(
																		    """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """ ,    _convert_yes_no_to_bool ,    default=_lowerCAmelCase ,    error_message="""Please enter yes or no.""" ,    )
																		__lowerCAmelCase     =  _ask_field(
																		    """Do you want to enable dynamic shape tracing? [yes/NO]: """ ,    _convert_yes_no_to_bool ,    default=_lowerCAmelCase ,    error_message="""Please enter yes or no.""" ,    )
						__lowerCAmelCase     =  """Which EC2 instance type you want to use for your training?"""
						if distributed_type != SageMakerDistributedType.NO:
												__lowerCAmelCase     =  _ask_options(
												    _lowerCAmelCase ,    _lowerCAmelCase ,    lambda _lowerCAmelCase						: SAGEMAKER_PARALLEL_EC2_INSTANCES[int(_lowerCAmelCase						)]						)
						else:
												eca_instance_query += "? [ml.p3.2xlarge]:"
												__lowerCAmelCase     =  _ask_field(_lowerCAmelCase ,    lambda _lowerCAmelCase						: str(_lowerCAmelCase						).lower() ,    default="""ml.p3.2xlarge"""						)

						__lowerCAmelCase     =  1
						if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL):
												__lowerCAmelCase     =  _ask_field(
												    """How many machines do you want use? [1]: """ ,    _lowerCAmelCase ,    default=1 ,    )

						__lowerCAmelCase     =  _ask_options(
						    """Do you wish to use FP16 or BF16 (mixed precision)?""" ,    ["""no""", """fp16""", """bf16""", """fp8"""] ,    _convert_mixed_precision ,    )

						if use_dynamo and mixed_precision == "no":
												print(
												    """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts."""						)

						return SageMakerConfig(
						    image_uri=_lowerCAmelCase ,    compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER ,    distributed_type=_lowerCAmelCase ,    use_cpu=_lowerCAmelCase ,    dynamo_config=_lowerCAmelCase ,    eca_instance_type=_lowerCAmelCase ,    profile=_lowerCAmelCase ,    region=_lowerCAmelCase ,    iam_role_name=_lowerCAmelCase ,    mixed_precision=_lowerCAmelCase ,    num_machines=_lowerCAmelCase ,    sagemaker_inputs_file=_lowerCAmelCase ,    sagemaker_metrics_file=_lowerCAmelCase ,    )


"""simple docstring"""
import torch

from diffusers import DDIMParallelScheduler

from .test_schedulers import SchedulerCommonTest
class       lowerCAmelCase_		(				A__ ):



							'''simple docstring'''





							_snake_case						      =		(DDIMParallelScheduler,)
							_snake_case						      =		(('''eta''', 0.0), ('''num_inference_steps''', 5_0))




							def    A__						( self    ,				**snake_case_				)       ->  Optional[Any]:
													__lowerCAmelCase     =  {
													    """num_train_timesteps""": 1_000,
													    """beta_start""": 0.0_001,
													    """beta_end""": 0.02,
													    """beta_schedule""": """linear""",
													    """clip_sample""": True,
													}

													config.update(**snake_case_				)
													return config




							def    A__						( self    ,				**snake_case_				)       ->  Tuple:
													__lowerCAmelCase     =  self.scheduler_classes[0]
													__lowerCAmelCase     =  self.get_scheduler_config(**snake_case_				)
													__lowerCAmelCase     =  scheduler_class(**snake_case_				)

													__lowerCAmelCase   ,     __lowerCAmelCase     =  10, 0.0

													__lowerCAmelCase     =  self.dummy_model()
													__lowerCAmelCase     =  self.dummy_sample_deter

													scheduler.set_timesteps(snake_case_				)

													for t in scheduler.timesteps:
																			__lowerCAmelCase     =  model(snake_case_    ,				snake_case_				)
																			__lowerCAmelCase     =  scheduler.step(snake_case_    ,				snake_case_    ,				snake_case_    ,				snake_case_				).prev_sample

													return sample




							def    A__						( self				)       ->  List[str]:
													for timesteps in [100, 500, 1_000]:
																			self.check_over_configs(num_train_timesteps=snake_case_				)




							def    A__						( self				)       ->  Tuple:
													for steps_offset in [0, 1]:
																			self.check_over_configs(steps_offset=snake_case_				)

													__lowerCAmelCase     =  self.scheduler_classes[0]
													__lowerCAmelCase     =  self.get_scheduler_config(steps_offset=1				)
													__lowerCAmelCase     =  scheduler_class(**snake_case_				)
													scheduler.set_timesteps(5				)
													assert torch.equal(scheduler.timesteps    ,				torch.LongTensor([801, 601, 401, 201, 1]				)				)




							def    A__						( self				)       ->  int:
													for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1]    ,				[0.002, 0.02, 0.2, 2]				):
																			self.check_over_configs(beta_start=snake_case_    ,				beta_end=snake_case_				)




							def    A__						( self				)       ->  str:
													for schedule in ["linear", "squaredcos_cap_v2"]:
																			self.check_over_configs(beta_schedule=snake_case_				)




							def    A__						( self				)       ->  Tuple:
													for prediction_type in ["epsilon", "v_prediction"]:
																			self.check_over_configs(prediction_type=snake_case_				)




							def    A__						( self				)       ->  Optional[int]:
													for clip_sample in [True, False]:
																			self.check_over_configs(clip_sample=snake_case_				)




							def    A__						( self				)       ->  Dict:
													for timestep_spacing in ["trailing", "leading"]:
																			self.check_over_configs(timestep_spacing=snake_case_				)




							def    A__						( self				)       ->  str:
													for rescale_betas_zero_snr in [True, False]:
																			self.check_over_configs(rescale_betas_zero_snr=snake_case_				)




							def    A__						( self				)       ->  Optional[int]:
													self.check_over_configs(thresholding=snake_case_				)
													for threshold in [0.5, 1.0, 2.0]:
																			for prediction_type in ["epsilon", "v_prediction"]:
																									self.check_over_configs(
																									    thresholding=snake_case_    ,				prediction_type=snake_case_    ,				sample_max_value=snake_case_    ,				)




							def    A__						( self				)       ->  Union[str, Any]:
													for t in [1, 10, 49]:
																			self.check_over_forward(time_step=snake_case_				)




							def    A__						( self				)       ->  Optional[int]:
													for t, num_inference_steps in zip([1, 10, 50]    ,				[10, 50, 500]				):
																			self.check_over_forward(time_step=snake_case_    ,				num_inference_steps=snake_case_				)




							def    A__						( self				)       ->  Optional[int]:
													for t, eta in zip([1, 10, 49]    ,				[0.0, 0.5, 1.0]				):
																			self.check_over_forward(time_step=snake_case_    ,				eta=snake_case_				)




							def    A__						( self				)       ->  Optional[int]:
													__lowerCAmelCase     =  self.scheduler_classes[0]
													__lowerCAmelCase     =  self.get_scheduler_config()
													__lowerCAmelCase     =  scheduler_class(**snake_case_				)

													assert torch.sum(torch.abs(scheduler._get_variance(0    ,				0				) - 0.0				)				) < 1e-5
													assert torch.sum(torch.abs(scheduler._get_variance(420    ,				400				) - 0.14_771				)				) < 1e-5
													assert torch.sum(torch.abs(scheduler._get_variance(980    ,				960				) - 0.32_460				)				) < 1e-5
													assert torch.sum(torch.abs(scheduler._get_variance(0    ,				0				) - 0.0				)				) < 1e-5
													assert torch.sum(torch.abs(scheduler._get_variance(487    ,				486				) - 0.00_979				)				) < 1e-5
													assert torch.sum(torch.abs(scheduler._get_variance(999    ,				998				) - 0.02				)				) < 1e-5




							def    A__						( self				)       ->  Optional[int]:
													__lowerCAmelCase     =  self.scheduler_classes[0]
													__lowerCAmelCase     =  self.get_scheduler_config()
													__lowerCAmelCase     =  scheduler_class(**snake_case_				)

													__lowerCAmelCase   ,     __lowerCAmelCase     =  10, 0.0
													scheduler.set_timesteps(snake_case_				)

													__lowerCAmelCase     =  self.dummy_model()
													__lowerCAmelCase     =  self.dummy_sample_deter
													__lowerCAmelCase     =  self.dummy_sample_deter + 0.1
													__lowerCAmelCase     =  self.dummy_sample_deter - 0.1

													__lowerCAmelCase     =  samplea.shape[0]
													__lowerCAmelCase     =  torch.stack([samplea, samplea, samplea]    ,				dim=0				)
													__lowerCAmelCase     =  torch.arange(snake_case_				)[0:3, None].repeat(1    ,				snake_case_				)

													__lowerCAmelCase     =  model(samples.flatten(0    ,				1				)    ,				timesteps.flatten(0    ,				1				)				)
													__lowerCAmelCase     =  scheduler.batch_step_no_noise(snake_case_    ,				timesteps.flatten(0    ,				1				)    ,				samples.flatten(0    ,				1				)    ,				snake_case_				)

													__lowerCAmelCase     =  torch.sum(torch.abs(snake_case_				)				)
													__lowerCAmelCase     =  torch.mean(torch.abs(snake_case_				)				)

													assert abs(result_sum.item() - 1_147.7_904				) < 1e-2
													assert abs(result_mean.item() - 0.4_982				) < 1e-3




							def    A__						( self				)       ->  Dict:
													__lowerCAmelCase     =  self.full_loop()

													__lowerCAmelCase     =  torch.sum(torch.abs(snake_case_				)				)
													__lowerCAmelCase     =  torch.mean(torch.abs(snake_case_				)				)

													assert abs(result_sum.item() - 172.0_067				) < 1e-2
													assert abs(result_mean.item() - 0.223_967				) < 1e-3




							def    A__						( self				)       ->  str:
													__lowerCAmelCase     =  self.full_loop(prediction_type="""v_prediction"""				)

													__lowerCAmelCase     =  torch.sum(torch.abs(snake_case_				)				)
													__lowerCAmelCase     =  torch.mean(torch.abs(snake_case_				)				)

													assert abs(result_sum.item() - 52.5_302				) < 1e-2
													assert abs(result_mean.item() - 0.0_684				) < 1e-3




							def    A__						( self				)       ->  Tuple:
													# We specify different beta, so that the first alpha is 0.99
													__lowerCAmelCase     =  self.full_loop(set_alpha_to_one=snake_case_    ,				beta_start=0.01				)
													__lowerCAmelCase     =  torch.sum(torch.abs(snake_case_				)				)
													__lowerCAmelCase     =  torch.mean(torch.abs(snake_case_				)				)

													assert abs(result_sum.item() - 149.8_295				) < 1e-2
													assert abs(result_mean.item() - 0.1_951				) < 1e-3




							def    A__						( self				)       ->  Union[str, Any]:
													# We specify different beta, so that the first alpha is 0.99
													__lowerCAmelCase     =  self.full_loop(set_alpha_to_one=snake_case_    ,				beta_start=0.01				)
													__lowerCAmelCase     =  torch.sum(torch.abs(snake_case_				)				)
													__lowerCAmelCase     =  torch.mean(torch.abs(snake_case_				)				)

													assert abs(result_sum.item() - 149.0_784				) < 1e-2
													assert abs(result_mean.item() - 0.1_941				) < 1e-3
