
    bi	4                         d dl Z d dlmZ d dlmZmZm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 G d dee	      Zy)    N)	dataclass)OptionalTupleUnion   )ConfigMixinregister_to_config)
BaseOutput)randn_tensor   )SchedulerMixinSchedulerOutputc                   N    e Zd ZU dZej
                  ed<   ej
                  ed<   y)SdeVeOutputa  
    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.
        prev_sample_mean (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
            Mean averaged `prev_sample` over previous timesteps.
    prev_sampleprev_sample_meanN)__name__
__module____qualname____doc__torchTensor__annotations__     a/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/schedulers/scheduling_sde_ve.pyr   r      s    	 ll"r   r   c                   6   e Zd ZdZdZe	 	 	 	 	 	 d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ededeee	j                  f   fdZ	 d!dedededefdZd Z	 	 d"de	j                  dede	j                  dee	j&                     dedeeef   fdZ	 	 d"de	j                  de	j                  dee	j&                     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 Zy
)#ScoreSdeVeSchedulera  
    `ScoreSdeVeScheduler` is a variance exploding stochastic differential equation (SDE) scheduler.

    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.
        snr (`float`, defaults to 0.15):
            A coefficient weighting the step from the `model_output` sample (from the network) to the random noise.
        sigma_min (`float`, defaults to 0.01):
            The initial noise scale for the sigma sequence in the sampling procedure. The minimum sigma should mirror
            the distribution of the data.
        sigma_max (`float`, defaults to 1348.0):
            The maximum value used for the range of continuous timesteps passed into the model.
        sampling_eps (`float`, defaults to 1e-5):
            The end value of sampling where timesteps decrease progressively from 1 to epsilon.
        correct_steps (`int`, defaults to 1):
            The number of correction steps performed on a produced sample.
    r   num_train_timestepssnr	sigma_min	sigma_maxsampling_epscorrect_stepsc                 H    || _         d | _        | j                  ||||       y N)init_noise_sigma	timesteps
set_sigmas)selfr   r    r!   r"   r#   r$   s          r   __init__zScoreSdeVeScheduler.__init__G   s(     !* +Y	<Pr   N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   )r*   r,   r-   s      r   scale_model_inputz%ScoreSdeVeScheduler.scale_model_inputY   s	     r   num_inference_stepsdevicec                 t    ||n| j                   j                  }t        j                  d|||      | _        y)aA  
        Sets the continuous 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.
            sampling_eps (`float`, *optional*):
                The final timestep value (overrides value given during scheduler instantiation).
            device (`str` or `torch.device`, *optional*):
                The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.

        Nr   r2   )configr#   r   linspacer(   )r*   r1   r#   r2   s       r   set_timestepsz!ScoreSdeVeScheduler.set_timestepsj   s2     (4'?|T[[E]E]<9LU[\r   c                 @   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }| j                  | j                  ||       |||z  | j                  |z  z  z  | _        t        j                  t        j                  t        j                  |      t        j                  |      |            | _        t        j                  | j                  D cg c]  }|||z  |z  z   c}      | _        yc c}w )a  
        Sets the noise scales used for the diffusion chain (to be run before inference). The sigmas control the weight
        of the `drift` and `diffusion` components of the sample update.

        Args:
            num_inference_steps (`int`):
                The number of diffusion steps used when generating samples with a pre-trained model.
            sigma_min (`float`, optional):
                The initial noise scale value (overrides value given during scheduler instantiation).
            sigma_max (`float`, optional):
                The final noise scale value (overrides value given during scheduler instantiation).
            sampling_eps (`float`, optional):
                The final timestep value (overrides value given during scheduler instantiation).

        N)r5   r!   r"   r#   r(   r7   sigmasr   expr6   mathlogdiscrete_sigmastensor)r*   r1   r!   r"   r#   ts         r   r)   zScoreSdeVeScheduler.set_sigmas}   s    $ "+!6IDKK<Q<Q	!*!6IDKK<Q<Q	'3'?|T[[E]E]>>!2LA9y#8dnn|>["\\$yy8KTXXV_M`bu)vwllVZVdVd#eQRIY1F10L$L#ef#es   <Dc                     t        j                  |dk(  t        j                  |j                  |j                              | j
                  |dz
     j                  |j                              S )Nr   r   )r   where
zeros_liketor2   r=   )r*   r(   r?   s      r   get_adjacent_sigmaz&ScoreSdeVeScheduler.get_adjacent_sigma   sZ    {{NQTT)"2"234  Q/2293C3CD
 	
r   model_output	generatorreturn_dictc                    | j                   t        d      |t        j                  |j                  d   |j
                        z  }|t        | j                         dz
  z  j                         }|j                  | j                  j
                        }| j                  |   j                  |j
                        }| j                  ||      j                  |j
                        }t        j                  |      }	|dz  |dz  z
  dz  }
|
j                         }
t        |
j                        t        |j                        k  r=|
j                  d      }
t        |
j                        t        |j                        k  r=|	|
dz  |z  z
  }	t        |j                  |j                  ||j
                  |j                         }||	z
  }||
|z  z   }|s||fS t#        ||	      S )
aD  
        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`, *optional*, defaults to `True`):
                Whether or not to return a [`~schedulers.scheduling_sde_ve.SdeVeOutput`] or `tuple`.

        Returns:
            [`~schedulers.scheduling_sde_ve.SdeVeOutput`] or `tuple`:
                If return_dict is `True`, [`~schedulers.scheduling_sde_ve.SdeVeOutput`] is returned, otherwise a tuple
                is returned where the first element is the sample tensor.

        Y`self.timesteps` is not set, you need to run 'set_timesteps' after creating the schedulerr   r4   r   r         ?)layoutrF   r2   dtype)r   r   )r(   
ValueErrorr   onesshaper2   lenlongrC   r=   rD   rB   flatten	unsqueezer   rL   rM   r   )r*   rE   r-   r,   rF   rG   r(   sigmaadjacent_sigmadrift	diffusionnoiser   r   s                 r   	step_predzScoreSdeVeScheduler.step_pred   s   < >>!k  ejjLLOFMM
 
 T^^!4q!89??A	 LL!5!5!<!<=	$$Y/226==A00HEHHW  (AX 11c9	 %%'	)//"S%66!++B/I )//"S%66	1|33 LL)FMMagamam
 "E>&U)::!122{EUVVr   c                    | j                   t        d      t        |j                  |j                  |      j                  |j                        }t        j                  |j                  |j                  d   d      d      j                         }t        j                  |j                  |j                  d   d      d      j                         }| j                  j                  |z  |z  dz  dz  }|t        j                  |j                  d         j                  |j                        z  }|j                         }t        |j                        t        |j                        k  r=|j!                  d      }t        |j                        t        |j                        k  r=|||z  z   }	|	|dz  dz  |z  z   }
|s|
fS t#        |
      S )	a  
        Correct the predicted sample based on the `model_output` of the network. This is often run repeatedly after
        making the prediction for the previous timestep.

        Args:
            model_output (`torch.Tensor`):
                The direct output from learned diffusion model.
            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`, *optional*, defaults to `True`):
                Whether or not to return a [`~schedulers.scheduling_sde_ve.SdeVeOutput`] or `tuple`.

        Returns:
            [`~schedulers.scheduling_sde_ve.SdeVeOutput`] or `tuple`:
                If return_dict is `True`, [`~schedulers.scheduling_sde_ve.SdeVeOutput`] is returned, otherwise a tuple
                is returned where the first element is the sample tensor.

        rI   )rL   rF   r   rK   )dimr   rJ   )r   )r(   rN   r   rP   rL   rC   r2   r   normreshapemeanr5   r    rO   rS   rQ   rT   r   )r*   rE   r,   rF   rG   rY   	grad_norm
noise_norm	step_sizer   r   s              r   step_correctz ScoreSdeVeScheduler.step_correct   s   6 >>!k  V\\&--9UXXY_YfYfg JJ|33L4F4Fq4I2NTVW\\^	ZZekk!nb ArJOOQ
[[__z1I=!CaG	

6<<? ; > >v}} MM	 %%'	)//"S%66!++B/I )//"S%66!I$<<&9q=S*@E)II>!;77r   original_samplesrY   r(   c                     |j                  |j                        }| j                  j                  |j                        |   }|||d d d d d f   z  n t        j                  |      |d d d d d f   z  }||z   }|S r&   )rC   r2   r=   r   
randn_like)r*   rd   rY   r(   r9   noisy_sampless         r   	add_noisezScoreSdeVeScheduler.add_noise  s     LL!1!8!89	%%(()9)@)@A)L   F1dD$.//!!"23fQdD=P6QQ 	
  00r   c                 .    | j                   j                  S r&   )r5   r   )r*   s    r   __len__zScoreSdeVeScheduler.__len__,  s    {{...r   )i  g333333?g{Gz?g     @gh㈵>r   r&   )NN)NNN)NT)r   r   r   r   orderr	   intfloatr+   r   r   r   r0   r   strr2   r7   r)   rD   	Generatorboolr   r   rZ   r   rc   rh   rj   r   r   r   r   r   .   s   , E $(!"Q Q Q 	Q
 Q Q Q Q"  Y^YeYe $ hl]#&]6;]LQRUW\WcWcRcLd]( qug#&g38gLQghmg8
 04 BWllBW BW 	BW
 EOO,BW BW 
{E!	"BWP 04 58ll58 58 EOO,	58
 58 
%	&58n,, || <<	
 
"/r   r   )r;   dataclassesr   typingr   r   r   r   configuration_utilsr   r	   utilsr
   utils.torch_utilsr   scheduling_utilsr   r   r   r   r   r   r   <module>rw      sM   "  ! ) )  A  , = #* # # /.+ /r   