o
    Gii0                     @   s   d dl 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 ddlmZmZmZ eeZejjG d	d
 d
ZeG dd deZG dd dee	ZdS )    )	dataclassN)random   )ConfigMixinregister_to_config)logging   )FlaxSchedulerMixinFlaxSchedulerOutputbroadcast_to_shape_from_leftc                   @   sP   e Zd ZU dZejdB ed< dZejdB ed< dZejdB ed< e	dd Z
dS )ScoreSdeVeSchedulerStateN	timestepsdiscrete_sigmassigmasc                 C   s   |  S N )clsr   r   _/home/ubuntu/.local/lib/python3.10/site-packages/diffusers/schedulers/scheduling_sde_ve_flax.pycreate+   s   zScoreSdeVeSchedulerState.create)__name__
__module____qualname__r   jnpndarray__annotations__r   r   classmethodr   r   r   r   r   r   $   s   
 r   c                   @   s6   e Zd ZU dZeed< ejed< dZejdB ed< dS )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   0   s
   
 
r   c                   @   s  e Zd ZdZedd Ze							d,d
edededededefddZ	dd Z
		d-dededededef
ddZ			d.dedededededefddZdd Z	 d/ded!ejd"ed#ejd$ejd%edeeB fd&d'Z	 d/ded!ejd#ejd$ejd%edeeB fd(d)Zd*d+ ZdS )0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                 C   s   dS )NTr   selfr   r   r   	has_state[   s   z!FlaxScoreSdeVeScheduler.has_state  333333?{Gz?     @h㈵>r   num_train_timestepssnr	sigma_min	sigma_maxsampling_epscorrect_stepsc                 C   s   t d d S )NzFlax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.)loggerwarning)r#   r*   r+   r,   r-   r.   r/   r   r   r   __init___   s   
z FlaxScoreSdeVeScheduler.__init__c                 C   s*   t  }| || jj| jj| jj| jjS r   )r   r   
set_sigmasconfigr*   r,   r-   r.   )r#   r   r   r   r   create_staten   s   z$FlaxScoreSdeVeScheduler.create_stater   Nr   num_inference_stepsshapereturnc                 C   s.   |dur|n| j j}td||}|j|d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).

        Nr   )r   )r4   r.   r   linspacereplace)r#   r   r6   r7   r.   r   r   r   r   set_timestepsx   s   z%FlaxScoreSdeVeScheduler.set_timestepsc                    s   durn| j j dur n| j j |dur|n| j j}|jdu r*| |||}ttt	t	 |}t
 fdd|jD }|j||dS )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).
        Nc                    s   g | ]
}  |  qS r   r   ).0tr-   r,   r   r   
<listcomp>   s    z6FlaxScoreSdeVeScheduler.set_sigmas.<locals>.<listcomp>)r   r   )r4   r,   r-   r.   r   r;   r   expr9   logarrayr:   )r#   r   r6   r,   r-   r.   r   r   r   r>   r   r3      s   
 z"FlaxScoreSdeVeScheduler.set_sigmasc                 C   s"   t |dkt ||j|d  S )Nr   r   )r   where
zeros_liker   )r#   r   r   r=   r   r   r   get_adjacent_sigma   s   "z*FlaxScoreSdeVeScheduler.get_adjacent_sigmaTmodel_outputtimestepsamplekeyreturn_dictc                 C   s   |j du r	td|t|jd  }|t|j d   }|j| }| |||}	t	|}
|d |	d  d }|
 }t||j}|
|d |  }
tj|dd}tj||jd}||
 }|||  }|sk|||fS t|||d	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.

        NZ`state.timesteps` is not set, you need to run 'set_timesteps' after creating the schedulerr   r   r         ?numrI   r7   )r   r   r   )r   
ValueErrorr   onesr7   lenlongr   rE   rD   flattenr   r   splitnormalr   )r#   r   rF   rG   rH   rI   rJ   r   sigmaadjacent_sigmadrift	diffusionnoiser   r   r   r   r   	step_pred   s,   



z!FlaxScoreSdeVeScheduler.step_predc                 C   s   |j du r	tdtj|dd}tj||jd}tj|}tj|}| j	j
| | d d }	|	t|jd  }	|	 }	t|	|j}	||	|  }
|
|	d d |  }|sZ||fS t||d	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.

        NrK   r   rM   rO   r   r   rL   )r   r   )r   rP   r   rU   rV   r7   r   linalgnormr4   r+   rQ   rT   r   r   )r#   r   rF   rH   rI   rJ   r[   	grad_norm
noise_norm	step_sizer   r   r   r   r   step_correct   s"   
z$FlaxScoreSdeVeScheduler.step_correctc                 C   s   | j jS r   )r4   r*   r"   r   r   r   __len__%  s   zFlaxScoreSdeVeScheduler.__len__)r%   r&   r'   r(   r)   r   )r   N)NNN)T)r   r   r   r    propertyr$   r   intfloatr2   r5   r   tupler;   r3   rE   r   r   jaxArrayboolr   r\   rb   rc   r   r   r   r   r!   C   s    


#

B
4r!   )dataclassesr   flaxrh   	jax.numpynumpyr   r   configuration_utilsr   r   utilsr   scheduling_utils_flaxr	   r
   r   
get_loggerr   r0   structr   r   r!   r   r   r   r   <module>   s   
