
    bi<l                         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mZ  e       rd dlZe G d	 d
e             Z	 	 ddZ G d dee      Zy)    N)	dataclass)ListOptionalTupleUnion   )ConfigMixinregister_to_config)
BaseOutputis_scipy_available   )KarrasDiffusionSchedulersSchedulerMixinc                   X    e Zd ZU dZej
                  ed<   dZeej
                     ed<   y)HeunDiscreteSchedulerOutputaq  
    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        h/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/schedulers/scheduling_heun_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_barr8   3   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	 	 	 	 	 	 	 	 	 	 	 	 	 d0de	de
de
dedeeej                  ee
   f      d	ed
ee   dee   dee   dee   de
dede	fd       Zd1dZed        Zed        Zed        Zd2de	fdZdej4                  dee
ej4                  f   dej4                  fdZ	 	 	 	 d3dee	   deeej8                  f   dee	   deee	      fdZd  Zd!ej4                  dej4                  fd"Zd!ej4                  de	dej4                  fd#Z 	 d4d!ej4                  de	d$e
d%e
dej4                  f
d&Z!ed'        Z"d( Z#	 d5d)eej4                  ej                  f   dee
ej4                  f   deej4                  ej                  f   d*edee$e%f   f
d+Z&d,ej4                  d-ej4                  dej4                  dej4                  fd.Z'd/ Z(yc c}} w )6HeunDiscreteScheduleru
  
    Scheduler with Heun steps for discrete beta schedules.

    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).
        clip_sample (`bool`, defaults to `True`):
            Clip the predicted sample for numerical stability.
        clip_sample_range (`float`, defaults to 1.0):
            The maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
        use_karras_sigmas (`bool`, *optional*, defaults to `False`):
            Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`,
            the sigmas are determined according to a sequence of noise levels {σi}.
        use_exponential_sigmas (`bool`, *optional*, defaults to `False`):
            Whether to use exponential sigmas for step sizes in the noise schedule during the sampling process.
        use_beta_sigmas (`bool`, *optional*, defaults to `False`):
            Whether to use beta sigmas for step sizes in the noise schedule during the sampling process. Refer to [Beta
            Sampling is All You Need](https://huggingface.co/papers/2407.12173) for more information.
        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.
    r   Nnum_train_timesteps
beta_startbeta_endbeta_scheduletrained_betasprediction_typeuse_karras_sigmasuse_exponential_sigmasuse_beta_sigmasclip_sampleclip_sample_rangetimestep_spacingsteps_offsetc                    | j                   j                  rt               st        d      t	        | j                   j                  | j                   j
                  | j                   j                  g      dkD  rt        d      |+t        j                  |t        j                        | _        n|dk(  r-t        j                  |||t        j                        | _        n|dk(  r6t        j                  |dz  |dz  |t        j                        dz  | _        nJ|d	k(  rt        |d
      | _        n2|dk(  rt        |d      | _        nt        | d| j                         d| j                  z
  | _        t        j"                  | j                   d      | _        | j'                  |d |       || _        d | _        d | _        | j,                  j/                  d      | _        y )Nz:Make sure to install scipy if you want to use beta sigmas.r   znOnly one of `config.use_beta_sigmas`, `config.use_exponential_sigmas`, `config.use_karras_sigmas` can be used.r)   linearscaled_linear      ?r   squaredcos_cap_v2r   )r3   r'   z is not implemented for       ?r   )dimcpu)configrC   r   ImportErrorsumrB   rA   r+   r   r/   r0   r4   linspacer8   NotImplementedError	__class__alphascumprodalphas_cumprodset_timesteps_step_index_begin_indexsigmasto)selfr;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   s                 r   __init__zHeunDiscreteScheduler.__init__   s   " ;;&&/A/CZ[[++T[[-O-OQUQ\Q\QnQnopstt A  $m5==IDJh&
H>QY^YfYfgDJo-
C3H[chcpcpquvvDJ11,-@W_`DJe#,-@W\]DJ%7OPTP^P^O_&`aaDJJ&#mmDKKQ? 	.6IJ!2 kknnU+r   c                     || j                   }||k(  j                         }t        |      dkD  rdnd}||   j                         S )Nr   r   )	timestepsnonzerolenitem)r^   timestepschedule_timestepsindicesposs        r   index_for_timestepz(HeunDiscreteScheduler.index_for_timestep   sL    %!%%1::< w<!#as|  ""r   c                     | j                   j                  dv r| j                  j                         S | j                  j                         dz  dz   dz  S )N)rS   trailingr   r   rK   )rP   rF   r\   maxr^   s    r   init_noise_sigmaz&HeunDiscreteScheduler.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.
        )rZ   rm   s    r   
step_indexz HeunDiscreteScheduler.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.
        r[   rm   s    r   begin_indexz!HeunDiscreteScheduler.begin_index   s    
    r   rs   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.
        Nrr   )r^   rs   s     r   set_begin_indexz%HeunDiscreteScheduler.set_begin_index   s     (r   samplere   returnc                     | j                   | j                  |       | j                  | j                      }||dz  dz   dz  z  }|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.
            timestep (`int`, *optional*):
                The current timestep in the diffusion chain.

        Returns:
            `torch.Tensor`:
                A scaled input sample.
        r   r   rK   )rp   _init_step_indexr\   )r^   rv   re   sigmas       r   scale_model_inputz'HeunDiscreteScheduler.scale_model_input   sJ    & ??"!!(+DOO,E1HqLS01r   num_inference_stepsdevicera   c           	      
   ||t        d      ||t        d      |!| j                  j                  rt        d      |!| j                  j                  rt        d      |!| j                  j                  rt        d      |xs t        |      }|| _        |xs | j                  j                  }|'t        j                  |t        j                        }n| j                  j                  dk(  r@t        j                  d	|d
z
  |t        j                        ddd   j                         }n;| j                  j                  dk(  r|| j                  z  }t        j                  d	|      |z  j                         ddd   j                         j!                  t        j                        }|| j                  j"                  z  }n| j                  j                  dk(  rf|| j                  z  }t        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(                  |t        j                  d	t        |            |      }| j                  j                  rQ| j+                  || j                        }t        j                  |D cg c]  }| j-                  ||       c}      }n| j                  j                  rG| j/                  ||      }t        j                  |D cg c]  }| j-                  ||       c}      }n\| j                  j                  rF| j1                  ||      }t        j                  |D cg c]  }| j-                  ||       c}      }t        j2                  |dgg      j!                  t        j                        }t5        j6                  |      j9                  |      }t5        j:                  |dd
 |d
d j=                  d      |dd g      | _        t5        j6                  |      }t5        j:                  |dd
 |d
d j=                  d      g      }|j9                  |t4        j                        | _         d| _!        d| _"        d| _#        d| _$        | j>                  j9                  d      | _        yc c}w c c}w c c}w )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.
            num_train_timesteps (`int`, *optional*):
                The number of diffusion steps used when training the model. If `None`, the default
                `num_train_timesteps` attribute is used.
            timesteps (`List[int]`, *optional*):
                Custom timesteps used to support arbitrary spacing between timesteps. If `None`, timesteps will be
                generated based on the `timestep_spacing` attribute. If `timesteps` is passed, `num_inference_steps`
                must be `None`, and `timestep_spacing` attribute will be ignored.
        NzEMust pass exactly one of `num_inference_steps` or `custom_timesteps`.zACan only pass one of `num_inference_steps` or `custom_timesteps`.z=Cannot use `timesteps` with `config.use_karras_sigmas = True`zCCannot set `timesteps` with `config.use_exponential_sigmas = True`.z<Cannot set `timesteps` with `config.use_beta_sigmas = True`.r)   rS   r   r   leadingrk   zY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.rK   )	in_sigmasr|   g        )r}   r   r}   r*   rO   )%r+   rP   rA   rB   rC   rc   r|   r;   nparrayr0   rF   rS   copyarangeroundastyperG   rX   loginterp_convert_to_karras_sigma_to_t_convert_to_exponential_convert_to_betaconcatenater   
from_numpyr]   catrepeat_interleaver\   ra   prev_derivativedtrZ   r[   )	r^   r|   r}   r;   ra   
step_ratior\   
log_sigmasrz   s	            r   rY   z#HeunDiscreteScheduler.set_timesteps  sy   . &9+<dee*y/D`aa T[[%B%B\]] T[[%G%Gbcc T[[%@%@[\\1CS^#6 1TT[[5T5T "**=I {{++z9KK+>+BDW_a_i_ijkomokopuuw	--:0D4L4LL
  YYq*=>KRRTUYWYUYZ__ahhikisist	T[[555	--;043K3KK
  YY':A
{KRRTYY[bbcecmcmn	Q	 {{334  5N  O  A 3 33t7J7JJsRSVVF^
9bii3v;&?H;;((,,vSWSkSk,lFSY!Z%$"2"25*"E!Z[I[[//11FXk1lFSY!Z%$"2"25*"E!Z[I[[((**VQd*eFSY!Z%$"2"25*"E!Z[I#077

C!!&),,F,;iiVAb\-K-KA-NPVWYWZP[ \]$$Y/	IIy!}im.M.Ma.PQR	"V5==I  $ kknnU+/ "[ "[ "[s   6UU0Uc                    t        j                  t        j                  |d            }||d d t         j                  f   z
  }t        j                  |dk\  d      j                  d      j                  |j                  d   dz
        }|dz   }||   }||   }||z
  ||z
  z  }	t        j                  |	dd      }	d|	z
  |z  |	|z  z   }
|
j                  |j                        }
|
S )Ng|=r   )axisr   )rl   r   )	r   r   maximumnewaxiscumsumargmaxclipshapereshape)r^   rz   r   	log_sigmadistslow_idxhigh_idxlowhighwr%   s              r   r   z!HeunDiscreteScheduler._sigma_to_td  s    FF2::eU34	 Jq"**}55 ))UaZq188a8@EE*JZJZ[\J]`aJaEbQ;!(# 9_t,GGAq! UgH,IIekk"r   r   c                    t        | j                  d      r| j                  j                  }nd}t        | j                  d      r| j                  j                  }nd}||n|d   j	                         }||n|d   j	                         }d}t        j                  dd|      }|d|z  z  }|d|z  z  }||||z
  z  z   |z  }	|	S )z6Constructs the noise schedule of Karras et al. (2022).	sigma_minN	sigma_maxr   r   g      @r   )hasattrrP   r   r   rd   r   rS   )
r^   r   r|   r   r   rhorampmin_inv_rhomax_inv_rhor\   s
             r   r   z(HeunDiscreteScheduler._convert_to_karras|  s    
 4;;,--II4;;,--II!*!6IIbM<N<N<P	!*!6IIaL<M<M<O	{{1a!45AG,AG,k(A BBsJr   c                    t        | j                  d      r| j                  j                  }nd}t        | j                  d      r| j                  j                  }nd}||n|d   j	                         }||n|d   j	                         }t        j                  t        j                  t        j                  |      t        j                  |      |            }|S )z)Constructs an exponential noise schedule.r   Nr   r   r   )
r   rP   r   r   rd   r   r'   rS   r!   r   )r^   r   r|   r   r   r\   s         r   r   z-HeunDiscreteScheduler._convert_to_exponential  s    
 4;;,--II4;;,--II!*!6IIbM<N<N<P	!*!6IIaL<M<M<O	DHHY$7)9LNabcr   alphabetac           
      (   t        | j                  d      r| j                  j                  }nd}t        | j                  d      r| j                  j                  }nd}||n|d   j	                         }||n|d   j	                         }t        j                  dt        j                  dd|      z
  D cg c]-  }t        j                  j                  j                  |||      / c}D cg c]  }||||z
  z  z    c}      }	|	S c c}w c c}w )zJFrom "Beta Sampling is All You Need" [arXiv:2407.12173] (Lee et. al, 2024)r   Nr   r   r   r   )r   rP   r   r   rd   r   r   rS   scipystatsr   ppf)
r^   r   r|   r   r   r   r   re   r   r\   s
             r   r   z&HeunDiscreteScheduler._convert_to_beta  s     4;;,--II4;;,--II!*!6IIbM<N<N<P	!*!6IIaL<M<M<O	
 %&Aq:M(N$N  KK$$((5$? SI	$9:;
 s   82D
/Dc                     | j                   d u S N)r   rm   s    r   state_in_first_orderz*HeunDiscreteScheduler.state_in_first_order  s    ww$r   c                     | j                   Vt        |t        j                        r%|j	                  | j
                  j                        }| j                  |      | _        y | j                  | _        y r   )
rs   
isinstancer   r   r]   ra   r}   ri   rZ   r[   )r^   re   s     r   ry   z&HeunDiscreteScheduler._init_step_index  sU    #(ELL1#;;t~~'<'<=#66x@D#00Dr   model_outputreturn_dictc                    | j                   | j                  |       | j                  r6| j                  | j                      }| j                  | j                   dz      }n5| j                  | j                   dz
     }| j                  | j                      }d}||dz   z  }| j                  j
                  dk(  r| j                  r|n|}	||	|z  z
  }
n| j                  j
                  dk(  r/| j                  r|n|}	||	 |	dz  dz   dz  z  z  ||	dz  dz   z  z   }
n?| j                  j
                  dk(  r|}
n#t        d	| j                  j
                   d
      | j                  j                  r;|
j                  | j                  j                   | j                  j                        }
| j                  r#||
z
  |z  }||z
  }|| _
        || _        || _        nG||
z
  |z  }| j                  |z   dz  }| j                  }| j                  }d| _
        d| _        d| _        |||z  z   }| 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.
            return_dict (`bool`):
                Whether or not to return a [`~schedulers.scheduling_heun_discrete.HeunDiscreteSchedulerOutput`] or
                tuple.

        Returns:
            [`~schedulers.scheduling_heun_discrete.HeunDiscreteSchedulerOutput`] or `tuple`:
                If return_dict is `True`, [`~schedulers.scheduling_heun_discrete.HeunDiscreteSchedulerOutput`] is
                returned, otherwise a tuple is returned where the first element is the sample tensor.
        Nr   r   epsilonv_predictionr   rK   rv   zprediction_type given as z, must be one of `epsilon`, or `v_prediction`)r   r   )rp   ry   r   r\   rP   r@   r+   rD   clamprE   r   r   rv   rZ   r   )r^   r   re   rv   r   rz   
sigma_nextgamma	sigma_hatsigma_inputr   
derivativer   r   s                 r   stepzHeunDiscreteScheduler.step  sj   6 ??"!!(+$$KK0ET__q%89J KK! 34ET__5J
 UQY'	 ;;&&)3'+'@'@)jK#)K,,F#F [[((N:'+'@'@)jK#/K<;PQ>TUCUZ]B]3]#^+q.1,-$  [[((H4#/ +DKK,G,G+HHtu  ;;""#7#=#=...0M0M$  $$ #779DJi'B $.D DG DK !#77:EJ..;q@J B[[F $(D DGDKzB. 	A$ 
 +{Ymnnr   original_samplesnoisec                    | 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 )Nr   mpsr)   r   r   )r\   r]   r}   r*   typer   is_floating_pointra   r0   rs   ri   rp   r   flattenrc   	unsqueeze)
r^   r   r   ra   r\   rf   r%   step_indicesrz   noisy_sampless
             r   	add_noisezHeunDiscreteScheduler.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   )rP   r;   rm   s    r   __len__zHeunDiscreteScheduler.__len__a  s    {{...r   )i  g_QK?g~jt?rI   Nr   FFFFrM   rS   r   r   )r   )NNNN)333333?r   )T))r   r   r   r   r   name_compatiblesorderr
   intfloatstrr   r   r   ndarrayr   boolr_   ri   propertyrn   rp   rs   ru   r   r   r{   r}   rY   r   r   r   r   r   ry   r   r   r   r   r   ).0es   00r   r:   r:   _   sQ   'R %>>qAFF>LE $(#%BF(,116*/&+#& *., ., ., 	.,
 .,  bjj$u+&= >?., ., $D>., !)., "$., d^., !., ., ., .,b# 3 3     ! !(3 ( u||+, 
	8 .2+/-1)-Z,%c]Z, c5<<'(Z, &c]	Z,
 DI&Z,z0ELL RWR^R^ 4 TW \a\h\h . dg<?HM[`	>  1 !eoELL"**45eo u||+,eo ellBJJ./	eo
 eo 
*E1	2eoP,, || <<	
 
B/q ?s   G-r:   )g+?r   )r!   dataclassesr   typingr   r   r   r   numpyr   r   configuration_utilsr	   r
   utilsr   r   scheduling_utilsr   r   scipy.statsr   r   r8   r:   r   r   r   <module>r      sf     ! / /   A 2 G  8* 8 8( !)4XC/NK C/r   