






from dataclasses import dataclass
from typing import Optional

import numpy as np
import torch
import torch.nn as nn

from ..utils import BaseOutput, is_torch_version, randn_tensor
from .attention_processor import SpatialNorm
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block







@dataclass
class 		_A						( UpperCAmelCase_ ):
  lowercase_						:			torch.FloatTensor







class 		_A						( nn.Module ):

  def __init__(    self						:	Any   ,				lowerCamelCase__						:	Tuple=3   ,				lowerCamelCase__						:	Tuple=3   ,				lowerCamelCase__						:	Dict=("DownEncoderBlock2D",)   ,				lowerCamelCase__						:	Optional[Any]=(64,)   ,				lowerCamelCase__						:	Optional[int]=2   ,				lowerCamelCase__						:	List[str]=32   ,				lowerCamelCase__						:	Dict="silu"   ,				lowerCamelCase__						:	Union[str, Any]=True   ,				):
     """simple docstring"""

     super().__init__()
     __UpperCamelCase	:			str					=					layers_per_block

     __UpperCamelCase	:			List[Any]					=					torch.nn.Convad(
         lowerCamelCase__   ,				block_out_channels[0]   ,				kernel_size=3   ,				stride=1   ,				padding=1   ,				)

     __UpperCamelCase	:			Optional[int]					=					None
     __UpperCamelCase	:			Any					=					nn.ModuleList([]			)

     # down
     __UpperCamelCase	:			Optional[Any]					=					block_out_channels[0]
     for i, down_block_type in enumerate(lowerCamelCase__			):
        __UpperCamelCase	:			int					=					output_channel
        __UpperCamelCase	:			Any					=					block_out_channels[i]
        __UpperCamelCase	:			Optional[Any]					=					i == len(lowerCamelCase__			) - 1

        __UpperCamelCase	:			str					=					get_down_block(
            lowerCamelCase__   ,				num_layers=self.layers_per_block   ,				in_channels=lowerCamelCase__   ,				out_channels=lowerCamelCase__   ,				add_downsample=not is_final_block   ,				resnet_eps=1e-6   ,				downsample_padding=0   ,				resnet_act_fn=lowerCamelCase__   ,				resnet_groups=lowerCamelCase__   ,				attention_head_dim=lowerCamelCase__   ,				temb_channels=lowerCamelCase__   ,				)
        self.down_blocks.append(lowerCamelCase__			)

     # mid
     __UpperCamelCase	:			Any					=					UNetMidBlockaD(
         in_channels=block_out_channels[-1]   ,				resnet_eps=1e-6   ,				resnet_act_fn=lowerCamelCase__   ,				output_scale_factor=1   ,				resnet_time_scale_shift="""default"""   ,				attention_head_dim=block_out_channels[-1]   ,				resnet_groups=lowerCamelCase__   ,				temb_channels=lowerCamelCase__   ,				)

     # out
     __UpperCamelCase	:			Dict					=					nn.GroupNorm(num_channels=block_out_channels[-1]   ,				num_groups=lowerCamelCase__   ,				eps=1e-6			)
     __UpperCamelCase	:			int					=					nn.SiLU()

     __UpperCamelCase	:			str					=					2 * out_channels if double_z else out_channels
     __UpperCamelCase	:			Dict					=					nn.Convad(block_out_channels[-1]   ,				lowerCamelCase__   ,				3   ,				padding=1			)

     __UpperCamelCase	:			Any					=					False

  def    a					(    self						:	Dict   ,				lowerCamelCase__						:	Optional[Any]			):
     """simple docstring"""

     __UpperCamelCase	:			Optional[int]					=					x
     __UpperCamelCase	:			List[str]					=					self.conv_in(lowerCamelCase__			)

     if self.training and self.gradient_checkpointing:

        def create_custom_forward(lowerCamelCase__						:	Tuple			):
           def custom_forward(*lowerCamelCase__						:	Any			):
              return module(*lowerCamelCase__			)

           return custom_forward

        # down
        if is_torch_version(""">="""   ,				"""1.11.0"""			):
           for down_block in self.down_blocks:
              __UpperCamelCase	:			str					=					torch.utils.checkpoint.checkpoint(
                  create_custom_forward(lowerCamelCase__			)   ,				lowerCamelCase__   ,				use_reentrant=lowerCamelCase__			)
           # middle
           __UpperCamelCase	:			int					=					torch.utils.checkpoint.checkpoint(
               create_custom_forward(self.mid_block			)   ,				lowerCamelCase__   ,				use_reentrant=lowerCamelCase__			)
        else:
           for down_block in self.down_blocks:
              __UpperCamelCase	:			Tuple					=					torch.utils.checkpoint.checkpoint(create_custom_forward(lowerCamelCase__			)   ,				lowerCamelCase__			)
           # middle
           __UpperCamelCase	:			int					=					torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block			)   ,				lowerCamelCase__			)

     else:
        # down
        for down_block in self.down_blocks:
           __UpperCamelCase	:			Tuple					=					down_block(lowerCamelCase__			)

        # middle
        __UpperCamelCase	:			Dict					=					self.mid_block(lowerCamelCase__			)

     # post-process
     __UpperCamelCase	:			int					=					self.conv_norm_out(lowerCamelCase__			)
     __UpperCamelCase	:			Optional[int]					=					self.conv_act(lowerCamelCase__			)
     __UpperCamelCase	:			Optional[Any]					=					self.conv_out(lowerCamelCase__			)

     return sample







class 		_A						( nn.Module ):

  def __init__(    self						:	Tuple   ,				lowerCamelCase__						:	Tuple=3   ,				lowerCamelCase__						:	List[Any]=3   ,				lowerCamelCase__						:	Optional[int]=("UpDecoderBlock2D",)   ,				lowerCamelCase__						:	Tuple=(64,)   ,				lowerCamelCase__						:	Any=2   ,				lowerCamelCase__						:	Tuple=32   ,				lowerCamelCase__						:	List[str]="silu"   ,				lowerCamelCase__						:	Optional[Any]="group"   ,				):
     """simple docstring"""

     super().__init__()
     __UpperCamelCase	:			Optional[Any]					=					layers_per_block

     __UpperCamelCase	:			Union[str, Any]					=					nn.Convad(
         lowerCamelCase__   ,				block_out_channels[-1]   ,				kernel_size=3   ,				stride=1   ,				padding=1   ,				)

     __UpperCamelCase	:			List[str]					=					None
     __UpperCamelCase	:			Any					=					nn.ModuleList([]			)

     __UpperCamelCase	:			List[str]					=					in_channels if norm_type == """spatial""" else None

     # mid
     __UpperCamelCase	:			List[Any]					=					UNetMidBlockaD(
         in_channels=block_out_channels[-1]   ,				resnet_eps=1e-6   ,				resnet_act_fn=lowerCamelCase__   ,				output_scale_factor=1   ,				resnet_time_scale_shift="""default""" if norm_type == """group""" else norm_type   ,				attention_head_dim=block_out_channels[-1]   ,				resnet_groups=lowerCamelCase__   ,				temb_channels=lowerCamelCase__   ,				)

     # up
     __UpperCamelCase	:			Union[str, Any]					=					list(reversed(lowerCamelCase__			)			)
     __UpperCamelCase	:			str					=					reversed_block_out_channels[0]
     for i, up_block_type in enumerate(lowerCamelCase__			):
        __UpperCamelCase	:			Optional[Any]					=					output_channel
        __UpperCamelCase	:			Any					=					reversed_block_out_channels[i]

        __UpperCamelCase	:			Any					=					i == len(lowerCamelCase__			) - 1

        __UpperCamelCase	:			str					=					get_up_block(
            lowerCamelCase__   ,				num_layers=self.layers_per_block + 1   ,				in_channels=lowerCamelCase__   ,				out_channels=lowerCamelCase__   ,				prev_output_channel=lowerCamelCase__   ,				add_upsample=not is_final_block   ,				resnet_eps=1e-6   ,				resnet_act_fn=lowerCamelCase__   ,				resnet_groups=lowerCamelCase__   ,				attention_head_dim=lowerCamelCase__   ,				temb_channels=lowerCamelCase__   ,				resnet_time_scale_shift=lowerCamelCase__   ,				)
        self.up_blocks.append(lowerCamelCase__			)
        __UpperCamelCase	:			Tuple					=					output_channel

     # out
     if norm_type == "spatial":
        __UpperCamelCase	:			Optional[int]					=					SpatialNorm(block_out_channels[0]   ,				lowerCamelCase__			)
     else:
        __UpperCamelCase	:			List[Any]					=					nn.GroupNorm(num_channels=block_out_channels[0]   ,				num_groups=lowerCamelCase__   ,				eps=1e-6			)
     __UpperCamelCase	:			Optional[Any]					=					nn.SiLU()
     __UpperCamelCase	:			Optional[int]					=					nn.Convad(block_out_channels[0]   ,				lowerCamelCase__   ,				3   ,				padding=1			)

     __UpperCamelCase	:			Tuple					=					False

  def    a					(    self						:	Optional[int]   ,				lowerCamelCase__						:	str   ,				lowerCamelCase__						:	Tuple=None			):
     """simple docstring"""

     __UpperCamelCase	:			Tuple					=					z
     __UpperCamelCase	:			Tuple					=					self.conv_in(lowerCamelCase__			)

     __UpperCamelCase	:			Optional[Any]					=					next(iter(self.up_blocks.parameters()			)			).dtype
     if self.training and self.gradient_checkpointing:

        def create_custom_forward(lowerCamelCase__						:	List[str]			):
           def custom_forward(*lowerCamelCase__						:	Union[str, Any]			):
              return module(*lowerCamelCase__			)

           return custom_forward

        if is_torch_version(""">="""   ,				"""1.11.0"""			):
           # middle
           __UpperCamelCase	:			str					=					torch.utils.checkpoint.checkpoint(
               create_custom_forward(self.mid_block			)   ,				lowerCamelCase__   ,				lowerCamelCase__   ,				use_reentrant=lowerCamelCase__			)
           __UpperCamelCase	:			Tuple					=					sample.to(lowerCamelCase__			)

           # up
           for up_block in self.up_blocks:
              __UpperCamelCase	:			Dict					=					torch.utils.checkpoint.checkpoint(
                  create_custom_forward(lowerCamelCase__			)   ,				lowerCamelCase__   ,				lowerCamelCase__   ,				use_reentrant=lowerCamelCase__			)
        else:
           # middle
           __UpperCamelCase	:			List[Any]					=					torch.utils.checkpoint.checkpoint(
               create_custom_forward(self.mid_block			)   ,				lowerCamelCase__   ,				lowerCamelCase__			)
           __UpperCamelCase	:			Tuple					=					sample.to(lowerCamelCase__			)

           # up
           for up_block in self.up_blocks:
              __UpperCamelCase	:			Tuple					=					torch.utils.checkpoint.checkpoint(create_custom_forward(lowerCamelCase__			)   ,				lowerCamelCase__   ,				lowerCamelCase__			)
     else:
        # middle
        __UpperCamelCase	:			Optional[int]					=					self.mid_block(lowerCamelCase__   ,				lowerCamelCase__			)
        __UpperCamelCase	:			Union[str, Any]					=					sample.to(lowerCamelCase__			)

        # up
        for up_block in self.up_blocks:
           __UpperCamelCase	:			int					=					up_block(lowerCamelCase__   ,				lowerCamelCase__			)

        # post-process
     if latent_embeds is None:
        __UpperCamelCase	:			Tuple					=					self.conv_norm_out(lowerCamelCase__			)
     else:
        __UpperCamelCase	:			Tuple					=					self.conv_norm_out(lowerCamelCase__   ,				lowerCamelCase__			)
     __UpperCamelCase	:			Optional[Any]					=					self.conv_act(lowerCamelCase__			)
     __UpperCamelCase	:			str					=					self.conv_out(lowerCamelCase__			)

     return sample







class 		_A						( nn.Module ):

  def __init__(    self						:	Tuple   ,				lowerCamelCase__						:	Optional[int]   ,				lowerCamelCase__						:	Any   ,				lowerCamelCase__						:	List[str]   ,				lowerCamelCase__						:	Union[str, Any]=None   ,				lowerCamelCase__						:	int="random"   ,				lowerCamelCase__						:	str=False   ,				lowerCamelCase__						:	str=True			):
     """simple docstring"""

     super().__init__()
     __UpperCamelCase	:			int					=					n_e
     __UpperCamelCase	:			Union[str, Any]					=					vq_embed_dim
     __UpperCamelCase	:			Any					=					beta
     __UpperCamelCase	:			Optional[Any]					=					legacy

     __UpperCamelCase	:			Tuple					=					nn.Embedding(self.n_e   ,				self.vq_embed_dim			)
     self.embedding.weight.data.uniform_(-1.0 / self.n_e   ,				1.0 / self.n_e			)

     __UpperCamelCase	:			Optional[int]					=					remap
     if self.remap is not None:
        self.register_buffer("""used"""   ,				torch.tensor(np.load(self.remap			)			)			)
        __UpperCamelCase	:			Optional[int]					=					self.used.shape[0]
        __UpperCamelCase	:			Dict					=					unknown_index  # "random" or "extra" or integer
        if self.unknown_index == "extra":
           __UpperCamelCase	:			int					=					self.re_embed
           __UpperCamelCase	:			Dict					=					self.re_embed + 1
        print(
            f'Remapping {self.n_e} indices to {self.re_embed} indices. '
            f'Using {self.unknown_index} for unknown indices.'			)
     else:
        __UpperCamelCase	:			List[str]					=					n_e

     __UpperCamelCase	:			Any					=					sane_index_shape

  def    a					(    self						:	Any   ,				lowerCamelCase__						:	Any			):
     """simple docstring"""

     __UpperCamelCase	:			Union[str, Any]					=					inds.shape
     assert len(lowerCamelCase__			) > 1
     __UpperCamelCase	:			Dict					=					inds.reshape(ishape[0]   ,				-1			)
     __UpperCamelCase	:			Optional[Any]					=					self.used.to(lowerCamelCase__			)
     __UpperCamelCase	:			List[Any]					=					(inds[:, :, None] == used[None, None, ...]).long()
     __UpperCamelCase	:			int					=					match.argmax(-1			)
     __UpperCamelCase	:			Tuple					=					match.sum(2			) < 1
     if self.unknown_index == "random":
        __UpperCamelCase	:			Dict					=					torch.randint(0   ,				self.re_embed   ,				size=new[unknown].shape			).to(device=new.device			)
     else:
        __UpperCamelCase	:			List[Any]					=					self.unknown_index
     return new.reshape(lowerCamelCase__			)

  def    a					(    self						:	Dict   ,				lowerCamelCase__						:	Any			):
     """simple docstring"""

     __UpperCamelCase	:			Tuple					=					inds.shape
     assert len(lowerCamelCase__			) > 1
     __UpperCamelCase	:			str					=					inds.reshape(ishape[0]   ,				-1			)
     __UpperCamelCase	:			Optional[int]					=					self.used.to(lowerCamelCase__			)
     if self.re_embed > self.used.shape[0]:  # extra token
        __UpperCamelCase	:			Union[str, Any]					=					0  # simply set to zero
     __UpperCamelCase	:			List[Any]					=					torch.gather(used[None, :][inds.shape[0] * [0], :]   ,				1   ,				lowerCamelCase__			)
     return back.reshape(lowerCamelCase__			)

  def    a					(    self						:	Tuple   ,				lowerCamelCase__						:	Optional[Any]			):
     """simple docstring"""

     __UpperCamelCase	:			Union[str, Any]					=					z.permute(0   ,				2   ,				3   ,				1			).contiguous()
     __UpperCamelCase	:			List[str]					=					z.view(-1   ,				self.vq_embed_dim			)

     # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
     __UpperCamelCase	:			List[Any]					=					torch.argmin(torch.cdist(lowerCamelCase__   ,				self.embedding.weight			)   ,				dim=1			)

     __UpperCamelCase	:			Union[str, Any]					=					self.embedding(lowerCamelCase__			).view(z.shape			)
     __UpperCamelCase	:			Optional[int]					=					None
     __UpperCamelCase	:			int					=					None

     # compute loss for embedding
     if not self.legacy:
        __UpperCamelCase	:			str					=					self.beta * torch.mean((z_q.detach() - z) ** 2			) + torch.mean((z_q - z.detach()) ** 2			)
     else:
        __UpperCamelCase	:			Optional[Any]					=					torch.mean((z_q.detach() - z) ** 2			) + self.beta * torch.mean((z_q - z.detach()) ** 2			)

     # preserve gradients
     __UpperCamelCase	:			int					=					z + (z_q - z).detach()

     # reshape back to match original input shape
     __UpperCamelCase	:			Optional[Any]					=					z_q.permute(0   ,				3   ,				1   ,				2			).contiguous()

     if self.remap is not None:
        __UpperCamelCase	:			List[Any]					=					min_encoding_indices.reshape(z.shape[0]   ,				-1			)  # add batch axis
        __UpperCamelCase	:			str					=					self.remap_to_used(lowerCamelCase__			)
        __UpperCamelCase	:			List[str]					=					min_encoding_indices.reshape(-1   ,				1			)  # flatten

     if self.sane_index_shape:
        __UpperCamelCase	:			List[Any]					=					min_encoding_indices.reshape(z_q.shape[0]   ,				z_q.shape[2]   ,				z_q.shape[3]			)

     return z_q, loss, (perplexity, min_encodings, min_encoding_indices)

  def    a					(    self						:	List[str]   ,				lowerCamelCase__						:	Dict   ,				lowerCamelCase__						:	Optional[int]			):
     """simple docstring"""

     if self.remap is not None:
        __UpperCamelCase	:			Any					=					indices.reshape(shape[0]   ,				-1			)  # add batch axis
        __UpperCamelCase	:			List[Any]					=					self.unmap_to_all(lowerCamelCase__			)
        __UpperCamelCase	:			Optional[int]					=					indices.reshape(-1			)  # flatten again

     # get quantized latent vectors
     __UpperCamelCase	:			List[Any]					=					self.embedding(lowerCamelCase__			)

     if shape is not None:
        __UpperCamelCase	:			List[Any]					=					z_q.view(lowerCamelCase__			)
        # reshape back to match original input shape
        __UpperCamelCase	:			Tuple					=					z_q.permute(0   ,				3   ,				1   ,				2			).contiguous()

     return z_q







class 		_A						( UpperCAmelCase_ ):

  def __init__(    self						:	Union[str, Any]   ,				lowerCamelCase__						:	Union[str, Any]   ,				lowerCamelCase__						:	int=False			):
     """simple docstring"""

     __UpperCamelCase	:			Any					=					parameters
     __UpperCamelCase	,     __UpperCamelCase	:			str					=					torch.chunk(lowerCamelCase__   ,				2   ,				dim=1			)
     __UpperCamelCase	:			List[Any]					=					torch.clamp(self.logvar   ,				-30.0   ,				20.0			)
     __UpperCamelCase	:			Tuple					=					deterministic
     __UpperCamelCase	:			Tuple					=					torch.exp(0.5 * self.logvar			)
     __UpperCamelCase	:			Union[str, Any]					=					torch.exp(self.logvar			)
     if self.deterministic:
        __UpperCamelCase	:			int					=					torch.zeros_like(
            self.mean   ,				device=self.parameters.device   ,				dtype=self.parameters.dtype			)

  def    a					(    self						:	List[str]   ,				lowerCamelCase__						:	Optional[torch.Generator] = None			):
     """simple docstring"""

     __UpperCamelCase	:			Optional[Any]					=					randn_tensor(
         self.mean.shape   ,				generator=lowerCamelCase__   ,				device=self.parameters.device   ,				dtype=self.parameters.dtype			)
     __UpperCamelCase	:			Optional[Any]					=					self.mean + self.std * sample
     return x

  def    a					(    self						:	Optional[int]   ,				lowerCamelCase__						:	Union[str, Any]=None			):
     """simple docstring"""

     if self.deterministic:
        return torch.Tensor([0.0]			)
     else:
        if other is None:
           return 0.5 * torch.sum(torch.pow(self.mean   ,				2			) + self.var - 1.0 - self.logvar   ,				dim=[1, 2, 3]			)
        else:
           return 0.5 * torch.sum(
               torch.pow(self.mean - other.mean   ,				2			) / other.var
               + self.var / other.var
               - 1.0
               - self.logvar
               + other.logvar   ,				dim=[1, 2, 3]   ,				)

  def    a					(    self						:	Optional[int]   ,				lowerCamelCase__						:	int   ,				lowerCamelCase__						:	int=[1, 2, 3]			):
     """simple docstring"""

     if self.deterministic:
        return torch.Tensor([0.0]			)
     __UpperCamelCase	:			List[str]					=					np.log(2.0 * np.pi			)
     return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean   ,				2			) / self.var   ,				dim=lowerCamelCase__			)

  def    a					(    self						:	Dict			):
     """simple docstring"""

     return self.mean











import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class 		_A						( UpperCAmelCase_	,				unittest.TestCase ):
  lowercase_						:			Union[str, Any]						=					LDMTextToImagePipeline
  lowercase_						:			Tuple						=					TEXT_TO_IMAGE_PARAMS - {
      '''negative_prompt''',
      '''negative_prompt_embeds''',
      '''cross_attention_kwargs''',
      '''prompt_embeds''',
  }
  lowercase_						:			Optional[Any]						=					PipelineTesterMixin.required_optional_params - {
      '''num_images_per_prompt''',
      '''callback''',
      '''callback_steps''',
  }
  lowercase_						:			Dict						=					TEXT_TO_IMAGE_BATCH_PARAMS
  lowercase_						:			Tuple						=					False

  def    a					(    self						:	Optional[Any]			):
     """simple docstring"""

     torch.manual_seed(0			)
     __UpperCamelCase	:			Any					=					UNetaDConditionModel(
         block_out_channels=(32, 64)   ,				layers_per_block=2   ,				sample_size=32   ,				in_channels=4   ,				out_channels=4   ,				down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")   ,				up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")   ,				cross_attention_dim=32   ,				)
     __UpperCamelCase	:			Union[str, Any]					=					DDIMScheduler(
         beta_start=0.0_0085   ,				beta_end=0.012   ,				beta_schedule="""scaled_linear"""   ,				clip_sample=lowerCamelCase__   ,				set_alpha_to_one=lowerCamelCase__   ,				)
     torch.manual_seed(0			)
     __UpperCamelCase	:			Any					=					AutoencoderKL(
         block_out_channels=(32, 64)   ,				in_channels=3   ,				out_channels=3   ,				down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""")   ,				up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""")   ,				latent_channels=4   ,				)
     torch.manual_seed(0			)
     __UpperCamelCase	:			Union[str, Any]					=					CLIPTextConfig(
         bos_token_id=0   ,				eos_token_id=2   ,				hidden_size=32   ,				intermediate_size=37   ,				layer_norm_eps=1e-05   ,				num_attention_heads=4   ,				num_hidden_layers=5   ,				pad_token_id=1   ,				vocab_size=10_00   ,				)
     __UpperCamelCase	:			List[str]					=					CLIPTextModel(lowerCamelCase__			)
     __UpperCamelCase	:			List[str]					=					CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""			)

     __UpperCamelCase	:			Any					=					{
         """unet""": unet,
         """scheduler""": scheduler,
         """vqvae""": vae,
         """bert""": text_encoder,
         """tokenizer""": tokenizer,
     }
     return components

  def    a					(    self						:	Tuple   ,				lowerCamelCase__						:	str   ,				lowerCamelCase__						:	List[str]=0			):
     """simple docstring"""

     if str(lowerCamelCase__			).startswith("""mps"""			):
        __UpperCamelCase	:			str					=					torch.manual_seed(lowerCamelCase__			)
     else:
        __UpperCamelCase	:			Optional[Any]					=					torch.Generator(device=lowerCamelCase__			).manual_seed(lowerCamelCase__			)
     __UpperCamelCase	:			Tuple					=					{
         """prompt""": """A painting of a squirrel eating a burger""",
         """generator""": generator,
         """num_inference_steps""": 2,
         """guidance_scale""": 6.0,
         """output_type""": """numpy""",
     }
     return inputs

  def    a					(    self						:	Tuple			):
     """simple docstring"""

     __UpperCamelCase	:			Dict					=					"""cpu"""  # ensure determinism for the device-dependent torch.Generator

     __UpperCamelCase	:			List[str]					=					self.get_dummy_components()
     __UpperCamelCase	:			Optional[int]					=					LDMTextToImagePipeline(**lowerCamelCase__			)
     pipe.to(lowerCamelCase__			)
     pipe.set_progress_bar_config(disable=lowerCamelCase__			)

     __UpperCamelCase	:			List[Any]					=					self.get_dummy_inputs(lowerCamelCase__			)
     __UpperCamelCase	:			List[Any]					=					pipe(**lowerCamelCase__			).images
     __UpperCamelCase	:			Tuple					=					image[0, -3:, -3:, -1]

     assert image.shape == (1, 16, 16, 3)
     __UpperCamelCase	:			int					=					np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014]			)

     assert np.abs(image_slice.flatten() - expected_slice			).max() < 1e-3







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

  def    a					(    self						:	Any			):
     """simple docstring"""

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

  def    a					(    self						:	Dict   ,				lowerCamelCase__						:	List[Any]   ,				lowerCamelCase__						:	Tuple=torch.floataa   ,				lowerCamelCase__						:	List[Any]=0			):
     """simple docstring"""

     __UpperCamelCase	:			Union[str, Any]					=					torch.manual_seed(lowerCamelCase__			)
     __UpperCamelCase	:			Tuple					=					np.random.RandomState(lowerCamelCase__			).standard_normal((1, 4, 32, 32)			)
     __UpperCamelCase	:			Any					=					torch.from_numpy(lowerCamelCase__			).to(device=lowerCamelCase__   ,				dtype=lowerCamelCase__			)
     __UpperCamelCase	:			Optional[int]					=					{
         """prompt""": """A painting of a squirrel eating a burger""",
         """latents""": latents,
         """generator""": generator,
         """num_inference_steps""": 3,
         """guidance_scale""": 6.0,
         """output_type""": """numpy""",
     }
     return inputs

  def    a					(    self						:	Optional[int]			):
     """simple docstring"""

     __UpperCamelCase	:			Any					=					LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""			).to(lowerCamelCase__			)
     pipe.set_progress_bar_config(disable=lowerCamelCase__			)

     __UpperCamelCase	:			Any					=					self.get_inputs(lowerCamelCase__			)
     __UpperCamelCase	:			Tuple					=					pipe(**lowerCamelCase__			).images
     __UpperCamelCase	:			Optional[int]					=					image[0, -3:, -3:, -1].flatten()

     assert image.shape == (1, 2_56, 2_56, 3)
     __UpperCamelCase	:			Optional[Any]					=					np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878]			)
     __UpperCamelCase	:			Union[str, Any]					=					np.abs(expected_slice - image_slice			).max()
     assert max_diff < 1e-3







@nightly
@require_torch_gpu
class 		_A						( unittest.TestCase ):

  def    a					(    self						:	Optional[Any]			):
     """simple docstring"""

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

  def    a					(    self						:	Tuple   ,				lowerCamelCase__						:	str   ,				lowerCamelCase__						:	Union[str, Any]=torch.floataa   ,				lowerCamelCase__						:	Tuple=0			):
     """simple docstring"""

     __UpperCamelCase	:			Union[str, Any]					=					torch.manual_seed(lowerCamelCase__			)
     __UpperCamelCase	:			Optional[Any]					=					np.random.RandomState(lowerCamelCase__			).standard_normal((1, 4, 32, 32)			)
     __UpperCamelCase	:			List[Any]					=					torch.from_numpy(lowerCamelCase__			).to(device=lowerCamelCase__   ,				dtype=lowerCamelCase__			)
     __UpperCamelCase	:			Union[str, Any]					=					{
         """prompt""": """A painting of a squirrel eating a burger""",
         """latents""": latents,
         """generator""": generator,
         """num_inference_steps""": 50,
         """guidance_scale""": 6.0,
         """output_type""": """numpy""",
     }
     return inputs

  def    a					(    self						:	Tuple			):
     """simple docstring"""

     __UpperCamelCase	:			Tuple					=					LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""			).to(lowerCamelCase__			)
     pipe.set_progress_bar_config(disable=lowerCamelCase__			)

     __UpperCamelCase	:			Dict					=					self.get_inputs(lowerCamelCase__			)
     __UpperCamelCase	:			List[Any]					=					pipe(**lowerCamelCase__			).images[0]

     __UpperCamelCase	:			Optional[Any]					=					load_numpy(
         """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy"""			)
     __UpperCamelCase	:			int					=					np.abs(expected_image - image			).max()
     assert max_diff < 1e-3



