
    +h%                         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
  S SKJr  SSKJrJr  SSKJr  SS	KJr  \R&                  R                   " S
 S5      5       r\ " S S\5      5       r " S S\\5      rg)    )	dataclass)OptionalTupleUnionN)random   )ConfigMixinregister_to_config)
BaseOutput   )FlaxSchedulerMixinc                       \ rS rSr% Sr\\   \S'   Sr\\	R                     \S'   Sr\\	R                     \S'   \S 5       rSrg)KarrasVeSchedulerState   Nnum_inference_steps	timestepsschedulec                     U " 5       $ N )clss    h/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/schedulers/scheduling_karras_ve_flax.pycreateKarrasVeSchedulerState.create$   s	    u    r   )__name__
__module____qualname____firstlineno__r   r   int__annotations__r   jnpndarrayr   classmethodr   __static_attributes__r   r   r   r   r      sK     *.#-'+Ix$+&*Hhs{{#* r   r   c                   `    \ rS rSr% Sr\R                  \S'   \R                  \S'   \\S'   Sr	g)FlaxKarrasVeOutput)   a  
Output class for the scheduler's step function output.

Args:
    prev_sample (`jnp.ndarray` 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.
    derivative (`jnp.ndarray` of shape `(batch_size, num_channels, height, width)` for images):
        Derivative of predicted original image sample (x_0).
    state (`KarrasVeSchedulerState`): the `FlaxKarrasVeScheduler` state data class.
prev_sample
derivativestater   N)
r   r   r   r   __doc__r"   r#   r!   r   r%   r   r   r   r'   r'   )   s#    
 !!r   r'   c                      \ rS rSrSr\S 5       r\      S!S\S\S\S\S\S	\4S
 jj5       r	S r
 S"S\S\S\S\4S jjrS\S\R                   S\S\R$                  S\\R                   \4   4
S jr S#S\S\R                   S\S\S\R                   S\S\\\4   4S jjr S#S\S\R                   S\S\S\R                   S\R                   S\R                   S\S\\\4   4S jjrS\4S jrSrg )$FlaxKarrasVeScheduler<   a  
Stochastic sampling from Karras et al. [1] tailored to the Variance-Expanding (VE) models [2]. Use Algorithm 2 and
the VE column of Table 1 from [1] for reference.

[1] Karras, Tero, et al. "Elucidating the Design Space of Diffusion-Based Generative Models."
https://huggingface.co/papers/2206.00364 [2] Song, Yang, et al. "Score-based generative modeling through stochastic
differential equations." https://huggingface.co/papers/2011.13456

[`~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 on the parameters, see the original paper's Appendix E.: "Elucidating the Design Space of
Diffusion-Based Generative Models." https://huggingface.co/papers/2206.00364. The grid search values used to find
the optimal {s_noise, s_churn, s_min, s_max} for a specific model are described in Table 5 of the paper.

Args:
    sigma_min (`float`): minimum noise magnitude
    sigma_max (`float`): maximum noise magnitude
    s_noise (`float`): the amount of additional noise to counteract loss of detail during sampling.
        A reasonable range is [1.000, 1.011].
    s_churn (`float`): the parameter controlling the overall amount of stochasticity.
        A reasonable range is [0, 100].
    s_min (`float`): the start value of the sigma range where we add noise (enable stochasticity).
        A reasonable range is [0, 10].
    s_max (`float`): the end value of the sigma range where we add noise.
        A reasonable range is [0.2, 80].
c                     g)NTr   selfs    r   	has_stateFlaxKarrasVeScheduler.has_state[   s    r   	sigma_min	sigma_maxs_noises_churns_mins_maxc                     g r   r   )r2   r5   r6   r7   r8   r9   r:   s          r   __init__FlaxKarrasVeScheduler.__init___   s     	r   c                 *    [         R                  5       $ r   )r   r   r1   s    r   create_state"FlaxKarrasVeScheduler.create_statek   s    %,,..r   r   r+   r   shapereturnc                    [         R                  " SU5      SSS2   R                  5       nU Vs/ s HX  nU R                  R                  S-  U R                  R
                  S-  U R                  R                  S-  -  XRS-
  -  -  -  PMZ     nnUR                  U[         R                  " U[         R                  S9US9$ s  snf )aO  
Sets the continuous timesteps used for the diffusion chain. Supporting function to be run before inference.

Args:
    state (`KarrasVeSchedulerState`):
        the `FlaxKarrasVeScheduler` state data class.
    num_inference_steps (`int`):
        the number of diffusion steps used when generating samples with a pre-trained model.

r   Nr   r   )dtype)r   r   r   )	r"   arangecopyconfigr6   r5   replacearrayfloat32)r2   r+   r   rA   r   ir   s          r   set_timesteps#FlaxKarrasVeScheduler.set_timestepsn   s     JJq"56tt<AAC	 

  %%q(;;((!+dkk.C.CQ.FFAghQhLijk  	 
 }} 3YYxs{{;  
 	

s   ACsamplesigmakeyc                    U R                   R                  Us=::  a  U R                   R                  ::  a1  O  O.[        U R                   R                  UR
                  -  S5      nOSn[        R                  " USS9nU R                   R                  [        R                  " XBR                  S9-  nX5U-  -   nX'S-  US-  -
  S-  U-  -   nX4$ )u   
Explicit Langevin-like "churn" step of adding noise to the sample according to a factor gamma_i ≥ 0 to reach a
higher noise level sigma_hat = sigma_i + gamma_i*sigma_i.

TODO Args:
g4y?r   r   )num)rQ   rA   r         ?)rH   r9   r:   minr8   r   r   splitr7   normalrA   )	r2   r+   rO   rP   rQ   gammaeps	sigma_hat
sample_hats	            r   add_noise_to_input(FlaxKarrasVeScheduler.add_noise_to_input   s     ;;:):)::++e.G.GGTEE ll3A&kk!!FMMc$NNEM)	1uax 7C?#EF
$$r   model_outputrZ   
sigma_prevr[   return_dictc                 \    XSU-  -   nXW-
  U-  nXTU-
  U-  -   n	U(       d  XU4$ [        XUS9$ )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:
    state (`KarrasVeSchedulerState`): the `FlaxKarrasVeScheduler` state data class.
    model_output (`torch.Tensor` or `np.ndarray`): direct output from learned diffusion model.
    sigma_hat (`float`): TODO
    sigma_prev (`float`): TODO
    sample_hat (`torch.Tensor` or `np.ndarray`): TODO
    return_dict (`bool`): option for returning tuple rather than FlaxKarrasVeOutput class

Returns:
    [`~schedulers.scheduling_karras_ve_flax.FlaxKarrasVeOutput`] or `tuple`: Updated sample in the diffusion
    chain and derivative. [`~schedulers.scheduling_karras_ve_flax.FlaxKarrasVeOutput`] if `return_dict` is
    True, otherwise a `tuple`. When returning a tuple, the first element is the sample tensor.
r)   r*   r+   r'   )
r2   r+   r^   rZ   r_   r[   r`   pred_original_sampler*   sample_prevs
             r   stepFlaxKarrasVeScheduler.step   sM    6  *,DD 79D
 $:j#HHU33!kX]^^r   re   r*   c	                 n    XdU-  -   n	Xi-
  U-  n
XTU-
  SU-  SU
-  -   -  -   nU(       d  XgU4$ [        XgUS9$ )a  
Correct the predicted sample based on the output model_output of the network. TODO complete description

Args:
    state (`KarrasVeSchedulerState`): the `FlaxKarrasVeScheduler` state data class.
    model_output (`torch.Tensor` or `np.ndarray`): direct output from learned diffusion model.
    sigma_hat (`float`): TODO
    sigma_prev (`float`): TODO
    sample_hat (`torch.Tensor` or `np.ndarray`): TODO
    sample_prev (`torch.Tensor` or `np.ndarray`): TODO
    derivative (`torch.Tensor` or `np.ndarray`): TODO
    return_dict (`bool`): option for returning tuple rather than FlaxKarrasVeOutput class

Returns:
    prev_sample (TODO): updated sample in the diffusion chain. derivative (TODO): TODO

rT   rb   rc   )r2   r+   r^   rZ   r_   r[   re   r*   r`   rd   derivative_corrs              r   step_correct"FlaxKarrasVeScheduler.step_correct   s^    8  +,-FF&=K $:sZ?ORUXgRg?g#hhU33!kX]^^r   c                     [        5       er   )NotImplementedError)r2   r+   original_samplesnoiser   s        r   	add_noiseFlaxKarrasVeScheduler.add_noise   s    !##r   N)g{Gz?d   g&1?P   g?2   )r   )T)r   r   r   r   r,   propertyr3   r
   floatr<   r?   r   r    r   rM   r"   r#   jaxArrayr\   boolr   r'   rf   rj   rp   r%   r   r   r   r.   r.   <   s   <     		 	 		
 	 	 	 	/ WY
+
BE
NS
	
8%%% % 	%
 YY% 
s{{E!	"%B !"_%"_ kk"_ 	"_
 "_ KK"_ "_ 
!5(	)"_Z !#_%#_ kk#_ 	#_
 #_ KK#_ [[#_ KK#_ #_ 
!5(	)#_J$5 $r   r.   )dataclassesr   typingr   r   r   flaxrw   	jax.numpynumpyr"   r   configuration_utilsr	   r
   utilsr   scheduling_utils_flaxr   structr   r'   r.   r   r   r   <module>r      st     " ) )  
   A  5    " " "$r$. r$r   