
    +h	4                         S SK r S SKJr  S SKJrJrJr  S SKrSSKJ	r	J
r
  SSKJr  SSKJr  SS	KJrJr  \ " S
 S\5      5       r " S S\\	5      rg)    N)	dataclass)OptionalTupleUnion   )ConfigMixinregister_to_config)
BaseOutput)randn_tensor   )SchedulerMixinSchedulerOutputc                   V    \ rS rSr% Sr\R                  \S'   \R                  \S'   Srg)SdeVeOutput   a  
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_mean N)	__name__
__module____qualname____firstlineno____doc__torchTensor__annotations____static_attributes__r       `/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/schedulers/scheduling_sde_ve.pyr   r      s    	 ll"r   r   c                   X   \ rS rSrSrSr\      S S\S\S\S\S\S	\4S
 jj5       r	S!S\
R                  S\\   S\
R                  4S jjr S"S\S\S\\\
R                   4   4S jjr S#S\S\S\S\4S jjrS r  S$S\
R                  S\S\
R                  S\\
R(                     S\S\\\4   4S jjr  S$S\
R                  S\
R                  S\\
R(                     S\S\\\4   4
S jjrS\
R                  S\
R                  S\
R                  S\
R                  4S jrS rSrg)%ScoreSdeVeScheduler.   at  
`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                 B    X@l         S U l        U R                  XXE5        g N)init_noise_sigma	timesteps
set_sigmas)selfr#   r$   r%   r&   r'   r(   s          r   __init__ScoreSdeVeScheduler.__init__G   s"     !* +	Pr   Nsampletimestepreturnc                     U$ )aN  
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_input%ScoreSdeVeScheduler.scale_model_inputY   s	     r   num_inference_stepsdevicec                 p    Ub  UOU R                   R                  n[        R                  " SX!US9U l        g)a  
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   r8   )configr'   r   linspacer,   )r.   r7   r'   r8   s       r   set_timesteps!ScoreSdeVeScheduler.set_timestepsj   s/     (4'?|T[[E]E]<U[\r   c                 P   Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nU R                  c  U R                  X5        X#U-  U R                  U-  -  -  U l        [        R                  " [        R                  " [        R                  " U5      [        R                  " U5      U5      5      U l        [        R                  " U R                   Vs/ s H  oRX2-  U-  -  PM     sn5      U l        gs  snf )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)r;   r%   r&   r'   r,   r=   sigmasr   expr<   mathlogdiscrete_sigmastensor)r.   r7   r%   r&   r'   ts         r   r-   ScoreSdeVeScheduler.set_sigmas}   s    $ "+!6IDKK<Q<Q	!*!6IDKK<Q<Q	'3'?|T[[E]E]>>!2Ay#8dnn|>["\\$yy8KTXXV_M`bu)vwllVZVdVd#eVdQR1F10L$LVd#ef#es   D#c                     [         R                  " US:H  [         R                  " UR                  UR                  5      5      U R
                  US-
     R                  UR                  5      5      $ )Nr   r   )r   where
zeros_liketor8   rD   )r.   r,   rF   s      r   get_adjacent_sigma&ScoreSdeVeScheduler.get_adjacent_sigma   sZ    {{NQTT)"2"234  Q/2293C3CD
 	
r   model_output	generatorreturn_dictc                    U R                   c  [        S5      eU[        R                  " UR                  S   UR
                  S9-  nU[        U R                   5      S-
  -  R                  5       nUR                  U R                  R
                  5      nU R                  U   R                  UR
                  5      nU R                  Xb5      R                  UR
                  5      n[        R                  " U5      n	US-  US-  -
  S-  n
U
R                  5       n
[        U
R                  5      [        UR                  5      :  a?  U
R                  S5      n
[        U
R                  5      [        UR                  5      :  a  M?  XS-  U-  -
  n	[        UR                  UR                  XCR
                  UR                   S9nX9-
  nXU-  -   nU(       d  X4$ [#        XS	9$ )
a  
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   r:   r   r         ?)layoutrO   r8   dtype)r   r   )r,   
ValueErrorr   onesshaper8   lenlongrK   rD   rL   rJ   flatten	unsqueezer   rU   rV   r   )r.   rN   r2   r1   rO   rP   r,   sigmaadjacent_sigmadrift	diffusionnoiser   r   s                 r   	step_predScoreSdeVeScheduler.step_pred   s   < >>!k  ejjLLOFMM
 
 T^^!4q!89??A	 LL!5!5!<!<=	$$Y/226==A00EHHW  (AX 11c9	 %%'	)//"S%66!++B/I )//"S%661|33 LL)MMagamam
 ">&U)::22{VVr   c                    U R                   c  [        S5      e[        UR                  UR                  US9R                  UR                  5      n[        R                  " UR                  UR                  S   S5      SS9R                  5       n[        R                  " UR                  UR                  S   S5      SS9R                  5       nU R                  R                  U-  U-  S-  S-  nU[        R                  " UR                  S   5      R                  UR                  5      -  nUR                  5       n[        UR                  5      [        UR                  5      :  a?  UR!                  S5      n[        UR                  5      [        UR                  5      :  a  M?  X(U-  -   n	XS-  S-  U-  -   n
U(       d  U
4$ [#        U
S9$ )	aI  
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.

rR   )rU   rO   r   rT   )dimr   rS   )r   )r,   rW   r   rY   rU   rK   r8   r   normreshapemeanr;   r$   rX   r\   rZ   r]   r   )r.   rN   r1   rO   rP   rb   	grad_norm
noise_norm	step_sizer   r   s              r   step_correct 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!$<<&q=S*@E)II>!;77r   original_samplesrb   r,   c                     UR                  UR                  5      nU R                  R                  UR                  5      U   nUb  X$S S 2S S S 4   -  O![        R                  " U5      US S 2S S S 4   -  nX!-   nU$ r*   )rK   r8   rD   r   
randn_like)r.   ro   rb   r,   r@   noisy_sampless         r   	add_noiseScoreSdeVeScheduler.add_noise  s     LL!1!8!89	%%(()9)@)@A)L   1dD$.//!!"23fQdD=P6QQ 	
 0r   c                 .    U R                   R                  $ r*   )r;   r#   )r.   s    r   __len__ScoreSdeVeScheduler.__len__,  s    {{...r   )rD   r+   r@   r,   )i  g333333?g{Gz?g     @gh㈵>r   r*   )NN)NNN)NT)r   r   r   r   r   orderr	   intfloatr/   r   r   r   r5   r   strr8   r=   r-   rL   	Generatorboolr   r   rc   r   rm   rs   rv   r   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!   )rB   dataclassesr   typingr   r   r   r   configuration_utilsr   r	   utilsr
   utils.torch_utilsr   scheduling_utilsr   r   r   r!   r   r   r   <module>r      sM   "  ! ) )  A  , = #* # # /.+ /r   