



# 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.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


__snake_case     :List[Any]			       ='Create a default config file for Accelerate with only a few flags set.'






def  lowerCamelCase_	(      lowerCAmelCase__	:	Optional[Any]="no"			,	lowerCAmelCase__	:	str = default_json_config_file			,	lowerCAmelCase__	:	bool = False				)       ->							str:

							'''simple docstring'''






							A      						=    Path(lowerCAmelCase__				)
							path.parent.mkdir(parents=lowerCAmelCase__			,	exist_ok=lowerCAmelCase__				)
							if path.exists():
														print(
														    F'''Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.'''				)
														return False
							A      						=    mixed_precision.lower()
							if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
														raise ValueError(
														    F'''`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}'''				)
							A      						=    {
							    'compute_environment': 'LOCAL_MACHINE',
							    'mixed_precision': mixed_precision,
							}
							if torch.cuda.is_available():
														A      						=    torch.cuda.device_count()
														A      						=    num_gpus
														A      						=    False
														if num_gpus > 1:
																					A      						=    'MULTI_GPU'
														else:
																					A      						=    'NO'
							elif is_xpu_available() and use_xpu:
														A      						=    torch.xpu.device_count()
														A      						=    num_xpus
														A      						=    False
														if num_xpus > 1:
																					A      						=    'MULTI_XPU'
														else:
																					A      						=    'NO'
							elif is_npu_available():
														A      						=    torch.npu.device_count()
														A      						=    num_npus
														A      						=    False
														if num_npus > 1:
																					A      						=    'MULTI_NPU'
														else:
																					A      						=    'NO'
							else:
														A      						=    0
														A      						=    True
														A      						=    1
														A      						=    'NO'
							A      						=    ClusterConfig(**lowerCAmelCase__				)
							config.to_json_file(lowerCAmelCase__				)
							return path






def  lowerCamelCase_	(      lowerCAmelCase__	:	Optional[Any]			,	lowerCAmelCase__	:	Optional[int]				)       ->							Optional[int]:

							'''simple docstring'''






							A      						=    parser.add_parser('default'			,	parents=lowerCAmelCase__			,	help=lowerCAmelCase__			,	formatter_class=lowerCAmelCase__				)
							parser.add_argument(
							    '--config_file'			,	default=lowerCAmelCase__			,	help=(
							        'The path to use to store the config file. Will default to a file named default_config.yaml in the cache '
							        'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '
							        'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '
							        'with \'huggingface\'.'
							    )			,	dest='save_location'			,	)

							parser.add_argument(
							    '--mixed_precision'			,	choices=['no', 'fp16', 'bf16']			,	type=lowerCAmelCase__			,	help='Whether or not to use mixed precision training. '
							    'Choose between FP16 and BF16 (bfloat16) training. '
							    'BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.'			,	default='no'			,	)
							parser.set_defaults(func=lowerCAmelCase__				)
							return parser






def  lowerCamelCase_	(      lowerCAmelCase__	:	Optional[int]				)       ->							Tuple:

							'''simple docstring'''






							A      						=    write_basic_config(args.mixed_precision			,	args.save_location				)
							if config_file:
														print(F'''accelerate configuration saved at {config_file}'''				)

import torch

from diffusers import KDPMaDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest







class 							lowerCAmelCase__   ( __lowercase						):
						UpperCamelCase_				:			int						=		(KDPMaDiscreteScheduler,)
						UpperCamelCase_				:			Optional[int]						=		10

						def 			A_					(      self							,				**a					)       ->   int:


								'''simple docstring'''

								_UpperCamelCase         =						{
								    """num_train_timesteps""": 11_00,
								    """beta_start""": 0.0001,
								    """beta_end""": 0.02,
								    """beta_schedule""": """linear""",
								}

								config.update(**a					)
								return config

						def 			A_					(      self					)       ->   List[str]:


								'''simple docstring'''

								for timesteps in [10, 50, 1_00, 10_00]:
										self.check_over_configs(num_train_timesteps=a					)

						def 			A_					(      self					)       ->   List[Any]:


								'''simple docstring'''

								for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001]							,				[0.0002, 0.002, 0.02]					):
										self.check_over_configs(beta_start=a							,				beta_end=a					)

						def 			A_					(      self					)       ->   Any:


								'''simple docstring'''

								for schedule in ["linear", "scaled_linear"]:
										self.check_over_configs(beta_schedule=a					)

						def 			A_					(      self					)       ->   Optional[int]:


								'''simple docstring'''

								for prediction_type in ["epsilon", "v_prediction"]:
										self.check_over_configs(prediction_type=a					)

						def 			A_					(      self					)       ->   List[Any]:


								'''simple docstring'''

								_UpperCamelCase         =						self.scheduler_classes[0]
								_UpperCamelCase         =						self.get_scheduler_config(prediction_type="""v_prediction"""					)
								_UpperCamelCase         =						scheduler_class(**a					)

								scheduler.set_timesteps(self.num_inference_steps					)

								_UpperCamelCase         =						self.dummy_model()
								_UpperCamelCase         =						self.dummy_sample_deter * scheduler.init_noise_sigma
								_UpperCamelCase         =						sample.to(a					)

								for i, t in enumerate(scheduler.timesteps					):
										_UpperCamelCase         =						scheduler.scale_model_input(a							,				a					)

										_UpperCamelCase         =						model(a							,				a					)

										_UpperCamelCase         =						scheduler.step(a							,				a							,				a					)
										_UpperCamelCase         =						output.prev_sample

								_UpperCamelCase         =						torch.sum(torch.abs(a					)					)
								_UpperCamelCase         =						torch.mean(torch.abs(a					)					)

								if torch_device in ["cpu", "mps"]:
										assert abs(result_sum.item() - 4.6934e-07					) < 1e-2
										assert abs(result_mean.item() - 6.1112e-10					) < 1e-3
								else:
										# CUDA
										assert abs(result_sum.item() - 4.693_4286_5017_0972e-07					) < 1e-2
										assert abs(result_mean.item() - 0.0002					) < 1e-3

						def 			A_					(      self					)       ->   str:


								'''simple docstring'''

								if torch_device == "mps":
										return
								_UpperCamelCase         =						self.scheduler_classes[0]
								_UpperCamelCase         =						self.get_scheduler_config()
								_UpperCamelCase         =						scheduler_class(**a					)

								scheduler.set_timesteps(self.num_inference_steps					)

								_UpperCamelCase         =						self.dummy_model()
								_UpperCamelCase         =						self.dummy_sample_deter * scheduler.init_noise_sigma
								_UpperCamelCase         =						sample.to(a					)

								for i, t in enumerate(scheduler.timesteps					):
										_UpperCamelCase         =						scheduler.scale_model_input(a							,				a					)

										_UpperCamelCase         =						model(a							,				a					)

										_UpperCamelCase         =						scheduler.step(a							,				a							,				a					)
										_UpperCamelCase         =						output.prev_sample

								_UpperCamelCase         =						torch.sum(torch.abs(a					)					)
								_UpperCamelCase         =						torch.mean(torch.abs(a					)					)

								if torch_device in ["cpu", "mps"]:
										assert abs(result_sum.item() - 20.4125					) < 1e-2
										assert abs(result_mean.item() - 0.0266					) < 1e-3
								else:
										# CUDA
										assert abs(result_sum.item() - 20.4125					) < 1e-2
										assert abs(result_mean.item() - 0.0266					) < 1e-3







						def 			A_					(      self					)       ->   str:


								'''simple docstring'''

								if torch_device == "mps":
										return
								_UpperCamelCase         =						self.scheduler_classes[0]
								_UpperCamelCase         =						self.get_scheduler_config()
								_UpperCamelCase         =						scheduler_class(**a					)

								scheduler.set_timesteps(self.num_inference_steps							,				device=a					)

								_UpperCamelCase         =						self.dummy_model()
								_UpperCamelCase         =						self.dummy_sample_deter.to(a					) * scheduler.init_noise_sigma

								for t in scheduler.timesteps:
										_UpperCamelCase         =						scheduler.scale_model_input(a							,				a					)

										_UpperCamelCase         =						model(a							,				a					)

										_UpperCamelCase         =						scheduler.step(a							,				a							,				a					)
										_UpperCamelCase         =						output.prev_sample

								_UpperCamelCase         =						torch.sum(torch.abs(a					)					)
								_UpperCamelCase         =						torch.mean(torch.abs(a					)					)

								if str(a					).startswith("""cpu"""					):
										# The following sum varies between 148 and 156 on mps. Why?
										assert abs(result_sum.item() - 20.4125					) < 1e-2
										assert abs(result_mean.item() - 0.0266					) < 1e-3
								else:
										# CUDA
										assert abs(result_sum.item() - 20.4125					) < 1e-2
										assert abs(result_mean.item() - 0.0266					) < 1e-3



