






def 						A_					(						lowercase_	,  lowercase_	,  lowercase_	,  lowercase_			)				->str:







 """simple docstring"""

 if start == end:
  return start if lst[start] > item else start + 1
 if start > end:
  return start

 SCREAMING_SNAKE_CASE				    =		(start + end) // 2
 if lst[mid] < item:
  return binary_search(lowercase_	,  lowercase_	,  mid + 1	,  lowercase_			)
 elif lst[mid] > item:
  return binary_search(lowercase_	,  lowercase_	,  lowercase_	,  mid - 1			)
 else:
  return mid





def 						A_					(						lowercase_			)				->Dict:







 """simple docstring"""

 SCREAMING_SNAKE_CASE				    =		len(lowercase_			)

 for index in range(1	,  lowercase_			):
  SCREAMING_SNAKE_CASE				    =		lst[index]
  SCREAMING_SNAKE_CASE				    =		binary_search(lowercase_	,  lowercase_	,  0	,  index - 1			)
  SCREAMING_SNAKE_CASE				    =		lst[:pos] + [value] + lst[pos:index] + lst[index + 1 :]

 return lst





def 						A_					(						lowercase_	,  lowercase_			)				->str:







 """simple docstring"""

 if not left:
  return right

 if not right:
  return left

 if left[0] < right[0]:
  return [left[0], *merge(left[1:]	,  lowercase_			)]

 return [right[0], *merge(lowercase_	,  right[1:]			)]





def 						A_					(						lowercase_			)				->Tuple:







 """simple docstring"""

 SCREAMING_SNAKE_CASE				    =		len(lowercase_			)
 SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		[], []
 SCREAMING_SNAKE_CASE				    =		[lst[0]]
 SCREAMING_SNAKE_CASE				    =		[]
 SCREAMING_SNAKE_CASE				    =		1
 while i < length:
  if lst[i] < lst[i - 1]:
   runs.append(lowercase_			)
   SCREAMING_SNAKE_CASE				    =		[lst[i]]
  else:
   new_run.append(lst[i]			)
  i += 1
 runs.append(lowercase_			)

 for run in runs:
  sorted_runs.append(insertion_sort(lowercase_			)			)
 for run in sorted_runs:
  SCREAMING_SNAKE_CASE				    =		merge(lowercase_	,  lowercase_			)

 return sorted_array





def 						A_					(						)				->Any:







 """simple docstring"""

 SCREAMING_SNAKE_CASE				    =		[5, 9, 1_0, 3, -4, 5, 1_7_8, 9_2, 4_6, -1_8, 0, 7]
 SCREAMING_SNAKE_CASE				    =		tim_sort(lowercase_			)
 print(lowercase_			)


if __name__ == "__main__":
      main()












import tempfile
import unittest

import torch

from diffusers import UNetaDConditionModel
from diffusers.training_utils import EMAModel
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps, torch_device


enable_full_determinism()
class 	a_(		unittest.TestCase	):



     """simple docstring"""



     __snake_case		:				str  					='''hf-internal-testing/tiny-stable-diffusion-pipe'''
     __snake_case		:				Union[str, Any]  					=1
     __snake_case		:				str  					=77
     __snake_case		:				int  					=32
     __snake_case		:				List[str]  					=4
     __snake_case		:				Any  					=64
     __snake_case		:				Optional[int]  					=torch.manual_seed(0	)





     def     __UpperCamelCase						(		self					:	Union[str, Any]  ,  lowerCAmelCase__					:	str=0.99_99)							->	List[Any]:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		UNetaDConditionModel.from_pretrained(self.model_id  ,  subfolder='unet')
      SCREAMING_SNAKE_CASE				    =		unet.to(lowerCAmelCase__)
      SCREAMING_SNAKE_CASE				    =		EMAModel(unet.parameters()  ,  decay=lowerCAmelCase__  ,  model_cls=lowerCAmelCase__  ,  model_config=unet.config)
      return unet, ema_unet





     def     __UpperCamelCase						(		self					:	List[str])							->	Dict:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		torch.randn(
          self.batch_size  ,  self.num_in_channels  ,  self.latent_height  ,  self.latent_width  ,  generator=self.generator).to(lowerCAmelCase__)
      SCREAMING_SNAKE_CASE				    =		torch.randint(0  ,  1_0_0_0  ,  size=(self.batch_size,)  ,  generator=self.generator).to(lowerCAmelCase__)
      SCREAMING_SNAKE_CASE				    =		torch.randn(
          self.batch_size  ,  self.prompt_length  ,  self.text_encoder_hidden_dim  ,  generator=self.generator).to(lowerCAmelCase__)
      return noisy_latents, timesteps, encoder_hidden_states





     def     __UpperCamelCase						(		self					:	int  ,  lowerCAmelCase__					:	Tuple)							->	Dict:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		{}
      for k, param in unet.state_dict().items():
       SCREAMING_SNAKE_CASE				    =		torch.randn_like(lowerCAmelCase__) + (param * torch.randn_like(lowerCAmelCase__))
       updated_state_dict.update({k: updated_param})
      unet.load_state_dict(lowerCAmelCase__)
      return unet





     def     __UpperCamelCase						(		self					:	Optional[int])							->	List[str]:

      """simple docstring"""
      SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		self.get_models()
      # Take the first (hypothetical) EMA step.
      ema_unet.step(unet.parameters())
      assert ema_unet.optimization_step == 1

      # Take two more.
      for _ in range(2):
       ema_unet.step(unet.parameters())
      assert ema_unet.optimization_step == 3





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

      """simple docstring"""
      SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		self.get_models()
      # Since the `unet` is not being updated (i.e., backprop'd)
      # there won't be any difference between the `params` of `unet`
      # and `ema_unet` even if we call `ema_unet.step(unet.parameters())`.
      ema_unet.step(unet.parameters())
      SCREAMING_SNAKE_CASE				    =		list(unet.parameters())
      for s_param, param in zip(ema_unet.shadow_params  ,  lowerCAmelCase__):
       assert torch.allclose(lowerCAmelCase__  ,  lowerCAmelCase__)

      # The above holds true even if we call `ema.step()` multiple times since
      # `unet` params are still not being updated.
      for _ in range(4):
       ema_unet.step(unet.parameters())
      for s_param, param in zip(ema_unet.shadow_params  ,  lowerCAmelCase__):
       assert torch.allclose(lowerCAmelCase__  ,  lowerCAmelCase__)





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

      """simple docstring"""
      SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		self.get_models()
      # Here we simulate the parameter updates for `unet`. Since there might
      # be some parameters which are initialized to zero we take extra care to
      # initialize their values to something non-zero before the multiplication.
      SCREAMING_SNAKE_CASE				    =		self.simulate_backprop(lowerCAmelCase__)

      # Take the EMA step.
      ema_unet.step(unet_pseudo_updated_step_one.parameters())

      # Now the EMA'd parameters won't be equal to the original model parameters.
      SCREAMING_SNAKE_CASE				    =		list(unet_pseudo_updated_step_one.parameters())
      for s_param, param in zip(ema_unet.shadow_params  ,  lowerCAmelCase__):
       assert ~torch.allclose(lowerCAmelCase__  ,  lowerCAmelCase__)

      # Ensure this is the case when we take multiple EMA steps.
      for _ in range(4):
       ema_unet.step(unet.parameters())
      for s_param, param in zip(ema_unet.shadow_params  ,  lowerCAmelCase__):
       assert ~torch.allclose(lowerCAmelCase__  ,  lowerCAmelCase__)





     def     __UpperCamelCase						(		self					:	Optional[Any])							->	Dict:

      """simple docstring"""
      # If we call EMA step after a backpropagation consecutively for two times,
      # the shadow params from those two steps should be different.
      SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		self.get_models()

      # First backprop + EMA
      SCREAMING_SNAKE_CASE				    =		self.simulate_backprop(lowerCAmelCase__)
      ema_unet.step(unet_step_one.parameters())
      SCREAMING_SNAKE_CASE				    =		ema_unet.shadow_params

      # Second backprop + EMA
      SCREAMING_SNAKE_CASE				    =		self.simulate_backprop(lowerCAmelCase__)
      ema_unet.step(unet_step_two.parameters())
      SCREAMING_SNAKE_CASE				    =		ema_unet.shadow_params

      for step_one, step_two in zip(lowerCAmelCase__  ,  lowerCAmelCase__):
       assert ~torch.allclose(lowerCAmelCase__  ,  lowerCAmelCase__)





     def     __UpperCamelCase						(		self					:	List[str])							->	Optional[Any]:

      """simple docstring"""
      # If there's no decay even if there are backprops, EMA steps
      # won't take any effect i.e., the shadow params would remain the
      # same.
      SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		self.get_models(decay=0.0)
      SCREAMING_SNAKE_CASE				    =		self.simulate_backprop(lowerCAmelCase__)
      ema_unet.step(unet_step_one.parameters())
      SCREAMING_SNAKE_CASE				    =		ema_unet.shadow_params

      SCREAMING_SNAKE_CASE				    =		self.simulate_backprop(lowerCAmelCase__)
      ema_unet.step(unet_step_two.parameters())
      SCREAMING_SNAKE_CASE				    =		ema_unet.shadow_params

      for step_one, step_two in zip(lowerCAmelCase__  ,  lowerCAmelCase__):
       assert torch.allclose(lowerCAmelCase__  ,  lowerCAmelCase__)





     @skip_mps
     def     __UpperCamelCase						(		self					:	Optional[int])							->	Tuple:

      """simple docstring"""
      SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		self.get_models()
      SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		self.get_dummy_inputs()

      with tempfile.TemporaryDirectory() as tmpdir:
       ema_unet.save_pretrained(lowerCAmelCase__)
       SCREAMING_SNAKE_CASE				    =		UNetaDConditionModel.from_pretrained(lowerCAmelCase__  ,  model_cls=lowerCAmelCase__)
       SCREAMING_SNAKE_CASE				    =		loaded_unet.to(unet.device)

      # Since no EMA step has been performed the outputs should match.
      SCREAMING_SNAKE_CASE				    =		unet(lowerCAmelCase__  ,  lowerCAmelCase__  ,  lowerCAmelCase__).sample
      SCREAMING_SNAKE_CASE				    =		loaded_unet(lowerCAmelCase__  ,  lowerCAmelCase__  ,  lowerCAmelCase__).sample

      assert torch.allclose(lowerCAmelCase__  ,  lowerCAmelCase__  ,  atol=1e-4)




