
    bin{                         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 ddlmZ dd	lmZmZ e G d
 de             Z	 	 ddZd Z G d dee      Zy)    N)	dataclass)ListOptionalTupleUnion   )ConfigMixinregister_to_config)
BaseOutput)randn_tensor   )KarrasDiffusionSchedulersSchedulerMixinc                   X    e Zd ZU dZej
                  ed<   dZeej
                     ed<   y)DDIMParallelSchedulerOutputaq  
    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_ddim_parallel.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                 (   d| z
  }t        j                  |d      }|j                         }|d   j                         }|d   j                         }||z  }||||z
  z  z  }|dz  }|dd |dd z  }t        j                  |dd |g      }d|z
  } | S )a.  
    Rescales betas to have zero terminal SNR Based on https://huggingface.co/papers/2305.08891 (Algorithm 1)


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

    Returns:
        `torch.Tensor`: rescaled betas with zero terminal SNR
          ?r   dimr   r   N)r   cumprodsqrtclonecat)r4   alphasalphas_cumprodalphas_bar_sqrtalphas_bar_sqrt_0alphas_bar_sqrt_T
alphas_bars          r   rescale_zero_terminal_snrrH   `   s     5[F]]6q1N$))+O (*002'+113 ((O (,=@Q,QRRO !!#J^j"o-FYY
1Q01FJELr   c                    l   e Zd ZdZeD  cg c]  }|j
                   c}} Zd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dededededefd       Zd-dej*                  dee
   dej*                  fdZd-dZd Zdej*                  dej*                  fdZd-de
deeej4                  f   fdZ	 	 	 	 	 d.dej*                  de
dej*                  d ed!ed"eej*                     d#edeeef   fd$Z	 	 d/dej*                  d%ee
   dej*                  d ed!edej*                  fd&Zd'ej*                  d(ej*                  d%ej@                  dej*                  fd)Z!dej*                  d(ej*                  d%ej@                  dej*                  fd*Z"d+ Z#yc c}} w )0DDIMParallelSchedulera  
    Denoising diffusion implicit models is a scheduler that extends the denoising procedure introduced in denoising
    diffusion probabilistic models (DDPMs) with non-Markovian guidance.

    [`~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/2010.02502

    Args:
        num_train_timesteps (`int`): number of diffusion steps used to train the model.
        beta_start (`float`): the starting `beta` value of inference.
        beta_end (`float`): the final `beta` value.
        beta_schedule (`str`):
            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):
            option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc.
        clip_sample (`bool`, default `True`):
            option to clip predicted sample for numerical stability.
        clip_sample_range (`float`, default `1.0`):
            the maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
        set_alpha_to_one (`bool`, default `True`):
            each diffusion step uses the value of alphas product 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 value of alpha at step 0.
        steps_offset (`int`, default `0`):
            An offset added to the inference steps, as required by some model families.
        prediction_type (`str`, default `epsilon`, optional):
            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://imagen.research.google/video/paper.pdf)
        thresholding (`bool`, default `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`, default `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`.
        sample_max_value (`float`, default `1.0`):
            the threshold value for dynamic thresholding. Valid only when `thresholding=True`.
        timestep_spacing (`str`, default `"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.
        rescale_betas_zero_snr (`bool`, default `False`):
            whether to rescale the betas to have zero terminal SNR (proposed by
            https://huggingface.co/papers/2305.08891). This can enable the model to generate very bright and dark
            samples instead of limiting it to samples with medium brightness. Loosely related to
            [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
    r   TNnum_train_timesteps
beta_startbeta_endbeta_scheduletrained_betasclip_sampleset_alpha_to_onesteps_offsetprediction_typethresholdingdynamic_thresholding_ratioclip_sample_rangesample_max_valuetimestep_spacingrescale_betas_zero_snrc                 t   |+t        j                  |t         j                        | _        n|dk(  r-t        j                  |||t         j                        | _        nk|dk(  r6t        j                  |dz  |dz  |t         j                        dz  | _        n0|dk(  rt        |      | _        nt        | d| j                         |rt        | j                        | _        d| j                  z
  | _	        t        j                  | j                  d	
      | _        |rt        j                  d      n| j                  d	   | _        d| _        d | _        t        j                  t!        j"                  d	|      d d d   j%                         j'                  t         j(                              | _        y )Nr)   linearscaled_linear      ?r   squaredcos_cap_v2z is not implemented for r:   r   r;   r=   )r   r/   r0   r4   linspacer8   NotImplementedError	__class__rH   rB   r>   rC   final_alpha_cumprodinit_noise_sigmanum_inference_steps
from_numpynparangecopyastypeint64	timesteps)selfrK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   s                   r   __init__zDDIMParallelScheduler.__init__   se   ( $m5==IDJh&
H>QY^YfYfgDJo-
C3H[chcpcpquvvDJ11,-@ADJ%7OPTP^P^O_&`aa "24::>DJDJJ&#mmDKKQ? 9I5<<#4dNaNabcNd  !$ $( ))"))A7J*KDbD*Q*V*V*X*_*_`b`h`h*ijr   sampletimestepreturnc                     |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   )rl   rn   ro   s      r   scale_model_inputz'DDIMParallelScheduler.scale_model_input   s	     r   c                     |&|| j                   j                  | j                  z  z
  }| j                  |   }|dk\  r| j                  |   n| j                  }d|z
  }d|z
  }||z  d||z  z
  z  }|S )Nr   r   )configrK   rd   rC   rb   )rl   ro   prev_timestepalpha_prod_talpha_prod_t_prevbeta_prod_tbeta_prod_t_prevvariances           r   _get_variancez#DDIMParallelScheduler._get_variance  s     $t{{'F'F$JbJb'bbM**84BOSTBTD//>Z^ZrZr,&00${2q<J[;[7[\r   c                     | j                   |   }| j                   t        j                  |d         }t        j                  d      ||dk  <   d|z
  }d|z
  }||z  d||z  z
  z  }|S )Nr   r.   r:   r   )rC   r   clipr/   )rl   r%   prev_trv   rw   rx   ry   rz   s           r   _batch_get_variancez)DDIMParallelScheduler._batch_get_variance  s{    **1- //

6q0IJ(-S(9&1*%,&00${2q<J[;[7[\r   c                 b   |j                   }|j                  ^}}}|t        j                  t        j                  fvr|j                         }|j                  ||t        j                  |      z        }|j                         }t        j                  || j                  j                  d      }t        j                  |d| j                  j                        }|j                  d      }t        j                  || |      |z  } |j                  ||g| }|j!                  |      }|S )a{  
        "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
        r   r;   )r.   max)r*   shaper   r0   float64floatreshaperf   prodabsquantilert   rU   clamprW   	unsqueezeto)rl   rn   r*   
batch_sizechannelsremaining_dims
abs_sampless           r   _threshold_samplez'DDIMParallelScheduler._threshold_sample  s     06-
H~66\\^F 
Hrww~7N,NOZZ\
NN:t{{'M'MSTUKK1$++66
 KKNVaR+a/
HF~F5!r   rd   devicec           	         || j                   j                  kD  r=t        d| d| j                   j                   d| j                   j                   d      || _        | j                   j                  dk(  rot        j                  d| j                   j                  dz
  |      j                         ddd	   j                         j                  t
        j                        }nn| j                   j                  d
k(  r| j                   j                  | j                  z  }t        j                  d|      |z  j                         ddd	   j                         j                  t
        j                        }|| j                   j                  z  }n| j                   j                  dk(  r| j                   j                  | j                  z  }t        j                  t        j                  | j                   j                  d|             j                  t
        j                        }|dz  }n"t        | j                   j                   d      t        j                  |      j                  |      | _        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.
        z`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.r_   r   r   Nr=   leadingtrailingzM is not supported. Please make sure to choose one of 'leading' or 'trailing'.)rt   rK   r+   rd   rX   rf   r_   roundrh   ri   rj   rg   rR   r   re   r   rk   )rl   rd   r   rk   
step_ratios        r   set_timestepsz#DDIMParallelScheduler.set_timesteps@  s    !@!@@)*=)> ?KK334 5 KK;;<KI  $7  ;;'':5At{{>>BDWX2!	  [[))Y688D<T<TTJ 1&9:ZGNNPQUSUQUV[[]ddegememnI111I[[))Z7884;S;SSJ 4;;+J+JAPZ{![\ccdfdldlmINI;;//00}~  )))477?r   model_outputetause_clipped_model_outputvariance_noisereturn_dictc	                    | j                   t        d      || j                  j                  | j                   z  z
  }	| j                  |   }
|	dk\  r| j                  |	   n| j
                  }d|
z
  }| j                  j                  dk(  r||dz  |z  z
  |
dz  z  }|}n| j                  j                  dk(  r|}||
dz  |z  z
  |dz  z  }n_| j                  j                  dk(  r#|
dz  |z  |dz  |z  z
  }|
dz  |z  |dz  |z  z   }n#t        d| j                  j                   d	      | j                  j                  r| j                  |      }nQ| j                  j                  r;|j                  | j                  j                   | j                  j                        }| j                  ||	      }||dz  z  }|r||
dz  |z  z
  |dz  z  }d|z
  |d
z  z
  dz  |z  }|dz  |z  |z   }|dkD  rH||t        d      |-t        |j                  ||j                  |j                         }||z  }||z   }|s||fS t#        ||      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.
            eta (`float`): weight of noise for added noise in diffusion step.
            use_clipped_model_output (`bool`): if `True`, compute "corrected" `model_output` from the clipped
                predicted original sample. Necessary because predicted original sample is clipped to [-1, 1] when
                `self.config.clip_sample` is `True`. If no clipping has happened, "corrected" `model_output` would
                coincide with the one provided as input and `use_clipped_model_output` will have not effect.
            generator: random number generator.
            variance_noise (`torch.Tensor`): instead of generating noise for the variance using `generator`, we
                can directly provide the noise for the variance itself. This is useful for methods such as
                CycleDiffusion. (https://huggingface.co/papers/2210.05559)
            return_dict (`bool`): option for returning tuple rather than DDIMParallelSchedulerOutput class

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

        aNumber of inference steps is 'None', you need to run 'set_timesteps' after creating the schedulerr   r   epsilonr]   rn   v_predictionprediction_type given as 6 must be one of `epsilon`, `sample`, or `v_prediction`r   zyCannot pass both generator and variance_noise. Please make sure that either `generator` or `variance_noise` stays `None`.)	generatorr   r*   )r   r   )rd   r+   rt   rK   rC   rb   rS   rT   r   rP   r   rV   r{   r   r   r   r*   r   )rl   r   ro   rn   r   r   r   r   r   ru   rv   rw   rx   r   pred_epsilonrz   	std_dev_tpred_sample_directionr   s                      r   stepzDDIMParallelScheduler.stepm  s   J ##+s   !4;;#B#BdF^F^#^^ **84BOSTBTD//>Z^ZrZr,& ;;&&)3$*[S-AL-P$PT`ehTi#i 'L[[((H4#/ "\c%:=Q%QQU`ehUiiL[[((N:$0#$5#?;PSCSWcBc#c (#-=cAQU[@[[L+DKK,G,G+H I" "  ;;###'#9#9:N#O [[$$#7#=#=...0M0M$  %%h>(s++	#"\c%:=Q%QQU`ehUiiL "#%6!6A!E3 OR^ ^ (C03GGJ__7)i.C 6 
 %!- &&)LDWDW_k_q_q" !>1H%0K$ 
 +{Ymnnr   rk   c                    | j                   t        d      |dk(  sJ |}|| j                  j                  | j                   z  z
  } |j                  dgdg|j
                  dz
  z   } |j                  dgdg|j
                  dz
  z   }| j                  j                  |j                        | _        | j                  j                  |j                        | _	        | j                  |   }| j                  t        j                  |d         }	t        j                  d      |	|dk  <   d|z
  }
| j                  j                  dk(  r||
d	z  |z  z
  |d	z  z  }|}n| j                  j                  d
k(  r|}||d	z  |z  z
  |
d	z  z  }n_| j                  j                  dk(  r#|d	z  |z  |
d	z  |z  z
  }|d	z  |z  |
d	z  |z  z   }n#t        d| j                  j                   d      | j                  j                  r| j                  |      }nQ| j                  j                   r;|j#                  | j                  j$                   | j                  j$                        } | j'                  ||      j                  |j                        j                  |	j(                   }||d	z  z  }|r||d	z  |z  z
  |
d	z  z  }d|	z
  |dz  z
  d	z  |z  }|	d	z  |z  |z   }|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 (`List[int]`):
                current discrete timesteps in the diffusion chain. This is now a list of integers.
            sample (`torch.Tensor`):
                current instance of sample being created by diffusion process.
            eta (`float`): weight of noise for added noise in diffusion step.
            use_clipped_model_output (`bool`): if `True`, compute "corrected" `model_output` from the clipped
                predicted original sample. Necessary because predicted original sample is clipped to [-1, 1] when
                `self.config.clip_sample` is `True`. If no clipping has happened, "corrected" `model_output` would
                coincide with the one provided as input and `use_clipped_model_output` will have not effect.

        Returns:
            `torch.Tensor`: sample tensor at previous timestep.

        r           r=   r   r   r}   r:   r   r]   rn   r   r   r   r   )rd   r+   rt   rK   viewndimrC   r   r   rb   r   r~   r/   rS   rT   r   rP   r   rV   r   r   )rl   r   rk   rn   r   r   r%   r   rv   rw   rx   r   r   rz   r   r   r   s                    r   batch_step_no_noisez)DDIMParallelScheduler.batch_step_no_noise  s(   @ ##+s  czz T[[448P8PPPAFF28! 1 1A 568RBA3,*;*;a*?#@B #1144\5H5HI#'#;#;#>#>|?R?R#S **1- //

6q0IJ(-S(9&1*%,& ;;&&)3$*[S-AL-P$PT`ehTi#i 'L[[((H4#/ "\c%:=Q%QQU`ehUiiL[[((N:$0#$5#?;PSCSWcBc#c (#-=cAQU[@[[L+DKK,G,G+H I" "  ;;###'#9#9:N#O [[$$#7#=#=...0M0M$  T4++Av699,:M:MNSSUfUlUlm(s++	#"\c%:=Q%QQU`ehUiiL "#%6!6A!E3 OR^ ^ (C03GGJ__r   original_samplesnoisec                    | 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)r   r)   r]   r=   r   rC   r   r   r*   flattenlenr   r   )rl   r   r   rk   rC   sqrt_alpha_prodsqrt_one_minus_alpha_prodnoisy_sampless           r   	add_noisezDDIMParallelScheduler.add_noiseW  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                  |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 r   r   )rl   rn   r   rk   rC   r   r   velocitys           r   get_velocityz"DDIMParallelScheduler.get_velocityr  sG   "1144FMM4J,,//fll/CLL/	(3s:)113/''(3v||+<<-77;O /''(3v||+<< &'	)B%Bs$J!$=$E$E$G!+112S5FF(A(K(KB(O% +112S5FF #U*-F-OOr   c                 .    | j                   j                  S N)rt   rK   )rl   s    r   __len__zDDIMParallelScheduler.__len__  s    {{...r   )i  g-C6?g{Gz?r[   NTTr   r   Fgףp=
?r:   r:   r   Fr   )r   FNNT)r   F)$r   r   r   r   r   name_compatiblesorder_is_ode_schedulerr
   intr   strr   r   rf   ndarrayr   boolrm   r   r   rr   r{   r   r   r   r   r   r   r   r   	IntTensorr   r   r   ).0es   00r   rJ   rJ      s
   3j %>>qAFF>LE $("%BF !%(",1#&"% )',!1k 1k 1k 	1k
 1k  bjj$u+&= >?1k 1k 1k 1k 1k 1k %*1k !1k  1k 1k  !%!1k 1kh  Y^YeYe "	  D+@ +@eCDU>V +@d ).15 {oll{o {o 	{o
 {o #'{o !.{o {o 
*E1	2{oD ).jllj 9j 	j
 j #'j 
jZ,, || ??	
 
65<<  QVQ`Q` ejeqeq &/W ?s   F0rJ   )g+?r   )r!   dataclassesr   typingr   r   r   r   numpyrf   r   configuration_utilsr	   r
   utilsr   utils.torch_utilsr   scheduling_utilsr   r   r   r8   rH   rJ   r   r   r   <module>r      sd   $  ! / /   A  , G 8* 8 8( !)4Z!HB/NK B/r   