
    wiP                         d dl Z d dlZd dlmZ d dlmZmZmZmZ d dl	Z
d dlZd dlmZ ddlmZmZ ddlmZ dd	lmZmZ e G d
 de                      Z	 	 ddZ G d dee          ZdS )    N)	dataclass)ListOptionalTupleUnion)	integrate   )ConfigMixinregister_to_config)
BaseOutput   )KarrasDiffusionSchedulersSchedulerMixinc                   L    e Zd ZU dZej        ed<   dZeej                 ed<   dS )LMSDiscreteSchedulerOutputaq  
    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        |/root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/diffusers/schedulers/scheduling_lms_discrete.pyr   r      sD         
 
 37(5<077777r   r   +?cosinec           
      F   |dk    rd }n|dk    rd }nt          d|           g }t          |           D ]J}|| z  }|dz   | z  }|                    t          d ||           ||          z  z
  |                     Kt	          j        |t          j                  S )a  
    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`): the maximum beta to use; use values lower than 1 to
                     prevent singularities.
        alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
                     Choose from `cosine` or `exp`

    Returns:
        betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
    r   c                 \    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_fnI   s,    8QY%/$'9A=>>!CCr   expc                 0    t          j        | dz            S )Ng      ()r"   r(   r%   s    r   r'   z)betas_for_alpha_bar.<locals>.alpha_bar_fnN   s    8AI&&&r   z"Unsupported alpha_transform_type: r   dtype)
ValueErrorrangeappendminr   tensorfloat32)num_diffusion_timestepsmax_betaalpha_transform_typer'   betasit1t2s           r   betas_for_alpha_barr9   0   s    . x''	D 	D 	D 	D 
	&	&	' 	' 	' 	' T>RTTUUUE*++ M M((!e..S\\"--R0@0@@@(KKLLLL<U]3333r   c                   b   e Zd ZdZd eD             ZdZe	 	 	 	 	 	 	 	 	 d4dede	de	de
deeej        ee	         f                  dee         de
de
defd            Zed             Zed             Zed             Zd5defdZdej        dee	ej        f         dej        fdZd  Zd6d!ed"ee
ej        f         fd#Zd6d$Zd% Zd& Zd'ej        dej        fd(Z 	 	 d7d+ej        dee	ej        f         dej        d,ed-edee!e"f         fd.Z#d/ej        d0ej        d1ej        dej        fd2Z$d3 Z%dS )8LMSDiscreteScheduleru  
    A linear multistep scheduler for discrete beta schedules.

    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 (`str`, defaults to `"linear"`):
            The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
            `linear` or `scaled_linear`.
        trained_betas (`np.ndarray`, *optional*):
            Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
        use_karras_sigmas (`bool`, *optional*, defaults to `False`):
            Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`,
            the sigmas are determined according to a sequence of noise levels {σi}.
        prediction_type (`str`, defaults to `epsilon`, *optional*):
            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://imagen.research.google/video/paper.pdf) paper).
        timestep_spacing (`str`, defaults to `"linspace"`):
            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.
    c                     g | ]	}|j         
S r   )name).0es     r   
<listcomp>zLMSDiscreteScheduler.<listcomp>}   s    >>>qAF>>>r   r     -C6?{Gz?linearNFepsilonlinspacer   num_train_timesteps
beta_startbeta_endbeta_scheduletrained_betasuse_karras_sigmasprediction_typetimestep_spacingsteps_offsetc
                    |&t          j        |t           j                  | _        n|dk    r(t          j        |||t           j                  | _        nk|dk    r1t          j        |dz  |dz  |t           j                  dz  | _        n4|dk    rt          |          | _        nt          | d| j                   d| j        z
  | _        t          j	        | j        d	
          | _
        t          j        d| j
        z
  | j
        z  dz            }
t          j        |
d d d         dgg                              t          j                  }
t          j        |
          | _        d | _        || _        |                     |d            g | _        d| _        d | _        d | _        | j                            d          | _        d S )Nr*   rD   scaled_linear      ?r	   squaredcos_cap_v2z is not implemented for       ?r   )dimr           Fcpu)r   r0   r1   r5   rF   r9   NotImplementedError	__class__alphascumprodalphas_cumprodnparrayconcatenateastype
from_numpysigmasnum_inference_stepsrL   set_timestepsderivativesis_scale_input_called_step_index_begin_indexto)selfrG   rH   rI   rJ   rK   rL   rM   rN   rO   rc   s              r   __init__zLMSDiscreteScheduler.__init__   s    $m5=IIIDJJh&&
H>QY^YfgggDJJo--
C3H[chcpqqquvvDJJ111,-@AADJJ%&`&`PTP^&`&`aaaDJ&#mDKQ???A 33t7JJsRSS"u 566==bjII&v.. $( !2.555%*" knnU++r   c                     | j         j        dv r| j                                        S | j                                        dz  dz   dz  S )N)rF   trailingr	   r   rR   )configrN   rc   maxrk   s    r   init_noise_sigmaz%LMSDiscreteScheduler.init_noise_sigma   sH     ;'+CCC;??$$$!!Q&*s22r   c                     | j         S )zg
        The index counter for current timestep. It will increase 1 after each scheduler step.
        )rh   rq   s    r   
step_indexzLMSDiscreteScheduler.step_index   s    
 r   c                     | j         S )zq
        The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
        ri   rq   s    r   begin_indexz LMSDiscreteScheduler.begin_index   s    
   r   rw   c                     || _         dS )z
        Sets the begin index for the scheduler. This function should be run from pipeline before the inference.

        Args:
            begin_index (`int`):
                The begin index for the scheduler.
        Nrv   )rk   rw   s     r   set_begin_indexz$LMSDiscreteScheduler.set_begin_index   s     (r   sampletimestepreturnc                     | j         |                     |           | j        | j                  }||dz  dz   dz  z  }d| _        |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 (`float` or `torch.Tensor`):
                The current timestep in the diffusion chain.

        Returns:
            `torch.Tensor`:
                A scaled input sample.
        Nr	   r   rR   T)rt   _init_step_indexrc   rg   )rk   rz   r{   sigmas       r   scale_model_inputz&LMSDiscreteScheduler.scale_model_input   sR      ?"!!(+++DO,E1HqLS01%)"r   c                       fd}t          j        | j                  j        dz            d          d         }|S )z
        Compute the linear multistep coefficient.

        Args:
            order ():
            t ():
            current_order ():
        c                     d}t                    D ]A}|k    r	|| j        |z
           z
  j        z
           j        |z
           z
  z  z  }B|S )NrT   )r-   rc   )tauprodkcurrent_orderorderrk   r&   s      r   lms_derivativez@LMSDiscreteScheduler.get_lms_coefficient.<locals>.lms_derivative   st    D5\\ k k A%%t{1q511dk!mBS6TW[WbcdghchWi6ijjKr   r   rB   )epsrelr   )r   quadrc   )rk   r   r&   r   r   integrated_coeffs   ````  r   get_lms_coefficientz(LMSDiscreteScheduler.get_lms_coefficient   sj    	 	 	 	 	 	 	 	 %>.$+a.$+VWZ[V[J\eijjjklmr   rd   devicec           	      8    | _          j        j        dk    rLt          j        d j        j        dz
  |t          j                  ddd                                         }n> j        j        dk    r j        j         j         z  }t          j        d|          |z  	                                ddd                                         
                    t          j                  }| j        j        z  }n j        j        dk    r| j        j         j         z  }t          j         j        j        d|           	                                                                
                    t          j                  }|dz  }nt           j        j         d	          t          j        d j        z
   j        z  d
z            }t          j        |          t          j        |t          j        dt#          |                    |          } j        j        r7                     |          }t          j         fd|D                       }t          j        |dgg          
                    t          j                  }t+          j        |                              |           _        t+          j        |                              |           _        d _        d _         j                            d           _        g  _        dS )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.
            device (`str` or `torch.device`, *optional*):
                The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
        rF   r   r   r*   NrV   leadingrn   zY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.rR   )	in_sigmasc                 <    g | ]}                     |          S r   )_sigma_to_t)r>   r   
log_sigmasrk   s     r   r@   z6LMSDiscreteScheduler.set_timesteps.<locals>.<listcomp>#  s)    !Z!Z!Z%$"2"25*"E"E!Z!Z!Zr   rW   )r   rX   )rd   ro   rN   r^   rF   rG   r1   copyarangeroundra   rO   r,   r_   r]   loginterplenrL   _convert_to_karrasr`   r   rb   rj   rc   	timestepsrh   ri   rf   )rk   rd   r   r   
step_ratiorc   r   s   `     @r   re   z"LMSDiscreteScheduler.set_timesteps   s    $7  ;':55At{'F'JL_gigqrrr"dff I [)Y668D<TTJ 1&9::ZGNNPPQUQUSUQUV[[]]ddegeoppI11II[)Z7784;SSJ 4;#BA
{SSZZ\\aaccjjkmkuvvINII;/  K  K  K   A 33t7JJsRSSVF^^
9bi3v;;&?&?HH;( 	\,,v,>>F!Z!Z!Z!Z!ZSY!Z!Z!Z[[I#0077
CC&v..111@@))4477v7FF knnU++r   c                     || j         }||k                                    }t          |          dk    rdnd}||                                         S )Nr   r   )r   nonzeror   item)rk   r{   schedule_timestepsindicesposs        r   index_for_timestepz'LMSDiscreteScheduler.index_for_timestep0  sW    %!%%1::<< w<<!##aas|  """r   c                     | j         Ut          |t          j                  r|                    | j        j                  }|                     |          | _        d S | j	        | _        d S N)
rw   
isinstancer   r   rj   r   r   r   rh   ri   )rk   r{   s     r   r~   z%LMSDiscreteScheduler._init_step_index?  sb    #(EL11 >#;;t~'<==#66x@@D#0Dr   c                    t          j        t          j        |d                    }||d d t           j        f         z
  }t          j        |dk    d                              d                              |j        d         dz
            }|dz   }||         }||         }||z
  ||z
  z  }	t          j        |	dd          }	d|	z
  |z  |	|z  z   }
|
                    |j                  }
|
S )Ng|=r   )axisr	   )rp   r   )	r^   r   maximumnewaxiscumsumargmaxclipshapereshape)rk   r   r   	log_sigmadistslow_idxhigh_idxlowhighwr&   s              r   r   z LMSDiscreteScheduler._sigma_to_tH  s    F2:eU3344	 Jqqq"*}55 )UaZq11188a8@@EE*JZ[\J]`aJaEbbQ;!(# 9_t,GAq! UgH,IIek""r   r   c                     |d                                          }|d                                          }d}t          j        dd| j                  }|d|z  z  }|d|z  z  }||||z
  z  z   |z  }|S )z6Constructs the noise schedule of Karras et al. (2022).rV   r   g      @r   )r   r^   rF   rd   )	rk   r   	sigma_min	sigma_maxrhorampmin_inv_rhomax_inv_rhorc   s	            r   r   z'LMSDiscreteScheduler._convert_to_karras`  s     %R=--//	$Q<,,..	{1a!9::AG,AG,k(A BBsJr      Tmodel_outputr   return_dictc           
      \     j         st          j        d            j                             |            j         j                 } j        j        dk    r	|||z  z
  }n_ j        j        dk    r|| |dz  dz   dz  z  z  ||dz  dz   z  z   }n0 j        j        dk    r|}nt          d	 j        j         d
          ||z
  |z  } j	        
                    |           t           j	                  k    r j	                            d           t           j        dz              fdt                    D             }	|t          d t!          |	t#           j	                            D                       z   }
 xj        dz  c_        |s|
fS t'          |
|          S )aa  
        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 (`float` or `torch.Tensor`):
                The current discrete timestep in the diffusion chain.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.
            order (`int`, defaults to 4):
                The order of the linear multistep method.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or tuple.

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

        zThe `scale_model_input` function should be called before `step` to ensure correct denoising. See `StableDiffusionPipeline` for a usage example.NrE   v_predictionr	   r   rR   rz   zprediction_type given as z, must be one of `epsilon`, or `v_prediction`r   c                 H    g | ]}                     j        |          S r   )r   rt   )r>   
curr_orderr   rk   s     r   r@   z-LMSDiscreteScheduler.step.<locals>.<listcomp>  s.    rrrWad..udozRRrrrr   c              3   &   K   | ]\  }}||z  V  d S r   r   )r>   coeff
derivatives      r   	<genexpr>z,LMSDiscreteScheduler.step.<locals>.<genexpr>  s<       #
 #
#45*EJ#
 #
 #
 #
 #
 #
r   )r   r   )rg   warningswarnrt   r~   rc   ro   rM   r,   rf   r.   r   popr/   r-   sumzipreversedrh   r   )rk   r   r{   rz   r   r   r   r   r   
lms_coeffsr   s   `   `      r   stepzLMSDiscreteScheduler.stepm  s   < ) 	ME  
 ?"!!(+++DO, ;&)33#)EL,@#@  [(N::#/E6UAX\c<Q3Q#RV\`egh`hkl`lVm#n  [(H44#/  uDK,Guuu  
 33u<

+++t  5((  ### DOa'//rrrrrejkpeqeqrrr
 s #
 #
8;JQUQaHbHb8c8c#
 #
 #
  
  
 

 	A 	">!)kXlmmmmr   original_samplesnoiser   c                 `     j                             |j        |j                  }|j        j        dk    rft          j        |          rR j                            |j        t
          j                  |                    |j        t
          j                  }n9 j                            |j                  |                    |j                  } j	         fd|D             }n4 j
         j
        g|j        d         z  }n j	        g|j        d         z  }||                                         }t          |j                  t          |j                  k     r?|                    d          }t          |j                  t          |j                  k     ?|||z  z   }|S )N)r   r+   mpsr*   c                 <    g | ]}                     |          S r   )r   )r>   r&   r   rk   s     r   r@   z2LMSDiscreteScheduler.add_noise.<locals>.<listcomp>  s*    ^^^qD33A7IJJ^^^r   r   rV   )rc   rj   r   r+   typer   is_floating_pointr   r1   rw   rt   r   flattenr   	unsqueeze)	rk   r   r   r   rc   step_indicesr   noisy_samplesr   s	   `       @r   	add_noisezLMSDiscreteScheduler.add_noise  s    '7'>FVF\]]"'500U5LY5W5W0!%!2!23C3JRWR_!2!`!`!%5%<EMRRII!%!2!23C3J!K!K!%5%<==I #^^^^^T]^^^LL_( O,yq/AALL !,-	0BBL|$,,..%+%5%;!<!<<<OOB''E %+%5%;!<!<<< )55=8r   c                     | j         j        S r   )ro   rG   rq   s    r   __len__zLMSDiscreteScheduler.__len__  s    {..r   )	rA   rB   rC   rD   NFrE   rF   r   )r   r   )r   T)&r   r   r   r   r   _compatiblesr   r   intfloatstrr   r   r^   ndarrayr   boolrl   propertyrr   rt   rw   ry   r   r   r   r   r   re   r   r~   r   r   r   r   r   r   r   r   r   r   r;   r;   \   s        @ ?>$=>>>LE $("%BF,1( *), ), ), ), 	),
 ),  bj$u+&= >?), $D>), ), ), ), ), ), ),V 3 3 X3     X  ! ! X!( (3 ( ( ( ( eU\FY@Z _d_k    0     ,2 2 2eCDU>V 2 2 2 2j# # # #1 1 1  0EL U\    $  Kn KnlKn u|+,Kn 	Kn
 Kn Kn 
)50	1Kn Kn Kn Kn\, | <	
 
   B/ / / / /r   r;   )r   r   )r"   r   dataclassesr   typingr   r   r   r   numpyr^   r   scipyr   configuration_utilsr
   r   utilsr   scheduling_utilsr   r   r   r9   r;   r   r   r   <module>r      sK     ! ! ! ! ! ! / / / / / / / / / / / /            A A A A A A A A       G G G G G G G G 8 8 8 8 8 8 8 8( !)4 )4 )4 )4XA/ A/ A/ A/ A/>; A/ A/ A/ A/ A/r   