
    bijR                         d dl Z d dlmZ d dlmZmZmZmZ d dlZ	d dl
Z
ddlmZmZ ddlmZmZ ddlmZ dd	lmZmZ  ej,                  e      Ze G d
 de             Z	 	 ddZd Z G d dee      Zy)    N)	dataclass)ListOptionalTupleUnion   )ConfigMixinregister_to_config)
BaseOutputlogging)randn_tensor   )KarrasDiffusionSchedulersSchedulerMixinc                   X    e Zd ZU dZej
                  ed<   dZeej
                     ed<   y)%EulerAncestralDiscreteSchedulerOutputaq  
    Output class for the scheduler's `step` function output.

    Args:
        prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
            Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
            denoising loop.
        pred_original_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
            The predicted denoised sample `(x_{0})` based on the model output from the current timestep.
            `pred_original_sample` can be used to preview progress or for guidance.
    prev_sampleNpred_original_sample)	__name__
__module____qualname____doc__torchTensor__annotations__r   r        s/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/schedulers/scheduling_euler_ancestral_discrete.pyr   r      s'    
 37(5<<07r   r   c           
      $   |dk(  rd }n|dk(  rd }nt        d|       g }t        |       D ]<  }|| z  }|dz   | z  }|j                  t        d ||       ||      z  z
  |             > t	        j
                  |t        j                        S )a  
    Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
    (1-beta) over time from t = [0,1].

    Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
    to that part of the diffusion process.


    Args:
        num_diffusion_timesteps (`int`): the number of betas to produce.
        max_beta (`float`): the maximum beta to use; use values lower than 1 to
                     prevent singularities.
        alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
                     Choose from `cosine` or `exp`

    Returns:
        betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
    cosinec                 f    t        j                  | dz   dz  t         j                  z  dz        dz  S )NgMb?gT㥛 ?r   )mathcospits    r   alpha_bar_fnz)betas_for_alpha_bar.<locals>.alpha_bar_fnL   s-    88QY%/$''9A=>!CCr   expc                 2    t        j                  | dz        S )Ng      ()r"   r(   r%   s    r   r'   z)betas_for_alpha_bar.<locals>.alpha_bar_fnQ   s    88AI&&r   z"Unsupported alpha_transform_type: r   dtype)
ValueErrorrangeappendminr   tensorfloat32)num_diffusion_timestepsmax_betaalpha_transform_typer'   betasit1t2s           r   betas_for_alpha_barr9   3   s    . x'	D 
	&	' =>R=STUUE*+ M((!e..S\"-R0@@@(KLM <<U]]33r   c                 (   d| z
  }t        j                  |d      }|j                         }|d   j                         }|d   j                         }||z  }||||z
  z  z  }|dz  }|dd |dd z  }t        j                  |dd |g      }d|z
  } | S )a.  
    Rescales betas to have zero terminal SNR Based on https://huggingface.co/papers/2305.08891 (Algorithm 1)


    Args:
        betas (`torch.Tensor`):
            the betas that the scheduler is being initialized with.

    Returns:
        `torch.Tensor`: rescaled betas with zero terminal SNR
          ?r   dimr   r   N)r   cumprodsqrtclonecat)r5   alphasalphas_cumprodalphas_bar_sqrtalphas_bar_sqrt_0alphas_bar_sqrt_T
alphas_bars          r   rescale_zero_terminal_snrrI   `   s     5[F]]6q1N$))+O (*002'+113 ((O (,=@Q,QRRO !!#J^j"o-FYY
1Q01FJELr   c                      e Zd ZdZeD  cg c]  }|j
                   c}} ZdZe	 	 	 	 	 	 	 	 	 d%de	de
de
dedeeej                  ee
   f      d	ed
ede	defd       Zed        Zed        Zed        Zd&de	fdZdej2                  dee
ej2                  f   dej2                  fdZd'de	deeej6                  f   fdZd'dZd Z	 	 d(dej2                  dee
ej2                  f   dej2                  deej>                     dedee e!f   fdZ"d ej2                  d!ej2                  d"ej2                  dej2                  fd#Z#d$ Z$yc c}} w ))EulerAncestralDiscreteScheduleram  
    Ancestral sampling with Euler method steps.

    This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
    methods the library implements for all schedulers such as loading and saving.

    Args:
        num_train_timesteps (`int`, defaults to 1000):
            The number of diffusion steps to train the model.
        beta_start (`float`, defaults to 0.0001):
            The starting `beta` value of inference.
        beta_end (`float`, defaults to 0.02):
            The final `beta` value.
        beta_schedule (`str`, defaults to `"linear"`):
            The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
            `linear` or `scaled_linear`.
        trained_betas (`np.ndarray`, *optional*):
            Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
        prediction_type (`str`, defaults to `epsilon`, *optional*):
            Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
            `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
            Video](https://imagen.research.google/video/paper.pdf) paper).
        timestep_spacing (`str`, defaults to `"linspace"`):
            The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
            Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
        steps_offset (`int`, defaults to 0):
            An offset added to the inference steps, as required by some model families.
        rescale_betas_zero_snr (`bool`, defaults to `False`):
            Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
            dark samples instead of limiting it to samples with medium brightness. Loosely related to
            [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
    r   Nnum_train_timesteps
beta_startbeta_endbeta_scheduletrained_betasprediction_typetimestep_spacingsteps_offsetrescale_betas_zero_snrc
                    |+t        j                  |t         j                        | _        n|dk(  r-t        j                  |||t         j                        | _        nk|dk(  r6t        j                  |dz  |dz  |t         j                        dz  | _        n0|dk(  rt        |      | _        nt        | d| j                         |	rt        | j                        | _        d| j                  z
  | _	        t        j                  | j                  d	
      | _        |	rd| j                  d<   t        j                  d| j                  z
  | j                  z  dz        }
t        j                  |
d d d   dgg      j                  t        j                        }
t        j                   |
      | _        d | _        t        j                  d	|dz
  |t&              d d d   j)                         }t        j                   |      | _        d| _        d | _        d | _        | j"                  j3                  d      | _        y )Nr*   linearscaled_linear      ?r   squaredcos_cap_v2z is not implemented for r;   r   r<   g      p>r>   r           Fcpu)r   r0   r1   r5   linspacer9   NotImplementedError	__class__rI   rC   r?   rD   nparrayconcatenateastype
from_numpysigmasnum_inference_stepsfloatcopy	timestepsis_scale_input_called_step_index_begin_indexto)selfrL   rM   rN   rO   rP   rQ   rR   rS   rT   rd   rh   s               r   __init__z(EulerAncestralDiscreteScheduler.__init__   s    $m5==IDJh&
H>QY^YfYfgDJo-
C3H[chcpcpquvvDJ11,-@ADJ%7OPTP^P^O_&`aa!24::>DJDJJ&#mmDKKQ?! '-D#A 3 33t7J7JJsRS"u 56==bjjI&&v. $( KK#6#:<OW\]^b`b^bchhj	)))4%*" kknnU+r   c                     | j                   j                  dv r| j                  j                         S | j                  j                         dz  dz   dz  S )N)r\   trailingr   r   rX   )configrR   rd   maxrm   s    r   init_noise_sigmaz0EulerAncestralDiscreteScheduler.init_noise_sigma   sH     ;;''+CC;;??$$!Q&*s22r   c                     | j                   S )zg
        The index counter for current timestep. It will increase 1 after each scheduler step.
        )rj   rs   s    r   
step_indexz*EulerAncestralDiscreteScheduler.step_index   s    
 r   c                     | j                   S )zq
        The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
        rk   rs   s    r   begin_indexz+EulerAncestralDiscreteScheduler.begin_index   s    
    r   ry   c                     || _         y)z
        Sets the begin index for the scheduler. This function should be run from pipeline before the inference.

        Args:
            begin_index (`int`):
                The begin index for the scheduler.
        Nrx   )rm   ry   s     r   set_begin_indexz/EulerAncestralDiscreteScheduler.set_begin_index   s     (r   sampletimestepreturnc                     | j                   | j                  |       | j                  | j                      }||dz  dz   dz  z  }d| _        |S )a   
        Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
        current timestep. Scales the denoising model input by `(sigma**2 + 1) ** 0.5` to match the Euler algorithm.

        Args:
            sample (`torch.Tensor`):
                The input sample.
            timestep (`int`, *optional*):
                The current timestep in the diffusion chain.

        Returns:
            `torch.Tensor`:
                A scaled input sample.
        r   r   rX   T)rv   _init_step_indexrd   ri   )rm   r|   r}   sigmas       r   scale_model_inputz1EulerAncestralDiscreteScheduler.scale_model_input   sR      ??"!!(+DOO,E1HqLS01%)"r   re   devicec           	         || _         | j                  j                  dk(  rTt        j                  d| j                  j
                  dz
  |t        j                        ddd   j                         }nw| j                  j                  dk(  r| j                  j
                  | j                   z  }t        j                  d|      |z  j                         ddd   j                         j                  t        j                        }|| j                  j                  z  }n| j                  j                  dk(  r| j                  j
                  | j                   z  }t        j                  | j                  j
                  d|       j                         j                         j                  t        j                        }|dz  }n"t        | j                  j                   d	      t        j                  d| j                  z
  | j                  z  d
z        }t        j                  |t        j                  dt!        |            |      }t        j"                  |dgg      j                  t        j                        }t%        j&                  |      j)                  |      | _        t%        j&                  |      j)                  |      | _        d| _        d| _        | j*                  j)                  d      | _        y)a  
        Sets the discrete timesteps used for the diffusion chain (to be run before inference).

        Args:
            num_inference_steps (`int`):
                The number of diffusion steps used when generating samples with a pre-trained model.
            device (`str` or `torch.device`, *optional*):
                The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
        r\   r   r   r*   Nr>   leadingrp   zY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.rX   rZ   )r   r[   )re   rq   rR   r_   r\   rL   r1   rg   arangeroundrb   rS   r,   r`   rD   interplenra   r   rc   rl   rd   rh   rj   rk   )rm   re   r   rh   
step_ratiord   s         r   set_timestepsz-EulerAncestralDiscreteScheduler.set_timesteps  s`    $7  ;;'':5At{{'F'F'JL_gigqgqr"df  [[))Y688D<T<TTJ 1&9:ZGNNPQUSUQUV[[]ddegeoeopI111I[[))Z7884;S;SSJ 4;;#B#BA
{SZZ\aacjjkmkukuvINI;;//0  1J  K  A 3 33t7J7JJsRS9bii3v;&?H#077

C&&v.111@)))477v7F kknnU+r   c                     || j                   }||k(  j                         }t        |      dkD  rdnd}||   j                         S )Nr   r   )rh   nonzeror   item)rm   r}   schedule_timestepsindicesposs        r   index_for_timestepz2EulerAncestralDiscreteScheduler.index_for_timestepB  sL    %!%%1::< w<!#as|  ""r   c                     | j                   Vt        |t        j                        r%|j	                  | j
                  j                        }| j                  |      | _        y | j                  | _        y N)
ry   
isinstancer   r   rl   rh   r   r   rj   rk   )rm   r}   s     r   r   z0EulerAncestralDiscreteScheduler._init_step_indexQ  sU    #(ELL1#;;t~~'<'<=#66x@D#00Dr   model_output	generatorreturn_dictc                 |   t        |t        t        j                  t        j                  f      rt        d      | j                  st        j                  d       | j                  | j                  |       | j                  | j                     }|j                  t        j                        }| j                  j                  dk(  r	|||z  z
  }n| j                  j                  dk(  r|| |dz  dz   dz  z  z  ||dz  dz   z  z   }nG| j                  j                  dk(  rt!        d	      t        d
| j                  j                   d      | j                  | j                     }| j                  | j                  dz      }	|	dz  |dz  |	dz  z
  z  |dz  z  dz  }
|	dz  |
dz  z
  dz  }||z
  |z  }||z
  }|||z  z   }|j"                  }t%        |j&                  |j(                  ||      }|||
z  z   }|j                  |j(                        }| xj*                  dz  c_        |s||fS t-        ||      S )a  
        Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
        process from the learned model outputs (most often the predicted noise).

        Args:
            model_output (`torch.Tensor`):
                The direct output from learned diffusion model.
            timestep (`float`):
                The current discrete timestep in the diffusion chain.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.
            generator (`torch.Generator`, *optional*):
                A random number generator.
            return_dict (`bool`):
                Whether or not to return a
                [`~schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteSchedulerOutput`] or tuple.

        Returns:
            [`~schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteSchedulerOutput`] or `tuple`:
                If return_dict is `True`,
                [`~schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteSchedulerOutput`] is returned,
                otherwise a tuple is returned where the first element is the sample tensor.

        zPassing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to `EulerDiscreteScheduler.step()` is not supported. Make sure to pass one of the `scheduler.timesteps` as a timestep.zThe `scale_model_input` function should be called before `step` to ensure correct denoising. See `StableDiffusionPipeline` for a usage example.epsilonv_predictionr   r   rX   r|   z+prediction_type not implemented yet: samplezprediction_type given as z, must be one of `epsilon`, or `v_prediction`)r+   r   r   )r   r   )r   intr   	IntTensor
LongTensorr,   ri   loggerwarningrv   r   rd   rl   r1   rq   rQ   r]   r   r   shaper+   rj   r   )rm   r   r}   r|   r   r   r   r   
sigma_fromsigma_tosigma_up
sigma_down
derivativedtr   r   noises                    r   stepz$EulerAncestralDiscreteScheduler.stepY  s_   B heoou7G7G HIG  ))NNE
 ??"!!(+DOO, 5==) ;;&&)3#)EL,@#@ [[((N:#/E6UAX\c<Q3Q#RV\`egh`hkl`lVm#n [[((H4%&STT+DKK,G,G+HHtu  [[1
;;t23aK:q=8Q;#>?*a-OTWWkHaK/C7
 33u<
%zB.$$\//|7I7IRXdmn!EH$44 "nn\%7%78 	A$ 
 5#:N
 	
r   original_samplesr   rh   c                    | j                   j                  |j                  |j                        }|j                  j                  dk(  rvt        j                  |      ra| j                  j                  |j                  t
        j                        }|j                  |j                  t
        j                        }n@| j                  j                  |j                        }|j                  |j                        }| j                   |D cg c]  }| j                  ||       }}nG| j                  | j                  g|j                  d   z  }n| j                  g|j                  d   z  }||   j                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=|||z  z   }	|	S c c}w )N)r   r+   mpsr*   r   r>   )rd   rl   r   r+   typer   is_floating_pointrh   r1   ry   r   rv   r   flattenr   	unsqueeze)
rm   r   r   rh   rd   r   r&   step_indicesr   noisy_sampless
             r   	add_noisez)EulerAncestralDiscreteScheduler.add_noise  s    '7'>'>FVF\F\]""''50U5L5LY5W!%!2!23C3J3JRWR_R_!2!`!%5%<%<EMMRI!%!2!23C3J3J!K!%5%<%<=I #T]^qD33A7IJ^L^__( OO,yq/AAL !,,-	0BBL|$,,.%++%5%;%;!<<OOB'E %++%5%;%;!<< )55=8 _s   G9c                 .    | j                   j                  S r   )rq   rL   rs   s    r   __len__z'EulerAncestralDiscreteScheduler.__len__  s    {{...r   )	i  g-C6?g{Gz?rV   Nr   r\   r   F)r   r   )NT)%r   r   r   r   r   name_compatiblesorderr
   r   rf   strr   r   r_   ndarrayr   boolrn   propertyrt   rv   ry   r{   r   r   r   r   r   r   r   	Generatorr   r   r   r   r   ).0es   00r   rK   rK      s)   B %>>qAFF>LE $("%BF( *',0, 0, 0, 	0,
 0,  bjj$u+&= >?0, 0, 0, 0, !%0, 0,d 3 3     ! !(3 ( eU\\FY@Z _d_k_k 0*, *,eCDU>V *,Z#1 04 d
lld
 u||+,d
 	d

 EOO,d
 d
 
4e;	<d
N,, || <<	
 
B/w	 ?s   E
rK   )g+?r    )r"   dataclassesr   typingr   r   r   r   numpyr_   r   configuration_utilsr	   r
   utilsr   r   utils.torch_utilsr   scheduling_utilsr   r   
get_loggerr   r   r   r9   rI   rK   r   r   r   <module>r      sx     ! / /   A ' , G 
		H	% 8J 8 8( !)4Z!H^/nk ^/r   