
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							):
							lowerCAmelCase__						:		Optional[Any]            =				"hf-internal-testing/tiny-stable-diffusion-pipe"
							lowerCAmelCase__						:		List[Any]            =				1
							lowerCAmelCase__						:		Union[str, Any]            =				77
							lowerCAmelCase__						:		int            =				32
							lowerCAmelCase__						:		List[Any]            =				4
							lowerCAmelCase__						:		str            =				64
							lowerCAmelCase__						:		Union[str, Any]            =				torch.manual_seed(0							)





							def      a__					(					self    :  Optional[Any]	,					_UpperCAmelCase    :  Dict=0.9_999							)		->						Optional[Any]:



											"""simple docstring"""


											__lowercase								=   UNetaDConditionModel.from_pretrained(self.model_id	,					subfolder='unet'							)
											__lowercase								=   unet.to(lowercase_							)
											__lowercase								=   EMAModel(unet.parameters()	,					decay=lowercase_	,					model_cls=lowercase_	,					model_config=unet.config							)
											return unet, ema_unet





							def      a__					(					self    :  Optional[int]							)		->						List[Any]:



											"""simple docstring"""


											__lowercase								=   torch.randn(
											    self.batch_size	,					self.num_in_channels	,					self.latent_height	,					self.latent_width	,					generator=self.generator							).to(lowercase_							)
											__lowercase								=   torch.randint(0	,					10_00	,					size=(self.batch_size,)	,					generator=self.generator							).to(lowercase_							)
											__lowercase								=   torch.randn(
											    self.batch_size	,					self.prompt_length	,					self.text_encoder_hidden_dim	,					generator=self.generator							).to(lowercase_							)
											return noisy_latents, timesteps, encoder_hidden_states





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



											"""simple docstring"""


											__lowercase								=   {}
											for k, param in unet.state_dict().items():
															__lowercase								=   torch.randn_like(lowercase_							) + (param * torch.randn_like(lowercase_							))
															updated_state_dict.update({k: updated_param}							)
											unet.load_state_dict(lowercase_							)
											return unet





							def      a__					(					self    :  Union[str, Any]							)		->						Optional[int]:



											"""simple docstring"""


											__lowercase						,   __lowercase								=   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      a__					(					self    :  Union[str, Any]							)		->						Tuple:



											"""simple docstring"""


											__lowercase						,   __lowercase								=   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()							)
											__lowercase								=   list(unet.parameters()							)
											for s_param, param in zip(ema_unet.shadow_params	,					lowercase_							):
															assert torch.allclose(lowercase_	,					lowercase_							)

											# 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	,					lowercase_							):
															assert torch.allclose(lowercase_	,					lowercase_							)





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



											"""simple docstring"""


											__lowercase						,   __lowercase								=   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.
											__lowercase								=   self.simulate_backprop(lowercase_							)

											# 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.
											__lowercase								=   list(unet_pseudo_updated_step_one.parameters()							)
											for s_param, param in zip(ema_unet.shadow_params	,					lowercase_							):
															assert ~torch.allclose(lowercase_	,					lowercase_							)

											# 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	,					lowercase_							):
															assert ~torch.allclose(lowercase_	,					lowercase_							)





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



											"""simple docstring"""


											__lowercase						,   __lowercase								=   self.get_models()

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

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

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





							def      a__					(					self    :  Optional[Any]							)		->						Optional[int]:



											"""simple docstring"""


											__lowercase						,   __lowercase								=   self.get_models(decay=0.0							)
											__lowercase								=   self.simulate_backprop(lowercase_							)
											ema_unet.step(unet_step_one.parameters()							)
											__lowercase								=   ema_unet.shadow_params

											__lowercase								=   self.simulate_backprop(lowercase_							)
											ema_unet.step(unet_step_two.parameters()							)
											__lowercase								=   ema_unet.shadow_params

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





							@skip_mps
							def      a__					(					self    :  Dict							)		->						Any:



											"""simple docstring"""


											__lowercase						,   __lowercase								=   self.get_models()
											__lowercase						,   __lowercase						,   __lowercase								=   self.get_dummy_inputs()

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

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

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








'''simple docstring'''

lowerCAmelCase_     =      "\n# Installation de Transformers\n! pip install transformers datasets\n# Pour installer à partir du code source au lieu de la dernière version, commentez la commande ci-dessus et décommentez la suivante.\n# ! pip install git+https://github.com/huggingface/transformers.git\n"

lowerCAmelCase_     =      [{"type": "code", "content": INSTALL_CONTENT}]
lowerCAmelCase_     =      {
    "{processor_class}": "FakeProcessorClass",
    "{model_class}": "FakeModelClass",
    "{object_class}": "FakeObjectClass",
}





