


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


__snake_case            =   False




class    UpperCAmelCase					(       unittest.TestCase    ):




			def   lowerCamelCase_					(						self							:		Optional[int]						):







						"""simple docstring"""







						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()




			@property
			def   lowerCamelCase_					(						self							:		int						):







						"""simple docstring"""







						return 1_2




			@property
			def   lowerCamelCase_					(						self							:		str						):







						"""simple docstring"""







						return 1_2




			@property
			def   lowerCamelCase_					(						self							:		str						):







						"""simple docstring"""







						return 3_2




			@property
			def   lowerCamelCase_					(						self							:		Dict						):







						"""simple docstring"""







						torch.manual_seed(0						)
						UpperCamelCase         =					VQModel(
						    block_out_channels=[3_2, 6_4]       ,       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   lowerCamelCase_					(						self							:		Tuple						):







						"""simple docstring"""







						UpperCamelCase         =					CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""						)
						return tokenizer




			@property
			def   lowerCamelCase_					(						self							:		Tuple						):







						"""simple docstring"""







						torch.manual_seed(0						)
						UpperCamelCase         =					CLIPTextConfig(
						    bos_token_id=0       ,       eos_token_id=2       ,       hidden_size=self.text_embedder_hidden_size       ,       intermediate_size=3_7       ,       layer_norm_eps=1e-05       ,       num_attention_heads=4       ,       num_hidden_layers=5       ,       pad_token_id=1       ,       vocab_size=1_0_0_0       ,       )
						return CLIPTextModel(__magic_name__						)




			@property
			def   lowerCamelCase_					(						self							:		Optional[Any]						):







						"""simple docstring"""







						torch.manual_seed(0						)

						UpperCamelCase         =					1_2
						UpperCamelCase         =					1_2

						UpperCamelCase         =					{
						    """attention_bias""": True,
						    """cross_attention_dim""": 3_2,
						    """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""": 3_2,
						    """sample_size""": width,
						    """activation_fn""": """geglu-approximate""",
						}

						UpperCamelCase         =					TransformeraDModel(**__magic_name__						)
						return model




			def   lowerCamelCase_					(						self							:		Optional[int]						):







						"""simple docstring"""







						UpperCamelCase         =					"""cpu"""

						UpperCamelCase         =					self.dummy_vqvae
						UpperCamelCase         =					self.dummy_text_encoder
						UpperCamelCase         =					self.dummy_tokenizer
						UpperCamelCase         =					self.dummy_transformer
						UpperCamelCase         =					VQDiffusionScheduler(self.num_embed						)
						UpperCamelCase         =					LearnedClassifierFreeSamplingEmbeddings(learnable=__magic_name__						)

						UpperCamelCase         =					VQDiffusionPipeline(
						    vqvae=__magic_name__       ,       text_encoder=__magic_name__       ,       tokenizer=__magic_name__       ,       transformer=__magic_name__       ,       scheduler=__magic_name__       ,       learned_classifier_free_sampling_embeddings=__magic_name__       ,       )
						UpperCamelCase         =					pipe.to(__magic_name__						)
						pipe.set_progress_bar_config(disable=__magic_name__						)

						UpperCamelCase         =					"""teddy bear playing in the pool"""

						UpperCamelCase         =					torch.Generator(device=__magic_name__						).manual_seed(0						)
						UpperCamelCase         =					pipe([prompt]       ,       generator=__magic_name__       ,       num_inference_steps=2       ,       output_type="""np"""						)
						UpperCamelCase         =					output.images

						UpperCamelCase         =					torch.Generator(device=__magic_name__						).manual_seed(0						)
						UpperCamelCase         =					pipe(
						    [prompt]       ,       generator=__magic_name__       ,       output_type="""np"""       ,       return_dict=__magic_name__       ,       num_inference_steps=2						)[0]

						UpperCamelCase         =					image[0, -3:, -3:, -1]
						UpperCamelCase         =					image_from_tuple[0, -3:, -3:, -1]

						assert image.shape == (1, 2_4, 2_4, 3)

						UpperCamelCase         =					np.array([0.6_551, 0.6_168, 0.5_008, 0.5_676, 0.5_659, 0.4_295, 0.6_073, 0.5_599, 0.4_992]						)

						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   lowerCamelCase_					(						self							:		Any						):







						"""simple docstring"""







						UpperCamelCase         =					"""cpu"""

						UpperCamelCase         =					self.dummy_vqvae
						UpperCamelCase         =					self.dummy_text_encoder
						UpperCamelCase         =					self.dummy_tokenizer
						UpperCamelCase         =					self.dummy_transformer
						UpperCamelCase         =					VQDiffusionScheduler(self.num_embed						)
						UpperCamelCase         =					LearnedClassifierFreeSamplingEmbeddings(
						    learnable=__magic_name__       ,       hidden_size=self.text_embedder_hidden_size       ,       length=tokenizer.model_max_length						)

						UpperCamelCase         =					VQDiffusionPipeline(
						    vqvae=__magic_name__       ,       text_encoder=__magic_name__       ,       tokenizer=__magic_name__       ,       transformer=__magic_name__       ,       scheduler=__magic_name__       ,       learned_classifier_free_sampling_embeddings=__magic_name__       ,       )
						UpperCamelCase         =					pipe.to(__magic_name__						)
						pipe.set_progress_bar_config(disable=__magic_name__						)

						UpperCamelCase         =					"""teddy bear playing in the pool"""

						UpperCamelCase         =					torch.Generator(device=__magic_name__						).manual_seed(0						)
						UpperCamelCase         =					pipe([prompt]       ,       generator=__magic_name__       ,       num_inference_steps=2       ,       output_type="""np"""						)
						UpperCamelCase         =					output.images

						UpperCamelCase         =					torch.Generator(device=__magic_name__						).manual_seed(0						)
						UpperCamelCase         =					pipe(
						    [prompt]       ,       generator=__magic_name__       ,       output_type="""np"""       ,       return_dict=__magic_name__       ,       num_inference_steps=2						)[0]

						UpperCamelCase         =					image[0, -3:, -3:, -1]
						UpperCamelCase         =					image_from_tuple[0, -3:, -3:, -1]

						assert image.shape == (1, 2_4, 2_4, 3)

						UpperCamelCase         =					np.array([0.6_693, 0.6_075, 0.4_959, 0.5_701, 0.5_583, 0.4_333, 0.6_171, 0.5_684, 0.4_988]						)

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




			def   lowerCamelCase_					(						self							:		Dict						):







						"""simple docstring"""







						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()





			def   lowerCamelCase_					(						self							:		Tuple						):







						"""simple docstring"""







						UpperCamelCase         =					load_numpy(
						    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
						    """/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy"""						)

						UpperCamelCase         =					VQDiffusionPipeline.from_pretrained("""microsoft/vq-diffusion-ithq"""						)
						UpperCamelCase         =					pipeline.to(__magic_name__						)
						pipeline.set_progress_bar_config(disable=__magic_name__						)

						# requires GPU generator for gumbel softmax
						# don't use GPU generator in tests though
						UpperCamelCase         =					torch.Generator(device=__magic_name__						).manual_seed(0						)
						UpperCamelCase         =					pipeline(
						    """teddy bear playing in the pool"""       ,       num_images_per_prompt=1       ,       generator=__magic_name__       ,       output_type="""np"""       ,       )

						UpperCamelCase         =					output.images[0]

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








import math
import unittest






def 							_lowercase    (		SCREAMING_SNAKE_CASE_   :		int	):





			"""simple docstring"""




			assert isinstance(SCREAMING_SNAKE_CASE_       ,  SCREAMING_SNAKE_CASE_	) and (
			    number >= 0
			), "'number' must been an int and positive"

			if 1 < number < 4:
						# 2 and 3 are primes
						return True
			elif number < 2 or number % 2 == 0 or number % 3 == 0:
						# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
						return False

			# All primes number are in format of 6k +/- 1
			for i in range(5       ,  int(math.sqrt(SCREAMING_SNAKE_CASE_	) + 1	)       ,  6	):
						if number % i == 0 or number % (i + 2) == 0:
									return False
			return True




class    UpperCAmelCase					(       unittest.TestCase    ):




			def   lowerCamelCase_					(						self							:		Any						):







						"""simple docstring"""







						self.assertTrue(is_prime(2						)						)
						self.assertTrue(is_prime(3						)						)
						self.assertTrue(is_prime(5						)						)
						self.assertTrue(is_prime(7						)						)
						self.assertTrue(is_prime(1_1						)						)
						self.assertTrue(is_prime(1_3						)						)
						self.assertTrue(is_prime(1_7						)						)
						self.assertTrue(is_prime(1_9						)						)
						self.assertTrue(is_prime(2_3						)						)
						self.assertTrue(is_prime(2_9						)						)





			def   lowerCamelCase_					(						self							:		Dict						):







						"""simple docstring"""







						with self.assertRaises(__magic_name__						):
									is_prime(-1_9						)
						self.assertFalse(
						    is_prime(0						)       ,       """Zero doesn't have any positive factors, primes must have exactly two."""       ,       )
						self.assertFalse(
						    is_prime(1						)       ,       """One only has 1 positive factor, primes must have exactly two."""       ,       )
						self.assertFalse(is_prime(2 * 2						)						)
						self.assertFalse(is_prime(2 * 3						)						)
						self.assertFalse(is_prime(3 * 3						)						)
						self.assertFalse(is_prime(3 * 5						)						)
						self.assertFalse(is_prime(3 * 5 * 7						)						)


if __name__ == "__main__":
			unittest.main()




