
    wi                         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 	 	 dd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+?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    /root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/diffusers/schedulers/scheduling_consistency_decoder.pyalpha_bar_fnz)betas_for_alpha_bar.<locals>.alpha_bar_fn'   s,    8QY%/$'9A=>>!CC    expc                 0    t          j        | dz            S )Ng      ()r   r   r   s    r   r   z)betas_for_alpha_bar.<locals>.alpha_bar_fn,   s    8AI&&&r   z"Unsupported alpha_transform_type: r   )dtype)
ValueErrorrangeappendmintorchtensorfloat32)num_diffusion_timestepsmax_betaalpha_transform_typer   betasit1t2s           r   betas_for_alpha_barr+      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                   (    e Zd ZU dZej        ed<   dS )!ConsistencyDecoderSchedulerOutputa>  
    Output class for the scheduler's `step` function.

    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_sampleN)__name__
__module____qualname____doc__r!   Tensor__annotations__ r   r   r-   r-   :   s,           r   r-   c                   :   e Zd ZdZe	 	 ddedefd            Z	 	 ddee         d	e	e
ej        f         fd
Zed             Zddej        dee         dej        fdZ	 	 ddej        de	eej        f         dej        deej                 dede	eef         fdZdS )ConsistencyDecoderSchedulerr            ?num_train_timesteps
sigma_datac                    t          |          }d|z
  }t          j        |d          }t          j        |          | _        t          j        d|z
            | _        t          j        d|z  dz
            }t          j        d|z            }||dz  z  |dz  |dz  z   z  | _        ||z  |dz  |dz  z   dz  z  | _        ||dz  |dz  z   dz  z  | _        d S )Ng      ?r   )dimr   r   r9   )	r+   r!   cumprodsqrtsqrt_alphas_cumprodsqrt_one_minus_alphas_cumprodc_skipc_outc_in)selfr:   r;   r'   alphasalphas_cumprodsigmassqrt_recip_alphas_cumprods           r   __init__z$ConsistencyDecoderScheduler.__init__K   s     $$788uv1555#(:n#=#= -2Zn8L-M-M*C.01455$)Js^/C$D$D!/*a-?619z[\}C\]j(FAI
A,E#+MM
-Z]1Js0RR			r   Nnum_inference_stepsdevicec                    |dk    rt          d          t          j        ddgt          j        |          | _        | j                            |          | _        | j                            |          | _        | j                            |          | _        | j	                            |          | _	        | j
                            |          | _
        d S )Nr   z8Currently more than 2 inference steps are not supported.i  i   )r   rL   )r   r!   r"   long	timestepsr@   torA   rB   rC   rD   )rE   rK   rL   s      r   set_timestepsz)ConsistencyDecoderScheduler.set_timestepsa   s    
 !##WXXXtSkFSSS#'#;#>#>v#F#F -1-O-R-RSY-Z-Z*knnV,,Z]]6**
ILL((			r   c                 2    | j         | j        d                  S )Nr   )rA   rO   )rE   s    r   init_noise_sigmaz,ConsistencyDecoderScheduler.init_noise_sigmap   s    1$.2CDDr   sampletimestepreturnc                 "    || j         |         z  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.
        )rD   )rE   rT   rU   s      r   scale_model_inputz-ConsistencyDecoderScheduler.scale_model_inputt   s     	(+++r   Tmodel_output	generatorreturn_dictc                    | j         |         |z  | j        |         |z  z   }t          j        | j        |k              d         }|t          | j                  dz
  k    r|}nt          |j        ||j        |j	                  }	| j
        | j        |dz                                         |j                  |z  | j        | j        |dz                                         |j                  |	z  z   }|s|fS t          |          S )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 the learned diffusion model.
            timestep (`float`):
                The current 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_consistency_models.ConsistencyDecoderSchedulerOutput`] or `tuple`.

        Returns:
            [`~schedulers.scheduling_consistency_models.ConsistencyDecoderSchedulerOutput`] or `tuple`:
                If return_dict is `True`,
                [`~schedulers.scheduling_consistency_models.ConsistencyDecoderSchedulerOutput`] is returned, otherwise
                a tuple is returned where the first element is the sample tensor.
        r   r   )rZ   r   rL   )r.   )rC   rB   r!   whererO   lenr   shaper   rL   r@   rP   rA   r-   )
rE   rY   rU   rT   rZ   r[   x_0timestep_idxr.   noises
             r   stepz ConsistencyDecoderScheduler.step   s   > j"\1DK4IF4RR{4>X#=>>qA3t~..222KK isyY\YcdddE(q8H)IJMMciXX[^^4T^LSTDT5UVYYZ]Zcddgllm 
  	">!0[IIIIr   )r8   r9   )NN)N)NT)r/   r0   r1   orderr	   intfloatrJ   r   r   strr!   rL   rQ   propertyrS   r3   rX   	Generatorboolr-   r   rc   r5   r   r   r7   r7   H   s       E $(S S S S S S S. .2+/) )%c]) c5<'() ) ) ) E E XE, , , ,Y^Ye , , , ,, 04 /J /Jl/J u|+,/J 	/J
 EO,/J /J 
0%7	8/J /J /J /J /J /Jr   r7   )r   r   )r   dataclassesr   typingr   r   r   r!   configuration_utilsr   r	   utilsr
   utils.torch_utilsr   scheduling_utilsr   r+   r-   r7   r5   r   r   <module>rq      s2    ! ! ! ! ! ! ) ) ) ) ) ) ) ) ) )  A A A A A A A A       , , , , , , , , , , , , !)4 )4 )4 )4X 
 
 
 
 

 
 
 
lJ lJ lJ lJ lJ.+ lJ lJ lJ lJ lJr   