o
    Gi:u                  	   @   s   d dl Z d dlmZ d dl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 r7d dlZeG d	d
 d
eZ		ddededed dejfddZG dd dee	ZdS )    N)	dataclass)Literal   )ConfigMixinregister_to_config)
BaseOutputis_scipy_available   )KarrasDiffusionSchedulersSchedulerMixinc                   @   s.   e Zd ZU dZejed< dZejdB ed< dS )KDPM2DiscreteSchedulerOutputaq  
    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   r   d/home/ubuntu/.local/lib/python3.10/site-packages/diffusers/schedulers/scheduling_k_dpm_2_discrete.pyr      s   
 
r   +?cosinenum_diffusion_timestepsmax_betaalpha_transform_type)r   explaplacereturnc                 C   s   |dkr	dd }n|dkrdd }n|dkrdd }nt d| g }t| D ]}||  }|d	 |  }|td	||||  | q(tj|tjd
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`, defaults to `0.999`):
            The maximum beta to use; use values lower than 1 to avoid numerical instability.
        alpha_transform_type (`str`, defaults to `"cosine"`):
            The type of noise schedule for `alpha_bar`. Choose from `cosine`, `exp`, or `laplace`.

    Returns:
        `torch.Tensor`:
            The betas used by the scheduler to step the model outputs.
    r   c                 S   s    t | d d t j d d S )NgMb?gT㥛 ?r   )mathcospitr   r   r   alpha_bar_fnM   s    z)betas_for_alpha_bar.<locals>.alpha_bar_fnr   c              	   S   sP   dt dd|   t ddt d|    d  }t |}t |d|  S )Ng      r	         ?r   gư>)r    copysignlogfabsr   sqrt)r$   lmbsnrr   r   r   r%   R   s   4
r   c                 S   s   t | d S )Ng      ()r    r   r#   r   r   r   r%   Y   s   z"Unsupported alpha_transform_type: r	   dtype)
ValueErrorrangeappendminr   tensorfloat32)r   r   r   r%   betasit1t2r   r   r   betas_for_alpha_bar3   s   


"r9   c                   @   s  e Zd ZdZdd eD ZdZe							
	
	
			dLdede	de	de
dejee	 B d	B dededede
de
defddZedd Zedd Zedd  ZdMd!efd"d#Zd$ejd%e	ejB d&ejfd'd(Z				dNd)ed*e
ejB defd+d,Zed-d. Z		dOd%e	ejB d/ejd	B d&efd0d1Zd%e	ejB d&d	fd2d3Zd4d5 Zd6ejd&ejfd7d8Zd6ejd)ed&ejfd9d:Z	;dPd6ejd)ed<e	d=e	d&ejf
d>d?Z 	@dQdAejejB d%e	ejB d$ejejB dBed&e!e"B f
dCdDZ#dEejdFejdGejd&ejfdHdIZ$dJdK Z%d	S )RKDPM2DiscreteScheduleru/
  
    KDPM2DiscreteScheduler is inspired by the DPMSolver2 and Algorithm 2 from the [Elucidating the Design Space of
    Diffusion-Based Generative Models](https://huggingface.co/papers/2206.00364) paper.

    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.00085):
            The starting `beta` value of inference.
        beta_end (`float`, defaults to 0.012):
            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`.
        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.
        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://huggingface.co/papers/2210.02303) 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.
    c                 C   s   g | ]}|j qS r   )name).0er   r   r   
<listcomp>   s    z!KDPM2DiscreteScheduler.<listcomp>r     _QK?~jt?linearNFepsilonlinspacer   num_train_timesteps
beta_startbeta_endbeta_scheduletrained_betasuse_karras_sigmasuse_exponential_sigmasuse_beta_sigmasprediction_typetimestep_spacingsteps_offsetc                 C   s  | j jrt stdt| j j| j j| j jgdkrtd|d ur,tj	|tj
d| _n:|dkr<tj|||tj
d| _n*|dkrRtj|d |d |tj
dd | _n|d	kr\t|| _n
t| d
| j d| j | _tj| jdd| _| |d | d | _d | _| jd| _d S )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-   rB   scaled_linearr&   r   squaredcos_cap_v2z is not implemented for g      ?r   dimcpu)configrL   r   ImportErrorsumrK   rJ   r/   r   r3   r4   r5   rD   r9   NotImplementedError	__class__alphascumprodalphas_cumprodset_timesteps_step_index_begin_indexsigmasto)selfrE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   r   r   r   __init__   s*   $zKDPM2DiscreteScheduler.__init__c                 C   s,   | j jdv r| j S | j d d d S )N)rD   trailingr   r	   r&   )rU   rN   r`   maxrb   r   r   r   init_noise_sigma   s   
z'KDPM2DiscreteScheduler.init_noise_sigmac                 C      | j S )zg
        The index counter for current timestep. It will increase 1 after each scheduler step.
        )r^   rf   r   r   r   
step_index      z!KDPM2DiscreteScheduler.step_indexc                 C   rh   )zq
        The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
        r_   rf   r   r   r   begin_index   rj   z"KDPM2DiscreteScheduler.begin_indexrl   c                 C   s
   || _ dS )z
        Sets the begin index for the scheduler. This function should be run from pipeline before the inference.

        Args:
            begin_index (`int`, defaults to `0`):
                The begin index for the scheduler.
        Nrk   )rb   rl   r   r   r   set_begin_index   s   
z&KDPM2DiscreteScheduler.set_begin_indexsampletimestepr   c                 C   sL   | j du r
| | | jr| j| j  }n| j| j  }||d d d  }|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.
        Nr   r	   r&   )ri   _init_step_indexstate_in_first_orderr`   sigmas_interpol)rb   rn   ro   sigmar   r   r   scale_model_input   s   

z(KDPM2DiscreteScheduler.scale_model_inputnum_inference_stepsdevicec           
         s4  |_ |pjj}jjdkr#tjd|d |tjdddd  }nPjjdkrJ|j  }td|| 	 ddd  
tj}|jj7 }n)jjdkrj|j  }t|d| 	  
tj}|d8 }n	tjj d	tdj j d
 }t| t|tdt||}jjrj||d}t fdd|D 	 }n1jjrƈj||d}t fdd|D }njjrވj||d}t fdd|D }t j|d_t|dgg
tj}t|j|d}| |d d
 }t |dd |dd !d|dd g_"t |dd |dd !d|dd g_#t||}|$ }j$  t fdd|D }t|j||j%d}tj&|dddf |dddf fdd' }	t |dd |	g_(d_)d_*d_+j"d_"dS )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.
        rD   r   r	   r-   Nleadingrd   zY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.r&   )	in_sigmasru   c                       g | ]} | qS r   _sigma_to_tr<   rs   
log_sigmasrb   r   r   r>   )      z8KDPM2DiscreteScheduler.set_timesteps.<locals>.<listcomp>c                    rz   r   r{   r}   r~   r   r   r>   ,  r   c                    rz   r   r{   r}   r~   r   r   r>   /  r   )rv   g        r   c                    rz   r   r{   )r<   sigma_interpolr~   r   r   r>   C  r   rR   rT   ),ru   rU   rE   rN   nprD   r4   copyarangeroundastyperO   r/   arrayr\   r(   interplenrJ   _convert_to_karrasrK   _convert_to_exponentialrL   _convert_to_betar   
from_numpyra   r   concatenatelerprollr   catrepeat_interleaver`   rr   rT   r.   stackflatten	timestepsrn   r^   r_   )
rb   ru   rv   rE   r   
step_ratior`   rr   timesteps_interpolinterleaved_timestepsr   r~   r   r]      s`   (
*
 

 0&
.z$KDPM2DiscreteScheduler.set_timestepsc                 C   s
   | j d u S N)rn   rf   r   r   r   rq   P  s   
z+KDPM2DiscreteScheduler.state_in_first_orderschedule_timestepsc                 C   s:   |du r| j }||k }t|dkrdnd}||  S )ak  
        Find the index of a given timestep in the timestep schedule.

        Args:
            timestep (`float` or `torch.Tensor`):
                The timestep value to find in the schedule.
            schedule_timesteps (`torch.Tensor`, *optional*):
                The timestep schedule to search in. If `None`, uses `self.timesteps`.

        Returns:
            `int`:
                The index of the timestep in the schedule. For the very first step, returns the second index if
                multiple matches exist to avoid skipping a sigma when starting mid-schedule (e.g., for image-to-image).
        Nr	   r   )r   nonzeror   item)rb   ro   r   indicesposr   r   r   index_for_timestepU  s
   z)KDPM2DiscreteScheduler.index_for_timestepc                 C   s@   | j du rt|tjr|| jj}| || _dS | j	| _dS )z
        Initialize the step index for the scheduler based on the given timestep.

        Args:
            timestep (`float` or `torch.Tensor`):
                The current timestep to initialize the step index from.
        N)
rl   
isinstancer   r   ra   r   rv   r   r^   r_   )rb   ro   r   r   r   rp   t  s
   
z'KDPM2DiscreteScheduler._init_step_indexc                 C   s   t t |d}||ddt jf  }t j|dkddjddj|jd d d}|d }|| }|| }|| ||  }	t |	dd}	d|	 | |	|  }
|
|j}
|
S )a  
        Convert sigma values to corresponding timestep values through interpolation.

        Args:
            sigma (`np.ndarray`):
                The sigma value(s) to convert to timestep(s).
            log_sigmas (`np.ndarray`):
                The logarithm of the sigma schedule used for interpolation.

        Returns:
            `np.ndarray`:
                The interpolated timestep value(s) corresponding to the input sigma(s).
        g|=Nr   )axisr   )re   r	   )	r   r(   maximumnewaxiscumsumargmaxclipshapereshape)rb   rs   r   	log_sigmadistslow_idxhigh_idxlowhighwr$   r   r   r   r|     s   ,z"KDPM2DiscreteScheduler._sigma_to_try   c           
      C   s   t | jdr| jj}nd}t | jdr| jj}nd}|dur |n|d  }|dur,|n|d  }d}tdd|}|d|  }|d|  }||||   | }	|	S )a  
        Construct the noise schedule as proposed in [Elucidating the Design Space of Diffusion-Based Generative
        Models](https://huggingface.co/papers/2206.00364).

        Args:
            in_sigmas (`torch.Tensor`):
                The input sigma values to be converted.
            num_inference_steps (`int`):
                The number of inference steps to generate the noise schedule for.

        Returns:
            `torch.Tensor`:
                The converted sigma values following the Karras noise schedule.
        	sigma_minN	sigma_maxrw   r   g      @r	   )hasattrrU   r   r   r   r   rD   )
rb   ry   ru   r   r   rhorampmin_inv_rhomax_inv_rhor`   r   r   r   r     s   

z)KDPM2DiscreteScheduler._convert_to_karrasc                 C   s   t | jdr| jj}nd}t | jdr| jj}nd}|dur |n|d  }|dur,|n|d  }ttt	|t	||}|S )a  
        Construct an exponential noise schedule.

        Args:
            in_sigmas (`torch.Tensor`):
                The input sigma values to be converted.
            num_inference_steps (`int`):
                The number of inference steps to generate the noise schedule for.

        Returns:
            `torch.Tensor`:
                The converted sigma values following an exponential schedule.
        r   Nr   rw   r   )
r   rU   r   r   r   r   r   rD   r    r(   )rb   ry   ru   r   r   r`   r   r   r   r     s   

 z.KDPM2DiscreteScheduler._convert_to_exponential333333?alphabetac              
      s   t | jdr| jjndt | jdr| jjnddur n|d  dur,n|d  tfdd fddd	tdd	| D D }|S )
a  
        Construct a beta noise schedule as proposed in [Beta Sampling is All You
        Need](https://huggingface.co/papers/2407.12173).

        Args:
            in_sigmas (`torch.Tensor`):
                The input sigma values to be converted.
            num_inference_steps (`int`):
                The number of inference steps to generate the noise schedule for.
            alpha (`float`, *optional*, defaults to `0.6`):
                The alpha parameter for the beta distribution.
            beta (`float`, *optional*, defaults to `0.6`):
                The beta parameter for the beta distribution.

        Returns:
            `torch.Tensor`:
                The converted sigma values following a beta distribution schedule.
        r   Nr   rw   r   c                    s   g | ]
}|    qS r   r   )r<   ppf)r   r   r   r   r>     s    z;KDPM2DiscreteScheduler._convert_to_beta.<locals>.<listcomp>c                    s   g | ]}t jj| qS r   )scipystatsr   r   )r<   ro   )r   r   r   r   r>     s    r	   )r   rU   r   r   r   r   r   rD   )rb   ry   ru   r   r   r`   r   )r   r   r   r   r   r     s    

	z'KDPM2DiscreteScheduler._convert_to_betaTmodel_outputreturn_dictc                 C   s  | j du r
| | | jr$| j| j  }| j| j d  }| j| j d  }n| j| j d  }| j| j  }| j| j  }d}||d  }	| jjdkrT| jrK|	n|}
||
|  }n7| jjdkrw| jr_|	n|}
||
 |
d d d   ||
d d   }n| jjdkrtd	td
| jj d| jr|| |	 }||	 }|| _	n|| | }||	 }| j	}d| _	|  j
d7  _
|||  }|s||fS t||d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_k_dpm_2_discrete.KDPM2DiscreteSchedulerOutput`] or
                tuple.

        Returns:
            [`~schedulers.scheduling_k_dpm_2_discrete.KDPM2DiscreteSchedulerOutput`] or `tuple`:
                If return_dict is `True`, [`~schedulers.scheduling_k_dpm_2_discrete.KDPM2DiscreteSchedulerOutput`] is
                returned, otherwise a tuple is returned where the first element is the sample tensor.
        Nr	   r   rC   v_predictionr   r&   rn   z+prediction_type not implemented yet: samplezprediction_type given as z, must be one of `epsilon`, or `v_prediction`)r   r   )ri   rp   rq   r`   rr   rU   rM   rX   r/   rn   r^   r   )rb   r   ro   rn   r   rs   r   
sigma_nextgamma	sigma_hatsigma_inputr   
derivativedtr   r   r   r   step"  sN   

zKDPM2DiscreteScheduler.steporiginal_samplesnoiser   c                    s
  j j|j|jd}|jjdkr)t|r)jj|jtjd |j|jtjd}nj|j ||j}j	du rF fdd|D }nj
durUj
g|jd  }n	j	g|jd  }||  }t|jt|jk r}|d}t|jt|jk sn|||  }|S )	am  
        Add noise to the original samples according to the noise schedule at the specified timesteps.

        Args:
            original_samples (`torch.Tensor`):
                The original samples to which noise will be added.
            noise (`torch.Tensor`):
                The noise tensor to add to the original samples.
            timesteps (`torch.Tensor`):
                The timesteps at which to add noise, determining the noise level from the schedule.

        Returns:
            `torch.Tensor`:
                The noisy samples with added noise scaled according to the timestep schedule.
        )rv   r.   mpsr-   Nc                    rz   r   )r   )r<   r$   r   rb   r   r   r>     r   z4KDPM2DiscreteScheduler.add_noise.<locals>.<listcomp>r   rw   )r`   ra   rv   r.   typer   is_floating_pointr   r4   rl   ri   r   r   r   	unsqueeze)rb   r   r   r   r`   step_indicesrs   noisy_samplesr   r   r   	add_noise  s"   


z KDPM2DiscreteScheduler.add_noisec                 C   s   | j jS r   )rU   rE   rf   r   r   r   __len__  s   zKDPM2DiscreteScheduler.__len__)r?   r@   rA   rB   NFFFrC   rD   r   )r   )NNr   )r   r   )T)&r   r   r   r   r
   _compatiblesorderr   intfloatstrr   ndarraylistboolrc   propertyrg   ri   rl   rm   r   r   rt   rv   r]   rq   r   rp   r|   r   r   r   r   tupler   r   r   r   r   r   r   r:   g   s    &	
+




!
T

%'#
5


_
0r:   )r   r   )r    dataclassesr   typingr   numpyr   r   configuration_utilsr   r   utilsr   r   scheduling_utilsr
   r   scipy.statsr   r   r   r   r   r9   r:   r   r   r   r   <module>   s0   
4