# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion
# and https://github.com/hojonathanho/diffusion

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

import flax
import jax.numpy as jnp

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils_flax import (
    CommonSchedulerState,
    FlaxKarrasDiffusionSchedulers,
    FlaxSchedulerMixin,
    FlaxSchedulerOutput,
    add_noise_common,
    get_velocity_common,
)






@flax.struct.dataclass
class 							_SCREAMING_SNAKE_CASE:
   UpperCamelCase_				:						CommonSchedulerState
   UpperCamelCase_				:						jnp.ndarray

   # setable values
   UpperCamelCase_				:						jnp.ndarray
   UpperCamelCase_				:						jnp.ndarray
   UpperCamelCase_				:						Optional[int] 			=   None
   @classmethod
   def _lowercase(    cls							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     )	->Any:
        return cls(
            common=lowerCAmelCase_							,     final_alpha_cumprod=lowerCAmelCase_							,     init_noise_sigma=lowerCAmelCase_							,     timesteps=lowerCAmelCase_							,     )






@dataclass
class 							_SCREAMING_SNAKE_CASE(   snake_case__	):
   UpperCamelCase_				:						DDIMSchedulerState






class 							_SCREAMING_SNAKE_CASE(   snake_case__       ,      snake_case__	):
   UpperCamelCase_				:						int 			=   [e.name for e in FlaxKarrasDiffusionSchedulers]

   UpperCamelCase_				:						jnp.dtype
   @property
   def _lowercase(    self    )	->List[Any]:
        return True
   @register_to_config
   def __init__(    self							,     lowerCAmelCase_ = 10_00							,     lowerCAmelCase_ = 0.00_01							,     lowerCAmelCase_ = 0.02							,     lowerCAmelCase_ = "linear"							,     lowerCAmelCase_ = None							,     lowerCAmelCase_ = True							,     lowerCAmelCase_ = 0							,     lowerCAmelCase_ = "epsilon"							,     lowerCAmelCase_ = jnp.floataa							,     )	->int:
        a  :    Tuple				=						dtype
   def _lowercase(    self							,     lowerCAmelCase_ = None    )	->DDIMSchedulerState:
        if common is None:
             a  :    List[Any]				=						CommonSchedulerState.create(self    )

        # At every step in ddim, we are looking into the previous alphas_cumprod
        # For the final step, there is no previous alphas_cumprod because we are already at 0
        # `set_alpha_to_one` decides whether we set this parameter simply to one or
        # whether we use the final alpha of the "non-previous" one.
        a  :    Optional[int]				=						(
            jnp.array(1.0							,     dtype=self.dtype    ) if self.config.set_alpha_to_one else common.alphas_cumprod[0]
        )

        # standard deviation of the initial noise distribution
        a  :    Optional[Any]				=						jnp.array(1.0							,     dtype=self.dtype    )

        a  :    List[str]				=						jnp.arange(0							,     self.config.num_train_timesteps    ).round()[::-1]

        return DDIMSchedulerState.create(
            common=lowerCAmelCase_							,     final_alpha_cumprod=lowerCAmelCase_							,     init_noise_sigma=lowerCAmelCase_							,     timesteps=lowerCAmelCase_							,     )
   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_ = None    )	->jnp.ndarray:
        return sample
   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_ = ()    )	->DDIMSchedulerState:
        a  :    Optional[int]				=						self.config.num_train_timesteps // num_inference_steps
        # creates integer timesteps by multiplying by ratio
        # rounding to avoid issues when num_inference_step is power of 3
        a  :    Any				=						(jnp.arange(0							,     lowerCAmelCase_    ) * step_ratio).round()[::-1] + self.config.steps_offset

        return state.replace(
            num_inference_steps=lowerCAmelCase_							,     timesteps=lowerCAmelCase_							,     )
   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )	->str:
        a  :    Any				=						state.common.alphas_cumprod[timestep]
        a  :    int				=						jnp.where(
            prev_timestep >= 0							,     state.common.alphas_cumprod[prev_timestep]							,     state.final_alpha_cumprod    )
        a  :    str				=						1 - alpha_prod_t
        a  :    int				=						1 - alpha_prod_t_prev

        a  :    Tuple				=						(beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)

        return variance
   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_ = 0.0							,     lowerCAmelCase_ = True							,     )	->Union[FlaxDDIMSchedulerOutput, Tuple]:
        if state.num_inference_steps is None:
             raise ValueError(
                 '''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler'''    )

        # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf
        # Ideally, read DDIM paper in-detail understanding

        # Notation (<variable name> -> <name in paper>
        # - pred_noise_t -> e_theta(x_t, t)
        # - pred_original_sample -> f_theta(x_t, t) or x_0
        # - std_dev_t -> sigma_t
        # - eta -> η
        # - pred_sample_direction -> "direction pointing to x_t"
        # - pred_prev_sample -> "x_t-1"

        # 1. get previous step value (=t-1)
        a  :    List[Any]				=						timestep - self.config.num_train_timesteps // state.num_inference_steps

        a  :    Tuple				=						state.common.alphas_cumprod
        a  :    Optional[Any]				=						state.final_alpha_cumprod

        # 2. compute alphas, betas
        a  :    Dict				=						alphas_cumprod[timestep]
        a  :    Optional[Any]				=						jnp.where(prev_timestep >= 0							,     alphas_cumprod[prev_timestep]							,     lowerCAmelCase_    )

        a  :    Any				=						1 - alpha_prod_t

        # 3. compute predicted original sample from predicted noise also called
        # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
        if self.config.prediction_type == "epsilon":
             a  :    List[Any]				=						(sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
             a  :    Tuple				=						model_output
        elif self.config.prediction_type == "sample":
             a  :    Union[str, Any]				=						model_output
             a  :    int				=						(sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5
        elif self.config.prediction_type == "v_prediction":
             a  :    Optional[int]				=						(alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
             a  :    Optional[Any]				=						(alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
        else:
             raise ValueError(
                 F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"""
                 ''' `v_prediction`'''    )

        # 4. compute variance: "sigma_t(η)" -> see formula (16)
        # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
        a  :    Any				=						self._get_variance(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )
        a  :    List[str]				=						eta * variance ** 0.5

        # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
        a  :    Any				=						(1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * pred_epsilon

        # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
        a  :    Any				=						alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction

        if not return_dict:
             return (prev_sample, state)

        return FlaxDDIMSchedulerOutput(prev_sample=lowerCAmelCase_							,     state=lowerCAmelCase_    )
   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     )	->jnp.ndarray:
        return add_noise_common(state.common							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )
   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     )	->jnp.ndarray:
        return get_velocity_common(state.common							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )


   def __len__(    self    )	->Optional[Any]:
        return self.config.num_train_timesteps
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_    )