
    wi#I                         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mZ ddlmZmZ ddlmZ dd	lmZ  ej        e          Ze G d
 de                      Z G d dee          ZdS )    )	dataclass)ListOptionalTupleUnionN   )ConfigMixinregister_to_config)
BaseOutputlogging)randn_tensor   )SchedulerMixinc                   (    e Zd ZU dZej        ed<   dS )$CMStochasticIterativeSchedulerOutputa>  
    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__torchTensor__annotations__     /root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/diffusers/schedulers/scheduling_consistency_models.pyr   r      s,           r   r   c                   6   e Zd ZdZdZe	 	 	 	 	 	 	 d/d
ededededededefd            Z	e
d             Ze
d             Zd0defdZdej        deeej        f         dej        fdZdeeej        f         fdZ	 	 	 d1dee         deeej        f         d eee                  fd!Zd" Zd# Zd$ Zd2d%Zd& Z	 	 d3d'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+ej        d,ej        d ej        dej        fd-Z#d. Z$dS )4CMStochasticIterativeSchedulera  
    Multistep and onestep sampling for consistency models.

    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 40):
            The number of diffusion steps to train the model.
        sigma_min (`float`, defaults to 0.002):
            Minimum noise magnitude in the sigma schedule. Defaults to 0.002 from the original implementation.
        sigma_max (`float`, defaults to 80.0):
            Maximum noise magnitude in the sigma schedule. Defaults to 80.0 from the original implementation.
        sigma_data (`float`, defaults to 0.5):
            The standard deviation of the data distribution from the EDM
            [paper](https://huggingface.co/papers/2206.00364). Defaults to 0.5 from the original implementation.
        s_noise (`float`, defaults to 1.0):
            The amount of additional noise to counteract loss of detail during sampling. A reasonable range is [1.000,
            1.011]. Defaults to 1.0 from the original implementation.
        rho (`float`, defaults to 7.0):
            The parameter for calculating the Karras sigma schedule from the EDM
            [paper](https://huggingface.co/papers/2206.00364). Defaults to 7.0 from the original implementation.
        clip_denoised (`bool`, defaults to `True`):
            Whether to clip the denoised outputs to `(-1, 1)`.
        timesteps (`List` or `np.ndarray` or `torch.Tensor`, *optional*):
            An explicit timestep schedule that can be optionally specified. The timesteps are expected to be in
            increasing order.
    r   (   Mb`?      T@      ?      ?      @Tnum_train_timesteps	sigma_min	sigma_max
sigma_datas_noiserhoclip_denoisedc                 |   || _         t          j        dd|          }|                     |          }	|                     |	          }
d | _        t          j        |	          | _        t          j        |
          | _	        d| _
        d| _        d | _        d | _        | j                            d          | _        d S )Nr   r   Fcpu)init_noise_sigmanplinspace_convert_to_karras
sigma_to_tnum_inference_stepsr   
from_numpysigmas	timestepscustom_timestepsis_scale_input_called_step_index_begin_indexto)selfr%   r&   r'   r(   r)   r*   r+   rampr5   r6   s              r   __init__z'CMStochasticIterativeScheduler.__init__L   s     !*{1a!455((..OOF++	 $( &v..))44 %%*" knnU++r   c                     | j         S )zg
        The index counter for current timestep. It will increase 1 after each scheduler step.
        )r9   r<   s    r   
step_indexz)CMStochasticIterativeScheduler.step_indexh   s    
 r   c                     | j         S )zq
        The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
        r:   r@   s    r   begin_indexz*CMStochasticIterativeScheduler.begin_indexo   s    
   r   r   rD   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.
        NrC   )r<   rD   s     r   set_begin_indexz.CMStochasticIterativeScheduler.set_begin_indexw   s     (r   sampletimestepreturnc                     | j         |                     |           | j        | j                  }||dz  | j        j        dz  z   dz  z  }d| _        |S )av  
        Scales the consistency model input by `(sigma**2 + sigma_data**2) ** 0.5`.

        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"   T)rA   _init_step_indexr5   configr(   r8   )r<   rG   rH   sigmas       r   scale_model_inputz0CMStochasticIterativeScheduler.scale_model_input   s]     ?"!!(+++DO,E1Ht{'=q'@@SHI%)"r   r5   c                     t          |t          j                  s t          j        |t          j                  }dt          j        |dz             z  }|S )ab  
        Gets scaled timesteps from the Karras sigmas for input to the consistency model.

        Args:
            sigmas (`float` or `np.ndarray`):
                A single Karras sigma or an array of Karras sigmas.

        Returns:
            `float` or `np.ndarray`:
                A scaled input timestep or scaled input timestep array.
        dtypeg     @o@ggE6)
isinstancer/   ndarrayarrayfloat64log)r<   r5   r6   s      r   r2   z)CMStochasticIterativeScheduler.sigma_to_t   sL     &"*-- 	8XfBJ777F"&%"8"88	r   Nr3   devicer6   c           	         ||t          d          ||t          d          |t          dt          |                    D ]&}||         ||dz
           k    rt          d          '|d         | j        j        k    rt          d| j        j         d          t          j        |t
          j        	          }d
| _        n|| j        j        k    r-t          d| d| j        j         d| j        j         d          || _	        | j        j        | j	        z  }t          j
        d|          |z                                  ddd                                                             t
          j                  }d| _        | j        j        }|ddd                                         }||dz
  z  }|                     |          }|                     |          }t          j        || j        j        gg                              t
          j                  }t'          j        |                              |          | _        t/          |                              d          r9t'          j        |                              |t&          j        	          | _        n-t'          j        |                              |          | _        d| _        d| _        | j                            d          | _        dS )a  
        Sets the 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.
            timesteps (`List[int]`, *optional*):
                Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
                timestep spacing strategy of equal spacing between timesteps is used. If `timesteps` is passed,
                `num_inference_steps` must be `None`.
        NzEExactly one of `num_inference_steps` or `timesteps` must be supplied.z:Can only pass one of `num_inference_steps` or `timesteps`.r   z(`timesteps` must be in descending order.r   z=`timesteps` must start before `self.config.train_timesteps`: .rP   Tz`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.F)rW   mpsr-   )
ValueErrorrangelenrL   r%   r/   rT   int64r7   r3   arangeroundcopyastyper1   r2   concatenater&   float32r   r4   r;   r5   str
startswithr6   r9   r:   )	r<   r3   rW   r6   i
step_ratior%   r=   r5   s	            r   set_timestepsz,CMStochasticIterativeScheduler.set_timesteps   s
   & &9+<deee*y/DYZZZ  1c)nn-- Q QQ<9QU#333$%OPPP 4 |t{>>> ;7; ; ;  
 "(;;;I$(D!!"T[%DDD M.A M M7M M $ ?M M M   (;D$8D<TTJ1&9::ZGNNPPQUQUSUQUV[[]]ddegemnnI$)D! #k=2##%%*Q./((..OOF++	$+*?)@ ABBII"*UU&v..111@@v;;!!%(( 	K"-i88;;F%-;XXDNN"-i88;;6;JJDN knnU++r   c                     | j         j        }| j         j        }| j         j        }|d|z  z  }|d|z  z  }||||z
  z  z   |z  }|S )z6Constructs the noise schedule of Karras et al. (2022).r   )rL   r&   r'   r*   )r<   r=   r&   r'   r*   min_inv_rhomax_inv_rhor5   s           r   r1   z1CMStochasticIterativeScheduler._convert_to_karras   s[      ;0	;0	koAG,AG,k(A BBsJr   c                 l    | j         j        }|dz  |dz  |dz  z   z  }||z  |dz  |dz  z   dz  z  }||fS )Nr   r"   )rL   r(   )r<   rM   r(   c_skipc_outs        r   get_scalingsz+CMStochasticIterativeScheduler.get_scalings  sR    [+
Q%(Z]":;
"eQhQ&>3%FFu}r   c                     | j         j        }| j         j        }|dz  ||z
  dz  |dz  z   z  }||z
  |z  |dz  |dz  z   dz  z  }||fS )a  
        Gets the scalings used in the consistency model parameterization (from Appendix C of the
        [paper](https://huggingface.co/papers/2303.01469)) to enforce boundary condition.

        <Tip>

        `epsilon` in the equations for `c_skip` and `c_out` is set to `sigma_min`.

        </Tip>

        Args:
            sigma (`torch.Tensor`):
                The current sigma in the Karras sigma schedule.

        Returns:
            `tuple`:
                A two-element tuple where `c_skip` (which weights the current sample) is the first element and `c_out`
                (which weights the consistency model output) is the second element.
        r   r"   )rL   r&   r(   )r<   rM   r&   r(   ro   rp   s         r   #get_scalings_for_boundary_conditionzBCMStochasticIterativeScheduler.get_scalings_for_boundary_condition  sj    ( K)	[+
Q59#4":Z]"JK"j0E1Hz1}4LQT3TTu}r   c                     || j         }||k                                    }t          |          dk    rdnd}||                                         S )Nr   r   )r6   nonzeror^   item)r<   rH   schedule_timestepsindicesposs        r   index_for_timestepz1CMStochasticIterativeScheduler.index_for_timestep'  sW    %!%%1::<< w<<!##aas|  """r   c                     | j         Ut          |t          j                  r|                    | j        j                  }|                     |          | _        d S | j	        | _        d S N)
rD   rR   r   r   r;   r6   rW   rz   r9   r:   )r<   rH   s     r   rK   z/CMStochasticIterativeScheduler._init_step_index6  sb    #(EL11 >#;;t~'<==#66x@@D#0Dr   model_output	generatorreturn_dictc                    t          |t          t          j        t          j        f          rt          d| j         d          | j        st          	                    d           | j
        j        }| j
        j        }| j        |                     |           | j        | j                 }| j        dz   | j
        j        k     r| j        | j        dz            }	n| j        d         }	|                     |          \  }
}||z  |
|z  z   }| j
        j        r|                    dd          }t)          | j                  dk    r#t-          |j        |j        |j        |          }nt          j        |          }|| j
        j        z  }|	                    ||          }|||d	z  |d	z  z
  d
z  z  z   }| xj        dz  c_        |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.CMStochasticIterativeSchedulerOutput`] or `tuple`.

        Returns:
            [`~schedulers.scheduling_consistency_models.CMStochasticIterativeSchedulerOutput`] or `tuple`:
                If return_dict is `True`,
                [`~schedulers.scheduling_consistency_models.CMStochasticIterativeSchedulerOutput`] is returned,
                otherwise a tuple is returned where the first element is the sample tensor.
        zLPassing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to `z\.step()` is not supported. Make sure to pass one of the `scheduler.timesteps` as a timestep.zThe `scale_model_input` function should be called before `step` to ensure correct denoising. See `StableDiffusionPipeline` for a usage example.Nr   rZ   )rQ   rW   r~   )minmaxr   r"   )r   )rR   intr   	IntTensor
LongTensorr\   	__class__r8   loggerwarningrL   r&   r'   rA   rK   r5   r%   rs   r+   clampr^   r6   r   shaperQ   rW   
zeros_liker)   r9   r   )r<   r}   rH   rG   r~   r   r&   r'   rM   
sigma_nextro   rp   denoisednoisez	sigma_hatr   s                    r   stepz#CMStochasticIterativeScheduler.step>  s   @ heou7G HII 	GG G G   ) 	NNE  
 K)	K)	?"!!(+++ DO,?Q!@@@T_q%89JJ RJ @@GG <'&6/9;$ 	-~~b!,,H t~"" ",*<\EXdm  EE $\22EDK''$$	$BB	 ilY\&Ac%I!II 	A 	">!3LLLLr   original_samplesr   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)rW   rQ   r[   rP   c                 <    g | ]}                     |          S r   )rz   ).0trw   r<   s     r   
<listcomp>z<CMStochasticIterativeScheduler.add_noise.<locals>.<listcomp>  s*    ^^^qD33A7IJJ^^^r   r   rZ   )r5   r;   rW   rQ   typer   is_floating_pointr6   re   rD   rA   r   flattenr^   	unsqueeze)	r<   r   r   r6   r5   step_indicesrM   noisy_samplesrw   s	   `       @r   	add_noisez(CMStochasticIterativeScheduler.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|   )rL   r%   r@   s    r   __len__z&CMStochasticIterativeScheduler.__len__  s    {..r   )r   r    r!   r"   r#   r$   T)r   )NNNr|   )NT)%r   r   r   r   orderr
   r   floatboolr>   propertyrA   rD   rF   r   r   r   rN   r/   rS   r2   r   rf   rW   r   rj   r1   rq   rs   rz   rK   	Generatorr   r   r   r   r   r   r   r   r   r   ,   s        : E $& ", , , , 	,
 , , , , , , ,6     X  ! ! X!( (3 ( ( ( ( eU\FY@Z _d_k    2ubj'8!9    * .2+/)-	H, H,%c]H, c5<'(H, DI&	H, H, H, H,V
 
 
    8# # # #1 1 1 04 [M [Ml[M u|+,[M 	[M
 EO,[M [M 
3U:	;[M [M [M [M|, | <	
 
   B/ / / / /r   r   )dataclassesr   typingr   r   r   r   numpyr/   r   configuration_utilsr	   r
   utilsr   r   utils.torch_utilsr   scheduling_utilsr   
get_loggerr   r   r   r   r   r   r   <module>r      s0   " ! ! ! ! ! / / / / / / / / / / / /      A A A A A A A A ' ' ' ' ' ' ' ' , , , , , , , , , , , , 
	H	%	% 
 
 
 
 
: 
 
 
R/ R/ R/ R/ R/^[ R/ R/ R/ R/ R/r   