
    
3j/                         S SK Jr  S SKrS SKrSSKJrJr  SSKJ	r	  SSK
JrJr  SSKJr  \R                  " \5      r\ " S S	\5      5       r " S
 S\	\5      rg)    )	dataclassN   )ConfigMixinregister_to_config)SchedulerMixin)
BaseOutputlogging)randn_tensorc                   `    \ rS rSr% Sr\R                  \S'   Sr\R                  S-  \S'   Sr	g)SCMSchedulerOutput    aM  
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____firstlineno____doc__torchTensor__annotations__r   __static_attributes__r       ]/home/wildlama/miniconda3/lib/python3.13/site-packages/diffusers/schedulers/scheduling_scm.pyr   r       s'    
 04%,,-4r   r   c                      \ rS rSrSrSr\   SS\S\S\	4S jj5       r
\S 5       r\S	 5       rS S
\4S jjr    S!S\S\R                   S\\R"                  -  S\	S\	4
S jjrS\	\R                   -  SS4S jr S"S\	\R                   -  S\R                   S-  S\4S jjr  S#S\R*                  S\	S\R*                  S\R,                  S\S\\-  4S jjrS rSrg)$SCMScheduler3   a  
`SCMScheduler` extends the denoising procedure introduced in denoising diffusion probabilistic models (DDPMs) with
non-Markovian guidance. 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.
    prediction_type (`str`, defaults to `trigflow`):
        Prediction type of the scheduler function. Currently only supports "trigflow".
    sigma_data (`float`, defaults to 0.5):
        The standard deviation of the noise added during multi-step inference.
   num_train_timestepsprediction_type
sigma_datac                     SU l         SU l        [        R                  " [        R
                  " SU5      SSS2   R                  5       R                  [        R                  5      5      U l	        SU l
        SU l        g)a  
Initialize the SCM scheduler.

Args:
    num_train_timesteps (`int`, defaults to 1000):
        The number of diffusion steps to train the model.
    prediction_type (`str`, defaults to `trigflow`):
        Prediction type of the scheduler function. Currently only supports "trigflow".
    sigma_data (`float`, defaults to 0.5):
        The standard deviation of the noise added during multi-step inference.
g      ?Nr   )init_noise_sigmanum_inference_stepsr   
from_numpynparangecopyastypeint64	timesteps_step_index_begin_index)selfr    r!   r"   s       r   __init__SCMScheduler.__init__E   sh    & !$ $( ))"))A7J*KDbD*Q*V*V*X*_*_`b`h`h*ij r   c                     U R                   $ N)r.   r0   s    r   
step_indexSCMScheduler.step_indexa   s    r   c                     U R                   $ r4   r/   r5   s    r   begin_indexSCMScheduler.begin_indexe   s       r   r:   c                     Xl         g)z
Sets the begin index for the scheduler. This function should be run from pipeline before the inference.

Args:
    begin_index (`int`, defaults to `0`):
        The begin index for the scheduler.
Nr9   )r0   r:   s     r   set_begin_indexSCMScheduler.set_begin_indexj   s
     (r   Nr&   r-   devicemax_timestepsintermediate_timestepsc           	      p   XR                   R                  :  a=  [        SU SU R                   R                   SU R                   R                   S35      eUb  [        U5      US-   :w  a  [        S5      eUb  Ub  [        S5      eUc  Uc  [        S	5      eUb  US
:w  a  [        S5      eXl        Ub  [        U[        5      (       a(  [        R                  " X#S9R                  5       U l
        O[        U[        R                  5      (       a%  UR                  U5      R                  5       U l
        Or[        S[        U5       35      eUb+  [        R                  " XES/US9R                  5       U l
        O-[        R                  " USUS-   US9R                  5       U l
        SU l        SU l        g)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.
    timesteps (`torch.Tensor`, *optional*):
        Custom timesteps to use for the denoising process.
    max_timesteps (`float`, defaults to 1.57080):
        The maximum timestep value used in the SCM scheduler.
    intermediate_timesteps (`float`, *optional*, defaults to 1.3):
        The intermediate timestep value used in SCM scheduler (only used when num_inference_steps=2).
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.Nr   zWIf providing custom timesteps, `timesteps` must be of length `num_inference_steps + 1`.zFIf providing custom timesteps, `max_timesteps` should not be provided.z5Should provide either `timesteps` or `max_timesteps`.r   zNIntermediate timesteps for SCM is not supported when num_inference_steps != 2.)r?   zUnsupported timesteps type: r   )configr    
ValueErrorlenr&   
isinstancelistr   tensorfloatr-   r   totypelinspacer.   r/   )r0   r&   r-   r?   r@   rA   s         r   set_timestepsSCMScheduler.set_timestepst   s   * !@!@@)*=)> ?KK334 5 KK;;<KI   S^7JQ7N%Nvww ]%>eff!6TUU!-2E2Jmnn#6  )T**!&i!G!M!M!OIu||44!*f!5!;!;!= #?Y?P!QRR#/"\\=RS*T]cdjjlDN #^^M1>QTU>U^dekkmDN r   timestepreturnc                     U R                   c[  [        U[        R                  5      (       a%  UR	                  U R
                  R                  5      nU R                  U5      U l        gU R                  U l        g)z
Initialize the step index for the scheduler based on the given timestep.

Args:
    timestep (`float` or `torch.Tensor`):
        The current timestep to initialize the step index from.
N)
r:   rF   r   r   rJ   r-   r?   index_for_timestepr.   r/   )r0   rO   s     r   _init_step_indexSCMScheduler._init_step_index   sZ     #(ELL11#;;t~~'<'<=#66x@D#00Dr   schedule_timestepsc                     Uc  U R                   nX!:H  R                  5       n[        U5      S:  a  SOSnX4   R                  5       $ )a  
Find the index of a given timestep in the timestep schedule.

Args:
    timestep (`float` or `torch.Tensor`):
        The timestep value to find in the schedule.
    schedule_timesteps (`torch.Tensor`, *optional*):
        The timestep schedule to search in. If `None`, uses `self.timesteps`.

Returns:
    `int`:
        The index of the timestep in the schedule. For the very first step, returns the second index if
        multiple matches exist to avoid skipping a sigma when starting mid-schedule (e.g., for image-to-image).
r   r   )r-   nonzerorE   item)r0   rO   rU   indicesposs        r   rR   SCMScheduler.index_for_timestep   sJ    " %!%%1::< w<!#a|  ""r   model_outputsample	generatorreturn_dictc                    U R                   c  [        S5      eU R                  c  U R                  U5        U R                  U R                  S-      nU R                  U R                     nU R
                  R                  nUS:X  a4  [        R                  " U5      U-  [        R                  " U5      U-  -
  n	O[        SU 35      e[        U R                  5      S:  aj  [        UR                  UR                  US9U R
                  R                  -  n
[        R                  " U5      U	-  [        R                  " U5      U
-  -   nOU	nU =R                  S-  sl        U(       d  X4$ [!        XS9$ )az  
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.FloatTensor`):
        The direct output from learned diffusion model.
    timestep (`float`):
        The current discrete timestep in the diffusion chain.
    sample (`torch.FloatTensor`):
        A current instance of a sample created by the diffusion process.
    return_dict (`bool`, *optional*, defaults to `True`):
        Whether or not to return a [`~schedulers.scheduling_scm.SCMSchedulerOutput`] or `tuple`.
Returns:
    [`~schedulers.scheduling_utils.SCMSchedulerOutput`] or `tuple`:
        If return_dict is `True`, [`~schedulers.scheduling_scm.SCMSchedulerOutput`] is returned, otherwise a
        tuple is returned where the first element is the sample tensor.
zaNumber of inference steps is 'None', you need to run 'set_timesteps' after creating the schedulerr   trigflowzUnsupported parameterization: )r?   r^   )r   r   )r&   rD   r6   rS   r-   rC   r!   r   cossinrE   r
   shaper?   r"   r.   r   )r0   r\   rO   r]   r^   r_   tsparameterizationpred_x0noiser   s               r   stepSCMScheduler.step   sN   4 ##+s  ??"!!(+ NN4??Q./NN4??+  ;;66z)iilV+eiil\.IIG=>N=OPQQ t~~"\//8K8KW`a++(()   ))A,0599Q<%3GGK!KA))!kXXr   c                 .    U R                   R                  $ r4   )rC   r    r5   s    r   __len__SCMScheduler.__len__  s    {{...r   )r/   r.   r%   r&   r-   )i  ra   g      ?)r   )NNgH.!?g?r4   )NT)r   r   r   r   r   orderr   intstrrI   r1   propertyr6   r:   r=   r   r   r?   rM   rS   rR   FloatTensor	Generatorboolr   tuplerj   rm   r   r   r   r   r   r   3   s    E $()	! ! ! 	! !6     ! !(3 ( #'%)&(+8! 8! <<8! ell"	8!
 8! !&8!v1)= 1$ 1" Y]#,#BG,,QUBU#	#F &* >Y''>Y >Y !!	>Y
 ??>Y >Y 
e	#>Y@/r   r   )dataclassesr   numpyr(   r   configuration_utilsr   r   schedulers.scheduling_utilsr   utilsr   r	   utils.torch_utilsr
   
get_loggerr   loggerr   r   r   r   r   <module>r      sY   $ "   A 8 ' , 
		H	% 5 5 5"k/>; k/r   