




'''simple docstring'''

import os
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device


if is_torch_available():
		import torch

		from transformers import GPTaLMHeadModel





@require_torch
@require_sentencepiece
@require_tokenizers
class __magic_name__(						unittest.TestCase      ):






						@slow
						@unittest.skip("""Model is not available."""       )
						def       __lowerCAmelCase(   self						:						Union[str, Any]       ):



									'''simple docstring'''






									snake_case__          =						"""nvidia/megatron-gpt2-345m/"""
									if "MYDIR" in os.environ:
												snake_case__          =						os.path.join(os.environ["""MYDIR"""]					,   __UpperCamelCase       )
									snake_case__          =						GPTaLMHeadModel.from_pretrained(__UpperCamelCase       )
									model.to(__UpperCamelCase       )
									model.half()

									snake_case__          =						torch.tensor(
									    [[1_0_1, 7_1_1_0, 1_0_0_5, 1_0_5_6, 2_0_2_3, 1_1_3_3_3, 1_7_4_1_3, 1_0_2_9, 1_0_2]]					,   device=__UpperCamelCase					,   dtype=torch.long					,   )

									with torch.no_grad():
												snake_case__          =						model(__UpperCamelCase       ).logits

									snake_case__          =						torch.Size((1, 9, 5_0_2_5_7)       )
									self.assertEqual(output.shape					,   __UpperCamelCase       )

									snake_case__          =						torch.tensor(
									    [
									        4.94_14,
									        -0.29_20,
									        -1.21_48,
									        -4.02_73,
									        -0.51_61,
									        -5.21_09,
									        -1.24_12,
									        -1.83_01,
									        -1.77_34,
									        -4.71_48,
									        -0.23_17,
									        -1.08_11,
									        -2.17_77,
									        0.41_41,
									        -3.79_69,
									        -4.05_86,
									        -2.53_32,
									        -3.38_09,
									        4.38_67,
									    ]					,   device=__UpperCamelCase					,   dtype=torch.half					,   )

									for i in range(1_9       ):
												snake_case__    ,			snake_case__          =						8 * i // 1_7, 2_7_9_2 * i  # along the diagonal
												snake_case__    ,			snake_case__          =						output[0, r, c], expected_diag[i]
												snake_case__          =						f"""row={r} col={c} computed={computed} expected={expected}"""
												self.assertAlmostEqual(__UpperCamelCase					,   __UpperCamelCase					,   delta=1E-4					,   msg=__UpperCamelCase       )







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)




