


"""simple docstring"""



import tempfile

import torch

from diffusers import PNDMScheduler

from .test_schedulers import SchedulerCommonTest







class _lowerCAmelCase				(      snake_case_	):
   __UpperCAmelCase :       Optional[int]							  =  (PNDMScheduler,)
   __UpperCAmelCase :       Union[str, Any]							  =  (('''num_inference_steps''', 50),)







   def  lowerCamelCase		(	self						,	**UpperCamelCase__						)	->		List[Any]:

       '''simple docstring'''




       snake_case    :      List[Any]      					=    {
           "num_train_timesteps": 1000,
           "beta_start": 0.0001,
           "beta_end": 0.02,
           "beta_schedule": "linear",
       }

       config.update(**UpperCamelCase__						)
       return config







   def  lowerCamelCase		(	self						,	UpperCamelCase__=0						,	**UpperCamelCase__						)	->		List[Any]:

       '''simple docstring'''




       snake_case    :      int      					=    dict(self.forward_default_kwargs						)
       snake_case    :      Optional[Any]      					=    kwargs.pop("num_inference_steps"						,	UpperCamelCase__						)
       snake_case    :      Optional[int]      					=    self.dummy_sample
       snake_case    :      Dict      					=    0.1 * sample
       snake_case    :      Tuple      					=    [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

       for scheduler_class in self.scheduler_classes:
           snake_case    :      Any      					=    self.get_scheduler_config(**UpperCamelCase__						)
           snake_case    :      List[Any]      					=    scheduler_class(**UpperCamelCase__						)
           scheduler.set_timesteps(UpperCamelCase__						)
           # copy over dummy past residuals
           snake_case    :      Union[str, Any]      					=    dummy_past_residuals[:]

           with tempfile.TemporaryDirectory() as tmpdirname:
               scheduler.save_config(UpperCamelCase__						)
               snake_case    :      Optional[int]      					=    scheduler_class.from_pretrained(UpperCamelCase__						)
               new_scheduler.set_timesteps(UpperCamelCase__						)
               # copy over dummy past residuals
               snake_case    :      List[str]      					=    dummy_past_residuals[:]

           snake_case    :      Tuple      					=    scheduler.step_prk(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	**UpperCamelCase__						).prev_sample
           snake_case    :      Any      					=    new_scheduler.step_prk(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	**UpperCamelCase__						).prev_sample

           assert torch.sum(torch.abs(output - new_output						)						) < 1e-5, "Scheduler outputs are not identical"

           snake_case    :      Any      					=    scheduler.step_plms(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	**UpperCamelCase__						).prev_sample
           snake_case    :      Optional[int]      					=    new_scheduler.step_plms(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	**UpperCamelCase__						).prev_sample

           assert torch.sum(torch.abs(output - new_output						)						) < 1e-5, "Scheduler outputs are not identical"







   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       pass







   def  lowerCamelCase		(	self						,	UpperCamelCase__=0						,	**UpperCamelCase__						)	->		Any:

       '''simple docstring'''




       snake_case    :      int      					=    dict(self.forward_default_kwargs						)
       snake_case    :      Any      					=    kwargs.pop("num_inference_steps"						,	UpperCamelCase__						)
       snake_case    :      str      					=    self.dummy_sample
       snake_case    :      Tuple      					=    0.1 * sample
       snake_case    :      Any      					=    [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

       for scheduler_class in self.scheduler_classes:
           snake_case    :      Optional[int]      					=    self.get_scheduler_config()
           snake_case    :      Optional[Any]      					=    scheduler_class(**UpperCamelCase__						)
           scheduler.set_timesteps(UpperCamelCase__						)

           # copy over dummy past residuals (must be after setting timesteps)
           snake_case    :      Optional[Any]      					=    dummy_past_residuals[:]

           with tempfile.TemporaryDirectory() as tmpdirname:
               scheduler.save_config(UpperCamelCase__						)
               snake_case    :      List[Any]      					=    scheduler_class.from_pretrained(UpperCamelCase__						)
               # copy over dummy past residuals
               new_scheduler.set_timesteps(UpperCamelCase__						)

               # copy over dummy past residual (must be after setting timesteps)
               snake_case    :      str      					=    dummy_past_residuals[:]

           snake_case    :      Optional[Any]      					=    scheduler.step_prk(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	**UpperCamelCase__						).prev_sample
           snake_case    :      Union[str, Any]      					=    new_scheduler.step_prk(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	**UpperCamelCase__						).prev_sample

           assert torch.sum(torch.abs(output - new_output						)						) < 1e-5, "Scheduler outputs are not identical"

           snake_case    :      Optional[int]      					=    scheduler.step_plms(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	**UpperCamelCase__						).prev_sample
           snake_case    :      List[str]      					=    new_scheduler.step_plms(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	**UpperCamelCase__						).prev_sample

           assert torch.sum(torch.abs(output - new_output						)						) < 1e-5, "Scheduler outputs are not identical"







   def  lowerCamelCase		(	self						,	**UpperCamelCase__						)	->		str:

       '''simple docstring'''




       snake_case    :      Optional[int]      					=    self.scheduler_classes[0]
       snake_case    :      Optional[int]      					=    self.get_scheduler_config(**UpperCamelCase__						)
       snake_case    :      Dict      					=    scheduler_class(**UpperCamelCase__						)

       snake_case    :      List[Any]      					=    10
       snake_case    :      Optional[int]      					=    self.dummy_model()
       snake_case    :      Any      					=    self.dummy_sample_deter
       scheduler.set_timesteps(UpperCamelCase__						)

       for i, t in enumerate(scheduler.prk_timesteps						):
           snake_case    :      str      					=    model(UpperCamelCase__						,	UpperCamelCase__						)
           snake_case    :      List[Any]      					=    scheduler.step_prk(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						).prev_sample

       for i, t in enumerate(scheduler.plms_timesteps						):
           snake_case    :      Optional[Any]      					=    model(UpperCamelCase__						,	UpperCamelCase__						)
           snake_case    :      Dict      					=    scheduler.step_plms(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						).prev_sample

       return sample







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case    :      str      					=    dict(self.forward_default_kwargs						)

       snake_case    :      Tuple      					=    kwargs.pop("num_inference_steps"						,	UpperCamelCase__						)

       for scheduler_class in self.scheduler_classes:
           snake_case    :      List[str]      					=    self.get_scheduler_config()
           snake_case    :      Union[str, Any]      					=    scheduler_class(**UpperCamelCase__						)

           snake_case    :      Tuple      					=    self.dummy_sample
           snake_case    :      str      					=    0.1 * sample

           if num_inference_steps is not None and hasattr(UpperCamelCase__						,	"set_timesteps"						):
               scheduler.set_timesteps(UpperCamelCase__						)
           elif num_inference_steps is not None and not hasattr(UpperCamelCase__						,	"set_timesteps"						):
               snake_case    :      Optional[Any]      					=    num_inference_steps

           # copy over dummy past residuals (must be done after set_timesteps)
           snake_case    :      str      					=    [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
           snake_case    :      List[Any]      					=    dummy_past_residuals[:]

           snake_case    :      str      					=    scheduler.step_prk(UpperCamelCase__						,	0						,	UpperCamelCase__						,	**UpperCamelCase__						).prev_sample
           snake_case    :      Union[str, Any]      					=    scheduler.step_prk(UpperCamelCase__						,	1						,	UpperCamelCase__						,	**UpperCamelCase__						).prev_sample

           self.assertEqual(output_a.shape						,	sample.shape						)
           self.assertEqual(output_a.shape						,	output_a.shape						)

           snake_case    :      Tuple      					=    scheduler.step_plms(UpperCamelCase__						,	0						,	UpperCamelCase__						,	**UpperCamelCase__						).prev_sample
           snake_case    :      Any      					=    scheduler.step_plms(UpperCamelCase__						,	1						,	UpperCamelCase__						,	**UpperCamelCase__						).prev_sample

           self.assertEqual(output_a.shape						,	sample.shape						)
           self.assertEqual(output_a.shape						,	output_a.shape						)







   def  lowerCamelCase		(	self						)	->		Dict:

       '''simple docstring'''




       for timesteps in [100, 1000]:
           self.check_over_configs(num_train_timesteps=UpperCamelCase__						)







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

       '''simple docstring'''




       for steps_offset in [0, 1]:
           self.check_over_configs(steps_offset=UpperCamelCase__						)

       snake_case    :      Any      					=    self.scheduler_classes[0]
       snake_case    :      List[Any]      					=    self.get_scheduler_config(steps_offset=1						)
       snake_case    :      List[Any]      					=    scheduler_class(**UpperCamelCase__						)
       scheduler.set_timesteps(10						)
       assert torch.equal(
           scheduler.timesteps						,	torch.LongTensor(
               [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1]						)						,	)







   def  lowerCamelCase		(	self						)	->		Dict:

       '''simple docstring'''




       for beta_start, beta_end in zip([0.0001, 0.001]						,	[0.002, 0.02]						):
           self.check_over_configs(beta_start=UpperCamelCase__						,	beta_end=UpperCamelCase__						)







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

       '''simple docstring'''




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







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




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







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

       '''simple docstring'''




       for t in [1, 5, 10]:
           self.check_over_forward(time_step=UpperCamelCase__						)







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

       '''simple docstring'''




       for t, num_inference_steps in zip([1, 5, 10]						,	[10, 50, 100]						):
           self.check_over_forward(num_inference_steps=UpperCamelCase__						)







   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       snake_case    :      Union[str, Any]      					=    27

       for scheduler_class in self.scheduler_classes:
           snake_case    :      int      					=    self.dummy_sample
           snake_case    :      str      					=    0.1 * sample

           snake_case    :      Optional[Any]      					=    self.get_scheduler_config()
           snake_case    :      List[Any]      					=    scheduler_class(**UpperCamelCase__						)

           scheduler.set_timesteps(UpperCamelCase__						)

           # before power of 3 fix, would error on first step, so we only need to do two
           for i, t in enumerate(scheduler.prk_timesteps[:2]						):
               snake_case    :      List[Any]      					=    scheduler.step_prk(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						).prev_sample







   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       with self.assertRaises(UpperCamelCase__						):
           snake_case    :      Any      					=    self.scheduler_classes[0]
           snake_case    :      Tuple      					=    self.get_scheduler_config()
           snake_case    :      Optional[int]      					=    scheduler_class(**UpperCamelCase__						)

           scheduler.step_plms(self.dummy_sample						,	1						,	self.dummy_sample						).prev_sample







   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       snake_case    :      Union[str, Any]      					=    self.full_loop()
       snake_case    :      int      					=    torch.sum(torch.abs(UpperCamelCase__						)						)
       snake_case    :      str      					=    torch.mean(torch.abs(UpperCamelCase__						)						)

       assert abs(result_sum.item() - 198.1318						) < 1e-2
       assert abs(result_mean.item() - 0.2580						) < 1e-3







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

       '''simple docstring'''




       snake_case    :      List[str]      					=    self.full_loop(prediction_type="v_prediction"						)
       snake_case    :      Union[str, Any]      					=    torch.sum(torch.abs(UpperCamelCase__						)						)
       snake_case    :      Tuple      					=    torch.mean(torch.abs(UpperCamelCase__						)						)

       assert abs(result_sum.item() - 67.3986						) < 1e-2
       assert abs(result_mean.item() - 0.0878						) < 1e-3







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

       '''simple docstring'''




       snake_case    :      str      					=    self.full_loop(set_alpha_to_one=UpperCamelCase__						,	beta_start=0.01						)
       snake_case    :      List[str]      					=    torch.sum(torch.abs(UpperCamelCase__						)						)
       snake_case    :      Any      					=    torch.mean(torch.abs(UpperCamelCase__						)						)

       assert abs(result_sum.item() - 230.0399						) < 1e-2
       assert abs(result_mean.item() - 0.2995						) < 1e-3







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

       '''simple docstring'''




       snake_case    :      Optional[int]      					=    self.full_loop(set_alpha_to_one=UpperCamelCase__						,	beta_start=0.01						)
       snake_case    :      Union[str, Any]      					=    torch.sum(torch.abs(UpperCamelCase__						)						)
       snake_case    :      Optional[int]      					=    torch.mean(torch.abs(UpperCamelCase__						)						)

       assert abs(result_sum.item() - 186.9482						) < 1e-2
       assert abs(result_mean.item() - 0.2434						) < 1e-3









"""simple docstring"""



import importlib.util
import json
import os
import warnings
from dataclasses import dataclass, field

import torch

from ..training_args import TrainingArguments
from ..utils import cached_property, is_sagemaker_dp_enabled, logging


__snake_case   			=    logging.get_logger(__name__)







def   __lowerCAmelCase						(						)	->						str:


    """simple docstring"""





    snake_case    :      Dict      					=    os.getenv("SM_HP_MP_PARAMETERS"						,							"{}" )
    try:
        # Parse it and check the field "partitions" is included, it is required for model parallel.
        snake_case    :      Optional[int]      					=    json.loads(lowercase )
        if "partitions" not in smp_options:
            return False
    except json.JSONDecodeError:
        return False

    # Get the sagemaker specific framework parameters from mpi_options variable.
    snake_case    :      Optional[int]      					=    os.getenv("SM_FRAMEWORK_PARAMS"						,							"{}" )
    try:
        # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
        snake_case    :      Any      					=    json.loads(lowercase )
        if not mpi_options.get("sagemaker_mpi_enabled"						,							lowercase ):
            return False
    except json.JSONDecodeError:
        return False
    # Lastly, check if the `smdistributed` module is present.
    return importlib.util.find_spec("smdistributed" ) is not None


if is_sagemaker_model_parallel_available():
  import smdistributed.modelparallel.torch as smp

  smp.init()







@dataclass
class _lowerCAmelCase				(      snake_case_	):
   __UpperCAmelCase :       str							  =  field(
       default=''''''    ,							metadata={'''help''': '''Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer'''}    ,							)







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

       '''simple docstring'''




       super().__post_init__()
       warnings.warn(
           "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use "
           "`TrainingArguments` instead."						,	UpperCamelCase__						,	)







   @cached_property
   def  lowerCamelCase		(	self						)	->		"torch.device":

       '''simple docstring'''




       logger.info("PyTorch: setting up devices"						)
       if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1:
           logger.warning(
               "torch.distributed process group is initialized, but local_rank == -1. "
               "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch"						)
       if self.no_cuda:
           snake_case    :      Optional[Any]      					=    torch.device("cpu"						)
           snake_case    :      List[Any]      					=    0
       elif is_sagemaker_model_parallel_available():
           snake_case    :      Tuple      					=    smp.local_rank()
           snake_case    :      int      					=    torch.device("cuda"						,	UpperCamelCase__						)
           snake_case    :      Dict      					=    1
       elif is_sagemaker_dp_enabled():
           import smdistributed.dataparallel.torch.torch_smddp  # noqa: F401

           torch.distributed.init_process_group(backend="smddp"						,	timeout=self.ddp_timeout_delta						)
           snake_case    :      Any      					=    int(os.getenv("SMDATAPARALLEL_LOCAL_RANK"						)						)
           snake_case    :      Optional[Any]      					=    torch.device("cuda"						,	self.local_rank						)
           snake_case    :      str      					=    1
       elif self.local_rank == -1:
           # if n_gpu is > 1 we'll use nn.DataParallel.
           # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
           # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will
           # trigger an error that a device index is missing. Index 0 takes into account the
           # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0`
           # will use the first GPU in that env, i.e. GPU#1
           snake_case    :      List[str]      					=    torch.device("cuda:0" if torch.cuda.is_available() else "cpu"						)
           # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at
           # the default value.
           snake_case    :      Optional[Any]      					=    torch.cuda.device_count()
       else:
           # Here, we'll use torch.distributed.
           # Initializes the distributed backend which will take care of synchronizing nodes/GPUs
           if not torch.distributed.is_initialized():
               torch.distributed.init_process_group(backend="nccl"						,	timeout=self.ddp_timeout_delta						)
           snake_case    :      Any      					=    torch.device("cuda"						,	self.local_rank						)
           snake_case    :      Dict      					=    1

       if device.type == "cuda":
           torch.cuda.set_device(UpperCamelCase__						)

       return device







   @property
   def  lowerCamelCase		(	self						)	->		Optional[int]:

       '''simple docstring'''




       if is_sagemaker_model_parallel_available():
           return smp.dp_size()

       return super().world_size







   @property
   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       return not is_sagemaker_model_parallel_available()







   @property
   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       return False





