o
    ۷i0                     @   sZ  d dl Z d dlZd dlZd dlmZ d dlmZ d dlZd dlm	Z
 d dlmZ ddlmZmZmZ eeZdZG dd	 d	eZeG d
d deZG dd deZde
jdee de
jfddZde
jfdede
jfddZejjG dd dZdede
jde
jde
jfddZ dede
jde
jde
jfdd Z!ded!e
jde
jde
jfd"d#Z"dS )$    N)	dataclass)Enum)validate_hf_hub_args   )
BaseOutputPushToHubMixinloggingzscheduler_config.jsonc                   @   s$   e Zd ZdZdZdZdZdZdZdS )FlaxKarrasDiffusionSchedulers   r               N)	__name__
__module____qualname__FlaxDDIMSchedulerFlaxDDPMSchedulerFlaxPNDMSchedulerFlaxLMSDiscreteSchedulerFlaxDPMSolverMultistepSchedulerFlaxEulerDiscreteScheduler r   r   `/home/ubuntu/vllm_env/lib/python3.10/site-packages/diffusers/schedulers/scheduling_utils_flax.pyr	   $   s    r	   c                   @   s   e Zd ZU dZejed< dS )FlaxSchedulerOutputa>  
    Base 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.
    prev_sampleN)r   r   r   __doc__jnpndarray__annotations__r   r   r   r   r   -   s   
 	r   c                   @   s   e Zd ZdZeZdgZg ZdZe	e
			ddeejB dB dedB fdd	Zdd
eejB defddZedd Ze	dd ZdS )FlaxSchedulerMixinaY  
    Mixin containing common functions for the schedulers.

    Class attributes:
        - **_compatibles** (`list[str]`) -- A list of classes that are compatible with the parent class, so that
          `from_config` can be used from a class different than the one used to save the config (should be overridden
          by parent class).
    dtypeTNFpretrained_model_name_or_path	subfolderc           	      K   st   t d | jd	||dd|\}}| j|fddi|\}}t|dr/t|ddr/| }|r6|||fS ||fS )
a  
        Instantiate a Scheduler class from a pre-defined JSON-file.

        Parameters:
            pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
                Can be either:

                    - A string, the *model id* of a model repo on huggingface.co. Valid model ids should have an
                      organization name, like `google/ddpm-celebahq-256`.
                    - A path to a *directory* containing model weights saved using [`~SchedulerMixin.save_pretrained`],
                      e.g., `./my_model_directory/`.
            subfolder (`str`, *optional*):
                In case the relevant files are located inside a subfolder of the model repo (either remote in
                huggingface.co or downloaded locally), you can specify the folder name here.
            return_unused_kwargs (`bool`, *optional*, defaults to `False`):
                Whether kwargs that are not consumed by the Python class should be returned or not.

            cache_dir (`str | os.PathLike`, *optional*):
                Path to a directory in which a downloaded pretrained model configuration should be cached if the
                standard cache should not be used.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.

            proxies (`dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            output_loading_info(`bool`, *optional*, defaults to `False`):
                Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
            local_files_only(`bool`, *optional*, defaults to `False`):
                Whether or not to only look at local files (i.e., do not try to download the model).
            token (`str` or *bool*, *optional*):
                The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
                when running `transformers-cli login` (stored in `~/.huggingface`).
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
                git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
                identifier allowed by git.

        > [!TIP] > It is required to be logged in (`hf auth login`) when you want to use private or [gated >
        models](https://huggingface.co/docs/hub/models-gated#gated-models).

        > [!TIP] > Activate the special
        ["offline-mode"](https://huggingface.co/transformers/installation.html#offline-mode) to > use this method in a
        firewalled environment.

        zFlax classes are deprecated and will be removed in Diffusers v1.0.0. We recommend migrating to PyTorch classes or pinning your version of Diffusers.T)r"   r#   return_unused_kwargsr$   create_state	has_stateFNr   )loggerwarningload_configfrom_confighasattrgetattrr%   )	clsr"   r#   r$   kwargsconfig	schedulerunused_kwargsstater   r   r   from_pretrainedJ   s    8

z"FlaxSchedulerMixin.from_pretrainedsave_directorypush_to_hubc                 K   s   | j d||d| dS )aX  
        Save a scheduler configuration object to the directory `save_directory`, so that it can be re-loaded using the
        [`~FlaxSchedulerMixin.from_pretrained`] class method.

        Args:
            save_directory (`str` or `os.PathLike`):
                Directory where the configuration JSON file will be saved (will be created if it does not exist).
            push_to_hub (`bool`, *optional*, defaults to `False`):
                Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
                repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
                namespace).
            kwargs (`dict[str, Any]`, *optional*):
                Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
        )r4   r5   Nr   )save_config)selfr4   r5   r.   r   r   r   save_pretrained   s   z"FlaxSchedulerMixin.save_pretrainedc                 C   s   |   S )z
        Returns all schedulers that are compatible with this scheduler

        Returns:
            `list[SchedulerMixin]`: list of compatible schedulers
        )_get_compatibles)r7   r   r   r   compatibles   s   zFlaxSchedulerMixin.compatiblesc                    s@   t t| jg| j }ttdd   fdd|D }|S )N.r   c                    s    g | ]}t  |rt |qS r   )r+   r,   ).0cdiffusers_libraryr   r   
<listcomp>   s
    
z7FlaxSchedulerMixin._get_compatibles.<locals>.<listcomp>)listsetr   _compatibles	importlibimport_modulesplit)r-   compatible_classes_strcompatible_classesr   r>   r   r9      s   
z#FlaxSchedulerMixin._get_compatibles)NNF)F)r   r   r   r   SCHEDULER_CONFIG_NAMEconfig_nameignore_for_configrC   has_compatiblesclassmethodr   strosPathLiker3   boolr8   propertyr:   r9   r   r   r   r   r    ;   s*    	J
	r    xshapereturnc                 C   s8   t || jks	J t| | jdt || j   |S )N)r
   )lenndimr   broadcast_toreshaperT   )rS   rT   r   r   r   broadcast_to_shape_from_left   s   &rZ   g+?num_diffusion_timestepsc                 C   s\   dd }g }t | D ]}||  }|d |  }|td||||  | q
tj||dS )az  
    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.

    Returns:
        betas (`jnp.ndarray`): the betas used by the scheduler to step the model outputs
    c                 S   s    t | d d t j d d S )NgMb?gT㥛 ?r   )mathcospi)	time_stepr   r   r   	alpha_bar   s    z&betas_for_alpha_bar.<locals>.alpha_barr
   r!   )rangeappendminr   array)r[   max_betar!   r`   betasit1t2r   r   r   betas_for_alpha_bar   s   "rk   c                   @   s8   e Zd ZU ejed< ejed< ejed< edd ZdS )CommonSchedulerStatealphasrg   alphas_cumprodc                 C   s   |j }|jd urtj|j|jd}nG|jdkr%tj|j|j|j	|jd}n4|jdkr>tj|jd |jd |j	|jdd }n|jdkrLt
|j	|jd}ntd|j d|jj d	| }tj|d
d}| |||dS )Nra   linearscaled_linear      ?r   squaredcos_cap_v2zbeta_schedule z" is not implemented for scheduler g      ?r   )axis)rm   rg   rn   )r/   trained_betasr   asarrayr!   beta_schedulelinspace
beta_startbeta_endnum_train_timestepsrk   NotImplementedError	__class__r   cumprod)r-   r0   r/   rg   rm   rn   r   r   r   create   s0   



zCommonSchedulerState.createN)r   r   r   r   r   r   rM   r~   r   r   r   r   rl      s   
 


rl   r2   original_samplesnoise	timestepsc                 C   sR   | j }|| d }| }t||j}d||  d }| }t||j}||fS )Nrq   r
   )rn   flattenrZ   rT   )r2   r   r   r   rn   sqrt_alpha_prodsqrt_one_minus_alpha_prodr   r   r   get_sqrt_alpha_prod  s   r   c                 C   s&   t | |||\}}|| ||  }|S Nr   )r2   r   r   r   r   r   noisy_samplesr   r   r   add_noise_common  s   r   samplec                 C   s&   t | |||\}}|| ||  }|S r   r   )r2   r   r   r   r   r   velocityr   r   r   get_velocity_common  s   r   )#rD   r\   rO   dataclassesr   enumr   flax	jax.numpynumpyr   huggingface_hub.utilsr   utilsr   r   r   
get_loggerr   r'   rI   r	   r   r    r   tupleintrZ   float32rk   structrl   r   r   r   r   r   r   r   <module>   sN   
	 (

$