o .eV@sddlZddlmZddlmZmZmZmZddlZ ddl Z ddl m Z m Z ddlmZddlmZeGdddeZ dd d Zd dZGddde e ZdS)N) dataclass)ListOptionalTupleUnion) ConfigMixinSchedulerMixin)register_to_config) BaseOutputc@s.eZdZUdZejed<dZeejed<dS)LCMSchedulerOutputa{ Output class for the scheduler's `step` function output. Args: prev_sample (`torch.FloatTensor` 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.FloatTensor` 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_sampleNdenoised) __name__ __module__ __qualname____doc__torch FloatTensor__annotations__r rrr7/home/patrick/Latent_Consistency_Model/lcm_scheduler.pyr s  r +?cosinecCs|dkr dd}n|dkrdd}ntd|g}t|D]}||}|d|}|td|||||qtj|tjdS) 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 rcSs t|ddtjddS)NgMb?gT㥛 ?)mathcospitrrr alpha_bar_fnKs z)betas_for_alpha_bar..alpha_bar_fnexpcSst|dS)Ng()rr rrrrrPsz!Unsupported alpha_tranform_type: dtype) ValueErrorrangeappendminrtensorfloat32)num_diffusion_timestepsmax_betaalpha_transform_typerbetasit1t2rrrbetas_for_alpha_bar2s    "r1cCsd|}tj|dd}|}|d}|d}||8}||||9}|d}|dd|dd}t|dd|g}d|}|S)a4 Rescales betas to have zero terminal SNR Based on https://arxiv.org/pdf/2305.08891.pdf (Algorithm 1) Args: betas (`torch.FloatTensor`): the betas that the scheduler is being initialized with. Returns: `torch.FloatTensor`: rescaled betas with zero terminal SNR ?rdimrr!N)rcumprodsqrtclonecat)r-alphasalphas_cumprodalphas_bar_sqrtalphas_bar_sqrt_0alphas_bar_sqrt_T alphas_barrrrrescale_zero_terminal_snr^s   r@c @seZdZdZdZe         dBdedededede e e j e efdedededededededededefddZdCd ejd!e ed"ejfd#d$Zd%d&Zd ejd"ejfd'd(ZdCd)ed*ed+e eejffd,d-Zd.d/Z 0   dDd1ejd2ed!ed ejd3ed4ed5e ejd6ed"e eeffd7d8Zd9ejd:ejd;ejd"ejfdd?Zd@dAZdS)E LCMSchedulera `LCMScheduler` extends the denoising procedure introduced in denoising diffusion probabilistic models (DDPMs) with non-Markovian guidance. 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`, `scaled_linear`, or `squaredcos_cap_v2`. trained_betas (`np.ndarray`, *optional*): Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`. clip_sample (`bool`, defaults to `True`): Clip the predicted sample for numerical stability. clip_sample_range (`float`, defaults to 1.0): The maximum magnitude for sample clipping. Valid only when `clip_sample=True`. set_alpha_to_one (`bool`, defaults to `True`): Each diffusion step uses the alphas product value at that step and at the previous one. For the final step there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`, otherwise it uses the alpha value at step 0. steps_offset (`int`, defaults to 0): An offset added to the inference steps. You can use a combination of `offset=1` and `set_alpha_to_one=False` to make the last step use step 0 for the previous alpha product like in Stable Diffusion. 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). thresholding (`bool`, defaults to `False`): Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such as Stable Diffusion. dynamic_thresholding_ratio (`float`, defaults to 0.995): The ratio for the dynamic thresholding method. Valid only when `thresholding=True`. sample_max_value (`float`, defaults to 1.0): The threshold value for dynamic thresholding. Valid only when `thresholding=True`. timestep_spacing (`str`, defaults to `"leading"`): 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. rescale_betas_zero_snr (`bool`, defaults to `False`): Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and dark samples instead of limiting it to samples with medium brightness. Loosely related to [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506). r!-C6?{Gz?linearNTrepsilonFףp= ?r2leadingnum_train_timesteps beta_startbeta_end beta_schedule trained_betas clip_sampleset_alpha_to_one steps_offsetprediction_type thresholdingdynamic_thresholding_ratioclip_sample_rangesample_max_valuetimestep_spacingrescale_betas_zero_snrcCs|durtj|tjd|_n:|dkrtj|||tjd|_n*|dkr4tj|d|d|tjdd|_n|dkr>t||_n t|d|j|rPt|j|_d|j|_ tj |j d d |_ |rftdn|j d |_ d|_ d|_ttd |ddd tj|_dS) Nr"rE scaled_linear?rsquaredcos_cap_v2z does is not implemented for r2rr3r5)rr(r)r-linspacer1NotImplementedError __class__r@r:r6r;final_alpha_cumprodinit_noise_sigmanum_inference_steps from_numpynparangecopyastypeint64 timesteps)selfrIrJrKrLrMrNrOrPrQrRrSrTrUrVrWrrr__init__s$   .zLCMScheduler.__init__sampletimestepreturncCs|S)a Ensures interchangeability with schedulers that need to scale the denoising model input depending on the current timestep. Args: sample (`torch.FloatTensor`): The input sample. timestep (`int`, *optional*): The current timestep in the diffusion chain. Returns: `torch.FloatTensor`: A scaled input sample. r)rhrjrkrrrscale_model_inputszLCMScheduler.scale_model_inputcCsJ|j|}|dkr|j|n|j}d|}d|}||d||}|S)Nrr!)r;r^)rhrk prev_timestep alpha_prod_talpha_prod_t_prev beta_prod_tbeta_prod_t_prevvariancerrr _get_variances zLCMScheduler._get_variancec Cs|j}|j\}}}}|tjtjfvr|}|||||}|}tj||j j dd}tj |d|j j d}| d}t || ||}|||||}||}|S)as "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing pixels from saturation at each step. We find that dynamic thresholding results in significantly better photorealism as well as better image-text alignment, especially when using very large guidance weights." https://arxiv.org/abs/2205.11487 r!r3)r'max)r#shaperr)float64floatreshapeabsquantileconfigrSclamprU unsqueezeto) rhrjr# batch_sizechannelsheightwidth abs_samplesrrr_threshold_sample s    zLCMScheduler._threshold_sampler`lcm_origin_stepsdevicecCs||jjkrtd|d|jjd|jjd||_|jj|}tttd|d|d}t||}|dd| d|}t |  ||_ dS)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. z`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.r!N)r|rIr$r`rbasarraylistr%lenrrardrrg)rhr`rrclcm_origin_timesteps skipping_steprgrrr set_timesteps-s    zLCMScheduler.set_timestepscCsPd|_|jd|dd|jd}|d|dd|jdd}||fS)NrYrg?) sigma_data)rhrc_skipc_outrrr,get_scalings_for_boundary_condition_discreteGs "z9LCMScheduler.get_scalings_for_boundary_condition_discrete model_output timeindexetause_clipped_model_outputvariance_noise return_dictc Cs8|jdur td|d} | t|jkr|j| } n|} |j|} | dkr*|j| n|j} d| }d| }||\}}|jj}|dkrQ|| || }n|dkrX|}n|dkrh| || |}||||}t|jdkrt |j  |j}| || |}n|}| s||fSt||dS) 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.FloatTensor`): The direct output from learned diffusion model. timestep (`float`): The current discrete timestep in the diffusion chain. sample (`torch.FloatTensor`): A current instance of a sample created by the diffusion process. eta (`float`): The weight of noise for added noise in diffusion step. use_clipped_model_output (`bool`, defaults to `False`): If `True`, computes "corrected" `model_output` from the clipped predicted original sample. Necessary because predicted original sample is clipped to [-1, 1] when `self.config.clip_sample` is `True`. If no clipping has happened, "corrected" `model_output` would coincide with the one provided as input and `use_clipped_model_output` has no effect. generator (`torch.Generator`, *optional*): A random number generator. variance_noise (`torch.FloatTensor`): Alternative to generating noise with `generator` by directly providing the noise for the variance itself. Useful for methods such as [`CycleDiffusion`]. return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] or `tuple`. Returns: [`~schedulers.scheduling_utils.LCMSchedulerOutput`] or `tuple`: If return_dict is `True`, [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] 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!rrFrj v_prediction)r r )r`r$rrgr;r^rr|rQr7rrandnrvrrr )rhrrrkrjrr generatorrrprev_timeindexrnrorprqrrrrparameterizationpred_x0r noiser rrrstepRs8 ,   zLCMScheduler.steporiginal_samplesrrgcCs|jj|j|jd}||j}||d}|}t|jt|jkr3|d}t|jt|jks$d||d}|}t|jt|jkrX|d}t|jt|jksI||||}|SN)rr#rYr5r!r;rrr#flattenrrvr~)rhrrrgr;sqrt_alpha_prodsqrt_one_minus_alpha_prod noisy_samplesrrr add_noises    zLCMScheduler.add_noisecCs|jj|j|jd}||j}||d}|}t|jt|jkr3|d}t|jt|jks$d||d}|}t|jt|jkrX|d}t|jt|jksI||||}|Srr)rhrjrrgr;rrvelocityrrr get_velocitys    zLCMScheduler.get_velocitycCs|jjSN)r|rI)rhrrr__len__szLCMScheduler.__len__)rBrCrDrENTTrrFFrGr2r2rHFr)rFNNT)rrrrorderr intrxstrrrrbndarrayrboolrirrrmrtrrrrr rr IntTensorrrrrrrrrAs4      5 ""   `  rA)rr)r dataclassesrtypingrrrrnumpyrbr diffusersrrdiffusers.configuration_utilsr diffusers.utilsr r r1r@rArrrrs    ,$