


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     lowerCamelCase__		(							unittest.TestCase ):






			"""simple docstring"""






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




			def 			snake_case__			(							self ,  snake_case=0.9999       ):

						'''simple docstring'''


						UpperCamelCase__   =    UNetaDConditionModel.from_pretrained(self.model_id ,  subfolder="unet"       )
						UpperCamelCase__   =    unet.to(snake_case       )
						UpperCamelCase__   =    EMAModel(unet.parameters() ,  decay=snake_case ,  model_cls=snake_case ,  model_config=unet.config       )
						return unet, ema_unet




			def 			snake_case__			(							self       ):

						'''simple docstring'''


						UpperCamelCase__   =    torch.randn(
						    self.batch_size ,  self.num_in_channels ,  self.latent_height ,  self.latent_width ,  generator=self.generator       ).to(snake_case       )
						UpperCamelCase__   =    torch.randint(0 ,  1000 ,  size=(self.batch_size,) ,  generator=self.generator       ).to(snake_case       )
						UpperCamelCase__   =    torch.randn(
						    self.batch_size ,  self.prompt_length ,  self.text_encoder_hidden_dim ,  generator=self.generator       ).to(snake_case       )
						return noisy_latents, timesteps, encoder_hidden_states




			def 			snake_case__			(							self ,  snake_case       ):

						'''simple docstring'''


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




			def 			snake_case__			(							self       ):

						'''simple docstring'''


						UpperCamelCase__, UpperCamelCase__   =    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 			snake_case__			(							self       ):

						'''simple docstring'''


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

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




			def 			snake_case__			(							self       ):

						'''simple docstring'''


						UpperCamelCase__, UpperCamelCase__   =    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.
						UpperCamelCase__   =    self.simulate_backprop(snake_case       )

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

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




			def 			snake_case__			(							self       ):

						'''simple docstring'''


						UpperCamelCase__, UpperCamelCase__   =    self.get_models()

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

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

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




			def 			snake_case__			(							self       ):

						'''simple docstring'''


						UpperCamelCase__, UpperCamelCase__   =    self.get_models(decay=0.0       )
						UpperCamelCase__   =    self.simulate_backprop(snake_case       )
						ema_unet.step(unet_step_one.parameters()       )
						UpperCamelCase__   =    ema_unet.shadow_params

						UpperCamelCase__   =    self.simulate_backprop(snake_case       )
						ema_unet.step(unet_step_two.parameters()       )
						UpperCamelCase__   =    ema_unet.shadow_params

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







			@skip_mps
			def 			snake_case__			(							self       ):

						'''simple docstring'''


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

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

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

						assert torch.allclose(snake_case ,  snake_case ,  atol=1E-4       )






import subprocess
from argparse import ArgumentParser
from typing import List, Union

from huggingface_hub.hf_api import HfFolder, create_repo, whoami
from requests.exceptions import HTTPError

from . import BaseTransformersCLICommand







class     lowerCamelCase__		(							UpperCAmelCase ):






			"""simple docstring"""






			@staticmethod
			def 			snake_case__			(							snake_case       ):

						'''simple docstring'''


						UpperCamelCase__   =    parser.add_parser("login" ,  help="Log in using the same credentials as on huggingface.co"       )
						login_parser.set_defaults(func=lambda snake_case       : LoginCommand(snake_case       )       )
						UpperCamelCase__   =    parser.add_parser("whoami" ,  help="Find out which huggingface.co account you are logged in as."       )
						whoami_parser.set_defaults(func=lambda snake_case       : WhoamiCommand(snake_case       )       )
						UpperCamelCase__   =    parser.add_parser("logout" ,  help="Log out"       )
						logout_parser.set_defaults(func=lambda snake_case       : LogoutCommand(snake_case       )       )

						# new system: git-based repo system
						UpperCamelCase__   =    parser.add_parser(
						    "repo" ,  help="Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos." ,  )
						UpperCamelCase__   =    repo_parser.add_subparsers(
						    help="Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands"       )
						UpperCamelCase__   =    repo_subparsers.add_parser(
						    "create" ,  help="Deprecated: use `huggingface-cli` instead. Create a new repo on huggingface.co"       )
						repo_create_parser.add_argument(
						    "name" ,  type=snake_case ,  help="Name for your model's repo. Will be namespaced under your username to build the model id." ,  )
						repo_create_parser.add_argument("--organization" ,  type=snake_case ,  help="Optional: organization namespace."       )
						repo_create_parser.add_argument("-y" ,  "--yes" ,  action="store_true" ,  help="Optional: answer Yes to the prompt"       )
						repo_create_parser.set_defaults(func=lambda snake_case       : RepoCreateCommand(snake_case       )       )







class     lowerCamelCase__		:






			"""simple docstring"""






			_UpperCamelCase						:   int					=						'\u001b[1m'
			_UpperCamelCase						:   List[Any]					=						'\u001b[31m'
			_UpperCamelCase						:   Tuple					=						'\u001b[90m'
			_UpperCamelCase						:   Tuple					=						'\u001b[0m'




			@classmethod
			def 			snake_case__			(							cls ,  snake_case       ):

						'''simple docstring'''


						return F'''{cls._bold}{s}{cls._reset}'''




			@classmethod
			def 			snake_case__			(							cls ,  snake_case       ):

						'''simple docstring'''


						return F'''{cls._bold}{cls._red}{s}{cls._reset}'''







			@classmethod
			def 			snake_case__			(							cls ,  snake_case       ):

						'''simple docstring'''


						return F'''{cls._gray}{s}{cls._reset}'''



def     UpperCamelCase_(			_A				:List[List[Union[str, int]]]			,       _A				:List[str]					)->						str:
			UpperCamelCase__   =    [max(len(str(_A					)					) for x in col					) for col in zip(*_A			,       _A					)]
			UpperCamelCase__   =    ("{{:{}}} " * len(_A					)).format(*_A					)
			UpperCamelCase__   =    []
			lines.append(row_format.format(*_A					)					)
			lines.append(row_format.format(*["-" * w for w in col_widths]					)					)
			for row in rows:
						lines.append(row_format.format(*_A					)					)
			return "\n".join(_A					)







class     lowerCamelCase__		:






			"""simple docstring"""






			def __init__(							self ,  snake_case       ):

						'''simple docstring'''


						UpperCamelCase__   =    args







class     lowerCamelCase__		(							UpperCAmelCase ):






			"""simple docstring"""






			def 			snake_case__			(							self       ):

						'''simple docstring'''


						print(
						    ANSI.red(
						        "ERROR! `huggingface-cli login` uses an outdated login mechanism "
						        "that is not compatible with the Hugging Face Hub backend anymore. "
						        "Please use `huggingface-cli login instead."       )       )







class     lowerCamelCase__		(							UpperCAmelCase ):






			"""simple docstring"""






			def 			snake_case__			(							self       ):

						'''simple docstring'''


						print(
						    ANSI.red(
						        "WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use "
						        "`huggingface-cli whoami` instead."       )       )
						UpperCamelCase__   =    HfFolder.get_token()
						if token is None:
									print("Not logged in"       )
									exit()
						try:
									UpperCamelCase__, UpperCamelCase__   =    whoami(snake_case       )
									print(snake_case       )
									if orgs:
												print(ANSI.bold("orgs: "       ) ,  ",".join(snake_case       )       )
						except HTTPError as e:
									print(snake_case       )
									print(ANSI.red(e.response.text       )       )
									exit(1       )







class     lowerCamelCase__		(							UpperCAmelCase ):






			"""simple docstring"""






			def 			snake_case__			(							self       ):

						'''simple docstring'''


						print(
						    ANSI.red(
						        "ERROR! `transformers-cli logout` uses an outdated logout mechanism "
						        "that is not compatible with the Hugging Face Hub backend anymore. "
						        "Please use `huggingface-cli logout instead."       )       )







class     lowerCamelCase__		(							UpperCAmelCase ):






			"""simple docstring"""






			def 			snake_case__			(							self       ):

						'''simple docstring'''


						print(
						    ANSI.red(
						        "WARNING! Managing repositories through transformers-cli is deprecated. "
						        "Please use `huggingface-cli` instead."       )       )
						UpperCamelCase__   =    HfFolder.get_token()
						if token is None:
									print("Not logged in"       )
									exit(1       )
						try:
									UpperCamelCase__   =    subprocess.check_output(["git", "--version"]       ).decode("utf-8"       )
									print(ANSI.gray(stdout.strip()       )       )
						except FileNotFoundError:
									print("Looks like you do not have git installed, please install."       )

						try:
									UpperCamelCase__   =    subprocess.check_output(["git-lfs", "--version"]       ).decode("utf-8"       )
									print(ANSI.gray(stdout.strip()       )       )
						except FileNotFoundError:
									print(
									    ANSI.red(
									        "Looks like you do not have git-lfs installed, please install."
									        " You can install from https://git-lfs.github.com/."
									        " Then run `git lfs install` (you only have to do this once)."       )       )
						print(""       )

						UpperCamelCase__, UpperCamelCase__   =    whoami(snake_case       )
						UpperCamelCase__   =    self.args.organization if self.args.organization is not None else user
						UpperCamelCase__   =    F'''{namespace}/{self.args.name}'''
						print(F'''You are about to create {ANSI.bold(snake_case       )}'''       )

						if not self.args.yes:
									UpperCamelCase__   =    input("Proceed? [Y/n] "       ).lower()
									if not (choice == "" or choice == "y" or choice == "yes"):
												print("Abort"       )
												exit()
						try:
									UpperCamelCase__   =    create_repo(snake_case ,  name=self.args.name ,  organization=self.args.organization       )
						except HTTPError as e:
									print(snake_case       )
									print(ANSI.red(e.response.text       )       )
									exit(1       )
						print("\nYour repo now lives at:"       )
						print(F'''  {ANSI.bold(snake_case       )}'''       )
						print("\nYou can clone it locally with the command below, and commit/push as usual."       )
						print(F'''\n  git clone {url}'''       )
						print(""       )


