
    wi	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dS )    N)	dataclass)OptionalTupleUnion   )ConfigMixinregister_to_config)
BaseOutput)randn_tensor   )SchedulerMixinSchedulerOutputc                   <    e Zd ZU dZej        ed<   ej        ed<   dS )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__     v/root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/diffusers/schedulers/scheduling_sde_ve.pyr   r      s:         	 	 l"""""r   r   c                      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dS ))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     333333?{Gz?     @h㈵>num_train_timestepssnr	sigma_min	sigma_maxsampling_epscorrect_stepsc                 R    || _         d | _        |                     ||||           d S N)init_noise_sigma	timesteps
set_sigmas)selfr$   r%   r&   r'   r(   r)   s          r   __init__zScoreSdeVeScheduler.__init__G   s4     !* +Y	<PPPP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/   r1   r2   s      r   scale_model_inputz%ScoreSdeVeScheduler.scale_model_inputY   s	     r   num_inference_stepsdevicec                 `    ||n| j         j        }t          j        d|||          | _        dS )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   r7   )configr(   r   linspacer-   )r/   r6   r(   r7   s       r   set_timestepsz!ScoreSdeVeScheduler.set_timestepsj   s7     (4'?||T[E]<9LU[\\\r   c                    n| j         j        n| j         j        ||n| j         j        }| j        |                     ||           z  | j        |z  z  z  | _        t          j        t          j	        t          j                  t          j                  |                    | _        t          j        fd| j        D                       | _        dS )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).

        Nc                 &    g | ]}z  |z  z  S r   r   ).0tr'   r&   s     r   
<listcomp>z2ScoreSdeVeScheduler.set_sigmas.<locals>.<listcomp>   s)    #e#e#eQRIY1F10L$L#e#e#er   )r:   r&   r'   r(   r-   r<   sigmasr   expr;   mathlogdiscrete_sigmastensor)r/   r6   r&   r'   r(   s     `` r   r.   zScoreSdeVeScheduler.set_sigmas}   s    $ "+!6IIDK<Q	!*!6IIDK<Q	'3'?||T[E]>!2LAAA9y#8dn|>["\\$y8K8KTXV_M`M`bu)v)vwwl#e#e#e#e#eVZVd#e#e#effr   c                     t          j        |dk    t          j        |                    |j                            | j        |dz
                               |j                            S )Nr   r   )r   where
zeros_liketor7   rF   )r/   r-   r@   s      r   get_adjacent_sigmaz&ScoreSdeVeScheduler.get_adjacent_sigma   sZ    {NQTT)"23344 Q/2293CDD
 
 	
r   Tmodel_output	generatorreturn_dictc                    | j         t          d          |t          j        |j        d         |j                  z  }|t          | j                   dz
  z                                  }|                    | j	        j                  }| j	        |                             |j                  }| 
                    ||                              |j                  }t          j        |          }	|dz  |dz  z
  dz  }
|
                                }
t          |
j                  t          |j                  k     r?|
                    d          }
t          |
j                  t          |j                  k     ?|	|
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.

        NY`self.timesteps` is not set, you need to run 'set_timesteps' after creating the schedulerr   r9   r   r         ?)layoutrN   r7   dtype)r   r   )r-   
ValueErrorr   onesshaper7   lenlongrK   rF   rL   rJ   flatten	unsqueezer   rT   rU   r   )r/   rM   r2   r1   rN   rO   r-   sigmaadjacent_sigmadrift	diffusionnoiser   r   s                 r   	step_predzScoreSdeVeScheduler.step_pred   s   < >!k   ejLOFM
 
 
 
 T^!4!4q!89??AA	 LL!5!<==	$Y/226=AA00HEEHHWW ((AX 11c9	 %%''	)/""S%6%666!++B//I )/""S%6%666	1|33 L)FMagam
 
 
 "E>&U):: 	3!122{EUVVVVr   c                    | j         t          d          t          |j        |j        |                              |j                  }t          j        |	                    |j        d         d          d          
                                }t          j        |	                    |j        d         d          d          
                                }| j        j        |z  |z  dz  dz  }|t          j        |j        d                                       |j                  z  }|                                }t          |j                  t          |j                  k     r?|                    d          }t          |j                  t          |j                  k     ?|||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.

        NrQ   )rT   rN   r   rS   )dimr   rR   )r   )r-   rV   r   rX   rT   rK   r7   r   normreshapemeanr:   r%   rW   r[   rY   r\   r   )r/   rM   r1   rN   rO   ra   	grad_norm
noise_norm	step_sizer   r   s              r   step_correctz ScoreSdeVeScheduler.step_correct   s   6 >!k   V\&-9UUUXXY_Yfgg J|33L4Fq4I2NNTVWWW\\^^	Zek!nb A ArJJJOOQQ
[_z1I=!CaG	
6<? ; ; > >v} M MM	 %%''	)/""S%6%666!++B//I )/""S%6%666!I$<<&9q=S*@E)II 	">!;7777r   original_samplesra   r-   c                     |                     |j                  }| j                             |j                  |         }|||d d d d d f         z  n"t          j        |          |d d d d d f         z  }||z   }|S r+   )rK   r7   rF   r   
randn_like)r/   rl   ra   r-   rB   noisy_sampless         r   	add_noisezScoreSdeVeScheduler.add_noise  s     LL!1!899	%(()9)@AA)L   F111dD$.///!"233fQQQdD=P6QQ 	
  00r   c                     | j         j        S r+   )r:   r$   )r/   s    r   __len__zScoreSdeVeScheduler.__len__,  s    {..r   )r   r    r!   r"   r#   r   r+   )NN)NNN)NT)r   r   r   r   orderr	   intfloatr0   r   r   r   r5   r   strr7   r<   r.   rL   	Generatorboolr   r   rb   r   rk   rp   rr   r   r   r   r   r   .   s        , E $(!"Q Q Q Q 	Q
 Q Q Q Q Q Q"   Y^Ye    $ hl] ]#&]6;]LQRUW\WcRcLd] ] ] ]( qug g#&g38gLQghmg g g g8
 
 
 04 BW BWlBW BW 	BW
 EO,BW BW 
{E!	"BW BW BW BWP 04 58 58l58 58 EO,	58
 58 
%	&58 58 58 58n, | <	
 
   "/ / / / /r   r   )rD   dataclassesr   typingr   r   r   r   configuration_utilsr   r	   utilsr
   utils.torch_utilsr   scheduling_utilsr   r   r   r   r   r   r   <module>r      s  "  ! ! ! ! ! ! ) ) ) ) ) ) ) ) ) )  A A A A A A A A       , , , , , , = = = = = = = = # # # # #* # # # / / / / /.+ / / / / /r   