
    bi)a                     x    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	m
Z
mZ ddlmZ ddlmZmZ  G d d	ee
      Zy)
    N)ListOptionalTupleUnion   )ConfigMixinregister_to_config   )BrownianTreeNoiseSampler)SchedulerMixinSchedulerOutputc                      e Zd ZdZg ZdZe	 	 	 	 	 	 	 	 	 	 	 	 d3dedededede	de	d	ed
edede
de
dee   fd       Zed        Zed        Zed        Zd4de	fdZd Zd Zd Zdej,                  deeej,                  f   dej,                  fdZd5de	deeej2                  f   fdZd5dej,                  fd Zd5dej,                  fd!Zd" Zd# Z	 d6d$ej,                  dej,                  dej,                  fd%Z	 	 d5d$ej,                  dej,                  d&eej,                     dej,                  fd'Z 	 	 d5d(e!ej,                     dej,                  d&eej,                     dej,                  fd)Z"d6d*Z#d+ Z$	 	 d7d$ej,                  dee	ej,                  f   d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d0Z(d1 Z)d2 Z*y)8!CosineDPMSolverMultistepSchedulerag  
    Implements a variant of `DPMSolverMultistepScheduler` with cosine schedule, proposed by Nichol and Dhariwal (2021).
    This scheduler was used in Stable Audio Open [1].

    [1] Evans, Parker, et al. "Stable Audio Open" https://huggingface.co/papers/2407.14358

    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:
        sigma_min (`float`, *optional*, defaults to 0.3):
            Minimum noise magnitude in the sigma schedule. This was set to 0.3 in Stable Audio Open [1].
        sigma_max (`float`, *optional*, defaults to 500):
            Maximum noise magnitude in the sigma schedule. This was set to 500 in Stable Audio Open [1].
        sigma_data (`float`, *optional*, defaults to 1.0):
            The standard deviation of the data distribution. This is set to 1.0 in Stable Audio Open [1].
        sigma_schedule (`str`, *optional*, defaults to `exponential`):
            Sigma schedule to compute the `sigmas`. By default, we the schedule introduced in the EDM paper
            (https://huggingface.co/papers/2206.00364). Other acceptable value is "exponential". The exponential
            schedule was incorporated in this model: https://huggingface.co/stabilityai/cosxl.
        num_train_timesteps (`int`, defaults to 1000):
            The number of diffusion steps to train the model.
        solver_order (`int`, defaults to 2):
            The DPMSolver order which can be `1` or `2`. It is recommended to use `solver_order=2`.
        prediction_type (`str`, defaults to `v_prediction`, *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).
        solver_type (`str`, defaults to `midpoint`):
            Solver type for the second-order solver; can be `midpoint` or `heun`. The solver type slightly affects the
            sample quality, especially for a small number of steps. It is recommended to use `midpoint` solvers.
        lower_order_final (`bool`, defaults to `True`):
            Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. This can
            stabilize the sampling of DPMSolver for steps < 15, especially for steps <= 10.
        euler_at_final (`bool`, defaults to `False`):
            Whether to use Euler's method in the final step. It is a trade-off between numerical stability and detail
            richness. This can stabilize the sampling of the SDE variant of DPMSolver for small number of inference
            steps, but sometimes may result in blurring.
        final_sigmas_type (`str`, defaults to `"zero"`):
            The final `sigma` value for the noise schedule during the sampling process. If `"sigma_min"`, the final
            sigma is the same as the last sigma in the training schedule. If `zero`, the final sigma is set to 0.
    r
   	sigma_min	sigma_max
sigma_datasigma_schedulenum_train_timestepssolver_orderprediction_typerhosolver_typelower_order_finaleuler_at_finalfinal_sigmas_typec                 &   |	dvr1|	dv r| j                  d       nt        |	 d| j                         t        j                  dd|      }|dk(  r| j                  |      }n|d	k(  r| j                  |      }| j                        | _        t        j                  |t        j                  d|j                  
      g      | _        d | _        d g|z  | _        d| _        d | _        d | _        | j                  j%                  d      | _        y )N)midpointheun)logrhobh1bh2r   )r   z is not implemented for r   r
   karrasexponential)devicecpu)r	   NotImplementedError	__class__torchlinspace_compute_karras_sigmas_compute_exponential_sigmasprecondition_noise	timestepscatzerosr$   sigmasnum_inference_stepsmodel_outputslower_order_nums_step_index_begin_indexto)selfr   r   r   r   r   r   r   r   r   r   r   r   rampr0   s                  u/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py__init__z*CosineDPMSolverMultistepScheduler.__init__K   s     2266''J'?)[M9QRVR`R`Qa*bcc~~a$78X%006F},55d;F008iiQv}})M NO $( "Vl2 ! kknnU+    c                 @    | j                   j                  dz  dz   dz  S )Nr   r
         ?)configr   r7   s    r9   init_noise_sigmaz2CosineDPMSolverMultistepScheduler.init_noise_sigmas   s#     %%q(1,44r;   c                     | j                   S )zg
        The index counter for current timestep. It will increase 1 after each scheduler step.
        )r4   r?   s    r9   
step_indexz,CosineDPMSolverMultistepScheduler.step_indexx   s    
 r;   c                     | j                   S )zq
        The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
        r5   r?   s    r9   begin_indexz-CosineDPMSolverMultistepScheduler.begin_index   s    
    r;   rE   c                     || _         y)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.
        NrD   )r7   rE   s     r9   set_begin_indexz1CosineDPMSolverMultistepScheduler.set_begin_index   s     (r;   c                 2    | j                  |      }||z  }|S N)_get_conditioning_c_in)r7   samplesigmac_inscaled_samples        r9   precondition_inputsz5CosineDPMSolverMultistepScheduler.precondition_inputs   s!    **51r;   c                     t        |t        j                        st        j                  |g      }|j	                         t
        j                  z  dz  S )Nr   )
isinstancer(   Tensortensoratanmathpi)r7   rL   s     r9   r,   z4CosineDPMSolverMultistepScheduler.precondition_noise   s:    %.LL%)Ezz|dgg%))r;   c                 j   | j                   j                  }|dz  |dz  |dz  z   z  }| j                   j                  dk(  r||z  |dz  |dz  z   dz  z  }nR| j                   j                  dk(  r| |z  |dz  |dz  z   dz  z  }n#t        d| j                   j                   d      ||z  ||z  z   }|S )Nr   epsilonr=   v_predictionzPrediction type z is not supported.)r>   r   r   
ValueError)r7   rK   model_outputrL   r   c_skipc_outdenoiseds           r9   precondition_outputsz6CosineDPMSolverMultistepScheduler.precondition_outputs   s    [[++
Q%(Z]":;;;&&)3J&%(Z]*Bs)JJE[[((N:FZ'5!8j!m+C*KKE/0K0K/LL^_``F?U\%99r;   rK   timestepreturnc                     | j                   | j                  |       | j                  | j                      }| j                  ||      }d| _        |S )a   
        Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
        current timestep. Scales the denoising model input by `(sigma**2 + 1) ** 0.5` to match the Euler algorithm.

        Args:
            sample (`torch.Tensor`):
                The input sample.
            timestep (`int`, *optional*):
                The current timestep in the diffusion chain.

        Returns:
            `torch.Tensor`:
                A scaled input sample.
        T)rB   _init_step_indexr0   rO   is_scale_input_called)r7   rK   r`   rL   s       r9   scale_model_inputz3CosineDPMSolverMultistepScheduler.scale_model_input   sM     ??"!!(+DOO,))&%8%)"r;   Nr1   r$   c                    || _         t        j                  dd| j                         }| j                  j                  dk(  r| j                  |      }n*| j                  j                  dk(  r| j                  |      }j                  t        j                  |      }| j                  |      | _
        | j                  j                  dk(  r| j                  j                  }n>| j                  j                  dk(  rd}n"t        d| j                  j                         t        j                  |t        j                  |gt        j                  |      g      | _        d	g| j                  j"                  z  | _        d| _        d	| _        d	| _        | j                   j                  d
      | _        d	| _        y	)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.
        r   r
   r"   r#   )dtyper$   r   zerozC`final_sigmas_type` must be one of 'zero', or 'sigma_min', but got Nr%   )r1   r(   r)   r>   r   r*   r+   r6   float32r,   r-   r   r   rZ   r.   rS   r0   r   r2   r3   r4   r5   noise_sampler)r7   r1   r$   r8   r0   
sigma_lasts         r9   set_timestepsz/CosineDPMSolverMultistepScheduler.set_timesteps   ss    $7 ~~aD$<$<=;;%%1006F[[''=855d;Fv>008;;((K7..J[[**f4JUVZVaVaVsVsUtu  iizl%--`f)g hi 
KK$$% !"   kknnU+ "r;   c                     |xs | j                   j                  }|xs | 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
   )r>   r   r   r   )r7   r8   r   r   r   min_inv_rhomax_inv_rhor0   s           r9   r*   z8CosineDPMSolverMultistepScheduler._compute_karras_sigmas   sq    6!6!6	6!6!6	kkooAG,AG,k(A BBsJr;   c                 4   |xs | j                   j                  }|xs | j                   j                  }t        j                  t        j                  |      t        j                  |      t        |            j                         j                  d      }|S )zImplementation closely follows k-diffusion.

        https://github.com/crowsonkb/k-diffusion/blob/6ab5146d4a5ef63901326489f31f1d8e7dd36b48/k_diffusion/sampling.py#L26
        r   )
r>   r   r   r(   r)   rU   loglenexpflip)r7   r8   r   r   r0   s        r9   r+   z=CosineDPMSolverMultistepScheduler._compute_exponential_sigmas  sn    
 6!6!6	6!6!6	 3TXXi5H#d)TXXZ__`abr;   c                    t        j                  t        j                  |d            }||d d t         j                  f   z
  }t        j                  |dk\  d      j                  d      j                  |j                  d   dz
        }|dz   }||   }||   }||z
  ||z
  z  }	t        j                  |	dd      }	d|	z
  |z  |	|z  z   }
|
j                  |j                        }
|
S )Ng|=r   )axisr   )maxr
   )	nprq   maximumnewaxiscumsumargmaxclipshapereshape)r7   rL   
log_sigmas	log_sigmadistslow_idxhigh_idxlowhighwts              r9   _sigma_to_tz-CosineDPMSolverMultistepScheduler._sigma_to_t  s    FF2::eU34	 Jq"**}55 ))UaZq188a8@EE*JZJZ[\J]`aJaEbQ;!(# 9_t,GGAq! UgH,IIekk"r;   c                 8    t        j                  d      }|}||fS )Nr
   )r(   rS   )r7   rL   alpha_tsigma_ts       r9   _sigma_to_alpha_sigma_tz9CosineDPMSolverMultistepScheduler._sigma_to_alpha_sigma_t#  s    ,,q/r;   r[   c                 ^    | j                   | j                     }| j                  |||      }|S )a0  
        Convert the model output to the corresponding type the DPMSolver/DPMSolver++ algorithm needs. DPM-Solver is
        designed to discretize an integral of the noise prediction model, and DPM-Solver++ is designed to discretize an
        integral of the data prediction model.

        <Tip>

        The algorithm and model type are decoupled. You can use either DPMSolver or DPMSolver++ for both noise
        prediction and data prediction models.

        </Tip>

        Args:
            model_output (`torch.Tensor`):
                The direct output from the learned diffusion model.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.

        Returns:
            `torch.Tensor`:
                The converted model output.
        )r0   rB   r_   )r7   r[   rK   rL   x0_preds        r9   convert_model_outputz6CosineDPMSolverMultistepScheduler.convert_model_output)  s/    6 DOO,++FL%Hr;   noisec           	      j   | j                   | j                  dz      | j                   | j                     }}| j                  |      \  }}| j                  |      \  }}t        j                  |      t        j                  |      z
  }t        j                  |      t        j                  |      z
  }	||	z
  }
|J ||z  t        j
                  |
       z  |z  |dt        j
                  d|
z        z
  z  |z  z   |t        j                  dt        j
                  d|
z        z
        z  |z  z   }|S )a  
        One step for the first-order DPMSolver (equivalent to DDIM).

        Args:
            model_output (`torch.Tensor`):
                The direct output from the learned diffusion model.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.

        Returns:
            `torch.Tensor`:
                The sample tensor at the previous timestep.
        r
                ?)r0   rB   r   r(   rq   rs   sqrt)r7   r[   rK   r   r   sigma_sr   alpha_slambda_tlambda_shx_ts               r9   dpm_solver_first_order_updatez?CosineDPMSolverMultistepScheduler.dpm_solver_first_order_updateI  s   &  ;;t':;T[[=Y77@77@99W%		'(::99W%		'(::x   wA2.&8!eiiq112lBC

326):#:;;eCD 	 
r;   model_output_listc           	      V   | j                   | j                  dz      | j                   | j                     | j                   | j                  dz
     }}}| j                  |      \  }}| j                  |      \  }}| j                  |      \  }	}t        j                  |      t        j                  |      z
  }
t        j                  |      t        j                  |      z
  }t        j                  |	      t        j                  |      z
  }|d   |d   }}|
|z
  ||z
  }}||z  }|d|z  ||z
  z  }}|J | j
                  j                  dk(  r||z  t        j                  |       z  |z  |dt        j                  d|z        z
  z  |z  z   d|dt        j                  d|z        z
  z  z  |z  z   |t        j                  dt        j                  d|z        z
        z  |z  z   }|S | j
                  j                  dk(  r||z  t        j                  |       z  |z  |dt        j                  d|z        z
  z  |z  z   |dt        j                  d|z        z
  d|z  z  dz   z  |z  z   |t        j                  dt        j                  d|z        z
        z  |z  z   }S )	a  
        One step for the second-order multistep DPMSolver.

        Args:
            model_output_list (`List[torch.Tensor]`):
                The direct outputs from learned diffusion model at current and latter timesteps.
            sample (`torch.Tensor`):
                A current instance of a sample created by the diffusion process.

        Returns:
            `torch.Tensor`:
                The sample tensor at the previous timestep.
        r
   r   r   r   r   r=   r   )	r0   rB   r   r(   rq   r>   r   rs   r   )r7   r   rK   r   r   sigma_s0sigma_s1r   alpha_s0alpha_s1r   	lambda_s0	lambda_s1m0m1r   h_0r0D0D1r   s                        r9   (multistep_dpm_solver_second_order_updatezJCosineDPMSolverMultistepScheduler.multistep_dpm_solver_second_order_updatel  s   ( KK!+,KK(KK!+, $  77@!99(C(!99(C(99W%		'(::IIh'%))H*==	IIh'%))H*==	"2&(9"(=BI%y9'<31WcBh27+B    ;;""j08#eiim3v=a%))D1H"556"<=A		$((;$;<=BC EJJsUYYrAv->'>??%GH  
 [[$$.8#eiim3v=a%))D1H"556"<=sUYYtax%88TAXFLMQSST EJJsUYYrAv->'>??%GH  
r;   c                    || j                   }||k(  j                         }t        |      dk(  rt        | j                         dz
  }|S t        |      dkD  r|d   j                         }|S |d   j                         }|S )Nr   r
   )r-   nonzerorr   item)r7   r`   schedule_timestepsindex_candidatesrB   s        r9   index_for_timestepz4CosineDPMSolverMultistepScheduler.index_for_timestep  s    %!%.(:CCE A%T^^,q0J  !"Q&)!,113J  *!,113Jr;   c                     | j                   Vt        |t        j                        r%|j	                  | j
                  j                        }| j                  |      | _        y| j                  | _        y)zF
        Initialize the step_index counter for the scheduler.
        N)
rE   rQ   r(   rR   r6   r-   r$   r   r4   r5   )r7   r`   s     r9   rc   z2CosineDPMSolverMultistepScheduler._init_step_index  sW    
 #(ELL1#;;t~~'<'<=#66x@D#00Dr;   return_dictc                    | j                   t        d      | j                  | j                  |       | j                  t	        | j
                        dz
  k(  xrc | j                  j                  xsK | j                  j                  xr t	        | j
                        dk  xs | j                  j                  dk(  }| j                  t	        | j
                        dz
  k(  xr0 | j                  j                  xr t	        | j
                        dk  }| j                  ||      }t        | j                  j                  dz
        D ]!  }| j                  |dz      | j                  |<   # || j                  d<   | j                  ~d}	|>t        |t               r|D 
cg c]  }
|
j#                          c}
n|j#                         }	t%        || j                  j&                  | j                  j(                  |		      | _        | j                  | j*                  | j                     | j*                  | j                  dz            j-                  |j.                        }| j                  j                  dk(  s| j0                  dk  s|r| j3                  |||
      }nH| j                  j                  dk(  s| j0                  dk  s|r| j5                  | j                  ||
      }| j0                  | j                  j                  k  r| xj0                  dz  c_        | xj6                  dz  c_        |sfS t9              S c c}
w )a  
        Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
        the multistep DPMSolver.

        Args:
            model_output (`torch.Tensor`):
                The direct output from learned diffusion model.
            timestep (`int`):
                The current discrete 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`):
                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.

        NzaNumber of inference steps is 'None', you need to run 'set_timesteps' after creating the schedulerr
      rh   r   )rK   r   )r   r   seed)rK   r   )prev_sample)r1   rZ   rB   rc   rr   r-   r>   r   r   r   r   ranger   r2   rj   rQ   listinitial_seedr   r   r   r0   r6   r$   r3   r   r   r4   r   )r7   r[   r`   rK   	generatorr   r   lower_order_secondir   gr   r   s                r9   stepz&CosineDPMSolverMultistepScheduler.step  s   < ##+s  ??"!!(+ "__DNN0Ca0GG 
KK&& 7--J#dnn2E2J7{{,,6 	 __DNN 3a 77wT[[=Z=Zw_bcgcqcq_ruw_w 	 00f0Mt{{//!34 	>A$($6$6q1u$=Dq!	>!-2%D$=G	SW=Xy9!Q^^%9^g^t^t^v  ":(=(=I^I^ei"D ""4;;t#?T___`M`Aabee
 ;;##q(D,A,AA,EIZ<<\RX`e<fK[[%%*d.C.Ca.GK]GGHZHZciqvGwK  4;;#;#;;!!Q&! 	A>!;77/ :s   "M	original_samplesr-   c                    | j                   j                  |j                  |j                        }|j                  j                  dk(  rvt        j                  |      ra| j                  j                  |j                  t
        j                        }|j                  |j                  t
        j                        }n@| j                  j                  |j                        }|j                  |j                        }| j                   |D cg c]  }| j                  ||       }}nG| j                  | j                  g|j                  d   z  }n| j                  g|j                  d   z  }||   j                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=|||z  z   }	|	S c c}w )N)r$   rg   mps)rg   r   r   )r0   r6   r$   rg   typer(   is_floating_pointr-   ri   rE   r   rB   r~   flattenrr   	unsqueeze)
r7   r   r   r-   r0   r   r   step_indicesrL   noisy_sampless
             r9   	add_noisez+CosineDPMSolverMultistepScheduler.add_noise  s    '7'>'>FVF\F\]""''50U5L5LY5W!%!2!23C3J3JRWR_R_!2!`!%5%<%<EMMRI!%!2!23C3J3J!K!%5%<%<=I #T]^qD33A7IJ^L^__( OO,yq/AAL !,,-	0BBL|$,,.%++%5%;%;!<<OOB'E %++%5%;%;!<< )55=8 _s   G9c                 P    d|dz  | j                   j                  dz  z   dz  z  }|S )Nr
   r   r=   )r>   r   )r7   rL   rM   s      r9   rJ   z8CosineDPMSolverMultistepScheduler._get_conditioning_c_in<  s.    UAX 6 6 99cABr;   c                 .    | j                   j                  S rI   )r>   r   r?   s    r9   __len__z)CosineDPMSolverMultistepScheduler.__len__@  s    {{...r;   )g333333?i  r   r#   i  r   rY   g      @r   TFrh   )r   )NNrI   )NT)+__name__
__module____qualname____doc___compatiblesorderr	   floatstrintboolr   r:   propertyr@   rB   rE   rG   rO   r,   r_   r(   rR   r   re   r$   rl   r*   r+   r   r   r   r   r   r   r   rc   r   r   r   r   rJ   r    r;   r9   r   r      s!   )V LE +#'-%"&$+1%,%, %, 	%,
 %, !%, %, %, %, %,  %, %, $C=%, %,N 5 5     ! !(3 (
*  eU\\FY@Z _d_k_k 0," ,"U3PUP\P\K\E] ,"^	ell 	SXS_S_ .   $ll  
	F  $(,	!ll! ! %	!
 
!L  $(,	8-8 8 %	8
 
8v(
1"  P8llP8 U\\)*P8 	P8 P8 
%	&P8f,, || <<	
 
D/r;   r   )rU   typingr   r   r   r   numpyrx   r(   configuration_utilsr   r	   scheduling_dpmsolver_sder   scheduling_utilsr   r   r   r   r;   r9   <module>r      s/   "  / /   A > =e/ e/r;   