
    biT                     |    d dl 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mZ 	 	 d
dZ G d d	ee
      Zy)    N)ListOptionalTupleUnion   )ConfigMixinregister_to_config   )KarrasDiffusionSchedulersSchedulerMixinSchedulerOutputc           
      $   |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    _/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/schedulers/scheduling_pndm.pyalpha_bar_fnz)betas_for_alpha_bar.<locals>.alpha_bar_fn5   s-    88QY%/$''9A=>!CC    expc                 2    t        j                  | dz        S )Ng      ()r   r   r   s    r   r   z)betas_for_alpha_bar.<locals>.alpha_bar_fn:   s    88AI&&r   z"Unsupported alpha_transform_type: r
   dtype)
ValueErrorrangeappendmintorchtensorfloat32)num_diffusion_timestepsmax_betaalpha_transform_typer   betasit1t2s           r   betas_for_alpha_barr+      s    . x'	D 
	&	' =>R=STUUE*+ M((!e..S\"-R0@@@(KLM <<U]]33r   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de	fd       Zd"de	deeej(                  f   fdZ	 d#dej,                  de	dej,                  dedeeef   f
dZ	 d#dej,                  de	dej,                  dedeeef   f
dZ	 d#dej,                  de	dej,                  dedeeef   f
dZdej,                  dej,                  fdZd Zdej,                  dej,                  dej<                  dej,                  fdZd  Z yc c}} w )$PNDMSchedulera  
    `PNDMScheduler` uses pseudo numerical methods for diffusion models such as the Runge-Kutta and linear multi-step
    method.

    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`, `scaled_linear`, or `squaredcos_cap_v2`.
        trained_betas (`np.ndarray`, *optional*):
            Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
        skip_prk_steps (`bool`, defaults to `False`):
            Allows the scheduler to skip the Runge-Kutta steps defined in the original paper as being required before
            PLMS steps.
        set_alpha_to_one (`bool`, defaults to `False`):
            Each diffusion step uses the alphas product value at that step and at the previous one. For the final step
            there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,
            otherwise it uses the alpha value at step 0.
        prediction_type (`str`, defaults to `epsilon`, *optional*):
            Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process)
            or `v_prediction` (see section 2.4 of [Imagen Video](https://imagen.research.google/video/paper.pdf)
            paper).
        timestep_spacing (`str`, defaults to `"leading"`):
            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.
    r
   Nnum_train_timesteps
beta_startbeta_endbeta_scheduletrained_betasskip_prk_stepsset_alpha_to_oneprediction_typetimestep_spacingsteps_offsetc                 L   |+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                         d| j                  z
  | _        t        j                  | j                  d	
      | _
        |rt        j                  d      n| j                  d	   | _        d| _        d| _        d	| _        d	| _        d | _        g | _        d | _        t'        j(                  d	|      d d d   j+                         | _        d | _        d | _        d | _        y )Nr   linearscaled_linear      ?r   squaredcos_cap_v2z is not implemented for g      ?r   )dim   )r!   r"   r#   r'   linspacer+   NotImplementedError	__class__alphascumprodalphas_cumprodfinal_alpha_cumprodinit_noise_sigma
pndm_ordercur_model_outputcounter
cur_sampleetsnum_inference_stepsnparangecopy
_timestepsprk_timestepsplms_timesteps	timesteps)selfr.   r/   r0   r1   r2   r3   r4   r5   r6   r7   s              r   __init__zPNDMScheduler.__init__q   so    $m5==IDJh&
H>QY^YfYfgDJo-
C3H[chcpcpquvvDJ11,-@ADJ%7OPTP^P^O_&`aaDJJ&#mmDKKQ?8H5<<#4dNaNabcNd  !$
  !" $( ))A':;DbDAFFH!"r   rM   devicec                    || _         | j                  j                  dk(  r`t        j                  d| j                  j
                  dz
  |      j                         j                  t        j                        | _	        nm| j                  j                  dk(  ry| j                  j
                  | j                   z  }t        j                  d|      |z  j                         | _	        | xj                  | j                  j                  z  c_	        n| j                  j                  dk(  r| j                  j
                  | j                   z  }t        j                  t        j                  | j                  j
                  d|             ddd   j                  t        j                        | _	        | xj                  dz  c_	        n"t        | j                  j                   d      | j                  j                  rst        j                  g       | _        t        j                   | j                  dd | j                  d	d | j                  dd g      ddd   j#                         | _        nt        j                  | j                  | j&                   d       j)                  d
      t        j*                  t        j                  d| j                  j
                  |z  d
z  g      | j&                        z   }|dd j)                  d
      dd ddd   j#                         | _        | j                  dd ddd   j#                         | _        t        j                   | j                  | j$                  g      j                  t        j                        }t-        j.                  |      j1                  |      | _        g | _        d| _        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
   leadingtrailingNr?   zY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.r   )rM   configr6   rN   r@   r.   roundastypeint64rQ   rO   r7   r   r3   arrayrR   concatenaterP   rS   rH   repeattiler!   
from_numpytorT   rL   rJ   rI   )rU   rM   rW   
step_ratiorR   rT   s         r   set_timestepszPNDMScheduler.set_timesteps   s(    $7 ;;'':5At{{>>BDWX^^`gghjhphpq O [[))Y688D<T<TTJ  "yy,?@:MTTVDOOOt{{777O[[))Z7884;S;SSJ !hhryy1P1PRSV`U`'abcgegcghooDO OOq O;;//0  1J  K  ;;%% "$"D"$..$//#22FXZ[]H^`d`o`oprps`t1u"v"#df  HHT__doo5E5G%HIPPQRSVXV]V]!T[[<<@SSWXXYZ\`\k\kW M #0"4";";A">q"Ddd!K!P!P!RD"&//#2"6"#df  NND$6$68K8K#LMTTUWU]U]^	)))477? !r   model_outputtimestepsamplereturn_dictreturnc                     | j                   t        | j                        k  r+| j                  j                  s| j                  ||||      S | j                  ||||      S )aG  
        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), and calls [`~PNDMScheduler.step_prk`]
        or [`~PNDMScheduler.step_plms`] depending on the internal variable `counter`.

        Args:
            model_output (`torch.Tensor`):
                The direct output from learned diffusion model.
            timestep (`int`):
                The current discrete timestep in the diffusion chain.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.
            return_dict (`bool`):
                Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`.

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

        )ri   rj   rk   rl   )rJ   lenrR   r]   r3   step_prk	step_plms)rU   ri   rj   rk   rl   s        r   stepzPNDMScheduler.step   sY    8 <<#d0011$++:T:T==lXV\ju=vv>>|hW]kv>wwr   c                 <   | j                   t        d      | j                  dz  rdn%| j                  j                  | j                   z  dz  }||z
  }| j
                  | j                  dz  dz     }| j                  dz  dk(  r;| xj                  d|z  z  c_        | j                  j                  |       || _	        n| j                  dz
  dz  dk(  r| xj                  d|z  z  c_        n\| j                  dz
  dz  dk(  r| xj                  d|z  z  c_        n.| j                  dz
  dz  dk(  r| j                  d|z  z   }d| _        | j                  | j                  n|}| 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 sample with
        the Runge-Kutta method. It performs four forward passes to approximate the solution to the differential
        equation.

        Args:
            model_output (`torch.Tensor`):
                The direct output from learned diffusion model.
            timestep (`int`):
                The current discrete timestep in the diffusion chain.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.
            return_dict (`bool`):
                Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or tuple.

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

        aNumber of inference steps is 'None', you need to run 'set_timesteps' after creating the schedulerr   r   r>   gUUUUUU?r
   gUUUUUU?   prev_sample)rM   r   rJ   r]   r.   rR   rI   rL   r   rK   _get_prev_sampler   )	rU   ri   rj   rk   rl   diff_to_prevprev_timesteprK   rw   s	            r   rp   zPNDMScheduler.step_prk  s   8 ##+s  !LL1,q$++2Q2QUYUmUm2mqr2r </%%dlla&7!&;<<<!q !!U\%99!HHOOL)$DOllQ!#q(!!U\%99!llQ!#q(!!U\%99!llQ!#q(005<3GGL$%D! )-(CT__
++J-Q]^>!;77r   c                    | j                   t        d      | j                  j                  s0t	        | j
                        dk  rt        | j                   d      || j                  j                  | j                   z  z
  }| j                  dk7  r0| j
                  dd | _        | j
                  j                  |       n(|}|| j                  j                  | j                   z  z   }t	        | j
                        dk(  r| j                  dk(  r|}|| _
        n0t	        | j
                        dk(  r8| j                  dk(  r)|| j
                  d   z   d	z  }| j                  }d| _
        nt	        | j
                        d	k(  r&d| j
                  d   z  | j
                  d
   z
  d	z  }nt	        | j
                        dk(  r<d| j
                  d   z  d| j
                  d
   z  z
  d| j
                  d   z  z   dz  }nNdd| j
                  d   z  d| j
                  d
   z  z
  d| j
                  d   z  z   d| j
                  d   z  z
  z  }| 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 sample with
        the linear multistep method. It performs one forward pass multiple times to approximate the solution.

        Args:
            model_output (`torch.Tensor`):
                The direct output from learned diffusion model.
            timestep (`int`):
                The current discrete timestep in the diffusion chain.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.
            return_dict (`bool`):
                Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or tuple.

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

        Nrt   ru   z can only be run AFTER scheduler has been run in 'prk' mode for at least 12 iterations See: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_pndm.py for more information.r
   r\   r   r?   r   r[               gUUUUUU?7   ;   %   	   rv   )rM   r   r]   r3   ro   rL   rB   r.   rJ   r   rK   rx   r   )rU   ri   rj   rk   rl   rz   rw   s          r   rq   zPNDMScheduler.step_plms?  sM   6 ##+s  {{))c$((ma.?>>" #( (  !4;;#B#BdF^F^#^^<<1xx}DHHHOOL)$M$++"A"ATE]E]"]]Htxx=A$,,!"3'L$DO]aDLLA$5(488B<71<L__F"DO]a,txx|;q@L]a"-TXXb\0AAAQSDTTXZZL"rDHHRL'82;L'LrTXT\T\]_T`O`'`cdgkgogoprgscs'stL++FHm\Z>!;77r   c                     |S )a?  
        Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
        current timestep.

        Args:
            sample (`torch.Tensor`):
                The input sample.

        Returns:
            `torch.Tensor`:
                A scaled input sample.
         )rU   rk   argskwargss       r   scale_model_inputzPNDMScheduler.scale_model_input  s	     r   c                    | j                   |   }|dk\  r| j                   |   n| j                  }d|z
  }d|z
  }| j                  j                  dk(  r|dz  |z  |dz  |z  z   }n<| j                  j                  dk7  r#t	        d| j                  j                   d      ||z  dz  }	||dz  z  ||z  |z  dz  z   }
|	|z  ||z
  |z  |
z  z
  }|S )Nr   r
   v_predictionr;   epsilonzprediction_type given as z+ must be one of `epsilon` or `v_prediction`)rE   rF   r]   r5   r   )rU   rk   rj   rz   ri   alpha_prod_talpha_prod_t_prevbeta_prod_tbeta_prod_t_prevsample_coeffmodel_output_denom_coeffrw   s               r   rx   zPNDMScheduler._get_prev_sample  s!    **84BOSTBTD//>Z^ZrZr,&00;;&&.8(#-=cAQU[@[[L[[((I5+DKK,G,G+HHst  *L8cB $02Bs2K#K;&)::O $  6!%6%E$UXp$pp 	 r   original_samplesnoiserT   c                    | j                   j                  |j                        | _         | j                   j                  |j                        }|j                  |j                        }||   dz  }|j	                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=d||   z
  dz  }|j	                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=||z  ||z  z   }|S )N)rW   r   r;   r?   r
   )rE   rf   rW   r   flattenro   shape	unsqueeze)rU   r   r   rT   rE   sqrt_alpha_prodsqrt_one_minus_alpha_prodnoisy_sampless           r   	add_noisezPNDMScheduler.add_noise  sa    #1144<L<S<S4T,,//6F6L6L/MLL!1!8!89	(3s:)113/''(3/?/E/E+FF-77;O /''(3/?/E/E+FF &'	)B%Bs$J!$=$E$E$G!+112S9I9O9O5PP(A(K(KB(O% +112S9I9O9O5PP (*::=VY^=^^r   c                 .    | j                   j                  S N)r]   r.   )rU   s    r   __len__zPNDMScheduler.__len__  s    {{...r   )
i  g-C6?g{Gz?r9   NFFr   rY   r   r   )T)!__name__
__module____qualname____doc__r   name_compatiblesorderr	   intfloatstrr   r   rN   ndarrayr   boolrV   r!   rW   rh   Tensorr   r   rr   rp   rq   r   rx   	IntTensorr   r   ).0es   00r   r-   r-   H   sK   #J %>>qAFF>LE $("%BF$!&( )2 2 2 	2
 2  bjj$u+&= >?2 2 2 2 2 2 2h:" :"eCDU>V :"B !xllx x 	x
 x 
%	&xL !:8ll:8 :8 	:8
 :8 
%	&:8B !E8llE8 E8 	E8
 E8 
%	&E8N %,, )X,, || ??	
 
4/[ ?s   Er-   )g+?r   )r   typingr   r   r   r   numpyrN   r!   configuration_utilsr   r	   scheduling_utilsr   r   r   r+   r-   r   r   r   <module>r      s=   "  / /   A X X !)4XT/NK T/r   