
    bin/                         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
 d dlmZ ddlmZmZ ddlmZmZmZ ej&                  j                   G d	 d
             Ze G d de             Z G d dee      Zy)    )	dataclass)OptionalTupleUnionN)random   )ConfigMixinregister_to_config   )FlaxSchedulerMixinFlaxSchedulerOutputbroadcast_to_shape_from_leftc                       e Zd ZU dZeej                     ed<   dZeej                     ed<   dZ	eej                     ed<   e
d        Zy)ScoreSdeVeSchedulerStateN	timestepsdiscrete_sigmassigmasc                      |        S N )clss    f/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/schedulers/scheduling_sde_ve_flax.pycreatezScoreSdeVeSchedulerState.create$   s	    u    )__name__
__module____qualname__r   r   jnpndarray__annotations__r   r   classmethodr   r   r   r   r   r      sO     (,Ix$+-1OXckk*1$(FHS[[!( r   r   c                   b    e Zd ZU dZeed<   ej                  ed<   dZe	ej                     ed<   y)FlaxSdeVeOutputaL  
    Output class for the ScoreSdeVeScheduler's step function output.

    Args:
        state (`ScoreSdeVeSchedulerState`):
        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.
        prev_sample_mean (`jnp.ndarray` of shape `(batch_size, num_channels, height, width)` for images):
            Mean averaged `prev_sample`. Same as `prev_sample`, only mean-averaged over previous timesteps.
    stateprev_sampleNprev_sample_mean)
r   r   r   __doc__r   r    r   r   r&   r   r   r   r   r#   r#   )   s-    
 $#.2hs{{+2r   r#   c                      e Zd ZdZed        Ze	 	 	 	 	 	 ddedededededefd	       Z	d
 Z
	 ddededededef
dZ	 	 	 ddedededededefdZd Z	 ddedej"                  dedej"                  dej&                  dedeeef   fdZ	 ddedej"                  dej"                  dej&                  dedeeef   fdZd Zy)FlaxScoreSdeVeSchedulera  
    The variance exploding stochastic differential equation (SDE) scheduler.

    For more information, see the original paper: 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.

    Args:
        num_train_timesteps (`int`): number of diffusion steps used to train the model.
        snr (`float`):
            coefficient weighting the step from the model_output sample (from the network) to the random noise.
        sigma_min (`float`):
                initial noise scale for sigma sequence in sampling procedure. The minimum sigma should mirror the
                distribution of the data.
        sigma_max (`float`): maximum value used for the range of continuous timesteps passed into the model.
        sampling_eps (`float`): the end value of sampling, where timesteps decrease progressively from 1 to
        epsilon.
        correct_steps (`int`): number of correction steps performed on a produced sample.
    c                      y)NTr   selfs    r   	has_statez!FlaxScoreSdeVeScheduler.has_stateT   s    r   num_train_timestepssnr	sigma_min	sigma_maxsampling_epscorrect_stepsc                      y r   r   )r,   r.   r/   r0   r1   r2   r3   s          r   __init__z FlaxScoreSdeVeScheduler.__init__X   s     	r   c                     t         j                         }| j                  || j                  j                  | j                  j
                  | j                  j                  | j                  j                        S r   )r   r   
set_sigmasconfigr.   r0   r1   r2   )r,   r$   s     r   create_statez$FlaxScoreSdeVeScheduler.create_stated   sX    (//1KK++KK!!KK!!KK$$
 	
r   Nr$   num_inference_stepsshapereturnc                     ||n| j                   j                  }t        j                  d||      }|j	                  |      S )a  
        Sets the continuous timesteps used for the diffusion chain. Supporting function to be run before inference.

        Args:
            state (`ScoreSdeVeSchedulerState`): the `FlaxScoreSdeVeScheduler` state data class instance.
            num_inference_steps (`int`):
                the number of diffusion steps used when generating samples with a pre-trained model.
            sampling_eps (`float`, optional):
                final timestep value (overrides value given at Scheduler instantiation).

        r   )r   )r8   r2   r   linspacereplace)r,   r$   r:   r;   r2   r   s         r   set_timestepsz%FlaxScoreSdeVeScheduler.set_timestepsn   s>     (4'?|T[[E]E]LLL2EF	}}y}11r   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|j                  | j                  |||      }t        j                  t        j                  t        j                  |      t        j                  |      |            }t        j                  |j                  D cg c]  }|||z  |z  z   c}      }|j                  ||      S c c}w )au  
        Sets the noise scales used for the diffusion chain. Supporting function to be run before inference.

        The sigmas control the weight of the `drift` and `diffusion` components of sample update.

        Args:
            state (`ScoreSdeVeSchedulerState`): the `FlaxScoreSdeVeScheduler` state data class instance.
            num_inference_steps (`int`):
                the number of diffusion steps used when generating samples with a pre-trained model.
            sigma_min (`float`, optional):
                initial noise scale value (overrides value given at Scheduler instantiation).
            sigma_max (`float`, optional):
                final noise scale value (overrides value given at Scheduler instantiation).
            sampling_eps (`float`, optional):
                final timestep value (overrides value given at Scheduler instantiation).
        )r   r   )r8   r0   r1   r2   r   r@   r   expr>   logarrayr?   )	r,   r$   r:   r0   r1   r2   r   tr   s	            r   r7   z"FlaxScoreSdeVeScheduler.set_sigmas   s    0 "+!6IDKK<Q<Q	!*!6IDKK<Q<Q	'3'?|T[[E]E]??"&&u.A<PE''#,,swwy/A3779CUWj"kleoo^IY)>1(DD^_}}_V}LL _s   Dc                 |    t        j                  |dk(  t        j                  |      |j                  |dz
           S )Nr   r   )r   where
zeros_liker   )r,   r$   r   rE   s       r   get_adjacent_sigmaz*FlaxScoreSdeVeScheduler.get_adjacent_sigma   s4    yya):E<Q<QR[^_R_<`aar   model_outputtimestepsamplekeyreturn_dictc                 l   |j                   t        d      |t        j                  |j                  d         z  }|t        |j                         dz
  z  j                         }|j                  |   }| j                  |||      }	t        j                  |      }
|dz  |	dz  z
  dz  }|j                         }t        ||j                        }|
|dz  |z  z
  }
t        j                  |d      }t        j                  ||j                        }||
z
  }|||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:
            state (`ScoreSdeVeSchedulerState`): the `FlaxScoreSdeVeScheduler` state data class instance.
            model_output (`jnp.ndarray`): direct output from learned diffusion model.
            timestep (`int`): current discrete timestep in the diffusion chain.
            sample (`jnp.ndarray`):
                current instance of sample being created by diffusion process.
            generator: random number generator.
            return_dict (`bool`): option for returning tuple rather than FlaxSdeVeOutput class

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

        Z`state.timesteps` is not set, you need to run 'set_timesteps' after creating the schedulerr   r   r         ?numrM   r;   )r%   r&   r$   )r   
ValueErrorr   onesr;   lenlongr   rI   rH   flattenr   r   splitnormalr#   )r,   r$   rJ   rK   rL   rM   rN   r   sigmaadjacent_sigmadrift	diffusionnoiser&   r%   s                  r   	step_predz!FlaxScoreSdeVeScheduler.step_pred   sA   6 ??"l  chhLLO
 
 U__!5!9:@@B	%%i000	8Lv&AX 11c9	 %%'	0FLLI		1|33 ll3A&#V\\:!E>&U)::!1599;IYafggr   c                 H   |j                   t        d      t        j                  |d      }t        j                  ||j
                        }t        j                  j                  |      }t        j                  j                  |      }| j                  j                  |z  |z  dz  dz  }	|	t        j                  |j
                  d         z  }	|	j                         }	t        |	|j
                        }	||	|z  z   }
|
|	dz  dz  |z  z   }|s||fS t        ||      S )	aY  
        Correct the predicted sample based on the output model_output of the network. This is often run repeatedly
        after making the prediction for the previous timestep.

        Args:
            state (`ScoreSdeVeSchedulerState`): the `FlaxScoreSdeVeScheduler` state data class instance.
            model_output (`jnp.ndarray`): direct output from learned diffusion model.
            sample (`jnp.ndarray`):
                current instance of sample being created by diffusion process.
            generator: random number generator.
            return_dict (`bool`): option for returning tuple rather than FlaxSdeVeOutput class

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

        rP   r   rR   rT   r   r   rQ   )r%   r$   )r   rU   r   rZ   r[   r;   r   linalgnormr8   r/   rV   rY   r   r#   )r,   r$   rJ   rL   rM   rN   r`   	grad_norm
noise_norm	step_sizer&   r%   s               r   step_correctz$FlaxScoreSdeVeScheduler.step_correct   s	   2 ??"l  ll3A&#V\\: JJOOL1	ZZ__U+
[[__z1I=!CaG	a 99	 %%'	0FLLI	!I$<<&9q=S*@E)II'';eDDr   c                 .    | j                   j                  S r   )r8   r.   r+   s    r   __len__zFlaxScoreSdeVeScheduler.__len__  s    {{...r   )i  g333333?g{Gz?g     @gh㈵>r   )r   N)NNN)T)r   r   r   r'   propertyr-   r
   intfloatr5   r9   r   r   r@   r7   rI   r   r   jaxArrayboolr   r#   ra   rh   rj   r   r   r   r)   r)   <   s   .    $(!"	 	 	 		
 	 	 	 	
 sw2-2DG2PU2jo2	!2.  "!M'!M !!M 	!M
 !M !M 
"!MFb !:h':h kk:h 	:h
 :h YY:h :h 
%	&:hD !2E'2E kk2E 	2E
 YY2E 2E 
%	&2Eh/r   r)   )dataclassesr   typingr   r   r   flaxrn   	jax.numpynumpyr   r   configuration_utilsr	   r
   scheduling_utils_flaxr   r   r   structr   r#   r)   r   r   r   <module>ry      su   " " ) )  
   A h h    3) 3 3$\/0+ \/r   