
    wi^                         d dl Z d dlmZmZmZmZ d dlZd dlZd dl	Z	ddl
mZmZ ddlmZmZmZ  G d d          Z G d	 d
          Z	 	 ddZ G d dee          ZdS )    N)ListOptionalTupleUnion   )ConfigMixinregister_to_config   )KarrasDiffusionSchedulersSchedulerMixinSchedulerOutputc                   6    e Zd ZdZddZed             Zd ZdS )BatchedBrownianTreezGA wrapper around torchsde.BrownianTree that enables batches of entropy.Nc                    |                                \  | _                            dt          j        |                    |(t          j        ddg                                           }d| _        	 t          |          |j	        d         k    sJ d         n# t          $ r |g}d| _        Y nw xY wfd|D             | _        d S )Nw0r   l    TFc                 <    g | ]}t          j        fd |iS )entropy)torchsdeBrownianTree).0skwargst0t1r   s     }/root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/diffusers/schedulers/scheduling_dpmsolver_sde.py
<listcomp>z0BatchedBrownianTree.__init__.<locals>.<listcomp>)   s6    [[[QRh+BBLLLVLL[[[    )sortsigngettorch
zeros_likerandintitembatchedlenshape	TypeErrortrees)selfxr   r   seedr   r   s     `` `@r   __init__zBatchedBrownianTree.__init__   s     IIb"--B	ZZe.q1122<=Ir227799D	!t99
****ABB 	! 	! 	!6D DLLL	! \[[[[[[VZ[[[


s   >(B' 'B>=B>c                 "    | |k     r| |dfn|| dfS )Nr
    )abs     r   r   zBatchedBrownianTree.sort+   s     EE1ayy1bz1r   c                     |                                \  }t          j        fd| j        D                       | j        |z  z  }| j        r|n|d         S )Nc                 (    g | ]} |          S r0   r0   )r   treer   r   s     r   r   z0BatchedBrownianTree.__call__.<locals>.<listcomp>1   s#    ===$b"===r   r   )r   r!   stackr)   r   r%   )r*   r   r   r   ws    ``  r   __call__zBatchedBrownianTree.__call__/   sg    yyR((BK=====$*===>>$)dBRSL*qqad*r   N)__name__
__module____qualname____doc__r-   staticmethodr   r8   r0   r   r   r   r      s\        QQ\ \ \ \ 2 2 \2+ + + + +r   r   c                   &    e Zd ZdZdd fdZd ZdS )BrownianTreeNoiseSampleras  A noise sampler backed by a torchsde.BrownianTree.

    Args:
        x (Tensor): The tensor whose shape, device and dtype to use to generate
            random samples.
        sigma_min (float): The low end of the valid interval.
        sigma_max (float): The high end of the valid interval.
        seed (int or List[int]): The random seed. If a list of seeds is
            supplied instead of a single integer, then the noise sampler will use one BrownianTree per batch item, each
            with its own seed.
        transform (callable): A function that maps sigma to the sampler's
            internal timestep.
    Nc                     | S r9   r0   )r+   s    r   <lambda>z!BrownianTreeNoiseSampler.<lambda>D   s    q r   c                     || _         |                      t          j        |                    |                      t          j        |                    }}t          ||||          | _        d S r9   )	transformr!   	as_tensorr   r5   )r*   r+   	sigma_min	sigma_maxr,   rD   r   r   s           r   r-   z!BrownianTreeNoiseSampler.__init__D   sX    "	 : :;;T^^EO\eLfLf=g=gB'2r488			r   c                    |                      t          j        |                    |                      t          j        |                    }}|                     ||          ||z
                                                                  z  S r9   )rD   r!   rE   r5   abssqrt)r*   sigma
sigma_nextr   r   s        r   r8   z!BrownianTreeNoiseSampler.__call__I   si     6 677XbHcHc9d9dByyR  BG==??#7#7#9#999r   )r:   r;   r<   r=   r-   r8   r0   r   r   r@   r@   5   sJ          6:[[ 9 9 9 9
: : : : :r   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
    rN   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_fnh   s,    8QY%/$'9A=>>!CCr   expc                 0    t          j        | dz            S )Ng      ()rQ   rW   rT   s    r   rV   z)betas_for_alpha_bar.<locals>.alpha_bar_fnm   s    8AI&&&r   z"Unsupported alpha_transform_type: r
   dtype)
ValueErrorrangeappendminr!   tensorfloat32)num_diffusion_timestepsmax_betaalpha_transform_typerV   betasir   t2s           r   betas_for_alpha_barrg   O   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dZd eD             ZdZe	 	 	 	 	 	 	 	 	 	 d6dede	de	de
deeej        ee	         f                  de
dee         dee         de
defd            Zd7dZd Zed             Zed             Zed             Zd8defdZdej        d ee	ej        f         d!ej        fd"Z	 	 d9d#ed$ee
ej        f         dee         fd%Zd& Zd' Zd(ej        d!ej        fd)Z ed*             Z!	 	 d:d-eej        ej        f         d ee	ej        f         deej        ej        f         d.ed/e	d!ee"e#f         fd0Z$d1ej        d2ej        d3ej        d!ej        fd4Z%d5 Z&dS );DPMSolverSDEScheduleru  
    DPMSolverSDEScheduler implements the stochastic sampler from the [Elucidating the Design Space of Diffusion-Based
    Generative Models](https://huggingface.co/papers/2206.00364) paper.

    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.00085):
            The starting `beta` value of inference.
        beta_end (`float`, defaults to 0.012):
            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`.
        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).
        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}.
        noise_sampler_seed (`int`, *optional*, defaults to `None`):
            The random seed to use for the noise sampler. If `None`, a random seed is generated.
        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 r0   )name)r   es     r   r   z DPMSolverSDEScheduler.<listcomp>   s    >>>qAF>>>r   r     _QK?~jt?linearNepsilonFlinspacer   num_train_timesteps
beta_startbeta_endbeta_scheduletrained_betasprediction_typeuse_karras_sigmasnoise_sampler_seed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	
          | _
        |                     |d |           || _        d | _        || _        d | _        d | _        | j                            d          | _        d S )NrY   rp   scaled_linear      ?r   squaredcos_cap_v2z is not implemented for       ?r   )dimcpu)r!   r_   r`   rd   rr   rg   NotImplementedError	__class__alphascumprodalphas_cumprodset_timestepsry   noise_samplerrz   _step_index_begin_indexsigmasto)r*   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   s              r   r-   zDPMSolverSDEScheduler.__init__   sL    $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??? 	.6IJJJ!2!"4 knnU++r   c                     || j         }||k                                    }t          |          dk    rdnd}||                                         S )Nr
   r   )	timestepsnonzeror&   r$   )r*   timestepschedule_timestepsindicesposs        r   index_for_timestepz(DPMSolverSDEScheduler.index_for_timestep   sW    %!%%1::<< w<<!##aas|  """r   c                     | j         Ut          |t          j                  r|                    | j        j                  }|                     |          | _        d S | j	        | _        d S r9   )
begin_index
isinstancer!   Tensorr   r   devicer   r   r   )r*   r   s     r   _init_step_indexz&DPMSolverSDEScheduler._init_step_index   sb    #(EL11 >#;;t~'<==#66x@@D#0Dr   c                     | j         j        dv r| j                                        S | j                                        dz  dz   dz  S )N)rr   trailingr   r
   r   )configr{   r   maxr*   s    r   init_noise_sigmaz&DPMSolverSDEScheduler.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.
        )r   r   s    r   
step_indexz DPMSolverSDEScheduler.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.
        r   r   s    r   r   z!DPMSolverSDEScheduler.begin_index   s    
   r   r   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.
        Nr   )r*   r   s     r   set_begin_indexz%DPMSolverSDEScheduler.set_begin_index   s     (r   sampler   returnc                     | j         |                     |           | j        | j                  }| j        r|n| j        }||dz  dz   dz  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.
        Nr   r
   r   )r   r   r   state_in_first_ordermid_point_sigma)r*   r   r   rK   sigma_inputs        r   scale_model_inputz'DPMSolverSDEScheduler.scale_model_input  s_    & ?"!!(+++DO,#8Reed>RKNQ.367r   num_inference_stepsr   c           	          | _         |p j        j        } j        j        dk    r=t	          j        d|dz
  |t                    ddd                                         }n j        j        dk    rw| j         z  }t	          j        d|          |z  	                                ddd                                         
                    t                    }| j        j        z  }n j        j        dk    rc| j         z  }t	          j        |d|           	                                                                
                    t                    }|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         |dd                             d          |dd         g           _        t/          j        |          }t/          j        |          }t/          j        |dd         |dd                             d          g          }||ddd<   t;          |                              d          r'|                    |t.          j                   _        n|                    |           _        d _         d _!        d _"        d _#         j                            d           _        d _$        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.
        rr   r   r
   rY   Nr/   leadingr   zY is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.r   )	in_sigmasc                 <    g | ]}                     |          S r0   _sigma_to_tr   rK   
log_sigmasr*   s     r   r   z7DPMSolverSDEScheduler.set_timesteps.<locals>.<listcomp>J  s)    !Z!Z!Z%$"2"25*"E"E!Z!Z!Zr   g        )r   r   mpsr   )%r   r   rs   r{   nprr   floatcopyarangeroundastyper|   r[   arrayr   loginterpr&   ry   _convert_to_karras_second_order_timestepsconcatenater`   r!   
from_numpyr   catrepeat_interleaver   str
startswithr   r   r   r   r   r   )	r*   r   r   rs   r   
step_ratior   second_order_timestepsr   s	   `       @r   r   z#DPMSolverSDEScheduler.set_timesteps  s    $7 1TT[5T ;':55A':Q'>@S[`aaabfbfdfbfgllnnII[)Y66,0HHJ 1&9::ZGNNPPQUQUSUQUV[[]]ddejkkI11II[)Z77,t/GGJ #6J;GGNNPPUUWW^^_deeI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!%!=!=fj!Q!Q#0077
CC!&)),,F,;;iVAbD\-K-KA-N-NPVWYWZWZP[ \]]$Y//	!&!12H!I!IIy!}im.M.Ma.P.PQRR	0	!$Q$v;;!!%(( 	9&\\&\FFDNN&\\\88DN # knnU++!r   c                      d }d }d} ||          }t          j        |          }|d d         ||z  z   } ||          }	t          j         fd|	D                       }
|
S )Nc                 ,    t          j        |            S r9   )r   rW   _ts    r   sigma_fnz?DPMSolverSDEScheduler._second_order_timesteps.<locals>.sigma_fng  s    62#;;r   c                 ,    t          j        |            S r9   )r   r   _sigmas    r   t_fnz;DPMSolverSDEScheduler._second_order_timesteps.<locals>.t_fnj  s    F6NN?"r   r   r/   c                 <    g | ]}                     |          S r0   r   r   s     r   r   zADPMSolverSDEScheduler._second_order_timesteps.<locals>.<listcomp>r  s)    \\\ed..ujAA\\\r   )r   diffr   )r*   r   r   r   r   midpoint_ratiorU   
delta_time
t_proposedsig_proposedr   s   ` `        r   r   z-DPMSolverSDEScheduler._second_order_timestepsf  s    	 	 		# 	# 	# DLLWQZZ
ssVj>99
x
++H\\\\\|\\\]]	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   )r   r
   )	r   r   maximumnewaxiscumsumargmaxclipr'   reshape)r*   rK   r   	log_sigmadistslow_idxhigh_idxlowhighr7   rU   s              r   r   z!DPMSolverSDEScheduler._sigma_to_tv  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).r/   r   g      @r
   )r$   r   rr   r   )	r*   r   rF   rG   rhorampmin_inv_rhomax_inv_rhor   s	            r   r   z(DPMSolverSDEScheduler._convert_to_karras  s     %R=--//	$Q<,,..	{1a!9::AG,AG,k(A BBsJr   c                     | j         d u S r9   )r   r   s    r   r   z*DPMSolverSDEScheduler.state_in_first_order  s    {d""r   Tr   model_outputreturn_dicts_noisec                 8   | j         |                     |           | j        ]| j        | j        dk                                             | j                                        }}t          |||| j                  | _        dt          j	        dt          j	        fd}dt          j	        dt          j	        fd}	| j
        r(| j        | j                  }
| j        | j         dz            }n'| j        | j         dz
           }
| j        | j                  }d	} |	|
           |	|          }}||z
  }|||z  z   }| j        j        d
k    r| j
        r|
n
 ||          }|||z  z
  }n| j        j        dk    r3| j
        r|
n
 ||          }|| |dz  dz   d	z  z  z  ||dz  dz   z  z   }n<| j        j        dk    rt          d          t          d| j        j         d          |dk    r||z
  |
z  }||
z
  }|||z  z   }n| j
        r|}n| j        } ||          } ||          }t	          ||dz  |dz  |dz  z
  z  |dz  z  d	z            }|dz  |dz  z
  d	z  } |	|          } ||           ||          z  |z  ||z
                                  |z  z
  }||                      ||           ||                    |z  |z  z   }| j
        r|| _         ||          | _        nd| _        d| _        | 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` or `np.ndarray`):
                The direct output from learned diffusion model.
            timestep (`float` or `torch.Tensor`):
                The current discrete timestep in the diffusion chain.
            sample (`torch.Tensor` or `np.ndarray`):
                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_utils.SchedulerOutput`] or tuple.
            s_noise (`float`, *optional*, defaults to 1.0):
                Scaling factor for noise added to the sample.

        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.
        Nr   r   r   c                 N    |                                                                  S r9   )negrW   r   s    r   r   z,DPMSolverSDEScheduler.step.<locals>.sigma_fn  s    6688<<>>!r   r   c                 N    |                                                                  S r9   )r   r   r   s    r   r   z(DPMSolverSDEScheduler.step.<locals>.t_fn  s    ::<<##%%%r   r
   r   rq   v_predictionr   r   z+prediction_type not implemented yet: samplezprediction_type given as z, must be one of `epsilon`, or `v_prediction`)prev_sample)r   r   r   r   r^   r   r@   rz   r!   r   r   r   rx   r   r[   r   expm1r   r   r   )r*   r   r   r   r   r   	min_sigma	max_sigmar   r   rK   rL   r   rU   t_nextr   r   r   pred_original_sample
derivativedtr   
sigma_fromsigma_tosigma_up
sigma_downancestral_ts                              r   stepzDPMSolverSDEScheduler.step  s   : ?"!!(+++ %#';t{Q#?#C#C#E#Et{GXGXyI!9&)YX\Xo!p!pD	" 	"%, 	" 	" 	" 	"	& 	&%, 	& 	& 	& 	& $ 	6K0ET_q%89JJ K! 34ET_5J DKKj!1!16aZ
n44
 ;&)33#'#<V%%((:BVBVK#)K,,F#F  [(N::#'#<V%%((:BVBVK#/K<;PQ>TUCUZ]B]3]#^+q.1,-$   [(H44%&STTTuDK,Guuu   ?? #775@Je#B :?2KK( %#!!Jx''H8hkZ]Xq[5P&QT^`aTa&afi%ijjH"A+!3;J$z**K#8K0088A;;>&HKegg,L- -K &(:(:88A;;QWHXHX(Y(Y\c(cfn(nnK( ,$'/x'7'7$$ #'+$ 	A 	">!;7777r   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   rZ   r   rY   c                 <    g | ]}                     |          S r0   )r   )r   rU   r   r*   s     r   r   z3DPMSolverSDEScheduler.add_noise.<locals>.<listcomp>!  s*    ^^^qD33A7IJJ^^^r   r   r/   )r   r   r   rZ   typer!   is_floating_pointr   r`   r   r   r'   flattenr&   	unsqueeze)	r*   r  r  r   r   step_indicesrK   noisy_samplesr   s	   `       @r   	add_noisezDPMSolverSDEScheduler.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 r9   )r   rs   r   s    r   __len__zDPMSolverSDEScheduler.__len__0  s    {..r   )
rm   rn   ro   rp   Nrq   FNrr   r   r9   )r   )NN)Tr   )'r:   r;   r<   r=   r   _compatiblesorderr	   intr   r   r   r   r   ndarrayr   boolr-   r   r   propertyr   r   r   r   r!   r   r   r   r   r   r   r   r   r   r   r  r  r  r0   r   r   ri   ri   {   sr       ! !F ?>$=>>>LE $(#%BF(,1,0 *$, $, $, $, 	$,
 $,  bj$u+&= >?$, $, $D>$, %SM$, $, $, $, $, $,N# # # #1 1 1 3 3 X3     X  ! ! X!( (3 ( ( ( ( u|+, 
	   < ,0-1	G" G" G" c5<'(G" &c]	G" G" G" G"R     0EL U\     # # X# !m8 m8EL"*45m8 u|+,m8 elBJ./	m8
 m8 m8 
%	&m8 m8 m8 m8`, | <	
 
   B/ / / / /r   ri   )rM   rN   )rQ   typingr   r   r   r   numpyr   r!   r   configuration_utilsr   r	   scheduling_utilsr   r   r   r   r@   rg   ri   r0   r   r   <module>r     s5    / / / / / / / / / / / /       A A A A A A A A X X X X X X X X X X+ + + + + + + +6: : : : : : : :8 !)4 )4 )4 )4Xv/ v/ v/ v/ v/NK v/ v/ v/ v/ v/r   