
    ihq              	       $   d dl Z d dlmZ d dlmZ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ededed   dej2                  fdZdej2                  dej2                  fdZ G d dee      Zy)    N)	dataclass)ListLiteral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)DDPMSchedulerOutputaq  
    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        n/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/schedulers/scheduling_ddpm.pyr   r      s'    
 37(5<<07r   r   num_diffusion_timestepsmax_betaalpha_transform_type)cosineexpreturnc           
      $   |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 )aB  
    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 (`"cosine"` or `"exp"`, defaults to `"cosine"`):
            The type of noise schedule for `alpha_bar`. Choose from `cosine` or `exp`.

    Returns:
        `torch.Tensor`:
            The betas used by the scheduler to step the model outputs.
    r"   c                 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_fnJ   s-    88QY%/$''9A=>!CCr   r#   c                 2    t        j                  | dz        S )Ng      ()r'   r#   r*   s    r   r,   z)betas_for_alpha_bar.<locals>.alpha_bar_fnO   s    88AI&&r   z"Unsupported alpha_transform_type: r   dtype)
ValueErrorrangeappendminr   tensorfloat32)r   r    r!   r,   betasit1t2s           r   betas_for_alpha_barr:   0   s    0 x'	D 
	&	' =>R=STUUE*+ M((!e..S\"-R0@@@(KLM <<U]]33r   r6   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)r6   alphasalphas_cumprodalphas_bar_sqrtalphas_bar_sqrt_0alphas_bar_sqrt_T
alphas_bars          r   rescale_zero_terminal_snrrJ   ^   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                       e Zd ZdZeD  cg c]  }|j
                   c}} ZdZe	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d.de	de
de
ded   d	eeej                  ee
   f      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       Zd/dej(                  dee	   dej(                  fdZ	 	 	 d0dee	   deeej.                  f   deee	      fdZ	 	 d1d e	d!eej(                     d
eed      dej(                  fd"Zdej(                  dej(                  fd#Z	 	 d2d$ej(                  de	dej(                  d%eej6                     d&edeeef   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e	fd,Z"de	de	fd-Z#yc c}} w )3DDPMSchedulera  
    `DDPMScheduler` explores the connections between denoising score matching and Langevin dynamics sampling.

    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 (`"linear"`, `"scaled_linear"`, `"squaredcos_cap_v2"`, or `"sigmoid"`, defaults to `"linear"`):
            The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model.
        trained_betas (`np.ndarray`, *optional*):
            An array of betas to pass directly to the constructor without using `beta_start` and `beta_end`.
        variance_type (`"fixed_small"`, `"fixed_small_log"`, `"fixed_large"`, `"fixed_large_log"`, `"learned"`, or `"learned_range"`, defaults to `"fixed_small"`):
            Clip the variance when adding noise to the denoised sample.
        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`.
        prediction_type (`"epsilon"`, `"sample"`, or `"v_prediction"`, defaults to `"epsilon"`):
            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).
        thresholding (`bool`, defaults to `False`):
            Whether to use the "dynamic thresholding" method. This 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. Valid only when `thresholding=True`.
        sample_max_value (`float`, defaults to `1.0`):
            The threshold value for dynamic thresholding. Valid only when `thresholding=True`.
        timestep_spacing (`"linspace"`, `"leading"`, or `"trailing"`, defaults to `"leading"`):
            The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
            Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
        steps_offset (`int`, defaults to `0`):
            An offset added to the inference steps, as required by some model families.
        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).
    r   Nnum_train_timesteps
beta_startbeta_endbeta_schedule)linearscaled_linearsquaredcos_cap_v2sigmoidtrained_betasvariance_type)fixed_smallfixed_small_logfixed_largefixed_large_loglearnedlearned_rangeclip_sampleprediction_type)epsilonsamplev_predictionthresholdingdynamic_thresholding_ratioclip_sample_rangesample_max_valuetimestep_spacing)linspaceleadingtrailingsteps_offsetrescale_betas_zero_snrc                    |+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  | _        np|dk(  rt        |      | _        nZ|dk(  r;t        j                  dd	|      }t        j                  |      ||z
  z  |z   | _        nt        | d
| j                         |rt        | j                        | _        d| j                  z
  | _
        t        j                  | j                  d      | _        t        j                  d      | _        d| _        d| _        d | _        t        j"                  t%        j&                  d|      d d d   j)                               | _        || _        y )Nr.   rQ   rR         ?r	   rS   rT   i   z is not implemented for r<   r   r=   Fr?   )r   r4   r5   r6   rg   r:   rT   NotImplementedError	__class__rJ   rD   r@   rE   oneinit_noise_sigmacustom_timestepsnum_inference_steps
from_numpynparangecopy	timestepsrV   )selfrM   rN   rO   rP   rU   rV   r]   r^   rb   rc   rd   re   rf   rj   rk   r6   s                    r   __init__zDDPMScheduler.__init__   s   * $m5==IDJh&
H>QY^YfYfgDJo-
C3H[chcpcpquvvDJ11,-@ADJi'NN2q*=>Eu-J1FG*TDJ%7OPTP^P^O_&`aa "24::>DJDJJ&#mmDKKQ?<<$ !$ !&#' ))"))A7J*KDbD*Q*V*V*XY*r   r`   timestepr$   c                     |S )a  
        Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
        current timestep.

        Args:
            sample (`torch.Tensor`):
                The input sample.
            timestep (`int`, *optional*):
                The current timestep in the diffusion chain.

        Returns:
            `torch.Tensor`:
                A scaled input sample.
        r   )rz   r`   r|   s      r   scale_model_inputzDDPMScheduler.scale_model_input   s	     r   rt   devicery   c           	      l   ||t        d      |t        dt        |            D ]  }||   ||dz
     k\  st        d       |d   | j                  j                  k\  r#t        d| j                  j                   d      t        j                  |t
        j                        }d	| _        nZ|| j                  j                  kD  r=t        d
| d| j                  j                   d| j                  j                   d      || _	        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. 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.Frg   r?   rh   ri   zY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.)r0   r1   lenconfigrM   rv   arrayint64rs   rt   rf   rg   roundrx   astyperw   rj   r   ru   tory   )rz   rt   r   ry   r7   
step_ratios         r   set_timestepszDDPMScheduler.set_timesteps   s   * *y/D`aa 1c)n- XQ<9QU#33$%VWWX |t{{>>> STXT_T_TsTsSttuv  "((;I$(D!"T[[%D%DD -.A-B C778 9  $ ? ?@M  (;D$$)D! {{++z9KK4;;#B#BQ#FH[\UWTrT#TVVBHH%	  --:![[<<@X@XX
  YYq*=>KRRTUYWYUYZ__ahhikiqiqr	T[[555	--;![[<<t?W?WW
 HHRYYt{{/N/NPQT^S^%_`gghjhphpq	Q	 {{334  5N  O  )))477?r   r+   predicted_variancec                 l   | j                  |      }| j                  |   }|dk\  r| j                  |   n| j                  }d||z  z
  }d|z
  d|z
  z  |z  }t        j                  |d      }|| j
                  j                  }|dk(  r|}|S |dk(  r/t        j                  |      }t        j                  d|z        }|S |dk(  r|}|S |d	k(  rt        j                  |      }|S |d
k(  r|S |dk(  r@t        j                  |      }	t        j                  |      }
|dz   dz  }||
z  d|z
  |	z  z   }|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;)r3   rW   rX   rm   rY   rZ   r[   r\   r	   )	previous_timesteprE   rq   r   clampr   rV   logr#   )rz   r+   r   rV   prev_talpha_prod_talpha_prod_t_prevcurrent_beta_tvariancemin_logmax_logfracs               r   _get_variancezDDPMScheduler._get_varianceF  sq   2 ''***1-;AQ;D//7DHH\,===
 ))a,.>?.P ;;xU3  KK55M M)H$ ! //yy*Hyyx0H  m+%H  //yy0H  i'%%o-ii)Gii/G&*a/Dg~TW(<<H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 )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=   )r3   max)r/   shaper   r5   float64floatreshaperv   prodabsquantiler   rc   r   re   	unsqueezer   )rz   r`   r/   
batch_sizechannelsremaining_dims
abs_sampless           r   _threshold_samplezDDPMScheduler._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   model_output	generatorreturn_dictc                 X   |}| j                  |      }|j                  d   |j                  d   dz  k(  r7| j                  dv r)t        j                  ||j                  d   d      \  }}nd}| j
                  |   }	|dk\  r| j
                  |   n| j                  }
d|	z
  }d|
z
  }|	|
z  }d|z
  }| j                  j                  dk(  r||dz  |z  z
  |	dz  z  }nj| j                  j                  d	k(  r|}nN| j                  j                  d
k(  r|	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                        }|
dz  |z  |z  }|dz  |z  |z  }||z  ||z  z   }d}|dkD  r|j                  }t!        |j                  |||j"                        }| j                  dk(  r| j%                  ||      |z  }nW| j                  dk(  r/| j%                  ||      }t        j&                  d|z        |z  }n| j%                  ||      dz  |z  }||z   }|s||fS t)        ||      S )aI  
        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 (`int`):
                The current discrete timestep in the diffusion chain.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.
            generator (`torch.Generator`, *optional*):
                A random number generator.
            return_dict (`bool`, defaults to `True`):
                Whether or not to return a [`~schedulers.scheduling_ddpm.DDPMSchedulerOutput`] or `tuple`.

        Returns:
            [`~schedulers.scheduling_ddpm.DDPMSchedulerOutput`] or `tuple`:
                If return_dict is `True`, [`~schedulers.scheduling_ddpm.DDPMSchedulerOutput`] is returned, otherwise a
                tuple is returned where the first element is the sample tensor.
        r   r	   )r[   r\   r=   Nr   r_   rm   r`   ra   zprediction_type given as zM must be one of `epsilon`, `sample` or `v_prediction`  for the DDPMScheduler.)r   r   r/   rX   )r   r\   )r   r   )r   r   rV   r   splitrE   rq   r   r^   r0   rb   r   r]   r   rd   r   r   r/   r   r#   r   )rz   r   r|   r`   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_noises                         r   stepzDDPMScheduler.step  s   : ''*a FLLOa$77D<N<NRn<n/4{{<VW^_/`,L,!% **1-;AQ;D//7DHH,&00&)::_, ;;&&)3$*[S-AL-P$PT`ehTi#i [[((H4#/ [[((N:$0#$5#?;PSCSWcBc#c +DKK,G,G+H I: :  ;;###'#9#9:N#O [[$$#7#=#=...0M0M$  '8C&@>&QU`%`".37:JJ[X 68LLOcflOll q5!((F)""ilN`N`N !!%66--aDV-WZhh##6--aDV-W 99S8^4~E ..qEW.X\__cqq+h6 $ 
 #/?Vjkkr   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 )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.   rm   r?   r   rE   r   r   r/   flattenr   r   r   )rz   r   r   ry   rE   sqrt_alpha_prodsqrt_one_minus_alpha_prodnoisy_sampless           r   	add_noisezDDPMScheduler.add_noise  sa   2 #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 )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.   rm   r?   r   r   )rz   r`   r   ry   rE   r   r   velocitys           r   get_velocityzDDPMScheduler.get_velocityA  sI   " #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)r   rM   )rz   s    r   __len__zDDPMScheduler.__len__c  s    {{...r   c                    | j                   s| j                  ro| j                  |k(  j                  d      d   d   }|| j                  j                  d   dz
  k(  rt        j                  d      }|S | j                  |dz      }|S |dz
  }|S )z
        Compute the previous timestep in the diffusion chain.

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

        Returns:
            `int`:
                The previous timestep.
        T)as_tupler   r   r?   )rs   rt   ry   nonzeror   r   r4   )rz   r|   indexr   s       r   r   zDDPMScheduler.previous_timestepf  s       D$<$<^^x/88$8GJ1ME,,Q/!33b)
  	2  \Fr   )i  g-C6?g{Gz?rQ   NrW   Tr_   Fgףp=
?r<   r<   rh   r   Fr   )NNN)NN)NT)$r   r   r   r   r   name_compatiblesorderr   intr   r   r   r   rv   ndarrayr   boolr{   r   r   r~   strr   r   r   r   	Generatorr   r   r   	IntTensorr   r   r   r   ).0es   00r   rL   rL      s   +Z %>>qAFF>LE $("\dBF  HQ",1#&"%GP',%5+ 5+ 5+ 	5+
 XY5+  bjj$u+&= >?5+ j
5+ 5+ !!DE5+ 5+ %*5+ !5+  5+  ""CD!5+" #5+$ !%%5+ 5+n  Y^YeYe & .2+/)-	H@%c]H@ c5<<'(H@ DI&	H@Z 6: >> %U\\2>  rs
	> 
>@) ) )` 04 dllldl dl 	dl
 EOO,dl dl 
"E)	*dlL(,,( ||( ??	(
 
(T 5<<    QVQ`Q`  ejeqeq  D/ /# # m ?s   F=rL   )g+?r"   )r'   dataclassesr   typingr   r   r   r   r   numpyrv   r   configuration_utilsr
   r   utilsr   utils.torch_utilsr   scheduling_utilsr   r   r   r   r   r   r:   rJ   rL   r   r   r   <module>r      s   "  ! 8 8   A  , G 8* 8 8& 5=*4 *4*4 "/2*4 \\	*4\!U\\ !ell !HxNK xr   