






"""simple docstring"""


import torch

from diffusers import HeunDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest






class 						snake_case  (  UpperCAmelCase       ):
    __magic_name__         =     (HeunDiscreteScheduler,)
    __magic_name__         =     10





    def 				lowerCamelCase__      (							self	:					int				,		**A	:					Optional[Any]			):


      '''simple docstring'''




      a     :			Union[str, Any]				=   {
          'num_train_timesteps': 1_1_0_0,
          'beta_start': 0.00_01,
          'beta_end': 0.02,
          'beta_schedule': 'linear',
      }

      config.update(**A			)
      return config





    def 				lowerCamelCase__      (							self	:					Dict			):


      '''simple docstring'''




      for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]:
        self.check_over_configs(num_train_timesteps=A			)





    def 				lowerCamelCase__      (							self	:					Union[str, Any]			):


      '''simple docstring'''




      for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01]				,		[0.00_02, 0.0_02, 0.02]			):
        self.check_over_configs(beta_start=A				,		beta_end=A			)





    def 				lowerCamelCase__      (							self	:					Tuple			):


      '''simple docstring'''




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





    def 				lowerCamelCase__      (							self	:					List[Any]			):


      '''simple docstring'''




      for clip_sample_range in [1.0, 2.0, 3.0]:
        self.check_over_configs(clip_sample_range=A				,		clip_sample=A			)





    def 				lowerCamelCase__      (							self	:					Tuple			):


      '''simple docstring'''




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





    def 				lowerCamelCase__      (							self	:					List[str]			):


      '''simple docstring'''




      a     :			Optional[int]				=   self.scheduler_classes[0]
      a     :			Optional[int]				=   self.get_scheduler_config()
      a     :			Union[str, Any]				=   scheduler_class(**A			)

      scheduler.set_timesteps(self.num_inference_steps			)

      a     :			Optional[Any]				=   self.dummy_model()
      a     :			str				=   self.dummy_sample_deter * scheduler.init_noise_sigma
      a     :			int				=   sample.to(A			)

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

        a     :			List[str]				=   model(A				,		A			)

        a     :			Tuple				=   scheduler.step(A				,		A				,		A			)
        a     :			Optional[int]				=   output.prev_sample

      a     :			Optional[Any]				=   torch.sum(torch.abs(A			)			)
      a     :			Optional[int]				=   torch.mean(torch.abs(A			)			)

      if torch_device in ["cpu", "mps"]:
        assert abs(result_sum.item() - 0.12_33			) < 1E-2
        assert abs(result_mean.item() - 0.00_02			) < 1E-3
      else:
        # CUDA
        assert abs(result_sum.item() - 0.12_33			) < 1E-2
        assert abs(result_mean.item() - 0.00_02			) < 1E-3





    def 				lowerCamelCase__      (							self	:					Optional[int]			):


      '''simple docstring'''




      a     :			Optional[Any]				=   self.scheduler_classes[0]
      a     :			List[str]				=   self.get_scheduler_config(prediction_type='v_prediction'			)
      a     :			Optional[Any]				=   scheduler_class(**A			)

      scheduler.set_timesteps(self.num_inference_steps			)

      a     :			Union[str, Any]				=   self.dummy_model()
      a     :			List[Any]				=   self.dummy_sample_deter * scheduler.init_noise_sigma
      a     :			Optional[Any]				=   sample.to(A			)

      for i, t in enumerate(scheduler.timesteps			):
        a     :			Optional[Any]				=   scheduler.scale_model_input(A				,		A			)

        a     :			Any				=   model(A				,		A			)

        a     :			Any				=   scheduler.step(A				,		A				,		A			)
        a     :			Optional[int]				=   output.prev_sample

      a     :			int				=   torch.sum(torch.abs(A			)			)
      a     :			Optional[Any]				=   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.00_02			) < 1E-3





    def 				lowerCamelCase__      (							self	:					List[str]			):


      '''simple docstring'''




      a     :			Optional[int]				=   self.scheduler_classes[0]
      a     :			List[str]				=   self.get_scheduler_config()
      a     :			List[Any]				=   scheduler_class(**A			)

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

      a     :			str				=   self.dummy_model()
      a     :			Any				=   self.dummy_sample_deter.to(A			) * scheduler.init_noise_sigma

      for t in scheduler.timesteps:
        a     :			List[Any]				=   scheduler.scale_model_input(A				,		A			)

        a     :			Optional[Any]				=   model(A				,		A			)

        a     :			List[str]				=   scheduler.step(A				,		A				,		A			)
        a     :			Tuple				=   output.prev_sample

      a     :			Optional[Any]				=   torch.sum(torch.abs(A			)			)
      a     :			List[str]				=   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() - 0.12_33			) < 1E-2
        assert abs(result_mean.item() - 0.00_02			) < 1E-3
      elif str(A			).startswith('mps'			):
        # Larger tolerance on mps
        assert abs(result_mean.item() - 0.00_02			) < 1E-2
      else:
        # CUDA
        assert abs(result_sum.item() - 0.12_33			) < 1E-2
        assert abs(result_mean.item() - 0.00_02			) < 1E-3





    def 				lowerCamelCase__      (							self	:					int			):


      '''simple docstring'''




      a     :			Tuple				=   self.scheduler_classes[0]
      a     :			int				=   self.get_scheduler_config()
      a     :			List[Any]				=   scheduler_class(**A				,		use_karras_sigmas=A			)

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

      a     :			str				=   self.dummy_model()
      a     :			List[str]				=   self.dummy_sample_deter.to(A			) * scheduler.init_noise_sigma
      a     :			Tuple				=   sample.to(A			)

      for t in scheduler.timesteps:
        a     :			List[str]				=   scheduler.scale_model_input(A				,		A			)

        a     :			List[Any]				=   model(A				,		A			)

        a     :			Dict				=   scheduler.step(A				,		A				,		A			)
        a     :			Optional[Any]				=   output.prev_sample

      a     :			Union[str, Any]				=   torch.sum(torch.abs(A			)			)
      a     :			Optional[Any]				=   torch.mean(torch.abs(A			)			)

      assert abs(result_sum.item() - 0.0_00_15			) < 1E-2
      assert abs(result_mean.item() - 1.9869_5545_3503_4695E-07			) < 1E-2







import os
import pickle
import unittest
from collections import UserDict, namedtuple

import torch

from accelerate.test_utils.testing import require_cuda, require_torch_min_version
from accelerate.test_utils.training import RegressionModel
from accelerate.utils import (
    convert_outputs_to_fpaa,
    extract_model_from_parallel,
    find_device,
    listify,
    patch_environment,
    recursively_apply,
    send_to_device,
)


_UpperCamelCase			       =			namedtuple('''ExampleNamedTuple''', '''a b c''')



class     lowercase						(       unittest.TestCase					):



 '''simple docstring'''


 def   UpperCamelCase__							(self ) ->					Tuple:






  """simple docstring"""





  UpperCAmelCase__							=				torch.randn(5       ,       2 )
  UpperCAmelCase__							=				torch.device('cuda' ) if torch.cuda.is_available() else torch.device('cpu' )

  UpperCAmelCase__							=				send_to_device(__a       ,       __a )
  self.assertTrue(torch.equal(resulta.cpu()       ,       __a ) )

  UpperCAmelCase__							=				send_to_device((tensor, [tensor, tensor], 1)       ,       __a )
  self.assertIsInstance(__a       ,       __a )
  self.assertTrue(torch.equal(resulta[0].cpu()       ,       __a ) )
  self.assertIsInstance(resulta[1]       ,       __a )
  self.assertTrue(torch.equal(resulta[1][0].cpu()       ,       __a ) )
  self.assertTrue(torch.equal(resulta[1][1].cpu()       ,       __a ) )
  self.assertEqual(resulta[2]       ,       1 )

  UpperCAmelCase__							=				send_to_device({'a': tensor, 'b': [tensor, tensor], 'c': 1}       ,       __a )
  self.assertIsInstance(__a       ,       __a )
  self.assertTrue(torch.equal(resulta['a'].cpu()       ,       __a ) )
  self.assertIsInstance(resulta['b']       ,       __a )
  self.assertTrue(torch.equal(resulta['b'][0].cpu()       ,       __a ) )
  self.assertTrue(torch.equal(resulta['b'][1].cpu()       ,       __a ) )
  self.assertEqual(resulta['c']       ,       1 )

  UpperCAmelCase__							=				send_to_device(ExampleNamedTuple(a=__a       ,       b=[tensor, tensor]       ,       c=1 )       ,       __a )
  self.assertIsInstance(__a       ,       __a )
  self.assertTrue(torch.equal(resulta.a.cpu()       ,       __a ) )
  self.assertIsInstance(resulta.b       ,       __a )
  self.assertTrue(torch.equal(resulta.b[0].cpu()       ,       __a ) )
  self.assertTrue(torch.equal(resulta.b[1].cpu()       ,       __a ) )
  self.assertEqual(resulta.c       ,       1 )

  UpperCAmelCase__							=				send_to_device(UserDict({'a': tensor, 'b': [tensor, tensor], 'c': 1} )       ,       __a )
  self.assertIsInstance(__a       ,       __a )
  self.assertTrue(torch.equal(resulta['a'].cpu()       ,       __a ) )
  self.assertIsInstance(resulta['b']       ,       __a )
  self.assertTrue(torch.equal(resulta['b'][0].cpu()       ,       __a ) )
  self.assertTrue(torch.equal(resulta['b'][1].cpu()       ,       __a ) )
  self.assertEqual(resulta['c']       ,       1 )




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






  """simple docstring"""





  with self.assertRaises(__a ) as cm:
   UpperCAmelCase__							=				recursively_apply(torch.tensor       ,       (torch.tensor(1 ), 1)       ,       error_on_other_type=__a )
  self.assertEqual(
      str(cm.exception )       ,       'Unsupported types (<class \'int\'>) passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed.'       ,       )




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






  """simple docstring"""





  UpperCAmelCase__							=				torch.tensor([1, 2, 3, 4, 5] )
  self.assertEqual(listify(__a )       ,       [1, 2, 3, 4, 5] )

  UpperCAmelCase__							=				torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] )
  self.assertEqual(listify(__a )       ,       [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] )

  UpperCAmelCase__							=				torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]] )
  self.assertEqual(
      listify(__a )       ,       [[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]] )




 def   UpperCamelCase__							(self ) ->					int:






  """simple docstring"""





  with patch_environment(aa=1       ,       BB=2 ):
   self.assertEqual(os.environ.get('AA' )       ,       '1' )
   self.assertEqual(os.environ.get('BB' )       ,       '2' )

  self.assertNotIn('AA'       ,       os.environ )
  self.assertNotIn('BB'       ,       os.environ )




 def   UpperCamelCase__							(self ) ->					Dict:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  UpperCAmelCase__							=				model.forward
  UpperCAmelCase__							=				convert_outputs_to_fpaa(model.forward )
  UpperCAmelCase__							=				extract_model_from_parallel(__a       ,       keep_fpaa_wrapper=__a )
  UpperCAmelCase__							=				pickle.dumps(__a )




 @require_cuda
 def   UpperCamelCase__							(self ) ->					Tuple:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  UpperCAmelCase__							=				model.forward
  UpperCAmelCase__							=				torch.cuda.amp.autocast(dtype=torch.floataa )(model.forward )
  UpperCAmelCase__							=				convert_outputs_to_fpaa(model.forward )
  UpperCAmelCase__							=				extract_model_from_parallel(__a       ,       keep_fpaa_wrapper=__a )
  UpperCAmelCase__							=				pickle.dumps(__a )




 @require_cuda
 @require_torch_min_version(version='2.0' )
 def   UpperCamelCase__							(self ) ->					List[str]:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  UpperCAmelCase__							=				model.forward
  UpperCAmelCase__							=				torch.cuda.amp.autocast(dtype=torch.floataa )(model.forward )
  UpperCAmelCase__							=				convert_outputs_to_fpaa(model.forward )
  UpperCAmelCase__							=				torch.compile(model.forward       ,       backend='inductor' )
  UpperCAmelCase__							=				torch.randn(4       ,       10 ).cuda()
  UpperCAmelCase__							=				model(__a )




 def   UpperCamelCase__							(self ) ->					Optional[Any]:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
  UpperCAmelCase__							=				torch.nn.parallel.DataParallel(__a )
  UpperCAmelCase__							=				extract_model_from_parallel(__a )

  self.assertEqual(__a       ,       __a )




 @require_torch_min_version(version='2.0' )
 def   UpperCamelCase__							(self ) ->					Optional[Any]:






  """simple docstring"""





  UpperCAmelCase__							=				RegressionModel()
  UpperCAmelCase__							=				torch.compile(__a )

  # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
  UpperCAmelCase__							=				torch.nn.parallel.DataParallel(__a )
  UpperCAmelCase__							=				torch.compile(__a )
  UpperCAmelCase__							=				extract_model_from_parallel(__a )

  self.assertEqual(compiled_model._orig_mod       ,       compiled_model_unwrapped._orig_mod )




 def   UpperCamelCase__							(self ) ->					str:






  """simple docstring"""





  self.assertEqual(find_device([1, 'a', torch.tensor([1, 2, 3] )] )       ,       torch.device('cpu' ) )
  self.assertEqual(find_device({'a': 1, 'b': torch.tensor([1, 2, 3] )} )       ,       torch.device('cpu' ) )
  self.assertIsNone(find_device([1, 'a'] ) )



