
    wi"                         d dl Z d dlmZ d dlmZ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 e G d
 de                      Z	 	 ddZ G d dee
          ZdS )    N)	dataclass)ListOptionalTupleUnion   )ConfigMixinregister_to_config)
BaseOutput)randn_tensor   )SchedulerMixinc                   (    e Zd ZU dZej        ed<   dS )DDPMWuerstchenSchedulerOutputaA  
    Output class for the scheduler's step function output.

    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_ddpm_wuerstchen.pyr   r      s,           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
    r   c                 \    t          j        | dz   dz  t           j        z  dz            dz  S )NMb?gT㥛 ?r   )mathcospits    r   alpha_bar_fnz)betas_for_alpha_bar.<locals>.alpha_bar_fnE   s,    8QY%/$'9A=>>!CCr   expc                 0    t          j        | dz            S )Ng      ()r!   r'   r$   s    r   r&   z)betas_for_alpha_bar.<locals>.alpha_bar_fnJ   s    8AI&&&r   z"Unsupported alpha_transform_type: r   dtype)
ValueErrorrangeappendminr   tensorfloat32)num_diffusion_timestepsmax_betaalpha_transform_typer&   betasit1t2s           r   betas_for_alpha_barr8   ,   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                   T   e Zd ZdZe	 	 ddedefd            Zd Zdd	ej	        d
e
e         dej	        fdZ	 	 	 ddede
ee                  deeej        f         fdZ	 	 ddej	        d
e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dZd Zd ZdS )DDPMWuerstchenSchedulera  
    Denoising diffusion probabilistic models (DDPMs) explores the connections between denoising score matching and
    Langevin dynamics sampling.

    [`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__init__`
    function, such as `num_train_timesteps`. They can be accessed via `scheduler.config.num_train_timesteps`.
    [`SchedulerMixin`] provides general loading and saving functionality via the [`SchedulerMixin.save_pretrained`] and
    [`~SchedulerMixin.from_pretrained`] functions.

    For more details, see the original paper: https://arxiv.org/abs/2006.11239

    Args:
        scaler (`float`): ....
        s (`float`): ....
          ?r    scalersc                     || _         t          j        |g          | _        t          j        | j        d| j        z   z  t          j        z  dz            dz  | _        d| _        d S )Nr         ?r   r;   )r<   r   r/   r=   r"   r#   _init_alpha_cumprodinit_noise_sigma)selfr<   r=   s      r   __init__z DDPMWuerstchenScheduler.__init__i   s`     qc""#(9TVq46z-BUX-MPS-S#T#TXY#Y  !$r   c                    | j         dk    rdd|z
  | j         z  z
  }n| j         dk     r
|| j         z  }t          j        || j                            |          z   d| j                            |          z   z  t          j        z  dz            dz  | j                            |          z  }|                    dd          S )Nr   r?   r   g-C6?gH.?)r<   r   r"   r=   tor#   r@   clamp)rB   r%   devicealpha_cumprods       r   _alpha_cumprodz&DDPMWuerstchenScheduler._alpha_cumprodv   s    ;??QUt{**AA[1__4;A	6"""q4699V+<+<'<=H3N
 
),,V445 ""66222r   Nsampletimestepreturnc                     |S )aP  
        Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
        current timestep.

        Args:
            sample (`torch.Tensor`): input sample
            timestep (`int`, optional): current timestep

        Returns:
            `torch.Tensor`: scaled input sample
        r   )rB   rJ   rK   s      r   scale_model_inputz)DDPMWuerstchenScheduler.scale_model_input   s	     r   num_inference_steps	timestepsrG   c                     |t          j        dd|dz   |          }t          |t           j                  s't          j        |                              |          }|| _        dS )a  
        Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference.

        Args:
            num_inference_steps (`Dict[float, int]`):
                the number of diffusion steps used when generating samples with a pre-trained model. If passed, then
                `timesteps` must be `None`.
            device (`str` or `torch.device`, optional):
                the device to which the timesteps are moved to. {2 / 3: 20, 0.0: 10}
        Nr;   g        r   rG   )r   linspace
isinstancer   rE   rP   )rB   rO   rP   rG   s       r   set_timestepsz%DDPMWuerstchenScheduler.set_timesteps   se      sC1Dq1HQWXXXI)U\22 	;Y//226::I"r   Tmodel_outputreturn_dictc           	         |j         }|j        }|}|                     |          }	 |                     ||          j        |                    d          gd |j        dd         D             R  }
 |                     |	|          j        |	                    d          gd |j        dd         D             R  }|
|z  }d|z                                  |d|z
  |z  d|
z
                                  z  z
  z  }t          |j        ||j        |j                   }d|z
  d|z
  z  d|
z
  z                                  |z  }|| |	dk    	                                j        |	                    d          gd |j        dd         D             R  z  z   }|s|
                    |          fS t          |
                    |          	          S )
a~  
        Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
        process from the learned model outputs (most often the predicted noise).

        Args:
            model_output (`torch.Tensor`): direct output from learned diffusion model.
            timestep (`int`): current discrete timestep in the diffusion chain.
            sample (`torch.Tensor`):
                current instance of sample being created by diffusion process.
            generator: random number generator.
            return_dict (`bool`): option for returning tuple rather than DDPMWuerstchenSchedulerOutput class

        Returns:
            [`DDPMWuerstchenSchedulerOutput`] or `tuple`: [`DDPMWuerstchenSchedulerOutput`] if `return_dict` is True,
            otherwise a `tuple`. When returning a tuple, the first element is the sample tensor.

        r   c                     g | ]}d S r   r   .0_s     r   
<listcomp>z0DDPMWuerstchenScheduler.step.<locals>.<listcomp>   s    HeHeHeqHeHeHer   r   Nc                     g | ]}d S rZ   r   r[   s     r   r^   z0DDPMWuerstchenScheduler.step.<locals>.<listcomp>   s    WtWtWt^_XYWtWtWtr   r;   )	generatorrG   r*   c                     g | ]}d S rZ   r   r[   s     r   r^   z0DDPMWuerstchenScheduler.step.<locals>.<listcomp>   s    FcFcFcQqFcFcFcr   )r   )r*   rG   previous_timesteprI   viewsizeshapesqrtr   floatrE   r   )rB   rV   rK   rJ   r`   rW   r*   rG   r%   prev_trH   alpha_cumprod_prevalphamu	std_noisestdpreds                    r   stepzDDPMWuerstchenScheduler.step   s   2 "$''**;++Av66;AFF1IIfHeHeTZT`abacacTdHeHeHefffET00@@EfkkRSnnuWtWtcicopqprprcsWtWtWtuuu 22Ek!!Vq5yL.HAP]L]KcKcKeKe.e%ef Y|GZbnbtuuu	E	c$6673;NOUUWWZccC46Q;--//4V[[^^dFcFcRXR^_`_a_aRbFcFcFcddddd 	%GGENN$$,HHHHr   original_samplesnoisec                 H   |j         }|j        } |                     ||          j        |                    d          gd |j        dd          D             R  }|                                |z  d|z
                                  |z  z   }|                    |          S )NrR   r   c                     g | ]}d S rZ   r   r[   s     r   r^   z5DDPMWuerstchenScheduler.add_noise.<locals>.<listcomp>   s     G G Gq G G Gr   r   r)   )rG   r*   rI   rc   rd   re   rf   rE   )rB   rp   rq   rP   rG   r*   rH   noisy_sampless           r   	add_noisez!DDPMWuerstchenScheduler.add_noise   s     "( &J++If+EEJNN1
 G G,<,B122,F G G G
 
 
 &**,,/??1}CTBZBZB\B\_dBdde,,,r   c                     | j         j        S N)confignum_train_timesteps)rB   s    r   __len__zDDPMWuerstchenScheduler.__len__   s    {..r   c                     | j         |d         z
                                                                                                  }| j         |dz            d                              |j        d                   }|S )Nr   r   )rP   absargminitemexpandre   )rB   rK   indexrh   s       r   rb   z)DDPMWuerstchenScheduler.previous_timestep   se    (1+-2244;;==BBDD	*4077q8IJJr   )r;   r    rw   )NNN)NT)r   r   r   r   r
   rg   rC   rI   r   r   r   intrN   r   r   strrG   rU   boolr   r   ro   ru   rz   rb   r   r   r   r:   r:   X   s           
$ 
$
$ 
$ 
$ 
$ 
$3 3 3   Y^Ye      $()-+/	# # # DI&# c5<'(	# # # #6  ,I ,Il,I ,I 	,I ,I 
,e3	4,I ,I ,I ,I\-,- |- <	-
 
- - - -/ / /    r   r:   )r   r   )r!   dataclassesr   typingr   r   r   r   r   configuration_utilsr	   r
   utilsr   utils.torch_utilsr   scheduling_utilsr   r   r8   r:   r   r   r   <module>r      s0  $  ! ! ! ! ! ! / / / / / / / / / / / /  A A A A A A A A       , , , , , , , , , , , , 
 
 
 
 
J 
 
 
 !)4 )4 )4 )4XN N N N Nnk N N N N Nr   