o
    ۷i                  	   @   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 ddlmZ dd	lmZmZ eG d
d deZ		ddededed dejfddZdd ZG dd dee	ZdS )    N)	dataclass)Literal   )ConfigMixinregister_to_config)
BaseOutput)randn_tensor   )KarrasDiffusionSchedulersSchedulerMixinc                   @   s.   e Zd ZU dZejed< dZejdB ed< dS )DDPMParallelSchedulerOutputaq  
    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   c/home/ubuntu/vllm_env/lib/python3.10/site-packages/diffusers/schedulers/scheduling_ddpm_parallel.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_fnL   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%   Q   s   4
r   c                 S   s   t | d S )Ng      ()r    r   r#   r   r   r   r%   X   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_bar2   s   


"r9   c                 C   s   d|  }t j|dd}| }|d  }|d  }||8 }||||  9 }|d }|dd |dd  }t |dd |g}d| } | 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   cumprodr*   clonecat)r5   alphasalphas_cumprodalphas_bar_sqrtalphas_bar_sqrt_0alphas_bar_sqrt_T
alphas_barr   r   r   rescale_zero_terminal_snrg   s   rG   c                    @   s  e Zd ZdZdd eD ZdZdZe						
										dHde	de
de
ded dejee
 B d
B ded deded dede
de
d e
d!ed" d#e	d$efd%d&ZdId'ejd(e	d
B d)ejfd*d+Z	
	
	
dJd,e	d-eejB d.ee	 d
B fd/d0Z	
	
dKd1e	d2ejd
B ded d
B d)ejfd3d4Zd'ejd)ejfd5d6Z	
	dLd7ejd(e	d'ejd8ejd
B d9ed)eeB fd:d;Zd7ejd.ejd'ejd)ejfd<d=Zd>ejd?ejd.ejd)ejfd@dAZd'ejd?ejd.ejd)ejfdBdCZ dDdE Z!d(e	d)e	ejB fdFdGZ"d
S )MDDPMParallelSchedulera  
    Denoising diffusion probabilistic models (DDPMs) explores the connections between denoising score matching and
    Langevin dynamics sampling.

    [`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__init__`
    function, such as `num_train_timesteps`. They can be accessed via `scheduler.config.num_train_timesteps`.
    [`SchedulerMixin`] provides general loading and saving functionality via the [`SchedulerMixin.save_pretrained`] and
    [`~SchedulerMixin.from_pretrained`] functions.

    For more details, see the original paper: https://huggingface.co/papers/2006.11239

    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`, `squaredcos_cap_v2` or `sigmoid`.
        trained_betas (`np.ndarray`, *optional*):
            Option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc.
        variance_type (`str`, defaults to `"fixed_small"`):
            Options to clip the variance used when adding noise to the denoised sample. Choose from `fixed_small`,
            `fixed_small_log`, `fixed_large`, `fixed_large_log`, `learned` or `learned_range`.
        clip_sample (`bool`, defaults to `True`):
            Option to clip predicted sample for numerical stability.
        prediction_type (`str`, defaults to `"epsilon"`):
            Prediction type of the scheduler function, one of `epsilon` (predicting the noise of the diffusion
            process), `sample` (directly predicting the noisy sample`) or `v_prediction` (see section 2.4
            https://huggingface.co/papers/2210.02303)
        thresholding (`bool`, defaults to `False`):
            Whether to use the "dynamic thresholding" method (introduced by Imagen,
            https://huggingface.co/papers/2205.11487). Note that the thresholding method is unsuitable for latent-space
            diffusion models (such as stable-diffusion).
        dynamic_thresholding_ratio (`float`, defaults to 0.995):
            The ratio for the dynamic thresholding method. Default is `0.995`, the same as Imagen
            (https://huggingface.co/papers/2205.11487). Valid only when `thresholding=True`.
        clip_sample_range (`float`, defaults to 1.0):
            The maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
        sample_max_value (`float`, defaults to 1.0):
            The threshold value for dynamic thresholding. Valid only when `thresholding=True`.
        timestep_spacing (`str`, defaults to `"leading"`):
            The way the timesteps should be scaled. Refer to Table 2. of [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).
    c                 C   s   g | ]}|j qS r   )name).0er   r   r   
<listcomp>   s    z DDPMParallelScheduler.<listcomp>r	   F  -C6?{Gz?linearNfixed_smallTepsilonףp=
?r:   leadingr   num_train_timesteps
beta_startbeta_endbeta_schedule)rP   scaled_linearsquaredcos_cap_v2sigmoidtrained_betasvariance_type)rQ   fixed_small_logfixed_largefixed_large_loglearnedlearned_rangeclip_sampleprediction_type)rR   samplev_predictionthresholdingdynamic_thresholding_ratioclip_sample_rangesample_max_valuetimestep_spacing)linspacerT   trailingsteps_offsetrescale_betas_zero_snrc                 C   sP  |d urt j|t jd| _n^|dkrt j|||t jd| _nN|dkr4t j|d |d |t jdd | _n8|dkr>t|| _n.|dkrJt|dd| _n"|d	krbt d
d|}t |||  | | _n
t| d| j |rtt	| j| _d| j | _
t j| j
dd| _t d| _d| _d| _d | _t td|d d d  | _|| _d S )Nr-   rP   rY   r&   r   rZ   r   )r   r[   i   z is not implemented for r:   r   r;   Fr=   )r   r3   r4   r5   rl   r9   r[   NotImplementedError	__class__rG   rA   r>   rB   oneinit_noise_sigmacustom_timestepsnum_inference_steps
from_numpynparangecopy	timestepsr]   )selfrU   rV   rW   rX   r\   r]   rc   rd   rg   rh   ri   rj   rk   rn   ro   r5   r   r   r   __init__   s@   	"
zDDPMParallelScheduler.__init__re   timestepr   c                 C   s   |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|   re   r~   r   r   r   scale_model_input  s   z'DDPMParallelScheduler.scale_model_inputrv   devicer{   c                 C   s  |dur|durt d|durFtdt|D ]}|| ||d  kr't dq|d | jjkr:t d| jj dtj|tjd}d	| _n|| jjkr^t d
| d| jj d| jj d|| _	d| _| jj
dkrtd| jjd | ddd  tj}nU| jj
dkr| jj| j	 }td||  ddd  tj}|| jj7 }n,| jj
dkr| jj| j	 }tt| jjd| tj}|d8 }n	t | jj
 dt||| _dS )a8  
        Sets the discrete timesteps used for the diffusion chain (to be run before inference).

        Args:
            num_inference_steps (`int`, *optional*):
                The number of diffusion steps used when generating samples with a pre-trained model. If used,
                `timesteps` must be `None`.
            device (`str` or `torch.device`, *optional*):
                The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
            timesteps (`list[int]`, *optional*):
                Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
                timestep spacing strategy of equal spacing between timesteps is used. If `timesteps` is passed,
                `num_inference_steps` must be `None`.

        NzACan only pass one of `num_inference_steps` or `custom_timesteps`.r	   z/`custom_timesteps` must be in descending order.r   z=`timesteps` must start before `self.config.train_timesteps`: .r-   Tz`num_inference_steps`: z6 cannot be larger than `self.config.train_timesteps`: zG as the unet model trained with this scheduler can only handle maximal z timesteps.Frl   r=   rT   rm   zY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.)r/   r0   lenconfigrU   rx   arrayint64ru   rv   rk   rl   roundrz   astypery   rn   r   rw   tor{   )r|   rv   r   r{   r6   
step_ratior   r   r   set_timesteps!  sT   *"
z#DDPMParallelScheduler.set_timestepsr$   predicted_variancec                 C   s  |  |}| j| }|dkr| j| n| j}d||  }d| d|  | }tj|dd}|du r5| jj}|dkr=|}|S |dkrOt|}td| }|S |d	krW|}|S |d
krbt|}|S |dkrh|S |dkrt|}	t|}
|d d }||
 d| |	  }|S )a  
        Compute the variance for a given timestep according to the specified variance type.

        Args:
            t (`int`):
                The current timestep.
            predicted_variance (`torch.Tensor`, *optional*):
                The predicted variance from the model. Used only when `variance_type` is `"learned"` or
                `"learned_range"`.
            variance_type (`"fixed_small"`, `"fixed_small_log"`, `"fixed_large"`, `"fixed_large_log"`, `"learned"`, or `"learned_range"`, *optional*):
                The type of variance to compute. If `None`, uses the variance type specified in the scheduler
                configuration.

        Returns:
            `torch.Tensor`:
                The computed variance.
        r   r	   g#B;r2   NrQ   r^   r&   r_   r`   ra   rb   r   )	previous_timesteprB   rs   r   clampr   r]   r(   r   )r|   r$   r   r]   prev_talpha_prod_talpha_prod_t_prevcurrent_beta_tvariancemin_logmax_logfracr   r   r   _get_variancel  s:   



	

z#DDPMParallelScheduler._get_variancec                 C   s   |j }|j^}}}|tjtjfvr| }|||t| }|	 }tj
|| jjdd}tj|d| jjd}|d}t|| || }|j||g|R  }||}|S )az  
        Apply dynamic thresholding to the predicted sample.

        "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
        prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
        s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
        pixels from saturation at each step. We find that dynamic thresholding results in significantly better
        photorealism as well as better image-text alignment, especially when using very large guidance weights."

        https://huggingface.co/papers/2205.11487

        Args:
            sample (`torch.Tensor`):
                The predicted sample to be thresholded.

        Returns:
            `torch.Tensor`:
                The thresholded sample.
        r	   r;   )r2   max)r.   shaper   r4   float64floatreshaperx   prodabsquantiler   rh   r   rj   	unsqueezer   )r|   re   r.   
batch_sizechannelsremaining_dims
abs_samplesr   r   r   _threshold_sample  s   


z'DDPMParallelScheduler._threshold_samplemodel_output	generatorreturn_dictc                 C   s  |}|  |}|jd |jd d kr&| jdv r&tj||jd dd\}}nd}| j| }	|dkr6| j| n| j}
d|	 }d|
 }|	|
 }d| }| jjdkr\||d |  |	d  }n&| jjd	kre|}n| jjd
krx|	d | |d |  }n
t	d| jj d| jj
r| |}n| jjr|| jj | jj}|
d | | }|d | | }|| ||  }d}|dkr|j}t|j|||jd}| jdkr| j||d| }n!| jdkr| j||d}td| | }n| j||dd | }|| }|s||fS t||dS )a  
        Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
        process from the learned model outputs (most often the predicted noise).

        Args:
            model_output (`torch.Tensor`): direct output from learned diffusion model.
            timestep (`int`): current discrete timestep in the diffusion chain.
            sample (`torch.Tensor`):
                current instance of sample being created by diffusion process.
            generator (`torch.Generator`, *optional*):
                Random number generator.
            return_dict (`bool`): option for returning tuple rather than DDPMParallelSchedulerOutput class

        Returns:
            [`~schedulers.scheduling_utils.DDPMParallelSchedulerOutput`] or `tuple`:
            [`~schedulers.scheduling_utils.DDPMParallelSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`.
            When returning a tuple, the first element is the sample tensor.

        r	   r   ra   rb   r;   Nr   rR   r&   re   rf   prediction_type given as zM must be one of `epsilon`, `sample` or `v_prediction`  for the DDPMScheduler.)r   r   r.   r^   )r   rb   )r   r   )r   r   r]   r   splitrB   rs   r   rd   r/   rg   r   rc   r   ri   r   r   r.   r   r   r   )r|   r   r~   re   r   r   r$   r   r   r   r   beta_prod_tbeta_prod_t_prevcurrent_alpha_tr   r   pred_original_sample_coeffcurrent_sample_coeffpred_prev_sampler   r   variance_noiser   r   r   step  sd   
"


zDDPMParallelScheduler.stepc                 C   s  |}| j r| j n| jj}|| jj|  }|jdgdg|jd  R  }|jdgdg|jd  R  }|jd |jd d krQ| jdv rQtj||jd dd\}}n	 | j	
|j| _	| j	| }| j	tj|dd }	td|	|dk < d| }
d|	 }||	 }d| }| jjd	kr||
d
 |  |d
  }n&| jjdkr|}n| jjdkr|d
 | |
d
 |  }n
td| jj d| jjr| |}n| jjr|| jj | jj}|	d
 | |
 }|d
 | |
 }|| ||  }|S )a  
        Batched version of the `step` function, to be able to reverse the SDE for multiple samples/timesteps at once.
        Also, does not add any noise to the predicted sample, which is necessary for parallel sampling where the noise
        is pre-sampled by the pipeline.

        Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
        process from the learned model outputs (most often the predicted noise).

        Args:
            model_output (`torch.Tensor`): direct output from learned diffusion model.
            timesteps (`torch.Tensor`):
                Current discrete timesteps in the diffusion chain. This is a tensor of integers.
            sample (`torch.Tensor`):
                current instance of sample being created by diffusion process.

        Returns:
            `torch.Tensor`: sample tensor at previous timestep.
        r=   r	   r   r   r;   r   r   r:   rR   r&   re   rf   r   zU must be one of `epsilon`, `sample` or `v_prediction`  for the DDPMParallelScheduler.)rv   r   rU   viewndimr   r]   r   r   rB   r   r   clipr3   rd   r/   rg   r   rc   r   ri   )r|   r   r{   re   r$   rv   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   batch_step_no_noiseH  sF   "
z)DDPMParallelScheduler.batch_step_no_noiseoriginal_samplesnoisec                 C   s   | j j|jd| _ | j j|jd}||j}|| d }| }t|jt|jk r:|d}t|jt|jk s+d||  d }| }t|jt|jk r_|d}t|jt|jk sP|| ||  }|S )a2  
        Add noise to the original samples according to the noise magnitude at each timestep (this is the forward
        diffusion process).

        Args:
            original_samples (`torch.Tensor`):
                The original samples to which noise will be added.
            noise (`torch.Tensor`):
                The noise to add to the samples.
            timesteps (`torch.IntTensor`):
                The timesteps indicating the noise level for each sample.

        Returns:
            `torch.Tensor`:
                The noisy samples.
        r   r-   r&   r=   r	   rB   r   r   r.   flattenr   r   r   )r|   r   r   r{   rB   sqrt_alpha_prodsqrt_one_minus_alpha_prodnoisy_samplesr   r   r   	add_noise  s   

zDDPMParallelScheduler.add_noisec                 C   s   | j j|jd| _ | j j|jd}||j}|| d }| }t|jt|jk r:|d}t|jt|jk s+d||  d }| }t|jt|jk r_|d}t|jt|jk sP|| ||  }|S )a  
        Compute the velocity prediction from the sample and noise according to the velocity formula.

        Args:
            sample (`torch.Tensor`):
                The input sample.
            noise (`torch.Tensor`):
                The noise tensor.
            timesteps (`torch.IntTensor`):
                The timesteps for velocity computation.

        Returns:
            `torch.Tensor`:
                The computed velocity.
        r   r-   r&   r=   r	   r   )r|   re   r   r{   rB   r   r   velocityr   r   r   get_velocity  s   

z"DDPMParallelScheduler.get_velocityc                 C   s   | j jS N)r   rU   )r|   r   r   r   __len__  s   zDDPMParallelScheduler.__len__c                 C   sf   | j s| jr-| j|kjddd d }|| jjd d kr$td}|S | j|d  }|S |d }|S )z
        Compute the previous timestep in the diffusion chain.

        Args:
            timestep (`int`):
                The current timestep.

        Returns:
            `int` or `torch.Tensor`:
                The previous timestep.
        T)as_tupler   r	   r=   )ru   rv   r{   nonzeror   r   r3   )r|   r~   indexr   r   r   r   r     s   
z'DDPMParallelScheduler.previous_timestep)rM   rN   rO   rP   NrQ   TrR   FrS   r:   r:   rT   r   Fr   )NNN)NN)NT)#r   r   r   r   r
   _compatiblesorder_is_ode_schedulerr   intr   r   rx   ndarraylistboolr}   r   r   r   strr   r   r   r   	Generatorr   tupler   r   	IntTensorr   r   r   r   r   r   r   r   rH      s    6 G

N	
G0
j
T
"+"rH   )r   r   )r    dataclassesr   typingr   numpyrx   r   configuration_utilsr   r   utilsr   utils.torch_utilsr   scheduling_utilsr
   r   r   r   r   r   r9   rG   rH   r   r   r   r   <module>   s0   
5$