

'''simple docstring'''



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

import torch
from transformers import CLIPTextModel, CLIPTokenizer

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin, TransformeraDModel, VQModel
from ...schedulers import VQDiffusionScheduler
from ...utils import logging
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


__snake_case			:     List[Any]										=      logging.get_logger(__name__)  # pylint: disable=invalid-name



class lowerCamelCase			(  lowercase_	,						lowercase_						):



			'''simple docstring'''






			@register_to_config
			def __init__(				self	:						List[Any]		,      lowerCAmelCase_	:						bool		,      lowerCAmelCase_	:						Optional[int] = None		,      lowerCAmelCase_	:						Optional[int] = None			)      ->		Optional[int]:





									'''simple docstring'''
									super().__init__()

									A__					:       Tuple     =learnable

									if self.learnable:
															assert hidden_size is not None, "learnable=True requires `hidden_size` to be set"
															assert length is not None, "learnable=True requires `length` to be set"

															A__					:       List[Any]     =torch.zeros(lowerCAmelCase_		,      lowerCAmelCase_			)
									else:
															A__					:       Tuple     =None

									A__					:       int     =torch.nn.Parameter(lowerCAmelCase_			)



class lowerCamelCase			(  lowercase_						):



			'''simple docstring'''






			__snake_case        =	42
			__snake_case        =	42
			__snake_case        =	42
			__snake_case        =	42
			__snake_case        =	42
			__snake_case        =	42


			def __init__(				self	:						List[str]		,      lowerCAmelCase_	:						VQModel		,      lowerCAmelCase_	:						CLIPTextModel		,      lowerCAmelCase_	:						CLIPTokenizer		,      lowerCAmelCase_	:						TransformeraDModel		,      lowerCAmelCase_	:						VQDiffusionScheduler		,      lowerCAmelCase_	:						LearnedClassifierFreeSamplingEmbeddings		,      )      ->		Any:





									'''simple docstring'''
									super().__init__()

									self.register_modules(
									    vqvae=lowerCAmelCase_		,      transformer=lowerCAmelCase_		,      text_encoder=lowerCAmelCase_		,      tokenizer=lowerCAmelCase_		,      scheduler=lowerCAmelCase_		,      learned_classifier_free_sampling_embeddings=lowerCAmelCase_		,      )


			def lowercase__						(				self	:						int		,      lowerCAmelCase_	:						Any		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						Union[str, Any]			)      ->		Tuple:





									'''simple docstring'''
									A__					:       str     =len(lowerCAmelCase_			) if isinstance(lowerCAmelCase_		,      lowerCAmelCase_			) else 1

									# get prompt text embeddings
									A__					:       str     =self.tokenizer(
									    lowerCAmelCase_		,      padding="""max_length"""		,      max_length=self.tokenizer.model_max_length		,      return_tensors="""pt"""		,      )
									A__					:       List[Any]     =text_inputs.input_ids

									if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
															A__					:       Tuple     =self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]			)
															logger.warning(
															    """The following part of your input was truncated because CLIP can only handle sequences up to"""
															    f" {self.tokenizer.model_max_length} tokens: {removed_text}"			)
															A__					:       List[str]     =text_input_ids[:, : self.tokenizer.model_max_length]
									A__					:       Any     =self.text_encoder(text_input_ids.to(self.device			)			)[0]

									# NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion.
									# While CLIP does normalize the pooled output of the text transformer when combining
									# the image and text embeddings, CLIP does not directly normalize the last hidden state.
									#
									# CLIP normalizing the pooled output.
									# https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053
									A__					:       Union[str, Any]     =prompt_embeds / prompt_embeds.norm(dim=-1		,      keepdim=lowerCAmelCase_			)

									# duplicate text embeddings for each generation per prompt
									A__					:       Tuple     =prompt_embeds.repeat_interleave(lowerCAmelCase_		,      dim=0			)

									if do_classifier_free_guidance:
															if self.learned_classifier_free_sampling_embeddings.learnable:
																					A__					:       Optional[int]     =self.learned_classifier_free_sampling_embeddings.embeddings
																					A__					:       List[Any]     =negative_prompt_embeds.unsqueeze(0			).repeat(lowerCAmelCase_		,      1		,      1			)
															else:
																					A__					:       Optional[int]     =[""""""] * batch_size

																					A__					:       Optional[int]     =text_input_ids.shape[-1]
																					A__					:       List[Any]     =self.tokenizer(
																					    lowerCAmelCase_		,      padding="""max_length"""		,      max_length=lowerCAmelCase_		,      truncation=lowerCAmelCase_		,      return_tensors="""pt"""		,      )
																					A__					:       Union[str, Any]     =self.text_encoder(uncond_input.input_ids.to(self.device			)			)[0]
																					# See comment for normalizing text embeddings
																					A__					:       List[Any]     =negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1		,      keepdim=lowerCAmelCase_			)

															# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
															A__					:       Optional[Any]     =negative_prompt_embeds.shape[1]
															A__					:       List[str]     =negative_prompt_embeds.repeat(1		,      lowerCAmelCase_		,      1			)
															A__					:       int     =negative_prompt_embeds.view(batch_size * num_images_per_prompt		,      lowerCAmelCase_		,      -1			)

															# For classifier free guidance, we need to do two forward passes.
															# Here we concatenate the unconditional and text embeddings into a single batch
															# to avoid doing two forward passes
															A__					:       List[str]     =torch.cat([negative_prompt_embeds, prompt_embeds]			)

									return prompt_embeds


			@torch.no_grad()
			def __call__(				self	:						List[Any]		,      lowerCAmelCase_	:						Union[str, List[str]]		,      lowerCAmelCase_	:						int = 1_00		,      lowerCAmelCase_	:						float = 5.0		,      lowerCAmelCase_	:						float = 1.0		,      lowerCAmelCase_	:						int = 1		,      lowerCAmelCase_	:						Optional[Union[torch.Generator, List[torch.Generator]]] = None		,      lowerCAmelCase_	:						Optional[torch.FloatTensor] = None		,      lowerCAmelCase_	:						Optional[str] = "pil"		,      lowerCAmelCase_	:						bool = True		,      lowerCAmelCase_	:						Optional[Callable[[int, int, torch.FloatTensor], None]] = None		,      lowerCAmelCase_	:						int = 1		,      )      ->		Union[ImagePipelineOutput, Tuple]:





									'''simple docstring'''
									if isinstance(lowerCAmelCase_		,      lowerCAmelCase_			):
															A__					:       str     =1
									elif isinstance(lowerCAmelCase_		,      lowerCAmelCase_			):
															A__					:       List[Any]     =len(lowerCAmelCase_			)
									else:
															raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase_			)}"			)

									A__					:       Union[str, Any]     =batch_size * num_images_per_prompt

									A__					:       Dict     =guidance_scale > 1.0

									A__					:       Tuple     =self._encode_prompt(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_			)

									if (callback_steps is None) or (
									    callback_steps is not None and (not isinstance(lowerCAmelCase_		,      lowerCAmelCase_			) or callback_steps <= 0)
									):
															raise ValueError(
															    f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
															    f" {type(lowerCAmelCase_			)}."			)

									# get the initial completely masked latents unless the user supplied it

									A__					:       Dict     =(batch_size, self.transformer.num_latent_pixels)
									if latents is None:
															A__					:       str     =self.transformer.num_vector_embeds - 1
															A__					:       Dict     =torch.full(lowerCAmelCase_		,      lowerCAmelCase_			).to(self.device			)
									else:
															if latents.shape != latents_shape:
																					raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}"			)
															if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any():
																					raise ValueError(
																					    """Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,"""
																					    f" {self.transformer.num_vector_embeds - 1} (inclusive)."			)
															A__					:       List[str]     =latents.to(self.device			)

									# set timesteps
									self.scheduler.set_timesteps(lowerCAmelCase_		,      device=self.device			)

									A__					:       Any     =self.scheduler.timesteps.to(self.device			)

									A__					:       Optional[Any]     =latents

									for i, t in enumerate(self.progress_bar(lowerCAmelCase_			)			):
															# expand the sample if we are doing classifier free guidance
															A__					:       List[str]     =torch.cat([sample] * 2			) if do_classifier_free_guidance else sample

															# predict the un-noised image
															# model_output == `log_p_x_0`
															A__					:       Tuple     =self.transformer(lowerCAmelCase_		,      encoder_hidden_states=lowerCAmelCase_		,      timestep=lowerCAmelCase_			).sample

															if do_classifier_free_guidance:
																					A__   ,						A__					:       Union[str, Any]     =model_output.chunk(2			)
																					A__					:       int     =model_output_uncond + guidance_scale * (model_output_text - model_output_uncond)
																					model_output -= torch.logsumexp(lowerCAmelCase_		,      dim=1		,      keepdim=lowerCAmelCase_			)

															A__					:       Union[str, Any]     =self.truncate(lowerCAmelCase_		,      lowerCAmelCase_			)

															# remove `log(0)`'s (`-inf`s)
															A__					:       Dict     =model_output.clamp(-70			)

															# compute the previous noisy sample x_t -> x_t-1
															A__					:       Any     =self.scheduler.step(lowerCAmelCase_		,      timestep=lowerCAmelCase_		,      sample=lowerCAmelCase_		,      generator=lowerCAmelCase_			).prev_sample

															# call the callback, if provided
															if callback is not None and i % callback_steps == 0:
																					callback(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_			)

									A__					:       List[str]     =self.vqvae.config.vq_embed_dim
									A__					:       List[str]     =(batch_size, self.transformer.height, self.transformer.width, embedding_channels)
									A__					:       Dict     =self.vqvae.quantize.get_codebook_entry(lowerCAmelCase_		,      shape=lowerCAmelCase_			)
									A__					:       Any     =self.vqvae.decode(lowerCAmelCase_		,      force_not_quantize=lowerCAmelCase_			).sample

									A__					:       str     =(image / 2 + 0.5).clamp(0		,      1			)
									A__					:       Union[str, Any]     =image.cpu().permute(0		,      2		,      3		,      1			).numpy()

									if output_type == "pil":
															A__					:       Optional[int]     =self.numpy_to_pil(lowerCAmelCase_			)

									if not return_dict:
															return (image,)

									return ImagePipelineOutput(images=lowerCAmelCase_			)



			def lowercase__						(				self	:						Dict		,      lowerCAmelCase_	:						torch.FloatTensor		,      lowerCAmelCase_	:						float			)      ->		torch.FloatTensor:





									'''simple docstring'''
									A__   ,						A__					:       List[str]     =torch.sort(lowerCAmelCase_		,      1		,      descending=lowerCAmelCase_			)
									A__					:       Union[str, Any]     =torch.exp(lowerCAmelCase_			)
									A__					:       List[str]     =sorted_p_x_0.cumsum(dim=1			) < truncation_rate

									# Ensure that at least the largest probability is not zeroed out
									A__					:       str     =torch.full_like(keep_mask[:, 0:1, :]		,      lowerCAmelCase_			)
									A__					:       Dict     =torch.cat((all_true, keep_mask)		,      dim=1			)
									A__					:       Tuple     =keep_mask[:, :-1, :]

									A__					:       Optional[int]     =keep_mask.gather(1		,      indices.argsort(1			)			)

									A__					:       Optional[int]     =log_p_x_0.clone()

									A__					:       str     =-torch.inf  # -inf = log(0)

									return rv




'''simple docstring'''



import gc
import unittest

from parameterized import parameterized

from diffusers import FlaxUNetaDConditionModel
from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow


if is_flax_available():
		import jax
		import jax.numpy as jnp



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



			'''simple docstring'''






			def lowercase__						(				self	:						Optional[Any]		,      lowerCAmelCase_	:						Union[str, Any]		,      lowerCAmelCase_	:						List[str]			)      ->		List[str]:





									'''simple docstring'''
									return f"gaussian_noise_s={seed}_shape={'_'.join([str(lowerCAmelCase_			) for s in shape]			)}.npy"


			def lowercase__						(				self	:						Optional[Any]			)      ->		Dict:





									'''simple docstring'''
									# clean up the VRAM after each test
									super().tearDown()
									gc.collect()


			def lowercase__						(				self	:						Tuple		,      lowerCAmelCase_	:						str=0		,      lowerCAmelCase_	:						List[str]=(4, 4, 64, 64)		,      lowerCAmelCase_	:						Optional[Any]=False			)      ->		str:





									'''simple docstring'''
									A__					:       Union[str, Any]     =jnp.bfloataa if fpaa else jnp.floataa
									A__					:       Any     =jnp.array(load_hf_numpy(self.get_file_format(lowerCAmelCase_		,      lowerCAmelCase_			)			)		,      dtype=lowerCAmelCase_			)
									return image


			def lowercase__						(				self	:						int		,      lowerCAmelCase_	:						Optional[int]=False		,      lowerCAmelCase_	:						Dict="CompVis/stable-diffusion-v1-4"			)      ->		List[Any]:





									'''simple docstring'''
									A__					:       Any     =jnp.bfloataa if fpaa else jnp.floataa
									A__					:       int     ="""bf16""" if fpaa else None

									A__   ,						A__					:       Any     =FlaxUNetaDConditionModel.from_pretrained(
									    lowerCAmelCase_		,      subfolder="""unet"""		,      dtype=lowerCAmelCase_		,      revision=lowerCAmelCase_			)
									return model, params


			def lowercase__						(				self	:						Optional[Any]		,      lowerCAmelCase_	:						int=0		,      lowerCAmelCase_	:						Optional[Any]=(4, 77, 7_68)		,      lowerCAmelCase_	:						List[str]=False			)      ->		Tuple:





									'''simple docstring'''
									A__					:       Union[str, Any]     =jnp.bfloataa if fpaa else jnp.floataa
									A__					:       Optional[int]     =jnp.array(load_hf_numpy(self.get_file_format(lowerCAmelCase_		,      lowerCAmelCase_			)			)		,      dtype=lowerCAmelCase_			)
									return hidden_states


			@parameterized.expand(
			    [
			        # fmt: off
			        [83, 4, [-0.2323, -0.1304, 0.0813, -0.3093, -0.0919, -0.1571, -0.1125, -0.5806]],
			        [17, 0.55, [-0.0831, -0.2443, 0.0901, -0.0919, 0.3396, 0.0103, -0.3743, 0.0701]],
			        [8, 0.89, [-0.4863, 0.0859, 0.0875, -0.1658, 0.9199, -0.0114, 0.4839, 0.4639]],
			        [3, 10_00, [-0.5649, 0.2402, -0.5518, 0.1248, 1.1328, -0.2443, -0.0325, -1.0078]],
			        # fmt: on
			    ]			)
			def lowercase__						(				self	:						Any		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						str			)      ->		int:





									'''simple docstring'''
									A__   ,						A__					:       Tuple     =self.get_unet_model(model_id="""CompVis/stable-diffusion-v1-4"""		,      fpaa=lowerCAmelCase_			)
									A__					:       List[Any]     =self.get_latents(lowerCAmelCase_		,      fpaa=lowerCAmelCase_			)
									A__					:       Optional[int]     =self.get_encoder_hidden_states(lowerCAmelCase_		,      fpaa=lowerCAmelCase_			)

									A__					:       Union[str, Any]     =model.apply(
									    {"""params""": params}		,      lowerCAmelCase_		,      jnp.array(lowerCAmelCase_		,      dtype=jnp.intaa			)		,      encoder_hidden_states=lowerCAmelCase_		,      ).sample

									assert sample.shape == latents.shape

									A__					:       Optional[int]     =jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten())			)		,      dtype=jnp.floataa			)
									A__					:       Tuple     =jnp.array(lowerCAmelCase_		,      dtype=jnp.floataa			)

									# Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware
									assert jnp.allclose(lowerCAmelCase_		,      lowerCAmelCase_		,      atol=1e-2			)



			@parameterized.expand(
			    [
			        # fmt: off
			        [83, 4, [0.1514, 0.0807, 0.1624, 0.1016, -0.1896, 0.0263, 0.0677, 0.2310]],
			        [17, 0.55, [0.1164, -0.0216, 0.0170, 0.1589, -0.3120, 0.1005, -0.0581, -0.1458]],
			        [8, 0.89, [-0.1758, -0.0169, 0.1004, -0.1411, 0.1312, 0.1103, -0.1996, 0.2139]],
			        [3, 10_00, [0.1214, 0.0352, -0.0731, -0.1562, -0.0994, -0.0906, -0.2340, -0.0539]],
			        # fmt: on
			    ]			)
			def lowercase__						(				self	:						Dict		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						int		,      lowerCAmelCase_	:						Optional[int]			)      ->		List[str]:





									'''simple docstring'''
									A__   ,						A__					:       List[str]     =self.get_unet_model(model_id="""stabilityai/stable-diffusion-2"""		,      fpaa=lowerCAmelCase_			)
									A__					:       Union[str, Any]     =self.get_latents(lowerCAmelCase_		,      shape=(4, 4, 96, 96)		,      fpaa=lowerCAmelCase_			)
									A__					:       Dict     =self.get_encoder_hidden_states(lowerCAmelCase_		,      shape=(4, 77, 10_24)		,      fpaa=lowerCAmelCase_			)

									A__					:       Optional[Any]     =model.apply(
									    {"""params""": params}		,      lowerCAmelCase_		,      jnp.array(lowerCAmelCase_		,      dtype=jnp.intaa			)		,      encoder_hidden_states=lowerCAmelCase_		,      ).sample

									assert sample.shape == latents.shape

									A__					:       Optional[Any]     =jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten())			)		,      dtype=jnp.floataa			)
									A__					:       List[Any]     =jnp.array(lowerCAmelCase_		,      dtype=jnp.floataa			)

									# Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware
									assert jnp.allclose(lowerCAmelCase_		,      lowerCAmelCase_		,      atol=1e-2			)

