import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModelWithProjection

from diffusers import (
    AutoencoderKL,
    DPMSolverMultistepScheduler,
    PNDMScheduler,
    StableDiffusionImageVariationPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class 							_SCREAMING_SNAKE_CASE(   snake_case__       ,      snake_case__       ,      snake_case__       ,      unittest.TestCase	):
   UpperCamelCase_				:						Optional[Any] 			=   StableDiffusionImageVariationPipeline
   UpperCamelCase_				:						Optional[Any] 			=   IMAGE_VARIATION_PARAMS
   UpperCamelCase_				:						List[Any] 			=   IMAGE_VARIATION_BATCH_PARAMS
   UpperCamelCase_				:						Dict 			=   frozenset([]	)
   # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
   UpperCamelCase_				:						int 			=   frozenset([]	)
   def _lowercase(    self    )	->int:
        torch.manual_seed(0    )
        a  :    Optional[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							,     )
        a  :    List[str]				=						PNDMScheduler(skip_prk_steps=lowerCAmelCase_    )
        torch.manual_seed(0    )
        a  :    int				=						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    )
        a  :    Dict				=						CLIPVisionConfig(
            hidden_size=32							,     projection_dim=32							,     intermediate_size=37							,     layer_norm_eps=1e-05							,     num_attention_heads=4							,     num_hidden_layers=5							,     image_size=32							,     patch_size=4							,     )
        a  :    Tuple				=						CLIPVisionModelWithProjection(lowerCAmelCase_    )
        a  :    int				=						CLIPImageProcessor(crop_size=32							,     size=32    )

        a  :    str				=						{
            '''unet''': unet,
            '''scheduler''': scheduler,
            '''vae''': vae,
            '''image_encoder''': image_encoder,
            '''feature_extractor''': feature_extractor,
            '''safety_checker''': None,
        }
        return components
   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_=0    )	->Any:
        a  :    List[str]				=						floats_tensor((1, 3, 32, 32)							,     rng=random.Random(lowerCAmelCase_    )    )
        a  :    List[Any]				=						image.cpu().permute(0							,     2							,     3							,     1    )[0]
        a  :    int				=						Image.fromarray(np.uinta(lowerCAmelCase_    )    ).convert('''RGB'''    ).resize((32, 32)    )
        if str(lowerCAmelCase_    ).startswith('''mps'''    ):
             a  :    Tuple				=						torch.manual_seed(lowerCAmelCase_    )
        else:
             a  :    Dict				=						torch.Generator(device=lowerCAmelCase_    ).manual_seed(lowerCAmelCase_    )
        a  :    List[Any]				=						{
            '''image''': image,
            '''generator''': generator,
            '''num_inference_steps''': 2,
            '''guidance_scale''': 6.0,
            '''output_type''': '''numpy''',
        }
        return inputs
   def _lowercase(    self    )	->Tuple:
        a  :    int				=						'''cpu'''  # ensure determinism for the device-dependent torch.Generator
        a  :    Any				=						self.get_dummy_components()
        a  :    str				=						StableDiffusionImageVariationPipeline(**lowerCAmelCase_    )
        a  :    List[str]				=						sd_pipe.to(lowerCAmelCase_    )
        sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_    )

        a  :    Optional[int]				=						self.get_dummy_inputs(lowerCAmelCase_    )
        a  :    Optional[Any]				=						sd_pipe(**lowerCAmelCase_    ).images
        a  :    List[str]				=						image[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        a  :    Any				=						np.array([0.52_39, 0.57_23, 0.47_96, 0.50_49, 0.55_50, 0.46_85, 0.53_29, 0.48_91, 0.49_21]    )

        assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-3
   def _lowercase(    self    )	->Dict:
        a  :    List[str]				=						'''cpu'''  # ensure determinism for the device-dependent torch.Generator
        a  :    str				=						self.get_dummy_components()
        a  :    List[str]				=						StableDiffusionImageVariationPipeline(**lowerCAmelCase_    )
        a  :    Any				=						sd_pipe.to(lowerCAmelCase_    )
        sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_    )

        a  :    Any				=						self.get_dummy_inputs(lowerCAmelCase_    )
        a  :    Optional[Any]				=						2 * [inputs['''image''']]
        a  :    str				=						sd_pipe(**lowerCAmelCase_    )

        a  :    Any				=						output.images

        a  :    Optional[Any]				=						image[-1, -3:, -3:, -1]

        assert image.shape == (2, 64, 64, 3)
        a  :    Dict				=						np.array([0.68_92, 0.56_37, 0.58_36, 0.57_71, 0.62_54, 0.64_09, 0.55_80, 0.55_69, 0.52_89]    )

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


   def _lowercase(    self    )	->int:
        super().test_inference_batch_single_identical(expected_max_diff=3e-3    )






@slow
@require_torch_gpu
class 							_SCREAMING_SNAKE_CASE(   unittest.TestCase	):
   def _lowercase(    self    )	->Any:
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()
   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_="cpu"							,     lowerCAmelCase_=torch.floataa							,     lowerCAmelCase_=0    )	->Any:
        a  :    List[str]				=						torch.Generator(device=lowerCAmelCase_    ).manual_seed(lowerCAmelCase_    )
        a  :    int				=						load_image(
            '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'''
            '''/stable_diffusion_imgvar/input_image_vermeer.png'''    )
        a  :    List[Any]				=						np.random.RandomState(lowerCAmelCase_    ).standard_normal((1, 4, 64, 64)    )
        a  :    Dict				=						torch.from_numpy(lowerCAmelCase_    ).to(device=lowerCAmelCase_							,     dtype=lowerCAmelCase_    )
        a  :    List[Any]				=						{
            '''image''': init_image,
            '''latents''': latents,
            '''generator''': generator,
            '''num_inference_steps''': 3,
            '''guidance_scale''': 7.5,
            '''output_type''': '''numpy''',
        }
        return inputs
   def _lowercase(    self    )	->Tuple:
        a  :    Tuple				=						StableDiffusionImageVariationPipeline.from_pretrained(
            '''lambdalabs/sd-image-variations-diffusers'''							,     safety_checker=lowerCAmelCase_    )
        a  :    Union[str, Any]				=						sd_pipe.to(lowerCAmelCase_    )
        sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_    )

        a  :    int				=						self.get_inputs(lowerCAmelCase_    )
        a  :    str				=						sd_pipe(**lowerCAmelCase_    ).images
        a  :    List[Any]				=						image[0, -3:, -3:, -1].flatten()

        assert image.shape == (1, 5_12, 5_12, 3)
        a  :    Any				=						np.array([0.8_44_91, 0.9_07_89, 0.7_57_08, 0.7_87_34, 0.8_34_85, 0.7_00_99, 0.6_69_38, 0.6_87_27, 0.6_13_79]    )
        assert np.abs(image_slice - expected_slice    ).max() < 6e-3
   def _lowercase(    self    )	->Tuple:
        a  :    Any				=						0

        def callback_fn(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    ) -> None:
             a  :    str				=						True
             nonlocal number_of_steps
             number_of_steps += 1
             if step == 1:
                  a  :    Any				=						latents.detach().cpu().numpy()
                  assert latents.shape == (1, 4, 64, 64)
                  a  :    List[str]				=						latents[0, -3:, -3:, -1]
                  a  :    Optional[Any]				=						np.array(
                      [-0.16_21, 0.28_37, -0.79_79, -0.12_21, -1.30_57, 0.76_81, -2.11_91, 0.04_64, 1.63_09]    )

                  assert np.abs(latents_slice.flatten() - expected_slice    ).max() < 5e-2
             elif step == 2:
                  a  :    Tuple				=						latents.detach().cpu().numpy()
                  assert latents.shape == (1, 4, 64, 64)
                  a  :    Optional[Any]				=						latents[0, -3:, -3:, -1]
                  a  :    Union[str, Any]				=						np.array([0.62_99, 1.75_00, 1.19_92, -2.15_82, -1.89_94, 0.73_34, -0.70_90, 1.01_37, 1.52_73]    )

                  assert np.abs(latents_slice.flatten() - expected_slice    ).max() < 5e-2

        a  :    Optional[int]				=						False

        a  :    int				=						StableDiffusionImageVariationPipeline.from_pretrained(
            '''fusing/sd-image-variations-diffusers'''							,     safety_checker=lowerCAmelCase_							,     torch_dtype=torch.floataa							,     )
        pipe.to(lowerCAmelCase_    )
        pipe.set_progress_bar_config(disable=lowerCAmelCase_    )
        pipe.enable_attention_slicing()

        a  :    Optional[int]				=						self.get_inputs(lowerCAmelCase_							,     dtype=torch.floataa    )
        pipe(**lowerCAmelCase_							,     callback=lowerCAmelCase_							,     callback_steps=1    )
        assert callback_fn.has_been_called
        assert number_of_steps == inputs["num_inference_steps"]


   def _lowercase(    self    )	->Union[str, Any]:
        torch.cuda.empty_cache()
        torch.cuda.reset_max_memory_allocated()
        torch.cuda.reset_peak_memory_stats()

        a  :    Union[str, Any]				=						'''fusing/sd-image-variations-diffusers'''
        a  :    List[str]				=						StableDiffusionImageVariationPipeline.from_pretrained(
            lowerCAmelCase_							,     safety_checker=lowerCAmelCase_							,     torch_dtype=torch.floataa    )
        a  :    Any				=						pipe.to(lowerCAmelCase_    )
        pipe.set_progress_bar_config(disable=lowerCAmelCase_    )
        pipe.enable_attention_slicing(1    )
        pipe.enable_sequential_cpu_offload()

        a  :    Tuple				=						self.get_inputs(lowerCAmelCase_							,     dtype=torch.floataa    )
        a  :    List[Any]				=						pipe(**lowerCAmelCase_    )

        a  :    Optional[Any]				=						torch.cuda.max_memory_allocated()
        # make sure that less than 2.6 GB is allocated
        assert mem_bytes < 2.6 * 10**9






@nightly
@require_torch_gpu
class 							_SCREAMING_SNAKE_CASE(   unittest.TestCase	):
   def _lowercase(    self    )	->List[Any]:
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()
   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_="cpu"							,     lowerCAmelCase_=torch.floataa							,     lowerCAmelCase_=0    )	->List[str]:
        a  :    List[Any]				=						torch.Generator(device=lowerCAmelCase_    ).manual_seed(lowerCAmelCase_    )
        a  :    Optional[Any]				=						load_image(
            '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'''
            '''/stable_diffusion_imgvar/input_image_vermeer.png'''    )
        a  :    Optional[Any]				=						np.random.RandomState(lowerCAmelCase_    ).standard_normal((1, 4, 64, 64)    )
        a  :    str				=						torch.from_numpy(lowerCAmelCase_    ).to(device=lowerCAmelCase_							,     dtype=lowerCAmelCase_    )
        a  :    Union[str, Any]				=						{
            '''image''': init_image,
            '''latents''': latents,
            '''generator''': generator,
            '''num_inference_steps''': 50,
            '''guidance_scale''': 7.5,
            '''output_type''': '''numpy''',
        }
        return inputs
   def _lowercase(    self    )	->Union[str, Any]:
        a  :    int				=						StableDiffusionImageVariationPipeline.from_pretrained('''fusing/sd-image-variations-diffusers'''    )
        sd_pipe.to(lowerCAmelCase_    )
        sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_    )

        a  :    Dict				=						self.get_inputs(lowerCAmelCase_    )
        a  :    Any				=						sd_pipe(**lowerCAmelCase_    ).images[0]

        a  :    Tuple				=						load_numpy(
            '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'''
            '''/stable_diffusion_imgvar/lambdalabs_variations_pndm.npy'''    )
        a  :    List[Any]				=						np.abs(expected_image - image    ).max()
        assert max_diff < 1e-3


   def _lowercase(    self    )	->List[str]:
        a  :    Tuple				=						StableDiffusionImageVariationPipeline.from_pretrained('''fusing/sd-image-variations-diffusers'''    )
        a  :    str				=						DPMSolverMultistepScheduler.from_config(sd_pipe.scheduler.config    )
        sd_pipe.to(lowerCAmelCase_    )
        sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_    )

        a  :    List[str]				=						self.get_inputs(lowerCAmelCase_    )
        a  :    str				=						25
        a  :    Optional[Any]				=						sd_pipe(**lowerCAmelCase_    ).images[0]

        a  :    Dict				=						load_numpy(
            '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'''
            '''/stable_diffusion_imgvar/lambdalabs_variations_dpm_multi.npy'''    )
        a  :    int				=						np.abs(expected_image - image    ).max()
        assert max_diff < 1e-3
from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block






@dataclass
class 							_SCREAMING_SNAKE_CASE(   snake_case__	):
   UpperCamelCase_				:						torch.FloatTensor






class 							_SCREAMING_SNAKE_CASE(   snake_case__       ,      snake_case__	):
   @register_to_config
   def __init__(    self							,     lowerCAmelCase_ = None							,     lowerCAmelCase_ = 3							,     lowerCAmelCase_ = 3							,     lowerCAmelCase_ = False							,     lowerCAmelCase_ = "positional"							,     lowerCAmelCase_ = 0							,     lowerCAmelCase_ = True							,     lowerCAmelCase_ = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")							,     lowerCAmelCase_ = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")							,     lowerCAmelCase_ = (2_24, 4_48, 6_72, 8_96)							,     lowerCAmelCase_ = 2							,     lowerCAmelCase_ = 1							,     lowerCAmelCase_ = 1							,     lowerCAmelCase_ = "conv"							,     lowerCAmelCase_ = "conv"							,     lowerCAmelCase_ = "silu"							,     lowerCAmelCase_ = 8							,     lowerCAmelCase_ = 32							,     lowerCAmelCase_ = 1e-5							,     lowerCAmelCase_ = "default"							,     lowerCAmelCase_ = True							,     lowerCAmelCase_ = None							,     lowerCAmelCase_ = None							,     )	->Tuple:
        super().__init__()

        a  :    List[Any]				=						sample_size
        a  :    List[Any]				=						block_out_channels[0] * 4

        # Check inputs
        if len(lowerCAmelCase_    ) != len(lowerCAmelCase_    ):
             raise ValueError(
                 F"""Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."""    )

        if len(lowerCAmelCase_    ) != len(lowerCAmelCase_    ):
             raise ValueError(
                 F"""Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."""    )

        # input
        a  :    List[Any]				=						nn.Convad(lowerCAmelCase_							,     block_out_channels[0]							,     kernel_size=3							,     padding=(1, 1)    )

        # time
        if time_embedding_type == "fourier":
             a  :    List[Any]				=						GaussianFourierProjection(embedding_size=block_out_channels[0]							,     scale=16    )
             a  :    List[Any]				=						2 * block_out_channels[0]
        elif time_embedding_type == "positional":
             a  :    Dict				=						Timesteps(block_out_channels[0]							,     lowerCAmelCase_							,     lowerCAmelCase_    )
             a  :    List[str]				=						block_out_channels[0]

        a  :    List[str]				=						TimestepEmbedding(lowerCAmelCase_							,     lowerCAmelCase_    )

        # class embedding
        if class_embed_type is None and num_class_embeds is not None:
             a  :    Dict				=						nn.Embedding(lowerCAmelCase_							,     lowerCAmelCase_    )
        elif class_embed_type == "timestep":
             a  :    str				=						TimestepEmbedding(lowerCAmelCase_							,     lowerCAmelCase_    )
        elif class_embed_type == "identity":
             a  :    List[str]				=						nn.Identity(lowerCAmelCase_							,     lowerCAmelCase_    )
        else:
             a  :    Optional[Any]				=						None

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

        # down
        a  :    List[Any]				=						block_out_channels[0]
        for i, down_block_type in enumerate(lowerCAmelCase_    ):
             a  :    Dict				=						output_channel
             a  :    Union[str, Any]				=						block_out_channels[i]
             a  :    int				=						i == len(lowerCAmelCase_    ) - 1

             a  :    Tuple				=						get_down_block(
                 lowerCAmelCase_							,     num_layers=lowerCAmelCase_							,     in_channels=lowerCAmelCase_							,     out_channels=lowerCAmelCase_							,     temb_channels=lowerCAmelCase_							,     add_downsample=not is_final_block							,     resnet_eps=lowerCAmelCase_							,     resnet_act_fn=lowerCAmelCase_							,     resnet_groups=lowerCAmelCase_							,     attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel							,     downsample_padding=lowerCAmelCase_							,     resnet_time_scale_shift=lowerCAmelCase_							,     downsample_type=lowerCAmelCase_							,     )
             self.down_blocks.append(lowerCAmelCase_    )

        # mid
        a  :    int				=						UNetMidBlockaD(
            in_channels=block_out_channels[-1]							,     temb_channels=lowerCAmelCase_							,     resnet_eps=lowerCAmelCase_							,     resnet_act_fn=lowerCAmelCase_							,     output_scale_factor=lowerCAmelCase_							,     resnet_time_scale_shift=lowerCAmelCase_							,     attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1]							,     resnet_groups=lowerCAmelCase_							,     add_attention=lowerCAmelCase_							,     )

        # up
        a  :    Optional[int]				=						list(reversed(lowerCAmelCase_    )    )
        a  :    Tuple				=						reversed_block_out_channels[0]
        for i, up_block_type in enumerate(lowerCAmelCase_    ):
             a  :    List[Any]				=						output_channel
             a  :    Optional[Any]				=						reversed_block_out_channels[i]
             a  :    Dict				=						reversed_block_out_channels[min(i + 1							,     len(lowerCAmelCase_    ) - 1    )]

             a  :    Any				=						i == len(lowerCAmelCase_    ) - 1

             a  :    List[Any]				=						get_up_block(
                 lowerCAmelCase_							,     num_layers=layers_per_block + 1							,     in_channels=lowerCAmelCase_							,     out_channels=lowerCAmelCase_							,     prev_output_channel=lowerCAmelCase_							,     temb_channels=lowerCAmelCase_							,     add_upsample=not is_final_block							,     resnet_eps=lowerCAmelCase_							,     resnet_act_fn=lowerCAmelCase_							,     resnet_groups=lowerCAmelCase_							,     attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel							,     resnet_time_scale_shift=lowerCAmelCase_							,     upsample_type=lowerCAmelCase_							,     )
             self.up_blocks.append(lowerCAmelCase_    )
             a  :    Any				=						output_channel

        # out
        a  :    str				=						norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4							,     32    )
        a  :    Tuple				=						nn.GroupNorm(num_channels=block_out_channels[0]							,     num_groups=lowerCAmelCase_							,     eps=lowerCAmelCase_    )
        a  :    Any				=						nn.SiLU()
        a  :    List[Any]				=						nn.Convad(block_out_channels[0]							,     lowerCAmelCase_							,     kernel_size=3							,     padding=1    )


   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_ = None							,     lowerCAmelCase_ = True							,     )	->Union[UNetaDOutput, Tuple]:
        # 0. center input if necessary
        if self.config.center_input_sample:
             a  :    Any				=						2 * sample - 1.0

        # 1. time
        a  :    Optional[Any]				=						timestep
        if not torch.is_tensor(lowerCAmelCase_    ):
             a  :    Dict				=						torch.tensor([timesteps]							,     dtype=torch.long							,     device=sample.device    )
        elif torch.is_tensor(lowerCAmelCase_    ) and len(timesteps.shape    ) == 0:
             a  :    Any				=						timesteps[None].to(sample.device    )

        # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
        a  :    Optional[Any]				=						timesteps * torch.ones(sample.shape[0]							,     dtype=timesteps.dtype							,     device=timesteps.device    )

        a  :    Dict				=						self.time_proj(lowerCAmelCase_    )

        # timesteps does not contain any weights and will always return f32 tensors
        # but time_embedding might actually be running in fp16. so we need to cast here.
        # there might be better ways to encapsulate this.
        a  :    Optional[Any]				=						t_emb.to(dtype=self.dtype    )
        a  :    Dict				=						self.time_embedding(lowerCAmelCase_    )

        if self.class_embedding is not None:
             if class_labels is None:
                  raise ValueError('''class_labels should be provided when doing class conditioning'''    )

             if self.config.class_embed_type == "timestep":
                  a  :    List[str]				=						self.time_proj(lowerCAmelCase_    )

             a  :    Any				=						self.class_embedding(lowerCAmelCase_    ).to(dtype=self.dtype    )
             a  :    Optional[int]				=						emb + class_emb

        # 2. pre-process
        a  :    int				=						sample
        a  :    Dict				=						self.conv_in(lowerCAmelCase_    )

        # 3. down
        a  :    Union[str, Any]				=						(sample,)
        for downsample_block in self.down_blocks:
             if hasattr(lowerCAmelCase_							,     '''skip_conv'''    ):
                  a			,							a			,							a  :    str				=						downsample_block(
                      hidden_states=lowerCAmelCase_							,     temb=lowerCAmelCase_							,     skip_sample=lowerCAmelCase_    )
             else:
                  a			,							a  :    List[str]				=						downsample_block(hidden_states=lowerCAmelCase_							,     temb=lowerCAmelCase_    )

             down_block_res_samples += res_samples

        # 4. mid
        a  :    str				=						self.mid_block(lowerCAmelCase_							,     lowerCAmelCase_    )

        # 5. up
        a  :    int				=						None
        for upsample_block in self.up_blocks:
             a  :    List[str]				=						down_block_res_samples[-len(upsample_block.resnets    ) :]
             a  :    Any				=						down_block_res_samples[: -len(upsample_block.resnets    )]

             if hasattr(lowerCAmelCase_							,     '''skip_conv'''    ):
                  a			,							a  :    Any				=						upsample_block(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )
             else:
                  a  :    Union[str, Any]				=						upsample_block(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )

        # 6. post-process
        a  :    Tuple				=						self.conv_norm_out(lowerCAmelCase_    )
        a  :    Optional[Any]				=						self.conv_act(lowerCAmelCase_    )
        a  :    Tuple				=						self.conv_out(lowerCAmelCase_    )

        if skip_sample is not None:
             sample += skip_sample

        if self.config.time_embedding_type == "fourier":
             a  :    Optional[Any]				=						timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]    )))    )
             a  :    int				=						sample / timesteps

        if not return_dict:
             return (sample,)

        return UNetaDOutput(sample=lowerCAmelCase_    )