a
    
dv'                     @   s  d dl Z d dlZd dlZd dlmZ d dlZd dlmZ d dl	m
Z
 d1ddZd2d
dZd3ddZd4ddZdd Zdd ZG dd dejjZd5ddZdd Zdd Zdd  Zd!d" ZG d#d$ d$ejZG d%d& d&ejZd'd( Zd)d* Zd+d, ZG d-d. d.ejZ d6d/d0Z!dS )7    N)repeat)instantiate_from_config-C6?{Gz?Mb?c                 C   s  | dkr*t j|d |d |t jdd }n| dkrt j|d t jd| | }|d|  tj d }t |d}||d  }d|dd  |d d   }tj|dd	d
}nh| dkrt	|dd S | dkrt j|||t jd}n4| dkrt j|||t jdd }nt
d|  d| S )Nlinearg      ?)dtype   cosine   r   +?)a_mina_maxZsquaredcos_cap_v2c                 S   s    t | d d t j d d S )Nr   gT㥛 ?r	   )mathcospi)t r   t/var/www/html/stable-diffusion-webui/repositories/stable-diffusion-stability-ai/ldm/modules/diffusionmodules/util.py<lambda>)       z$make_beta_schedule.<locals>.<lambda>Zsqrt_linearsqrtz
schedule 'z
' unknown.)torchlinspacefloat64arangenpr   r   powclipbetas_for_alpha_bar
ValueErrornumpy)schedule
n_timesteplinear_start
linear_endcosine_sbetas	timestepsalphasr   r   r   make_beta_schedule   s,    
r+   Tc                 C   s   | dkr(|| }t ttd||}n<| dkrTt dt |d |d t}ntd|  d|d }|r~t	d	|  |S )
Nuniformr   quadg?r	   z/There is no ddim discretization method called ""r   z%Selected timesteps for ddim sampler: )
r   asarraylistranger   r   astypeintNotImplementedErrorprint)Zddim_discr_methodZnum_ddim_timestepsZnum_ddpm_timestepsverbosecddim_timestepsZ	steps_outr   r   r   make_ddim_timesteps5   s    $r9   c                 C   s   | | }t | d g| |d d    }|t d| d|  d||    }|r~td| d|  td| d|  |||fS )Nr   r   r   z'Selected alphas for ddim sampler: a_t: z; a_(t-1): z&For the chosen value of eta, which is zB, this results in the following sigma_t schedule for ddim sampler )r   r/   tolistr   r5   )Z	alphacumsr8   etar6   r*   Zalphas_prevsigmasr   r   r   make_ddim_sampling_parametersF   s    $&
r=   r   c                 C   sP   g }t | D ]8}||  }|d |  }|td||||  | qt|S )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].
    :param num_diffusion_timesteps: the number of betas to produce.
    :param alpha_bar: a lambda that takes an argument t from 0 to 1 and
                      produces the cumulative product of (1-beta) up to that
                      part of the diffusion process.
    :param max_beta: the maximum beta to use; use values lower than 1 to
                     prevent singularities.
    r   )r1   appendminr   array)Znum_diffusion_timesteps	alpha_barZmax_betar(   it1t2r   r   r   r    T   s    "r    c                 C   s4   |j ^}}| d|}|j|gdt|d  R  S )Nr   r   r   )shapegatherreshapelen)ar   x_shapeb_outr   r   r   extract_into_tensorg   s    
rO   c                 C   s8   |r,t |t | }tj| t|g|R  S | | S dS )a  
    Evaluate a function without caching intermediate activations, allowing for
    reduced memory at the expense of extra compute in the backward pass.
    :param func: the function to evaluate.
    :param inputs: the argument sequence to pass to `func`.
    :param params: a sequence of parameters `func` depends on but does not
                   explicitly take as arguments.
    :param flag: if False, disable gradient checkpointing.
    N)tupleCheckpointFunctionapplyrI   )funcinputsparamsflagargsr   r   r   
checkpointm   s    
rX   c                   @   s$   e Zd Zedd Zedd ZdS )rQ   c                 G   s|   || _ t|d | | _t||d  | _t t t d| _t	  | j | j }W d    n1 sn0    Y  |S )N)enabledr   cache_enabled)
run_functionr0   input_tensorsinput_paramsr   is_autocast_enabledget_autocast_gpu_dtypeis_autocast_cache_enabledgpu_autocast_kwargsno_grad)ctxr[   lengthrW   output_tensorsr   r   r   forward   s    
*zCheckpointFunction.forwardc              	   G   s   dd | j D | _ t ` tjjjf i | j* dd | j D }| j| }W d    n1 sb0    Y  W d    n1 s0    Y  tjj	|| j | j
 |dd}| ` | `
~d| S )Nc                 S   s   g | ]}|  d qS )T)detachrequires_grad_.0xr   r   r   
<listcomp>   r   z/CheckpointFunction.backward.<locals>.<listcomp>c                 S   s   g | ]}| |qS r   )view_asri   r   r   r   rl      r   T)allow_unused)NN)r\   r   enable_gradcudaampautocastra   r[   autogradgradr]   )rc   output_gradsshallow_copiesre   input_gradsr   r   r   backward   s     
F
zCheckpointFunction.backwardN)__name__
__module____qualname__staticmethodrf   rx   r   r   r   r   rQ   ~   s   
rQ   '  Fc                 C   s   |s|d }t t| t jd|t jd | j| jd}| dddf  |d  }t j	t 
|t |gdd}|d rt j	|t |ddddf gdd}nt| d	|d
}|S )aX  
    Create sinusoidal timestep embeddings.
    :param timesteps: a 1-D Tensor of N indices, one per batch element.
                      These may be fractional.
    :param dim: the dimension of the output.
    :param max_period: controls the minimum frequency of the embeddings.
    :return: an [N x dim] Tensor of positional embeddings.
    r	   r   )startendr   deviceNr   dimr   zb -> b d)d)r   expr   logr   float32tor   floatcatr   sin
zeros_liker   )r)   r   
max_periodrepeat_onlyhalffreqsrW   	embeddingr   r   r   timestep_embedding   s    	 *r   c                 C   s   |   D ]}|   q| S )z<
    Zero out the parameters of a module and return it.
    )
parametersrg   zero_)modulepr   r   r   zero_module   s    r   c                 C   s    |   D ]}| | q| S )z9
    Scale the parameters of a module and return it.
    )r   rg   mul_)r   scaler   r   r   r   scale_module   s    r   c                 C   s   | j ttdt| jdS )z6
    Take the mean over all non-batch dimensions.
    r   r   )meanr0   r1   rI   rF   )tensorr   r   r   	mean_flat   s    r   c                 C   s
   t d| S )z
    Make a standard normalization layer.
    :param channels: number of input channels.
    :return: an nn.Module for normalization.
        )GroupNorm32)channelsr   r   r   normalization   s    r   c                   @   s   e Zd Zdd ZdS )SiLUc                 C   s   |t | S N)r   sigmoidselfrk   r   r   r   rf      s    zSiLU.forwardN)ry   rz   r{   rf   r   r   r   r   r      s   r   c                       s   e Zd Z fddZ  ZS )r   c                    s   t  | |jS r   )superrf   r   typer   r   	__class__r   r   rf      s    zGroupNorm32.forward)ry   rz   r{   rf   __classcell__r   r   r   r   r      s   r   c                 O   sZ   | dkrt j|i |S | dkr0t j|i |S | dkrHt j|i |S td|  dS )z4
    Create a 1D, 2D, or 3D convolution module.
    r   r	      unsupported dimensions: N)nnConv1dConv2dConv3dr!   dimsrW   kwargsr   r   r   conv_nd   s    r   c                  O   s   t j| i |S )z!
    Create a linear module.
    )r   Linear)rW   r   r   r   r   r      s    r   c                 O   sZ   | dkrt j|i |S | dkr0t j|i |S | dkrHt j|i |S td|  dS )z8
    Create a 1D, 2D, or 3D average pooling module.
    r   r	   r   r   N)r   	AvgPool1d	AvgPool2d	AvgPool3dr!   r   r   r   r   avg_pool_nd   s    r   c                       s$   e Zd Z fddZdd Z  ZS )HybridConditionerc                    s"   t    t|| _t|| _d S r   )r   __init__r   concat_conditionercrossattn_conditioner)r   Zc_concat_configZc_crossattn_configr   r   r   r     s    

zHybridConditioner.__init__c                 C   s"   |  |}| |}|g|gdS )N)c_concatc_crossattn)r   r   )r   r   r   r   r   r   rf     s    

zHybridConditioner.forward)ry   rz   r{   r   rf   r   r   r   r   r   r     s   r   c                    s,    fdd} fdd}|r&| S | S )Nc                      s<   t jdgdd  R  djd gdtd  R  S )Nr   r   r   rE   )r   randnr   rI   r   r   rF   r   r   r     r   znoise_like.<locals>.<lambda>c                      s   t j dS )Nr   )r   r   r   r   r   r   r     r   r   )rF   r   r   Zrepeat_noisenoiser   r   r   
noise_like  s    r   )r   r   r   )T)T)r   )r}   F)F)"osr   r   torch.nnr   r"   r   einopsr   ldm.utilr   r+   r9   r=   r    rO   rX   rs   FunctionrQ   r   r   r   r   r   Moduler   	GroupNormr   r   r   r   r   r   r   r   r   r   <module>   s2   
 


#
		
