




import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel
from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings
from diffusers.utils import load_numpy, slow, torch_device
from diffusers.utils.testing_utils import require_torch_gpu


__lowerCamelCase   :						List[str]				=			False


class    lowerCamelCase    (		unittest.TestCase						):






			'''simple docstring'''





			def 							UpperCAmelCase__       ( self			:   Optional[Any]  )						->   Any:
								# clean up the VRAM after each test
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()

			@property
			def 							UpperCAmelCase__       ( self			:   List[str]  )						->   Any:
								return 12

			@property
			def 							UpperCAmelCase__       ( self			:   Dict  )						->   List[Any]:
								return 12

			@property
			def 							UpperCAmelCase__       ( self			:   List[str]  )						->   Optional[int]:
								return 32

			@property
			def 							UpperCAmelCase__       ( self			:   Union[str, Any]  )						->   str:
								torch.manual_seed(0  )
								__magic_name__							:	List[Any]    							=							VQModel(
								    block_out_channels=[32, 64]       ,						in_channels=3       ,						out_channels=3       ,						down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']       ,						up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']       ,						latent_channels=3       ,						num_vq_embeddings=self.num_embed       ,						vq_embed_dim=3       ,						)
								return model

			@property
			def 							UpperCAmelCase__       ( self			:   List[str]  )						->   Dict:
								__magic_name__							:	Tuple    							=							CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''  )
								return tokenizer

			@property
			def 							UpperCAmelCase__       ( self			:   Any  )						->   int:
								torch.manual_seed(0  )
								__magic_name__							:	List[str]    							=							CLIPTextConfig(
								    bos_token_id=0       ,						eos_token_id=2       ,						hidden_size=self.text_embedder_hidden_size       ,						intermediate_size=37       ,						layer_norm_eps=1E-05       ,						num_attention_heads=4       ,						num_hidden_layers=5       ,						pad_token_id=1       ,						vocab_size=1000       ,						)
								return CLIPTextModel(lowerCamelCase_  )

			@property
			def 							UpperCAmelCase__       ( self			:   int  )						->   int:
								torch.manual_seed(0  )

								__magic_name__							:	Optional[int]    							=							12
								__magic_name__							:	int    							=							12

								__magic_name__							:	str    							=							{
								    '''attention_bias''': True,
								    '''cross_attention_dim''': 32,
								    '''attention_head_dim''': height * width,
								    '''num_attention_heads''': 1,
								    '''num_vector_embeds''': self.num_embed,
								    '''num_embeds_ada_norm''': self.num_embeds_ada_norm,
								    '''norm_num_groups''': 32,
								    '''sample_size''': width,
								    '''activation_fn''': '''geglu-approximate''',
								}

								__magic_name__							:	Tuple    							=							TransformeraDModel(**lowerCamelCase_  )
								return model

			def 							UpperCAmelCase__       ( self			:   List[Any]  )						->   str:
								__magic_name__							:	Tuple    							=							'''cpu'''

								__magic_name__							:	List[Any]    							=							self.dummy_vqvae
								__magic_name__							:	Tuple    							=							self.dummy_text_encoder
								__magic_name__							:	Optional[Any]    							=							self.dummy_tokenizer
								__magic_name__							:	Optional[int]    							=							self.dummy_transformer
								__magic_name__							:	List[Any]    							=							VQDiffusionScheduler(self.num_embed  )
								__magic_name__							:	Union[str, Any]    							=							LearnedClassifierFreeSamplingEmbeddings(learnable=lowerCamelCase_  )

								__magic_name__							:	Optional[Any]    							=							VQDiffusionPipeline(
								    vqvae=lowerCamelCase_       ,						text_encoder=lowerCamelCase_       ,						tokenizer=lowerCamelCase_       ,						transformer=lowerCamelCase_       ,						scheduler=lowerCamelCase_       ,						learned_classifier_free_sampling_embeddings=lowerCamelCase_       ,						)
								__magic_name__							:	Union[str, Any]    							=							pipe.to(lowerCamelCase_  )
								pipe.set_progress_bar_config(disable=lowerCamelCase_  )

								__magic_name__							:	Optional[int]    							=							'''teddy bear playing in the pool'''

								__magic_name__							:	Any    							=							torch.Generator(device=lowerCamelCase_  ).manual_seed(0  )
								__magic_name__							:	Union[str, Any]    							=							pipe([prompt]       ,						generator=lowerCamelCase_       ,						num_inference_steps=2       ,						output_type='''np'''  )
								__magic_name__							:	str    							=							output.images

								__magic_name__							:	int    							=							torch.Generator(device=lowerCamelCase_  ).manual_seed(0  )
								__magic_name__							:	Optional[Any]    							=							pipe(
								    [prompt]       ,						generator=lowerCamelCase_       ,						output_type='''np'''       ,						return_dict=lowerCamelCase_       ,						num_inference_steps=2  )[0]

								__magic_name__							:	Any    							=							image[0, -3:, -3:, -1]
								__magic_name__							:	Optional[int]    							=							image_from_tuple[0, -3:, -3:, -1]

								assert image.shape == (1, 24, 24, 3)

								__magic_name__							:	Optional[Any]    							=							np.array([0.6_5_5_1, 0.6_1_6_8, 0.5_0_0_8, 0.5_6_7_6, 0.5_6_5_9, 0.4_2_9_5, 0.6_0_7_3, 0.5_5_9_9, 0.4_9_9_2]  )

								assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1E-2
								assert np.abs(image_from_tuple_slice.flatten() - expected_slice  ).max() < 1E-2


			def 							UpperCAmelCase__       ( self			:   Tuple  )						->   Optional[int]:
								__magic_name__							:	List[Any]    							=							'''cpu'''

								__magic_name__							:	Optional[Any]    							=							self.dummy_vqvae
								__magic_name__							:	int    							=							self.dummy_text_encoder
								__magic_name__							:	List[str]    							=							self.dummy_tokenizer
								__magic_name__							:	str    							=							self.dummy_transformer
								__magic_name__							:	Any    							=							VQDiffusionScheduler(self.num_embed  )
								__magic_name__							:	Any    							=							LearnedClassifierFreeSamplingEmbeddings(
								    learnable=lowerCamelCase_       ,						hidden_size=self.text_embedder_hidden_size       ,						length=tokenizer.model_max_length  )

								__magic_name__							:	Optional[Any]    							=							VQDiffusionPipeline(
								    vqvae=lowerCamelCase_       ,						text_encoder=lowerCamelCase_       ,						tokenizer=lowerCamelCase_       ,						transformer=lowerCamelCase_       ,						scheduler=lowerCamelCase_       ,						learned_classifier_free_sampling_embeddings=lowerCamelCase_       ,						)
								__magic_name__							:	Dict    							=							pipe.to(lowerCamelCase_  )
								pipe.set_progress_bar_config(disable=lowerCamelCase_  )

								__magic_name__							:	Dict    							=							'''teddy bear playing in the pool'''

								__magic_name__							:	List[str]    							=							torch.Generator(device=lowerCamelCase_  ).manual_seed(0  )
								__magic_name__							:	List[str]    							=							pipe([prompt]       ,						generator=lowerCamelCase_       ,						num_inference_steps=2       ,						output_type='''np'''  )
								__magic_name__							:	str    							=							output.images

								__magic_name__							:	Optional[int]    							=							torch.Generator(device=lowerCamelCase_  ).manual_seed(0  )
								__magic_name__							:	str    							=							pipe(
								    [prompt]       ,						generator=lowerCamelCase_       ,						output_type='''np'''       ,						return_dict=lowerCamelCase_       ,						num_inference_steps=2  )[0]

								__magic_name__							:	Optional[int]    							=							image[0, -3:, -3:, -1]
								__magic_name__							:	Tuple    							=							image_from_tuple[0, -3:, -3:, -1]

								assert image.shape == (1, 24, 24, 3)

								__magic_name__							:	List[str]    							=							np.array([0.6_6_9_3, 0.6_0_7_5, 0.4_9_5_9, 0.5_7_0_1, 0.5_5_8_3, 0.4_3_3_3, 0.6_1_7_1, 0.5_6_8_4, 0.4_9_8_8]  )

								assert np.abs(image_slice.flatten() - expected_slice  ).max() < 2.0
								assert np.abs(image_from_tuple_slice.flatten() - expected_slice  ).max() < 1E-2






@slow
@require_torch_gpu
class    lowerCamelCase    (		unittest.TestCase						):






			'''simple docstring'''





			def 							UpperCAmelCase__       ( self			:   Dict  )						->   Tuple:
								# clean up the VRAM after each test
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()


			def 							UpperCAmelCase__       ( self			:   int  )						->   Optional[Any]:
								__magic_name__							:	int    							=							load_numpy(
								    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
								    '''/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy'''  )

								__magic_name__							:	Tuple    							=							VQDiffusionPipeline.from_pretrained('''microsoft/vq-diffusion-ithq'''  )
								__magic_name__							:	str    							=							pipeline.to(lowerCamelCase_  )
								pipeline.set_progress_bar_config(disable=lowerCamelCase_  )

								# requires GPU generator for gumbel softmax
								# don't use GPU generator in tests though
								__magic_name__							:	int    							=							torch.Generator(device=lowerCamelCase_  ).manual_seed(0  )
								__magic_name__							:	List[Any]    							=							pipeline(
								    '''teddy bear playing in the pool'''       ,						num_images_per_prompt=1       ,						generator=lowerCamelCase_       ,						output_type='''np'''       ,						)

								__magic_name__							:	Optional[int]    							=							output.images[0]

								assert image.shape == (256, 256, 3)
								assert np.abs(expected_image - image  ).max() < 2.0









import re
from typing import Callable, List, Optional, Union

import tensorflow as tf


try:
	from tensorflow.keras.optimizers.legacy import Adam
except ImportError:
	from tensorflow.keras.optimizers import Adam


class    lowerCamelCase    (		tf.keras.optimizers.schedules.LearningRateSchedule						):






			'''simple docstring'''





			def __init__( self			:   Union[str, Any]       ,						lowerCamelCase_			:   float       ,						lowerCamelCase_			:   Callable       ,						lowerCamelCase_			:   int       ,						lowerCamelCase_			:   float = 1.0       ,						lowerCamelCase_			:   str = None       ,						)						->   Optional[int]:
								super().__init__()
								__magic_name__							:	Union[str, Any]    							=							initial_learning_rate
								__magic_name__							:	Optional[int]    							=							warmup_steps
								__magic_name__							:	Union[str, Any]    							=							power
								__magic_name__							:	List[Any]    							=							decay_schedule_fn
								__magic_name__							:	Dict    							=							name

			def __call__( self			:   Any       ,						lowerCamelCase_			:   Dict  )						->   Optional[Any]:
								with tf.name_scope(self.name or '''WarmUp'''  ) as name:
													# Implements polynomial warmup. i.e., if global_step < warmup_steps, the
													# learning rate will be `global_step/num_warmup_steps * init_lr`.
													__magic_name__							:	Union[str, Any]    							=							tf.cast(lowerCamelCase_       ,						tf.floataa  )
													__magic_name__							:	Dict    							=							tf.cast(self.warmup_steps       ,						tf.floataa  )
													__magic_name__							:	Dict    							=							global_step_float / warmup_steps_float
													__magic_name__							:	List[str]    							=							self.initial_learning_rate * tf.math.pow(lowerCamelCase_       ,						self.power  )
													return tf.cond(
													    global_step_float < warmup_steps_float       ,						lambda: warmup_learning_rate       ,						lambda: self.decay_schedule_fn(step - self.warmup_steps  )       ,						name=lowerCamelCase_       ,						)


			def 							UpperCAmelCase__       ( self			:   Optional[int]  )						->   str:
								return {
								    "initial_learning_rate": self.initial_learning_rate,
								    "decay_schedule_fn": self.decay_schedule_fn,
								    "warmup_steps": self.warmup_steps,
								    "power": self.power,
								    "name": self.name,
								}







def 		lowercase__   (		__A:	float							,__A:	int							,__A:	int							,__A:	float = 0.0							,__A:	float = 0.9							,__A:	float = 0.999							,__A:	float = 1e-8							,__A:	Optional[float] = None							,__A:	Optional[float] = None							,__A:	float = 0.0							,__A:	float = 1.0							,__A:	Optional[List[str]] = None							,):





					'''simple docstring'''






					__magic_name__							:	Any    							=							tf.keras.optimizers.schedules.PolynomialDecay(
					    initial_learning_rate=__A							,decay_steps=num_train_steps - num_warmup_steps							,end_learning_rate=init_lr * min_lr_ratio							,power=__A							,)
					if num_warmup_steps:
										__magic_name__							:	Tuple    							=							WarmUp(
										    initial_learning_rate=__A							,decay_schedule_fn=__A							,warmup_steps=__A							,)
					if weight_decay_rate > 0.0:
										__magic_name__							:	Union[str, Any]    							=							AdamWeightDecay(
										    learning_rate=__A							,weight_decay_rate=__A							,beta_a=__A							,beta_a=__A							,epsilon=__A							,clipnorm=__A							,global_clipnorm=__A							,exclude_from_weight_decay=['''LayerNorm''', '''layer_norm''', '''bias''']							,include_in_weight_decay=__A							,)
					else:
										__magic_name__							:	str    							=							tf.keras.optimizers.Adam(
										    learning_rate=__A							,beta_a=__A							,beta_a=__A							,epsilon=__A							,clipnorm=__A							,global_clipnorm=__A							,)
					# We return the optimizer and the LR scheduler in order to better track the
					# evolution of the LR independently of the optimizer.
					return optimizer, lr_schedule


class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			def __init__( self			:   Optional[int]       ,						lowerCamelCase_			:   Union[float, tf.keras.optimizers.schedules.LearningRateSchedule] = 0.0_0_1       ,						lowerCamelCase_			:   float = 0.9       ,						lowerCamelCase_			:   float = 0.9_9_9       ,						lowerCamelCase_			:   float = 1E-7       ,						lowerCamelCase_			:   bool = False       ,						lowerCamelCase_			:   float = 0.0       ,						lowerCamelCase_			:   Optional[List[str]] = None       ,						lowerCamelCase_			:   Optional[List[str]] = None       ,						lowerCamelCase_			:   str = "AdamWeightDecay"       ,						**lowerCamelCase_			:   int       ,						)						->   List[str]:
								super().__init__(lowerCamelCase_       ,						lowerCamelCase_       ,						lowerCamelCase_       ,						lowerCamelCase_       ,						lowerCamelCase_       ,						lowerCamelCase_       ,						**lowerCamelCase_  )
								__magic_name__							:	int    							=							weight_decay_rate
								__magic_name__							:	Tuple    							=							include_in_weight_decay
								__magic_name__							:	Union[str, Any]    							=							exclude_from_weight_decay

			@classmethod
			def 							UpperCAmelCase__       ( cls			:   int       ,						lowerCamelCase_			:   int  )						->   Optional[Any]:
								__magic_name__							:	Tuple    							=							{'''WarmUp''': WarmUp}
								return super(lowerCamelCase_       ,						cls  ).from_config(lowerCamelCase_       ,						custom_objects=lowerCamelCase_  )

			def 							UpperCAmelCase__       ( self			:   Union[str, Any]       ,						lowerCamelCase_			:   int       ,						lowerCamelCase_			:   Optional[int]       ,						lowerCamelCase_			:   Optional[int]  )						->   int:
								super(lowerCamelCase_       ,						self  )._prepare_local(lowerCamelCase_       ,						lowerCamelCase_       ,						lowerCamelCase_  )
								__magic_name__							:	Any    							=							tf.constant(
								    self.weight_decay_rate       ,						name='''adam_weight_decay_rate'''  )

			def 							UpperCAmelCase__       ( self			:   Optional[int]       ,						lowerCamelCase_			:   List[str]       ,						lowerCamelCase_			:   Optional[Any]       ,						lowerCamelCase_			:   Any  )						->   Optional[Any]:
								__magic_name__							:	Optional[int]    							=							self._do_use_weight_decay(var.name  )
								if do_decay:
													return var.assign_sub(
													    learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]['''weight_decay_rate''']       ,						use_locking=self._use_locking       ,						)
								return tf.no_op()

			def 							UpperCAmelCase__       ( self			:   str       ,						lowerCamelCase_			:   Optional[Any]       ,						lowerCamelCase_			:   int=None       ,						**lowerCamelCase_			:   Union[str, Any]  )						->   Optional[int]:
								__magic_name__							,    __magic_name__							:	Dict    							=							list(zip(*lowerCamelCase_  )  )
								return super(lowerCamelCase_       ,						self  ).apply_gradients(zip(lowerCamelCase_       ,						lowerCamelCase_  )       ,						name=lowerCamelCase_       ,						**lowerCamelCase_  )

			def 							UpperCAmelCase__       ( self			:   List[Any]       ,						lowerCamelCase_			:   Optional[int]       ,						lowerCamelCase_			:   int       ,						lowerCamelCase_			:   Union[str, Any]  )						->   Union[str, Any]:
								if apply_state is None:
													return self._decayed_lr_t[var_dtype], {}

								__magic_name__							:	str    							=							apply_state or {}
								__magic_name__							:	Optional[Any]    							=							apply_state.get((var_device, var_dtype)  )
								if coefficients is None:
													__magic_name__							:	List[str]    							=							self._fallback_apply_state(lowerCamelCase_       ,						lowerCamelCase_  )
													__magic_name__							:	List[Any]    							=							coefficients

								return coefficients["lr_t"], {"apply_state": apply_state}

			def 							UpperCAmelCase__       ( self			:   List[str]       ,						lowerCamelCase_			:   List[str]       ,						lowerCamelCase_			:   List[str]       ,						lowerCamelCase_			:   Dict=None  )						->   Optional[Any]:
								__magic_name__							,    __magic_name__							:	Union[str, Any]    							=							self._get_lr(var.device       ,						var.dtype.base_dtype       ,						lowerCamelCase_  )
								__magic_name__							:	Optional[Any]    							=							self._decay_weights_op(lowerCamelCase_       ,						lowerCamelCase_       ,						lowerCamelCase_  )
								with tf.control_dependencies([decay]  ):
													return super(lowerCamelCase_       ,						self  )._resource_apply_dense(lowerCamelCase_       ,						lowerCamelCase_       ,						**lowerCamelCase_  )

			def 							UpperCAmelCase__       ( self			:   Dict       ,						lowerCamelCase_			:   List[Any]       ,						lowerCamelCase_			:   List[Any]       ,						lowerCamelCase_			:   Optional[Any]       ,						lowerCamelCase_			:   Union[str, Any]=None  )						->   Any:
								__magic_name__							,    __magic_name__							:	Tuple    							=							self._get_lr(var.device       ,						var.dtype.base_dtype       ,						lowerCamelCase_  )
								__magic_name__							:	Optional[int]    							=							self._decay_weights_op(lowerCamelCase_       ,						lowerCamelCase_       ,						lowerCamelCase_  )
								with tf.control_dependencies([decay]  ):
													return super(lowerCamelCase_       ,						self  )._resource_apply_sparse(lowerCamelCase_       ,						lowerCamelCase_       ,						lowerCamelCase_       ,						**lowerCamelCase_  )

			def 							UpperCAmelCase__       ( self			:   int  )						->   Dict:
								__magic_name__							:	List[Any]    							=							super().get_config()
								config.update({'''weight_decay_rate''': self.weight_decay_rate}  )
								return config


			def 							UpperCAmelCase__       ( self			:   Dict       ,						lowerCamelCase_			:   Union[str, Any]  )						->   Union[str, Any]:
								if self.weight_decay_rate == 0:
													return False

								if self._include_in_weight_decay:
													for r in self._include_in_weight_decay:
																		if re.search(lowerCamelCase_       ,						lowerCamelCase_  ) is not None:
																							return True

								if self._exclude_from_weight_decay:
													for r in self._exclude_from_weight_decay:
																		if re.search(lowerCamelCase_       ,						lowerCamelCase_  ) is not None:
																							return False
								return True






class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			def __init__( self			:   Optional[Any]  )						->   Any:
								__magic_name__							:	Optional[int]    							=							[]
								__magic_name__							:	Dict    							=							None

			@property
			def 							UpperCAmelCase__       ( self			:   Optional[int]  )						->   Any:
								if self._accum_steps is None:
													__magic_name__							:	Optional[Any]    							=							tf.Variable(
													    tf.constant(0       ,						dtype=tf.intaa  )       ,						trainable=lowerCamelCase_       ,						synchronization=tf.VariableSynchronization.ON_READ       ,						aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA       ,						)

								return self._accum_steps.value()

			@property
			def 							UpperCAmelCase__       ( self			:   Optional[Any]  )						->   Optional[Any]:
								if not self._gradients:
													raise ValueError('''The accumulator should be called first to initialize the gradients'''  )
								return [gradient.value() if gradient is not None else gradient for gradient in self._gradients]

			def __call__( self			:   Optional[int]       ,						lowerCamelCase_			:   Any  )						->   List[str]:
								if not self._gradients:
													__magic_name__							:	int    							=							self.step  # Create the step variable.
													self._gradients.extend(
													    [
													        tf.Variable(
													            tf.zeros_like(lowerCamelCase_  )       ,						trainable=lowerCamelCase_       ,						synchronization=tf.VariableSynchronization.ON_READ       ,						aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA       ,						)
													        if gradient is not None
													        else gradient
													        for gradient in gradients
													    ]  )
								if len(lowerCamelCase_  ) != len(self._gradients  ):
													raise ValueError(F'''Expected {len(self._gradients  )} gradients, but got {len(lowerCamelCase_  )}'''  )

								for accum_gradient, gradient in zip(self._gradients       ,						lowerCamelCase_  ):
													if accum_gradient is not None and gradient is not None:
																		accum_gradient.assign_add(lowerCamelCase_  )

								self._accum_steps.assign_add(1  )


			def 							UpperCAmelCase__       ( self			:   str  )						->   Optional[int]:
								if not self._gradients:
													return
								self._accum_steps.assign(0  )
								for gradient in self._gradients:
													if gradient is not None:
																		gradient.assign(tf.zeros_like(lowerCamelCase_  )  )



