import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput






def 				__lowerCamelCase		(						lowerCAmelCase__     ,  lowerCAmelCase__=0.9_9_9     ,  lowerCAmelCase__="cosine"     ,  ):
       if alpha_transform_type == "cosine":

              def alpha_bar_fn(lowerCAmelCase__     ):
                     return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2     ) ** 2

       elif alpha_transform_type == "exp":

              def alpha_bar_fn(lowerCAmelCase__     ):
                     return math.exp(t * -1_2.0     )

       else:
              raise ValueError(F"""Unsupported alpha_tranform_type: {alpha_transform_type}"""     )

       lowerCAmelCase__					     = []
       for i in range(A_     ):
              lowerCAmelCase__					     = i / num_diffusion_timesteps
              lowerCAmelCase__					     = (i + 1) / num_diffusion_timesteps
              betas.append(min(1 - alpha_bar_fn(A_     ) / alpha_bar_fn(A_     )     ,  A_     )     )
       return torch.tensor(A_     ,  dtype=torch.floataa     )



class     a_			(						a_	,					a_						):






 '''simple docstring'''






 UpperCAmelCase_     			= [e.name for e in KarrasDiffusionSchedulers]
 UpperCAmelCase_     			= 2




 @register_to_config
 def __init__(      self :  Optional[int]      ,   lowercase__ :  int = 1_000      ,   lowercase__ :  float = 0.00_085      ,   lowercase__ :  float = 0.012      ,   lowercase__ :  str = "linear"      ,   lowercase__ :  Optional[Union[np.ndarray, List[float]]] = None      ,   lowercase__ :  str = "epsilon"      ,   lowercase__ :  Optional[bool] = False      ,   lowercase__ :  Optional[bool] = False      ,   lowercase__ :  float = 1.0      ,   lowercase__ :  str = "linspace"      ,   lowercase__ :  int = 0      ,   ):







        '''simple docstring'''



        if trained_betas is not None:
               lowerCAmelCase__					     = torch.tensor(lowercase_      ,   dtype=torch.floataa)
        elif beta_schedule == "linear":
               lowerCAmelCase__					     = torch.linspace(lowercase_      ,   lowercase_      ,   lowercase_      ,   dtype=torch.floataa)
        elif beta_schedule == "scaled_linear":
               # this schedule is very specific to the latent diffusion model.
               lowerCAmelCase__					     = (
                   torch.linspace(beta_start**0.5      ,   beta_end**0.5      ,   lowercase_      ,   dtype=torch.floataa) ** 2
               )
        elif beta_schedule == "squaredcos_cap_v2":
               # Glide cosine schedule
               lowerCAmelCase__					     = betas_for_alpha_bar(lowercase_      ,   alpha_transform_type='cosine')
        elif beta_schedule == "exp":
               lowerCAmelCase__					     = betas_for_alpha_bar(lowercase_      ,   alpha_transform_type='exp')
        else:
               raise NotImplementedError(F"""{beta_schedule} does is not implemented for {self.__class__}""")

        lowerCAmelCase__					     = 1.0 - self.betas
        lowerCAmelCase__					     = torch.cumprod(self.alphas      ,   dim=0)

        #  set all values
        self.set_timesteps(lowercase_      ,   lowercase_      ,   lowercase_)
        lowerCAmelCase__					     = use_karras_sigmas




 def 		__snake_case						(      self :  Optional[int]      ,   lowercase__ :  Union[str, Any]      ,   lowercase__ :  Dict=None):







        '''simple docstring'''



        if schedule_timesteps is None:
               lowerCAmelCase__					     = self.timesteps

        lowerCAmelCase__					     = (schedule_timesteps == timestep).nonzero()

        # The sigma index that is taken for the **very** first `step`
        # is always the second index (or the last index if there is only 1)
        # This way we can ensure we don't accidentally skip a sigma in
        # case we start in the middle of the denoising schedule (e.g. for image-to-image)
        if len(self._index_counter) == 0:
               lowerCAmelCase__					     = 1 if len(lowercase_) > 1 else 0
        else:
               lowerCAmelCase__					     = timestep.cpu().item() if torch.is_tensor(lowercase_) else timestep
               lowerCAmelCase__					     = self._index_counter[timestep_int]

        return indices[pos].item()




 @property
 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        if self.config.timestep_spacing in ["linspace", "trailing"]:
               return self.sigmas.max()

        return (self.sigmas.max() ** 2 + 1) ** 0.5




 def 		__snake_case						(      self :  str      ,   lowercase__ :  torch.FloatTensor      ,   lowercase__ :  Union[float, torch.FloatTensor]      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = self.index_for_timestep(lowercase_)

        lowerCAmelCase__					     = self.sigmas[step_index]
        lowerCAmelCase__					     = sample / ((sigma**2 + 1) ** 0.5)
        return sample




 def 		__snake_case						(      self :  int      ,   lowercase__ :  int      ,   lowercase__ :  Union[str, torch.device] = None      ,   lowercase__ :  Optional[int] = None      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = num_inference_steps

        lowerCAmelCase__					     = num_train_timesteps or self.config.num_train_timesteps

        # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
        if self.config.timestep_spacing == "linspace":
               lowerCAmelCase__					     = np.linspace(0      ,   num_train_timesteps - 1      ,   lowercase_      ,   dtype=lowercase_)[::-1].copy()
        elif self.config.timestep_spacing == "leading":
               lowerCAmelCase__					     = num_train_timesteps // self.num_inference_steps
               # creates integer timesteps by multiplying by ratio
               # casting to int to avoid issues when num_inference_step is power of 3
               lowerCAmelCase__					     = (np.arange(0      ,   lowercase_) * step_ratio).round()[::-1].copy().astype(lowercase_)
               timesteps += self.config.steps_offset
        elif self.config.timestep_spacing == "trailing":
               lowerCAmelCase__					     = num_train_timesteps / self.num_inference_steps
               # creates integer timesteps by multiplying by ratio
               # casting to int to avoid issues when num_inference_step is power of 3
               lowerCAmelCase__					     = (np.arange(lowercase_      ,   0      ,   -step_ratio)).round().copy().astype(lowercase_)
               timesteps -= 1
        else:
               raise ValueError(
                   F"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.""")

        lowerCAmelCase__					     = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
        lowerCAmelCase__					     = np.log(lowercase_)
        lowerCAmelCase__					     = np.interp(lowercase_      ,   np.arange(0      ,   len(lowercase_))      ,   lowercase_)

        if self.config.use_karras_sigmas:
               lowerCAmelCase__					     = self._convert_to_karras(in_sigmas=lowercase_      ,   num_inference_steps=self.num_inference_steps)
               lowerCAmelCase__					     = np.array([self._sigma_to_t(lowercase_      ,   lowercase_) for sigma in sigmas])

        lowerCAmelCase__					     = np.concatenate([sigmas, [0.0]]).astype(np.floataa)
        lowerCAmelCase__					     = torch.from_numpy(lowercase_).to(device=lowercase_)
        lowerCAmelCase__					     = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2), sigmas[-1:]])

        lowerCAmelCase__					     = torch.from_numpy(lowercase_)
        lowerCAmelCase__					     = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2)])

        if str(lowercase_).startswith('mps'):
               # mps does not support float64
               lowerCAmelCase__					     = timesteps.to(lowercase_      ,   dtype=torch.floataa)
        else:
               lowerCAmelCase__					     = timesteps.to(device=lowercase_)

        # empty dt and derivative
        lowerCAmelCase__					     = None
        lowerCAmelCase__					     = None

        # for exp beta schedules, such as the one for `pipeline_shap_e.py`
        # we need an index counter
        lowerCAmelCase__					     = defaultdict(lowercase_)




 def 		__snake_case						(      self :  Any      ,   lowercase__ :  Dict      ,   lowercase__ :  Optional[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = np.log(lowercase_)

        # get distribution
        lowerCAmelCase__					     = log_sigma - log_sigmas[:, np.newaxis]

        # get sigmas range
        lowerCAmelCase__					     = np.cumsum((dists >= 0)      ,   axis=0).argmax(axis=0).clip(max=log_sigmas.shape[0] - 2)
        lowerCAmelCase__					     = low_idx + 1

        lowerCAmelCase__					     = log_sigmas[low_idx]
        lowerCAmelCase__					     = log_sigmas[high_idx]

        # interpolate sigmas
        lowerCAmelCase__					     = (low - log_sigma) / (low - high)
        lowerCAmelCase__					     = np.clip(lowercase_      ,   0      ,   1)

        # transform interpolation to time range
        lowerCAmelCase__					     = (1 - w) * low_idx + w * high_idx
        lowerCAmelCase__					     = t.reshape(sigma.shape)
        return t




 def 		__snake_case						(      self :  Optional[int]      ,   lowercase__ :  torch.FloatTensor      ,   lowercase__ :  Union[str, Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = in_sigmas[-1].item()
        lowerCAmelCase__					     = in_sigmas[0].item()

        lowerCAmelCase__					     = 7.0  # 7.0 is the value used in the paper
        lowerCAmelCase__					     = np.linspace(0      ,   1      ,   lowercase_)
        lowerCAmelCase__					     = sigma_min ** (1 / rho)
        lowerCAmelCase__					     = sigma_max ** (1 / rho)
        lowerCAmelCase__					     = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
        return sigmas




 @property
 def 		__snake_case						(      self :  Tuple):







        '''simple docstring'''



        return self.dt is None




 def 		__snake_case						(      self :  str      ,   lowercase__ :  Union[torch.FloatTensor, np.ndarray]      ,   lowercase__ :  Union[float, torch.FloatTensor]      ,   lowercase__ :  Union[torch.FloatTensor, np.ndarray]      ,   lowercase__ :  bool = True      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = self.index_for_timestep(lowercase_)

        # advance index counter by 1
        lowerCAmelCase__					     = timestep.cpu().item() if torch.is_tensor(lowercase_) else timestep
        self._index_counter[timestep_int] += 1

        if self.state_in_first_order:
               lowerCAmelCase__					     = self.sigmas[step_index]
               lowerCAmelCase__					     = self.sigmas[step_index + 1]
        else:
               # 2nd order / Heun's method
               lowerCAmelCase__					     = self.sigmas[step_index - 1]
               lowerCAmelCase__					     = self.sigmas[step_index]

        # currently only gamma=0 is supported. This usually works best anyways.
        # We can support gamma in the future but then need to scale the timestep before
        # passing it to the model which requires a change in API
        lowerCAmelCase__					     = 0
        lowerCAmelCase__					     = sigma * (gamma + 1)  # Note: sigma_hat == sigma for now

        # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
        if self.config.prediction_type == "epsilon":
               lowerCAmelCase__					     = sigma_hat if self.state_in_first_order else sigma_next
               lowerCAmelCase__					     = sample - sigma_input * model_output
        elif self.config.prediction_type == "v_prediction":
               lowerCAmelCase__					     = sigma_hat if self.state_in_first_order else sigma_next
               lowerCAmelCase__					     = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
                   sample / (sigma_input**2 + 1)
               )
        elif self.config.prediction_type == "sample":
               lowerCAmelCase__					     = model_output
        else:
               raise ValueError(
                   F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""")

        if self.config.clip_sample:
               lowerCAmelCase__					     = pred_original_sample.clamp(
                   -self.config.clip_sample_range      ,   self.config.clip_sample_range)

        if self.state_in_first_order:
               # 2. Convert to an ODE derivative for 1st order
               lowerCAmelCase__					     = (sample - pred_original_sample) / sigma_hat
               # 3. delta timestep
               lowerCAmelCase__					     = sigma_next - sigma_hat

               # store for 2nd order step
               lowerCAmelCase__					     = derivative
               lowerCAmelCase__					     = dt
               lowerCAmelCase__					     = sample
        else:
               # 2. 2nd order / Heun's method
               lowerCAmelCase__					     = (sample - pred_original_sample) / sigma_next
               lowerCAmelCase__					     = (self.prev_derivative + derivative) / 2

               # 3. take prev timestep & sample
               lowerCAmelCase__					     = self.dt
               lowerCAmelCase__					     = self.sample

               # free dt and derivative
               # Note, this puts the scheduler in "first order mode"
               lowerCAmelCase__					     = None
               lowerCAmelCase__					     = None
               lowerCAmelCase__					     = None

        lowerCAmelCase__					     = sample + derivative * dt

        if not return_dict:
               return (prev_sample,)

        return SchedulerOutput(prev_sample=lowercase_)




 def 		__snake_case						(      self :  List[Any]      ,   lowercase__ :  torch.FloatTensor      ,   lowercase__ :  torch.FloatTensor      ,   lowercase__ :  torch.FloatTensor      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = self.sigmas.to(device=original_samples.device      ,   dtype=original_samples.dtype)
        if original_samples.device.type == "mps" and torch.is_floating_point(lowercase_):
               # mps does not support float64
               lowerCAmelCase__					     = self.timesteps.to(original_samples.device      ,   dtype=torch.floataa)
               lowerCAmelCase__					     = timesteps.to(original_samples.device      ,   dtype=torch.floataa)
        else:
               lowerCAmelCase__					     = self.timesteps.to(original_samples.device)
               lowerCAmelCase__					     = timesteps.to(original_samples.device)

        lowerCAmelCase__					     = [self.index_for_timestep(lowercase_      ,   lowercase_) for t in timesteps]

        lowerCAmelCase__					     = sigmas[step_indices].flatten()
        while len(sigma.shape) < len(original_samples.shape):
               lowerCAmelCase__					     = sigma.unsqueeze(-1)

        lowerCAmelCase__					     = original_samples + noise * sigma
        return noisy_samples




 def __len__(      self :  Dict):







        '''simple docstring'''



        return self.config.num_train_timesteps

from typing import Optional, Tuple, Union

import flax
import flax.linen as nn
import jax
import jax.numpy as jnp
from flax.core.frozen_dict import FrozenDict

from ..configuration_utils import ConfigMixin, flax_register_to_config
from ..utils import BaseOutput
from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps
from .modeling_flax_utils import FlaxModelMixin
from .unet_ad_blocks_flax import (
    FlaxCrossAttnDownBlockaD,
    FlaxCrossAttnUpBlockaD,
    FlaxDownBlockaD,
    FlaxUNetMidBlockaDCrossAttn,
    FlaxUpBlockaD,
)
@flax.struct.dataclass
class     a_			(						SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






 UpperCAmelCase_     			= 42






@flax_register_to_config
class     a_			(						nn.Module	,					SCREAMING_SNAKE_CASE	,					SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






 UpperCAmelCase_     			= 32
 UpperCAmelCase_     			= 4
 UpperCAmelCase_     			= 4
 UpperCAmelCase_     			= (
     "CrossAttnDownBlock2D",
     "CrossAttnDownBlock2D",
     "CrossAttnDownBlock2D",
     "DownBlock2D",
 )
 UpperCAmelCase_     			= ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= (320, 640, 1_280, 1_280)
 UpperCAmelCase_     			= 2
 UpperCAmelCase_     			= 8
 UpperCAmelCase_     			= None
 UpperCAmelCase_     			= 1_280
 UpperCAmelCase_     			= 0.0
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= jnp.floataa
 UpperCAmelCase_     			= True
 UpperCAmelCase_     			= 0
 UpperCAmelCase_     			= False




 def 		__snake_case						(      self :  Optional[int]      ,   lowercase__ :  jax.random.KeyArray):







        '''simple docstring'''



        lowerCAmelCase__					     = (1, self.in_channels, self.sample_size, self.sample_size)
        lowerCAmelCase__					     = jnp.zeros(lowercase__      ,   dtype=jnp.floataa)
        lowerCAmelCase__					     = jnp.ones((1,)      ,   dtype=jnp.intaa)
        lowerCAmelCase__					     = jnp.zeros((1, 1, self.cross_attention_dim)      ,   dtype=jnp.floataa)

        lowerCAmelCase__     , lowerCAmelCase__					     = jax.random.split(lowercase__)
        lowerCAmelCase__					     = {'params': params_rng, 'dropout': dropout_rng}

        return self.init(lowercase__      ,   lowercase__      ,   lowercase__      ,   lowercase__)["params"]




 def 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.block_out_channels
        lowerCAmelCase__					     = block_out_channels[0] * 4

        if self.num_attention_heads is not None:
               raise ValueError(
                   'At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.')

        # If `num_attention_heads` is not defined (which is the case for most models)
        # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
        # The reason for this behavior is to correct for incorrectly named variables that were introduced
        # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
        # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
        # which is why we correct for the naming here.
        lowerCAmelCase__					     = self.num_attention_heads or self.attention_head_dim

        # input
        lowerCAmelCase__					     = nn.Conv(
            block_out_channels[0]      ,   kernel_size=(3, 3)      ,   strides=(1, 1)      ,   padding=((1, 1), (1, 1))      ,   dtype=self.dtype      ,   )

        # time
        lowerCAmelCase__					     = FlaxTimesteps(
            block_out_channels[0]      ,   flip_sin_to_cos=self.flip_sin_to_cos      ,   freq_shift=self.config.freq_shift)
        lowerCAmelCase__					     = FlaxTimestepEmbedding(lowercase__      ,   dtype=self.dtype)

        lowerCAmelCase__					     = self.only_cross_attention
        if isinstance(lowercase__      ,   lowercase__):
               lowerCAmelCase__					     = (only_cross_attention,) * len(self.down_block_types)

        if isinstance(lowercase__      ,   lowercase__):
               lowerCAmelCase__					     = (num_attention_heads,) * len(self.down_block_types)

        # down
        lowerCAmelCase__					     = []
        lowerCAmelCase__					     = block_out_channels[0]
        for i, down_block_type in enumerate(self.down_block_types):
               lowerCAmelCase__					     = output_channel
               lowerCAmelCase__					     = block_out_channels[i]
               lowerCAmelCase__					     = i == len(lowercase__) - 1

               if down_block_type == "CrossAttnDownBlock2D":
                      lowerCAmelCase__					     = FlaxCrossAttnDownBlockaD(
                          in_channels=lowercase__      ,   out_channels=lowercase__      ,   dropout=self.dropout      ,   num_layers=self.layers_per_block      ,   num_attention_heads=num_attention_heads[i]      ,   add_downsample=not is_final_block      ,   use_linear_projection=self.use_linear_projection      ,   only_cross_attention=only_cross_attention[i]      ,   use_memory_efficient_attention=self.use_memory_efficient_attention      ,   dtype=self.dtype      ,   )
               else:
                      lowerCAmelCase__					     = FlaxDownBlockaD(
                          in_channels=lowercase__      ,   out_channels=lowercase__      ,   dropout=self.dropout      ,   num_layers=self.layers_per_block      ,   add_downsample=not is_final_block      ,   dtype=self.dtype      ,   )

               down_blocks.append(lowercase__)
        lowerCAmelCase__					     = down_blocks

        # mid
        lowerCAmelCase__					     = FlaxUNetMidBlockaDCrossAttn(
            in_channels=block_out_channels[-1]      ,   dropout=self.dropout      ,   num_attention_heads=num_attention_heads[-1]      ,   use_linear_projection=self.use_linear_projection      ,   use_memory_efficient_attention=self.use_memory_efficient_attention      ,   dtype=self.dtype      ,   )

        # up
        lowerCAmelCase__					     = []
        lowerCAmelCase__					     = list(reversed(lowercase__))
        lowerCAmelCase__					     = list(reversed(lowercase__))
        lowerCAmelCase__					     = list(reversed(lowercase__))
        lowerCAmelCase__					     = reversed_block_out_channels[0]
        for i, up_block_type in enumerate(self.up_block_types):
               lowerCAmelCase__					     = output_channel
               lowerCAmelCase__					     = reversed_block_out_channels[i]
               lowerCAmelCase__					     = reversed_block_out_channels[min(i + 1      ,   len(lowercase__) - 1)]

               lowerCAmelCase__					     = i == len(lowercase__) - 1

               if up_block_type == "CrossAttnUpBlock2D":
                      lowerCAmelCase__					     = FlaxCrossAttnUpBlockaD(
                          in_channels=lowercase__      ,   out_channels=lowercase__      ,   prev_output_channel=lowercase__      ,   num_layers=self.layers_per_block + 1      ,   num_attention_heads=reversed_num_attention_heads[i]      ,   add_upsample=not is_final_block      ,   dropout=self.dropout      ,   use_linear_projection=self.use_linear_projection      ,   only_cross_attention=only_cross_attention[i]      ,   use_memory_efficient_attention=self.use_memory_efficient_attention      ,   dtype=self.dtype      ,   )
               else:
                      lowerCAmelCase__					     = FlaxUpBlockaD(
                          in_channels=lowercase__      ,   out_channels=lowercase__      ,   prev_output_channel=lowercase__      ,   num_layers=self.layers_per_block + 1      ,   add_upsample=not is_final_block      ,   dropout=self.dropout      ,   dtype=self.dtype      ,   )

               up_blocks.append(lowercase__)
               lowerCAmelCase__					     = output_channel
        lowerCAmelCase__					     = up_blocks

        # out
        lowerCAmelCase__					     = nn.GroupNorm(num_groups=32      ,   epsilon=1e-5)
        lowerCAmelCase__					     = nn.Conv(
            self.out_channels      ,   kernel_size=(3, 3)      ,   strides=(1, 1)      ,   padding=((1, 1), (1, 1))      ,   dtype=self.dtype      ,   )




 def __call__(      self :  Optional[Any]      ,   lowercase__ :  Optional[int]      ,   lowercase__ :  List[str]      ,   lowercase__ :  int      ,   lowercase__ :  List[Any]=None      ,   lowercase__ :  Union[str, Any]=None      ,   lowercase__ :  bool = True      ,   lowercase__ :  bool = False      ,   ):







        '''simple docstring'''



        if not isinstance(lowercase__      ,   jnp.ndarray):
               lowerCAmelCase__					     = jnp.array([timesteps]      ,   dtype=jnp.intaa)
        elif isinstance(lowercase__      ,   jnp.ndarray) and len(timesteps.shape) == 0:
               lowerCAmelCase__					     = timesteps.astype(dtype=jnp.floataa)
               lowerCAmelCase__					     = jnp.expand_dims(lowercase__      ,   0)

        lowerCAmelCase__					     = self.time_proj(lowercase__)
        lowerCAmelCase__					     = self.time_embedding(lowercase__)

        # 2. pre-process
        lowerCAmelCase__					     = jnp.transpose(lowercase__      ,   (0, 2, 3, 1))
        lowerCAmelCase__					     = self.conv_in(lowercase__)

        # 3. down
        lowerCAmelCase__					     = (sample,)
        for down_block in self.down_blocks:
               if isinstance(lowercase__      ,   lowercase__):
                      lowerCAmelCase__     , lowerCAmelCase__					     = down_block(lowercase__      ,   lowercase__      ,   lowercase__      ,   deterministic=not train)
               else:
                      lowerCAmelCase__     , lowerCAmelCase__					     = down_block(lowercase__      ,   lowercase__      ,   deterministic=not train)
               down_block_res_samples += res_samples

        if down_block_additional_residuals is not None:
               lowerCAmelCase__					     = ()

               for down_block_res_sample, down_block_additional_residual in zip(
                   lowercase__      ,   lowercase__):
                      down_block_res_sample += down_block_additional_residual
                      new_down_block_res_samples += (down_block_res_sample,)

               lowerCAmelCase__					     = new_down_block_res_samples

        # 4. mid
        lowerCAmelCase__					     = self.mid_block(lowercase__      ,   lowercase__      ,   lowercase__      ,   deterministic=not train)

        if mid_block_additional_residual is not None:
               sample += mid_block_additional_residual

        # 5. up
        for up_block in self.up_blocks:
               lowerCAmelCase__					     = down_block_res_samples[-(self.layers_per_block + 1) :]
               lowerCAmelCase__					     = down_block_res_samples[: -(self.layers_per_block + 1)]
               if isinstance(lowercase__      ,   lowercase__):
                      lowerCAmelCase__					     = up_block(
                          lowercase__      ,   temb=lowercase__      ,   encoder_hidden_states=lowercase__      ,   res_hidden_states_tuple=lowercase__      ,   deterministic=not train      ,   )
               else:
                      lowerCAmelCase__					     = up_block(lowercase__      ,   temb=lowercase__      ,   res_hidden_states_tuple=lowercase__      ,   deterministic=not train)

        # 6. post-process
        lowerCAmelCase__					     = self.conv_norm_out(lowercase__)
        lowerCAmelCase__					     = nn.silu(lowercase__)
        lowerCAmelCase__					     = self.conv_out(lowercase__)
        lowerCAmelCase__					     = jnp.transpose(lowercase__      ,   (0, 3, 1, 2))

        if not return_dict:
               return (sample,)

        return FlaxUNetaDConditionOutput(sample=lowercase__)
