
    bi:                         d dl Z d dlmZ d dl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 dd	lmZ e G d
 de             Z	 	 ddZ G d dee      Zy)    N)	dataclass)OptionalTupleUnion   )ConfigMixinregister_to_config)
BaseOutput)randn_tensor   )SchedulerMixinc                   X    e Zd ZU dZej
                  ed<   dZeej
                     ed<   y)UnCLIPSchedulerOutputaq  
    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.
        pred_original_sample (`torch.Tensor` 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_sampleNpred_original_sample)	__name__
__module____qualname____doc__torchTensor__annotations__r   r        a/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/schedulers/scheduling_unclip.pyr   r      s'    
 37(5<<07r   r   c           
      $   |dk(  rd }n|dk(  rd }nt        d|       g }t        |       D ]<  }|| z  }|dz   | z  }|j                  t        d ||       ||      z  z
  |             > t	        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
    cosinec                 f    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_fnI   s-    88QY%/$''9A=>!CCr   expc                 2    t        j                  | dz        S )Ng      ()r   r%   r"   s    r   r$   z)betas_for_alpha_bar.<locals>.alpha_bar_fnN   s    88A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_barr6   0   s    . x'	D 
	&	' =>R=STUUE*+ M((!e..S\"-R0@@@(KLM <<U]]33r   c                      e Zd ZdZe	 	 	 	 	 	 ddedededee	   dedefd       Z
dd
ej                  dee   dej                  fdZddedeeej                  f   fdZddZ	 	 	 ddej                  ded
ej                  dee   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y	)UnCLIPSchedulera  
    NOTE: do not use this scheduler. The DDPM scheduler has been updated to support the changes made here. This
    scheduler will be removed and replaced with DDPM.

    This is a modified DDPM Scheduler specifically for the karlo unCLIP model.

    This scheduler has some minor variations in how it calculates the learned range variance and dynamically
    re-calculates betas based off the timesteps it is skipping.

    The scheduler also uses a slightly different step ratio when computing timesteps to use for inference.

    See [`~DDPMScheduler`] for more information on DDPM scheduling

    Args:
        num_train_timesteps (`int`): number of diffusion steps used to train the model.
        variance_type (`str`):
            options to clip the variance used when adding noise to the denoised sample. Choose from `fixed_small_log`
            or `learned_range`.
        clip_sample (`bool`, default `True`):
            option to clip predicted sample between `-clip_sample_range` and `clip_sample_range` for numerical
            stability.
        clip_sample_range (`float`, default `1.0`):
            The range to clip the sample between. See `clip_sample`.
        prediction_type (`str`, default `epsilon`, optional):
            prediction type of the scheduler function, one of `epsilon` (predicting the noise of the diffusion process)
            or `sample` (directly predicting the noisy sample`)
    num_train_timestepsvariance_typeclip_sampleclip_sample_rangeprediction_typebeta_schedulec                    |dk7  rt        d      t        |      | _        d| j                  z
  | _        t	        j
                  | j                  d      | _        t	        j                  d      | _        d| _	        d | _
        t	        j                  t        j                  d|      d d d   j                               | _        || _        y )Nsquaredcos_cap_v2zBUnCLIPScheduler only supports `beta_schedule`: 'squaredcos_cap_v2'      ?r   dim)r)   r6   r2   alphasr   cumprodalphas_cumprodr-   oneinit_noise_sigmanum_inference_steps
from_numpynparangecopy	timestepsr:   )selfr9   r:   r;   r<   r=   r>   s          r   __init__zUnCLIPScheduler.__init__y   s     //abb()<=
DJJ&#mmDKKQ?<<$ !$ $( ))"))A7J*KDbD*Q*V*V*XY*r   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   )rP   rR   rS   s      r   scale_model_inputz!UnCLIPScheduler.scale_model_input   s	     r   rJ   devicec                 f   || _         | j                  j                  dz
  | j                   dz
  z  }t        j                  d|      |z  j                         ddd   j                         j                  t        j                        }t        j                  |      j                  |      | _        y)a  
        Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference.

        Note that this scheduler uses a slightly different step ratio than the other diffusers schedulers. The
        different step ratio is to mimic the original karlo implementation and does not affect the quality or accuracy
        of the results.

        Args:
            num_inference_steps (`int`):
                the number of diffusion steps used when generating samples with a pre-trained model.
        r   r   NrD   )rJ   configr9   rL   rM   roundrN   astypeint64r   rK   torO   )rP   rJ   rW   
step_ratiorO   s        r   set_timestepszUnCLIPScheduler.set_timesteps   s     $7 kk559d>V>VYZ>Z[
YYq"56CJJLTrTRWWY``acaiaij	)))477?r   c                    ||dz
  }| j                   |   }|dk\  r| j                   |   n| j                  }d|z
  }d|z
  }||dz
  k(  r| j                  |   }	nd||z  z
  }	||z  |	z  }
|| j                  j                  }|dk(  rDt        j                  t        j                  |
d            }
t        j                  d|
z        }
|
S |dk(  r6|
j                         }|	j                         }|dz   dz  }||z  d|z
  |z  z   }
|
S )	Nr   r   fixed_small_logg#B;)r,         ?learned_ranger   )	rG   rH   r2   rY   r:   r   logclampr%   )rP   r#   prev_timesteppredicted_variancer:   alpha_prod_talpha_prod_t_prevbeta_prod_tbeta_prod_t_prevbetavariancemin_logmax_logfracs                 r   _get_variancezUnCLIPScheduler._get_variance   s0    EM**1-BOSTBTD//>Z^ZbZb,&00AE!::a=D|&777D
 $k1D8  KK55M --yyX5!ABHyyx0H  o-llnGhhjG&*a/Dg~TW(<<Hr   model_outputrf   return_dictc                    |}|j                   d   |j                   d   dz  k(  r8| j                  dk(  r)t        j                  ||j                   d   d      \  }}nd}||dz
  }| j                  |   }	|dk\  r| j                  |   n| j
                  }
d|	z
  }d|
z
  }||dz
  k(  r| j                  |   }| j                  |   }nd|	|
z  z
  }d|z
  }| j                  j                  dk(  r||dz  |z  z
  |	dz  z  }n?| j                  j                  d	k(  r|}n#t        d
| j                  j                   d      | j                  j                  r@t        j                  || j                  j                   | j                  j                        }|
dz  |z  |z  }|dz  |z  |z  }||z  ||z  z   }d}|dkD  rt        |j                   |j                  ||j                         }| j#                  |||      }| j                  dk(  r|}n<| j                  dk(  rd|z  j%                         }nt        d| j                   d      ||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.
            prev_timestep (`int`, *optional*): The previous timestep to predict the previous sample at.
                Used to dynamically compute beta. If not given, `t-1` is used and the pre-computed beta is used.
            generator: random number generator.
            return_dict (`bool`): option for returning tuple rather than UnCLIPSchedulerOutput class

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

        r   r   rc   rB   Nr   epsilonrb   rR   zprediction_type given as z> must be one of `epsilon` or `sample` for the UnCLIPScheduler.)r(   	generatorrW   )rg   rf   ra   zvariance_type given as zM must be one of `fixed_small_log` or `learned_range` for the UnCLIPScheduler.)r   r   )shaper:   r   splitrG   rH   r2   rE   rY   r=   r)   r;   re   r<   r   r(   rW   rq   r%   r   )rP   rr   rS   rR   rf   rv   rs   r#   rg   rh   ri   rj   rk   rl   alphar   pred_original_sample_coeffcurrent_sample_coeffpred_prev_samplerm   variance_noises                        r   stepzUnCLIPScheduler.step   s   : a FLLOa$77D<N<NRa<a/4{{<VW^_/`,L,!%  EM**1-BOSTBTD//>Z^ZbZb,&00AE!::a=DKKNE|&777DHE ;;&&)3$*[S-AL-P$PT`ehTi#i [[((H4#/ +DKK,G,G+H I, ,  ;;""#(;;$t{{'D'D&DdkkFcFc$  '8C&@4&G;%V"$~0@@;N 68LLOcflOll q5)"",*<*<	ZfZmZmN ))#5+ * H !!%66###6(N//1 -d.@.@-A B0 0 
  .0H+h6 $ 
 %1AXlmmr   original_samplesnoiserO   c                    | j                   j                  |j                        | _         | j                   j                  |j                        }|j                  |j                        }||   dz  }|j	                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=d||   z
  dz  }|j	                         }t        |j                        t        |j                        k  r=|j                  d      }t        |j                        t        |j                        k  r=||z  ||z  z   }|S )N)rW   r'   rb   rD   r   )rG   r]   rW   r(   flattenlenrw   	unsqueeze)rP   r   r   rO   rG   sqrt_alpha_prodsqrt_one_minus_alpha_prodnoisy_sampless           r   	add_noisezUnCLIPScheduler.add_noiseK  sa    #1144<L<S<S4T,,//6F6L6L/MLL!1!8!89	(3s:)113/''(3/?/E/E+FF-77;O /''(3/?/E/E+FF &'	)B%Bs$J!$=$E$E$G!+112S9I9O9O5PP(A(K(KB(O% +112S9I9O9O5PP (*::=VY^=^^r   )i  ra   TrA   ru   r@   )N)NNN)NNT)r   r   r   r   r	   intstrboolr   floatrQ   r   r   rV   r   rW   r_   rq   r   r   r~   	IntTensorr   r   r   r   r8   r8   \   sk   8  $(. -0(0+ + + 	+
 $E?+ + + +6  Y^YeYe @ @eCDU>V @""R (, pnllpn pn 	pn
  }pn pn 
$e+	,pnf,, || ??	
 
r   r8   )g+?r   )r   dataclassesr   typingr   r   r   numpyrL   r   configuration_utilsr   r	   utilsr
   utils.torch_utilsr   scheduling_utilsr   r   r6   r8   r   r   r   <module>r      s^     ! ) )   A  , , 8J 8 8( !)4XGnk Gr   