
    +h=                         S SK r S SKJr  S SKJrJrJr  S SKrS SK	r	SSK
JrJr  SSKJr  SSKJr  SS	KJr  \ " S
 S\5      5       r  SS jr " S S\\5      rg)    N)	dataclass)OptionalTupleUnion   )ConfigMixinregister_to_config)
BaseOutput)randn_tensor   )SchedulerMixinc                   V    \ rS rSr% Sr\R                  \S'   \R                  \S'   Srg)RePaintSchedulerOutput   aH  
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_samplepred_original_sample N)	__name__
__module____qualname____firstlineno____doc__torchTensor__annotations____static_attributes__r       a/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/schedulers/scheduling_repaint.pyr   r      s    
 ,,&r   r   c           
      &   US:X  a  S nOUS:X  a  S nO[        SU 35      e/ n[        U 5       H<  nXP-  nUS-   U -  nUR                  [        SU" U5      U" U5      -  -
  U5      5        M>     [        R
                  " U[        R                  S9$ )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                 h    [         R                  " U S-   S-  [         R                  -  S-  5      S-  $ )NgMb?gT㥛 ?r   )mathcospits    r   alpha_bar_fn)betas_for_alpha_bar.<locals>.alpha_bar_fnH   s-    88QY%/$''9A=>!CCr   expc                 4    [         R                  " U S-  5      $ )Ng      ()r"   r)   r%   s    r   r'   r(   M   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_barr:   /   s    . x'	D 
	&	' =>R=STUUE*+(!e..S\"-R0@@@(KL , <<U]]33r   c                   (   \ rS rSrSrSr\       S$S\S\S\S\	S	\S
\
\R                     S\4S jj5       rS%S\R                   S\
\   S\R                   4S jjr   S&S\S\S\S\\	\R&                  4   4S jjrS r  S'S\R                   S\S\R                   S\R                   S\R                   S\
\R,                     S\S\\\4   4S jjrS%S jrS\R                   S\R                   S \R6                  S\R                   4S! jrS" rS#rg)(RePaintScheduler[   a  
`RePaintScheduler` is a scheduler for DDPM inpainting inside a given mask.

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`, `squaredcos_cap_v2`, or `sigmoid`.
    eta (`float`):
        The weight of noise for added noise in diffusion step. If its value is between 0.0 and 1.0 it corresponds
        to the DDIM scheduler, and if its value is between -0.0 and 1.0 it corresponds to the DDPM scheduler.
    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 between -1 and 1 for numerical stability.

r   Nnum_train_timesteps
beta_startbeta_endbeta_scheduleetatrained_betasclip_samplec                    Ub  [         R                  " U5      U l        OUS:X  a*  [         R                  " X#U[         R                  S9U l        OUS:X  a4  [         R                  " US-  US-  U[         R                  S9S-  U l        OsUS:X  a  [        U5      U l        O\US:X  a<  [         R                  " SS	U5      n[         R                  " U5      X2-
  -  U-   U l        O[        U S
U R                   35      eSU R                  -
  U l	        [         R                  " U R                  SS9U l        [         R                  " S5      U l        [         R                  " S5      U l        SU l        S U l        [         R                  " ["        R$                  " SU5      S S S2   R'                  5       5      U l        XPl        g )Nlinearr+   scaled_linear      ?r   squaredcos_cap_v2sigmoidi   z is not implemented for       ?r   )dim)r   
from_numpyr6   linspacer2   r:   rJ   NotImplementedError	__class__alphascumprodalphas_cumprodr1   onefinal_alpha_cumprodinit_noise_sigmanum_inference_stepsnparangecopy	timestepsrB   )	selfr>   r?   r@   rA   rB   rC   rD   r6   s	            r   __init__RePaintScheduler.__init__x   sr    $))-8DJh&
>QY^YfYfgDJo-
C3H[chcpcpquvvDJ11,-@ADJi'NN2q*=>Eu-1FG*TDJ%7OPTP^P^O_&`aaDJJ&#mmDKKQ?<<$#(<<#4  !$ $( ))"))A7J*KDbD*Q*V*V*XYr   sampletimestepreturnc                     U$ )aN  
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.
r   )r^   ra   rb   s      r   scale_model_input"RePaintScheduler.scale_model_input   s	     r   rY   jump_lengthjump_n_sampledevicec                 4   [        U R                  R                  U5      nXl        / n0 n[	        SX-
  U5       H
  nUS-
  Xg'   M     UnUS:  ae  US-
  nUR                  U5        UR                  US5      S:  a1  Xh   S-
  Xh'   [	        U5       H  n	US-   nUR                  U5        M     US:  a  Me  [        R                  " U5      U R                  R                  U R                  -  -  n[        R                  " U5      R                  U5      U l        g)u7  
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. If used,
        `timesteps` must be `None`.
    jump_length (`int`, defaults to 10):
        The number of steps taken forward in time before going backward in time for a single jump (“j” in
        RePaint paper). Take a look at Figure 9 and 10 in the paper.
    jump_n_sample (`int`, defaults to 10):
        The number of times to make a forward time jump for a given chosen time sample. Take a look at Figure 9
        and 10 in the paper.
    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   N)r0   configr>   rY   r.   r/   getrZ   arrayr   rO   tor]   )
r^   rY   rg   rh   ri   r]   jumpsjr&   _s
             r   set_timestepsRePaintScheduler.set_timesteps   s
   0 "$++"A"ACVW#6 	q-;[IA$q(EH J  1fAAQyyA" 8a<{+AAA$$Q' , 1f HHY'4;;+J+JdNfNf+fg	)))477?r   c                     XR                   R                  U R                  -  -
  nU R                  U   nUS:  a  U R                  U   OU R                  nSU-
  nSU-
  nXe-  SX4-  -
  -  nU$ )Nr   r   )rk   r>   rY   rU   rW   )r^   r&   prev_timestepalpha_prod_talpha_prod_t_prevbeta_prod_tbeta_prod_t_prevvariances           r   _get_varianceRePaintScheduler._get_variance   s    KK;;t?W?WWW**1-BOSTBTD//>Z^ZrZr,&00 %2q<;[7[\r   model_outputoriginal_imagemask	generatorreturn_dictc                    UnX R                   R                  U R                  -  -
  n	U R                  U   n
U	S:  a  U R                  U	   OU R                  nSU
-
  nX<S-  U-  -
  U
S-  -  nU R                   R
                  (       a  [        R                  " USS5      nUR                  n[        UR                  XnUR                  S9nU R                  U R                  U5      S-  -  nSnUS:  a  U R                  S:  a  UU-  nSU-
  US-  -
  S-  U-  nUS-  U-  U-   U-   nUS-  U-  SU-
  S-  U-  -   nUU-  SU-
  U-  -   nU(       d  UU4$ [        UUS9$ )	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`):
        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.
    original_image (`torch.Tensor`):
        The original image to inpaint on.
    mask (`torch.Tensor`):
        The mask where a value of 0.0 indicates which part of the original image to inpaint.
    generator (`torch.Generator`, *optional*):
        A random number generator.
    return_dict (`bool`, *optional*, defaults to `True`):
        Whether or not to return a [`~schedulers.scheduling_repaint.RePaintSchedulerOutput`] or `tuple`.

Returns:
    [`~schedulers.scheduling_repaint.RePaintSchedulerOutput`] or `tuple`:
        If return_dict is `True`, [`~schedulers.scheduling_repaint.RePaintSchedulerOutput`] is returned,
        otherwise a tuple is returned where the first element is the sample tensor.

r   r   rH   rN   r   ri   r,   r   rL   )r   r   )rk   r>   rY   rU   rW   rD   r   clampri   r   shaper,   rB   r{   r   )r^   r}   rb   ra   r~   r   r   r   r&   ru   rv   rw   rx   r   ri   noise	std_dev_trz   pred_sample_directionprev_unknown_partprev_known_partpred_prev_samples                         r   stepRePaintScheduler.step   s   H  ;;#B#BdF^F^#^^ **1-BOSTBTD//>Z^ZrZr,& !'c)9L)H HLZ]L]] ;;""#(;;/CR#K  $$\//9[g[m[mnHHt11(;sBB	q5TXX\ 5(H "#%6!6A!E# MP\ \ .s25IILaadll -c1^CL]H]beGeinFnn  /1S4ZCT4TT $ 
 &2BYmnnr   c                    U R                   R                  U R                  -  n[        U5       H  nU R                  X%-      nUR
                  R                  S:X  a;  [        UR                  UR                  US9nUR                  UR
                  5      nO)[        UR                  X1R
                  UR                  S9nSU-
  S-  U-  US-  U-  -   nM     U$ )Nmps)r,   r   r   r   rH   )rk   r>   rY   r.   r6   ri   typer   r   r,   rn   )r^   ra   rb   r   nr7   betar   s           r   	undo_stepRePaintScheduler.undo_stepS  s    KK++t/G/GGqA::hl+D}}!!U*$V\\QZ[/$V\\Y}}djdpdpq $h3&/$)e2CCF  r   original_samplesr   r]   c                     [        S5      e)NzCUse `DDPMScheduler.add_noise()` to train for sampling with RePaint.)rQ   )r^   r   r   r]   s       r   	add_noiseRePaintScheduler.add_noised  s     ""ghhr   c                 .    U R                   R                  $ N)rk   r>   )r^   s    r   __len__RePaintScheduler.__len__l  s    {{...r   )	rS   rU   r6   rB   rW   rX   rY   rV   r]   )i  g-C6?g{Gz?rF   g        NTr   )
   r   N)NT)r   r   r   r   r   orderr	   intfloatstrr   rZ   ndarrayboolr_   r   r   re   r   ri   rr   r{   	Generatorr   r   r   r   	IntTensorr   r   r   r   r   r   r<   r<   [   s   4 E $("%.2 ( ( ( 	(
 ( (  

+( ( (T  Y^YeYe ( +/-@ -@ -@ 	-@
 c5<<'(-@^4 04 [oll[o [o 	[o
 [o ll[o EOO,[o [o 
%u,	-[oz"i,,i ||i ??	i
 
i/r   r<   )g+?r    )r"   dataclassesr   typingr   r   r   numpyrZ   r   configuration_utilsr   r	   utilsr
   utils.torch_utilsr   scheduling_utilsr   r   r:   r<   r   r   r   <module>r      s^     ! ) )   A  , , 'Z ' '( !)4XR/~{ R/r   