
    
3j>              	           S SK r S SKJr  S SK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\S\S\S   S\R(                  4S jjr " S S\\	5      rg)    N)	dataclass)Literal   )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/wildlama/miniconda3/lib/python3.13/site-packages/diffusers/schedulers/scheduling_repaint.pyr   r      s    
 ,,&r   r   num_diffusion_timestepsmax_betaalpha_transform_type)cosineexplaplacereturnc           
      :   US:X  a  S nO"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`, defaults to `0.999`):
        The maximum beta to use; use values lower than 1 to avoid numerical instability.
    alpha_transform_type (`str`, defaults to `"cosine"`):
        The type of noise schedule for `alpha_bar`. Choose from `cosine`, `exp`, or `laplace`.

Returns:
    `torch.Tensor`:
        The betas used by the scheduler to step the model outputs.
r    c                 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_fnI   s-    88QY%/$''9A=>!CCr   r"   c           	         S[         R                  " SSU -
  5      -  [         R                  " SS[         R                  " SU -
  5      -  -
  S-   5      -  n[         R                  " U5      n[         R
                  " USU-   -  5      $ )Ng      r
         ?r   gư>)r&   copysignlogfabsr!   sqrt)r*   lmbsnrs      r   r+   r,   N   sm    q#'22TXXa!diiPSVWPWFXBX>X[_>_5``C((3-C99SAG_--r   r!   c                 4    [         R                  " U S-  5      $ )Ng      ()r&   r!   r)   s    r   r+   r,   U   s    88AI&&r   z"Unsupported alpha_transform_type: r
   dtype)
ValueErrorrangeappendminr   tensorfloat32)r   r   r   r+   betasit1t2s           r   betas_for_alpha_barrB   /   s    0 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-  S\4S jj5       rS%S\R                  S\S-  S\R                  4S jjr   S&S\S\S\S\	\R"                  -  4S jjrS r  S'S\R                  S\S\R                  S\R                  S\R                  S\R(                  S-  S\S\\-  4S jjrS%S jrS\R                  S\R                  S \R2                  S\R                  4S! jrS" rS#rg)(RePaintSchedulerc   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linearr6   scaled_linearr.   r   squaredcos_cap_v2sigmoidi   z is not implemented for       ?r   )dim)r   
from_numpyr>   linspacer=   rB   rQ   NotImplementedError	__class__alphascumprodalphas_cumprodr<   onefinal_alpha_cumprodinit_noise_sigmanum_inference_stepsnparangecopy	timestepsrJ   )	selfrF   rG   rH   rI   rJ   rK   rL   r>   s	            r   __init__RePaintScheduler.__init__   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timestepr#   c                     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   )re   rh   ri   s      r   scale_model_input"RePaintScheduler.scale_model_input   s	     r   r`   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)r;   configrF   r`   r9   r:   getra   arrayr   rV   tord   )
re   r`   rm   rn   ro   rd   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
   )rq   rF   r`   r\   r^   )re   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
   r.   rU   r   ro   r7   r   rS   )r   r   )rq   rF   r`   r\   r^   rL   r   clampro   r	   shaper7   rJ   r   r   )re   r   ri   rh   r   r   r   r   r*   r{   r|   r}   r~   r   ro   noise	std_dev_tr   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)r7   r   r   r
   r.   )rq   rF   r`   r9   r>   ro   typer	   r   r7   rt   )re   rh   ri   r   nr?   betar   s           r   	undo_stepRePaintScheduler.undo_step[  s    KK++t/G/GGqA::hl+D}}!!U*$V\\QZ[/$V\\Y}}djdpdpq $h3&/$)e2CCF  r   original_samplesr   rd   c                     [        S5      e)NzCUse `DDPMScheduler.add_noise()` to train for sampling with RePaint.)rX   )re   r   r   rd   s       r   	add_noiseRePaintScheduler.add_noisel  s     ""ghhr   c                 .    U R                   R                  $ N)rq   rF   )re   s    r   __len__RePaintScheduler.__len__t  s    {{...r   )	rZ   r\   r>   rJ   r^   r_   r`   r]   rd   )i  g-C6?g{Gz?rN   g        NTr   )
   r   N)NT)r   r   r   r   r   orderr   intfloatstrra   ndarrayboolrf   r   r   rk   ro   rx   r   	Generatorr   tupler   r   	IntTensorr   r   r   r   r   r   rD   rD   c   s   4 E $("%+/ ( ( ( 	(
 ( ( zzD(( ( (T d
 V[VbVb ( %)-@ -@ -@ 	-@
 ell"-@^4 -1 [oll[o [o 	[o
 [o ll[o ??T)[o [o 
 %	'[oz"i,,i ||i ??	i
 
i/r   rD   )g+?r    )r&   dataclassesr   typingr   numpyra   r   configuration_utilsr   r   utilsr   utils.torch_utilsr	   scheduling_utilsr   r   r   r   r   rB   rD   r   r   r   <module>r      s     !    A  , , 'Z ' '( @H14 1414 ""<=14 \\	14hR/~{ R/r   