





import tempfile
import unittest

import numpy as np

from diffusers import (
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionPipeline,
    PNDMScheduler,
)
from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
      import onnxruntime as ort







class    __snake_case	(							__lowerCamelCase       ,      unittest.TestCase      ):





       '''simple docstring'''







       lowerCAmelCase__						=					"""hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"""




       def 							UpperCAmelCase__			(  self			:   Tuple							,    A			:   str=0		):
         __snake_case:						List[str]			  =						np.random.RandomState(A		)
         __snake_case:						List[Any]			  =						{
             """prompt""": """A painting of a squirrel eating a burger""",
             """generator""": generator,
             """num_inference_steps""": 2,
             """guidance_scale""": 7.5,
             """output_type""": """numpy""",
         }
         return inputs




       def 							UpperCAmelCase__			(  self			:   Optional[Any]		):
         __snake_case:						Optional[int]			  =						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint							,    provider="""CPUExecutionProvider"""		)
         pipe.set_progress_bar_config(disable=A		)

         __snake_case:						int			  =						self.get_dummy_inputs()
         __snake_case:						List[Any]			  =						pipe(**A		).images
         __snake_case:						Optional[int]			  =						image[0, -3:, -3:, -1]

         assert image.shape == (1, 128, 128, 3)
         __snake_case:						Any			  =						np.array([0.6_5072, 0.5_8492, 0.4_8219, 0.5_5521, 0.5_3180, 0.5_5939, 0.5_0697, 0.3_9800, 0.4_6455]		)

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




       def 							UpperCAmelCase__			(  self			:   Dict		):
         __snake_case:						str			  =						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint							,    provider="""CPUExecutionProvider"""		)
         __snake_case:						List[Any]			  =						PNDMScheduler.from_config(pipe.scheduler.config							,    skip_prk_steps=A		)
         pipe.set_progress_bar_config(disable=A		)

         __snake_case:						str			  =						self.get_dummy_inputs()
         __snake_case:						Union[str, Any]			  =						pipe(**A		).images
         __snake_case:						Optional[Any]			  =						image[0, -3:, -3:, -1]

         assert image.shape == (1, 128, 128, 3)
         __snake_case:						List[str]			  =						np.array([0.6_5863, 0.5_9425, 0.4_9326, 0.5_6313, 0.5_3875, 0.5_6627, 0.5_1065, 0.3_9777, 0.4_6330]		)

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




       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         __snake_case:						str			  =						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint							,    provider="""CPUExecutionProvider"""		)
         __snake_case:						int			  =						LMSDiscreteScheduler.from_config(pipe.scheduler.config		)
         pipe.set_progress_bar_config(disable=A		)

         __snake_case:						str			  =						self.get_dummy_inputs()
         __snake_case:						Optional[int]			  =						pipe(**A		).images
         __snake_case:						Optional[Any]			  =						image[0, -3:, -3:, -1]

         assert image.shape == (1, 128, 128, 3)
         __snake_case:						Optional[int]			  =						np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279]		)

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




       def 							UpperCAmelCase__			(  self			:   List[str]		):
         __snake_case:						Optional[Any]			  =						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint							,    provider="""CPUExecutionProvider"""		)
         __snake_case:						Dict			  =						EulerDiscreteScheduler.from_config(pipe.scheduler.config		)
         pipe.set_progress_bar_config(disable=A		)

         __snake_case:						Union[str, Any]			  =						self.get_dummy_inputs()
         __snake_case:						int			  =						pipe(**A		).images
         __snake_case:						str			  =						image[0, -3:, -3:, -1]

         assert image.shape == (1, 128, 128, 3)
         __snake_case:						Optional[int]			  =						np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279]		)

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




       def 							UpperCAmelCase__			(  self			:   Any		):
         __snake_case:						Dict			  =						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint							,    provider="""CPUExecutionProvider"""		)
         __snake_case:						str			  =						EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config		)
         pipe.set_progress_bar_config(disable=A		)

         __snake_case:						int			  =						self.get_dummy_inputs()
         __snake_case:						Optional[Any]			  =						pipe(**A		).images
         __snake_case:						List[Any]			  =						image[0, -3:, -3:, -1]

         assert image.shape == (1, 128, 128, 3)
         __snake_case:						List[Any]			  =						np.array([0.5_3817, 0.6_0812, 0.4_7384, 0.4_9530, 0.5_1894, 0.4_9814, 0.4_7984, 0.3_8958, 0.4_4271]		)

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




       def 							UpperCAmelCase__			(  self			:   Optional[Any]		):
         __snake_case:						str			  =						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint							,    provider="""CPUExecutionProvider"""		)
         __snake_case:						Optional[Any]			  =						DPMSolverMultistepScheduler.from_config(pipe.scheduler.config		)
         pipe.set_progress_bar_config(disable=A		)

         __snake_case:						str			  =						self.get_dummy_inputs()
         __snake_case:						Any			  =						pipe(**A		).images
         __snake_case:						Any			  =						image[0, -3:, -3:, -1]

         assert image.shape == (1, 128, 128, 3)
         __snake_case:						Optional[Any]			  =						np.array([0.5_3895, 0.6_0808, 0.4_7933, 0.4_9608, 0.5_1886, 0.4_9950, 0.4_8053, 0.3_8957, 0.4_4200]		)

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




       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         __snake_case:						Any			  =						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint							,    provider="""CPUExecutionProvider"""		)
         pipe.set_progress_bar_config(disable=A		)

         __snake_case:						str			  =						self.get_dummy_inputs()
         __snake_case:						List[Any]			  =						3 * [inputs["""prompt"""]]

         # forward
         __snake_case:						str			  =						pipe(**A		)
         __snake_case:						List[Any]			  =						output.images[0, -3:, -3:, -1]

         __snake_case:						Optional[Any]			  =						self.get_dummy_inputs()
         __snake_case:						Dict			  =						3 * [inputs.pop("""prompt"""		)]

         __snake_case:						Optional[int]			  =						pipe.tokenizer(
             A							,    padding="""max_length"""							,    max_length=pipe.tokenizer.model_max_length							,    truncation=A							,    return_tensors="""np"""							,    )
         __snake_case:						Union[str, Any]			  =						text_inputs["""input_ids"""]

         __snake_case:						int			  =						pipe.text_encoder(input_ids=text_inputs.astype(np.intaa		)		)[0]

         __snake_case:						Optional[Any]			  =						prompt_embeds

         # forward
         __snake_case:						List[str]			  =						pipe(**A		)
         __snake_case:						Optional[Any]			  =						output.images[0, -3:, -3:, -1]

         assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()		).max() < 1E-4






       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         __snake_case:						Tuple			  =						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint							,    provider="""CPUExecutionProvider"""		)
         pipe.set_progress_bar_config(disable=A		)

         __snake_case:						Optional[Any]			  =						self.get_dummy_inputs()
         __snake_case:						List[Any]			  =						3 * ["""this is a negative prompt"""]
         __snake_case:						Any			  =						negative_prompt
         __snake_case:						Dict			  =						3 * [inputs["""prompt"""]]

         # forward
         __snake_case:						Union[str, Any]			  =						pipe(**A		)
         __snake_case:						List[Any]			  =						output.images[0, -3:, -3:, -1]

         __snake_case:						Optional[Any]			  =						self.get_dummy_inputs()
         __snake_case:						Union[str, Any]			  =						3 * [inputs.pop("""prompt"""		)]

         __snake_case:						List[str]			  =						[]
         for p in [prompt, negative_prompt]:
           __snake_case:						Union[str, Any]			  =						pipe.tokenizer(
               A							,    padding="""max_length"""							,    max_length=pipe.tokenizer.model_max_length							,    truncation=A							,    return_tensors="""np"""							,    )
           __snake_case:						List[Any]			  =						text_inputs["""input_ids"""]

           embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa		)		)[0]		)

         __snake_case  ,       __snake_case:						Optional[int]			  =						embeds

         # forward
         __snake_case:						Dict			  =						pipe(**A		)
         __snake_case:						List[Any]			  =						output.images[0, -3:, -3:, -1]

         assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()		).max() < 1E-4







@nightly
@require_onnxruntime
@require_torch_gpu
class    __snake_case	(							unittest.TestCase      ):





       '''simple docstring'''







       @property
       def 							UpperCAmelCase__			(  self			:   str		):
         return (
             "CUDAExecutionProvider",
             {
                 "gpu_mem_limit": "15000000000",  # 15GB
                 "arena_extend_strategy": "kSameAsRequested",
             },
         )




       @property
       def 							UpperCAmelCase__			(  self			:   str		):
         __snake_case:						Tuple			  =						ort.SessionOptions()
         __snake_case:						List[str]			  =						False
         return options




       def 							UpperCAmelCase__			(  self			:   int		):
         # using the PNDM scheduler by default
         __snake_case:						int			  =						OnnxStableDiffusionPipeline.from_pretrained(
             """CompVis/stable-diffusion-v1-4"""							,    revision="""onnx"""							,    safety_checker=A							,    feature_extractor=A							,    provider=self.gpu_provider							,    sess_options=self.gpu_options							,    )
         sd_pipe.set_progress_bar_config(disable=A		)

         __snake_case:						int			  =						"""A painting of a squirrel eating a burger"""
         np.random.seed(0		)
         __snake_case:						Optional[Any]			  =						sd_pipe([prompt]							,    guidance_scale=6.0							,    num_inference_steps=10							,    output_type="""np"""		)
         __snake_case:						Optional[int]			  =						output.images

         __snake_case:						List[Any]			  =						image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         __snake_case:						Optional[Any]			  =						np.array([0.0452, 0.0390, 0.0087, 0.0350, 0.0617, 0.0364, 0.0544, 0.0523, 0.0720]		)

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




       def 							UpperCAmelCase__			(  self			:   Optional[Any]		):
         __snake_case:						List[Any]			  =						DDIMScheduler.from_pretrained(
             """runwayml/stable-diffusion-v1-5"""							,    subfolder="""scheduler"""							,    revision="""onnx"""		)
         __snake_case:						Dict			  =						OnnxStableDiffusionPipeline.from_pretrained(
             """runwayml/stable-diffusion-v1-5"""							,    revision="""onnx"""							,    scheduler=A							,    safety_checker=A							,    feature_extractor=A							,    provider=self.gpu_provider							,    sess_options=self.gpu_options							,    )
         sd_pipe.set_progress_bar_config(disable=A		)

         __snake_case:						str			  =						"""open neural network exchange"""
         __snake_case:						List[Any]			  =						np.random.RandomState(0		)
         __snake_case:						Union[str, Any]			  =						sd_pipe([prompt]							,    guidance_scale=7.5							,    num_inference_steps=10							,    generator=A							,    output_type="""np"""		)
         __snake_case:						Tuple			  =						output.images
         __snake_case:						str			  =						image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         __snake_case:						Tuple			  =						np.array([0.2867, 0.1974, 0.1481, 0.7294, 0.7251, 0.6667, 0.4194, 0.5642, 0.6486]		)

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




       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         __snake_case:						int			  =						LMSDiscreteScheduler.from_pretrained(
             """runwayml/stable-diffusion-v1-5"""							,    subfolder="""scheduler"""							,    revision="""onnx"""		)
         __snake_case:						List[str]			  =						OnnxStableDiffusionPipeline.from_pretrained(
             """runwayml/stable-diffusion-v1-5"""							,    revision="""onnx"""							,    scheduler=A							,    safety_checker=A							,    feature_extractor=A							,    provider=self.gpu_provider							,    sess_options=self.gpu_options							,    )
         sd_pipe.set_progress_bar_config(disable=A		)

         __snake_case:						str			  =						"""open neural network exchange"""
         __snake_case:						Optional[int]			  =						np.random.RandomState(0		)
         __snake_case:						str			  =						sd_pipe([prompt]							,    guidance_scale=7.5							,    num_inference_steps=10							,    generator=A							,    output_type="""np"""		)
         __snake_case:						List[str]			  =						output.images
         __snake_case:						List[Any]			  =						image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         __snake_case:						List[str]			  =						np.array([0.2306, 0.1959, 0.1593, 0.6549, 0.6394, 0.5408, 0.5065, 0.6010, 0.6161]		)

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




       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         __snake_case:						Any			  =						0

         def test_callback_fn(A			:   int							,    A			:   int							,    A			:   np.ndarray		) -> None:
           __snake_case:						Dict			  =						True
           nonlocal number_of_steps
           number_of_steps += 1
           if step == 0:
             assert latents.shape == (1, 4, 64, 64)
             __snake_case:						str			  =						latents[0, -3:, -3:, -1]
             __snake_case:						Optional[Any]			  =						np.array(
                 [-0.6772, -0.3835, -1.2456, 0.1905, -1.0974, 0.6967, -1.9353, 0.0178, 1.0167]		)

             assert np.abs(latents_slice.flatten() - expected_slice		).max() < 1E-3
           elif step == 5:
             assert latents.shape == (1, 4, 64, 64)
             __snake_case:						Optional[int]			  =						latents[0, -3:, -3:, -1]
             __snake_case:						List[str]			  =						np.array(
                 [-0.3351, 0.2241, -0.1837, -0.2325, -0.6577, 0.3393, -0.0241, 0.5899, 1.3875]		)

             assert np.abs(latents_slice.flatten() - expected_slice		).max() < 1E-3

         __snake_case:						Dict			  =						False

         __snake_case:						Any			  =						OnnxStableDiffusionPipeline.from_pretrained(
             """runwayml/stable-diffusion-v1-5"""							,    revision="""onnx"""							,    safety_checker=A							,    feature_extractor=A							,    provider=self.gpu_provider							,    sess_options=self.gpu_options							,    )
         pipe.set_progress_bar_config(disable=A		)

         __snake_case:						List[str]			  =						"""Andromeda galaxy in a bottle"""

         __snake_case:						Union[str, Any]			  =						np.random.RandomState(0		)
         pipe(
             prompt=A							,    num_inference_steps=5							,    guidance_scale=7.5							,    generator=A							,    callback=A							,    callback_steps=1							,    )
         assert test_callback_fn.has_been_called
         assert number_of_steps == 6






       def 							UpperCAmelCase__			(  self			:   Tuple		):
         __snake_case:						Optional[int]			  =						OnnxStableDiffusionPipeline.from_pretrained(
             """runwayml/stable-diffusion-v1-5"""							,    revision="""onnx"""							,    safety_checker=A							,    feature_extractor=A							,    provider=self.gpu_provider							,    sess_options=self.gpu_options							,    )
         assert isinstance(A							,    A		)
         assert pipe.safety_checker is None

         __snake_case:						List[str]			  =						pipe("""example prompt"""							,    num_inference_steps=2		).images[0]
         assert image is not None

         # check that there's no error when saving a pipeline with one of the models being None
         with tempfile.TemporaryDirectory() as tmpdirname:
           pipe.save_pretrained(A		)
           __snake_case:						List[str]			  =						OnnxStableDiffusionPipeline.from_pretrained(A		)

         # sanity check that the pipeline still works
         assert pipe.safety_checker is None
         __snake_case:						int			  =						pipe("""example prompt"""							,    num_inference_steps=2		).images[0]
         assert image is not None













from dataclasses import dataclass
from typing import Dict, Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .attention_processor import AttentionProcessor, AttnProcessor
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder







@dataclass
class    __snake_case	(							__lowerCamelCase      ):





       '''simple docstring'''







       lowerCAmelCase__						=					42







class    __snake_case	(							__lowerCamelCase       ,      __lowerCamelCase      ):





       '''simple docstring'''







       lowerCAmelCase__						=					True




       @register_to_config
       def __init__(  self			:   Union[str, Any]							,    A			:   int = 3							,    A			:   int = 3							,    A			:   Tuple[str] = ("DownEncoderBlock2D",)							,    A			:   Tuple[str] = ("UpDecoderBlock2D",)							,    A			:   Tuple[int] = (64,)							,    A			:   int = 1							,    A			:   str = "silu"							,    A			:   int = 4							,    A			:   int = 32							,    A			:   int = 32							,    A			:   float = 0.1_8215							,    ):
         super().__init__()

         # pass init params to Encoder
         __snake_case:						Any			  =						Encoder(
             in_channels=A							,    out_channels=A							,    down_block_types=A							,    block_out_channels=A							,    layers_per_block=A							,    act_fn=A							,    norm_num_groups=A							,    double_z=A							,    )

         # pass init params to Decoder
         __snake_case:						int			  =						Decoder(
             in_channels=A							,    out_channels=A							,    up_block_types=A							,    block_out_channels=A							,    layers_per_block=A							,    norm_num_groups=A							,    act_fn=A							,    )

         __snake_case:						Dict			  =						nn.Convad(2 * latent_channels							,    2 * latent_channels							,    1		)
         __snake_case:						int			  =						nn.Convad(A							,    A							,    1		)

         __snake_case:						List[str]			  =						False
         __snake_case:						Optional[int]			  =						False

         # only relevant if vae tiling is enabled
         __snake_case:						Any			  =						self.config.sample_size
         __snake_case:						int			  =						(
             self.config.sample_size[0]
             if isinstance(self.config.sample_size							,    (list, tuple)		)
             else self.config.sample_size
         )
         __snake_case:						Union[str, Any]			  =						int(sample_size / (2 ** (len(self.config.block_out_channels		) - 1))		)
         __snake_case:						Optional[int]			  =						0.25




       def 							UpperCAmelCase__			(  self			:   int							,    A			:   List[str]							,    A			:   Optional[Any]=False		):
         if isinstance(A							,    (Encoder, Decoder)		):
           __snake_case:						str			  =						value




       def 							UpperCAmelCase__			(  self			:   str							,    A			:   bool = True		):
         __snake_case:						Union[str, Any]			  =						use_tiling




       def 							UpperCAmelCase__			(  self			:   Optional[int]		):
         self.enable_tiling(A		)




       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         __snake_case:						List[str]			  =						True




       def 							UpperCAmelCase__			(  self			:   List[str]		):
         __snake_case:						List[str]			  =						False




       @property
       # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
       def 							UpperCAmelCase__			(  self			:   Tuple		):
         __snake_case:						Any			  =						{}

         def fn_recursive_add_processors(A			:   str							,    A			:   torch.nn.Module							,    A			:   Dict[str, AttentionProcessor]		):
           if hasattr(A							,    """set_processor"""		):
             __snake_case:						List[Any]			  =						module.processor

           for sub_name, child in module.named_children():
             fn_recursive_add_processors(f'''{name}.{sub_name}'''							,    A							,    A		)

           return processors

         for name, module in self.named_children():
           fn_recursive_add_processors(A							,    A							,    A		)

         return processors




       def 							UpperCAmelCase__			(  self			:   Optional[int]							,    A			:   Union[AttentionProcessor, Dict[str, AttentionProcessor]]		):
         __snake_case:						Any			  =						len(self.attn_processors.keys()		)

         if isinstance(A							,    A		) and len(A		) != count:
           raise ValueError(
               f'''A dict of processors was passed, but the number of processors {len(A		)} does not match the'''
               f''' number of attention layers: {count}. Please make sure to pass {count} processor classes.'''		)

         def fn_recursive_attn_processor(A			:   str							,    A			:   torch.nn.Module							,    A			:   Optional[Any]		):
           if hasattr(A							,    """set_processor"""		):
             if not isinstance(A							,    A		):
               module.set_processor(A		)
             else:
               module.set_processor(processor.pop(f'''{name}.processor'''		)		)

           for sub_name, child in module.named_children():
             fn_recursive_attn_processor(f'''{name}.{sub_name}'''							,    A							,    A		)

         for name, module in self.named_children():
           fn_recursive_attn_processor(A							,    A							,    A		)




       def 							UpperCAmelCase__			(  self			:   List[str]		):
         self.set_attn_processor(AttnProcessor()		)




       @apply_forward_hook
       def 							UpperCAmelCase__			(  self			:   Optional[Any]							,    A			:   torch.FloatTensor							,    A			:   bool = True		):
         if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
           return self.tiled_encode(A							,    return_dict=A		)

         if self.use_slicing and x.shape[0] > 1:
           __snake_case:						List[Any]			  =						[self.encoder(A		) for x_slice in x.split(1		)]
           __snake_case:						Optional[Any]			  =						torch.cat(A		)
         else:
           __snake_case:						str			  =						self.encoder(A		)

         __snake_case:						Any			  =						self.quant_conv(A		)
         __snake_case:						Tuple			  =						DiagonalGaussianDistribution(A		)

         if not return_dict:
           return (posterior,)

         return AutoencoderKLOutput(latent_dist=A		)




       def 							UpperCAmelCase__			(  self			:   Tuple							,    A			:   torch.FloatTensor							,    A			:   bool = True		):
         if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size):
           return self.tiled_decode(A							,    return_dict=A		)

         __snake_case:						Optional[int]			  =						self.post_quant_conv(A		)
         __snake_case:						Union[str, Any]			  =						self.decoder(A		)

         if not return_dict:
           return (dec,)

         return DecoderOutput(sample=A		)




       @apply_forward_hook
       def 							UpperCAmelCase__			(  self			:   Tuple							,    A			:   torch.FloatTensor							,    A			:   bool = True		):
         if self.use_slicing and z.shape[0] > 1:
           __snake_case:						Union[str, Any]			  =						[self._decode(A		).sample for z_slice in z.split(1		)]
           __snake_case:						List[str]			  =						torch.cat(A		)
         else:
           __snake_case:						int			  =						self._decode(A		).sample

         if not return_dict:
           return (decoded,)

         return DecoderOutput(sample=A		)




       def 							UpperCAmelCase__			(  self			:   Any							,    A			:   Tuple							,    A			:   int							,    A			:   List[Any]		):
         __snake_case:						int			  =						min(a.shape[2]							,    b.shape[2]							,    A		)
         for y in range(A		):
           __snake_case:						Dict			  =						a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
         return b




       def 							UpperCAmelCase__			(  self			:   Union[str, Any]							,    A			:   Optional[Any]							,    A			:   List[str]							,    A			:   List[str]		):
         __snake_case:						Dict			  =						min(a.shape[3]							,    b.shape[3]							,    A		)
         for x in range(A		):
           __snake_case:						Tuple			  =						a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
         return b




       def 							UpperCAmelCase__			(  self			:   int							,    A			:   torch.FloatTensor							,    A			:   bool = True		):
         __snake_case:						List[str]			  =						int(self.tile_sample_min_size * (1 - self.tile_overlap_factor)		)
         __snake_case:						Dict			  =						int(self.tile_latent_min_size * self.tile_overlap_factor		)
         __snake_case:						Dict			  =						self.tile_latent_min_size - blend_extent

         # Split the image into 512x512 tiles and encode them separately.
         __snake_case:						Optional[int]			  =						[]
         for i in range(0							,    x.shape[2]							,    A		):
           __snake_case:						Optional[int]			  =						[]
           for j in range(0							,    x.shape[3]							,    A		):
             __snake_case:						int			  =						x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
             __snake_case:						Tuple			  =						self.encoder(A		)
             __snake_case:						Dict			  =						self.quant_conv(A		)
             row.append(A		)
           rows.append(A		)
         __snake_case:						Tuple			  =						[]
         for i, row in enumerate(A		):
           __snake_case:						str			  =						[]
           for j, tile in enumerate(A		):
             # blend the above tile and the left tile
             # to the current tile and add the current tile to the result row
             if i > 0:
               __snake_case:						Optional[Any]			  =						self.blend_v(rows[i - 1][j]							,    A							,    A		)
             if j > 0:
               __snake_case:						Tuple			  =						self.blend_h(row[j - 1]							,    A							,    A		)
             result_row.append(tile[:, :, :row_limit, :row_limit]		)
           result_rows.append(torch.cat(A							,    dim=3		)		)

         __snake_case:						Tuple			  =						torch.cat(A							,    dim=2		)
         __snake_case:						Optional[int]			  =						DiagonalGaussianDistribution(A		)

         if not return_dict:
           return (posterior,)

         return AutoencoderKLOutput(latent_dist=A		)




       def 							UpperCAmelCase__			(  self			:   Union[str, Any]							,    A			:   torch.FloatTensor							,    A			:   bool = True		):
         __snake_case:						Optional[Any]			  =						int(self.tile_latent_min_size * (1 - self.tile_overlap_factor)		)
         __snake_case:						str			  =						int(self.tile_sample_min_size * self.tile_overlap_factor		)
         __snake_case:						int			  =						self.tile_sample_min_size - blend_extent

         # Split z into overlapping 64x64 tiles and decode them separately.
         # The tiles have an overlap to avoid seams between tiles.
         __snake_case:						List[Any]			  =						[]
         for i in range(0							,    z.shape[2]							,    A		):
           __snake_case:						Optional[Any]			  =						[]
           for j in range(0							,    z.shape[3]							,    A		):
             __snake_case:						Dict			  =						z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
             __snake_case:						Any			  =						self.post_quant_conv(A		)
             __snake_case:						Optional[Any]			  =						self.decoder(A		)
             row.append(A		)
           rows.append(A		)
         __snake_case:						Optional[Any]			  =						[]
         for i, row in enumerate(A		):
           __snake_case:						Optional[Any]			  =						[]
           for j, tile in enumerate(A		):
             # blend the above tile and the left tile
             # to the current tile and add the current tile to the result row
             if i > 0:
               __snake_case:						Tuple			  =						self.blend_v(rows[i - 1][j]							,    A							,    A		)
             if j > 0:
               __snake_case:						List[str]			  =						self.blend_h(row[j - 1]							,    A							,    A		)
             result_row.append(tile[:, :, :row_limit, :row_limit]		)
           result_rows.append(torch.cat(A							,    dim=3		)		)

         __snake_case:						Dict			  =						torch.cat(A							,    dim=2		)
         if not return_dict:
           return (dec,)

         return DecoderOutput(sample=A		)






       def 							UpperCAmelCase__			(  self			:   List[Any]							,    A			:   torch.FloatTensor							,    A			:   bool = False							,    A			:   bool = True							,    A			:   Optional[torch.Generator] = None							,    ):
         __snake_case:						Optional[Any]			  =						sample
         __snake_case:						Union[str, Any]			  =						self.encode(A		).latent_dist
         if sample_posterior:
           __snake_case:						Optional[Any]			  =						posterior.sample(generator=A		)
         else:
           __snake_case:						Dict			  =						posterior.mode()
         __snake_case:						Any			  =						self.decode(A		).sample

         if not return_dict:
           return (dec,)

         return DecoderOutput(sample=A		)






