


"""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 warnings
from typing import List
from unittest.mock import Mock

import torch
from torch.utils.data import DataLoader, IterableDataset, TensorDataset

from accelerate.accelerator import Accelerator
from accelerate.utils.dataclasses import DistributedType


class 				SCREAMING_SNAKE_CASE__    (		lowercase    ):
       """simple docstring"""


       def __init__(						self		,					snake_case__						):






         """simple docstring"""





         lowerCAmelCase					:					List[str]								=							data







       def __iter__(						self						):






         """simple docstring"""





         for element in self.data:
           yield element

def  a__      (    SCREAMING_SNAKE_CASE   :   Optional[Any]=True    ):


  '''simple docstring'''







  lowerCAmelCase					:					Union[str, Any]								=							Accelerator(even_batches=SCREAMING_SNAKE_CASE    )
  assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
  return accelerator
def  a__      (    SCREAMING_SNAKE_CASE   :   Accelerator    ,				SCREAMING_SNAKE_CASE   :   int    ,				SCREAMING_SNAKE_CASE   :   int    ,				SCREAMING_SNAKE_CASE   :   bool = False    ):


  '''simple docstring'''







  if iterable:
    lowerCAmelCase					:					int								=							DummyIterableDataset(torch.as_tensor(range(SCREAMING_SNAKE_CASE    )    )    )
  else:
    lowerCAmelCase					:					Tuple								=							TensorDataset(torch.as_tensor(range(SCREAMING_SNAKE_CASE    )    )    )

  lowerCAmelCase					:					Any								=							DataLoader(SCREAMING_SNAKE_CASE    ,				batch_size=SCREAMING_SNAKE_CASE    )
  lowerCAmelCase					:					Union[str, Any]								=							accelerator.prepare(SCREAMING_SNAKE_CASE    )

  return dl
def  a__      (    SCREAMING_SNAKE_CASE   :   Accelerator    ,				SCREAMING_SNAKE_CASE   :   int    ,				SCREAMING_SNAKE_CASE   :   int    ,				SCREAMING_SNAKE_CASE   :   List[int]    ,				SCREAMING_SNAKE_CASE   :   List[int]    ,				):


  '''simple docstring'''







  lowerCAmelCase					:					str								=							create_dataloader(accelerator=SCREAMING_SNAKE_CASE    ,				dataset_size=SCREAMING_SNAKE_CASE    ,				batch_size=SCREAMING_SNAKE_CASE    )

  lowerCAmelCase					:					List[str]								=							[len(batch[0]    ) for batch in dl]

  if accelerator.process_index == 0:
    assert batch_sizes == process_0_expected_batch_sizes
  elif accelerator.process_index == 1:
    assert batch_sizes == process_1_expected_batch_sizes
def  a__      (    ):


  '''simple docstring'''







  lowerCAmelCase					:					List[Any]								=							create_accelerator()

  # without padding, we would expect a different number of batches
  verify_dataloader_batch_sizes(
      SCREAMING_SNAKE_CASE    ,				dataset_size=3    ,				batch_size=1    ,				process_0_expected_batch_sizes=[1, 1]    ,				process_1_expected_batch_sizes=[1, 1]    ,				)

  # without padding, we would expect the same number of batches, but different sizes
  verify_dataloader_batch_sizes(
      SCREAMING_SNAKE_CASE    ,				dataset_size=7    ,				batch_size=2    ,				process_0_expected_batch_sizes=[2, 2]    ,				process_1_expected_batch_sizes=[2, 2]    ,				)
def  a__      (    ):


  '''simple docstring'''







  lowerCAmelCase					:					int								=							create_accelerator(even_batches=SCREAMING_SNAKE_CASE    )

  verify_dataloader_batch_sizes(
      SCREAMING_SNAKE_CASE    ,				dataset_size=3    ,				batch_size=1    ,				process_0_expected_batch_sizes=[1, 1]    ,				process_1_expected_batch_sizes=[1]    ,				)

  verify_dataloader_batch_sizes(
      SCREAMING_SNAKE_CASE    ,				dataset_size=7    ,				batch_size=2    ,				process_0_expected_batch_sizes=[2, 2]    ,				process_1_expected_batch_sizes=[2, 1]    ,				)
def  a__      (    ):


  '''simple docstring'''







  lowerCAmelCase					:					List[str]								=							create_accelerator(even_batches=SCREAMING_SNAKE_CASE    )

  lowerCAmelCase					:					Optional[int]								=							torch.nn.Linear(1    ,				1    )
  lowerCAmelCase					:					Optional[int]								=							accelerator.prepare(SCREAMING_SNAKE_CASE    )

  lowerCAmelCase					:					Optional[int]								=							create_dataloader(SCREAMING_SNAKE_CASE    ,				dataset_size=3    ,				batch_size=1    )

  lowerCAmelCase					:					Union[str, Any]								=							[]
  with accelerator.join_uneven_inputs([ddp_model]    ):
    for batch_idx, batch in enumerate(SCREAMING_SNAKE_CASE    ):
      lowerCAmelCase					:					str								=							ddp_model(batch[0].float()    )
      lowerCAmelCase					:					Union[str, Any]								=							output.sum()
      loss.backward()
      batch_idxs.append(SCREAMING_SNAKE_CASE    )

  accelerator.wait_for_everyone()

  if accelerator.process_index == 0:
    assert batch_idxs == [0, 1]
  elif accelerator.process_index == 1:
    assert batch_idxs == [0]
def  a__      (    SCREAMING_SNAKE_CASE   :   Tuple    ):


  '''simple docstring'''







  with warnings.catch_warnings(record=SCREAMING_SNAKE_CASE    ) as w:
    with accelerator.join_uneven_inputs([Mock()]    ):
      pass

    assert issubclass(w[-1].category    ,				SCREAMING_SNAKE_CASE    )
    assert "only supported for multi-GPU" in str(w[-1].message    )
def  a__      (    ):


  '''simple docstring'''







  lowerCAmelCase					:					Union[str, Any]								=							True
  lowerCAmelCase					:					List[Any]								=							False
  lowerCAmelCase					:					Any								=							create_accelerator(even_batches=SCREAMING_SNAKE_CASE    )
  lowerCAmelCase					:					str								=							torch.nn.Linear(1    ,				1    )
  lowerCAmelCase					:					str								=							accelerator.prepare(SCREAMING_SNAKE_CASE    )
  lowerCAmelCase					:					List[Any]								=							create_dataloader(SCREAMING_SNAKE_CASE    ,				dataset_size=3    ,				batch_size=1    )
  lowerCAmelCase					:					Tuple								=							create_dataloader(SCREAMING_SNAKE_CASE    ,				dataset_size=3    ,				batch_size=1    )

  with accelerator.join_uneven_inputs([ddp_model]    ,				even_batches=SCREAMING_SNAKE_CASE    ):
    lowerCAmelCase					:					Optional[Any]								=							train_dl.batch_sampler.even_batches
    lowerCAmelCase					:					Optional[int]								=							valid_dl.batch_sampler.even_batches

  assert train_dl_overridden_value == overridden_even_batches
  assert valid_dl_overridden_value == overridden_even_batches
  assert train_dl.batch_sampler.even_batches == default_even_batches
  assert valid_dl.batch_sampler.even_batches == default_even_batches
def  a__      (    ):


  '''simple docstring'''







  lowerCAmelCase					:					Dict								=							True
  lowerCAmelCase					:					str								=							False
  lowerCAmelCase					:					Dict								=							create_accelerator(even_batches=SCREAMING_SNAKE_CASE    )
  lowerCAmelCase					:					List[Any]								=							torch.nn.Linear(1    ,				1    )
  lowerCAmelCase					:					int								=							accelerator.prepare(SCREAMING_SNAKE_CASE    )
  create_dataloader(SCREAMING_SNAKE_CASE    ,				dataset_size=3    ,				batch_size=1    ,				iterable=SCREAMING_SNAKE_CASE    )
  lowerCAmelCase					:					List[Any]								=							create_dataloader(SCREAMING_SNAKE_CASE    ,				dataset_size=3    ,				batch_size=1    )

  with warnings.catch_warnings():
    warnings.filterwarnings("ignore"    )
    try:
      with accelerator.join_uneven_inputs([ddp_model]    ,				even_batches=SCREAMING_SNAKE_CASE    ):
        lowerCAmelCase					:					Optional[int]								=							batch_dl.batch_sampler.even_batches
    except AttributeError:
      # ensure attribute error is not raised when processing iterable dl
      raise AssertionError

  assert batch_dl_overridden_value == overridden_even_batches
  assert batch_dl.batch_sampler.even_batches == default_even_batches
def  a__      (    ):


  '''simple docstring'''







  lowerCAmelCase					:					str								=							create_accelerator()
  lowerCAmelCase					:					Optional[int]								=							torch.nn.Linear(1    ,				1    )
  lowerCAmelCase					:					Optional[int]								=							accelerator.prepare(SCREAMING_SNAKE_CASE    )
  create_dataloader(SCREAMING_SNAKE_CASE    ,				dataset_size=3    ,				batch_size=1    ,				iterable=SCREAMING_SNAKE_CASE    )

  with warnings.catch_warnings(record=SCREAMING_SNAKE_CASE    ) as w:
    with accelerator.join_uneven_inputs([ddp_model]    ,				even_batches=SCREAMING_SNAKE_CASE    ):
      pass

    assert issubclass(w[-1].category    ,				SCREAMING_SNAKE_CASE    )
    assert "only supported for map-style datasets" in str(w[-1].message    )
def  a__      (    ):


  '''simple docstring'''







  lowerCAmelCase					:					str								=							create_accelerator()

  accelerator.print("Test that even_batches variable ensures uniform batches across processes"    )
  test_default_ensures_even_batch_sizes()

  accelerator.print("Run tests with even_batches disabled"    )
  test_can_disable_even_batches()

  accelerator.print("Test joining uneven inputs"    )
  test_can_join_uneven_inputs()

  accelerator.print("Test overriding even_batches when joining uneven inputs"    )
  test_join_can_override_even_batches()

  accelerator.print("Test overriding even_batches for mixed dataloader types"    )
  test_join_can_override_for_mixed_type_dataloaders()

  accelerator.print("Test overriding even_batches raises a warning for iterable dataloaders"    )
  test_join_raises_warning_for_iterable_when_overriding_even_batches()

  accelerator.print("Test join with non DDP distributed raises warning"    )
  lowerCAmelCase					:					Any								=							accelerator.state.distributed_type
  lowerCAmelCase					:					Union[str, Any]								=							DistributedType.FSDP
  test_join_raises_warning_for_non_ddp_distributed(SCREAMING_SNAKE_CASE    )
  lowerCAmelCase					:					Optional[int]								=							original_state


if __name__ == "__main__":
     main()









"""simple docstring"""







import tempfile

import torch

from diffusers import (
    DEISMultistepScheduler,
    DPMSolverMultistepScheduler,
    DPMSolverSinglestepScheduler,
    UniPCMultistepScheduler,
)

from .test_schedulers import SchedulerCommonTest


class 				SCREAMING_SNAKE_CASE__    (		lowercase    ):
       """simple docstring"""


       a  :    Optional[int]       =(DEISMultistepScheduler,)
       a  :    str       =(("num_inference_steps", 25),)

       def 	lowercase__							(						self		,					**snake_case__						):






         """simple docstring"""





         lowerCAmelCase					:					Tuple								=							{
             "num_train_timesteps": 1_000,
             "beta_start": 0.0001,
             "beta_end": 0.02,
             "beta_schedule": "linear",
             "solver_order": 2,
         }

         config.update(**snake_case__						)
         return config

       def 	lowercase__							(						self		,					snake_case__=0		,					**snake_case__						):






         """simple docstring"""





         lowerCAmelCase					:					List[str]								=							dict(self.forward_default_kwargs						)
         lowerCAmelCase					:					List[str]								=							kwargs.pop("num_inference_steps"		,					snake_case__						)
         lowerCAmelCase					:					List[str]								=							self.dummy_sample
         lowerCAmelCase					:					int								=							0.1 * sample
         lowerCAmelCase					:					Tuple								=							[residual + 0.2, residual + 0.15, residual + 0.10]

         for scheduler_class in self.scheduler_classes:
           lowerCAmelCase					:					Any								=							self.get_scheduler_config(**snake_case__						)
           lowerCAmelCase					:					List[str]								=							scheduler_class(**snake_case__						)
           scheduler.set_timesteps(snake_case__						)
           # copy over dummy past residuals
           lowerCAmelCase					:					str								=							dummy_past_residuals[: scheduler.config.solver_order]

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

           lowerCAmelCase						,  lowerCAmelCase					:					Union[str, Any]								=							sample, sample
           for t in range(snake_case__		,					time_step + scheduler.config.solver_order + 1						):
             lowerCAmelCase					:					Any								=							scheduler.step(snake_case__		,					snake_case__		,					snake_case__		,					**snake_case__						).prev_sample
             lowerCAmelCase					:					str								=							new_scheduler.step(snake_case__		,					snake_case__		,					snake_case__		,					**snake_case__						).prev_sample

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

       def 	lowercase__							(						self						):






         """simple docstring"""





         pass

       def 	lowercase__							(						self		,					snake_case__=0		,					**snake_case__						):






         """simple docstring"""





         lowerCAmelCase					:					Dict								=							dict(self.forward_default_kwargs						)
         lowerCAmelCase					:					List[str]								=							kwargs.pop("num_inference_steps"		,					snake_case__						)
         lowerCAmelCase					:					List[str]								=							self.dummy_sample
         lowerCAmelCase					:					Optional[int]								=							0.1 * sample
         lowerCAmelCase					:					List[Any]								=							[residual + 0.2, residual + 0.15, residual + 0.10]

         for scheduler_class in self.scheduler_classes:
           lowerCAmelCase					:					int								=							self.get_scheduler_config()
           lowerCAmelCase					:					Any								=							scheduler_class(**snake_case__						)
           scheduler.set_timesteps(snake_case__						)

           # copy over dummy past residuals (must be after setting timesteps)
           lowerCAmelCase					:					Union[str, Any]								=							dummy_past_residuals[: scheduler.config.solver_order]

           with tempfile.TemporaryDirectory() as tmpdirname:
             scheduler.save_config(snake_case__						)
             lowerCAmelCase					:					Any								=							scheduler_class.from_pretrained(snake_case__						)
             # copy over dummy past residuals
             new_scheduler.set_timesteps(snake_case__						)

             # copy over dummy past residual (must be after setting timesteps)
             lowerCAmelCase					:					Optional[int]								=							dummy_past_residuals[: new_scheduler.config.solver_order]

           lowerCAmelCase					:					Union[str, Any]								=							scheduler.step(snake_case__		,					snake_case__		,					snake_case__		,					**snake_case__						).prev_sample
           lowerCAmelCase					:					int								=							new_scheduler.step(snake_case__		,					snake_case__		,					snake_case__		,					**snake_case__						).prev_sample

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

       def 	lowercase__							(						self		,					snake_case__=None		,					**snake_case__						):






         """simple docstring"""





         if scheduler is None:
           lowerCAmelCase					:					List[str]								=							self.scheduler_classes[0]
           lowerCAmelCase					:					Optional[int]								=							self.get_scheduler_config(**snake_case__						)
           lowerCAmelCase					:					Any								=							scheduler_class(**snake_case__						)

         lowerCAmelCase					:					List[str]								=							self.scheduler_classes[0]
         lowerCAmelCase					:					Tuple								=							self.get_scheduler_config(**snake_case__						)
         lowerCAmelCase					:					List[str]								=							scheduler_class(**snake_case__						)

         lowerCAmelCase					:					int								=							10
         lowerCAmelCase					:					List[str]								=							self.dummy_model()
         lowerCAmelCase					:					List[Any]								=							self.dummy_sample_deter
         scheduler.set_timesteps(snake_case__						)

         for i, t in enumerate(scheduler.timesteps						):
           lowerCAmelCase					:					Any								=							model(snake_case__		,					snake_case__						)
           lowerCAmelCase					:					List[Any]								=							scheduler.step(snake_case__		,					snake_case__		,					snake_case__						).prev_sample

         return sample

       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					Dict								=							dict(self.forward_default_kwargs						)

         lowerCAmelCase					:					Optional[Any]								=							kwargs.pop("num_inference_steps"		,					snake_case__						)

         for scheduler_class in self.scheduler_classes:
           lowerCAmelCase					:					Dict								=							self.get_scheduler_config()
           lowerCAmelCase					:					List[Any]								=							scheduler_class(**snake_case__						)

           lowerCAmelCase					:					int								=							self.dummy_sample
           lowerCAmelCase					:					int								=							0.1 * sample

           if num_inference_steps is not None and hasattr(snake_case__		,					"set_timesteps"						):
             scheduler.set_timesteps(snake_case__						)
           elif num_inference_steps is not None and not hasattr(snake_case__		,					"set_timesteps"						):
             lowerCAmelCase					:					List[str]								=							num_inference_steps

           # copy over dummy past residuals (must be done after set_timesteps)
           lowerCAmelCase					:					int								=							[residual + 0.2, residual + 0.15, residual + 0.10]
           lowerCAmelCase					:					Tuple								=							dummy_past_residuals[: scheduler.config.solver_order]

           lowerCAmelCase					:					int								=							scheduler.timesteps[5]
           lowerCAmelCase					:					str								=							scheduler.timesteps[6]

           lowerCAmelCase					:					str								=							scheduler.step(snake_case__		,					snake_case__		,					snake_case__		,					**snake_case__						).prev_sample
           lowerCAmelCase					:					Union[str, Any]								=							scheduler.step(snake_case__		,					snake_case__		,					snake_case__		,					**snake_case__						).prev_sample

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

       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					int								=							DEISMultistepScheduler(**self.get_scheduler_config()						)
         lowerCAmelCase					:					Dict								=							self.full_loop(scheduler=snake_case__						)
         lowerCAmelCase					:					Optional[Any]								=							torch.mean(torch.abs(snake_case__						)						)

         assert abs(result_mean.item() - 0.23916						) < 1e-3

         lowerCAmelCase					:					List[str]								=							DPMSolverSinglestepScheduler.from_config(scheduler.config						)
         lowerCAmelCase					:					Any								=							DPMSolverMultistepScheduler.from_config(scheduler.config						)
         lowerCAmelCase					:					str								=							UniPCMultistepScheduler.from_config(scheduler.config						)
         lowerCAmelCase					:					Union[str, Any]								=							DEISMultistepScheduler.from_config(scheduler.config						)

         lowerCAmelCase					:					Union[str, Any]								=							self.full_loop(scheduler=snake_case__						)
         lowerCAmelCase					:					str								=							torch.mean(torch.abs(snake_case__						)						)

         assert abs(result_mean.item() - 0.23916						) < 1e-3

       def 	lowercase__							(						self						):






         """simple docstring"""





         for timesteps in [25, 50, 100, 999, 1_000]:
           self.check_over_configs(num_train_timesteps=snake_case__						)

       def 	lowercase__							(						self						):






         """simple docstring"""





         self.check_over_configs(thresholding=snake_case__						)
         for order in [1, 2, 3]:
           for solver_type in ["logrho"]:
             for threshold in [0.5, 1.0, 2.0]:
               for prediction_type in ["epsilon", "sample"]:
                 self.check_over_configs(
                     thresholding=snake_case__		,					prediction_type=snake_case__		,					sample_max_value=snake_case__		,					algorithm_type="deis"		,					solver_order=snake_case__		,					solver_type=snake_case__		,					)

       def 	lowercase__							(						self						):






         """simple docstring"""





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

       def 	lowercase__							(						self						):






         """simple docstring"""





         for algorithm_type in ["deis"]:
           for solver_type in ["logrho"]:
             for order in [1, 2, 3]:
               for prediction_type in ["epsilon", "sample"]:
                 self.check_over_configs(
                     solver_order=snake_case__		,					solver_type=snake_case__		,					prediction_type=snake_case__		,					algorithm_type=snake_case__		,					)
                 lowerCAmelCase					:					Any								=							self.full_loop(
                     solver_order=snake_case__		,					solver_type=snake_case__		,					prediction_type=snake_case__		,					algorithm_type=snake_case__		,					)
                 assert not torch.isnan(snake_case__						).any(), "Samples have nan numbers"

       def 	lowercase__							(						self						):






         """simple docstring"""





         self.check_over_configs(lower_order_final=snake_case__						)
         self.check_over_configs(lower_order_final=snake_case__						)

       def 	lowercase__							(						self						):






         """simple docstring"""





         for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1_000]:
           self.check_over_forward(num_inference_steps=snake_case__		,					time_step=0						)

       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					List[str]								=							self.full_loop()
         lowerCAmelCase					:					Dict								=							torch.mean(torch.abs(snake_case__						)						)

         assert abs(result_mean.item() - 0.23916						) < 1e-3

       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					Optional[Any]								=							self.full_loop(prediction_type="v_prediction"						)
         lowerCAmelCase					:					List[Any]								=							torch.mean(torch.abs(snake_case__						)						)

         assert abs(result_mean.item() - 0.091						) < 1e-3







       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					Dict								=							self.scheduler_classes[0]
         lowerCAmelCase					:					str								=							self.get_scheduler_config(thresholding=snake_case__		,					dynamic_thresholding_ratio=0						)
         lowerCAmelCase					:					Optional[Any]								=							scheduler_class(**snake_case__						)

         lowerCAmelCase					:					Optional[Any]								=							10
         lowerCAmelCase					:					Tuple								=							self.dummy_model()
         lowerCAmelCase					:					List[str]								=							self.dummy_sample_deter.half()
         scheduler.set_timesteps(snake_case__						)

         for i, t in enumerate(scheduler.timesteps						):
           lowerCAmelCase					:					Union[str, Any]								=							model(snake_case__		,					snake_case__						)
           lowerCAmelCase					:					Tuple								=							scheduler.step(snake_case__		,					snake_case__		,					snake_case__						).prev_sample

         assert sample.dtype == torch.floataa





